"use client";
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });

// src/hooks/useApiKey.ts
import { useCallback, useState } from "react";

// src/_api/generated/_cfg_accounts/hooks/useCfgAccountsApiKeyRegenerateCreate.ts
import useSWRMutation from "swr/mutation";

// src/_api/generated/core/bodySerializer.gen.ts
var jsonBodySerializer = {
  bodySerializer: /* @__PURE__ */ __name((body) => JSON.stringify(body, (_key, value) => typeof value === "bigint" ? value.toString() : value), "bodySerializer")
};

// src/_api/generated/core/params.gen.ts
var extraPrefixesMap = {
  $body_: "body",
  $headers_: "headers",
  $path_: "path",
  $query_: "query"
};
var extraPrefixes = Object.entries(extraPrefixesMap);

// src/_api/generated/core/serverSentEvents.gen.ts
function createSseClient({
  onRequest,
  onSseError,
  onSseEvent,
  responseTransformer,
  responseValidator,
  sseDefaultRetryDelay,
  sseMaxRetryAttempts,
  sseMaxRetryDelay,
  sseSleepFn,
  url,
  ...options
}) {
  let lastEventId;
  const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
  const createStream = /* @__PURE__ */ __name(async function* () {
    let retryDelay = sseDefaultRetryDelay ?? 3e3;
    let attempt = 0;
    const signal = options.signal ?? new AbortController().signal;
    while (true) {
      if (signal.aborted) break;
      attempt++;
      const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
      if (lastEventId !== void 0) {
        headers.set("Last-Event-ID", lastEventId);
      }
      try {
        const requestInit = {
          redirect: "follow",
          ...options,
          body: options.serializedBody,
          headers,
          signal
        };
        let request = new Request(url, requestInit);
        if (onRequest) {
          request = await onRequest(url, requestInit);
        }
        const _fetch = options.fetch ?? globalThis.fetch;
        const response = await _fetch(request);
        if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
        if (!response.body) throw new Error("No body in SSE response");
        const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
        let buffer = "";
        const abortHandler = /* @__PURE__ */ __name(() => {
          try {
            reader.cancel();
          } catch {
          }
        }, "abortHandler");
        signal.addEventListener("abort", abortHandler);
        try {
          while (true) {
            const { done, value } = await reader.read();
            if (done) break;
            buffer += value;
            buffer = buffer.replace(/\r\n?/g, "\n");
            const chunks = buffer.split("\n\n");
            buffer = chunks.pop() ?? "";
            for (const chunk of chunks) {
              const lines = chunk.split("\n");
              const dataLines = [];
              let eventName;
              for (const line of lines) {
                if (line.startsWith("data:")) {
                  dataLines.push(line.replace(/^data:\s*/, ""));
                } else if (line.startsWith("event:")) {
                  eventName = line.replace(/^event:\s*/, "");
                } else if (line.startsWith("id:")) {
                  lastEventId = line.replace(/^id:\s*/, "");
                } else if (line.startsWith("retry:")) {
                  const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10);
                  if (!Number.isNaN(parsed)) {
                    retryDelay = parsed;
                  }
                }
              }
              let data;
              let parsedJson = false;
              if (dataLines.length) {
                const rawData = dataLines.join("\n");
                try {
                  data = JSON.parse(rawData);
                  parsedJson = true;
                } catch {
                  data = rawData;
                }
              }
              if (parsedJson) {
                if (responseValidator) {
                  await responseValidator(data);
                }
                if (responseTransformer) {
                  data = await responseTransformer(data);
                }
              }
              onSseEvent?.({
                data,
                event: eventName,
                id: lastEventId,
                retry: retryDelay
              });
              if (dataLines.length) {
                yield data;
              }
            }
          }
        } finally {
          signal.removeEventListener("abort", abortHandler);
          reader.releaseLock();
        }
        break;
      } catch (error) {
        onSseError?.(error);
        if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) {
          break;
        }
        const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 3e4);
        await sleep(backoff);
      }
    }
  }, "createStream");
  const stream = createStream();
  return { stream };
}
__name(createSseClient, "createSseClient");

// src/_api/generated/core/pathSerializer.gen.ts
var separatorArrayExplode = /* @__PURE__ */ __name((style) => {
  switch (style) {
    case "label":
      return ".";
    case "matrix":
      return ";";
    case "simple":
      return ",";
    default:
      return "&";
  }
}, "separatorArrayExplode");
var separatorArrayNoExplode = /* @__PURE__ */ __name((style) => {
  switch (style) {
    case "form":
      return ",";
    case "pipeDelimited":
      return "|";
    case "spaceDelimited":
      return "%20";
    default:
      return ",";
  }
}, "separatorArrayNoExplode");
var separatorObjectExplode = /* @__PURE__ */ __name((style) => {
  switch (style) {
    case "label":
      return ".";
    case "matrix":
      return ";";
    case "simple":
      return ",";
    default:
      return "&";
  }
}, "separatorObjectExplode");
var serializeArrayParam = /* @__PURE__ */ __name(({
  allowReserved,
  explode,
  name,
  style,
  value
}) => {
  if (!explode) {
    const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
    switch (style) {
      case "label":
        return `.${joinedValues2}`;
      case "matrix":
        return `;${name}=${joinedValues2}`;
      case "simple":
        return joinedValues2;
      default:
        return `${name}=${joinedValues2}`;
    }
  }
  const separator = separatorArrayExplode(style);
  const joinedValues = value.map((v) => {
    if (style === "label" || style === "simple") {
      return allowReserved ? v : encodeURIComponent(v);
    }
    return serializePrimitiveParam({
      allowReserved,
      name,
      value: v
    });
  }).join(separator);
  return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
}, "serializeArrayParam");
var serializePrimitiveParam = /* @__PURE__ */ __name(({
  allowReserved,
  name,
  value
}) => {
  if (value === void 0 || value === null) {
    return "";
  }
  if (typeof value === "object") {
    throw new Error(
      "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
    );
  }
  return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
}, "serializePrimitiveParam");
var serializeObjectParam = /* @__PURE__ */ __name(({
  allowReserved,
  explode,
  name,
  style,
  value,
  valueOnly
}) => {
  if (value instanceof Date) {
    return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
  }
  if (style !== "deepObject" && !explode) {
    let values = [];
    Object.entries(value).forEach(([key, v]) => {
      values = [...values, key, allowReserved ? v : encodeURIComponent(v)];
    });
    const joinedValues2 = values.join(",");
    switch (style) {
      case "form":
        return `${name}=${joinedValues2}`;
      case "label":
        return `.${joinedValues2}`;
      case "matrix":
        return `;${name}=${joinedValues2}`;
      default:
        return joinedValues2;
    }
  }
  const separator = separatorObjectExplode(style);
  const joinedValues = Object.entries(value).map(
    ([key, v]) => serializePrimitiveParam({
      allowReserved,
      name: style === "deepObject" ? `${name}[${key}]` : key,
      value: v
    })
  ).join(separator);
  return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
}, "serializeObjectParam");

