@langchain/google 0.1.0

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 (93) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/LICENSE +21 -0
  3. package/README.md +97 -0
  4. package/dist/_virtual/rolldown_runtime.cjs +25 -0
  5. package/dist/chat_models/api-types.d.cts +1506 -0
  6. package/dist/chat_models/api-types.d.ts +1506 -0
  7. package/dist/chat_models/base.cjs +445 -0
  8. package/dist/chat_models/base.cjs.map +1 -0
  9. package/dist/chat_models/base.d.cts +319 -0
  10. package/dist/chat_models/base.d.ts +319 -0
  11. package/dist/chat_models/base.js +442 -0
  12. package/dist/chat_models/base.js.map +1 -0
  13. package/dist/chat_models/index.cjs +23 -0
  14. package/dist/chat_models/index.cjs.map +1 -0
  15. package/dist/chat_models/index.d.cts +39 -0
  16. package/dist/chat_models/index.d.ts +39 -0
  17. package/dist/chat_models/index.js +22 -0
  18. package/dist/chat_models/index.js.map +1 -0
  19. package/dist/chat_models/node.cjs +35 -0
  20. package/dist/chat_models/node.cjs.map +1 -0
  21. package/dist/chat_models/node.d.cts +13 -0
  22. package/dist/chat_models/node.d.ts +13 -0
  23. package/dist/chat_models/node.js +34 -0
  24. package/dist/chat_models/node.js.map +1 -0
  25. package/dist/chat_models/profiles.cjs +373 -0
  26. package/dist/chat_models/profiles.cjs.map +1 -0
  27. package/dist/chat_models/profiles.js +372 -0
  28. package/dist/chat_models/profiles.js.map +1 -0
  29. package/dist/chat_models/types.d.cts +250 -0
  30. package/dist/chat_models/types.d.ts +250 -0
  31. package/dist/clients/index.cjs +219 -0
  32. package/dist/clients/index.cjs.map +1 -0
  33. package/dist/clients/index.d.cts +49 -0
  34. package/dist/clients/index.d.ts +49 -0
  35. package/dist/clients/index.js +217 -0
  36. package/dist/clients/index.js.map +1 -0
  37. package/dist/clients/node.cjs +327 -0
  38. package/dist/clients/node.cjs.map +1 -0
  39. package/dist/clients/node.d.cts +59 -0
  40. package/dist/clients/node.d.ts +59 -0
  41. package/dist/clients/node.js +325 -0
  42. package/dist/clients/node.js.map +1 -0
  43. package/dist/const.cjs +13 -0
  44. package/dist/const.cjs.map +1 -0
  45. package/dist/const.js +9 -0
  46. package/dist/const.js.map +1 -0
  47. package/dist/converters/messages.cjs +697 -0
  48. package/dist/converters/messages.cjs.map +1 -0
  49. package/dist/converters/messages.js +691 -0
  50. package/dist/converters/messages.js.map +1 -0
  51. package/dist/converters/params.cjs +205 -0
  52. package/dist/converters/params.cjs.map +1 -0
  53. package/dist/converters/params.js +202 -0
  54. package/dist/converters/params.js.map +1 -0
  55. package/dist/converters/tools.cjs +356 -0
  56. package/dist/converters/tools.cjs.map +1 -0
  57. package/dist/converters/tools.js +353 -0
  58. package/dist/converters/tools.js.map +1 -0
  59. package/dist/index.cjs +7 -0
  60. package/dist/index.d.cts +3 -0
  61. package/dist/index.d.ts +3 -0
  62. package/dist/index.js +4 -0
  63. package/dist/node.cjs +7 -0
  64. package/dist/node.d.cts +3 -0
  65. package/dist/node.d.ts +3 -0
  66. package/dist/node.js +4 -0
  67. package/dist/utils/errors.cjs +543 -0
  68. package/dist/utils/errors.cjs.map +1 -0
  69. package/dist/utils/errors.js +535 -0
  70. package/dist/utils/errors.js.map +1 -0
  71. package/dist/utils/gcp-auth.cjs +188 -0
  72. package/dist/utils/gcp-auth.cjs.map +1 -0
  73. package/dist/utils/gcp-auth.d.cts +43 -0
  74. package/dist/utils/gcp-auth.d.ts +43 -0
  75. package/dist/utils/gcp-auth.js +186 -0
  76. package/dist/utils/gcp-auth.js.map +1 -0
  77. package/dist/utils/handler.cjs +67 -0
  78. package/dist/utils/handler.cjs.map +1 -0
  79. package/dist/utils/handler.d.cts +34 -0
  80. package/dist/utils/handler.d.ts +34 -0
  81. package/dist/utils/handler.js +64 -0
  82. package/dist/utils/handler.js.map +1 -0
  83. package/dist/utils/misc.cjs +10 -0
  84. package/dist/utils/misc.cjs.map +1 -0
  85. package/dist/utils/misc.d.cts +14 -0
  86. package/dist/utils/misc.d.ts +14 -0
  87. package/dist/utils/misc.js +9 -0
  88. package/dist/utils/misc.js.map +1 -0
  89. package/dist/utils/stream.cjs +26 -0
  90. package/dist/utils/stream.cjs.map +1 -0
  91. package/dist/utils/stream.js +25 -0
  92. package/dist/utils/stream.js.map +1 -0
  93. package/package.json +96 -0
