@google/genai 1.32.0 → 1.33.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.
@@ -6,7 +6,7 @@ var fs$1 = require('fs/promises');
6
6
  var node_stream = require('node:stream');
7
7
  var promises = require('node:stream/promises');
8
8
  var NodeWs = require('ws');
9
- var path = require('path');
9
+ var path$1 = require('path');
10
10
 
11
11
  function _interopNamespaceDefault(e) {
12
12
  var n = Object.create(null);
@@ -27,7 +27,7 @@ function _interopNamespaceDefault(e) {
27
27
 
28
28
  var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs$1);
29
29
  var NodeWs__namespace = /*#__PURE__*/_interopNamespaceDefault(NodeWs);
30
- var path__namespace = /*#__PURE__*/_interopNamespaceDefault(path);
30
+ var path__namespace = /*#__PURE__*/_interopNamespaceDefault(path$1);
31
31
 
32
32
  /**
33
33
  * @license
@@ -990,6 +990,14 @@ exports.FinishReason = void 0;
990
990
  * The model was expected to generate an image, but none was generated.
991
991
  */
992
992
  FinishReason["NO_IMAGE"] = "NO_IMAGE";
993
+ /**
994
+ * Image generation stopped because the generated image may be a recitation from a source.
995
+ */
996
+ FinishReason["IMAGE_RECITATION"] = "IMAGE_RECITATION";
997
+ /**
998
+ * Image generation stopped for a reason not otherwise specified.
999
+ */
1000
+ FinishReason["IMAGE_OTHER"] = "IMAGE_OTHER";
993
1001
  })(exports.FinishReason || (exports.FinishReason = {}));
994
1002
  /** Output only. Harm probability levels in the content. */
995
1003
  exports.HarmProbability = void 0;
@@ -1612,6 +1620,22 @@ exports.MediaModality = void 0;
1612
1620
  */
1613
1621
  MediaModality["DOCUMENT"] = "DOCUMENT";
1614
1622
  })(exports.MediaModality || (exports.MediaModality = {}));
1623
+ /** The type of the VAD signal. */
1624
+ exports.VadSignalType = void 0;
1625
+ (function (VadSignalType) {
1626
+ /**
1627
+ * The default is VAD_SIGNAL_TYPE_UNSPECIFIED.
1628
+ */
1629
+ VadSignalType["VAD_SIGNAL_TYPE_UNSPECIFIED"] = "VAD_SIGNAL_TYPE_UNSPECIFIED";
1630
+ /**
1631
+ * Start of sentence signal.
1632
+ */
1633
+ VadSignalType["VAD_SIGNAL_TYPE_SOS"] = "VAD_SIGNAL_TYPE_SOS";
1634
+ /**
1635
+ * End of sentence signal.
1636
+ */
1637
+ VadSignalType["VAD_SIGNAL_TYPE_EOS"] = "VAD_SIGNAL_TYPE_EOS";
1638
+ })(exports.VadSignalType || (exports.VadSignalType = {}));
1615
1639
  /** Start of speech sensitivity. */
1616
1640
  exports.StartSensitivity = void 0;
