@coze/realtime-api 1.0.2 → 1.0.3-beta.2

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
- "?e272": function() {
10
+ "?666e": function() {
11
11
  /* (ignored) */ },
12
- "?5742": function() {
12
+ "?79fd": function() {
13
13
  /* (ignored) */ },
14
- "?9caf": 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, {
@@ -93,478 +108,1040 @@
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;
560
- };
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;
561
762
  /**
562
- * If the thing is a FormData object, return true, otherwise return false.
763
+ * Determine if a value is a Boolean
563
764
  *
564
- * @param {unknown} thing - The thing to check.
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
565
770
  *
566
- * @returns {boolean}
567
- */ function isSpecCompliantForm(thing) {
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);
778
+ };
779
+ /**
780
+ * Determine if a value is a Date
781
+ *
782
+ * @param {*} val The value to test
783
+ *
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) {
568
1145
  return !!(thing && isFunction(thing.append) && 'FormData' === thing[Symbol.toStringTag] && thing[Symbol.iterator]);
569
1146
  }
570
1147
  const toJSONObject = (obj)=>{
@@ -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);
@@ -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),
@@ -2535,887 +3112,333 @@
2535
3112
  });
2536
3113
  let promise;
2537
3114
  let i = 0;
2538
- let len;
2539
- if (!synchronousRequestInterceptors) {
2540
- const chain = [
2541
- dispatchRequest.bind(this),
2542
- void 0
2543
- ];
2544
- 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__("?9caf");
2867
- // EXTERNAL MODULE: crypto (ignored)
2868
- __webpack_require__("?e272");
2869
- // EXTERNAL MODULE: jsonwebtoken (ignored)
2870
- __webpack_require__("?5742");
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
- const handleAdditionalMessages = (additional_messages)=>null == additional_messages ? void 0 : additional_messages.map((i)=>({
3113
- ...i,
3114
- content: 'object' == typeof i.content ? JSON.stringify(i.content) : i.content
3115
- }));
3116
- class Chat extends APIResource {
3117
- /**
3118
- * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
3119
- * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
3120
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
3121
- * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
3122
- * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
3123
- * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
3124
- * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
3125
- * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义变量。
3126
- * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
3127
- * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
3128
- * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
3129
- * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
3130
- * @returns The data of the created chat. | 创建的对话数据。
3131
- */ async create(params, options) {
3132
- if (!params.user_id) params.user_id = uuid();
3133
- const { conversation_id, ...rest } = params;
3134
- const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
3135
- const payload = {
3136
- ...rest,
3137
- additional_messages: handleAdditionalMessages(params.additional_messages),
3138
- stream: false
3139
- };
3140
- const result = await this._client.post(apiUrl, payload, false, options);
3141
- return result.data;
3142
- }
3143
- /**
3144
- * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
3145
- * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
3146
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
3147
- * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
3148
- * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
3149
- * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
3150
- * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
3151
- * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
3152
- * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
3153
- * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
3154
- * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
3155
- * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
3156
- * @returns
3157
- */ async createAndPoll(params, options) {
3158
- if (!params.user_id) params.user_id = uuid();
3159
- const { conversation_id, ...rest } = params;
3160
- const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
3161
- const payload = {
3162
- ...rest,
3163
- additional_messages: handleAdditionalMessages(params.additional_messages),
3164
- stream: false
3165
- };
3166
- const result = await this._client.post(apiUrl, payload, false, options);
3167
- const chatId = result.data.id;
3168
- const conversationId = result.data.conversation_id;
3169
- let chat;
3170
- while(true){
3171
- await sleep(100);
3172
- chat = await this.retrieve(conversationId, chatId);
3173
- if ('completed' === chat.status || 'failed' === chat.status || 'requires_action' === chat.status) break;
3174
- }
3175
- const messageList = await this.messages.list(conversationId, chatId);
3176
- return {
3177
- chat,
3178
- messages: messageList
3179
- };
3180
- }
3181
- /**
3182
- * Call the Chat API to send messages to a published Coze agent with streaming response. | 调用此接口发起一次对话,支持流式响应。
3183
- * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
3184
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
3185
- * @param params - Required The parameters for streaming a chat session. | 流式会话的参数。
3186
- * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
3187
- * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
3188
- * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
3189
- * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
3190
- * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
3191
- * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
3192
- * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
3193
- * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
3194
- * @returns A stream of chat data. | 对话数据流。
3195
- */ async *stream(params, options) {
3196
- if (!params.user_id) params.user_id = uuid();
3197
- const { conversation_id, ...rest } = params;
3198
- const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
3199
- const payload = {
3200
- ...rest,
3201
- additional_messages: handleAdditionalMessages(params.additional_messages),
3202
- stream: true
3203
- };
3204
- const result = await this._client.post(apiUrl, payload, true, options);
3205
- for await (const message of result)if ("done" === message.event) {
3206
- const ret = {
3207
- event: message.event,
3208
- data: '[DONE]'
3209
- };
3210
- yield ret;
3211
- } else try {
3212
- const ret = {
3213
- event: message.event,
3214
- data: JSON.parse(message.data)
3215
- };
3216
- yield ret;
3217
- } catch (error) {
3218
- throw new CozeError(`Could not parse message into JSON:${message.data}`);
3219
- }
3220
- }
3221
- /**
3222
- * Get the detailed information of the chat. | 查看对话的详细信息。
3223
- * @docs en:https://www.coze.com/docs/developer_guides/retrieve_chat?_lang=en
3224
- * @docs zh:https://www.coze.cn/docs/developer_guides/retrieve_chat?_lang=zh
3225
- * @param conversation_id - Required The ID of the conversation. | 会话 ID。
3226
- * @param chat_id - Required The ID of the chat. | 对话 ID。
3227
- * @returns The data of the retrieved chat. | 检索到的对话数据。
3228
- */ async retrieve(conversation_id, chat_id, options) {
3229
- const apiUrl = `/v3/chat/retrieve?conversation_id=${conversation_id}&chat_id=${chat_id}`;
3230
- const result = await this._client.post(apiUrl, void 0, false, options);
3231
- return result.data;
3232
- }
3233
- /**
3234
- * Cancel a chat session. | 取消对话会话。
3235
- * @docs en:https://www.coze.com/docs/developer_guides/cancel_chat?_lang=en
3236
- * @docs zh:https://www.coze.cn/docs/developer_guides/cancel_chat?_lang=zh
3237
- * @param conversation_id - Required The ID of the conversation. | 会话 ID。
3238
- * @param chat_id - Required The ID of the chat. | 对话 ID。
3239
- * @returns The data of the canceled chat. | 取消的对话数据。
3240
- */ async cancel(conversation_id, chat_id, options) {
3241
- const apiUrl = '/v3/chat/cancel';
3242
- const payload = {
3243
- conversation_id,
3244
- chat_id
3245
- };
3246
- const result = await this._client.post(apiUrl, payload, false, options);
3247
- return result.data;
3248
- }
3249
- /**
3250
- * Submit tool outputs for a chat session. | 提交对话会话的工具输出。
3251
- * @docs en:https://www.coze.com/docs/developer_guides/chat_submit_tool_outputs?_lang=en
3252
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_submit_tool_outputs?_lang=zh
3253
- * @param params - Required Parameters for submitting tool outputs. | 提交工具输出的参数。
3254
- * @param params.conversation_id - Required The ID of the conversation. | 会话 ID。
3255
- * @param params.chat_id - Required The ID of the chat. | 对话 ID。
3256
- * @param params.tool_outputs - Required The outputs of the tool. | 工具的输出。
3257
- * @param params.stream - Optional Whether to use streaming response. | 是否使用流式响应。
3258
- * @returns The data of the submitted tool outputs or a stream of chat data. | 提交的工具输出数据或对话数据流。
3259
- */ async *submitToolOutputs(params, options) {
3260
- const { conversation_id, chat_id, ...rest } = params;
3261
- const apiUrl = `/v3/chat/submit_tool_outputs?conversation_id=${params.conversation_id}&chat_id=${params.chat_id}`;
3262
- const payload = {
3263
- ...rest
3264
- };
3265
- if (false === params.stream) {
3266
- const response = await this._client.post(apiUrl, payload, false, options);
3267
- return response.data;
3268
- }
3269
- {
3270
- const result = await this._client.post(apiUrl, payload, true, options);
3271
- for await (const message of result)if ("done" === message.event) {
3272
- const ret = {
3273
- event: message.event,
3274
- data: '[DONE]'
3275
- };
3276
- yield ret;
3277
- } else try {
3278
- const ret = {
3279
- event: message.event,
3280
- data: JSON.parse(message.data)
3281
- };
3282
- yield ret;
3115
+ let len;
3116
+ if (!synchronousRequestInterceptors) {
3117
+ const chain = [
3118
+ dispatchRequest.bind(this),
3119
+ void 0
3120
+ ];
3121
+ chain.unshift.apply(chain, requestInterceptorChain);
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;
3127
+ }
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);
3283
3136
  } catch (error) {
3284
- throw new CozeError(`Could not parse message into JSON:${message.data}`);
3137
+ onRejected.call(this, error);
3138
+ break;
3285
3139
  }
3286
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;
3287
3150
  }
3288
- constructor(...args){
3289
- 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);
3290
3155
  }
