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

// src/auth/middlewares/proxy.ts
import { NextResponse } from "next/server";
function proxyMiddleware(request) {
  const { pathname, search } = request.nextUrl;
  const apiUrl2 = process.env.NEXT_PUBLIC_API_URL;
  if (pathname.startsWith("/media/")) {
    const targetUrl = `${apiUrl2}${pathname}${search}`;
    return NextResponse.rewrite(targetUrl, { request: { headers: request.headers } });
  }
  if (pathname.startsWith("/api/")) {
    const targetUrl = `${apiUrl2}${pathname}${search}`;
    return NextResponse.rewrite(targetUrl, { request: { headers: request.headers } });
  }
  return NextResponse.next();
}
__name(proxyMiddleware, "proxyMiddleware");
var proxyMiddlewareConfig = {
  matcher: ["/media/:path*", "/api/:path*"]
};

// src/generated/cfg_accounts/accounts__auth/client.ts
var Auth = class {
  static {
    __name(this, "Auth");
  }
  constructor(client) {
    this.client = client;
  }
  /**
   * Refresh JWT token.
   */
  async accountsTokenRefreshCreate(data) {
    const response = await this.client.request("POST", "/cfg/accounts/token/refresh/", { body: data });
    return response;
  }
};

// src/generated/cfg_accounts/accounts__oauth/client.ts
var Oauth = class {
  static {
    __name(this, "Oauth");
  }
  constructor(client) {
    this.client = client;
  }
  /**
   * List OAuth connections
   * 
   * Get all OAuth connections for the current user.
   */
  async accountsOauthConnectionsList() {
    const response = await this.client.request("GET", "/cfg/accounts/oauth/connections/");
    return response;
  }
  /**
   * Disconnect OAuth provider
   * 
   * Remove OAuth connection for the specified provider.
   */
  async accountsOauthDisconnectCreate(data) {
    const response = await this.client.request("POST", "/cfg/accounts/oauth/disconnect/", { body: data });
    return response;
  }
  /**
   * Start GitHub OAuth
   * 
   * Generate GitHub OAuth authorization URL. Redirect user to this URL to
   * start authentication.
   */
  async accountsOauthGithubAuthorizeCreate(data) {
    const response = await this.client.request("POST", "/cfg/accounts/oauth/github/authorize/", { body: data });
    return response;
  }
  /**
   * Complete GitHub OAuth
   * 
   * Exchange authorization code for JWT tokens. Call this after GitHub
   * redirects back with code.
   */
  async accountsOauthGithubCallbackCreate(data) {
    const response = await this.client.request("POST", "/cfg/accounts/oauth/github/callback/", { body: data });
    return response;
  }
  /**
   * List OAuth providers
   * 
   * Get list of available OAuth providers for authentication.
   */
  async accountsOauthProvidersRetrieve() {
    const response = await this.client.request("GET", "/cfg/accounts/oauth/providers/");
    return response;
  }
};

// src/generated/cfg_accounts/accounts__user_profile/client.ts
var UserProfile = class {
  static {
    __name(this, "UserProfile");
  }
  constructor(client) {
    this.client = client;
  }
  /**
   * Get current user profile
   * 
   * Retrieve the current authenticated user's profile information.
   */
  async accountsProfileRetrieve() {
    const response = await this.client.request("GET", "/cfg/accounts/profile/");
    return response;
  }
  /**
   * Upload user avatar
   * 
   * Upload avatar image for the current authenticated user. Accepts
   * multipart/form-data with 'avatar' field.
   */
  async accountsProfileAvatarCreate(data) {
    const formData = new FormData();
    formData.append("avatar", data.avatar);
    const response = await this.client.request("POST", "/cfg/accounts/profile/avatar/", { formData });
    return response;
  }
  /**
   * Delete user account
   * 
   * Permanently delete the current user's account. This operation: -
   * Deactivates the account (user cannot log in) - Anonymizes personal data
   * (GDPR compliance) - Frees up the email address for re-registration -
   * Preserves audit trail The account can be restored by an administrator if
   * needed.
   */
  async accountsProfileDeleteCreate() {
    const response = await this.client.request("POST", "/cfg/accounts/profile/delete/");
    return response;
  }
  /**
   * Partial update user profile
   * 
   * Partially update the current authenticated user's profile information.
   * Supports avatar upload.
   */
  async accountsProfilePartialUpdate(data) {
    const response = await this.client.request("PUT", "/cfg/accounts/profile/partial/", { body: data });
    return response;
  }
  /**
   * Partial update user profile
   * 
   * Partially update the current authenticated user's profile information.
   * Supports avatar upload.
   */
  async accountsProfilePartialPartialUpdate(data) {
    const response = await this.client.request("PATCH", "/cfg/accounts/profile/partial/", { body: data });
    return response;
  }
  /**
   * Update user profile
   * 
   * Update the current authenticated user's profile information.
   */
  async accountsProfileUpdateUpdate(data) {
    const response = await this.client.request("PUT", "/cfg/accounts/profile/update/", { body: data });
    return response;
  }
  /**
   * Update user profile
   * 
   * Update the current authenticated user's profile information.
   */
  async accountsProfileUpdatePartialUpdate(data) {
    const response = await this.client.request("PATCH", "/cfg/accounts/profile/update/", { body: data });
    return response;
  }
};

// src/generated/cfg_accounts/accounts/client.ts
var Accounts = class {
  static {
    __name(this, "Accounts");
  }
  constructor(client) {
    this.client = client;
  }
  /**
   * Request OTP code to email or phone.
   */
  async otpRequestCreate(data) {
    const response = await this.client.request("POST", "/cfg/accounts/otp/request/", { body: data });
    return response;
  }
  /**
   * Verify OTP code and return JWT tokens or 2FA session. If user has 2FA
   * enabled: - Returns requires_2fa=True with session_id - Client must
   * complete 2FA verification at /cfg/totp/verify/ If user has no 2FA: -
   * Returns JWT tokens and user data directly
   */
  async otpVerifyCreate(data) {
    const response = await this.client.request("POST", "/cfg/accounts/otp/verify/", { body: data });
    return response;
  }
};

// src/generated/cfg_accounts/http.ts
var FetchAdapter = class {
  static {
    __name(this, "FetchAdapter");
  }
  async request(request) {
    const { method, url, headers, body, params, formData, binaryBody } = request;
    let finalUrl = url;
    if (params) {
      const searchParams = new URLSearchParams();
      Object.entries(params).forEach(([key, value]) => {
        if (value !== null && value !== void 0) {
          searchParams.append(key, String(value));
        }
      });
      const queryString = searchParams.toString();
      if (queryString) {
        finalUrl = url.includes("?") ? `${url}&${queryString}` : `${url}?${queryString}`;
      }
    }
    const finalHeaders = { ...headers };
    let requestBody;
    if (formData) {
      requestBody = formData;
    } else if (binaryBody) {
      finalHeaders["Content-Type"] = "application/octet-stream";
      requestBody = binaryBody;
    } else if (body) {
      finalHeaders["Content-Type"] = "application/json";
      requestBody = JSON.stringify(body);
    }
    const response = await fetch(finalUrl, {
      method,
      headers: finalHeaders,
      body: requestBody,
      credentials: "include"
      // Include Django session cookies
    });
    let data = null;
    const contentType = response.headers.get("content-type");
    if (response.status !== 204 && contentType?.includes("application/json")) {
      data = await response.json();
    } else if (response.status !== 204) {
      data = await response.text();
    }
    const responseHeaders = {};
    response.headers.forEach((value, key) => {
      responseHeaders[key] = value;
    });
    return {
      data,
      status: response.status,
      statusText: response.statusText,
      headers: responseHeaders
    };
  }
};

