// Force strict mode and setup for ESM
"use strict";
import "./chunk-QQOPXQYM.js";
import "./chunk-TWPJO254.js";
import "./chunk-H6XPXXMH.js";
import "./chunk-5M6IDOMF.js";
import "./chunk-UPUG4GXM.js";
import "./chunk-64LQLPL7.js";
import "./chunk-2LQTH543.js";
import "./chunk-KRXPRVGL.js";
import "./chunk-GNCIZTNJ.js";
import "./chunk-CVHIL5IG.js";
import "./chunk-IRH27ZC2.js";
import "./chunk-QHWCP53L.js";
import "./chunk-PONHVBRT.js";
import "./chunk-T26EAKDL.js";
import "./chunk-6PVPNMXU.js";
import "./chunk-CPBF7KYF.js";
import "./chunk-6QIGFD5W.js";
import "./chunk-XWWKIXVD.js";
import "./chunk-75GFAX4R.js";
import "./chunk-OKF7JF3R.js";
import "./chunk-JSD33JG6.js";
import "./chunk-S6LOFUVP.js";
import "./chunk-JCW2R7WC.js";
import "./chunk-2DN4J57Y.js";
import "./chunk-ZPJWUGCS.js";
import {
  OpenAIContentGenerator
} from "./chunk-SAYSPULY.js";
import {
  DashScopeOpenAICompatibleProvider
} from "./chunk-WBSMNTSV.js";
import {
  SharedTokenManager
} from "./chunk-2LKVPASC.js";
import "./chunk-NAVJD2PQ.js";
import "./chunk-LW3RFMG7.js";
import "./chunk-W4MIWP6M.js";
import "./chunk-DGEIYUC3.js";
import "./chunk-FNMZK765.js";
import "./chunk-MPHPFVKK.js";
import {
  DEFAULT_DASHSCOPE_BASE_URL
} from "./chunk-GLNBDYUX.js";
import "./chunk-DJ2GSRLV.js";
import "./chunk-6D2RWQMA.js";
import "./chunk-75MIQ3LV.js";
import "./chunk-5TBMQLGG.js";
import "./chunk-2J3OJGTL.js";
import "./chunk-P3QQPMQA.js";
import "./chunk-RPLGZJV2.js";
import "./chunk-NOKIVHOL.js";
import "./chunk-GLCZKT5V.js";
import "./chunk-5YKDXHUY.js";
import "./chunk-DZLYR4U3.js";
import "./chunk-NKHOVMWF.js";
import "./chunk-VGC4I5JJ.js";
import "./chunk-SGFT55XI.js";
import "./chunk-Y4IHBGBP.js";
import "./chunk-Y6AXW2OG.js";
import "./chunk-2M3XQKPR.js";
import "./chunk-46UV252V.js";
import "./chunk-ZBVS26BY.js";
import "./chunk-WZRWHXFE.js";
import "./chunk-A3NDJ5SB.js";
import "./chunk-7XATOOE7.js";
import "./chunk-BGTQCTQW.js";
import "./chunk-W4RQUHY3.js";
import "./chunk-S7W2GKIO.js";
import {
  createDebugLogger
} from "./chunk-UHUSJ6X7.js";
import "./chunk-VOQXFAY5.js";
import "./chunk-75DOP5OR.js";
import "./chunk-DMTGGOSA.js";
import "./chunk-YQ3U5MUC.js";
import "./chunk-22C7BQ6D.js";
import "./chunk-TYAMGABM.js";
import "./chunk-FCMNKVXT.js";
import "./chunk-AMDSOFFV.js";
import "./chunk-QUGAUQGJ.js";
import {
  init_esbuild_shims
} from "./chunk-5O2XNYP6.js";
import {
  __name
} from "./chunk-J2S4EL5Y.js";