3291
3156
  }
3292
- class messages_Messages extends APIResource {
3293
- /**
3294
- * Create a message and add it to the specified conversation. | 创建一条消息,并将其添加到指定的会话中。
3295
- * @docs en: https://www.coze.com/docs/developer_guides/create_message?_lang=en
3296
- * @docs zh: https://www.coze.cn/docs/developer_guides/create_message?_lang=zh
3297
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3298
- * @param params - Required The parameters for creating a message | 创建消息所需的参数
3299
- * @param params.role - Required The entity that sent this message. Possible values: user, assistant. | 发送这条消息的实体。取值:user, assistant。
3300
- * @param params.content - Required The content of the message. | 消息的内容。
3301
- * @param params.content_type - Required The type of the message content. | 消息内容的类型。
3302
- * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
3303
- * @returns Information about the new message. | 消息详情。
3304
- */ async create(conversation_id, params, options) {
3305
- const apiUrl = `/v1/conversation/message/create?conversation_id=${conversation_id}`;
3306
- const response = await this._client.post(apiUrl, params, false, options);
3307
- return response.data;
3308
- }
3309
- /**
3310
- * Modify a message, supporting the modification of message content, additional content, and message type. | 修改一条消息,支持修改消息内容、附加内容和消息类型。
3311
- * @docs en: https://www.coze.com/docs/developer_guides/modify_message?_lang=en
3312
- * @docs zh: https://www.coze.cn/docs/developer_guides/modify_message?_lang=zh
3313
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3314
- * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
3315
- * @param params - Required The parameters for modifying a message | 修改消息所需的参数
3316
- * @param params.meta_data - Optional Additional information when modifying a message. | 修改消息时的附加消息。
3317
- * @param params.content - Optional The content of the message. | 消息的内容。
3318
- * @param params.content_type - Optional The type of the message content. | 消息内容的类型。
3319
- * @returns Information about the modified message. | 消息详情。
3320
- */ // eslint-disable-next-line max-params
3321
- async update(conversation_id, message_id, params, options) {
3322
- const apiUrl = `/v1/conversation/message/modify?conversation_id=${conversation_id}&message_id=${message_id}`;
3323
- const response = await this._client.post(apiUrl, params, false, options);
3324
- return response.message;
3325
- }
3326
- /**
3327
- * Get the detailed information of specified message. | 查看指定消息的详细信息。
3328
- * @docs en: https://www.coze.com/docs/developer_guides/retrieve_message?_lang=en
3329
- * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_message?_lang=zh
3330
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3331
- * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
3332
- * @returns Information about the message. | 消息详情。
3333
- */ async retrieve(conversation_id, message_id, options) {
3334
- const apiUrl = `/v1/conversation/message/retrieve?conversation_id=${conversation_id}&message_id=${message_id}`;
3335
- const response = await this._client.get(apiUrl, null, false, options);
3336
- 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
+ };
3337
3188
  }
