'use strict';

var chunkW7C7RY6I_cjs = require('./chunk-W7C7RY6I.cjs');
var chunkGLBBBSS5_cjs = require('./chunk-GLBBBSS5.cjs');
var chunk4U7ZLI36_cjs = require('./chunk-4U7ZLI36.cjs');

// src/llm/model/gateways/netlify.ts
var NetlifyGateway = class extends chunkW7C7RY6I_cjs.MastraModelGateway {
  id = "netlify";
  name = "Netlify AI Gateway";
  tokenCache = new chunkGLBBBSS5_cjs.InMemoryServerCache();
  async fetchProviders() {
    const response = await fetch("https://api.netlify.com/api/v1/ai-gateway/providers");
    if (!response.ok) {
      throw new Error(`Failed to fetch from Netlify: ${response.statusText}`);
    }
    const data = await response.json();
    const config = {
      apiKeyEnvVar: ["NETLIFY_TOKEN", "NETLIFY_SITE_ID"],
      apiKeyHeader: "Authorization",
      name: `Netlify`,
      gateway: `netlify`,
      models: [],
      docUrl: "https://docs.netlify.com/build/ai-gateway/overview/"
    };
    for (const [providerId, provider] of Object.entries(data.providers)) {
      for (const model of provider.models) {
        config.models.push(`${providerId}/${model}`);
      }
    }
    return { netlify: config };
  }
  async buildUrl(routerId, envVars) {
    const siteId = envVars?.["NETLIFY_SITE_ID"] || process.env["NETLIFY_SITE_ID"];
    const netlifyToken = envVars?.["NETLIFY_TOKEN"] || process.env["NETLIFY_TOKEN"];
    if (!netlifyToken) {
      throw new chunk4U7ZLI36_cjs.MastraError({
        id: "NETLIFY_GATEWAY_NO_TOKEN",
        domain: "LLM",
        category: "UNKNOWN",
        text: `Missing NETLIFY_TOKEN environment variable required for model: ${routerId}`
      });
    }
    if (!siteId) {
      throw new chunk4U7ZLI36_cjs.MastraError({
        id: "NETLIFY_GATEWAY_NO_SITE_ID",
        domain: "LLM",
        category: "UNKNOWN",
        text: `Missing NETLIFY_SITE_ID environment variable required for model: ${routerId}`
      });
    }
    try {
      const tokenData = await this.getOrFetchToken(siteId, netlifyToken);
      return tokenData.url.endsWith(`/`) ? tokenData.url.substring(0, tokenData.url.length - 1) : tokenData.url;
    } catch (error) {
      throw new chunk4U7ZLI36_cjs.MastraError({
        id: "NETLIFY_GATEWAY_TOKEN_ERROR",
        domain: "LLM",
        category: "UNKNOWN",
        text: `Failed to get Netlify AI Gateway token for model ${routerId}: ${error instanceof Error ? error.message : String(error)}`
      });
    }
  }
  /**
   * Get cached token or fetch a new site-specific AI Gateway token from Netlify
   */
  async getOrFetchToken(siteId, netlifyToken) {
    const cacheKey = `netlify-token:${siteId}:${netlifyToken}`;
    const cached = await this.tokenCache.get(cacheKey);
    if (cached && cached.expiresAt > Date.now() / 1e3 + 60) {
      return { token: cached.token, url: cached.url };
    }
    const response = await fetch(`https://api.netlify.com/api/v1/sites/${siteId}/ai-gateway/token`, {
      method: "GET",
      headers: {
        Authorization: `Bearer ${netlifyToken}`
      }
    });
    if (!response.ok) {
      const error = await response.text();
      throw new Error(`Failed to get Netlify AI Gateway token: ${response.status} ${error}`);
    }
    const tokenResponse = await response.json();
    await this.tokenCache.set(cacheKey, {
      token: tokenResponse.token,
      url: tokenResponse.url,
      expiresAt: tokenResponse.expires_at
    });
    return { token: tokenResponse.token, url: tokenResponse.url };
  }
  /**
   * Get cached token or fetch a new site-specific AI Gateway token from Netlify
   */
  async getApiKey(modelId) {
    const siteId = process.env["NETLIFY_SITE_ID"];
    const netlifyToken = process.env["NETLIFY_TOKEN"];
    if (!netlifyToken) {
      throw new chunk4U7ZLI36_cjs.MastraError({
        id: "NETLIFY_GATEWAY_NO_TOKEN",
        domain: "LLM",
        category: "UNKNOWN",
        text: `Missing NETLIFY_TOKEN environment variable required for model: ${modelId}`
      });
    }
    if (!siteId) {
      throw new chunk4U7ZLI36_cjs.MastraError({
        id: "NETLIFY_GATEWAY_NO_SITE_ID",
        domain: "LLM",
        category: "UNKNOWN",
        text: `Missing NETLIFY_SITE_ID environment variable required for model: ${modelId}`
      });
    }
    try {
      return (await this.getOrFetchToken(siteId, netlifyToken)).token;
    } catch (error) {
      throw new chunk4U7ZLI36_cjs.MastraError({
        id: "NETLIFY_GATEWAY_TOKEN_ERROR",
        domain: "LLM",
        category: "UNKNOWN",
        text: `Failed to get Netlify AI Gateway token for model ${modelId}: ${error instanceof Error ? error.message : String(error)}`
      });
    }
  }
  async resolveLanguageModel({
    modelId,
    providerId,
    apiKey,
    headers
  }) {
    const baseURL = await this.buildUrl(`${providerId}/${modelId}`);
    const mastraHeaders = { "User-Agent": chunkW7C7RY6I_cjs.MASTRA_USER_AGENT, ...headers };
    switch (providerId) {
      case "openai":
        return chunkW7C7RY6I_cjs.createOpenAI({ apiKey, baseURL, headers: mastraHeaders }).responses(modelId);
      case "gemini":
        return chunkW7C7RY6I_cjs.createGoogleGenerativeAI({
          baseURL: `${baseURL}/v1beta/`,
          apiKey,
          headers: {
            "user-agent": "google-genai-sdk/",
            ...mastraHeaders
          }
        }).chat(modelId);
      case "anthropic":
        return chunkW7C7RY6I_cjs.createAnthropic({
          apiKey,
          baseURL: `${baseURL}/v1/`,
          headers: {
            "anthropic-version": "2023-06-01",
            ...mastraHeaders
          }
        })(modelId);
      default:
        return chunkW7C7RY6I_cjs.createOpenAICompatible({
          name: providerId,
          apiKey,
          baseURL,
          headers: mastraHeaders,
          supportsStructuredOutputs: true
        }).chatModel(modelId);
    }
  }
};

exports.NetlifyGateway = NetlifyGateway;
//# sourceMappingURL=chunk-OSMMAURN.cjs.map
//# sourceMappingURL=chunk-OSMMAURN.cjs.map