// src/generated/cfg_accounts/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";
  }
  static {
    __name(this, "APIError");
  }
  /**
   * Get error details from response.
   * DRF typically returns: { "detail": "Error message" } or { "field": ["error1", "error2"] }
   */
  get details() {
    if (typeof this.response === "object" && this.response !== null) {
      return this.response;
    }
    return null;
  }
  /**
   * Get field-specific validation errors from DRF.
   * Returns: { "field_name": ["error1", "error2"], ... }
   */
  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 single error message from DRF.
   * Checks for "detail", "message", or first field error.
   */
  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.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;
  }
  // Helper methods for common HTTP status codes
  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;
  }
};
var NetworkError = class extends Error {
  constructor(message, url, originalError) {
    super(message);
    this.url = url;
    this.originalError = originalError;
    this.name = "NetworkError";
  }
  static {
    __name(this, "NetworkError");
  }
};

// src/generated/cfg_accounts/logger.ts
import { createConsola } from "consola";
var DEFAULT_CONFIG = {
  enabled: process.env.NODE_ENV !== "production",
  logRequests: true,
  logResponses: true,
  logErrors: true,
  logBodies: true,
  logHeaders: false
};
var SENSITIVE_HEADERS = [
  "authorization",
  "cookie",
  "set-cookie",
  "x-api-key",
  "x-csrf-token"
];
var APILogger = class {
  static {
    __name(this, "APILogger");
  }
  constructor(config = {}) {
    this.config = { ...DEFAULT_CONFIG, ...config };
    this.consola = config.consola || createConsola({
      level: this.config.enabled ? 4 : 0
    });
  }
  /**
   * Enable logging
   */
  enable() {
    this.config.enabled = true;
  }
  /**
   * Disable logging
   */
  disable() {
    this.config.enabled = false;
  }
  /**
   * Update configuration
   */
  setConfig(config) {
    this.config = { ...this.config, ...config };
  }
  /**
   * Filter sensitive headers
   */
  filterHeaders(headers) {
    if (!headers) return {};
    const filtered = {};
    Object.keys(headers).forEach((key) => {
      const lowerKey = key.toLowerCase();
      if (SENSITIVE_HEADERS.includes(lowerKey)) {
        filtered[key] = "***";
      } else {
        filtered[key] = headers[key] || "";
      }
    });
    return filtered;
  }
  /**
   * Log request
   */
  logRequest(request) {
    if (!this.config.enabled || !this.config.logRequests) return;
    const { method, url, headers, body } = request;
    this.consola.start(`${method} ${url}`);
    if (this.config.logHeaders && headers) {
      this.consola.debug("Headers:", this.filterHeaders(headers));
    }
    if (this.config.logBodies && body) {
      this.consola.debug("Body:", body);
    }
  }
  /**
   * Log response
   */
  logResponse(request, response) {
    if (!this.config.enabled || !this.config.logResponses) return;
    const { method, url } = request;
    const { status, statusText, data, duration } = response;
    const statusColor = status >= 500 ? "red" : status >= 400 ? "yellow" : status >= 300 ? "cyan" : "green";
    this.consola.success(
      `${method} ${url} ${status} ${statusText} (${duration}ms)`
    );
    if (this.config.logBodies && data) {
      this.consola.debug("Response:", data);
    }
  }
  /**
   * Log error
   */
  logError(request, error) {
    if (!this.config.enabled || !this.config.logErrors) return;
    const { method, url } = request;
    const { message, statusCode, fieldErrors, duration } = error;
    this.consola.error(
      `${method} ${url} ${statusCode || "Network"} Error (${duration}ms)`
    );
    this.consola.error("Message:", message);
    if (fieldErrors && Object.keys(fieldErrors).length > 0) {
      this.consola.error("Field Errors:");
      Object.entries(fieldErrors).forEach(([field, errors]) => {
        errors.forEach((err) => {
          this.consola.error(`  \u2022 ${field}: ${err}`);
        });
      });
    }
  }
  /**
   * Log general info
   */
  info(message, ...args) {
    if (!this.config.enabled) return;
    this.consola.info(message, ...args);
  }
  /**
   * Log warning
   */
  warn(message, ...args) {
    if (!this.config.enabled) return;
    this.consola.warn(message, ...args);
  }
  /**
   * Log error
   */
  error(message, ...args) {
    if (!this.config.enabled) return;
    this.consola.error(message, ...args);
  }
  /**
   * Log debug
   */
  debug(message, ...args) {
    if (!this.config.enabled) return;
    this.consola.debug(message, ...args);
  }
  /**
   * Log success
   */
  success(message, ...args) {
    if (!this.config.enabled) return;
    this.consola.success(message, ...args);
  }
  /**
   * Create a sub-logger with prefix
   */
  withTag(tag) {
    return this.consola.withTag(tag);
  }
};
var defaultLogger = new APILogger();

// src/generated/cfg_accounts/retry.ts
import pRetry, { AbortError } from "p-retry";
var DEFAULT_RETRY_CONFIG = {
  retries: 3,
  factor: 2,
  minTimeout: 1e3,
  maxTimeout: 6e4,
  randomize: true,
  onFailedAttempt: /* @__PURE__ */ __name(() => {
  }, "onFailedAttempt")
};
function shouldRetry(error) {
  if (error instanceof NetworkError) {
    return true;
  }
  if (error instanceof APIError) {
    const status = error.statusCode;
    if (status >= 500 && status < 600) {
      return true;
    }
    if (status === 429) {
      return true;
    }
    return false;
  }
  return true;
}
__name(shouldRetry, "shouldRetry");
async function withRetry(fn, config) {
  const finalConfig = { ...DEFAULT_RETRY_CONFIG, ...config };
  return pRetry(
    async () => {
      try {
        return await fn();
      } catch (error) {
        if (!shouldRetry(error)) {
          throw new AbortError(error);
        }
        throw error;
      }
    },
    {
      retries: finalConfig.retries,
      factor: finalConfig.factor,
      minTimeout: finalConfig.minTimeout,
      maxTimeout: finalConfig.maxTimeout,
      randomize: finalConfig.randomize,
      onFailedAttempt: finalConfig.onFailedAttempt ? (error) => {
        const pRetryError = error;
        finalConfig.onFailedAttempt({
          error: pRetryError,
          attemptNumber: pRetryError.attemptNumber,
          retriesLeft: pRetryError.retriesLeft
        });
      } : void 0
    }
  );
}
__name(withRetry, "withRetry");