3338
- /**
3339
- * List messages in a conversation. | 列出会话中的消息。
3340
- * @docs en: https://www.coze.com/docs/developer_guides/message_list?_lang=en
3341
- * @docs zh: https://www.coze.cn/docs/developer_guides/message_list?_lang=zh
3342
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3343
- * @param params - Optional The parameters for listing messages | 列出消息所需的参数
3344
- * @param params.order - Optional The order of the messages. | 消息的顺序。
3345
- * @param params.chat_id - Optional The ID of the chat. | 聊天 ID。
3346
- * @param params.before_id - Optional The ID of the message before which to list. | 列出此消息之前的消息 ID。
3347
- * @param params.after_id - Optional The ID of the message after which to list. | 列出此消息之后的消息 ID。
3348
- * @param params.limit - Optional The maximum number of messages to return. | 返回的最大消息数。
3349
- * @returns A list of messages. | 消息列表。
3350
- */ async list(conversation_id, params, options) {
3351
- const apiUrl = `/v1/conversation/message/list?conversation_id=${conversation_id}`;
3352
- const response = await this._client.post(apiUrl, params, false, options);
3353
- return response;
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
+ });
3354
3233
  }
3355
3234
  /**
3356
- * Call the API to delete a message within a specified conversation. | 调用接口在指定会话中删除消息。
3357
- * @docs en: https://www.coze.com/docs/developer_guides/delete_message?_lang=en
3358
- * @docs zh: https://www.coze.cn/docs/developer_guides/delete_message?_lang=zh
3359
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3360
- * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
3361
- * @returns Details of the deleted message. | 已删除的消息详情。
3362
- */ async delete(conversation_id, message_id, options) {
3363
- const apiUrl = `/v1/conversation/message/delete?conversation_id=${conversation_id}&message_id=${message_id}`;
3364
- const response = await this._client.post(apiUrl, void 0, false, options);
3365
- return response.data;
3235
+ * Throws a `CanceledError` if cancellation has been requested.
3236
+ */ throwIfRequested() {
3237
+ if (this.reason) throw this.reason;
3366
3238
  }
3367
- }
3368
- class Conversations extends APIResource {
3369
3239
  /**
3370
- * Create a conversation. Conversation is an interaction between an agent and a user, including one or more messages. | 调用接口创建一个会话。
3371
- * @docs en: https://www.coze.com/docs/developer_guides/create_conversation?_lang=en
3372
- * @docs zh: https://www.coze.cn/docs/developer_guides/create_conversation?_lang=zh
3373
- * @param params - Required The parameters for creating a conversation | 创建会话所需的参数
3374
- * @param params.messages - Optional Messages in the conversation. | 会话中的消息内容。
3375
- * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
3376
- * @param params.bot_id - Optional Bind and isolate conversation on different bots. | 绑定和隔离不同Bot的会话。
3377
- * @returns Information about the created conversation. | 会话的基础信息。
3378
- */ async create(params, options) {
3379
- const apiUrl = '/v1/conversation/create';
3380
- const response = await this._client.post(apiUrl, params, false, options);
3381
- return response.data;
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
+ ];
3382
3250
  }
