@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.
package/dist/umd/index.js CHANGED
@@ -7,11 +7,11 @@
7
7
  })(self, ()=>(()=>{
8
8
  "use strict";
9
9
  var __webpack_modules__ = {
10
- "?de24": function() {
10
+ "?666e": function() {
11
11
  /* (ignored) */ },
12
- "?2a9f": function() {
12
+ "?79fd": function() {
13
13
  /* (ignored) */ },
14
- "?d039": function() {
14
+ "?9050": function() {
15
15
  /* (ignored) */ }
16
16
  };
17
17
  /************************************************************************/ // The module cache
@@ -30,7 +30,22 @@
30
30
  // Return the exports of the module
31
31
  return module1.exports;
32
32
  }
33
- /************************************************************************/ // webpack/runtime/define_property_getters
33
+ /************************************************************************/ // webpack/runtime/compat_get_default_export
34
+ (()=>{
35
+ // getDefaultExport function for compatibility with non-ESM modules
36
+ __webpack_require__.n = function(module1) {
37
+ var getter = module1 && module1.__esModule ? function() {
38
+ return module1['default'];
39
+ } : function() {
40
+ return module1;
41
+ };
42
+ __webpack_require__.d(getter, {
43
+ a: getter
44
+ });
45
+ return getter;
46
+ };
47
+ })();
48
+ // webpack/runtime/define_property_getters
34
49
  (()=>{
35
50
  __webpack_require__.d = function(exports1, definition) {
36
51
  for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
@@ -79,7 +94,7 @@
79
94
  EventNames: ()=>/* reexport */ event_handler_EventNames,
80
95
  RealtimeClient: ()=>/* binding */ RealtimeClient
81
96
  });
82
- // NAMESPACE OBJECT: ../../common/temp/default/node_modules/.pnpm/axios@1.7.7/node_modules/axios/lib/platform/common/utils.js
97
+ // NAMESPACE OBJECT: ../../common/temp/default/node_modules/.pnpm/axios@1.7.7_debug@4.3.7/node_modules/axios/lib/platform/common/utils.js
83
98
  var common_utils_namespaceObject = {};
84
99
  __webpack_require__.r(common_utils_namespaceObject);
85
100
  __webpack_require__.d(common_utils_namespaceObject, {
@@ -93,486 +108,1048 @@
93
108
  var src_utils_namespaceObject = {};
94
109
  __webpack_require__.r(src_utils_namespaceObject);
95
110
  __webpack_require__.d(src_utils_namespaceObject, {
111
+ checkDevicePermission: ()=>checkDevicePermission,
96
112
  checkPermission: ()=>checkPermission,
97
113
  getAudioDevices: ()=>getAudioDevices,
98
- sleep: ()=>utils_sleep
114
+ sleep: ()=>src_utils_sleep
99
115
  });
100
- function bind(fn, thisArg) {
101
- return function() {
102
- return fn.apply(thisArg, arguments);
103
- };
116
+ class APIResource {
117
+ constructor(client){
118
+ this._client = client;
119
+ }
104
120
  }
105
- // utils is a library of generic helper functions non-specific to axios
106
- const { toString: utils_toString } = Object.prototype;
107
- const { getPrototypeOf } = Object;
108
- const kindOf = ((cache)=>(thing)=>{
109
- const str = utils_toString.call(thing);
110
- return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
111
- })(Object.create(null));
112
- const kindOfTest = (type)=>{
113
- type = type.toLowerCase();
114
- return (thing)=>kindOf(thing) === type;
115
- };
116
- const typeOfTest = (type)=>(thing)=>typeof thing === type;
117
- /**
118
- * Determine if a value is an Array
119
- *
120
- * @param {Object} val The value to test
121
- *
122
- * @returns {boolean} True if value is an Array, otherwise false
123
- */ const { isArray } = Array;
124
- /**
125
- * Determine if a value is undefined
126
- *
127
- * @param {*} val The value to test
128
- *
129
- * @returns {boolean} True if the value is undefined, otherwise false
130
- */ const isUndefined = typeOfTest('undefined');
131
- /**
132
- * Determine if a value is a Buffer
133
- *
134
- * @param {*} val The value to test
135
- *
136
- * @returns {boolean} True if value is a Buffer, otherwise false
137
- */ function isBuffer(val) {
138
- return null !== val && !isUndefined(val) && null !== val.constructor && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
121
+ /* eslint-disable @typescript-eslint/no-namespace */ class Bots extends APIResource {
122
+ /**
123
+ * Create a new agent. | 调用接口创建一个新的智能体。
124
+ * @docs en:https://www.coze.com/docs/developer_guides/create_bot?_lang=en
125
+ * @docs zh:https://www.coze.cn/docs/developer_guides/create_bot?_lang=zh
126
+ * @param params - Required The parameters for creating a bot. | 创建 Bot 的参数。
127
+ * @param params.space_id - Required The Space ID of the space where the agent is located. | Bot 所在的空间的 Space ID。
128
+ * @param params.name - Required The name of the agent. It should be 1 to 20 characters long. | Bot 的名称。
129
+ * @param params.description - Optional The description of the agent. It can be 0 to 500 characters long. | Bot 的描述信息。
130
+ * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
131
+ * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
132
+ * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
133
+ * @returns Information about the created bot. | 创建的 Bot 信息。
134
+ */ async create(params, options) {
135
+ const apiUrl = '/v1/bot/create';
136
+ const result = await this._client.post(apiUrl, params, false, options);
137
+ return result.data;
138
+ }
139
+ /**
140
+ * Update the configuration of an agent. | 调用接口修改智能体的配置。
141
+ * @docs en:https://www.coze.com/docs/developer_guides/update_bot?_lang=en
142
+ * @docs zh:https://www.coze.cn/docs/developer_guides/update_bot?_lang=zh
143
+ * @param params - Required The parameters for updating a bot. | 修改 Bot 的参数。
144
+ * @param params.bot_id - Required The ID of the agent that the API interacts with. | 待修改配置的智能体ID。
145
+ * @param params.name - Optional The name of the agent. | Bot 的名称。
146
+ * @param params.description - Optional The description of the agent. | Bot 的描述信息。
147
+ * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
148
+ * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
149
+ * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
150
+ * @param params.knowledge - Optional Knowledge configurations of the agent. | Bot 的知识库配置。
151
+ * @returns Undefined | 无返回值
152
+ */ async update(params, options) {
153
+ const apiUrl = '/v1/bot/update';
154
+ const result = await this._client.post(apiUrl, params, false, options);
155
+ return result.data;
156
+ }
157
+ /**
158
+ * Get the agents published as API service. | 调用接口查看指定空间发布到 Agent as API 渠道的智能体列表。
159
+ * @docs en:https://www.coze.com/docs/developer_guides/published_bots_list?_lang=en
160
+ * @docs zh:https://www.coze.cn/docs/developer_guides/published_bots_list?_lang=zh
161
+ * @param params - Required The parameters for listing bots. | 列出 Bot 的参数。
162
+ * @param params.space_id - Required The ID of the space. | Bot 所在的空间的 Space ID。
163
+ * @param params.page_size - Optional Pagination size. | 分页大小。
164
+ * @param params.page_index - Optional Page number for paginated queries. | 分页查询时的页码。
165
+ * @returns List of published bots. | 已发布的 Bot 列表。
166
+ */ async list(params, options) {
167
+ const apiUrl = '/v1/space/published_bots_list';
168
+ const result = await this._client.get(apiUrl, params, false, options);
169
+ return result.data;
170
+ }
171
+ /**
172
+ * Publish the specified agent as an API service. | 调用接口创建一个新的智能体。
173
+ * @docs en:https://www.coze.com/docs/developer_guides/publish_bot?_lang=en
174
+ * @docs zh:https://www.coze.cn/docs/developer_guides/publish_bot?_lang=zh
175
+ * @param params - Required The parameters for publishing a bot. | 发布 Bot 的参数。
176
+ * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要发布的智能体ID。
177
+ * @param params.connector_ids - Required The list of publishing channel IDs for the agent. | 智能体的发布渠道 ID 列表。
178
+ * @returns Undefined | 无返回值
179
+ */ async publish(params, options) {
180
+ const apiUrl = '/v1/bot/publish';
181
+ const result = await this._client.post(apiUrl, params, false, options);
182
+ return result.data;
183
+ }
184
+ /**
185
+ * Get the configuration information of the agent. | 获取指定智能体的配置信息。
186
+ * @docs en:https://www.coze.com/docs/developer_guides/get_metadata?_lang=en
187
+ * @docs zh:https://www.coze.cn/docs/developer_guides/get_metadata?_lang=zh
188
+ * @param params - Required The parameters for retrieving a bot. | 获取 Bot 的参数。
189
+ * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要查看的智能体ID。
190
+ * @returns Information about the bot. | Bot 的配置信息。
191
+ */ async retrieve(params, options) {
192
+ const apiUrl = '/v1/bot/get_online_info';
193
+ const result = await this._client.get(apiUrl, params, false, options);
194
+ return result.data;
195
+ }
139
196
  }
140
- /**
141
- * Determine if a value is an ArrayBuffer
142
- *
143
- * @param {*} val The value to test
144
- *
145
- * @returns {boolean} True if value is an ArrayBuffer, otherwise false
146
- */ const isArrayBuffer = kindOfTest('ArrayBuffer');
147
- /**
148
- * Determine if a value is a view on an ArrayBuffer
149
- *
150
- * @param {*} val The value to test
151
- *
152
- * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
153
- */ function isArrayBufferView(val) {
154
- let result;
155
- result = 'undefined' != typeof ArrayBuffer && ArrayBuffer.isView ? ArrayBuffer.isView(val) : val && val.buffer && isArrayBuffer(val.buffer);
156
- return result;
197
+ /* eslint-disable security/detect-object-injection */ /* eslint-disable @typescript-eslint/no-explicit-any */ function safeJsonParse(jsonString) {
198
+ let defaultValue = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : '';
199
+ try {
200
+ return JSON.parse(jsonString);
201
+ } catch (error) {
202
+ return defaultValue;
203
+ }
157
204
  }
158
- /**
159
- * Determine if a value is a String
160
- *
161
- * @param {*} val The value to test
162
- *
163
- * @returns {boolean} True if value is a String, otherwise false
164
- */ const isString = typeOfTest('string');
165
- /**
166
- * Determine if a value is a Function
167
- *
168
- * @param {*} val The value to test
169
- * @returns {boolean} True if value is a Function, otherwise false
170
- */ const isFunction = typeOfTest('function');
171
- /**
172
- * Determine if a value is a Number
173
- *
174
- * @param {*} val The value to test
175
- *
176
- * @returns {boolean} True if value is a Number, otherwise false
177
- */ const isNumber = typeOfTest('number');
178
- /**
179
- * Determine if a value is an Object
180
- *
181
- * @param {*} thing The value to test
182
- *
183
- * @returns {boolean} True if value is an Object, otherwise false
184
- */ const isObject = (thing)=>null !== thing && 'object' == typeof thing;
185
- /**
186
- * Determine if a value is a Boolean
187
- *
188
- * @param {*} thing The value to test
189
- * @returns {boolean} True if value is a Boolean, otherwise false
190
- */ const isBoolean = (thing)=>true === thing || false === thing;
191
- /**
192
- * Determine if a value is a plain Object
193
- *
194
- * @param {*} val The value to test
195
- *
196
- * @returns {boolean} True if value is a plain Object, otherwise false
197
- */ const isPlainObject = (val)=>{
198
- if ('object' !== kindOf(val)) return false;
199
- const prototype = getPrototypeOf(val);
200
- return (null === prototype || prototype === Object.prototype || null === Object.getPrototypeOf(prototype)) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
201
- };
202
- /**
203
- * Determine if a value is a Date
204
- *
205
- * @param {*} val The value to test
206
- *
207
- * @returns {boolean} True if value is a Date, otherwise false
208
- */ const isDate = kindOfTest('Date');
209
- /**
210
- * Determine if a value is a File
211
- *
212
- * @param {*} val The value to test
213
- *
214
- * @returns {boolean} True if value is a File, otherwise false
215
- */ const isFile = kindOfTest('File');
216
- /**
217
- * Determine if a value is a Blob
218
- *
219
- * @param {*} val The value to test
220
- *
221
- * @returns {boolean} True if value is a Blob, otherwise false
222
- */ const isBlob = kindOfTest('Blob');
223
- /**
224
- * Determine if a value is a FileList
225
- *
226
- * @param {*} val The value to test
227
- *
228
- * @returns {boolean} True if value is a File, otherwise false
229
- */ const utils_isFileList = kindOfTest('FileList');
230
- /**
231
- * Determine if a value is a Stream
232
- *
233
- * @param {*} val The value to test
234
- *
235
- * @returns {boolean} True if value is a Stream, otherwise false
236
- */ const utils_isStream = (val)=>isObject(val) && isFunction(val.pipe);
237
- /**
238
- * Determine if a value is a FormData
239
- *
240
- * @param {*} thing The value to test
241
- *
242
- * @returns {boolean} True if value is an FormData, otherwise false
243
- */ const utils_isFormData = (thing)=>{
244
- let kind;
245
- return thing && ('function' == typeof FormData && thing instanceof FormData || isFunction(thing.append) && ('formdata' === (kind = kindOf(thing)) || // detect form-data instance
246
- 'object' === kind && isFunction(thing.toString) && '[object FormData]' === thing.toString()));
247
- };
248
- /**
249
- * Determine if a value is a URLSearchParams object
250
- *
251
- * @param {*} val The value to test
252
- *
253
- * @returns {boolean} True if value is a URLSearchParams object, otherwise false
254
- */ const isURLSearchParams = kindOfTest('URLSearchParams');
255
- const [isReadableStream, isRequest, isResponse, isHeaders] = [
256
- 'ReadableStream',
257
- 'Request',
258
- 'Response',
259
- 'Headers'
260
- ].map(kindOfTest);
261
- /**
262
- * Trim excess whitespace off the beginning and end of a string
263
- *
264
- * @param {String} str The String to trim
265
- *
266
- * @returns {String} The String freed of excess whitespace
267
- */ const trim = (str)=>str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
268
- /**
269
- * Iterate over an Array or an Object invoking a function for each item.
270
- *
271
- * If `obj` is an Array callback will be called passing
272
- * the value, index, and complete array for each item.
273
- *
274
- * If 'obj' is an Object callback will be called passing
275
- * the value, key, and complete object for each property.
276
- *
277
- * @param {Object|Array} obj The object to iterate
278
- * @param {Function} fn The callback to invoke for each item
279
- *
280
- * @param {Boolean} [allOwnKeys = false]
281
- * @returns {any}
282
- */ function forEach(obj, fn, { allOwnKeys = false } = {}) {
283
- // Don't bother if no value provided
284
- if (null == obj) return;
285
- let i;
286
- let l;
287
- // Force an array if not already something iterable
288
- if ('object' != typeof obj) /*eslint no-param-reassign:0*/ obj = [
289
- obj
290
- ];
291
- if (isArray(obj)) // Iterate over array values
292
- for(i = 0, l = obj.length; i < l; i++)fn.call(null, obj[i], i, obj);
293
- else {
294
- // Iterate over object keys
295
- const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
296
- const len = keys.length;
297
- let key;
298
- for(i = 0; i < len; i++){
299
- key = keys[i];
300
- fn.call(null, obj[key], key, obj);
205
+ function utils_sleep(ms) {
206
+ return new Promise((resolve)=>{
207
+ setTimeout(resolve, ms);
208
+ });
209
+ }
210
+ function utils_isBrowser() {
211
+ return 'undefined' != typeof window;
212
+ }
213
+ function isPlainObject(obj) {
214
+ if ('object' != typeof obj || null === obj) return false;
215
+ const proto = Object.getPrototypeOf(obj);
216
+ if (null === proto) return true;
217
+ let baseProto = proto;
218
+ while(null !== Object.getPrototypeOf(baseProto))baseProto = Object.getPrototypeOf(baseProto);
219
+ return proto === baseProto;
220
+ }
221
+ function mergeConfig() {
222
+ for(var _len = arguments.length, objects = new Array(_len), _key = 0; _key < _len; _key++)objects[_key] = arguments[_key];
223
+ return objects.reduce((result, obj)=>{
224
+ if (void 0 === obj) return result || {};
225
+ for(const key in obj)if (Object.prototype.hasOwnProperty.call(obj, key)) {
226
+ if (isPlainObject(obj[key]) && !Array.isArray(obj[key])) result[key] = mergeConfig(result[key] || {}, obj[key]);
227
+ else result[key] = obj[key];
228
+ }
229
+ return result;
230
+ }, {});
231
+ }
232
+ function isPersonalAccessToken(token) {
233
+ return null == token ? void 0 : token.startsWith('pat_');
234
+ }
235
+ /* eslint-disable max-params */ class CozeError extends Error {
236
+ }
237
+ class error_APIError extends CozeError {
238
+ static makeMessage(status, errorBody, message, headers) {
239
+ if (!errorBody && message) return message;
240
+ if (errorBody) {
241
+ const list = [];
242
+ const { code, msg, error } = errorBody;
243
+ if (code) list.push(`code: ${code}`);
244
+ if (msg) list.push(`msg: ${msg}`);
245
+ if ((null == error ? void 0 : error.detail) && msg !== error.detail) list.push(`detail: ${error.detail}`);
246
+ const logId = (null == error ? void 0 : error.logid) || (null == headers ? void 0 : headers['x-tt-logid']);
247
+ if (logId) list.push(`logid: ${logId}`);
248
+ const help_doc = null == error ? void 0 : error.help_doc;
249
+ if (help_doc) list.push(`help doc: ${help_doc}`);
250
+ return list.join(', ');
301
251
  }
252
+ if (status) return `http status code: ${status} (no body)`;
253
+ return '(no status code or body)';
254
+ }
255
+ static generate(status, errorResponse, message, headers) {
256
+ if (!status) return new APIConnectionError({
257
+ cause: castToError(errorResponse)
258
+ });
259
+ const error = errorResponse;
260
+ // https://www.coze.cn/docs/developer_guides/coze_error_codes
261
+ if (400 === status || (null == error ? void 0 : error.code) === 4000) return new BadRequestError(status, error, message, headers);
262
+ if (401 === status || (null == error ? void 0 : error.code) === 4100) return new AuthenticationError(status, error, message, headers);
263
+ if (403 === status || (null == error ? void 0 : error.code) === 4101) return new PermissionDeniedError(status, error, message, headers);
264
+ if (404 === status || (null == error ? void 0 : error.code) === 4200) return new NotFoundError(status, error, message, headers);
265
+ if (429 === status || (null == error ? void 0 : error.code) === 4013) return new RateLimitError(status, error, message, headers);
266
+ if (408 === status) return new TimeoutError(status, error, message, headers);
267
+ if (502 === status) return new GatewayError(status, error, message, headers);
268
+ if (status >= 500) return new InternalServerError(status, error, message, headers);
269
+ return new error_APIError(status, error, message, headers);
270
+ }
271
+ constructor(status, error, message, headers){
272
+ var _error_error, _error_error1;
273
+ super(`${error_APIError.makeMessage(status, error, message, headers)}`);
274
+ this.status = status;
275
+ this.headers = headers;
276
+ this.logid = null == headers ? void 0 : headers['x-tt-logid'];
277
+ // this.error = error;
278
+ this.code = null == error ? void 0 : error.code;
279
+ this.msg = null == error ? void 0 : error.msg;
280
+ this.detail = null == error ? void 0 : null === (_error_error = error.error) || void 0 === _error_error ? void 0 : _error_error.detail;
281
+ this.help_doc = null == error ? void 0 : null === (_error_error1 = error.error) || void 0 === _error_error1 ? void 0 : _error_error1.help_doc;
282
+ this.rawError = error;
302
283
  }
303
284
  }
304
- function findKey(obj, key) {
305
- key = key.toLowerCase();
306
- const keys = Object.keys(obj);
307
- let i = keys.length;
308
- let _key;
309
- while(i-- > 0){
310
- _key = keys[i];
311
- if (key === _key.toLowerCase()) return _key;
285
+ class APIConnectionError extends error_APIError {
286
+ constructor({ message, cause }){
287
+ super(void 0, void 0, message || 'Connection error.', void 0), this.status = void 0;
288
+ // if (cause) {
289
+ // this.cause = cause;
290
+ // }
312
291
  }
313
- return null;
314
292
  }
315
- const _global = (()=>{
316
- /*eslint no-undef:0*/ if ("undefined" != typeof globalThis) return globalThis;
317
- return "undefined" != typeof self ? self : 'undefined' != typeof window ? window : global;
318
- })();
319
- const isContextDefined = (context)=>!isUndefined(context) && context !== _global;
320
- /**
321
- * Accepts varargs expecting each argument to be an object, then
322
- * immutably merges the properties of each object and returns result.
323
- *
324
- * When multiple objects contain the same key the later object in
325
- * the arguments list will take precedence.
326
- *
327
- * Example:
328
- *
329
- * ```js
330
- * var result = merge({foo: 123}, {foo: 456});
331
- * console.log(result.foo); // outputs 456
332
- * ```
333
- *
334
- * @param {Object} obj1 Object to merge
335
- *
336
- * @returns {Object} Result of all merge properties
337
- */ function utils_merge() {
338
- const { caseless } = isContextDefined(this) && this || {};
339
- const result = {};
340
- const assignValue = (val, key)=>{
341
- const targetKey = caseless && findKey(result, key) || key;
342
- if (isPlainObject(result[targetKey]) && isPlainObject(val)) result[targetKey] = utils_merge(result[targetKey], val);
343
- else if (isPlainObject(val)) result[targetKey] = utils_merge({}, val);
344
- else if (isArray(val)) result[targetKey] = val.slice();
345
- else result[targetKey] = val;
346
- };
347
- for(let i = 0, l = arguments.length; i < l; i++)arguments[i] && forEach(arguments[i], assignValue);
348
- return result;
293
+ class APIUserAbortError extends error_APIError {
294
+ constructor(message){
295
+ super(void 0, void 0, message || 'Request was aborted.', void 0), this.name = 'UserAbortError', this.status = void 0;
296
+ }
349
297
  }
350
- /**
351
- * Extends object a by mutably adding to it the properties of object b.
352
- *
353
- * @param {Object} a The object to be extended
354
- * @param {Object} b The object to copy properties from
355
- * @param {Object} thisArg The object to bind function to
356
- *
357
- * @param {Boolean} [allOwnKeys]
358
- * @returns {Object} The resulting value of object a
359
- */ const extend = (a, b, thisArg, { allOwnKeys } = {})=>{
360
- forEach(b, (val, key)=>{
361
- if (thisArg && isFunction(val)) a[key] = bind(val, thisArg);
362
- else a[key] = val;
363
- }, {
364
- allOwnKeys
365
- });
366
- return a;
367
- };
368
- /**
369
- * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
370
- *
371
- * @param {string} content with BOM
372
- *
373
- * @returns {string} content value without BOM
374
- */ const stripBOM = (content)=>{
375
- if (0xFEFF === content.charCodeAt(0)) content = content.slice(1);
376
- return content;
377
- };
378
- /**
379
- * Inherit the prototype methods from one constructor into another
380
- * @param {function} constructor
381
- * @param {function} superConstructor
382
- * @param {object} [props]
383
- * @param {object} [descriptors]
384
- *
385
- * @returns {void}
386
- */ const inherits = (constructor, superConstructor, props, descriptors)=>{
387
- constructor.prototype = Object.create(superConstructor.prototype, descriptors);
388
- constructor.prototype.constructor = constructor;
389
- Object.defineProperty(constructor, 'super', {
390
- value: superConstructor.prototype
391
- });
392
- props && Object.assign(constructor.prototype, props);
298
+ class BadRequestError extends error_APIError {
299
+ constructor(...args){
300
+ super(...args), this.name = 'BadRequestError', this.status = 400;
301
+ }
302
+ }
303
+ class AuthenticationError extends error_APIError {
304
+ constructor(...args){
305
+ super(...args), this.name = 'AuthenticationError', this.status = 401;
306
+ }
307
+ }
308
+ class PermissionDeniedError extends error_APIError {
309
+ constructor(...args){
310
+ super(...args), this.name = 'PermissionDeniedError', this.status = 403;
311
+ }
312
+ }
313
+ class NotFoundError extends error_APIError {
314
+ constructor(...args){
315
+ super(...args), this.name = 'NotFoundError', this.status = 404;
316
+ }
317
+ }
318
+ class TimeoutError extends error_APIError {
319
+ constructor(...args){
320
+ super(...args), this.name = 'TimeoutError', this.status = 408;
321
+ }
322
+ }
323
+ class RateLimitError extends error_APIError {
324
+ constructor(...args){
325
+ super(...args), this.name = 'RateLimitError', this.status = 429;
326
+ }
327
+ }
328
+ class InternalServerError extends error_APIError {
329
+ constructor(...args){
330
+ super(...args), this.name = 'InternalServerError', this.status = 500;
331
+ }
332
+ }
333
+ class GatewayError extends error_APIError {
334
+ constructor(...args){
335
+ super(...args), this.name = 'GatewayError', this.status = 502;
336
+ }
337
+ }
338
+ const castToError = (err)=>{
339
+ if (err instanceof Error) return err;
340
+ return new Error(err);
393
341
  };
394
- /**
395
- * Resolve object with deep prototype chain to a flat object
396
- * @param {Object} sourceObj source object
397
- * @param {Object} [destObj]
398
- * @param {Function|Boolean} [filter]
399
- * @param {Function} [propFilter]
400
- *
401
- * @returns {Object}
402
- */ const toFlatObject = (sourceObj, destObj, filter, propFilter)=>{
403
- let props;
404
- let i;
405
- let prop;
406
- const merged = {};
407
- destObj = destObj || {};
408
- // eslint-disable-next-line no-eq-null,eqeqeq
409
- if (null == sourceObj) return destObj;
410
- do {
411
- props = Object.getOwnPropertyNames(sourceObj);
412
- i = props.length;
413
- while(i-- > 0){
414
- prop = props[i];
415
- if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
416
- destObj[prop] = sourceObj[prop];
417
- merged[prop] = true;
418
- }
419
- }
420
- sourceObj = false !== filter && getPrototypeOf(sourceObj);
421
- }while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
422
- return destObj;
342
+ class Messages extends APIResource {
343
+ /**
344
+ * Get the list of messages in a chat. | 获取对话中的消息列表。
345
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_message_list?_lang=en
346
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_message_list?_lang=zh
347
+ * @param conversation_id - Required The ID of the conversation. | 会话 ID。
348
+ * @param chat_id - Required The ID of the chat. | 对话 ID。
349
+ * @returns An array of chat messages. | 对话消息数组。
350
+ */ async list(conversation_id, chat_id, options) {
351
+ const apiUrl = `/v3/chat/message/list?conversation_id=${conversation_id}&chat_id=${chat_id}`;
352
+ const result = await this._client.get(apiUrl, void 0, false, options);
353
+ return result.data;
354
+ }
355
+ }
356
+ const uuid = ()=>(Math.random() * new Date().getTime()).toString();
357
+ const handleAdditionalMessages = (additional_messages)=>null == additional_messages ? void 0 : additional_messages.map((i)=>({
358
+ ...i,
359
+ content: 'object' == typeof i.content ? JSON.stringify(i.content) : i.content
360
+ }));
361
+ class Chat extends APIResource {
362
+ /**
363
+ * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
364
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
365
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
366
+ * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
367
+ * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
368
+ * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
369
+ * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
370
+ * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义变量。
371
+ * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
372
+ * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
373
+ * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
374
+ * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
375
+ * @returns The data of the created chat. | 创建的对话数据。
376
+ */ async create(params, options) {
377
+ if (!params.user_id) params.user_id = uuid();
378
+ const { conversation_id, ...rest } = params;
379
+ const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
380
+ const payload = {
381
+ ...rest,
382
+ additional_messages: handleAdditionalMessages(params.additional_messages),
383
+ stream: false
384
+ };
385
+ const result = await this._client.post(apiUrl, payload, false, options);
386
+ return result.data;
387
+ }
388
+ /**
389
+ * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
390
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
391
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
392
+ * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
393
+ * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
394
+ * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
395
+ * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
396
+ * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
397
+ * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
398
+ * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
399
+ * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
400
+ * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
401
+ * @returns
402
+ */ async createAndPoll(params, options) {
403
+ if (!params.user_id) params.user_id = uuid();
404
+ const { conversation_id, ...rest } = params;
405
+ const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
406
+ const payload = {
407
+ ...rest,
408
+ additional_messages: handleAdditionalMessages(params.additional_messages),
409
+ stream: false
410
+ };
411
+ const result = await this._client.post(apiUrl, payload, false, options);
412
+ const chatId = result.data.id;
413
+ const conversationId = result.data.conversation_id;
414
+ let chat;
415
+ while(true){
416
+ await utils_sleep(100);
417
+ chat = await this.retrieve(conversationId, chatId);
418
+ if ('completed' === chat.status || 'failed' === chat.status || 'requires_action' === chat.status) break;
419
+ }
420
+ const messageList = await this.messages.list(conversationId, chatId);
421
+ return {
422
+ chat,
423
+ messages: messageList
424
+ };
425
+ }
426
+ /**
427
+ * Call the Chat API to send messages to a published Coze agent with streaming response. | 调用此接口发起一次对话,支持流式响应。
428
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
429
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
430
+ * @param params - Required The parameters for streaming a chat session. | 流式会话的参数。
431
+ * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
432
+ * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
433
+ * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
434
+ * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
435
+ * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
436
+ * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
437
+ * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
438
+ * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
439
+ * @returns A stream of chat data. | 对话数据流。
440
+ */ async *stream(params, options) {
441
+ if (!params.user_id) params.user_id = uuid();
442
+ const { conversation_id, ...rest } = params;
443
+ const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
444
+ const payload = {
445
+ ...rest,
446
+ additional_messages: handleAdditionalMessages(params.additional_messages),
447
+ stream: true
448
+ };
449
+ const result = await this._client.post(apiUrl, payload, true, options);
450
+ for await (const message of result)if ("done" === message.event) {
451
+ const ret = {
452
+ event: message.event,
453
+ data: '[DONE]'
454
+ };
455
+ yield ret;
456
+ } else try {
457
+ const ret = {
458
+ event: message.event,
459
+ data: JSON.parse(message.data)
460
+ };
461
+ yield ret;
462
+ } catch (error) {
463
+ throw new CozeError(`Could not parse message into JSON:${message.data}`);
464
+ }
465
+ }
466
+ /**
467
+ * Get the detailed information of the chat. | 查看对话的详细信息。
468
+ * @docs en:https://www.coze.com/docs/developer_guides/retrieve_chat?_lang=en
469
+ * @docs zh:https://www.coze.cn/docs/developer_guides/retrieve_chat?_lang=zh
470
+ * @param conversation_id - Required The ID of the conversation. | 会话 ID。
471
+ * @param chat_id - Required The ID of the chat. | 对话 ID。
472
+ * @returns The data of the retrieved chat. | 检索到的对话数据。
473
+ */ async retrieve(conversation_id, chat_id, options) {
474
+ const apiUrl = `/v3/chat/retrieve?conversation_id=${conversation_id}&chat_id=${chat_id}`;
475
+ const result = await this._client.post(apiUrl, void 0, false, options);
476
+ return result.data;
477
+ }
478
+ /**
479
+ * Cancel a chat session. | 取消对话会话。
480
+ * @docs en:https://www.coze.com/docs/developer_guides/cancel_chat?_lang=en
481
+ * @docs zh:https://www.coze.cn/docs/developer_guides/cancel_chat?_lang=zh
482
+ * @param conversation_id - Required The ID of the conversation. | 会话 ID。
483
+ * @param chat_id - Required The ID of the chat. | 对话 ID。
484
+ * @returns The data of the canceled chat. | 取消的对话数据。
485
+ */ async cancel(conversation_id, chat_id, options) {
486
+ const apiUrl = '/v3/chat/cancel';
487
+ const payload = {
488
+ conversation_id,
489
+ chat_id
490
+ };
491
+ const result = await this._client.post(apiUrl, payload, false, options);
492
+ return result.data;
493
+ }
494
+ /**
495
+ * Submit tool outputs for a chat session. | 提交对话会话的工具输出。
496
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_submit_tool_outputs?_lang=en
497
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_submit_tool_outputs?_lang=zh
498
+ * @param params - Required Parameters for submitting tool outputs. | 提交工具输出的参数。
499
+ * @param params.conversation_id - Required The ID of the conversation. | 会话 ID。
500
+ * @param params.chat_id - Required The ID of the chat. | 对话 ID。
501
+ * @param params.tool_outputs - Required The outputs of the tool. | 工具的输出。
502
+ * @param params.stream - Optional Whether to use streaming response. | 是否使用流式响应。
503
+ * @returns The data of the submitted tool outputs or a stream of chat data. | 提交的工具输出数据或对话数据流。
504
+ */ async *submitToolOutputs(params, options) {
505
+ const { conversation_id, chat_id, ...rest } = params;
506
+ const apiUrl = `/v3/chat/submit_tool_outputs?conversation_id=${params.conversation_id}&chat_id=${params.chat_id}`;
507
+ const payload = {
508
+ ...rest
509
+ };
510
+ if (false === params.stream) {
511
+ const response = await this._client.post(apiUrl, payload, false, options);
512
+ return response.data;
513
+ }
514
+ {
515
+ const result = await this._client.post(apiUrl, payload, true, options);
516
+ for await (const message of result)if ("done" === message.event) {
517
+ const ret = {
518
+ event: message.event,
519
+ data: '[DONE]'
520
+ };
521
+ yield ret;
522
+ } else try {
523
+ const ret = {
524
+ event: message.event,
525
+ data: JSON.parse(message.data)
526
+ };
527
+ yield ret;
528
+ } catch (error) {
529
+ throw new CozeError(`Could not parse message into JSON:${message.data}`);
530
+ }
531
+ }
532
+ }
533
+ constructor(...args){
534
+ super(...args), this.messages = new Messages(this._client);
535
+ }
536
+ }
537
+ var chat_ChatEventType = /*#__PURE__*/ function(ChatEventType) {
538
+ ChatEventType["CONVERSATION_CHAT_CREATED"] = "conversation.chat.created";
539
+ ChatEventType["CONVERSATION_CHAT_IN_PROGRESS"] = "conversation.chat.in_progress";
540
+ ChatEventType["CONVERSATION_CHAT_COMPLETED"] = "conversation.chat.completed";
541
+ ChatEventType["CONVERSATION_CHAT_FAILED"] = "conversation.chat.failed";
542
+ ChatEventType["CONVERSATION_CHAT_REQUIRES_ACTION"] = "conversation.chat.requires_action";
543
+ ChatEventType["CONVERSATION_MESSAGE_DELTA"] = "conversation.message.delta";
544
+ ChatEventType["CONVERSATION_MESSAGE_COMPLETED"] = "conversation.message.completed";
545
+ ChatEventType["CONVERSATION_AUDIO_DELTA"] = "conversation.audio.delta";
546
+ ChatEventType["DONE"] = "done";
547
+ ChatEventType["ERROR"] = "error";
548
+ return ChatEventType;
549
+ }({});
550
+ class messages_Messages extends APIResource {
551
+ /**
552
+ * Create a message and add it to the specified conversation. | 创建一条消息,并将其添加到指定的会话中。
553
+ * @docs en: https://www.coze.com/docs/developer_guides/create_message?_lang=en
554
+ * @docs zh: https://www.coze.cn/docs/developer_guides/create_message?_lang=zh
555
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
556
+ * @param params - Required The parameters for creating a message | 创建消息所需的参数
557
+ * @param params.role - Required The entity that sent this message. Possible values: user, assistant. | 发送这条消息的实体。取值:user, assistant。
558
+ * @param params.content - Required The content of the message. | 消息的内容。
559
+ * @param params.content_type - Required The type of the message content. | 消息内容的类型。
560
+ * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
561
+ * @returns Information about the new message. | 消息详情。
562
+ */ async create(conversation_id, params, options) {
563
+ const apiUrl = `/v1/conversation/message/create?conversation_id=${conversation_id}`;
564
+ const response = await this._client.post(apiUrl, params, false, options);
565
+ return response.data;
566
+ }
567
+ /**
568
+ * Modify a message, supporting the modification of message content, additional content, and message type. | 修改一条消息,支持修改消息内容、附加内容和消息类型。
569
+ * @docs en: https://www.coze.com/docs/developer_guides/modify_message?_lang=en
570
+ * @docs zh: https://www.coze.cn/docs/developer_guides/modify_message?_lang=zh
571
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
572
+ * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
573
+ * @param params - Required The parameters for modifying a message | 修改消息所需的参数
574
+ * @param params.meta_data - Optional Additional information when modifying a message. | 修改消息时的附加消息。
575
+ * @param params.content - Optional The content of the message. | 消息的内容。
576
+ * @param params.content_type - Optional The type of the message content. | 消息内容的类型。
577
+ * @returns Information about the modified message. | 消息详情。
578
+ */ // eslint-disable-next-line max-params
579
+ async update(conversation_id, message_id, params, options) {
580
+ const apiUrl = `/v1/conversation/message/modify?conversation_id=${conversation_id}&message_id=${message_id}`;
581
+ const response = await this._client.post(apiUrl, params, false, options);
582
+ return response.message;
583
+ }
584
+ /**
585
+ * Get the detailed information of specified message. | 查看指定消息的详细信息。
586
+ * @docs en: https://www.coze.com/docs/developer_guides/retrieve_message?_lang=en
587
+ * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_message?_lang=zh
588
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
589
+ * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
590
+ * @returns Information about the message. | 消息详情。
591
+ */ async retrieve(conversation_id, message_id, options) {
592
+ const apiUrl = `/v1/conversation/message/retrieve?conversation_id=${conversation_id}&message_id=${message_id}`;
593
+ const response = await this._client.get(apiUrl, null, false, options);
594
+ return response.data;
595
+ }
596
+ /**
597
+ * List messages in a conversation. | 列出会话中的消息。
598
+ * @docs en: https://www.coze.com/docs/developer_guides/message_list?_lang=en
599
+ * @docs zh: https://www.coze.cn/docs/developer_guides/message_list?_lang=zh
600
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
601
+ * @param params - Optional The parameters for listing messages | 列出消息所需的参数
602
+ * @param params.order - Optional The order of the messages. | 消息的顺序。
603
+ * @param params.chat_id - Optional The ID of the chat. | 聊天 ID。
604
+ * @param params.before_id - Optional The ID of the message before which to list. | 列出此消息之前的消息 ID。
605
+ * @param params.after_id - Optional The ID of the message after which to list. | 列出此消息之后的消息 ID。
606
+ * @param params.limit - Optional The maximum number of messages to return. | 返回的最大消息数。
607
+ * @returns A list of messages. | 消息列表。
608
+ */ async list(conversation_id, params, options) {
609
+ const apiUrl = `/v1/conversation/message/list?conversation_id=${conversation_id}`;
610
+ const response = await this._client.post(apiUrl, params, false, options);
611
+ return response;
612
+ }
613
+ /**
614
+ * Call the API to delete a message within a specified conversation. | 调用接口在指定会话中删除消息。
615
+ * @docs en: https://www.coze.com/docs/developer_guides/delete_message?_lang=en
616
+ * @docs zh: https://www.coze.cn/docs/developer_guides/delete_message?_lang=zh
617
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
618
+ * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
619
+ * @returns Details of the deleted message. | 已删除的消息详情。
620
+ */ async delete(conversation_id, message_id, options) {
621
+ const apiUrl = `/v1/conversation/message/delete?conversation_id=${conversation_id}&message_id=${message_id}`;
622
+ const response = await this._client.post(apiUrl, void 0, false, options);
623
+ return response.data;
624
+ }
625
+ }
626
+ class Conversations extends APIResource {
627
+ /**
628
+ * Create a conversation. Conversation is an interaction between an agent and a user, including one or more messages. | 调用接口创建一个会话。
629
+ * @docs en: https://www.coze.com/docs/developer_guides/create_conversation?_lang=en
630
+ * @docs zh: https://www.coze.cn/docs/developer_guides/create_conversation?_lang=zh
631
+ * @param params - Required The parameters for creating a conversation | 创建会话所需的参数
632
+ * @param params.messages - Optional Messages in the conversation. | 会话中的消息内容。
633
+ * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
634
+ * @param params.bot_id - Optional Bind and isolate conversation on different bots. | 绑定和隔离不同Bot的会话。
635
+ * @returns Information about the created conversation. | 会话的基础信息。
636
+ */ async create(params, options) {
637
+ const apiUrl = '/v1/conversation/create';
638
+ const response = await this._client.post(apiUrl, params, false, options);
639
+ return response.data;
640
+ }
641
+ /**
642
+ * Get the information of specific conversation. | 通过会话 ID 查看会话信息。
643
+ * @docs en: https://www.coze.com/docs/developer_guides/retrieve_conversation?_lang=en
644
+ * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_conversation?_lang=zh
645
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
646
+ * @returns Information about the conversation. | 会话的基础信息。
647
+ */ async retrieve(conversation_id, options) {
648
+ const apiUrl = `/v1/conversation/retrieve?conversation_id=${conversation_id}`;
649
+ const response = await this._client.get(apiUrl, null, false, options);
650
+ return response.data;
651
+ }
652
+ /**
653
+ * List all conversations. | 列出 Bot 下所有会话。
654
+ * @param params
655
+ * @param params.bot_id - Required Bot ID. | Bot ID。
656
+ * @param params.page_num - Optional The page number. | 页码,默认值为 1。
657
+ * @param params.page_size - Optional The number of conversations per page. | 每页的会话数量,默认值为 50。
658
+ * @returns Information about the conversations. | 会话的信息。
659
+ */ async list(params, options) {
660
+ const apiUrl = '/v1/conversations';
661
+ const response = await this._client.get(apiUrl, params, false, options);
662
+ return response.data;
663
+ }
664
+ /**
665
+ * Clear a conversation. | 清空会话。
666
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
667
+ * @returns Information about the conversation session. | 会话的会话 ID。
668
+ */ async clear(conversation_id, options) {
669
+ const apiUrl = `/v1/conversations/${conversation_id}/clear`;
670
+ const response = await this._client.post(apiUrl, null, false, options);
671
+ return response.data;
672
+ }
673
+ constructor(...args){
674
+ super(...args), this.messages = new messages_Messages(this._client);
675
+ }
676
+ }
677
+ function bind(fn, thisArg) {
678
+ return function() {
679
+ return fn.apply(thisArg, arguments);
680
+ };
681
+ }
682
+ // utils is a library of generic helper functions non-specific to axios
683
+ const { toString: utils_toString } = Object.prototype;
684
+ const { getPrototypeOf } = Object;
685
+ const kindOf = ((cache)=>(thing)=>{
686
+ const str = utils_toString.call(thing);
687
+ return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
688
+ })(Object.create(null));
689
+ const kindOfTest = (type)=>{
690
+ type = type.toLowerCase();
691
+ return (thing)=>kindOf(thing) === type;
423
692
  };
693
+ const typeOfTest = (type)=>(thing)=>typeof thing === type;
424
694
  /**
425
- * Determines whether a string ends with the characters of a specified string
695
+ * Determine if a value is an Array
426
696
  *
427
- * @param {String} str
428
- * @param {String} searchString
429
- * @param {Number} [position= 0]
697
+ * @param {Object} val The value to test
430
698
  *
431
- * @returns {boolean}
432
- */ const endsWith = (str, searchString, position)=>{
433
- str = String(str);
434
- if (void 0 === position || position > str.length) position = str.length;
435
- position -= searchString.length;
436
- const lastIndex = str.indexOf(searchString, position);
437
- return -1 !== lastIndex && lastIndex === position;
438
- };
699
+ * @returns {boolean} True if value is an Array, otherwise false
700
+ */ const { isArray } = Array;
439
701
  /**
440
- * Returns new array from array like object or null if failed
702
+ * Determine if a value is undefined
441
703
  *
442
- * @param {*} [thing]
704
+ * @param {*} val The value to test
443
705
  *
444
- * @returns {?Array}
445
- */ const toArray = (thing)=>{
446
- if (!thing) return null;
447
- if (isArray(thing)) return thing;
448
- let i = thing.length;
449
- if (!isNumber(i)) return null;
450
- const arr = new Array(i);
451
- while(i-- > 0)arr[i] = thing[i];
452
- return arr;
453
- };
706
+ * @returns {boolean} True if the value is undefined, otherwise false
707
+ */ const isUndefined = typeOfTest('undefined');
454
708
  /**
455
- * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
456
- * thing passed in is an instance of Uint8Array
709
+ * Determine if a value is a Buffer
457
710
  *
458
- * @param {TypedArray}
711
+ * @param {*} val The value to test
459
712
  *
460
- * @returns {Array}
461
- */ // eslint-disable-next-line func-names
462
- const isTypedArray = ((TypedArray)=>(thing)=>TypedArray && thing instanceof TypedArray)('undefined' != typeof Uint8Array && getPrototypeOf(Uint8Array));
713
+ * @returns {boolean} True if value is a Buffer, otherwise false
714
+ */ function isBuffer(val) {
715
+ return null !== val && !isUndefined(val) && null !== val.constructor && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
716
+ }
463
717
  /**
464
- * For each entry in the object, call the function with the key and value.
718
+ * Determine if a value is an ArrayBuffer
465
719
  *
466
- * @param {Object<any, any>} obj - The object to iterate over.
467
- * @param {Function} fn - The function to call for each entry.
720
+ * @param {*} val The value to test
468
721
  *
469
- * @returns {void}
470
- */ const forEachEntry = (obj, fn)=>{
471
- const generator = obj && obj[Symbol.iterator];
472
- const iterator = generator.call(obj);
722
+ * @returns {boolean} True if value is an ArrayBuffer, otherwise false
723
+ */ const isArrayBuffer = kindOfTest('ArrayBuffer');
724
+ /**
725
+ * Determine if a value is a view on an ArrayBuffer
726
+ *
727
+ * @param {*} val The value to test
728
+ *
729
+ * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
730
+ */ function isArrayBufferView(val) {
473
731
  let result;
474
- while((result = iterator.next()) && !result.done){
475
- const pair = result.value;
476
- fn.call(obj, pair[0], pair[1]);
477
- }
478
- };
732
+ result = 'undefined' != typeof ArrayBuffer && ArrayBuffer.isView ? ArrayBuffer.isView(val) : val && val.buffer && isArrayBuffer(val.buffer);
733
+ return result;
734
+ }
479
735
  /**
480
- * It takes a regular expression and a string, and returns an array of all the matches
736
+ * Determine if a value is a String
481
737
  *
482
- * @param {string} regExp - The regular expression to match against.
483
- * @param {string} str - The string to search.
738
+ * @param {*} val The value to test
484
739
  *
485
- * @returns {Array<boolean>}
486
- */ const matchAll = (regExp, str)=>{
487
- let matches;
488
- const arr = [];
489
- while(null !== (matches = regExp.exec(str)))arr.push(matches);
490
- return arr;
491
- };
492
- /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ const isHTMLForm = kindOfTest('HTMLFormElement');
493
- const toCamelCase = (str)=>str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function(m, p1, p2) {
494
- return p1.toUpperCase() + p2;
495
- });
496
- /* Creating a function that will check if an object has a property. */ const utils_hasOwnProperty = (({ hasOwnProperty })=>(obj, prop)=>hasOwnProperty.call(obj, prop))(Object.prototype);
740
+ * @returns {boolean} True if value is a String, otherwise false
741
+ */ const isString = typeOfTest('string');
497
742
  /**
498
- * Determine if a value is a RegExp object
743
+ * Determine if a value is a Function
744
+ *
745
+ * @param {*} val The value to test
746
+ * @returns {boolean} True if value is a Function, otherwise false
747
+ */ const isFunction = typeOfTest('function');
748
+ /**
749
+ * Determine if a value is a Number
499
750
  *
500
751
  * @param {*} val The value to test
501
752
  *
502
- * @returns {boolean} True if value is a RegExp object, otherwise false
503
- */ const isRegExp = kindOfTest('RegExp');
504
- const reduceDescriptors = (obj, reducer)=>{
505
- const descriptors = Object.getOwnPropertyDescriptors(obj);
506
- const reducedDescriptors = {};
507
- forEach(descriptors, (descriptor, name)=>{
508
- let ret;
509
- if (false !== (ret = reducer(descriptor, name, obj))) reducedDescriptors[name] = ret || descriptor;
510
- });
511
- Object.defineProperties(obj, reducedDescriptors);
512
- };
753
+ * @returns {boolean} True if value is a Number, otherwise false
754
+ */ const isNumber = typeOfTest('number');
513
755
  /**
514
- * Makes all methods read-only
515
- * @param {Object} obj
516
- */ const freezeMethods = (obj)=>{
517
- reduceDescriptors(obj, (descriptor, name)=>{
518
- // skip restricted props in strict mode
519
- if (isFunction(obj) && -1 !== [
520
- 'arguments',
521
- 'caller',
522
- 'callee'
523
- ].indexOf(name)) return false;
524
- const value = obj[name];
525
- if (!isFunction(value)) return;
526
- descriptor.enumerable = false;
527
- if ('writable' in descriptor) {
528
- descriptor.writable = false;
529
- return;
530
- }
531
- if (!descriptor.set) descriptor.set = ()=>{
532
- throw Error('Can not rewrite read-only method \'' + name + '\'');
533
- };
534
- });
535
- };
536
- const toObjectSet = (arrayOrString, delimiter)=>{
537
- const obj = {};
538
- const define1 = (arr)=>{
539
- arr.forEach((value)=>{
540
- obj[value] = true;
541
- });
542
- };
543
- isArray(arrayOrString) ? define1(arrayOrString) : define1(String(arrayOrString).split(delimiter));
544
- return obj;
545
- };
546
- const noop = ()=>{};
547
- const toFiniteNumber = (value, defaultValue)=>null != value && Number.isFinite(value = +value) ? value : defaultValue;
548
- const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
549
- const DIGIT = '0123456789';
550
- const ALPHABET = {
551
- DIGIT,
552
- ALPHA,
553
- ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
554
- };
555
- const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT)=>{
556
- let str = '';
557
- const { length } = alphabet;
558
- while(size--)str += alphabet[Math.random() * length | 0];
559
- return str;
756
+ * Determine if a value is an Object
757
+ *
758
+ * @param {*} thing The value to test
759
+ *
760
+ * @returns {boolean} True if value is an Object, otherwise false
761
+ */ const isObject = (thing)=>null !== thing && 'object' == typeof thing;
762
+ /**
763
+ * Determine if a value is a Boolean
764
+ *
765
+ * @param {*} thing The value to test
766
+ * @returns {boolean} True if value is a Boolean, otherwise false
767
+ */ const isBoolean = (thing)=>true === thing || false === thing;
768
+ /**
769
+ * Determine if a value is a plain Object
770
+ *
771
+ * @param {*} val The value to test
772
+ *
773
+ * @returns {boolean} True if value is a plain Object, otherwise false
774
+ */ const utils_isPlainObject = (val)=>{
775
+ if ('object' !== kindOf(val)) return false;
776
+ const prototype = getPrototypeOf(val);
777
+ return (null === prototype || prototype === Object.prototype || null === Object.getPrototypeOf(prototype)) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
560
778
  };
561
779
  /**
562
- * If the thing is a FormData object, return true, otherwise return false.
780
+ * Determine if a value is a Date
563
781
  *
564
- * @param {unknown} thing - The thing to check.
782
+ * @param {*} val The value to test
565
783
  *
566
- * @returns {boolean}
567
- */ function isSpecCompliantForm(thing) {
568
- return !!(thing && isFunction(thing.append) && 'FormData' === thing[Symbol.toStringTag] && thing[Symbol.iterator]);
569
- }
570
- const toJSONObject = (obj)=>{
571
- const stack = new Array(10);
572
- const visit = (source, i)=>{
573
- if (isObject(source)) {
574
- if (stack.indexOf(source) >= 0) return;
575
- if (!('toJSON' in source)) {
784
+ * @returns {boolean} True if value is a Date, otherwise false
785
+ */ const isDate = kindOfTest('Date');
786
+ /**
787
+ * Determine if a value is a File
788
+ *
789
+ * @param {*} val The value to test
790
+ *
791
+ * @returns {boolean} True if value is a File, otherwise false
792
+ */ const isFile = kindOfTest('File');
793
+ /**
794
+ * Determine if a value is a Blob
795
+ *
796
+ * @param {*} val The value to test
797
+ *
798
+ * @returns {boolean} True if value is a Blob, otherwise false
799
+ */ const isBlob = kindOfTest('Blob');
800
+ /**
801
+ * Determine if a value is a FileList
802
+ *
803
+ * @param {*} val The value to test
804
+ *
805
+ * @returns {boolean} True if value is a File, otherwise false
806
+ */ const utils_isFileList = kindOfTest('FileList');
807
+ /**
808
+ * Determine if a value is a Stream
809
+ *
810
+ * @param {*} val The value to test
811
+ *
812
+ * @returns {boolean} True if value is a Stream, otherwise false
813
+ */ const utils_isStream = (val)=>isObject(val) && isFunction(val.pipe);
814
+ /**
815
+ * Determine if a value is a FormData
816
+ *
817
+ * @param {*} thing The value to test
818
+ *
819
+ * @returns {boolean} True if value is an FormData, otherwise false
820
+ */ const utils_isFormData = (thing)=>{
821
+ let kind;
822
+ return thing && ('function' == typeof FormData && thing instanceof FormData || isFunction(thing.append) && ('formdata' === (kind = kindOf(thing)) || // detect form-data instance
823
+ 'object' === kind && isFunction(thing.toString) && '[object FormData]' === thing.toString()));
824
+ };
825
+ /**
826
+ * Determine if a value is a URLSearchParams object
827
+ *
828
+ * @param {*} val The value to test
829
+ *
830
+ * @returns {boolean} True if value is a URLSearchParams object, otherwise false
831
+ */ const isURLSearchParams = kindOfTest('URLSearchParams');
832
+ const [isReadableStream, isRequest, isResponse, isHeaders] = [
833
+ 'ReadableStream',
834
+ 'Request',
835
+ 'Response',
836
+ 'Headers'
837
+ ].map(kindOfTest);
838
+ /**
839
+ * Trim excess whitespace off the beginning and end of a string
840
+ *
841
+ * @param {String} str The String to trim
842
+ *
843
+ * @returns {String} The String freed of excess whitespace
844
+ */ const trim = (str)=>str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
845
+ /**
846
+ * Iterate over an Array or an Object invoking a function for each item.
847
+ *
848
+ * If `obj` is an Array callback will be called passing
849
+ * the value, index, and complete array for each item.
850
+ *
851
+ * If 'obj' is an Object callback will be called passing
852
+ * the value, key, and complete object for each property.
853
+ *
854
+ * @param {Object|Array} obj The object to iterate
855
+ * @param {Function} fn The callback to invoke for each item
856
+ *
857
+ * @param {Boolean} [allOwnKeys = false]
858
+ * @returns {any}
859
+ */ function forEach(obj, fn, { allOwnKeys = false } = {}) {
860
+ // Don't bother if no value provided
861
+ if (null == obj) return;
862
+ let i;
863
+ let l;
864
+ // Force an array if not already something iterable
865
+ if ('object' != typeof obj) /*eslint no-param-reassign:0*/ obj = [
866
+ obj
867
+ ];
868
+ if (isArray(obj)) // Iterate over array values
869
+ for(i = 0, l = obj.length; i < l; i++)fn.call(null, obj[i], i, obj);
870
+ else {
871
+ // Iterate over object keys
872
+ const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
873
+ const len = keys.length;
874
+ let key;
875
+ for(i = 0; i < len; i++){
876
+ key = keys[i];
877
+ fn.call(null, obj[key], key, obj);
878
+ }
879
+ }
880
+ }
881
+ function findKey(obj, key) {
882
+ key = key.toLowerCase();
883
+ const keys = Object.keys(obj);
884
+ let i = keys.length;
885
+ let _key;
886
+ while(i-- > 0){
887
+ _key = keys[i];
888
+ if (key === _key.toLowerCase()) return _key;
889
+ }
890
+ return null;
891
+ }
892
+ const _global = (()=>{
893
+ /*eslint no-undef:0*/ if ("undefined" != typeof globalThis) return globalThis;
894
+ return "undefined" != typeof self ? self : 'undefined' != typeof window ? window : global;
895
+ })();
896
+ const isContextDefined = (context)=>!isUndefined(context) && context !== _global;
897
+ /**
898
+ * Accepts varargs expecting each argument to be an object, then
899
+ * immutably merges the properties of each object and returns result.
900
+ *
901
+ * When multiple objects contain the same key the later object in
902
+ * the arguments list will take precedence.
903
+ *
904
+ * Example:
905
+ *
906
+ * ```js
907
+ * var result = merge({foo: 123}, {foo: 456});
908
+ * console.log(result.foo); // outputs 456
909
+ * ```
910
+ *
911
+ * @param {Object} obj1 Object to merge
912
+ *
913
+ * @returns {Object} Result of all merge properties
914
+ */ function utils_merge() {
915
+ const { caseless } = isContextDefined(this) && this || {};
916
+ const result = {};
917
+ const assignValue = (val, key)=>{
918
+ const targetKey = caseless && findKey(result, key) || key;
919
+ if (utils_isPlainObject(result[targetKey]) && utils_isPlainObject(val)) result[targetKey] = utils_merge(result[targetKey], val);
920
+ else if (utils_isPlainObject(val)) result[targetKey] = utils_merge({}, val);
921
+ else if (isArray(val)) result[targetKey] = val.slice();
922
+ else result[targetKey] = val;
923
+ };
924
+ for(let i = 0, l = arguments.length; i < l; i++)arguments[i] && forEach(arguments[i], assignValue);
925
+ return result;
926
+ }
927
+ /**
928
+ * Extends object a by mutably adding to it the properties of object b.
929
+ *
930
+ * @param {Object} a The object to be extended
931
+ * @param {Object} b The object to copy properties from
932
+ * @param {Object} thisArg The object to bind function to
933
+ *
934
+ * @param {Boolean} [allOwnKeys]
935
+ * @returns {Object} The resulting value of object a
936
+ */ const extend = (a, b, thisArg, { allOwnKeys } = {})=>{
937
+ forEach(b, (val, key)=>{
938
+ if (thisArg && isFunction(val)) a[key] = bind(val, thisArg);
939
+ else a[key] = val;
940
+ }, {
941
+ allOwnKeys
942
+ });
943
+ return a;
944
+ };
945
+ /**
946
+ * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
947
+ *
948
+ * @param {string} content with BOM
949
+ *
950
+ * @returns {string} content value without BOM
951
+ */ const stripBOM = (content)=>{
952
+ if (0xFEFF === content.charCodeAt(0)) content = content.slice(1);
953
+ return content;
954
+ };
955
+ /**
956
+ * Inherit the prototype methods from one constructor into another
957
+ * @param {function} constructor
958
+ * @param {function} superConstructor
959
+ * @param {object} [props]
960
+ * @param {object} [descriptors]
961
+ *
962
+ * @returns {void}
963
+ */ const inherits = (constructor, superConstructor, props, descriptors)=>{
964
+ constructor.prototype = Object.create(superConstructor.prototype, descriptors);
965
+ constructor.prototype.constructor = constructor;
966
+ Object.defineProperty(constructor, 'super', {
967
+ value: superConstructor.prototype
968
+ });
969
+ props && Object.assign(constructor.prototype, props);
970
+ };
971
+ /**
972
+ * Resolve object with deep prototype chain to a flat object
973
+ * @param {Object} sourceObj source object
974
+ * @param {Object} [destObj]
975
+ * @param {Function|Boolean} [filter]
976
+ * @param {Function} [propFilter]
977
+ *
978
+ * @returns {Object}
979
+ */ const toFlatObject = (sourceObj, destObj, filter, propFilter)=>{
980
+ let props;
981
+ let i;
982
+ let prop;
983
+ const merged = {};
984
+ destObj = destObj || {};
985
+ // eslint-disable-next-line no-eq-null,eqeqeq
986
+ if (null == sourceObj) return destObj;
987
+ do {
988
+ props = Object.getOwnPropertyNames(sourceObj);
989
+ i = props.length;
990
+ while(i-- > 0){
991
+ prop = props[i];
992
+ if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
993
+ destObj[prop] = sourceObj[prop];
994
+ merged[prop] = true;
995
+ }
996
+ }
997
+ sourceObj = false !== filter && getPrototypeOf(sourceObj);
998
+ }while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
999
+ return destObj;
1000
+ };
1001
+ /**
1002
+ * Determines whether a string ends with the characters of a specified string
1003
+ *
1004
+ * @param {String} str
1005
+ * @param {String} searchString
1006
+ * @param {Number} [position= 0]
1007
+ *
1008
+ * @returns {boolean}
1009
+ */ const endsWith = (str, searchString, position)=>{
1010
+ str = String(str);
1011
+ if (void 0 === position || position > str.length) position = str.length;
1012
+ position -= searchString.length;
1013
+ const lastIndex = str.indexOf(searchString, position);
1014
+ return -1 !== lastIndex && lastIndex === position;
1015
+ };
1016
+ /**
1017
+ * Returns new array from array like object or null if failed
1018
+ *
1019
+ * @param {*} [thing]
1020
+ *
1021
+ * @returns {?Array}
1022
+ */ const toArray = (thing)=>{
1023
+ if (!thing) return null;
1024
+ if (isArray(thing)) return thing;
1025
+ let i = thing.length;
1026
+ if (!isNumber(i)) return null;
1027
+ const arr = new Array(i);
1028
+ while(i-- > 0)arr[i] = thing[i];
1029
+ return arr;
1030
+ };
1031
+ /**
1032
+ * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
1033
+ * thing passed in is an instance of Uint8Array
1034
+ *
1035
+ * @param {TypedArray}
1036
+ *
1037
+ * @returns {Array}
1038
+ */ // eslint-disable-next-line func-names
1039
+ const isTypedArray = ((TypedArray)=>(thing)=>TypedArray && thing instanceof TypedArray)('undefined' != typeof Uint8Array && getPrototypeOf(Uint8Array));
1040
+ /**
1041
+ * For each entry in the object, call the function with the key and value.
1042
+ *
1043
+ * @param {Object<any, any>} obj - The object to iterate over.
1044
+ * @param {Function} fn - The function to call for each entry.
1045
+ *
1046
+ * @returns {void}
1047
+ */ const forEachEntry = (obj, fn)=>{
1048
+ const generator = obj && obj[Symbol.iterator];
1049
+ const iterator = generator.call(obj);
1050
+ let result;
1051
+ while((result = iterator.next()) && !result.done){
1052
+ const pair = result.value;
1053
+ fn.call(obj, pair[0], pair[1]);
1054
+ }
1055
+ };
1056
+ /**
1057
+ * It takes a regular expression and a string, and returns an array of all the matches
1058
+ *
1059
+ * @param {string} regExp - The regular expression to match against.
1060
+ * @param {string} str - The string to search.
1061
+ *
1062
+ * @returns {Array<boolean>}
1063
+ */ const matchAll = (regExp, str)=>{
1064
+ let matches;
1065
+ const arr = [];
1066
+ while(null !== (matches = regExp.exec(str)))arr.push(matches);
1067
+ return arr;
1068
+ };
1069
+ /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ const isHTMLForm = kindOfTest('HTMLFormElement');
1070
+ const toCamelCase = (str)=>str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function(m, p1, p2) {
1071
+ return p1.toUpperCase() + p2;
1072
+ });
1073
+ /* Creating a function that will check if an object has a property. */ const utils_hasOwnProperty = (({ hasOwnProperty })=>(obj, prop)=>hasOwnProperty.call(obj, prop))(Object.prototype);
1074
+ /**
1075
+ * Determine if a value is a RegExp object
1076
+ *
1077
+ * @param {*} val The value to test
1078
+ *
1079
+ * @returns {boolean} True if value is a RegExp object, otherwise false
1080
+ */ const isRegExp = kindOfTest('RegExp');
1081
+ const reduceDescriptors = (obj, reducer)=>{
1082
+ const descriptors = Object.getOwnPropertyDescriptors(obj);
1083
+ const reducedDescriptors = {};
1084
+ forEach(descriptors, (descriptor, name)=>{
1085
+ let ret;
1086
+ if (false !== (ret = reducer(descriptor, name, obj))) reducedDescriptors[name] = ret || descriptor;
1087
+ });
1088
+ Object.defineProperties(obj, reducedDescriptors);
1089
+ };
1090
+ /**
1091
+ * Makes all methods read-only
1092
+ * @param {Object} obj
1093
+ */ const freezeMethods = (obj)=>{
1094
+ reduceDescriptors(obj, (descriptor, name)=>{
1095
+ // skip restricted props in strict mode
1096
+ if (isFunction(obj) && -1 !== [
1097
+ 'arguments',
1098
+ 'caller',
1099
+ 'callee'
1100
+ ].indexOf(name)) return false;
1101
+ const value = obj[name];
1102
+ if (!isFunction(value)) return;
1103
+ descriptor.enumerable = false;
1104
+ if ('writable' in descriptor) {
1105
+ descriptor.writable = false;
1106
+ return;
1107
+ }
1108
+ if (!descriptor.set) descriptor.set = ()=>{
1109
+ throw Error('Can not rewrite read-only method \'' + name + '\'');
1110
+ };
1111
+ });
1112
+ };
1113
+ const toObjectSet = (arrayOrString, delimiter)=>{
1114
+ const obj = {};
1115
+ const define1 = (arr)=>{
1116
+ arr.forEach((value)=>{
1117
+ obj[value] = true;
1118
+ });
1119
+ };
1120
+ isArray(arrayOrString) ? define1(arrayOrString) : define1(String(arrayOrString).split(delimiter));
1121
+ return obj;
1122
+ };
1123
+ const noop = ()=>{};
1124
+ const toFiniteNumber = (value, defaultValue)=>null != value && Number.isFinite(value = +value) ? value : defaultValue;
1125
+ const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
1126
+ const DIGIT = '0123456789';
1127
+ const ALPHABET = {
1128
+ DIGIT,
1129
+ ALPHA,
1130
+ ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
1131
+ };
1132
+ const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT)=>{
1133
+ let str = '';
1134
+ const { length } = alphabet;
1135
+ while(size--)str += alphabet[Math.random() * length | 0];
1136
+ return str;
1137
+ };
1138
+ /**
1139
+ * If the thing is a FormData object, return true, otherwise return false.
1140
+ *
1141
+ * @param {unknown} thing - The thing to check.
1142
+ *
1143
+ * @returns {boolean}
1144
+ */ function isSpecCompliantForm(thing) {
1145
+ return !!(thing && isFunction(thing.append) && 'FormData' === thing[Symbol.toStringTag] && thing[Symbol.iterator]);
1146
+ }
1147
+ const toJSONObject = (obj)=>{
1148
+ const stack = new Array(10);
1149
+ const visit = (source, i)=>{
1150
+ if (isObject(source)) {
1151
+ if (stack.indexOf(source) >= 0) return;
1152
+ if (!('toJSON' in source)) {
576
1153
  stack[i] = source;
577
1154
  const target = isArray(source) ? [] : {};
578
1155
  forEach(source, (value, key)=>{
@@ -615,7 +1192,7 @@
615
1192
  isNumber,
616
1193
  isBoolean,
617
1194
  isObject,
618
- isPlainObject,
1195
+ isPlainObject: utils_isPlainObject,
619
1196
  isReadableStream,
620
1197
  isRequest,
621
1198
  isResponse,
@@ -1813,7 +2390,7 @@
1813
2390
  * @param {Object} config2
1814
2391
  *
1815
2392
  * @returns {Object} New object resulting from merging config2 to config1
1816
- */ function mergeConfig(config1, config2) {
2393
+ */ function mergeConfig_mergeConfig(config1, config2) {
1817
2394
  // eslint-disable-next-line no-param-reassign
1818
2395
  config2 = config2 || {};
1819
2396
  const config = {};
@@ -1883,7 +2460,7 @@
1883
2460
  return config;
1884
2461
  }
1885
2462
  /* ESM default export */ const resolveConfig = (config)=>{
1886
- const newConfig = mergeConfig({}, config);
2463
+ const newConfig = mergeConfig_mergeConfig({}, config);
1887
2464
  let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig;
1888
2465
  newConfig.headers = headers = AxiosHeaders.from(headers);
1889
2466
  newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer);
@@ -2141,7 +2718,7 @@
2141
2718
  }, {
2142
2719
  highWaterMark: 2
2143
2720
  });
2144
- }; // CONCATENATED MODULE: ../../common/temp/default/node_modules/.pnpm/axios@1.7.7/node_modules/axios/lib/adapters/fetch.js
2721
+ }; // CONCATENATED MODULE: ../../common/temp/default/node_modules/.pnpm/axios@1.7.7_debug@4.3.7/node_modules/axios/lib/adapters/fetch.js
2145
2722
  const isFetchSupported = 'function' == typeof fetch && 'function' == typeof Request && 'function' == typeof Response;
2146
2723
  const isReadableStreamSupported = isFetchSupported && 'function' == typeof ReadableStream;
2147
2724
  // used only inside the fetch adapter
@@ -2489,7 +3066,7 @@
2489
3066
  config = config || {};
2490
3067
  config.url = configOrUrl;
2491
3068
  } else config = configOrUrl || {};
2492
- config = mergeConfig(this.defaults, config);
3069
+ config = mergeConfig_mergeConfig(this.defaults, config);
2493
3070
  const { transitional, paramsSerializer, headers } = config;
2494
3071
  if (void 0 !== transitional) helpers_validator.assertOptions(transitional, {
2495
3072
  silentJSONParsing: Axios_validators.transitional(Axios_validators.boolean),
@@ -2542,851 +3119,326 @@
2542
3119
  void 0
2543
3120
  ];
2544
3121
  chain.unshift.apply(chain, requestInterceptorChain);
2545
- chain.push.apply(chain, responseInterceptorChain);
2546
- len = chain.length;
2547
- promise = Promise.resolve(config);
2548
- while(i < len)promise = promise.then(chain[i++], chain[i++]);
2549
- return promise;
2550
- }
2551
- len = requestInterceptorChain.length;
2552
- let newConfig = config;
2553
- i = 0;
2554
- while(i < len){
2555
- const onFulfilled = requestInterceptorChain[i++];
2556
- const onRejected = requestInterceptorChain[i++];
2557
- try {
2558
- newConfig = onFulfilled(newConfig);
2559
- } catch (error) {
2560
- onRejected.call(this, error);
2561
- break;
2562
- }
2563
- }
2564
- try {
2565
- promise = dispatchRequest.call(this, newConfig);
2566
- } catch (error) {
2567
- return Promise.reject(error);
2568
- }
2569
- i = 0;
2570
- len = responseInterceptorChain.length;
2571
- while(i < len)promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
2572
- return promise;
2573
- }
2574
- getUri(config) {
2575
- config = mergeConfig(this.defaults, config);
2576
- const fullPath = buildFullPath(config.baseURL, config.url);
2577
- return buildURL(fullPath, config.params, config.paramsSerializer);
2578
- }
2579
- }
2580
- // Provide aliases for supported request methods
2581
- utils.forEach([
2582
- 'delete',
2583
- 'get',
2584
- 'head',
2585
- 'options'
2586
- ], function(method) {
2587
- /*eslint func-names:0*/ Axios_Axios.prototype[method] = function(url, config) {
2588
- return this.request(mergeConfig(config || {}, {
2589
- method,
2590
- url,
2591
- data: (config || {}).data
2592
- }));
2593
- };
2594
- });
2595
- utils.forEach([
2596
- 'post',
2597
- 'put',
2598
- 'patch'
2599
- ], function(method) {
2600
- /*eslint func-names:0*/ function generateHTTPMethod(isForm) {
2601
- return function(url, data, config) {
2602
- return this.request(mergeConfig(config || {}, {
2603
- method,
2604
- headers: isForm ? {
2605
- 'Content-Type': 'multipart/form-data'
2606
- } : {},
2607
- url,
2608
- data
2609
- }));
2610
- };
2611
- }
2612
- Axios_Axios.prototype[method] = generateHTTPMethod();
2613
- Axios_Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
2614
- });
2615
- /* ESM default export */ const Axios = Axios_Axios;
2616
- /**
2617
- * A `CancelToken` is an object that can be used to request cancellation of an operation.
2618
- *
2619
- * @param {Function} executor The executor function.
2620
- *
2621
- * @returns {CancelToken}
2622
- */ class CancelToken_CancelToken {
2623
- constructor(executor){
2624
- if ('function' != typeof executor) throw new TypeError('executor must be a function.');
2625
- let resolvePromise;
2626
- this.promise = new Promise(function(resolve) {
2627
- resolvePromise = resolve;
2628
- });
2629
- const token = this;
2630
- // eslint-disable-next-line func-names
2631
- this.promise.then((cancel)=>{
2632
- if (!token._listeners) return;
2633
- let i = token._listeners.length;
2634
- while(i-- > 0)token._listeners[i](cancel);
2635
- token._listeners = null;
2636
- });
2637
- // eslint-disable-next-line func-names
2638
- this.promise.then = (onfulfilled)=>{
2639
- let _resolve;
2640
- // eslint-disable-next-line func-names
2641
- const promise = new Promise((resolve)=>{
2642
- token.subscribe(resolve);
2643
- _resolve = resolve;
2644
- }).then(onfulfilled);
2645
- promise.cancel = function() {
2646
- token.unsubscribe(_resolve);
2647
- };
2648
- return promise;
2649
- };
2650
- executor(function(message, config, request) {
2651
- if (token.reason) // Cancellation has already been requested
2652
- return;
2653
- token.reason = new CanceledError(message, config, request);
2654
- resolvePromise(token.reason);
2655
- });
2656
- }
2657
- /**
2658
- * Throws a `CanceledError` if cancellation has been requested.
2659
- */ throwIfRequested() {
2660
- if (this.reason) throw this.reason;
2661
- }
2662
- /**
2663
- * Subscribe to the cancel signal
2664
- */ subscribe(listener) {
2665
- if (this.reason) {
2666
- listener(this.reason);
2667
- return;
2668
- }
2669
- if (this._listeners) this._listeners.push(listener);
2670
- else this._listeners = [
2671
- listener
2672
- ];
2673
- }
2674
- /**
2675
- * Unsubscribe from the cancel signal
2676
- */ unsubscribe(listener) {
2677
- if (!this._listeners) return;
2678
- const index = this._listeners.indexOf(listener);
2679
- if (-1 !== index) this._listeners.splice(index, 1);
2680
- }
2681
- toAbortSignal() {
2682
- const controller = new AbortController();
2683
- const abort = (err)=>{
2684
- controller.abort(err);
2685
- };
2686
- this.subscribe(abort);
2687
- controller.signal.unsubscribe = ()=>this.unsubscribe(abort);
2688
- return controller.signal;
2689
- }
2690
- /**
2691
- * Returns an object that contains a new `CancelToken` and a function that, when called,
2692
- * cancels the `CancelToken`.
2693
- */ static source() {
2694
- let cancel;
2695
- const token = new CancelToken_CancelToken(function(c) {
2696
- cancel = c;
2697
- });
2698
- return {
2699
- token,
2700
- cancel
2701
- };
2702
- }
2703
- }
2704
- /* ESM default export */ const CancelToken = CancelToken_CancelToken;
2705
- /**
2706
- * Syntactic sugar for invoking a function and expanding an array for arguments.
2707
- *
2708
- * Common use case would be to use `Function.prototype.apply`.
2709
- *
2710
- * ```js
2711
- * function f(x, y, z) {}
2712
- * var args = [1, 2, 3];
2713
- * f.apply(null, args);
2714
- * ```
2715
- *
2716
- * With `spread` this example can be re-written.
2717
- *
2718
- * ```js
2719
- * spread(function(x, y, z) {})([1, 2, 3]);
2720
- * ```
2721
- *
2722
- * @param {Function} callback
2723
- *
2724
- * @returns {Function}
2725
- */ function spread(callback) {
2726
- return function(arr) {
2727
- return callback.apply(null, arr);
2728
- };
2729
- }
2730
- /**
2731
- * Determines whether the payload is an error thrown by Axios
2732
- *
2733
- * @param {*} payload The value to test
2734
- *
2735
- * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
2736
- */ function isAxiosError(payload) {
2737
- return utils.isObject(payload) && true === payload.isAxiosError;
2738
- }
2739
- const HttpStatusCode = {
2740
- Continue: 100,
2741
- SwitchingProtocols: 101,
2742
- Processing: 102,
2743
- EarlyHints: 103,
2744
- Ok: 200,
2745
- Created: 201,
2746
- Accepted: 202,
2747
- NonAuthoritativeInformation: 203,
2748
- NoContent: 204,
2749
- ResetContent: 205,
2750
- PartialContent: 206,
2751
- MultiStatus: 207,
2752
- AlreadyReported: 208,
2753
- ImUsed: 226,
2754
- MultipleChoices: 300,
2755
- MovedPermanently: 301,
2756
- Found: 302,
2757
- SeeOther: 303,
2758
- NotModified: 304,
2759
- UseProxy: 305,
2760
- Unused: 306,
2761
- TemporaryRedirect: 307,
2762
- PermanentRedirect: 308,
2763
- BadRequest: 400,
2764
- Unauthorized: 401,
2765
- PaymentRequired: 402,
2766
- Forbidden: 403,
2767
- NotFound: 404,
2768
- MethodNotAllowed: 405,
2769
- NotAcceptable: 406,
2770
- ProxyAuthenticationRequired: 407,
2771
- RequestTimeout: 408,
2772
- Conflict: 409,
2773
- Gone: 410,
2774
- LengthRequired: 411,
2775
- PreconditionFailed: 412,
2776
- PayloadTooLarge: 413,
2777
- UriTooLong: 414,
2778
- UnsupportedMediaType: 415,
2779
- RangeNotSatisfiable: 416,
2780
- ExpectationFailed: 417,
2781
- ImATeapot: 418,
2782
- MisdirectedRequest: 421,
2783
- UnprocessableEntity: 422,
2784
- Locked: 423,
2785
- FailedDependency: 424,
2786
- TooEarly: 425,
2787
- UpgradeRequired: 426,
2788
- PreconditionRequired: 428,
2789
- TooManyRequests: 429,
2790
- RequestHeaderFieldsTooLarge: 431,
2791
- UnavailableForLegalReasons: 451,
2792
- InternalServerError: 500,
2793
- NotImplemented: 501,
2794
- BadGateway: 502,
2795
- ServiceUnavailable: 503,
2796
- GatewayTimeout: 504,
2797
- HttpVersionNotSupported: 505,
2798
- VariantAlsoNegotiates: 506,
2799
- InsufficientStorage: 507,
2800
- LoopDetected: 508,
2801
- NotExtended: 510,
2802
- NetworkAuthenticationRequired: 511
2803
- };
2804
- Object.entries(HttpStatusCode).forEach(([key, value])=>{
2805
- HttpStatusCode[value] = key;
2806
- });
2807
- /* ESM default export */ const helpers_HttpStatusCode = HttpStatusCode;
2808
- /**
2809
- * Create an instance of Axios
2810
- *
2811
- * @param {Object} defaultConfig The default config for the instance
2812
- *
2813
- * @returns {Axios} A new instance of Axios
2814
- */ function createInstance(defaultConfig) {
2815
- const context = new Axios(defaultConfig);
2816
- const instance = bind(Axios.prototype.request, context);
2817
- // Copy axios.prototype to instance
2818
- utils.extend(instance, Axios.prototype, context, {
2819
- allOwnKeys: true
2820
- });
2821
- // Copy context to instance
2822
- utils.extend(instance, context, null, {
2823
- allOwnKeys: true
2824
- });
2825
- // Factory for creating new instances
2826
- instance.create = function(instanceConfig) {
2827
- return createInstance(mergeConfig(defaultConfig, instanceConfig));
2828
- };
2829
- return instance;
2830
- }
2831
- // Create the default instance to be exported
2832
- const axios = createInstance(defaults);
2833
- // Expose Axios class to allow class inheritance
2834
- axios.Axios = Axios;
2835
- // Expose Cancel & CancelToken
2836
- axios.CanceledError = CanceledError;
2837
- axios.CancelToken = CancelToken;
2838
- axios.isCancel = isCancel;
2839
- axios.VERSION = VERSION;
2840
- axios.toFormData = toFormData;
2841
- // Expose AxiosError class
2842
- axios.AxiosError = core_AxiosError;
2843
- // alias for CanceledError for backward compatibility
2844
- axios.Cancel = axios.CanceledError;
2845
- // Expose all/spread
2846
- axios.all = function(promises) {
2847
- return Promise.all(promises);
2848
- };
2849
- axios.spread = spread;
2850
- // Expose isAxiosError
2851
- axios.isAxiosError = isAxiosError;
2852
- // Expose mergeConfig
2853
- axios.mergeConfig = mergeConfig;
2854
- axios.AxiosHeaders = AxiosHeaders;
2855
- axios.formToJSON = (thing)=>formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
2856
- axios.getAdapter = adapters_adapters.getAdapter;
2857
- axios.HttpStatusCode = helpers_HttpStatusCode;
2858
- axios.default = axios;
2859
- // this module should only have a default export
2860
- /* ESM default export */ const lib_axios = axios;
2861
- // This module is intended to unwrap Axios default export as named.
2862
- // Keep top-level export same with static properties
2863
- // so that it can keep same with es module or cjs
2864
- 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;
2865
- // EXTERNAL MODULE: os (ignored)
2866
- var os_ignored_ = __webpack_require__("?d039");
2867
- // EXTERNAL MODULE: crypto (ignored)
2868
- __webpack_require__("?de24");
2869
- // EXTERNAL MODULE: jsonwebtoken (ignored)
2870
- __webpack_require__("?2a9f");
2871
- class APIResource {
2872
- constructor(client){
2873
- this._client = client;
2874
- }
2875
- }
2876
- /* eslint-disable @typescript-eslint/no-namespace */ class Bots extends APIResource {
2877
- /**
2878
- * Create a new agent. | 调用接口创建一个新的智能体。
2879
- * @docs en:https://www.coze.com/docs/developer_guides/create_bot?_lang=en
2880
- * @docs zh:https://www.coze.cn/docs/developer_guides/create_bot?_lang=zh
2881
- * @param params - Required The parameters for creating a bot. | 创建 Bot 的参数。
2882
- * @param params.space_id - Required The Space ID of the space where the agent is located. | Bot 所在的空间的 Space ID。
2883
- * @param params.name - Required The name of the agent. It should be 1 to 20 characters long. | Bot 的名称。
2884
- * @param params.description - Optional The description of the agent. It can be 0 to 500 characters long. | Bot 的描述信息。
2885
- * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
2886
- * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
2887
- * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
2888
- * @returns Information about the created bot. | 创建的 Bot 信息。
2889
- */ async create(params, options) {
2890
- const apiUrl = '/v1/bot/create';
2891
- const result = await this._client.post(apiUrl, params, false, options);
2892
- return result.data;
2893
- }
2894
- /**
2895
- * Update the configuration of an agent. | 调用接口修改智能体的配置。
2896
- * @docs en:https://www.coze.com/docs/developer_guides/update_bot?_lang=en
2897
- * @docs zh:https://www.coze.cn/docs/developer_guides/update_bot?_lang=zh
2898
- * @param params - Required The parameters for updating a bot. | 修改 Bot 的参数。
2899
- * @param params.bot_id - Required The ID of the agent that the API interacts with. | 待修改配置的智能体ID。
2900
- * @param params.name - Optional The name of the agent. | Bot 的名称。
2901
- * @param params.description - Optional The description of the agent. | Bot 的描述信息。
2902
- * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
2903
- * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
2904
- * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
2905
- * @param params.knowledge - Optional Knowledge configurations of the agent. | Bot 的知识库配置。
2906
- * @returns Undefined | 无返回值
2907
- */ async update(params, options) {
2908
- const apiUrl = '/v1/bot/update';
2909
- const result = await this._client.post(apiUrl, params, false, options);
2910
- return result.data;
2911
- }
2912
- /**
2913
- * Get the agents published as API service. | 调用接口查看指定空间发布到 Agent as API 渠道的智能体列表。
2914
- * @docs en:https://www.coze.com/docs/developer_guides/published_bots_list?_lang=en
2915
- * @docs zh:https://www.coze.cn/docs/developer_guides/published_bots_list?_lang=zh
2916
- * @param params - Required The parameters for listing bots. | 列出 Bot 的参数。
2917
- * @param params.space_id - Required The ID of the space. | Bot 所在的空间的 Space ID。
2918
- * @param params.page_size - Optional Pagination size. | 分页大小。
2919
- * @param params.page_index - Optional Page number for paginated queries. | 分页查询时的页码。
2920
- * @returns List of published bots. | 已发布的 Bot 列表。
2921
- */ async list(params, options) {
2922
- const apiUrl = '/v1/space/published_bots_list';
2923
- const result = await this._client.get(apiUrl, params, false, options);
2924
- return result.data;
2925
- }
2926
- /**
2927
- * Publish the specified agent as an API service. | 调用接口创建一个新的智能体。
2928
- * @docs en:https://www.coze.com/docs/developer_guides/publish_bot?_lang=en
2929
- * @docs zh:https://www.coze.cn/docs/developer_guides/publish_bot?_lang=zh
2930
- * @param params - Required The parameters for publishing a bot. | 发布 Bot 的参数。
2931
- * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要发布的智能体ID。
2932
- * @param params.connector_ids - Required The list of publishing channel IDs for the agent. | 智能体的发布渠道 ID 列表。
2933
- * @returns Undefined | 无返回值
2934
- */ async publish(params, options) {
2935
- const apiUrl = '/v1/bot/publish';
2936
- const result = await this._client.post(apiUrl, params, false, options);
2937
- return result.data;
2938
- }
2939
- /**
2940
- * Get the configuration information of the agent. | 获取指定智能体的配置信息。
2941
- * @docs en:https://www.coze.com/docs/developer_guides/get_metadata?_lang=en
2942
- * @docs zh:https://www.coze.cn/docs/developer_guides/get_metadata?_lang=zh
2943
- * @param params - Required The parameters for retrieving a bot. | 获取 Bot 的参数。
2944
- * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要查看的智能体ID。
2945
- * @returns Information about the bot. | Bot 的配置信息。
2946
- */ async retrieve(params, options) {
2947
- const apiUrl = '/v1/bot/get_online_info';
2948
- const result = await this._client.get(apiUrl, params, false, options);
2949
- return result.data;
2950
- }
2951
- }
2952
- /* eslint-disable security/detect-object-injection */ /* eslint-disable @typescript-eslint/no-explicit-any */ function safeJsonParse(jsonString) {
2953
- let defaultValue = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : '';
2954
- try {
2955
- return JSON.parse(jsonString);
2956
- } catch (error) {
2957
- return defaultValue;
2958
- }
2959
- }
2960
- function sleep(ms) {
2961
- return new Promise((resolve)=>{
2962
- setTimeout(resolve, ms);
2963
- });
2964
- }
2965
- function isBrowser() {
2966
- return 'undefined' != typeof window;
2967
- }
2968
- function esm_isPlainObject(obj) {
2969
- if ('object' != typeof obj || null === obj) return false;
2970
- const proto = Object.getPrototypeOf(obj);
2971
- if (null === proto) return true;
2972
- let baseProto = proto;
2973
- while(null !== Object.getPrototypeOf(baseProto))baseProto = Object.getPrototypeOf(baseProto);
2974
- return proto === baseProto;
2975
- }
2976
- function esm_mergeConfig() {
2977
- for(var _len = arguments.length, objects = new Array(_len), _key = 0; _key < _len; _key++)objects[_key] = arguments[_key];
2978
- return objects.reduce((result, obj)=>{
2979
- if (void 0 === obj) return result || {};
2980
- for(const key in obj)if (Object.prototype.hasOwnProperty.call(obj, key)) {
2981
- if (esm_isPlainObject(obj[key]) && !Array.isArray(obj[key])) result[key] = esm_mergeConfig(result[key] || {}, obj[key]);
2982
- else result[key] = obj[key];
2983
- }
2984
- return result;
2985
- }, {});
2986
- }
2987
- function isPersonalAccessToken(token) {
2988
- return null == token ? void 0 : token.startsWith('pat_');
2989
- }
2990
- /* eslint-disable max-params */ class CozeError extends Error {
2991
- }
2992
- class APIError extends CozeError {
2993
- static makeMessage(status, errorBody, message, headers) {
2994
- if (!errorBody && message) return message;
2995
- if (errorBody) {
2996
- const list = [];
2997
- const { code, msg, error } = errorBody;
2998
- if (code) list.push(`code: ${code}`);
2999
- if (msg) list.push(`msg: ${msg}`);
3000
- if ((null == error ? void 0 : error.detail) && msg !== error.detail) list.push(`detail: ${error.detail}`);
3001
- const logId = (null == error ? void 0 : error.logid) || (null == headers ? void 0 : headers['x-tt-logid']);
3002
- if (logId) list.push(`logid: ${logId}`);
3003
- const help_doc = null == error ? void 0 : error.help_doc;
3004
- if (help_doc) list.push(`help doc: ${help_doc}`);
3005
- return list.join(', ');
3006
- }
3007
- if (status) return `http status code: ${status} (no body)`;
3008
- return '(no status code or body)';
3009
- }
3010
- static generate(status, errorResponse, message, headers) {
3011
- if (!status) return new APIConnectionError({
3012
- cause: castToError(errorResponse)
3013
- });
3014
- const error = errorResponse;
3015
- // https://www.coze.cn/docs/developer_guides/coze_error_codes
3016
- if (400 === status || (null == error ? void 0 : error.code) === 4000) return new BadRequestError(status, error, message, headers);
3017
- if (401 === status || (null == error ? void 0 : error.code) === 4100) return new AuthenticationError(status, error, message, headers);
3018
- if (403 === status || (null == error ? void 0 : error.code) === 4101) return new PermissionDeniedError(status, error, message, headers);
3019
- if (404 === status || (null == error ? void 0 : error.code) === 4200) return new NotFoundError(status, error, message, headers);
3020
- if (429 === status || (null == error ? void 0 : error.code) === 4013) return new RateLimitError(status, error, message, headers);
3021
- if (408 === status) return new TimeoutError(status, error, message, headers);
3022
- if (502 === status) return new GatewayError(status, error, message, headers);
3023
- if (status >= 500) return new InternalServerError(status, error, message, headers);
3024
- return new APIError(status, error, message, headers);
3025
- }
3026
- constructor(status, error, message, headers){
3027
- var _error_error, _error_error1;
3028
- super(`${APIError.makeMessage(status, error, message, headers)}`);
3029
- this.status = status;
3030
- this.headers = headers;
3031
- this.logid = null == headers ? void 0 : headers['x-tt-logid'];
3032
- // this.error = error;
3033
- this.code = null == error ? void 0 : error.code;
3034
- this.msg = null == error ? void 0 : error.msg;
3035
- this.detail = null == error ? void 0 : null === (_error_error = error.error) || void 0 === _error_error ? void 0 : _error_error.detail;
3036
- this.help_doc = null == error ? void 0 : null === (_error_error1 = error.error) || void 0 === _error_error1 ? void 0 : _error_error1.help_doc;
3037
- this.rawError = error;
3038
- }
3039
- }
3040
- class APIConnectionError extends APIError {
3041
- constructor({ message, cause }){
3042
- super(void 0, void 0, message || 'Connection error.', void 0), this.status = void 0;
3043
- // if (cause) {
3044
- // this.cause = cause;
3045
- // }
3046
- }
3047
- }
3048
- class APIUserAbortError extends APIError {
3049
- constructor(message){
3050
- super(void 0, void 0, message || 'Request was aborted.', void 0), this.name = 'UserAbortError', this.status = void 0;
3051
- }
3052
- }
3053
- class BadRequestError extends APIError {
3054
- constructor(...args){
3055
- super(...args), this.name = 'BadRequestError', this.status = 400;
3056
- }
3057
- }
3058
- class AuthenticationError extends APIError {
3059
- constructor(...args){
3060
- super(...args), this.name = 'AuthenticationError', this.status = 401;
3061
- }
3062
- }
3063
- class PermissionDeniedError extends APIError {
3064
- constructor(...args){
3065
- super(...args), this.name = 'PermissionDeniedError', this.status = 403;
3066
- }
3067
- }
3068
- class NotFoundError extends APIError {
3069
- constructor(...args){
3070
- super(...args), this.name = 'NotFoundError', this.status = 404;
3071
- }
3072
- }
3073
- class TimeoutError extends APIError {
3074
- constructor(...args){
3075
- super(...args), this.name = 'TimeoutError', this.status = 408;
3076
- }
3077
- }
3078
- class RateLimitError extends APIError {
3079
- constructor(...args){
3080
- super(...args), this.name = 'RateLimitError', this.status = 429;
3081
- }
3082
- }
3083
- class InternalServerError extends APIError {
3084
- constructor(...args){
3085
- super(...args), this.name = 'InternalServerError', this.status = 500;
3086
- }
3087
- }
3088
- class GatewayError extends APIError {
3089
- constructor(...args){
3090
- super(...args), this.name = 'GatewayError', this.status = 502;
3091
- }
3092
- }
3093
- const castToError = (err)=>{
3094
- if (err instanceof Error) return err;
3095
- return new Error(err);
3096
- };
3097
- class Messages extends APIResource {
3098
- /**
3099
- * Get the list of messages in a chat. | 获取对话中的消息列表。
3100
- * @docs en:https://www.coze.com/docs/developer_guides/chat_message_list?_lang=en
3101
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_message_list?_lang=zh
3102
- * @param conversation_id - Required The ID of the conversation. | 会话 ID。
3103
- * @param chat_id - Required The ID of the chat. | 对话 ID。
3104
- * @returns An array of chat messages. | 对话消息数组。
3105
- */ async list(conversation_id, chat_id, options) {
3106
- const apiUrl = `/v3/chat/message/list?conversation_id=${conversation_id}&chat_id=${chat_id}`;
3107
- const result = await this._client.get(apiUrl, void 0, false, options);
3108
- return result.data;
3109
- }
3110
- }
3111
- const uuid = ()=>(Math.random() * new Date().getTime()).toString();
3112
- class Chat extends APIResource {
3113
- /**
3114
- * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
3115
- * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
3116
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
3117
- * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
3118
- * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
3119
- * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
3120
- * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
3121
- * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义变量。
3122
- * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
3123
- * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
3124
- * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
3125
- * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
3126
- * @returns The data of the created chat. | 创建的对话数据。
3127
- */ async create(params, options) {
3128
- if (!params.user_id) params.user_id = uuid();
3129
- const { conversation_id, ...rest } = params;
3130
- const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
3131
- const payload = {
3132
- ...rest,
3133
- stream: false
3134
- };
3135
- const result = await this._client.post(apiUrl, payload, false, options);
3136
- return result.data;
3137
- }
3138
- /**
3139
- * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
3140
- * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
3141
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
3142
- * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
3143
- * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
3144
- * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
3145
- * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
3146
- * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
3147
- * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
3148
- * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
3149
- * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
3150
- * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
3151
- * @returns
3152
- */ async createAndPoll(params, options) {
3153
- if (!params.user_id) params.user_id = uuid();
3154
- const { conversation_id, ...rest } = params;
3155
- const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
3156
- const payload = {
3157
- ...rest,
3158
- stream: false
3159
- };
3160
- const result = await this._client.post(apiUrl, payload, false, options);
3161
- const chatId = result.data.id;
3162
- const conversationId = result.data.conversation_id;
3163
- let chat;
3164
- while(true){
3165
- await sleep(100);
3166
- chat = await this.retrieve(conversationId, chatId);
3167
- if ('completed' === chat.status || 'failed' === chat.status || 'requires_action' === chat.status) break;
3168
- }
3169
- const messageList = await this.messages.list(conversationId, chatId);
3170
- return {
3171
- chat,
3172
- messages: messageList
3173
- };
3174
- }
3175
- /**
3176
- * Call the Chat API to send messages to a published Coze agent with streaming response. | 调用此接口发起一次对话,支持流式响应。
3177
- * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
3178
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
3179
- * @param params - Required The parameters for streaming a chat session. | 流式会话的参数。
3180
- * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
3181
- * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
3182
- * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
3183
- * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
3184
- * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
3185
- * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
3186
- * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
3187
- * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
3188
- * @returns A stream of chat data. | 对话数据流。
3189
- */ async *stream(params, options) {
3190
- if (!params.user_id) params.user_id = uuid();
3191
- const { conversation_id, ...rest } = params;
3192
- const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
3193
- const payload = {
3194
- ...rest,
3195
- stream: true
3196
- };
3197
- const result = await this._client.post(apiUrl, payload, true, options);
3198
- for await (const message of result)if ("done" === message.event) {
3199
- const ret = {
3200
- event: message.event,
3201
- data: '[DONE]'
3202
- };
3203
- yield ret;
3204
- } else try {
3205
- const ret = {
3206
- event: message.event,
3207
- data: JSON.parse(message.data)
3208
- };
3209
- yield ret;
3210
- } catch (error) {
3211
- throw new CozeError(`Could not parse message into JSON:${message.data}`);
3212
- }
3213
- }
3214
- /**
3215
- * Get the detailed information of the chat. | 查看对话的详细信息。
3216
- * @docs en:https://www.coze.com/docs/developer_guides/retrieve_chat?_lang=en
3217
- * @docs zh:https://www.coze.cn/docs/developer_guides/retrieve_chat?_lang=zh
3218
- * @param conversation_id - Required The ID of the conversation. | 会话 ID。
3219
- * @param chat_id - Required The ID of the chat. | 对话 ID。
3220
- * @returns The data of the retrieved chat. | 检索到的对话数据。
3221
- */ async retrieve(conversation_id, chat_id, options) {
3222
- const apiUrl = `/v3/chat/retrieve?conversation_id=${conversation_id}&chat_id=${chat_id}`;
3223
- const result = await this._client.post(apiUrl, void 0, false, options);
3224
- return result.data;
3225
- }
3226
- /**
3227
- * Cancel a chat session. | 取消对话会话。
3228
- * @docs en:https://www.coze.com/docs/developer_guides/cancel_chat?_lang=en
3229
- * @docs zh:https://www.coze.cn/docs/developer_guides/cancel_chat?_lang=zh
3230
- * @param conversation_id - Required The ID of the conversation. | 会话 ID。
3231
- * @param chat_id - Required The ID of the chat. | 对话 ID。
3232
- * @returns The data of the canceled chat. | 取消的对话数据。
3233
- */ async cancel(conversation_id, chat_id, options) {
3234
- const apiUrl = '/v3/chat/cancel';
3235
- const payload = {
3236
- conversation_id,
3237
- chat_id
3238
- };
3239
- const result = await this._client.post(apiUrl, payload, false, options);
3240
- return result.data;
3241
- }
3242
- /**
3243
- * Submit tool outputs for a chat session. | 提交对话会话的工具输出。
3244
- * @docs en:https://www.coze.com/docs/developer_guides/chat_submit_tool_outputs?_lang=en
3245
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_submit_tool_outputs?_lang=zh
3246
- * @param params - Required Parameters for submitting tool outputs. | 提交工具输出的参数。
3247
- * @param params.conversation_id - Required The ID of the conversation. | 会话 ID。
3248
- * @param params.chat_id - Required The ID of the chat. | 对话 ID。
3249
- * @param params.tool_outputs - Required The outputs of the tool. | 工具的输出。
3250
- * @param params.stream - Optional Whether to use streaming response. | 是否使用流式响应。
3251
- * @returns The data of the submitted tool outputs or a stream of chat data. | 提交的工具输出数据或对话数据流。
3252
- */ async *submitToolOutputs(params, options) {
3253
- const { conversation_id, chat_id, ...rest } = params;
3254
- const apiUrl = `/v3/chat/submit_tool_outputs?conversation_id=${params.conversation_id}&chat_id=${params.chat_id}`;
3255
- const payload = {
3256
- ...rest
3257
- };
3258
- if (false === params.stream) {
3259
- const response = await this._client.post(apiUrl, payload, false, options);
3260
- return response.data;
3122
+ chain.push.apply(chain, responseInterceptorChain);
3123
+ len = chain.length;
3124
+ promise = Promise.resolve(config);
3125
+ while(i < len)promise = promise.then(chain[i++], chain[i++]);
3126
+ return promise;
3261
3127
  }
3262
- {
3263
- const result = await this._client.post(apiUrl, payload, true, options);
3264
- for await (const message of result)if ("done" === message.event) {
3265
- const ret = {
3266
- event: message.event,
3267
- data: '[DONE]'
3268
- };
3269
- yield ret;
3270
- } else try {
3271
- const ret = {
3272
- event: message.event,
3273
- data: JSON.parse(message.data)
3274
- };
3275
- yield ret;
3128
+ len = requestInterceptorChain.length;
3129
+ let newConfig = config;
3130
+ i = 0;
3131
+ while(i < len){
3132
+ const onFulfilled = requestInterceptorChain[i++];
3133
+ const onRejected = requestInterceptorChain[i++];
3134
+ try {
3135
+ newConfig = onFulfilled(newConfig);
3276
3136
  } catch (error) {
3277
- throw new CozeError(`Could not parse message into JSON:${message.data}`);
3137
+ onRejected.call(this, error);
3138
+ break;
3278
3139
  }
3279
3140
  }
3141
+ try {
3142
+ promise = dispatchRequest.call(this, newConfig);
3143
+ } catch (error) {
3144
+ return Promise.reject(error);
3145
+ }
3146
+ i = 0;
3147
+ len = responseInterceptorChain.length;
3148
+ while(i < len)promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
3149
+ return promise;
3280
3150
  }
3281
- constructor(...args){
3282
- super(...args), this.messages = new Messages(this._client);
3151
+ getUri(config) {
3152
+ config = mergeConfig_mergeConfig(this.defaults, config);
3153
+ const fullPath = buildFullPath(config.baseURL, config.url);
3154
+ return buildURL(fullPath, config.params, config.paramsSerializer);
3283
3155
  }
3284
3156
  }
3285
- class messages_Messages extends APIResource {
3286
- /**
3287
- * Create a message and add it to the specified conversation. | 创建一条消息,并将其添加到指定的会话中。
3288
- * @docs en: https://www.coze.com/docs/developer_guides/create_message?_lang=en
3289
- * @docs zh: https://www.coze.cn/docs/developer_guides/create_message?_lang=zh
3290
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3291
- * @param params - Required The parameters for creating a message | 创建消息所需的参数
3292
- * @param params.role - Required The entity that sent this message. Possible values: user, assistant. | 发送这条消息的实体。取值:user, assistant。
3293
- * @param params.content - Required The content of the message. | 消息的内容。
3294
- * @param params.content_type - Required The type of the message content. | 消息内容的类型。
3295
- * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
3296
- * @returns Information about the new message. | 消息详情。
3297
- */ async create(conversation_id, params, options) {
3298
- const apiUrl = `/v1/conversation/message/create?conversation_id=${conversation_id}`;
3299
- const response = await this._client.post(apiUrl, params, false, options);
3300
- return response.data;
3157
+ // Provide aliases for supported request methods
3158
+ utils.forEach([
3159
+ 'delete',
3160
+ 'get',
3161
+ 'head',
3162
+ 'options'
3163
+ ], function(method) {
3164
+ /*eslint func-names:0*/ Axios_Axios.prototype[method] = function(url, config) {
3165
+ return this.request(mergeConfig_mergeConfig(config || {}, {
3166
+ method,
3167
+ url,
3168
+ data: (config || {}).data
3169
+ }));
3170
+ };
3171
+ });
3172
+ utils.forEach([
3173
+ 'post',
3174
+ 'put',
3175
+ 'patch'
3176
+ ], function(method) {
3177
+ /*eslint func-names:0*/ function generateHTTPMethod(isForm) {
3178
+ return function(url, data, config) {
3179
+ return this.request(mergeConfig_mergeConfig(config || {}, {
3180
+ method,
3181
+ headers: isForm ? {
3182
+ 'Content-Type': 'multipart/form-data'
3183
+ } : {},
3184
+ url,
3185
+ data
3186
+ }));
3187
+ };
3301
3188
  }
3302
- /**
3303
- * Modify a message, supporting the modification of message content, additional content, and message type. | 修改一条消息,支持修改消息内容、附加内容和消息类型。
3304
- * @docs en: https://www.coze.com/docs/developer_guides/modify_message?_lang=en
3305
- * @docs zh: https://www.coze.cn/docs/developer_guides/modify_message?_lang=zh
3306
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3307
- * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
3308
- * @param params - Required The parameters for modifying a message | 修改消息所需的参数
3309
- * @param params.meta_data - Optional Additional information when modifying a message. | 修改消息时的附加消息。
3310
- * @param params.content - Optional The content of the message. | 消息的内容。
3311
- * @param params.content_type - Optional The type of the message content. | 消息内容的类型。
3312
- * @returns Information about the modified message. | 消息详情。
3313
- */ // eslint-disable-next-line max-params
3314
- async update(conversation_id, message_id, params, options) {
3315
- const apiUrl = `/v1/conversation/message/modify?conversation_id=${conversation_id}&message_id=${message_id}`;
3316
- const response = await this._client.post(apiUrl, params, false, options);
3317
- return response.message;
3189
+ Axios_Axios.prototype[method] = generateHTTPMethod();
3190
+ Axios_Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
3191
+ });
3192
+ /* ESM default export */ const Axios = Axios_Axios;
3193
+ /**
3194
+ * A `CancelToken` is an object that can be used to request cancellation of an operation.
3195
+ *
3196
+ * @param {Function} executor The executor function.
3197
+ *
3198
+ * @returns {CancelToken}
3199
+ */ class CancelToken_CancelToken {
3200
+ constructor(executor){
3201
+ if ('function' != typeof executor) throw new TypeError('executor must be a function.');
3202
+ let resolvePromise;
3203
+ this.promise = new Promise(function(resolve) {
3204
+ resolvePromise = resolve;
3205
+ });
3206
+ const token = this;
3207
+ // eslint-disable-next-line func-names
3208
+ this.promise.then((cancel)=>{
3209
+ if (!token._listeners) return;
3210
+ let i = token._listeners.length;
3211
+ while(i-- > 0)token._listeners[i](cancel);
3212
+ token._listeners = null;
3213
+ });
3214
+ // eslint-disable-next-line func-names
3215
+ this.promise.then = (onfulfilled)=>{
3216
+ let _resolve;
3217
+ // eslint-disable-next-line func-names
3218
+ const promise = new Promise((resolve)=>{
3219
+ token.subscribe(resolve);
3220
+ _resolve = resolve;
3221
+ }).then(onfulfilled);
3222
+ promise.cancel = function() {
3223
+ token.unsubscribe(_resolve);
3224
+ };
3225
+ return promise;
3226
+ };
3227
+ executor(function(message, config, request) {
3228
+ if (token.reason) // Cancellation has already been requested
3229
+ return;
3230
+ token.reason = new CanceledError(message, config, request);
3231
+ resolvePromise(token.reason);
3232
+ });
3318
3233
  }
3319
3234
  /**
3320
- * Get the detailed information of specified message. | 查看指定消息的详细信息。
3321
- * @docs en: https://www.coze.com/docs/developer_guides/retrieve_message?_lang=en
3322
- * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_message?_lang=zh
3323
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3324
- * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
3325
- * @returns Information about the message. | 消息详情。
3326
- */ async retrieve(conversation_id, message_id, options) {
3327
- const apiUrl = `/v1/conversation/message/retrieve?conversation_id=${conversation_id}&message_id=${message_id}`;
3328
- const response = await this._client.get(apiUrl, null, false, options);
3329
- return response.data;
3235
+ * Throws a `CanceledError` if cancellation has been requested.
3236
+ */ throwIfRequested() {
3237
+ if (this.reason) throw this.reason;
3330
3238
  }
3331
3239
  /**
3332
- * List messages in a conversation. | 列出会话中的消息。
3333
- * @docs en: https://www.coze.com/docs/developer_guides/message_list?_lang=en
3334
- * @docs zh: https://www.coze.cn/docs/developer_guides/message_list?_lang=zh
3335
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3336
- * @param params - Optional The parameters for listing messages | 列出消息所需的参数
3337
- * @param params.order - Optional The order of the messages. | 消息的顺序。
3338
- * @param params.chat_id - Optional The ID of the chat. | 聊天 ID。
3339
- * @param params.before_id - Optional The ID of the message before which to list. | 列出此消息之前的消息 ID。
3340
- * @param params.after_id - Optional The ID of the message after which to list. | 列出此消息之后的消息 ID。
3341
- * @param params.limit - Optional The maximum number of messages to return. | 返回的最大消息数。
3342
- * @returns A list of messages. | 消息列表。
3343
- */ async list(conversation_id, params, options) {
3344
- const apiUrl = `/v1/conversation/message/list?conversation_id=${conversation_id}`;
3345
- const response = await this._client.post(apiUrl, params, false, options);
3346
- return response;
3240
+ * Subscribe to the cancel signal
3241
+ */ subscribe(listener) {
3242
+ if (this.reason) {
3243
+ listener(this.reason);
3244
+ return;
3245
+ }
3246
+ if (this._listeners) this._listeners.push(listener);
3247
+ else this._listeners = [
3248
+ listener
3249
+ ];
3347
3250
  }
3348
3251
  /**
3349
- * Call the API to delete a message within a specified conversation. | 调用接口在指定会话中删除消息。
3350
- * @docs en: https://www.coze.com/docs/developer_guides/delete_message?_lang=en
3351
- * @docs zh: https://www.coze.cn/docs/developer_guides/delete_message?_lang=zh
3352
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3353
- * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
3354
- * @returns Details of the deleted message. | 已删除的消息详情。
3355
- */ async delete(conversation_id, message_id, options) {
3356
- const apiUrl = `/v1/conversation/message/delete?conversation_id=${conversation_id}&message_id=${message_id}`;
3357
- const response = await this._client.post(apiUrl, void 0, false, options);
3358
- return response.data;
3252
+ * Unsubscribe from the cancel signal
3253
+ */ unsubscribe(listener) {
3254
+ if (!this._listeners) return;
3255
+ const index = this._listeners.indexOf(listener);
3256
+ if (-1 !== index) this._listeners.splice(index, 1);
3359
3257
  }
3360
- }
3361
- class Conversations extends APIResource {
3362
- /**
3363
- * Create a conversation. Conversation is an interaction between an agent and a user, including one or more messages. | 调用接口创建一个会话。
3364
- * @docs en: https://www.coze.com/docs/developer_guides/create_conversation?_lang=en
3365
- * @docs zh: https://www.coze.cn/docs/developer_guides/create_conversation?_lang=zh
3366
- * @param params - Required The parameters for creating a conversation | 创建会话所需的参数
3367
- * @param params.messages - Optional Messages in the conversation. | 会话中的消息内容。
3368
- * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
3369
- * @returns Information about the created conversation. | 会话的基础信息。
3370
- */ async create(params, options) {
3371
- const apiUrl = '/v1/conversation/create';
3372
- const response = await this._client.post(apiUrl, params, false, options);
3373
- return response.data;
3258
+ toAbortSignal() {
3259
+ const controller = new AbortController();
3260
+ const abort = (err)=>{
3261
+ controller.abort(err);
3262
+ };
3263
+ this.subscribe(abort);
3264
+ controller.signal.unsubscribe = ()=>this.unsubscribe(abort);
3265
+ return controller.signal;
3374
3266
  }
3375
3267
  /**
3376
- * Get the information of specific conversation. | 通过会话 ID 查看会话信息。
3377
- * @docs en: https://www.coze.com/docs/developer_guides/retrieve_conversation?_lang=en
3378
- * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_conversation?_lang=zh
3379
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3380
- * @returns Information about the conversation. | 会话的基础信息。
3381
- */ async retrieve(conversation_id, options) {
3382
- const apiUrl = `/v1/conversation/retrieve?conversation_id=${conversation_id}`;
3383
- const response = await this._client.get(apiUrl, null, false, options);
3384
- return response.data;
3385
- }
3386
- constructor(...args){
3387
- super(...args), this.messages = new messages_Messages(this._client);
3268
+ * Returns an object that contains a new `CancelToken` and a function that, when called,
3269
+ * cancels the `CancelToken`.
3270
+ */ static source() {
3271
+ let cancel;
3272
+ const token = new CancelToken_CancelToken(function(c) {
3273
+ cancel = c;
3274
+ });
3275
+ return {
3276
+ token,
3277
+ cancel
3278
+ };
3388
3279
  }
3389
3280
  }
3281
+ /* ESM default export */ const CancelToken = CancelToken_CancelToken;
3282
+ /**
3283
+ * Syntactic sugar for invoking a function and expanding an array for arguments.
3284
+ *
3285
+ * Common use case would be to use `Function.prototype.apply`.
3286
+ *
3287
+ * ```js
3288
+ * function f(x, y, z) {}
3289
+ * var args = [1, 2, 3];
3290
+ * f.apply(null, args);
3291
+ * ```
3292
+ *
3293
+ * With `spread` this example can be re-written.
3294
+ *
3295
+ * ```js
3296
+ * spread(function(x, y, z) {})([1, 2, 3]);
3297
+ * ```
3298
+ *
3299
+ * @param {Function} callback
3300
+ *
3301
+ * @returns {Function}
3302
+ */ function spread(callback) {
3303
+ return function(arr) {
3304
+ return callback.apply(null, arr);
3305
+ };
3306
+ }
3307
+ /**
3308
+ * Determines whether the payload is an error thrown by Axios
3309
+ *
3310
+ * @param {*} payload The value to test
3311
+ *
3312
+ * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
3313
+ */ function isAxiosError(payload) {
3314
+ return utils.isObject(payload) && true === payload.isAxiosError;
3315
+ }
3316
+ const HttpStatusCode = {
3317
+ Continue: 100,
3318
+ SwitchingProtocols: 101,
3319
+ Processing: 102,
3320
+ EarlyHints: 103,
3321
+ Ok: 200,
3322
+ Created: 201,
3323
+ Accepted: 202,
3324
+ NonAuthoritativeInformation: 203,
3325
+ NoContent: 204,
3326
+ ResetContent: 205,
3327
+ PartialContent: 206,
3328
+ MultiStatus: 207,
3329
+ AlreadyReported: 208,
3330
+ ImUsed: 226,
3331
+ MultipleChoices: 300,
3332
+ MovedPermanently: 301,
3333
+ Found: 302,
3334
+ SeeOther: 303,
3335
+ NotModified: 304,
3336
+ UseProxy: 305,
3337
+ Unused: 306,
3338
+ TemporaryRedirect: 307,
3339
+ PermanentRedirect: 308,
3340
+ BadRequest: 400,
3341
+ Unauthorized: 401,
3342
+ PaymentRequired: 402,
3343
+ Forbidden: 403,
3344
+ NotFound: 404,
3345
+ MethodNotAllowed: 405,
3346
+ NotAcceptable: 406,
3347
+ ProxyAuthenticationRequired: 407,
3348
+ RequestTimeout: 408,
3349
+ Conflict: 409,
3350
+ Gone: 410,
3351
+ LengthRequired: 411,
3352
+ PreconditionFailed: 412,
3353
+ PayloadTooLarge: 413,
3354
+ UriTooLong: 414,
3355
+ UnsupportedMediaType: 415,
3356
+ RangeNotSatisfiable: 416,
3357
+ ExpectationFailed: 417,
3358
+ ImATeapot: 418,
3359
+ MisdirectedRequest: 421,
3360
+ UnprocessableEntity: 422,
3361
+ Locked: 423,
3362
+ FailedDependency: 424,
3363
+ TooEarly: 425,
3364
+ UpgradeRequired: 426,
3365
+ PreconditionRequired: 428,
3366
+ TooManyRequests: 429,
3367
+ RequestHeaderFieldsTooLarge: 431,
3368
+ UnavailableForLegalReasons: 451,
3369
+ InternalServerError: 500,
3370
+ NotImplemented: 501,
3371
+ BadGateway: 502,
3372
+ ServiceUnavailable: 503,
3373
+ GatewayTimeout: 504,
3374
+ HttpVersionNotSupported: 505,
3375
+ VariantAlsoNegotiates: 506,
3376
+ InsufficientStorage: 507,
3377
+ LoopDetected: 508,
3378
+ NotExtended: 510,
3379
+ NetworkAuthenticationRequired: 511
3380
+ };
3381
+ Object.entries(HttpStatusCode).forEach(([key, value])=>{
3382
+ HttpStatusCode[value] = key;
3383
+ });
3384
+ /* ESM default export */ const helpers_HttpStatusCode = HttpStatusCode;
3385
+ /**
3386
+ * Create an instance of Axios
3387
+ *
3388
+ * @param {Object} defaultConfig The default config for the instance
3389
+ *
3390
+ * @returns {Axios} A new instance of Axios
3391
+ */ function createInstance(defaultConfig) {
3392
+ const context = new Axios(defaultConfig);
3393
+ const instance = bind(Axios.prototype.request, context);
3394
+ // Copy axios.prototype to instance
3395
+ utils.extend(instance, Axios.prototype, context, {
3396
+ allOwnKeys: true
3397
+ });
3398
+ // Copy context to instance
3399
+ utils.extend(instance, context, null, {
3400
+ allOwnKeys: true
3401
+ });
3402
+ // Factory for creating new instances
3403
+ instance.create = function(instanceConfig) {
3404
+ return createInstance(mergeConfig_mergeConfig(defaultConfig, instanceConfig));
3405
+ };
3406
+ return instance;
3407
+ }
3408
+ // Create the default instance to be exported
3409
+ const axios = createInstance(defaults);
3410
+ // Expose Axios class to allow class inheritance
3411
+ axios.Axios = Axios;
3412
+ // Expose Cancel & CancelToken
3413
+ axios.CanceledError = CanceledError;
3414
+ axios.CancelToken = CancelToken;
3415
+ axios.isCancel = isCancel;
3416
+ axios.VERSION = VERSION;
3417
+ axios.toFormData = toFormData;
3418
+ // Expose AxiosError class
3419
+ axios.AxiosError = core_AxiosError;
3420
+ // alias for CanceledError for backward compatibility
3421
+ axios.Cancel = axios.CanceledError;
3422
+ // Expose all/spread
3423
+ axios.all = function(promises) {
3424
+ return Promise.all(promises);
3425
+ };
3426
+ axios.spread = spread;
3427
+ // Expose isAxiosError
3428
+ axios.isAxiosError = isAxiosError;
3429
+ // Expose mergeConfig
3430
+ axios.mergeConfig = mergeConfig_mergeConfig;
3431
+ axios.AxiosHeaders = AxiosHeaders;
3432
+ axios.formToJSON = (thing)=>formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
3433
+ axios.getAdapter = adapters_adapters.getAdapter;
3434
+ axios.HttpStatusCode = helpers_HttpStatusCode;
3435
+ axios.default = axios;
3436
+ // this module should only have a default export
3437
+ /* ESM default export */ const lib_axios = axios;
3438
+ // This module is intended to unwrap Axios default export as named.
3439
+ // Keep top-level export same with static properties
3440
+ // so that it can keep same with es module or cjs
3441
+ 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;
3390
3442
  class Files extends APIResource {
3391
3443
  /**
3392
3444
  * Upload files to Coze platform. | 调用接口上传文件到扣子。
@@ -3421,6 +3473,9 @@
3421
3473
  * @param params.bot_id - Optional The ID of the bot associated with the workflow. | 可选 与工作流关联的机器人 ID。
3422
3474
  * @param params.parameters - Optional Parameters for the workflow execution. | 可选 工作流执行的参数。
3423
3475
  * @param params.ext - Optional Additional information for the workflow execution. | 可选 工作流执行的附加信息。
3476
+ * @param params.execute_mode - Optional The mode in which to execute the workflow. | 可选 工作流执行的模式。
3477
+ * @param params.connector_id - Optional The ID of the connector to use for the workflow. | 可选 用于工作流的连接器 ID。
3478
+ * @param params.app_id - Optional The ID of the app. | 可选 要进行会话聊天的 App ID
3424
3479
  * @returns RunWorkflowData | 工作流运行数据
3425
3480
  */ async create(params, options) {
3426
3481
  const apiUrl = '/v1/workflow/run';
@@ -3435,6 +3490,9 @@
3435
3490
  * @param params.bot_id - Optional The ID of the bot associated with the workflow. | 可选 与工作流关联的机器人 ID。
3436
3491
  * @param params.parameters - Optional Parameters for the workflow execution. | 可选 工作流执行的参数。
3437
3492
  * @param params.ext - Optional Additional information for the workflow execution. | 可选 工作流执行的附加信息。
3493
+ * @param params.execute_mode - Optional The mode in which to execute the workflow. | 可选 工作流执行的模式。
3494
+ * @param params.connector_id - Optional The ID of the connector to use for the workflow. | 可选 用于工作流的连接器 ID。
3495
+ * @param params.app_id - Optional The ID of the app. | 可选 要进行会话聊天的 App ID
3438
3496
  * @returns Stream<WorkflowEvent, { id: string; event: string; data: string }> | 工作流事件流
3439
3497
  */ async *stream(params, options) {
3440
3498
  const apiUrl = '/v1/workflow/stream_run';
@@ -3468,9 +3526,46 @@
3468
3526
  this.data = data;
3469
3527
  }
3470
3528
  }
3529
+ class WorkflowChat extends APIResource {
3530
+ /**
3531
+ * Execute a chat workflow. | 执行对话流
3532
+ * @docs en: https://www.coze.cn/docs/developer_guides/workflow_chat?_lang=en
3533
+ * @docs zh: https://www.coze.cn/docs/developer_guides/workflow_chat?_lang=zh
3534
+ * @param params.workflow_id - Required The ID of the workflow to chat with. | 必选 要对话的工作流 ID。
3535
+ * @param params.additional_messages - Required Array of messages for the chat. | 必选 对话的消息数组。
3536
+ * @param params.parameters - Required Parameters for the workflow execution. | 必选 工作流执行的参数。
3537
+ * @param params.app_id - Optional The ID of the app. | 可选 应用 ID。
3538
+ * @param params.bot_id - Optional The ID of the bot. | 可选 Bot ID。
3539
+ * @param params.conversation_id - Optional The ID of the conversation. | 可选 会话 ID。
3540
+ * @param params.ext - Optional Additional information for the chat. | 可选 对话的附加信息。
3541
+ * @returns AsyncGenerator<StreamChatData> | 对话数据流
3542
+ */ async *stream(params, options) {
3543
+ const apiUrl = '/v1/workflows/chat';
3544
+ const payload = {
3545
+ ...params,
3546
+ additional_messages: handleAdditionalMessages(params.additional_messages)
3547
+ };
3548
+ const result = await this._client.post(apiUrl, payload, true, options);
3549
+ for await (const message of result)if (message.event === chat_ChatEventType.DONE) {
3550
+ const ret = {
3551
+ event: message.event,
3552
+ data: '[DONE]'
3553
+ };
3554
+ yield ret;
3555
+ } else try {
3556
+ const ret = {
3557
+ event: message.event,
3558
+ data: JSON.parse(message.data)
3559
+ };
3560
+ yield ret;
3561
+ } catch (error) {
3562
+ throw new CozeError(`Could not parse message into JSON:${message.data}`);
3563
+ }
3564
+ }
3565
+ }
3471
3566
  class Workflows extends APIResource {
3472
3567
  constructor(...args){
3473
- super(...args), this.runs = new Runs(this._client);
3568
+ super(...args), this.runs = new Runs(this._client), this.chat = new WorkflowChat(this._client);
3474
3569
  }
3475
3570
  }
3476
3571
  class WorkSpaces extends APIResource {
@@ -3494,6 +3589,8 @@
3494
3589
  };
3495
3590
  class Documents extends APIResource {
3496
3591
  /**
3592
+ * @deprecated The method is deprecated and will be removed in a future version. Please use 'client.datasets.documents.list' instead.
3593
+ *
3497
3594
  * View the file list of a specified knowledge base, which includes lists of documents, spreadsheets, or images.
3498
3595
  * | 调用接口查看指定知识库的内容列表,即文件、表格或图像列表。
3499
3596
  * @docs en: https://www.coze.com/docs/developer_guides/list_knowledge_files?_lang=en
@@ -3504,12 +3601,14 @@
3504
3601
  * @returns ListDocumentData | 知识库文件列表
3505
3602
  */ list(params, options) {
3506
3603
  const apiUrl = '/open_api/knowledge/document/list';
3507
- const response = this._client.get(apiUrl, params, false, esm_mergeConfig(options, {
3604
+ const response = this._client.get(apiUrl, params, false, mergeConfig(options, {
3508
3605
  headers: documents_headers
3509
3606
  }));
3510
3607
  return response;
3511
3608
  }
3512
3609
  /**
3610
+ * @deprecated The method is deprecated and will be removed in a future version. Please use 'client.datasets.documents.create' instead.
3611
+ *
3513
3612
  * Upload files to the specific knowledge. | 调用此接口向指定知识库中上传文件。
3514
3613
  * @docs en: https://www.coze.com/docs/developer_guides/create_knowledge_files?_lang=en
3515
3614
  * @docs zh: https://www.coze.cn/docs/developer_guides/create_knowledge_files?_lang=zh
@@ -3520,12 +3619,14 @@
3520
3619
  * @returns DocumentInfo[] | 已上传文件的基本信息
3521
3620
  */ async create(params, options) {
3522
3621
  const apiUrl = '/open_api/knowledge/document/create';
3523
- const response = await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3622
+ const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
3524
3623
  headers: documents_headers
3525
3624
  }));
3526
3625
  return response.document_infos;
3527
3626
  }
3528
3627
  /**
3628
+ * @deprecated The method is deprecated and will be removed in a future version. Please use 'client.datasets.documents.delete' instead.
3629
+ *
3529
3630
  * Delete text, images, sheets, and other files in the knowledge base, supporting batch deletion.
3530
3631
  * | 删除知识库中的文本、图像、表格等文件,支持批量删除。
3531
3632
  * @docs en: https://www.coze.com/docs/developer_guides/delete_knowledge_files?_lang=en
@@ -3534,11 +3635,13 @@
3534
3635
  * @returns void | 无返回
3535
3636
  */ async delete(params, options) {
3536
3637
  const apiUrl = '/open_api/knowledge/document/delete';
3537
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3638
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3538
3639
  headers: documents_headers
3539
3640
  }));
3540
3641
  }
3541
3642
  /**
3643
+ * @deprecated The method is deprecated and will be removed in a future version. Please use 'client.datasets.documents.update' instead.
3644
+ *
3542
3645
  * Modify the knowledge base file name and update strategy. | 调用接口修改知识库文件名称和更新策略。
3543
3646
  * @docs en: https://www.coze.com/docs/developer_guides/modify_knowledge_files?_lang=en
3544
3647
  * @docs zh: https://www.coze.cn/docs/developer_guides/modify_knowledge_files?_lang=zh
@@ -3548,14 +3651,86 @@
3548
3651
  * @returns void | 无返回
3549
3652
  */ async update(params, options) {
3550
3653
  const apiUrl = '/open_api/knowledge/document/update';
3551
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3654
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3552
3655
  headers: documents_headers
3553
3656
  }));
3554
3657
  }
3555
3658
  }
3556
3659
  class Knowledge extends APIResource {
3557
3660
  constructor(...args){
3558
- super(...args), this.documents = new Documents(this._client);
3661
+ super(...args), /**
3662
+ * @deprecated
3663
+ */ this.documents = new Documents(this._client);
3664
+ }
3665
+ }
3666
+ // Required header for knowledge APIs
3667
+ const documents_documents_headers = {
3668
+ 'agw-js-conv': 'str'
3669
+ };
3670
+ class documents_Documents extends APIResource {
3671
+ /**
3672
+ * View the file list of a specified knowledge base, which includes lists of documents, spreadsheets, or images.
3673
+ * | 调用接口查看指定知识库的内容列表,即文件、表格或图像列表。
3674
+ * @docs en: https://www.coze.com/docs/developer_guides/list_knowledge_files?_lang=en
3675
+ * @docs zh: https://www.coze.cn/docs/developer_guides/list_knowledge_files?_lang=zh
3676
+ * @param params.dataset_id - Required The ID of the knowledge base. | 必选 待查看文件的知识库 ID。
3677
+ * @param params.page - Optional The page number for paginated queries. Default is 1. | 可选 分页查询时的页码。默认为 1。
3678
+ * @param params.page_size - Optional The size of pagination. Default is 10. | 可选 分页大小。默认为 10。
3679
+ * @returns ListDocumentData | 知识库文件列表
3680
+ */ list(params, options) {
3681
+ const apiUrl = '/open_api/knowledge/document/list';
3682
+ const response = this._client.get(apiUrl, params, false, mergeConfig(options, {
3683
+ headers: documents_documents_headers
3684
+ }));
3685
+ return response;
3686
+ }
3687
+ /**
3688
+ * Upload files to the specific knowledge. | 调用此接口向指定知识库中上传文件。
3689
+ * @docs en: https://www.coze.com/docs/developer_guides/create_knowledge_files?_lang=en
3690
+ * @docs zh: https://www.coze.cn/docs/developer_guides/create_knowledge_files?_lang=zh
3691
+ * @param params.dataset_id - Required The ID of the knowledge. | 必选 知识库 ID。
3692
+ * @param params.document_bases - Required The metadata information of the files awaiting upload. | 必选 待上传文件的元数据信息。
3693
+ * @param params.chunk_strategy - Required when uploading files to a new knowledge for the first time. Chunk strategy.
3694
+ * | 向新知识库首次上传文件时必选 分段规则。
3695
+ * @returns DocumentInfo[] | 已上传文件的基本信息
3696
+ */ async create(params, options) {
3697
+ const apiUrl = '/open_api/knowledge/document/create';
3698
+ const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
3699
+ headers: documents_documents_headers
3700
+ }));
3701
+ return response.document_infos;
3702
+ }
3703
+ /**
3704
+ * Delete text, images, sheets, and other files in the knowledge base, supporting batch deletion.
3705
+ * | 删除知识库中的文本、图像、表格等文件,支持批量删除。
3706
+ * @docs en: https://www.coze.com/docs/developer_guides/delete_knowledge_files?_lang=en
3707
+ * @docs zh: https://www.coze.cn/docs/developer_guides/delete_knowledge_files?_lang=zh
3708
+ * @param params.document_ids - Required The list of knowledge base files to be deleted. | 必选 待删除的文件 ID。
3709
+ * @returns void | 无返回
3710
+ */ async delete(params, options) {
3711
+ const apiUrl = '/open_api/knowledge/document/delete';
3712
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3713
+ headers: documents_documents_headers
3714
+ }));
3715
+ }
3716
+ /**
3717
+ * Modify the knowledge base file name and update strategy. | 调用接口修改知识库文件名称和更新策略。
3718
+ * @docs en: https://www.coze.com/docs/developer_guides/modify_knowledge_files?_lang=en
3719
+ * @docs zh: https://www.coze.cn/docs/developer_guides/modify_knowledge_files?_lang=zh
3720
+ * @param params.document_id - Required The ID of the knowledge base file. | 必选 待修改的知识库文件 ID。
3721
+ * @param params.document_name - Optional The new name of the knowledge base file. | 可选 知识库文件的新名称。
3722
+ * @param params.update_rule - Optional The update strategy for online web pages. | 可选 在线网页更新策略。
3723
+ * @returns void | 无返回
3724
+ */ async update(params, options) {
3725
+ const apiUrl = '/open_api/knowledge/document/update';
3726
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3727
+ headers: documents_documents_headers
3728
+ }));
3729
+ }
3730
+ }
3731
+ class Datasets extends APIResource {
3732
+ constructor(...args){
3733
+ super(...args), this.documents = new documents_Documents(this._client);
3559
3734
  }
3560
3735
  }
3561
3736
  class Voices extends APIResource {
@@ -3612,7 +3787,7 @@
3612
3787
  * @returns Speech synthesis data
3613
3788
  */ async create(params, options) {
3614
3789
  const apiUrl = '/v1/audio/speech';
3615
- const response = await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3790
+ const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
3616
3791
  responseType: 'arraybuffer'
3617
3792
  }));
3618
3793
  return response;
@@ -3625,23 +3800,26 @@
3625
3800
  return response.data;
3626
3801
  }
3627
3802
  }
3628
- class esm_Audio extends APIResource {
3803
+ class audio_Audio extends APIResource {
3629
3804
  constructor(...args){
3630
3805
  super(...args), this.rooms = new Rooms(this._client), this.voices = new Voices(this._client), this.speech = new Speech(this._client);
3631
3806
  }
3632
3807
  }
3633
- 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
3634
- const { version: esm_version } = package_namespaceObject;
3808
+ // EXTERNAL MODULE: os (ignored)
3809
+ var os_ignored_ = __webpack_require__("?9050");
3810
+ var os_ignored_default = /*#__PURE__*/ __webpack_require__.n(os_ignored_);
3811
+ 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
3812
+ const { version: version_version } = package_namespaceObject;
3635
3813
  const getEnv = ()=>{
3636
3814
  const nodeVersion = process.version.slice(1); // Remove 'v' prefix
3637
3815
  const { platform } = process;
3638
3816
  let osName = platform.toLowerCase();
3639
- let osVersion = os_ignored_.release();
3817
+ let osVersion = os_ignored_default().release();
3640
3818
  if ('darwin' === platform) {
3641
3819
  osName = 'macos';
3642
3820
  // Try to parse the macOS version
3643
3821
  try {
3644
- const darwinVersion = os_ignored_.release().split('.');
3822
+ const darwinVersion = os_ignored_default().release().split('.');
3645
3823
  if (darwinVersion.length >= 2) {
3646
3824
  const majorVersion = parseInt(darwinVersion[0], 10);
3647
3825
  if (!isNaN(majorVersion) && majorVersion >= 9) {
@@ -3654,10 +3832,10 @@
3654
3832
  }
3655
3833
  } else if ('win32' === platform) {
3656
3834
  osName = 'windows';
3657
- osVersion = os_ignored_.release();
3835
+ osVersion = os_ignored_default().release();
3658
3836
  } else if ('linux' === platform) {
3659
3837
  osName = 'linux';
3660
- osVersion = os_ignored_.release();
3838
+ osVersion = os_ignored_default().release();
3661
3839
  }
3662
3840
  return {
3663
3841
  osName,
@@ -3667,12 +3845,12 @@
3667
3845
  };
3668
3846
  const getUserAgent = ()=>{
3669
3847
  const { nodeVersion, osName, osVersion } = getEnv();
3670
- return `coze-js/${esm_version} node/${nodeVersion} ${osName}/${osVersion}`.toLowerCase();
3848
+ return `coze-js/${version_version} node/${nodeVersion} ${osName}/${osVersion}`.toLowerCase();
3671
3849
  };
3672
3850
  const getNodeClientUserAgent = ()=>{
3673
3851
  const { osVersion, nodeVersion, osName } = getEnv();
3674
3852
  const ua = {
3675
- version: esm_version,
3853
+ version: version_version,
3676
3854
  lang: 'node',
3677
3855
  lang_version: nodeVersion,
3678
3856
  os_name: osName,
@@ -3680,37 +3858,44 @@
3680
3858
  };
3681
3859
  return JSON.stringify(ua);
3682
3860
  };
3683
- /* eslint-disable @typescript-eslint/no-explicit-any */ const esm_handleError = (error)=>{
3861
+ /* eslint-disable @typescript-eslint/no-explicit-any */ const fetcher_handleError = (error)=>{
3684
3862
  if (!error.isAxiosError && (!error.code || !error.message)) return new CozeError(`Unexpected error: ${error.message}`);
3685
3863
  if ('ECONNABORTED' === error.code && error.message.includes('timeout') || 'ETIMEDOUT' === error.code) {
3686
3864
  var _error_response;
3687
3865
  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);
3688
3866
  }
3689
3867
  if ('ERR_CANCELED' === error.code) return new APIUserAbortError(error.message);
3690
- var _error_response1, _error_response2, _error_response3;
3691
- 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);
3868
+ else {
3869
+ var _error_response1, _error_response2, _error_response3;
3870
+ 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);
3871
+ }
3692
3872
  };
3693
3873
  async function fetchAPI(url) {
3694
3874
  let options = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
3695
3875
  const axiosInstance = options.axiosInstance || lib_axios;
3876
+ // Add version check for streaming requests
3877
+ if (options.isStreaming && isAxiosStatic(axiosInstance)) {
3878
+ const axiosVersion = axiosInstance.VERSION || lib_axios.VERSION;
3879
+ 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.');
3880
+ }
3696
3881
  const response = await axiosInstance({
3697
3882
  url,
3698
3883
  responseType: options.isStreaming ? 'stream' : 'json',
3699
3884
  adapter: options.isStreaming ? 'fetch' : void 0,
3700
3885
  ...options
3701
3886
  }).catch((error)=>{
3702
- throw esm_handleError(error);
3887
+ throw fetcher_handleError(error);
3703
3888
  });
3704
3889
  return {
3705
3890
  async *stream () {
3706
3891
  try {
3707
3892
  const stream = response.data;
3708
- const reader = stream[Symbol.asyncIterator]();
3893
+ const reader = stream[Symbol.asyncIterator] ? stream[Symbol.asyncIterator]() : stream.getReader();
3709
3894
  const decoder = new TextDecoder();
3710
3895
  const fieldValues = {};
3711
3896
  let buffer = '';
3712
3897
  while(true){
3713
- const { done, value } = await reader.next();
3898
+ const { done, value } = await (reader.next ? reader.next() : reader.read());
3714
3899
  if (done) {
3715
3900
  if (buffer) {
3716
3901
  // If the stream ends without a newline, it means an error occurred
@@ -3737,26 +3922,46 @@
3737
3922
  buffer = lines[lines.length - 1]; // Keep the last incomplete line in the buffer
3738
3923
  }
3739
3924
  } catch (error) {
3740
- esm_handleError(error);
3925
+ fetcher_handleError(error);
3741
3926
  }
3742
3927
  },
3743
3928
  json: ()=>response.data,
3744
3929
  response
3745
3930
  };
3746
3931
  }
3932
+ // Add version comparison utility
3933
+ function compareVersions(v1, v2) {
3934
+ const v1Parts = v1.split('.').map(Number);
3935
+ const v2Parts = v2.split('.').map(Number);
3936
+ for(let i = 0; i < 3; i++){
3937
+ const part1 = v1Parts[i] || 0;
3938
+ const part2 = v2Parts[i] || 0;
3939
+ if (part1 > part2) return 1;
3940
+ if (part1 < part2) return -1;
3941
+ }
3942
+ return 0;
3943
+ }
3944
+ function isAxiosStatic(instance) {
3945
+ return !!(null == instance ? void 0 : instance.Axios);
3946
+ }
3747
3947
  /**
3748
3948
  * default coze base URL is api.coze.com
3749
- */ const COZE_COM_BASE_URL = 'https://api.coze.com';
3750
- /* eslint-disable max-params */ class APIClient {
3751
- buildOptions(method, body, options) {
3949
+ */ const constant_COZE_COM_BASE_URL = 'https://api.coze.com';
3950
+ /* eslint-disable max-params */ class core_APIClient {
3951
+ async getToken() {
3952
+ if ('function' == typeof this.token) return await this.token();
3953
+ return this.token;
3954
+ }
3955
+ async buildOptions(method, body, options) {
3956
+ const token = await this.getToken();
3752
3957
  const headers = {
3753
- authorization: `Bearer ${this.token}`
3958
+ authorization: `Bearer ${token}`
3754
3959
  };
3755
- if (!isBrowser()) {
3960
+ if (!utils_isBrowser()) {
3756
3961
  headers['User-Agent'] = getUserAgent();
3757
3962
  headers['X-Coze-Client-User-Agent'] = getNodeClientUserAgent();
3758
3963
  }
3759
- const config = esm_mergeConfig(this.axiosOptions, options, {
3964
+ const config = mergeConfig(this.axiosOptions, options, {
3760
3965
  headers
3761
3966
  });
3762
3967
  config.method = method;
@@ -3765,19 +3970,22 @@
3765
3970
  }
3766
3971
  async makeRequest(apiUrl, method, body, isStream, options) {
3767
3972
  const fullUrl = `${this.baseURL}${apiUrl}`;
3768
- const fetchOptions = this.buildOptions(method, body, options);
3973
+ const fetchOptions = await this.buildOptions(method, body, options);
3769
3974
  fetchOptions.isStreaming = isStream;
3975
+ fetchOptions.axiosInstance = this.axiosInstance;
3770
3976
  this.debugLog(`--- request url: ${fullUrl}`);
3771
3977
  this.debugLog('--- request options:', fetchOptions);
3772
3978
  const { response, stream, json } = await fetchAPI(fullUrl, fetchOptions);
3773
3979
  this.debugLog(`--- response status: ${response.status}`);
3774
3980
  this.debugLog('--- response headers: ', response.headers);
3775
- const contentType = response.headers['content-type'];
3981
+ var _response_headers;
3982
+ // Taro use `header`
3983
+ const contentType = (null !== (_response_headers = response.headers) && void 0 !== _response_headers ? _response_headers : response.header)['content-type'];
3776
3984
  if (isStream) {
3777
3985
  if (contentType && contentType.includes('application/json')) {
3778
3986
  const result = await json();
3779
3987
  const { code, msg } = result;
3780
- if (0 !== code && void 0 !== code) throw APIError.generate(response.status, result, msg, response.headers);
3988
+ if (0 !== code && void 0 !== code) throw error_APIError.generate(response.status, result, msg, response.headers);
3781
3989
  }
3782
3990
  return stream();
3783
3991
  }
@@ -3785,7 +3993,7 @@
3785
3993
  {
3786
3994
  const result = await json();
3787
3995
  const { code, msg } = result;
3788
- if (0 !== code && void 0 !== code) throw APIError.generate(response.status, result, msg, response.headers);
3996
+ if (0 !== code && void 0 !== code) throw error_APIError.generate(response.status, result, msg, response.headers);
3789
3997
  return result;
3790
3998
  }
3791
3999
  }
@@ -3817,28 +4025,35 @@
3817
4025
  }
3818
4026
  constructor(config){
3819
4027
  this._config = config;
3820
- this.baseURL = config.baseURL || COZE_COM_BASE_URL;
4028
+ this.baseURL = config.baseURL || constant_COZE_COM_BASE_URL;
3821
4029
  this.token = config.token;
3822
4030
  this.axiosOptions = config.axiosOptions || {};
4031
+ this.axiosInstance = config.axiosInstance;
3823
4032
  this.debug = config.debug || false;
3824
4033
  this.allowPersonalAccessTokenInBrowser = config.allowPersonalAccessTokenInBrowser || false;
3825
4034
  this.headers = config.headers;
3826
- 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');
3827
- }
3828
- }
3829
- APIClient.APIError = APIError;
3830
- APIClient.BadRequestError = BadRequestError;
3831
- APIClient.AuthenticationError = AuthenticationError;
3832
- APIClient.PermissionDeniedError = PermissionDeniedError;
3833
- APIClient.NotFoundError = NotFoundError;
3834
- APIClient.RateLimitError = RateLimitError;
3835
- APIClient.InternalServerError = InternalServerError;
3836
- APIClient.GatewayError = GatewayError;
3837
- APIClient.TimeoutError = TimeoutError;
3838
- APIClient.UserAbortError = APIUserAbortError;
3839
- class CozeAPI extends APIClient {
4035
+ 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');
4036
+ }
4037
+ }
4038
+ core_APIClient.APIError = error_APIError;
4039
+ core_APIClient.BadRequestError = BadRequestError;
4040
+ core_APIClient.AuthenticationError = AuthenticationError;
4041
+ core_APIClient.PermissionDeniedError = PermissionDeniedError;
4042
+ core_APIClient.NotFoundError = NotFoundError;
4043
+ core_APIClient.RateLimitError = RateLimitError;
4044
+ core_APIClient.InternalServerError = InternalServerError;
4045
+ core_APIClient.GatewayError = GatewayError;
4046
+ core_APIClient.TimeoutError = TimeoutError;
4047
+ core_APIClient.UserAbortError = APIUserAbortError;
4048
+ // EXTERNAL MODULE: crypto (ignored)
4049
+ __webpack_require__("?666e");
4050
+ // EXTERNAL MODULE: jsonwebtoken (ignored)
4051
+ __webpack_require__("?79fd");
4052
+ class CozeAPI extends core_APIClient {
3840
4053
  constructor(...args){
3841
- 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);
4054
+ super(...args), this.bots = new Bots(this), this.chat = new Chat(this), this.conversations = new Conversations(this), this.files = new Files(this), /**
4055
+ * @deprecated
4056
+ */ 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);
3842
4057
  }
3843
4058
  }
3844
4059
  /**
@@ -9070,7 +9285,7 @@
9070
9285
  }, stringPad = {
9071
9286
  start: createMethod(!1),
9072
9287
  end: createMethod(!0)
9073
- }, userAgent = engineUserAgent, stringPadWebkitBug = /Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(userAgent), $$F = _export, $padEnd = stringPad.end, WEBKIT_BUG$1 = stringPadWebkitBug;
9288
+ }, 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;
9074
9289
  $$F({
9075
9290
  target: "String",
9076
9291
  proto: !0,
@@ -12643,8 +12858,8 @@
12643
12858
  }
12644
12859
  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]);
12645
12860
  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]);
12646
- var v2 = !isSSR2() && (null === (_userAgentString$matc2 = userAgentString.match(/Firefox\/(\d+)/i)) || void 0 === _userAgentString$matc2 ? void 0 : _userAgentString$matc2[1]);
12647
- isFirefox && v2 && (sv = Number(v2));
12861
+ var index_esm_min_v2 = !isSSR2() && (null === (_userAgentString$matc2 = userAgentString.match(/Firefox\/(\d+)/i)) || void 0 === _userAgentString$matc2 ? void 0 : _userAgentString$matc2[1]);
12862
+ isFirefox && index_esm_min_v2 && (sv = Number(index_esm_min_v2));
12648
12863
  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) {
12649
12864
  return _parseInt$7(e);
12650
12865
  }))) && 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]);
@@ -38223,11 +38438,12 @@
38223
38438
  + * @param milliseconds The time to sleep in milliseconds
38224
38439
  + * @throws {Error} If milliseconds is negative
38225
38440
  + * @returns Promise that resolves after the specified duration
38226
- + */ const utils_sleep = (milliseconds)=>{
38441
+ + */ const src_utils_sleep = (milliseconds)=>{
38227
38442
  if (milliseconds < 0) throw new Error('Sleep duration must be non-negative');
38228
38443
  return new Promise((resolve)=>setTimeout(resolve, milliseconds));
38229
38444
  };
38230
38445
  /**
38446
+ * @deprecated use checkDevicePermission instead
38231
38447
  * Check microphone permission,return boolean
38232
38448
  */ const checkPermission = async function() {
38233
38449
  let { audio = true, video = false } = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
@@ -38242,22 +38458,32 @@
38242
38458
  return false;
38243
38459
  }
38244
38460
  };
38461
+ const checkDevicePermission = async function() {
38462
+ let checkVideo = arguments.length > 0 && void 0 !== arguments[0] && arguments[0];
38463
+ return await index_esm_min_index.enableDevices({
38464
+ audio: true,
38465
+ video: checkVideo
38466
+ });
38467
+ };
38245
38468
  /**
38246
38469
  * Get audio devices
38247
38470
  * @returns Promise<AudioDevices> Object containing arrays of audio input and output devices
38248
- */ const getAudioDevices = async ()=>{
38249
- const devices = await index_esm_min_index.enumerateDevices();
38471
+ */ const getAudioDevices = async function() {
38472
+ let { video = false } = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
38473
+ let devices = [];
38474
+ devices = video ? await index_esm_min_index.enumerateDevices() : await [
38475
+ ...await index_esm_min_index.enumerateAudioCaptureDevices(),
38476
+ ...await index_esm_min_index.enumerateAudioPlaybackDevices()
38477
+ ];
38250
38478
  if (!(null == devices ? void 0 : devices.length)) return {
38251
38479
  audioInputs: [],
38252
38480
  audioOutputs: [],
38253
- videoInputs: [],
38254
- videoOutputs: []
38481
+ videoInputs: []
38255
38482
  };
38256
38483
  return {
38257
38484
  audioInputs: devices.filter((i)=>i.deviceId && 'audioinput' === i.kind),
38258
38485
  audioOutputs: devices.filter((i)=>i.deviceId && 'audiooutput' === i.kind),
38259
- videoInputs: devices.filter((i)=>i.deviceId && 'videoinput' === i.kind),
38260
- videoOutputs: devices.filter((i)=>i.deviceId && 'videooutput' === i.kind)
38486
+ videoInputs: devices.filter((i)=>i.deviceId && 'videoinput' === i.kind)
38261
38487
  };
38262
38488
  };
38263
38489
  var error_RealtimeError = /*#__PURE__*/ function(RealtimeError) {
@@ -38360,6 +38586,34 @@
38360
38586
  * en: Bot left
38361
38587
  * zh: Bot 离开
38362
38588
  */ EventNames["BOT_LEAVE"] = "server.bot.leave";
38589
+ /**
38590
+ * en: Audio speech started
38591
+ * zh: 开始说话
38592
+ */ EventNames["AUDIO_AGENT_SPEECH_STARTED"] = "server.audio.agent.speech_started";
38593
+ /**
38594
+ * en: Audio speech stopped
38595
+ * zh: 停止说话
38596
+ */ EventNames["AUDIO_SPEECH_STOPPED"] = "server.audio.speech_stopped";
38597
+ /**
38598
+ * en: Server error
38599
+ * zh: 服务端错误
38600
+ */ EventNames["SERVER_ERROR"] = "server.error";
38601
+ /**
38602
+ * en: User speech started
38603
+ * zh: 用户开始说话
38604
+ */ EventNames["AUDIO_USER_SPEECH_STARTED"] = "server.audio.user.speech_started";
38605
+ /**
38606
+ * en: User speech stopped
38607
+ * zh: 用户停止说话
38608
+ */ EventNames["AUDIO_USER_SPEECH_STOPPED"] = "server.audio.user.speech_stopped";
38609
+ /**
38610
+ * en: User successfully enters the room
38611
+ * zh: 用户成功进入房间后,会收到该事件
38612
+ */ EventNames["SESSION_CREATED"] = "server.session.created";
38613
+ /**
38614
+ * en: Session updated
38615
+ * zh: 会话更新
38616
+ */ EventNames["SESSION_UPDATE"] = "server.session.update";
38363
38617
  return EventNames;
38364
38618
  }({});
38365
38619
  class RealtimeEventHandler {
@@ -38390,7 +38644,8 @@
38390
38644
  }
38391
38645
  }
38392
38646
  dispatch(eventName, event) {
38393
- this._log(`dispatch ${eventName} event`);
38647
+ let consoleLog = !(arguments.length > 2) || void 0 === arguments[2] || arguments[2];
38648
+ if (consoleLog) this._log(`dispatch ${eventName} event`);
38394
38649
  const handlers = (this.eventHandlers[eventName] || []).slice();
38395
38650
  this._dispatchToHandlers(eventName, event, handlers);
38396
38651
  const allHandlers = (this.eventHandlers["realtime.event"] || []).slice();
@@ -41659,7 +41914,7 @@
41659
41914
  this.engine.on(index_esm_min_index.events.onUserJoined, this.handleUserJoin);
41660
41915
  this.engine.on(index_esm_min_index.events.onUserLeave, this.handleUserLeave);
41661
41916
  this.engine.on(index_esm_min_index.events.onError, this.handleEventError);
41662
- this.engine.on(index_esm_min_index.events.onPlayerEvent, this.handlePlayerEvent);
41917
+ if (this._isSupportVideo) this.engine.on(index_esm_min_index.events.onPlayerEvent, this.handlePlayerEvent);
41663
41918
  if (this._debug) {
41664
41919
  this.engine.on(index_esm_min_index.events.onLocalAudioPropertiesReport, this.handleLocalAudioPropertiesReport);
41665
41920
  this.engine.on(index_esm_min_index.events.onRemoteAudioPropertiesReport, this.handleRemoteAudioPropertiesReport);
@@ -41670,7 +41925,7 @@
41670
41925
  this.engine.off(index_esm_min_index.events.onUserJoined, this.handleUserJoin);
41671
41926
  this.engine.off(index_esm_min_index.events.onUserLeave, this.handleUserLeave);
41672
41927
  this.engine.off(index_esm_min_index.events.onError, this.handleEventError);
41673
- this.engine.off(index_esm_min_index.events.onPlayerEvent, this.handlePlayerEvent);
41928
+ if (this._isSupportVideo) this.engine.off(index_esm_min_index.events.onPlayerEvent, this.handlePlayerEvent);
41674
41929
  if (this._debug) {
41675
41930
  this.engine.off(index_esm_min_index.events.onLocalAudioPropertiesReport, this.handleLocalAudioPropertiesReport);
41676
41931
  this.engine.off(index_esm_min_index.events.onRemoteAudioPropertiesReport, this.handleRemoteAudioPropertiesReport);
@@ -41715,13 +41970,13 @@
41715
41970
  this.dispatch(event_handler_EventNames.PLAYER_EVENT, event);
41716
41971
  }
41717
41972
  async joinRoom(options) {
41718
- const { token, roomId, uid, audioMutedDefault, videoOnDefault } = options;
41973
+ const { token, roomId, uid, audioMutedDefault, videoOnDefault, isAutoSubscribeAudio } = options;
41719
41974
  try {
41720
41975
  await this.engine.joinRoom(token, roomId, {
41721
41976
  userId: uid
41722
41977
  }, {
41723
41978
  isAutoPublish: !audioMutedDefault,
41724
- isAutoSubscribeAudio: true,
41979
+ isAutoSubscribeAudio,
41725
41980
  isAutoSubscribeVideo: this._isSupportVideo && videoOnDefault
41726
41981
  });
41727
41982
  } catch (e) {
@@ -41735,14 +41990,18 @@
41735
41990
  await this.engine.startAudioCapture(deviceId);
41736
41991
  }
41737
41992
  async setAudioOutputDevice(deviceId) {
41738
- const devices = await getAudioDevices();
41993
+ const devices = await getAudioDevices({
41994
+ video: false
41995
+ });
41739
41996
  if (-1 === devices.audioOutputs.findIndex((i)=>i.deviceId === deviceId)) throw new RealtimeAPIError(error_RealtimeError.DEVICE_ACCESS_ERROR, `Audio output device not found: ${deviceId}`);
41740
41997
  await this.engine.setAudioPlaybackDevice(deviceId);
41741
41998
  }
41742
41999
  async createLocalStream(userId, videoConfig) {
41743
- const devices = await getAudioDevices();
41744
- if (!devices.audioInputs.length) throw new RealtimeAPIError(error_RealtimeError.DEVICE_ACCESS_ERROR, 'Failed to get devices');
41745
- if (this._isSupportVideo && !devices.videoInputs.length) throw new RealtimeAPIError(error_RealtimeError.DEVICE_ACCESS_ERROR, 'Failed to get devices');
42000
+ const devices = await getAudioDevices({
42001
+ video: this._isSupportVideo
42002
+ });
42003
+ if (!devices.audioInputs.length) throw new RealtimeAPIError(error_RealtimeError.DEVICE_ACCESS_ERROR, 'Failed to get audio devices');
42004
+ if (this._isSupportVideo && !devices.videoInputs.length) throw new RealtimeAPIError(error_RealtimeError.DEVICE_ACCESS_ERROR, 'Failed to get video devices');
41746
42005
  await this.engine.startAudioCapture(devices.audioInputs[0].deviceId);
41747
42006
  if (this._isSupportVideo && (null == videoConfig ? void 0 : videoConfig.videoOnDefault)) await this.engine.startVideoCapture(devices.videoInputs[0].deviceId);
41748
42007
  if (this._isSupportVideo) this.engine.setLocalVideoPlayer(StreamIndex$1.STREAM_INDEX_MAIN, {
@@ -41895,7 +42154,7 @@
41895
42154
  // Step3 bind engine events
41896
42155
  this._client.bindEngineEvents();
41897
42156
  this._client.on(event_handler_EventNames.ALL, (eventName, data)=>{
41898
- this.dispatch(eventName, data);
42157
+ this.dispatch(eventName, data, false);
41899
42158
  });
41900
42159
  if (this._config.suppressStationaryNoise) {
41901
42160
  await this._client.enableAudioNoiseReduction();
@@ -41906,14 +42165,15 @@
41906
42165
  this._client.changeAIAnsExtension(true);
41907
42166
  this.dispatch(event_handler_EventNames.SUPPRESS_NON_STATIONARY_NOISE, {});
41908
42167
  }
41909
- var _this__config_audioMutedDefault, _this__config_videoConfig_videoOnDefault;
42168
+ var _this__config_audioMutedDefault, _this__config_videoConfig_videoOnDefault, _this__config_isAutoSubscribeAudio;
41910
42169
  // Step4 join room
41911
42170
  await this._client.joinRoom({
41912
42171
  token: roomInfo.token,
41913
42172
  roomId: roomInfo.room_id,
41914
42173
  uid: roomInfo.uid,
41915
42174
  audioMutedDefault: null !== (_this__config_audioMutedDefault = this._config.audioMutedDefault) && void 0 !== _this__config_audioMutedDefault && _this__config_audioMutedDefault,
41916
- 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
42175
+ 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,
42176
+ isAutoSubscribeAudio: null === (_this__config_isAutoSubscribeAudio = this._config.isAutoSubscribeAudio) || void 0 === _this__config_isAutoSubscribeAudio || _this__config_isAutoSubscribeAudio
41917
42177
  });
41918
42178
  // Step5 create local stream
41919
42179
  await this._client.createLocalStream(roomInfo.uid, this._config.videoConfig);
@@ -41925,7 +42185,6 @@
41925
42185
  token: roomInfo.token,
41926
42186
  appId: roomInfo.app_id
41927
42187
  });
41928
- this._log('dispatch client.connected event');
41929
42188
  }
41930
42189
  /**
41931
42190
  * en: Interrupt the current conversation
@@ -41935,7 +42194,6 @@
41935
42194
  var _this__client;
41936
42195
  await (null === (_this__client = this._client) || void 0 === _this__client ? void 0 : _this__client.stop());
41937
42196
  this.dispatch(event_handler_EventNames.INTERRUPTED, {});
41938
- this._log('dispatch client.interrupted event');
41939
42197
  }
41940
42198
  /**
41941
42199
  * en: Disconnect from the current session
@@ -42057,6 +42315,7 @@
42057
42315
  * 可选,默认是否抑制静态噪声,默认值为 false。
42058
42316
  * @param config.suppressNonStationaryNoise - Optional, suppress non-stationary noise, defaults to false. |
42059
42317
  * 可选,默认是否抑制非静态噪声,默认值为 false。
42318
+ * @param config.isAutoSubscribeAudio - Optional, whether to automatically subscribe to bot reply audio streams, defaults to true. |
42060
42319
  */ constructor(config){
42061
42320
  super(config.debug), this._client = null, this.isConnected = false, this._isTestEnv = false, this._isSupportVideo = false;
42062
42321
  this._config = config;