@langchain/google 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/chat_models/base.cjs +39 -21
  3. package/dist/chat_models/base.cjs.map +1 -1
  4. package/dist/chat_models/base.d.cts +1 -3
  5. package/dist/chat_models/base.d.ts +1 -3
  6. package/dist/chat_models/base.js +39 -22
  7. package/dist/chat_models/base.js.map +1 -1
  8. package/dist/chat_models/index.cjs.map +1 -1
  9. package/dist/chat_models/index.d.cts +0 -1
  10. package/dist/chat_models/index.d.ts +0 -1
  11. package/dist/chat_models/index.js.map +1 -1
  12. package/dist/chat_models/node.cjs +1 -1
  13. package/dist/chat_models/node.cjs.map +1 -1
  14. package/dist/chat_models/node.d.cts +1 -2
  15. package/dist/chat_models/node.d.ts +1 -2
  16. package/dist/chat_models/node.js +1 -1
  17. package/dist/chat_models/node.js.map +1 -1
  18. package/dist/chat_models/profiles.cjs.map +1 -1
  19. package/dist/chat_models/profiles.js.map +1 -1
  20. package/dist/chat_models/types.cjs.map +1 -1
  21. package/dist/chat_models/types.d.cts +1 -2
  22. package/dist/chat_models/types.d.ts +1 -2
  23. package/dist/chat_models/types.js.map +1 -1
  24. package/dist/clients/index.cjs +1 -0
  25. package/dist/clients/index.cjs.map +1 -1
  26. package/dist/clients/index.js +1 -0
  27. package/dist/clients/index.js.map +1 -1
  28. package/dist/clients/node.cjs +1 -0
  29. package/dist/clients/node.cjs.map +1 -1
  30. package/dist/clients/node.d.cts +0 -1
  31. package/dist/clients/node.d.ts +0 -1
  32. package/dist/clients/node.js +1 -0
  33. package/dist/clients/node.js.map +1 -1
  34. package/dist/const.cjs.map +1 -1
  35. package/dist/const.js.map +1 -1
  36. package/dist/converters/messages.cjs +2 -0
  37. package/dist/converters/messages.cjs.map +1 -1
  38. package/dist/converters/messages.js +1 -1
  39. package/dist/converters/messages.js.map +1 -1
  40. package/dist/converters/params.cjs +5 -0
  41. package/dist/converters/params.cjs.map +1 -1
  42. package/dist/converters/params.js +1 -1
  43. package/dist/converters/params.js.map +1 -1
  44. package/dist/converters/tools.cjs +1 -0
  45. package/dist/converters/tools.cjs.map +1 -1
  46. package/dist/converters/tools.js +1 -1
  47. package/dist/converters/tools.js.map +1 -1
  48. package/dist/node.cjs +1 -1
  49. package/dist/node.d.cts +2 -2
  50. package/dist/node.d.ts +2 -2
  51. package/dist/node.js +1 -1
  52. package/dist/utils/errors.cjs +27 -10
  53. package/dist/utils/errors.cjs.map +1 -1
  54. package/dist/utils/errors.js +28 -12
  55. package/dist/utils/errors.js.map +1 -1
  56. package/dist/utils/gcp-auth.cjs +2 -0
  57. package/dist/utils/gcp-auth.cjs.map +1 -1
  58. package/dist/utils/gcp-auth.js +1 -1
  59. package/dist/utils/gcp-auth.js.map +1 -1
  60. package/dist/utils/handler.cjs.map +1 -1
  61. package/dist/utils/handler.d.cts +0 -1
  62. package/dist/utils/handler.d.ts +0 -1
  63. package/dist/utils/handler.js.map +1 -1
  64. package/dist/utils/metadata.cjs.map +1 -1
  65. package/dist/utils/metadata.js.map +1 -1
  66. package/dist/utils/misc.cjs.map +1 -1
  67. package/dist/utils/misc.d.cts +1 -1
  68. package/dist/utils/misc.d.ts +1 -1
  69. package/dist/utils/misc.js.map +1 -1
  70. package/dist/utils/stream.cjs.map +1 -1
  71. package/dist/utils/stream.js.map +1 -1
  72. package/dist/utils/stream_events.cjs.map +1 -1
  73. package/dist/utils/stream_events.js.map +1 -1
  74. package/package.json +6 -6
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","names":[],"sources":["../../src/chat_models/types.ts"],"sourcesContent":["/* oxlint-disable @typescript-eslint/no-namespace */\n\nimport type { InteropZodType } from \"@langchain/core/utils/types\";\nimport type { BindToolsInput } from \"@langchain/core/language_models/chat_models\";\nimport type { Gemini as GeminiBase } from \"./api-types.js\";\nimport type { LowercaseLiteral, Prettify } from \"../utils/misc.js\";\n\nexport interface ChatGoogleFields {\n /**\n * The temperature is used for sampling during response generation, which\n * occurs when topP and topK are applied. Temperature controls the degree of\n * randomness in token selection. Lower temperatures are good for prompts that\n * require a less open-ended or creative response, while higher temperatures\n * can lead to more diverse or creative results.\n *\n * Specify a lower value for less random responses and a higher value for more\n * random responses.\n */\n temperature?: number;\n\n /**\n * Top-P changes how the model selects tokens for output. Tokens are selected\n * from the most probable to least probable until the sum of their\n * probabilities equals the top-P value.\n *\n * Specify a lower value for less random responses and a higher value for more\n * random responses.\n */\n topP?: number;\n\n /**\n * Top-K changes how the model selects tokens for output. A top-K of 1 means\n * the selected token is the most probable among all tokens in the model's\n * vocabulary (also called greedy decoding), while a top-K of 3 means that the\n * next token is selected from among the 3 most probable tokens (using\n * temperature).\n */\n topK?: number;\n\n /**\n * Maximum number of tokens that can be generated in the response. A token is\n * approximately four characters. 100 tokens correspond to roughly 60-80 words.\n * Specify a lower value for shorter responses and a higher value for\n * potentially longer responses.\n */\n maxOutputTokens?: number;\n\n /**\n * Positive values penalize tokens that already appear in the generated text,\n * increasing the probability of generating more diverse content.\n */\n presencePenalty?: number;\n\n /**\n * Positive values penalize tokens that repeatedly appear in the generated\n * text, decreasing the probability of repeating content.\n */\n frequencyPenalty?: number;\n\n /**\n * Specifies a list of strings that tells the model to stop generating text if\n * one of the strings is encountered in the response. If a string appears\n * multiple times in the response, then the response truncates where it's\n * first encountered. The strings are case-sensitive.\n */\n stopSequences?: string[];\n\n /**\n * When seed is fixed to a specific value, the model makes a best effort to\n * provide the same response for repeated requests. Deterministic output isn't\n * guaranteed. Also, changing the model or parameter settings, such as the\n * temperature, can cause variations in the response even when you use the\n * same seed value. By default, a random seed value is used.\n */\n seed?: number;\n\n /**\n * If true, returns the log probabilities of the tokens that were chosen by\n * the model at each step. By default, this parameter is set to false.\n */\n responseLogprobs?: boolean;\n\n /**\n * Returns the log probabilities of the top candidate tokens at each generation\n * step. The model's chosen token might not be the same as the top candidate\n * token at each step. Specify the number of candidates to return by using an\n * integer value in the range of 1-20.\n */\n logprobs?: number;\n\n /**\n * Per request settings for blocking unsafe content\n */\n safetySettings?: Prettify<GeminiBase.SafetySetting>[];\n\n /**\n * Configuration for the model's thinking process\n */\n thinkingConfig?: Prettify<GeminiBase.ThinkingConfig>;\n\n /**\n * The schema that the generated response should match.\n * Can be a Zod schema or a JSON Schema object.\n * When set, the response will be structured according to this schema\n * and `responseMimeType` will automatically be set to \"application/json\".\n */\n responseSchema?: InteropZodType | Record<string, unknown>;\n\n /**\n * A list of tools the model may use to generate the next response.\n * Can be LangChain tools, OpenAI tools, or Gemini function declarations.\n */\n tools?: BindToolsInput[];\n\n /**\n * The requested modalities of the response.\n * Represents the set of modalities that the model can return.\n * An empty list is equivalent to requesting only text.\n */\n responseModalities?: Prettify<GeminiBase.GenerativeLanguageModality>[];\n\n /**\n * If true, enables enhanced civic answers feature.\n */\n enableEnhancedCivicAnswers?: boolean;\n\n /**\n * Speech generation configuration.\n * You can use either Google's definition of the speech configuration,\n * or a simplified version we've defined (which can be as simple\n * as the name of a pre-defined voice).\n */\n speechConfig?: Prettify<GeminiBase.SpeechConfig> | SimplifiedSpeechConfig;\n\n /**\n * Configuration for image generation.\n */\n imageConfig?: Prettify<GeminiBase.ImageConfig>;\n\n /**\n * Media resolution for input media processing.\n *\n * This maps to `generationConfig.mediaResolution`, which is a scalar enum-like\n * string value in the Gemini API.\n */\n mediaResolution?: GeminiBase.GenerationConfig[\"mediaResolution\"];\n\n /**\n * OpenAI-compatible alias for media input detail level.\n *\n * This is mapped to `generationConfig.mediaResolution`:\n * - `\"auto\"` => default Gemini behavior (`mediaResolution` omitted)\n * - `\"low\"` => `\"MEDIA_RESOLUTION_LOW\"`\n * - `\"high\"` => `\"MEDIA_RESOLUTION_HIGH\"`\n *\n * If both `mediaResolution` and `detail` are provided, `mediaResolution` wins.\n */\n detail?: \"auto\" | \"low\" | \"high\";\n\n /**\n * The number of reasoning tokens that the model should generate.\n * If explicitly set, then the reasoning blocks will be returned.\n */\n maxReasoningTokens?: number;\n\n /**\n * An alias for `maxReasoningTokens` for compatibility.\n */\n thinkingBudget?: number;\n\n /**\n * An alias for `maxReasoningTokens` under Gemini 2.5 or\n * the primary thinking/reasoning setting for Gemini 3.\n * If explicitly set, then the reasoning blocks will be returned.\n */\n reasoningEffort?: GeminiBase.ThinkingLevel;\n\n /**\n * An alias for `reasoningEffort` for compatibility.\n */\n thinkingLevel?: GeminiBase.ThinkingLevel;\n\n /**\n * Inference service tiers.\n * \"priority\" offers highest reliability for higher rates.\n * \"flex\" offers a discount for preemptable processing.\n * Other values are treated as the standard service tier.\n */\n serviceTier?: GeminiBase.ServiceTier;\n\n /**\n * Custom / additional headers to include with every request to the API.\n * When set on both constructor params and per-invocation call options,\n * per-invocation headers take precidence for matching keys.\n */\n customHeaders?: Record<string, string>;\n}\n\nexport type GooglePlatformType = \"gai\" | \"gcp\";\n\n// These are service tiers that we specifically need to send.\n// Other values will be ignored, resulting in the default\n// or \"standard\" setting.\nexport const settableServiceTier: GeminiBase.ServiceTier[] = [\n \"flex\",\n \"priority\",\n];\n\nexport { type Gemini } from \"./api-types.js\";\n\n// There's a fair number of utilities that we need to extract from the base\n// Gemini OpenAPI types, Adding these directly to the base types\n// would pollute the typegen output, so we're adding them here instead.\ndeclare module \"./api-types.js\" {\n export namespace Gemini {\n // Gemini parts are contained as one intersecting type\n // in the spec, so we need to pick out the specific parts we need.\n export namespace Part {\n export type CodeExecutionResult = Pick<\n GeminiBase.Part,\n \"codeExecutionResult\"\n >;\n export type ExecutableCode = Pick<GeminiBase.Part, \"executableCode\">;\n export type FileData = Pick<\n GeminiBase.Part,\n \"fileData\" | \"videoMetadata\"\n >;\n export type FunctionCall = Required<\n Pick<GeminiBase.Part, \"functionCall\">\n > &\n Pick<GeminiBase.Part, \"thoughtSignature\">;\n export type FunctionResponse = Pick<GeminiBase.Part, \"functionResponse\">;\n export type InlineData = Pick<\n GeminiBase.Part,\n \"inlineData\" | \"videoMetadata\"\n >;\n export type MediaResolution = Pick<GeminiBase.Part, \"mediaResolution\">;\n export type PartMetadata = Pick<GeminiBase.Part, \"partMetadata\">;\n export type Text = Pick<GeminiBase.Part, \"text\">;\n export type Thought = Pick<GeminiBase.Part, \"thought\">;\n export type ThoughtSignature = Pick<GeminiBase.Part, \"thoughtSignature\">;\n }\n\n export namespace PrebuiltVoiceConfig {\n /**\n * The name of a prebuilt voice that can be used for speech synthesis.\n *\n * Extracted as a non-nullable type from the GeminiBase.PrebuiltVoiceConfig[\"voiceName\"] property.\n */\n export type VoiceName = NonNullable<\n GeminiBase.PrebuiltVoiceConfig[\"voiceName\"]\n >;\n }\n\n export namespace SpeakerVoiceConfig {\n /**\n * The speaker identifier for a custom or multi-speaker TTS configuration.\n *\n * Extracted as a non-nullable type from the GeminiBase.SpeakerVoiceConfig[\"speaker\"] property.\n */\n export type Speaker = NonNullable<\n GeminiBase.SpeakerVoiceConfig[\"speaker\"]\n >;\n }\n\n export namespace SpeechConfig {\n /**\n * The BCP-47 language code for speech synthesis (e.g., \"en-US\").\n *\n * Extracted as a non-nullable type from the GeminiBase.SpeechConfig[\"languageCode\"] property.\n */\n export type LanguageCode = NonNullable<\n GeminiBase.SpeechConfig[\"languageCode\"]\n >;\n }\n\n /**\n * The level of \"thinking\" or reasoning configured for the model.\n *\n * Extends GeminiBase.ThinkingConfig[\"thinkingLevel\"] to also accept\n * lowercase variants (e.g. \"high\" in addition to \"HIGH\").\n */\n export type ThinkingLevel =\n | GeminiBase.ThinkingConfig[\"thinkingLevel\"]\n | LowercaseLiteral<GeminiBase.ThinkingConfig[\"thinkingLevel\"]>;\n\n /**\n * The role of a content message. The spec types this as `string`, but\n * the API only accepts these specific values.\n */\n export type Role = \"user\" | \"model\" | \"function\";\n\n /**\n * Alias for the unwieldy generated grounding support type name.\n */\n export type GroundingSupport =\n GeminiBase.GoogleAiGenerativelanguageV1betaGroundingSupport;\n\n /**\n * Alias for the unwieldy generated segment type name.\n */\n export type Segment = GeminiBase.GoogleAiGenerativelanguageV1betaSegment;\n\n export namespace Tools {\n /**\n * The mode for function calling configuration, extracted from the\n * FunctionCallingConfig interface.\n */\n export type FunctionCallingConfigMode =\n GeminiBase.Tools.FunctionCallingConfig[\"mode\"];\n }\n\n /**\n * Legacy URL retrieval metadata (predecessor of UrlContextMetadata).\n * Not in the current OpenAPI spec but still returned by the API.\n */\n export interface UrlRetrievalMetadata {\n urlRetrievalContexts?: Array<GeminiBase.UrlMetadata>;\n }\n\n // Augment Candidate with legacy field the API still returns.\n export interface Candidate {\n /** @deprecated Use urlContextMetadata instead. */\n readonly urlRetrievalMetadata?: UrlRetrievalMetadata;\n }\n }\n}\n\n/**\n * Simplified speaker/name pair for multi-speaker config.\n * - `speaker` derived from SpeakerVoiceConfig[\"speaker\"]\n * - `name` is the prebuilt voice name\n */\nexport interface SpeechSpeakerName {\n speaker: GeminiBase.SpeakerVoiceConfig.Speaker;\n name: GeminiBase.PrebuiltVoiceConfig.VoiceName;\n}\n\n/** A voice can be a prebuilt voice name, a speaker/name pair, or an array of pairs */\nexport type SpeechVoice =\n | GeminiBase.PrebuiltVoiceConfig.VoiceName\n | SpeechSpeakerName\n | SpeechSpeakerName[];\n\n/** Voice with language code (derived from SpeechConfig's languageCode) */\nexport interface SpeechVoiceLanguage {\n voice: SpeechVoice;\n languageCode: GeminiBase.SpeechConfig.LanguageCode;\n}\n\n/** Voices with language code */\nexport interface SpeechVoicesLanguage {\n voices: SpeechVoice;\n languageCode: GeminiBase.SpeechConfig.LanguageCode;\n}\n\n/** Simplified language config (with voice or voices) */\nexport type SimplifiedSpeechLanguageConfig =\n | SpeechVoiceLanguage\n | SpeechVoicesLanguage;\n\n/** Top-level simplified config: just a voice, or voice+language */\nexport type SimplifiedSpeechConfig =\n | SpeechVoice\n | SimplifiedSpeechLanguageConfig;\n"],"mappings":";AA2MA,MAAa,sBAAgD,CAC3D,QACA,WACD"}
1
+ {"version":3,"file":"types.js","names":[],"sources":["../../src/chat_models/types.ts"],"sourcesContent":["/* oxlint-disable @typescript-eslint/no-namespace */\n\nimport type { InteropZodType } from \"@langchain/core/utils/types\";\nimport type { BindToolsInput } from \"@langchain/core/language_models/chat_models\";\nimport type { Gemini as GeminiBase } from \"./api-types.js\";\nimport type { LowercaseLiteral, Prettify } from \"../utils/misc.js\";\n\nexport interface ChatGoogleFields {\n /**\n * The temperature is used for sampling during response generation, which\n * occurs when topP and topK are applied. Temperature controls the degree of\n * randomness in token selection. Lower temperatures are good for prompts that\n * require a less open-ended or creative response, while higher temperatures\n * can lead to more diverse or creative results.\n *\n * Specify a lower value for less random responses and a higher value for more\n * random responses.\n */\n temperature?: number;\n\n /**\n * Top-P changes how the model selects tokens for output. Tokens are selected\n * from the most probable to least probable until the sum of their\n * probabilities equals the top-P value.\n *\n * Specify a lower value for less random responses and a higher value for more\n * random responses.\n */\n topP?: number;\n\n /**\n * Top-K changes how the model selects tokens for output. A top-K of 1 means\n * the selected token is the most probable among all tokens in the model's\n * vocabulary (also called greedy decoding), while a top-K of 3 means that the\n * next token is selected from among the 3 most probable tokens (using\n * temperature).\n */\n topK?: number;\n\n /**\n * Maximum number of tokens that can be generated in the response. A token is\n * approximately four characters. 100 tokens correspond to roughly 60-80 words.\n * Specify a lower value for shorter responses and a higher value for\n * potentially longer responses.\n */\n maxOutputTokens?: number;\n\n /**\n * Positive values penalize tokens that already appear in the generated text,\n * increasing the probability of generating more diverse content.\n */\n presencePenalty?: number;\n\n /**\n * Positive values penalize tokens that repeatedly appear in the generated\n * text, decreasing the probability of repeating content.\n */\n frequencyPenalty?: number;\n\n /**\n * Specifies a list of strings that tells the model to stop generating text if\n * one of the strings is encountered in the response. If a string appears\n * multiple times in the response, then the response truncates where it's\n * first encountered. The strings are case-sensitive.\n */\n stopSequences?: string[];\n\n /**\n * When seed is fixed to a specific value, the model makes a best effort to\n * provide the same response for repeated requests. Deterministic output isn't\n * guaranteed. Also, changing the model or parameter settings, such as the\n * temperature, can cause variations in the response even when you use the\n * same seed value. By default, a random seed value is used.\n */\n seed?: number;\n\n /**\n * If true, returns the log probabilities of the tokens that were chosen by\n * the model at each step. By default, this parameter is set to false.\n */\n responseLogprobs?: boolean;\n\n /**\n * Returns the log probabilities of the top candidate tokens at each generation\n * step. The model's chosen token might not be the same as the top candidate\n * token at each step. Specify the number of candidates to return by using an\n * integer value in the range of 1-20.\n */\n logprobs?: number;\n\n /**\n * Per request settings for blocking unsafe content\n */\n safetySettings?: Prettify<GeminiBase.SafetySetting>[];\n\n /**\n * Configuration for the model's thinking process\n */\n thinkingConfig?: Prettify<GeminiBase.ThinkingConfig>;\n\n /**\n * The schema that the generated response should match.\n * Can be a Zod schema or a JSON Schema object.\n * When set, the response will be structured according to this schema\n * and `responseMimeType` will automatically be set to \"application/json\".\n */\n responseSchema?: InteropZodType | Record<string, unknown>;\n\n /**\n * A list of tools the model may use to generate the next response.\n * Can be LangChain tools, OpenAI tools, or Gemini function declarations.\n */\n tools?: BindToolsInput[];\n\n /**\n * The requested modalities of the response.\n * Represents the set of modalities that the model can return.\n * An empty list is equivalent to requesting only text.\n */\n responseModalities?: Prettify<GeminiBase.GenerativeLanguageModality>[];\n\n /**\n * If true, enables enhanced civic answers feature.\n */\n enableEnhancedCivicAnswers?: boolean;\n\n /**\n * Speech generation configuration.\n * You can use either Google's definition of the speech configuration,\n * or a simplified version we've defined (which can be as simple\n * as the name of a pre-defined voice).\n */\n speechConfig?: Prettify<GeminiBase.SpeechConfig> | SimplifiedSpeechConfig;\n\n /**\n * Configuration for image generation.\n */\n imageConfig?: Prettify<GeminiBase.ImageConfig>;\n\n /**\n * Media resolution for input media processing.\n *\n * This maps to `generationConfig.mediaResolution`, which is a scalar enum-like\n * string value in the Gemini API.\n */\n mediaResolution?: GeminiBase.GenerationConfig[\"mediaResolution\"];\n\n /**\n * OpenAI-compatible alias for media input detail level.\n *\n * This is mapped to `generationConfig.mediaResolution`:\n * - `\"auto\"` => default Gemini behavior (`mediaResolution` omitted)\n * - `\"low\"` => `\"MEDIA_RESOLUTION_LOW\"`\n * - `\"high\"` => `\"MEDIA_RESOLUTION_HIGH\"`\n *\n * If both `mediaResolution` and `detail` are provided, `mediaResolution` wins.\n */\n detail?: \"auto\" | \"low\" | \"high\";\n\n /**\n * The number of reasoning tokens that the model should generate.\n * If explicitly set, then the reasoning blocks will be returned.\n */\n maxReasoningTokens?: number;\n\n /**\n * An alias for `maxReasoningTokens` for compatibility.\n */\n thinkingBudget?: number;\n\n /**\n * An alias for `maxReasoningTokens` under Gemini 2.5 or\n * the primary thinking/reasoning setting for Gemini 3.\n * If explicitly set, then the reasoning blocks will be returned.\n */\n reasoningEffort?: GeminiBase.ThinkingLevel;\n\n /**\n * An alias for `reasoningEffort` for compatibility.\n */\n thinkingLevel?: GeminiBase.ThinkingLevel;\n\n /**\n * Inference service tiers.\n * \"priority\" offers highest reliability for higher rates.\n * \"flex\" offers a discount for preemptable processing.\n * Other values are treated as the standard service tier.\n */\n serviceTier?: GeminiBase.ServiceTier;\n\n /**\n * Custom / additional headers to include with every request to the API.\n * When set on both constructor params and per-invocation call options,\n * per-invocation headers take precidence for matching keys.\n */\n customHeaders?: Record<string, string>;\n}\n\nexport type GooglePlatformType = \"gai\" | \"gcp\";\n\n// These are service tiers that we specifically need to send.\n// Other values will be ignored, resulting in the default\n// or \"standard\" setting.\nexport const settableServiceTier: GeminiBase.ServiceTier[] = [\n \"flex\",\n \"priority\",\n];\n\nexport { type Gemini } from \"./api-types.js\";\n\n// There's a fair number of utilities that we need to extract from the base\n// Gemini OpenAPI types, Adding these directly to the base types\n// would pollute the typegen output, so we're adding them here instead.\ndeclare module \"./api-types.js\" {\n export namespace Gemini {\n // Gemini parts are contained as one intersecting type\n // in the spec, so we need to pick out the specific parts we need.\n export namespace Part {\n export type CodeExecutionResult = Pick<\n GeminiBase.Part,\n \"codeExecutionResult\"\n >;\n export type ExecutableCode = Pick<GeminiBase.Part, \"executableCode\">;\n export type FileData = Pick<\n GeminiBase.Part,\n \"fileData\" | \"videoMetadata\"\n >;\n export type FunctionCall = Required<\n Pick<GeminiBase.Part, \"functionCall\">\n > &\n Pick<GeminiBase.Part, \"thoughtSignature\">;\n export type FunctionResponse = Pick<GeminiBase.Part, \"functionResponse\">;\n export type InlineData = Pick<\n GeminiBase.Part,\n \"inlineData\" | \"videoMetadata\"\n >;\n export type MediaResolution = Pick<GeminiBase.Part, \"mediaResolution\">;\n export type PartMetadata = Pick<GeminiBase.Part, \"partMetadata\">;\n export type Text = Pick<GeminiBase.Part, \"text\">;\n export type Thought = Pick<GeminiBase.Part, \"thought\">;\n export type ThoughtSignature = Pick<GeminiBase.Part, \"thoughtSignature\">;\n }\n\n export namespace PrebuiltVoiceConfig {\n /**\n * The name of a prebuilt voice that can be used for speech synthesis.\n *\n * Extracted as a non-nullable type from the GeminiBase.PrebuiltVoiceConfig[\"voiceName\"] property.\n */\n export type VoiceName = NonNullable<\n GeminiBase.PrebuiltVoiceConfig[\"voiceName\"]\n >;\n }\n\n export namespace SpeakerVoiceConfig {\n /**\n * The speaker identifier for a custom or multi-speaker TTS configuration.\n *\n * Extracted as a non-nullable type from the GeminiBase.SpeakerVoiceConfig[\"speaker\"] property.\n */\n export type Speaker = NonNullable<\n GeminiBase.SpeakerVoiceConfig[\"speaker\"]\n >;\n }\n\n export namespace SpeechConfig {\n /**\n * The BCP-47 language code for speech synthesis (e.g., \"en-US\").\n *\n * Extracted as a non-nullable type from the GeminiBase.SpeechConfig[\"languageCode\"] property.\n */\n export type LanguageCode = NonNullable<\n GeminiBase.SpeechConfig[\"languageCode\"]\n >;\n }\n\n /**\n * The level of \"thinking\" or reasoning configured for the model.\n *\n * Extends GeminiBase.ThinkingConfig[\"thinkingLevel\"] to also accept\n * lowercase variants (e.g. \"high\" in addition to \"HIGH\").\n */\n export type ThinkingLevel =\n | GeminiBase.ThinkingConfig[\"thinkingLevel\"]\n | LowercaseLiteral<GeminiBase.ThinkingConfig[\"thinkingLevel\"]>;\n\n /**\n * The role of a content message. The spec types this as `string`, but\n * the API only accepts these specific values.\n */\n export type Role = \"user\" | \"model\" | \"function\";\n\n /**\n * Alias for the unwieldy generated grounding support type name.\n */\n export type GroundingSupport =\n GeminiBase.GoogleAiGenerativelanguageV1betaGroundingSupport;\n\n /**\n * Alias for the unwieldy generated segment type name.\n */\n export type Segment = GeminiBase.GoogleAiGenerativelanguageV1betaSegment;\n\n export namespace Tools {\n /**\n * The mode for function calling configuration, extracted from the\n * FunctionCallingConfig interface.\n */\n export type FunctionCallingConfigMode =\n GeminiBase.Tools.FunctionCallingConfig[\"mode\"];\n }\n\n /**\n * Legacy URL retrieval metadata (predecessor of UrlContextMetadata).\n * Not in the current OpenAPI spec but still returned by the API.\n */\n export interface UrlRetrievalMetadata {\n urlRetrievalContexts?: Array<GeminiBase.UrlMetadata>;\n }\n\n // Augment Candidate with legacy field the API still returns.\n export interface Candidate {\n /** @deprecated Use urlContextMetadata instead. */\n readonly urlRetrievalMetadata?: UrlRetrievalMetadata;\n }\n }\n}\n\n/**\n * Simplified speaker/name pair for multi-speaker config.\n * - `speaker` derived from SpeakerVoiceConfig[\"speaker\"]\n * - `name` is the prebuilt voice name\n */\nexport interface SpeechSpeakerName {\n speaker: GeminiBase.SpeakerVoiceConfig.Speaker;\n name: GeminiBase.PrebuiltVoiceConfig.VoiceName;\n}\n\n/** A voice can be a prebuilt voice name, a speaker/name pair, or an array of pairs */\nexport type SpeechVoice =\n | GeminiBase.PrebuiltVoiceConfig.VoiceName\n | SpeechSpeakerName\n | SpeechSpeakerName[];\n\n/** Voice with language code (derived from SpeechConfig's languageCode) */\nexport interface SpeechVoiceLanguage {\n voice: SpeechVoice;\n languageCode: GeminiBase.SpeechConfig.LanguageCode;\n}\n\n/** Voices with language code */\nexport interface SpeechVoicesLanguage {\n voices: SpeechVoice;\n languageCode: GeminiBase.SpeechConfig.LanguageCode;\n}\n\n/** Simplified language config (with voice or voices) */\nexport type SimplifiedSpeechLanguageConfig =\n | SpeechVoiceLanguage\n | SpeechVoicesLanguage;\n\n/** Top-level simplified config: just a voice, or voice+language */\nexport type SimplifiedSpeechConfig =\n | SpeechVoice\n | SimplifiedSpeechLanguageConfig;\n"],"mappings":";AA2MA,MAAa,sBAAgD,CAC3D,QACA,UACF"}
@@ -95,6 +95,7 @@ var ApiClient = class {
95
95
  * @see {@link GCPCredentials} for service account credential structure
96
96
  */
97
97
  var WebApiClient = class extends ApiClient {
98
+ params;
98
99
  hasApiKey() {
99
100
  return typeof this.apiKey === "string" && this.apiKey !== "";
100
101
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["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);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,IAAsB,YAAtB,MAAgC;;;;;CAU9B,MAAM,eAAgC;AACpC,SAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyHX,IAAa,eAAb,cAAkC,UAAU;CAC1C,YAAqB;AACnB,SAAO,OAAO,KAAK,WAAW,YAAY,KAAK,WAAW;;CAG5D,MAAM,eAAgC;AACpC,MAAI,OAAO,KAAK,gBAAgB,YAC9B,QAAO,KAAK,YAAY;MAExB,QAAO,MAAM,cAAc;;;;;;;;;;CAY/B;;;;;;;;;;CAWA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqCA,YAAY,QAAsC;AAChD,SAAO;AADa,OAAA,SAAA;AAEpB,OAAK,SAAS,OAAO,WAAA,GAAA,0BAAA,wBAAiC,iBAAiB;AACvE,OAAK,cAAcA,aAAAA,WAAW;AAC5B,OAAI,OAAO,YACT,QAAOC,iBAAAA,wBAAwB,OAAO,YAAY;GAEpD,MAAM,kBAAA,GAAA,0BAAA,wBAAwC,2BAA2B;AACzE,OAAI,eACF,QAAOA,iBAAAA,wBAAwB,eAAe;IAGhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuCJ,MAAM,MAAM,SAAqC;AAC/C,MAAI,CAAC,KAAK,UAAU,CAAC,KAAK,YACxB,OAAM,IAAIC,eAAAA,UAAU,EAClB,SACE,uFACH,CAAC;AAEJ,MAAI,KAAK,OACP,SAAQ,QAAQ,IAAIC,cAAAA,uBAAuB,KAAK,OAAO;AAEzD,MAAI,KAAK,YACP,SAAQ,QAAQ,IACdC,cAAAA,oBACA,UAAU,MAAMC,iBAAAA,6BAA6B,KAAK,YAAY,GAC/D;AAEH,SAAO,MAAM,QAAQ"}
1
+ {"version":3,"file":"index.cjs","names":["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);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,IAAsB,YAAtB,MAAgC;;;;;CAU9B,MAAM,eAAgC;EACpC,OAAO;CACT;AAcF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0GA,IAAa,eAAb,cAAkC,UAAU;CAqEpB;CApEtB,YAAqB;EACnB,OAAO,OAAO,KAAK,WAAW,YAAY,KAAK,WAAW;CAC5D;CAEA,MAAM,eAAgC;EACpC,IAAI,OAAO,KAAK,gBAAgB,aAC9B,OAAO,KAAK,YAAY;OAExB,OAAO,MAAM,aAAa;CAE9B;;;;;;;;;CAUA;;;;;;;;;;CAWA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqCA,YAAY,QAAsC;EAChD,MAAM;EADc,KAAA,SAAA;EAEpB,KAAK,SAAS,OAAO,WAAA,GAAA,0BAAA,uBAAA,CAAiC,gBAAgB;EACtE,KAAK,cAAcA,aAAAA,WAAW;GAC5B,IAAI,OAAO,aACT,OAAOC,iBAAAA,wBAAwB,OAAO,WAAW;GAEnD,MAAM,kBAAA,GAAA,0BAAA,uBAAA,CAAwC,0BAA0B;GACxE,IAAI,gBACF,OAAOA,iBAAAA,wBAAwB,cAAc;EAGjD,CAAC;CACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAsCA,MAAM,MAAM,SAAqC;EAC/C,IAAI,CAAC,KAAK,UAAU,CAAC,KAAK,aACxB,MAAM,IAAIC,eAAAA,UAAU,EAClB,SACE,sFACJ,CAAC;EAEH,IAAI,KAAK,QACP,QAAQ,QAAQ,IAAIC,cAAAA,uBAAuB,KAAK,MAAM;EAExD,IAAI,KAAK,aACP,QAAQ,QAAQ,IACdC,cAAAA,oBACA,UAAU,MAAMC,iBAAAA,6BAA6B,KAAK,WAAW,GAC/D;EAEF,OAAO,MAAM,OAAO;CACtB;AACF"}
@@ -95,6 +95,7 @@ var ApiClient = class {
95
95
  * @see {@link GCPCredentials} for service account credential structure
96
96
  */
97
97
  var WebApiClient = class extends ApiClient {
98
+ params;
98
99
  hasApiKey() {
99
100
  return typeof this.apiKey === "string" && this.apiKey !== "";
100
101
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"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);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,IAAsB,YAAtB,MAAgC;;;;;CAU9B,MAAM,eAAgC;AACpC,SAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyHX,IAAa,eAAb,cAAkC,UAAU;CAC1C,YAAqB;AACnB,SAAO,OAAO,KAAK,WAAW,YAAY,KAAK,WAAW;;CAG5D,MAAM,eAAgC;AACpC,MAAI,OAAO,KAAK,gBAAgB,YAC9B,QAAO,KAAK,YAAY;MAExB,QAAO,MAAM,cAAc;;;;;;;;;;CAY/B;;;;;;;;;;CAWA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqCA,YAAY,QAAsC;AAChD,SAAO;AADa,OAAA,SAAA;AAEpB,OAAK,SAAS,OAAO,UAAU,uBAAuB,iBAAiB;AACvE,OAAK,cAAc,WAAW;AAC5B,OAAI,OAAO,YACT,QAAO,wBAAwB,OAAO,YAAY;GAEpD,MAAM,iBAAiB,uBAAuB,2BAA2B;AACzE,OAAI,eACF,QAAO,wBAAwB,eAAe;IAGhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuCJ,MAAM,MAAM,SAAqC;AAC/C,MAAI,CAAC,KAAK,UAAU,CAAC,KAAK,YACxB,OAAM,IAAI,UAAU,EAClB,SACE,uFACH,CAAC;AAEJ,MAAI,KAAK,OACP,SAAQ,QAAQ,IAAI,uBAAuB,KAAK,OAAO;AAEzD,MAAI,KAAK,YACP,SAAQ,QAAQ,IACd,oBACA,UAAU,MAAM,6BAA6B,KAAK,YAAY,GAC/D;AAEH,SAAO,MAAM,QAAQ"}
1
+ {"version":3,"file":"index.js","names":[],"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);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,IAAsB,YAAtB,MAAgC;;;;;CAU9B,MAAM,eAAgC;EACpC,OAAO;CACT;AAcF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0GA,IAAa,eAAb,cAAkC,UAAU;CAqEpB;CApEtB,YAAqB;EACnB,OAAO,OAAO,KAAK,WAAW,YAAY,KAAK,WAAW;CAC5D;CAEA,MAAM,eAAgC;EACpC,IAAI,OAAO,KAAK,gBAAgB,aAC9B,OAAO,KAAK,YAAY;OAExB,OAAO,MAAM,aAAa;CAE9B;;;;;;;;;CAUA;;;;;;;;;;CAWA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqCA,YAAY,QAAsC;EAChD,MAAM;EADc,KAAA,SAAA;EAEpB,KAAK,SAAS,OAAO,UAAU,uBAAuB,gBAAgB;EACtE,KAAK,cAAc,WAAW;GAC5B,IAAI,OAAO,aACT,OAAO,wBAAwB,OAAO,WAAW;GAEnD,MAAM,iBAAiB,uBAAuB,0BAA0B;GACxE,IAAI,gBACF,OAAO,wBAAwB,cAAc;EAGjD,CAAC;CACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAsCA,MAAM,MAAM,SAAqC;EAC/C,IAAI,CAAC,KAAK,UAAU,CAAC,KAAK,aACxB,MAAM,IAAI,UAAU,EAClB,SACE,sFACJ,CAAC;EAEH,IAAI,KAAK,QACP,QAAQ,QAAQ,IAAI,uBAAuB,KAAK,MAAM;EAExD,IAAI,KAAK,aACP,QAAQ,QAAQ,IACd,oBACA,UAAU,MAAM,6BAA6B,KAAK,WAAW,GAC/D;EAEF,OAAO,MAAM,OAAO;CACtB;AACF"}
@@ -87,6 +87,7 @@ let google_auth_library = require("google-auth-library");
87
87
  * @see {@link GoogleAuthOptions} for advanced authentication configuration
88
88
  */
89
89
  var NodeApiClient = class extends require_index.ApiClient {
90
+ params;
90
91
  hasApiKey() {
91
92
  return typeof this.apiKey === "string" && this.apiKey !== "";
92
93
  }
@@ -1 +1 @@
1
- {"version":3,"file":"node.cjs","names":["ApiClient","iife","normalizeGCPCredentials","GoogleAuth","GOOGLE_API_KEY_HEADER","GCP_API_KEY_HEADER","getGCPCredentialsAccessToken","ConfigurationError"],"sources":["../../src/clients/node.ts"],"sourcesContent":["import { GoogleAuth, type GoogleAuthOptions } from \"google-auth-library\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { GCP_API_KEY_HEADER, GOOGLE_API_KEY_HEADER } from \"../const.js\";\nimport { ApiClient } from \"./index.js\";\nimport {\n GCPCredentials,\n getGCPCredentialsAccessToken,\n normalizeGCPCredentials,\n} from \"../utils/gcp-auth.js\";\nimport { ConfigurationError } from \"../utils/errors.js\";\nimport { iife } from \"../utils/misc.js\";\n\n/**\n * Configuration parameters for the NodeApiClient.\n *\n * This interface defines the authentication options available for Node.js-based\n * API clients. Authentication can be provided via an API key, GCP service\n * account credentials, or advanced Google Auth options. The client will\n * automatically check environment variables if explicit values are not provided.\n *\n * @interface\n */\nexport interface NodeApiClientParams {\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 * Provides fine-grained control over authentication behavior using the\n * google-auth-library. This option enables:\n * - Custom OAuth2 scopes\n * - Application Default Credentials (ADC)\n * - Impersonation and delegation\n * - Custom credential sources\n *\n * When provided, this takes precedence over simple credential-based auth\n * but is lower priority than API key authentication.\n *\n * @see https://github.com/googleapis/google-auth-library-nodejs\n * @see https://cloud.google.com/docs/authentication/application-default-credentials\n */\n googleAuthOptions?: GoogleAuthOptions;\n}\n\n/**\n * Node.js-specific API client for Google services.\n *\n * This client provides comprehensive authentication for Google API requests in\n * Node.js environments, leveraging the full capabilities of the google-auth-library.\n * It supports three authentication methods with the following priority:\n *\n * 1. **API Key Authentication**: Simple key-based authentication suitable for\n * public APIs and development environments.\n *\n * 2. **Service Account Credentials**: OAuth2-based authentication using GCP\n * service account keys. The client automatically handles token generation\n * and caching using a web-compatible implementation.\n *\n * 3. **Google Auth Library**: Advanced authentication using google-auth-library,\n * supporting Application Default Credentials (ADC), custom scopes, and\n * various credential sources.\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 * 5. `googleAuthOptions` parameter\n * 6. Application Default Credentials (if googleAuthOptions is provided without explicit credentials)\n *\n * @extends ApiClient\n *\n * @example\n * ```typescript\n * // Using API key\n * const client = new NodeApiClient({\n * apiKey: 'your-api-key'\n * });\n *\n * // Using service account credentials\n * const client = new NodeApiClient({\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 Google Auth with custom scopes\n * const client = new NodeApiClient({\n * googleAuthOptions: {\n * scopes: ['https://www.googleapis.com/auth/cloud-platform'],\n * keyFilename: '/path/to/service-account-key.json'\n * }\n * });\n *\n * // Using Application Default Credentials\n * const client = new NodeApiClient({\n * googleAuthOptions: {}\n * });\n *\n * // Using environment variables\n * // Set GOOGLE_API_KEY or GOOGLE_CLOUD_CREDENTIALS\n * const client = new NodeApiClient();\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 * - Google Auth headers are automatically generated and added by google-auth-library\n * - Tokens are automatically cached and refreshed as needed\n * - For web/edge environments without google-auth-library, use WebApiClient instead\n *\n * @see {@link WebApiClient} for web-compatible authentication without google-auth-library\n * @see {@link GCPCredentials} for service account credential structure\n * @see {@link GoogleAuthOptions} for advanced authentication configuration\n */\nexport class NodeApiClient 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 if (typeof this.googleAuth !== \"undefined\") {\n return this.googleAuth.getProjectId();\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 * The Google Auth instance for advanced authentication, if configured.\n *\n * This instance is created when `googleAuthOptions` is provided and\n * handles Application Default Credentials, custom scopes, and other\n * advanced authentication scenarios.\n *\n * @protected\n */\n protected googleAuth?: GoogleAuth;\n\n /**\n * Creates a new NodeApiClient 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 * 3. Application Default Credentials (if googleAuthOptions is provided)\n *\n * Credentials are normalized and frozen to prevent accidental modification.\n * The GoogleAuth instance is lazily initialized only when googleAuthOptions\n * is provided.\n *\n * @param params - Configuration parameters for the client. Defaults to an empty object.\n *\n * @example\n * ```typescript\n * // Minimal configuration (uses environment variables or ADC)\n * const client = new NodeApiClient();\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 NodeApiClient({\n * credentials: {\n * type: \"service_account\",\n * // ... other fields\n * }\n * });\n *\n * // With Google Auth options\n * const client = new NodeApiClient({\n * googleAuthOptions: {\n * scopes: ['https://www.googleapis.com/auth/cloud-platform'],\n * projectId: 'my-project'\n * }\n * });\n * ```\n */\n constructor(protected params: NodeApiClientParams = {}) {\n super();\n\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 this.googleAuth = iife(() => {\n if (params.googleAuthOptions) {\n return new GoogleAuth(params.googleAuthOptions);\n }\n if (!this.apiKey && !this.credentials) {\n return new GoogleAuth();\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, following this priority:\n *\n * 1. If an API key is configured, adds the `X-Goog-Api-Key` header\n * 2. If service account credentials are configured, generates an access token\n * and adds it via the `Authorization` header with Bearer scheme\n * 3. If Google Auth is configured, uses google-auth-library to generate\n * appropriate authentication headers (may include Authorization, x-goog-user-project, etc.)\n *\n * The authentication priority ensures that explicit API keys take precedence,\n * followed by service account credentials, and finally Google Auth options.\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 service account authentication fails (e.g., invalid\n * credentials, network error, or token generation failure)\n * @throws {Error} If Google Auth authentication fails (e.g., missing credentials,\n * invalid configuration, or ADC not available)\n *\n * @example\n * ```typescript\n * const client = new NodeApiClient({ 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 * - Google Auth tokens are managed by google-auth-library with automatic refresh\n * - Only one authentication method is used per request (based on priority)\n * - Google Auth may add multiple headers depending on the authentication type\n */\n async fetch(request: Request): Promise<Response> {\n if (this.apiKey) {\n request.headers.set(GOOGLE_API_KEY_HEADER, this.apiKey);\n } else if (this.credentials) {\n request.headers.set(\n GCP_API_KEY_HEADER,\n `Bearer ${getGCPCredentialsAccessToken(this.credentials)}`\n );\n } else if (this.googleAuth) {\n const authHeaders = await this.googleAuth.getRequestHeaders(request.url);\n authHeaders.forEach((value, key) => {\n if (value !== null) {\n request.headers.set(key, value);\n }\n });\n }\n return fetch(request);\n }\n}\n\n/**\n * Ensures that Google Auth options include required OAuth2 scopes.\n *\n * This utility function validates and augments GoogleAuthOptions to ensure\n * that all required OAuth2 scopes are present. It handles three scenarios:\n *\n * 1. **No auth options provided**: Creates new options with required scopes\n * 2. **Auth options without scopes**: Adds required scopes to existing options\n * 3. **Auth options with scopes**: Validates that all required scopes are present\n *\n * This is particularly useful when working with Google APIs that require specific\n * scopes for access, ensuring that authentication is properly configured before\n * making API requests.\n *\n * @param authOptions - The existing Google Auth options to validate/augment.\n * Can be undefined or an empty object.\n * @param requiredScopes - Array of OAuth2 scope URLs that must be present.\n * These are typically Google API scope URLs like\n * 'https://www.googleapis.com/auth/cloud-platform'\n * @returns The validated/augmented GoogleAuthOptions with all required scopes\n *\n * @throws {Error} If authOptions already has scopes but is missing any of the\n * required scopes. This prevents accidental scope reduction that\n * could break API access.\n *\n * @example\n * ```typescript\n * // Create new options with required scopes\n * const options = ensureAuthScopes(undefined, [\n * 'https://www.googleapis.com/auth/cloud-platform'\n * ]);\n * // Result: { scopes: ['https://www.googleapis.com/auth/cloud-platform'] }\n *\n * // Add scopes to existing options\n * const options = ensureAuthScopes(\n * { projectId: 'my-project' },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * // Result: { projectId: 'my-project', scopes: [...] }\n *\n * // Validate existing scopes\n * const options = ensureAuthScopes(\n * { scopes: ['https://www.googleapis.com/auth/cloud-platform'] },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * // Result: Original options (validation passed)\n *\n * // Error case - missing required scope\n * try {\n * ensureAuthScopes(\n * { scopes: ['https://www.googleapis.com/auth/userinfo.email'] },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * } catch (error) {\n * // Error: Invalid auth scopes. Scopes must include ...\n * }\n * ```\n *\n * @remarks\n * - Scopes can be provided as a string or array of strings in GoogleAuthOptions\n * - The function normalizes single-string scopes to arrays for validation\n * - Required scopes are not automatically added if existing scopes are present;\n * instead, an error is thrown to prevent unintended scope changes\n * - This function does not modify the original authOptions object\n *\n * @see https://developers.google.com/identity/protocols/oauth2/scopes\n * @see {@link GoogleAuthOptions} for the full authentication configuration interface\n */\nexport function ensureAuthScopes(\n authOptions: GoogleAuthOptions,\n requiredScopes: string[]\n): GoogleAuthOptions {\n if (!authOptions) {\n return { scopes: requiredScopes };\n } else if (!authOptions.scopes) {\n return { ...authOptions, scopes: requiredScopes };\n } else {\n const existingScopes = Array.isArray(authOptions.scopes)\n ? authOptions.scopes\n : [authOptions.scopes];\n const missingScopes = requiredScopes.filter(\n (scope) => !existingScopes.includes(scope)\n );\n if (missingScopes.length > 0) {\n throw new ConfigurationError(\n `Invalid auth scopes. Scopes must include ${requiredScopes.join(\", \")}`\n );\n }\n }\n return authOptions;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkJA,IAAa,gBAAb,cAAmCA,cAAAA,UAAU;CAC3C,YAAqB;AACnB,SAAO,OAAO,KAAK,WAAW,YAAY,KAAK,WAAW;;CAG5D,MAAM,eAAgC;AACpC,MAAI,OAAO,KAAK,gBAAgB,YAC9B,QAAO,KAAK,YAAY;WACf,OAAO,KAAK,eAAe,YACpC,QAAO,KAAK,WAAW,cAAc;MAErC,QAAO,MAAM,cAAc;;;;;;;;;;CAY/B;;;;;;;;;;CAWA;;;;;;;;;;CAWA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgDA,YAAY,SAAwC,EAAE,EAAE;AACtD,SAAO;AADa,OAAA,SAAA;AAGpB,OAAK,SAAS,OAAO,WAAA,GAAA,0BAAA,wBAAiC,iBAAiB;AACvE,OAAK,cAAcC,aAAAA,WAAW;AAC5B,OAAI,OAAO,YACT,QAAOC,iBAAAA,wBAAwB,OAAO,YAAY;GAEpD,MAAM,kBAAA,GAAA,0BAAA,wBAAwC,2BAA2B;AACzE,OAAI,eACF,QAAOA,iBAAAA,wBAAwB,eAAe;IAGhD;AACF,OAAK,aAAaD,aAAAA,WAAW;AAC3B,OAAI,OAAO,kBACT,QAAO,IAAIE,oBAAAA,WAAW,OAAO,kBAAkB;AAEjD,OAAI,CAAC,KAAK,UAAU,CAAC,KAAK,YACxB,QAAO,IAAIA,oBAAAA,YAAY;IAGzB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0CJ,MAAM,MAAM,SAAqC;AAC/C,MAAI,KAAK,OACP,SAAQ,QAAQ,IAAIC,cAAAA,uBAAuB,KAAK,OAAO;WAC9C,KAAK,YACd,SAAQ,QAAQ,IACdC,cAAAA,oBACA,UAAUC,iBAAAA,6BAA6B,KAAK,YAAY,GACzD;WACQ,KAAK,WAEd,EAAA,MAD0B,KAAK,WAAW,kBAAkB,QAAQ,IAAI,EAC5D,SAAS,OAAO,QAAQ;AAClC,OAAI,UAAU,KACZ,SAAQ,QAAQ,IAAI,KAAK,MAAM;IAEjC;AAEJ,SAAO,MAAM,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwEzB,SAAgB,iBACd,aACA,gBACmB;AACnB,KAAI,CAAC,YACH,QAAO,EAAE,QAAQ,gBAAgB;UACxB,CAAC,YAAY,OACtB,QAAO;EAAE,GAAG;EAAa,QAAQ;EAAgB;MAC5C;EACL,MAAM,iBAAiB,MAAM,QAAQ,YAAY,OAAO,GACpD,YAAY,SACZ,CAAC,YAAY,OAAO;AAIxB,MAHsB,eAAe,QAClC,UAAU,CAAC,eAAe,SAAS,MAAM,CAE3B,CAAC,SAAS,EACzB,OAAM,IAAIC,eAAAA,mBACR,4CAA4C,eAAe,KAAK,KAAK,GACtE;;AAGL,QAAO"}
1
+ {"version":3,"file":"node.cjs","names":["ApiClient","iife","normalizeGCPCredentials","GoogleAuth","GOOGLE_API_KEY_HEADER","GCP_API_KEY_HEADER","getGCPCredentialsAccessToken","ConfigurationError"],"sources":["../../src/clients/node.ts"],"sourcesContent":["import { GoogleAuth, type GoogleAuthOptions } from \"google-auth-library\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { GCP_API_KEY_HEADER, GOOGLE_API_KEY_HEADER } from \"../const.js\";\nimport { ApiClient } from \"./index.js\";\nimport {\n GCPCredentials,\n getGCPCredentialsAccessToken,\n normalizeGCPCredentials,\n} from \"../utils/gcp-auth.js\";\nimport { ConfigurationError } from \"../utils/errors.js\";\nimport { iife } from \"../utils/misc.js\";\n\n/**\n * Configuration parameters for the NodeApiClient.\n *\n * This interface defines the authentication options available for Node.js-based\n * API clients. Authentication can be provided via an API key, GCP service\n * account credentials, or advanced Google Auth options. The client will\n * automatically check environment variables if explicit values are not provided.\n *\n * @interface\n */\nexport interface NodeApiClientParams {\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 * Provides fine-grained control over authentication behavior using the\n * google-auth-library. This option enables:\n * - Custom OAuth2 scopes\n * - Application Default Credentials (ADC)\n * - Impersonation and delegation\n * - Custom credential sources\n *\n * When provided, this takes precedence over simple credential-based auth\n * but is lower priority than API key authentication.\n *\n * @see https://github.com/googleapis/google-auth-library-nodejs\n * @see https://cloud.google.com/docs/authentication/application-default-credentials\n */\n googleAuthOptions?: GoogleAuthOptions;\n}\n\n/**\n * Node.js-specific API client for Google services.\n *\n * This client provides comprehensive authentication for Google API requests in\n * Node.js environments, leveraging the full capabilities of the google-auth-library.\n * It supports three authentication methods with the following priority:\n *\n * 1. **API Key Authentication**: Simple key-based authentication suitable for\n * public APIs and development environments.\n *\n * 2. **Service Account Credentials**: OAuth2-based authentication using GCP\n * service account keys. The client automatically handles token generation\n * and caching using a web-compatible implementation.\n *\n * 3. **Google Auth Library**: Advanced authentication using google-auth-library,\n * supporting Application Default Credentials (ADC), custom scopes, and\n * various credential sources.\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 * 5. `googleAuthOptions` parameter\n * 6. Application Default Credentials (if googleAuthOptions is provided without explicit credentials)\n *\n * @extends ApiClient\n *\n * @example\n * ```typescript\n * // Using API key\n * const client = new NodeApiClient({\n * apiKey: 'your-api-key'\n * });\n *\n * // Using service account credentials\n * const client = new NodeApiClient({\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 Google Auth with custom scopes\n * const client = new NodeApiClient({\n * googleAuthOptions: {\n * scopes: ['https://www.googleapis.com/auth/cloud-platform'],\n * keyFilename: '/path/to/service-account-key.json'\n * }\n * });\n *\n * // Using Application Default Credentials\n * const client = new NodeApiClient({\n * googleAuthOptions: {}\n * });\n *\n * // Using environment variables\n * // Set GOOGLE_API_KEY or GOOGLE_CLOUD_CREDENTIALS\n * const client = new NodeApiClient();\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 * - Google Auth headers are automatically generated and added by google-auth-library\n * - Tokens are automatically cached and refreshed as needed\n * - For web/edge environments without google-auth-library, use WebApiClient instead\n *\n * @see {@link WebApiClient} for web-compatible authentication without google-auth-library\n * @see {@link GCPCredentials} for service account credential structure\n * @see {@link GoogleAuthOptions} for advanced authentication configuration\n */\nexport class NodeApiClient 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 if (typeof this.googleAuth !== \"undefined\") {\n return this.googleAuth.getProjectId();\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 * The Google Auth instance for advanced authentication, if configured.\n *\n * This instance is created when `googleAuthOptions` is provided and\n * handles Application Default Credentials, custom scopes, and other\n * advanced authentication scenarios.\n *\n * @protected\n */\n protected googleAuth?: GoogleAuth;\n\n /**\n * Creates a new NodeApiClient 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 * 3. Application Default Credentials (if googleAuthOptions is provided)\n *\n * Credentials are normalized and frozen to prevent accidental modification.\n * The GoogleAuth instance is lazily initialized only when googleAuthOptions\n * is provided.\n *\n * @param params - Configuration parameters for the client. Defaults to an empty object.\n *\n * @example\n * ```typescript\n * // Minimal configuration (uses environment variables or ADC)\n * const client = new NodeApiClient();\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 NodeApiClient({\n * credentials: {\n * type: \"service_account\",\n * // ... other fields\n * }\n * });\n *\n * // With Google Auth options\n * const client = new NodeApiClient({\n * googleAuthOptions: {\n * scopes: ['https://www.googleapis.com/auth/cloud-platform'],\n * projectId: 'my-project'\n * }\n * });\n * ```\n */\n constructor(protected params: NodeApiClientParams = {}) {\n super();\n\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 this.googleAuth = iife(() => {\n if (params.googleAuthOptions) {\n return new GoogleAuth(params.googleAuthOptions);\n }\n if (!this.apiKey && !this.credentials) {\n return new GoogleAuth();\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, following this priority:\n *\n * 1. If an API key is configured, adds the `X-Goog-Api-Key` header\n * 2. If service account credentials are configured, generates an access token\n * and adds it via the `Authorization` header with Bearer scheme\n * 3. If Google Auth is configured, uses google-auth-library to generate\n * appropriate authentication headers (may include Authorization, x-goog-user-project, etc.)\n *\n * The authentication priority ensures that explicit API keys take precedence,\n * followed by service account credentials, and finally Google Auth options.\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 service account authentication fails (e.g., invalid\n * credentials, network error, or token generation failure)\n * @throws {Error} If Google Auth authentication fails (e.g., missing credentials,\n * invalid configuration, or ADC not available)\n *\n * @example\n * ```typescript\n * const client = new NodeApiClient({ 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 * - Google Auth tokens are managed by google-auth-library with automatic refresh\n * - Only one authentication method is used per request (based on priority)\n * - Google Auth may add multiple headers depending on the authentication type\n */\n async fetch(request: Request): Promise<Response> {\n if (this.apiKey) {\n request.headers.set(GOOGLE_API_KEY_HEADER, this.apiKey);\n } else if (this.credentials) {\n request.headers.set(\n GCP_API_KEY_HEADER,\n `Bearer ${getGCPCredentialsAccessToken(this.credentials)}`\n );\n } else if (this.googleAuth) {\n const authHeaders = await this.googleAuth.getRequestHeaders(request.url);\n authHeaders.forEach((value, key) => {\n if (value !== null) {\n request.headers.set(key, value);\n }\n });\n }\n return fetch(request);\n }\n}\n\n/**\n * Ensures that Google Auth options include required OAuth2 scopes.\n *\n * This utility function validates and augments GoogleAuthOptions to ensure\n * that all required OAuth2 scopes are present. It handles three scenarios:\n *\n * 1. **No auth options provided**: Creates new options with required scopes\n * 2. **Auth options without scopes**: Adds required scopes to existing options\n * 3. **Auth options with scopes**: Validates that all required scopes are present\n *\n * This is particularly useful when working with Google APIs that require specific\n * scopes for access, ensuring that authentication is properly configured before\n * making API requests.\n *\n * @param authOptions - The existing Google Auth options to validate/augment.\n * Can be undefined or an empty object.\n * @param requiredScopes - Array of OAuth2 scope URLs that must be present.\n * These are typically Google API scope URLs like\n * 'https://www.googleapis.com/auth/cloud-platform'\n * @returns The validated/augmented GoogleAuthOptions with all required scopes\n *\n * @throws {Error} If authOptions already has scopes but is missing any of the\n * required scopes. This prevents accidental scope reduction that\n * could break API access.\n *\n * @example\n * ```typescript\n * // Create new options with required scopes\n * const options = ensureAuthScopes(undefined, [\n * 'https://www.googleapis.com/auth/cloud-platform'\n * ]);\n * // Result: { scopes: ['https://www.googleapis.com/auth/cloud-platform'] }\n *\n * // Add scopes to existing options\n * const options = ensureAuthScopes(\n * { projectId: 'my-project' },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * // Result: { projectId: 'my-project', scopes: [...] }\n *\n * // Validate existing scopes\n * const options = ensureAuthScopes(\n * { scopes: ['https://www.googleapis.com/auth/cloud-platform'] },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * // Result: Original options (validation passed)\n *\n * // Error case - missing required scope\n * try {\n * ensureAuthScopes(\n * { scopes: ['https://www.googleapis.com/auth/userinfo.email'] },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * } catch (error) {\n * // Error: Invalid auth scopes. Scopes must include ...\n * }\n * ```\n *\n * @remarks\n * - Scopes can be provided as a string or array of strings in GoogleAuthOptions\n * - The function normalizes single-string scopes to arrays for validation\n * - Required scopes are not automatically added if existing scopes are present;\n * instead, an error is thrown to prevent unintended scope changes\n * - This function does not modify the original authOptions object\n *\n * @see https://developers.google.com/identity/protocols/oauth2/scopes\n * @see {@link GoogleAuthOptions} for the full authentication configuration interface\n */\nexport function ensureAuthScopes(\n authOptions: GoogleAuthOptions,\n requiredScopes: string[]\n): GoogleAuthOptions {\n if (!authOptions) {\n return { scopes: requiredScopes };\n } else if (!authOptions.scopes) {\n return { ...authOptions, scopes: requiredScopes };\n } else {\n const existingScopes = Array.isArray(authOptions.scopes)\n ? authOptions.scopes\n : [authOptions.scopes];\n const missingScopes = requiredScopes.filter(\n (scope) => !existingScopes.includes(scope)\n );\n if (missingScopes.length > 0) {\n throw new ConfigurationError(\n `Invalid auth scopes. Scopes must include ${requiredScopes.join(\", \")}`\n );\n }\n }\n return authOptions;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkJA,IAAa,gBAAb,cAAmCA,cAAAA,UAAU;CA6FrB;CA5FtB,YAAqB;EACnB,OAAO,OAAO,KAAK,WAAW,YAAY,KAAK,WAAW;CAC5D;CAEA,MAAM,eAAgC;EACpC,IAAI,OAAO,KAAK,gBAAgB,aAC9B,OAAO,KAAK,YAAY;OACnB,IAAI,OAAO,KAAK,eAAe,aACpC,OAAO,KAAK,WAAW,aAAa;OAEpC,OAAO,MAAM,aAAa;CAE9B;;;;;;;;;CAUA;;;;;;;;;;CAWA;;;;;;;;;;CAWA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgDA,YAAY,SAAwC,CAAC,GAAG;EACtD,MAAM;EADc,KAAA,SAAA;EAGpB,KAAK,SAAS,OAAO,WAAA,GAAA,0BAAA,uBAAA,CAAiC,gBAAgB;EACtE,KAAK,cAAcC,aAAAA,WAAW;GAC5B,IAAI,OAAO,aACT,OAAOC,iBAAAA,wBAAwB,OAAO,WAAW;GAEnD,MAAM,kBAAA,GAAA,0BAAA,uBAAA,CAAwC,0BAA0B;GACxE,IAAI,gBACF,OAAOA,iBAAAA,wBAAwB,cAAc;EAGjD,CAAC;EACD,KAAK,aAAaD,aAAAA,WAAW;GAC3B,IAAI,OAAO,mBACT,OAAO,IAAIE,oBAAAA,WAAW,OAAO,iBAAiB;GAEhD,IAAI,CAAC,KAAK,UAAU,CAAC,KAAK,aACxB,OAAO,IAAIA,oBAAAA,WAAW;EAG1B,CAAC;CACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAyCA,MAAM,MAAM,SAAqC;EAC/C,IAAI,KAAK,QACP,QAAQ,QAAQ,IAAIC,cAAAA,uBAAuB,KAAK,MAAM;OACjD,IAAI,KAAK,aACd,QAAQ,QAAQ,IACdC,cAAAA,oBACA,UAAUC,iBAAAA,6BAA6B,KAAK,WAAW,GACzD;OACK,IAAI,KAAK,YAEd,CAAA,MAD0B,KAAK,WAAW,kBAAkB,QAAQ,GAAG,EAAA,CAC3D,SAAS,OAAO,QAAQ;GAClC,IAAI,UAAU,MACZ,QAAQ,QAAQ,IAAI,KAAK,KAAK;EAElC,CAAC;EAEH,OAAO,MAAM,OAAO;CACtB;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,SAAgB,iBACd,aACA,gBACmB;CACnB,IAAI,CAAC,aACH,OAAO,EAAE,QAAQ,eAAe;MAC3B,IAAI,CAAC,YAAY,QACtB,OAAO;EAAE,GAAG;EAAa,QAAQ;CAAe;MAC3C;EACL,MAAM,iBAAiB,MAAM,QAAQ,YAAY,MAAM,IACnD,YAAY,SACZ,CAAC,YAAY,MAAM;EAIvB,IAHsB,eAAe,QAClC,UAAU,CAAC,eAAe,SAAS,KAAK,CAE3B,CAAC,CAAC,SAAS,GACzB,MAAM,IAAIC,eAAAA,mBACR,4CAA4C,eAAe,KAAK,IAAI,GACtE;CAEJ;CACA,OAAO;AACT"}
@@ -1,6 +1,5 @@
1
1
  import { GCPCredentials } from "../utils/gcp-auth.cjs";
2
2
  import { GoogleAuthOptions } from "google-auth-library";
3
-
4
3
  //#region src/clients/node.d.ts
5
4
  /**
6
5
  * Configuration parameters for the NodeApiClient.
@@ -1,6 +1,5 @@
1
1
  import { GCPCredentials } from "../utils/gcp-auth.js";
2
2
  import { GoogleAuth, GoogleAuthOptions } from "google-auth-library";
3
-
4
3
  //#region src/clients/node.d.ts
5
4
  /**
6
5
  * Configuration parameters for the NodeApiClient.
@@ -87,6 +87,7 @@ import { GoogleAuth } from "google-auth-library";
87
87
  * @see {@link GoogleAuthOptions} for advanced authentication configuration
88
88
  */
89
89
  var NodeApiClient = class extends ApiClient {
90
+ params;
90
91
  hasApiKey() {
91
92
  return typeof this.apiKey === "string" && this.apiKey !== "";
92
93
  }
@@ -1 +1 @@
1
- {"version":3,"file":"node.js","names":[],"sources":["../../src/clients/node.ts"],"sourcesContent":["import { GoogleAuth, type GoogleAuthOptions } from \"google-auth-library\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { GCP_API_KEY_HEADER, GOOGLE_API_KEY_HEADER } from \"../const.js\";\nimport { ApiClient } from \"./index.js\";\nimport {\n GCPCredentials,\n getGCPCredentialsAccessToken,\n normalizeGCPCredentials,\n} from \"../utils/gcp-auth.js\";\nimport { ConfigurationError } from \"../utils/errors.js\";\nimport { iife } from \"../utils/misc.js\";\n\n/**\n * Configuration parameters for the NodeApiClient.\n *\n * This interface defines the authentication options available for Node.js-based\n * API clients. Authentication can be provided via an API key, GCP service\n * account credentials, or advanced Google Auth options. The client will\n * automatically check environment variables if explicit values are not provided.\n *\n * @interface\n */\nexport interface NodeApiClientParams {\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 * Provides fine-grained control over authentication behavior using the\n * google-auth-library. This option enables:\n * - Custom OAuth2 scopes\n * - Application Default Credentials (ADC)\n * - Impersonation and delegation\n * - Custom credential sources\n *\n * When provided, this takes precedence over simple credential-based auth\n * but is lower priority than API key authentication.\n *\n * @see https://github.com/googleapis/google-auth-library-nodejs\n * @see https://cloud.google.com/docs/authentication/application-default-credentials\n */\n googleAuthOptions?: GoogleAuthOptions;\n}\n\n/**\n * Node.js-specific API client for Google services.\n *\n * This client provides comprehensive authentication for Google API requests in\n * Node.js environments, leveraging the full capabilities of the google-auth-library.\n * It supports three authentication methods with the following priority:\n *\n * 1. **API Key Authentication**: Simple key-based authentication suitable for\n * public APIs and development environments.\n *\n * 2. **Service Account Credentials**: OAuth2-based authentication using GCP\n * service account keys. The client automatically handles token generation\n * and caching using a web-compatible implementation.\n *\n * 3. **Google Auth Library**: Advanced authentication using google-auth-library,\n * supporting Application Default Credentials (ADC), custom scopes, and\n * various credential sources.\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 * 5. `googleAuthOptions` parameter\n * 6. Application Default Credentials (if googleAuthOptions is provided without explicit credentials)\n *\n * @extends ApiClient\n *\n * @example\n * ```typescript\n * // Using API key\n * const client = new NodeApiClient({\n * apiKey: 'your-api-key'\n * });\n *\n * // Using service account credentials\n * const client = new NodeApiClient({\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 Google Auth with custom scopes\n * const client = new NodeApiClient({\n * googleAuthOptions: {\n * scopes: ['https://www.googleapis.com/auth/cloud-platform'],\n * keyFilename: '/path/to/service-account-key.json'\n * }\n * });\n *\n * // Using Application Default Credentials\n * const client = new NodeApiClient({\n * googleAuthOptions: {}\n * });\n *\n * // Using environment variables\n * // Set GOOGLE_API_KEY or GOOGLE_CLOUD_CREDENTIALS\n * const client = new NodeApiClient();\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 * - Google Auth headers are automatically generated and added by google-auth-library\n * - Tokens are automatically cached and refreshed as needed\n * - For web/edge environments without google-auth-library, use WebApiClient instead\n *\n * @see {@link WebApiClient} for web-compatible authentication without google-auth-library\n * @see {@link GCPCredentials} for service account credential structure\n * @see {@link GoogleAuthOptions} for advanced authentication configuration\n */\nexport class NodeApiClient 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 if (typeof this.googleAuth !== \"undefined\") {\n return this.googleAuth.getProjectId();\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 * The Google Auth instance for advanced authentication, if configured.\n *\n * This instance is created when `googleAuthOptions` is provided and\n * handles Application Default Credentials, custom scopes, and other\n * advanced authentication scenarios.\n *\n * @protected\n */\n protected googleAuth?: GoogleAuth;\n\n /**\n * Creates a new NodeApiClient 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 * 3. Application Default Credentials (if googleAuthOptions is provided)\n *\n * Credentials are normalized and frozen to prevent accidental modification.\n * The GoogleAuth instance is lazily initialized only when googleAuthOptions\n * is provided.\n *\n * @param params - Configuration parameters for the client. Defaults to an empty object.\n *\n * @example\n * ```typescript\n * // Minimal configuration (uses environment variables or ADC)\n * const client = new NodeApiClient();\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 NodeApiClient({\n * credentials: {\n * type: \"service_account\",\n * // ... other fields\n * }\n * });\n *\n * // With Google Auth options\n * const client = new NodeApiClient({\n * googleAuthOptions: {\n * scopes: ['https://www.googleapis.com/auth/cloud-platform'],\n * projectId: 'my-project'\n * }\n * });\n * ```\n */\n constructor(protected params: NodeApiClientParams = {}) {\n super();\n\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 this.googleAuth = iife(() => {\n if (params.googleAuthOptions) {\n return new GoogleAuth(params.googleAuthOptions);\n }\n if (!this.apiKey && !this.credentials) {\n return new GoogleAuth();\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, following this priority:\n *\n * 1. If an API key is configured, adds the `X-Goog-Api-Key` header\n * 2. If service account credentials are configured, generates an access token\n * and adds it via the `Authorization` header with Bearer scheme\n * 3. If Google Auth is configured, uses google-auth-library to generate\n * appropriate authentication headers (may include Authorization, x-goog-user-project, etc.)\n *\n * The authentication priority ensures that explicit API keys take precedence,\n * followed by service account credentials, and finally Google Auth options.\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 service account authentication fails (e.g., invalid\n * credentials, network error, or token generation failure)\n * @throws {Error} If Google Auth authentication fails (e.g., missing credentials,\n * invalid configuration, or ADC not available)\n *\n * @example\n * ```typescript\n * const client = new NodeApiClient({ 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 * - Google Auth tokens are managed by google-auth-library with automatic refresh\n * - Only one authentication method is used per request (based on priority)\n * - Google Auth may add multiple headers depending on the authentication type\n */\n async fetch(request: Request): Promise<Response> {\n if (this.apiKey) {\n request.headers.set(GOOGLE_API_KEY_HEADER, this.apiKey);\n } else if (this.credentials) {\n request.headers.set(\n GCP_API_KEY_HEADER,\n `Bearer ${getGCPCredentialsAccessToken(this.credentials)}`\n );\n } else if (this.googleAuth) {\n const authHeaders = await this.googleAuth.getRequestHeaders(request.url);\n authHeaders.forEach((value, key) => {\n if (value !== null) {\n request.headers.set(key, value);\n }\n });\n }\n return fetch(request);\n }\n}\n\n/**\n * Ensures that Google Auth options include required OAuth2 scopes.\n *\n * This utility function validates and augments GoogleAuthOptions to ensure\n * that all required OAuth2 scopes are present. It handles three scenarios:\n *\n * 1. **No auth options provided**: Creates new options with required scopes\n * 2. **Auth options without scopes**: Adds required scopes to existing options\n * 3. **Auth options with scopes**: Validates that all required scopes are present\n *\n * This is particularly useful when working with Google APIs that require specific\n * scopes for access, ensuring that authentication is properly configured before\n * making API requests.\n *\n * @param authOptions - The existing Google Auth options to validate/augment.\n * Can be undefined or an empty object.\n * @param requiredScopes - Array of OAuth2 scope URLs that must be present.\n * These are typically Google API scope URLs like\n * 'https://www.googleapis.com/auth/cloud-platform'\n * @returns The validated/augmented GoogleAuthOptions with all required scopes\n *\n * @throws {Error} If authOptions already has scopes but is missing any of the\n * required scopes. This prevents accidental scope reduction that\n * could break API access.\n *\n * @example\n * ```typescript\n * // Create new options with required scopes\n * const options = ensureAuthScopes(undefined, [\n * 'https://www.googleapis.com/auth/cloud-platform'\n * ]);\n * // Result: { scopes: ['https://www.googleapis.com/auth/cloud-platform'] }\n *\n * // Add scopes to existing options\n * const options = ensureAuthScopes(\n * { projectId: 'my-project' },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * // Result: { projectId: 'my-project', scopes: [...] }\n *\n * // Validate existing scopes\n * const options = ensureAuthScopes(\n * { scopes: ['https://www.googleapis.com/auth/cloud-platform'] },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * // Result: Original options (validation passed)\n *\n * // Error case - missing required scope\n * try {\n * ensureAuthScopes(\n * { scopes: ['https://www.googleapis.com/auth/userinfo.email'] },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * } catch (error) {\n * // Error: Invalid auth scopes. Scopes must include ...\n * }\n * ```\n *\n * @remarks\n * - Scopes can be provided as a string or array of strings in GoogleAuthOptions\n * - The function normalizes single-string scopes to arrays for validation\n * - Required scopes are not automatically added if existing scopes are present;\n * instead, an error is thrown to prevent unintended scope changes\n * - This function does not modify the original authOptions object\n *\n * @see https://developers.google.com/identity/protocols/oauth2/scopes\n * @see {@link GoogleAuthOptions} for the full authentication configuration interface\n */\nexport function ensureAuthScopes(\n authOptions: GoogleAuthOptions,\n requiredScopes: string[]\n): GoogleAuthOptions {\n if (!authOptions) {\n return { scopes: requiredScopes };\n } else if (!authOptions.scopes) {\n return { ...authOptions, scopes: requiredScopes };\n } else {\n const existingScopes = Array.isArray(authOptions.scopes)\n ? authOptions.scopes\n : [authOptions.scopes];\n const missingScopes = requiredScopes.filter(\n (scope) => !existingScopes.includes(scope)\n );\n if (missingScopes.length > 0) {\n throw new ConfigurationError(\n `Invalid auth scopes. Scopes must include ${requiredScopes.join(\", \")}`\n );\n }\n }\n return authOptions;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkJA,IAAa,gBAAb,cAAmC,UAAU;CAC3C,YAAqB;AACnB,SAAO,OAAO,KAAK,WAAW,YAAY,KAAK,WAAW;;CAG5D,MAAM,eAAgC;AACpC,MAAI,OAAO,KAAK,gBAAgB,YAC9B,QAAO,KAAK,YAAY;WACf,OAAO,KAAK,eAAe,YACpC,QAAO,KAAK,WAAW,cAAc;MAErC,QAAO,MAAM,cAAc;;;;;;;;;;CAY/B;;;;;;;;;;CAWA;;;;;;;;;;CAWA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgDA,YAAY,SAAwC,EAAE,EAAE;AACtD,SAAO;AADa,OAAA,SAAA;AAGpB,OAAK,SAAS,OAAO,UAAU,uBAAuB,iBAAiB;AACvE,OAAK,cAAc,WAAW;AAC5B,OAAI,OAAO,YACT,QAAO,wBAAwB,OAAO,YAAY;GAEpD,MAAM,iBAAiB,uBAAuB,2BAA2B;AACzE,OAAI,eACF,QAAO,wBAAwB,eAAe;IAGhD;AACF,OAAK,aAAa,WAAW;AAC3B,OAAI,OAAO,kBACT,QAAO,IAAI,WAAW,OAAO,kBAAkB;AAEjD,OAAI,CAAC,KAAK,UAAU,CAAC,KAAK,YACxB,QAAO,IAAI,YAAY;IAGzB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0CJ,MAAM,MAAM,SAAqC;AAC/C,MAAI,KAAK,OACP,SAAQ,QAAQ,IAAI,uBAAuB,KAAK,OAAO;WAC9C,KAAK,YACd,SAAQ,QAAQ,IACd,oBACA,UAAU,6BAA6B,KAAK,YAAY,GACzD;WACQ,KAAK,WAEd,EAAA,MAD0B,KAAK,WAAW,kBAAkB,QAAQ,IAAI,EAC5D,SAAS,OAAO,QAAQ;AAClC,OAAI,UAAU,KACZ,SAAQ,QAAQ,IAAI,KAAK,MAAM;IAEjC;AAEJ,SAAO,MAAM,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwEzB,SAAgB,iBACd,aACA,gBACmB;AACnB,KAAI,CAAC,YACH,QAAO,EAAE,QAAQ,gBAAgB;UACxB,CAAC,YAAY,OACtB,QAAO;EAAE,GAAG;EAAa,QAAQ;EAAgB;MAC5C;EACL,MAAM,iBAAiB,MAAM,QAAQ,YAAY,OAAO,GACpD,YAAY,SACZ,CAAC,YAAY,OAAO;AAIxB,MAHsB,eAAe,QAClC,UAAU,CAAC,eAAe,SAAS,MAAM,CAE3B,CAAC,SAAS,EACzB,OAAM,IAAI,mBACR,4CAA4C,eAAe,KAAK,KAAK,GACtE;;AAGL,QAAO"}
1
+ {"version":3,"file":"node.js","names":[],"sources":["../../src/clients/node.ts"],"sourcesContent":["import { GoogleAuth, type GoogleAuthOptions } from \"google-auth-library\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { GCP_API_KEY_HEADER, GOOGLE_API_KEY_HEADER } from \"../const.js\";\nimport { ApiClient } from \"./index.js\";\nimport {\n GCPCredentials,\n getGCPCredentialsAccessToken,\n normalizeGCPCredentials,\n} from \"../utils/gcp-auth.js\";\nimport { ConfigurationError } from \"../utils/errors.js\";\nimport { iife } from \"../utils/misc.js\";\n\n/**\n * Configuration parameters for the NodeApiClient.\n *\n * This interface defines the authentication options available for Node.js-based\n * API clients. Authentication can be provided via an API key, GCP service\n * account credentials, or advanced Google Auth options. The client will\n * automatically check environment variables if explicit values are not provided.\n *\n * @interface\n */\nexport interface NodeApiClientParams {\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 * Provides fine-grained control over authentication behavior using the\n * google-auth-library. This option enables:\n * - Custom OAuth2 scopes\n * - Application Default Credentials (ADC)\n * - Impersonation and delegation\n * - Custom credential sources\n *\n * When provided, this takes precedence over simple credential-based auth\n * but is lower priority than API key authentication.\n *\n * @see https://github.com/googleapis/google-auth-library-nodejs\n * @see https://cloud.google.com/docs/authentication/application-default-credentials\n */\n googleAuthOptions?: GoogleAuthOptions;\n}\n\n/**\n * Node.js-specific API client for Google services.\n *\n * This client provides comprehensive authentication for Google API requests in\n * Node.js environments, leveraging the full capabilities of the google-auth-library.\n * It supports three authentication methods with the following priority:\n *\n * 1. **API Key Authentication**: Simple key-based authentication suitable for\n * public APIs and development environments.\n *\n * 2. **Service Account Credentials**: OAuth2-based authentication using GCP\n * service account keys. The client automatically handles token generation\n * and caching using a web-compatible implementation.\n *\n * 3. **Google Auth Library**: Advanced authentication using google-auth-library,\n * supporting Application Default Credentials (ADC), custom scopes, and\n * various credential sources.\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 * 5. `googleAuthOptions` parameter\n * 6. Application Default Credentials (if googleAuthOptions is provided without explicit credentials)\n *\n * @extends ApiClient\n *\n * @example\n * ```typescript\n * // Using API key\n * const client = new NodeApiClient({\n * apiKey: 'your-api-key'\n * });\n *\n * // Using service account credentials\n * const client = new NodeApiClient({\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 Google Auth with custom scopes\n * const client = new NodeApiClient({\n * googleAuthOptions: {\n * scopes: ['https://www.googleapis.com/auth/cloud-platform'],\n * keyFilename: '/path/to/service-account-key.json'\n * }\n * });\n *\n * // Using Application Default Credentials\n * const client = new NodeApiClient({\n * googleAuthOptions: {}\n * });\n *\n * // Using environment variables\n * // Set GOOGLE_API_KEY or GOOGLE_CLOUD_CREDENTIALS\n * const client = new NodeApiClient();\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 * - Google Auth headers are automatically generated and added by google-auth-library\n * - Tokens are automatically cached and refreshed as needed\n * - For web/edge environments without google-auth-library, use WebApiClient instead\n *\n * @see {@link WebApiClient} for web-compatible authentication without google-auth-library\n * @see {@link GCPCredentials} for service account credential structure\n * @see {@link GoogleAuthOptions} for advanced authentication configuration\n */\nexport class NodeApiClient 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 if (typeof this.googleAuth !== \"undefined\") {\n return this.googleAuth.getProjectId();\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 * The Google Auth instance for advanced authentication, if configured.\n *\n * This instance is created when `googleAuthOptions` is provided and\n * handles Application Default Credentials, custom scopes, and other\n * advanced authentication scenarios.\n *\n * @protected\n */\n protected googleAuth?: GoogleAuth;\n\n /**\n * Creates a new NodeApiClient 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 * 3. Application Default Credentials (if googleAuthOptions is provided)\n *\n * Credentials are normalized and frozen to prevent accidental modification.\n * The GoogleAuth instance is lazily initialized only when googleAuthOptions\n * is provided.\n *\n * @param params - Configuration parameters for the client. Defaults to an empty object.\n *\n * @example\n * ```typescript\n * // Minimal configuration (uses environment variables or ADC)\n * const client = new NodeApiClient();\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 NodeApiClient({\n * credentials: {\n * type: \"service_account\",\n * // ... other fields\n * }\n * });\n *\n * // With Google Auth options\n * const client = new NodeApiClient({\n * googleAuthOptions: {\n * scopes: ['https://www.googleapis.com/auth/cloud-platform'],\n * projectId: 'my-project'\n * }\n * });\n * ```\n */\n constructor(protected params: NodeApiClientParams = {}) {\n super();\n\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 this.googleAuth = iife(() => {\n if (params.googleAuthOptions) {\n return new GoogleAuth(params.googleAuthOptions);\n }\n if (!this.apiKey && !this.credentials) {\n return new GoogleAuth();\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, following this priority:\n *\n * 1. If an API key is configured, adds the `X-Goog-Api-Key` header\n * 2. If service account credentials are configured, generates an access token\n * and adds it via the `Authorization` header with Bearer scheme\n * 3. If Google Auth is configured, uses google-auth-library to generate\n * appropriate authentication headers (may include Authorization, x-goog-user-project, etc.)\n *\n * The authentication priority ensures that explicit API keys take precedence,\n * followed by service account credentials, and finally Google Auth options.\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 service account authentication fails (e.g., invalid\n * credentials, network error, or token generation failure)\n * @throws {Error} If Google Auth authentication fails (e.g., missing credentials,\n * invalid configuration, or ADC not available)\n *\n * @example\n * ```typescript\n * const client = new NodeApiClient({ 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 * - Google Auth tokens are managed by google-auth-library with automatic refresh\n * - Only one authentication method is used per request (based on priority)\n * - Google Auth may add multiple headers depending on the authentication type\n */\n async fetch(request: Request): Promise<Response> {\n if (this.apiKey) {\n request.headers.set(GOOGLE_API_KEY_HEADER, this.apiKey);\n } else if (this.credentials) {\n request.headers.set(\n GCP_API_KEY_HEADER,\n `Bearer ${getGCPCredentialsAccessToken(this.credentials)}`\n );\n } else if (this.googleAuth) {\n const authHeaders = await this.googleAuth.getRequestHeaders(request.url);\n authHeaders.forEach((value, key) => {\n if (value !== null) {\n request.headers.set(key, value);\n }\n });\n }\n return fetch(request);\n }\n}\n\n/**\n * Ensures that Google Auth options include required OAuth2 scopes.\n *\n * This utility function validates and augments GoogleAuthOptions to ensure\n * that all required OAuth2 scopes are present. It handles three scenarios:\n *\n * 1. **No auth options provided**: Creates new options with required scopes\n * 2. **Auth options without scopes**: Adds required scopes to existing options\n * 3. **Auth options with scopes**: Validates that all required scopes are present\n *\n * This is particularly useful when working with Google APIs that require specific\n * scopes for access, ensuring that authentication is properly configured before\n * making API requests.\n *\n * @param authOptions - The existing Google Auth options to validate/augment.\n * Can be undefined or an empty object.\n * @param requiredScopes - Array of OAuth2 scope URLs that must be present.\n * These are typically Google API scope URLs like\n * 'https://www.googleapis.com/auth/cloud-platform'\n * @returns The validated/augmented GoogleAuthOptions with all required scopes\n *\n * @throws {Error} If authOptions already has scopes but is missing any of the\n * required scopes. This prevents accidental scope reduction that\n * could break API access.\n *\n * @example\n * ```typescript\n * // Create new options with required scopes\n * const options = ensureAuthScopes(undefined, [\n * 'https://www.googleapis.com/auth/cloud-platform'\n * ]);\n * // Result: { scopes: ['https://www.googleapis.com/auth/cloud-platform'] }\n *\n * // Add scopes to existing options\n * const options = ensureAuthScopes(\n * { projectId: 'my-project' },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * // Result: { projectId: 'my-project', scopes: [...] }\n *\n * // Validate existing scopes\n * const options = ensureAuthScopes(\n * { scopes: ['https://www.googleapis.com/auth/cloud-platform'] },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * // Result: Original options (validation passed)\n *\n * // Error case - missing required scope\n * try {\n * ensureAuthScopes(\n * { scopes: ['https://www.googleapis.com/auth/userinfo.email'] },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * } catch (error) {\n * // Error: Invalid auth scopes. Scopes must include ...\n * }\n * ```\n *\n * @remarks\n * - Scopes can be provided as a string or array of strings in GoogleAuthOptions\n * - The function normalizes single-string scopes to arrays for validation\n * - Required scopes are not automatically added if existing scopes are present;\n * instead, an error is thrown to prevent unintended scope changes\n * - This function does not modify the original authOptions object\n *\n * @see https://developers.google.com/identity/protocols/oauth2/scopes\n * @see {@link GoogleAuthOptions} for the full authentication configuration interface\n */\nexport function ensureAuthScopes(\n authOptions: GoogleAuthOptions,\n requiredScopes: string[]\n): GoogleAuthOptions {\n if (!authOptions) {\n return { scopes: requiredScopes };\n } else if (!authOptions.scopes) {\n return { ...authOptions, scopes: requiredScopes };\n } else {\n const existingScopes = Array.isArray(authOptions.scopes)\n ? authOptions.scopes\n : [authOptions.scopes];\n const missingScopes = requiredScopes.filter(\n (scope) => !existingScopes.includes(scope)\n );\n if (missingScopes.length > 0) {\n throw new ConfigurationError(\n `Invalid auth scopes. Scopes must include ${requiredScopes.join(\", \")}`\n );\n }\n }\n return authOptions;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkJA,IAAa,gBAAb,cAAmC,UAAU;CA6FrB;CA5FtB,YAAqB;EACnB,OAAO,OAAO,KAAK,WAAW,YAAY,KAAK,WAAW;CAC5D;CAEA,MAAM,eAAgC;EACpC,IAAI,OAAO,KAAK,gBAAgB,aAC9B,OAAO,KAAK,YAAY;OACnB,IAAI,OAAO,KAAK,eAAe,aACpC,OAAO,KAAK,WAAW,aAAa;OAEpC,OAAO,MAAM,aAAa;CAE9B;;;;;;;;;CAUA;;;;;;;;;;CAWA;;;;;;;;;;CAWA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgDA,YAAY,SAAwC,CAAC,GAAG;EACtD,MAAM;EADc,KAAA,SAAA;EAGpB,KAAK,SAAS,OAAO,UAAU,uBAAuB,gBAAgB;EACtE,KAAK,cAAc,WAAW;GAC5B,IAAI,OAAO,aACT,OAAO,wBAAwB,OAAO,WAAW;GAEnD,MAAM,iBAAiB,uBAAuB,0BAA0B;GACxE,IAAI,gBACF,OAAO,wBAAwB,cAAc;EAGjD,CAAC;EACD,KAAK,aAAa,WAAW;GAC3B,IAAI,OAAO,mBACT,OAAO,IAAI,WAAW,OAAO,iBAAiB;GAEhD,IAAI,CAAC,KAAK,UAAU,CAAC,KAAK,aACxB,OAAO,IAAI,WAAW;EAG1B,CAAC;CACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAyCA,MAAM,MAAM,SAAqC;EAC/C,IAAI,KAAK,QACP,QAAQ,QAAQ,IAAI,uBAAuB,KAAK,MAAM;OACjD,IAAI,KAAK,aACd,QAAQ,QAAQ,IACd,oBACA,UAAU,6BAA6B,KAAK,WAAW,GACzD;OACK,IAAI,KAAK,YAEd,CAAA,MAD0B,KAAK,WAAW,kBAAkB,QAAQ,GAAG,EAAA,CAC3D,SAAS,OAAO,QAAQ;GAClC,IAAI,UAAU,MACZ,QAAQ,QAAQ,IAAI,KAAK,KAAK;EAElC,CAAC;EAEH,OAAO,MAAM,OAAO;CACtB;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,SAAgB,iBACd,aACA,gBACmB;CACnB,IAAI,CAAC,aACH,OAAO,EAAE,QAAQ,eAAe;MAC3B,IAAI,CAAC,YAAY,QACtB,OAAO;EAAE,GAAG;EAAa,QAAQ;CAAe;MAC3C;EACL,MAAM,iBAAiB,MAAM,QAAQ,YAAY,MAAM,IACnD,YAAY,SACZ,CAAC,YAAY,MAAM;EAIvB,IAHsB,eAAe,QAClC,UAAU,CAAC,eAAe,SAAS,KAAK,CAE3B,CAAC,CAAC,SAAS,GACzB,MAAM,IAAI,mBACR,4CAA4C,eAAe,KAAK,IAAI,GACtE;CAEJ;CACA,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"const.cjs","names":[],"sources":["../src/const.ts"],"sourcesContent":["export const GOOGLE_API_KEY_HEADER = \"x-goog-api-key\";\n\nexport const GCP_API_KEY_HEADER = \"Authorization\";\n\nexport const GENERATIVE_AI_AUTH_SCOPES = [\n \"https://www.googleapis.com/auth/generative-language\",\n];\n\nexport const VERTEX_AI_AUTH_SCOPES = [\n \"https://www.googleapis.com/auth/cloud-platform\",\n];\n"],"mappings":";AAAA,MAAa,wBAAwB;AAErC,MAAa,qBAAqB;AAElC,MAAa,4BAA4B,CACvC,sDACD;AAED,MAAa,wBAAwB,CACnC,iDACD"}
1
+ {"version":3,"file":"const.cjs","names":[],"sources":["../src/const.ts"],"sourcesContent":["export const GOOGLE_API_KEY_HEADER = \"x-goog-api-key\";\n\nexport const GCP_API_KEY_HEADER = \"Authorization\";\n\nexport const GENERATIVE_AI_AUTH_SCOPES = [\n \"https://www.googleapis.com/auth/generative-language\",\n];\n\nexport const VERTEX_AI_AUTH_SCOPES = [\n \"https://www.googleapis.com/auth/cloud-platform\",\n];\n"],"mappings":";AAAA,MAAa,wBAAwB;AAErC,MAAa,qBAAqB;AAElC,MAAa,4BAA4B,CACvC,qDACF;AAEA,MAAa,wBAAwB,CACnC,gDACF"}
package/dist/const.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"const.js","names":[],"sources":["../src/const.ts"],"sourcesContent":["export const GOOGLE_API_KEY_HEADER = \"x-goog-api-key\";\n\nexport const GCP_API_KEY_HEADER = \"Authorization\";\n\nexport const GENERATIVE_AI_AUTH_SCOPES = [\n \"https://www.googleapis.com/auth/generative-language\",\n];\n\nexport const VERTEX_AI_AUTH_SCOPES = [\n \"https://www.googleapis.com/auth/cloud-platform\",\n];\n"],"mappings":";AAAA,MAAa,wBAAwB;AAErC,MAAa,qBAAqB;AAElC,MAAa,4BAA4B,CACvC,sDACD;AAED,MAAa,wBAAwB,CACnC,iDACD"}
1
+ {"version":3,"file":"const.js","names":[],"sources":["../src/const.ts"],"sourcesContent":["export const GOOGLE_API_KEY_HEADER = \"x-goog-api-key\";\n\nexport const GCP_API_KEY_HEADER = \"Authorization\";\n\nexport const GENERATIVE_AI_AUTH_SCOPES = [\n \"https://www.googleapis.com/auth/generative-language\",\n];\n\nexport const VERTEX_AI_AUTH_SCOPES = [\n \"https://www.googleapis.com/auth/cloud-platform\",\n];\n"],"mappings":";AAAA,MAAa,wBAAwB;AAErC,MAAa,qBAAqB;AAElC,MAAa,4BAA4B,CACvC,qDACF;AAEA,MAAa,wBAAwB,CACnC,gDACF"}
@@ -697,8 +697,10 @@ const convertGeminiGenerateContentResponseToUsageMetadata = (data) => {
697
697
  exports.convertAIMessageToText = convertAIMessageToText;
698
698
  exports.convertGeminiCandidateToAIMessage = convertGeminiCandidateToAIMessage;
699
699
  exports.convertGeminiGenerateContentResponseToUsageMetadata = convertGeminiGenerateContentResponseToUsageMetadata;
700
+ exports.convertGeminiPartToContentBlock = convertGeminiPartToContentBlock;
700
701
  exports.convertGeminiPartsToToolCalls = convertGeminiPartsToToolCalls;
701
702
  exports.convertMessagesToGeminiContents = convertMessagesToGeminiContents;
702
703
  exports.convertMessagesToGeminiSystemInstruction = convertMessagesToGeminiSystemInstruction;
704
+ exports.geminiContentBlockConverter = geminiContentBlockConverter;
703
705
 
704
706
  //# sourceMappingURL=messages.cjs.map