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