// src/_api/generated/core/utils.gen.ts
var PATH_PARAM_RE = /\{[^{}]+\}/g;
var defaultPathSerializer = /* @__PURE__ */ __name(({ path, url: _url }) => {
  let url = _url;
  const matches = _url.match(PATH_PARAM_RE);
  if (matches) {
    for (const match of matches) {
      let explode = false;
      let name = match.substring(1, match.length - 1);
      let style = "simple";
      if (name.endsWith("*")) {
        explode = true;
        name = name.substring(0, name.length - 1);
      }
      if (name.startsWith(".")) {
        name = name.substring(1);
        style = "label";
      } else if (name.startsWith(";")) {
        name = name.substring(1);
        style = "matrix";
      }
      const value = path[name];
      if (value === void 0 || value === null) {
        continue;
      }
      if (Array.isArray(value)) {
        url = url.replace(match, serializeArrayParam({ explode, name, style, value }));
        continue;
      }
      if (typeof value === "object") {
        url = url.replace(
          match,
          serializeObjectParam({
            explode,
            name,
            style,
            value,
            valueOnly: true
          })
        );
        continue;
      }
      if (style === "matrix") {
        url = url.replace(
          match,
          `;${serializePrimitiveParam({
            name,
            value
          })}`
        );
        continue;
      }
      const replaceValue = encodeURIComponent(
        style === "label" ? `.${value}` : value
      );
      url = url.replace(match, replaceValue);
    }
  }
  return url;
}, "defaultPathSerializer");
var getUrl = /* @__PURE__ */ __name(({
  baseUrl,
  path,
  query,
  querySerializer,
  url: _url
}) => {
  const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
  let url = (baseUrl ?? "") + pathUrl;
  if (path) {
    url = defaultPathSerializer({ path, url });
  }
  let search = query ? querySerializer(query) : "";
  if (search.startsWith("?")) {
    search = search.substring(1);
  }
  if (search) {
    url += `?${search}`;
  }
  return url;
}, "getUrl");
function getValidRequestBody(options) {
  const hasBody = options.body !== void 0;
  const isSerializedBody = hasBody && options.bodySerializer;
  if (isSerializedBody) {
    if ("serializedBody" in options) {
      const hasSerializedBody = options.serializedBody !== void 0 && options.serializedBody !== "";
      return hasSerializedBody ? options.serializedBody : null;
    }
    return options.body !== "" ? options.body : null;
  }
  if (hasBody) {
    return options.body;
  }
  return void 0;
}
__name(getValidRequestBody, "getValidRequestBody");

// src/_api/generated/core/auth.gen.ts
var getAuthToken = /* @__PURE__ */ __name(async (auth2, callback) => {
  const token = typeof callback === "function" ? await callback(auth2) : callback;
  if (!token) {
    return;
  }
  if (auth2.scheme === "bearer") {
    return `Bearer ${token}`;
  }
  if (auth2.scheme === "basic") {
    return `Basic ${btoa(token)}`;
  }
  return token;
}, "getAuthToken");

// src/_api/generated/client/utils.gen.ts
var createQuerySerializer = /* @__PURE__ */ __name(({
  parameters = {},
  ...args
} = {}) => {
  const querySerializer = /* @__PURE__ */ __name((queryParams) => {
    const search = [];
    if (queryParams && typeof queryParams === "object") {
      for (const name in queryParams) {
        const value = queryParams[name];
        if (value === void 0 || value === null) {
          continue;
        }
        const options = parameters[name] || args;
        if (Array.isArray(value)) {
          const serializedArray = serializeArrayParam({
            allowReserved: options.allowReserved,
            explode: true,
            name,
            style: "form",
            value,
            ...options.array
          });
          if (serializedArray) search.push(serializedArray);
        } else if (typeof value === "object") {
          const serializedObject = serializeObjectParam({
            allowReserved: options.allowReserved,
            explode: true,
            name,
            style: "deepObject",
            value,
            ...options.object
          });
          if (serializedObject) search.push(serializedObject);
        } else {
          const serializedPrimitive = serializePrimitiveParam({
            allowReserved: options.allowReserved,
            name,
            value
          });
          if (serializedPrimitive) search.push(serializedPrimitive);
        }
      }
    }
    return search.join("&");
  }, "querySerializer");
  return querySerializer;
}, "createQuerySerializer");
var getParseAs = /* @__PURE__ */ __name((contentType) => {
  if (!contentType) {
    return "stream";
  }
  const cleanContent = contentType.split(";")[0]?.trim();
  if (!cleanContent) {
    return;
  }
  if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
    return "json";
  }
  if (cleanContent === "multipart/form-data") {
    return "formData";
  }
  if (["application/", "audio/", "image/", "video/"].some((type) => cleanContent.startsWith(type))) {
    return "blob";
  }
  if (cleanContent.startsWith("text/")) {
    return "text";
  }
  return;
}, "getParseAs");
var checkForExistence = /* @__PURE__ */ __name((options, name) => {
  if (!name) {
    return false;
  }
  if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
    return true;
  }
  return false;
}, "checkForExistence");
async function setAuthParams(options) {
  for (const auth2 of options.security ?? []) {
    if (checkForExistence(options, auth2.name)) {
      continue;
    }
    const token = await getAuthToken(auth2, options.auth);
    if (!token) {
      continue;
    }
    const name = auth2.name ?? "Authorization";
    switch (auth2.in) {
      case "query":
        if (!options.query) {
          options.query = {};
        }
        options.query[name] = token;
        break;
      case "cookie":
        options.headers.append("Cookie", `${name}=${token}`);
        break;
      case "header":
      default:
        options.headers.set(name, token);
        break;
    }
  }
}
__name(setAuthParams, "setAuthParams");
var buildUrl = /* @__PURE__ */ __name((options) => getUrl({
  baseUrl: options.baseUrl,
  path: options.path,
  query: options.query,
  querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
  url: options.url
}), "buildUrl");
var mergeConfigs = /* @__PURE__ */ __name((a, b) => {
  const config = { ...a, ...b };
  if (config.baseUrl?.endsWith("/")) {
    config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
  }
  config.headers = mergeHeaders(a.headers, b.headers);
  return config;
}, "mergeConfigs");
var headersEntries = /* @__PURE__ */ __name((headers) => {
  const entries = [];
  headers.forEach((value, key) => {
    entries.push([key, value]);
  });
  return entries;
}, "headersEntries");
var mergeHeaders = /* @__PURE__ */ __name((...headers) => {
  const mergedHeaders = new Headers();
  for (const header of headers) {
    if (!header) {
      continue;
    }
    const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
    for (const [key, value] of iterator) {
      if (value === null) {
        mergedHeaders.delete(key);
      } else if (Array.isArray(value)) {
        for (const v of value) {
          mergedHeaders.append(key, v);
        }
      } else if (value !== void 0) {
        mergedHeaders.set(
          key,
          typeof value === "object" ? JSON.stringify(value) : value
        );
      }
    }
  }
  return mergedHeaders;
}, "mergeHeaders");
var Interceptors = class {
  static {
    __name(this, "Interceptors");
  }
  fns = [];
  clear() {
    this.fns = [];
  }
  eject(id) {
    const index = this.getInterceptorIndex(id);
    if (this.fns[index]) {
      this.fns[index] = null;
    }
  }
  exists(id) {
    const index = this.getInterceptorIndex(id);
    return Boolean(this.fns[index]);
  }
  getInterceptorIndex(id) {
    if (typeof id === "number") {
      return this.fns[id] ? id : -1;
    }
    return this.fns.indexOf(id);
  }
  update(id, fn) {
    const index = this.getInterceptorIndex(id);
    if (this.fns[index]) {
      this.fns[index] = fn;
      return id;
    }
    return false;
  }
  use(fn) {
    this.fns.push(fn);
    return this.fns.length - 1;
  }
};
var createInterceptors = /* @__PURE__ */ __name(() => ({
  error: new Interceptors(),
  request: new Interceptors(),
  response: new Interceptors()
}), "createInterceptors");
var defaultQuerySerializer = createQuerySerializer({
  allowReserved: false,
  array: {
    explode: true,
    style: "form"
  },
  object: {
    explode: true,
    style: "deepObject"
  }
});
var defaultHeaders = {
  "Content-Type": "application/json"
};
var createConfig = /* @__PURE__ */ __name((override = {}) => ({
  ...jsonBodySerializer,
  headers: defaultHeaders,
  parseAs: "auto",
  querySerializer: defaultQuerySerializer,
  ...override
}), "createConfig");