1617
1641
  (function (StartSensitivity) {
@@ -6282,6 +6306,18 @@ PERFORMANCE OF THIS SOFTWARE.
6282
6306
  /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
6283
6307
 
6284
6308
 
6309
+ function __rest(s, e) {
6310
+ var t = {};
6311
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
6312
+ t[p] = s[p];
6313
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
6314
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
6315
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
6316
+ t[p[i]] = s[p[i]];
6317
+ }
6318
+ return t;
6319
+ }
6320
+
6285
6321
  function __values(o) {
6286
6322
  var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
6287
6323
  if (m) return m.call(o);
@@ -7408,6 +7444,9 @@ function liveConnectConfigToMldev$1(fromObject, parentObject) {
7408
7444
  if (parentObject !== undefined && fromProactivity != null) {
7409
7445
  setValueByPath(parentObject, ['setup', 'proactivity'], fromProactivity);
7410
7446
  }
7447
+ if (getValueByPath(fromObject, ['explicitVadSignal']) !== undefined) {
7448
+ throw new Error('explicitVadSignal parameter is not supported in Gemini API.');
7449
+ }
7411
7450
  return toObject;
7412
7451
  }
7413
7452
  function liveConnectConfigToVertex(fromObject, parentObject) {
@@ -7518,6 +7557,12 @@ function liveConnectConfigToVertex(fromObject, parentObject) {
7518
7557
  if (parentObject !== undefined && fromProactivity != null) {
7519
7558
  setValueByPath(parentObject, ['setup', 'proactivity'], fromProactivity);
7520
7559
  }
7560
+ const fromExplicitVadSignal = getValueByPath(fromObject, [
7561
+ 'explicitVadSignal',
7562
+ ]);
7563
+ if (parentObject !== undefined && fromExplicitVadSignal != null) {
7564
+ setValueByPath(parentObject, ['setup', 'explicitVadSignal'], fromExplicitVadSignal);
7565
+ }
7521
7566
  return toObject;
7522
7567
  }
7523
7568
  function liveConnectParametersToMldev(apiClient, fromObject) {
@@ -7694,6 +7739,12 @@ function liveServerMessageFromVertex(fromObject) {
7694
7739
  if (fromSessionResumptionUpdate != null) {
7695
7740
  setValueByPath(toObject, ['sessionResumptionUpdate'], fromSessionResumptionUpdate);
7696
7741
  }
7742
+ const fromVoiceActivityDetectionSignal = getValueByPath(fromObject, [
7743
+ 'voiceActivityDetectionSignal',
7744
+ ]);
7745
+ if (fromVoiceActivityDetectionSignal != null) {
7746
+ setValueByPath(toObject, ['voiceActivityDetectionSignal'], fromVoiceActivityDetectionSignal);
7747
+ }
7697
7748
  return toObject;
7698
7749
  }
7699
7750
  function partToMldev$2(fromObject) {
@@ -11468,7 +11519,7 @@ const CONTENT_TYPE_HEADER = 'Content-Type';
11468
11519
  const SERVER_TIMEOUT_HEADER = 'X-Server-Timeout';
11469
11520
  const USER_AGENT_HEADER = 'User-Agent';
11470
11521
  const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client';
11471
- const SDK_VERSION = '1.32.0'; // x-release-please-version
11522
+ const SDK_VERSION = '1.33.0'; // x-release-please-version
11472
11523
  const LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;
11473
11524
  const VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1';
11474
11525
  const GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta';
@@ -14940,6 +14991,9 @@ function liveConnectConfigToMldev(fromObject, parentObject) {
14940
14991
  if (parentObject !== undefined && fromProactivity != null) {
14941
14992
  setValueByPath(parentObject, ['setup', 'proactivity'], fromProactivity);
14942
14993
  }
14994
+ if (getValueByPath(fromObject, ['explicitVadSignal']) !== undefined) {
14995
+ throw new Error('explicitVadSignal parameter is not supported in Gemini API.');
14996
+ }
14943
14997
  return toObject;
14944
14998
  }
14945
14999
  function liveConnectConstraintsToMldev(apiClient, fromObject) {
@@ -15852,199 +15906,2170 @@ class FileSearchStores extends BaseModule {
15852
15906
  * Copyright 2025 Google LLC
15853
15907
  * SPDX-License-Identifier: Apache-2.0
15854
15908
  */
15855
- const GOOGLE_API_KEY_HEADER = 'x-goog-api-key';
15856
- const REQUIRED_VERTEX_AI_SCOPE = 'https://www.googleapis.com/auth/cloud-platform';
15857
- class NodeAuth {
15858
- constructor(opts) {
15859
- if (opts.apiKey !== undefined) {
15860
- this.apiKey = opts.apiKey;
15861
- return;
15862
- }
15863
- const vertexAuthOptions = buildGoogleAuthOptions(opts.googleAuthOptions);
15864
- this.googleAuth = new googleAuthLibrary.GoogleAuth(vertexAuthOptions);
15865
- }
15866
- async addAuthHeaders(headers, url) {
15867
- if (this.apiKey !== undefined) {
15868
- if (this.apiKey.startsWith('auth_tokens/')) {
15869
- throw new Error('Ephemeral tokens are only supported by the live API.');
15909
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
15910
+ /**
15911
+ * https://stackoverflow.com/a/2117523
15912
+ */
15913
+ let uuid4Internal = function () {
15914
+ const { crypto } = globalThis;
15915
+ if (crypto === null || crypto === void 0 ? void 0 : crypto.randomUUID) {
15916
+ uuid4Internal = crypto.randomUUID.bind(crypto);
15917
+ return crypto.randomUUID();
15918
+ }
15919
+ const u8 = new Uint8Array(1);
15920
+ const randomByte = crypto ? () => crypto.getRandomValues(u8)[0] : () => (Math.random() * 0xff) & 0xff;
15921
+ return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c) => (+c ^ (randomByte() & (15 >> (+c / 4)))).toString(16));
15922
+ };
15923
+ const uuid4 = () => uuid4Internal();
15924
+
15925
+ /**
15926
+ * @license
15927
+ * Copyright 2025 Google LLC
15928
+ * SPDX-License-Identifier: Apache-2.0
15929
+ */
15930
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
15931
+ function isAbortError(err) {
15932
+ return (typeof err === 'object' &&
15933
+ err !== null &&
15934
+ // Spec-compliant fetch implementations
15935
+ (('name' in err && err.name === 'AbortError') ||
15936
+ // Expo fetch
15937
+ ('message' in err && String(err.message).includes('FetchRequestCanceledException'))));
15938
+ }
15939
+ const castToError = (err) => {
15940
+ if (err instanceof Error)
15941
+ return err;
15942
+ if (typeof err === 'object' && err !== null) {
15943
+ try {
15944
+ if (Object.prototype.toString.call(err) === '[object Error]') {
15945
+ // @ts-ignore - not all envs have native support for cause yet
15946
+ const error = new Error(err.message, err.cause ? { cause: err.cause } : {});
15947
+ if (err.stack)
15948
+ error.stack = err.stack;
15949
+ // @ts-ignore - not all envs have native support for cause yet
15950
+ if (err.cause && !error.cause)
15951
+ error.cause = err.cause;
15952
+ if (err.name)
15953
+ error.name = err.name;
15954
+ return error;
15870
15955
  }
15871
- this.addKeyHeader(headers);
15872
- return;
15873
15956
  }
15874
- return this.addGoogleAuthHeaders(headers, url);
15957
+ catch (_a) { }
15958
+ try {
15959
+ return new Error(JSON.stringify(err));
15960
+ }
15961
+ catch (_b) { }
15875
15962
  }
15876
- addKeyHeader(headers) {
15877
- if (headers.get(GOOGLE_API_KEY_HEADER) !== null) {
15878
- return;
15963
+ return new Error(err);
15964
+ };
15965
+
15966
+ /**
15967
+ * @license
15968
+ * Copyright 2025 Google LLC
15969
+ * SPDX-License-Identifier: Apache-2.0
15970
+ */
15971
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
15972
+ class GeminiNextGenAPIClientError extends Error {
15973
+ }
15974
+ class APIError extends GeminiNextGenAPIClientError {
15975
+ constructor(status, error, message, headers) {
15976
+ super(`${APIError.makeMessage(status, error, message)}`);
15977
+ this.status = status;
15978
+ this.headers = headers;
15979
+ this.error = error;
15980
+ }
15981
+ static makeMessage(status, error, message) {
15982
+ const msg = (error === null || error === void 0 ? void 0 : error.message) ?
15983
+ typeof error.message === 'string' ?
15984
+ error.message
15985
+ : JSON.stringify(error.message)
15986
+ : error ? JSON.stringify(error)
15987
+ : message;
15988
+ if (status && msg) {
15989
+ return `${status} ${msg}`;
15879
15990
  }
15880
- if (this.apiKey === undefined) {
15881
- // This should never happen, this method is only called
15882
- // when apiKey is set.
15883
- throw new Error('Trying to set API key header but apiKey is not set');
15991
+ if (status) {
15992
+ return `${status} status code (no body)`;
15884
15993
  }
15885
- headers.append(GOOGLE_API_KEY_HEADER, this.apiKey);
15994
+ if (msg) {
15995
+ return msg;
15996
+ }
15997
+ return '(no status code or body)';
15886
15998
  }
15887
- async addGoogleAuthHeaders(headers, url) {
15888
- if (this.googleAuth === undefined) {
15889
- // This should never happen, addGoogleAuthHeaders should only be
15890
- // called when there is no apiKey set and in these cases googleAuth
15891
- // is set.
15892
- throw new Error('Trying to set google-auth headers but googleAuth is unset');
15999
+ static generate(status, errorResponse, message, headers) {
16000
+ if (!status || !headers) {
16001
+ return new APIConnectionError({ message, cause: castToError(errorResponse) });
15893
16002
  }
15894
- const authHeaders = await this.googleAuth.getRequestHeaders(url);
15895
- for (const [key, value] of authHeaders) {
15896
- if (headers.get(key) !== null) {
15897
- continue;
15898
- }
15899
- headers.append(key, value);
16003
+ const error = errorResponse;
16004
+ if (status === 400) {
16005
+ return new BadRequestError(status, error, message, headers);
15900
16006
  }
16007
+ if (status === 401) {
16008
+ return new AuthenticationError(status, error, message, headers);
16009
+ }
16010
+ if (status === 403) {
16011
+ return new PermissionDeniedError(status, error, message, headers);
16012
+ }
16013
+ if (status === 404) {
16014
+ return new NotFoundError(status, error, message, headers);
16015
+ }
16016
+ if (status === 409) {
16017
+ return new ConflictError(status, error, message, headers);
16018
+ }
16019
+ if (status === 422) {
16020
+ return new UnprocessableEntityError(status, error, message, headers);
16021
+ }
16022
+ if (status === 429) {
16023
+ return new RateLimitError(status, error, message, headers);
16024
+ }
16025
+ if (status >= 500) {
16026
+ return new InternalServerError(status, error, message, headers);
16027
+ }
16028
+ return new APIError(status, error, message, headers);
15901
16029
  }
15902
16030
  }
15903
- function buildGoogleAuthOptions(googleAuthOptions) {
15904
- let authOptions;
15905
- if (!googleAuthOptions) {
15906
- authOptions = {
15907
- scopes: [REQUIRED_VERTEX_AI_SCOPE],
15908
- };
15909
- return authOptions;
16031
+ class APIUserAbortError extends APIError {
16032
+ constructor({ message } = {}) {
16033
+ super(undefined, undefined, message || 'Request was aborted.', undefined);
15910
16034
  }
15911
- else {
15912
- authOptions = googleAuthOptions;
15913
- if (!authOptions.scopes) {
15914
- authOptions.scopes = [REQUIRED_VERTEX_AI_SCOPE];
15915
- return authOptions;
15916
- }
15917
- else if ((typeof authOptions.scopes === 'string' &&
15918
- authOptions.scopes !== REQUIRED_VERTEX_AI_SCOPE) ||
15919
- (Array.isArray(authOptions.scopes) &&
15920
- authOptions.scopes.indexOf(REQUIRED_VERTEX_AI_SCOPE) < 0)) {
15921
- throw new Error(`Invalid auth scopes. Scopes must include: ${REQUIRED_VERTEX_AI_SCOPE}`);
15922
- }
15923
- return authOptions;
16035
+ }
16036
+ class APIConnectionError extends APIError {
16037
+ constructor({ message, cause }) {
16038
+ super(undefined, undefined, message || 'Connection error.', undefined);
16039
+ // in some environments the 'cause' property is already declared
16040
+ // @ts-ignore
16041
+ if (cause)
16042
+ this.cause = cause;
15924
16043
  }
15925
16044
  }
16045
+ class APIConnectionTimeoutError extends APIConnectionError {
16046
+ constructor({ message } = {}) {
16047
+ super({ message: message !== null && message !== void 0 ? message : 'Request timed out.' });
16048
+ }
16049
+ }
16050
+ class BadRequestError extends APIError {
16051
+ }
16052
+ class AuthenticationError extends APIError {
16053
+ }
16054
+ class PermissionDeniedError extends APIError {
16055
+ }
16056
+ class NotFoundError extends APIError {
16057
+ }
16058
+ class ConflictError extends APIError {
16059
+ }
16060
+ class UnprocessableEntityError extends APIError {
16061
+ }
16062
+ class RateLimitError extends APIError {
16063
+ }
16064
+ class InternalServerError extends APIError {
16065
+ }
15926
16066
 
15927
16067
  /**
15928
16068
  * @license
15929
16069
  * Copyright 2025 Google LLC
15930
16070
  * SPDX-License-Identifier: Apache-2.0
15931
16071
  */
15932
- class NodeDownloader {
15933
- async download(params, apiClient) {
15934
- if (params.downloadPath) {
15935
- const response = await downloadFile(params, apiClient);
15936
- if (response instanceof HttpResponse) {
15937
- const writer = fs.createWriteStream(params.downloadPath);
15938
- const body = node_stream.Readable.fromWeb(response.responseInternal.body);
15939
- body.pipe(writer);
15940
- await promises.finished(writer);
15941
- }
15942
- else {
15943
- try {
15944
- await fs$1.writeFile(params.downloadPath, response, {
15945
- encoding: 'base64',
15946
- });
15947
- }
15948
- catch (error) {
15949
- throw new Error(`Failed to write file to ${params.downloadPath}: ${error}`);
15950
- }
15951
- }
15952
- }
15953
- }
16072
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
16073
+ // https://url.spec.whatwg.org/#url-scheme-string
16074
+ const startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;
16075
+ const isAbsoluteURL = (url) => {
16076
+ return startsWithSchemeRegexp.test(url);
16077
+ };
16078
+ let isArrayInternal = (val) => ((isArrayInternal = Array.isArray), isArrayInternal(val));
16079
+ const isArray = isArrayInternal;
16080
+ let isReadonlyArrayInternal = isArray;
16081
+ const isReadonlyArray = isReadonlyArrayInternal;
16082
+ // https://stackoverflow.com/a/34491287
16083
+ function isEmptyObj(obj) {
16084
+ if (!obj)
16085
+ return true;
16086
+ for (const _k in obj)
16087
+ return false;
16088
+ return true;
15954
16089
  }
15955
- async function downloadFile(params, apiClient) {
15956
- var _a, _b, _c;
15957
- const name = tFileName(params.file);
15958
- if (name !== undefined) {
15959
- return await apiClient.request({
15960
- path: `files/${name}:download`,
15961
- httpMethod: 'GET',
15962
- queryParams: {
15963
- 'alt': 'media',
15964
- },
15965
- httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
15966
- abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
15967
- });
16090
+ // https://eslint.org/docs/latest/rules/no-prototype-builtins
16091
+ function hasOwn(obj, key) {
16092
+ return Object.prototype.hasOwnProperty.call(obj, key);
16093
+ }
16094
+ const validatePositiveInteger = (name, n) => {
16095
+ if (typeof n !== 'number' || !Number.isInteger(n)) {
16096
+ throw new GeminiNextGenAPIClientError(`${name} must be an integer`);
15968
16097
  }
15969
- else if (isGeneratedVideo(params.file)) {
15970
- const videoBytes = (_c = params.file.video) === null || _c === void 0 ? void 0 : _c.videoBytes;
15971
- if (typeof videoBytes === 'string') {
15972
- return videoBytes;
15973
- }
15974
- else {
15975
- throw new Error('Failed to download generated video, Uri or videoBytes not found.');
15976
- }
16098
+ if (n < 0) {
16099
+ throw new GeminiNextGenAPIClientError(`${name} must be a positive integer`);
15977
16100
  }
15978
- else if (isVideo(params.file)) {
15979
- const videoBytes = params.file.videoBytes;
15980
- if (typeof videoBytes === 'string') {
15981
- return videoBytes;
15982
- }
15983
- else {
15984
- throw new Error('Failed to download video, Uri or videoBytes not found.');
15985
- }
16101
+ return n;
16102
+ };
16103
+ const safeJSON = (text) => {
16104
+ try {
16105
+ return JSON.parse(text);
15986
16106
  }
15987
- else {
15988
- throw new Error('Unsupported file type');
16107
+ catch (err) {
16108
+ return undefined;
15989
16109
  }
15990
- }
16110
+ };
15991
16111
 
15992
16112
  /**
15993
16113
  * @license
15994
16114
  * Copyright 2025 Google LLC
15995
16115
  * SPDX-License-Identifier: Apache-2.0
15996
16116
  */
15997
- class NodeWebSocketFactory {
15998
- create(url, headers, callbacks) {
15999
- return new NodeWebSocket(url, headers, callbacks);
16117
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
16118
+ const sleep$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
16119
+
16120
+ /**
16121
+ * @license
16122
+ * Copyright 2025 Google LLC
16123
+ * SPDX-License-Identifier: Apache-2.0
16124
+ */
16125
+ const VERSION = '0.0.1';
16126
+
16127
+ /**
16128
+ * @license
16129
+ * Copyright 2025 Google LLC
16130
+ * SPDX-License-Identifier: Apache-2.0
16131
+ */
16132
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
16133
+ /**
16134
+ * Note this does not detect 'browser'; for that, use getBrowserInfo().
16135
+ */
16136
+ function getDetectedPlatform() {
16137
+ if (typeof Deno !== 'undefined' && Deno.build != null) {
16138
+ return 'deno';
16139
+ }
16140
+ if (typeof EdgeRuntime !== 'undefined') {
16141
+ return 'edge';
16142
+ }
16143
+ if (Object.prototype.toString.call(typeof globalThis.process !== 'undefined' ? globalThis.process : 0) === '[object process]') {
16144
+ return 'node';
16000
16145
  }
16146
+ return 'unknown';
16001
16147
  }
16002
- class NodeWebSocket {
16003
- constructor(url, headers, callbacks) {
16004
- this.url = url;
16005
- this.headers = headers;
16006
- this.callbacks = callbacks;
16148
+ const getPlatformProperties = () => {
16149
+ var _a, _b, _c, _d, _e;
16150
+ const detectedPlatform = getDetectedPlatform();
16151
+ if (detectedPlatform === 'deno') {
16152
+ return {
16153
+ 'X-Stainless-Lang': 'js',
16154
+ 'X-Stainless-Package-Version': VERSION,
16155
+ 'X-Stainless-OS': normalizePlatform(Deno.build.os),
16156
+ 'X-Stainless-Arch': normalizeArch(Deno.build.arch),
16157
+ 'X-Stainless-Runtime': 'deno',
16158
+ 'X-Stainless-Runtime-Version': typeof Deno.version === 'string' ? Deno.version : (_b = (_a = Deno.version) === null || _a === void 0 ? void 0 : _a.deno) !== null && _b !== void 0 ? _b : 'unknown',
16159
+ };
16007
16160
  }
16008
- connect() {
16009
- this.ws = new NodeWs__namespace.WebSocket(this.url, { headers: this.headers });
16010
- this.ws.onopen = this.callbacks.onopen;
16011
- this.ws.onerror = this.callbacks.onerror;
16012
- this.ws.onclose = this.callbacks.onclose;
16013
- this.ws.onmessage = this.callbacks.onmessage;
16161
+ if (typeof EdgeRuntime !== 'undefined') {
16162
+ return {
16163
+ 'X-Stainless-Lang': 'js',
16164
+ 'X-Stainless-Package-Version': VERSION,
16165
+ 'X-Stainless-OS': 'Unknown',
16166
+ 'X-Stainless-Arch': `other:${EdgeRuntime}`,
16167
+ 'X-Stainless-Runtime': 'edge',
16168
+ 'X-Stainless-Runtime-Version': globalThis.process.version,
16169
+ };
16014
16170
  }
16015
- send(message) {
16016
- if (this.ws === undefined) {
16017
- throw new Error('WebSocket is not connected');
16018
- }
16019
- this.ws.send(message);
16171
+ // Check if Node.js
16172
+ if (detectedPlatform === 'node') {
16173
+ return {
16174
+ 'X-Stainless-Lang': 'js',
16175
+ 'X-Stainless-Package-Version': VERSION,
16176
+ 'X-Stainless-OS': normalizePlatform((_c = globalThis.process.platform) !== null && _c !== void 0 ? _c : 'unknown'),
16177
+ 'X-Stainless-Arch': normalizeArch((_d = globalThis.process.arch) !== null && _d !== void 0 ? _d : 'unknown'),
16178
+ 'X-Stainless-Runtime': 'node',
16179
+ 'X-Stainless-Runtime-Version': (_e = globalThis.process.version) !== null && _e !== void 0 ? _e : 'unknown',
16180
+ };
16020
16181
  }
16021
- close() {
16022
- if (this.ws === undefined) {
16023
- throw new Error('WebSocket is not connected');
16024
- }
16025
- this.ws.close();
16182
+ const browserInfo = getBrowserInfo();
16183
+ if (browserInfo) {
16184
+ return {
16185
+ 'X-Stainless-Lang': 'js',
16186
+ 'X-Stainless-Package-Version': VERSION,
16187
+ 'X-Stainless-OS': 'Unknown',
16188
+ 'X-Stainless-Arch': 'unknown',
16189
+ 'X-Stainless-Runtime': `browser:${browserInfo.browser}`,
16190
+ 'X-Stainless-Runtime-Version': browserInfo.version,
16191
+ };
16026
16192
  }
16027
- }
16193
+ // TODO add support for Cloudflare workers, etc.
16194
+ return {
16195
+ 'X-Stainless-Lang': 'js',
16196
+ 'X-Stainless-Package-Version': VERSION,
16197
+ 'X-Stainless-OS': 'Unknown',
16198
+ 'X-Stainless-Arch': 'unknown',
16199
+ 'X-Stainless-Runtime': 'unknown',
16200
+ 'X-Stainless-Runtime-Version': 'unknown',
16201
+ };
16202
+ };
16203
+ // Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts
16204
+ function getBrowserInfo() {
16205
+ if (typeof navigator === 'undefined' || !navigator) {
16206
+ return null;
16207
+ }
16208
+ // NOTE: The order matters here!
16209
+ const browserPatterns = [
16210
+ { key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
16211
+ { key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
16212
+ { key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
16213
+ { key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
16214
+ { key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
16215
+ { key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ },
16216
+ ];
16217
+ // Find the FIRST matching browser
16218
+ for (const { key, pattern } of browserPatterns) {
16219
+ const match = pattern.exec(navigator.userAgent);
16220
+ if (match) {
16221
+ const major = match[1] || 0;
16222
+ const minor = match[2] || 0;
16223
+ const patch = match[3] || 0;
16224
+ return { browser: key, version: `${major}.${minor}.${patch}` };
16225
+ }
16226
+ }
16227
+ return null;
16228
+ }
16229
+ const normalizeArch = (arch) => {
16230
+ // Node docs:
16231
+ // - https://nodejs.org/api/process.html#processarch
16232
+ // Deno docs:
16233
+ // - https://doc.deno.land/deno/stable/~/Deno.build
16234
+ if (arch === 'x32')
16235
+ return 'x32';
16236
+ if (arch === 'x86_64' || arch === 'x64')
16237
+ return 'x64';
16238
+ if (arch === 'arm')
16239
+ return 'arm';
16240
+ if (arch === 'aarch64' || arch === 'arm64')
16241
+ return 'arm64';
16242
+ if (arch)
16243
+ return `other:${arch}`;
16244
+ return 'unknown';
16245
+ };
16246
+ const normalizePlatform = (platform) => {
16247
+ // Node platforms:
16248
+ // - https://nodejs.org/api/process.html#processplatform
16249
+ // Deno platforms:
16250
+ // - https://doc.deno.land/deno/stable/~/Deno.build
16251
+ // - https://github.com/denoland/deno/issues/14799
16252
+ platform = platform.toLowerCase();
16253
+ // NOTE: this iOS check is untested and may not work
16254
+ // Node does not work natively on IOS, there is a fork at
16255
+ // https://github.com/nodejs-mobile/nodejs-mobile
16256
+ // however it is unknown at the time of writing how to detect if it is running
16257
+ if (platform.includes('ios'))
16258
+ return 'iOS';
16259
+ if (platform === 'android')
16260
+ return 'Android';
16261
+ if (platform === 'darwin')
16262
+ return 'MacOS';
16263
+ if (platform === 'win32')
16264
+ return 'Windows';
16265
+ if (platform === 'freebsd')
16266
+ return 'FreeBSD';
16267
+ if (platform === 'openbsd')
16268
+ return 'OpenBSD';
16269
+ if (platform === 'linux')
16270
+ return 'Linux';
16271
+ if (platform)
16272
+ return `Other:${platform}`;
16273
+ return 'Unknown';
16274
+ };
16275
+ let _platformHeaders;
16276
+ const getPlatformHeaders = () => {
16277
+ return (_platformHeaders !== null && _platformHeaders !== void 0 ? _platformHeaders : (_platformHeaders = getPlatformProperties()));
16278
+ };
16028
16279
 
16029
16280
  /**
16030
16281
  * @license
16031
16282
  * Copyright 2025 Google LLC
16032
16283
  * SPDX-License-Identifier: Apache-2.0
16033
16284
  */
16034
- // Code generated by the Google Gen AI SDK generator DO NOT EDIT.
16035
- function cancelTuningJobParametersToMldev(fromObject, _rootObject) {
16036
- const toObject = {};
16037
- const fromName = getValueByPath(fromObject, ['name']);
16038
- if (fromName != null) {
16039
- setValueByPath(toObject, ['_url', 'name'], fromName);
16040
- }
16041
- return toObject;
16285
+ function getDefaultFetch() {
16286
+ if (typeof fetch !== 'undefined') {
16287
+ return fetch;
16288
+ }
16289
+ throw new Error('`fetch` is not defined as a global; Either pass `fetch` to the client, `new GeminiNextGenAPIClient({ fetch })` or polyfill the global, `globalThis.fetch = fetch`');
16290
+ }
16291
+ function makeReadableStream(...args) {
16292
+ const ReadableStream = globalThis.ReadableStream;
16293
+ if (typeof ReadableStream === 'undefined') {
16294
+ // Note: All of the platforms / runtimes we officially support already define
16295
+ // `ReadableStream` as a global, so this should only ever be hit on unsupported runtimes.
16296
+ throw new Error('`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`');
16297
+ }
16298
+ return new ReadableStream(...args);
16299
+ }
16300
+ function ReadableStreamFrom(iterable) {
16301
+ let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
16302
+ return makeReadableStream({
16303
+ start() { },
16304
+ async pull(controller) {
16305
+ const { done, value } = await iter.next();
16306
+ if (done) {
16307
+ controller.close();
16308
+ }
16309
+ else {
16310
+ controller.enqueue(value);
16311
+ }
16312
+ },
16313
+ async cancel() {
16314
+ var _a;
16315
+ await ((_a = iter.return) === null || _a === void 0 ? void 0 : _a.call(iter));
16316
+ },
16317
+ });
16042
16318
  }
16043
- function cancelTuningJobParametersToVertex(fromObject, _rootObject) {
16044
- const toObject = {};
16045
- const fromName = getValueByPath(fromObject, ['name']);
16046
- if (fromName != null) {
16047
- setValueByPath(toObject, ['_url', 'name'], fromName);
16319
+ /**
16320
+ * Most browsers don't yet have async iterable support for ReadableStream,
16321
+ * and Node has a very different way of reading bytes from its "ReadableStream".
16322
+ *
16323
+ * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490
16324
+ */
16325
+ function ReadableStreamToAsyncIterable(stream) {
16326
+ if (stream[Symbol.asyncIterator])
16327
+ return stream;
16328
+ const reader = stream.getReader();
16329
+ return {
16330
+ async next() {
16331
+ try {
16332
+ const result = await reader.read();
16333
+ if (result === null || result === void 0 ? void 0 : result.done)
16334
+ reader.releaseLock(); // release lock when stream becomes closed
16335
+ return result;
16336
+ }
16337
+ catch (e) {
16338
+ reader.releaseLock(); // release lock when stream becomes errored
16339
+ throw e;
16340
+ }
16341
+ },
16342
+ async return() {
16343
+ const cancelPromise = reader.cancel();
16344
+ reader.releaseLock();
16345
+ await cancelPromise;
16346
+ return { done: true, value: undefined };
16347
+ },
16348
+ [Symbol.asyncIterator]() {
16349
+ return this;
16350
+ },
16351
+ };
16352
+ }
16353
+ /**
16354
+ * Cancels a ReadableStream we don't need to consume.
16355
+ * See https://undici.nodejs.org/#/?id=garbage-collection
16356
+ */
16357
+ async function CancelReadableStream(stream) {
16358
+ var _a, _b;
16359
+ if (stream === null || typeof stream !== 'object')
16360
+ return;
16361
+ if (stream[Symbol.asyncIterator]) {
16362
+ await ((_b = (_a = stream[Symbol.asyncIterator]()).return) === null || _b === void 0 ? void 0 : _b.call(_a));
16363
+ return;
16364
+ }
16365
+ const reader = stream.getReader();
16366
+ const cancelPromise = reader.cancel();
16367
+ reader.releaseLock();
16368
+ await cancelPromise;
16369
+ }
16370
+
16371
+ /**
16372
+ * @license
16373
+ * Copyright 2025 Google LLC
16374
+ * SPDX-License-Identifier: Apache-2.0
16375
+ */
16376
+ const FallbackEncoder = ({ headers, body }) => {
16377
+ return {
16378
+ bodyHeaders: {
16379
+ 'content-type': 'application/json',
16380
+ },
16381
+ body: JSON.stringify(body),
16382
+ };
16383
+ };
16384
+
16385
+ /**
16386
+ * @license
16387
+ * Copyright 2025 Google LLC
16388
+ * SPDX-License-Identifier: Apache-2.0
16389
+ */
16390
+ const checkFileSupport = () => {
16391
+ var _a;
16392
+ if (typeof File === 'undefined') {
16393
+ const { process } = globalThis;
16394
+ const isOldNode = typeof ((_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node) === 'string' && parseInt(process.versions.node.split('.')) < 20;
16395
+ throw new Error('`File` is not defined as a global, which is required for file uploads.' +
16396
+ (isOldNode ?
16397
+ " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`."
16398
+ : ''));
16399
+ }
16400
+ };
16401
+ /**
16402
+ * Construct a `File` instance. This is used to ensure a helpful error is thrown
16403
+ * for environments that don't define a global `File` yet.
16404
+ */
16405
+ function makeFile(fileBits, fileName, options) {
16406
+ checkFileSupport();
16407
+ return new File(fileBits, fileName !== null && fileName !== void 0 ? fileName : 'unknown_file', options);
16408
+ }
16409
+ function getName(value) {
16410
+ return (((typeof value === 'object' &&
16411
+ value !== null &&
16412
+ (('name' in value && value.name && String(value.name)) ||
16413
+ ('url' in value && value.url && String(value.url)) ||
16414
+ ('filename' in value && value.filename && String(value.filename)) ||
16415
+ ('path' in value && value.path && String(value.path)))) ||
16416
+ '')
16417
+ .split(/[\\/]/)
16418
+ .pop() || undefined);
16419
+ }
16420
+ const isAsyncIterable = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function';
16421
+
16422
+ /**
16423
+ * @license
16424
+ * Copyright 2025 Google LLC
16425
+ * SPDX-License-Identifier: Apache-2.0
16426
+ */
16427
+ /**
16428
+ * This check adds the arrayBuffer() method type because it is available and used at runtime
16429
+ */
16430
+ const isBlobLike = (value) => value != null &&
16431
+ typeof value === 'object' &&
16432
+ typeof value.size === 'number' &&
16433
+ typeof value.type === 'string' &&
16434
+ typeof value.text === 'function' &&
16435
+ typeof value.slice === 'function' &&
16436
+ typeof value.arrayBuffer === 'function';
16437
+ /**
16438
+ * This check adds the arrayBuffer() method type because it is available and used at runtime
16439
+ */
16440
+ const isFileLike = (value) => value != null &&
16441
+ typeof value === 'object' &&
16442
+ typeof value.name === 'string' &&
16443
+ typeof value.lastModified === 'number' &&
16444
+ isBlobLike(value);
16445
+ const isResponseLike = (value) => value != null &&
16446
+ typeof value === 'object' &&
16447
+ typeof value.url === 'string' &&
16448
+ typeof value.blob === 'function';
16449
+ /**
16450
+ * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats
16451
+ * @param value the raw content of the file. Can be an {@link Uploadable}, BlobLikePart, or AsyncIterable of BlobLikeParts
16452
+ * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible
16453
+ * @param {Object=} options additional properties
16454
+ * @param {string=} options.type the MIME type of the content
16455
+ * @param {number=} options.lastModified the last modified timestamp
16456
+ * @returns a {@link File} with the given properties
16457
+ */
16458
+ async function toFile(value, name, options) {
16459
+ checkFileSupport();
16460
+ // If it's a promise, resolve it.
16461
+ value = await value;
16462
+ // If we've been given a `File` we don't need to do anything
16463
+ if (isFileLike(value)) {
16464
+ if (value instanceof File) {
16465
+ return value;
16466
+ }
16467
+ return makeFile([await value.arrayBuffer()], value.name);
16468
+ }
16469
+ if (isResponseLike(value)) {
16470
+ const blob = await value.blob();
16471
+ name || (name = new URL(value.url).pathname.split(/[\\/]/).pop());
16472
+ return makeFile(await getBytes(blob), name, options);
16473
+ }
16474
+ const parts = await getBytes(value);
16475
+ name || (name = getName(value));
16476
+ if (!(options === null || options === void 0 ? void 0 : options.type)) {
16477
+ const type = parts.find((part) => typeof part === 'object' && 'type' in part && part.type);
16478
+ if (typeof type === 'string') {
16479
+ options = Object.assign(Object.assign({}, options), { type });
16480
+ }
16481
+ }
16482
+ return makeFile(parts, name, options);
16483
+ }
16484
+ async function getBytes(value) {
16485
+ var _a, e_1, _b, _c;
16486
+ var _d;
16487
+ let parts = [];
16488
+ if (typeof value === 'string' ||
16489
+ ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
16490
+ value instanceof ArrayBuffer) {
16491
+ parts.push(value);
16492
+ }
16493
+ else if (isBlobLike(value)) {
16494
+ parts.push(value instanceof Blob ? value : await value.arrayBuffer());
16495
+ }
16496
+ else if (isAsyncIterable(value) // includes Readable, ReadableStream, etc.
16497
+ ) {
16498
+ try {
16499
+ for (var _e = true, value_1 = __asyncValues(value), value_1_1; value_1_1 = await value_1.next(), _a = value_1_1.done, !_a; _e = true) {
16500
+ _c = value_1_1.value;
16501
+ _e = false;
16502
+ const chunk = _c;
16503
+ parts.push(...(await getBytes(chunk))); // TODO, consider validating?
16504
+ }
16505
+ }
16506
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
16507
+ finally {
16508
+ try {
16509
+ if (!_e && !_a && (_b = value_1.return)) await _b.call(value_1);
16510
+ }
16511
+ finally { if (e_1) throw e_1.error; }
16512
+ }
16513
+ }
16514
+ else {
16515
+ const constructor = (_d = value === null || value === void 0 ? void 0 : value.constructor) === null || _d === void 0 ? void 0 : _d.name;
16516
+ throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ''}${propsForError(value)}`);
16517
+ }
16518
+ return parts;
16519
+ }
16520
+ function propsForError(value) {
16521
+ if (typeof value !== 'object' || value === null)
16522
+ return '';
16523
+ const props = Object.getOwnPropertyNames(value);
16524
+ return `; props: [${props.map((p) => `"${p}"`).join(', ')}]`;
16525
+ }
16526
+
16527
+ /**
16528
+ * @license
16529
+ * Copyright 2025 Google LLC
16530
+ * SPDX-License-Identifier: Apache-2.0
16531
+ */
16532
+ class APIResource {
16533
+ constructor(client) {
16534
+ this._client = client;
16535
+ }
16536
+ }
16537
+ /**
16538
+ * The key path from the client. For example, a resource accessible as `client.resource.subresource` would
16539
+ * have a property `static override readonly _key = Object.freeze(['resource', 'subresource'] as const);`.
16540
+ */
16541
+ APIResource._key = [];
16542
+
16543
+ /**
16544
+ * @license
16545
+ * Copyright 2025 Google LLC
16546
+ * SPDX-License-Identifier: Apache-2.0
16547
+ */
16548
+ /**
16549
+ * Percent-encode everything that isn't safe to have in a path without encoding safe chars.
16550
+ *
16551
+ * Taken from https://datatracker.ietf.org/doc/html/rfc3986#section-3.3:
16552
+ * > unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
16553
+ * > sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
16554
+ * > pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
16555
+ */
16556
+ function encodeURIPath(str) {
16557
+ return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);
16558
+ }
16559
+ const EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null));
16560
+ const createPathTagFunction = (pathEncoder = encodeURIPath) => (function path(statics, ...params) {
16561
+ // If there are no params, no processing is needed.
16562
+ if (statics.length === 1)
16563
+ return statics[0];
16564
+ let postPath = false;
16565
+ const invalidSegments = [];
16566
+ const path = statics.reduce((previousValue, currentValue, index) => {
16567
+ var _a, _b, _c;
16568
+ if (/[?#]/.test(currentValue)) {
16569
+ postPath = true;
16570
+ }
16571
+ const value = params[index];
16572
+ let encoded = (postPath ? encodeURIComponent : pathEncoder)('' + value);
16573
+ if (index !== params.length &&
16574
+ (value == null ||
16575
+ (typeof value === 'object' &&
16576
+ // handle values from other realms
16577
+ value.toString ===
16578
+ ((_c = Object.getPrototypeOf((_b = Object.getPrototypeOf((_a = value.hasOwnProperty) !== null && _a !== void 0 ? _a : EMPTY)) !== null && _b !== void 0 ? _b : EMPTY)) === null || _c === void 0 ? void 0 : _c.toString)))) {
16579
+ encoded = value + '';
16580
+ invalidSegments.push({
16581
+ start: previousValue.length + currentValue.length,
16582
+ length: encoded.length,
16583
+ error: `Value of type ${Object.prototype.toString
16584
+ .call(value)
16585
+ .slice(8, -1)} is not a valid path parameter`,
16586
+ });
16587
+ }
16588
+ return previousValue + currentValue + (index === params.length ? '' : encoded);
16589
+ }, '');
16590
+ const pathOnly = path.split(/[?#]/, 1)[0];
16591
+ const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;
16592
+ let match;
16593
+ // Find all invalid segments
16594
+ while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) {
16595
+ invalidSegments.push({
16596
+ start: match.index,
16597
+ length: match[0].length,
16598
+ error: `Value "${match[0]}" can\'t be safely passed as a path parameter`,
16599
+ });
16600
+ }
16601
+ invalidSegments.sort((a, b) => a.start - b.start);
16602
+ if (invalidSegments.length > 0) {
16603
+ let lastEnd = 0;
16604
+ const underline = invalidSegments.reduce((acc, segment) => {
16605
+ const spaces = ' '.repeat(segment.start - lastEnd);
16606
+ const arrows = '^'.repeat(segment.length);
16607
+ lastEnd = segment.start + segment.length;
16608
+ return acc + spaces + arrows;
16609
+ }, '');
16610
+ throw new GeminiNextGenAPIClientError(`Path parameters result in path with invalid segments:\n${invalidSegments
16611
+ .map((e) => e.error)
16612
+ .join('\n')}\n${path}\n${underline}`);
16613
+ }
16614
+ return path;
16615
+ });
16616
+ /**
16617
+ * URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced.
16618
+ */
16619
+ const path = /* @__PURE__ */ createPathTagFunction(encodeURIPath);
16620
+
16621
+ /**
16622
+ * @license
16623
+ * Copyright 2025 Google LLC
16624
+ * SPDX-License-Identifier: Apache-2.0
16625
+ */
16626
+ class BaseInteractions extends APIResource {
16627
+ create(params, options) {
16628
+ var _a;
16629
+ const { api_version = this._client.apiVersion } = params, body = __rest(params, ["api_version"]);
16630
+ if ('model' in body && 'agent_config' in body) {
16631
+ throw new GeminiNextGenAPIClientError(`Invalid request: specified \`model\` and \`agent_config\`. If specifying \`model\`, use \`generation_config\`.`);
16632
+ }
16633
+ if ('agent' in body && 'generation_config' in body) {
16634
+ throw new GeminiNextGenAPIClientError(`Invalid request: specified \`agent\` and \`generation_config\`. If specifying \`agent\`, use \`agent_config\`.`);
16635
+ }
16636
+ return this._client.post(path `/${api_version}/interactions`, Object.assign(Object.assign({ body }, options), { stream: (_a = params.stream) !== null && _a !== void 0 ? _a : false }));
16637
+ }
16638
+ /**
16639
+ * Deletes the interaction by id.
16640
+ *
16641
+ * @example
16642
+ * ```ts
16643
+ * const interaction = await client.interactions.delete('id');
16644
+ * ```
16645
+ */
16646
+ delete(id, params = {}, options) {
16647
+ const { api_version = this._client.apiVersion } = params !== null && params !== void 0 ? params : {};
16648
+ return this._client.delete(path `/${api_version}/interactions/${id}`, options);
16649
+ }
16650
+ /**
16651
+ * Cancels an interaction by id. This only applies to background interactions that are still running.
16652
+ *
16653
+ * @example
16654
+ * ```ts
16655
+ * const interaction = await client.interactions.cancel('id');
16656
+ * ```
16657
+ */
16658
+ cancel(id, params = {}, options) {
16659
+ const { api_version = this._client.apiVersion } = params !== null && params !== void 0 ? params : {};
16660
+ return this._client.post(path `/${api_version}/interactions/${id}/cancel`, options);
16661
+ }
16662
+ get(id, params = {}, options) {
16663
+ var _a;
16664
+ const _b = params !== null && params !== void 0 ? params : {}, { api_version = this._client.apiVersion } = _b, query = __rest(_b, ["api_version"]);
16665
+ return this._client.get(path `/${api_version}/interactions/${id}`, Object.assign(Object.assign({ query }, options), { stream: (_a = params === null || params === void 0 ? void 0 : params.stream) !== null && _a !== void 0 ? _a : false }));
16666
+ }
16667
+ }
16668
+ BaseInteractions._key = Object.freeze(['interactions']);
16669
+ class Interactions extends BaseInteractions {
16670
+ }
16671
+
16672
+ /**
16673
+ * @license
16674
+ * Copyright 2025 Google LLC
16675
+ * SPDX-License-Identifier: Apache-2.0
16676
+ */
16677
+ function concatBytes(buffers) {
16678
+ let length = 0;
16679
+ for (const buffer of buffers) {
16680
+ length += buffer.length;
16681
+ }
16682
+ const output = new Uint8Array(length);
16683
+ let index = 0;
16684
+ for (const buffer of buffers) {
16685
+ output.set(buffer, index);
16686
+ index += buffer.length;
16687
+ }
16688
+ return output;
16689
+ }
16690
+ let encodeUTF8_;
16691
+ function encodeUTF8(str) {
16692
+ let encoder;
16693
+ return (encodeUTF8_ !== null && encodeUTF8_ !== void 0 ? encodeUTF8_ : ((encoder = new globalThis.TextEncoder()), (encodeUTF8_ = encoder.encode.bind(encoder))))(str);
16694
+ }
16695
+ let decodeUTF8_;
16696
+ function decodeUTF8(bytes) {
16697
+ let decoder;
16698
+ return (decodeUTF8_ !== null && decodeUTF8_ !== void 0 ? decodeUTF8_ : ((decoder = new globalThis.TextDecoder()), (decodeUTF8_ = decoder.decode.bind(decoder))))(bytes);
16699
+ }
16700
+
16701
+ /**
16702
+ * @license
16703
+ * Copyright 2025 Google LLC
16704
+ * SPDX-License-Identifier: Apache-2.0
16705
+ */
16706
+ /**
16707
+ * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally
16708
+ * reading lines from text.
16709
+ *
16710
+ * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258
16711
+ */
16712
+ class LineDecoder {
16713
+ constructor() {
16714
+ this.buffer = new Uint8Array();
16715
+ this.carriageReturnIndex = null;
16716
+ }
16717
+ decode(chunk) {
16718
+ if (chunk == null) {
16719
+ return [];
16720
+ }
16721
+ const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk)
16722
+ : typeof chunk === 'string' ? encodeUTF8(chunk)
16723
+ : chunk;
16724
+ this.buffer = concatBytes([this.buffer, binaryChunk]);
16725
+ const lines = [];
16726
+ let patternIndex;
16727
+ while ((patternIndex = findNewlineIndex(this.buffer, this.carriageReturnIndex)) != null) {
16728
+ if (patternIndex.carriage && this.carriageReturnIndex == null) {
16729
+ // skip until we either get a corresponding `\n`, a new `\r` or nothing
16730
+ this.carriageReturnIndex = patternIndex.index;
16731
+ continue;
16732
+ }
16733
+ // we got double \r or \rtext\n
16734
+ if (this.carriageReturnIndex != null &&
16735
+ (patternIndex.index !== this.carriageReturnIndex + 1 || patternIndex.carriage)) {
16736
+ lines.push(decodeUTF8(this.buffer.subarray(0, this.carriageReturnIndex - 1)));
16737
+ this.buffer = this.buffer.subarray(this.carriageReturnIndex);
16738
+ this.carriageReturnIndex = null;
16739
+ continue;
16740
+ }
16741
+ const endIndex = this.carriageReturnIndex !== null ? patternIndex.preceding - 1 : patternIndex.preceding;
16742
+ const line = decodeUTF8(this.buffer.subarray(0, endIndex));
16743
+ lines.push(line);
16744
+ this.buffer = this.buffer.subarray(patternIndex.index);
16745
+ this.carriageReturnIndex = null;
16746
+ }
16747
+ return lines;
16748
+ }
16749
+ flush() {
16750
+ if (!this.buffer.length) {
16751
+ return [];
16752
+ }
16753
+ return this.decode('\n');
16754
+ }
16755
+ }
16756
+ // prettier-ignore
16757
+ LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r']);
16758
+ LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
16759
+ /**
16760
+ * This function searches the buffer for the end patterns, (\r or \n)
16761
+ * and returns an object with the index preceding the matched newline and the
16762
+ * index after the newline char. `null` is returned if no new line is found.
16763
+ *
16764
+ * ```ts
16765
+ * findNewLineIndex('abc\ndef') -> { preceding: 2, index: 3 }
16766
+ * ```
16767
+ */
16768
+ function findNewlineIndex(buffer, startIndex) {
16769
+ const newline = 0x0a; // \n
16770
+ const carriage = 0x0d; // \r
16771
+ for (let i = startIndex !== null && startIndex !== void 0 ? startIndex : 0; i < buffer.length; i++) {
16772
+ if (buffer[i] === newline) {
16773
+ return { preceding: i, index: i + 1, carriage: false };
16774
+ }
16775
+ if (buffer[i] === carriage) {
16776
+ return { preceding: i, index: i + 1, carriage: true };
16777
+ }
16778
+ }
16779
+ return null;
16780
+ }
16781
+ function findDoubleNewlineIndex(buffer) {
16782
+ // This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n)
16783
+ // and returns the index right after the first occurrence of any pattern,
16784
+ // or -1 if none of the patterns are found.
16785
+ const newline = 0x0a; // \n
16786
+ const carriage = 0x0d; // \r
16787
+ for (let i = 0; i < buffer.length - 1; i++) {
16788
+ if (buffer[i] === newline && buffer[i + 1] === newline) {
16789
+ // \n\n
16790
+ return i + 2;
16791
+ }
16792
+ if (buffer[i] === carriage && buffer[i + 1] === carriage) {
16793
+ // \r\r
16794
+ return i + 2;
16795
+ }
16796
+ if (buffer[i] === carriage &&
16797
+ buffer[i + 1] === newline &&
16798
+ i + 3 < buffer.length &&
16799
+ buffer[i + 2] === carriage &&
16800
+ buffer[i + 3] === newline) {
16801
+ // \r\n\r\n
16802
+ return i + 4;
16803
+ }
16804
+ }
16805
+ return -1;
16806
+ }
16807
+
16808
+ /**
16809
+ * @license
16810
+ * Copyright 2025 Google LLC
16811
+ * SPDX-License-Identifier: Apache-2.0
16812
+ */
16813
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
16814
+ const levelNumbers = {
16815
+ off: 0,
16816
+ error: 200,
16817
+ warn: 300,
16818
+ info: 400,
16819
+ debug: 500,
16820
+ };
16821
+ const parseLogLevel = (maybeLevel, sourceName, client) => {
16822
+ if (!maybeLevel) {
16823
+ return undefined;
16824
+ }
16825
+ if (hasOwn(levelNumbers, maybeLevel)) {
16826
+ return maybeLevel;
16827
+ }
16828
+ loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`);
16829
+ return undefined;
16830
+ };
16831
+ function noop() { }
16832
+ function makeLogFn(fnLevel, logger, logLevel) {
16833
+ if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) {
16834
+ return noop;
16835
+ }
16836
+ else {
16837
+ // Don't wrap logger functions, we want the stacktrace intact!
16838
+ return logger[fnLevel].bind(logger);
16839
+ }
16840
+ }
16841
+ const noopLogger = {
16842
+ error: noop,
16843
+ warn: noop,
16844
+ info: noop,
16845
+ debug: noop,
16846
+ };
16847
+ let cachedLoggers = /* @__PURE__ */ new WeakMap();
16848
+ function loggerFor(client) {
16849
+ var _a;
16850
+ const logger = client.logger;
16851
+ const logLevel = (_a = client.logLevel) !== null && _a !== void 0 ? _a : 'off';
16852
+ if (!logger) {
16853
+ return noopLogger;
16854
+ }
16855
+ const cachedLogger = cachedLoggers.get(logger);
16856
+ if (cachedLogger && cachedLogger[0] === logLevel) {
16857
+ return cachedLogger[1];
16858
+ }
16859
+ const levelLogger = {
16860
+ error: makeLogFn('error', logger, logLevel),
16861
+ warn: makeLogFn('warn', logger, logLevel),
16862
+ info: makeLogFn('info', logger, logLevel),
16863
+ debug: makeLogFn('debug', logger, logLevel),
16864
+ };
16865
+ cachedLoggers.set(logger, [logLevel, levelLogger]);
16866
+ return levelLogger;
16867
+ }
16868
+ const formatRequestDetails = (details) => {
16869
+ if (details.options) {
16870
+ details.options = Object.assign({}, details.options);
16871
+ delete details.options['headers']; // redundant + leaks internals
16872
+ }
16873
+ if (details.headers) {
16874
+ details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [
16875
+ name,
16876
+ (name.toLowerCase() === 'x-goog-api-key' ||
16877
+ name.toLowerCase() === 'authorization' ||
16878
+ name.toLowerCase() === 'cookie' ||
16879
+ name.toLowerCase() === 'set-cookie') ?
16880
+ '***'
16881
+ : value,
16882
+ ]));
16883
+ }
16884
+ if ('retryOfRequestLogID' in details) {
16885
+ if (details.retryOfRequestLogID) {
16886
+ details.retryOf = details.retryOfRequestLogID;
16887
+ }
16888
+ delete details.retryOfRequestLogID;
16889
+ }
16890
+ return details;
16891
+ };
16892
+
16893
+ /**
16894
+ * @license
16895
+ * Copyright 2025 Google LLC
16896
+ * SPDX-License-Identifier: Apache-2.0
16897
+ */
16898
+ class Stream {
16899
+ constructor(iterator, controller, client) {
16900
+ this.iterator = iterator;
16901
+ this.controller = controller;
16902
+ this.client = client;
16903
+ }
16904
+ static fromSSEResponse(response, controller, client) {
16905
+ let consumed = false;
16906
+ const logger = client ? loggerFor(client) : console;
16907
+ function iterator() {
16908
+ return __asyncGenerator(this, arguments, function* iterator_1() {
16909
+ var _a, e_1, _b, _c;
16910
+ if (consumed) {
16911
+ throw new GeminiNextGenAPIClientError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
16912
+ }
16913
+ consumed = true;
16914
+ let done = false;
16915
+ try {
16916
+ try {
16917
+ for (var _d = true, _e = __asyncValues(_iterSSEMessages(response, controller)), _f; _f = yield __await(_e.next()), _a = _f.done, !_a; _d = true) {
16918
+ _c = _f.value;
16919
+ _d = false;
16920
+ const sse = _c;
16921
+ if (done)
16922
+ continue;
16923
+ if (sse.data.startsWith('[DONE]')) {
16924
+ done = true;
16925
+ continue;
16926
+ }
16927
+ else {
16928
+ try {
16929
+ // @ts-ignore
16930
+ yield yield __await(JSON.parse(sse.data));
16931
+ }
16932
+ catch (e) {
16933
+ logger.error(`Could not parse message into JSON:`, sse.data);
16934
+ logger.error(`From chunk:`, sse.raw);
16935
+ throw e;
16936
+ }
16937
+ }
16938
+ }
16939
+ }
16940
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
16941
+ finally {
16942
+ try {
16943
+ if (!_d && !_a && (_b = _e.return)) yield __await(_b.call(_e));
16944
+ }
16945
+ finally { if (e_1) throw e_1.error; }
16946
+ }
16947
+ done = true;
16948
+ }
16949
+ catch (e) {
16950
+ // If the user calls `stream.controller.abort()`, we should exit without throwing.
16951
+ if (isAbortError(e))
16952
+ return yield __await(void 0);
16953
+ throw e;
16954
+ }
16955
+ finally {
16956
+ // If the user `break`s, abort the ongoing request.
16957
+ if (!done)
16958
+ controller.abort();
16959
+ }
16960
+ });
16961
+ }
16962
+ return new Stream(iterator, controller, client);
16963
+ }
16964
+ /**
16965
+ * Generates a Stream from a newline-separated ReadableStream
16966
+ * where each item is a JSON value.
16967
+ */
16968
+ static fromReadableStream(readableStream, controller, client) {
16969
+ let consumed = false;
16970
+ function iterLines() {
16971
+ return __asyncGenerator(this, arguments, function* iterLines_1() {
16972
+ var _a, e_2, _b, _c;
16973
+ const lineDecoder = new LineDecoder();
16974
+ const iter = ReadableStreamToAsyncIterable(readableStream);
16975
+ try {
16976
+ for (var _d = true, iter_1 = __asyncValues(iter), iter_1_1; iter_1_1 = yield __await(iter_1.next()), _a = iter_1_1.done, !_a; _d = true) {
16977
+ _c = iter_1_1.value;
16978
+ _d = false;
16979
+ const chunk = _c;
16980
+ for (const line of lineDecoder.decode(chunk)) {
16981
+ yield yield __await(line);
16982
+ }
16983
+ }
16984
+ }
16985
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
16986
+ finally {
16987
+ try {
16988
+ if (!_d && !_a && (_b = iter_1.return)) yield __await(_b.call(iter_1));
16989
+ }
16990
+ finally { if (e_2) throw e_2.error; }
16991
+ }
16992
+ for (const line of lineDecoder.flush()) {
16993
+ yield yield __await(line);
16994
+ }
16995
+ });
16996
+ }
16997
+ function iterator() {
16998
+ return __asyncGenerator(this, arguments, function* iterator_2() {
16999
+ var _a, e_3, _b, _c;
17000
+ if (consumed) {
17001
+ throw new GeminiNextGenAPIClientError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
17002
+ }
17003
+ consumed = true;
17004
+ let done = false;
17005
+ try {
17006
+ try {
17007
+ for (var _d = true, _e = __asyncValues(iterLines()), _f; _f = yield __await(_e.next()), _a = _f.done, !_a; _d = true) {
17008
+ _c = _f.value;
17009
+ _d = false;
17010
+ const line = _c;
17011
+ if (done)
17012
+ continue;
17013
+ // @ts-ignore
17014
+ if (line)
17015
+ yield yield __await(JSON.parse(line));
17016
+ }
17017
+ }
17018
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
17019
+ finally {
17020
+ try {
17021
+ if (!_d && !_a && (_b = _e.return)) yield __await(_b.call(_e));
17022
+ }
17023
+ finally { if (e_3) throw e_3.error; }
17024
+ }
17025
+ done = true;
17026
+ }
17027
+ catch (e) {
17028
+ // If the user calls `stream.controller.abort()`, we should exit without throwing.
17029
+ if (isAbortError(e))
17030
+ return yield __await(void 0);
17031
+ throw e;
17032
+ }
17033
+ finally {
17034
+ // If the user `break`s, abort the ongoing request.
17035
+ if (!done)
17036
+ controller.abort();
17037
+ }
17038
+ });
17039
+ }
17040
+ return new Stream(iterator, controller, client);
17041
+ }
17042
+ [Symbol.asyncIterator]() {
17043
+ return this.iterator();
17044
+ }
17045
+ /**
17046
+ * Splits the stream into two streams which can be
17047
+ * independently read from at different speeds.
17048
+ */
17049
+ tee() {
17050
+ const left = [];
17051
+ const right = [];
17052
+ const iterator = this.iterator();
17053
+ const teeIterator = (queue) => {
17054
+ return {
17055
+ next: () => {
17056
+ if (queue.length === 0) {
17057
+ const result = iterator.next();
17058
+ left.push(result);
17059
+ right.push(result);
17060
+ }
17061
+ return queue.shift();
17062
+ },
17063
+ };
17064
+ };
17065
+ return [
17066
+ new Stream(() => teeIterator(left), this.controller, this.client),
17067
+ new Stream(() => teeIterator(right), this.controller, this.client),
17068
+ ];
17069
+ }
17070
+ /**
17071
+ * Converts this stream to a newline-separated ReadableStream of
17072
+ * JSON stringified values in the stream
17073
+ * which can be turned back into a Stream with `Stream.fromReadableStream()`.
17074
+ */
17075
+ toReadableStream() {
17076
+ const self = this;
17077
+ let iter;
17078
+ return makeReadableStream({
17079
+ async start() {
17080
+ iter = self[Symbol.asyncIterator]();
17081
+ },
17082
+ async pull(ctrl) {
17083
+ try {
17084
+ const { value, done } = await iter.next();
17085
+ if (done)
17086
+ return ctrl.close();
17087
+ const bytes = encodeUTF8(JSON.stringify(value) + '\n');
17088
+ ctrl.enqueue(bytes);
17089
+ }
17090
+ catch (err) {
17091
+ ctrl.error(err);
17092
+ }
17093
+ },
17094
+ async cancel() {
17095
+ var _a;
17096
+ await ((_a = iter.return) === null || _a === void 0 ? void 0 : _a.call(iter));
17097
+ },
17098
+ });
17099
+ }
17100
+ }
17101
+ function _iterSSEMessages(response, controller) {
17102
+ return __asyncGenerator(this, arguments, function* _iterSSEMessages_1() {
17103
+ var _a, e_4, _b, _c;
17104
+ if (!response.body) {
17105
+ controller.abort();
17106
+ if (typeof globalThis.navigator !== 'undefined' &&
17107
+ globalThis.navigator.product === 'ReactNative') {
17108
+ throw new GeminiNextGenAPIClientError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
17109
+ }
17110
+ throw new GeminiNextGenAPIClientError(`Attempted to iterate over a response with no body`);
17111
+ }
17112
+ const sseDecoder = new SSEDecoder();
17113
+ const lineDecoder = new LineDecoder();
17114
+ const iter = ReadableStreamToAsyncIterable(response.body);
17115
+ try {
17116
+ for (var _d = true, _e = __asyncValues(iterSSEChunks(iter)), _f; _f = yield __await(_e.next()), _a = _f.done, !_a; _d = true) {
17117
+ _c = _f.value;
17118
+ _d = false;
17119
+ const sseChunk = _c;
17120
+ for (const line of lineDecoder.decode(sseChunk)) {
17121
+ const sse = sseDecoder.decode(line);
17122
+ if (sse)
17123
+ yield yield __await(sse);
17124
+ }
17125
+ }
17126
+ }
17127
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
17128
+ finally {
17129
+ try {
17130
+ if (!_d && !_a && (_b = _e.return)) yield __await(_b.call(_e));
17131
+ }
17132
+ finally { if (e_4) throw e_4.error; }
17133
+ }
17134
+ for (const line of lineDecoder.flush()) {
17135
+ const sse = sseDecoder.decode(line);
17136
+ if (sse)
17137
+ yield yield __await(sse);
17138
+ }
17139
+ });
17140
+ }
17141
+ /**
17142
+ * Given an async iterable iterator, iterates over it and yields full
17143
+ * SSE chunks, i.e. yields when a double new-line is encountered.
17144
+ */
17145
+ function iterSSEChunks(iterator) {
17146
+ return __asyncGenerator(this, arguments, function* iterSSEChunks_1() {
17147
+ var _a, e_5, _b, _c;
17148
+ let data = new Uint8Array();
17149
+ try {
17150
+ for (var _d = true, iterator_3 = __asyncValues(iterator), iterator_3_1; iterator_3_1 = yield __await(iterator_3.next()), _a = iterator_3_1.done, !_a; _d = true) {
17151
+ _c = iterator_3_1.value;
17152
+ _d = false;
17153
+ const chunk = _c;
17154
+ if (chunk == null) {
17155
+ continue;
17156
+ }
17157
+ const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk)
17158
+ : typeof chunk === 'string' ? encodeUTF8(chunk)
17159
+ : chunk;
17160
+ let newData = new Uint8Array(data.length + binaryChunk.length);
17161
+ newData.set(data);
17162
+ newData.set(binaryChunk, data.length);
17163
+ data = newData;
17164
+ let patternIndex;
17165
+ while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {
17166
+ yield yield __await(data.slice(0, patternIndex));
17167
+ data = data.slice(patternIndex);
17168
+ }
17169
+ }
17170
+ }
17171
+ catch (e_5_1) { e_5 = { error: e_5_1 }; }
17172
+ finally {
17173
+ try {
17174
+ if (!_d && !_a && (_b = iterator_3.return)) yield __await(_b.call(iterator_3));
17175
+ }
17176
+ finally { if (e_5) throw e_5.error; }
17177
+ }
17178
+ if (data.length > 0) {
17179
+ yield yield __await(data);
17180
+ }
17181
+ });
17182
+ }
17183
+ class SSEDecoder {
17184
+ constructor() {
17185
+ this.event = null;
17186
+ this.data = [];
17187
+ this.chunks = [];
17188
+ }
17189
+ decode(line) {
17190
+ if (line.endsWith('\r')) {
17191
+ line = line.substring(0, line.length - 1);
17192
+ }
17193
+ if (!line) {
17194
+ // empty line and we didn't previously encounter any messages
17195
+ if (!this.event && !this.data.length)
17196
+ return null;
17197
+ const sse = {
17198
+ event: this.event,
17199
+ data: this.data.join('\n'),
17200
+ raw: this.chunks,
17201
+ };
17202
+ this.event = null;
17203
+ this.data = [];
17204
+ this.chunks = [];
17205
+ return sse;
17206
+ }
17207
+ this.chunks.push(line);
17208
+ if (line.startsWith(':')) {
17209
+ return null;
17210
+ }
17211
+ let [fieldname, _, value] = partition(line, ':');
17212
+ if (value.startsWith(' ')) {
17213
+ value = value.substring(1);
17214
+ }
17215
+ if (fieldname === 'event') {
17216
+ this.event = value;
17217
+ }
17218
+ else if (fieldname === 'data') {
17219
+ this.data.push(value);
17220
+ }
17221
+ return null;
17222
+ }
17223
+ }
17224
+ function partition(str, delimiter) {
17225
+ const index = str.indexOf(delimiter);
17226
+ if (index !== -1) {
17227
+ return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];
17228
+ }
17229
+ return [str, '', ''];
17230
+ }
17231
+
17232
+ /**
17233
+ * @license
17234
+ * Copyright 2025 Google LLC
17235
+ * SPDX-License-Identifier: Apache-2.0
17236
+ */
17237
+ async function defaultParseResponse(client, props) {
17238
+ const { response, requestLogID, retryOfRequestLogID, startTime } = props;
17239
+ const body = await (async () => {
17240
+ var _a;
17241
+ if (props.options.stream) {
17242
+ loggerFor(client).debug('response', response.status, response.url, response.headers, response.body);
17243
+ // Note: there is an invariant here that isn't represented in the type system
17244
+ // that if you set `stream: true` the response type must also be `Stream<T>`
17245
+ if (props.options.__streamClass) {
17246
+ return props.options.__streamClass.fromSSEResponse(response, props.controller, client);
17247
+ }
17248
+ return Stream.fromSSEResponse(response, props.controller, client);
17249
+ }
17250
+ // fetch refuses to read the body when the status code is 204.
17251
+ if (response.status === 204) {
17252
+ return null;
17253
+ }
17254
+ if (props.options.__binaryResponse) {
17255
+ return response;
17256
+ }
17257
+ const contentType = response.headers.get('content-type');
17258
+ const mediaType = (_a = contentType === null || contentType === void 0 ? void 0 : contentType.split(';')[0]) === null || _a === void 0 ? void 0 : _a.trim();
17259
+ const isJSON = (mediaType === null || mediaType === void 0 ? void 0 : mediaType.includes('application/json')) || (mediaType === null || mediaType === void 0 ? void 0 : mediaType.endsWith('+json'));
17260
+ if (isJSON) {
17261
+ const json = await response.json();
17262
+ return json;
17263
+ }
17264
+ const text = await response.text();
17265
+ return text;
17266
+ })();
17267
+ loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({
17268
+ retryOfRequestLogID,
17269
+ url: response.url,
17270
+ status: response.status,
17271
+ body,
17272
+ durationMs: Date.now() - startTime,
17273
+ }));
17274
+ return body;
17275
+ }
17276
+
17277
+ /**
17278
+ * @license
17279
+ * Copyright 2025 Google LLC
17280
+ * SPDX-License-Identifier: Apache-2.0
17281
+ */
17282
+ /**
17283
+ * A subclass of `Promise` providing additional helper methods
17284
+ * for interacting with the SDK.
17285
+ */
17286
+ class APIPromise extends Promise {
17287
+ constructor(client, responsePromise, parseResponse = defaultParseResponse) {
17288
+ super((resolve) => {
17289
+ // this is maybe a bit weird but this has to be a no-op to not implicitly
17290
+ // parse the response body; instead .then, .catch, .finally are overridden
17291
+ // to parse the response
17292
+ resolve(null);
17293
+ });
17294
+ this.responsePromise = responsePromise;
17295
+ this.parseResponse = parseResponse;
17296
+ this.client = client;
17297
+ }
17298
+ _thenUnwrap(transform) {
17299
+ return new APIPromise(this.client, this.responsePromise, async (client, props) => transform(await this.parseResponse(client, props), props));
17300
+ }
17301
+ /**
17302
+ * Gets the raw `Response` instance instead of parsing the response
17303
+ * data.
17304
+ *
17305
+ * If you want to parse the response body but still get the `Response`
17306
+ * instance, you can use {@link withResponse()}.
17307
+ *
17308
+ * 👋 Getting the wrong TypeScript type for `Response`?
17309
+ * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
17310
+ * to your `tsconfig.json`.
17311
+ */
17312
+ asResponse() {
17313
+ return this.responsePromise.then((p) => p.response);
17314
+ }
17315
+ /**
17316
+ * Gets the parsed response data and the raw `Response` instance.
17317
+ *
17318
+ * If you just want to get the raw `Response` instance without parsing it,
17319
+ * you can use {@link asResponse()}.
17320
+ *
17321
+ * 👋 Getting the wrong TypeScript type for `Response`?
17322
+ * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
17323
+ * to your `tsconfig.json`.
17324
+ */
17325
+ async withResponse() {
17326
+ const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
17327
+ return { data, response };
17328
+ }
17329
+ parse() {
17330
+ if (!this.parsedPromise) {
17331
+ this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(this.client, data));
17332
+ }
17333
+ return this.parsedPromise;
17334
+ }
17335
+ then(onfulfilled, onrejected) {
17336
+ return this.parse().then(onfulfilled, onrejected);
17337
+ }
17338
+ catch(onrejected) {
17339
+ return this.parse().catch(onrejected);
17340
+ }
17341
+ finally(onfinally) {
17342
+ return this.parse().finally(onfinally);
17343
+ }
17344
+ }
17345
+
17346
+ /**
17347
+ * @license
17348
+ * Copyright 2025 Google LLC
17349
+ * SPDX-License-Identifier: Apache-2.0
17350
+ */
17351
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
17352
+ const brand_privateNullableHeaders = /* @__PURE__ */ Symbol('brand.privateNullableHeaders');
17353
+ function* iterateHeaders(headers) {
17354
+ if (!headers)
17355
+ return;
17356
+ if (brand_privateNullableHeaders in headers) {
17357
+ const { values, nulls } = headers;
17358
+ yield* values.entries();
17359
+ for (const name of nulls) {
17360
+ yield [name, null];
17361
+ }
17362
+ return;
17363
+ }
17364
+ let shouldClear = false;
17365
+ let iter;
17366
+ if (headers instanceof Headers) {
17367
+ iter = headers.entries();
17368
+ }
17369
+ else if (isReadonlyArray(headers)) {
17370
+ iter = headers;
17371
+ }
17372
+ else {
17373
+ shouldClear = true;
17374
+ iter = Object.entries(headers !== null && headers !== void 0 ? headers : {});
17375
+ }
17376
+ for (let row of iter) {
17377
+ const name = row[0];
17378
+ if (typeof name !== 'string')
17379
+ throw new TypeError('expected header name to be a string');
17380
+ const values = isReadonlyArray(row[1]) ? row[1] : [row[1]];
17381
+ let didClear = false;
17382
+ for (const value of values) {
17383
+ if (value === undefined)
17384
+ continue;
17385
+ // Objects keys always overwrite older headers, they never append.
17386
+ // Yield a null to clear the header before adding the new values.
17387
+ if (shouldClear && !didClear) {
17388
+ didClear = true;
17389
+ yield [name, null];
17390
+ }
17391
+ yield [name, value];
17392
+ }
17393
+ }
17394
+ }
17395
+ const buildHeaders = (newHeaders) => {
17396
+ const targetHeaders = new Headers();
17397
+ const nullHeaders = new Set();
17398
+ for (const headers of newHeaders) {
17399
+ const seenHeaders = new Set();
17400
+ for (const [name, value] of iterateHeaders(headers)) {
17401
+ const lowerName = name.toLowerCase();
17402
+ if (!seenHeaders.has(lowerName)) {
17403
+ targetHeaders.delete(name);
17404
+ seenHeaders.add(lowerName);
17405
+ }
17406
+ if (value === null) {
17407
+ targetHeaders.delete(name);
17408
+ nullHeaders.add(lowerName);
17409
+ }
17410
+ else {
17411
+ targetHeaders.append(name, value);
17412
+ nullHeaders.delete(lowerName);
17413
+ }
17414
+ }
17415
+ }
17416
+ return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders };
17417
+ };
17418
+
17419
+ /**
17420
+ * @license
17421
+ * Copyright 2025 Google LLC
17422
+ * SPDX-License-Identifier: Apache-2.0
17423
+ */
17424
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
17425
+ /**
17426
+ * Read an environment variable.
17427
+ *
17428
+ * Trims beginning and trailing whitespace.
17429
+ *
17430
+ * Will return undefined if the environment variable doesn't exist or cannot be accessed.
17431
+ */
17432
+ const readEnv = (env) => {
17433
+ var _a, _b, _c, _d, _e, _f;
17434
+ if (typeof globalThis.process !== 'undefined') {
17435
+ return (_c = (_b = (_a = globalThis.process.env) === null || _a === void 0 ? void 0 : _a[env]) === null || _b === void 0 ? void 0 : _b.trim()) !== null && _c !== void 0 ? _c : undefined;
17436
+ }
17437
+ if (typeof globalThis.Deno !== 'undefined') {
17438
+ return (_f = (_e = (_d = globalThis.Deno.env) === null || _d === void 0 ? void 0 : _d.get) === null || _e === void 0 ? void 0 : _e.call(_d, env)) === null || _f === void 0 ? void 0 : _f.trim();
17439
+ }
17440
+ return undefined;
17441
+ };
17442
+
17443
+ /**
17444
+ * @license
17445
+ * Copyright 2025 Google LLC
17446
+ * SPDX-License-Identifier: Apache-2.0
17447
+ */
17448
+ var _a;
17449
+ /**
17450
+ * Base class for Gemini Next Gen API API clients.
17451
+ */
17452
+ class BaseGeminiNextGenAPIClient {
17453
+ /**
17454
+ * API Client for interfacing with the Gemini Next Gen API API.
17455
+ *
17456
+ * @param {string | null | undefined} [opts.apiKey=process.env['GEMINI_API_KEY'] ?? null]
17457
+ * @param {string | undefined} [opts.apiVersion=v1beta]
17458
+ * @param {string} [opts.baseURL=process.env['GEMINI_NEXT_GEN_API_BASE_URL'] ?? https://generativelanguage.googleapis.com] - Override the default base URL for the API.
17459
+ * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
17460
+ * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
17461
+ * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
17462
+ * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
17463
+ * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
17464
+ * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
17465
+ */
17466
+ constructor(_b) {
17467
+ var _c, _d, _e, _f, _g, _h, _j;
17468
+ var _k = _b === void 0 ? {} : _b, { baseURL = readEnv('GEMINI_NEXT_GEN_API_BASE_URL'), apiKey = (_c = readEnv('GEMINI_API_KEY')) !== null && _c !== void 0 ? _c : null, apiVersion = 'v1beta' } = _k, opts = __rest(_k, ["baseURL", "apiKey", "apiVersion"]);
17469
+ const options = Object.assign(Object.assign({ apiKey,
17470
+ apiVersion }, opts), { baseURL: baseURL || `https://generativelanguage.googleapis.com` });
17471
+ this.baseURL = options.baseURL;
17472
+ this.timeout = (_d = options.timeout) !== null && _d !== void 0 ? _d : BaseGeminiNextGenAPIClient.DEFAULT_TIMEOUT /* 1 minute */;
17473
+ this.logger = (_e = options.logger) !== null && _e !== void 0 ? _e : console;
17474
+ const defaultLogLevel = 'warn';
17475
+ // Set default logLevel early so that we can log a warning in parseLogLevel.
17476
+ this.logLevel = defaultLogLevel;
17477
+ this.logLevel =
17478
+ (_g = (_f = parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this)) !== null && _f !== void 0 ? _f : parseLogLevel(readEnv('GEMINI_NEXT_GEN_API_LOG'), "process.env['GEMINI_NEXT_GEN_API_LOG']", this)) !== null && _g !== void 0 ? _g : defaultLogLevel;
17479
+ this.fetchOptions = options.fetchOptions;
17480
+ this.maxRetries = (_h = options.maxRetries) !== null && _h !== void 0 ? _h : 2;
17481
+ this.fetch = (_j = options.fetch) !== null && _j !== void 0 ? _j : getDefaultFetch();
17482
+ this.encoder = FallbackEncoder;
17483
+ this._options = options;
17484
+ this.apiKey = apiKey;
17485
+ this.apiVersion = apiVersion;
17486
+ }
17487
+ /**
17488
+ * Create a new client instance re-using the same options given to the current client with optional overriding.
17489
+ */
17490
+ withOptions(options) {
17491
+ const client = new this.constructor(Object.assign(Object.assign(Object.assign({}, this._options), { baseURL: this.baseURL, maxRetries: this.maxRetries, timeout: this.timeout, logger: this.logger, logLevel: this.logLevel, fetch: this.fetch, fetchOptions: this.fetchOptions, apiKey: this.apiKey, apiVersion: this.apiVersion }), options));
17492
+ return client;
17493
+ }
17494
+ /**
17495
+ * Check whether the base URL is set to its default.
17496
+ */
17497
+ baseURLOverridden() {
17498
+ return this.baseURL !== 'https://generativelanguage.googleapis.com';
17499
+ }
17500
+ defaultQuery() {
17501
+ return this._options.defaultQuery;
17502
+ }
17503
+ validateHeaders({ values, nulls }) {
17504
+ if (this.apiKey && values.get('x-goog-api-key')) {
17505
+ return;
17506
+ }
17507
+ if (nulls.has('x-goog-api-key')) {
17508
+ return;
17509
+ }
17510
+ throw new Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "x-goog-api-key" headers to be explicitly omitted');
17511
+ }
17512
+ async authHeaders(opts) {
17513
+ if (this.apiKey == null) {
17514
+ return undefined;
17515
+ }
17516
+ return buildHeaders([{ 'x-goog-api-key': this.apiKey }]);
17517
+ }
17518
+ /**
17519
+ * Basic re-implementation of `qs.stringify` for primitive types.
17520
+ */
17521
+ stringifyQuery(query) {
17522
+ return Object.entries(query)
17523
+ .filter(([_, value]) => typeof value !== 'undefined')
17524
+ .map(([key, value]) => {
17525
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
17526
+ return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
17527
+ }
17528
+ if (value === null) {
17529
+ return `${encodeURIComponent(key)}=`;
17530
+ }
17531
+ throw new GeminiNextGenAPIClientError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
17532
+ })
17533
+ .join('&');
17534
+ }
17535
+ getUserAgent() {
17536
+ return `${this.constructor.name}/JS ${VERSION}`;
17537
+ }
17538
+ defaultIdempotencyKey() {
17539
+ return `stainless-node-retry-${uuid4()}`;
17540
+ }
17541
+ makeStatusError(status, error, message, headers) {
17542
+ return APIError.generate(status, error, message, headers);
17543
+ }
17544
+ buildURL(path, query, defaultBaseURL) {
17545
+ const baseURL = (!this.baseURLOverridden() && defaultBaseURL) || this.baseURL;
17546
+ const url = isAbsoluteURL(path) ?
17547
+ new URL(path)
17548
+ : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
17549
+ const defaultQuery = this.defaultQuery();
17550
+ if (!isEmptyObj(defaultQuery)) {
17551
+ query = Object.assign(Object.assign({}, defaultQuery), query);
17552
+ }
17553
+ if (typeof query === 'object' && query && !Array.isArray(query)) {
17554
+ url.search = this.stringifyQuery(query);
17555
+ }
17556
+ return url.toString();
17557
+ }
17558
+ /**
17559
+ * Used as a callback for mutating the given `FinalRequestOptions` object.
17560
+ */
17561
+ async prepareOptions(options) { }
17562
+ /**
17563
+ * Used as a callback for mutating the given `RequestInit` object.
17564
+ *
17565
+ * This is useful for cases where you want to add certain headers based off of
17566
+ * the request properties, e.g. `method` or `url`.
17567
+ */
17568
+ async prepareRequest(request, { url, options }) { }
17569
+ get(path, opts) {
17570
+ return this.methodRequest('get', path, opts);
17571
+ }
17572
+ post(path, opts) {
17573
+ return this.methodRequest('post', path, opts);
17574
+ }
17575
+ patch(path, opts) {
17576
+ return this.methodRequest('patch', path, opts);
17577
+ }
17578
+ put(path, opts) {
17579
+ return this.methodRequest('put', path, opts);
17580
+ }
17581
+ delete(path, opts) {
17582
+ return this.methodRequest('delete', path, opts);
17583
+ }
17584
+ methodRequest(method, path, opts) {
17585
+ return this.request(Promise.resolve(opts).then((opts) => {
17586
+ return Object.assign({ method, path }, opts);
17587
+ }));
17588
+ }
17589
+ request(options, remainingRetries = null) {
17590
+ return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
17591
+ }
17592
+ async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
17593
+ var _b, _c, _d;
17594
+ const options = await optionsInput;
17595
+ const maxRetries = (_b = options.maxRetries) !== null && _b !== void 0 ? _b : this.maxRetries;
17596
+ if (retriesRemaining == null) {
17597
+ retriesRemaining = maxRetries;
17598
+ }
17599
+ await this.prepareOptions(options);
17600
+ const { req, url, timeout } = await this.buildRequest(options, {
17601
+ retryCount: maxRetries - retriesRemaining,
17602
+ });
17603
+ await this.prepareRequest(req, { url, options });
17604
+ /** Not an API request ID, just for correlating local log entries. */
17605
+ const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
17606
+ const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
17607
+ const startTime = Date.now();
17608
+ loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
17609
+ retryOfRequestLogID,
17610
+ method: options.method,
17611
+ url,
17612
+ options,
17613
+ headers: req.headers,
17614
+ }));
17615
+ if ((_c = options.signal) === null || _c === void 0 ? void 0 : _c.aborted) {
17616
+ throw new APIUserAbortError();
17617
+ }
17618
+ const controller = new AbortController();
17619
+ const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
17620
+ const headersTime = Date.now();
17621
+ if (response instanceof globalThis.Error) {
17622
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
17623
+ if ((_d = options.signal) === null || _d === void 0 ? void 0 : _d.aborted) {
17624
+ throw new APIUserAbortError();
17625
+ }
17626
+ // detect native connection timeout errors
17627
+ // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)"
17628
+ // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
17629
+ // others do not provide enough information to distinguish timeouts from other connection errors
17630
+ const isTimeout = isAbortError(response) ||
17631
+ /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
17632
+ if (retriesRemaining) {
17633
+ loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);
17634
+ loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({
17635
+ retryOfRequestLogID,
17636
+ url,
17637
+ durationMs: headersTime - startTime,
17638
+ message: response.message,
17639
+ }));
17640
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID !== null && retryOfRequestLogID !== void 0 ? retryOfRequestLogID : requestLogID);
17641
+ }
17642
+ loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);
17643
+ loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({
17644
+ retryOfRequestLogID,
17645
+ url,
17646
+ durationMs: headersTime - startTime,
17647
+ message: response.message,
17648
+ }));
17649
+ if (isTimeout) {
17650
+ throw new APIConnectionTimeoutError();
17651
+ }
17652
+ throw new APIConnectionError({ cause: response });
17653
+ }
17654
+ const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;
17655
+ if (!response.ok) {
17656
+ const shouldRetry = await this.shouldRetry(response);
17657
+ if (retriesRemaining && shouldRetry) {
17658
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
17659
+ // We don't need the body of this response.
17660
+ await CancelReadableStream(response.body);
17661
+ loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
17662
+ loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
17663
+ retryOfRequestLogID,
17664
+ url: response.url,
17665
+ status: response.status,
17666
+ headers: response.headers,
17667
+ durationMs: headersTime - startTime,
17668
+ }));
17669
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID !== null && retryOfRequestLogID !== void 0 ? retryOfRequestLogID : requestLogID, response.headers);
17670
+ }
17671
+ const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
17672
+ loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
17673
+ const errText = await response.text().catch((err) => castToError(err).message);
17674
+ const errJSON = safeJSON(errText);
17675
+ const errMessage = errJSON ? undefined : errText;
17676
+ loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
17677
+ retryOfRequestLogID,
17678
+ url: response.url,
17679
+ status: response.status,
17680
+ headers: response.headers,
17681
+ message: errMessage,
17682
+ durationMs: Date.now() - startTime,
17683
+ }));
17684
+ // @ts-ignore
17685
+ const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
17686
+ throw err;
17687
+ }
17688
+ loggerFor(this).info(responseInfo);
17689
+ loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
17690
+ retryOfRequestLogID,
17691
+ url: response.url,
17692
+ status: response.status,
17693
+ headers: response.headers,
17694
+ durationMs: headersTime - startTime,
17695
+ }));
17696
+ return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
17697
+ }
17698
+ async fetchWithTimeout(url, init, ms, controller) {
17699
+ const _b = init || {}, { signal, method } = _b, options = __rest(_b, ["signal", "method"]);
17700
+ if (signal)
17701
+ signal.addEventListener('abort', () => controller.abort());
17702
+ const timeout = setTimeout(() => controller.abort(), ms);
17703
+ const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
17704
+ (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
17705
+ const fetchOptions = Object.assign(Object.assign(Object.assign({ signal: controller.signal }, (isReadableBody ? { duplex: 'half' } : {})), { method: 'GET' }), options);
17706
+ if (method) {
17707
+ // Custom methods like 'patch' need to be uppercased
17708
+ // See https://github.com/nodejs/undici/issues/2294
17709
+ fetchOptions.method = method.toUpperCase();
17710
+ }
17711
+ try {
17712
+ // use undefined this binding; fetch errors if bound to something else in browser/cloudflare
17713
+ return await this.fetch.call(undefined, url, fetchOptions);
17714
+ }
17715
+ finally {
17716
+ clearTimeout(timeout);
17717
+ }
17718
+ }
17719
+ async shouldRetry(response) {
17720
+ // Note this is not a standard header.
17721
+ const shouldRetryHeader = response.headers.get('x-should-retry');
17722
+ // If the server explicitly says whether or not to retry, obey.
17723
+ if (shouldRetryHeader === 'true')
17724
+ return true;
17725
+ if (shouldRetryHeader === 'false')
17726
+ return false;
17727
+ // Retry on request timeouts.
17728
+ if (response.status === 408)
17729
+ return true;
17730
+ // Retry on lock timeouts.
17731
+ if (response.status === 409)
17732
+ return true;
17733
+ // Retry on rate limits.
17734
+ if (response.status === 429)
17735
+ return true;
17736
+ // Retry internal errors.
17737
+ if (response.status >= 500)
17738
+ return true;
17739
+ return false;
17740
+ }
17741
+ async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
17742
+ var _b;
17743
+ let timeoutMillis;
17744
+ // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
17745
+ const retryAfterMillisHeader = responseHeaders === null || responseHeaders === void 0 ? void 0 : responseHeaders.get('retry-after-ms');
17746
+ if (retryAfterMillisHeader) {
17747
+ const timeoutMs = parseFloat(retryAfterMillisHeader);
17748
+ if (!Number.isNaN(timeoutMs)) {
17749
+ timeoutMillis = timeoutMs;
17750
+ }
17751
+ }
17752
+ // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
17753
+ const retryAfterHeader = responseHeaders === null || responseHeaders === void 0 ? void 0 : responseHeaders.get('retry-after');
17754
+ if (retryAfterHeader && !timeoutMillis) {
17755
+ const timeoutSeconds = parseFloat(retryAfterHeader);
17756
+ if (!Number.isNaN(timeoutSeconds)) {
17757
+ timeoutMillis = timeoutSeconds * 1000;
17758
+ }
17759
+ else {
17760
+ timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
17761
+ }
17762
+ }
17763
+ // If the API asks us to wait a certain amount of time (and it's a reasonable amount),
17764
+ // just do what it says, but otherwise calculate a default
17765
+ if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
17766
+ const maxRetries = (_b = options.maxRetries) !== null && _b !== void 0 ? _b : this.maxRetries;
17767
+ timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
17768
+ }
17769
+ await sleep$1(timeoutMillis);
17770
+ return this.makeRequest(options, retriesRemaining - 1, requestLogID);
17771
+ }
17772
+ calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
17773
+ const initialRetryDelay = 0.5;
17774
+ const maxRetryDelay = 8.0;
17775
+ const numRetries = maxRetries - retriesRemaining;
17776
+ // Apply exponential backoff, but not more than the max.
17777
+ const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
17778
+ // Apply some jitter, take up to at most 25 percent of the retry time.
17779
+ const jitter = 1 - Math.random() * 0.25;
17780
+ return sleepSeconds * jitter * 1000;
17781
+ }
17782
+ async buildRequest(inputOptions, { retryCount = 0 } = {}) {
17783
+ var _b, _c, _d;
17784
+ const options = Object.assign({}, inputOptions);
17785
+ const { method, path, query, defaultBaseURL } = options;
17786
+ const url = this.buildURL(path, query, defaultBaseURL);
17787
+ if ('timeout' in options)
17788
+ validatePositiveInteger('timeout', options.timeout);
17789
+ options.timeout = (_b = options.timeout) !== null && _b !== void 0 ? _b : this.timeout;
17790
+ const { bodyHeaders, body } = this.buildBody({ options });
17791
+ const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
17792
+ const req = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ method, headers: reqHeaders }, (options.signal && { signal: options.signal })), (globalThis.ReadableStream &&
17793
+ body instanceof globalThis.ReadableStream && { duplex: 'half' })), (body && { body })), ((_c = this.fetchOptions) !== null && _c !== void 0 ? _c : {})), ((_d = options.fetchOptions) !== null && _d !== void 0 ? _d : {}));
17794
+ return { req, url, timeout: options.timeout };
17795
+ }
17796
+ async buildHeaders({ options, method, bodyHeaders, retryCount, }) {
17797
+ let idempotencyHeaders = {};
17798
+ if (this.idempotencyHeader && method !== 'get') {
17799
+ if (!options.idempotencyKey)
17800
+ options.idempotencyKey = this.defaultIdempotencyKey();
17801
+ idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
17802
+ }
17803
+ const headers = buildHeaders([
17804
+ idempotencyHeaders,
17805
+ Object.assign(Object.assign({ Accept: 'application/json', 'User-Agent': this.getUserAgent(), 'X-Stainless-Retry-Count': String(retryCount) }, (options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {})), getPlatformHeaders()),
17806
+ await this.authHeaders(options),
17807
+ this._options.defaultHeaders,
17808
+ bodyHeaders,
17809
+ options.headers,
17810
+ ]);
17811
+ this.validateHeaders(headers);
17812
+ return headers.values;
17813
+ }
17814
+ buildBody({ options: { body, headers: rawHeaders } }) {
17815
+ if (!body) {
17816
+ return { bodyHeaders: undefined, body: undefined };
17817
+ }
17818
+ const headers = buildHeaders([rawHeaders]);
17819
+ if (
17820
+ // Pass raw type verbatim
17821
+ ArrayBuffer.isView(body) ||
17822
+ body instanceof ArrayBuffer ||
17823
+ body instanceof DataView ||
17824
+ (typeof body === 'string' &&
17825
+ // Preserve legacy string encoding behavior for now
17826
+ headers.values.has('content-type')) ||
17827
+ // `Blob` is superset of `File`
17828
+ (globalThis.Blob && body instanceof globalThis.Blob) ||
17829
+ // `FormData` -> `multipart/form-data`
17830
+ body instanceof FormData ||
17831
+ // `URLSearchParams` -> `application/x-www-form-urlencoded`
17832
+ body instanceof URLSearchParams ||
17833
+ // Send chunked stream (each chunk has own `length`)
17834
+ (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {
17835
+ return { bodyHeaders: undefined, body: body };
17836
+ }
17837
+ else if (typeof body === 'object' &&
17838
+ (Symbol.asyncIterator in body ||
17839
+ (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
17840
+ return { bodyHeaders: undefined, body: ReadableStreamFrom(body) };
17841
+ }
17842
+ else {
17843
+ return this.encoder({ body, headers });
17844
+ }
17845
+ }
17846
+ }
17847
+ BaseGeminiNextGenAPIClient.DEFAULT_TIMEOUT = 60000; // 1 minute
17848
+ /**
17849
+ * API Client for interfacing with the Gemini Next Gen API API.
17850
+ */
17851
+ class GeminiNextGenAPIClient extends BaseGeminiNextGenAPIClient {
17852
+ constructor() {
17853
+ super(...arguments);
17854
+ this.interactions = new Interactions(this);
17855
+ }
17856
+ }
17857
+ _a = GeminiNextGenAPIClient;
17858
+ GeminiNextGenAPIClient.GeminiNextGenAPIClient = _a;
17859
+ GeminiNextGenAPIClient.GeminiNextGenAPIClientError = GeminiNextGenAPIClientError;
17860
+ GeminiNextGenAPIClient.APIError = APIError;
17861
+ GeminiNextGenAPIClient.APIConnectionError = APIConnectionError;
17862
+ GeminiNextGenAPIClient.APIConnectionTimeoutError = APIConnectionTimeoutError;
17863
+ GeminiNextGenAPIClient.APIUserAbortError = APIUserAbortError;
17864
+ GeminiNextGenAPIClient.NotFoundError = NotFoundError;
17865
+ GeminiNextGenAPIClient.ConflictError = ConflictError;
17866
+ GeminiNextGenAPIClient.RateLimitError = RateLimitError;
17867
+ GeminiNextGenAPIClient.BadRequestError = BadRequestError;
17868
+ GeminiNextGenAPIClient.AuthenticationError = AuthenticationError;
17869
+ GeminiNextGenAPIClient.InternalServerError = InternalServerError;
17870
+ GeminiNextGenAPIClient.PermissionDeniedError = PermissionDeniedError;
17871
+ GeminiNextGenAPIClient.UnprocessableEntityError = UnprocessableEntityError;
17872
+ GeminiNextGenAPIClient.toFile = toFile;
17873
+ GeminiNextGenAPIClient.Interactions = Interactions;
17874
+
17875
+ /**
17876
+ * @license
17877
+ * Copyright 2025 Google LLC
17878
+ * SPDX-License-Identifier: Apache-2.0
17879
+ */
17880
+ const GOOGLE_API_KEY_HEADER = 'x-goog-api-key';
17881
+ const REQUIRED_VERTEX_AI_SCOPE = 'https://www.googleapis.com/auth/cloud-platform';
17882
+ class NodeAuth {
17883
+ constructor(opts) {
17884
+ if (opts.apiKey !== undefined) {
17885
+ this.apiKey = opts.apiKey;
17886
+ return;
17887
+ }
17888
+ const vertexAuthOptions = buildGoogleAuthOptions(opts.googleAuthOptions);
17889
+ this.googleAuth = new googleAuthLibrary.GoogleAuth(vertexAuthOptions);
17890
+ }
17891
+ async addAuthHeaders(headers, url) {
17892
+ if (this.apiKey !== undefined) {
17893
+ if (this.apiKey.startsWith('auth_tokens/')) {
17894
+ throw new Error('Ephemeral tokens are only supported by the live API.');
17895
+ }
17896
+ this.addKeyHeader(headers);
17897
+ return;
17898
+ }
17899
+ return this.addGoogleAuthHeaders(headers, url);
17900
+ }
17901
+ addKeyHeader(headers) {
17902
+ if (headers.get(GOOGLE_API_KEY_HEADER) !== null) {
17903
+ return;
17904
+ }
17905
+ if (this.apiKey === undefined) {
17906
+ // This should never happen, this method is only called
17907
+ // when apiKey is set.
17908
+ throw new Error('Trying to set API key header but apiKey is not set');
17909
+ }
17910
+ headers.append(GOOGLE_API_KEY_HEADER, this.apiKey);
17911
+ }
17912
+ async addGoogleAuthHeaders(headers, url) {
17913
+ if (this.googleAuth === undefined) {
17914
+ // This should never happen, addGoogleAuthHeaders should only be
17915
+ // called when there is no apiKey set and in these cases googleAuth
17916
+ // is set.
17917
+ throw new Error('Trying to set google-auth headers but googleAuth is unset');
17918
+ }
17919
+ const authHeaders = await this.googleAuth.getRequestHeaders(url);
17920
+ for (const [key, value] of authHeaders) {
17921
+ if (headers.get(key) !== null) {
17922
+ continue;
17923
+ }
17924
+ headers.append(key, value);
17925
+ }
17926
+ }
17927
+ }
17928
+ function buildGoogleAuthOptions(googleAuthOptions) {
17929
+ let authOptions;
17930
+ if (!googleAuthOptions) {
17931
+ authOptions = {
17932
+ scopes: [REQUIRED_VERTEX_AI_SCOPE],
17933
+ };
17934
+ return authOptions;
17935
+ }
17936
+ else {
17937
+ authOptions = googleAuthOptions;
17938
+ if (!authOptions.scopes) {
17939
+ authOptions.scopes = [REQUIRED_VERTEX_AI_SCOPE];
17940
+ return authOptions;
17941
+ }
17942
+ else if ((typeof authOptions.scopes === 'string' &&
17943
+ authOptions.scopes !== REQUIRED_VERTEX_AI_SCOPE) ||
17944
+ (Array.isArray(authOptions.scopes) &&
17945
+ authOptions.scopes.indexOf(REQUIRED_VERTEX_AI_SCOPE) < 0)) {
17946
+ throw new Error(`Invalid auth scopes. Scopes must include: ${REQUIRED_VERTEX_AI_SCOPE}`);
17947
+ }
17948
+ return authOptions;
17949
+ }
17950
+ }
17951
+
17952
+ /**
17953
+ * @license
17954
+ * Copyright 2025 Google LLC
17955
+ * SPDX-License-Identifier: Apache-2.0
17956
+ */
17957
+ class NodeDownloader {
17958
+ async download(params, apiClient) {
17959
+ if (params.downloadPath) {
17960
+ const response = await downloadFile(params, apiClient);
17961
+ if (response instanceof HttpResponse) {
17962
+ const writer = fs.createWriteStream(params.downloadPath);
17963
+ const body = node_stream.Readable.fromWeb(response.responseInternal.body);
17964
+ body.pipe(writer);
17965
+ await promises.finished(writer);
17966
+ }
17967
+ else {
17968
+ try {
17969
+ await fs$1.writeFile(params.downloadPath, response, {
17970
+ encoding: 'base64',
17971
+ });
17972
+ }
17973
+ catch (error) {
17974
+ throw new Error(`Failed to write file to ${params.downloadPath}: ${error}`);
17975
+ }
17976
+ }
17977
+ }
17978
+ }
17979
+ }
17980
+ async function downloadFile(params, apiClient) {
17981
+ var _a, _b, _c;
17982
+ const name = tFileName(params.file);
17983
+ if (name !== undefined) {
17984
+ return await apiClient.request({
17985
+ path: `files/${name}:download`,
17986
+ httpMethod: 'GET',
17987
+ queryParams: {
17988
+ 'alt': 'media',
17989
+ },
17990
+ httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
17991
+ abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
17992
+ });
17993
+ }
17994
+ else if (isGeneratedVideo(params.file)) {
17995
+ const videoBytes = (_c = params.file.video) === null || _c === void 0 ? void 0 : _c.videoBytes;
17996
+ if (typeof videoBytes === 'string') {
17997
+ return videoBytes;
17998
+ }
17999
+ else {
18000
+ throw new Error('Failed to download generated video, Uri or videoBytes not found.');
18001
+ }
18002
+ }
18003
+ else if (isVideo(params.file)) {
18004
+ const videoBytes = params.file.videoBytes;
18005
+ if (typeof videoBytes === 'string') {
18006
+ return videoBytes;
18007
+ }
18008
+ else {
18009
+ throw new Error('Failed to download video, Uri or videoBytes not found.');
18010
+ }
18011
+ }
18012
+ else {
18013
+ throw new Error('Unsupported file type');
18014
+ }
18015
+ }
18016
+
18017
+ /**
18018
+ * @license
18019
+ * Copyright 2025 Google LLC
18020
+ * SPDX-License-Identifier: Apache-2.0
18021
+ */
18022
+ class NodeWebSocketFactory {
18023
+ create(url, headers, callbacks) {
18024
+ return new NodeWebSocket(url, headers, callbacks);
18025
+ }
18026
+ }
18027
+ class NodeWebSocket {
18028
+ constructor(url, headers, callbacks) {
18029
+ this.url = url;
18030
+ this.headers = headers;
18031
+ this.callbacks = callbacks;
18032
+ }
18033
+ connect() {
18034
+ this.ws = new NodeWs__namespace.WebSocket(this.url, { headers: this.headers });
18035
+ this.ws.onopen = this.callbacks.onopen;
18036
+ this.ws.onerror = this.callbacks.onerror;
18037
+ this.ws.onclose = this.callbacks.onclose;
18038
+ this.ws.onmessage = this.callbacks.onmessage;
18039
+ }
18040
+ send(message) {
18041
+ if (this.ws === undefined) {
18042
+ throw new Error('WebSocket is not connected');
18043
+ }
18044
+ this.ws.send(message);
18045
+ }
18046
+ close() {
18047
+ if (this.ws === undefined) {
18048
+ throw new Error('WebSocket is not connected');
18049
+ }
18050
+ this.ws.close();
18051
+ }
18052
+ }
18053
+
18054
+ /**
18055
+ * @license
18056
+ * Copyright 2025 Google LLC
18057
+ * SPDX-License-Identifier: Apache-2.0
18058
+ */
18059
+ // Code generated by the Google Gen AI SDK generator DO NOT EDIT.
18060
+ function cancelTuningJobParametersToMldev(fromObject, _rootObject) {
18061
+ const toObject = {};
18062
+ const fromName = getValueByPath(fromObject, ['name']);
18063
+ if (fromName != null) {
18064
+ setValueByPath(toObject, ['_url', 'name'], fromName);
18065
+ }
18066
+ return toObject;
18067
+ }
18068
+ function cancelTuningJobParametersToVertex(fromObject, _rootObject) {
18069
+ const toObject = {};
18070
+ const fromName = getValueByPath(fromObject, ['name']);
18071
+ if (fromName != null) {
18072
+ setValueByPath(toObject, ['_url', 'name'], fromName);
16048
18073
  }
16049
18074
  return toObject;
16050
18075
  }
@@ -17442,6 +19467,28 @@ const LANGUAGE_LABEL_PREFIX = 'gl-node/';
17442
19467
  *
17443
19468
  */
17444
19469
  class GoogleGenAI {
19470
+ get interactions() {
19471
+ if (this._interactions !== undefined) {
19472
+ return this._interactions;
19473
+ }
19474
+ console.warn('GoogleGenAI.interactions: Interactions usage is experimental and may change in future versions.');
19475
+ if (this.vertexai) {
19476
+ throw new Error('This version of the GenAI SDK does not support Vertex AI API for interactions.');
19477
+ }
19478
+ const httpOpts = this.httpOptions;
19479
+ // Unsupported Options Warnings
19480
+ if (httpOpts === null || httpOpts === void 0 ? void 0 : httpOpts.extraBody) {
19481
+ console.warn('GoogleGenAI.interactions: Client level httpOptions.extraBody is not supported by the interactions client and will be ignored.');
19482
+ }
19483
+ const nextGenClient = new GeminiNextGenAPIClient({
19484
+ baseURL: this.apiClient.getBaseUrl(),
19485
+ apiKey: this.apiKey,
19486
+ defaultHeaders: this.apiClient.getDefaultHeaders(),
19487
+ timeout: httpOpts === null || httpOpts === void 0 ? void 0 : httpOpts.timeout,
19488
+ });
19489
+ this._interactions = nextGenClient.interactions;
19490
+ return this._interactions;
19491
+ }
17445
19492
  constructor(options) {
17446
19493
  var _a, _b, _c, _d, _e, _f;
17447
19494
  // Validate explicitly set initializer values.