// src/generated/cfg_accounts/client.ts
var APIClient = class {
  constructor(baseUrl, options) {
    this.logger = null;
    this.retryConfig = null;
    this.tokenGetter = null;
    this.baseUrl = baseUrl.replace(/\/$/, "");
    this.httpClient = options?.httpClient || new FetchAdapter();
    this.tokenGetter = options?.tokenGetter || null;
    if (options?.loggerConfig !== void 0) {
      this.logger = new APILogger(options.loggerConfig);
    }
    if (options?.retryConfig !== void 0) {
      this.retryConfig = options.retryConfig;
    }
    this.auth = new Auth(this);
    this.oauth = new Oauth(this);
    this.user_profile = new UserProfile(this);
    this.accounts = new Accounts(this);
  }
  static {
    __name(this, "APIClient");
  }
  /**
   * Get CSRF token from cookies (for SessionAuthentication).
   *
   * Returns null if cookie doesn't exist (JWT-only auth).
   */
  getCsrfToken() {
    const name = "csrftoken";
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) {
      return parts.pop()?.split(";").shift() || null;
    }
    return null;
  }
  /**
   * Get the base URL for building streaming/download URLs.
   */
  getBaseUrl() {
    return this.baseUrl;
  }
  /**
   * Get JWT token for URL authentication (used in streaming endpoints).
   * Returns null if no token getter is configured or no token is available.
   */
  getToken() {
    return this.tokenGetter ? this.tokenGetter() : null;
  }
  /**
   * Make HTTP request with Django CSRF and session handling.
   * Automatically retries on network errors and 5xx server errors.
   */
  async request(method, path, options) {
    if (this.retryConfig) {
      return withRetry(() => this._makeRequest(method, path, options), {
        ...this.retryConfig,
        onFailedAttempt: /* @__PURE__ */ __name((info) => {
          if (this.logger) {
            this.logger.warn(
              `Retry attempt ${info.attemptNumber}/${info.retriesLeft + info.attemptNumber} for ${method} ${path}: ${info.error.message}`
            );
          }
          this.retryConfig?.onFailedAttempt?.(info);
        }, "onFailedAttempt")
      });
    }
    return this._makeRequest(method, path, options);
  }
  /**
   * Internal request method (without retry wrapper).
   * Used by request() method with optional retry logic.
   */
  async _makeRequest(method, path, options) {
    const url = this.baseUrl ? `${this.baseUrl}${path}` : path;
    const startTime = Date.now();
    const headers = {
      ...options?.headers || {}
    };
    if (!options?.formData && !options?.binaryBody && !headers["Content-Type"]) {
      headers["Content-Type"] = "application/json";
    }
    if (this.logger) {
      this.logger.logRequest({
        method,
        url,
        headers,
        body: options?.formData || options?.body,
        timestamp: startTime
      });
    }
    try {
      const response = await this.httpClient.request({
        method,
        url,
        headers,
        params: options?.params,
        body: options?.body,
        formData: options?.formData,
        binaryBody: options?.binaryBody
      });
      const duration = Date.now() - startTime;
      if (response.status >= 400) {
        const error = new APIError(
          response.status,
          response.statusText,
          response.data,
          url
        );
        if (this.logger) {
          this.logger.logError(
            {
              method,
              url,
              headers,
              body: options?.formData || options?.body,
              timestamp: startTime
            },
            {
              message: error.message,
              statusCode: response.status,
              duration,
              timestamp: Date.now()
            }
          );
        }
        throw error;
      }
      if (this.logger) {
        this.logger.logResponse(
          {
            method,
            url,
            headers,
            body: options?.formData || options?.body,
            timestamp: startTime
          },
          {
            status: response.status,
            statusText: response.statusText,
            data: response.data,
            duration,
            timestamp: Date.now()
          }
        );
      }
      return response.data;
    } catch (error) {
      const duration = Date.now() - startTime;
      if (error instanceof APIError) {
        throw error;
      }
      const isCORSError = error instanceof TypeError && (error.message.toLowerCase().includes("cors") || error.message.toLowerCase().includes("failed to fetch") || error.message.toLowerCase().includes("network request failed"));
      if (this.logger) {
        if (isCORSError) {
          this.logger.error(`\u{1F6AB} CORS Error: ${method} ${url}`);
          this.logger.error(`  \u2192 ${error instanceof Error ? error.message : String(error)}`);
          this.logger.error(`  \u2192 Configure security_domains parameter on the server`);
        } else {
          this.logger.error(`\u26A0\uFE0F  Network Error: ${method} ${url}`);
          this.logger.error(`  \u2192 ${error instanceof Error ? error.message : String(error)}`);
        }
      }
      if (typeof window !== "undefined") {
        try {
          if (isCORSError) {
            window.dispatchEvent(new CustomEvent("cors-error", {
              detail: {
                url,
                method,
                error: error instanceof Error ? error.message : String(error),
                timestamp: /* @__PURE__ */ new Date()
              },
              bubbles: true,
              cancelable: false
            }));
          } else {
            window.dispatchEvent(new CustomEvent("network-error", {
              detail: {
                url,
                method,
                error: error instanceof Error ? error.message : String(error),
                timestamp: /* @__PURE__ */ new Date()
              },
              bubbles: true,
              cancelable: false
            }));
          }
        } catch (eventError) {
        }
      }
      const networkError = error instanceof Error ? new NetworkError(error.message, url, error) : new NetworkError("Unknown error", url);
      if (this.logger) {
        this.logger.logError(
          {
            method,
            url,
            headers,
            body: options?.formData || options?.body,
            timestamp: startTime
          },
          {
            message: networkError.message,
            duration,
            timestamp: Date.now()
          }
        );
      }
      throw networkError;
    }
  }
};

// src/generated/cfg_accounts/storage.ts
var LocalStorageAdapter = class {
  static {
    __name(this, "LocalStorageAdapter");
  }
  constructor(logger2) {
    this.logger = logger2;
  }
  getItem(key) {
    try {
      if (typeof window !== "undefined" && window.localStorage) {
        const value = localStorage.getItem(key);
        this.logger?.debug(`LocalStorage.getItem("${key}"): ${value ? "found" : "not found"}`);
        return value;
      }
      this.logger?.warn("LocalStorage not available: window.localStorage is undefined");
    } catch (error) {
      this.logger?.error("LocalStorage.getItem failed:", error);
    }
    return null;
  }
  setItem(key, value) {
    try {
      if (typeof window !== "undefined" && window.localStorage) {
        localStorage.setItem(key, value);
        this.logger?.debug(`LocalStorage.setItem("${key}"): success`);
      } else {
        this.logger?.warn("LocalStorage not available: window.localStorage is undefined");
      }
    } catch (error) {
      this.logger?.error("LocalStorage.setItem failed:", error);
    }
  }
  removeItem(key) {
    try {
      if (typeof window !== "undefined" && window.localStorage) {
        localStorage.removeItem(key);
        this.logger?.debug(`LocalStorage.removeItem("${key}"): success`);
      } else {
        this.logger?.warn("LocalStorage not available: window.localStorage is undefined");
      }
    } catch (error) {
      this.logger?.error("LocalStorage.removeItem failed:", error);
    }
  }
};

// src/generated/cfg_accounts/enums.ts
var OAuthConnectionProvider = /* @__PURE__ */ ((OAuthConnectionProvider2) => {
  OAuthConnectionProvider2["GITHUB"] = "github";
  return OAuthConnectionProvider2;
})(OAuthConnectionProvider || {});
var OAuthDisconnectRequestRequestProvider = /* @__PURE__ */ ((OAuthDisconnectRequestRequestProvider2) => {
  OAuthDisconnectRequestRequestProvider2["GITHUB"] = "github";
  return OAuthDisconnectRequestRequestProvider2;
})(OAuthDisconnectRequestRequestProvider || {});
var OTPRequestRequestChannel = /* @__PURE__ */ ((OTPRequestRequestChannel2) => {
  OTPRequestRequestChannel2["EMAIL"] = "email";
  OTPRequestRequestChannel2["PHONE"] = "phone";
  return OTPRequestRequestChannel2;
})(OTPRequestRequestChannel || {});
var OTPVerifyRequestChannel = /* @__PURE__ */ ((OTPVerifyRequestChannel2) => {
  OTPVerifyRequestChannel2["EMAIL"] = "email";
  OTPVerifyRequestChannel2["PHONE"] = "phone";
  return OTPVerifyRequestChannel2;
})(OTPVerifyRequestChannel || {});