// src/_api/generated/client/client.gen.ts
var createClient = /* @__PURE__ */ __name((config = {}) => {
  let _config = mergeConfigs(createConfig(), config);
  const getConfig = /* @__PURE__ */ __name(() => ({ ..._config }), "getConfig");
  const setConfig = /* @__PURE__ */ __name((config2) => {
    _config = mergeConfigs(_config, config2);
    return getConfig();
  }, "setConfig");
  const interceptors = createInterceptors();
  const beforeRequest = /* @__PURE__ */ __name(async (options) => {
    const opts = {
      ..._config,
      ...options,
      fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
      headers: mergeHeaders(_config.headers, options.headers),
      serializedBody: void 0
    };
    if (opts.security) {
      await setAuthParams(opts);
    }
    if (opts.requestValidator) {
      await opts.requestValidator(opts);
    }
    if (opts.body !== void 0 && opts.bodySerializer) {
      opts.serializedBody = opts.bodySerializer(opts.body);
    }
    if (opts.body === void 0 || opts.serializedBody === "") {
      opts.headers.delete("Content-Type");
    }
    const resolvedOpts = opts;
    const url = buildUrl(resolvedOpts);
    return { opts: resolvedOpts, url };
  }, "beforeRequest");
  const request = /* @__PURE__ */ __name(async (options) => {
    const throwOnError = options.throwOnError ?? _config.throwOnError;
    const responseStyle = options.responseStyle ?? _config.responseStyle;
    let request2;
    let response;
    try {
      const { opts, url } = await beforeRequest(options);
      const requestInit = {
        redirect: "follow",
        ...opts,
        body: getValidRequestBody(opts)
      };
      request2 = new Request(url, requestInit);
      for (const fn of interceptors.request.fns) {
        if (fn) {
          request2 = await fn(request2, opts);
        }
      }
      const _fetch = opts.fetch;
      response = await _fetch(request2);
      for (const fn of interceptors.response.fns) {
        if (fn) {
          response = await fn(response, request2, opts);
        }
      }
      const result = {
        request: request2,
        response
      };
      if (response.ok) {
        const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
        if (response.status === 204 || response.headers.get("Content-Length") === "0") {
          let emptyData;
          switch (parseAs) {
            case "arrayBuffer":
            case "blob":
            case "text":
              emptyData = await response[parseAs]();
              break;
            case "formData":
              emptyData = new FormData();
              break;
            case "stream":
              emptyData = response.body;
              break;
            case "json":
            default:
              emptyData = {};
              break;
          }
          return opts.responseStyle === "data" ? emptyData : {
            data: emptyData,
            ...result
          };
        }
        let data;
        switch (parseAs) {
          case "arrayBuffer":
          case "blob":
          case "formData":
          case "text":
            data = await response[parseAs]();
            break;
          case "json": {
            const text = await response.text();
            data = text ? JSON.parse(text) : {};
            break;
          }
          case "stream":
            return opts.responseStyle === "data" ? response.body : {
              data: response.body,
              ...result
            };
        }
        if (parseAs === "json") {
          if (opts.responseValidator) {
            await opts.responseValidator(data);
          }
          if (opts.responseTransformer) {
            data = await opts.responseTransformer(data);
          }
        }
        return opts.responseStyle === "data" ? data : {
          data,
          ...result
        };
      }
      const textError = await response.text();
      let jsonError;
      try {
        jsonError = JSON.parse(textError);
      } catch {
      }
      throw jsonError ?? textError;
    } catch (error) {
      let finalError = error;
      for (const fn of interceptors.error.fns) {
        if (fn) {
          finalError = await fn(finalError, response, request2, options);
        }
      }
      finalError = finalError || {};
      if (throwOnError) {
        throw finalError;
      }
      return responseStyle === "data" ? void 0 : {
        error: finalError,
        request: request2,
        response
      };
    }
  }, "request");
  const makeMethodFn = /* @__PURE__ */ __name((method) => (options) => request({ ...options, method }), "makeMethodFn");
  const makeSseFn = /* @__PURE__ */ __name((method) => async (options) => {
    const { opts, url } = await beforeRequest(options);
    return createSseClient({
      ...opts,
      body: opts.body,
      method,
      onRequest: /* @__PURE__ */ __name(async (url2, init) => {
        let request2 = new Request(url2, init);
        for (const fn of interceptors.request.fns) {
          if (fn) {
            request2 = await fn(request2, opts);
          }
        }
        return request2;
      }, "onRequest"),
      serializedBody: getValidRequestBody(opts),
      url
    });
  }, "makeSseFn");
  const _buildUrl = /* @__PURE__ */ __name((options) => buildUrl({ ..._config, ...options }), "_buildUrl");
  return {
    buildUrl: _buildUrl,
    connect: makeMethodFn("CONNECT"),
    delete: makeMethodFn("DELETE"),
    get: makeMethodFn("GET"),
    getConfig,
    head: makeMethodFn("HEAD"),
    interceptors,
    options: makeMethodFn("OPTIONS"),
    patch: makeMethodFn("PATCH"),
    post: makeMethodFn("POST"),
    put: makeMethodFn("PUT"),
    request,
    setConfig,
    sse: {
      connect: makeSseFn("CONNECT"),
      delete: makeSseFn("DELETE"),
      get: makeSseFn("GET"),
      head: makeSseFn("HEAD"),
      options: makeSseFn("OPTIONS"),
      patch: makeSseFn("PATCH"),
      post: makeSseFn("POST"),
      put: makeSseFn("PUT"),
      trace: makeSseFn("TRACE")
    },
    trace: makeMethodFn("TRACE")
  };
}, "createClient");