3383
3251
  /**
3384
- * Get the information of specific conversation. | 通过会话 ID 查看会话信息。
3385
- * @docs en: https://www.coze.com/docs/developer_guides/retrieve_conversation?_lang=en
3386
- * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_conversation?_lang=zh
3387
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3388
- * @returns Information about the conversation. | 会话的基础信息。
3389
- */ async retrieve(conversation_id, options) {
3390
- const apiUrl = `/v1/conversation/retrieve?conversation_id=${conversation_id}`;
3391
- const response = await this._client.get(apiUrl, null, false, options);
3392
- 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);
3393
3257
  }
3394
- /**
3395
- * List all conversations. | 列出 Bot 下所有会话。
3396
- * @param params
3397
- * @param params.bot_id - Required Bot ID. | Bot ID。
3398
- * @param params.page_num - Optional The page number. | 页码,默认值为 1。
3399
- * @param params.page_size - Optional The number of conversations per page. | 每页的会话数量,默认值为 50。
3400
- * @returns Information about the conversations. | 会话的信息。
3401
- */ async list(params, options) {
3402
- const apiUrl = '/v1/conversations';
3403
- const response = await this._client.get(apiUrl, params, false, options);
3404
- 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;
3405
3266
  }
3406
3267
  /**
3407
- * Clear a conversation. | 清空会话。
3408
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3409
- * @returns Information about the conversation session. | 会话的会话 ID。
3410
- */ async clear(conversation_id, options) {
3411
- const apiUrl = `/v1/conversations/${conversation_id}/clear`;
3412
- const response = await this._client.post(apiUrl, null, false, options);
3413
- return response.data;
3414
- }
3415
- constructor(...args){
3416
- 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
+ };
3417
3279
  }