// src/generated/cfg_accounts/_utils/schemas/AccountDeleteResponse.schema.ts
import { z } from "zod";
var AccountDeleteResponseSchema = z.object({
  success: z.boolean(),
  message: z.string()
});

// src/generated/cfg_accounts/_utils/schemas/CentrifugoToken.schema.ts
import { z as z2 } from "zod";
var CentrifugoTokenSchema = z2.object({
  token: z2.string(),
  centrifugo_url: z2.union([z2.url(), z2.literal("")]),
  expires_at: z2.iso.datetime(),
  channels: z2.array(z2.string())
});

// src/generated/cfg_accounts/_utils/schemas/CfgAccountsProfileAvatarCreateRequest.schema.ts
import { z as z3 } from "zod";
var CfgAccountsProfileAvatarCreateRequestSchema = z3.object({
  avatar: z3.union([z3.instanceof(File), z3.instanceof(Blob)])
});

// src/generated/cfg_accounts/_utils/schemas/OAuthAuthorizeRequestRequest.schema.ts
import { z as z4 } from "zod";
var OAuthAuthorizeRequestRequestSchema = z4.object({
  redirect_uri: z4.union([z4.url(), z4.literal("")]).optional(),
  source_url: z4.union([z4.url(), z4.literal("")]).optional()
});

// src/generated/cfg_accounts/_utils/schemas/OAuthAuthorizeResponse.schema.ts
import { z as z5 } from "zod";
var OAuthAuthorizeResponseSchema = z5.object({
  authorization_url: z5.union([z5.url(), z5.literal("")]),
  state: z5.string()
});

// src/generated/cfg_accounts/_utils/schemas/OAuthCallbackRequestRequest.schema.ts
import { z as z6 } from "zod";
var OAuthCallbackRequestRequestSchema = z6.object({
  code: z6.string().min(10).max(500),
  state: z6.string().min(20).max(100),
  redirect_uri: z6.union([z6.url(), z6.literal("")]).optional()
});

// src/generated/cfg_accounts/_utils/schemas/OAuthConnection.schema.ts
import { z as z7 } from "zod";
var OAuthConnectionSchema = z7.object({
  id: z7.int(),
  provider: z7.nativeEnum(OAuthConnectionProvider),
  provider_display: z7.string(),
  provider_username: z7.string(),
  provider_email: z7.email(),
  provider_avatar_url: z7.union([z7.url(), z7.literal("")]),
  connected_at: z7.iso.datetime(),
  last_login_at: z7.iso.datetime()
});

// src/generated/cfg_accounts/_utils/schemas/OAuthDisconnectRequestRequest.schema.ts
import { z as z8 } from "zod";
var OAuthDisconnectRequestRequestSchema = z8.object({
  provider: z8.nativeEnum(OAuthDisconnectRequestRequestProvider)
});

// src/generated/cfg_accounts/_utils/schemas/OAuthError.schema.ts
import { z as z9 } from "zod";
var OAuthErrorSchema = z9.object({
  error: z9.string(),
  error_description: z9.string().optional()
});

// src/generated/cfg_accounts/_utils/schemas/OAuthProvidersResponse.schema.ts
import { z as z10 } from "zod";
var OAuthProvidersResponseSchema = z10.object({
  providers: z10.array(z10.record(z10.string(), z10.any()))
});

// src/generated/cfg_accounts/_utils/schemas/OAuthTokenResponse.schema.ts
import { z as z11 } from "zod";
var OAuthTokenResponseSchema = z11.object({
  requires_2fa: z11.boolean().optional(),
  session_id: z11.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i).nullable().optional(),
  access: z11.string().nullable().optional(),
  refresh: z11.string().nullable().optional(),
  user: z11.record(z11.string(), z11.any()).nullable().optional(),
  is_new_user: z11.boolean(),
  is_new_connection: z11.boolean(),
  should_prompt_2fa: z11.boolean().optional()
});

// src/generated/cfg_accounts/_utils/schemas/OTPErrorResponse.schema.ts
import { z as z12 } from "zod";
var OTPErrorResponseSchema = z12.object({
  error: z12.string()
});

// src/generated/cfg_accounts/_utils/schemas/OTPRequestRequest.schema.ts
import { z as z13 } from "zod";
var OTPRequestRequestSchema = z13.object({
  identifier: z13.string().min(1),
  channel: z13.nativeEnum(OTPRequestRequestChannel).optional(),
  source_url: z13.union([z13.url(), z13.literal("")]).optional()
});

// src/generated/cfg_accounts/_utils/schemas/OTPRequestResponse.schema.ts
import { z as z14 } from "zod";
var OTPRequestResponseSchema = z14.object({
  message: z14.string()
});

// src/generated/cfg_accounts/_utils/schemas/OTPVerifyRequest.schema.ts
import { z as z15 } from "zod";
var OTPVerifyRequestSchema = z15.object({
  identifier: z15.string().min(1),
  otp: z15.string().min(6).max(6),
  channel: z15.nativeEnum(OTPVerifyRequestChannel).optional(),
  source_url: z15.union([z15.url(), z15.literal("")]).optional()
});

// src/generated/cfg_accounts/_utils/schemas/OTPVerifyResponse.schema.ts
import { z as z17 } from "zod";

// src/generated/cfg_accounts/_utils/schemas/User.schema.ts
import { z as z16 } from "zod";
var UserSchema = z16.object({
  id: z16.int(),
  email: z16.email(),
  first_name: z16.string().max(50).optional(),
  last_name: z16.string().max(50).optional(),
  full_name: z16.string(),
  initials: z16.string(),
  display_username: z16.string(),
  company: z16.string().max(100).optional(),
  phone: z16.string().max(20).optional(),
  position: z16.string().max(100).optional(),
  avatar: z16.union([z16.url(), z16.literal("")]).nullable(),
  is_staff: z16.boolean(),
  is_superuser: z16.boolean(),
  date_joined: z16.iso.datetime(),
  last_login: z16.iso.datetime().nullable(),
  unanswered_messages_count: z16.int(),
  centrifugo: CentrifugoTokenSchema.nullable()
});

// src/generated/cfg_accounts/_utils/schemas/OTPVerifyResponse.schema.ts
var OTPVerifyResponseSchema = z17.object({
  requires_2fa: z17.boolean().optional(),
  session_id: z17.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i).nullable().optional(),
  refresh: z17.string().nullable().optional(),
  access: z17.string().nullable().optional(),
  user: UserSchema.nullable().optional(),
  should_prompt_2fa: z17.boolean().optional()
});

// src/generated/cfg_accounts/_utils/schemas/PatchedUserProfileUpdateRequest.schema.ts
import { z as z18 } from "zod";
var PatchedUserProfileUpdateRequestSchema = z18.object({
  first_name: z18.string().max(50).optional(),
  last_name: z18.string().max(50).optional(),
  company: z18.string().max(100).optional(),
  phone: z18.string().max(20).optional(),
  position: z18.string().max(100).optional()
});

// src/generated/cfg_accounts/_utils/schemas/TokenRefresh.schema.ts
import { z as z19 } from "zod";
var TokenRefreshSchema = z19.object({
  access: z19.string(),
  refresh: z19.string()
});

// src/generated/cfg_accounts/_utils/schemas/TokenRefreshRequest.schema.ts
import { z as z20 } from "zod";
var TokenRefreshRequestSchema = z20.object({
  refresh: z20.string().min(1)
});

