// Force strict mode and setup for ESM
"use strict";
const __papertOriginalEmitWarning = process.emitWarning.bind(process);
process.emitWarning = function patchedEmitWarning(warning, ...args) {
  if (!process.env.PAPERT_SHOW_NODE_DEPRECATIONS) {
    const warningCode =
      (warning && typeof warning === 'object' && 'code' in warning && warning.code) ||
      (args.length > 1 && typeof args[1] === 'string' && args[1]) ||
      (args.length > 0 &&
        args[0] &&
        typeof args[0] === 'object' &&
        'code' in args[0] &&
        args[0].code);
    if (warningCode === 'DEP0040' || warningCode === 'DEP0169') {
      return;
    }
  }
  return __papertOriginalEmitWarning(warning, ...args);
};
import "./chunk-PGKEXZYI.js";
import {
  DashScopeOpenAICompatibleProvider,
  OpenAIContentGenerator
} from "./chunk-ZHTGXQAR.js";
import {
  DEFAULT_DASHSCOPE_BASE_URL
} from "./chunk-TQNFJUNM.js";
import "./chunk-F77EGXST.js";
import "./chunk-2MUETKKX.js";
import "./chunk-B4UTHNG5.js";
import "./chunk-423NGIST.js";
import "./chunk-MHFXK3XK.js";
import "./chunk-BMT6LRT3.js";
import "./chunk-FJQLUUKC.js";
import {
  SharedTokenManager
} from "./chunk-K5KJBM44.js";
import "./chunk-4YLWLT76.js";
import {
  __name,
  init_esbuild_shims
} from "./chunk-NCFEMX7E.js";

// packages/core/dist/src/papert/papertContentGenerator.js
init_esbuild_shims();
var PapertContentGenerator = class extends OpenAIContentGenerator {
  static {
    __name(this, "PapertContentGenerator");
  }
  papertClient;
  sharedManager;
  currentToken;
  constructor(papertClient, contentGeneratorConfig, cliConfig) {
    const dashscopeProvider = new DashScopeOpenAICompatibleProvider(contentGeneratorConfig, cliConfig);
    super(contentGeneratorConfig, cliConfig, dashscopeProvider);
    this.papertClient = papertClient;
    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 = baseEndpoint.startsWith("http") ? 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.papertClient);
      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;
      }
      console.warn("Failed to get token from shared manager:", error);
      throw new Error("Failed to obtain valid Papert 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.papertClient, 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 {
  PapertContentGenerator
};
/**
 * @license
 * Copyright 2025 Papert
 * SPDX-License-Identifier: Apache-2.0
 */
