{"version":3,"file":"index.cjs","names":["getEnvironmentVariable","iife","normalizeGCPCredentials","AuthError","GOOGLE_API_KEY_HEADER","GCP_API_KEY_HEADER","getGCPCredentialsAccessToken"],"sources":["../../src/clients/index.ts"],"sourcesContent":["import { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { GCP_API_KEY_HEADER, GOOGLE_API_KEY_HEADER } from \"../const.js\";\nimport {\n  GCPCredentials,\n  getGCPCredentialsAccessToken,\n  normalizeGCPCredentials,\n} from \"../utils/gcp-auth.js\";\nimport { AuthError } from \"../utils/errors.js\";\nimport { iife } from \"../utils/misc.js\";\n\n/**\n * Abstract base class for API clients that interact with Google services.\n *\n * This class defines the contract for API clients, requiring implementations\n * to provide a fetch method that handles HTTP requests with appropriate\n * authentication headers. Concrete implementations should handle different\n * authentication strategies (API keys, service account credentials, etc.)\n * based on the runtime environment.\n *\n * @abstract\n *\n * @example\n * ```typescript\n * class MyApiClient extends ApiClient {\n *   async fetch(request: Request): Promise<Response> {\n *     // Add authentication headers\n *     request.headers.set('Authorization', 'Bearer token');\n *     return fetch(request);\n *   }\n * }\n * ```\n */\nexport abstract class ApiClient {\n  /**\n   * Has an API Key been set for this client?\n   */\n  abstract hasApiKey(): boolean;\n\n  /**\n   * For some credential methods, we know what the project ID is.\n   * This is necessary for OAuth-based access to Vertex\n   */\n  async getProjectId(): Promise<string> {\n    return \"unknown-project-id\";\n  }\n\n  /**\n   * Executes an HTTP request with appropriate authentication.\n   *\n   * Implementations should add necessary authentication headers to the request\n   * before forwarding it to the underlying fetch implementation.\n   *\n   * @param request - The HTTP request to execute\n   * @returns A Promise that resolves to the HTTP response\n   *\n   * @abstract\n   */\n  abstract fetch(request: Request): Promise<Response>;\n}\n\n/**\n * Configuration parameters for the WebApiClient.\n *\n * This interface defines the authentication options available for web-based\n * API clients. Authentication can be provided via an API key or GCP service\n * account credentials. The client will automatically check environment variables\n * if explicit values are not provided.\n *\n * @interface\n */\nexport interface WebApiClientParams {\n  /**\n   * Google API key for authentication.\n   *\n   * If not provided, the client will attempt to read from the\n   * `GOOGLE_API_KEY` environment variable.\n   *\n   * @see https://cloud.google.com/docs/authentication/api-keys\n   */\n  apiKey?: string;\n\n  /**\n   * GCP service account credentials for authentication.\n   *\n   * Can be provided as either:\n   * - A JSON string containing the service account key\n   * - A GCPCredentials object\n   *\n   * If not provided, the client will attempt to read from the\n   * `GOOGLE_CLOUD_CREDENTIALS` environment variable.\n   *\n   * @see https://cloud.google.com/iam/docs/creating-managing-service-account-keys\n   */\n  credentials?: string | GCPCredentials;\n\n  /**\n   * Google Auth options configuration.\n   *\n   * @deprecated This option is not supported in web environments.\n   *             Import from `@langchain/google/node` to configure google auth options\n   *             using the NodeApiClient instead.\n   */\n  googleAuthOptions?: never;\n}\n\n/**\n * Web-compatible API client for Google services.\n *\n * This client provides authentication for Google API requests in web environments\n * (browsers, edge functions, etc.) where the google-auth-library is not available.\n * It supports two authentication methods:\n *\n * 1. **API Key Authentication**: Simple key-based authentication suitable for\n *    public APIs and client-side applications.\n *\n * 2. **Service Account Credentials**: OAuth2-based authentication using GCP\n *    service account keys. The client automatically handles token generation\n *    and caching.\n *\n * The client follows this authentication priority:\n * 1. Explicit `apiKey` parameter\n * 2. `GOOGLE_API_KEY` environment variable\n * 3. Explicit `credentials` parameter\n * 4. `GOOGLE_CLOUD_CREDENTIALS` environment variable\n *\n * @extends ApiClient\n *\n * @example\n * ```typescript\n * // Using API key\n * const client = new WebApiClient({\n *   apiKey: 'your-api-key'\n * });\n *\n * // Using service account credentials\n * const client = new WebApiClient({\n *   credentials: {\n *     type: \"service_account\",\n *     project_id: \"my-project\",\n *     private_key_id: \"key-id\",\n *     private_key: \"-----BEGIN PRIVATE KEY-----\\n...\",\n *     client_email: \"service-account@project.iam.gserviceaccount.com\",\n *     // ... other required fields\n *   }\n * });\n *\n * // Using environment variables\n * // Set GOOGLE_API_KEY or GOOGLE_CLOUD_CREDENTIALS\n * const client = new WebApiClient({});\n *\n * // Make authenticated requests\n * const request = new Request('https://api.google.com/...');\n * const response = await client.fetch(request);\n * ```\n *\n * @remarks\n * - API keys are added via the `X-Goog-Api-Key` header\n * - Service account tokens are added via the `Authorization` header with Bearer scheme\n * - Tokens are automatically cached and refreshed as needed\n * - For Node.js environments with advanced auth requirements, use NodeApiClient instead\n *\n * @see {@link NodeApiClient} for Node.js-specific authentication options\n * @see {@link GCPCredentials} for service account credential structure\n */\nexport class WebApiClient extends ApiClient {\n  hasApiKey(): boolean {\n    return typeof this.apiKey === \"string\" && this.apiKey !== \"\";\n  }\n\n  async getProjectId(): Promise<string> {\n    if (typeof this.credentials !== \"undefined\") {\n      return this.credentials.project_id;\n    } else {\n      return super.getProjectId();\n    }\n  }\n\n  /**\n   * The Google API key used for authentication, if provided.\n   *\n   * This value is resolved from either the constructor parameter or the\n   * `GOOGLE_API_KEY` environment variable.\n   *\n   * @protected\n   */\n  protected apiKey?: string;\n\n  /**\n   * The normalized GCP service account credentials, if provided.\n   *\n   * This value is resolved from either the constructor parameter or the\n   * `GOOGLE_CLOUD_CREDENTIALS` environment variable, and is normalized\n   * to ensure immutability.\n   *\n   * @protected\n   */\n  protected credentials?: GCPCredentials;\n\n  /**\n   * Creates a new WebApiClient instance.\n   *\n   * The constructor initializes authentication credentials by checking:\n   * 1. Explicit parameters passed to the constructor\n   * 2. Environment variables (`GOOGLE_API_KEY`, `GOOGLE_CLOUD_CREDENTIALS`)\n   *\n   * Credentials are normalized and frozen to prevent accidental modification.\n   *\n   * @param params - Configuration parameters for the client\n   *\n   * @example\n   * ```typescript\n   * // Minimal configuration (uses environment variables)\n   * const client = new WebApiClient({});\n   *\n   * // With explicit API key\n   * const client = new WebApiClient({\n   *   apiKey: 'your-api-key'\n   * });\n   *\n   * // With service account credentials as JSON string\n   * const client = new WebApiClient({\n   *   credentials: '{\"type\":\"service_account\",...}'\n   * });\n   *\n   * // With service account credentials as object\n   * const client = new WebApiClient({\n   *   credentials: {\n   *     type: \"service_account\",\n   *     // ... other fields\n   *   }\n   * });\n   * ```\n   */\n  constructor(protected params: WebApiClientParams) {\n    super();\n    this.apiKey = params.apiKey ?? getEnvironmentVariable(\"GOOGLE_API_KEY\");\n    this.credentials = iife(() => {\n      if (params.credentials) {\n        return normalizeGCPCredentials(params.credentials);\n      }\n      const credentialsVar = getEnvironmentVariable(\"GOOGLE_CLOUD_CREDENTIALS\");\n      if (credentialsVar) {\n        return normalizeGCPCredentials(credentialsVar);\n      }\n      return undefined;\n    });\n  }\n\n  /**\n   * Executes an HTTP request with appropriate Google API authentication.\n   *\n   * This method adds authentication headers to the request based on the\n   * configured authentication method:\n   *\n   * - If an API key is configured, adds the `X-Goog-Api-Key` header\n   * - If service account credentials are configured, generates an access token\n   *   and adds it via the `Authorization` header with Bearer scheme\n   *\n   * The authentication priority is:\n   * 1. API key (if provided)\n   * 2. Service account credentials (if provided)\n   *\n   * @param request - The HTTP request to execute. Headers will be modified\n   *                  in-place to include authentication information.\n   * @returns A Promise that resolves to the HTTP response\n   *\n   * @throws {AuthError} If no authentication method is available (neither apiKey\n   *                     nor credentials), or if service account authentication\n   *                     fails (e.g., invalid credentials, network error, or\n   *                     token generation failure)\n   *\n   * @example\n   * ```typescript\n   * const client = new WebApiClient({ apiKey: 'your-key' });\n   * const request = new Request('https://generativelanguage.googleapis.com/v1/models');\n   * const response = await client.fetch(request);\n   * const data = await response.json();\n   * ```\n   *\n   * @remarks\n   * - The request object is modified in-place by adding headers\n   * - Service account tokens are automatically cached and refreshed\n   * - If both API key and credentials are provided, API key takes precedence\n   */\n  async fetch(request: Request): Promise<Response> {\n    if (!this.apiKey && !this.credentials) {\n      throw new AuthError({\n        message:\n          \"No authentication method available. Please provide either an apiKey or credentials.\",\n      });\n    }\n    if (this.apiKey) {\n      request.headers.set(GOOGLE_API_KEY_HEADER, this.apiKey);\n    }\n    if (this.credentials) {\n      request.headers.set(\n        GCP_API_KEY_HEADER,\n        `Bearer ${await getGCPCredentialsAccessToken(this.credentials)}`\n      );\n    }\n    return fetch(request);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