// src/generated/cfg_accounts/_utils/schemas/UserProfileUpdateRequest.schema.ts
import { z as z21 } from "zod";
var UserProfileUpdateRequestSchema = z21.object({
  first_name: z21.string().max(50).optional(),
  last_name: z21.string().max(50).optional(),
  company: z21.string().max(100).optional(),
  phone: z21.string().max(20).optional(),
  position: z21.string().max(100).optional()
});

// src/generated/cfg_accounts/_utils/fetchers/accounts.ts
import { consola } from "consola";

// src/generated/cfg_accounts/_utils/fetchers/accounts__auth.ts
import { consola as consola2 } from "consola";

// src/generated/cfg_accounts/_utils/fetchers/accounts__oauth.ts
import { consola as consola3 } from "consola";

// src/generated/cfg_accounts/_utils/fetchers/accounts__user_profile.ts
import { consola as consola4 } from "consola";

// src/generated/cfg_accounts/index.ts
var TOKEN_KEY = "auth_token";
var REFRESH_TOKEN_KEY = "refresh_token";
var API = class {
  constructor(baseUrl, options) {
    this._token = null;
    this._refreshToken = null;
    this.baseUrl = baseUrl;
    this.options = options;
    const logger2 = options?.loggerConfig ? new APILogger(options.loggerConfig) : void 0;
    this.storage = options?.storage || new LocalStorageAdapter(logger2);
    this._loadTokensFromStorage();
    this._client = new APIClient(this.baseUrl, {
      retryConfig: this.options?.retryConfig,
      loggerConfig: this.options?.loggerConfig,
      tokenGetter: /* @__PURE__ */ __name(() => this.getToken(), "tokenGetter")
    });
    this._injectAuthHeader();
    this.auth = this._client.auth;
    this.oauth = this._client.oauth;
    this.user_profile = this._client.user_profile;
    this.accounts = this._client.accounts;
  }
  static {
    __name(this, "API");
  }
  _loadTokensFromStorage() {
    this._token = this.storage.getItem(TOKEN_KEY);
    this._refreshToken = this.storage.getItem(REFRESH_TOKEN_KEY);
  }
  _reinitClients() {
    this._client = new APIClient(this.baseUrl, {
      retryConfig: this.options?.retryConfig,
      loggerConfig: this.options?.loggerConfig,
      tokenGetter: /* @__PURE__ */ __name(() => this.getToken(), "tokenGetter")
    });
    this._injectAuthHeader();
    this.auth = this._client.auth;
    this.oauth = this._client.oauth;
    this.user_profile = this._client.user_profile;
    this.accounts = this._client.accounts;
  }
  _injectAuthHeader() {
    const originalRequest = this._client.request.bind(this._client);
    this._client.request = async (method, path, options) => {
      const token = this.getToken();
      const mergedOptions = {
        ...options,
        headers: {
          ...options?.headers || {},
          ...token ? { "Authorization": `Bearer ${token}` } : {}
        }
      };
      return originalRequest(method, path, mergedOptions);
    };
  }
  /**
   * Get current JWT token
   */
  getToken() {
    return this.storage.getItem(TOKEN_KEY);
  }
  /**
   * Get current refresh token
   */
  getRefreshToken() {
    return this.storage.getItem(REFRESH_TOKEN_KEY);
  }
  /**
   * Set JWT token and refresh token
   * @param token - JWT access token
   * @param refreshToken - JWT refresh token (optional)
   */
  setToken(token, refreshToken) {
    this._token = token;
    this.storage.setItem(TOKEN_KEY, token);
    if (refreshToken) {
      this._refreshToken = refreshToken;
      this.storage.setItem(REFRESH_TOKEN_KEY, refreshToken);
    }
    this._reinitClients();
  }
  /**
   * Clear all tokens
   */
  clearTokens() {
    this._token = null;
    this._refreshToken = null;
    this.storage.removeItem(TOKEN_KEY);
    this.storage.removeItem(REFRESH_TOKEN_KEY);
    this._reinitClients();
  }
  /**
   * Check if user is authenticated
   */
  isAuthenticated() {
    return !!this.getToken();
  }
  /**
   * Update base URL and reinitialize clients
   * @param url - New base URL
   */
  setBaseUrl(url) {
    this.baseUrl = url;
    this._reinitClients();
  }
  /**
   * Get current base URL
   */
  getBaseUrl() {
    return this.baseUrl;
  }
  /**
   * Get OpenAPI schema path
   * @returns Path to the OpenAPI schema JSON file
   *
   * Note: The OpenAPI schema is available in the schema.json file.
   * You can load it dynamically using:
   * ```typescript
   * const schema = await fetch('./schema.json').then(r => r.json());
   * // or using fs in Node.js:
   * // const schema = JSON.parse(fs.readFileSync('./schema.json', 'utf-8'));
   * ```
   */
  getSchemaPath() {
    return "./schema.json";
  }
};

// src/generated/cfg_centrifugo/logger.ts
import { createConsola as createConsola2 } from "consola";
var DEFAULT_CONFIG2 = {
  enabled: process.env.NODE_ENV !== "production",
  logRequests: true,
  logResponses: true,
  logErrors: true,
  logBodies: true,
  logHeaders: false
};
var SENSITIVE_HEADERS2 = [
  "authorization",
  "cookie",
  "set-cookie",
  "x-api-key",
  "x-csrf-token"
];
var APILogger2 = class {
  static {
    __name(this, "APILogger");
  }
  constructor(config = {}) {
    this.config = { ...DEFAULT_CONFIG2, ...config };
    this.consola = config.consola || createConsola2({
      level: this.config.enabled ? 4 : 0
    });
  }
  /**
   * Enable logging
   */
  enable() {
    this.config.enabled = true;
  }
  /**
   * Disable logging
   */
  disable() {
    this.config.enabled = false;
  }
  /**
   * Update configuration
   */
  setConfig(config) {
    this.config = { ...this.config, ...config };
  }
  /**
   * Filter sensitive headers
   */
  filterHeaders(headers) {
    if (!headers) return {};
    const filtered = {};
    Object.keys(headers).forEach((key) => {
      const lowerKey = key.toLowerCase();
      if (SENSITIVE_HEADERS2.includes(lowerKey)) {
        filtered[key] = "***";
      } else {
        filtered[key] = headers[key] || "";
      }
    });
    return filtered;
  }
  /**
   * Log request
   */
  logRequest(request) {
    if (!this.config.enabled || !this.config.logRequests) return;
    const { method, url, headers, body } = request;
    this.consola.start(`${method} ${url}`);
    if (this.config.logHeaders && headers) {
      this.consola.debug("Headers:", this.filterHeaders(headers));
    }
    if (this.config.logBodies && body) {
      this.consola.debug("Body:", body);
    }
  }
  /**
   * Log response
   */
  logResponse(request, response) {
    if (!this.config.enabled || !this.config.logResponses) return;
    const { method, url } = request;
    const { status, statusText, data, duration } = response;
    const statusColor = status >= 500 ? "red" : status >= 400 ? "yellow" : status >= 300 ? "cyan" : "green";
    this.consola.success(
      `${method} ${url} ${status} ${statusText} (${duration}ms)`
    );
    if (this.config.logBodies && data) {
      this.consola.debug("Response:", data);
    }
  }
  /**
   * Log error
   */
  logError(request, error) {
    if (!this.config.enabled || !this.config.logErrors) return;
    const { method, url } = request;
    const { message, statusCode, fieldErrors, duration } = error;
    this.consola.error(
      `${method} ${url} ${statusCode || "Network"} Error (${duration}ms)`
    );
    this.consola.error("Message:", message);
    if (fieldErrors && Object.keys(fieldErrors).length > 0) {
      this.consola.error("Field Errors:");
      Object.entries(fieldErrors).forEach(([field, errors]) => {
        errors.forEach((err) => {
          this.consola.error(`  \u2022 ${field}: ${err}`);
        });
      });
    }
  }
  /**
   * Log general info
   */
  info(message, ...args) {
    if (!this.config.enabled) return;
    this.consola.info(message, ...args);
  }
  /**
   * Log warning
   */
  warn(message, ...args) {
    if (!this.config.enabled) return;
    this.consola.warn(message, ...args);
  }
  /**
   * Log error
   */
  error(message, ...args) {
    if (!this.config.enabled) return;
    this.consola.error(message, ...args);
  }
  /**
   * Log debug
   */
  debug(message, ...args) {
    if (!this.config.enabled) return;
    this.consola.debug(message, ...args);
  }
  /**
   * Log success
   */
  success(message, ...args) {
    if (!this.config.enabled) return;
    this.consola.success(message, ...args);
  }
  /**
   * Create a sub-logger with prefix
   */
  withTag(tag) {
    return this.consola.withTag(tag);
  }
};
var defaultLogger2 = new APILogger2();