@@ -0,0 +1,217 @@
1
+ import { GCP_API_KEY_HEADER, GOOGLE_API_KEY_HEADER } from "../const.js";
2
+ import { iife } from "../utils/misc.js";
3
+ import { AuthError } from "../utils/errors.js";
4
+ import { getGCPCredentialsAccessToken, normalizeGCPCredentials } from "../utils/gcp-auth.js";
5
+ import { getEnvironmentVariable } from "@langchain/core/utils/env";
6
+
7
+ //#region src/clients/index.ts
8
+ /**
9
+ * Abstract base class for API clients that interact with Google services.
10
+ *
11
+ * This class defines the contract for API clients, requiring implementations
12
+ * to provide a fetch method that handles HTTP requests with appropriate
13
+ * authentication headers. Concrete implementations should handle different
14
+ * authentication strategies (API keys, service account credentials, etc.)
15
+ * based on the runtime environment.
16
+ *
17
+ * @abstract
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * class MyApiClient extends ApiClient {
22
+ * async fetch(request: Request): Promise<Response> {
23
+ * // Add authentication headers
24
+ * request.headers.set('Authorization', 'Bearer token');
25
+ * return fetch(request);
26
+ * }
27
+ * }
28
+ * ```
29
+ */
30
+ var ApiClient = class {
31
+ /**
32
+ * For some credential methods, we know what the project ID is.
33
+ * This is necessary for OAuth-based access to Vertex
34
+ */
35
+ async getProjectId() {
36
+ return "unknown-project-id";
37
+ }
38
+ };
39
+ /**
40
+ * Web-compatible API client for Google services.
41
+ *
42
+ * This client provides authentication for Google API requests in web environments
43
+ * (browsers, edge functions, etc.) where the google-auth-library is not available.
44
+ * It supports two authentication methods:
45
+ *
46
+ * 1. **API Key Authentication**: Simple key-based authentication suitable for
47
+ * public APIs and client-side applications.
48
+ *
49
+ * 2. **Service Account Credentials**: OAuth2-based authentication using GCP
50
+ * service account keys. The client automatically handles token generation
51
+ * and caching.
52
+ *
53
+ * The client follows this authentication priority:
54
+ * 1. Explicit `apiKey` parameter
55
+ * 2. `GOOGLE_API_KEY` environment variable
56
+ * 3. Explicit `credentials` parameter
57
+ * 4. `GOOGLE_CLOUD_CREDENTIALS` environment variable
58
+ *
59
+ * @extends ApiClient
60
+ *
61
+ * @example
62
+ * ```typescript
63
+ * // Using API key
64
+ * const client = new WebApiClient({
65
+ * apiKey: 'your-api-key'
66
+ * });
67
+ *
68
+ * // Using service account credentials
69
+ * const client = new WebApiClient({
70
+ * credentials: {
71
+ * type: "service_account",
72
+ * project_id: "my-project",
73
+ * private_key_id: "key-id",
74
+ * private_key: "-----BEGIN PRIVATE KEY-----\n...",
75
+ * client_email: "service-account@project.iam.gserviceaccount.com",
76
+ * // ... other required fields
77
+ * }
78
+ * });
79
+ *
80
+ * // Using environment variables
81
+ * // Set GOOGLE_API_KEY or GOOGLE_CLOUD_CREDENTIALS
82
+ * const client = new WebApiClient({});
83
+ *
84
+ * // Make authenticated requests
85
+ * const request = new Request('https://api.google.com/...');
86
+ * const response = await client.fetch(request);
87
+ * ```
88
+ *
89
+ * @remarks
90
+ * - API keys are added via the `X-Goog-Api-Key` header
91
+ * - Service account tokens are added via the `Authorization` header with Bearer scheme
92
+ * - Tokens are automatically cached and refreshed as needed
93
+ * - For Node.js environments with advanced auth requirements, use NodeApiClient instead
94
+ *
95
+ * @see {@link NodeApiClient} for Node.js-specific authentication options
96
+ * @see {@link GCPCredentials} for service account credential structure
97
+ */
98
+ var WebApiClient = class extends ApiClient {
99
+ hasApiKey() {
100
+ return typeof this.apiKey === "string" && this.apiKey !== "";
101
+ }
102
+ async getProjectId() {
103
+ if (typeof this.credentials !== "undefined") return this.credentials.project_id;
104
+ else return super.getProjectId();
105
+ }
106
+ /**
107
+ * The Google API key used for authentication, if provided.
108
+ *
109
+ * This value is resolved from either the constructor parameter or the
110
+ * `GOOGLE_API_KEY` environment variable.
111
+ *
112
+ * @protected
113
+ */
114
+ apiKey;
115
+ /**
116
+ * The normalized GCP service account credentials, if provided.
117
+ *
118
+ * This value is resolved from either the constructor parameter or the
119
+ * `GOOGLE_CLOUD_CREDENTIALS` environment variable, and is normalized
120
+ * to ensure immutability.
121
+ *
122
+ * @protected
123
+ */
124
+ credentials;
125
+ /**
126
+ * Creates a new WebApiClient instance.
127
+ *
128
+ * The constructor initializes authentication credentials by checking:
129
+ * 1. Explicit parameters passed to the constructor
130
+ * 2. Environment variables (`GOOGLE_API_KEY`, `GOOGLE_CLOUD_CREDENTIALS`)
131
+ *
132
+ * Credentials are normalized and frozen to prevent accidental modification.
133
+ *
134
+ * @param params - Configuration parameters for the client
135
+ *
136
+ * @example
137
+ * ```typescript
138
+ * // Minimal configuration (uses environment variables)
139
+ * const client = new WebApiClient({});
140
+ *
141
+ * // With explicit API key
142
+ * const client = new WebApiClient({
143
+ * apiKey: 'your-api-key'
144
+ * });
145
+ *
146
+ * // With service account credentials as JSON string
147
+ * const client = new WebApiClient({
148
+ * credentials: '{"type":"service_account",...}'
149
+ * });
150
+ *
151
+ * // With service account credentials as object
152
+ * const client = new WebApiClient({
153
+ * credentials: {
154
+ * type: "service_account",
155
+ * // ... other fields
156
+ * }
157
+ * });
158
+ * ```
159
+ */
160
+ constructor(params) {
161
+ super();
162
+ this.params = params;
163
+ this.apiKey = params.apiKey ?? getEnvironmentVariable("GOOGLE_API_KEY");
164
+ this.credentials = iife(() => {
165
+ if (params.credentials) return normalizeGCPCredentials(params.credentials);
166
+ const credentialsVar = getEnvironmentVariable("GOOGLE_CLOUD_CREDENTIALS");
167
+ if (credentialsVar) return normalizeGCPCredentials(credentialsVar);
168
+ return void 0;
169
+ });
170
+ }
171
+ /**
172
+ * Executes an HTTP request with appropriate Google API authentication.
173
+ *
174
+ * This method adds authentication headers to the request based on the
175
+ * configured authentication method:
176
+ *
177
+ * - If an API key is configured, adds the `X-Goog-Api-Key` header
178
+ * - If service account credentials are configured, generates an access token
179
+ * and adds it via the `Authorization` header with Bearer scheme
180
+ *
181
+ * The authentication priority is:
182
+ * 1. API key (if provided)
183
+ * 2. Service account credentials (if provided)
184
+ *
185
+ * @param request - The HTTP request to execute. Headers will be modified
186
+ * in-place to include authentication information.
187
+ * @returns A Promise that resolves to the HTTP response
188
+ *
189
+ * @throws {AuthError} If no authentication method is available (neither apiKey
190
+ * nor credentials), or if service account authentication
191
+ * fails (e.g., invalid credentials, network error, or
192
+ * token generation failure)
193
+ *
194
+ * @example
195
+ * ```typescript
196
+ * const client = new WebApiClient({ apiKey: 'your-key' });
197
+ * const request = new Request('https://generativelanguage.googleapis.com/v1/models');
198
+ * const response = await client.fetch(request);
199
+ * const data = await response.json();
200
+ * ```
201
+ *
202
+ * @remarks
203
+ * - The request object is modified in-place by adding headers
204
+ * - Service account tokens are automatically cached and refreshed
205
+ * - If both API key and credentials are provided, API key takes precedence
206
+ */
207
+ async fetch(request) {
208
+ if (!this.apiKey && !this.credentials) throw new AuthError({ message: "No authentication method available. Please provide either an apiKey or credentials." });
209
+ if (this.apiKey) request.headers.set(GOOGLE_API_KEY_HEADER, this.apiKey);
210
+ if (this.credentials) request.headers.set(GCP_API_KEY_HEADER, `Bearer ${await getGCPCredentialsAccessToken(this.credentials)}`);
211
+ return fetch(request);
212
+ }
213
+ };
214
+
215
+ //#endregion
216
+ export { ApiClient, WebApiClient };
217
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["params: WebApiClientParams","request: Request"],"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;CACR;AAcF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0GD,IAAa,eAAb,cAAkC,UAAU;CAC1C,YAAqB;AACnB,SAAO,OAAO,KAAK,WAAW,YAAY,KAAK,WAAW;CAC3D;CAED,MAAM,eAAgC;AACpC,MAAI,OAAO,KAAK,gBAAgB,YAC9B,QAAO,KAAK,YAAY;MAExB,QAAO,MAAM,cAAc;CAE9B;;;;;;;;;CAUD,AAAU;;;;;;;;;;CAWV,AAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqCV,YAAsBA,QAA4B;EAChD,OAAO;EADa;EAEpB,KAAK,SAAS,OAAO,UAAU,uBAAuB,iBAAiB;EACvE,KAAK,cAAc,KAAK,MAAM;AAC5B,OAAI,OAAO,YACT,QAAO,wBAAwB,OAAO,YAAY;GAEpD,MAAM,iBAAiB,uBAAuB,2BAA2B;AACzE,OAAI,eACF,QAAO,wBAAwB,eAAe;AAEhD,UAAO;EACR,EAAC;CACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAsCD,MAAM,MAAMC,SAAqC;AAC/C,MAAI,CAAC,KAAK,UAAU,CAAC,KAAK,YACxB,OAAM,IAAI,UAAU,EAClB,SACE,sFACH;AAEH,MAAI,KAAK,QACP,QAAQ,QAAQ,IAAI,uBAAuB,KAAK,OAAO;AAEzD,MAAI,KAAK,aACP,QAAQ,QAAQ,IACd,oBACA,CAAC,OAAO,EAAE,MAAM,6BAA6B,KAAK,YAAY,EAAE,CACjE;AAEH,SAAO,MAAM,QAAQ;CACtB;AACF"}
@@ -0,0 +1,327 @@
1
+ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
2
+ const require_const = require('../const.cjs');
3
+ const require_misc = require('../utils/misc.cjs');
4
+ const require_errors = require('../utils/errors.cjs');
5
+ const require_gcp_auth = require('../utils/gcp-auth.cjs');
6
+ const require_index = require('./index.cjs');
7
+ const __langchain_core_utils_env = require_rolldown_runtime.__toESM(require("@langchain/core/utils/env"));
8
+ const google_auth_library = require_rolldown_runtime.__toESM(require("google-auth-library"));
9
+
10
+ //#region src/clients/node.ts
11
+ /**
12
+ * Node.js-specific API client for Google services.
13
+ *
14
+ * This client provides comprehensive authentication for Google API requests in
15
+ * Node.js environments, leveraging the full capabilities of the google-auth-library.
16
+ * It supports three authentication methods with the following priority:
17
+ *
18
+ * 1. **API Key Authentication**: Simple key-based authentication suitable for
19
+ * public APIs and development environments.
20
+ *
21
+ * 2. **Service Account Credentials**: OAuth2-based authentication using GCP
22
+ * service account keys. The client automatically handles token generation
23
+ * and caching using a web-compatible implementation.
24
+ *
25
+ * 3. **Google Auth Library**: Advanced authentication using google-auth-library,
26
+ * supporting Application Default Credentials (ADC), custom scopes, and
27
+ * various credential sources.
28
+ *
29
+ * The client follows this authentication priority:
30
+ * 1. Explicit `apiKey` parameter
31
+ * 2. `GOOGLE_API_KEY` environment variable
32
+ * 3. Explicit `credentials` parameter
33
+ * 4. `GOOGLE_CLOUD_CREDENTIALS` environment variable
34
+ * 5. `googleAuthOptions` parameter
35
+ * 6. Application Default Credentials (if googleAuthOptions is provided without explicit credentials)
36
+ *
37
+ * @extends ApiClient
38
+ *
39
+ * @example
40
+ * ```typescript
41
+ * // Using API key
42
+ * const client = new NodeApiClient({
43
+ * apiKey: 'your-api-key'
44
+ * });
45
+ *
46
+ * // Using service account credentials
47
+ * const client = new NodeApiClient({
48
+ * credentials: {
49
+ * type: "service_account",
50
+ * project_id: "my-project",
51
+ * private_key_id: "key-id",
52
+ * private_key: "-----BEGIN PRIVATE KEY-----\n...",
53
+ * client_email: "service-account@project.iam.gserviceaccount.com",
54
+ * // ... other required fields
55
+ * }
56
+ * });
57
+ *
58
+ * // Using Google Auth with custom scopes
59
+ * const client = new NodeApiClient({
60
+ * googleAuthOptions: {
61
+ * scopes: ['https://www.googleapis.com/auth/cloud-platform'],
62
+ * keyFilename: '/path/to/service-account-key.json'
63
+ * }
64
+ * });
65
+ *
66
+ * // Using Application Default Credentials
67
+ * const client = new NodeApiClient({
68
+ * googleAuthOptions: {}
69
+ * });
70
+ *
71
+ * // Using environment variables
72
+ * // Set GOOGLE_API_KEY or GOOGLE_CLOUD_CREDENTIALS
73
+ * const client = new NodeApiClient();
74
+ *
75
+ * // Make authenticated requests
76
+ * const request = new Request('https://api.google.com/...');
77
+ * const response = await client.fetch(request);
78
+ * ```
79
+ *
80
+ * @remarks
81
+ * - API keys are added via the `X-Goog-Api-Key` header
82
+ * - Service account tokens are added via the `Authorization` header with Bearer scheme
83
+ * - Google Auth headers are automatically generated and added by google-auth-library
84
+ * - Tokens are automatically cached and refreshed as needed
85
+ * - For web/edge environments without google-auth-library, use WebApiClient instead
86
+ *
87
+ * @see {@link WebApiClient} for web-compatible authentication without google-auth-library
88
+ * @see {@link GCPCredentials} for service account credential structure
89
+ * @see {@link GoogleAuthOptions} for advanced authentication configuration
90
+ */
91
+ var NodeApiClient = class extends require_index.ApiClient {
92
+ hasApiKey() {
93
+ return typeof this.apiKey === "string" && this.apiKey !== "";
94
+ }
95
+ async getProjectId() {
96
+ if (typeof this.credentials !== "undefined") return this.credentials.project_id;
97
+ else if (typeof this.googleAuth !== "undefined") return this.googleAuth.getProjectId();
98
+ else return super.getProjectId();
99
+ }
100
+ /**
101
+ * The Google API key used for authentication, if provided.
102
+ *
103
+ * This value is resolved from either the constructor parameter or the
104
+ * `GOOGLE_API_KEY` environment variable.
105
+ *
106
+ * @protected
107
+ */
108
+ apiKey;
109
+ /**
110
+ * The normalized GCP service account credentials, if provided.
111
+ *
112
+ * This value is resolved from either the constructor parameter or the
113
+ * `GOOGLE_CLOUD_CREDENTIALS` environment variable, and is normalized
114
+ * to ensure immutability.
115
+ *
116
+ * @protected
117
+ */
118
+ credentials;
119
+ /**
120
+ * The Google Auth instance for advanced authentication, if configured.
121
+ *
122
+ * This instance is created when `googleAuthOptions` is provided and
123
+ * handles Application Default Credentials, custom scopes, and other
124
+ * advanced authentication scenarios.
125
+ *
126
+ * @protected
127
+ */
128
+ googleAuth;
129
+ /**
130
+ * Creates a new NodeApiClient instance.
131
+ *
132
+ * The constructor initializes authentication credentials by checking:
133
+ * 1. Explicit parameters passed to the constructor
134
+ * 2. Environment variables (`GOOGLE_API_KEY`, `GOOGLE_CLOUD_CREDENTIALS`)
135
+ * 3. Application Default Credentials (if googleAuthOptions is provided)
136
+ *
137
+ * Credentials are normalized and frozen to prevent accidental modification.
138
+ * The GoogleAuth instance is lazily initialized only when googleAuthOptions
139
+ * is provided.
140
+ *
141
+ * @param params - Configuration parameters for the client. Defaults to an empty object.
142
+ *
143
+ * @example
144
+ * ```typescript
145
+ * // Minimal configuration (uses environment variables or ADC)
146
+ * const client = new NodeApiClient();
147
+ *
148
+ * // With explicit API key
149
+ * const client = new WebApiClient({
150
+ * apiKey: 'your-api-key'
151
+ * });
152
+ *
153
+ * // With service account credentials as JSON string
154
+ * const client = new WebApiClient({
155
+ * credentials: '{"type":"service_account",...}'
156
+ * });
157
+ *
158
+ * // With service account credentials as object
159
+ * const client = new NodeApiClient({
160
+ * credentials: {
161
+ * type: "service_account",
162
+ * // ... other fields
163
+ * }
164
+ * });
165
+ *
166
+ * // With Google Auth options
167
+ * const client = new NodeApiClient({
168
+ * googleAuthOptions: {
169
+ * scopes: ['https://www.googleapis.com/auth/cloud-platform'],
170
+ * projectId: 'my-project'
171
+ * }
172
+ * });
173
+ * ```
174
+ */
175
+ constructor(params = {}) {
176
+ super();
177
+ this.params = params;
178
+ this.apiKey = params.apiKey ?? (0, __langchain_core_utils_env.getEnvironmentVariable)("GOOGLE_API_KEY");
179
+ this.credentials = require_misc.iife(() => {
180
+ if (params.credentials) return require_gcp_auth.normalizeGCPCredentials(params.credentials);
181
+ const credentialsVar = (0, __langchain_core_utils_env.getEnvironmentVariable)("GOOGLE_CLOUD_CREDENTIALS");
182
+ if (credentialsVar) return require_gcp_auth.normalizeGCPCredentials(credentialsVar);
183
+ return void 0;
184
+ });
185
+ this.googleAuth = require_misc.iife(() => {
186
+ if (params.googleAuthOptions) return new google_auth_library.GoogleAuth(params.googleAuthOptions);
187
+ if (!this.apiKey && !this.credentials) return new google_auth_library.GoogleAuth();
188
+ return void 0;
189
+ });
190
+ }
191
+ /**
192
+ * Executes an HTTP request with appropriate Google API authentication.
193
+ *
194
+ * This method adds authentication headers to the request based on the
195
+ * configured authentication method, following this priority:
196
+ *
197
+ * 1. If an API key is configured, adds the `X-Goog-Api-Key` header
198
+ * 2. If service account credentials are configured, generates an access token
199
+ * and adds it via the `Authorization` header with Bearer scheme
200
+ * 3. If Google Auth is configured, uses google-auth-library to generate
201
+ * appropriate authentication headers (may include Authorization, x-goog-user-project, etc.)
202
+ *
203
+ * The authentication priority ensures that explicit API keys take precedence,
204
+ * followed by service account credentials, and finally Google Auth options.
205
+ *
206
+ * @param request - The HTTP request to execute. Headers will be modified
207
+ * in-place to include authentication information.
208
+ * @returns A Promise that resolves to the HTTP response
209
+ *
210
+ * @throws {AuthError} If service account authentication fails (e.g., invalid
211
+ * credentials, network error, or token generation failure)
212
+ * @throws {Error} If Google Auth authentication fails (e.g., missing credentials,
213
+ * invalid configuration, or ADC not available)
214
+ *
215
+ * @example
216
+ * ```typescript
217
+ * const client = new NodeApiClient({ apiKey: 'your-key' });
218
+ * const request = new Request('https://generativelanguage.googleapis.com/v1/models');
219
+ * const response = await client.fetch(request);
220
+ * const data = await response.json();
221
+ * ```
222
+ *
223
+ * @remarks
224
+ * - The request object is modified in-place by adding headers
225
+ * - Service account tokens are automatically cached and refreshed
226
+ * - Google Auth tokens are managed by google-auth-library with automatic refresh
227
+ * - Only one authentication method is used per request (based on priority)
228
+ * - Google Auth may add multiple headers depending on the authentication type
229
+ */
230
+ async fetch(request) {
231
+ if (this.apiKey) request.headers.set(require_const.GOOGLE_API_KEY_HEADER, this.apiKey);
232
+ else if (this.credentials) request.headers.set(require_const.GCP_API_KEY_HEADER, `Bearer ${require_gcp_auth.getGCPCredentialsAccessToken(this.credentials)}`);
233
+ else if (this.googleAuth) {
234
+ const authHeaders = await this.googleAuth.getRequestHeaders(request.url);
235
+ authHeaders.forEach((value, key) => {
236
+ if (value !== null) request.headers.set(key, value);
237
+ });
238
+ }
239
+ return fetch(request);
240
+ }
241
+ };
242
+ /**
243
+ * Ensures that Google Auth options include required OAuth2 scopes.
244
+ *
245
+ * This utility function validates and augments GoogleAuthOptions to ensure
246
+ * that all required OAuth2 scopes are present. It handles three scenarios:
247
+ *
248
+ * 1. **No auth options provided**: Creates new options with required scopes
249
+ * 2. **Auth options without scopes**: Adds required scopes to existing options
250
+ * 3. **Auth options with scopes**: Validates that all required scopes are present
251
+ *
252
+ * This is particularly useful when working with Google APIs that require specific
253
+ * scopes for access, ensuring that authentication is properly configured before
254
+ * making API requests.
255
+ *
256
+ * @param authOptions - The existing Google Auth options to validate/augment.
257
+ * Can be undefined or an empty object.
258
+ * @param requiredScopes - Array of OAuth2 scope URLs that must be present.
259
+ * These are typically Google API scope URLs like
260
+ * 'https://www.googleapis.com/auth/cloud-platform'
261
+ * @returns The validated/augmented GoogleAuthOptions with all required scopes
262
+ *
263
+ * @throws {Error} If authOptions already has scopes but is missing any of the
264
+ * required scopes. This prevents accidental scope reduction that
265
+ * could break API access.
266
+ *
267
+ * @example
268
+ * ```typescript
269
+ * // Create new options with required scopes
270
+ * const options = ensureAuthScopes(undefined, [
271
+ * 'https://www.googleapis.com/auth/cloud-platform'
272
+ * ]);
273
+ * // Result: { scopes: ['https://www.googleapis.com/auth/cloud-platform'] }
274
+ *
275
+ * // Add scopes to existing options
276
+ * const options = ensureAuthScopes(
277
+ * { projectId: 'my-project' },
278
+ * ['https://www.googleapis.com/auth/cloud-platform']
279
+ * );
280
+ * // Result: { projectId: 'my-project', scopes: [...] }
281
+ *
282
+ * // Validate existing scopes
283
+ * const options = ensureAuthScopes(
284
+ * { scopes: ['https://www.googleapis.com/auth/cloud-platform'] },
285
+ * ['https://www.googleapis.com/auth/cloud-platform']
286
+ * );
287
+ * // Result: Original options (validation passed)
288
+ *
289
+ * // Error case - missing required scope
290
+ * try {
291
+ * ensureAuthScopes(
292
+ * { scopes: ['https://www.googleapis.com/auth/userinfo.email'] },
293
+ * ['https://www.googleapis.com/auth/cloud-platform']
294
+ * );
295
+ * } catch (error) {
296
+ * // Error: Invalid auth scopes. Scopes must include ...
297
+ * }
298
+ * ```
299
+ *
300
+ * @remarks
301
+ * - Scopes can be provided as a string or array of strings in GoogleAuthOptions
302
+ * - The function normalizes single-string scopes to arrays for validation
303
+ * - Required scopes are not automatically added if existing scopes are present;
304
+ * instead, an error is thrown to prevent unintended scope changes
305
+ * - This function does not modify the original authOptions object
306
+ *
307
+ * @see https://developers.google.com/identity/protocols/oauth2/scopes
308
+ * @see {@link GoogleAuthOptions} for the full authentication configuration interface
309
+ */
310
+ function ensureAuthScopes(authOptions, requiredScopes) {
311
+ if (!authOptions) return { scopes: requiredScopes };
312
+ else if (!authOptions.scopes) return {
313
+ ...authOptions,
314
+ scopes: requiredScopes
315
+ };
316
+ else {
317
+ const existingScopes = Array.isArray(authOptions.scopes) ? authOptions.scopes : [authOptions.scopes];
318
+ const missingScopes = requiredScopes.filter((scope) => !existingScopes.includes(scope));
319
+ if (missingScopes.length > 0) throw new require_errors.ConfigurationError(`Invalid auth scopes. Scopes must include ${requiredScopes.join(", ")}`);
320
+ }
321
+ return authOptions;
322
+ }
323
+
324
+ //#endregion
325
+ exports.NodeApiClient = NodeApiClient;
326
+ exports.ensureAuthScopes = ensureAuthScopes;
327
+ //# sourceMappingURL=node.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node.cjs","names":["ApiClient","params: NodeApiClientParams","iife","normalizeGCPCredentials","GoogleAuth","request: Request","GOOGLE_API_KEY_HEADER","GCP_API_KEY_HEADER","getGCPCredentialsAccessToken","authOptions: GoogleAuthOptions","requiredScopes: string[]","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,wBAAU;CAC3C,YAAqB;AACnB,SAAO,OAAO,KAAK,WAAW,YAAY,KAAK,WAAW;CAC3D;CAED,MAAM,eAAgC;AACpC,MAAI,OAAO,KAAK,gBAAgB,YAC9B,QAAO,KAAK,YAAY;WACf,OAAO,KAAK,eAAe,YACpC,QAAO,KAAK,WAAW,cAAc;MAErC,QAAO,MAAM,cAAc;CAE9B;;;;;;;;;CAUD,AAAU;;;;;;;;;;CAWV,AAAU;;;;;;;;;;CAWV,AAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgDV,YAAsBC,SAA8B,CAAE,GAAE;EACtD,OAAO;EADa;EAGpB,KAAK,SAAS,OAAO,iEAAiC,iBAAiB;EACvE,KAAK,cAAcC,kBAAK,MAAM;AAC5B,OAAI,OAAO,YACT,QAAOC,yCAAwB,OAAO,YAAY;GAEpD,MAAM,wEAAwC,2BAA2B;AACzE,OAAI,eACF,QAAOA,yCAAwB,eAAe;AAEhD,UAAO;EACR,EAAC;EACF,KAAK,aAAaD,kBAAK,MAAM;AAC3B,OAAI,OAAO,kBACT,QAAO,IAAIE,+BAAW,OAAO;AAE/B,OAAI,CAAC,KAAK,UAAU,CAAC,KAAK,YACxB,QAAO,IAAIA;AAEb,UAAO;EACR,EAAC;CACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAyCD,MAAM,MAAMC,SAAqC;AAC/C,MAAI,KAAK,QACP,QAAQ,QAAQ,IAAIC,qCAAuB,KAAK,OAAO;WAC9C,KAAK,aACd,QAAQ,QAAQ,IACdC,kCACA,CAAC,OAAO,EAAEC,8CAA6B,KAAK,YAAY,EAAE,CAC3D;WACQ,KAAK,YAAY;GAC1B,MAAM,cAAc,MAAM,KAAK,WAAW,kBAAkB,QAAQ,IAAI;GACxE,YAAY,QAAQ,CAAC,OAAO,QAAQ;AAClC,QAAI,UAAU,MACZ,QAAQ,QAAQ,IAAI,KAAK,MAAM;GAElC,EAAC;EACH;AACD,SAAO,MAAM,QAAQ;CACtB;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsED,SAAgB,iBACdC,aACAC,gBACmB;AACnB,KAAI,CAAC,YACH,QAAO,EAAE,QAAQ,eAAgB;UACxB,CAAC,YAAY,OACtB,QAAO;EAAE,GAAG;EAAa,QAAQ;CAAgB;MAC5C;EACL,MAAM,iBAAiB,MAAM,QAAQ,YAAY,OAAO,GACpD,YAAY,SACZ,CAAC,YAAY,MAAO;EACxB,MAAM,gBAAgB,eAAe,OACnC,CAAC,UAAU,CAAC,eAAe,SAAS,MAAM,CAC3C;AACD,MAAI,cAAc,SAAS,EACzB,OAAM,IAAIC,kCACR,CAAC,yCAAyC,EAAE,eAAe,KAAK,KAAK,EAAE;CAG5E;AACD,QAAO;AACR"}
@@ -0,0 +1,59 @@
1
+ import { GCPCredentials } from "../utils/gcp-auth.cjs";
2
+ import { GoogleAuthOptions } from "google-auth-library";
3
+
4
+ //#region src/clients/node.d.ts
5
+
6
+ /**
7
+ * Configuration parameters for the NodeApiClient.
8
+ *
9
+ * This interface defines the authentication options available for Node.js-based
10
+ * API clients. Authentication can be provided via an API key, GCP service
11
+ * account credentials, or advanced Google Auth options. The client will
12
+ * automatically check environment variables if explicit values are not provided.
13
+ *
14
+ * @interface
15
+ */
16
+ interface NodeApiClientParams {
17
+ /**
18
+ * Google API key for authentication.
19
+ *
20
+ * If not provided, the client will attempt to read from the
21
+ * `GOOGLE_API_KEY` environment variable.
22
+ *
23
+ * @see https://cloud.google.com/docs/authentication/api-keys
24
+ */
25
+ apiKey?: string;
26
+ /**
27
+ * GCP service account credentials for authentication.
28
+ *
29
+ * Can be provided as either:
30
+ * - A JSON string containing the service account key
31
+ * - A GCPCredentials object
32
+ *
33
+ * If not provided, the client will attempt to read from the
34
+ * `GOOGLE_CLOUD_CREDENTIALS` environment variable.
35
+ *
36
+ * @see https://cloud.google.com/iam/docs/creating-managing-service-account-keys
37
+ */
38
+ credentials?: string | GCPCredentials;
39
+ /**
40
+ * Google Auth options configuration.
41
+ *
42
+ * Provides fine-grained control over authentication behavior using the
43
+ * google-auth-library. This option enables:
44
+ * - Custom OAuth2 scopes
45
+ * - Application Default Credentials (ADC)
46
+ * - Impersonation and delegation
47
+ * - Custom credential sources
48
+ *
49
+ * When provided, this takes precedence over simple credential-based auth
50
+ * but is lower priority than API key authentication.
51
+ *
52
+ * @see https://github.com/googleapis/google-auth-library-nodejs
53
+ * @see https://cloud.google.com/docs/authentication/application-default-credentials
54
+ */
55
+ googleAuthOptions?: GoogleAuthOptions;
56
+ }
57
+ //#endregion
58
+ export { NodeApiClientParams };
59
+ //# sourceMappingURL=node.d.cts.map