@coze/realtime-api 1.0.3 → 1.0.4-alpha.2d8e39

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