// src/generated/cfg_centrifugo/retry.ts
import pRetry2, { AbortError as AbortError2 } from "p-retry";

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoChannelInfo.schema.ts
import { z as z22 } from "zod";
var CentrifugoChannelInfoSchema = z22.object({
  num_clients: z22.int()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoChannelsRequestRequest.schema.ts
import { z as z23 } from "zod";
var CentrifugoChannelsRequestRequestSchema = z23.object({
  pattern: z23.string().nullable().optional()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoChannelsResponse.schema.ts
import { z as z26 } from "zod";

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoChannelsResult.schema.ts
import { z as z24 } from "zod";
var CentrifugoChannelsResultSchema = z24.object({
  channels: z24.record(z24.string(), CentrifugoChannelInfoSchema)
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoError.schema.ts
import { z as z25 } from "zod";
var CentrifugoErrorSchema = z25.object({
  code: z25.int().optional(),
  message: z25.string().optional()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoChannelsResponse.schema.ts
var CentrifugoChannelsResponseSchema = z26.object({
  error: CentrifugoErrorSchema.optional(),
  result: CentrifugoChannelsResultSchema.optional()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoClientInfo.schema.ts
import { z as z27 } from "zod";
var CentrifugoClientInfoSchema = z27.object({
  user: z27.string(),
  client: z27.string(),
  conn_info: z27.record(z27.string(), z27.any()).nullable().optional(),
  chan_info: z27.record(z27.string(), z27.any()).nullable().optional()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoHealthCheck.schema.ts
import { z as z28 } from "zod";
var CentrifugoHealthCheckSchema = z28.object({
  status: z28.string(),
  wrapper_url: z28.string(),
  has_api_key: z28.boolean(),
  timestamp: z28.string()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoHistoryRequestRequest.schema.ts
import { z as z30 } from "zod";

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoStreamPosition.schema.ts
import { z as z29 } from "zod";
var CentrifugoStreamPositionSchema = z29.object({
  offset: z29.int(),
  epoch: z29.string()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoHistoryRequestRequest.schema.ts
var CentrifugoHistoryRequestRequestSchema = z30.object({
  channel: z30.string(),
  limit: z30.int().nullable().optional(),
  since: CentrifugoStreamPositionSchema.optional(),
  reverse: z30.boolean().nullable().optional()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoHistoryResponse.schema.ts
import { z as z33 } from "zod";

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoHistoryResult.schema.ts
import { z as z32 } from "zod";

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPublication.schema.ts
import { z as z31 } from "zod";
var CentrifugoPublicationSchema = z31.object({
  data: z31.record(z31.string(), z31.any()),
  info: CentrifugoClientInfoSchema.optional(),
  offset: z31.int(),
  tags: z31.record(z31.string(), z31.any()).nullable().optional()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoHistoryResult.schema.ts
var CentrifugoHistoryResultSchema = z32.object({
  publications: z32.array(CentrifugoPublicationSchema),
  epoch: z32.string(),
  offset: z32.int()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoHistoryResponse.schema.ts
var CentrifugoHistoryResponseSchema = z33.object({
  error: CentrifugoErrorSchema.optional(),
  result: CentrifugoHistoryResultSchema.optional()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoInfoResponse.schema.ts
import { z as z38 } from "zod";

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoInfoResult.schema.ts
import { z as z37 } from "zod";

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoNodeInfo.schema.ts
import { z as z36 } from "zod";

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoMetrics.schema.ts
import { z as z34 } from "zod";
var CentrifugoMetricsSchema = z34.object({
  interval: z34.number(),
  items: z34.record(z34.string(), z34.number())
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoProcess.schema.ts
import { z as z35 } from "zod";
var CentrifugoProcessSchema = z35.object({
  cpu: z35.number(),
  rss: z35.int()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoNodeInfo.schema.ts
var CentrifugoNodeInfoSchema = z36.object({
  uid: z36.string(),
  name: z36.string(),
  version: z36.string(),
  num_clients: z36.int(),
  num_users: z36.int(),
  num_channels: z36.int(),
  uptime: z36.int(),
  num_subs: z36.int(),
  metrics: CentrifugoMetricsSchema.optional(),
  process: CentrifugoProcessSchema.optional()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoInfoResult.schema.ts
var CentrifugoInfoResultSchema = z37.object({
  nodes: z37.array(CentrifugoNodeInfoSchema)
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoInfoResponse.schema.ts
var CentrifugoInfoResponseSchema = z38.object({
  error: CentrifugoErrorSchema.optional(),
  result: CentrifugoInfoResultSchema.optional()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoOverviewStats.schema.ts
import { z as z39 } from "zod";
var CentrifugoOverviewStatsSchema = z39.object({
  total: z39.int(),
  successful: z39.int(),
  failed: z39.int(),
  timeout: z39.int(),
  success_rate: z39.number(),
  avg_duration_ms: z39.number(),
  avg_acks_received: z39.number(),
  period_hours: z39.int()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceRequestRequest.schema.ts
import { z as z40 } from "zod";
var CentrifugoPresenceRequestRequestSchema = z40.object({
  channel: z40.string()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceResponse.schema.ts
import { z as z42 } from "zod";

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceResult.schema.ts
import { z as z41 } from "zod";
var CentrifugoPresenceResultSchema = z41.object({
  presence: z41.record(z41.string(), CentrifugoClientInfoSchema)
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceResponse.schema.ts
var CentrifugoPresenceResponseSchema = z42.object({
  error: CentrifugoErrorSchema.optional(),
  result: CentrifugoPresenceResultSchema.optional()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceStatsRequestRequest.schema.ts
import { z as z43 } from "zod";
var CentrifugoPresenceStatsRequestRequestSchema = z43.object({
  channel: z43.string()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceStatsResponse.schema.ts
import { z as z45 } from "zod";

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceStatsResult.schema.ts
import { z as z44 } from "zod";
var CentrifugoPresenceStatsResultSchema = z44.object({
  num_clients: z44.int(),
  num_users: z44.int()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceStatsResponse.schema.ts
var CentrifugoPresenceStatsResponseSchema = z45.object({
  error: CentrifugoErrorSchema.optional(),
  result: CentrifugoPresenceStatsResultSchema.optional()
});

// src/generated/cfg_centrifugo/_utils/schemas/ChannelList.schema.ts
import { z as z47 } from "zod";

// src/generated/cfg_centrifugo/_utils/schemas/ChannelStats.schema.ts
import { z as z46 } from "zod";
var ChannelStatsSchema = z46.object({
  channel: z46.string(),
  total: z46.int(),
  successful: z46.int(),
  failed: z46.int(),
  avg_duration_ms: z46.number(),
  avg_acks: z46.number(),
  last_activity_at: z46.string().nullable()
});

// src/generated/cfg_centrifugo/_utils/schemas/ChannelList.schema.ts
var ChannelListSchema = z47.object({
  channels: z47.array(ChannelStatsSchema),
  total_channels: z47.int()
});

// src/generated/cfg_centrifugo/_utils/schemas/ConnectionTokenResponse.schema.ts
import { z as z48 } from "zod";
var ConnectionTokenResponseSchema = z48.object({
  token: z48.string(),
  centrifugo_url: z48.string(),
  expires_at: z48.string(),
  channels: z48.array(z48.string())
});

// src/generated/cfg_centrifugo/_utils/schemas/ManualAckRequestRequest.schema.ts
import { z as z49 } from "zod";
var ManualAckRequestRequestSchema = z49.object({
  message_id: z49.string(),
  client_id: z49.string()
});

// src/generated/cfg_centrifugo/_utils/schemas/ManualAckResponse.schema.ts
import { z as z50 } from "zod";
var ManualAckResponseSchema = z50.object({
  success: z50.boolean(),
  message_id: z50.string(),
  error: z50.string().nullable().optional()
});

// src/generated/cfg_centrifugo/_utils/schemas/PaginatedPublishList.schema.ts
import { z as z52 } from "zod";

// src/generated/cfg_centrifugo/_utils/schemas/Publish.schema.ts
import { z as z51 } from "zod";
var PublishSchema = z51.object({
  message_id: z51.string(),
  channel: z51.string(),
  status: z51.string(),
  wait_for_ack: z51.boolean(),
  acks_received: z51.int(),
  acks_expected: z51.int().nullable(),
  duration_ms: z51.number().nullable(),
  created_at: z51.iso.datetime(),
  completed_at: z51.iso.datetime().nullable(),
  error_code: z51.string().nullable(),
  error_message: z51.string().nullable()
});

// src/generated/cfg_centrifugo/_utils/schemas/PaginatedPublishList.schema.ts
var PaginatedPublishListSchema = z52.object({
  count: z52.int(),
  page: z52.int(),
  pages: z52.int(),
  page_size: z52.int(),
  has_next: z52.boolean(),
  has_previous: z52.boolean(),
  next_page: z52.int().nullable().optional(),
  previous_page: z52.int().nullable().optional(),
  results: z52.array(PublishSchema)
});

// src/generated/cfg_centrifugo/_utils/schemas/PublishTestRequestRequest.schema.ts
import { z as z53 } from "zod";
var PublishTestRequestRequestSchema = z53.object({
  channel: z53.string(),
  data: z53.record(z53.string(), z53.any()),
  wait_for_ack: z53.boolean().optional(),
  ack_timeout: z53.int().min(1).max(60).optional()
});

// src/generated/cfg_centrifugo/_utils/schemas/PublishTestResponse.schema.ts
import { z as z54 } from "zod";
var PublishTestResponseSchema = z54.object({
  success: z54.boolean(),
  message_id: z54.string(),
  channel: z54.string(),
  acks_received: z54.int().optional(),
  delivered: z54.boolean().optional(),
  error: z54.string().nullable().optional()
});

// src/generated/cfg_centrifugo/_utils/schemas/TimelineItem.schema.ts
import { z as z55 } from "zod";
var TimelineItemSchema = z55.object({
  timestamp: z55.string(),
  count: z55.int(),
  successful: z55.int(),
  failed: z55.int(),
  timeout: z55.int()
});

// src/generated/cfg_centrifugo/_utils/schemas/TimelineResponse.schema.ts
import { z as z56 } from "zod";
var TimelineResponseSchema = z56.object({
  timeline: z56.array(TimelineItemSchema),
  period_hours: z56.int(),
  interval: z56.string()
});

// src/generated/cfg_centrifugo/_utils/fetchers/centrifugo__centrifugo_admin_api.ts
import { consola as consola5 } from "consola";

// src/generated/cfg_centrifugo/_utils/fetchers/centrifugo__centrifugo_auth.ts
import { consola as consola6 } from "consola";

// src/generated/cfg_centrifugo/_utils/fetchers/centrifugo__centrifugo_monitoring.ts
import { consola as consola7 } from "consola";

// src/generated/cfg_centrifugo/_utils/fetchers/centrifugo__centrifugo_testing.ts
import { consola as consola8 } from "consola";

// src/generated/cfg_webpush/logger.ts
import { createConsola as createConsola3 } from "consola";
var DEFAULT_CONFIG3 = {
  enabled: process.env.NODE_ENV !== "production",
  logRequests: true,
  logResponses: true,
  logErrors: true,
  logBodies: true,
  logHeaders: false
};
var SENSITIVE_HEADERS3 = [
  "authorization",
  "cookie",
  "set-cookie",
  "x-api-key",
  "x-csrf-token"
];
var APILogger3 = class {
  static {
    __name(this, "APILogger");
  }
  constructor(config = {}) {
    this.config = { ...DEFAULT_CONFIG3, ...config };
    this.consola = config.consola || createConsola3({
      level: this.config.enabled ? 4 : 0
    });
  }
  /**
   * Enable logging
   */
  enable() {
    this.config.enabled = true;
  }
  /**
   * Disable logging
   */
  disable() {
    this.config.enabled = false;
  }
  /**
   * Update configuration
   */
  setConfig(config) {
    this.config = { ...this.config, ...config };
  }
  /**
   * Filter sensitive headers
   */
  filterHeaders(headers) {
    if (!headers) return {};
    const filtered = {};
    Object.keys(headers).forEach((key) => {
      const lowerKey = key.toLowerCase();
      if (SENSITIVE_HEADERS3.includes(lowerKey)) {
        filtered[key] = "***";
      } else {
        filtered[key] = headers[key] || "";
      }
    });
    return filtered;
  }
  /**
   * Log request
   */
  logRequest(request) {
    if (!this.config.enabled || !this.config.logRequests) return;
    const { method, url, headers, body } = request;
    this.consola.start(`${method} ${url}`);
    if (this.config.logHeaders && headers) {
      this.consola.debug("Headers:", this.filterHeaders(headers));
    }
    if (this.config.logBodies && body) {
      this.consola.debug("Body:", body);
    }
  }
  /**
   * Log response
   */
  logResponse(request, response) {
    if (!this.config.enabled || !this.config.logResponses) return;
    const { method, url } = request;
    const { status, statusText, data, duration } = response;
    const statusColor = status >= 500 ? "red" : status >= 400 ? "yellow" : status >= 300 ? "cyan" : "green";
    this.consola.success(
      `${method} ${url} ${status} ${statusText} (${duration}ms)`
    );
    if (this.config.logBodies && data) {
      this.consola.debug("Response:", data);
    }
  }
  /**
   * Log error
   */
  logError(request, error) {
    if (!this.config.enabled || !this.config.logErrors) return;
    const { method, url } = request;
    const { message, statusCode, fieldErrors, duration } = error;
    this.consola.error(
      `${method} ${url} ${statusCode || "Network"} Error (${duration}ms)`
    );
    this.consola.error("Message:", message);
    if (fieldErrors && Object.keys(fieldErrors).length > 0) {
      this.consola.error("Field Errors:");
      Object.entries(fieldErrors).forEach(([field, errors]) => {
        errors.forEach((err) => {
          this.consola.error(`  \u2022 ${field}: ${err}`);
        });
      });
    }
  }
  /**
   * Log general info
   */
  info(message, ...args) {
    if (!this.config.enabled) return;
    this.consola.info(message, ...args);
  }
  /**
   * Log warning
   */
  warn(message, ...args) {
    if (!this.config.enabled) return;
    this.consola.warn(message, ...args);
  }
  /**
   * Log error
   */
  error(message, ...args) {
    if (!this.config.enabled) return;
    this.consola.error(message, ...args);
  }
  /**
   * Log debug
   */
  debug(message, ...args) {
    if (!this.config.enabled) return;
    this.consola.debug(message, ...args);
  }
  /**
   * Log success
   */
  success(message, ...args) {
    if (!this.config.enabled) return;
    this.consola.success(message, ...args);
  }
  /**
   * Create a sub-logger with prefix
   */
  withTag(tag) {
    return this.consola.withTag(tag);
  }
};
var defaultLogger3 = new APILogger3();

// src/generated/cfg_webpush/retry.ts
import pRetry3, { AbortError as AbortError3 } from "p-retry";

// src/generated/cfg_webpush/_utils/schemas/SendPushRequestRequest.schema.ts
import { z as z57 } from "zod";
var SendPushRequestRequestSchema = z57.object({
  title: z57.string().min(1).max(255),
  body: z57.string().min(1),
  icon: z57.union([z57.url(), z57.literal("")]).nullable().optional(),
  url: z57.union([z57.url(), z57.literal("")]).nullable().optional()
});

// src/generated/cfg_webpush/_utils/schemas/SendPushResponse.schema.ts
import { z as z58 } from "zod";
var SendPushResponseSchema = z58.object({
  success: z58.boolean(),
  sent_to: z58.int()
});

// src/generated/cfg_webpush/_utils/schemas/SubscribeRequestRequest.schema.ts
import { z as z59 } from "zod";
var SubscribeRequestRequestSchema = z59.object({
  endpoint: z59.union([z59.url(), z59.literal("")]),
  keys: z59.record(z59.string(), z59.string().min(1))
});

// src/generated/cfg_webpush/_utils/schemas/SubscribeResponse.schema.ts
import { z as z60 } from "zod";
var SubscribeResponseSchema = z60.object({
  success: z60.boolean(),
  subscription_id: z60.int(),
  created: z60.boolean()
});

// src/generated/cfg_webpush/_utils/schemas/VapidPublicKeyResponse.schema.ts
import { z as z61 } from "zod";
var VapidPublicKeyResponseSchema = z61.object({
  publicKey: z61.string()
});

// src/generated/cfg_webpush/_utils/fetchers/webpush__web_push.ts
import { consola as consola9 } from "consola";

// src/index.ts
var isStaticBuild = process.env.NEXT_PUBLIC_STATIC_BUILD === "true";
var apiUrl = isStaticBuild ? "" : process.env.NEXT_PUBLIC_API_URL || "";
var api = new API(
  apiUrl,
  {
    storage: new LocalStorageAdapter()
  }
);
var BaseClient = class {
  static {
    __name(this, "BaseClient");
  }
  static {
    this.api = api;
  }
};

// src/auth/utils/logger.ts
import { createConsola as createConsola4 } from "consola";
var isDevelopment = process.env.NODE_ENV === "development";
var isStaticBuild2 = process.env.NEXT_PUBLIC_STATIC_BUILD === "true";
var showLogs = isDevelopment || isStaticBuild2;
var logger = createConsola4({
  level: showLogs ? 4 : 1
  // dev: debug, production: errors only
}).withTag("api");
var authLogger = logger.withTag("auth");

// src/auth/middlewares/tokenRefresh.ts
var isRefreshing = false;
var refreshSubscribers = [];
function subscribeTokenRefresh(callback) {
  refreshSubscribers.push(callback);
}
__name(subscribeTokenRefresh, "subscribeTokenRefresh");
function onTokenRefreshed(token) {
  refreshSubscribers.forEach((callback) => callback(token));
  refreshSubscribers = [];
}
__name(onTokenRefreshed, "onTokenRefreshed");
async function refreshAccessToken() {
  if (isRefreshing) {
    return new Promise((resolve) => {
      subscribeTokenRefresh((token) => resolve(token));
    });
  }
  isRefreshing = true;
  authLogger.info("Starting token refresh...");
  try {
    const refreshToken = api.getRefreshToken();
    if (!refreshToken) {
      authLogger.warn("No refresh token available for refresh");
      onTokenRefreshed(null);
      return null;
    }
    const result = await api.auth.accountsTokenRefreshCreate({
      refresh: refreshToken
    });
    const newAccessToken = result.access;
    if (!newAccessToken) {
      authLogger.error("Token refresh response missing access token");
      onTokenRefreshed(null);
      return null;
    }
    api.setToken(newAccessToken, refreshToken);
    authLogger.info("Token refreshed successfully");
    onTokenRefreshed(newAccessToken);
    return newAccessToken;
  } catch (error) {
    authLogger.error("Token refresh error:", error);
    onTokenRefreshed(null);
    return null;
  } finally {
    isRefreshing = false;
  }
}
__name(refreshAccessToken, "refreshAccessToken");
function isAuthenticationError(response) {
  return response.status === 401;
}
__name(isAuthenticationError, "isAuthenticationError");
function createAutoRefreshFetch(originalFetch) {
  return async (input, init) => {
    let response = await originalFetch(input, init);
    if (isAuthenticationError(response) && api.getRefreshToken()) {
      authLogger.info("Received 401, attempting token refresh...");
      const newToken = await refreshAccessToken();
      if (newToken) {
        const newInit = {
          ...init,
          headers: {
            ...init?.headers,
            Authorization: `Bearer ${newToken}`
          }
        };
        authLogger.info("Retrying request with new token...");
        response = await originalFetch(input, newInit);
      } else {
        authLogger.warn("Token refresh failed, returning original 401 response");
      }
    }
    return response;
  };
}
__name(createAutoRefreshFetch, "createAutoRefreshFetch");
function isTokenExpiringSoon(thresholdMs = 5 * 60 * 1e3) {
  const token = api.getToken();
  if (!token) return false;
  try {
    const payload = JSON.parse(atob(token.split(".")[1]));
    const expiresAt = payload.exp * 1e3;
    const now = Date.now();
    const timeUntilExpiry = expiresAt - now;
    return timeUntilExpiry < thresholdMs;
  } catch (error) {
    authLogger.error("Error checking token expiry:", error);
    return false;
  }
}
__name(isTokenExpiringSoon, "isTokenExpiringSoon");
async function refreshIfExpiringSoon(thresholdMs = 5 * 60 * 1e3) {
  if (isTokenExpiringSoon(thresholdMs)) {
    authLogger.info("Token expiring soon, proactively refreshing...");
    await refreshAccessToken();
  }
}
__name(refreshIfExpiringSoon, "refreshIfExpiringSoon");
export {
  createAutoRefreshFetch,
  isAuthenticationError,
  isTokenExpiringSoon,
  proxyMiddleware,
  proxyMiddlewareConfig,
  refreshAccessToken,
  refreshIfExpiringSoon
};
//# sourceMappingURL=auth-server.mjs.map