3418
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;
3419
3442
  class Files extends APIResource {
3420
3443
  /**
3421
3444
  * Upload files to Coze platform. | 调用接口上传文件到扣子。
@@ -3503,9 +3526,46 @@
3503
3526
  this.data = data;
3504
3527
  }
3505
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
+ }
3506
3566
  class Workflows extends APIResource {
3507
3567
  constructor(...args){
3508
- super(...args), this.runs = new Runs(this._client);
3568
+ super(...args), this.runs = new Runs(this._client), this.chat = new WorkflowChat(this._client);
3509
3569
  }
3510
3570
  }
3511
3571
  class WorkSpaces extends APIResource {
@@ -3529,6 +3589,8 @@
3529
3589
  };
3530
3590
  class Documents extends APIResource {
3531
3591
  /**
3592
+ * @deprecated The method is deprecated and will be removed in a future version. Please use 'client.datasets.documents.list' instead.
3593
+ *
3532
3594
  * View the file list of a specified knowledge base, which includes lists of documents, spreadsheets, or images.
3533
3595
  * | 调用接口查看指定知识库的内容列表,即文件、表格或图像列表。
3534
3596
  * @docs en: https://www.coze.com/docs/developer_guides/list_knowledge_files?_lang=en
@@ -3539,12 +3601,14 @@
3539
3601
  * @returns ListDocumentData | 知识库文件列表
3540
3602
  */ list(params, options) {
3541
3603
  const apiUrl = '/open_api/knowledge/document/list';
3542
- const response = this._client.get(apiUrl, params, false, esm_mergeConfig(options, {
3604
+ const response = this._client.get(apiUrl, params, false, mergeConfig(options, {
3543
3605
  headers: documents_headers
3544
3606
  }));
3545
3607
  return response;
3546
3608
  }
3547
3609
  /**
3610
+ * @deprecated The method is deprecated and will be removed in a future version. Please use 'client.datasets.documents.create' instead.
3611
+ *
3548
3612
  * Upload files to the specific knowledge. | 调用此接口向指定知识库中上传文件。
3549
3613
  * @docs en: https://www.coze.com/docs/developer_guides/create_knowledge_files?_lang=en
3550
3614
  * @docs zh: https://www.coze.cn/docs/developer_guides/create_knowledge_files?_lang=zh
@@ -3555,12 +3619,14 @@
3555
3619
  * @returns DocumentInfo[] | 已上传文件的基本信息
3556
3620
  */ async create(params, options) {
3557
3621
  const apiUrl = '/open_api/knowledge/document/create';
3558
- const response = await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3622
+ const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
3559
3623
  headers: documents_headers
3560
3624
  }));
3561
3625
  return response.document_infos;
3562
3626
  }
3563
3627
  /**
3628
+ * @deprecated The method is deprecated and will be removed in a future version. Please use 'client.datasets.documents.delete' instead.
3629
+ *
3564
3630
  * Delete text, images, sheets, and other files in the knowledge base, supporting batch deletion.
3565
3631
  * | 删除知识库中的文本、图像、表格等文件,支持批量删除。
3566
3632
  * @docs en: https://www.coze.com/docs/developer_guides/delete_knowledge_files?_lang=en
@@ -3569,11 +3635,13 @@
3569
3635
  * @returns void | 无返回
3570
3636
  */ async delete(params, options) {
3571
3637
  const apiUrl = '/open_api/knowledge/document/delete';
3572
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3638
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3573
3639
  headers: documents_headers
3574
3640
  }));