// packages/core/src/qwen/qwenContentGenerator.ts
init_esbuild_shims();
var QwenContentGenerator = class extends OpenAIContentGenerator {
  static {
    __name(this, "QwenContentGenerator");
  }
  debugLogger = createDebugLogger("QWEN");
  qwenClient;
  sharedManager;
  currentToken;
  constructor(qwenClient, contentGeneratorConfig, cliConfig) {
    const dashscopeProvider = new DashScopeOpenAICompatibleProvider(
      contentGeneratorConfig,
      cliConfig
    );
    super(contentGeneratorConfig, cliConfig, dashscopeProvider);
    this.qwenClient = qwenClient;
    this.sharedManager = SharedTokenManager.getInstance();
    if (contentGeneratorConfig?.baseUrl && contentGeneratorConfig?.apiKey) {
      this.pipeline.client.baseURL = contentGeneratorConfig?.baseUrl;
      this.pipeline.client.apiKey = contentGeneratorConfig?.apiKey;
    }
  }
  /**
   * Get the current endpoint URL with proper protocol and /v1 suffix
   */
  getCurrentEndpoint(resourceUrl) {
    const baseEndpoint = resourceUrl || DEFAULT_DASHSCOPE_BASE_URL;
    const suffix = "/v1";
    const normalizedUrl = /^https?:\/\//i.test(baseEndpoint) ? baseEndpoint : `https://${baseEndpoint}`;
    return normalizedUrl.endsWith(suffix) ? normalizedUrl : `${normalizedUrl}${suffix}`;
  }
  /**
   * Override error logging behavior to suppress auth errors during token refresh
   */
  shouldSuppressErrorLogging(error, _request) {
    return this.isAuthError(error);
  }
  /**
   * Get valid token and endpoint using the shared token manager
   */
  async getValidToken() {
    try {
      const credentials = await this.sharedManager.getValidCredentials(
        this.qwenClient
      );
      if (!credentials.access_token) {
        throw new Error("No access token available");
      }
      return {
        token: credentials.access_token,
        endpoint: this.getCurrentEndpoint(credentials.resource_url)
      };
    } catch (error) {
      if (this.isAuthError(error)) {
        throw error;
      }
      this.debugLogger.warn("Failed to get token from shared manager:", error);
      throw new Error(
        "Failed to obtain valid Qwen access token. Please re-authenticate."
      );
    }
  }
  /**
   * Execute an operation with automatic credential management and retry logic.
   * This method handles:
   * - Dynamic token and endpoint retrieval
   * - Client configuration updates
   * - Retry logic on authentication errors with token refresh
   *
   * @param operation - The operation to execute with updated client configuration
   * @returns The result of the operation
   */
  async executeWithCredentialManagement(operation) {
    const attemptOperation = /* @__PURE__ */ __name(async () => {
      const { token, endpoint } = await this.getValidToken();
      this.pipeline.client.apiKey = token;
      this.pipeline.client.baseURL = endpoint;
      return await operation();
    }, "attemptOperation");
    try {
      return await attemptOperation();
    } catch (error) {
      if (this.isAuthError(error)) {
        await this.sharedManager.getValidCredentials(this.qwenClient, true);
        return await attemptOperation();
      }
      throw error;
    }
  }
  /**
   * Override to use dynamic token and endpoint with automatic retry
   */
  async generateContent(request, userPromptId) {
    return this.executeWithCredentialManagement(
      () => super.generateContent(request, userPromptId)
    );
  }
  /**
   * Override to use dynamic token and endpoint with automatic retry
   */
  async generateContentStream(request, userPromptId) {
    return this.executeWithCredentialManagement(
      () => super.generateContentStream(request, userPromptId)
    );
  }
  /**
   * Override to use dynamic token and endpoint with automatic retry
   */
  async countTokens(request) {
    return super.countTokens(request);
  }
  /**
   * Override to use dynamic token and endpoint with automatic retry
   */
  async embedContent(request) {
    return this.executeWithCredentialManagement(
      () => super.embedContent(request)
    );
  }
  /**
   * Check if an error is related to authentication/authorization
   */
  isAuthError(error) {
    if (!error) return false;
    const errorMessage = error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase();
    const errorWithCode = error;
    const errorCode = errorWithCode?.status || errorWithCode?.code;
    return errorCode === 401 || errorCode === 403 || errorCode === "401" || errorCode === "403" || errorMessage.includes("unauthorized") || errorMessage.includes("forbidden") || errorMessage.includes("invalid api key") || errorMessage.includes("invalid access token") || errorMessage.includes("token expired") || errorMessage.includes("authentication") || errorMessage.includes("access denied") || errorMessage.includes("token") && errorMessage.includes("expired");
  }
  /**
   * Get the current cached token (may be expired)
   */
  getCurrentToken() {
    if (this.currentToken) {
      return this.currentToken;
    }
    const credentials = this.sharedManager.getCurrentCredentials();
    return credentials?.access_token || null;
  }
  /**
   * Clear the cached token
   */
  clearToken() {
    this.currentToken = void 0;
    this.sharedManager.clearCache();
  }
};
export {
  QwenContentGenerator
};
/**
 * @license
 * Copyright 2025 Qwen
 * SPDX-License-Identifier: Apache-2.0
 */