// src/_api/generated/helpers/errors.ts
var APIError = class extends Error {
  constructor(statusCode, statusText, response, url, message) {
    super(message || `HTTP ${statusCode}: ${statusText}`);
    this.statusCode = statusCode;
    this.statusText = statusText;
    this.response = response;
    this.url = url;
    this.name = "APIError";
  }
  statusCode;
  statusText;
  response;
  url;
  static {
    __name(this, "APIError");
  }
  get details() {
    if (typeof this.response === "object" && this.response !== null) {
      return this.response;
    }
    return null;
  }
  get fieldErrors() {
    const details = this.details;
    if (!details) return null;
    const fieldErrors = {};
    for (const [key, value] of Object.entries(details)) {
      if (Array.isArray(value)) fieldErrors[key] = value;
    }
    return Object.keys(fieldErrors).length > 0 ? fieldErrors : null;
  }
  get errorMessage() {
    const details = this.details;
    if (!details) return this.message;
    if (details.detail) {
      return Array.isArray(details.detail) ? details.detail.join(", ") : String(details.detail);
    }
    if (details.error) return String(details.error);
    if (details.message) return String(details.message);
    const fieldErrors = this.fieldErrors;
    if (fieldErrors) {
      const firstField = Object.keys(fieldErrors)[0];
      if (firstField) return `${firstField}: ${fieldErrors[firstField]?.join(", ")}`;
    }
    return this.message;
  }
  get isValidationError() {
    return this.statusCode === 400;
  }
  get isAuthError() {
    return this.statusCode === 401;
  }
  get isPermissionError() {
    return this.statusCode === 403;
  }
  get isNotFoundError() {
    return this.statusCode === 404;
  }
  get isServerError() {
    return this.statusCode >= 500 && this.statusCode < 600;
  }
};

