@coze/realtime-api 1.0.4-beta.1 → 1.0.4

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.
@@ -1,10 +1,10 @@
1
- /*! For license information please see index.mjs.LICENSE.txt */
1
+ /*! For license information please see index.js.LICENSE.txt */
2
2
  var __webpack_modules__ = {
3
- "?666e": function() {
3
+ "?e272": function() {
4
4
  /* (ignored) */ },
5
- "?79fd": function() {
5
+ "?5742": function() {
6
6
  /* (ignored) */ },
7
- "?9050": function() {
7
+ "?9caf": function() {
8
8
  /* (ignored) */ }
9
9
  };
10
10
  /************************************************************************/ // The module cache
@@ -23,22 +23,7 @@ function __webpack_require__(moduleId) {
23
23
  // Return the exports of the module
24
24
  return module.exports;
25
25
  }
26
- /************************************************************************/ // webpack/runtime/compat_get_default_export
27
- (()=>{
28
- // getDefaultExport function for compatibility with non-ESM modules
29
- __webpack_require__.n = function(module) {
30
- var getter = module && module.__esModule ? function() {
31
- return module['default'];
32
- } : function() {
33
- return module;
34
- };
35
- __webpack_require__.d(getter, {
36
- a: getter
37
- });
38
- return getter;
39
- };
40
- })();
41
- // webpack/runtime/define_property_getters
26
+ /************************************************************************/ // webpack/runtime/define_property_getters
42
27
  (()=>{
43
28
  __webpack_require__.d = function(exports, definition) {
44
29
  for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) Object.defineProperty(exports, key, {
@@ -83,7 +68,7 @@ __webpack_require__.d(common_utils_namespaceObject, {
83
68
  hasBrowserEnv: ()=>hasBrowserEnv,
84
69
  hasStandardBrowserEnv: ()=>hasStandardBrowserEnv,
85
70
  hasStandardBrowserWebWorkerEnv: ()=>hasStandardBrowserWebWorkerEnv,
86
- navigator: ()=>_navigator,
71
+ navigator: ()=>utils_navigator,
87
72
  origin: ()=>origin
88
73
  });
89
74
  // NAMESPACE OBJECT: ./src/utils.ts
@@ -93,968 +78,409 @@ __webpack_require__.d(src_utils_namespaceObject, {
93
78
  checkDevicePermission: ()=>checkDevicePermission,
94
79
  checkPermission: ()=>checkPermission,
95
80
  getAudioDevices: ()=>getAudioDevices,
96
- sleep: ()=>src_utils_sleep
81
+ isScreenShareDevice: ()=>isScreenShareDevice,
82
+ isScreenShareSupported: ()=>isScreenShareSupported,
83
+ sleep: ()=>utils_sleep
97
84
  });
98
- class APIResource {
99
- constructor(client){
100
- this._client = client;
101
- }
102
- }
103
- /* eslint-disable @typescript-eslint/no-namespace */ class Bots extends APIResource {
104
- /**
105
- * Create a new agent. | 调用接口创建一个新的智能体。
106
- * @docs en:https://www.coze.com/docs/developer_guides/create_bot?_lang=en
107
- * @docs zh:https://www.coze.cn/docs/developer_guides/create_bot?_lang=zh
108
- * @param params - Required The parameters for creating a bot. | 创建 Bot 的参数。
109
- * @param params.space_id - Required The Space ID of the space where the agent is located. | Bot 所在的空间的 Space ID。
110
- * @param params.name - Required The name of the agent. It should be 1 to 20 characters long. | Bot 的名称。
111
- * @param params.description - Optional The description of the agent. It can be 0 to 500 characters long. | Bot 的描述信息。
112
- * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
113
- * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
114
- * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
115
- * @returns Information about the created bot. | 创建的 Bot 信息。
116
- */ async create(params, options) {
117
- const apiUrl = '/v1/bot/create';
118
- const result = await this._client.post(apiUrl, params, false, options);
119
- return result.data;
120
- }
121
- /**
122
- * Update the configuration of an agent. | 调用接口修改智能体的配置。
123
- * @docs en:https://www.coze.com/docs/developer_guides/update_bot?_lang=en
124
- * @docs zh:https://www.coze.cn/docs/developer_guides/update_bot?_lang=zh
125
- * @param params - Required The parameters for updating a bot. | 修改 Bot 的参数。
126
- * @param params.bot_id - Required The ID of the agent that the API interacts with. | 待修改配置的智能体ID。
127
- * @param params.name - Optional The name of the agent. | Bot 的名称。
128
- * @param params.description - Optional The description of the agent. | Bot 的描述信息。
129
- * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
130
- * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
131
- * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
132
- * @param params.knowledge - Optional Knowledge configurations of the agent. | Bot 的知识库配置。
133
- * @returns Undefined | 无返回值
134
- */ async update(params, options) {
135
- const apiUrl = '/v1/bot/update';
136
- const result = await this._client.post(apiUrl, params, false, options);
137
- return result.data;
138
- }
139
- /**
140
- * Get the agents published as API service. | 调用接口查看指定空间发布到 Agent as API 渠道的智能体列表。
141
- * @docs en:https://www.coze.com/docs/developer_guides/published_bots_list?_lang=en
142
- * @docs zh:https://www.coze.cn/docs/developer_guides/published_bots_list?_lang=zh
143
- * @param params - Required The parameters for listing bots. | 列出 Bot 的参数。
144
- * @param params.space_id - Required The ID of the space. | Bot 所在的空间的 Space ID。
145
- * @param params.page_size - Optional Pagination size. | 分页大小。
146
- * @param params.page_index - Optional Page number for paginated queries. | 分页查询时的页码。
147
- * @returns List of published bots. | 已发布的 Bot 列表。
148
- */ async list(params, options) {
149
- const apiUrl = '/v1/space/published_bots_list';
150
- const result = await this._client.get(apiUrl, params, false, options);
151
- return result.data;
152
- }
153
- /**
154
- * Publish the specified agent as an API service. | 调用接口创建一个新的智能体。
155
- * @docs en:https://www.coze.com/docs/developer_guides/publish_bot?_lang=en
156
- * @docs zh:https://www.coze.cn/docs/developer_guides/publish_bot?_lang=zh
157
- * @param params - Required The parameters for publishing a bot. | 发布 Bot 的参数。
158
- * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要发布的智能体ID。
159
- * @param params.connector_ids - Required The list of publishing channel IDs for the agent. | 智能体的发布渠道 ID 列表。
160
- * @returns Undefined | 无返回值
161
- */ async publish(params, options) {
162
- const apiUrl = '/v1/bot/publish';
163
- const result = await this._client.post(apiUrl, params, false, options);
164
- return result.data;
165
- }
166
- /**
167
- * Get the configuration information of the agent. | 获取指定智能体的配置信息。
168
- * @docs en:https://www.coze.com/docs/developer_guides/get_metadata?_lang=en
169
- * @docs zh:https://www.coze.cn/docs/developer_guides/get_metadata?_lang=zh
170
- * @param params - Required The parameters for retrieving a bot. | 获取 Bot 的参数。
171
- * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要查看的智能体ID。
172
- * @returns Information about the bot. | Bot 的配置信息。
173
- */ async retrieve(params, options) {
174
- const apiUrl = '/v1/bot/get_online_info';
175
- const result = await this._client.get(apiUrl, params, false, options);
176
- return result.data;
177
- }
178
- }
179
- /* eslint-disable security/detect-object-injection */ /* eslint-disable @typescript-eslint/no-explicit-any */ function safeJsonParse(jsonString) {
180
- let defaultValue = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : '';
181
- try {
182
- return JSON.parse(jsonString);
183
- } catch (error) {
184
- return defaultValue;
185
- }
186
- }
187
- function utils_sleep(ms) {
188
- return new Promise((resolve)=>{
189
- setTimeout(resolve, ms);
190
- });
191
- }
192
- function utils_isBrowser() {
193
- return 'undefined' != typeof window;
194
- }
195
- function isPlainObject(obj) {
196
- if ('object' != typeof obj || null === obj) return false;
197
- const proto = Object.getPrototypeOf(obj);
198
- if (null === proto) return true;
199
- let baseProto = proto;
200
- while(null !== Object.getPrototypeOf(baseProto))baseProto = Object.getPrototypeOf(baseProto);
201
- return proto === baseProto;
202
- }
203
- function mergeConfig() {
204
- for(var _len = arguments.length, objects = new Array(_len), _key = 0; _key < _len; _key++)objects[_key] = arguments[_key];
205
- return objects.reduce((result, obj)=>{
206
- if (void 0 === obj) return result || {};
207
- for(const key in obj)if (Object.prototype.hasOwnProperty.call(obj, key)) {
208
- if (isPlainObject(obj[key]) && !Array.isArray(obj[key])) result[key] = mergeConfig(result[key] || {}, obj[key]);
209
- else result[key] = obj[key];
210
- }
211
- return result;
212
- }, {});
85
+ function bind(fn, thisArg) {
86
+ return function() {
87
+ return fn.apply(thisArg, arguments);
88
+ };
213
89
  }
214
- function isPersonalAccessToken(token) {
215
- return null == token ? void 0 : token.startsWith('pat_');
90
+ // utils is a library of generic helper functions non-specific to axios
91
+ const { toString: utils_toString } = Object.prototype;
92
+ const { getPrototypeOf } = Object;
93
+ const kindOf = ((cache)=>(thing)=>{
94
+ const str = utils_toString.call(thing);
95
+ return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
96
+ })(Object.create(null));
97
+ const kindOfTest = (type)=>{
98
+ type = type.toLowerCase();
99
+ return (thing)=>kindOf(thing) === type;
100
+ };
101
+ const typeOfTest = (type)=>(thing)=>typeof thing === type;
102
+ /**
103
+ * Determine if a value is an Array
104
+ *
105
+ * @param {Object} val The value to test
106
+ *
107
+ * @returns {boolean} True if value is an Array, otherwise false
108
+ */ const { isArray } = Array;
109
+ /**
110
+ * Determine if a value is undefined
111
+ *
112
+ * @param {*} val The value to test
113
+ *
114
+ * @returns {boolean} True if the value is undefined, otherwise false
115
+ */ const isUndefined = typeOfTest('undefined');
116
+ /**
117
+ * Determine if a value is a Buffer
118
+ *
119
+ * @param {*} val The value to test
120
+ *
121
+ * @returns {boolean} True if value is a Buffer, otherwise false
122
+ */ function isBuffer(val) {
123
+ return null !== val && !isUndefined(val) && null !== val.constructor && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
216
124
  }
217
- /* eslint-disable max-params */ class CozeError extends Error {
125
+ /**
126
+ * Determine if a value is an ArrayBuffer
127
+ *
128
+ * @param {*} val The value to test
129
+ *
130
+ * @returns {boolean} True if value is an ArrayBuffer, otherwise false
131
+ */ const isArrayBuffer = kindOfTest('ArrayBuffer');
132
+ /**
133
+ * Determine if a value is a view on an ArrayBuffer
134
+ *
135
+ * @param {*} val The value to test
136
+ *
137
+ * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
138
+ */ function isArrayBufferView(val) {
139
+ let result;
140
+ result = 'undefined' != typeof ArrayBuffer && ArrayBuffer.isView ? ArrayBuffer.isView(val) : val && val.buffer && isArrayBuffer(val.buffer);
141
+ return result;
218
142
  }
219
- class error_APIError extends CozeError {
220
- static makeMessage(status, errorBody, message, headers) {
221
- if (!errorBody && message) return message;
222
- if (errorBody) {
223
- const list = [];
224
- const { code, msg, error } = errorBody;
225
- if (code) list.push(`code: ${code}`);
226
- if (msg) list.push(`msg: ${msg}`);
227
- if ((null == error ? void 0 : error.detail) && msg !== error.detail) list.push(`detail: ${error.detail}`);
228
- const logId = (null == error ? void 0 : error.logid) || (null == headers ? void 0 : headers['x-tt-logid']);
229
- if (logId) list.push(`logid: ${logId}`);
230
- const help_doc = null == error ? void 0 : error.help_doc;
231
- if (help_doc) list.push(`help doc: ${help_doc}`);
232
- return list.join(', ');
143
+ /**
144
+ * Determine if a value is a String
145
+ *
146
+ * @param {*} val The value to test
147
+ *
148
+ * @returns {boolean} True if value is a String, otherwise false
149
+ */ const isString = typeOfTest('string');
150
+ /**
151
+ * Determine if a value is a Function
152
+ *
153
+ * @param {*} val The value to test
154
+ * @returns {boolean} True if value is a Function, otherwise false
155
+ */ const isFunction = typeOfTest('function');
156
+ /**
157
+ * Determine if a value is a Number
158
+ *
159
+ * @param {*} val The value to test
160
+ *
161
+ * @returns {boolean} True if value is a Number, otherwise false
162
+ */ const isNumber = typeOfTest('number');
163
+ /**
164
+ * Determine if a value is an Object
165
+ *
166
+ * @param {*} thing The value to test
167
+ *
168
+ * @returns {boolean} True if value is an Object, otherwise false
169
+ */ const isObject = (thing)=>null !== thing && 'object' == typeof thing;
170
+ /**
171
+ * Determine if a value is a Boolean
172
+ *
173
+ * @param {*} thing The value to test
174
+ * @returns {boolean} True if value is a Boolean, otherwise false
175
+ */ const isBoolean = (thing)=>true === thing || false === thing;
176
+ /**
177
+ * Determine if a value is a plain Object
178
+ *
179
+ * @param {*} val The value to test
180
+ *
181
+ * @returns {boolean} True if value is a plain Object, otherwise false
182
+ */ const isPlainObject = (val)=>{
183
+ if ('object' !== kindOf(val)) return false;
184
+ const prototype = getPrototypeOf(val);
185
+ return (null === prototype || prototype === Object.prototype || null === Object.getPrototypeOf(prototype)) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
186
+ };
187
+ /**
188
+ * Determine if a value is a Date
189
+ *
190
+ * @param {*} val The value to test
191
+ *
192
+ * @returns {boolean} True if value is a Date, otherwise false
193
+ */ const isDate = kindOfTest('Date');
194
+ /**
195
+ * Determine if a value is a File
196
+ *
197
+ * @param {*} val The value to test
198
+ *
199
+ * @returns {boolean} True if value is a File, otherwise false
200
+ */ const isFile = kindOfTest('File');
201
+ /**
202
+ * Determine if a value is a Blob
203
+ *
204
+ * @param {*} val The value to test
205
+ *
206
+ * @returns {boolean} True if value is a Blob, otherwise false
207
+ */ const isBlob = kindOfTest('Blob');
208
+ /**
209
+ * Determine if a value is a FileList
210
+ *
211
+ * @param {*} val The value to test
212
+ *
213
+ * @returns {boolean} True if value is a File, otherwise false
214
+ */ const utils_isFileList = kindOfTest('FileList');
215
+ /**
216
+ * Determine if a value is a Stream
217
+ *
218
+ * @param {*} val The value to test
219
+ *
220
+ * @returns {boolean} True if value is a Stream, otherwise false
221
+ */ const utils_isStream = (val)=>isObject(val) && isFunction(val.pipe);
222
+ /**
223
+ * Determine if a value is a FormData
224
+ *
225
+ * @param {*} thing The value to test
226
+ *
227
+ * @returns {boolean} True if value is an FormData, otherwise false
228
+ */ const utils_isFormData = (thing)=>{
229
+ let kind;
230
+ return thing && ('function' == typeof FormData && thing instanceof FormData || isFunction(thing.append) && ('formdata' === (kind = kindOf(thing)) || // detect form-data instance
231
+ 'object' === kind && isFunction(thing.toString) && '[object FormData]' === thing.toString()));
232
+ };
233
+ /**
234
+ * Determine if a value is a URLSearchParams object
235
+ *
236
+ * @param {*} val The value to test
237
+ *
238
+ * @returns {boolean} True if value is a URLSearchParams object, otherwise false
239
+ */ const isURLSearchParams = kindOfTest('URLSearchParams');
240
+ const [isReadableStream, isRequest, isResponse, isHeaders] = [
241
+ 'ReadableStream',
242
+ 'Request',
243
+ 'Response',
244
+ 'Headers'
245
+ ].map(kindOfTest);
246
+ /**
247
+ * Trim excess whitespace off the beginning and end of a string
248
+ *
249
+ * @param {String} str The String to trim
250
+ *
251
+ * @returns {String} The String freed of excess whitespace
252
+ */ const trim = (str)=>str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
253
+ /**
254
+ * Iterate over an Array or an Object invoking a function for each item.
255
+ *
256
+ * If `obj` is an Array callback will be called passing
257
+ * the value, index, and complete array for each item.
258
+ *
259
+ * If 'obj' is an Object callback will be called passing
260
+ * the value, key, and complete object for each property.
261
+ *
262
+ * @param {Object|Array} obj The object to iterate
263
+ * @param {Function} fn The callback to invoke for each item
264
+ *
265
+ * @param {Boolean} [allOwnKeys = false]
266
+ * @returns {any}
267
+ */ function forEach(obj, fn, { allOwnKeys = false } = {}) {
268
+ // Don't bother if no value provided
269
+ if (null == obj) return;
270
+ let i;
271
+ let l;
272
+ // Force an array if not already something iterable
273
+ if ('object' != typeof obj) /*eslint no-param-reassign:0*/ obj = [
274
+ obj
275
+ ];
276
+ if (isArray(obj)) // Iterate over array values
277
+ for(i = 0, l = obj.length; i < l; i++)fn.call(null, obj[i], i, obj);
278
+ else {
279
+ // Iterate over object keys
280
+ const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
281
+ const len = keys.length;
282
+ let key;
283
+ for(i = 0; i < len; i++){
284
+ key = keys[i];
285
+ fn.call(null, obj[key], key, obj);
233
286
  }
234
- if (status) return `http status code: ${status} (no body)`;
235
- return '(no status code or body)';
236
- }
237
- static generate(status, errorResponse, message, headers) {
238
- if (!status) return new APIConnectionError({
239
- cause: castToError(errorResponse)
240
- });
241
- const error = errorResponse;
242
- // https://www.coze.cn/docs/developer_guides/coze_error_codes
243
- if (400 === status || (null == error ? void 0 : error.code) === 4000) return new BadRequestError(status, error, message, headers);
244
- if (401 === status || (null == error ? void 0 : error.code) === 4100) return new AuthenticationError(status, error, message, headers);
245
- if (403 === status || (null == error ? void 0 : error.code) === 4101) return new PermissionDeniedError(status, error, message, headers);
246
- if (404 === status || (null == error ? void 0 : error.code) === 4200) return new NotFoundError(status, error, message, headers);
247
- if (429 === status || (null == error ? void 0 : error.code) === 4013) return new RateLimitError(status, error, message, headers);
248
- if (408 === status) return new TimeoutError(status, error, message, headers);
249
- if (502 === status) return new GatewayError(status, error, message, headers);
250
- if (status >= 500) return new InternalServerError(status, error, message, headers);
251
- return new error_APIError(status, error, message, headers);
252
- }
253
- constructor(status, error, message, headers){
254
- var _error_error, _error_error1;
255
- super(`${error_APIError.makeMessage(status, error, message, headers)}`);
256
- this.status = status;
257
- this.headers = headers;
258
- this.logid = null == headers ? void 0 : headers['x-tt-logid'];
259
- // this.error = error;
260
- this.code = null == error ? void 0 : error.code;
261
- this.msg = null == error ? void 0 : error.msg;
262
- this.detail = null == error ? void 0 : null === (_error_error = error.error) || void 0 === _error_error ? void 0 : _error_error.detail;
263
- this.help_doc = null == error ? void 0 : null === (_error_error1 = error.error) || void 0 === _error_error1 ? void 0 : _error_error1.help_doc;
264
- this.rawError = error;
265
- }
266
- }
267
- class APIConnectionError extends error_APIError {
268
- constructor({ message, cause }){
269
- super(void 0, void 0, message || 'Connection error.', void 0), this.status = void 0;
270
- // if (cause) {
271
- // this.cause = cause;
272
- // }
273
- }
274
- }
275
- class APIUserAbortError extends error_APIError {
276
- constructor(message){
277
- super(void 0, void 0, message || 'Request was aborted.', void 0), this.name = 'UserAbortError', this.status = void 0;
278
- }
279
- }
280
- class BadRequestError extends error_APIError {
281
- constructor(...args){
282
- super(...args), this.name = 'BadRequestError', this.status = 400;
283
- }
284
- }
285
- class AuthenticationError extends error_APIError {
286
- constructor(...args){
287
- super(...args), this.name = 'AuthenticationError', this.status = 401;
288
- }
289
- }
290
- class PermissionDeniedError extends error_APIError {
291
- constructor(...args){
292
- super(...args), this.name = 'PermissionDeniedError', this.status = 403;
293
- }
294
- }
295
- class NotFoundError extends error_APIError {
296
- constructor(...args){
297
- super(...args), this.name = 'NotFoundError', this.status = 404;
298
287
  }
299
288
  }
300
- class TimeoutError extends error_APIError {
301
- constructor(...args){
302
- super(...args), this.name = 'TimeoutError', this.status = 408;
303
- }
304
- }
305
- class RateLimitError extends error_APIError {
306
- constructor(...args){
307
- super(...args), this.name = 'RateLimitError', this.status = 429;
308
- }
309
- }
310
- class InternalServerError extends error_APIError {
311
- constructor(...args){
312
- super(...args), this.name = 'InternalServerError', this.status = 500;
289
+ function findKey(obj, key) {
290
+ key = key.toLowerCase();
291
+ const keys = Object.keys(obj);
292
+ let i = keys.length;
293
+ let _key;
294
+ while(i-- > 0){
295
+ _key = keys[i];
296
+ if (key === _key.toLowerCase()) return _key;
313
297
  }
298
+ return null;
314
299
  }
315
- class GatewayError extends error_APIError {
316
- constructor(...args){
317
- super(...args), this.name = 'GatewayError', this.status = 502;
318
- }
300
+ const _global = (()=>{
301
+ /*eslint no-undef:0*/ if ("undefined" != typeof globalThis) return globalThis;
302
+ return "undefined" != typeof self ? self : 'undefined' != typeof window ? window : global;
303
+ })();
304
+ const isContextDefined = (context)=>!isUndefined(context) && context !== _global;
305
+ /**
306
+ * Accepts varargs expecting each argument to be an object, then
307
+ * immutably merges the properties of each object and returns result.
308
+ *
309
+ * When multiple objects contain the same key the later object in
310
+ * the arguments list will take precedence.
311
+ *
312
+ * Example:
313
+ *
314
+ * ```js
315
+ * var result = merge({foo: 123}, {foo: 456});
316
+ * console.log(result.foo); // outputs 456
317
+ * ```
318
+ *
319
+ * @param {Object} obj1 Object to merge
320
+ *
321
+ * @returns {Object} Result of all merge properties
322
+ */ function utils_merge() {
323
+ const { caseless } = isContextDefined(this) && this || {};
324
+ const result = {};
325
+ const assignValue = (val, key)=>{
326
+ const targetKey = caseless && findKey(result, key) || key;
327
+ if (isPlainObject(result[targetKey]) && isPlainObject(val)) result[targetKey] = utils_merge(result[targetKey], val);
328
+ else if (isPlainObject(val)) result[targetKey] = utils_merge({}, val);
329
+ else if (isArray(val)) result[targetKey] = val.slice();
330
+ else result[targetKey] = val;
331
+ };
332
+ for(let i = 0, l = arguments.length; i < l; i++)arguments[i] && forEach(arguments[i], assignValue);
333
+ return result;
319
334
  }
320
- const castToError = (err)=>{
321
- if (err instanceof Error) return err;
322
- return new Error(err);
335
+ /**
336
+ * Extends object a by mutably adding to it the properties of object b.
337
+ *
338
+ * @param {Object} a The object to be extended
339
+ * @param {Object} b The object to copy properties from
340
+ * @param {Object} thisArg The object to bind function to
341
+ *
342
+ * @param {Boolean} [allOwnKeys]
343
+ * @returns {Object} The resulting value of object a
344
+ */ const extend = (a, b, thisArg, { allOwnKeys } = {})=>{
345
+ forEach(b, (val, key)=>{
346
+ if (thisArg && isFunction(val)) a[key] = bind(val, thisArg);
347
+ else a[key] = val;
348
+ }, {
349
+ allOwnKeys
350
+ });
351
+ return a;
323
352
  };
324
- class Messages extends APIResource {
325
- /**
326
- * Get the list of messages in a chat. | 获取对话中的消息列表。
327
- * @docs en:https://www.coze.com/docs/developer_guides/chat_message_list?_lang=en
328
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_message_list?_lang=zh
329
- * @param conversation_id - Required The ID of the conversation. | 会话 ID。
330
- * @param chat_id - Required The ID of the chat. | 对话 ID。
331
- * @returns An array of chat messages. | 对话消息数组。
332
- */ async list(conversation_id, chat_id, options) {
333
- const apiUrl = `/v3/chat/message/list?conversation_id=${conversation_id}&chat_id=${chat_id}`;
334
- const result = await this._client.get(apiUrl, void 0, false, options);
335
- return result.data;
336
- }
337
- }
338
- const uuid = ()=>(Math.random() * new Date().getTime()).toString();
339
- const handleAdditionalMessages = (additional_messages)=>null == additional_messages ? void 0 : additional_messages.map((i)=>({
340
- ...i,
341
- content: 'object' == typeof i.content ? JSON.stringify(i.content) : i.content
342
- }));
343
- class Chat extends APIResource {
344
- /**
345
- * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
346
- * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
347
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
348
- * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
349
- * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
350
- * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
351
- * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
352
- * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义变量。
353
- * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
354
- * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
355
- * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
356
- * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
357
- * @returns The data of the created chat. | 创建的对话数据。
358
- */ async create(params, options) {
359
- if (!params.user_id) params.user_id = uuid();
360
- const { conversation_id, ...rest } = params;
361
- const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
362
- const payload = {
363
- ...rest,
364
- additional_messages: handleAdditionalMessages(params.additional_messages),
365
- stream: false
366
- };
367
- const result = await this._client.post(apiUrl, payload, false, options);
368
- return result.data;
369
- }
370
- /**
371
- * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
372
- * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
373
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
374
- * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
375
- * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
376
- * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
377
- * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
378
- * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
379
- * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
380
- * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
381
- * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
382
- * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
383
- * @returns
384
- */ async createAndPoll(params, options) {
385
- if (!params.user_id) params.user_id = uuid();
386
- const { conversation_id, ...rest } = params;
387
- const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
388
- const payload = {
389
- ...rest,
390
- additional_messages: handleAdditionalMessages(params.additional_messages),
391
- stream: false
392
- };
393
- const result = await this._client.post(apiUrl, payload, false, options);
394
- const chatId = result.data.id;
395
- const conversationId = result.data.conversation_id;
396
- let chat;
397
- while(true){
398
- await utils_sleep(100);
399
- chat = await this.retrieve(conversationId, chatId);
400
- if ('completed' === chat.status || 'failed' === chat.status || 'requires_action' === chat.status) break;
401
- }
402
- const messageList = await this.messages.list(conversationId, chatId);
403
- return {
404
- chat,
405
- messages: messageList
406
- };
407
- }
408
- /**
409
- * Call the Chat API to send messages to a published Coze agent with streaming response. | 调用此接口发起一次对话,支持流式响应。
410
- * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
411
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
412
- * @param params - Required The parameters for streaming a chat session. | 流式会话的参数。
413
- * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
414
- * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
415
- * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
416
- * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
417
- * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
418
- * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
419
- * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
420
- * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
421
- * @returns A stream of chat data. | 对话数据流。
422
- */ async *stream(params, options) {
423
- if (!params.user_id) params.user_id = uuid();
424
- const { conversation_id, ...rest } = params;
425
- const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
426
- const payload = {
427
- ...rest,
428
- additional_messages: handleAdditionalMessages(params.additional_messages),
429
- stream: true
430
- };
431
- const result = await this._client.post(apiUrl, payload, true, options);
432
- for await (const message of result)if ("done" === message.event) {
433
- const ret = {
434
- event: message.event,
435
- data: '[DONE]'
436
- };
437
- yield ret;
438
- } else try {
439
- const ret = {
440
- event: message.event,
441
- data: JSON.parse(message.data)
442
- };
443
- yield ret;
444
- } catch (error) {
445
- throw new CozeError(`Could not parse message into JSON:${message.data}`);
446
- }
447
- }
448
- /**
449
- * Get the detailed information of the chat. | 查看对话的详细信息。
450
- * @docs en:https://www.coze.com/docs/developer_guides/retrieve_chat?_lang=en
451
- * @docs zh:https://www.coze.cn/docs/developer_guides/retrieve_chat?_lang=zh
452
- * @param conversation_id - Required The ID of the conversation. | 会话 ID。
453
- * @param chat_id - Required The ID of the chat. | 对话 ID。
454
- * @returns The data of the retrieved chat. | 检索到的对话数据。
455
- */ async retrieve(conversation_id, chat_id, options) {
456
- const apiUrl = `/v3/chat/retrieve?conversation_id=${conversation_id}&chat_id=${chat_id}`;
457
- const result = await this._client.post(apiUrl, void 0, false, options);
458
- return result.data;
459
- }
460
- /**
461
- * Cancel a chat session. | 取消对话会话。
462
- * @docs en:https://www.coze.com/docs/developer_guides/cancel_chat?_lang=en
463
- * @docs zh:https://www.coze.cn/docs/developer_guides/cancel_chat?_lang=zh
464
- * @param conversation_id - Required The ID of the conversation. | 会话 ID。
465
- * @param chat_id - Required The ID of the chat. | 对话 ID。
466
- * @returns The data of the canceled chat. | 取消的对话数据。
467
- */ async cancel(conversation_id, chat_id, options) {
468
- const apiUrl = '/v3/chat/cancel';
469
- const payload = {
470
- conversation_id,
471
- chat_id
472
- };
473
- const result = await this._client.post(apiUrl, payload, false, options);
474
- return result.data;
475
- }
476
- /**
477
- * Submit tool outputs for a chat session. | 提交对话会话的工具输出。
478
- * @docs en:https://www.coze.com/docs/developer_guides/chat_submit_tool_outputs?_lang=en
479
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_submit_tool_outputs?_lang=zh
480
- * @param params - Required Parameters for submitting tool outputs. | 提交工具输出的参数。
481
- * @param params.conversation_id - Required The ID of the conversation. | 会话 ID。
482
- * @param params.chat_id - Required The ID of the chat. | 对话 ID。
483
- * @param params.tool_outputs - Required The outputs of the tool. | 工具的输出。
484
- * @param params.stream - Optional Whether to use streaming response. | 是否使用流式响应。
485
- * @returns The data of the submitted tool outputs or a stream of chat data. | 提交的工具输出数据或对话数据流。
486
- */ async *submitToolOutputs(params, options) {
487
- const { conversation_id, chat_id, ...rest } = params;
488
- const apiUrl = `/v3/chat/submit_tool_outputs?conversation_id=${params.conversation_id}&chat_id=${params.chat_id}`;
489
- const payload = {
490
- ...rest
491
- };
492
- if (false === params.stream) {
493
- const response = await this._client.post(apiUrl, payload, false, options);
494
- return response.data;
495
- }
496
- {
497
- const result = await this._client.post(apiUrl, payload, true, options);
498
- for await (const message of result)if ("done" === message.event) {
499
- const ret = {
500
- event: message.event,
501
- data: '[DONE]'
502
- };
503
- yield ret;
504
- } else try {
505
- const ret = {
506
- event: message.event,
507
- data: JSON.parse(message.data)
508
- };
509
- yield ret;
510
- } catch (error) {
511
- throw new CozeError(`Could not parse message into JSON:${message.data}`);
512
- }
513
- }
514
- }
515
- constructor(...args){
516
- super(...args), this.messages = new Messages(this._client);
517
- }
518
- }
519
- var chat_ChatEventType = /*#__PURE__*/ function(ChatEventType) {
520
- ChatEventType["CONVERSATION_CHAT_CREATED"] = "conversation.chat.created";
521
- ChatEventType["CONVERSATION_CHAT_IN_PROGRESS"] = "conversation.chat.in_progress";
522
- ChatEventType["CONVERSATION_CHAT_COMPLETED"] = "conversation.chat.completed";
523
- ChatEventType["CONVERSATION_CHAT_FAILED"] = "conversation.chat.failed";
524
- ChatEventType["CONVERSATION_CHAT_REQUIRES_ACTION"] = "conversation.chat.requires_action";
525
- ChatEventType["CONVERSATION_MESSAGE_DELTA"] = "conversation.message.delta";
526
- ChatEventType["CONVERSATION_MESSAGE_COMPLETED"] = "conversation.message.completed";
527
- ChatEventType["CONVERSATION_AUDIO_DELTA"] = "conversation.audio.delta";
528
- ChatEventType["DONE"] = "done";
529
- ChatEventType["ERROR"] = "error";
530
- return ChatEventType;
531
- }({});
532
- class messages_Messages extends APIResource {
533
- /**
534
- * Create a message and add it to the specified conversation. | 创建一条消息,并将其添加到指定的会话中。
535
- * @docs en: https://www.coze.com/docs/developer_guides/create_message?_lang=en
536
- * @docs zh: https://www.coze.cn/docs/developer_guides/create_message?_lang=zh
537
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
538
- * @param params - Required The parameters for creating a message | 创建消息所需的参数
539
- * @param params.role - Required The entity that sent this message. Possible values: user, assistant. | 发送这条消息的实体。取值:user, assistant。
540
- * @param params.content - Required The content of the message. | 消息的内容。
541
- * @param params.content_type - Required The type of the message content. | 消息内容的类型。
542
- * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
543
- * @returns Information about the new message. | 消息详情。
544
- */ async create(conversation_id, params, options) {
545
- const apiUrl = `/v1/conversation/message/create?conversation_id=${conversation_id}`;
546
- const response = await this._client.post(apiUrl, params, false, options);
547
- return response.data;
548
- }
549
- /**
550
- * Modify a message, supporting the modification of message content, additional content, and message type. | 修改一条消息,支持修改消息内容、附加内容和消息类型。
551
- * @docs en: https://www.coze.com/docs/developer_guides/modify_message?_lang=en
552
- * @docs zh: https://www.coze.cn/docs/developer_guides/modify_message?_lang=zh
553
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
554
- * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
555
- * @param params - Required The parameters for modifying a message | 修改消息所需的参数
556
- * @param params.meta_data - Optional Additional information when modifying a message. | 修改消息时的附加消息。
557
- * @param params.content - Optional The content of the message. | 消息的内容。
558
- * @param params.content_type - Optional The type of the message content. | 消息内容的类型。
559
- * @returns Information about the modified message. | 消息详情。
560
- */ // eslint-disable-next-line max-params
561
- async update(conversation_id, message_id, params, options) {
562
- const apiUrl = `/v1/conversation/message/modify?conversation_id=${conversation_id}&message_id=${message_id}`;
563
- const response = await this._client.post(apiUrl, params, false, options);
564
- return response.message;
565
- }
566
- /**
567
- * Get the detailed information of specified message. | 查看指定消息的详细信息。
568
- * @docs en: https://www.coze.com/docs/developer_guides/retrieve_message?_lang=en
569
- * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_message?_lang=zh
570
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
571
- * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
572
- * @returns Information about the message. | 消息详情。
573
- */ async retrieve(conversation_id, message_id, options) {
574
- const apiUrl = `/v1/conversation/message/retrieve?conversation_id=${conversation_id}&message_id=${message_id}`;
575
- const response = await this._client.get(apiUrl, null, false, options);
576
- return response.data;
577
- }
578
- /**
579
- * List messages in a conversation. | 列出会话中的消息。
580
- * @docs en: https://www.coze.com/docs/developer_guides/message_list?_lang=en
581
- * @docs zh: https://www.coze.cn/docs/developer_guides/message_list?_lang=zh
582
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
583
- * @param params - Optional The parameters for listing messages | 列出消息所需的参数
584
- * @param params.order - Optional The order of the messages. | 消息的顺序。
585
- * @param params.chat_id - Optional The ID of the chat. | 聊天 ID。
586
- * @param params.before_id - Optional The ID of the message before which to list. | 列出此消息之前的消息 ID。
587
- * @param params.after_id - Optional The ID of the message after which to list. | 列出此消息之后的消息 ID。
588
- * @param params.limit - Optional The maximum number of messages to return. | 返回的最大消息数。
589
- * @returns A list of messages. | 消息列表。
590
- */ async list(conversation_id, params, options) {
591
- const apiUrl = `/v1/conversation/message/list?conversation_id=${conversation_id}`;
592
- const response = await this._client.post(apiUrl, params, false, options);
593
- return response;
594
- }
595
- /**
596
- * Call the API to delete a message within a specified conversation. | 调用接口在指定会话中删除消息。
597
- * @docs en: https://www.coze.com/docs/developer_guides/delete_message?_lang=en
598
- * @docs zh: https://www.coze.cn/docs/developer_guides/delete_message?_lang=zh
599
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
600
- * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
601
- * @returns Details of the deleted message. | 已删除的消息详情。
602
- */ async delete(conversation_id, message_id, options) {
603
- const apiUrl = `/v1/conversation/message/delete?conversation_id=${conversation_id}&message_id=${message_id}`;
604
- const response = await this._client.post(apiUrl, void 0, false, options);
605
- return response.data;
606
- }
607
- }
608
- class Conversations extends APIResource {
609
- /**
610
- * Create a conversation. Conversation is an interaction between an agent and a user, including one or more messages. | 调用接口创建一个会话。
611
- * @docs en: https://www.coze.com/docs/developer_guides/create_conversation?_lang=en
612
- * @docs zh: https://www.coze.cn/docs/developer_guides/create_conversation?_lang=zh
613
- * @param params - Required The parameters for creating a conversation | 创建会话所需的参数
614
- * @param params.messages - Optional Messages in the conversation. | 会话中的消息内容。
615
- * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
616
- * @param params.bot_id - Optional Bind and isolate conversation on different bots. | 绑定和隔离不同Bot的会话。
617
- * @returns Information about the created conversation. | 会话的基础信息。
618
- */ async create(params, options) {
619
- const apiUrl = '/v1/conversation/create';
620
- const response = await this._client.post(apiUrl, params, false, options);
621
- return response.data;
622
- }
623
- /**
624
- * Get the information of specific conversation. | 通过会话 ID 查看会话信息。
625
- * @docs en: https://www.coze.com/docs/developer_guides/retrieve_conversation?_lang=en
626
- * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_conversation?_lang=zh
627
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
628
- * @returns Information about the conversation. | 会话的基础信息。
629
- */ async retrieve(conversation_id, options) {
630
- const apiUrl = `/v1/conversation/retrieve?conversation_id=${conversation_id}`;
631
- const response = await this._client.get(apiUrl, null, false, options);
632
- return response.data;
633
- }
634
- /**
635
- * List all conversations. | 列出 Bot 下所有会话。
636
- * @param params
637
- * @param params.bot_id - Required Bot ID. | Bot ID。
638
- * @param params.page_num - Optional The page number. | 页码,默认值为 1。
639
- * @param params.page_size - Optional The number of conversations per page. | 每页的会话数量,默认值为 50。
640
- * @returns Information about the conversations. | 会话的信息。
641
- */ async list(params, options) {
642
- const apiUrl = '/v1/conversations';
643
- const response = await this._client.get(apiUrl, params, false, options);
644
- return response.data;
645
- }
646
- /**
647
- * Clear a conversation. | 清空会话。
648
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
649
- * @returns Information about the conversation session. | 会话的会话 ID。
650
- */ async clear(conversation_id, options) {
651
- const apiUrl = `/v1/conversations/${conversation_id}/clear`;
652
- const response = await this._client.post(apiUrl, null, false, options);
653
- return response.data;
654
- }
655
- constructor(...args){
656
- super(...args), this.messages = new messages_Messages(this._client);
657
- }
658
- }
659
- function bind(fn, thisArg) {
660
- return function() {
661
- return fn.apply(thisArg, arguments);
662
- };
663
- }
664
- // utils is a library of generic helper functions non-specific to axios
665
- const { toString: utils_toString } = Object.prototype;
666
- const { getPrototypeOf } = Object;
667
- const kindOf = ((cache)=>(thing)=>{
668
- const str = utils_toString.call(thing);
669
- return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
670
- })(Object.create(null));
671
- const kindOfTest = (type)=>{
672
- type = type.toLowerCase();
673
- return (thing)=>kindOf(thing) === type;
674
- };
675
- const typeOfTest = (type)=>(thing)=>typeof thing === type;
676
- /**
677
- * Determine if a value is an Array
678
- *
679
- * @param {Object} val The value to test
680
- *
681
- * @returns {boolean} True if value is an Array, otherwise false
682
- */ const { isArray } = Array;
683
- /**
684
- * Determine if a value is undefined
685
- *
686
- * @param {*} val The value to test
687
- *
688
- * @returns {boolean} True if the value is undefined, otherwise false
689
- */ const isUndefined = typeOfTest('undefined');
690
- /**
691
- * Determine if a value is a Buffer
692
- *
693
- * @param {*} val The value to test
694
- *
695
- * @returns {boolean} True if value is a Buffer, otherwise false
696
- */ function isBuffer(val) {
697
- return null !== val && !isUndefined(val) && null !== val.constructor && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
698
- }
699
353
  /**
700
- * Determine if a value is an ArrayBuffer
701
- *
702
- * @param {*} val The value to test
703
- *
704
- * @returns {boolean} True if value is an ArrayBuffer, otherwise false
705
- */ const isArrayBuffer = kindOfTest('ArrayBuffer');
706
- /**
707
- * Determine if a value is a view on an ArrayBuffer
708
- *
709
- * @param {*} val The value to test
710
- *
711
- * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
712
- */ function isArrayBufferView(val) {
713
- let result;
714
- result = 'undefined' != typeof ArrayBuffer && ArrayBuffer.isView ? ArrayBuffer.isView(val) : val && val.buffer && isArrayBuffer(val.buffer);
715
- return result;
716
- }
717
- /**
718
- * Determine if a value is a String
719
- *
720
- * @param {*} val The value to test
721
- *
722
- * @returns {boolean} True if value is a String, otherwise false
723
- */ const isString = typeOfTest('string');
724
- /**
725
- * Determine if a value is a Function
726
- *
727
- * @param {*} val The value to test
728
- * @returns {boolean} True if value is a Function, otherwise false
729
- */ const isFunction = typeOfTest('function');
730
- /**
731
- * Determine if a value is a Number
732
- *
733
- * @param {*} val The value to test
734
- *
735
- * @returns {boolean} True if value is a Number, otherwise false
736
- */ const isNumber = typeOfTest('number');
737
- /**
738
- * Determine if a value is an Object
739
- *
740
- * @param {*} thing The value to test
354
+ * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
741
355
  *
742
- * @returns {boolean} True if value is an Object, otherwise false
743
- */ const isObject = (thing)=>null !== thing && 'object' == typeof thing;
744
- /**
745
- * Determine if a value is a Boolean
356
+ * @param {string} content with BOM
746
357
  *
747
- * @param {*} thing The value to test
748
- * @returns {boolean} True if value is a Boolean, otherwise false
749
- */ const isBoolean = (thing)=>true === thing || false === thing;
358
+ * @returns {string} content value without BOM
359
+ */ const stripBOM = (content)=>{
360
+ if (0xFEFF === content.charCodeAt(0)) content = content.slice(1);
361
+ return content;
362
+ };
750
363
  /**
751
- * Determine if a value is a plain Object
752
- *
753
- * @param {*} val The value to test
364
+ * Inherit the prototype methods from one constructor into another
365
+ * @param {function} constructor
366
+ * @param {function} superConstructor
367
+ * @param {object} [props]
368
+ * @param {object} [descriptors]
754
369
  *
755
- * @returns {boolean} True if value is a plain Object, otherwise false
756
- */ const utils_isPlainObject = (val)=>{
757
- if ('object' !== kindOf(val)) return false;
758
- const prototype = getPrototypeOf(val);
759
- return (null === prototype || prototype === Object.prototype || null === Object.getPrototypeOf(prototype)) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
370
+ * @returns {void}
371
+ */ const inherits = (constructor, superConstructor, props, descriptors)=>{
372
+ constructor.prototype = Object.create(superConstructor.prototype, descriptors);
373
+ constructor.prototype.constructor = constructor;
374
+ Object.defineProperty(constructor, 'super', {
375
+ value: superConstructor.prototype
376
+ });
377
+ props && Object.assign(constructor.prototype, props);
760
378
  };
761
379
  /**
762
- * Determine if a value is a Date
763
- *
764
- * @param {*} val The value to test
380
+ * Resolve object with deep prototype chain to a flat object
381
+ * @param {Object} sourceObj source object
382
+ * @param {Object} [destObj]
383
+ * @param {Function|Boolean} [filter]
384
+ * @param {Function} [propFilter]
765
385
  *
766
- * @returns {boolean} True if value is a Date, otherwise false
767
- */ const isDate = kindOfTest('Date');
386
+ * @returns {Object}
387
+ */ const toFlatObject = (sourceObj, destObj, filter, propFilter)=>{
388
+ let props;
389
+ let i;
390
+ let prop;
391
+ const merged = {};
392
+ destObj = destObj || {};
393
+ // eslint-disable-next-line no-eq-null,eqeqeq
394
+ if (null == sourceObj) return destObj;
395
+ do {
396
+ props = Object.getOwnPropertyNames(sourceObj);
397
+ i = props.length;
398
+ while(i-- > 0){
399
+ prop = props[i];
400
+ if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
401
+ destObj[prop] = sourceObj[prop];
402
+ merged[prop] = true;
403
+ }
404
+ }
405
+ sourceObj = false !== filter && getPrototypeOf(sourceObj);
406
+ }while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
407
+ return destObj;
408
+ };
768
409
  /**
769
- * Determine if a value is a File
410
+ * Determines whether a string ends with the characters of a specified string
770
411
  *
771
- * @param {*} val The value to test
412
+ * @param {String} str
413
+ * @param {String} searchString
414
+ * @param {Number} [position= 0]
772
415
  *
773
- * @returns {boolean} True if value is a File, otherwise false
774
- */ const isFile = kindOfTest('File');
416
+ * @returns {boolean}
417
+ */ const endsWith = (str, searchString, position)=>{
418
+ str = String(str);
419
+ if (void 0 === position || position > str.length) position = str.length;
420
+ position -= searchString.length;
421
+ const lastIndex = str.indexOf(searchString, position);
422
+ return -1 !== lastIndex && lastIndex === position;
423
+ };
775
424
  /**
776
- * Determine if a value is a Blob
425
+ * Returns new array from array like object or null if failed
777
426
  *
778
- * @param {*} val The value to test
427
+ * @param {*} [thing]
779
428
  *
780
- * @returns {boolean} True if value is a Blob, otherwise false
781
- */ const isBlob = kindOfTest('Blob');
429
+ * @returns {?Array}
430
+ */ const toArray = (thing)=>{
431
+ if (!thing) return null;
432
+ if (isArray(thing)) return thing;
433
+ let i = thing.length;
434
+ if (!isNumber(i)) return null;
435
+ const arr = new Array(i);
436
+ while(i-- > 0)arr[i] = thing[i];
437
+ return arr;
438
+ };
782
439
  /**
783
- * Determine if a value is a FileList
440
+ * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
441
+ * thing passed in is an instance of Uint8Array
784
442
  *
785
- * @param {*} val The value to test
443
+ * @param {TypedArray}
786
444
  *
787
- * @returns {boolean} True if value is a File, otherwise false
788
- */ const utils_isFileList = kindOfTest('FileList');
445
+ * @returns {Array}
446
+ */ // eslint-disable-next-line func-names
447
+ const isTypedArray = ((TypedArray)=>(thing)=>TypedArray && thing instanceof TypedArray)('undefined' != typeof Uint8Array && getPrototypeOf(Uint8Array));
789
448
  /**
790
- * Determine if a value is a Stream
449
+ * For each entry in the object, call the function with the key and value.
791
450
  *
792
- * @param {*} val The value to test
451
+ * @param {Object<any, any>} obj - The object to iterate over.
452
+ * @param {Function} fn - The function to call for each entry.
793
453
  *
794
- * @returns {boolean} True if value is a Stream, otherwise false
795
- */ const utils_isStream = (val)=>isObject(val) && isFunction(val.pipe);
454
+ * @returns {void}
455
+ */ const forEachEntry = (obj, fn)=>{
456
+ const generator = obj && obj[Symbol.iterator];
457
+ const iterator = generator.call(obj);
458
+ let result;
459
+ while((result = iterator.next()) && !result.done){
460
+ const pair = result.value;
461
+ fn.call(obj, pair[0], pair[1]);
462
+ }
463
+ };
796
464
  /**
797
- * Determine if a value is a FormData
465
+ * It takes a regular expression and a string, and returns an array of all the matches
798
466
  *
799
- * @param {*} thing The value to test
467
+ * @param {string} regExp - The regular expression to match against.
468
+ * @param {string} str - The string to search.
800
469
  *
801
- * @returns {boolean} True if value is an FormData, otherwise false
802
- */ const utils_isFormData = (thing)=>{
803
- let kind;
804
- return thing && ('function' == typeof FormData && thing instanceof FormData || isFunction(thing.append) && ('formdata' === (kind = kindOf(thing)) || // detect form-data instance
805
- 'object' === kind && isFunction(thing.toString) && '[object FormData]' === thing.toString()));
470
+ * @returns {Array<boolean>}
471
+ */ const matchAll = (regExp, str)=>{
472
+ let matches;
473
+ const arr = [];
474
+ while(null !== (matches = regExp.exec(str)))arr.push(matches);
475
+ return arr;
806
476
  };
477
+ /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ const isHTMLForm = kindOfTest('HTMLFormElement');
478
+ const toCamelCase = (str)=>str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function(m, p1, p2) {
479
+ return p1.toUpperCase() + p2;
480
+ });
481
+ /* Creating a function that will check if an object has a property. */ const utils_hasOwnProperty = (({ hasOwnProperty })=>(obj, prop)=>hasOwnProperty.call(obj, prop))(Object.prototype);
807
482
  /**
808
- * Determine if a value is a URLSearchParams object
809
- *
810
- * @param {*} val The value to test
811
- *
812
- * @returns {boolean} True if value is a URLSearchParams object, otherwise false
813
- */ const isURLSearchParams = kindOfTest('URLSearchParams');
814
- const [isReadableStream, isRequest, isResponse, isHeaders] = [
815
- 'ReadableStream',
816
- 'Request',
817
- 'Response',
818
- 'Headers'
819
- ].map(kindOfTest);
820
- /**
821
- * Trim excess whitespace off the beginning and end of a string
822
- *
823
- * @param {String} str The String to trim
824
- *
825
- * @returns {String} The String freed of excess whitespace
826
- */ const trim = (str)=>str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
827
- /**
828
- * Iterate over an Array or an Object invoking a function for each item.
829
- *
830
- * If `obj` is an Array callback will be called passing
831
- * the value, index, and complete array for each item.
832
- *
833
- * If 'obj' is an Object callback will be called passing
834
- * the value, key, and complete object for each property.
835
- *
836
- * @param {Object|Array} obj The object to iterate
837
- * @param {Function} fn The callback to invoke for each item
838
- *
839
- * @param {Boolean} [allOwnKeys = false]
840
- * @returns {any}
841
- */ function forEach(obj, fn, { allOwnKeys = false } = {}) {
842
- // Don't bother if no value provided
843
- if (null == obj) return;
844
- let i;
845
- let l;
846
- // Force an array if not already something iterable
847
- if ('object' != typeof obj) /*eslint no-param-reassign:0*/ obj = [
848
- obj
849
- ];
850
- if (isArray(obj)) // Iterate over array values
851
- for(i = 0, l = obj.length; i < l; i++)fn.call(null, obj[i], i, obj);
852
- else {
853
- // Iterate over object keys
854
- const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
855
- const len = keys.length;
856
- let key;
857
- for(i = 0; i < len; i++){
858
- key = keys[i];
859
- fn.call(null, obj[key], key, obj);
860
- }
861
- }
862
- }
863
- function findKey(obj, key) {
864
- key = key.toLowerCase();
865
- const keys = Object.keys(obj);
866
- let i = keys.length;
867
- let _key;
868
- while(i-- > 0){
869
- _key = keys[i];
870
- if (key === _key.toLowerCase()) return _key;
871
- }
872
- return null;
873
- }
874
- const _global = (()=>{
875
- /*eslint no-undef:0*/ if ("undefined" != typeof globalThis) return globalThis;
876
- return "undefined" != typeof self ? self : 'undefined' != typeof window ? window : global;
877
- })();
878
- const isContextDefined = (context)=>!isUndefined(context) && context !== _global;
879
- /**
880
- * Accepts varargs expecting each argument to be an object, then
881
- * immutably merges the properties of each object and returns result.
882
- *
883
- * When multiple objects contain the same key the later object in
884
- * the arguments list will take precedence.
885
- *
886
- * Example:
887
- *
888
- * ```js
889
- * var result = merge({foo: 123}, {foo: 456});
890
- * console.log(result.foo); // outputs 456
891
- * ```
892
- *
893
- * @param {Object} obj1 Object to merge
894
- *
895
- * @returns {Object} Result of all merge properties
896
- */ function utils_merge() {
897
- const { caseless } = isContextDefined(this) && this || {};
898
- const result = {};
899
- const assignValue = (val, key)=>{
900
- const targetKey = caseless && findKey(result, key) || key;
901
- if (utils_isPlainObject(result[targetKey]) && utils_isPlainObject(val)) result[targetKey] = utils_merge(result[targetKey], val);
902
- else if (utils_isPlainObject(val)) result[targetKey] = utils_merge({}, val);
903
- else if (isArray(val)) result[targetKey] = val.slice();
904
- else result[targetKey] = val;
905
- };
906
- for(let i = 0, l = arguments.length; i < l; i++)arguments[i] && forEach(arguments[i], assignValue);
907
- return result;
908
- }
909
- /**
910
- * Extends object a by mutably adding to it the properties of object b.
911
- *
912
- * @param {Object} a The object to be extended
913
- * @param {Object} b The object to copy properties from
914
- * @param {Object} thisArg The object to bind function to
915
- *
916
- * @param {Boolean} [allOwnKeys]
917
- * @returns {Object} The resulting value of object a
918
- */ const extend = (a, b, thisArg, { allOwnKeys } = {})=>{
919
- forEach(b, (val, key)=>{
920
- if (thisArg && isFunction(val)) a[key] = bind(val, thisArg);
921
- else a[key] = val;
922
- }, {
923
- allOwnKeys
924
- });
925
- return a;
926
- };
927
- /**
928
- * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
929
- *
930
- * @param {string} content with BOM
931
- *
932
- * @returns {string} content value without BOM
933
- */ const stripBOM = (content)=>{
934
- if (0xFEFF === content.charCodeAt(0)) content = content.slice(1);
935
- return content;
936
- };
937
- /**
938
- * Inherit the prototype methods from one constructor into another
939
- * @param {function} constructor
940
- * @param {function} superConstructor
941
- * @param {object} [props]
942
- * @param {object} [descriptors]
943
- *
944
- * @returns {void}
945
- */ const inherits = (constructor, superConstructor, props, descriptors)=>{
946
- constructor.prototype = Object.create(superConstructor.prototype, descriptors);
947
- constructor.prototype.constructor = constructor;
948
- Object.defineProperty(constructor, 'super', {
949
- value: superConstructor.prototype
950
- });
951
- props && Object.assign(constructor.prototype, props);
952
- };
953
- /**
954
- * Resolve object with deep prototype chain to a flat object
955
- * @param {Object} sourceObj source object
956
- * @param {Object} [destObj]
957
- * @param {Function|Boolean} [filter]
958
- * @param {Function} [propFilter]
959
- *
960
- * @returns {Object}
961
- */ const toFlatObject = (sourceObj, destObj, filter, propFilter)=>{
962
- let props;
963
- let i;
964
- let prop;
965
- const merged = {};
966
- destObj = destObj || {};
967
- // eslint-disable-next-line no-eq-null,eqeqeq
968
- if (null == sourceObj) return destObj;
969
- do {
970
- props = Object.getOwnPropertyNames(sourceObj);
971
- i = props.length;
972
- while(i-- > 0){
973
- prop = props[i];
974
- if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
975
- destObj[prop] = sourceObj[prop];
976
- merged[prop] = true;
977
- }
978
- }
979
- sourceObj = false !== filter && getPrototypeOf(sourceObj);
980
- }while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
981
- return destObj;
982
- };
983
- /**
984
- * Determines whether a string ends with the characters of a specified string
985
- *
986
- * @param {String} str
987
- * @param {String} searchString
988
- * @param {Number} [position= 0]
989
- *
990
- * @returns {boolean}
991
- */ const endsWith = (str, searchString, position)=>{
992
- str = String(str);
993
- if (void 0 === position || position > str.length) position = str.length;
994
- position -= searchString.length;
995
- const lastIndex = str.indexOf(searchString, position);
996
- return -1 !== lastIndex && lastIndex === position;
997
- };
998
- /**
999
- * Returns new array from array like object or null if failed
1000
- *
1001
- * @param {*} [thing]
1002
- *
1003
- * @returns {?Array}
1004
- */ const toArray = (thing)=>{
1005
- if (!thing) return null;
1006
- if (isArray(thing)) return thing;
1007
- let i = thing.length;
1008
- if (!isNumber(i)) return null;
1009
- const arr = new Array(i);
1010
- while(i-- > 0)arr[i] = thing[i];
1011
- return arr;
1012
- };
1013
- /**
1014
- * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
1015
- * thing passed in is an instance of Uint8Array
1016
- *
1017
- * @param {TypedArray}
1018
- *
1019
- * @returns {Array}
1020
- */ // eslint-disable-next-line func-names
1021
- const isTypedArray = ((TypedArray)=>(thing)=>TypedArray && thing instanceof TypedArray)('undefined' != typeof Uint8Array && getPrototypeOf(Uint8Array));
1022
- /**
1023
- * For each entry in the object, call the function with the key and value.
1024
- *
1025
- * @param {Object<any, any>} obj - The object to iterate over.
1026
- * @param {Function} fn - The function to call for each entry.
1027
- *
1028
- * @returns {void}
1029
- */ const forEachEntry = (obj, fn)=>{
1030
- const generator = obj && obj[Symbol.iterator];
1031
- const iterator = generator.call(obj);
1032
- let result;
1033
- while((result = iterator.next()) && !result.done){
1034
- const pair = result.value;
1035
- fn.call(obj, pair[0], pair[1]);
1036
- }
1037
- };
1038
- /**
1039
- * It takes a regular expression and a string, and returns an array of all the matches
1040
- *
1041
- * @param {string} regExp - The regular expression to match against.
1042
- * @param {string} str - The string to search.
1043
- *
1044
- * @returns {Array<boolean>}
1045
- */ const matchAll = (regExp, str)=>{
1046
- let matches;
1047
- const arr = [];
1048
- while(null !== (matches = regExp.exec(str)))arr.push(matches);
1049
- return arr;
1050
- };
1051
- /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ const isHTMLForm = kindOfTest('HTMLFormElement');
1052
- const toCamelCase = (str)=>str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function(m, p1, p2) {
1053
- return p1.toUpperCase() + p2;
1054
- });
1055
- /* Creating a function that will check if an object has a property. */ const utils_hasOwnProperty = (({ hasOwnProperty })=>(obj, prop)=>hasOwnProperty.call(obj, prop))(Object.prototype);
1056
- /**
1057
- * Determine if a value is a RegExp object
483
+ * Determine if a value is a RegExp object
1058
484
  *
1059
485
  * @param {*} val The value to test
1060
486
  *
@@ -1174,7 +600,7 @@ const asap = 'undefined' != typeof queueMicrotask ? queueMicrotask.bind(_global)
1174
600
  isNumber,
1175
601
  isBoolean,
1176
602
  isObject,
1177
- isPlainObject: utils_isPlainObject,
603
+ isPlainObject,
1178
604
  isReadableStream,
1179
605
  isRequest,
1180
606
  isResponse,
@@ -1616,7 +1042,7 @@ class InterceptorManager_InterceptorManager {
1616
1042
  ]
1617
1043
  };
1618
1044
  const hasBrowserEnv = 'undefined' != typeof window && 'undefined' != typeof document;
1619
- const _navigator = 'object' == typeof navigator && navigator || void 0;
1045
+ const utils_navigator = 'object' == typeof navigator && navigator || void 0;
1620
1046
  /**
1621
1047
  * Determine if we're running in a standard browser environment
1622
1048
  *
@@ -1633,11 +1059,11 @@ const _navigator = 'object' == typeof navigator && navigator || void 0;
1633
1059
  * navigator.product -> 'NativeScript' or 'NS'
1634
1060
  *
1635
1061
  * @returns {boolean}
1636
- */ const hasStandardBrowserEnv = hasBrowserEnv && (!_navigator || [
1062
+ */ const hasStandardBrowserEnv = hasBrowserEnv && (!utils_navigator || [
1637
1063
  'ReactNative',
1638
1064
  'NativeScript',
1639
1065
  'NS'
1640
- ].indexOf(_navigator.product) < 0);
1066
+ ].indexOf(utils_navigator.product) < 0);
1641
1067
  /**
1642
1068
  * Determine if we're running in a standard browser webWorker environment
1643
1069
  *
@@ -2372,7 +1798,7 @@ const headersToObject = (thing)=>thing instanceof AxiosHeaders ? {
2372
1798
  * @param {Object} config2
2373
1799
  *
2374
1800
  * @returns {Object} New object resulting from merging config2 to config1
2375
- */ function mergeConfig_mergeConfig(config1, config2) {
1801
+ */ function mergeConfig(config1, config2) {
2376
1802
  // eslint-disable-next-line no-param-reassign
2377
1803
  config2 = config2 || {};
2378
1804
  const config = {};
@@ -2442,7 +1868,7 @@ const headersToObject = (thing)=>thing instanceof AxiosHeaders ? {
2442
1868
  return config;
2443
1869
  }
2444
1870
  /* ESM default export */ const resolveConfig = (config)=>{
2445
- const newConfig = mergeConfig_mergeConfig({}, config);
1871
+ const newConfig = mergeConfig({}, config);
2446
1872
  let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig;
2447
1873
  newConfig.headers = headers = AxiosHeaders.from(headers);
2448
1874
  newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer);
@@ -3048,7 +2474,7 @@ const Axios_validators = helpers_validator.validators;
3048
2474
  config = config || {};
3049
2475
  config.url = configOrUrl;
3050
2476
  } else config = configOrUrl || {};
3051
- config = mergeConfig_mergeConfig(this.defaults, config);
2477
+ config = mergeConfig(this.defaults, config);
3052
2478
  const { transitional, paramsSerializer, headers } = config;
3053
2479
  if (void 0 !== transitional) helpers_validator.assertOptions(transitional, {
3054
2480
  silentJSONParsing: Axios_validators.transitional(Axios_validators.boolean),
@@ -3107,320 +2533,887 @@ const Axios_validators = helpers_validator.validators;
3107
2533
  while(i < len)promise = promise.then(chain[i++], chain[i++]);
3108
2534
  return promise;
3109
2535
  }
3110
- len = requestInterceptorChain.length;
3111
- let newConfig = config;
3112
- i = 0;
3113
- while(i < len){
3114
- const onFulfilled = requestInterceptorChain[i++];
3115
- const onRejected = requestInterceptorChain[i++];
3116
- try {
3117
- newConfig = onFulfilled(newConfig);
2536
+ len = requestInterceptorChain.length;
2537
+ let newConfig = config;
2538
+ i = 0;
2539
+ while(i < len){
2540
+ const onFulfilled = requestInterceptorChain[i++];
2541
+ const onRejected = requestInterceptorChain[i++];
2542
+ try {
2543
+ newConfig = onFulfilled(newConfig);
2544
+ } catch (error) {
2545
+ onRejected.call(this, error);
2546
+ break;
2547
+ }
2548
+ }
2549
+ try {
2550
+ promise = dispatchRequest.call(this, newConfig);
2551
+ } catch (error) {
2552
+ return Promise.reject(error);
2553
+ }
2554
+ i = 0;
2555
+ len = responseInterceptorChain.length;
2556
+ while(i < len)promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
2557
+ return promise;
2558
+ }
2559
+ getUri(config) {
2560
+ config = mergeConfig(this.defaults, config);
2561
+ const fullPath = buildFullPath(config.baseURL, config.url);
2562
+ return buildURL(fullPath, config.params, config.paramsSerializer);
2563
+ }
2564
+ }
2565
+ // Provide aliases for supported request methods
2566
+ utils.forEach([
2567
+ 'delete',
2568
+ 'get',
2569
+ 'head',
2570
+ 'options'
2571
+ ], function(method) {
2572
+ /*eslint func-names:0*/ Axios_Axios.prototype[method] = function(url, config) {
2573
+ return this.request(mergeConfig(config || {}, {
2574
+ method,
2575
+ url,
2576
+ data: (config || {}).data
2577
+ }));
2578
+ };
2579
+ });
2580
+ utils.forEach([
2581
+ 'post',
2582
+ 'put',
2583
+ 'patch'
2584
+ ], function(method) {
2585
+ /*eslint func-names:0*/ function generateHTTPMethod(isForm) {
2586
+ return function(url, data, config) {
2587
+ return this.request(mergeConfig(config || {}, {
2588
+ method,
2589
+ headers: isForm ? {
2590
+ 'Content-Type': 'multipart/form-data'
2591
+ } : {},
2592
+ url,
2593
+ data
2594
+ }));
2595
+ };
2596
+ }
2597
+ Axios_Axios.prototype[method] = generateHTTPMethod();
2598
+ Axios_Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
2599
+ });
2600
+ /* ESM default export */ const Axios = Axios_Axios;
2601
+ /**
2602
+ * A `CancelToken` is an object that can be used to request cancellation of an operation.
2603
+ *
2604
+ * @param {Function} executor The executor function.
2605
+ *
2606
+ * @returns {CancelToken}
2607
+ */ class CancelToken_CancelToken {
2608
+ constructor(executor){
2609
+ if ('function' != typeof executor) throw new TypeError('executor must be a function.');
2610
+ let resolvePromise;
2611
+ this.promise = new Promise(function(resolve) {
2612
+ resolvePromise = resolve;
2613
+ });
2614
+ const token = this;
2615
+ // eslint-disable-next-line func-names
2616
+ this.promise.then((cancel)=>{
2617
+ if (!token._listeners) return;
2618
+ let i = token._listeners.length;
2619
+ while(i-- > 0)token._listeners[i](cancel);
2620
+ token._listeners = null;
2621
+ });
2622
+ // eslint-disable-next-line func-names
2623
+ this.promise.then = (onfulfilled)=>{
2624
+ let _resolve;
2625
+ // eslint-disable-next-line func-names
2626
+ const promise = new Promise((resolve)=>{
2627
+ token.subscribe(resolve);
2628
+ _resolve = resolve;
2629
+ }).then(onfulfilled);
2630
+ promise.cancel = function() {
2631
+ token.unsubscribe(_resolve);
2632
+ };
2633
+ return promise;
2634
+ };
2635
+ executor(function(message, config, request) {
2636
+ if (token.reason) // Cancellation has already been requested
2637
+ return;
2638
+ token.reason = new CanceledError(message, config, request);
2639
+ resolvePromise(token.reason);
2640
+ });
2641
+ }
2642
+ /**
2643
+ * Throws a `CanceledError` if cancellation has been requested.
2644
+ */ throwIfRequested() {
2645
+ if (this.reason) throw this.reason;
2646
+ }
2647
+ /**
2648
+ * Subscribe to the cancel signal
2649
+ */ subscribe(listener) {
2650
+ if (this.reason) {
2651
+ listener(this.reason);
2652
+ return;
2653
+ }
2654
+ if (this._listeners) this._listeners.push(listener);
2655
+ else this._listeners = [
2656
+ listener
2657
+ ];
2658
+ }
2659
+ /**
2660
+ * Unsubscribe from the cancel signal
2661
+ */ unsubscribe(listener) {
2662
+ if (!this._listeners) return;
2663
+ const index = this._listeners.indexOf(listener);
2664
+ if (-1 !== index) this._listeners.splice(index, 1);
2665
+ }
2666
+ toAbortSignal() {
2667
+ const controller = new AbortController();
2668
+ const abort = (err)=>{
2669
+ controller.abort(err);
2670
+ };
2671
+ this.subscribe(abort);
2672
+ controller.signal.unsubscribe = ()=>this.unsubscribe(abort);
2673
+ return controller.signal;
2674
+ }
2675
+ /**
2676
+ * Returns an object that contains a new `CancelToken` and a function that, when called,
2677
+ * cancels the `CancelToken`.
2678
+ */ static source() {
2679
+ let cancel;
2680
+ const token = new CancelToken_CancelToken(function(c) {
2681
+ cancel = c;
2682
+ });
2683
+ return {
2684
+ token,
2685
+ cancel
2686
+ };
2687
+ }
2688
+ }
2689
+ /* ESM default export */ const CancelToken = CancelToken_CancelToken;
2690
+ /**
2691
+ * Syntactic sugar for invoking a function and expanding an array for arguments.
2692
+ *
2693
+ * Common use case would be to use `Function.prototype.apply`.
2694
+ *
2695
+ * ```js
2696
+ * function f(x, y, z) {}
2697
+ * var args = [1, 2, 3];
2698
+ * f.apply(null, args);
2699
+ * ```
2700
+ *
2701
+ * With `spread` this example can be re-written.
2702
+ *
2703
+ * ```js
2704
+ * spread(function(x, y, z) {})([1, 2, 3]);
2705
+ * ```
2706
+ *
2707
+ * @param {Function} callback
2708
+ *
2709
+ * @returns {Function}
2710
+ */ function spread(callback) {
2711
+ return function(arr) {
2712
+ return callback.apply(null, arr);
2713
+ };
2714
+ }
2715
+ /**
2716
+ * Determines whether the payload is an error thrown by Axios
2717
+ *
2718
+ * @param {*} payload The value to test
2719
+ *
2720
+ * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
2721
+ */ function isAxiosError(payload) {
2722
+ return utils.isObject(payload) && true === payload.isAxiosError;
2723
+ }
2724
+ const HttpStatusCode = {
2725
+ Continue: 100,
2726
+ SwitchingProtocols: 101,
2727
+ Processing: 102,
2728
+ EarlyHints: 103,
2729
+ Ok: 200,
2730
+ Created: 201,
2731
+ Accepted: 202,
2732
+ NonAuthoritativeInformation: 203,
2733
+ NoContent: 204,
2734
+ ResetContent: 205,
2735
+ PartialContent: 206,
2736
+ MultiStatus: 207,
2737
+ AlreadyReported: 208,
2738
+ ImUsed: 226,
2739
+ MultipleChoices: 300,
2740
+ MovedPermanently: 301,
2741
+ Found: 302,
2742
+ SeeOther: 303,
2743
+ NotModified: 304,
2744
+ UseProxy: 305,
2745
+ Unused: 306,
2746
+ TemporaryRedirect: 307,
2747
+ PermanentRedirect: 308,
2748
+ BadRequest: 400,
2749
+ Unauthorized: 401,
2750
+ PaymentRequired: 402,
2751
+ Forbidden: 403,
2752
+ NotFound: 404,
2753
+ MethodNotAllowed: 405,
2754
+ NotAcceptable: 406,
2755
+ ProxyAuthenticationRequired: 407,
2756
+ RequestTimeout: 408,
2757
+ Conflict: 409,
2758
+ Gone: 410,
2759
+ LengthRequired: 411,
2760
+ PreconditionFailed: 412,
2761
+ PayloadTooLarge: 413,
2762
+ UriTooLong: 414,
2763
+ UnsupportedMediaType: 415,
2764
+ RangeNotSatisfiable: 416,
2765
+ ExpectationFailed: 417,
2766
+ ImATeapot: 418,
2767
+ MisdirectedRequest: 421,
2768
+ UnprocessableEntity: 422,
2769
+ Locked: 423,
2770
+ FailedDependency: 424,
2771
+ TooEarly: 425,
2772
+ UpgradeRequired: 426,
2773
+ PreconditionRequired: 428,
2774
+ TooManyRequests: 429,
2775
+ RequestHeaderFieldsTooLarge: 431,
2776
+ UnavailableForLegalReasons: 451,
2777
+ InternalServerError: 500,
2778
+ NotImplemented: 501,
2779
+ BadGateway: 502,
2780
+ ServiceUnavailable: 503,
2781
+ GatewayTimeout: 504,
2782
+ HttpVersionNotSupported: 505,
2783
+ VariantAlsoNegotiates: 506,
2784
+ InsufficientStorage: 507,
2785
+ LoopDetected: 508,
2786
+ NotExtended: 510,
2787
+ NetworkAuthenticationRequired: 511
2788
+ };
2789
+ Object.entries(HttpStatusCode).forEach(([key, value])=>{
2790
+ HttpStatusCode[value] = key;
2791
+ });
2792
+ /* ESM default export */ const helpers_HttpStatusCode = HttpStatusCode;
2793
+ /**
2794
+ * Create an instance of Axios
2795
+ *
2796
+ * @param {Object} defaultConfig The default config for the instance
2797
+ *
2798
+ * @returns {Axios} A new instance of Axios
2799
+ */ function createInstance(defaultConfig) {
2800
+ const context = new Axios(defaultConfig);
2801
+ const instance = bind(Axios.prototype.request, context);
2802
+ // Copy axios.prototype to instance
2803
+ utils.extend(instance, Axios.prototype, context, {
2804
+ allOwnKeys: true
2805
+ });
2806
+ // Copy context to instance
2807
+ utils.extend(instance, context, null, {
2808
+ allOwnKeys: true
2809
+ });
2810
+ // Factory for creating new instances
2811
+ instance.create = function(instanceConfig) {
2812
+ return createInstance(mergeConfig(defaultConfig, instanceConfig));
2813
+ };
2814
+ return instance;
2815
+ }
2816
+ // Create the default instance to be exported
2817
+ const axios = createInstance(defaults);
2818
+ // Expose Axios class to allow class inheritance
2819
+ axios.Axios = Axios;
2820
+ // Expose Cancel & CancelToken
2821
+ axios.CanceledError = CanceledError;
2822
+ axios.CancelToken = CancelToken;
2823
+ axios.isCancel = isCancel;
2824
+ axios.VERSION = VERSION;
2825
+ axios.toFormData = toFormData;
2826
+ // Expose AxiosError class
2827
+ axios.AxiosError = core_AxiosError;
2828
+ // alias for CanceledError for backward compatibility
2829
+ axios.Cancel = axios.CanceledError;
2830
+ // Expose all/spread
2831
+ axios.all = function(promises) {
2832
+ return Promise.all(promises);
2833
+ };
2834
+ axios.spread = spread;
2835
+ // Expose isAxiosError
2836
+ axios.isAxiosError = isAxiosError;
2837
+ // Expose mergeConfig
2838
+ axios.mergeConfig = mergeConfig;
2839
+ axios.AxiosHeaders = AxiosHeaders;
2840
+ axios.formToJSON = (thing)=>formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
2841
+ axios.getAdapter = adapters_adapters.getAdapter;
2842
+ axios.HttpStatusCode = helpers_HttpStatusCode;
2843
+ axios.default = axios;
2844
+ // this module should only have a default export
2845
+ /* ESM default export */ const lib_axios = axios;
2846
+ // This module is intended to unwrap Axios default export as named.
2847
+ // Keep top-level export same with static properties
2848
+ // so that it can keep same with es module or cjs
2849
+ const { Axios: axios_Axios, AxiosError: axios_AxiosError, CanceledError: axios_CanceledError, isCancel: axios_isCancel, CancelToken: axios_CancelToken, VERSION: axios_VERSION, all: axios_all, Cancel, isAxiosError: axios_isAxiosError, spread: axios_spread, toFormData: axios_toFormData, AxiosHeaders: axios_AxiosHeaders, HttpStatusCode: axios_HttpStatusCode, formToJSON, getAdapter, mergeConfig: axios_mergeConfig } = lib_axios;
2850
+ // EXTERNAL MODULE: os (ignored)
2851
+ var os_ignored_ = __webpack_require__("?9caf");
2852
+ // EXTERNAL MODULE: crypto (ignored)
2853
+ __webpack_require__("?e272");
2854
+ // EXTERNAL MODULE: jsonwebtoken (ignored)
2855
+ __webpack_require__("?5742");
2856
+ class APIResource {
2857
+ constructor(client){
2858
+ this._client = client;
2859
+ }
2860
+ }
2861
+ /* eslint-disable @typescript-eslint/no-namespace */ class Bots extends APIResource {
2862
+ /**
2863
+ * Create a new agent. | 调用接口创建一个新的智能体。
2864
+ * @docs en:https://www.coze.com/docs/developer_guides/create_bot?_lang=en
2865
+ * @docs zh:https://www.coze.cn/docs/developer_guides/create_bot?_lang=zh
2866
+ * @param params - Required The parameters for creating a bot. | 创建 Bot 的参数。
2867
+ * @param params.space_id - Required The Space ID of the space where the agent is located. | Bot 所在的空间的 Space ID。
2868
+ * @param params.name - Required The name of the agent. It should be 1 to 20 characters long. | Bot 的名称。
2869
+ * @param params.description - Optional The description of the agent. It can be 0 to 500 characters long. | Bot 的描述信息。
2870
+ * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
2871
+ * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
2872
+ * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
2873
+ * @returns Information about the created bot. | 创建的 Bot 信息。
2874
+ */ async create(params, options) {
2875
+ const apiUrl = '/v1/bot/create';
2876
+ const result = await this._client.post(apiUrl, params, false, options);
2877
+ return result.data;
2878
+ }
2879
+ /**
2880
+ * Update the configuration of an agent. | 调用接口修改智能体的配置。
2881
+ * @docs en:https://www.coze.com/docs/developer_guides/update_bot?_lang=en
2882
+ * @docs zh:https://www.coze.cn/docs/developer_guides/update_bot?_lang=zh
2883
+ * @param params - Required The parameters for updating a bot. | 修改 Bot 的参数。
2884
+ * @param params.bot_id - Required The ID of the agent that the API interacts with. | 待修改配置的智能体ID。
2885
+ * @param params.name - Optional The name of the agent. | Bot 的名称。
2886
+ * @param params.description - Optional The description of the agent. | Bot 的描述信息。
2887
+ * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
2888
+ * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
2889
+ * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
2890
+ * @param params.knowledge - Optional Knowledge configurations of the agent. | Bot 的知识库配置。
2891
+ * @returns Undefined | 无返回值
2892
+ */ async update(params, options) {
2893
+ const apiUrl = '/v1/bot/update';
2894
+ const result = await this._client.post(apiUrl, params, false, options);
2895
+ return result.data;
2896
+ }
2897
+ /**
2898
+ * Get the agents published as API service. | 调用接口查看指定空间发布到 Agent as API 渠道的智能体列表。
2899
+ * @docs en:https://www.coze.com/docs/developer_guides/published_bots_list?_lang=en
2900
+ * @docs zh:https://www.coze.cn/docs/developer_guides/published_bots_list?_lang=zh
2901
+ * @param params - Required The parameters for listing bots. | 列出 Bot 的参数。
2902
+ * @param params.space_id - Required The ID of the space. | Bot 所在的空间的 Space ID。
2903
+ * @param params.page_size - Optional Pagination size. | 分页大小。
2904
+ * @param params.page_index - Optional Page number for paginated queries. | 分页查询时的页码。
2905
+ * @returns List of published bots. | 已发布的 Bot 列表。
2906
+ */ async list(params, options) {
2907
+ const apiUrl = '/v1/space/published_bots_list';
2908
+ const result = await this._client.get(apiUrl, params, false, options);
2909
+ return result.data;
2910
+ }
2911
+ /**
2912
+ * Publish the specified agent as an API service. | 调用接口创建一个新的智能体。
2913
+ * @docs en:https://www.coze.com/docs/developer_guides/publish_bot?_lang=en
2914
+ * @docs zh:https://www.coze.cn/docs/developer_guides/publish_bot?_lang=zh
2915
+ * @param params - Required The parameters for publishing a bot. | 发布 Bot 的参数。
2916
+ * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要发布的智能体ID。
2917
+ * @param params.connector_ids - Required The list of publishing channel IDs for the agent. | 智能体的发布渠道 ID 列表。
2918
+ * @returns Undefined | 无返回值
2919
+ */ async publish(params, options) {
2920
+ const apiUrl = '/v1/bot/publish';
2921
+ const result = await this._client.post(apiUrl, params, false, options);
2922
+ return result.data;
2923
+ }
2924
+ /**
2925
+ * Get the configuration information of the agent. | 获取指定智能体的配置信息。
2926
+ * @docs en:https://www.coze.com/docs/developer_guides/get_metadata?_lang=en
2927
+ * @docs zh:https://www.coze.cn/docs/developer_guides/get_metadata?_lang=zh
2928
+ * @param params - Required The parameters for retrieving a bot. | 获取 Bot 的参数。
2929
+ * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要查看的智能体ID。
2930
+ * @returns Information about the bot. | Bot 的配置信息。
2931
+ */ async retrieve(params, options) {
2932
+ const apiUrl = '/v1/bot/get_online_info';
2933
+ const result = await this._client.get(apiUrl, params, false, options);
2934
+ return result.data;
2935
+ }
2936
+ }
2937
+ /* eslint-disable security/detect-object-injection */ /* eslint-disable @typescript-eslint/no-explicit-any */ function safeJsonParse(jsonString) {
2938
+ let defaultValue = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : '';
2939
+ try {
2940
+ return JSON.parse(jsonString);
2941
+ } catch (error) {
2942
+ return defaultValue;
2943
+ }
2944
+ }
2945
+ function sleep(ms) {
2946
+ return new Promise((resolve)=>{
2947
+ setTimeout(resolve, ms);
2948
+ });
2949
+ }
2950
+ function isBrowser() {
2951
+ return 'undefined' != typeof window;
2952
+ }
2953
+ function esm_isPlainObject(obj) {
2954
+ if ('object' != typeof obj || null === obj) return false;
2955
+ const proto = Object.getPrototypeOf(obj);
2956
+ if (null === proto) return true;
2957
+ let baseProto = proto;
2958
+ while(null !== Object.getPrototypeOf(baseProto))baseProto = Object.getPrototypeOf(baseProto);
2959
+ return proto === baseProto;
2960
+ }
2961
+ function esm_mergeConfig() {
2962
+ for(var _len = arguments.length, objects = new Array(_len), _key = 0; _key < _len; _key++)objects[_key] = arguments[_key];
2963
+ return objects.reduce((result, obj)=>{
2964
+ if (void 0 === obj) return result || {};
2965
+ for(const key in obj)if (Object.prototype.hasOwnProperty.call(obj, key)) {
2966
+ if (esm_isPlainObject(obj[key]) && !Array.isArray(obj[key])) result[key] = esm_mergeConfig(result[key] || {}, obj[key]);
2967
+ else result[key] = obj[key];
2968
+ }
2969
+ return result;
2970
+ }, {});
2971
+ }
2972
+ function isPersonalAccessToken(token) {
2973
+ return null == token ? void 0 : token.startsWith('pat_');
2974
+ }
2975
+ /* eslint-disable max-params */ class CozeError extends Error {
2976
+ }
2977
+ class APIError extends CozeError {
2978
+ static makeMessage(status, errorBody, message, headers) {
2979
+ if (!errorBody && message) return message;
2980
+ if (errorBody) {
2981
+ const list = [];
2982
+ const { code, msg, error } = errorBody;
2983
+ if (code) list.push(`code: ${code}`);
2984
+ if (msg) list.push(`msg: ${msg}`);
2985
+ if ((null == error ? void 0 : error.detail) && msg !== error.detail) list.push(`detail: ${error.detail}`);
2986
+ const logId = (null == error ? void 0 : error.logid) || (null == headers ? void 0 : headers['x-tt-logid']);
2987
+ if (logId) list.push(`logid: ${logId}`);
2988
+ const help_doc = null == error ? void 0 : error.help_doc;
2989
+ if (help_doc) list.push(`help doc: ${help_doc}`);
2990
+ return list.join(', ');
2991
+ }
2992
+ if (status) return `http status code: ${status} (no body)`;
2993
+ return '(no status code or body)';
2994
+ }
2995
+ static generate(status, errorResponse, message, headers) {
2996
+ if (!status) return new APIConnectionError({
2997
+ cause: castToError(errorResponse)
2998
+ });
2999
+ const error = errorResponse;
3000
+ // https://www.coze.cn/docs/developer_guides/coze_error_codes
3001
+ if (400 === status || (null == error ? void 0 : error.code) === 4000) return new BadRequestError(status, error, message, headers);
3002
+ if (401 === status || (null == error ? void 0 : error.code) === 4100) return new AuthenticationError(status, error, message, headers);
3003
+ if (403 === status || (null == error ? void 0 : error.code) === 4101) return new PermissionDeniedError(status, error, message, headers);
3004
+ if (404 === status || (null == error ? void 0 : error.code) === 4200) return new NotFoundError(status, error, message, headers);
3005
+ if (429 === status || (null == error ? void 0 : error.code) === 4013) return new RateLimitError(status, error, message, headers);
3006
+ if (408 === status) return new TimeoutError(status, error, message, headers);
3007
+ if (502 === status) return new GatewayError(status, error, message, headers);
3008
+ if (status >= 500) return new InternalServerError(status, error, message, headers);
3009
+ return new APIError(status, error, message, headers);
3010
+ }
3011
+ constructor(status, error, message, headers){
3012
+ var _error_error, _error_error1;
3013
+ super(`${APIError.makeMessage(status, error, message, headers)}`);
3014
+ this.status = status;
3015
+ this.headers = headers;
3016
+ this.logid = null == headers ? void 0 : headers['x-tt-logid'];
3017
+ // this.error = error;
3018
+ this.code = null == error ? void 0 : error.code;
3019
+ this.msg = null == error ? void 0 : error.msg;
3020
+ this.detail = null == error ? void 0 : null === (_error_error = error.error) || void 0 === _error_error ? void 0 : _error_error.detail;
3021
+ this.help_doc = null == error ? void 0 : null === (_error_error1 = error.error) || void 0 === _error_error1 ? void 0 : _error_error1.help_doc;
3022
+ this.rawError = error;
3023
+ }
3024
+ }
3025
+ class APIConnectionError extends APIError {
3026
+ constructor({ message, cause }){
3027
+ super(void 0, void 0, message || 'Connection error.', void 0), this.status = void 0;
3028
+ // if (cause) {
3029
+ // this.cause = cause;
3030
+ // }
3031
+ }
3032
+ }
3033
+ class APIUserAbortError extends APIError {
3034
+ constructor(message){
3035
+ super(void 0, void 0, message || 'Request was aborted.', void 0), this.name = 'UserAbortError', this.status = void 0;
3036
+ }
3037
+ }
3038
+ class BadRequestError extends APIError {
3039
+ constructor(...args){
3040
+ super(...args), this.name = 'BadRequestError', this.status = 400;
3041
+ }
3042
+ }
3043
+ class AuthenticationError extends APIError {
3044
+ constructor(...args){
3045
+ super(...args), this.name = 'AuthenticationError', this.status = 401;
3046
+ }
3047
+ }
3048
+ class PermissionDeniedError extends APIError {
3049
+ constructor(...args){
3050
+ super(...args), this.name = 'PermissionDeniedError', this.status = 403;
3051
+ }
3052
+ }
3053
+ class NotFoundError extends APIError {
3054
+ constructor(...args){
3055
+ super(...args), this.name = 'NotFoundError', this.status = 404;
3056
+ }
3057
+ }
3058
+ class TimeoutError extends APIError {
3059
+ constructor(...args){
3060
+ super(...args), this.name = 'TimeoutError', this.status = 408;
3061
+ }
3062
+ }
3063
+ class RateLimitError extends APIError {
3064
+ constructor(...args){
3065
+ super(...args), this.name = 'RateLimitError', this.status = 429;
3066
+ }
3067
+ }
3068
+ class InternalServerError extends APIError {
3069
+ constructor(...args){
3070
+ super(...args), this.name = 'InternalServerError', this.status = 500;
3071
+ }
3072
+ }
3073
+ class GatewayError extends APIError {
3074
+ constructor(...args){
3075
+ super(...args), this.name = 'GatewayError', this.status = 502;
3076
+ }
3077
+ }
3078
+ const castToError = (err)=>{
3079
+ if (err instanceof Error) return err;
3080
+ return new Error(err);
3081
+ };
3082
+ class Messages extends APIResource {
3083
+ /**
3084
+ * Get the list of messages in a chat. | 获取对话中的消息列表。
3085
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_message_list?_lang=en
3086
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_message_list?_lang=zh
3087
+ * @param conversation_id - Required The ID of the conversation. | 会话 ID。
3088
+ * @param chat_id - Required The ID of the chat. | 对话 ID。
3089
+ * @returns An array of chat messages. | 对话消息数组。
3090
+ */ async list(conversation_id, chat_id, options) {
3091
+ const apiUrl = `/v3/chat/message/list?conversation_id=${conversation_id}&chat_id=${chat_id}`;
3092
+ const result = await this._client.get(apiUrl, void 0, false, options);
3093
+ return result.data;
3094
+ }
3095
+ }
3096
+ const uuid = ()=>(Math.random() * new Date().getTime()).toString();
3097
+ const handleAdditionalMessages = (additional_messages)=>null == additional_messages ? void 0 : additional_messages.map((i)=>({
3098
+ ...i,
3099
+ content: 'object' == typeof i.content ? JSON.stringify(i.content) : i.content
3100
+ }));
3101
+ class Chat extends APIResource {
3102
+ /**
3103
+ * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
3104
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
3105
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
3106
+ * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
3107
+ * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
3108
+ * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
3109
+ * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
3110
+ * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义变量。
3111
+ * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
3112
+ * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
3113
+ * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
3114
+ * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
3115
+ * @returns The data of the created chat. | 创建的对话数据。
3116
+ */ async create(params, options) {
3117
+ if (!params.user_id) params.user_id = uuid();
3118
+ const { conversation_id, ...rest } = params;
3119
+ const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
3120
+ const payload = {
3121
+ ...rest,
3122
+ additional_messages: handleAdditionalMessages(params.additional_messages),
3123
+ stream: false
3124
+ };
3125
+ const result = await this._client.post(apiUrl, payload, false, options);
3126
+ return result.data;
3127
+ }
3128
+ /**
3129
+ * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
3130
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
3131
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
3132
+ * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
3133
+ * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
3134
+ * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
3135
+ * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
3136
+ * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
3137
+ * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
3138
+ * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
3139
+ * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
3140
+ * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
3141
+ * @returns
3142
+ */ async createAndPoll(params, options) {
3143
+ if (!params.user_id) params.user_id = uuid();
3144
+ const { conversation_id, ...rest } = params;
3145
+ const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
3146
+ const payload = {
3147
+ ...rest,
3148
+ additional_messages: handleAdditionalMessages(params.additional_messages),
3149
+ stream: false
3150
+ };
3151
+ const result = await this._client.post(apiUrl, payload, false, options);
3152
+ const chatId = result.data.id;
3153
+ const conversationId = result.data.conversation_id;
3154
+ let chat;
3155
+ while(true){
3156
+ await sleep(100);
3157
+ chat = await this.retrieve(conversationId, chatId);
3158
+ if ('completed' === chat.status || 'failed' === chat.status || 'requires_action' === chat.status) break;
3159
+ }
3160
+ const messageList = await this.messages.list(conversationId, chatId);
3161
+ return {
3162
+ chat,
3163
+ messages: messageList
3164
+ };
3165
+ }
3166
+ /**
3167
+ * Call the Chat API to send messages to a published Coze agent with streaming response. | 调用此接口发起一次对话,支持流式响应。
3168
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
3169
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
3170
+ * @param params - Required The parameters for streaming a chat session. | 流式会话的参数。
3171
+ * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
3172
+ * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
3173
+ * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
3174
+ * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
3175
+ * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
3176
+ * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
3177
+ * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
3178
+ * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
3179
+ * @returns A stream of chat data. | 对话数据流。
3180
+ */ async *stream(params, options) {
3181
+ if (!params.user_id) params.user_id = uuid();
3182
+ const { conversation_id, ...rest } = params;
3183
+ const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
3184
+ const payload = {
3185
+ ...rest,
3186
+ additional_messages: handleAdditionalMessages(params.additional_messages),
3187
+ stream: true
3188
+ };
3189
+ const result = await this._client.post(apiUrl, payload, true, options);
3190
+ for await (const message of result)if ("done" === message.event) {
3191
+ const ret = {
3192
+ event: message.event,
3193
+ data: '[DONE]'
3194
+ };
3195
+ yield ret;
3196
+ } else try {
3197
+ const ret = {
3198
+ event: message.event,
3199
+ data: JSON.parse(message.data)
3200
+ };
3201
+ yield ret;
3202
+ } catch (error) {
3203
+ throw new CozeError(`Could not parse message into JSON:${message.data}`);
3204
+ }
3205
+ }
3206
+ /**
3207
+ * Get the detailed information of the chat. | 查看对话的详细信息。
3208
+ * @docs en:https://www.coze.com/docs/developer_guides/retrieve_chat?_lang=en
3209
+ * @docs zh:https://www.coze.cn/docs/developer_guides/retrieve_chat?_lang=zh
3210
+ * @param conversation_id - Required The ID of the conversation. | 会话 ID。
3211
+ * @param chat_id - Required The ID of the chat. | 对话 ID。
3212
+ * @returns The data of the retrieved chat. | 检索到的对话数据。
3213
+ */ async retrieve(conversation_id, chat_id, options) {
3214
+ const apiUrl = `/v3/chat/retrieve?conversation_id=${conversation_id}&chat_id=${chat_id}`;
3215
+ const result = await this._client.post(apiUrl, void 0, false, options);
3216
+ return result.data;
3217
+ }
3218
+ /**
3219
+ * Cancel a chat session. | 取消对话会话。
3220
+ * @docs en:https://www.coze.com/docs/developer_guides/cancel_chat?_lang=en
3221
+ * @docs zh:https://www.coze.cn/docs/developer_guides/cancel_chat?_lang=zh
3222
+ * @param conversation_id - Required The ID of the conversation. | 会话 ID。
3223
+ * @param chat_id - Required The ID of the chat. | 对话 ID。
3224
+ * @returns The data of the canceled chat. | 取消的对话数据。
3225
+ */ async cancel(conversation_id, chat_id, options) {
3226
+ const apiUrl = '/v3/chat/cancel';
3227
+ const payload = {
3228
+ conversation_id,
3229
+ chat_id
3230
+ };
3231
+ const result = await this._client.post(apiUrl, payload, false, options);
3232
+ return result.data;
3233
+ }
3234
+ /**
3235
+ * Submit tool outputs for a chat session. | 提交对话会话的工具输出。
3236
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_submit_tool_outputs?_lang=en
3237
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_submit_tool_outputs?_lang=zh
3238
+ * @param params - Required Parameters for submitting tool outputs. | 提交工具输出的参数。
3239
+ * @param params.conversation_id - Required The ID of the conversation. | 会话 ID。
3240
+ * @param params.chat_id - Required The ID of the chat. | 对话 ID。
3241
+ * @param params.tool_outputs - Required The outputs of the tool. | 工具的输出。
3242
+ * @param params.stream - Optional Whether to use streaming response. | 是否使用流式响应。
3243
+ * @returns The data of the submitted tool outputs or a stream of chat data. | 提交的工具输出数据或对话数据流。
3244
+ */ async *submitToolOutputs(params, options) {
3245
+ const { conversation_id, chat_id, ...rest } = params;
3246
+ const apiUrl = `/v3/chat/submit_tool_outputs?conversation_id=${params.conversation_id}&chat_id=${params.chat_id}`;
3247
+ const payload = {
3248
+ ...rest
3249
+ };
3250
+ if (false === params.stream) {
3251
+ const response = await this._client.post(apiUrl, payload, false, options);
3252
+ return response.data;
3253
+ }
3254
+ {
3255
+ const result = await this._client.post(apiUrl, payload, true, options);
3256
+ for await (const message of result)if ("done" === message.event) {
3257
+ const ret = {
3258
+ event: message.event,
3259
+ data: '[DONE]'
3260
+ };
3261
+ yield ret;
3262
+ } else try {
3263
+ const ret = {
3264
+ event: message.event,
3265
+ data: JSON.parse(message.data)
3266
+ };
3267
+ yield ret;
3118
3268
  } catch (error) {
3119
- onRejected.call(this, error);
3120
- break;
3269
+ throw new CozeError(`Could not parse message into JSON:${message.data}`);
3121
3270
  }
3122
3271
  }
3123
- try {
3124
- promise = dispatchRequest.call(this, newConfig);
3125
- } catch (error) {
3126
- return Promise.reject(error);
3127
- }
3128
- i = 0;
3129
- len = responseInterceptorChain.length;
3130
- while(i < len)promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
3131
- return promise;
3132
3272
  }
3133
- getUri(config) {
3134
- config = mergeConfig_mergeConfig(this.defaults, config);
3135
- const fullPath = buildFullPath(config.baseURL, config.url);
3136
- return buildURL(fullPath, config.params, config.paramsSerializer);
3273
+ constructor(...args){
3274
+ super(...args), this.messages = new Messages(this._client);
3137
3275
  }
3138
3276
  }
3139
- // Provide aliases for supported request methods
3140
- utils.forEach([
3141
- 'delete',
3142
- 'get',
3143
- 'head',
3144
- 'options'
3145
- ], function(method) {
3146
- /*eslint func-names:0*/ Axios_Axios.prototype[method] = function(url, config) {
3147
- return this.request(mergeConfig_mergeConfig(config || {}, {
3148
- method,
3149
- url,
3150
- data: (config || {}).data
3151
- }));
3152
- };
3153
- });
3154
- utils.forEach([
3155
- 'post',
3156
- 'put',
3157
- 'patch'
3158
- ], function(method) {
3159
- /*eslint func-names:0*/ function generateHTTPMethod(isForm) {
3160
- return function(url, data, config) {
3161
- return this.request(mergeConfig_mergeConfig(config || {}, {
3162
- method,
3163
- headers: isForm ? {
3164
- 'Content-Type': 'multipart/form-data'
3165
- } : {},
3166
- url,
3167
- data
3168
- }));
3169
- };
3277
+ var chat_ChatEventType = /*#__PURE__*/ function(ChatEventType) {
3278
+ ChatEventType["CONVERSATION_CHAT_CREATED"] = "conversation.chat.created";
3279
+ ChatEventType["CONVERSATION_CHAT_IN_PROGRESS"] = "conversation.chat.in_progress";
3280
+ ChatEventType["CONVERSATION_CHAT_COMPLETED"] = "conversation.chat.completed";
3281
+ ChatEventType["CONVERSATION_CHAT_FAILED"] = "conversation.chat.failed";
3282
+ ChatEventType["CONVERSATION_CHAT_REQUIRES_ACTION"] = "conversation.chat.requires_action";
3283
+ ChatEventType["CONVERSATION_MESSAGE_DELTA"] = "conversation.message.delta";
3284
+ ChatEventType["CONVERSATION_MESSAGE_COMPLETED"] = "conversation.message.completed";
3285
+ ChatEventType["CONVERSATION_AUDIO_DELTA"] = "conversation.audio.delta";
3286
+ ChatEventType["DONE"] = "done";
3287
+ ChatEventType["ERROR"] = "error";
3288
+ return ChatEventType;
3289
+ }({});
3290
+ class messages_Messages extends APIResource {
3291
+ /**
3292
+ * Create a message and add it to the specified conversation. | 创建一条消息,并将其添加到指定的会话中。
3293
+ * @docs en: https://www.coze.com/docs/developer_guides/create_message?_lang=en
3294
+ * @docs zh: https://www.coze.cn/docs/developer_guides/create_message?_lang=zh
3295
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3296
+ * @param params - Required The parameters for creating a message | 创建消息所需的参数
3297
+ * @param params.role - Required The entity that sent this message. Possible values: user, assistant. | 发送这条消息的实体。取值:user, assistant。
3298
+ * @param params.content - Required The content of the message. | 消息的内容。
3299
+ * @param params.content_type - Required The type of the message content. | 消息内容的类型。
3300
+ * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
3301
+ * @returns Information about the new message. | 消息详情。
3302
+ */ async create(conversation_id, params, options) {
3303
+ const apiUrl = `/v1/conversation/message/create?conversation_id=${conversation_id}`;
3304
+ const response = await this._client.post(apiUrl, params, false, options);
3305
+ return response.data;
3170
3306
  }
3171
- Axios_Axios.prototype[method] = generateHTTPMethod();
3172
- Axios_Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
3173
- });
3174
- /* ESM default export */ const Axios = Axios_Axios;
3175
- /**
3176
- * A `CancelToken` is an object that can be used to request cancellation of an operation.
3177
- *
3178
- * @param {Function} executor The executor function.
3179
- *
3180
- * @returns {CancelToken}
3181
- */ class CancelToken_CancelToken {
3182
- constructor(executor){
3183
- if ('function' != typeof executor) throw new TypeError('executor must be a function.');
3184
- let resolvePromise;
3185
- this.promise = new Promise(function(resolve) {
3186
- resolvePromise = resolve;
3187
- });
3188
- const token = this;
3189
- // eslint-disable-next-line func-names
3190
- this.promise.then((cancel)=>{
3191
- if (!token._listeners) return;
3192
- let i = token._listeners.length;
3193
- while(i-- > 0)token._listeners[i](cancel);
3194
- token._listeners = null;
3195
- });
3196
- // eslint-disable-next-line func-names
3197
- this.promise.then = (onfulfilled)=>{
3198
- let _resolve;
3199
- // eslint-disable-next-line func-names
3200
- const promise = new Promise((resolve)=>{
3201
- token.subscribe(resolve);
3202
- _resolve = resolve;
3203
- }).then(onfulfilled);
3204
- promise.cancel = function() {
3205
- token.unsubscribe(_resolve);
3206
- };
3207
- return promise;
3208
- };
3209
- executor(function(message, config, request) {
3210
- if (token.reason) // Cancellation has already been requested
3211
- return;
3212
- token.reason = new CanceledError(message, config, request);
3213
- resolvePromise(token.reason);
3214
- });
3307
+ /**
3308
+ * Modify a message, supporting the modification of message content, additional content, and message type. | 修改一条消息,支持修改消息内容、附加内容和消息类型。
3309
+ * @docs en: https://www.coze.com/docs/developer_guides/modify_message?_lang=en
3310
+ * @docs zh: https://www.coze.cn/docs/developer_guides/modify_message?_lang=zh
3311
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3312
+ * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
3313
+ * @param params - Required The parameters for modifying a message | 修改消息所需的参数
3314
+ * @param params.meta_data - Optional Additional information when modifying a message. | 修改消息时的附加消息。
3315
+ * @param params.content - Optional The content of the message. | 消息的内容。
3316
+ * @param params.content_type - Optional The type of the message content. | 消息内容的类型。
3317
+ * @returns Information about the modified message. | 消息详情。
3318
+ */ // eslint-disable-next-line max-params
3319
+ async update(conversation_id, message_id, params, options) {
3320
+ const apiUrl = `/v1/conversation/message/modify?conversation_id=${conversation_id}&message_id=${message_id}`;
3321
+ const response = await this._client.post(apiUrl, params, false, options);
3322
+ return response.message;
3215
3323
  }
3216
3324
  /**
3217
- * Throws a `CanceledError` if cancellation has been requested.
3218
- */ throwIfRequested() {
3219
- if (this.reason) throw this.reason;
3325
+ * Get the detailed information of specified message. | 查看指定消息的详细信息。
3326
+ * @docs en: https://www.coze.com/docs/developer_guides/retrieve_message?_lang=en
3327
+ * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_message?_lang=zh
3328
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3329
+ * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
3330
+ * @returns Information about the message. | 消息详情。
3331
+ */ async retrieve(conversation_id, message_id, options) {
3332
+ const apiUrl = `/v1/conversation/message/retrieve?conversation_id=${conversation_id}&message_id=${message_id}`;
3333
+ const response = await this._client.get(apiUrl, null, false, options);
3334
+ return response.data;
3220
3335
  }
3221
3336
  /**
3222
- * Subscribe to the cancel signal
3223
- */ subscribe(listener) {
3224
- if (this.reason) {
3225
- listener(this.reason);
3226
- return;
3227
- }
3228
- if (this._listeners) this._listeners.push(listener);
3229
- else this._listeners = [
3230
- listener
3231
- ];
3337
+ * List messages in a conversation. | 列出会话中的消息。
3338
+ * @docs en: https://www.coze.com/docs/developer_guides/message_list?_lang=en
3339
+ * @docs zh: https://www.coze.cn/docs/developer_guides/message_list?_lang=zh
3340
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3341
+ * @param params - Optional The parameters for listing messages | 列出消息所需的参数
3342
+ * @param params.order - Optional The order of the messages. | 消息的顺序。
3343
+ * @param params.chat_id - Optional The ID of the chat. | 聊天 ID。
3344
+ * @param params.before_id - Optional The ID of the message before which to list. | 列出此消息之前的消息 ID。
3345
+ * @param params.after_id - Optional The ID of the message after which to list. | 列出此消息之后的消息 ID。
3346
+ * @param params.limit - Optional The maximum number of messages to return. | 返回的最大消息数。
3347
+ * @returns A list of messages. | 消息列表。
3348
+ */ async list(conversation_id, params, options) {
3349
+ const apiUrl = `/v1/conversation/message/list?conversation_id=${conversation_id}`;
3350
+ const response = await this._client.post(apiUrl, params, false, options);
3351
+ return response;
3232
3352
  }
3233
3353
  /**
3234
- * Unsubscribe from the cancel signal
3235
- */ unsubscribe(listener) {
3236
- if (!this._listeners) return;
3237
- const index = this._listeners.indexOf(listener);
3238
- if (-1 !== index) this._listeners.splice(index, 1);
3354
+ * Call the API to delete a message within a specified conversation. | 调用接口在指定会话中删除消息。
3355
+ * @docs en: https://www.coze.com/docs/developer_guides/delete_message?_lang=en
3356
+ * @docs zh: https://www.coze.cn/docs/developer_guides/delete_message?_lang=zh
3357
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3358
+ * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
3359
+ * @returns Details of the deleted message. | 已删除的消息详情。
3360
+ */ async delete(conversation_id, message_id, options) {
3361
+ const apiUrl = `/v1/conversation/message/delete?conversation_id=${conversation_id}&message_id=${message_id}`;
3362
+ const response = await this._client.post(apiUrl, void 0, false, options);
3363
+ return response.data;
3239
3364
  }
3240
- toAbortSignal() {
3241
- const controller = new AbortController();
3242
- const abort = (err)=>{
3243
- controller.abort(err);
3244
- };
3245
- this.subscribe(abort);
3246
- controller.signal.unsubscribe = ()=>this.unsubscribe(abort);
3247
- return controller.signal;
3365
+ }
3366
+ class Conversations extends APIResource {
3367
+ /**
3368
+ * Create a conversation. Conversation is an interaction between an agent and a user, including one or more messages. | 调用接口创建一个会话。
3369
+ * @docs en: https://www.coze.com/docs/developer_guides/create_conversation?_lang=en
3370
+ * @docs zh: https://www.coze.cn/docs/developer_guides/create_conversation?_lang=zh
3371
+ * @param params - Required The parameters for creating a conversation | 创建会话所需的参数
3372
+ * @param params.messages - Optional Messages in the conversation. | 会话中的消息内容。
3373
+ * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
3374
+ * @param params.bot_id - Optional Bind and isolate conversation on different bots. | 绑定和隔离不同Bot的会话。
3375
+ * @returns Information about the created conversation. | 会话的基础信息。
3376
+ */ async create(params, options) {
3377
+ const apiUrl = '/v1/conversation/create';
3378
+ const response = await this._client.post(apiUrl, params, false, options);
3379
+ return response.data;
3248
3380
  }
3249
3381
  /**
3250
- * Returns an object that contains a new `CancelToken` and a function that, when called,
3251
- * cancels the `CancelToken`.
3252
- */ static source() {
3253
- let cancel;
3254
- const token = new CancelToken_CancelToken(function(c) {
3255
- cancel = c;
3256
- });
3257
- return {
3258
- token,
3259
- cancel
3260
- };
3382
+ * Get the information of specific conversation. | 通过会话 ID 查看会话信息。
3383
+ * @docs en: https://www.coze.com/docs/developer_guides/retrieve_conversation?_lang=en
3384
+ * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_conversation?_lang=zh
3385
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3386
+ * @returns Information about the conversation. | 会话的基础信息。
3387
+ */ async retrieve(conversation_id, options) {
3388
+ const apiUrl = `/v1/conversation/retrieve?conversation_id=${conversation_id}`;
3389
+ const response = await this._client.get(apiUrl, null, false, options);
3390
+ return response.data;
3391
+ }
3392
+ /**
3393
+ * List all conversations. | 列出 Bot 下所有会话。
3394
+ * @param params
3395
+ * @param params.bot_id - Required Bot ID. | Bot ID。
3396
+ * @param params.page_num - Optional The page number. | 页码,默认值为 1。
3397
+ * @param params.page_size - Optional The number of conversations per page. | 每页的会话数量,默认值为 50。
3398
+ * @returns Information about the conversations. | 会话的信息。
3399
+ */ async list(params, options) {
3400
+ const apiUrl = '/v1/conversations';
3401
+ const response = await this._client.get(apiUrl, params, false, options);
3402
+ return response.data;
3403
+ }
3404
+ /**
3405
+ * Clear a conversation. | 清空会话。
3406
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3407
+ * @returns Information about the conversation session. | 会话的会话 ID。
3408
+ */ async clear(conversation_id, options) {
3409
+ const apiUrl = `/v1/conversations/${conversation_id}/clear`;
3410
+ const response = await this._client.post(apiUrl, null, false, options);
3411
+ return response.data;
3412
+ }
3413
+ constructor(...args){
3414
+ super(...args), this.messages = new messages_Messages(this._client);
3261
3415
  }
3262
3416
  }
3263
- /* ESM default export */ const CancelToken = CancelToken_CancelToken;
3264
- /**
3265
- * Syntactic sugar for invoking a function and expanding an array for arguments.
3266
- *
3267
- * Common use case would be to use `Function.prototype.apply`.
3268
- *
3269
- * ```js
3270
- * function f(x, y, z) {}
3271
- * var args = [1, 2, 3];
3272
- * f.apply(null, args);
3273
- * ```
3274
- *
3275
- * With `spread` this example can be re-written.
3276
- *
3277
- * ```js
3278
- * spread(function(x, y, z) {})([1, 2, 3]);
3279
- * ```
3280
- *
3281
- * @param {Function} callback
3282
- *
3283
- * @returns {Function}
3284
- */ function spread(callback) {
3285
- return function(arr) {
3286
- return callback.apply(null, arr);
3287
- };
3288
- }
3289
- /**
3290
- * Determines whether the payload is an error thrown by Axios
3291
- *
3292
- * @param {*} payload The value to test
3293
- *
3294
- * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
3295
- */ function isAxiosError(payload) {
3296
- return utils.isObject(payload) && true === payload.isAxiosError;
3297
- }
3298
- const HttpStatusCode = {
3299
- Continue: 100,
3300
- SwitchingProtocols: 101,
3301
- Processing: 102,
3302
- EarlyHints: 103,
3303
- Ok: 200,
3304
- Created: 201,
3305
- Accepted: 202,
3306
- NonAuthoritativeInformation: 203,
3307
- NoContent: 204,
3308
- ResetContent: 205,
3309
- PartialContent: 206,
3310
- MultiStatus: 207,
3311
- AlreadyReported: 208,
3312
- ImUsed: 226,
3313
- MultipleChoices: 300,
3314
- MovedPermanently: 301,
3315
- Found: 302,
3316
- SeeOther: 303,
3317
- NotModified: 304,
3318
- UseProxy: 305,
3319
- Unused: 306,
3320
- TemporaryRedirect: 307,
3321
- PermanentRedirect: 308,
3322
- BadRequest: 400,
3323
- Unauthorized: 401,
3324
- PaymentRequired: 402,
3325
- Forbidden: 403,
3326
- NotFound: 404,
3327
- MethodNotAllowed: 405,
3328
- NotAcceptable: 406,
3329
- ProxyAuthenticationRequired: 407,
3330
- RequestTimeout: 408,
3331
- Conflict: 409,
3332
- Gone: 410,
3333
- LengthRequired: 411,
3334
- PreconditionFailed: 412,
3335
- PayloadTooLarge: 413,
3336
- UriTooLong: 414,
3337
- UnsupportedMediaType: 415,
3338
- RangeNotSatisfiable: 416,
3339
- ExpectationFailed: 417,
3340
- ImATeapot: 418,
3341
- MisdirectedRequest: 421,
3342
- UnprocessableEntity: 422,
3343
- Locked: 423,
3344
- FailedDependency: 424,
3345
- TooEarly: 425,
3346
- UpgradeRequired: 426,
3347
- PreconditionRequired: 428,
3348
- TooManyRequests: 429,
3349
- RequestHeaderFieldsTooLarge: 431,
3350
- UnavailableForLegalReasons: 451,
3351
- InternalServerError: 500,
3352
- NotImplemented: 501,
3353
- BadGateway: 502,
3354
- ServiceUnavailable: 503,
3355
- GatewayTimeout: 504,
3356
- HttpVersionNotSupported: 505,
3357
- VariantAlsoNegotiates: 506,
3358
- InsufficientStorage: 507,
3359
- LoopDetected: 508,
3360
- NotExtended: 510,
3361
- NetworkAuthenticationRequired: 511
3362
- };
3363
- Object.entries(HttpStatusCode).forEach(([key, value])=>{
3364
- HttpStatusCode[value] = key;
3365
- });
3366
- /* ESM default export */ const helpers_HttpStatusCode = HttpStatusCode;
3367
- /**
3368
- * Create an instance of Axios
3369
- *
3370
- * @param {Object} defaultConfig The default config for the instance
3371
- *
3372
- * @returns {Axios} A new instance of Axios
3373
- */ function createInstance(defaultConfig) {
3374
- const context = new Axios(defaultConfig);
3375
- const instance = bind(Axios.prototype.request, context);
3376
- // Copy axios.prototype to instance
3377
- utils.extend(instance, Axios.prototype, context, {
3378
- allOwnKeys: true
3379
- });
3380
- // Copy context to instance
3381
- utils.extend(instance, context, null, {
3382
- allOwnKeys: true
3383
- });
3384
- // Factory for creating new instances
3385
- instance.create = function(instanceConfig) {
3386
- return createInstance(mergeConfig_mergeConfig(defaultConfig, instanceConfig));
3387
- };
3388
- return instance;
3389
- }
3390
- // Create the default instance to be exported
3391
- const axios = createInstance(defaults);
3392
- // Expose Axios class to allow class inheritance
3393
- axios.Axios = Axios;
3394
- // Expose Cancel & CancelToken
3395
- axios.CanceledError = CanceledError;
3396
- axios.CancelToken = CancelToken;
3397
- axios.isCancel = isCancel;
3398
- axios.VERSION = VERSION;
3399
- axios.toFormData = toFormData;
3400
- // Expose AxiosError class
3401
- axios.AxiosError = core_AxiosError;
3402
- // alias for CanceledError for backward compatibility
3403
- axios.Cancel = axios.CanceledError;
3404
- // Expose all/spread
3405
- axios.all = function(promises) {
3406
- return Promise.all(promises);
3407
- };
3408
- axios.spread = spread;
3409
- // Expose isAxiosError
3410
- axios.isAxiosError = isAxiosError;
3411
- // Expose mergeConfig
3412
- axios.mergeConfig = mergeConfig_mergeConfig;
3413
- axios.AxiosHeaders = AxiosHeaders;
3414
- axios.formToJSON = (thing)=>formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
3415
- axios.getAdapter = adapters_adapters.getAdapter;
3416
- axios.HttpStatusCode = helpers_HttpStatusCode;
3417
- axios.default = axios;
3418
- // this module should only have a default export
3419
- /* ESM default export */ const lib_axios = axios;
3420
- // This module is intended to unwrap Axios default export as named.
3421
- // Keep top-level export same with static properties
3422
- // so that it can keep same with es module or cjs
3423
- const { Axios: axios_Axios, AxiosError: axios_AxiosError, CanceledError: axios_CanceledError, isCancel: axios_isCancel, CancelToken: axios_CancelToken, VERSION: axios_VERSION, all: axios_all, Cancel, isAxiosError: axios_isAxiosError, spread: axios_spread, toFormData: axios_toFormData, AxiosHeaders: axios_AxiosHeaders, HttpStatusCode: axios_HttpStatusCode, formToJSON, getAdapter, mergeConfig: axios_mergeConfig } = lib_axios;
3424
3417
  class Files extends APIResource {
3425
3418
  /**
3426
3419
  * Upload files to Coze platform. | 调用接口上传文件到扣子。
@@ -3583,7 +3576,7 @@ class Documents extends APIResource {
3583
3576
  * @returns ListDocumentData | 知识库文件列表
3584
3577
  */ list(params, options) {
3585
3578
  const apiUrl = '/open_api/knowledge/document/list';
3586
- const response = this._client.get(apiUrl, params, false, mergeConfig(options, {
3579
+ const response = this._client.get(apiUrl, params, false, esm_mergeConfig(options, {
3587
3580
  headers: documents_headers
3588
3581
  }));
3589
3582
  return response;
@@ -3601,7 +3594,7 @@ class Documents extends APIResource {
3601
3594
  * @returns DocumentInfo[] | 已上传文件的基本信息
3602
3595
  */ async create(params, options) {
3603
3596
  const apiUrl = '/open_api/knowledge/document/create';
3604
- const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
3597
+ const response = await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3605
3598
  headers: documents_headers
3606
3599
  }));
3607
3600
  return response.document_infos;
@@ -3617,7 +3610,7 @@ class Documents extends APIResource {
3617
3610
  * @returns void | 无返回
3618
3611
  */ async delete(params, options) {
3619
3612
  const apiUrl = '/open_api/knowledge/document/delete';
3620
- await this._client.post(apiUrl, params, false, mergeConfig(options, {
3613
+ await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3621
3614
  headers: documents_headers
3622
3615
  }));
3623
3616
  }
@@ -3633,7 +3626,7 @@ class Documents extends APIResource {
3633
3626
  * @returns void | 无返回
3634
3627
  */ async update(params, options) {
3635
3628
  const apiUrl = '/open_api/knowledge/document/update';
3636
- await this._client.post(apiUrl, params, false, mergeConfig(options, {
3629
+ await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3637
3630
  headers: documents_headers
3638
3631
  }));
3639
3632
  }
@@ -3659,9 +3652,9 @@ class documents_Documents extends APIResource {
3659
3652
  * @param params.page - Optional The page number for paginated queries. Default is 1. | 可选 分页查询时的页码。默认为 1。
3660
3653
  * @param params.page_size - Optional The size of pagination. Default is 10. | 可选 分页大小。默认为 10。
3661
3654
  * @returns ListDocumentData | 知识库文件列表
3662
- */ list(params, options) {
3655
+ */ async list(params, options) {
3663
3656
  const apiUrl = '/open_api/knowledge/document/list';
3664
- const response = this._client.get(apiUrl, params, false, mergeConfig(options, {
3657
+ const response = await this._client.get(apiUrl, params, false, esm_mergeConfig(options, {
3665
3658
  headers: documents_documents_headers
3666
3659
  }));
3667
3660
  return response;
@@ -3677,7 +3670,7 @@ class documents_Documents extends APIResource {
3677
3670
  * @returns DocumentInfo[] | 已上传文件的基本信息
3678
3671
  */ async create(params, options) {
3679
3672
  const apiUrl = '/open_api/knowledge/document/create';
3680
- const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
3673
+ const response = await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3681
3674
  headers: documents_documents_headers
3682
3675
  }));
3683
3676
  return response.document_infos;
@@ -3691,7 +3684,7 @@ class documents_Documents extends APIResource {
3691
3684
  * @returns void | 无返回
3692
3685
  */ async delete(params, options) {
3693
3686
  const apiUrl = '/open_api/knowledge/document/delete';
3694
- await this._client.post(apiUrl, params, false, mergeConfig(options, {
3687
+ await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3695
3688
  headers: documents_documents_headers
3696
3689
  }));
3697
3690
  }
@@ -3705,14 +3698,109 @@ class documents_Documents extends APIResource {
3705
3698
  * @returns void | 无返回
3706
3699
  */ async update(params, options) {
3707
3700
  const apiUrl = '/open_api/knowledge/document/update';
3708
- await this._client.post(apiUrl, params, false, mergeConfig(options, {
3701
+ await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3709
3702
  headers: documents_documents_headers
3710
3703
  }));
3711
3704
  }
3712
3705
  }
3706
+ class Images extends APIResource {
3707
+ /**
3708
+ * Update the description of an image in the knowledge base | 更新知识库中的图片描述
3709
+ * @docs en: https://www.coze.com/docs/developer_guides/developer_guides/update_image_caption?_lang=en
3710
+ * @docs zh: https://www.coze.cn/docs/developer_guides/developer_guides/update_image_caption?_lang=zh
3711
+ * @param datasetId - The ID of the dataset | 必选 知识库 ID
3712
+ * @param documentId - The ID of the document | 必选 知识库文件 ID
3713
+ * @param params - The parameters for updating the image
3714
+ * @param params.caption - Required. The description of the image | 必选 图片的描述信息
3715
+ * @returns undefined
3716
+ */ // eslint-disable-next-line max-params
3717
+ async update(datasetId, documentId, params, options) {
3718
+ const apiUrl = `/v1/datasets/${datasetId}/images/${documentId}`;
3719
+ await this._client.put(apiUrl, params, false, options);
3720
+ }
3721
+ /**
3722
+ * List images in the knowledge base | 列出知识库中的图片
3723
+ * @docs en: https://www.coze.com/docs/developer_guides/developer_guides/get_images?_lang=en
3724
+ * @docs zh: https://www.coze.cn/docs/developer_guides/developer_guides/get_images?_lang=zh
3725
+ * @param datasetId - The ID of the dataset | 必选 知识库 ID
3726
+ * @param params - The parameters for listing images
3727
+ * @param params.page_num - Optional. Page number for pagination, minimum value is 1, defaults to 1 | 可选 分页查询时的页码。默认为 1。
3728
+ * @param params.page_size - Optional. Number of items per page, range 1-299, defaults to 10 | 可选 分页大小。默认为 10。
3729
+ * @param params.keyword - Optional. Search keyword for image descriptions | 可选 图片描述的搜索关键词。
3730
+ * @param params.has_caption - Optional. Filter for images with/without captions | 可选 是否过滤有/无描述的图片。
3731
+ */ async list(datasetId, params, options) {
3732
+ const apiUrl = `/v1/datasets/${datasetId}/images`;
3733
+ const response = await this._client.get(apiUrl, params, false, options);
3734
+ return response.data;
3735
+ }
3736
+ }
3713
3737
  class Datasets extends APIResource {
3738
+ /**
3739
+ * Creates a new dataset | 创建数据集
3740
+ * @docs en: https://www.coze.com/docs/developer_guides/create_dataset?_lang=en
3741
+ * @docs zh: https://www.coze.cn/docs/developer_guides/create_dataset?_lang=zh
3742
+ * @param params - The parameters for creating a dataset
3743
+ * @param {string} params.name - Required. Dataset name, maximum length of 100 characters | 必选 数据集名称,最大长度为 100 个字符
3744
+ * @param {string} params.space_id - Required. Space ID where the dataset belongs | 必选 数据集所属的空间 ID
3745
+ * @param {number} params.format_type - Required. Dataset type (0: Text type, 2: Image type) | 必选 数据集类型 (0: 文本类型, 2: 图片类型)
3746
+ * @param {string} [params.description] - Optional. Dataset description | 可选 数据集描述
3747
+ * @param {string} [params.file_id] - Optional. Dataset icon file ID from file upload
3748
+ */ async create(params, options) {
3749
+ const apiUrl = '/v1/datasets';
3750
+ const response = await this._client.post(apiUrl, params, false, options);
3751
+ return response.data;
3752
+ }
3753
+ /**
3754
+ * Lists all datasets in a space | 列出空间中的所有数据集
3755
+ * @docs en: https://www.coze.com/docs/developer_guides/list_dataset?_lang=en
3756
+ * @docs zh: https://www.coze.cn/docs/developer_guides/list_dataset?_lang=zh
3757
+ * @param params - The parameters for listing datasets | 列出数据集的参数
3758
+ * @param {string} params.space_id - Required. Space ID where the datasets belong | 必选 数据集所属的空间 ID
3759
+ * @param {string} [params.name] - Optional. Dataset name for fuzzy search | 可选 数据集名称用于模糊搜索
3760
+ * @param {number} [params.format_type] - Optional. Dataset type (0: Text type, 2: Image type) | 可选 数据集类型 (0: 文本类型, 2: 图片类型)
3761
+ * @param {number} [params.page_num] - Optional. Page number for pagination (default: 1) | 可选 分页查询时的页码。默认为 1。
3762
+ * @param {number} [params.page_size] - Optional. Number of items per page (default: 10) | 可选 分页大小。默认为 10。
3763
+ */ async list(params, options) {
3764
+ const apiUrl = '/v1/datasets';
3765
+ const response = await this._client.get(apiUrl, params, false, options);
3766
+ return response.data;
3767
+ }
3768
+ /**
3769
+ * Updates a dataset | 更新数据集
3770
+ * @docs en: https://www.coze.com/docs/developer_guides/update_dataset?_lang=en
3771
+ * @docs zh: https://www.coze.cn/docs/developer_guides/update_dataset?_lang=zh
3772
+ * @param dataset_id - Required. The ID of the dataset to update | 必选 数据集 ID
3773
+ * @param params - Required. The parameters for updating the dataset | 必选 更新数据集的参数
3774
+ * @param params.name - Required. Dataset name, maximum length of 100 characters. | 必选 数据集名称,最大长度为 100 个字符。
3775
+ * @param params.file_id - Optional. Dataset icon, should pass the file_id obtained from the file upload interface. | 可选 数据集图标,应传递从文件上传接口获取的 file_id。
3776
+ * @param params.description - Optional. Dataset description. | 可选 数据集描述。
3777
+ */ async update(dataset_id, params, options) {
3778
+ const apiUrl = `/v1/datasets/${dataset_id}`;
3779
+ await this._client.put(apiUrl, params, false, options);
3780
+ }
3781
+ /**
3782
+ * Deletes a dataset | 删除数据集
3783
+ * @docs en: https://www.coze.com/docs/developer_guides/delete_dataset?_lang=en
3784
+ * @docs zh: https://www.coze.cn/docs/developer_guides/delete_dataset?_lang=zh
3785
+ * @param dataset_id - Required. The ID of the dataset to delete | 必选 数据集 ID
3786
+ */ async delete(dataset_id, options) {
3787
+ const apiUrl = `/v1/datasets/${dataset_id}`;
3788
+ await this._client.delete(apiUrl, false, options);
3789
+ }
3790
+ /**
3791
+ * Views the progress of dataset upload | 查看数据集上传进度
3792
+ * @docs en: https://www.coze.com/docs/developer_guides/get_dataset_progress?_lang=en
3793
+ * @docs zh: https://www.coze.cn/docs/developer_guides/get_dataset_progress?_lang=zh
3794
+ * @param dataset_id - Required. The ID of the dataset to process | 必选 数据集 ID
3795
+ * @param params - Required. The parameters for processing the dataset | 必选 处理数据集的参数
3796
+ * @param params.dataset_ids - Required. List of dataset IDs | 必选 数据集 ID 列表
3797
+ */ async process(dataset_id, params, options) {
3798
+ const apiUrl = `/v1/datasets/${dataset_id}/process`;
3799
+ const response = await this._client.post(apiUrl, params, false, options);
3800
+ return response.data;
3801
+ }
3714
3802
  constructor(...args){
3715
- super(...args), this.documents = new documents_Documents(this._client);
3803
+ super(...args), this.documents = new documents_Documents(this._client), this.images = new Images(this._client);
3716
3804
  }
3717
3805
  }
3718
3806
  class Voices extends APIResource {
@@ -3769,7 +3857,10 @@ class Speech extends APIResource {
3769
3857
  * @returns Speech synthesis data
3770
3858
  */ async create(params, options) {
3771
3859
  const apiUrl = '/v1/audio/speech';
3772
- const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
3860
+ const response = await this._client.post(apiUrl, {
3861
+ ...params,
3862
+ sample_rate: params.sample_rate || 24000
3863
+ }, false, esm_mergeConfig(options, {
3773
3864
  responseType: 'arraybuffer'
3774
3865
  }));
3775
3866
  return response;
@@ -3782,26 +3873,37 @@ class Rooms extends APIResource {
3782
3873
  return response.data;
3783
3874
  }
3784
3875
  }
3785
- class audio_Audio extends APIResource {
3876
+ class esm_Audio extends APIResource {
3786
3877
  constructor(...args){
3787
3878
  super(...args), this.rooms = new Rooms(this._client), this.voices = new Voices(this._client), this.speech = new Speech(this._client);
3788
3879
  }
3789
3880
  }
3790
- // EXTERNAL MODULE: os (ignored)
3791
- var os_ignored_ = __webpack_require__("?9050");
3792
- var os_ignored_default = /*#__PURE__*/ __webpack_require__.n(os_ignored_);
3793
- var package_namespaceObject = JSON.parse('{"name":"@coze/api","version":"1.0.16-beta.1","description":"Official Coze Node.js SDK for seamless AI integration into your applications | 扣子官方 Node.js SDK,助您轻松集成 AI 能力到应用中","keywords":["coze","ai","nodejs","sdk","chatbot","typescript"],"homepage":"https://github.com/coze-dev/coze-js/tree/main/packages/coze-js","bugs":{"url":"https://github.com/coze-dev/coze-js/issues"},"repository":{"type":"git","url":"https://github.com/coze-dev/coze-js.git","directory":"packages/coze-js"},"license":"MIT","author":"Leeight <leeight@gmail.com>","type":"module","main":"src/index.ts","browser":{"crypto":false,"os":false,"jsonwebtoken":false},"types":"src/index.ts","files":["dist","LICENSE","README.md"],"scripts":{"build":"rm -rf dist && rslib build","format":"prettier --write .","lint":"eslint ./ --cache --quiet","start":"rm -rf dist && rslib build -w","test":"vitest","test:cov":"vitest --coverage --run"},"dependencies":{"jsonwebtoken":"^9.0.2"},"devDependencies":{"@coze-infra/eslint-config":"workspace:*","@coze-infra/ts-config":"workspace:*","@coze-infra/vitest-config":"workspace:*","@rslib/core":"0.0.18","@swc/core":"^1.3.14","@types/jsonwebtoken":"^9.0.0","@types/node":"^20","@types/uuid":"^9.0.1","@types/whatwg-fetch":"^0.0.33","@vitest/coverage-v8":"~2.1.4","axios":"^1.7.7","typescript":"^5.5.3","vitest":"~2.1.4"},"peerDependencies":{"axios":"^1.7.1"},"cozePublishConfig":{"exports":{".":{"require":"./dist/cjs/index.cjs","import":"./dist/esm/index.js","types":"./dist/types/index.d.ts"}},"main":"dist/cjs/index.cjs","module":"dist/esm/index.js","types":"dist/types/index.d.ts"}}'); // CONCATENATED MODULE: ../coze-js/src/version.ts
3794
- const { version: version_version } = package_namespaceObject;
3881
+ class Templates extends APIResource {
3882
+ /**
3883
+ * Duplicate a template. | 复制一个模板。
3884
+ * @param templateId - Required. The ID of the template to duplicate. | 要复制的模板的 ID。
3885
+ * @param params - Optional. The parameters for the duplicate operation. | 可选参数,用于复制操作。
3886
+ * @param params.workspace_id - Required. The ID of the workspace to duplicate the template into. | 要复制到的目标工作空间的 ID。
3887
+ * @param params.name - Optional. The name of the new template. | 新模板的名称。
3888
+ * @returns TemplateDuplicateRes | 复制模板结果
3889
+ */ async duplicate(templateId, params, options) {
3890
+ const apiUrl = `/v1/templates/${templateId}/duplicate`;
3891
+ const response = await this._client.post(apiUrl, params, false, options);
3892
+ return response.data;
3893
+ }
3894
+ }
3895
+ var package_namespaceObject = JSON.parse('{"name":"@coze/api","version":"1.0.16","description":"Official Coze Node.js SDK for seamless AI integration into your applications | 扣子官方 Node.js SDK,助您轻松集成 AI 能力到应用中","keywords":["coze","ai","nodejs","sdk","chatbot","typescript"],"homepage":"https://github.com/coze-dev/coze-js/tree/main/packages/coze-js","bugs":{"url":"https://github.com/coze-dev/coze-js/issues"},"repository":{"type":"git","url":"https://github.com/coze-dev/coze-js.git","directory":"packages/coze-js"},"license":"MIT","author":"Leeight <leeight@gmail.com>","type":"module","exports":{".":{"require":"./dist/cjs/index.cjs","import":"./dist/esm/index.js","types":"./dist/types/index.d.ts"}},"main":"dist/cjs/index.cjs","module":"dist/esm/index.js","browser":{"crypto":false,"os":false,"jsonwebtoken":false},"types":"dist/types/index.d.ts","files":["dist","LICENSE","README.md","README.zh-CN.md"],"scripts":{"build":"rm -rf dist && rslib build","format":"prettier --write .","lint":"eslint ./ --cache --quiet","start":"rm -rf dist && rslib build -w","test":"vitest","test:cov":"vitest --coverage --run"},"dependencies":{"jsonwebtoken":"^9.0.2"},"devDependencies":{"@coze-infra/eslint-config":"workspace:*","@coze-infra/ts-config":"workspace:*","@coze-infra/vitest-config":"workspace:*","@rslib/core":"0.0.18","@swc/core":"^1.3.14","@types/jsonwebtoken":"^9.0.0","@types/node":"^20","@types/uuid":"^9.0.1","@types/whatwg-fetch":"^0.0.33","@vitest/coverage-v8":"~2.1.4","axios":"^1.7.7","typescript":"^5.5.3","vitest":"~2.1.4"},"peerDependencies":{"axios":"^1.7.1"}}'); // CONCATENATED MODULE: ./src/version.ts
3896
+ const { version: esm_version } = package_namespaceObject;
3795
3897
  const getEnv = ()=>{
3796
3898
  const nodeVersion = process.version.slice(1); // Remove 'v' prefix
3797
3899
  const { platform } = process;
3798
3900
  let osName = platform.toLowerCase();
3799
- let osVersion = os_ignored_default().release();
3901
+ let osVersion = os_ignored_.release();
3800
3902
  if ('darwin' === platform) {
3801
3903
  osName = 'macos';
3802
3904
  // Try to parse the macOS version
3803
3905
  try {
3804
- const darwinVersion = os_ignored_default().release().split('.');
3906
+ const darwinVersion = os_ignored_.release().split('.');
3805
3907
  if (darwinVersion.length >= 2) {
3806
3908
  const majorVersion = parseInt(darwinVersion[0], 10);
3807
3909
  if (!isNaN(majorVersion) && majorVersion >= 9) {
@@ -3814,10 +3916,10 @@ const getEnv = ()=>{
3814
3916
  }
3815
3917
  } else if ('win32' === platform) {
3816
3918
  osName = 'windows';
3817
- osVersion = os_ignored_default().release();
3919
+ osVersion = os_ignored_.release();
3818
3920
  } else if ('linux' === platform) {
3819
3921
  osName = 'linux';
3820
- osVersion = os_ignored_default().release();
3922
+ osVersion = os_ignored_.release();
3821
3923
  }
3822
3924
  return {
3823
3925
  osName,
@@ -3827,12 +3929,12 @@ const getEnv = ()=>{
3827
3929
  };
3828
3930
  const getUserAgent = ()=>{
3829
3931
  const { nodeVersion, osName, osVersion } = getEnv();
3830
- return `coze-js/${version_version} node/${nodeVersion} ${osName}/${osVersion}`.toLowerCase();
3932
+ return `coze-js/${esm_version} node/${nodeVersion} ${osName}/${osVersion}`.toLowerCase();
3831
3933
  };
3832
3934
  const getNodeClientUserAgent = ()=>{
3833
3935
  const { osVersion, nodeVersion, osName } = getEnv();
3834
3936
  const ua = {
3835
- version: version_version,
3937
+ version: esm_version,
3836
3938
  lang: 'node',
3837
3939
  lang_version: nodeVersion,
3838
3940
  os_name: osName,
@@ -3840,17 +3942,64 @@ const getNodeClientUserAgent = ()=>{
3840
3942
  };
3841
3943
  return JSON.stringify(ua);
3842
3944
  };
3843
- /* eslint-disable @typescript-eslint/no-explicit-any */ const fetcher_handleError = (error)=>{
3945
+ const getBrowserClientUserAgent = ()=>{
3946
+ const browserInfo = {
3947
+ name: 'unknown',
3948
+ version: 'unknown'
3949
+ };
3950
+ const osInfo = {
3951
+ name: 'unknown',
3952
+ version: 'unknown'
3953
+ };
3954
+ const { userAgent } = navigator;
3955
+ // 检测操作系统及版本
3956
+ if (userAgent.indexOf('Windows') > -1) {
3957
+ var _userAgent_match;
3958
+ osInfo.name = 'windows';
3959
+ const windowsVersion = (null === (_userAgent_match = userAgent.match(/Windows NT ([0-9.]+)/)) || void 0 === _userAgent_match ? void 0 : _userAgent_match[1]) || 'unknown';
3960
+ osInfo.version = windowsVersion;
3961
+ } else if (userAgent.indexOf('Mac OS X') > -1) {
3962
+ var _userAgent_match1;
3963
+ osInfo.name = 'macos';
3964
+ // 将 10_15_7 格式转换为 10.15.7
3965
+ osInfo.version = ((null === (_userAgent_match1 = userAgent.match(/Mac OS X ([0-9_]+)/)) || void 0 === _userAgent_match1 ? void 0 : _userAgent_match1[1]) || 'unknown').replace(/_/g, '.');
3966
+ } else if (userAgent.indexOf('Linux') > -1) {
3967
+ var _userAgent_match2;
3968
+ osInfo.name = 'linux';
3969
+ osInfo.version = (null === (_userAgent_match2 = userAgent.match(/Linux ([0-9.]+)/)) || void 0 === _userAgent_match2 ? void 0 : _userAgent_match2[1]) || 'unknown';
3970
+ }
3971
+ // 检测浏览器及版本
3972
+ if (userAgent.indexOf('Chrome') > -1) {
3973
+ var _userAgent_match3;
3974
+ browserInfo.name = 'chrome';
3975
+ browserInfo.version = (null === (_userAgent_match3 = userAgent.match(/Chrome\/([0-9.]+)/)) || void 0 === _userAgent_match3 ? void 0 : _userAgent_match3[1]) || 'unknown';
3976
+ } else if (userAgent.indexOf('Firefox') > -1) {
3977
+ var _userAgent_match4;
3978
+ browserInfo.name = 'firefox';
3979
+ browserInfo.version = (null === (_userAgent_match4 = userAgent.match(/Firefox\/([0-9.]+)/)) || void 0 === _userAgent_match4 ? void 0 : _userAgent_match4[1]) || 'unknown';
3980
+ } else if (userAgent.indexOf('Safari') > -1) {
3981
+ var _userAgent_match5;
3982
+ browserInfo.name = 'safari';
3983
+ browserInfo.version = (null === (_userAgent_match5 = userAgent.match(/Version\/([0-9.]+)/)) || void 0 === _userAgent_match5 ? void 0 : _userAgent_match5[1]) || 'unknown';
3984
+ }
3985
+ const ua = {
3986
+ version: esm_version,
3987
+ browser: browserInfo.name,
3988
+ browser_version: browserInfo.version,
3989
+ os_name: osInfo.name,
3990
+ os_version: osInfo.version
3991
+ };
3992
+ return JSON.stringify(ua);
3993
+ };
3994
+ /* eslint-disable @typescript-eslint/no-explicit-any */ const esm_handleError = (error)=>{
3844
3995
  if (!error.isAxiosError && (!error.code || !error.message)) return new CozeError(`Unexpected error: ${error.message}`);
3845
3996
  if ('ECONNABORTED' === error.code && error.message.includes('timeout') || 'ETIMEDOUT' === error.code) {
3846
3997
  var _error_response;
3847
3998
  return new TimeoutError(408, void 0, `Request timed out: ${error.message}`, null === (_error_response = error.response) || void 0 === _error_response ? void 0 : _error_response.headers);
3848
3999
  }
3849
4000
  if ('ERR_CANCELED' === error.code) return new APIUserAbortError(error.message);
3850
- else {
3851
- var _error_response1, _error_response2, _error_response3;
3852
- return error_APIError.generate((null === (_error_response1 = error.response) || void 0 === _error_response1 ? void 0 : _error_response1.status) || 500, null === (_error_response2 = error.response) || void 0 === _error_response2 ? void 0 : _error_response2.data, error.message, null === (_error_response3 = error.response) || void 0 === _error_response3 ? void 0 : _error_response3.headers);
3853
- }
4001
+ var _error_response1, _error_response2, _error_response3;
4002
+ return APIError.generate((null === (_error_response1 = error.response) || void 0 === _error_response1 ? void 0 : _error_response1.status) || 500, null === (_error_response2 = error.response) || void 0 === _error_response2 ? void 0 : _error_response2.data, error.message, null === (_error_response3 = error.response) || void 0 === _error_response3 ? void 0 : _error_response3.headers);
3854
4003
  };
3855
4004
  async function fetchAPI(url) {
3856
4005
  let options = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
@@ -3866,7 +4015,7 @@ async function fetchAPI(url) {
3866
4015
  adapter: options.isStreaming ? 'fetch' : void 0,
3867
4016
  ...options
3868
4017
  }).catch((error)=>{
3869
- throw fetcher_handleError(error);
4018
+ throw esm_handleError(error);
3870
4019
  });
3871
4020
  return {
3872
4021
  async *stream () {
@@ -3904,7 +4053,7 @@ async function fetchAPI(url) {
3904
4053
  buffer = lines[lines.length - 1]; // Keep the last incomplete line in the buffer
3905
4054
  }
3906
4055
  } catch (error) {
3907
- fetcher_handleError(error);
4056
+ esm_handleError(error);
3908
4057
  }
3909
4058
  },
3910
4059
  json: ()=>response.data,
@@ -3928,8 +4077,8 @@ function isAxiosStatic(instance) {
3928
4077
  }
3929
4078
  /**
3930
4079
  * default coze base URL is api.coze.com
3931
- */ const constant_COZE_COM_BASE_URL = 'https://api.coze.com';
3932
- /* eslint-disable max-params */ class core_APIClient {
4080
+ */ const COZE_COM_BASE_URL = 'https://api.coze.com';
4081
+ /* eslint-disable max-params */ class APIClient {
3933
4082
  async getToken() {
3934
4083
  if ('function' == typeof this.token) return await this.token();
3935
4084
  return this.token;
@@ -3939,11 +4088,12 @@ function isAxiosStatic(instance) {
3939
4088
  const headers = {
3940
4089
  authorization: `Bearer ${token}`
3941
4090
  };
3942
- if (!utils_isBrowser()) {
4091
+ if (isBrowser()) headers['X-Coze-Client-User-Agent'] = getBrowserClientUserAgent();
4092
+ else {
3943
4093
  headers['User-Agent'] = getUserAgent();
3944
4094
  headers['X-Coze-Client-User-Agent'] = getNodeClientUserAgent();
3945
4095
  }
3946
- const config = mergeConfig(this.axiosOptions, options, {
4096
+ const config = esm_mergeConfig(this.axiosOptions, options, {
3947
4097
  headers
3948
4098
  });
3949
4099
  config.method = method;
@@ -3967,7 +4117,7 @@ function isAxiosStatic(instance) {
3967
4117
  if (contentType && contentType.includes('application/json')) {
3968
4118
  const result = await json();
3969
4119
  const { code, msg } = result;
3970
- if (0 !== code && void 0 !== code) throw error_APIError.generate(response.status, result, msg, response.headers);
4120
+ if (0 !== code && void 0 !== code) throw APIError.generate(response.status, result, msg, response.headers);
3971
4121
  }
3972
4122
  return stream();
3973
4123
  }
@@ -3975,7 +4125,7 @@ function isAxiosStatic(instance) {
3975
4125
  {
3976
4126
  const result = await json();
3977
4127
  const { code, msg } = result;
3978
- if (0 !== code && void 0 !== code) throw error_APIError.generate(response.status, result, msg, response.headers);
4128
+ if (0 !== code && void 0 !== code) throw APIError.generate(response.status, result, msg, response.headers);
3979
4129
  return result;
3980
4130
  }
3981
4131
  }
@@ -4007,35 +4157,31 @@ function isAxiosStatic(instance) {
4007
4157
  }
4008
4158
  constructor(config){
4009
4159
  this._config = config;
4010
- this.baseURL = config.baseURL || constant_COZE_COM_BASE_URL;
4160
+ this.baseURL = config.baseURL || COZE_COM_BASE_URL;
4011
4161
  this.token = config.token;
4012
4162
  this.axiosOptions = config.axiosOptions || {};
4013
4163
  this.axiosInstance = config.axiosInstance;
4014
4164
  this.debug = config.debug || false;
4015
4165
  this.allowPersonalAccessTokenInBrowser = config.allowPersonalAccessTokenInBrowser || false;
4016
4166
  this.headers = config.headers;
4017
- if (utils_isBrowser() && 'function' != typeof this.token && isPersonalAccessToken(this.token) && !this.allowPersonalAccessTokenInBrowser) throw new CozeError('Browser environments do not support authentication using Personal Access Token (PAT) by default.\nas it may expose secret API keys. \n\nPlease use OAuth2.0 authentication mechanism. see:\nhttps://www.coze.com/docs/developer_guides/oauth_apps?_lang=en \n\nIf you need to force use, please set the `allowPersonalAccessTokenInBrowser` option to `true`. \n\ne.g new CozeAPI({ token, allowPersonalAccessTokenInBrowser: true });\n\n');
4018
- }
4019
- }
4020
- core_APIClient.APIError = error_APIError;
4021
- core_APIClient.BadRequestError = BadRequestError;
4022
- core_APIClient.AuthenticationError = AuthenticationError;
4023
- core_APIClient.PermissionDeniedError = PermissionDeniedError;
4024
- core_APIClient.NotFoundError = NotFoundError;
4025
- core_APIClient.RateLimitError = RateLimitError;
4026
- core_APIClient.InternalServerError = InternalServerError;
4027
- core_APIClient.GatewayError = GatewayError;
4028
- core_APIClient.TimeoutError = TimeoutError;
4029
- core_APIClient.UserAbortError = APIUserAbortError;
4030
- // EXTERNAL MODULE: crypto (ignored)
4031
- __webpack_require__("?666e");
4032
- // EXTERNAL MODULE: jsonwebtoken (ignored)
4033
- __webpack_require__("?79fd");
4034
- class CozeAPI extends core_APIClient {
4167
+ if (isBrowser() && 'function' != typeof this.token && isPersonalAccessToken(this.token) && !this.allowPersonalAccessTokenInBrowser) throw new CozeError('Browser environments do not support authentication using Personal Access Token (PAT) by default.\nas it may expose secret API keys. \n\nPlease use OAuth2.0 authentication mechanism. see:\nhttps://www.coze.com/docs/developer_guides/oauth_apps?_lang=en \n\nIf you need to force use, please set the `allowPersonalAccessTokenInBrowser` option to `true`. \n\ne.g new CozeAPI({ token, allowPersonalAccessTokenInBrowser: true });\n\n');
4168
+ }
4169
+ }
4170
+ APIClient.APIError = APIError;
4171
+ APIClient.BadRequestError = BadRequestError;
4172
+ APIClient.AuthenticationError = AuthenticationError;
4173
+ APIClient.PermissionDeniedError = PermissionDeniedError;
4174
+ APIClient.NotFoundError = NotFoundError;
4175
+ APIClient.RateLimitError = RateLimitError;
4176
+ APIClient.InternalServerError = InternalServerError;
4177
+ APIClient.GatewayError = GatewayError;
4178
+ APIClient.TimeoutError = TimeoutError;
4179
+ APIClient.UserAbortError = APIUserAbortError;
4180
+ class CozeAPI extends APIClient {
4035
4181
  constructor(...args){
4036
4182
  super(...args), this.bots = new Bots(this), this.chat = new Chat(this), this.conversations = new Conversations(this), this.files = new Files(this), /**
4037
4183
  * @deprecated
4038
- */ this.knowledge = new Knowledge(this), this.datasets = new Datasets(this), this.workflows = new Workflows(this), this.workspaces = new WorkSpaces(this), this.audio = new audio_Audio(this);
4184
+ */ this.knowledge = new Knowledge(this), this.datasets = new Datasets(this), this.workflows = new Workflows(this), this.workspaces = new WorkSpaces(this), this.audio = new esm_Audio(this), this.templates = new Templates(this);
4039
4185
  }
4040
4186
  }
4041
4187
  /**
@@ -38420,7 +38566,7 @@ var VERTC = _createClass(function e() {
38420
38566
  + * @param milliseconds The time to sleep in milliseconds
38421
38567
  + * @throws {Error} If milliseconds is negative
38422
38568
  + * @returns Promise that resolves after the specified duration
38423
- + */ const src_utils_sleep = (milliseconds)=>{
38569
+ + */ const utils_sleep = (milliseconds)=>{
38424
38570
  if (milliseconds < 0) throw new Error('Sleep duration must be non-negative');
38425
38571
  return new Promise((resolve)=>setTimeout(resolve, milliseconds));
38426
38572
  };
@@ -38440,7 +38586,11 @@ var VERTC = _createClass(function e() {
38440
38586
  return false;
38441
38587
  }
38442
38588
  };
38443
- const checkDevicePermission = async function() {
38589
+ /**
38590
+ * Checks device permissions for audio and video
38591
+ * @param checkVideo Whether to check video permissions (default: false)
38592
+ * @returns Promise that resolves with the device permission status
38593
+ */ const checkDevicePermission = async function() {
38444
38594
  let checkVideo = arguments.length > 0 && void 0 !== arguments[0] && arguments[0];
38445
38595
  return await index_esm_min_index.enableDevices({
38446
38596
  audio: true,
@@ -38453,7 +38603,16 @@ const checkDevicePermission = async function() {
38453
38603
  */ const getAudioDevices = async function() {
38454
38604
  let { video = false } = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
38455
38605
  let devices = [];
38456
- devices = video ? await index_esm_min_index.enumerateDevices() : await [
38606
+ if (video) {
38607
+ devices = await index_esm_min_index.enumerateDevices();
38608
+ if (isScreenShareSupported()) // @ts-expect-error - add screenShare device to devices
38609
+ devices.push({
38610
+ deviceId: 'screenShare',
38611
+ kind: 'videoinput',
38612
+ label: 'Screen Share',
38613
+ groupId: 'screenShare'
38614
+ });
38615
+ } else devices = await [
38457
38616
  ...await index_esm_min_index.enumerateAudioCaptureDevices(),
38458
38617
  ...await index_esm_min_index.enumerateAudioPlaybackDevices()
38459
38618
  ];
@@ -38468,6 +38627,14 @@ const checkDevicePermission = async function() {
38468
38627
  videoInputs: devices.filter((i)=>i.deviceId && 'videoinput' === i.kind)
38469
38628
  };
38470
38629
  };
38630
+ const isScreenShareDevice = (deviceId)=>'screenShare' === deviceId;
38631
+ /**
38632
+ * Check if browser supports screen sharing
38633
+ * 检查浏览器是否支持屏幕共享
38634
+ */ function isScreenShareSupported() {
38635
+ var _navigator_mediaDevices, _navigator;
38636
+ return !!(null === (_navigator = navigator) || void 0 === _navigator ? void 0 : null === (_navigator_mediaDevices = _navigator.mediaDevices) || void 0 === _navigator_mediaDevices ? void 0 : _navigator_mediaDevices.getDisplayMedia);
38637
+ }
38471
38638
  var error_RealtimeError = /*#__PURE__*/ function(RealtimeError) {
38472
38639
  RealtimeError["DEVICE_ACCESS_ERROR"] = "DEVICE_ACCESS_ERROR";
38473
38640
  RealtimeError["STREAM_CREATION_ERROR"] = "STREAM_CREATION_ERROR";
@@ -38561,6 +38728,10 @@ var event_handler_EventNames = /*#__PURE__*/ function(EventNames) {
38561
38728
  * zh: 音频输出设备改变
38562
38729
  */ EventNames["AUDIO_OUTPUT_DEVICE_CHANGED"] = "client.output.device.changed";
38563
38730
  /**
38731
+ * en: Video input device changed
38732
+ * zh: 视频输入设备改变
38733
+ */ EventNames["VIDEO_INPUT_DEVICE_CHANGED"] = "client.video.input.device.changed";
38734
+ /**
38564
38735
  * en: Bot joined
38565
38736
  * zh: Bot 加入
38566
38737
  */ EventNames["BOT_JOIN"] = "server.bot.join";
@@ -41978,23 +42149,47 @@ class EngineClient extends RealtimeEventHandler {
41978
42149
  if (-1 === devices.audioOutputs.findIndex((i)=>i.deviceId === deviceId)) throw new RealtimeAPIError(error_RealtimeError.DEVICE_ACCESS_ERROR, `Audio output device not found: ${deviceId}`);
41979
42150
  await this.engine.setAudioPlaybackDevice(deviceId);
41980
42151
  }
42152
+ async setVideoInputDevice(deviceId) {
42153
+ let isAutoCapture = !(arguments.length > 1) || void 0 === arguments[1] || arguments[1];
42154
+ var _this__videoConfig;
42155
+ const devices = await getAudioDevices({
42156
+ video: true
42157
+ });
42158
+ if (-1 === devices.videoInputs.findIndex((i)=>i.deviceId === deviceId)) throw new RealtimeAPIError(error_RealtimeError.DEVICE_ACCESS_ERROR, `Video input device not found: ${deviceId}`);
42159
+ await this.changeVideoState(false);
42160
+ if (isScreenShareDevice(deviceId)) {
42161
+ if (this._streamIndex === StreamIndex$1.STREAM_INDEX_MAIN) this.engine.setLocalVideoPlayer(StreamIndex$1.STREAM_INDEX_MAIN);
42162
+ if (isAutoCapture) {
42163
+ var _this__videoConfig1;
42164
+ this.engine.setVideoSourceType(StreamIndex$1.STREAM_INDEX_SCREEN, VideoSourceType.VIDEO_SOURCE_TYPE_INTERNAL);
42165
+ await this.engine.startScreenCapture(null === (_this__videoConfig1 = this._videoConfig) || void 0 === _this__videoConfig1 ? void 0 : _this__videoConfig1.screenConfig);
42166
+ await this.engine.publishScreen(MediaType$1.VIDEO);
42167
+ }
42168
+ this._streamIndex = StreamIndex$1.STREAM_INDEX_SCREEN;
42169
+ } else {
42170
+ if (this._streamIndex === StreamIndex$1.STREAM_INDEX_SCREEN) this.engine.setLocalVideoPlayer(StreamIndex$1.STREAM_INDEX_SCREEN);
42171
+ if (isAutoCapture) await this.engine.startVideoCapture(deviceId);
42172
+ this._streamIndex = StreamIndex$1.STREAM_INDEX_MAIN;
42173
+ }
42174
+ this.engine.setLocalVideoPlayer(this._streamIndex, {
42175
+ renderDom: (null === (_this__videoConfig = this._videoConfig) || void 0 === _this__videoConfig ? void 0 : _this__videoConfig.renderDom) || 'local-player',
42176
+ userId: this._roomUserId
42177
+ });
42178
+ }
41981
42179
  async createLocalStream(userId, videoConfig) {
42180
+ this._roomUserId = userId;
41982
42181
  const devices = await getAudioDevices({
41983
42182
  video: this._isSupportVideo
41984
42183
  });
41985
42184
  if (!devices.audioInputs.length) throw new RealtimeAPIError(error_RealtimeError.DEVICE_ACCESS_ERROR, 'Failed to get audio devices');
41986
42185
  if (this._isSupportVideo && !devices.videoInputs.length) throw new RealtimeAPIError(error_RealtimeError.DEVICE_ACCESS_ERROR, 'Failed to get video devices');
41987
42186
  await this.engine.startAudioCapture(devices.audioInputs[0].deviceId);
41988
- if (this._isSupportVideo && (null == videoConfig ? void 0 : videoConfig.videoOnDefault)) await this.engine.startVideoCapture(devices.videoInputs[0].deviceId);
41989
- if (this._isSupportVideo) this.engine.setLocalVideoPlayer(StreamIndex$1.STREAM_INDEX_MAIN, {
41990
- renderDom: (null == videoConfig ? void 0 : videoConfig.renderDom) || 'local-player',
41991
- userId
41992
- });
42187
+ if (this._isSupportVideo) this.setVideoInputDevice((null == videoConfig ? void 0 : videoConfig.videoInputDeviceId) || devices.videoInputs[0].deviceId, null == videoConfig ? void 0 : videoConfig.videoOnDefault);
41993
42188
  }
41994
42189
  async disconnect() {
41995
42190
  try {
41996
- if (this._isSupportVideo) await this.engine.stopVideoCapture();
41997
- await this.engine.stopAudioCapture();
42191
+ if (this._isSupportVideo) await this.changeVideoState(false);
42192
+ await this.changeAudioState(false);
41998
42193
  await this.engine.unpublishStream(MediaType$1.AUDIO);
41999
42194
  await this.engine.leaveRoom();
42000
42195
  this.removeEventListener();
@@ -42014,8 +42209,19 @@ class EngineClient extends RealtimeEventHandler {
42014
42209
  }
42015
42210
  async changeVideoState(isVideoOn) {
42016
42211
  try {
42017
- if (isVideoOn) await this.engine.startVideoCapture();
42018
- else await this.engine.stopVideoCapture();
42212
+ if (isVideoOn) {
42213
+ if (this._streamIndex === StreamIndex$1.STREAM_INDEX_MAIN) await this.engine.startVideoCapture();
42214
+ else {
42215
+ var _this__videoConfig;
42216
+ this.engine.setVideoSourceType(StreamIndex$1.STREAM_INDEX_SCREEN, VideoSourceType.VIDEO_SOURCE_TYPE_INTERNAL);
42217
+ await this.engine.startScreenCapture(null === (_this__videoConfig = this._videoConfig) || void 0 === _this__videoConfig ? void 0 : _this__videoConfig.screenConfig);
42218
+ await this.engine.publishScreen(MediaType$1.VIDEO);
42219
+ }
42220
+ } else if (this._streamIndex === StreamIndex$1.STREAM_INDEX_MAIN) await this.engine.stopVideoCapture();
42221
+ else {
42222
+ await this.engine.stopScreenCapture();
42223
+ await this.engine.unpublishScreen(MediaType$1.VIDEO);
42224
+ }
42019
42225
  } catch (e) {
42020
42226
  this.dispatch(event_handler_EventNames.ERROR, e);
42021
42227
  throw e;
@@ -42093,7 +42299,7 @@ class EngineClient extends RealtimeEventHandler {
42093
42299
  }
42094
42300
  }
42095
42301
  // eslint-disable-next-line max-params
42096
- constructor(appId, debug = false, isTestEnv = false, isSupportVideo = false){
42302
+ constructor(appId, debug = false, isTestEnv = false, isSupportVideo = false, videoConfig){
42097
42303
  super(debug), this.joinUserId = '', this._AIAnsExtension = null, this._isSupportVideo = false;
42098
42304
  if (isTestEnv) index_esm_min_index.setParameter('ICE_CONFIG_REQUEST_URLS', [
42099
42305
  'rtc-test.bytedance.com'
@@ -42108,6 +42314,7 @@ class EngineClient extends RealtimeEventHandler {
42108
42314
  this.handleLocalAudioPropertiesReport = this.handleLocalAudioPropertiesReport.bind(this);
42109
42315
  this.handleRemoteAudioPropertiesReport = this.handleRemoteAudioPropertiesReport.bind(this);
42110
42316
  this._isSupportVideo = isSupportVideo;
42317
+ this._videoConfig = videoConfig;
42111
42318
  }
42112
42319
  }
42113
42320
  class RealtimeClient extends RealtimeEventHandler {
@@ -42132,7 +42339,7 @@ class RealtimeClient extends RealtimeEventHandler {
42132
42339
  throw new RealtimeAPIError(error_RealtimeError.CREATE_ROOM_ERROR, error instanceof Error ? error.message : 'Unknown error', error);
42133
42340
  }
42134
42341
  // Step2 create engine
42135
- this._client = new EngineClient(roomInfo.app_id, this._config.debug, this._isTestEnv, this._isSupportVideo);
42342
+ this._client = new EngineClient(roomInfo.app_id, this._config.debug, this._isTestEnv, this._isSupportVideo, this._config.videoConfig);
42136
42343
  // Step3 bind engine events
42137
42344
  this._client.bindEngineEvents();
42138
42345
  this._client.on(event_handler_EventNames.ALL, (eventName, data)=>{
@@ -42268,6 +42475,13 @@ class RealtimeClient extends RealtimeEventHandler {
42268
42475
  deviceId
42269
42476
  });
42270
42477
  }
42478
+ async setVideoInputDevice(deviceId) {
42479
+ var _this__client;
42480
+ await (null === (_this__client = this._client) || void 0 === _this__client ? void 0 : _this__client.setVideoInputDevice(deviceId));
42481
+ this.dispatch(event_handler_EventNames.VIDEO_INPUT_DEVICE_CHANGED, {
42482
+ deviceId
42483
+ });
42484
+ }
42271
42485
  /**
42272
42486
  * Constructor for initializing a RealtimeClient instance.
42273
42487
  *
@@ -42298,6 +42512,16 @@ class RealtimeClient extends RealtimeEventHandler {
42298
42512
  * @param config.suppressNonStationaryNoise - Optional, suppress non-stationary noise, defaults to false. |
42299
42513
  * 可选,默认是否抑制非静态噪声,默认值为 false。
42300
42514
  * @param config.isAutoSubscribeAudio - Optional, whether to automatically subscribe to bot reply audio streams, defaults to true. |
42515
+ * @param config.videoConfig - Optional, Video configuration. |
42516
+ * 可选,视频配置。
42517
+ * @param config.videoConfig.videoOnDefault - Optional, Whether to turn on video by default, defaults to true. |
42518
+ * 可选,默认是否开启视频,默认值为 true。
42519
+ * @param config.videoConfig.renderDom - Optional, The DOM element to render the video stream to. |
42520
+ * 可选,渲染视频流的 DOM 元素。
42521
+ * @param config.videoConfig.videoInputDeviceId - Optional, The device ID of the video input device to use. |
42522
+ * 可选,视频输入设备的设备 ID。
42523
+ * @param config.videoConfig.screenConfig - Optional, Screen share configuration if videoInputDeviceId is 'screenShare' see https://www.volcengine.com/docs/6348/104481#screenconfig for more details. |
42524
+ * 可选,屏幕共享配置,如果 videoInputDeviceId 是 'screenShare',请参考 https://www.volcengine.com/docs/6348/104481#screenconfig 了解更多详情。
42301
42525
  */ constructor(config){
42302
42526
  super(config.debug), this._client = null, this.isConnected = false, this._isTestEnv = false, this._isSupportVideo = false;
42303
42527
  this._config = config;