3575
3641
  }
3576
3642
  /**
3643
+ * @deprecated The method is deprecated and will be removed in a future version. Please use 'client.datasets.documents.update' instead.
3644
+ *
3577
3645
  * Modify the knowledge base file name and update strategy. | 调用接口修改知识库文件名称和更新策略。
3578
3646
  * @docs en: https://www.coze.com/docs/developer_guides/modify_knowledge_files?_lang=en
3579
3647
  * @docs zh: https://www.coze.cn/docs/developer_guides/modify_knowledge_files?_lang=zh
@@ -3583,14 +3651,86 @@
3583
3651
  * @returns void | 无返回
3584
3652
  */ async update(params, options) {
3585
3653
  const apiUrl = '/open_api/knowledge/document/update';
3586
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3654
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3587
3655
  headers: documents_headers
3588
3656
  }));
3589
3657
  }
3590
3658
  }
3591
3659
  class Knowledge extends APIResource {
3592
3660
  constructor(...args){
3593
- 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);
3594
3734
  }
3595
3735
  }
3596
3736
  class Voices extends APIResource {
@@ -3647,7 +3787,7 @@
3647
3787
  * @returns Speech synthesis data
3648
3788
  */ async create(params, options) {
3649
3789
  const apiUrl = '/v1/audio/speech';
3650
- const response = await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3790
+ const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
3651
3791
  responseType: 'arraybuffer'
3652
3792
  }));
3653
3793
  return response;
@@ -3660,23 +3800,26 @@
3660
3800
  return response.data;
3661
3801
  }
3662
3802
  }