// src/_api/generated/helpers/auth.ts
var ACCESS_KEY = "cfg.access_token";
var REFRESH_KEY = "cfg.refresh_token";
var API_KEY_KEY = "cfg.api_key";
var isBrowser = typeof window !== "undefined";
var localStorageBackend = {
  get(key) {
    if (!isBrowser) return null;
    try {
      return window.localStorage.getItem(key);
    } catch {
      return null;
    }
  },
  set(key, value) {
    if (!isBrowser) return;
    try {
      if (value === null) window.localStorage.removeItem(key);
      else window.localStorage.setItem(key, value);
    } catch {
    }
  }
};
var COOKIE_MAX_AGE = 60 * 60 * 24 * 30;
var cookieBackend = {
  get(key) {
    if (!isBrowser) return null;
    try {
      const re = new RegExp(`(?:^|;\\s*)${encodeURIComponent(key)}=([^;]*)`);
      const m = document.cookie.match(re);
      return m ? decodeURIComponent(m[1]) : null;
    } catch {
      return null;
    }
  },
  set(key, value) {
    if (!isBrowser) return;
    try {
      const k = encodeURIComponent(key);
      const secure = window.location.protocol === "https:" ? "; Secure" : "";
      if (value === null) {
        document.cookie = `${k}=; Path=/; Max-Age=0; SameSite=Lax${secure}`;
      } else {
        const v = encodeURIComponent(value);
        document.cookie = `${k}=${v}; Path=/; Max-Age=${COOKIE_MAX_AGE}; SameSite=Lax${secure}`;
      }
    } catch {
    }
  }
};
var _storage = localStorageBackend;
var _storageMode = "localStorage";
function detectLocale() {
  try {
    if (typeof document !== "undefined") {
      const m = document.cookie.match(/(?:^|;\s*)NEXT_LOCALE=([^;]*)/);
      if (m) return decodeURIComponent(m[1]);
    }
    if (typeof navigator !== "undefined" && navigator.language) {
      return navigator.language;
    }
  } catch {
  }
  return null;
}
__name(detectLocale, "detectLocale");
function defaultBaseUrl() {
  if (typeof window !== "undefined") {
    try {
      if (typeof process !== "undefined" && process.env) {
        if (process.env.NEXT_PUBLIC_STATIC_BUILD === "true") return "";
        if (process.env.NEXT_PUBLIC_API_PROXY_URL !== void 0)
          return process.env.NEXT_PUBLIC_API_PROXY_URL;
        return process.env.NEXT_PUBLIC_API_URL || "";
      }
    } catch {
    }
    return "";
  }
  try {
    if (typeof process !== "undefined" && process.env) {
      if (process.env.NEXT_PUBLIC_STATIC_BUILD === "true") return "";
      return process.env.NEXT_PUBLIC_API_URL || "";
    }
  } catch {
  }
  return "";
}
__name(defaultBaseUrl, "defaultBaseUrl");
function defaultApiKey() {
  try {
    if (typeof process !== "undefined" && process.env?.NEXT_PUBLIC_API_KEY) {
      return process.env.NEXT_PUBLIC_API_KEY;
    }
  } catch {
  }
  return null;
}
__name(defaultApiKey, "defaultApiKey");
var _localeOverride = null;
var _apiKeyOverride = null;
var _baseUrlOverride = null;
var _withCredentials = true;
var _onUnauthorized = null;
var _refreshHandler = null;
var _refreshInflight = null;
var RETRY_MARKER = "X-Auth-Retry";
function jwtExpMs(token) {
  try {
    const payload = token.split(".")[1];
    if (!payload) return null;
    const json = JSON.parse(atob(payload.replace(/-/g, "+").replace(/_/g, "/")));
    return typeof json.exp === "number" ? json.exp * 1e3 : null;
  } catch {
    return null;
  }
}
__name(jwtExpMs, "jwtExpMs");
function computeSnapshot() {
  const access = _storage.get(ACCESS_KEY);
  const refresh = _storage.get(REFRESH_KEY);
  const now = Date.now();
  const accessExp = access ? jwtExpMs(access) : null;
  const accessAlive = access !== null && (accessExp === null || accessExp > now);
  const refreshExp = refresh ? jwtExpMs(refresh) : null;
  const refreshAlive = refresh !== null && (refreshExp === null || refreshExp > now);
  return {
    status: accessAlive || refreshAlive ? "authenticated" : "anonymous",
    accessExpiresAt: accessExp
  };
}
__name(computeSnapshot, "computeSnapshot");
var SERVER_SNAPSHOT = { status: "anonymous", accessExpiresAt: null };
var SESSION_SYNC_EVENT = `cfg-auth:changed:${ACCESS_KEY}`;
var _snapshot = computeSnapshot();
var _sessionListeners = /* @__PURE__ */ new Set();
var _expiryTimer = null;
var _storageListenerInstalled = false;
function scheduleExpiryFlip() {
  if (!isBrowser) return;
  if (_expiryTimer !== null) {
    clearTimeout(_expiryTimer);
    _expiryTimer = null;
  }
  if (_sessionListeners.size === 0) return;
  const now = Date.now();
  const exps = [];
  const access = _storage.get(ACCESS_KEY);
  const refresh = _storage.get(REFRESH_KEY);
  const accessExp = access ? jwtExpMs(access) : null;
  const refreshExp = refresh ? jwtExpMs(refresh) : null;
  if (accessExp !== null && accessExp > now) exps.push(accessExp);
  if (refreshExp !== null && refreshExp > now) exps.push(refreshExp);
  if (!exps.length) return;
  const delay = Math.min(Math.min(...exps) - now + 250, 2147483647);
  _expiryTimer = setTimeout(notifySessionChanged, delay);
}
__name(scheduleExpiryFlip, "scheduleExpiryFlip");
function notifySessionChanged() {
  const next = computeSnapshot();
  const changed = next.status !== _snapshot.status || next.accessExpiresAt !== _snapshot.accessExpiresAt;
  if (changed) _snapshot = next;
  scheduleExpiryFlip();
  if (!changed) return;
  for (const listener of Array.from(_sessionListeners)) {
    try {
      listener();
    } catch {
    }
  }
  if (isBrowser) {
    try {
      window.dispatchEvent(new Event(SESSION_SYNC_EVENT));
    } catch {
    }
  }
}
__name(notifySessionChanged, "notifySessionChanged");
function ensureStorageSync() {
  if (!isBrowser || _storageListenerInstalled) return;
  _storageListenerInstalled = true;
  window.addEventListener("storage", (e) => {
    if (e.key === null || e.key === ACCESS_KEY || e.key === REFRESH_KEY) {
      notifySessionChanged();
    }
  });
  window.addEventListener(SESSION_SYNC_EVENT, () => notifySessionChanged());
}
__name(ensureStorageSync, "ensureStorageSync");
var _sessionExpiredHandlers = /* @__PURE__ */ new Set();
var _client = null;
function pushClientConfig() {
  if (!_client) return;
  _client.setConfig({
    baseUrl: auth.getBaseUrl(),
    credentials: _withCredentials ? "include" : "same-origin"
  });
}
__name(pushClientConfig, "pushClientConfig");
var auth = {
  // ── Storage mode ──────────────────────────────────────────────────
  getStorageMode() {
    return _storageMode;
  },
  setStorageMode(mode) {
    _storageMode = mode;
    _storage = mode === "cookie" ? cookieBackend : localStorageBackend;
    notifySessionChanged();
  },
  // ── Bearer token ──────────────────────────────────────────────────
  getToken() {
    return _storage.get(ACCESS_KEY);
  },
  setToken(token) {
    _storage.set(ACCESS_KEY, token);
    notifySessionChanged();
  },
  getRefreshToken() {
    return _storage.get(REFRESH_KEY);
  },
  setRefreshToken(token) {
    _storage.set(REFRESH_KEY, token);
    notifySessionChanged();
  },
  clearTokens() {
    _storage.set(ACCESS_KEY, null);
    _storage.set(REFRESH_KEY, null);
    notifySessionChanged();
  },
  /** Session-aware: token PRESENT and not past its `exp` (or a live refresh
   * token exists that can mint one). Prefer `getSnapshot().status` in React. */
  isAuthenticated() {
    return computeSnapshot().status === "authenticated";
  },
  // ── Session (the ONE write path for login/logout flows) ──────────
  /**
   * Persist a token pair atomically. Every login flow (OTP verify, 2FA,
   * OAuth callback) and the refresh handler should end here — do NOT
   * scatter `setToken`/`setRefreshToken` pairs through app code.
   * `refresh: undefined` keeps the current refresh token (access-only
   * rotation); `refresh: null` explicitly drops it.
   */
  setSession(tokens) {
    _storage.set(ACCESS_KEY, tokens.access);
    if (tokens.refresh !== void 0) _storage.set(REFRESH_KEY, tokens.refresh);
    notifySessionChanged();
  },
  clearSession() {
    auth.clearTokens();
  },
  // ── Reactive snapshot (for useSyncExternalStore) ──────────────────
  /**
   * @example React:
   *   const session = useSyncExternalStore(
   *     auth.subscribe, auth.getSnapshot, auth.getServerSnapshot,
   *   );
   *   const isAuthenticated = session.status === 'authenticated';
   */
  getSnapshot() {
    return _snapshot;
  },
  getServerSnapshot() {
    return SERVER_SNAPSHOT;
  },
  subscribe(listener) {
    ensureStorageSync();
    _sessionListeners.add(listener);
    notifySessionChanged();
    return () => {
      _sessionListeners.delete(listener);
      if (_sessionListeners.size === 0 && _expiryTimer !== null) {
        clearTimeout(_expiryTimer);
        _expiryTimer = null;
      }
    };
  },
  /**
   * Fired on TERMINAL 401 — after the refresh+retry path is exhausted.
   * The store has already cleared the session before calling back, so
   * handlers only need to route to login (no clear-then-redirect
   * ordering to get wrong). Returns an unsubscribe function; multiple
   * handlers compose (unlike the legacy single-slot `onUnauthorized`).
   */
  onSessionExpired(cb) {
    _sessionExpiredHandlers.add(cb);
    return () => {
      _sessionExpiredHandlers.delete(cb);
    };
  },
  // ── API key ───────────────────────────────────────────────────────
  getApiKey() {
    return _apiKeyOverride ?? _storage.get(API_KEY_KEY) ?? defaultApiKey();
  },
  setApiKey(key) {
    _apiKeyOverride = key;
  },
  setApiKeyPersist(key) {
    _apiKeyOverride = key;
    _storage.set(API_KEY_KEY, key);
  },
  clearApiKey() {
    _apiKeyOverride = null;
    _storage.set(API_KEY_KEY, null);
  },
  // ── Locale ────────────────────────────────────────────────────────
  getLocale() {
    return _localeOverride ?? detectLocale();
  },
  setLocale(locale) {
    _localeOverride = locale;
  },
  // ── Base URL ──────────────────────────────────────────────────────
  getBaseUrl() {
    const url = _baseUrlOverride ?? defaultBaseUrl();
    return url.replace(/\/$/, "");
  },
  setBaseUrl(url) {
    _baseUrlOverride = url ? url.replace(/\/$/, "") : null;
    pushClientConfig();
  },
  // ── Credentials toggle ────────────────────────────────────────────
  getWithCredentials() {
    return _withCredentials;
  },
  setWithCredentials(value) {
    _withCredentials = value;
    pushClientConfig();
  },
  // ── 401 handler ───────────────────────────────────────────────────
  /**
   * Fired when the server returns 401 AND no refresh path recovers it
   * (no refresh token, no refresh handler, refresh failed, or retry
   * still 401). The app should clear local state and redirect to login.
   *
   * NOT fired for 401 that gets transparently recovered by the refresh
   * handler — those are invisible to callers.
   */
  onUnauthorized(cb) {
    _onUnauthorized = cb;
  },
  /**
   * Register the refresh strategy. The handler receives the current
   * refresh token and must call your refresh endpoint, returning
   * `{ access, refresh? }` on success or `null` on failure.
   *
   * @example
   *   auth.setRefreshHandler(async (refresh) => {
   *     const { data } = await Auth.tokenRefreshCreate({ body: { refresh } });
   *     return data ? { access: data.access, refresh: data.refresh } : null;
   *   });
   */
  setRefreshHandler(fn) {
    _refreshHandler = fn;
  },
  /**
   * Proactively run the registered refresh handler right now, reusing the
   * SAME single-flight promise as the 401-recovery interceptor. Callers
   * (e.g. an expiry timer / focus / reconnect) get token rotation,
   * de-duplication and rotated-token persistence for free — they must NOT
   * re-implement any of it. Returns the fresh access token, or null if
   * there is no handler / no refresh token / the refresh failed.
   */
  refreshNow() {
    return tryRefresh();
  }
};
async function tryRefresh() {
  if (_refreshInflight) return _refreshInflight;
  if (!_refreshHandler) return null;
  const runRefresh = /* @__PURE__ */ __name(async () => {
    const refresh = auth.getRefreshToken();
    if (!refresh) return null;
    const result = await _refreshHandler(refresh);
    if (!result?.access) return null;
    auth.setToken(result.access);
    if (result.refresh) auth.setRefreshToken(result.refresh);
    return result.access;
  }, "runRefresh");
  _refreshInflight = (async () => {
    try {
      const locks = typeof navigator !== "undefined" ? navigator.locks : void 0;
      if (locks?.request) {
        return await locks.request(`${REFRESH_KEY}:refresh`, runRefresh);
      }
      return await runRefresh();
    } catch {
      return null;
    } finally {
      _refreshInflight = null;
    }
  })();
  return _refreshInflight;
}
__name(tryRefresh, "tryRefresh");
function expireSession(response) {
  auth.clearTokens();
  for (const cb of Array.from(_sessionExpiredHandlers)) {
    try {
      cb(response);
    } catch {
    }
  }
  if (_onUnauthorized) {
    try {
      _onUnauthorized(response);
    } catch {
    }
  }
}
__name(expireSession, "expireSession");
function dpopEnabled() {
  try {
    return typeof process !== "undefined" && process.env?.NEXT_PUBLIC_DPOP_ENABLED === "true";
  } catch {
    return false;
  }
}
__name(dpopEnabled, "dpopEnabled");
var _DPOP_DB = "cfg-auth";
var _DPOP_STORE = "keys";
var _DPOP_KEY_ID = "dpop-ec-p256";
function _idbOpen() {
  return new Promise((resolve, reject) => {
    const req = indexedDB.open(_DPOP_DB, 1);
    req.onupgradeneeded = () => req.result.createObjectStore(_DPOP_STORE);
    req.onsuccess = () => resolve(req.result);
    req.onerror = () => reject(req.error);
  });
}
__name(_idbOpen, "_idbOpen");
function _idbGet(key) {
  return _idbOpen().then((db) => new Promise((resolve, reject) => {
    const tx = db.transaction(_DPOP_STORE, "readonly");
    const req = tx.objectStore(_DPOP_STORE).get(key);
    req.onsuccess = () => resolve(req.result);
    req.onerror = () => reject(req.error);
  }));
}
__name(_idbGet, "_idbGet");
function _idbPut(key, value) {
  return _idbOpen().then((db) => new Promise((resolve, reject) => {
    const tx = db.transaction(_DPOP_STORE, "readwrite");
    tx.objectStore(_DPOP_STORE).put(value, key);
    tx.oncomplete = () => resolve();
    tx.onerror = () => reject(tx.error);
  }));
}
__name(_idbPut, "_idbPut");
var _dpopKeyPromise = null;
function _getDpopKeyPair() {
  if (_dpopKeyPromise) return _dpopKeyPromise;
  _dpopKeyPromise = (async () => {
    const existing = await _idbGet(_DPOP_KEY_ID).catch(() => void 0);
    if (existing) return existing;
    const pair = await crypto.subtle.generateKey(
      { name: "ECDSA", namedCurve: "P-256" },
      false,
      // extractable:false — JS can sign but never export the private key
      ["sign"]
    );
    await _idbPut(_DPOP_KEY_ID, pair).catch(() => {
    });
    return pair;
  })();
  return _dpopKeyPromise;
}
__name(_getDpopKeyPair, "_getDpopKeyPair");
function _b64urlFromBytes(bytes) {
  const arr = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
  let s = "";
  for (let i = 0; i < arr.length; i++) s += String.fromCharCode(arr[i]);
  return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
__name(_b64urlFromBytes, "_b64urlFromBytes");
function _b64urlFromString(str) {
  return _b64urlFromBytes(new TextEncoder().encode(str));
}
__name(_b64urlFromString, "_b64urlFromString");
async function _publicJwk(pub) {
  const jwk = await crypto.subtle.exportKey("jwk", pub);
  return { kty: "EC", crv: "P-256", x: jwk.x, y: jwk.y };
}
__name(_publicJwk, "_publicJwk");
async function _makeDpopProof(method, url) {
  try {
    const pair = await _getDpopKeyPair();
    const jwk = await _publicJwk(pair.publicKey);
    const header = { typ: "dpop+jwt", alg: "ES256", jwk };
    const htu = url.split("#")[0].split("?")[0];
    const jti = crypto.randomUUID && crypto.randomUUID() || _b64urlFromBytes(crypto.getRandomValues(new Uint8Array(16)));
    const payload = { htm: method.toUpperCase(), htu, iat: Math.floor(Date.now() / 1e3), jti };
    const signingInput = `${_b64urlFromString(JSON.stringify(header))}.${_b64urlFromString(JSON.stringify(payload))}`;
    const sig = await crypto.subtle.sign(
      { name: "ECDSA", hash: "SHA-256" },
      pair.privateKey,
      new TextEncoder().encode(signingInput)
    );
    return `${signingInput}.${_b64urlFromBytes(sig)}`;
  } catch {
    return null;
  }
}
__name(_makeDpopProof, "_makeDpopProof");
function installAuthOnClient(client2) {
  if (_client) return;
  _client = client2;
  client2.setConfig({
    baseUrl: auth.getBaseUrl(),
    credentials: _withCredentials ? "include" : "same-origin"
  });
  client2.interceptors.request.use(async (request) => {
    const token = auth.getToken();
    if (token) request.headers.set("Authorization", `Bearer ${token}`);
    const locale = auth.getLocale();
    if (locale) request.headers.set("Accept-Language", locale);
    const apiKey = auth.getApiKey();
    if (apiKey && !request.headers.has("X-API-Key")) request.headers.set("X-API-Key", apiKey);
    try {
      const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
      if (tz) request.headers.set("X-Timezone", tz);
    } catch {
    }
    request.headers.set("X-Client-Time", (/* @__PURE__ */ new Date()).toISOString());
    if (dpopEnabled() && typeof window !== "undefined") {
      const proof = await _makeDpopProof(request.method, request.url);
      if (proof) request.headers.set("DPoP", proof);
    }
    return request;
  });
  client2.interceptors.error.use((err, res, req) => {
    if (err instanceof APIError) return err;
    const url = req?.url ?? "";
    const status = res?.status ?? 0;
    const statusText = res?.statusText ?? "";
    return new APIError(status, statusText, err, url);
  });
  client2.interceptors.response.use(async (response, request) => {
    if (response.status !== 401) return response;
    if (request.headers.get(RETRY_MARKER)) {
      expireSession(response);
      return response;
    }
    const newToken = await tryRefresh();
    if (!newToken) {
      expireSession(response);
      return response;
    }
    const retry = request.clone();
    retry.headers.set("Authorization", `Bearer ${newToken}`);
    retry.headers.set(RETRY_MARKER, "1");
    if (dpopEnabled() && typeof window !== "undefined") {
      const proof = await _makeDpopProof(retry.method, retry.url);
      if (proof) retry.headers.set("DPoP", proof);
    }
    try {
      const retried = await fetch(retry);
      if (retried.status === 401) expireSession(retried);
      return retried;
    } catch {
      return response;
    }
  });
}
__name(installAuthOnClient, "installAuthOnClient");
var REFRESH_ENDPOINT = "/cfg/accounts/token/refresh/";
auth.setRefreshHandler(async (refresh) => {
  try {
    const url = `${auth.getBaseUrl()}${REFRESH_ENDPOINT}`;
    const headers = { "Content-Type": "application/json" };
    if (dpopEnabled() && typeof window !== "undefined") {
      const proof = await _makeDpopProof("POST", url);
      if (proof) headers["DPoP"] = proof;
    }
    const res = await fetch(url, {
      method: "POST",
      headers,
      credentials: auth.getWithCredentials() ? "include" : "same-origin",
      body: JSON.stringify({ refresh })
    });
    if (!res.ok) return null;
    const data = await res.json();
    return data?.access ? { access: data.access, refresh: data.refresh ?? refresh } : null;
  } catch {
    return null;
  }
});

// src/_api/generated/client.gen.ts
var client = createClient(createConfig({ baseUrl: "http://localhost:8000" }));
installAuthOnClient(client);

// src/_api/generated/sdk.gen.ts
var CfgAccountsApiKey = class {
  static {
    __name(this, "CfgAccountsApiKey");
  }
  /**
   * Get API key details
   *
   * Retrieve the current user's API key (masked) and metadata.
   */
  static cfgAccountsApiKeyRetrieve(options) {
    return (options?.client ?? client).get({
      security: [
        { scheme: "bearer", type: "http" },
        {
          in: "cookie",
          name: "sessionid",
          type: "apiKey"
        },
        { name: "X-API-Key", type: "apiKey" }
      ],
      url: "/cfg/accounts/api-key/",
      ...options
    });
  }
  /**
   * Regenerate API key
   *
   * Generate a new API key. The full key is returned only once.
   */
  static cfgAccountsApiKeyRegenerateCreate(options) {
    return (options.client ?? client).post({
      security: [
        { scheme: "bearer", type: "http" },
        {
          in: "cookie",
          name: "sessionid",
          type: "apiKey"
        },
        { name: "X-API-Key", type: "apiKey" }
      ],
      url: "/cfg/accounts/api-key/regenerate/",
      ...options,
      headers: {
        "Content-Type": "application/json",
        ...options.headers
      }
    });
  }
  /**
   * Reveal API key
   *
   * Return the current full API key WITHOUT rotating it. The same durable value every one of the user's agents uses — for the signed-in user to copy and paste into agent onboarding. Default GET stays masked; this is the explicit reveal action.
   */
  static cfgAccountsApiKeyRevealCreate(options) {
    return (options.client ?? client).post({
      security: [
        { scheme: "bearer", type: "http" },
        {
          in: "cookie",
          name: "sessionid",
          type: "apiKey"
        },
        { name: "X-API-Key", type: "apiKey" }
      ],
      url: "/cfg/accounts/api-key/reveal/",
      ...options,
      headers: {
        "Content-Type": "application/json",
        ...options.headers
      }
    });
  }
  /**
   * Test API key
   *
   * Test whether an API key is valid without consuming it.
   */
  static cfgAccountsApiKeyTestCreate(options) {
    return (options.client ?? client).post({
      security: [
        { scheme: "bearer", type: "http" },
        {
          in: "cookie",
          name: "sessionid",
          type: "apiKey"
        },
        { name: "X-API-Key", type: "apiKey" }
      ],
      url: "/cfg/accounts/api-key/test/",
      ...options,
      headers: {
        "Content-Type": "application/json",
        ...options.headers
      }
    });
  }
};

// src/_api/generated/_cfg_accounts/schemas/APIKeyRegenerate.ts
import { z } from "zod";
var APIKeyRegenerateSchema = z.object({
  key: z.string(),
  reissued_at: z.string().datetime({ offset: true })
});

// src/_api/generated/_cfg_accounts/hooks/useCfgAccountsApiKeyRegenerateCreate.ts
function useCfgAccountsApiKeyRegenerateCreate(config) {
  return useSWRMutation(
    ["cfg_accounts_api_key_regenerate_create"],
    async (_key, { arg }) => {
      const res = await CfgAccountsApiKey.cfgAccountsApiKeyRegenerateCreate({ ...arg, throwOnError: true });
      const data = res.data;
      const parsed = APIKeyRegenerateSchema.safeParse(data);
      if (!parsed.success) {
        console.warn(
          "[zod] response did not match schema",
          {
            operation: "cfg_accounts_api_key_regenerate_create",
            method: "POST",
            path: "/cfg/accounts/api-key/regenerate/",
            issues: parsed.error.issues,
            data
          }
        );
        if (typeof window !== "undefined") {
          try {
            window.dispatchEvent(
              new CustomEvent("zod-validation-error", {
                detail: {
                  operation: "cfg_accounts_api_key_regenerate_create",
                  method: "POST",
                  path: "/cfg/accounts/api-key/regenerate/",
                  issues: parsed.error.issues,
                  data,
                  timestamp: /* @__PURE__ */ new Date()
                },
                bubbles: true,
                cancelable: false
              })
            );
          } catch {
          }
        }
        return data;
      }
      return parsed.data;
    },
    config
  );
}
__name(useCfgAccountsApiKeyRegenerateCreate, "useCfgAccountsApiKeyRegenerateCreate");

// src/_api/generated/_cfg_accounts/hooks/useCfgAccountsApiKeyRetrieve.ts
import useSWR from "swr";

// src/_api/generated/_cfg_accounts/schemas/APIKey.ts
import { z as z2 } from "zod";
var APIKeySchema = z2.object({
  key: z2.string(),
  reissued_at: z2.string().datetime({ offset: true }).nullable(),
  created_at: z2.string().datetime({ offset: true })
});

// src/_api/generated/_cfg_accounts/hooks/useCfgAccountsApiKeyRetrieve.ts
function useCfgAccountsApiKeyRetrieve(args, config) {
  const { enabled = true, ...swrConfig } = config ?? {};
  const key = enabled ? ["cfg_accounts_api_key_retrieve", args ?? {}] : null;
  return useSWR(
    key,
    async () => {
      const res = await CfgAccountsApiKey.cfgAccountsApiKeyRetrieve({ ...args ?? {}, throwOnError: true });
      const data = res.data;
      const parsed = APIKeySchema.safeParse(data);
      if (!parsed.success) {
        console.warn(
          "[zod] response did not match schema",
          {
            operation: "cfg_accounts_api_key_retrieve",
            method: "GET",
            path: "/cfg/accounts/api-key/",
            issues: parsed.error.issues,
            data
          }
        );
        if (typeof window !== "undefined") {
          try {
            window.dispatchEvent(
              new CustomEvent("zod-validation-error", {
                detail: {
                  operation: "cfg_accounts_api_key_retrieve",
                  method: "GET",
                  path: "/cfg/accounts/api-key/",
                  issues: parsed.error.issues,
                  data,
                  timestamp: /* @__PURE__ */ new Date()
                },
                bubbles: true,
                cancelable: false
              })
            );
          } catch {
          }
        }
        return data;
      }
      return parsed.data;
    },
    swrConfig
  );
}
__name(useCfgAccountsApiKeyRetrieve, "useCfgAccountsApiKeyRetrieve");

// src/_api/generated/_cfg_accounts/hooks/useCfgAccountsApiKeyRevealCreate.ts
import useSWRMutation2 from "swr/mutation";

// src/_api/generated/_cfg_accounts/schemas/APIKeyReveal.ts
import { z as z3 } from "zod";
var APIKeyRevealSchema = z3.object({
  key: z3.string(),
  created_at: z3.string().datetime({ offset: true }),
  reissued_at: z3.string().datetime({ offset: true }).nullable()
});

// src/_api/generated/_cfg_accounts/hooks/useCfgAccountsApiKeyRevealCreate.ts
function useCfgAccountsApiKeyRevealCreate(config) {
  return useSWRMutation2(
    ["cfg_accounts_api_key_reveal_create"],
    async (_key, { arg }) => {
      const res = await CfgAccountsApiKey.cfgAccountsApiKeyRevealCreate({ ...arg, throwOnError: true });
      const data = res.data;
      const parsed = APIKeyRevealSchema.safeParse(data);
      if (!parsed.success) {
        console.warn(
          "[zod] response did not match schema",
          {
            operation: "cfg_accounts_api_key_reveal_create",
            method: "POST",
            path: "/cfg/accounts/api-key/reveal/",
            issues: parsed.error.issues,
            data
          }
        );
        if (typeof window !== "undefined") {
          try {
            window.dispatchEvent(
              new CustomEvent("zod-validation-error", {
                detail: {
                  operation: "cfg_accounts_api_key_reveal_create",
                  method: "POST",
                  path: "/cfg/accounts/api-key/reveal/",
                  issues: parsed.error.issues,
                  data,
                  timestamp: /* @__PURE__ */ new Date()
                },
                bubbles: true,
                cancelable: false
              })
            );
          } catch {
          }
        }
        return data;
      }
      return parsed.data;
    },
    config
  );
}
__name(useCfgAccountsApiKeyRevealCreate, "useCfgAccountsApiKeyRevealCreate");

// src/_api/generated/_cfg_accounts/hooks/useCfgAccountsApiKeyTestCreate.ts
import useSWRMutation3 from "swr/mutation";

// src/_api/generated/_cfg_accounts/schemas/APIKeyTestResult.ts
import { z as z4 } from "zod";
var APIKeyTestResultSchema = z4.object({
  valid: z4.boolean(),
  user_id: z4.string().nullable()
});

// src/_api/generated/_cfg_accounts/hooks/useCfgAccountsApiKeyTestCreate.ts
function useCfgAccountsApiKeyTestCreate(config) {
  return useSWRMutation3(
    ["cfg_accounts_api_key_test_create"],
    async (_key, { arg }) => {
      const res = await CfgAccountsApiKey.cfgAccountsApiKeyTestCreate({ ...arg, throwOnError: true });
      const data = res.data;
      const parsed = APIKeyTestResultSchema.safeParse(data);
      if (!parsed.success) {
        console.warn(
          "[zod] response did not match schema",
          {
            operation: "cfg_accounts_api_key_test_create",
            method: "POST",
            path: "/cfg/accounts/api-key/test/",
            issues: parsed.error.issues,
            data
          }
        );
        if (typeof window !== "undefined") {
          try {
            window.dispatchEvent(
              new CustomEvent("zod-validation-error", {
                detail: {
                  operation: "cfg_accounts_api_key_test_create",
                  method: "POST",
                  path: "/cfg/accounts/api-key/test/",
                  issues: parsed.error.issues,
                  data,
                  timestamp: /* @__PURE__ */ new Date()
                },
                bubbles: true,
                cancelable: false
              })
            );
          } catch {
          }
        }
        return data;
      }
      return parsed.data;
    },
    config
  );
}
__name(useCfgAccountsApiKeyTestCreate, "useCfgAccountsApiKeyTestCreate");

// src/hooks/useApiKey.ts
function useApiKey() {
  const { data, isLoading, mutate } = useCfgAccountsApiKeyRetrieve();
  const { trigger: revealTrigger, isMutating: isRevealing } = useCfgAccountsApiKeyRevealCreate();
  const { trigger: regenerateTrigger, isMutating: isRegenerating } = useCfgAccountsApiKeyRegenerateCreate();
  const { trigger: testTrigger, isMutating: isTesting } = useCfgAccountsApiKeyTestCreate();
  const [freshKey, setFreshKey] = useState(null);
  const apiKey = freshKey ?? (data?.key ?? null);
  const isRevealed = freshKey !== null;
  const reissuedAt = data?.reissued_at ?? null;
  const createdAt = data?.created_at ?? null;
  const reveal = useCallback(async () => {
    const result = await revealTrigger({});
    const fullKey = result?.key;
    if (fullKey) {
      setFreshKey(fullKey);
    }
  }, [revealTrigger]);
  const regenerate = useCallback(async () => {
    const result = await regenerateTrigger({});
    const newKey = result?.key;
    if (newKey) {
      setFreshKey(newKey);
    }
  }, [regenerateTrigger]);
  const testKey = useCallback(async (key) => {
    const result = await testTrigger({ body: { key } });
    const record = result;
    return {
      valid: Boolean(record?.valid),
      userId: record?.user_id ?? null
    };
  }, [testTrigger]);
  const refresh = useCallback(() => {
    setFreshKey(null);
    mutate();
  }, [mutate]);
  return {
    apiKey,
    isRevealed,
    reissuedAt,
    createdAt,
    isLoading,
    isRevealing,
    isRegenerating,
    isTesting,
    reveal,
    regenerate,
    testKey,
    refresh
  };
}
__name(useApiKey, "useApiKey");
export {
  useApiKey
};
//# sourceMappingURL=hooks.mjs.map