@coze/realtime-api 1.0.1 → 1.0.3-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,10 @@
1
- /*! For license information please see index.js.LICENSE.txt */
1
+ /*! For license information please see index.mjs.LICENSE.txt */
2
2
  var __webpack_modules__ = {
3
- "?de24": function() {
3
+ "?666e": function() {
4
4
  /* (ignored) */ },
5
- "?2a9f": function() {
5
+ "?79fd": function() {
6
6
  /* (ignored) */ },
7
- "?d039": 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, {
@@ -61,7 +76,7 @@ function __webpack_require__(moduleId) {
61
76
  });
62
77
  };
63
78
  })();
64
- /************************************************************************/ // NAMESPACE OBJECT: ../../common/temp/default/node_modules/.pnpm/axios@1.7.7/node_modules/axios/lib/platform/common/utils.js
79
+ /************************************************************************/ // NAMESPACE OBJECT: ../../common/temp/default/node_modules/.pnpm/axios@1.7.7_debug@4.3.7/node_modules/axios/lib/platform/common/utils.js
65
80
  var common_utils_namespaceObject = {};
66
81
  __webpack_require__.r(common_utils_namespaceObject);
67
82
  __webpack_require__.d(common_utils_namespaceObject, {
@@ -75,486 +90,1048 @@ __webpack_require__.d(common_utils_namespaceObject, {
75
90
  var src_utils_namespaceObject = {};
76
91
  __webpack_require__.r(src_utils_namespaceObject);
77
92
  __webpack_require__.d(src_utils_namespaceObject, {
93
+ checkDevicePermission: ()=>checkDevicePermission,
78
94
  checkPermission: ()=>checkPermission,
79
95
  getAudioDevices: ()=>getAudioDevices,
80
- sleep: ()=>utils_sleep
96
+ sleep: ()=>src_utils_sleep
81
97
  });
82
- function bind(fn, thisArg) {
83
- return function() {
84
- return fn.apply(thisArg, arguments);
85
- };
98
+ class APIResource {
99
+ constructor(client){
100
+ this._client = client;
101
+ }
86
102
  }
87
- // utils is a library of generic helper functions non-specific to axios
88
- const { toString: utils_toString } = Object.prototype;
89
- const { getPrototypeOf } = Object;
90
- const kindOf = ((cache)=>(thing)=>{
91
- const str = utils_toString.call(thing);
92
- return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
93
- })(Object.create(null));
94
- const kindOfTest = (type)=>{
95
- type = type.toLowerCase();
96
- return (thing)=>kindOf(thing) === type;
97
- };
98
- const typeOfTest = (type)=>(thing)=>typeof thing === type;
99
- /**
100
- * Determine if a value is an Array
101
- *
102
- * @param {Object} val The value to test
103
- *
104
- * @returns {boolean} True if value is an Array, otherwise false
105
- */ const { isArray } = Array;
106
- /**
107
- * Determine if a value is undefined
108
- *
109
- * @param {*} val The value to test
110
- *
111
- * @returns {boolean} True if the value is undefined, otherwise false
112
- */ const isUndefined = typeOfTest('undefined');
113
- /**
114
- * Determine if a value is a Buffer
115
- *
116
- * @param {*} val The value to test
117
- *
118
- * @returns {boolean} True if value is a Buffer, otherwise false
119
- */ function isBuffer(val) {
120
- return null !== val && !isUndefined(val) && null !== val.constructor && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
103
+ /* eslint-disable @typescript-eslint/no-namespace */ class Bots extends APIResource {
104
+ /**
105
+ * Create a new agent. | 调用接口创建一个新的智能体。
106
+ * @docs en:https://www.coze.com/docs/developer_guides/create_bot?_lang=en
107
+ * @docs zh:https://www.coze.cn/docs/developer_guides/create_bot?_lang=zh
108
+ * @param params - Required The parameters for creating a bot. | 创建 Bot 的参数。
109
+ * @param params.space_id - Required The Space ID of the space where the agent is located. | Bot 所在的空间的 Space ID。
110
+ * @param params.name - Required The name of the agent. It should be 1 to 20 characters long. | Bot 的名称。
111
+ * @param params.description - Optional The description of the agent. It can be 0 to 500 characters long. | Bot 的描述信息。
112
+ * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
113
+ * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
114
+ * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
115
+ * @returns Information about the created bot. | 创建的 Bot 信息。
116
+ */ async create(params, options) {
117
+ const apiUrl = '/v1/bot/create';
118
+ const result = await this._client.post(apiUrl, params, false, options);
119
+ return result.data;
120
+ }
121
+ /**
122
+ * Update the configuration of an agent. | 调用接口修改智能体的配置。
123
+ * @docs en:https://www.coze.com/docs/developer_guides/update_bot?_lang=en
124
+ * @docs zh:https://www.coze.cn/docs/developer_guides/update_bot?_lang=zh
125
+ * @param params - Required The parameters for updating a bot. | 修改 Bot 的参数。
126
+ * @param params.bot_id - Required The ID of the agent that the API interacts with. | 待修改配置的智能体ID。
127
+ * @param params.name - Optional The name of the agent. | Bot 的名称。
128
+ * @param params.description - Optional The description of the agent. | Bot 的描述信息。
129
+ * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
130
+ * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
131
+ * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
132
+ * @param params.knowledge - Optional Knowledge configurations of the agent. | Bot 的知识库配置。
133
+ * @returns Undefined | 无返回值
134
+ */ async update(params, options) {
135
+ const apiUrl = '/v1/bot/update';
136
+ const result = await this._client.post(apiUrl, params, false, options);
137
+ return result.data;
138
+ }
139
+ /**
140
+ * Get the agents published as API service. | 调用接口查看指定空间发布到 Agent as API 渠道的智能体列表。
141
+ * @docs en:https://www.coze.com/docs/developer_guides/published_bots_list?_lang=en
142
+ * @docs zh:https://www.coze.cn/docs/developer_guides/published_bots_list?_lang=zh
143
+ * @param params - Required The parameters for listing bots. | 列出 Bot 的参数。
144
+ * @param params.space_id - Required The ID of the space. | Bot 所在的空间的 Space ID。
145
+ * @param params.page_size - Optional Pagination size. | 分页大小。
146
+ * @param params.page_index - Optional Page number for paginated queries. | 分页查询时的页码。
147
+ * @returns List of published bots. | 已发布的 Bot 列表。
148
+ */ async list(params, options) {
149
+ const apiUrl = '/v1/space/published_bots_list';
150
+ const result = await this._client.get(apiUrl, params, false, options);
151
+ return result.data;
152
+ }
153
+ /**
154
+ * Publish the specified agent as an API service. | 调用接口创建一个新的智能体。
155
+ * @docs en:https://www.coze.com/docs/developer_guides/publish_bot?_lang=en
156
+ * @docs zh:https://www.coze.cn/docs/developer_guides/publish_bot?_lang=zh
157
+ * @param params - Required The parameters for publishing a bot. | 发布 Bot 的参数。
158
+ * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要发布的智能体ID。
159
+ * @param params.connector_ids - Required The list of publishing channel IDs for the agent. | 智能体的发布渠道 ID 列表。
160
+ * @returns Undefined | 无返回值
161
+ */ async publish(params, options) {
162
+ const apiUrl = '/v1/bot/publish';
163
+ const result = await this._client.post(apiUrl, params, false, options);
164
+ return result.data;
165
+ }
166
+ /**
167
+ * Get the configuration information of the agent. | 获取指定智能体的配置信息。
168
+ * @docs en:https://www.coze.com/docs/developer_guides/get_metadata?_lang=en
169
+ * @docs zh:https://www.coze.cn/docs/developer_guides/get_metadata?_lang=zh
170
+ * @param params - Required The parameters for retrieving a bot. | 获取 Bot 的参数。
171
+ * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要查看的智能体ID。
172
+ * @returns Information about the bot. | Bot 的配置信息。
173
+ */ async retrieve(params, options) {
174
+ const apiUrl = '/v1/bot/get_online_info';
175
+ const result = await this._client.get(apiUrl, params, false, options);
176
+ return result.data;
177
+ }
121
178
  }
122
- /**
123
- * Determine if a value is an ArrayBuffer
124
- *
125
- * @param {*} val The value to test
126
- *
127
- * @returns {boolean} True if value is an ArrayBuffer, otherwise false
128
- */ const isArrayBuffer = kindOfTest('ArrayBuffer');
129
- /**
130
- * Determine if a value is a view on an ArrayBuffer
131
- *
132
- * @param {*} val The value to test
133
- *
134
- * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
135
- */ function isArrayBufferView(val) {
136
- let result;
137
- result = 'undefined' != typeof ArrayBuffer && ArrayBuffer.isView ? ArrayBuffer.isView(val) : val && val.buffer && isArrayBuffer(val.buffer);
138
- return result;
179
+ /* eslint-disable security/detect-object-injection */ /* eslint-disable @typescript-eslint/no-explicit-any */ function safeJsonParse(jsonString) {
180
+ let defaultValue = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : '';
181
+ try {
182
+ return JSON.parse(jsonString);
183
+ } catch (error) {
184
+ return defaultValue;
185
+ }
139
186
  }
140
- /**
141
- * Determine if a value is a String
142
- *
143
- * @param {*} val The value to test
144
- *
145
- * @returns {boolean} True if value is a String, otherwise false
146
- */ const isString = typeOfTest('string');
147
- /**
148
- * Determine if a value is a Function
149
- *
150
- * @param {*} val The value to test
151
- * @returns {boolean} True if value is a Function, otherwise false
152
- */ const isFunction = typeOfTest('function');
153
- /**
154
- * Determine if a value is a Number
155
- *
156
- * @param {*} val The value to test
157
- *
158
- * @returns {boolean} True if value is a Number, otherwise false
159
- */ const isNumber = typeOfTest('number');
160
- /**
161
- * Determine if a value is an Object
162
- *
163
- * @param {*} thing The value to test
164
- *
165
- * @returns {boolean} True if value is an Object, otherwise false
166
- */ const isObject = (thing)=>null !== thing && 'object' == typeof thing;
167
- /**
168
- * Determine if a value is a Boolean
169
- *
170
- * @param {*} thing The value to test
171
- * @returns {boolean} True if value is a Boolean, otherwise false
172
- */ const isBoolean = (thing)=>true === thing || false === thing;
173
- /**
174
- * Determine if a value is a plain Object
175
- *
176
- * @param {*} val The value to test
177
- *
178
- * @returns {boolean} True if value is a plain Object, otherwise false
179
- */ const isPlainObject = (val)=>{
180
- if ('object' !== kindOf(val)) return false;
181
- const prototype = getPrototypeOf(val);
182
- return (null === prototype || prototype === Object.prototype || null === Object.getPrototypeOf(prototype)) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
183
- };
184
- /**
185
- * Determine if a value is a Date
186
- *
187
- * @param {*} val The value to test
188
- *
189
- * @returns {boolean} True if value is a Date, otherwise false
190
- */ const isDate = kindOfTest('Date');
191
- /**
192
- * Determine if a value is a File
193
- *
194
- * @param {*} val The value to test
195
- *
196
- * @returns {boolean} True if value is a File, otherwise false
197
- */ const isFile = kindOfTest('File');
198
- /**
199
- * Determine if a value is a Blob
200
- *
201
- * @param {*} val The value to test
202
- *
203
- * @returns {boolean} True if value is a Blob, otherwise false
204
- */ const isBlob = kindOfTest('Blob');
205
- /**
206
- * Determine if a value is a FileList
207
- *
208
- * @param {*} val The value to test
209
- *
210
- * @returns {boolean} True if value is a File, otherwise false
211
- */ const utils_isFileList = kindOfTest('FileList');
212
- /**
213
- * Determine if a value is a Stream
214
- *
215
- * @param {*} val The value to test
216
- *
217
- * @returns {boolean} True if value is a Stream, otherwise false
218
- */ const utils_isStream = (val)=>isObject(val) && isFunction(val.pipe);
219
- /**
220
- * Determine if a value is a FormData
221
- *
222
- * @param {*} thing The value to test
223
- *
224
- * @returns {boolean} True if value is an FormData, otherwise false
225
- */ const utils_isFormData = (thing)=>{
226
- let kind;
227
- return thing && ('function' == typeof FormData && thing instanceof FormData || isFunction(thing.append) && ('formdata' === (kind = kindOf(thing)) || // detect form-data instance
228
- 'object' === kind && isFunction(thing.toString) && '[object FormData]' === thing.toString()));
229
- };
230
- /**
231
- * Determine if a value is a URLSearchParams object
232
- *
233
- * @param {*} val The value to test
234
- *
235
- * @returns {boolean} True if value is a URLSearchParams object, otherwise false
236
- */ const isURLSearchParams = kindOfTest('URLSearchParams');
237
- const [isReadableStream, isRequest, isResponse, isHeaders] = [
238
- 'ReadableStream',
239
- 'Request',
240
- 'Response',
241
- 'Headers'
242
- ].map(kindOfTest);
243
- /**
244
- * Trim excess whitespace off the beginning and end of a string
245
- *
246
- * @param {String} str The String to trim
247
- *
248
- * @returns {String} The String freed of excess whitespace
249
- */ const trim = (str)=>str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
250
- /**
251
- * Iterate over an Array or an Object invoking a function for each item.
252
- *
253
- * If `obj` is an Array callback will be called passing
254
- * the value, index, and complete array for each item.
255
- *
256
- * If 'obj' is an Object callback will be called passing
257
- * the value, key, and complete object for each property.
258
- *
259
- * @param {Object|Array} obj The object to iterate
260
- * @param {Function} fn The callback to invoke for each item
261
- *
262
- * @param {Boolean} [allOwnKeys = false]
263
- * @returns {any}
264
- */ function forEach(obj, fn, { allOwnKeys = false } = {}) {
265
- // Don't bother if no value provided
266
- if (null == obj) return;
267
- let i;
268
- let l;
269
- // Force an array if not already something iterable
270
- if ('object' != typeof obj) /*eslint no-param-reassign:0*/ obj = [
271
- obj
272
- ];
273
- if (isArray(obj)) // Iterate over array values
274
- for(i = 0, l = obj.length; i < l; i++)fn.call(null, obj[i], i, obj);
275
- else {
276
- // Iterate over object keys
277
- const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
278
- const len = keys.length;
279
- let key;
280
- for(i = 0; i < len; i++){
281
- key = keys[i];
282
- fn.call(null, obj[key], key, obj);
187
+ function utils_sleep(ms) {
188
+ return new Promise((resolve)=>{
189
+ setTimeout(resolve, ms);
190
+ });
191
+ }
192
+ function utils_isBrowser() {
193
+ return 'undefined' != typeof window;
194
+ }
195
+ function isPlainObject(obj) {
196
+ if ('object' != typeof obj || null === obj) return false;
197
+ const proto = Object.getPrototypeOf(obj);
198
+ if (null === proto) return true;
199
+ let baseProto = proto;
200
+ while(null !== Object.getPrototypeOf(baseProto))baseProto = Object.getPrototypeOf(baseProto);
201
+ return proto === baseProto;
202
+ }
203
+ function mergeConfig() {
204
+ for(var _len = arguments.length, objects = new Array(_len), _key = 0; _key < _len; _key++)objects[_key] = arguments[_key];
205
+ return objects.reduce((result, obj)=>{
206
+ if (void 0 === obj) return result || {};
207
+ for(const key in obj)if (Object.prototype.hasOwnProperty.call(obj, key)) {
208
+ if (isPlainObject(obj[key]) && !Array.isArray(obj[key])) result[key] = mergeConfig(result[key] || {}, obj[key]);
209
+ else result[key] = obj[key];
210
+ }
211
+ return result;
212
+ }, {});
213
+ }
214
+ function isPersonalAccessToken(token) {
215
+ return null == token ? void 0 : token.startsWith('pat_');
216
+ }
217
+ /* eslint-disable max-params */ class CozeError extends Error {
218
+ }
219
+ class error_APIError extends CozeError {
220
+ static makeMessage(status, errorBody, message, headers) {
221
+ if (!errorBody && message) return message;
222
+ if (errorBody) {
223
+ const list = [];
224
+ const { code, msg, error } = errorBody;
225
+ if (code) list.push(`code: ${code}`);
226
+ if (msg) list.push(`msg: ${msg}`);
227
+ if ((null == error ? void 0 : error.detail) && msg !== error.detail) list.push(`detail: ${error.detail}`);
228
+ const logId = (null == error ? void 0 : error.logid) || (null == headers ? void 0 : headers['x-tt-logid']);
229
+ if (logId) list.push(`logid: ${logId}`);
230
+ const help_doc = null == error ? void 0 : error.help_doc;
231
+ if (help_doc) list.push(`help doc: ${help_doc}`);
232
+ return list.join(', ');
283
233
  }
234
+ if (status) return `http status code: ${status} (no body)`;
235
+ return '(no status code or body)';
236
+ }
237
+ static generate(status, errorResponse, message, headers) {
238
+ if (!status) return new APIConnectionError({
239
+ cause: castToError(errorResponse)
240
+ });
241
+ const error = errorResponse;
242
+ // https://www.coze.cn/docs/developer_guides/coze_error_codes
243
+ if (400 === status || (null == error ? void 0 : error.code) === 4000) return new BadRequestError(status, error, message, headers);
244
+ if (401 === status || (null == error ? void 0 : error.code) === 4100) return new AuthenticationError(status, error, message, headers);
245
+ if (403 === status || (null == error ? void 0 : error.code) === 4101) return new PermissionDeniedError(status, error, message, headers);
246
+ if (404 === status || (null == error ? void 0 : error.code) === 4200) return new NotFoundError(status, error, message, headers);
247
+ if (429 === status || (null == error ? void 0 : error.code) === 4013) return new RateLimitError(status, error, message, headers);
248
+ if (408 === status) return new TimeoutError(status, error, message, headers);
249
+ if (502 === status) return new GatewayError(status, error, message, headers);
250
+ if (status >= 500) return new InternalServerError(status, error, message, headers);
251
+ return new error_APIError(status, error, message, headers);
252
+ }
253
+ constructor(status, error, message, headers){
254
+ var _error_error, _error_error1;
255
+ super(`${error_APIError.makeMessage(status, error, message, headers)}`);
256
+ this.status = status;
257
+ this.headers = headers;
258
+ this.logid = null == headers ? void 0 : headers['x-tt-logid'];
259
+ // this.error = error;
260
+ this.code = null == error ? void 0 : error.code;
261
+ this.msg = null == error ? void 0 : error.msg;
262
+ this.detail = null == error ? void 0 : null === (_error_error = error.error) || void 0 === _error_error ? void 0 : _error_error.detail;
263
+ this.help_doc = null == error ? void 0 : null === (_error_error1 = error.error) || void 0 === _error_error1 ? void 0 : _error_error1.help_doc;
264
+ this.rawError = error;
284
265
  }
285
266
  }
286
- function findKey(obj, key) {
287
- key = key.toLowerCase();
288
- const keys = Object.keys(obj);
289
- let i = keys.length;
290
- let _key;
291
- while(i-- > 0){
292
- _key = keys[i];
293
- if (key === _key.toLowerCase()) return _key;
267
+ class APIConnectionError extends error_APIError {
268
+ constructor({ message, cause }){
269
+ super(void 0, void 0, message || 'Connection error.', void 0), this.status = void 0;
270
+ // if (cause) {
271
+ // this.cause = cause;
272
+ // }
294
273
  }
295
- return null;
296
274
  }
297
- const _global = (()=>{
298
- /*eslint no-undef:0*/ if ("undefined" != typeof globalThis) return globalThis;
299
- return "undefined" != typeof self ? self : 'undefined' != typeof window ? window : global;
300
- })();
301
- const isContextDefined = (context)=>!isUndefined(context) && context !== _global;
302
- /**
303
- * Accepts varargs expecting each argument to be an object, then
304
- * immutably merges the properties of each object and returns result.
305
- *
306
- * When multiple objects contain the same key the later object in
307
- * the arguments list will take precedence.
308
- *
309
- * Example:
310
- *
311
- * ```js
312
- * var result = merge({foo: 123}, {foo: 456});
313
- * console.log(result.foo); // outputs 456
314
- * ```
315
- *
316
- * @param {Object} obj1 Object to merge
317
- *
318
- * @returns {Object} Result of all merge properties
319
- */ function utils_merge() {
320
- const { caseless } = isContextDefined(this) && this || {};
321
- const result = {};
322
- const assignValue = (val, key)=>{
323
- const targetKey = caseless && findKey(result, key) || key;
324
- if (isPlainObject(result[targetKey]) && isPlainObject(val)) result[targetKey] = utils_merge(result[targetKey], val);
325
- else if (isPlainObject(val)) result[targetKey] = utils_merge({}, val);
326
- else if (isArray(val)) result[targetKey] = val.slice();
327
- else result[targetKey] = val;
328
- };
329
- for(let i = 0, l = arguments.length; i < l; i++)arguments[i] && forEach(arguments[i], assignValue);
330
- return result;
275
+ class APIUserAbortError extends error_APIError {
276
+ constructor(message){
277
+ super(void 0, void 0, message || 'Request was aborted.', void 0), this.name = 'UserAbortError', this.status = void 0;
278
+ }
331
279
  }
332
- /**
333
- * Extends object a by mutably adding to it the properties of object b.
334
- *
335
- * @param {Object} a The object to be extended
336
- * @param {Object} b The object to copy properties from
337
- * @param {Object} thisArg The object to bind function to
338
- *
339
- * @param {Boolean} [allOwnKeys]
340
- * @returns {Object} The resulting value of object a
341
- */ const extend = (a, b, thisArg, { allOwnKeys } = {})=>{
342
- forEach(b, (val, key)=>{
343
- if (thisArg && isFunction(val)) a[key] = bind(val, thisArg);
344
- else a[key] = val;
345
- }, {
346
- allOwnKeys
347
- });
348
- return a;
349
- };
350
- /**
351
- * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
352
- *
353
- * @param {string} content with BOM
354
- *
355
- * @returns {string} content value without BOM
356
- */ const stripBOM = (content)=>{
357
- if (0xFEFF === content.charCodeAt(0)) content = content.slice(1);
358
- return content;
359
- };
360
- /**
361
- * Inherit the prototype methods from one constructor into another
362
- * @param {function} constructor
363
- * @param {function} superConstructor
364
- * @param {object} [props]
365
- * @param {object} [descriptors]
366
- *
367
- * @returns {void}
368
- */ const inherits = (constructor, superConstructor, props, descriptors)=>{
369
- constructor.prototype = Object.create(superConstructor.prototype, descriptors);
370
- constructor.prototype.constructor = constructor;
371
- Object.defineProperty(constructor, 'super', {
372
- value: superConstructor.prototype
373
- });
374
- props && Object.assign(constructor.prototype, props);
280
+ class BadRequestError extends error_APIError {
281
+ constructor(...args){
282
+ super(...args), this.name = 'BadRequestError', this.status = 400;
283
+ }
284
+ }
285
+ class AuthenticationError extends error_APIError {
286
+ constructor(...args){
287
+ super(...args), this.name = 'AuthenticationError', this.status = 401;
288
+ }
289
+ }
290
+ class PermissionDeniedError extends error_APIError {
291
+ constructor(...args){
292
+ super(...args), this.name = 'PermissionDeniedError', this.status = 403;
293
+ }
294
+ }
295
+ class NotFoundError extends error_APIError {
296
+ constructor(...args){
297
+ super(...args), this.name = 'NotFoundError', this.status = 404;
298
+ }
299
+ }
300
+ class TimeoutError extends error_APIError {
301
+ constructor(...args){
302
+ super(...args), this.name = 'TimeoutError', this.status = 408;
303
+ }
304
+ }
305
+ class RateLimitError extends error_APIError {
306
+ constructor(...args){
307
+ super(...args), this.name = 'RateLimitError', this.status = 429;
308
+ }
309
+ }
310
+ class InternalServerError extends error_APIError {
311
+ constructor(...args){
312
+ super(...args), this.name = 'InternalServerError', this.status = 500;
313
+ }
314
+ }
315
+ class GatewayError extends error_APIError {
316
+ constructor(...args){
317
+ super(...args), this.name = 'GatewayError', this.status = 502;
318
+ }
319
+ }
320
+ const castToError = (err)=>{
321
+ if (err instanceof Error) return err;
322
+ return new Error(err);
375
323
  };
376
- /**
377
- * Resolve object with deep prototype chain to a flat object
378
- * @param {Object} sourceObj source object
379
- * @param {Object} [destObj]
380
- * @param {Function|Boolean} [filter]
381
- * @param {Function} [propFilter]
382
- *
383
- * @returns {Object}
384
- */ const toFlatObject = (sourceObj, destObj, filter, propFilter)=>{
385
- let props;
386
- let i;
387
- let prop;
388
- const merged = {};
389
- destObj = destObj || {};
390
- // eslint-disable-next-line no-eq-null,eqeqeq
391
- if (null == sourceObj) return destObj;
392
- do {
393
- props = Object.getOwnPropertyNames(sourceObj);
394
- i = props.length;
395
- while(i-- > 0){
396
- prop = props[i];
397
- if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
398
- destObj[prop] = sourceObj[prop];
399
- merged[prop] = true;
400
- }
401
- }
402
- sourceObj = false !== filter && getPrototypeOf(sourceObj);
403
- }while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
404
- return destObj;
324
+ class Messages extends APIResource {
325
+ /**
326
+ * Get the list of messages in a chat. | 获取对话中的消息列表。
327
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_message_list?_lang=en
328
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_message_list?_lang=zh
329
+ * @param conversation_id - Required The ID of the conversation. | 会话 ID。
330
+ * @param chat_id - Required The ID of the chat. | 对话 ID。
331
+ * @returns An array of chat messages. | 对话消息数组。
332
+ */ async list(conversation_id, chat_id, options) {
333
+ const apiUrl = `/v3/chat/message/list?conversation_id=${conversation_id}&chat_id=${chat_id}`;
334
+ const result = await this._client.get(apiUrl, void 0, false, options);
335
+ return result.data;
336
+ }
337
+ }
338
+ const uuid = ()=>(Math.random() * new Date().getTime()).toString();
339
+ const handleAdditionalMessages = (additional_messages)=>null == additional_messages ? void 0 : additional_messages.map((i)=>({
340
+ ...i,
341
+ content: 'object' == typeof i.content ? JSON.stringify(i.content) : i.content
342
+ }));
343
+ class Chat extends APIResource {
344
+ /**
345
+ * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
346
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
347
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
348
+ * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
349
+ * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
350
+ * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
351
+ * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
352
+ * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义变量。
353
+ * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
354
+ * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
355
+ * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
356
+ * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
357
+ * @returns The data of the created chat. | 创建的对话数据。
358
+ */ async create(params, options) {
359
+ if (!params.user_id) params.user_id = uuid();
360
+ const { conversation_id, ...rest } = params;
361
+ const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
362
+ const payload = {
363
+ ...rest,
364
+ additional_messages: handleAdditionalMessages(params.additional_messages),
365
+ stream: false
366
+ };
367
+ const result = await this._client.post(apiUrl, payload, false, options);
368
+ return result.data;
369
+ }
370
+ /**
371
+ * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
372
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
373
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
374
+ * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
375
+ * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
376
+ * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
377
+ * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
378
+ * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
379
+ * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
380
+ * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
381
+ * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
382
+ * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
383
+ * @returns
384
+ */ async createAndPoll(params, options) {
385
+ if (!params.user_id) params.user_id = uuid();
386
+ const { conversation_id, ...rest } = params;
387
+ const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
388
+ const payload = {
389
+ ...rest,
390
+ additional_messages: handleAdditionalMessages(params.additional_messages),
391
+ stream: false
392
+ };
393
+ const result = await this._client.post(apiUrl, payload, false, options);
394
+ const chatId = result.data.id;
395
+ const conversationId = result.data.conversation_id;
396
+ let chat;
397
+ while(true){
398
+ await utils_sleep(100);
399
+ chat = await this.retrieve(conversationId, chatId);
400
+ if ('completed' === chat.status || 'failed' === chat.status || 'requires_action' === chat.status) break;
401
+ }
402
+ const messageList = await this.messages.list(conversationId, chatId);
403
+ return {
404
+ chat,
405
+ messages: messageList
406
+ };
407
+ }
408
+ /**
409
+ * Call the Chat API to send messages to a published Coze agent with streaming response. | 调用此接口发起一次对话,支持流式响应。
410
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
411
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
412
+ * @param params - Required The parameters for streaming a chat session. | 流式会话的参数。
413
+ * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
414
+ * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
415
+ * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
416
+ * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
417
+ * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
418
+ * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
419
+ * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
420
+ * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
421
+ * @returns A stream of chat data. | 对话数据流。
422
+ */ async *stream(params, options) {
423
+ if (!params.user_id) params.user_id = uuid();
424
+ const { conversation_id, ...rest } = params;
425
+ const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
426
+ const payload = {
427
+ ...rest,
428
+ additional_messages: handleAdditionalMessages(params.additional_messages),
429
+ stream: true
430
+ };
431
+ const result = await this._client.post(apiUrl, payload, true, options);
432
+ for await (const message of result)if ("done" === message.event) {
433
+ const ret = {
434
+ event: message.event,
435
+ data: '[DONE]'
436
+ };
437
+ yield ret;
438
+ } else try {
439
+ const ret = {
440
+ event: message.event,
441
+ data: JSON.parse(message.data)
442
+ };
443
+ yield ret;
444
+ } catch (error) {
445
+ throw new CozeError(`Could not parse message into JSON:${message.data}`);
446
+ }
447
+ }
448
+ /**
449
+ * Get the detailed information of the chat. | 查看对话的详细信息。
450
+ * @docs en:https://www.coze.com/docs/developer_guides/retrieve_chat?_lang=en
451
+ * @docs zh:https://www.coze.cn/docs/developer_guides/retrieve_chat?_lang=zh
452
+ * @param conversation_id - Required The ID of the conversation. | 会话 ID。
453
+ * @param chat_id - Required The ID of the chat. | 对话 ID。
454
+ * @returns The data of the retrieved chat. | 检索到的对话数据。
455
+ */ async retrieve(conversation_id, chat_id, options) {
456
+ const apiUrl = `/v3/chat/retrieve?conversation_id=${conversation_id}&chat_id=${chat_id}`;
457
+ const result = await this._client.post(apiUrl, void 0, false, options);
458
+ return result.data;
459
+ }
460
+ /**
461
+ * Cancel a chat session. | 取消对话会话。
462
+ * @docs en:https://www.coze.com/docs/developer_guides/cancel_chat?_lang=en
463
+ * @docs zh:https://www.coze.cn/docs/developer_guides/cancel_chat?_lang=zh
464
+ * @param conversation_id - Required The ID of the conversation. | 会话 ID。
465
+ * @param chat_id - Required The ID of the chat. | 对话 ID。
466
+ * @returns The data of the canceled chat. | 取消的对话数据。
467
+ */ async cancel(conversation_id, chat_id, options) {
468
+ const apiUrl = '/v3/chat/cancel';
469
+ const payload = {
470
+ conversation_id,
471
+ chat_id
472
+ };
473
+ const result = await this._client.post(apiUrl, payload, false, options);
474
+ return result.data;
475
+ }
476
+ /**
477
+ * Submit tool outputs for a chat session. | 提交对话会话的工具输出。
478
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_submit_tool_outputs?_lang=en
479
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_submit_tool_outputs?_lang=zh
480
+ * @param params - Required Parameters for submitting tool outputs. | 提交工具输出的参数。
481
+ * @param params.conversation_id - Required The ID of the conversation. | 会话 ID。
482
+ * @param params.chat_id - Required The ID of the chat. | 对话 ID。
483
+ * @param params.tool_outputs - Required The outputs of the tool. | 工具的输出。
484
+ * @param params.stream - Optional Whether to use streaming response. | 是否使用流式响应。
485
+ * @returns The data of the submitted tool outputs or a stream of chat data. | 提交的工具输出数据或对话数据流。
486
+ */ async *submitToolOutputs(params, options) {
487
+ const { conversation_id, chat_id, ...rest } = params;
488
+ const apiUrl = `/v3/chat/submit_tool_outputs?conversation_id=${params.conversation_id}&chat_id=${params.chat_id}`;
489
+ const payload = {
490
+ ...rest
491
+ };
492
+ if (false === params.stream) {
493
+ const response = await this._client.post(apiUrl, payload, false, options);
494
+ return response.data;
495
+ }
496
+ {
497
+ const result = await this._client.post(apiUrl, payload, true, options);
498
+ for await (const message of result)if ("done" === message.event) {
499
+ const ret = {
500
+ event: message.event,
501
+ data: '[DONE]'
502
+ };
503
+ yield ret;
504
+ } else try {
505
+ const ret = {
506
+ event: message.event,
507
+ data: JSON.parse(message.data)
508
+ };
509
+ yield ret;
510
+ } catch (error) {
511
+ throw new CozeError(`Could not parse message into JSON:${message.data}`);
512
+ }
513
+ }
514
+ }
515
+ constructor(...args){
516
+ super(...args), this.messages = new Messages(this._client);
517
+ }
518
+ }
519
+ var chat_ChatEventType = /*#__PURE__*/ function(ChatEventType) {
520
+ ChatEventType["CONVERSATION_CHAT_CREATED"] = "conversation.chat.created";
521
+ ChatEventType["CONVERSATION_CHAT_IN_PROGRESS"] = "conversation.chat.in_progress";
522
+ ChatEventType["CONVERSATION_CHAT_COMPLETED"] = "conversation.chat.completed";
523
+ ChatEventType["CONVERSATION_CHAT_FAILED"] = "conversation.chat.failed";
524
+ ChatEventType["CONVERSATION_CHAT_REQUIRES_ACTION"] = "conversation.chat.requires_action";
525
+ ChatEventType["CONVERSATION_MESSAGE_DELTA"] = "conversation.message.delta";
526
+ ChatEventType["CONVERSATION_MESSAGE_COMPLETED"] = "conversation.message.completed";
527
+ ChatEventType["CONVERSATION_AUDIO_DELTA"] = "conversation.audio.delta";
528
+ ChatEventType["DONE"] = "done";
529
+ ChatEventType["ERROR"] = "error";
530
+ return ChatEventType;
531
+ }({});
532
+ class messages_Messages extends APIResource {
533
+ /**
534
+ * Create a message and add it to the specified conversation. | 创建一条消息,并将其添加到指定的会话中。
535
+ * @docs en: https://www.coze.com/docs/developer_guides/create_message?_lang=en
536
+ * @docs zh: https://www.coze.cn/docs/developer_guides/create_message?_lang=zh
537
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
538
+ * @param params - Required The parameters for creating a message | 创建消息所需的参数
539
+ * @param params.role - Required The entity that sent this message. Possible values: user, assistant. | 发送这条消息的实体。取值:user, assistant。
540
+ * @param params.content - Required The content of the message. | 消息的内容。
541
+ * @param params.content_type - Required The type of the message content. | 消息内容的类型。
542
+ * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
543
+ * @returns Information about the new message. | 消息详情。
544
+ */ async create(conversation_id, params, options) {
545
+ const apiUrl = `/v1/conversation/message/create?conversation_id=${conversation_id}`;
546
+ const response = await this._client.post(apiUrl, params, false, options);
547
+ return response.data;
548
+ }
549
+ /**
550
+ * Modify a message, supporting the modification of message content, additional content, and message type. | 修改一条消息,支持修改消息内容、附加内容和消息类型。
551
+ * @docs en: https://www.coze.com/docs/developer_guides/modify_message?_lang=en
552
+ * @docs zh: https://www.coze.cn/docs/developer_guides/modify_message?_lang=zh
553
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
554
+ * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
555
+ * @param params - Required The parameters for modifying a message | 修改消息所需的参数
556
+ * @param params.meta_data - Optional Additional information when modifying a message. | 修改消息时的附加消息。
557
+ * @param params.content - Optional The content of the message. | 消息的内容。
558
+ * @param params.content_type - Optional The type of the message content. | 消息内容的类型。
559
+ * @returns Information about the modified message. | 消息详情。
560
+ */ // eslint-disable-next-line max-params
561
+ async update(conversation_id, message_id, params, options) {
562
+ const apiUrl = `/v1/conversation/message/modify?conversation_id=${conversation_id}&message_id=${message_id}`;
563
+ const response = await this._client.post(apiUrl, params, false, options);
564
+ return response.message;
565
+ }
566
+ /**
567
+ * Get the detailed information of specified message. | 查看指定消息的详细信息。
568
+ * @docs en: https://www.coze.com/docs/developer_guides/retrieve_message?_lang=en
569
+ * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_message?_lang=zh
570
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
571
+ * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
572
+ * @returns Information about the message. | 消息详情。
573
+ */ async retrieve(conversation_id, message_id, options) {
574
+ const apiUrl = `/v1/conversation/message/retrieve?conversation_id=${conversation_id}&message_id=${message_id}`;
575
+ const response = await this._client.get(apiUrl, null, false, options);
576
+ return response.data;
577
+ }
578
+ /**
579
+ * List messages in a conversation. | 列出会话中的消息。
580
+ * @docs en: https://www.coze.com/docs/developer_guides/message_list?_lang=en
581
+ * @docs zh: https://www.coze.cn/docs/developer_guides/message_list?_lang=zh
582
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
583
+ * @param params - Optional The parameters for listing messages | 列出消息所需的参数
584
+ * @param params.order - Optional The order of the messages. | 消息的顺序。
585
+ * @param params.chat_id - Optional The ID of the chat. | 聊天 ID。
586
+ * @param params.before_id - Optional The ID of the message before which to list. | 列出此消息之前的消息 ID。
587
+ * @param params.after_id - Optional The ID of the message after which to list. | 列出此消息之后的消息 ID。
588
+ * @param params.limit - Optional The maximum number of messages to return. | 返回的最大消息数。
589
+ * @returns A list of messages. | 消息列表。
590
+ */ async list(conversation_id, params, options) {
591
+ const apiUrl = `/v1/conversation/message/list?conversation_id=${conversation_id}`;
592
+ const response = await this._client.post(apiUrl, params, false, options);
593
+ return response;
594
+ }
595
+ /**
596
+ * Call the API to delete a message within a specified conversation. | 调用接口在指定会话中删除消息。
597
+ * @docs en: https://www.coze.com/docs/developer_guides/delete_message?_lang=en
598
+ * @docs zh: https://www.coze.cn/docs/developer_guides/delete_message?_lang=zh
599
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
600
+ * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
601
+ * @returns Details of the deleted message. | 已删除的消息详情。
602
+ */ async delete(conversation_id, message_id, options) {
603
+ const apiUrl = `/v1/conversation/message/delete?conversation_id=${conversation_id}&message_id=${message_id}`;
604
+ const response = await this._client.post(apiUrl, void 0, false, options);
605
+ return response.data;
606
+ }
607
+ }
608
+ class Conversations extends APIResource {
609
+ /**
610
+ * Create a conversation. Conversation is an interaction between an agent and a user, including one or more messages. | 调用接口创建一个会话。
611
+ * @docs en: https://www.coze.com/docs/developer_guides/create_conversation?_lang=en
612
+ * @docs zh: https://www.coze.cn/docs/developer_guides/create_conversation?_lang=zh
613
+ * @param params - Required The parameters for creating a conversation | 创建会话所需的参数
614
+ * @param params.messages - Optional Messages in the conversation. | 会话中的消息内容。
615
+ * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
616
+ * @param params.bot_id - Optional Bind and isolate conversation on different bots. | 绑定和隔离不同Bot的会话。
617
+ * @returns Information about the created conversation. | 会话的基础信息。
618
+ */ async create(params, options) {
619
+ const apiUrl = '/v1/conversation/create';
620
+ const response = await this._client.post(apiUrl, params, false, options);
621
+ return response.data;
622
+ }
623
+ /**
624
+ * Get the information of specific conversation. | 通过会话 ID 查看会话信息。
625
+ * @docs en: https://www.coze.com/docs/developer_guides/retrieve_conversation?_lang=en
626
+ * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_conversation?_lang=zh
627
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
628
+ * @returns Information about the conversation. | 会话的基础信息。
629
+ */ async retrieve(conversation_id, options) {
630
+ const apiUrl = `/v1/conversation/retrieve?conversation_id=${conversation_id}`;
631
+ const response = await this._client.get(apiUrl, null, false, options);
632
+ return response.data;
633
+ }
634
+ /**
635
+ * List all conversations. | 列出 Bot 下所有会话。
636
+ * @param params
637
+ * @param params.bot_id - Required Bot ID. | Bot ID。
638
+ * @param params.page_num - Optional The page number. | 页码,默认值为 1。
639
+ * @param params.page_size - Optional The number of conversations per page. | 每页的会话数量,默认值为 50。
640
+ * @returns Information about the conversations. | 会话的信息。
641
+ */ async list(params, options) {
642
+ const apiUrl = '/v1/conversations';
643
+ const response = await this._client.get(apiUrl, params, false, options);
644
+ return response.data;
645
+ }
646
+ /**
647
+ * Clear a conversation. | 清空会话。
648
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
649
+ * @returns Information about the conversation session. | 会话的会话 ID。
650
+ */ async clear(conversation_id, options) {
651
+ const apiUrl = `/v1/conversations/${conversation_id}/clear`;
652
+ const response = await this._client.post(apiUrl, null, false, options);
653
+ return response.data;
654
+ }
655
+ constructor(...args){
656
+ super(...args), this.messages = new messages_Messages(this._client);
657
+ }
658
+ }
659
+ function bind(fn, thisArg) {
660
+ return function() {
661
+ return fn.apply(thisArg, arguments);
662
+ };
663
+ }
664
+ // utils is a library of generic helper functions non-specific to axios
665
+ const { toString: utils_toString } = Object.prototype;
666
+ const { getPrototypeOf } = Object;
667
+ const kindOf = ((cache)=>(thing)=>{
668
+ const str = utils_toString.call(thing);
669
+ return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
670
+ })(Object.create(null));
671
+ const kindOfTest = (type)=>{
672
+ type = type.toLowerCase();
673
+ return (thing)=>kindOf(thing) === type;
405
674
  };
675
+ const typeOfTest = (type)=>(thing)=>typeof thing === type;
406
676
  /**
407
- * Determines whether a string ends with the characters of a specified string
677
+ * Determine if a value is an Array
408
678
  *
409
- * @param {String} str
410
- * @param {String} searchString
411
- * @param {Number} [position= 0]
679
+ * @param {Object} val The value to test
412
680
  *
413
- * @returns {boolean}
414
- */ const endsWith = (str, searchString, position)=>{
415
- str = String(str);
416
- if (void 0 === position || position > str.length) position = str.length;
417
- position -= searchString.length;
418
- const lastIndex = str.indexOf(searchString, position);
419
- return -1 !== lastIndex && lastIndex === position;
420
- };
681
+ * @returns {boolean} True if value is an Array, otherwise false
682
+ */ const { isArray } = Array;
421
683
  /**
422
- * Returns new array from array like object or null if failed
684
+ * Determine if a value is undefined
423
685
  *
424
- * @param {*} [thing]
686
+ * @param {*} val The value to test
425
687
  *
426
- * @returns {?Array}
427
- */ const toArray = (thing)=>{
428
- if (!thing) return null;
429
- if (isArray(thing)) return thing;
430
- let i = thing.length;
431
- if (!isNumber(i)) return null;
432
- const arr = new Array(i);
433
- while(i-- > 0)arr[i] = thing[i];
434
- return arr;
435
- };
688
+ * @returns {boolean} True if the value is undefined, otherwise false
689
+ */ const isUndefined = typeOfTest('undefined');
436
690
  /**
437
- * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
438
- * thing passed in is an instance of Uint8Array
691
+ * Determine if a value is a Buffer
439
692
  *
440
- * @param {TypedArray}
693
+ * @param {*} val The value to test
441
694
  *
442
- * @returns {Array}
443
- */ // eslint-disable-next-line func-names
444
- const isTypedArray = ((TypedArray)=>(thing)=>TypedArray && thing instanceof TypedArray)('undefined' != typeof Uint8Array && getPrototypeOf(Uint8Array));
695
+ * @returns {boolean} True if value is a Buffer, otherwise false
696
+ */ function isBuffer(val) {
697
+ return null !== val && !isUndefined(val) && null !== val.constructor && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
698
+ }
445
699
  /**
446
- * For each entry in the object, call the function with the key and value.
700
+ * Determine if a value is an ArrayBuffer
447
701
  *
448
- * @param {Object<any, any>} obj - The object to iterate over.
449
- * @param {Function} fn - The function to call for each entry.
702
+ * @param {*} val The value to test
450
703
  *
451
- * @returns {void}
452
- */ const forEachEntry = (obj, fn)=>{
453
- const generator = obj && obj[Symbol.iterator];
454
- const iterator = generator.call(obj);
704
+ * @returns {boolean} True if value is an ArrayBuffer, otherwise false
705
+ */ const isArrayBuffer = kindOfTest('ArrayBuffer');
706
+ /**
707
+ * Determine if a value is a view on an ArrayBuffer
708
+ *
709
+ * @param {*} val The value to test
710
+ *
711
+ * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
712
+ */ function isArrayBufferView(val) {
455
713
  let result;
456
- while((result = iterator.next()) && !result.done){
457
- const pair = result.value;
458
- fn.call(obj, pair[0], pair[1]);
459
- }
460
- };
714
+ result = 'undefined' != typeof ArrayBuffer && ArrayBuffer.isView ? ArrayBuffer.isView(val) : val && val.buffer && isArrayBuffer(val.buffer);
715
+ return result;
716
+ }
461
717
  /**
462
- * It takes a regular expression and a string, and returns an array of all the matches
718
+ * Determine if a value is a String
463
719
  *
464
- * @param {string} regExp - The regular expression to match against.
465
- * @param {string} str - The string to search.
720
+ * @param {*} val The value to test
466
721
  *
467
- * @returns {Array<boolean>}
468
- */ const matchAll = (regExp, str)=>{
469
- let matches;
470
- const arr = [];
471
- while(null !== (matches = regExp.exec(str)))arr.push(matches);
472
- return arr;
473
- };
474
- /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ const isHTMLForm = kindOfTest('HTMLFormElement');
475
- const toCamelCase = (str)=>str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function(m, p1, p2) {
476
- return p1.toUpperCase() + p2;
477
- });
478
- /* Creating a function that will check if an object has a property. */ const utils_hasOwnProperty = (({ hasOwnProperty })=>(obj, prop)=>hasOwnProperty.call(obj, prop))(Object.prototype);
722
+ * @returns {boolean} True if value is a String, otherwise false
723
+ */ const isString = typeOfTest('string');
479
724
  /**
480
- * Determine if a value is a RegExp object
725
+ * Determine if a value is a Function
726
+ *
727
+ * @param {*} val The value to test
728
+ * @returns {boolean} True if value is a Function, otherwise false
729
+ */ const isFunction = typeOfTest('function');
730
+ /**
731
+ * Determine if a value is a Number
481
732
  *
482
733
  * @param {*} val The value to test
483
734
  *
484
- * @returns {boolean} True if value is a RegExp object, otherwise false
485
- */ const isRegExp = kindOfTest('RegExp');
486
- const reduceDescriptors = (obj, reducer)=>{
487
- const descriptors = Object.getOwnPropertyDescriptors(obj);
488
- const reducedDescriptors = {};
489
- forEach(descriptors, (descriptor, name)=>{
490
- let ret;
491
- if (false !== (ret = reducer(descriptor, name, obj))) reducedDescriptors[name] = ret || descriptor;
492
- });
493
- Object.defineProperties(obj, reducedDescriptors);
494
- };
735
+ * @returns {boolean} True if value is a Number, otherwise false
736
+ */ const isNumber = typeOfTest('number');
495
737
  /**
496
- * Makes all methods read-only
497
- * @param {Object} obj
498
- */ const freezeMethods = (obj)=>{
499
- reduceDescriptors(obj, (descriptor, name)=>{
500
- // skip restricted props in strict mode
501
- if (isFunction(obj) && -1 !== [
502
- 'arguments',
503
- 'caller',
504
- 'callee'
505
- ].indexOf(name)) return false;
506
- const value = obj[name];
507
- if (!isFunction(value)) return;
508
- descriptor.enumerable = false;
509
- if ('writable' in descriptor) {
510
- descriptor.writable = false;
511
- return;
512
- }
513
- if (!descriptor.set) descriptor.set = ()=>{
514
- throw Error('Can not rewrite read-only method \'' + name + '\'');
515
- };
516
- });
517
- };
518
- const toObjectSet = (arrayOrString, delimiter)=>{
519
- const obj = {};
520
- const define = (arr)=>{
521
- arr.forEach((value)=>{
522
- obj[value] = true;
523
- });
524
- };
525
- isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
526
- return obj;
527
- };
528
- const noop = ()=>{};
529
- const toFiniteNumber = (value, defaultValue)=>null != value && Number.isFinite(value = +value) ? value : defaultValue;
530
- const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
531
- const DIGIT = '0123456789';
532
- const ALPHABET = {
533
- DIGIT,
534
- ALPHA,
535
- ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
536
- };
537
- const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT)=>{
538
- let str = '';
539
- const { length } = alphabet;
540
- while(size--)str += alphabet[Math.random() * length | 0];
541
- return str;
738
+ * Determine if a value is an Object
739
+ *
740
+ * @param {*} thing The value to test
741
+ *
742
+ * @returns {boolean} True if value is an Object, otherwise false
743
+ */ const isObject = (thing)=>null !== thing && 'object' == typeof thing;
744
+ /**
745
+ * Determine if a value is a Boolean
746
+ *
747
+ * @param {*} thing The value to test
748
+ * @returns {boolean} True if value is a Boolean, otherwise false
749
+ */ const isBoolean = (thing)=>true === thing || false === thing;
750
+ /**
751
+ * Determine if a value is a plain Object
752
+ *
753
+ * @param {*} val The value to test
754
+ *
755
+ * @returns {boolean} True if value is a plain Object, otherwise false
756
+ */ const utils_isPlainObject = (val)=>{
757
+ if ('object' !== kindOf(val)) return false;
758
+ const prototype = getPrototypeOf(val);
759
+ return (null === prototype || prototype === Object.prototype || null === Object.getPrototypeOf(prototype)) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
542
760
  };
543
761
  /**
544
- * If the thing is a FormData object, return true, otherwise return false.
762
+ * Determine if a value is a Date
545
763
  *
546
- * @param {unknown} thing - The thing to check.
764
+ * @param {*} val The value to test
547
765
  *
548
- * @returns {boolean}
549
- */ function isSpecCompliantForm(thing) {
550
- return !!(thing && isFunction(thing.append) && 'FormData' === thing[Symbol.toStringTag] && thing[Symbol.iterator]);
551
- }
552
- const toJSONObject = (obj)=>{
553
- const stack = new Array(10);
554
- const visit = (source, i)=>{
555
- if (isObject(source)) {
556
- if (stack.indexOf(source) >= 0) return;
557
- if (!('toJSON' in source)) {
766
+ * @returns {boolean} True if value is a Date, otherwise false
767
+ */ const isDate = kindOfTest('Date');
768
+ /**
769
+ * Determine if a value is a File
770
+ *
771
+ * @param {*} val The value to test
772
+ *
773
+ * @returns {boolean} True if value is a File, otherwise false
774
+ */ const isFile = kindOfTest('File');
775
+ /**
776
+ * Determine if a value is a Blob
777
+ *
778
+ * @param {*} val The value to test
779
+ *
780
+ * @returns {boolean} True if value is a Blob, otherwise false
781
+ */ const isBlob = kindOfTest('Blob');
782
+ /**
783
+ * Determine if a value is a FileList
784
+ *
785
+ * @param {*} val The value to test
786
+ *
787
+ * @returns {boolean} True if value is a File, otherwise false
788
+ */ const utils_isFileList = kindOfTest('FileList');
789
+ /**
790
+ * Determine if a value is a Stream
791
+ *
792
+ * @param {*} val The value to test
793
+ *
794
+ * @returns {boolean} True if value is a Stream, otherwise false
795
+ */ const utils_isStream = (val)=>isObject(val) && isFunction(val.pipe);
796
+ /**
797
+ * Determine if a value is a FormData
798
+ *
799
+ * @param {*} thing The value to test
800
+ *
801
+ * @returns {boolean} True if value is an FormData, otherwise false
802
+ */ const utils_isFormData = (thing)=>{
803
+ let kind;
804
+ return thing && ('function' == typeof FormData && thing instanceof FormData || isFunction(thing.append) && ('formdata' === (kind = kindOf(thing)) || // detect form-data instance
805
+ 'object' === kind && isFunction(thing.toString) && '[object FormData]' === thing.toString()));
806
+ };
807
+ /**
808
+ * Determine if a value is a URLSearchParams object
809
+ *
810
+ * @param {*} val The value to test
811
+ *
812
+ * @returns {boolean} True if value is a URLSearchParams object, otherwise false
813
+ */ const isURLSearchParams = kindOfTest('URLSearchParams');
814
+ const [isReadableStream, isRequest, isResponse, isHeaders] = [
815
+ 'ReadableStream',
816
+ 'Request',
817
+ 'Response',
818
+ 'Headers'
819
+ ].map(kindOfTest);
820
+ /**
821
+ * Trim excess whitespace off the beginning and end of a string
822
+ *
823
+ * @param {String} str The String to trim
824
+ *
825
+ * @returns {String} The String freed of excess whitespace
826
+ */ const trim = (str)=>str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
827
+ /**
828
+ * Iterate over an Array or an Object invoking a function for each item.
829
+ *
830
+ * If `obj` is an Array callback will be called passing
831
+ * the value, index, and complete array for each item.
832
+ *
833
+ * If 'obj' is an Object callback will be called passing
834
+ * the value, key, and complete object for each property.
835
+ *
836
+ * @param {Object|Array} obj The object to iterate
837
+ * @param {Function} fn The callback to invoke for each item
838
+ *
839
+ * @param {Boolean} [allOwnKeys = false]
840
+ * @returns {any}
841
+ */ function forEach(obj, fn, { allOwnKeys = false } = {}) {
842
+ // Don't bother if no value provided
843
+ if (null == obj) return;
844
+ let i;
845
+ let l;
846
+ // Force an array if not already something iterable
847
+ if ('object' != typeof obj) /*eslint no-param-reassign:0*/ obj = [
848
+ obj
849
+ ];
850
+ if (isArray(obj)) // Iterate over array values
851
+ for(i = 0, l = obj.length; i < l; i++)fn.call(null, obj[i], i, obj);
852
+ else {
853
+ // Iterate over object keys
854
+ const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
855
+ const len = keys.length;
856
+ let key;
857
+ for(i = 0; i < len; i++){
858
+ key = keys[i];
859
+ fn.call(null, obj[key], key, obj);
860
+ }
861
+ }
862
+ }
863
+ function findKey(obj, key) {
864
+ key = key.toLowerCase();
865
+ const keys = Object.keys(obj);
866
+ let i = keys.length;
867
+ let _key;
868
+ while(i-- > 0){
869
+ _key = keys[i];
870
+ if (key === _key.toLowerCase()) return _key;
871
+ }
872
+ return null;
873
+ }
874
+ const _global = (()=>{
875
+ /*eslint no-undef:0*/ if ("undefined" != typeof globalThis) return globalThis;
876
+ return "undefined" != typeof self ? self : 'undefined' != typeof window ? window : global;
877
+ })();
878
+ const isContextDefined = (context)=>!isUndefined(context) && context !== _global;
879
+ /**
880
+ * Accepts varargs expecting each argument to be an object, then
881
+ * immutably merges the properties of each object and returns result.
882
+ *
883
+ * When multiple objects contain the same key the later object in
884
+ * the arguments list will take precedence.
885
+ *
886
+ * Example:
887
+ *
888
+ * ```js
889
+ * var result = merge({foo: 123}, {foo: 456});
890
+ * console.log(result.foo); // outputs 456
891
+ * ```
892
+ *
893
+ * @param {Object} obj1 Object to merge
894
+ *
895
+ * @returns {Object} Result of all merge properties
896
+ */ function utils_merge() {
897
+ const { caseless } = isContextDefined(this) && this || {};
898
+ const result = {};
899
+ const assignValue = (val, key)=>{
900
+ const targetKey = caseless && findKey(result, key) || key;
901
+ if (utils_isPlainObject(result[targetKey]) && utils_isPlainObject(val)) result[targetKey] = utils_merge(result[targetKey], val);
902
+ else if (utils_isPlainObject(val)) result[targetKey] = utils_merge({}, val);
903
+ else if (isArray(val)) result[targetKey] = val.slice();
904
+ else result[targetKey] = val;
905
+ };
906
+ for(let i = 0, l = arguments.length; i < l; i++)arguments[i] && forEach(arguments[i], assignValue);
907
+ return result;
908
+ }
909
+ /**
910
+ * Extends object a by mutably adding to it the properties of object b.
911
+ *
912
+ * @param {Object} a The object to be extended
913
+ * @param {Object} b The object to copy properties from
914
+ * @param {Object} thisArg The object to bind function to
915
+ *
916
+ * @param {Boolean} [allOwnKeys]
917
+ * @returns {Object} The resulting value of object a
918
+ */ const extend = (a, b, thisArg, { allOwnKeys } = {})=>{
919
+ forEach(b, (val, key)=>{
920
+ if (thisArg && isFunction(val)) a[key] = bind(val, thisArg);
921
+ else a[key] = val;
922
+ }, {
923
+ allOwnKeys
924
+ });
925
+ return a;
926
+ };
927
+ /**
928
+ * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
929
+ *
930
+ * @param {string} content with BOM
931
+ *
932
+ * @returns {string} content value without BOM
933
+ */ const stripBOM = (content)=>{
934
+ if (0xFEFF === content.charCodeAt(0)) content = content.slice(1);
935
+ return content;
936
+ };
937
+ /**
938
+ * Inherit the prototype methods from one constructor into another
939
+ * @param {function} constructor
940
+ * @param {function} superConstructor
941
+ * @param {object} [props]
942
+ * @param {object} [descriptors]
943
+ *
944
+ * @returns {void}
945
+ */ const inherits = (constructor, superConstructor, props, descriptors)=>{
946
+ constructor.prototype = Object.create(superConstructor.prototype, descriptors);
947
+ constructor.prototype.constructor = constructor;
948
+ Object.defineProperty(constructor, 'super', {
949
+ value: superConstructor.prototype
950
+ });
951
+ props && Object.assign(constructor.prototype, props);
952
+ };
953
+ /**
954
+ * Resolve object with deep prototype chain to a flat object
955
+ * @param {Object} sourceObj source object
956
+ * @param {Object} [destObj]
957
+ * @param {Function|Boolean} [filter]
958
+ * @param {Function} [propFilter]
959
+ *
960
+ * @returns {Object}
961
+ */ const toFlatObject = (sourceObj, destObj, filter, propFilter)=>{
962
+ let props;
963
+ let i;
964
+ let prop;
965
+ const merged = {};
966
+ destObj = destObj || {};
967
+ // eslint-disable-next-line no-eq-null,eqeqeq
968
+ if (null == sourceObj) return destObj;
969
+ do {
970
+ props = Object.getOwnPropertyNames(sourceObj);
971
+ i = props.length;
972
+ while(i-- > 0){
973
+ prop = props[i];
974
+ if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
975
+ destObj[prop] = sourceObj[prop];
976
+ merged[prop] = true;
977
+ }
978
+ }
979
+ sourceObj = false !== filter && getPrototypeOf(sourceObj);
980
+ }while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
981
+ return destObj;
982
+ };
983
+ /**
984
+ * Determines whether a string ends with the characters of a specified string
985
+ *
986
+ * @param {String} str
987
+ * @param {String} searchString
988
+ * @param {Number} [position= 0]
989
+ *
990
+ * @returns {boolean}
991
+ */ const endsWith = (str, searchString, position)=>{
992
+ str = String(str);
993
+ if (void 0 === position || position > str.length) position = str.length;
994
+ position -= searchString.length;
995
+ const lastIndex = str.indexOf(searchString, position);
996
+ return -1 !== lastIndex && lastIndex === position;
997
+ };
998
+ /**
999
+ * Returns new array from array like object or null if failed
1000
+ *
1001
+ * @param {*} [thing]
1002
+ *
1003
+ * @returns {?Array}
1004
+ */ const toArray = (thing)=>{
1005
+ if (!thing) return null;
1006
+ if (isArray(thing)) return thing;
1007
+ let i = thing.length;
1008
+ if (!isNumber(i)) return null;
1009
+ const arr = new Array(i);
1010
+ while(i-- > 0)arr[i] = thing[i];
1011
+ return arr;
1012
+ };
1013
+ /**
1014
+ * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
1015
+ * thing passed in is an instance of Uint8Array
1016
+ *
1017
+ * @param {TypedArray}
1018
+ *
1019
+ * @returns {Array}
1020
+ */ // eslint-disable-next-line func-names
1021
+ const isTypedArray = ((TypedArray)=>(thing)=>TypedArray && thing instanceof TypedArray)('undefined' != typeof Uint8Array && getPrototypeOf(Uint8Array));
1022
+ /**
1023
+ * For each entry in the object, call the function with the key and value.
1024
+ *
1025
+ * @param {Object<any, any>} obj - The object to iterate over.
1026
+ * @param {Function} fn - The function to call for each entry.
1027
+ *
1028
+ * @returns {void}
1029
+ */ const forEachEntry = (obj, fn)=>{
1030
+ const generator = obj && obj[Symbol.iterator];
1031
+ const iterator = generator.call(obj);
1032
+ let result;
1033
+ while((result = iterator.next()) && !result.done){
1034
+ const pair = result.value;
1035
+ fn.call(obj, pair[0], pair[1]);
1036
+ }
1037
+ };
1038
+ /**
1039
+ * It takes a regular expression and a string, and returns an array of all the matches
1040
+ *
1041
+ * @param {string} regExp - The regular expression to match against.
1042
+ * @param {string} str - The string to search.
1043
+ *
1044
+ * @returns {Array<boolean>}
1045
+ */ const matchAll = (regExp, str)=>{
1046
+ let matches;
1047
+ const arr = [];
1048
+ while(null !== (matches = regExp.exec(str)))arr.push(matches);
1049
+ return arr;
1050
+ };
1051
+ /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ const isHTMLForm = kindOfTest('HTMLFormElement');
1052
+ const toCamelCase = (str)=>str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function(m, p1, p2) {
1053
+ return p1.toUpperCase() + p2;
1054
+ });
1055
+ /* Creating a function that will check if an object has a property. */ const utils_hasOwnProperty = (({ hasOwnProperty })=>(obj, prop)=>hasOwnProperty.call(obj, prop))(Object.prototype);
1056
+ /**
1057
+ * Determine if a value is a RegExp object
1058
+ *
1059
+ * @param {*} val The value to test
1060
+ *
1061
+ * @returns {boolean} True if value is a RegExp object, otherwise false
1062
+ */ const isRegExp = kindOfTest('RegExp');
1063
+ const reduceDescriptors = (obj, reducer)=>{
1064
+ const descriptors = Object.getOwnPropertyDescriptors(obj);
1065
+ const reducedDescriptors = {};
1066
+ forEach(descriptors, (descriptor, name)=>{
1067
+ let ret;
1068
+ if (false !== (ret = reducer(descriptor, name, obj))) reducedDescriptors[name] = ret || descriptor;
1069
+ });
1070
+ Object.defineProperties(obj, reducedDescriptors);
1071
+ };
1072
+ /**
1073
+ * Makes all methods read-only
1074
+ * @param {Object} obj
1075
+ */ const freezeMethods = (obj)=>{
1076
+ reduceDescriptors(obj, (descriptor, name)=>{
1077
+ // skip restricted props in strict mode
1078
+ if (isFunction(obj) && -1 !== [
1079
+ 'arguments',
1080
+ 'caller',
1081
+ 'callee'
1082
+ ].indexOf(name)) return false;
1083
+ const value = obj[name];
1084
+ if (!isFunction(value)) return;
1085
+ descriptor.enumerable = false;
1086
+ if ('writable' in descriptor) {
1087
+ descriptor.writable = false;
1088
+ return;
1089
+ }
1090
+ if (!descriptor.set) descriptor.set = ()=>{
1091
+ throw Error('Can not rewrite read-only method \'' + name + '\'');
1092
+ };
1093
+ });
1094
+ };
1095
+ const toObjectSet = (arrayOrString, delimiter)=>{
1096
+ const obj = {};
1097
+ const define = (arr)=>{
1098
+ arr.forEach((value)=>{
1099
+ obj[value] = true;
1100
+ });
1101
+ };
1102
+ isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
1103
+ return obj;
1104
+ };
1105
+ const noop = ()=>{};
1106
+ const toFiniteNumber = (value, defaultValue)=>null != value && Number.isFinite(value = +value) ? value : defaultValue;
1107
+ const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
1108
+ const DIGIT = '0123456789';
1109
+ const ALPHABET = {
1110
+ DIGIT,
1111
+ ALPHA,
1112
+ ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
1113
+ };
1114
+ const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT)=>{
1115
+ let str = '';
1116
+ const { length } = alphabet;
1117
+ while(size--)str += alphabet[Math.random() * length | 0];
1118
+ return str;
1119
+ };
1120
+ /**
1121
+ * If the thing is a FormData object, return true, otherwise return false.
1122
+ *
1123
+ * @param {unknown} thing - The thing to check.
1124
+ *
1125
+ * @returns {boolean}
1126
+ */ function isSpecCompliantForm(thing) {
1127
+ return !!(thing && isFunction(thing.append) && 'FormData' === thing[Symbol.toStringTag] && thing[Symbol.iterator]);
1128
+ }
1129
+ const toJSONObject = (obj)=>{
1130
+ const stack = new Array(10);
1131
+ const visit = (source, i)=>{
1132
+ if (isObject(source)) {
1133
+ if (stack.indexOf(source) >= 0) return;
1134
+ if (!('toJSON' in source)) {
558
1135
  stack[i] = source;
559
1136
  const target = isArray(source) ? [] : {};
560
1137
  forEach(source, (value, key)=>{
@@ -597,7 +1174,7 @@ const asap = 'undefined' != typeof queueMicrotask ? queueMicrotask.bind(_global)
597
1174
  isNumber,
598
1175
  isBoolean,
599
1176
  isObject,
600
- isPlainObject,
1177
+ isPlainObject: utils_isPlainObject,
601
1178
  isReadableStream,
602
1179
  isRequest,
603
1180
  isResponse,
@@ -1795,7 +2372,7 @@ const headersToObject = (thing)=>thing instanceof AxiosHeaders ? {
1795
2372
  * @param {Object} config2
1796
2373
  *
1797
2374
  * @returns {Object} New object resulting from merging config2 to config1
1798
- */ function mergeConfig(config1, config2) {
2375
+ */ function mergeConfig_mergeConfig(config1, config2) {
1799
2376
  // eslint-disable-next-line no-param-reassign
1800
2377
  config2 = config2 || {};
1801
2378
  const config = {};
@@ -1865,7 +2442,7 @@ const headersToObject = (thing)=>thing instanceof AxiosHeaders ? {
1865
2442
  return config;
1866
2443
  }
1867
2444
  /* ESM default export */ const resolveConfig = (config)=>{
1868
- const newConfig = mergeConfig({}, config);
2445
+ const newConfig = mergeConfig_mergeConfig({}, config);
1869
2446
  let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig;
1870
2447
  newConfig.headers = headers = AxiosHeaders.from(headers);
1871
2448
  newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer);
@@ -2123,7 +2700,7 @@ const trackStream = (stream, chunkSize, onProgress, onFinish)=>{
2123
2700
  }, {
2124
2701
  highWaterMark: 2
2125
2702
  });
2126
- }; // CONCATENATED MODULE: ../../common/temp/default/node_modules/.pnpm/axios@1.7.7/node_modules/axios/lib/adapters/fetch.js
2703
+ }; // CONCATENATED MODULE: ../../common/temp/default/node_modules/.pnpm/axios@1.7.7_debug@4.3.7/node_modules/axios/lib/adapters/fetch.js
2127
2704
  const isFetchSupported = 'function' == typeof fetch && 'function' == typeof Request && 'function' == typeof Response;
2128
2705
  const isReadableStreamSupported = isFetchSupported && 'function' == typeof ReadableStream;
2129
2706
  // used only inside the fetch adapter
@@ -2471,7 +3048,7 @@ const Axios_validators = helpers_validator.validators;
2471
3048
  config = config || {};
2472
3049
  config.url = configOrUrl;
2473
3050
  } else config = configOrUrl || {};
2474
- config = mergeConfig(this.defaults, config);
3051
+ config = mergeConfig_mergeConfig(this.defaults, config);
2475
3052
  const { transitional, paramsSerializer, headers } = config;
2476
3053
  if (void 0 !== transitional) helpers_validator.assertOptions(transitional, {
2477
3054
  silentJSONParsing: Axios_validators.transitional(Axios_validators.boolean),
@@ -2524,851 +3101,326 @@ const Axios_validators = helpers_validator.validators;
2524
3101
  void 0
2525
3102
  ];
2526
3103
  chain.unshift.apply(chain, requestInterceptorChain);
2527
- chain.push.apply(chain, responseInterceptorChain);
2528
- len = chain.length;
2529
- promise = Promise.resolve(config);
2530
- while(i < len)promise = promise.then(chain[i++], chain[i++]);
2531
- return promise;
2532
- }
2533
- len = requestInterceptorChain.length;
2534
- let newConfig = config;
2535
- i = 0;
2536
- while(i < len){
2537
- const onFulfilled = requestInterceptorChain[i++];
2538
- const onRejected = requestInterceptorChain[i++];
2539
- try {
2540
- newConfig = onFulfilled(newConfig);
2541
- } catch (error) {
2542
- onRejected.call(this, error);
2543
- break;
2544
- }
2545
- }
2546
- try {
2547
- promise = dispatchRequest.call(this, newConfig);
2548
- } catch (error) {
2549
- return Promise.reject(error);
2550
- }
2551
- i = 0;
2552
- len = responseInterceptorChain.length;
2553
- while(i < len)promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
2554
- return promise;
2555
- }
2556
- getUri(config) {
2557
- config = mergeConfig(this.defaults, config);
2558
- const fullPath = buildFullPath(config.baseURL, config.url);
2559
- return buildURL(fullPath, config.params, config.paramsSerializer);
2560
- }
2561
- }
2562
- // Provide aliases for supported request methods
2563
- utils.forEach([
2564
- 'delete',
2565
- 'get',
2566
- 'head',
2567
- 'options'
2568
- ], function(method) {
2569
- /*eslint func-names:0*/ Axios_Axios.prototype[method] = function(url, config) {
2570
- return this.request(mergeConfig(config || {}, {
2571
- method,
2572
- url,
2573
- data: (config || {}).data
2574
- }));
2575
- };
2576
- });
2577
- utils.forEach([
2578
- 'post',
2579
- 'put',
2580
- 'patch'
2581
- ], function(method) {
2582
- /*eslint func-names:0*/ function generateHTTPMethod(isForm) {
2583
- return function(url, data, config) {
2584
- return this.request(mergeConfig(config || {}, {
2585
- method,
2586
- headers: isForm ? {
2587
- 'Content-Type': 'multipart/form-data'
2588
- } : {},
2589
- url,
2590
- data
2591
- }));
2592
- };
2593
- }
2594
- Axios_Axios.prototype[method] = generateHTTPMethod();
2595
- Axios_Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
2596
- });
2597
- /* ESM default export */ const Axios = Axios_Axios;
2598
- /**
2599
- * A `CancelToken` is an object that can be used to request cancellation of an operation.
2600
- *
2601
- * @param {Function} executor The executor function.
2602
- *
2603
- * @returns {CancelToken}
2604
- */ class CancelToken_CancelToken {
2605
- constructor(executor){
2606
- if ('function' != typeof executor) throw new TypeError('executor must be a function.');
2607
- let resolvePromise;
2608
- this.promise = new Promise(function(resolve) {
2609
- resolvePromise = resolve;
2610
- });
2611
- const token = this;
2612
- // eslint-disable-next-line func-names
2613
- this.promise.then((cancel)=>{
2614
- if (!token._listeners) return;
2615
- let i = token._listeners.length;
2616
- while(i-- > 0)token._listeners[i](cancel);
2617
- token._listeners = null;
2618
- });
2619
- // eslint-disable-next-line func-names
2620
- this.promise.then = (onfulfilled)=>{
2621
- let _resolve;
2622
- // eslint-disable-next-line func-names
2623
- const promise = new Promise((resolve)=>{
2624
- token.subscribe(resolve);
2625
- _resolve = resolve;
2626
- }).then(onfulfilled);
2627
- promise.cancel = function() {
2628
- token.unsubscribe(_resolve);
2629
- };
2630
- return promise;
2631
- };
2632
- executor(function(message, config, request) {
2633
- if (token.reason) // Cancellation has already been requested
2634
- return;
2635
- token.reason = new CanceledError(message, config, request);
2636
- resolvePromise(token.reason);
2637
- });
2638
- }
2639
- /**
2640
- * Throws a `CanceledError` if cancellation has been requested.
2641
- */ throwIfRequested() {
2642
- if (this.reason) throw this.reason;
2643
- }
2644
- /**
2645
- * Subscribe to the cancel signal
2646
- */ subscribe(listener) {
2647
- if (this.reason) {
2648
- listener(this.reason);
2649
- return;
2650
- }
2651
- if (this._listeners) this._listeners.push(listener);
2652
- else this._listeners = [
2653
- listener
2654
- ];
2655
- }
2656
- /**
2657
- * Unsubscribe from the cancel signal
2658
- */ unsubscribe(listener) {
2659
- if (!this._listeners) return;
2660
- const index = this._listeners.indexOf(listener);
2661
- if (-1 !== index) this._listeners.splice(index, 1);
2662
- }
2663
- toAbortSignal() {
2664
- const controller = new AbortController();
2665
- const abort = (err)=>{
2666
- controller.abort(err);
2667
- };
2668
- this.subscribe(abort);
2669
- controller.signal.unsubscribe = ()=>this.unsubscribe(abort);
2670
- return controller.signal;
2671
- }
2672
- /**
2673
- * Returns an object that contains a new `CancelToken` and a function that, when called,
2674
- * cancels the `CancelToken`.
2675
- */ static source() {
2676
- let cancel;
2677
- const token = new CancelToken_CancelToken(function(c) {
2678
- cancel = c;
2679
- });
2680
- return {
2681
- token,
2682
- cancel
2683
- };
2684
- }
2685
- }
2686
- /* ESM default export */ const CancelToken = CancelToken_CancelToken;
2687
- /**
2688
- * Syntactic sugar for invoking a function and expanding an array for arguments.
2689
- *
2690
- * Common use case would be to use `Function.prototype.apply`.
2691
- *
2692
- * ```js
2693
- * function f(x, y, z) {}
2694
- * var args = [1, 2, 3];
2695
- * f.apply(null, args);
2696
- * ```
2697
- *
2698
- * With `spread` this example can be re-written.
2699
- *
2700
- * ```js
2701
- * spread(function(x, y, z) {})([1, 2, 3]);
2702
- * ```
2703
- *
2704
- * @param {Function} callback
2705
- *
2706
- * @returns {Function}
2707
- */ function spread(callback) {
2708
- return function(arr) {
2709
- return callback.apply(null, arr);
2710
- };
2711
- }
2712
- /**
2713
- * Determines whether the payload is an error thrown by Axios
2714
- *
2715
- * @param {*} payload The value to test
2716
- *
2717
- * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
2718
- */ function isAxiosError(payload) {
2719
- return utils.isObject(payload) && true === payload.isAxiosError;
2720
- }
2721
- const HttpStatusCode = {
2722
- Continue: 100,
2723
- SwitchingProtocols: 101,
2724
- Processing: 102,
2725
- EarlyHints: 103,
2726
- Ok: 200,
2727
- Created: 201,
2728
- Accepted: 202,
2729
- NonAuthoritativeInformation: 203,
2730
- NoContent: 204,
2731
- ResetContent: 205,
2732
- PartialContent: 206,
2733
- MultiStatus: 207,
2734
- AlreadyReported: 208,
2735
- ImUsed: 226,
2736
- MultipleChoices: 300,
2737
- MovedPermanently: 301,
2738
- Found: 302,
2739
- SeeOther: 303,
2740
- NotModified: 304,
2741
- UseProxy: 305,
2742
- Unused: 306,
2743
- TemporaryRedirect: 307,
2744
- PermanentRedirect: 308,
2745
- BadRequest: 400,
2746
- Unauthorized: 401,
2747
- PaymentRequired: 402,
2748
- Forbidden: 403,
2749
- NotFound: 404,
2750
- MethodNotAllowed: 405,
2751
- NotAcceptable: 406,
2752
- ProxyAuthenticationRequired: 407,
2753
- RequestTimeout: 408,
2754
- Conflict: 409,
2755
- Gone: 410,
2756
- LengthRequired: 411,
2757
- PreconditionFailed: 412,
2758
- PayloadTooLarge: 413,
2759
- UriTooLong: 414,
2760
- UnsupportedMediaType: 415,
2761
- RangeNotSatisfiable: 416,
2762
- ExpectationFailed: 417,
2763
- ImATeapot: 418,
2764
- MisdirectedRequest: 421,
2765
- UnprocessableEntity: 422,
2766
- Locked: 423,
2767
- FailedDependency: 424,
2768
- TooEarly: 425,
2769
- UpgradeRequired: 426,
2770
- PreconditionRequired: 428,
2771
- TooManyRequests: 429,
2772
- RequestHeaderFieldsTooLarge: 431,
2773
- UnavailableForLegalReasons: 451,
2774
- InternalServerError: 500,
2775
- NotImplemented: 501,
2776
- BadGateway: 502,
2777
- ServiceUnavailable: 503,
2778
- GatewayTimeout: 504,
2779
- HttpVersionNotSupported: 505,
2780
- VariantAlsoNegotiates: 506,
2781
- InsufficientStorage: 507,
2782
- LoopDetected: 508,
2783
- NotExtended: 510,
2784
- NetworkAuthenticationRequired: 511
2785
- };
2786
- Object.entries(HttpStatusCode).forEach(([key, value])=>{
2787
- HttpStatusCode[value] = key;
2788
- });
2789
- /* ESM default export */ const helpers_HttpStatusCode = HttpStatusCode;
2790
- /**
2791
- * Create an instance of Axios
2792
- *
2793
- * @param {Object} defaultConfig The default config for the instance
2794
- *
2795
- * @returns {Axios} A new instance of Axios
2796
- */ function createInstance(defaultConfig) {
2797
- const context = new Axios(defaultConfig);
2798
- const instance = bind(Axios.prototype.request, context);
2799
- // Copy axios.prototype to instance
2800
- utils.extend(instance, Axios.prototype, context, {
2801
- allOwnKeys: true
2802
- });
2803
- // Copy context to instance
2804
- utils.extend(instance, context, null, {
2805
- allOwnKeys: true
2806
- });
2807
- // Factory for creating new instances
2808
- instance.create = function(instanceConfig) {
2809
- return createInstance(mergeConfig(defaultConfig, instanceConfig));
2810
- };
2811
- return instance;
2812
- }
2813
- // Create the default instance to be exported
2814
- const axios = createInstance(defaults);
2815
- // Expose Axios class to allow class inheritance
2816
- axios.Axios = Axios;
2817
- // Expose Cancel & CancelToken
2818
- axios.CanceledError = CanceledError;
2819
- axios.CancelToken = CancelToken;
2820
- axios.isCancel = isCancel;
2821
- axios.VERSION = VERSION;
2822
- axios.toFormData = toFormData;
2823
- // Expose AxiosError class
2824
- axios.AxiosError = core_AxiosError;
2825
- // alias for CanceledError for backward compatibility
2826
- axios.Cancel = axios.CanceledError;
2827
- // Expose all/spread
2828
- axios.all = function(promises) {
2829
- return Promise.all(promises);
2830
- };
2831
- axios.spread = spread;
2832
- // Expose isAxiosError
2833
- axios.isAxiosError = isAxiosError;
2834
- // Expose mergeConfig
2835
- axios.mergeConfig = mergeConfig;
2836
- axios.AxiosHeaders = AxiosHeaders;
2837
- axios.formToJSON = (thing)=>formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
2838
- axios.getAdapter = adapters_adapters.getAdapter;
2839
- axios.HttpStatusCode = helpers_HttpStatusCode;
2840
- axios.default = axios;
2841
- // this module should only have a default export
2842
- /* ESM default export */ const lib_axios = axios;
2843
- // This module is intended to unwrap Axios default export as named.
2844
- // Keep top-level export same with static properties
2845
- // so that it can keep same with es module or cjs
2846
- 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;
2847
- // EXTERNAL MODULE: os (ignored)
2848
- var os_ignored_ = __webpack_require__("?d039");
2849
- // EXTERNAL MODULE: crypto (ignored)
2850
- __webpack_require__("?de24");
2851
- // EXTERNAL MODULE: jsonwebtoken (ignored)
2852
- __webpack_require__("?2a9f");
2853
- class APIResource {
2854
- constructor(client){
2855
- this._client = client;
2856
- }
2857
- }
2858
- /* eslint-disable @typescript-eslint/no-namespace */ class Bots extends APIResource {
2859
- /**
2860
- * Create a new agent. | 调用接口创建一个新的智能体。
2861
- * @docs en:https://www.coze.com/docs/developer_guides/create_bot?_lang=en
2862
- * @docs zh:https://www.coze.cn/docs/developer_guides/create_bot?_lang=zh
2863
- * @param params - Required The parameters for creating a bot. | 创建 Bot 的参数。
2864
- * @param params.space_id - Required The Space ID of the space where the agent is located. | Bot 所在的空间的 Space ID。
2865
- * @param params.name - Required The name of the agent. It should be 1 to 20 characters long. | Bot 的名称。
2866
- * @param params.description - Optional The description of the agent. It can be 0 to 500 characters long. | Bot 的描述信息。
2867
- * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
2868
- * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
2869
- * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
2870
- * @returns Information about the created bot. | 创建的 Bot 信息。
2871
- */ async create(params, options) {
2872
- const apiUrl = '/v1/bot/create';
2873
- const result = await this._client.post(apiUrl, params, false, options);
2874
- return result.data;
2875
- }
2876
- /**
2877
- * Update the configuration of an agent. | 调用接口修改智能体的配置。
2878
- * @docs en:https://www.coze.com/docs/developer_guides/update_bot?_lang=en
2879
- * @docs zh:https://www.coze.cn/docs/developer_guides/update_bot?_lang=zh
2880
- * @param params - Required The parameters for updating a bot. | 修改 Bot 的参数。
2881
- * @param params.bot_id - Required The ID of the agent that the API interacts with. | 待修改配置的智能体ID。
2882
- * @param params.name - Optional The name of the agent. | Bot 的名称。
2883
- * @param params.description - Optional The description of the agent. | Bot 的描述信息。
2884
- * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
2885
- * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
2886
- * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
2887
- * @param params.knowledge - Optional Knowledge configurations of the agent. | Bot 的知识库配置。
2888
- * @returns Undefined | 无返回值
2889
- */ async update(params, options) {
2890
- const apiUrl = '/v1/bot/update';
2891
- const result = await this._client.post(apiUrl, params, false, options);
2892
- return result.data;
2893
- }
2894
- /**
2895
- * Get the agents published as API service. | 调用接口查看指定空间发布到 Agent as API 渠道的智能体列表。
2896
- * @docs en:https://www.coze.com/docs/developer_guides/published_bots_list?_lang=en
2897
- * @docs zh:https://www.coze.cn/docs/developer_guides/published_bots_list?_lang=zh
2898
- * @param params - Required The parameters for listing bots. | 列出 Bot 的参数。
2899
- * @param params.space_id - Required The ID of the space. | Bot 所在的空间的 Space ID。
2900
- * @param params.page_size - Optional Pagination size. | 分页大小。
2901
- * @param params.page_index - Optional Page number for paginated queries. | 分页查询时的页码。
2902
- * @returns List of published bots. | 已发布的 Bot 列表。
2903
- */ async list(params, options) {
2904
- const apiUrl = '/v1/space/published_bots_list';
2905
- const result = await this._client.get(apiUrl, params, false, options);
2906
- return result.data;
2907
- }
2908
- /**
2909
- * Publish the specified agent as an API service. | 调用接口创建一个新的智能体。
2910
- * @docs en:https://www.coze.com/docs/developer_guides/publish_bot?_lang=en
2911
- * @docs zh:https://www.coze.cn/docs/developer_guides/publish_bot?_lang=zh
2912
- * @param params - Required The parameters for publishing a bot. | 发布 Bot 的参数。
2913
- * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要发布的智能体ID。
2914
- * @param params.connector_ids - Required The list of publishing channel IDs for the agent. | 智能体的发布渠道 ID 列表。
2915
- * @returns Undefined | 无返回值
2916
- */ async publish(params, options) {
2917
- const apiUrl = '/v1/bot/publish';
2918
- const result = await this._client.post(apiUrl, params, false, options);
2919
- return result.data;
2920
- }
2921
- /**
2922
- * Get the configuration information of the agent. | 获取指定智能体的配置信息。
2923
- * @docs en:https://www.coze.com/docs/developer_guides/get_metadata?_lang=en
2924
- * @docs zh:https://www.coze.cn/docs/developer_guides/get_metadata?_lang=zh
2925
- * @param params - Required The parameters for retrieving a bot. | 获取 Bot 的参数。
2926
- * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要查看的智能体ID。
2927
- * @returns Information about the bot. | Bot 的配置信息。
2928
- */ async retrieve(params, options) {
2929
- const apiUrl = '/v1/bot/get_online_info';
2930
- const result = await this._client.get(apiUrl, params, false, options);
2931
- return result.data;
2932
- }
2933
- }
2934
- /* eslint-disable security/detect-object-injection */ /* eslint-disable @typescript-eslint/no-explicit-any */ function safeJsonParse(jsonString) {
2935
- let defaultValue = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : '';
2936
- try {
2937
- return JSON.parse(jsonString);
2938
- } catch (error) {
2939
- return defaultValue;
2940
- }
2941
- }
2942
- function sleep(ms) {
2943
- return new Promise((resolve)=>{
2944
- setTimeout(resolve, ms);
2945
- });
2946
- }
2947
- function isBrowser() {
2948
- return 'undefined' != typeof window;
2949
- }
2950
- function esm_isPlainObject(obj) {
2951
- if ('object' != typeof obj || null === obj) return false;
2952
- const proto = Object.getPrototypeOf(obj);
2953
- if (null === proto) return true;
2954
- let baseProto = proto;
2955
- while(null !== Object.getPrototypeOf(baseProto))baseProto = Object.getPrototypeOf(baseProto);
2956
- return proto === baseProto;
2957
- }
2958
- function esm_mergeConfig() {
2959
- for(var _len = arguments.length, objects = new Array(_len), _key = 0; _key < _len; _key++)objects[_key] = arguments[_key];
2960
- return objects.reduce((result, obj)=>{
2961
- if (void 0 === obj) return result || {};
2962
- for(const key in obj)if (Object.prototype.hasOwnProperty.call(obj, key)) {
2963
- if (esm_isPlainObject(obj[key]) && !Array.isArray(obj[key])) result[key] = esm_mergeConfig(result[key] || {}, obj[key]);
2964
- else result[key] = obj[key];
2965
- }
2966
- return result;
2967
- }, {});
2968
- }
2969
- function isPersonalAccessToken(token) {
2970
- return null == token ? void 0 : token.startsWith('pat_');
2971
- }
2972
- /* eslint-disable max-params */ class CozeError extends Error {
2973
- }
2974
- class APIError extends CozeError {
2975
- static makeMessage(status, errorBody, message, headers) {
2976
- if (!errorBody && message) return message;
2977
- if (errorBody) {
2978
- const list = [];
2979
- const { code, msg, error } = errorBody;
2980
- if (code) list.push(`code: ${code}`);
2981
- if (msg) list.push(`msg: ${msg}`);
2982
- if ((null == error ? void 0 : error.detail) && msg !== error.detail) list.push(`detail: ${error.detail}`);
2983
- const logId = (null == error ? void 0 : error.logid) || (null == headers ? void 0 : headers['x-tt-logid']);
2984
- if (logId) list.push(`logid: ${logId}`);
2985
- const help_doc = null == error ? void 0 : error.help_doc;
2986
- if (help_doc) list.push(`help doc: ${help_doc}`);
2987
- return list.join(', ');
2988
- }
2989
- if (status) return `http status code: ${status} (no body)`;
2990
- return '(no status code or body)';
2991
- }
2992
- static generate(status, errorResponse, message, headers) {
2993
- if (!status) return new APIConnectionError({
2994
- cause: castToError(errorResponse)
2995
- });
2996
- const error = errorResponse;
2997
- // https://www.coze.cn/docs/developer_guides/coze_error_codes
2998
- if (400 === status || (null == error ? void 0 : error.code) === 4000) return new BadRequestError(status, error, message, headers);
2999
- if (401 === status || (null == error ? void 0 : error.code) === 4100) return new AuthenticationError(status, error, message, headers);
3000
- if (403 === status || (null == error ? void 0 : error.code) === 4101) return new PermissionDeniedError(status, error, message, headers);
3001
- if (404 === status || (null == error ? void 0 : error.code) === 4200) return new NotFoundError(status, error, message, headers);
3002
- if (429 === status || (null == error ? void 0 : error.code) === 4013) return new RateLimitError(status, error, message, headers);
3003
- if (408 === status) return new TimeoutError(status, error, message, headers);
3004
- if (502 === status) return new GatewayError(status, error, message, headers);
3005
- if (status >= 500) return new InternalServerError(status, error, message, headers);
3006
- return new APIError(status, error, message, headers);
3007
- }
3008
- constructor(status, error, message, headers){
3009
- var _error_error, _error_error1;
3010
- super(`${APIError.makeMessage(status, error, message, headers)}`);
3011
- this.status = status;
3012
- this.headers = headers;
3013
- this.logid = null == headers ? void 0 : headers['x-tt-logid'];
3014
- // this.error = error;
3015
- this.code = null == error ? void 0 : error.code;
3016
- this.msg = null == error ? void 0 : error.msg;
3017
- this.detail = null == error ? void 0 : null === (_error_error = error.error) || void 0 === _error_error ? void 0 : _error_error.detail;
3018
- this.help_doc = null == error ? void 0 : null === (_error_error1 = error.error) || void 0 === _error_error1 ? void 0 : _error_error1.help_doc;
3019
- this.rawError = error;
3020
- }
3021
- }
3022
- class APIConnectionError extends APIError {
3023
- constructor({ message, cause }){
3024
- super(void 0, void 0, message || 'Connection error.', void 0), this.status = void 0;
3025
- // if (cause) {
3026
- // this.cause = cause;
3027
- // }
3028
- }
3029
- }
3030
- class APIUserAbortError extends APIError {
3031
- constructor(message){
3032
- super(void 0, void 0, message || 'Request was aborted.', void 0), this.name = 'UserAbortError', this.status = void 0;
3033
- }
3034
- }
3035
- class BadRequestError extends APIError {
3036
- constructor(...args){
3037
- super(...args), this.name = 'BadRequestError', this.status = 400;
3038
- }
3039
- }
3040
- class AuthenticationError extends APIError {
3041
- constructor(...args){
3042
- super(...args), this.name = 'AuthenticationError', this.status = 401;
3043
- }
3044
- }
3045
- class PermissionDeniedError extends APIError {
3046
- constructor(...args){
3047
- super(...args), this.name = 'PermissionDeniedError', this.status = 403;
3048
- }
3049
- }
3050
- class NotFoundError extends APIError {
3051
- constructor(...args){
3052
- super(...args), this.name = 'NotFoundError', this.status = 404;
3053
- }
3054
- }
3055
- class TimeoutError extends APIError {
3056
- constructor(...args){
3057
- super(...args), this.name = 'TimeoutError', this.status = 408;
3058
- }
3059
- }
3060
- class RateLimitError extends APIError {
3061
- constructor(...args){
3062
- super(...args), this.name = 'RateLimitError', this.status = 429;
3063
- }
3064
- }
3065
- class InternalServerError extends APIError {
3066
- constructor(...args){
3067
- super(...args), this.name = 'InternalServerError', this.status = 500;
3068
- }
3069
- }
3070
- class GatewayError extends APIError {
3071
- constructor(...args){
3072
- super(...args), this.name = 'GatewayError', this.status = 502;
3073
- }
3074
- }
3075
- const castToError = (err)=>{
3076
- if (err instanceof Error) return err;
3077
- return new Error(err);
3078
- };
3079
- class Messages extends APIResource {
3080
- /**
3081
- * Get the list of messages in a chat. | 获取对话中的消息列表。
3082
- * @docs en:https://www.coze.com/docs/developer_guides/chat_message_list?_lang=en
3083
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_message_list?_lang=zh
3084
- * @param conversation_id - Required The ID of the conversation. | 会话 ID。
3085
- * @param chat_id - Required The ID of the chat. | 对话 ID。
3086
- * @returns An array of chat messages. | 对话消息数组。
3087
- */ async list(conversation_id, chat_id, options) {
3088
- const apiUrl = `/v3/chat/message/list?conversation_id=${conversation_id}&chat_id=${chat_id}`;
3089
- const result = await this._client.get(apiUrl, void 0, false, options);
3090
- return result.data;
3091
- }
3092
- }
3093
- const uuid = ()=>(Math.random() * new Date().getTime()).toString();
3094
- class Chat extends APIResource {
3095
- /**
3096
- * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
3097
- * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
3098
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
3099
- * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
3100
- * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
3101
- * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
3102
- * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
3103
- * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义变量。
3104
- * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
3105
- * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
3106
- * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
3107
- * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
3108
- * @returns The data of the created chat. | 创建的对话数据。
3109
- */ async create(params, options) {
3110
- if (!params.user_id) params.user_id = uuid();
3111
- const { conversation_id, ...rest } = params;
3112
- const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
3113
- const payload = {
3114
- ...rest,
3115
- stream: false
3116
- };
3117
- const result = await this._client.post(apiUrl, payload, false, options);
3118
- return result.data;
3119
- }
3120
- /**
3121
- * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
3122
- * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
3123
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
3124
- * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
3125
- * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
3126
- * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
3127
- * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
3128
- * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
3129
- * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
3130
- * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
3131
- * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
3132
- * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
3133
- * @returns
3134
- */ async createAndPoll(params, options) {
3135
- if (!params.user_id) params.user_id = uuid();
3136
- const { conversation_id, ...rest } = params;
3137
- const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
3138
- const payload = {
3139
- ...rest,
3140
- stream: false
3141
- };
3142
- const result = await this._client.post(apiUrl, payload, false, options);
3143
- const chatId = result.data.id;
3144
- const conversationId = result.data.conversation_id;
3145
- let chat;
3146
- while(true){
3147
- await sleep(100);
3148
- chat = await this.retrieve(conversationId, chatId);
3149
- if ('completed' === chat.status || 'failed' === chat.status || 'requires_action' === chat.status) break;
3150
- }
3151
- const messageList = await this.messages.list(conversationId, chatId);
3152
- return {
3153
- chat,
3154
- messages: messageList
3155
- };
3156
- }
3157
- /**
3158
- * Call the Chat API to send messages to a published Coze agent with streaming response. | 调用此接口发起一次对话,支持流式响应。
3159
- * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
3160
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
3161
- * @param params - Required The parameters for streaming a chat session. | 流式会话的参数。
3162
- * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
3163
- * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
3164
- * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
3165
- * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
3166
- * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
3167
- * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
3168
- * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
3169
- * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
3170
- * @returns A stream of chat data. | 对话数据流。
3171
- */ async *stream(params, options) {
3172
- if (!params.user_id) params.user_id = uuid();
3173
- const { conversation_id, ...rest } = params;
3174
- const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
3175
- const payload = {
3176
- ...rest,
3177
- stream: true
3178
- };
3179
- const result = await this._client.post(apiUrl, payload, true, options);
3180
- for await (const message of result)if ("done" === message.event) {
3181
- const ret = {
3182
- event: message.event,
3183
- data: '[DONE]'
3184
- };
3185
- yield ret;
3186
- } else try {
3187
- const ret = {
3188
- event: message.event,
3189
- data: JSON.parse(message.data)
3190
- };
3191
- yield ret;
3192
- } catch (error) {
3193
- throw new CozeError(`Could not parse message into JSON:${message.data}`);
3194
- }
3195
- }
3196
- /**
3197
- * Get the detailed information of the chat. | 查看对话的详细信息。
3198
- * @docs en:https://www.coze.com/docs/developer_guides/retrieve_chat?_lang=en
3199
- * @docs zh:https://www.coze.cn/docs/developer_guides/retrieve_chat?_lang=zh
3200
- * @param conversation_id - Required The ID of the conversation. | 会话 ID。
3201
- * @param chat_id - Required The ID of the chat. | 对话 ID。
3202
- * @returns The data of the retrieved chat. | 检索到的对话数据。
3203
- */ async retrieve(conversation_id, chat_id, options) {
3204
- const apiUrl = `/v3/chat/retrieve?conversation_id=${conversation_id}&chat_id=${chat_id}`;
3205
- const result = await this._client.post(apiUrl, void 0, false, options);
3206
- return result.data;
3207
- }
3208
- /**
3209
- * Cancel a chat session. | 取消对话会话。
3210
- * @docs en:https://www.coze.com/docs/developer_guides/cancel_chat?_lang=en
3211
- * @docs zh:https://www.coze.cn/docs/developer_guides/cancel_chat?_lang=zh
3212
- * @param conversation_id - Required The ID of the conversation. | 会话 ID。
3213
- * @param chat_id - Required The ID of the chat. | 对话 ID。
3214
- * @returns The data of the canceled chat. | 取消的对话数据。
3215
- */ async cancel(conversation_id, chat_id, options) {
3216
- const apiUrl = '/v3/chat/cancel';
3217
- const payload = {
3218
- conversation_id,
3219
- chat_id
3220
- };
3221
- const result = await this._client.post(apiUrl, payload, false, options);
3222
- return result.data;
3223
- }
3224
- /**
3225
- * Submit tool outputs for a chat session. | 提交对话会话的工具输出。
3226
- * @docs en:https://www.coze.com/docs/developer_guides/chat_submit_tool_outputs?_lang=en
3227
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_submit_tool_outputs?_lang=zh
3228
- * @param params - Required Parameters for submitting tool outputs. | 提交工具输出的参数。
3229
- * @param params.conversation_id - Required The ID of the conversation. | 会话 ID。
3230
- * @param params.chat_id - Required The ID of the chat. | 对话 ID。
3231
- * @param params.tool_outputs - Required The outputs of the tool. | 工具的输出。
3232
- * @param params.stream - Optional Whether to use streaming response. | 是否使用流式响应。
3233
- * @returns The data of the submitted tool outputs or a stream of chat data. | 提交的工具输出数据或对话数据流。
3234
- */ async *submitToolOutputs(params, options) {
3235
- const { conversation_id, chat_id, ...rest } = params;
3236
- const apiUrl = `/v3/chat/submit_tool_outputs?conversation_id=${params.conversation_id}&chat_id=${params.chat_id}`;
3237
- const payload = {
3238
- ...rest
3239
- };
3240
- if (false === params.stream) {
3241
- const response = await this._client.post(apiUrl, payload, false, options);
3242
- return response.data;
3104
+ chain.push.apply(chain, responseInterceptorChain);
3105
+ len = chain.length;
3106
+ promise = Promise.resolve(config);
3107
+ while(i < len)promise = promise.then(chain[i++], chain[i++]);
3108
+ return promise;
3243
3109
  }
3244
- {
3245
- const result = await this._client.post(apiUrl, payload, true, options);
3246
- for await (const message of result)if ("done" === message.event) {
3247
- const ret = {
3248
- event: message.event,
3249
- data: '[DONE]'
3250
- };
3251
- yield ret;
3252
- } else try {
3253
- const ret = {
3254
- event: message.event,
3255
- data: JSON.parse(message.data)
3256
- };
3257
- yield ret;
3110
+ len = requestInterceptorChain.length;
3111
+ let newConfig = config;
3112
+ i = 0;
3113
+ while(i < len){
3114
+ const onFulfilled = requestInterceptorChain[i++];
3115
+ const onRejected = requestInterceptorChain[i++];
3116
+ try {
3117
+ newConfig = onFulfilled(newConfig);
3258
3118
  } catch (error) {
3259
- throw new CozeError(`Could not parse message into JSON:${message.data}`);
3119
+ onRejected.call(this, error);
3120
+ break;
3260
3121
  }
3261
3122
  }
3123
+ try {
3124
+ promise = dispatchRequest.call(this, newConfig);
3125
+ } catch (error) {
3126
+ return Promise.reject(error);
3127
+ }
3128
+ i = 0;
3129
+ len = responseInterceptorChain.length;
3130
+ while(i < len)promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
3131
+ return promise;
3262
3132
  }
3263
- constructor(...args){
3264
- super(...args), this.messages = new Messages(this._client);
3133
+ getUri(config) {
3134
+ config = mergeConfig_mergeConfig(this.defaults, config);
3135
+ const fullPath = buildFullPath(config.baseURL, config.url);
3136
+ return buildURL(fullPath, config.params, config.paramsSerializer);
3265
3137
  }
3266
3138
  }
3267
- class messages_Messages extends APIResource {
3268
- /**
3269
- * Create a message and add it to the specified conversation. | 创建一条消息,并将其添加到指定的会话中。
3270
- * @docs en: https://www.coze.com/docs/developer_guides/create_message?_lang=en
3271
- * @docs zh: https://www.coze.cn/docs/developer_guides/create_message?_lang=zh
3272
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3273
- * @param params - Required The parameters for creating a message | 创建消息所需的参数
3274
- * @param params.role - Required The entity that sent this message. Possible values: user, assistant. | 发送这条消息的实体。取值:user, assistant。
3275
- * @param params.content - Required The content of the message. | 消息的内容。
3276
- * @param params.content_type - Required The type of the message content. | 消息内容的类型。
3277
- * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
3278
- * @returns Information about the new message. | 消息详情。
3279
- */ async create(conversation_id, params, options) {
3280
- const apiUrl = `/v1/conversation/message/create?conversation_id=${conversation_id}`;
3281
- const response = await this._client.post(apiUrl, params, false, options);
3282
- return response.data;
3139
+ // Provide aliases for supported request methods
3140
+ utils.forEach([
3141
+ 'delete',
3142
+ 'get',
3143
+ 'head',
3144
+ 'options'
3145
+ ], function(method) {
3146
+ /*eslint func-names:0*/ Axios_Axios.prototype[method] = function(url, config) {
3147
+ return this.request(mergeConfig_mergeConfig(config || {}, {
3148
+ method,
3149
+ url,
3150
+ data: (config || {}).data
3151
+ }));
3152
+ };
3153
+ });
3154
+ utils.forEach([
3155
+ 'post',
3156
+ 'put',
3157
+ 'patch'
3158
+ ], function(method) {
3159
+ /*eslint func-names:0*/ function generateHTTPMethod(isForm) {
3160
+ return function(url, data, config) {
3161
+ return this.request(mergeConfig_mergeConfig(config || {}, {
3162
+ method,
3163
+ headers: isForm ? {
3164
+ 'Content-Type': 'multipart/form-data'
3165
+ } : {},
3166
+ url,
3167
+ data
3168
+ }));
3169
+ };
3283
3170
  }
3284
- /**
3285
- * Modify a message, supporting the modification of message content, additional content, and message type. | 修改一条消息,支持修改消息内容、附加内容和消息类型。
3286
- * @docs en: https://www.coze.com/docs/developer_guides/modify_message?_lang=en
3287
- * @docs zh: https://www.coze.cn/docs/developer_guides/modify_message?_lang=zh
3288
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3289
- * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
3290
- * @param params - Required The parameters for modifying a message | 修改消息所需的参数
3291
- * @param params.meta_data - Optional Additional information when modifying a message. | 修改消息时的附加消息。
3292
- * @param params.content - Optional The content of the message. | 消息的内容。
3293
- * @param params.content_type - Optional The type of the message content. | 消息内容的类型。
3294
- * @returns Information about the modified message. | 消息详情。
3295
- */ // eslint-disable-next-line max-params
3296
- async update(conversation_id, message_id, params, options) {
3297
- const apiUrl = `/v1/conversation/message/modify?conversation_id=${conversation_id}&message_id=${message_id}`;
3298
- const response = await this._client.post(apiUrl, params, false, options);
3299
- return response.message;
3171
+ Axios_Axios.prototype[method] = generateHTTPMethod();
3172
+ Axios_Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
3173
+ });
3174
+ /* ESM default export */ const Axios = Axios_Axios;
3175
+ /**
3176
+ * A `CancelToken` is an object that can be used to request cancellation of an operation.
3177
+ *
3178
+ * @param {Function} executor The executor function.
3179
+ *
3180
+ * @returns {CancelToken}
3181
+ */ class CancelToken_CancelToken {
3182
+ constructor(executor){
3183
+ if ('function' != typeof executor) throw new TypeError('executor must be a function.');
3184
+ let resolvePromise;
3185
+ this.promise = new Promise(function(resolve) {
3186
+ resolvePromise = resolve;
3187
+ });
3188
+ const token = this;
3189
+ // eslint-disable-next-line func-names
3190
+ this.promise.then((cancel)=>{
3191
+ if (!token._listeners) return;
3192
+ let i = token._listeners.length;
3193
+ while(i-- > 0)token._listeners[i](cancel);
3194
+ token._listeners = null;
3195
+ });
3196
+ // eslint-disable-next-line func-names
3197
+ this.promise.then = (onfulfilled)=>{
3198
+ let _resolve;
3199
+ // eslint-disable-next-line func-names
3200
+ const promise = new Promise((resolve)=>{
3201
+ token.subscribe(resolve);
3202
+ _resolve = resolve;
3203
+ }).then(onfulfilled);
3204
+ promise.cancel = function() {
3205
+ token.unsubscribe(_resolve);
3206
+ };
3207
+ return promise;
3208
+ };
3209
+ executor(function(message, config, request) {
3210
+ if (token.reason) // Cancellation has already been requested
3211
+ return;
3212
+ token.reason = new CanceledError(message, config, request);
3213
+ resolvePromise(token.reason);
3214
+ });
3300
3215
  }
3301
3216
  /**
3302
- * Get the detailed information of specified message. | 查看指定消息的详细信息。
3303
- * @docs en: https://www.coze.com/docs/developer_guides/retrieve_message?_lang=en
3304
- * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_message?_lang=zh
3305
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3306
- * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
3307
- * @returns Information about the message. | 消息详情。
3308
- */ async retrieve(conversation_id, message_id, options) {
3309
- const apiUrl = `/v1/conversation/message/retrieve?conversation_id=${conversation_id}&message_id=${message_id}`;
3310
- const response = await this._client.get(apiUrl, null, false, options);
3311
- return response.data;
3217
+ * Throws a `CanceledError` if cancellation has been requested.
3218
+ */ throwIfRequested() {
3219
+ if (this.reason) throw this.reason;
3312
3220
  }
3313
3221
  /**
3314
- * List messages in a conversation. | 列出会话中的消息。
3315
- * @docs en: https://www.coze.com/docs/developer_guides/message_list?_lang=en
3316
- * @docs zh: https://www.coze.cn/docs/developer_guides/message_list?_lang=zh
3317
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3318
- * @param params - Optional The parameters for listing messages | 列出消息所需的参数
3319
- * @param params.order - Optional The order of the messages. | 消息的顺序。
3320
- * @param params.chat_id - Optional The ID of the chat. | 聊天 ID。
3321
- * @param params.before_id - Optional The ID of the message before which to list. | 列出此消息之前的消息 ID。
3322
- * @param params.after_id - Optional The ID of the message after which to list. | 列出此消息之后的消息 ID。
3323
- * @param params.limit - Optional The maximum number of messages to return. | 返回的最大消息数。
3324
- * @returns A list of messages. | 消息列表。
3325
- */ async list(conversation_id, params, options) {
3326
- const apiUrl = `/v1/conversation/message/list?conversation_id=${conversation_id}`;
3327
- const response = await this._client.post(apiUrl, params, false, options);
3328
- return response;
3222
+ * Subscribe to the cancel signal
3223
+ */ subscribe(listener) {
3224
+ if (this.reason) {
3225
+ listener(this.reason);
3226
+ return;
3227
+ }
3228
+ if (this._listeners) this._listeners.push(listener);
3229
+ else this._listeners = [
3230
+ listener
3231
+ ];
3329
3232
  }
3330
3233
  /**
3331
- * Call the API to delete a message within a specified conversation. | 调用接口在指定会话中删除消息。
3332
- * @docs en: https://www.coze.com/docs/developer_guides/delete_message?_lang=en
3333
- * @docs zh: https://www.coze.cn/docs/developer_guides/delete_message?_lang=zh
3334
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3335
- * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
3336
- * @returns Details of the deleted message. | 已删除的消息详情。
3337
- */ async delete(conversation_id, message_id, options) {
3338
- const apiUrl = `/v1/conversation/message/delete?conversation_id=${conversation_id}&message_id=${message_id}`;
3339
- const response = await this._client.post(apiUrl, void 0, false, options);
3340
- return response.data;
3234
+ * Unsubscribe from the cancel signal
3235
+ */ unsubscribe(listener) {
3236
+ if (!this._listeners) return;
3237
+ const index = this._listeners.indexOf(listener);
3238
+ if (-1 !== index) this._listeners.splice(index, 1);
3341
3239
  }
3342
- }
3343
- class Conversations extends APIResource {
3344
- /**
3345
- * Create a conversation. Conversation is an interaction between an agent and a user, including one or more messages. | 调用接口创建一个会话。
3346
- * @docs en: https://www.coze.com/docs/developer_guides/create_conversation?_lang=en
3347
- * @docs zh: https://www.coze.cn/docs/developer_guides/create_conversation?_lang=zh
3348
- * @param params - Required The parameters for creating a conversation | 创建会话所需的参数
3349
- * @param params.messages - Optional Messages in the conversation. | 会话中的消息内容。
3350
- * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
3351
- * @returns Information about the created conversation. | 会话的基础信息。
3352
- */ async create(params, options) {
3353
- const apiUrl = '/v1/conversation/create';
3354
- const response = await this._client.post(apiUrl, params, false, options);
3355
- return response.data;
3240
+ toAbortSignal() {
3241
+ const controller = new AbortController();
3242
+ const abort = (err)=>{
3243
+ controller.abort(err);
3244
+ };
3245
+ this.subscribe(abort);
3246
+ controller.signal.unsubscribe = ()=>this.unsubscribe(abort);
3247
+ return controller.signal;
3356
3248
  }
3357
3249
  /**
3358
- * Get the information of specific conversation. | 通过会话 ID 查看会话信息。
3359
- * @docs en: https://www.coze.com/docs/developer_guides/retrieve_conversation?_lang=en
3360
- * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_conversation?_lang=zh
3361
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3362
- * @returns Information about the conversation. | 会话的基础信息。
3363
- */ async retrieve(conversation_id, options) {
3364
- const apiUrl = `/v1/conversation/retrieve?conversation_id=${conversation_id}`;
3365
- const response = await this._client.get(apiUrl, null, false, options);
3366
- return response.data;
3367
- }
3368
- constructor(...args){
3369
- super(...args), this.messages = new messages_Messages(this._client);
3250
+ * Returns an object that contains a new `CancelToken` and a function that, when called,
3251
+ * cancels the `CancelToken`.
3252
+ */ static source() {
3253
+ let cancel;
3254
+ const token = new CancelToken_CancelToken(function(c) {
3255
+ cancel = c;
3256
+ });
3257
+ return {
3258
+ token,
3259
+ cancel
3260
+ };
3370
3261
  }
3371
3262
  }
3263
+ /* ESM default export */ const CancelToken = CancelToken_CancelToken;
3264
+ /**
3265
+ * Syntactic sugar for invoking a function and expanding an array for arguments.
3266
+ *
3267
+ * Common use case would be to use `Function.prototype.apply`.
3268
+ *
3269
+ * ```js
3270
+ * function f(x, y, z) {}
3271
+ * var args = [1, 2, 3];
3272
+ * f.apply(null, args);
3273
+ * ```
3274
+ *
3275
+ * With `spread` this example can be re-written.
3276
+ *
3277
+ * ```js
3278
+ * spread(function(x, y, z) {})([1, 2, 3]);
3279
+ * ```
3280
+ *
3281
+ * @param {Function} callback
3282
+ *
3283
+ * @returns {Function}
3284
+ */ function spread(callback) {
3285
+ return function(arr) {
3286
+ return callback.apply(null, arr);
3287
+ };
3288
+ }
3289
+ /**
3290
+ * Determines whether the payload is an error thrown by Axios
3291
+ *
3292
+ * @param {*} payload The value to test
3293
+ *
3294
+ * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
3295
+ */ function isAxiosError(payload) {
3296
+ return utils.isObject(payload) && true === payload.isAxiosError;
3297
+ }
3298
+ const HttpStatusCode = {
3299
+ Continue: 100,
3300
+ SwitchingProtocols: 101,
3301
+ Processing: 102,
3302
+ EarlyHints: 103,
3303
+ Ok: 200,
3304
+ Created: 201,
3305
+ Accepted: 202,
3306
+ NonAuthoritativeInformation: 203,
3307
+ NoContent: 204,
3308
+ ResetContent: 205,
3309
+ PartialContent: 206,
3310
+ MultiStatus: 207,
3311
+ AlreadyReported: 208,
3312
+ ImUsed: 226,
3313
+ MultipleChoices: 300,
3314
+ MovedPermanently: 301,
3315
+ Found: 302,
3316
+ SeeOther: 303,
3317
+ NotModified: 304,
3318
+ UseProxy: 305,
3319
+ Unused: 306,
3320
+ TemporaryRedirect: 307,
3321
+ PermanentRedirect: 308,
3322
+ BadRequest: 400,
3323
+ Unauthorized: 401,
3324
+ PaymentRequired: 402,
3325
+ Forbidden: 403,
3326
+ NotFound: 404,
3327
+ MethodNotAllowed: 405,
3328
+ NotAcceptable: 406,
3329
+ ProxyAuthenticationRequired: 407,
3330
+ RequestTimeout: 408,
3331
+ Conflict: 409,
3332
+ Gone: 410,
3333
+ LengthRequired: 411,
3334
+ PreconditionFailed: 412,
3335
+ PayloadTooLarge: 413,
3336
+ UriTooLong: 414,
3337
+ UnsupportedMediaType: 415,
3338
+ RangeNotSatisfiable: 416,
3339
+ ExpectationFailed: 417,
3340
+ ImATeapot: 418,
3341
+ MisdirectedRequest: 421,
3342
+ UnprocessableEntity: 422,
3343
+ Locked: 423,
3344
+ FailedDependency: 424,
3345
+ TooEarly: 425,
3346
+ UpgradeRequired: 426,
3347
+ PreconditionRequired: 428,
3348
+ TooManyRequests: 429,
3349
+ RequestHeaderFieldsTooLarge: 431,
3350
+ UnavailableForLegalReasons: 451,
3351
+ InternalServerError: 500,
3352
+ NotImplemented: 501,
3353
+ BadGateway: 502,
3354
+ ServiceUnavailable: 503,
3355
+ GatewayTimeout: 504,
3356
+ HttpVersionNotSupported: 505,
3357
+ VariantAlsoNegotiates: 506,
3358
+ InsufficientStorage: 507,
3359
+ LoopDetected: 508,
3360
+ NotExtended: 510,
3361
+ NetworkAuthenticationRequired: 511
3362
+ };
3363
+ Object.entries(HttpStatusCode).forEach(([key, value])=>{
3364
+ HttpStatusCode[value] = key;
3365
+ });
3366
+ /* ESM default export */ const helpers_HttpStatusCode = HttpStatusCode;
3367
+ /**
3368
+ * Create an instance of Axios
3369
+ *
3370
+ * @param {Object} defaultConfig The default config for the instance
3371
+ *
3372
+ * @returns {Axios} A new instance of Axios
3373
+ */ function createInstance(defaultConfig) {
3374
+ const context = new Axios(defaultConfig);
3375
+ const instance = bind(Axios.prototype.request, context);
3376
+ // Copy axios.prototype to instance
3377
+ utils.extend(instance, Axios.prototype, context, {
3378
+ allOwnKeys: true
3379
+ });
3380
+ // Copy context to instance
3381
+ utils.extend(instance, context, null, {
3382
+ allOwnKeys: true
3383
+ });
3384
+ // Factory for creating new instances
3385
+ instance.create = function(instanceConfig) {
3386
+ return createInstance(mergeConfig_mergeConfig(defaultConfig, instanceConfig));
3387
+ };
3388
+ return instance;
3389
+ }
3390
+ // Create the default instance to be exported
3391
+ const axios = createInstance(defaults);
3392
+ // Expose Axios class to allow class inheritance
3393
+ axios.Axios = Axios;
3394
+ // Expose Cancel & CancelToken
3395
+ axios.CanceledError = CanceledError;
3396
+ axios.CancelToken = CancelToken;
3397
+ axios.isCancel = isCancel;
3398
+ axios.VERSION = VERSION;
3399
+ axios.toFormData = toFormData;
3400
+ // Expose AxiosError class
3401
+ axios.AxiosError = core_AxiosError;
3402
+ // alias for CanceledError for backward compatibility
3403
+ axios.Cancel = axios.CanceledError;
3404
+ // Expose all/spread
3405
+ axios.all = function(promises) {
3406
+ return Promise.all(promises);
3407
+ };
3408
+ axios.spread = spread;
3409
+ // Expose isAxiosError
3410
+ axios.isAxiosError = isAxiosError;
3411
+ // Expose mergeConfig
3412
+ axios.mergeConfig = mergeConfig_mergeConfig;
3413
+ axios.AxiosHeaders = AxiosHeaders;
3414
+ axios.formToJSON = (thing)=>formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
3415
+ axios.getAdapter = adapters_adapters.getAdapter;
3416
+ axios.HttpStatusCode = helpers_HttpStatusCode;
3417
+ axios.default = axios;
3418
+ // this module should only have a default export
3419
+ /* ESM default export */ const lib_axios = axios;
3420
+ // This module is intended to unwrap Axios default export as named.
3421
+ // Keep top-level export same with static properties
3422
+ // so that it can keep same with es module or cjs
3423
+ const { Axios: axios_Axios, AxiosError: axios_AxiosError, CanceledError: axios_CanceledError, isCancel: axios_isCancel, CancelToken: axios_CancelToken, VERSION: axios_VERSION, all: axios_all, Cancel, isAxiosError: axios_isAxiosError, spread: axios_spread, toFormData: axios_toFormData, AxiosHeaders: axios_AxiosHeaders, HttpStatusCode: axios_HttpStatusCode, formToJSON, getAdapter, mergeConfig: axios_mergeConfig } = lib_axios;
3372
3424
  class Files extends APIResource {
3373
3425
  /**
3374
3426
  * Upload files to Coze platform. | 调用接口上传文件到扣子。
@@ -3403,6 +3455,9 @@ class Runs extends APIResource {
3403
3455
  * @param params.bot_id - Optional The ID of the bot associated with the workflow. | 可选 与工作流关联的机器人 ID。
3404
3456
  * @param params.parameters - Optional Parameters for the workflow execution. | 可选 工作流执行的参数。
3405
3457
  * @param params.ext - Optional Additional information for the workflow execution. | 可选 工作流执行的附加信息。
3458
+ * @param params.execute_mode - Optional The mode in which to execute the workflow. | 可选 工作流执行的模式。
3459
+ * @param params.connector_id - Optional The ID of the connector to use for the workflow. | 可选 用于工作流的连接器 ID。
3460
+ * @param params.app_id - Optional The ID of the app. | 可选 要进行会话聊天的 App ID
3406
3461
  * @returns RunWorkflowData | 工作流运行数据
3407
3462
  */ async create(params, options) {
3408
3463
  const apiUrl = '/v1/workflow/run';
@@ -3417,6 +3472,9 @@ class Runs extends APIResource {
3417
3472
  * @param params.bot_id - Optional The ID of the bot associated with the workflow. | 可选 与工作流关联的机器人 ID。
3418
3473
  * @param params.parameters - Optional Parameters for the workflow execution. | 可选 工作流执行的参数。
3419
3474
  * @param params.ext - Optional Additional information for the workflow execution. | 可选 工作流执行的附加信息。
3475
+ * @param params.execute_mode - Optional The mode in which to execute the workflow. | 可选 工作流执行的模式。
3476
+ * @param params.connector_id - Optional The ID of the connector to use for the workflow. | 可选 用于工作流的连接器 ID。
3477
+ * @param params.app_id - Optional The ID of the app. | 可选 要进行会话聊天的 App ID
3420
3478
  * @returns Stream<WorkflowEvent, { id: string; event: string; data: string }> | 工作流事件流
3421
3479
  */ async *stream(params, options) {
3422
3480
  const apiUrl = '/v1/workflow/stream_run';
@@ -3450,9 +3508,46 @@ class WorkflowEvent {
3450
3508
  this.data = data;
3451
3509
  }
3452
3510
  }
3511
+ class WorkflowChat extends APIResource {
3512
+ /**
3513
+ * Execute a chat workflow. | 执行对话流
3514
+ * @docs en: https://www.coze.cn/docs/developer_guides/workflow_chat?_lang=en
3515
+ * @docs zh: https://www.coze.cn/docs/developer_guides/workflow_chat?_lang=zh
3516
+ * @param params.workflow_id - Required The ID of the workflow to chat with. | 必选 要对话的工作流 ID。
3517
+ * @param params.additional_messages - Required Array of messages for the chat. | 必选 对话的消息数组。
3518
+ * @param params.parameters - Required Parameters for the workflow execution. | 必选 工作流执行的参数。
3519
+ * @param params.app_id - Optional The ID of the app. | 可选 应用 ID。
3520
+ * @param params.bot_id - Optional The ID of the bot. | 可选 Bot ID。
3521
+ * @param params.conversation_id - Optional The ID of the conversation. | 可选 会话 ID。
3522
+ * @param params.ext - Optional Additional information for the chat. | 可选 对话的附加信息。
3523
+ * @returns AsyncGenerator<StreamChatData> | 对话数据流
3524
+ */ async *stream(params, options) {
3525
+ const apiUrl = '/v1/workflows/chat';
3526
+ const payload = {
3527
+ ...params,
3528
+ additional_messages: handleAdditionalMessages(params.additional_messages)
3529
+ };
3530
+ const result = await this._client.post(apiUrl, payload, true, options);
3531
+ for await (const message of result)if (message.event === chat_ChatEventType.DONE) {
3532
+ const ret = {
3533
+ event: message.event,
3534
+ data: '[DONE]'
3535
+ };
3536
+ yield ret;
3537
+ } else try {
3538
+ const ret = {
3539
+ event: message.event,
3540
+ data: JSON.parse(message.data)
3541
+ };
3542
+ yield ret;
3543
+ } catch (error) {
3544
+ throw new CozeError(`Could not parse message into JSON:${message.data}`);
3545
+ }
3546
+ }
3547
+ }
3453
3548
  class Workflows extends APIResource {
3454
3549
  constructor(...args){
3455
- super(...args), this.runs = new Runs(this._client);
3550
+ super(...args), this.runs = new Runs(this._client), this.chat = new WorkflowChat(this._client);
3456
3551
  }
3457
3552
  }
3458
3553
  class WorkSpaces extends APIResource {
@@ -3476,6 +3571,8 @@ const documents_headers = {
3476
3571
  };
3477
3572
  class Documents extends APIResource {
3478
3573
  /**
3574
+ * @deprecated The method is deprecated and will be removed in a future version. Please use 'client.datasets.documents.list' instead.
3575
+ *
3479
3576
  * View the file list of a specified knowledge base, which includes lists of documents, spreadsheets, or images.
3480
3577
  * | 调用接口查看指定知识库的内容列表,即文件、表格或图像列表。
3481
3578
  * @docs en: https://www.coze.com/docs/developer_guides/list_knowledge_files?_lang=en
@@ -3486,12 +3583,14 @@ class Documents extends APIResource {
3486
3583
  * @returns ListDocumentData | 知识库文件列表
3487
3584
  */ list(params, options) {
3488
3585
  const apiUrl = '/open_api/knowledge/document/list';
3489
- const response = this._client.get(apiUrl, params, false, esm_mergeConfig(options, {
3586
+ const response = this._client.get(apiUrl, params, false, mergeConfig(options, {
3490
3587
  headers: documents_headers
3491
3588
  }));
3492
3589
  return response;
3493
3590
  }
3494
3591
  /**
3592
+ * @deprecated The method is deprecated and will be removed in a future version. Please use 'client.datasets.documents.create' instead.
3593
+ *
3495
3594
  * Upload files to the specific knowledge. | 调用此接口向指定知识库中上传文件。
3496
3595
  * @docs en: https://www.coze.com/docs/developer_guides/create_knowledge_files?_lang=en
3497
3596
  * @docs zh: https://www.coze.cn/docs/developer_guides/create_knowledge_files?_lang=zh
@@ -3502,12 +3601,14 @@ class Documents extends APIResource {
3502
3601
  * @returns DocumentInfo[] | 已上传文件的基本信息
3503
3602
  */ async create(params, options) {
3504
3603
  const apiUrl = '/open_api/knowledge/document/create';
3505
- const response = await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3604
+ const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
3506
3605
  headers: documents_headers
3507
3606
  }));
3508
3607
  return response.document_infos;
3509
3608
  }
3510
3609
  /**
3610
+ * @deprecated The method is deprecated and will be removed in a future version. Please use 'client.datasets.documents.delete' instead.
3611
+ *
3511
3612
  * Delete text, images, sheets, and other files in the knowledge base, supporting batch deletion.
3512
3613
  * | 删除知识库中的文本、图像、表格等文件,支持批量删除。
3513
3614
  * @docs en: https://www.coze.com/docs/developer_guides/delete_knowledge_files?_lang=en
@@ -3516,11 +3617,13 @@ class Documents extends APIResource {
3516
3617
  * @returns void | 无返回
3517
3618
  */ async delete(params, options) {
3518
3619
  const apiUrl = '/open_api/knowledge/document/delete';
3519
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3620
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3520
3621
  headers: documents_headers
3521
3622
  }));
3522
3623
  }
3523
3624
  /**
3625
+ * @deprecated The method is deprecated and will be removed in a future version. Please use 'client.datasets.documents.update' instead.
3626
+ *
3524
3627
  * Modify the knowledge base file name and update strategy. | 调用接口修改知识库文件名称和更新策略。
3525
3628
  * @docs en: https://www.coze.com/docs/developer_guides/modify_knowledge_files?_lang=en
3526
3629
  * @docs zh: https://www.coze.cn/docs/developer_guides/modify_knowledge_files?_lang=zh
@@ -3530,14 +3633,86 @@ class Documents extends APIResource {
3530
3633
  * @returns void | 无返回
3531
3634
  */ async update(params, options) {
3532
3635
  const apiUrl = '/open_api/knowledge/document/update';
3533
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3636
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3534
3637
  headers: documents_headers
3535
3638
  }));
3536
3639
  }
3537
3640
  }
3538
3641
  class Knowledge extends APIResource {
3539
3642
  constructor(...args){
3540
- super(...args), this.documents = new Documents(this._client);
3643
+ super(...args), /**
3644
+ * @deprecated
3645
+ */ this.documents = new Documents(this._client);
3646
+ }
3647
+ }
3648
+ // Required header for knowledge APIs
3649
+ const documents_documents_headers = {
3650
+ 'agw-js-conv': 'str'
3651
+ };
3652
+ class documents_Documents extends APIResource {
3653
+ /**
3654
+ * View the file list of a specified knowledge base, which includes lists of documents, spreadsheets, or images.
3655
+ * | 调用接口查看指定知识库的内容列表,即文件、表格或图像列表。
3656
+ * @docs en: https://www.coze.com/docs/developer_guides/list_knowledge_files?_lang=en
3657
+ * @docs zh: https://www.coze.cn/docs/developer_guides/list_knowledge_files?_lang=zh
3658
+ * @param params.dataset_id - Required The ID of the knowledge base. | 必选 待查看文件的知识库 ID。
3659
+ * @param params.page - Optional The page number for paginated queries. Default is 1. | 可选 分页查询时的页码。默认为 1。
3660
+ * @param params.page_size - Optional The size of pagination. Default is 10. | 可选 分页大小。默认为 10。
3661
+ * @returns ListDocumentData | 知识库文件列表
3662
+ */ list(params, options) {
3663
+ const apiUrl = '/open_api/knowledge/document/list';
3664
+ const response = this._client.get(apiUrl, params, false, mergeConfig(options, {
3665
+ headers: documents_documents_headers
3666
+ }));
3667
+ return response;
3668
+ }
3669
+ /**
3670
+ * Upload files to the specific knowledge. | 调用此接口向指定知识库中上传文件。
3671
+ * @docs en: https://www.coze.com/docs/developer_guides/create_knowledge_files?_lang=en
3672
+ * @docs zh: https://www.coze.cn/docs/developer_guides/create_knowledge_files?_lang=zh
3673
+ * @param params.dataset_id - Required The ID of the knowledge. | 必选 知识库 ID。
3674
+ * @param params.document_bases - Required The metadata information of the files awaiting upload. | 必选 待上传文件的元数据信息。
3675
+ * @param params.chunk_strategy - Required when uploading files to a new knowledge for the first time. Chunk strategy.
3676
+ * | 向新知识库首次上传文件时必选 分段规则。
3677
+ * @returns DocumentInfo[] | 已上传文件的基本信息
3678
+ */ async create(params, options) {
3679
+ const apiUrl = '/open_api/knowledge/document/create';
3680
+ const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
3681
+ headers: documents_documents_headers
3682
+ }));
3683
+ return response.document_infos;
3684
+ }
3685
+ /**
3686
+ * Delete text, images, sheets, and other files in the knowledge base, supporting batch deletion.
3687
+ * | 删除知识库中的文本、图像、表格等文件,支持批量删除。
3688
+ * @docs en: https://www.coze.com/docs/developer_guides/delete_knowledge_files?_lang=en
3689
+ * @docs zh: https://www.coze.cn/docs/developer_guides/delete_knowledge_files?_lang=zh
3690
+ * @param params.document_ids - Required The list of knowledge base files to be deleted. | 必选 待删除的文件 ID。
3691
+ * @returns void | 无返回
3692
+ */ async delete(params, options) {
3693
+ const apiUrl = '/open_api/knowledge/document/delete';
3694
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3695
+ headers: documents_documents_headers
3696
+ }));
3697
+ }
3698
+ /**
3699
+ * Modify the knowledge base file name and update strategy. | 调用接口修改知识库文件名称和更新策略。
3700
+ * @docs en: https://www.coze.com/docs/developer_guides/modify_knowledge_files?_lang=en
3701
+ * @docs zh: https://www.coze.cn/docs/developer_guides/modify_knowledge_files?_lang=zh
3702
+ * @param params.document_id - Required The ID of the knowledge base file. | 必选 待修改的知识库文件 ID。
3703
+ * @param params.document_name - Optional The new name of the knowledge base file. | 可选 知识库文件的新名称。
3704
+ * @param params.update_rule - Optional The update strategy for online web pages. | 可选 在线网页更新策略。
3705
+ * @returns void | 无返回
3706
+ */ async update(params, options) {
3707
+ const apiUrl = '/open_api/knowledge/document/update';
3708
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3709
+ headers: documents_documents_headers
3710
+ }));
3711
+ }
3712
+ }
3713
+ class Datasets extends APIResource {
3714
+ constructor(...args){
3715
+ super(...args), this.documents = new documents_Documents(this._client);
3541
3716
  }
3542
3717
  }
3543
3718
  class Voices extends APIResource {
@@ -3594,7 +3769,7 @@ class Speech extends APIResource {
3594
3769
  * @returns Speech synthesis data
3595
3770
  */ async create(params, options) {
3596
3771
  const apiUrl = '/v1/audio/speech';
3597
- const response = await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3772
+ const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
3598
3773
  responseType: 'arraybuffer'
3599
3774
  }));
3600
3775
  return response;
@@ -3607,23 +3782,26 @@ class Rooms extends APIResource {
3607
3782
  return response.data;
3608
3783
  }
3609
3784
  }
3610
- class esm_Audio extends APIResource {
3785
+ class audio_Audio extends APIResource {
3611
3786
  constructor(...args){
3612
3787
  super(...args), this.rooms = new Rooms(this._client), this.voices = new Voices(this._client), this.speech = new Speech(this._client);
3613
3788
  }
3614
3789
  }
3615
- var package_namespaceObject = JSON.parse('{"name":"@coze/api","version":"1.0.11","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
3616
- const { version: esm_version } = package_namespaceObject;
3790
+ // EXTERNAL MODULE: os (ignored)
3791
+ var os_ignored_ = __webpack_require__("?9050");
3792
+ var os_ignored_default = /*#__PURE__*/ __webpack_require__.n(os_ignored_);
3793
+ var package_namespaceObject = JSON.parse('{"name":"@coze/api","version":"1.0.15-beta.1","description":"Official Coze Node.js SDK for seamless AI integration into your applications | 扣子官方 Node.js SDK,助您轻松集成 AI 能力到应用中","keywords":["coze","ai","nodejs","sdk","chatbot","typescript"],"homepage":"https://github.com/coze-dev/coze-js/tree/main/packages/coze-js","bugs":{"url":"https://github.com/coze-dev/coze-js/issues"},"repository":{"type":"git","url":"https://github.com/coze-dev/coze-js.git","directory":"packages/coze-js"},"license":"MIT","author":"Leeight <leeight@gmail.com>","type":"module","main":"src/index.ts","browser":{"crypto":false,"os":false,"jsonwebtoken":false},"types":"src/index.ts","files":["dist","LICENSE","README.md"],"scripts":{"build":"rm -rf dist && rslib build","format":"prettier --write .","lint":"eslint ./ --cache --quiet","start":"rm -rf dist && rslib build -w","test":"vitest","test:cov":"vitest --coverage --run"},"dependencies":{"jsonwebtoken":"^9.0.2"},"devDependencies":{"@coze-infra/eslint-config":"workspace:*","@coze-infra/ts-config":"workspace:*","@coze-infra/vitest-config":"workspace:*","@rslib/core":"0.0.18","@swc/core":"^1.3.14","@types/jsonwebtoken":"^9.0.0","@types/node":"^20","@types/uuid":"^9.0.1","@types/whatwg-fetch":"^0.0.33","@vitest/coverage-v8":"~2.1.4","axios":"^1.7.7","typescript":"^5.5.3","vitest":"~2.1.4"},"peerDependencies":{"axios":"^1.7.1"},"cozePublishConfig":{"exports":{".":{"require":"./dist/cjs/index.cjs","import":"./dist/esm/index.js","types":"./dist/types/index.d.ts"}},"main":"dist/cjs/index.cjs","module":"dist/esm/index.js","types":"dist/types/index.d.ts"}}'); // CONCATENATED MODULE: ../coze-js/src/version.ts
3794
+ const { version: version_version } = package_namespaceObject;
3617
3795
  const getEnv = ()=>{
3618
3796
  const nodeVersion = process.version.slice(1); // Remove 'v' prefix
3619
3797
  const { platform } = process;
3620
3798
  let osName = platform.toLowerCase();
3621
- let osVersion = os_ignored_.release();
3799
+ let osVersion = os_ignored_default().release();
3622
3800
  if ('darwin' === platform) {
3623
3801
  osName = 'macos';
3624
3802
  // Try to parse the macOS version
3625
3803
  try {
3626
- const darwinVersion = os_ignored_.release().split('.');
3804
+ const darwinVersion = os_ignored_default().release().split('.');
3627
3805
  if (darwinVersion.length >= 2) {
3628
3806
  const majorVersion = parseInt(darwinVersion[0], 10);
3629
3807
  if (!isNaN(majorVersion) && majorVersion >= 9) {
@@ -3636,10 +3814,10 @@ const getEnv = ()=>{
3636
3814
  }
3637
3815
  } else if ('win32' === platform) {
3638
3816
  osName = 'windows';
3639
- osVersion = os_ignored_.release();
3817
+ osVersion = os_ignored_default().release();
3640
3818
  } else if ('linux' === platform) {
3641
3819
  osName = 'linux';
3642
- osVersion = os_ignored_.release();
3820
+ osVersion = os_ignored_default().release();
3643
3821
  }
3644
3822
  return {
3645
3823
  osName,
@@ -3649,12 +3827,12 @@ const getEnv = ()=>{
3649
3827
  };
3650
3828
  const getUserAgent = ()=>{
3651
3829
  const { nodeVersion, osName, osVersion } = getEnv();
3652
- return `coze-js/${esm_version} node/${nodeVersion} ${osName}/${osVersion}`.toLowerCase();
3830
+ return `coze-js/${version_version} node/${nodeVersion} ${osName}/${osVersion}`.toLowerCase();
3653
3831
  };
3654
3832
  const getNodeClientUserAgent = ()=>{
3655
3833
  const { osVersion, nodeVersion, osName } = getEnv();
3656
3834
  const ua = {
3657
- version: esm_version,
3835
+ version: version_version,
3658
3836
  lang: 'node',
3659
3837
  lang_version: nodeVersion,
3660
3838
  os_name: osName,
@@ -3662,37 +3840,44 @@ const getNodeClientUserAgent = ()=>{
3662
3840
  };
3663
3841
  return JSON.stringify(ua);
3664
3842
  };
3665
- /* eslint-disable @typescript-eslint/no-explicit-any */ const esm_handleError = (error)=>{
3843
+ /* eslint-disable @typescript-eslint/no-explicit-any */ const fetcher_handleError = (error)=>{
3666
3844
  if (!error.isAxiosError && (!error.code || !error.message)) return new CozeError(`Unexpected error: ${error.message}`);
3667
3845
  if ('ECONNABORTED' === error.code && error.message.includes('timeout') || 'ETIMEDOUT' === error.code) {
3668
3846
  var _error_response;
3669
3847
  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);
3670
3848
  }
3671
3849
  if ('ERR_CANCELED' === error.code) return new APIUserAbortError(error.message);
3672
- var _error_response1, _error_response2, _error_response3;
3673
- 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);
3850
+ else {
3851
+ var _error_response1, _error_response2, _error_response3;
3852
+ return error_APIError.generate((null === (_error_response1 = error.response) || void 0 === _error_response1 ? void 0 : _error_response1.status) || 500, null === (_error_response2 = error.response) || void 0 === _error_response2 ? void 0 : _error_response2.data, error.message, null === (_error_response3 = error.response) || void 0 === _error_response3 ? void 0 : _error_response3.headers);
3853
+ }
3674
3854
  };
3675
3855
  async function fetchAPI(url) {
3676
3856
  let options = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
3677
3857
  const axiosInstance = options.axiosInstance || lib_axios;
3858
+ // Add version check for streaming requests
3859
+ if (options.isStreaming && isAxiosStatic(axiosInstance)) {
3860
+ const axiosVersion = axiosInstance.VERSION || lib_axios.VERSION;
3861
+ if (!axiosVersion || compareVersions(axiosVersion, '1.7.1') < 0) throw new CozeError('Streaming requests require axios version 1.7.1 or higher. Please upgrade your axios version.');
3862
+ }
3678
3863
  const response = await axiosInstance({
3679
3864
  url,
3680
3865
  responseType: options.isStreaming ? 'stream' : 'json',
3681
3866
  adapter: options.isStreaming ? 'fetch' : void 0,
3682
3867
  ...options
3683
3868
  }).catch((error)=>{
3684
- throw esm_handleError(error);
3869
+ throw fetcher_handleError(error);
3685
3870
  });
3686
3871
  return {
3687
3872
  async *stream () {
3688
3873
  try {
3689
3874
  const stream = response.data;
3690
- const reader = stream[Symbol.asyncIterator]();
3875
+ const reader = stream[Symbol.asyncIterator] ? stream[Symbol.asyncIterator]() : stream.getReader();
3691
3876
  const decoder = new TextDecoder();
3692
3877
  const fieldValues = {};
3693
3878
  let buffer = '';
3694
3879
  while(true){
3695
- const { done, value } = await reader.next();
3880
+ const { done, value } = await (reader.next ? reader.next() : reader.read());
3696
3881
  if (done) {
3697
3882
  if (buffer) {
3698
3883
  // If the stream ends without a newline, it means an error occurred
@@ -3719,26 +3904,46 @@ async function fetchAPI(url) {
3719
3904
  buffer = lines[lines.length - 1]; // Keep the last incomplete line in the buffer
3720
3905
  }
3721
3906
  } catch (error) {
3722
- esm_handleError(error);
3907
+ fetcher_handleError(error);
3723
3908
  }
3724
3909
  },
3725
3910
  json: ()=>response.data,
3726
3911
  response
3727
3912
  };
3728
3913
  }
3914
+ // Add version comparison utility
3915
+ function compareVersions(v1, v2) {
3916
+ const v1Parts = v1.split('.').map(Number);
3917
+ const v2Parts = v2.split('.').map(Number);
3918
+ for(let i = 0; i < 3; i++){
3919
+ const part1 = v1Parts[i] || 0;
3920
+ const part2 = v2Parts[i] || 0;
3921
+ if (part1 > part2) return 1;
3922
+ if (part1 < part2) return -1;
3923
+ }
3924
+ return 0;
3925
+ }
3926
+ function isAxiosStatic(instance) {
3927
+ return !!(null == instance ? void 0 : instance.Axios);
3928
+ }
3729
3929
  /**
3730
3930
  * default coze base URL is api.coze.com
3731
- */ const COZE_COM_BASE_URL = 'https://api.coze.com';
3732
- /* eslint-disable max-params */ class APIClient {
3733
- buildOptions(method, body, options) {
3931
+ */ const constant_COZE_COM_BASE_URL = 'https://api.coze.com';
3932
+ /* eslint-disable max-params */ class core_APIClient {
3933
+ async getToken() {
3934
+ if ('function' == typeof this.token) return await this.token();
3935
+ return this.token;
3936
+ }
3937
+ async buildOptions(method, body, options) {
3938
+ const token = await this.getToken();
3734
3939
  const headers = {
3735
- authorization: `Bearer ${this.token}`
3940
+ authorization: `Bearer ${token}`
3736
3941
  };
3737
- if (!isBrowser()) {
3942
+ if (!utils_isBrowser()) {
3738
3943
  headers['User-Agent'] = getUserAgent();
3739
3944
  headers['X-Coze-Client-User-Agent'] = getNodeClientUserAgent();
3740
3945
  }
3741
- const config = esm_mergeConfig(this.axiosOptions, options, {
3946
+ const config = mergeConfig(this.axiosOptions, options, {
3742
3947
  headers
3743
3948
  });
3744
3949
  config.method = method;
@@ -3747,19 +3952,22 @@ async function fetchAPI(url) {
3747
3952
  }
3748
3953
  async makeRequest(apiUrl, method, body, isStream, options) {
3749
3954
  const fullUrl = `${this.baseURL}${apiUrl}`;
3750
- const fetchOptions = this.buildOptions(method, body, options);
3955
+ const fetchOptions = await this.buildOptions(method, body, options);
3751
3956
  fetchOptions.isStreaming = isStream;
3957
+ fetchOptions.axiosInstance = this.axiosInstance;
3752
3958
  this.debugLog(`--- request url: ${fullUrl}`);
3753
3959
  this.debugLog('--- request options:', fetchOptions);
3754
3960
  const { response, stream, json } = await fetchAPI(fullUrl, fetchOptions);
3755
3961
  this.debugLog(`--- response status: ${response.status}`);
3756
3962
  this.debugLog('--- response headers: ', response.headers);
3757
- const contentType = response.headers['content-type'];
3963
+ var _response_headers;
3964
+ // Taro use `header`
3965
+ const contentType = (null !== (_response_headers = response.headers) && void 0 !== _response_headers ? _response_headers : response.header)['content-type'];
3758
3966
  if (isStream) {
3759
3967
  if (contentType && contentType.includes('application/json')) {
3760
3968
  const result = await json();
3761
3969
  const { code, msg } = result;
3762
- if (0 !== code && void 0 !== code) throw APIError.generate(response.status, result, msg, response.headers);
3970
+ if (0 !== code && void 0 !== code) throw error_APIError.generate(response.status, result, msg, response.headers);
3763
3971
  }
3764
3972
  return stream();
3765
3973
  }
@@ -3767,7 +3975,7 @@ async function fetchAPI(url) {
3767
3975
  {
3768
3976
  const result = await json();
3769
3977
  const { code, msg } = result;
3770
- if (0 !== code && void 0 !== code) throw APIError.generate(response.status, result, msg, response.headers);
3978
+ if (0 !== code && void 0 !== code) throw error_APIError.generate(response.status, result, msg, response.headers);
3771
3979
  return result;
3772
3980
  }
3773
3981
  }
@@ -3799,28 +4007,35 @@ async function fetchAPI(url) {
3799
4007
  }
3800
4008
  constructor(config){
3801
4009
  this._config = config;
3802
- this.baseURL = config.baseURL || COZE_COM_BASE_URL;
4010
+ this.baseURL = config.baseURL || constant_COZE_COM_BASE_URL;
3803
4011
  this.token = config.token;
3804
4012
  this.axiosOptions = config.axiosOptions || {};
4013
+ this.axiosInstance = config.axiosInstance;
3805
4014
  this.debug = config.debug || false;
3806
4015
  this.allowPersonalAccessTokenInBrowser = config.allowPersonalAccessTokenInBrowser || false;
3807
4016
  this.headers = config.headers;
3808
- if (isBrowser() && 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');
3809
- }
3810
- }
3811
- APIClient.APIError = APIError;
3812
- APIClient.BadRequestError = BadRequestError;
3813
- APIClient.AuthenticationError = AuthenticationError;
3814
- APIClient.PermissionDeniedError = PermissionDeniedError;
3815
- APIClient.NotFoundError = NotFoundError;
3816
- APIClient.RateLimitError = RateLimitError;
3817
- APIClient.InternalServerError = InternalServerError;
3818
- APIClient.GatewayError = GatewayError;
3819
- APIClient.TimeoutError = TimeoutError;
3820
- APIClient.UserAbortError = APIUserAbortError;
3821
- class CozeAPI extends APIClient {
4017
+ if (utils_isBrowser() && 'function' != typeof this.token && isPersonalAccessToken(this.token) && !this.allowPersonalAccessTokenInBrowser) throw new CozeError('Browser environments do not support authentication using Personal Access Token (PAT) by default.\nas it may expose secret API keys. \n\nPlease use OAuth2.0 authentication mechanism. see:\nhttps://www.coze.com/docs/developer_guides/oauth_apps?_lang=en \n\nIf you need to force use, please set the `allowPersonalAccessTokenInBrowser` option to `true`. \n\ne.g new CozeAPI({ token, allowPersonalAccessTokenInBrowser: true });\n\n');
4018
+ }
4019
+ }
4020
+ core_APIClient.APIError = error_APIError;
4021
+ core_APIClient.BadRequestError = BadRequestError;
4022
+ core_APIClient.AuthenticationError = AuthenticationError;
4023
+ core_APIClient.PermissionDeniedError = PermissionDeniedError;
4024
+ core_APIClient.NotFoundError = NotFoundError;
4025
+ core_APIClient.RateLimitError = RateLimitError;
4026
+ core_APIClient.InternalServerError = InternalServerError;
4027
+ core_APIClient.GatewayError = GatewayError;
4028
+ core_APIClient.TimeoutError = TimeoutError;
4029
+ core_APIClient.UserAbortError = APIUserAbortError;
4030
+ // EXTERNAL MODULE: crypto (ignored)
4031
+ __webpack_require__("?666e");
4032
+ // EXTERNAL MODULE: jsonwebtoken (ignored)
4033
+ __webpack_require__("?79fd");
4034
+ class CozeAPI extends core_APIClient {
3822
4035
  constructor(...args){
3823
- super(...args), this.bots = new Bots(this), this.chat = new Chat(this), this.conversations = new Conversations(this), this.files = new Files(this), this.knowledge = new Knowledge(this), this.workflows = new Workflows(this), this.workspaces = new WorkSpaces(this), this.audio = new esm_Audio(this);
4036
+ super(...args), this.bots = new Bots(this), this.chat = new Chat(this), this.conversations = new Conversations(this), this.files = new Files(this), /**
4037
+ * @deprecated
4038
+ */ this.knowledge = new Knowledge(this), this.datasets = new Datasets(this), this.workflows = new Workflows(this), this.workspaces = new WorkSpaces(this), this.audio = new audio_Audio(this);
3824
4039
  }
3825
4040
  }
3826
4041
  /**
@@ -9052,7 +9267,7 @@ var setPrototypeOf = setPrototypeOf$2, _Object$setPrototypeOf = getDefaultExport
9052
9267
  }, stringPad = {
9053
9268
  start: createMethod(!1),
9054
9269
  end: createMethod(!0)
9055
- }, userAgent = engineUserAgent, stringPadWebkitBug = /Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(userAgent), $$F = _export, $padEnd = stringPad.end, WEBKIT_BUG$1 = stringPadWebkitBug;
9270
+ }, 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;
9056
9271
  $$F({
9057
9272
  target: "String",
9058
9273
  proto: !0,
@@ -12625,8 +12840,8 @@ function getBrowser() {
12625
12840
  }
12626
12841
  var _navigator$userAgent$, isFirefox = "mozilla" === getBrowser(), isSafari = "safari" === getBrowser(), isChrome = "chrome-stable" === getBrowser(), isCriOS = !isSSR2() && /CriOS/i.test(userAgentString), isEdgeForDesktop = !isSSR2() && /Edg\//i.test(userAgentString), isEdgeForAndroid = !isSSR2() && /EdgA/i.test(userAgentString), isEdgeForIOS = !isSSR2() && /EdgiOS/i.test(userAgentString), isEdge = isEdgeForDesktop || isEdgeForAndroid || isEdgeForIOS, isDingTalk = !isSSR2() && /DingTalk/i.test(navigator.userAgent), isOpera = !isSSR2() && /OPR\//.test(navigator.userAgent), isIPad = !isSSR2() && (!!/(iPad)/i.exec(userAgentString) || /Macintosh/i.test(userAgentString) && "ontouchend" in document), isMac = !isSSR2() && /Macintosh/i.test(userAgentString), isWeChat = !isSSR2() && /MicroMessenger/i.test(userAgentString), isMobile = !isSSR2() && _includesInstanceProperty(_context$3 = userAgentString.toLowerCase()).call(_context$3, "mobile"), isIOS = !isSSR2() && !!/(iPhone|iPad|iPod)/i.exec(userAgentString), isAndroid = !isSSR2() && /Android/i.test(userAgentString), isWindows = !isSSR2() && /Windows/i.test(userAgentString), isOpenHarmony = !isSSR2() && /OpenHarmony/i.test(userAgentString), sv = 0, sv2 = "0", index_esm_min_v = !isSSR2() && (null === (_userAgentString$matc = userAgentString.match(/version\/(\d+)/i)) || void 0 === _userAgentString$matc ? void 0 : _userAgentString$matc[1]);
12627
12842
  isSafari && index_esm_min_v && (sv = Number(index_esm_min_v), sv2 = null === (_navigator$userAgent$ = navigator.userAgent.match(/version\/(\d+\.\d+)/i)) || void 0 === _navigator$userAgent$ ? void 0 : _navigator$userAgent$[1]);
12628
- var v2 = !isSSR2() && (null === (_userAgentString$matc2 = userAgentString.match(/Firefox\/(\d+)/i)) || void 0 === _userAgentString$matc2 ? void 0 : _userAgentString$matc2[1]);
12629
- isFirefox && v2 && (sv = Number(v2));
12843
+ var index_esm_min_v2 = !isSSR2() && (null === (_userAgentString$matc2 = userAgentString.match(/Firefox\/(\d+)/i)) || void 0 === _userAgentString$matc2 ? void 0 : _userAgentString$matc2[1]);
12844
+ isFirefox && index_esm_min_v2 && (sv = Number(index_esm_min_v2));
12630
12845
  var safariVersion = sv, firefoxVersion = sv, safariMinorVersion = sv2, iOSVersion = null !== (_ref = !isSSR2() && (null === (_userAgentString$matc3 = userAgentString.match(/ ([\d_]+) like Mac OS X/i)) || void 0 === _userAgentString$matc3 || null === (_userAgentString$matc4 = _userAgentString$matc3[1]) || void 0 === _userAgentString$matc4 ? void 0 : _mapInstanceProperty(_context2 = _userAgentString$matc4.split("_")).call(_context2, function(e) {
12631
12846
  return _parseInt$7(e);
12632
12847
  }))) && void 0 !== _ref ? _ref : [], cv = 0, cvs = !isSSR2() && (null === (_userAgentString$matc5 = userAgentString.match(/Chrome\/(\d+)/i)) || void 0 === _userAgentString$matc5 ? void 0 : _userAgentString$matc5[1]);
@@ -38205,11 +38420,12 @@ var VERTC = _createClass(function e() {
38205
38420
  + * @param milliseconds The time to sleep in milliseconds
38206
38421
  + * @throws {Error} If milliseconds is negative
38207
38422
  + * @returns Promise that resolves after the specified duration
38208
- + */ const utils_sleep = (milliseconds)=>{
38423
+ + */ const src_utils_sleep = (milliseconds)=>{
38209
38424
  if (milliseconds < 0) throw new Error('Sleep duration must be non-negative');
38210
38425
  return new Promise((resolve)=>setTimeout(resolve, milliseconds));
38211
38426
  };
38212
38427
  /**
38428
+ * @deprecated use checkDevicePermission instead
38213
38429
  * Check microphone permission,return boolean
38214
38430
  */ const checkPermission = async function() {
38215
38431
  let { audio = true, video = false } = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
@@ -38224,22 +38440,32 @@ var VERTC = _createClass(function e() {
38224
38440
  return false;
38225
38441
  }
38226
38442
  };
38443
+ const checkDevicePermission = async function() {
38444
+ let checkVideo = arguments.length > 0 && void 0 !== arguments[0] && arguments[0];
38445
+ return await index_esm_min_index.enableDevices({
38446
+ audio: true,
38447
+ video: checkVideo
38448
+ });
38449
+ };
38227
38450
  /**
38228
38451
  * Get audio devices
38229
38452
  * @returns Promise<AudioDevices> Object containing arrays of audio input and output devices
38230
- */ const getAudioDevices = async ()=>{
38231
- const devices = await index_esm_min_index.enumerateDevices();
38453
+ */ const getAudioDevices = async function() {
38454
+ let { video = false } = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
38455
+ let devices = [];
38456
+ devices = video ? await index_esm_min_index.enumerateDevices() : await [
38457
+ ...await index_esm_min_index.enumerateAudioCaptureDevices(),
38458
+ ...await index_esm_min_index.enumerateAudioPlaybackDevices()
38459
+ ];
38232
38460
  if (!(null == devices ? void 0 : devices.length)) return {
38233
38461
  audioInputs: [],
38234
38462
  audioOutputs: [],
38235
- videoInputs: [],
38236
- videoOutputs: []
38463
+ videoInputs: []
38237
38464
  };
38238
38465
  return {
38239
38466
  audioInputs: devices.filter((i)=>i.deviceId && 'audioinput' === i.kind),
38240
38467
  audioOutputs: devices.filter((i)=>i.deviceId && 'audiooutput' === i.kind),
38241
- videoInputs: devices.filter((i)=>i.deviceId && 'videoinput' === i.kind),
38242
- videoOutputs: devices.filter((i)=>i.deviceId && 'videooutput' === i.kind)
38468
+ videoInputs: devices.filter((i)=>i.deviceId && 'videoinput' === i.kind)
38243
38469
  };
38244
38470
  };
38245
38471
  var error_RealtimeError = /*#__PURE__*/ function(RealtimeError) {
@@ -38342,6 +38568,34 @@ var event_handler_EventNames = /*#__PURE__*/ function(EventNames) {
38342
38568
  * en: Bot left
38343
38569
  * zh: Bot 离开
38344
38570
  */ EventNames["BOT_LEAVE"] = "server.bot.leave";
38571
+ /**
38572
+ * en: Audio speech started
38573
+ * zh: 开始说话
38574
+ */ EventNames["AUDIO_AGENT_SPEECH_STARTED"] = "server.audio.agent.speech_started";
38575
+ /**
38576
+ * en: Audio speech stopped
38577
+ * zh: 停止说话
38578
+ */ EventNames["AUDIO_SPEECH_STOPPED"] = "server.audio.speech_stopped";
38579
+ /**
38580
+ * en: Server error
38581
+ * zh: 服务端错误
38582
+ */ EventNames["SERVER_ERROR"] = "server.error";
38583
+ /**
38584
+ * en: User speech started
38585
+ * zh: 用户开始说话
38586
+ */ EventNames["AUDIO_USER_SPEECH_STARTED"] = "server.audio.user.speech_started";
38587
+ /**
38588
+ * en: User speech stopped
38589
+ * zh: 用户停止说话
38590
+ */ EventNames["AUDIO_USER_SPEECH_STOPPED"] = "server.audio.user.speech_stopped";
38591
+ /**
38592
+ * en: User successfully enters the room
38593
+ * zh: 用户成功进入房间后,会收到该事件
38594
+ */ EventNames["SESSION_CREATED"] = "server.session.created";
38595
+ /**
38596
+ * en: Session updated
38597
+ * zh: 会话更新
38598
+ */ EventNames["SESSION_UPDATE"] = "server.session.update";
38345
38599
  return EventNames;
38346
38600
  }({});
38347
38601
  class RealtimeEventHandler {
@@ -38372,7 +38626,8 @@ class RealtimeEventHandler {
38372
38626
  }
38373
38627
  }
38374
38628
  dispatch(eventName, event) {
38375
- this._log(`dispatch ${eventName} event`);
38629
+ let consoleLog = !(arguments.length > 2) || void 0 === arguments[2] || arguments[2];
38630
+ if (consoleLog) this._log(`dispatch ${eventName} event`);
38376
38631
  const handlers = (this.eventHandlers[eventName] || []).slice();
38377
38632
  this._dispatchToHandlers(eventName, event, handlers);
38378
38633
  const allHandlers = (this.eventHandlers["realtime.event"] || []).slice();
@@ -41641,7 +41896,7 @@ class EngineClient extends RealtimeEventHandler {
41641
41896
  this.engine.on(index_esm_min_index.events.onUserJoined, this.handleUserJoin);
41642
41897
  this.engine.on(index_esm_min_index.events.onUserLeave, this.handleUserLeave);
41643
41898
  this.engine.on(index_esm_min_index.events.onError, this.handleEventError);
41644
- this.engine.on(index_esm_min_index.events.onPlayerEvent, this.handlePlayerEvent);
41899
+ if (this._isSupportVideo) this.engine.on(index_esm_min_index.events.onPlayerEvent, this.handlePlayerEvent);
41645
41900
  if (this._debug) {
41646
41901
  this.engine.on(index_esm_min_index.events.onLocalAudioPropertiesReport, this.handleLocalAudioPropertiesReport);
41647
41902
  this.engine.on(index_esm_min_index.events.onRemoteAudioPropertiesReport, this.handleRemoteAudioPropertiesReport);
@@ -41652,7 +41907,7 @@ class EngineClient extends RealtimeEventHandler {
41652
41907
  this.engine.off(index_esm_min_index.events.onUserJoined, this.handleUserJoin);
41653
41908
  this.engine.off(index_esm_min_index.events.onUserLeave, this.handleUserLeave);
41654
41909
  this.engine.off(index_esm_min_index.events.onError, this.handleEventError);
41655
- this.engine.off(index_esm_min_index.events.onPlayerEvent, this.handlePlayerEvent);
41910
+ if (this._isSupportVideo) this.engine.off(index_esm_min_index.events.onPlayerEvent, this.handlePlayerEvent);
41656
41911
  if (this._debug) {
41657
41912
  this.engine.off(index_esm_min_index.events.onLocalAudioPropertiesReport, this.handleLocalAudioPropertiesReport);
41658
41913
  this.engine.off(index_esm_min_index.events.onRemoteAudioPropertiesReport, this.handleRemoteAudioPropertiesReport);
@@ -41697,13 +41952,13 @@ class EngineClient extends RealtimeEventHandler {
41697
41952
  this.dispatch(event_handler_EventNames.PLAYER_EVENT, event);
41698
41953
  }
41699
41954
  async joinRoom(options) {
41700
- const { token, roomId, uid, audioMutedDefault, videoOnDefault } = options;
41955
+ const { token, roomId, uid, audioMutedDefault, videoOnDefault, isAutoSubscribeAudio } = options;
41701
41956
  try {
41702
41957
  await this.engine.joinRoom(token, roomId, {
41703
41958
  userId: uid
41704
41959
  }, {
41705
41960
  isAutoPublish: !audioMutedDefault,
41706
- isAutoSubscribeAudio: true,
41961
+ isAutoSubscribeAudio,
41707
41962
  isAutoSubscribeVideo: this._isSupportVideo && videoOnDefault
41708
41963
  });
41709
41964
  } catch (e) {
@@ -41717,14 +41972,18 @@ class EngineClient extends RealtimeEventHandler {
41717
41972
  await this.engine.startAudioCapture(deviceId);
41718
41973
  }
41719
41974
  async setAudioOutputDevice(deviceId) {
41720
- const devices = await getAudioDevices();
41975
+ const devices = await getAudioDevices({
41976
+ video: false
41977
+ });
41721
41978
  if (-1 === devices.audioOutputs.findIndex((i)=>i.deviceId === deviceId)) throw new RealtimeAPIError(error_RealtimeError.DEVICE_ACCESS_ERROR, `Audio output device not found: ${deviceId}`);
41722
41979
  await this.engine.setAudioPlaybackDevice(deviceId);
41723
41980
  }
41724
41981
  async createLocalStream(userId, videoConfig) {
41725
- const devices = await getAudioDevices();
41726
- if (!devices.audioInputs.length) throw new RealtimeAPIError(error_RealtimeError.DEVICE_ACCESS_ERROR, 'Failed to get devices');
41727
- if (this._isSupportVideo && !devices.videoInputs.length) throw new RealtimeAPIError(error_RealtimeError.DEVICE_ACCESS_ERROR, 'Failed to get devices');
41982
+ const devices = await getAudioDevices({
41983
+ video: this._isSupportVideo
41984
+ });
41985
+ if (!devices.audioInputs.length) throw new RealtimeAPIError(error_RealtimeError.DEVICE_ACCESS_ERROR, 'Failed to get audio devices');
41986
+ if (this._isSupportVideo && !devices.videoInputs.length) throw new RealtimeAPIError(error_RealtimeError.DEVICE_ACCESS_ERROR, 'Failed to get video devices');
41728
41987
  await this.engine.startAudioCapture(devices.audioInputs[0].deviceId);
41729
41988
  if (this._isSupportVideo && (null == videoConfig ? void 0 : videoConfig.videoOnDefault)) await this.engine.startVideoCapture(devices.videoInputs[0].deviceId);
41730
41989
  if (this._isSupportVideo) this.engine.setLocalVideoPlayer(StreamIndex$1.STREAM_INDEX_MAIN, {
@@ -41877,7 +42136,7 @@ class RealtimeClient extends RealtimeEventHandler {
41877
42136
  // Step3 bind engine events
41878
42137
  this._client.bindEngineEvents();
41879
42138
  this._client.on(event_handler_EventNames.ALL, (eventName, data)=>{
41880
- this.dispatch(eventName, data);
42139
+ this.dispatch(eventName, data, false);
41881
42140
  });
41882
42141
  if (this._config.suppressStationaryNoise) {
41883
42142
  await this._client.enableAudioNoiseReduction();
@@ -41888,14 +42147,15 @@ class RealtimeClient extends RealtimeEventHandler {
41888
42147
  this._client.changeAIAnsExtension(true);
41889
42148
  this.dispatch(event_handler_EventNames.SUPPRESS_NON_STATIONARY_NOISE, {});
41890
42149
  }
41891
- var _this__config_audioMutedDefault, _this__config_videoConfig_videoOnDefault;
42150
+ var _this__config_audioMutedDefault, _this__config_videoConfig_videoOnDefault, _this__config_isAutoSubscribeAudio;
41892
42151
  // Step4 join room
41893
42152
  await this._client.joinRoom({
41894
42153
  token: roomInfo.token,
41895
42154
  roomId: roomInfo.room_id,
41896
42155
  uid: roomInfo.uid,
41897
42156
  audioMutedDefault: null !== (_this__config_audioMutedDefault = this._config.audioMutedDefault) && void 0 !== _this__config_audioMutedDefault && _this__config_audioMutedDefault,
41898
- videoOnDefault: null === (_this__config_videoConfig_videoOnDefault = null === (_this__config_videoConfig = this._config.videoConfig) || void 0 === _this__config_videoConfig ? void 0 : _this__config_videoConfig.videoOnDefault) || void 0 === _this__config_videoConfig_videoOnDefault || _this__config_videoConfig_videoOnDefault
42157
+ videoOnDefault: null === (_this__config_videoConfig_videoOnDefault = null === (_this__config_videoConfig = this._config.videoConfig) || void 0 === _this__config_videoConfig ? void 0 : _this__config_videoConfig.videoOnDefault) || void 0 === _this__config_videoConfig_videoOnDefault || _this__config_videoConfig_videoOnDefault,
42158
+ isAutoSubscribeAudio: null === (_this__config_isAutoSubscribeAudio = this._config.isAutoSubscribeAudio) || void 0 === _this__config_isAutoSubscribeAudio || _this__config_isAutoSubscribeAudio
41899
42159
  });
41900
42160
  // Step5 create local stream
41901
42161
  await this._client.createLocalStream(roomInfo.uid, this._config.videoConfig);
@@ -41907,7 +42167,6 @@ class RealtimeClient extends RealtimeEventHandler {
41907
42167
  token: roomInfo.token,
41908
42168
  appId: roomInfo.app_id
41909
42169
  });
41910
- this._log('dispatch client.connected event');
41911
42170
  }
41912
42171
  /**
41913
42172
  * en: Interrupt the current conversation
@@ -41917,7 +42176,6 @@ class RealtimeClient extends RealtimeEventHandler {
41917
42176
  var _this__client;
41918
42177
  await (null === (_this__client = this._client) || void 0 === _this__client ? void 0 : _this__client.stop());
41919
42178
  this.dispatch(event_handler_EventNames.INTERRUPTED, {});
41920
- this._log('dispatch client.interrupted event');
41921
42179
  }
41922
42180
  /**
41923
42181
  * en: Disconnect from the current session
@@ -42039,6 +42297,7 @@ class RealtimeClient extends RealtimeEventHandler {
42039
42297
  * 可选,默认是否抑制静态噪声,默认值为 false。
42040
42298
  * @param config.suppressNonStationaryNoise - Optional, suppress non-stationary noise, defaults to false. |
42041
42299
  * 可选,默认是否抑制非静态噪声,默认值为 false。
42300
+ * @param config.isAutoSubscribeAudio - Optional, whether to automatically subscribe to bot reply audio streams, defaults to true. |
42042
42301
  */ constructor(config){
42043
42302
  super(config.debug), this._client = null, this.isConnected = false, this._isTestEnv = false, this._isSupportVideo = false;
42044
42303
  this._config = config;