3663
- class esm_Audio extends APIResource {
3803
+ class audio_Audio extends APIResource {
3664
3804
  constructor(...args){
3665
3805
  super(...args), this.rooms = new Rooms(this._client), this.voices = new Voices(this._client), this.speech = new Speech(this._client);
3666
3806
  }
3667
3807
  }
3668
- var package_namespaceObject = JSON.parse('{"name":"@coze/api","version":"1.0.14","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
3669
- 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.2","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;
3670
3813
  const getEnv = ()=>{
3671
3814
  const nodeVersion = process.version.slice(1); // Remove 'v' prefix
3672
3815
  const { platform } = process;
3673
3816
  let osName = platform.toLowerCase();
3674
- let osVersion = os_ignored_.release();
3817
+ let osVersion = os_ignored_default().release();
3675
3818
  if ('darwin' === platform) {
3676
3819
  osName = 'macos';
3677
3820
  // Try to parse the macOS version
3678
3821
  try {
3679
- const darwinVersion = os_ignored_.release().split('.');
3822
+ const darwinVersion = os_ignored_default().release().split('.');
3680
3823
  if (darwinVersion.length >= 2) {
3681
3824
  const majorVersion = parseInt(darwinVersion[0], 10);
3682
3825
  if (!isNaN(majorVersion) && majorVersion >= 9) {
@@ -3689,10 +3832,10 @@
3689
3832
  }
3690
3833
  } else if ('win32' === platform) {
3691
3834
  osName = 'windows';
3692
- osVersion = os_ignored_.release();
3835
+ osVersion = os_ignored_default().release();
3693
3836
  } else if ('linux' === platform) {
3694
3837
  osName = 'linux';
3695
- osVersion = os_ignored_.release();
3838
+ osVersion = os_ignored_default().release();
3696
3839
  }
3697
3840
  return {
3698
3841
  osName,
@@ -3702,12 +3845,12 @@
3702
3845
  };
3703
3846
  const getUserAgent = ()=>{
3704
3847
  const { nodeVersion, osName, osVersion } = getEnv();
3705
- return `coze-js/${esm_version} node/${nodeVersion} ${osName}/${osVersion}`.toLowerCase();
3848
+ return `coze-js/${version_version} node/${nodeVersion} ${osName}/${osVersion}`.toLowerCase();
3706
3849
  };
3707
3850
  const getNodeClientUserAgent = ()=>{
3708
3851
  const { osVersion, nodeVersion, osName } = getEnv();
3709
3852
  const ua = {
3710
- version: esm_version,
3853
+ version: version_version,
3711
3854
  lang: 'node',
3712
3855
  lang_version: nodeVersion,
3713
3856
  os_name: osName,
@@ -3715,15 +3858,17 @@
3715
3858
  };
3716
3859
  return JSON.stringify(ua);
3717
3860
  };
3718
- /* eslint-disable @typescript-eslint/no-explicit-any */ const esm_handleError = (error)=>{
3861
+ /* eslint-disable @typescript-eslint/no-explicit-any */ const fetcher_handleError = (error)=>{
3719
3862
  if (!error.isAxiosError && (!error.code || !error.message)) return new CozeError(`Unexpected error: ${error.message}`);
3720
3863
  if ('ECONNABORTED' === error.code && error.message.includes('timeout') || 'ETIMEDOUT' === error.code) {
3721
3864
  var _error_response;
3722
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);
3723
3866
  }
3724
3867
  if ('ERR_CANCELED' === error.code) return new APIUserAbortError(error.message);
3725
- var _error_response1, _error_response2, _error_response3;
3726
- 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
+ }
3727
3872
  };
3728
3873
  async function fetchAPI(url) {
3729
3874
  let options = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
@@ -3739,7 +3884,7 @@
3739
3884
  adapter: options.isStreaming ? 'fetch' : void 0,
3740
3885
  ...options
3741
3886
  }).catch((error)=>{
3742
- throw esm_handleError(error);
3887
+ throw fetcher_handleError(error);
3743
3888
  });
3744
3889
  return {
3745
3890
  async *stream () {
@@ -3777,7 +3922,7 @@
3777
3922
  buffer = lines[lines.length - 1]; // Keep the last incomplete line in the buffer
3778
3923
  }
3779
3924
  } catch (error) {
3780
- esm_handleError(error);
3925
+ fetcher_handleError(error);
3781
3926
  }
3782
3927
  },
3783
3928
  json: ()=>response.data,
@@ -3801,17 +3946,22 @@
3801
3946
  }
3802
3947
  /**
3803
3948
  * default coze base URL is api.coze.com
3804
- */ const COZE_COM_BASE_URL = 'https://api.coze.com';
3805
- /* eslint-disable max-params */ class APIClient {
3806
- 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();
3807
3957
  const headers = {
3808
- authorization: `Bearer ${this.token}`
3958
+ authorization: `Bearer ${token}`
3809
3959
  };
3810
- if (!isBrowser()) {
3960
+ if (!utils_isBrowser()) {
3811
3961
  headers['User-Agent'] = getUserAgent();
3812
3962
  headers['X-Coze-Client-User-Agent'] = getNodeClientUserAgent();
3813
3963
  }
3814
- const config = esm_mergeConfig(this.axiosOptions, options, {
3964
+ const config = mergeConfig(this.axiosOptions, options, {
3815
3965
  headers
3816
3966
  });
3817
3967
  config.method = method;
@@ -3820,7 +3970,7 @@
3820
3970
  }
3821
3971
  async makeRequest(apiUrl, method, body, isStream, options) {
3822
3972
  const fullUrl = `${this.baseURL}${apiUrl}`;
3823
- const fetchOptions = this.buildOptions(method, body, options);
3973
+ const fetchOptions = await this.buildOptions(method, body, options);
3824
3974
  fetchOptions.isStreaming = isStream;
3825
3975
  fetchOptions.axiosInstance = this.axiosInstance;
3826
3976
  this.debugLog(`--- request url: ${fullUrl}`);
@@ -3835,7 +3985,7 @@
3835
3985
  if (contentType && contentType.includes('application/json')) {
3836
3986
  const result = await json();
3837
3987
  const { code, msg } = result;
3838
- 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);
3839
3989
  }
3840
3990
  return stream();
3841
3991
  }
@@ -3843,7 +3993,7 @@
3843
3993
  {
3844
3994
  const result = await json();
3845
3995
  const { code, msg } = result;
3846
- 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);
3847
3997
  return result;
3848
3998
  }
3849
3999
  }
@@ -3875,29 +4025,35 @@
3875
4025
  }
3876
4026
  constructor(config){
3877
4027
  this._config = config;
3878
- this.baseURL = config.baseURL || COZE_COM_BASE_URL;
4028
+ this.baseURL = config.baseURL || constant_COZE_COM_BASE_URL;
3879
4029
  this.token = config.token;
3880
4030
  this.axiosOptions = config.axiosOptions || {};
3881
4031
  this.axiosInstance = config.axiosInstance;
3882
4032
  this.debug = config.debug || false;
3883
4033
  this.allowPersonalAccessTokenInBrowser = config.allowPersonalAccessTokenInBrowser || false;
3884
4034
  this.headers = config.headers;
3885
- 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');
3886
- }
3887
- }
3888
- APIClient.APIError = APIError;
3889
- APIClient.BadRequestError = BadRequestError;
3890
- APIClient.AuthenticationError = AuthenticationError;
3891
- APIClient.PermissionDeniedError = PermissionDeniedError;
3892
- APIClient.NotFoundError = NotFoundError;
3893
- APIClient.RateLimitError = RateLimitError;
3894
- APIClient.InternalServerError = InternalServerError;
3895
- APIClient.GatewayError = GatewayError;
3896
- APIClient.TimeoutError = TimeoutError;
3897
- APIClient.UserAbortError = APIUserAbortError;
3898
- 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 {
3899
4053
  constructor(...args){
3900
- 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);
3901
4057
  }
3902
4058
  }
3903
4059
  /**
@@ -9129,7 +9285,7 @@
9129
9285
  }, stringPad = {
9130
9286
  start: createMethod(!1),
9131
9287
  end: createMethod(!0)
9132
- }, 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;
9133
9289
  $$F({
9134
9290
  target: "String",
9135
9291
  proto: !0,
@@ -38282,11 +38438,12 @@
38282
38438
  + * @param milliseconds The time to sleep in milliseconds
38283
38439
  + * @throws {Error} If milliseconds is negative
38284
38440
  + * @returns Promise that resolves after the specified duration
38285
- + */ const utils_sleep = (milliseconds)=>{
38441
+ + */ const src_utils_sleep = (milliseconds)=>{
38286
38442
  if (milliseconds < 0) throw new Error('Sleep duration must be non-negative');
38287
38443
  return new Promise((resolve)=>setTimeout(resolve, milliseconds));
38288
38444
  };
38289
38445
  /**
38446
+ * @deprecated use checkDevicePermission instead
38290
38447
  * Check microphone permission,return boolean
38291
38448
  */ const checkPermission = async function() {
38292
38449
  let { audio = true, video = false } = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
@@ -38301,6 +38458,13 @@
38301
38458
  return false;
38302
38459
  }
38303
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
+ };
38304
38468
  /**
38305
38469
  * Get audio devices
38306
38470
  * @returns Promise<AudioDevices> Object containing arrays of audio input and output devices