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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,10 @@
1
- /*! For license information please see index.js.LICENSE.txt */
1
+ /*! For license information please see index.mjs.LICENSE.txt */
2
2
  var __webpack_modules__ = {
3
- "?c628": function() {
3
+ "?666e": function() {
4
4
  /* (ignored) */ },
5
- "?9452": function() {
5
+ "?79fd": function() {
6
6
  /* (ignored) */ },
7
- "?e2b1": function() {
7
+ "?9050": function() {
8
8
  /* (ignored) */ }
9
9
  };
10
10
  /************************************************************************/ // The module cache
@@ -23,7 +23,22 @@ function __webpack_require__(moduleId) {
23
23
  // Return the exports of the module
24
24
  return module.exports;
25
25
  }
26
- /************************************************************************/ // webpack/runtime/define_property_getters
26
+ /************************************************************************/ // webpack/runtime/compat_get_default_export
27
+ (()=>{
28
+ // getDefaultExport function for compatibility with non-ESM modules
29
+ __webpack_require__.n = function(module) {
30
+ var getter = module && module.__esModule ? function() {
31
+ return module['default'];
32
+ } : function() {
33
+ return module;
34
+ };
35
+ __webpack_require__.d(getter, {
36
+ a: getter
37
+ });
38
+ return getter;
39
+ };
40
+ })();
41
+ // webpack/runtime/define_property_getters
27
42
  (()=>{
28
43
  __webpack_require__.d = function(exports, definition) {
29
44
  for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) Object.defineProperty(exports, key, {
@@ -78,480 +93,1041 @@ __webpack_require__.d(src_utils_namespaceObject, {
78
93
  checkDevicePermission: ()=>checkDevicePermission,
79
94
  checkPermission: ()=>checkPermission,
80
95
  getAudioDevices: ()=>getAudioDevices,
81
- sleep: ()=>utils_sleep
96
+ sleep: ()=>src_utils_sleep
82
97
  });
83
- function bind(fn, thisArg) {
84
- return function() {
85
- return fn.apply(thisArg, arguments);
86
- };
98
+ class APIResource {
99
+ constructor(client){
100
+ this._client = client;
101
+ }
87
102
  }
88
- // utils is a library of generic helper functions non-specific to axios
89
- const { toString: utils_toString } = Object.prototype;
90
- const { getPrototypeOf } = Object;
91
- const kindOf = ((cache)=>(thing)=>{
92
- const str = utils_toString.call(thing);
93
- return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
94
- })(Object.create(null));
95
- const kindOfTest = (type)=>{
96
- type = type.toLowerCase();
97
- return (thing)=>kindOf(thing) === type;
98
- };
99
- const typeOfTest = (type)=>(thing)=>typeof thing === type;
100
- /**
101
- * Determine if a value is an Array
102
- *
103
- * @param {Object} val The value to test
104
- *
105
- * @returns {boolean} True if value is an Array, otherwise false
106
- */ const { isArray } = Array;
107
- /**
108
- * Determine if a value is undefined
109
- *
110
- * @param {*} val The value to test
111
- *
112
- * @returns {boolean} True if the value is undefined, otherwise false
113
- */ const isUndefined = typeOfTest('undefined');
114
- /**
115
- * Determine if a value is a Buffer
116
- *
117
- * @param {*} val The value to test
118
- *
119
- * @returns {boolean} True if value is a Buffer, otherwise false
120
- */ function isBuffer(val) {
121
- return null !== val && !isUndefined(val) && null !== val.constructor && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
103
+ /* eslint-disable @typescript-eslint/no-namespace */ class Bots extends APIResource {
104
+ /**
105
+ * Create a new agent. | 调用接口创建一个新的智能体。
106
+ * @docs en:https://www.coze.com/docs/developer_guides/create_bot?_lang=en
107
+ * @docs zh:https://www.coze.cn/docs/developer_guides/create_bot?_lang=zh
108
+ * @param params - Required The parameters for creating a bot. | 创建 Bot 的参数。
109
+ * @param params.space_id - Required The Space ID of the space where the agent is located. | Bot 所在的空间的 Space ID。
110
+ * @param params.name - Required The name of the agent. It should be 1 to 20 characters long. | Bot 的名称。
111
+ * @param params.description - Optional The description of the agent. It can be 0 to 500 characters long. | Bot 的描述信息。
112
+ * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
113
+ * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
114
+ * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
115
+ * @returns Information about the created bot. | 创建的 Bot 信息。
116
+ */ async create(params, options) {
117
+ const apiUrl = '/v1/bot/create';
118
+ const result = await this._client.post(apiUrl, params, false, options);
119
+ return result.data;
120
+ }
121
+ /**
122
+ * Update the configuration of an agent. | 调用接口修改智能体的配置。
123
+ * @docs en:https://www.coze.com/docs/developer_guides/update_bot?_lang=en
124
+ * @docs zh:https://www.coze.cn/docs/developer_guides/update_bot?_lang=zh
125
+ * @param params - Required The parameters for updating a bot. | 修改 Bot 的参数。
126
+ * @param params.bot_id - Required The ID of the agent that the API interacts with. | 待修改配置的智能体ID。
127
+ * @param params.name - Optional The name of the agent. | Bot 的名称。
128
+ * @param params.description - Optional The description of the agent. | Bot 的描述信息。
129
+ * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
130
+ * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
131
+ * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
132
+ * @param params.knowledge - Optional Knowledge configurations of the agent. | Bot 的知识库配置。
133
+ * @returns Undefined | 无返回值
134
+ */ async update(params, options) {
135
+ const apiUrl = '/v1/bot/update';
136
+ const result = await this._client.post(apiUrl, params, false, options);
137
+ return result.data;
138
+ }
139
+ /**
140
+ * Get the agents published as API service. | 调用接口查看指定空间发布到 Agent as API 渠道的智能体列表。
141
+ * @docs en:https://www.coze.com/docs/developer_guides/published_bots_list?_lang=en
142
+ * @docs zh:https://www.coze.cn/docs/developer_guides/published_bots_list?_lang=zh
143
+ * @param params - Required The parameters for listing bots. | 列出 Bot 的参数。
144
+ * @param params.space_id - Required The ID of the space. | Bot 所在的空间的 Space ID。
145
+ * @param params.page_size - Optional Pagination size. | 分页大小。
146
+ * @param params.page_index - Optional Page number for paginated queries. | 分页查询时的页码。
147
+ * @returns List of published bots. | 已发布的 Bot 列表。
148
+ */ async list(params, options) {
149
+ const apiUrl = '/v1/space/published_bots_list';
150
+ const result = await this._client.get(apiUrl, params, false, options);
151
+ return result.data;
152
+ }
153
+ /**
154
+ * Publish the specified agent as an API service. | 调用接口创建一个新的智能体。
155
+ * @docs en:https://www.coze.com/docs/developer_guides/publish_bot?_lang=en
156
+ * @docs zh:https://www.coze.cn/docs/developer_guides/publish_bot?_lang=zh
157
+ * @param params - Required The parameters for publishing a bot. | 发布 Bot 的参数。
158
+ * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要发布的智能体ID。
159
+ * @param params.connector_ids - Required The list of publishing channel IDs for the agent. | 智能体的发布渠道 ID 列表。
160
+ * @returns Undefined | 无返回值
161
+ */ async publish(params, options) {
162
+ const apiUrl = '/v1/bot/publish';
163
+ const result = await this._client.post(apiUrl, params, false, options);
164
+ return result.data;
165
+ }
166
+ /**
167
+ * Get the configuration information of the agent. | 获取指定智能体的配置信息。
168
+ * @docs en:https://www.coze.com/docs/developer_guides/get_metadata?_lang=en
169
+ * @docs zh:https://www.coze.cn/docs/developer_guides/get_metadata?_lang=zh
170
+ * @param params - Required The parameters for retrieving a bot. | 获取 Bot 的参数。
171
+ * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要查看的智能体ID。
172
+ * @returns Information about the bot. | Bot 的配置信息。
173
+ */ async retrieve(params, options) {
174
+ const apiUrl = '/v1/bot/get_online_info';
175
+ const result = await this._client.get(apiUrl, params, false, options);
176
+ return result.data;
177
+ }
122
178
  }
123
- /**
124
- * Determine if a value is an ArrayBuffer
125
- *
126
- * @param {*} val The value to test
127
- *
128
- * @returns {boolean} True if value is an ArrayBuffer, otherwise false
129
- */ const isArrayBuffer = kindOfTest('ArrayBuffer');
130
- /**
131
- * Determine if a value is a view on an ArrayBuffer
132
- *
133
- * @param {*} val The value to test
134
- *
135
- * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
136
- */ function isArrayBufferView(val) {
137
- let result;
138
- result = 'undefined' != typeof ArrayBuffer && ArrayBuffer.isView ? ArrayBuffer.isView(val) : val && val.buffer && isArrayBuffer(val.buffer);
139
- return result;
179
+ /* eslint-disable security/detect-object-injection */ /* eslint-disable @typescript-eslint/no-explicit-any */ function safeJsonParse(jsonString) {
180
+ let defaultValue = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : '';
181
+ try {
182
+ return JSON.parse(jsonString);
183
+ } catch (error) {
184
+ return defaultValue;
185
+ }
140
186
  }
141
- /**
142
- * Determine if a value is a String
143
- *
144
- * @param {*} val The value to test
145
- *
146
- * @returns {boolean} True if value is a String, otherwise false
147
- */ const isString = typeOfTest('string');
148
- /**
149
- * Determine if a value is a Function
150
- *
151
- * @param {*} val The value to test
152
- * @returns {boolean} True if value is a Function, otherwise false
153
- */ const isFunction = typeOfTest('function');
154
- /**
155
- * Determine if a value is a Number
156
- *
157
- * @param {*} val The value to test
158
- *
159
- * @returns {boolean} True if value is a Number, otherwise false
160
- */ const isNumber = typeOfTest('number');
161
- /**
162
- * Determine if a value is an Object
163
- *
164
- * @param {*} thing The value to test
165
- *
166
- * @returns {boolean} True if value is an Object, otherwise false
167
- */ const isObject = (thing)=>null !== thing && 'object' == typeof thing;
168
- /**
169
- * Determine if a value is a Boolean
170
- *
171
- * @param {*} thing The value to test
172
- * @returns {boolean} True if value is a Boolean, otherwise false
173
- */ const isBoolean = (thing)=>true === thing || false === thing;
174
- /**
175
- * Determine if a value is a plain Object
176
- *
177
- * @param {*} val The value to test
178
- *
179
- * @returns {boolean} True if value is a plain Object, otherwise false
180
- */ const isPlainObject = (val)=>{
181
- if ('object' !== kindOf(val)) return false;
182
- const prototype = getPrototypeOf(val);
183
- return (null === prototype || prototype === Object.prototype || null === Object.getPrototypeOf(prototype)) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
184
- };
185
- /**
186
- * Determine if a value is a Date
187
- *
188
- * @param {*} val The value to test
189
- *
190
- * @returns {boolean} True if value is a Date, otherwise false
191
- */ const isDate = kindOfTest('Date');
192
- /**
193
- * Determine if a value is a File
194
- *
195
- * @param {*} val The value to test
196
- *
197
- * @returns {boolean} True if value is a File, otherwise false
198
- */ const isFile = kindOfTest('File');
199
- /**
200
- * Determine if a value is a Blob
201
- *
202
- * @param {*} val The value to test
203
- *
204
- * @returns {boolean} True if value is a Blob, otherwise false
205
- */ const isBlob = kindOfTest('Blob');
206
- /**
207
- * Determine if a value is a FileList
208
- *
209
- * @param {*} val The value to test
210
- *
211
- * @returns {boolean} True if value is a File, otherwise false
212
- */ const utils_isFileList = kindOfTest('FileList');
213
- /**
214
- * Determine if a value is a Stream
215
- *
216
- * @param {*} val The value to test
217
- *
218
- * @returns {boolean} True if value is a Stream, otherwise false
219
- */ const utils_isStream = (val)=>isObject(val) && isFunction(val.pipe);
220
- /**
221
- * Determine if a value is a FormData
222
- *
223
- * @param {*} thing The value to test
224
- *
225
- * @returns {boolean} True if value is an FormData, otherwise false
226
- */ const utils_isFormData = (thing)=>{
227
- let kind;
228
- return thing && ('function' == typeof FormData && thing instanceof FormData || isFunction(thing.append) && ('formdata' === (kind = kindOf(thing)) || // detect form-data instance
229
- 'object' === kind && isFunction(thing.toString) && '[object FormData]' === thing.toString()));
230
- };
231
- /**
232
- * Determine if a value is a URLSearchParams object
233
- *
234
- * @param {*} val The value to test
235
- *
236
- * @returns {boolean} True if value is a URLSearchParams object, otherwise false
237
- */ const isURLSearchParams = kindOfTest('URLSearchParams');
238
- const [isReadableStream, isRequest, isResponse, isHeaders] = [
239
- 'ReadableStream',
240
- 'Request',
241
- 'Response',
242
- 'Headers'
243
- ].map(kindOfTest);
244
- /**
245
- * Trim excess whitespace off the beginning and end of a string
246
- *
247
- * @param {String} str The String to trim
248
- *
249
- * @returns {String} The String freed of excess whitespace
250
- */ const trim = (str)=>str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
251
- /**
252
- * Iterate over an Array or an Object invoking a function for each item.
253
- *
254
- * If `obj` is an Array callback will be called passing
255
- * the value, index, and complete array for each item.
256
- *
257
- * If 'obj' is an Object callback will be called passing
258
- * the value, key, and complete object for each property.
259
- *
260
- * @param {Object|Array} obj The object to iterate
261
- * @param {Function} fn The callback to invoke for each item
262
- *
263
- * @param {Boolean} [allOwnKeys = false]
264
- * @returns {any}
265
- */ function forEach(obj, fn, { allOwnKeys = false } = {}) {
266
- // Don't bother if no value provided
267
- if (null == obj) return;
268
- let i;
269
- let l;
270
- // Force an array if not already something iterable
271
- if ('object' != typeof obj) /*eslint no-param-reassign:0*/ obj = [
272
- obj
273
- ];
274
- if (isArray(obj)) // Iterate over array values
275
- for(i = 0, l = obj.length; i < l; i++)fn.call(null, obj[i], i, obj);
276
- else {
277
- // Iterate over object keys
278
- const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
279
- const len = keys.length;
280
- let key;
281
- for(i = 0; i < len; i++){
282
- key = keys[i];
283
- fn.call(null, obj[key], key, obj);
187
+ function utils_sleep(ms) {
188
+ return new Promise((resolve)=>{
189
+ setTimeout(resolve, ms);
190
+ });
191
+ }
192
+ function utils_isBrowser() {
193
+ return 'undefined' != typeof window;
194
+ }
195
+ function isPlainObject(obj) {
196
+ if ('object' != typeof obj || null === obj) return false;
197
+ const proto = Object.getPrototypeOf(obj);
198
+ if (null === proto) return true;
199
+ let baseProto = proto;
200
+ while(null !== Object.getPrototypeOf(baseProto))baseProto = Object.getPrototypeOf(baseProto);
201
+ return proto === baseProto;
202
+ }
203
+ function mergeConfig() {
204
+ for(var _len = arguments.length, objects = new Array(_len), _key = 0; _key < _len; _key++)objects[_key] = arguments[_key];
205
+ return objects.reduce((result, obj)=>{
206
+ if (void 0 === obj) return result || {};
207
+ for(const key in obj)if (Object.prototype.hasOwnProperty.call(obj, key)) {
208
+ if (isPlainObject(obj[key]) && !Array.isArray(obj[key])) result[key] = mergeConfig(result[key] || {}, obj[key]);
209
+ else result[key] = obj[key];
210
+ }
211
+ return result;
212
+ }, {});
213
+ }
214
+ function isPersonalAccessToken(token) {
215
+ return null == token ? void 0 : token.startsWith('pat_');
216
+ }
217
+ /* eslint-disable max-params */ class CozeError extends Error {
218
+ }
219
+ class error_APIError extends CozeError {
220
+ static makeMessage(status, errorBody, message, headers) {
221
+ if (!errorBody && message) return message;
222
+ if (errorBody) {
223
+ const list = [];
224
+ const { code, msg, error } = errorBody;
225
+ if (code) list.push(`code: ${code}`);
226
+ if (msg) list.push(`msg: ${msg}`);
227
+ if ((null == error ? void 0 : error.detail) && msg !== error.detail) list.push(`detail: ${error.detail}`);
228
+ const logId = (null == error ? void 0 : error.logid) || (null == headers ? void 0 : headers['x-tt-logid']);
229
+ if (logId) list.push(`logid: ${logId}`);
230
+ const help_doc = null == error ? void 0 : error.help_doc;
231
+ if (help_doc) list.push(`help doc: ${help_doc}`);
232
+ return list.join(', ');
284
233
  }
234
+ if (status) return `http status code: ${status} (no body)`;
235
+ return '(no status code or body)';
236
+ }
237
+ static generate(status, errorResponse, message, headers) {
238
+ if (!status) return new APIConnectionError({
239
+ cause: castToError(errorResponse)
240
+ });
241
+ const error = errorResponse;
242
+ // https://www.coze.cn/docs/developer_guides/coze_error_codes
243
+ if (400 === status || (null == error ? void 0 : error.code) === 4000) return new BadRequestError(status, error, message, headers);
244
+ if (401 === status || (null == error ? void 0 : error.code) === 4100) return new AuthenticationError(status, error, message, headers);
245
+ if (403 === status || (null == error ? void 0 : error.code) === 4101) return new PermissionDeniedError(status, error, message, headers);
246
+ if (404 === status || (null == error ? void 0 : error.code) === 4200) return new NotFoundError(status, error, message, headers);
247
+ if (429 === status || (null == error ? void 0 : error.code) === 4013) return new RateLimitError(status, error, message, headers);
248
+ if (408 === status) return new TimeoutError(status, error, message, headers);
249
+ if (502 === status) return new GatewayError(status, error, message, headers);
250
+ if (status >= 500) return new InternalServerError(status, error, message, headers);
251
+ return new error_APIError(status, error, message, headers);
252
+ }
253
+ constructor(status, error, message, headers){
254
+ var _error_error, _error_error1;
255
+ super(`${error_APIError.makeMessage(status, error, message, headers)}`);
256
+ this.status = status;
257
+ this.headers = headers;
258
+ this.logid = null == headers ? void 0 : headers['x-tt-logid'];
259
+ // this.error = error;
260
+ this.code = null == error ? void 0 : error.code;
261
+ this.msg = null == error ? void 0 : error.msg;
262
+ this.detail = null == error ? void 0 : null === (_error_error = error.error) || void 0 === _error_error ? void 0 : _error_error.detail;
263
+ this.help_doc = null == error ? void 0 : null === (_error_error1 = error.error) || void 0 === _error_error1 ? void 0 : _error_error1.help_doc;
264
+ this.rawError = error;
285
265
  }
286
266
  }
287
- function findKey(obj, key) {
288
- key = key.toLowerCase();
289
- const keys = Object.keys(obj);
290
- let i = keys.length;
291
- let _key;
292
- while(i-- > 0){
293
- _key = keys[i];
294
- if (key === _key.toLowerCase()) return _key;
267
+ class APIConnectionError extends error_APIError {
268
+ constructor({ message, cause }){
269
+ super(void 0, void 0, message || 'Connection error.', void 0), this.status = void 0;
270
+ // if (cause) {
271
+ // this.cause = cause;
272
+ // }
295
273
  }
296
- return null;
297
274
  }
298
- const _global = (()=>{
299
- /*eslint no-undef:0*/ if ("undefined" != typeof globalThis) return globalThis;
300
- return "undefined" != typeof self ? self : 'undefined' != typeof window ? window : global;
301
- })();
302
- const isContextDefined = (context)=>!isUndefined(context) && context !== _global;
303
- /**
304
- * Accepts varargs expecting each argument to be an object, then
305
- * immutably merges the properties of each object and returns result.
306
- *
307
- * When multiple objects contain the same key the later object in
308
- * the arguments list will take precedence.
309
- *
310
- * Example:
311
- *
312
- * ```js
313
- * var result = merge({foo: 123}, {foo: 456});
314
- * console.log(result.foo); // outputs 456
315
- * ```
316
- *
317
- * @param {Object} obj1 Object to merge
318
- *
319
- * @returns {Object} Result of all merge properties
320
- */ function utils_merge() {
321
- const { caseless } = isContextDefined(this) && this || {};
322
- const result = {};
323
- const assignValue = (val, key)=>{
324
- const targetKey = caseless && findKey(result, key) || key;
325
- if (isPlainObject(result[targetKey]) && isPlainObject(val)) result[targetKey] = utils_merge(result[targetKey], val);
326
- else if (isPlainObject(val)) result[targetKey] = utils_merge({}, val);
327
- else if (isArray(val)) result[targetKey] = val.slice();
328
- else result[targetKey] = val;
329
- };
330
- for(let i = 0, l = arguments.length; i < l; i++)arguments[i] && forEach(arguments[i], assignValue);
331
- return result;
275
+ class APIUserAbortError extends error_APIError {
276
+ constructor(message){
277
+ super(void 0, void 0, message || 'Request was aborted.', void 0), this.name = 'UserAbortError', this.status = void 0;
278
+ }
332
279
  }
333
- /**
334
- * Extends object a by mutably adding to it the properties of object b.
335
- *
336
- * @param {Object} a The object to be extended
337
- * @param {Object} b The object to copy properties from
338
- * @param {Object} thisArg The object to bind function to
339
- *
340
- * @param {Boolean} [allOwnKeys]
341
- * @returns {Object} The resulting value of object a
342
- */ const extend = (a, b, thisArg, { allOwnKeys } = {})=>{
343
- forEach(b, (val, key)=>{
344
- if (thisArg && isFunction(val)) a[key] = bind(val, thisArg);
345
- else a[key] = val;
346
- }, {
347
- allOwnKeys
348
- });
349
- return a;
350
- };
351
- /**
352
- * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
353
- *
354
- * @param {string} content with BOM
355
- *
356
- * @returns {string} content value without BOM
357
- */ const stripBOM = (content)=>{
358
- if (0xFEFF === content.charCodeAt(0)) content = content.slice(1);
359
- return content;
360
- };
361
- /**
362
- * Inherit the prototype methods from one constructor into another
363
- * @param {function} constructor
364
- * @param {function} superConstructor
365
- * @param {object} [props]
366
- * @param {object} [descriptors]
367
- *
368
- * @returns {void}
369
- */ const inherits = (constructor, superConstructor, props, descriptors)=>{
370
- constructor.prototype = Object.create(superConstructor.prototype, descriptors);
371
- constructor.prototype.constructor = constructor;
372
- Object.defineProperty(constructor, 'super', {
373
- value: superConstructor.prototype
374
- });
375
- props && Object.assign(constructor.prototype, props);
280
+ class BadRequestError extends error_APIError {
281
+ constructor(...args){
282
+ super(...args), this.name = 'BadRequestError', this.status = 400;
283
+ }
284
+ }
285
+ class AuthenticationError extends error_APIError {
286
+ constructor(...args){
287
+ super(...args), this.name = 'AuthenticationError', this.status = 401;
288
+ }
289
+ }
290
+ class PermissionDeniedError extends error_APIError {
291
+ constructor(...args){
292
+ super(...args), this.name = 'PermissionDeniedError', this.status = 403;
293
+ }
294
+ }
295
+ class NotFoundError extends error_APIError {
296
+ constructor(...args){
297
+ super(...args), this.name = 'NotFoundError', this.status = 404;
298
+ }
299
+ }
300
+ class TimeoutError extends error_APIError {
301
+ constructor(...args){
302
+ super(...args), this.name = 'TimeoutError', this.status = 408;
303
+ }
304
+ }
305
+ class RateLimitError extends error_APIError {
306
+ constructor(...args){
307
+ super(...args), this.name = 'RateLimitError', this.status = 429;
308
+ }
309
+ }
310
+ class InternalServerError extends error_APIError {
311
+ constructor(...args){
312
+ super(...args), this.name = 'InternalServerError', this.status = 500;
313
+ }
314
+ }
315
+ class GatewayError extends error_APIError {
316
+ constructor(...args){
317
+ super(...args), this.name = 'GatewayError', this.status = 502;
318
+ }
319
+ }
320
+ const castToError = (err)=>{
321
+ if (err instanceof Error) return err;
322
+ return new Error(err);
376
323
  };
377
- /**
378
- * Resolve object with deep prototype chain to a flat object
379
- * @param {Object} sourceObj source object
380
- * @param {Object} [destObj]
381
- * @param {Function|Boolean} [filter]
382
- * @param {Function} [propFilter]
383
- *
384
- * @returns {Object}
385
- */ const toFlatObject = (sourceObj, destObj, filter, propFilter)=>{
386
- let props;
387
- let i;
388
- let prop;
389
- const merged = {};
390
- destObj = destObj || {};
391
- // eslint-disable-next-line no-eq-null,eqeqeq
392
- if (null == sourceObj) return destObj;
393
- do {
394
- props = Object.getOwnPropertyNames(sourceObj);
395
- i = props.length;
396
- while(i-- > 0){
397
- prop = props[i];
398
- if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
399
- destObj[prop] = sourceObj[prop];
400
- merged[prop] = true;
401
- }
402
- }
403
- sourceObj = false !== filter && getPrototypeOf(sourceObj);
404
- }while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
405
- return destObj;
324
+ class Messages extends APIResource {
325
+ /**
326
+ * Get the list of messages in a chat. | 获取对话中的消息列表。
327
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_message_list?_lang=en
328
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_message_list?_lang=zh
329
+ * @param conversation_id - Required The ID of the conversation. | 会话 ID。
330
+ * @param chat_id - Required The ID of the chat. | 对话 ID。
331
+ * @returns An array of chat messages. | 对话消息数组。
332
+ */ async list(conversation_id, chat_id, options) {
333
+ const apiUrl = `/v3/chat/message/list?conversation_id=${conversation_id}&chat_id=${chat_id}`;
334
+ const result = await this._client.get(apiUrl, void 0, false, options);
335
+ return result.data;
336
+ }
337
+ }
338
+ const uuid = ()=>(Math.random() * new Date().getTime()).toString();
339
+ const handleAdditionalMessages = (additional_messages)=>null == additional_messages ? void 0 : additional_messages.map((i)=>({
340
+ ...i,
341
+ content: 'object' == typeof i.content ? JSON.stringify(i.content) : i.content
342
+ }));
343
+ class Chat extends APIResource {
344
+ /**
345
+ * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
346
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
347
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
348
+ * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
349
+ * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
350
+ * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
351
+ * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
352
+ * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义变量。
353
+ * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
354
+ * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
355
+ * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
356
+ * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
357
+ * @returns The data of the created chat. | 创建的对话数据。
358
+ */ async create(params, options) {
359
+ if (!params.user_id) params.user_id = uuid();
360
+ const { conversation_id, ...rest } = params;
361
+ const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
362
+ const payload = {
363
+ ...rest,
364
+ additional_messages: handleAdditionalMessages(params.additional_messages),
365
+ stream: false
366
+ };
367
+ const result = await this._client.post(apiUrl, payload, false, options);
368
+ return result.data;
369
+ }
370
+ /**
371
+ * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
372
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
373
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
374
+ * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
375
+ * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
376
+ * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
377
+ * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
378
+ * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
379
+ * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
380
+ * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
381
+ * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
382
+ * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
383
+ * @returns
384
+ */ async createAndPoll(params, options) {
385
+ if (!params.user_id) params.user_id = uuid();
386
+ const { conversation_id, ...rest } = params;
387
+ const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
388
+ const payload = {
389
+ ...rest,
390
+ additional_messages: handleAdditionalMessages(params.additional_messages),
391
+ stream: false
392
+ };
393
+ const result = await this._client.post(apiUrl, payload, false, options);
394
+ const chatId = result.data.id;
395
+ const conversationId = result.data.conversation_id;
396
+ let chat;
397
+ while(true){
398
+ await utils_sleep(100);
399
+ chat = await this.retrieve(conversationId, chatId);
400
+ if ('completed' === chat.status || 'failed' === chat.status || 'requires_action' === chat.status) break;
401
+ }
402
+ const messageList = await this.messages.list(conversationId, chatId);
403
+ return {
404
+ chat,
405
+ messages: messageList
406
+ };
407
+ }
408
+ /**
409
+ * Call the Chat API to send messages to a published Coze agent with streaming response. | 调用此接口发起一次对话,支持流式响应。
410
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
411
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
412
+ * @param params - Required The parameters for streaming a chat session. | 流式会话的参数。
413
+ * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
414
+ * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
415
+ * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
416
+ * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
417
+ * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
418
+ * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
419
+ * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
420
+ * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
421
+ * @returns A stream of chat data. | 对话数据流。
422
+ */ async *stream(params, options) {
423
+ if (!params.user_id) params.user_id = uuid();
424
+ const { conversation_id, ...rest } = params;
425
+ const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
426
+ const payload = {
427
+ ...rest,
428
+ additional_messages: handleAdditionalMessages(params.additional_messages),
429
+ stream: true
430
+ };
431
+ const result = await this._client.post(apiUrl, payload, true, options);
432
+ for await (const message of result)if ("done" === message.event) {
433
+ const ret = {
434
+ event: message.event,
435
+ data: '[DONE]'
436
+ };
437
+ yield ret;
438
+ } else try {
439
+ const ret = {
440
+ event: message.event,
441
+ data: JSON.parse(message.data)
442
+ };
443
+ yield ret;
444
+ } catch (error) {
445
+ throw new CozeError(`Could not parse message into JSON:${message.data}`);
446
+ }
447
+ }
448
+ /**
449
+ * Get the detailed information of the chat. | 查看对话的详细信息。
450
+ * @docs en:https://www.coze.com/docs/developer_guides/retrieve_chat?_lang=en
451
+ * @docs zh:https://www.coze.cn/docs/developer_guides/retrieve_chat?_lang=zh
452
+ * @param conversation_id - Required The ID of the conversation. | 会话 ID。
453
+ * @param chat_id - Required The ID of the chat. | 对话 ID。
454
+ * @returns The data of the retrieved chat. | 检索到的对话数据。
455
+ */ async retrieve(conversation_id, chat_id, options) {
456
+ const apiUrl = `/v3/chat/retrieve?conversation_id=${conversation_id}&chat_id=${chat_id}`;
457
+ const result = await this._client.post(apiUrl, void 0, false, options);
458
+ return result.data;
459
+ }
460
+ /**
461
+ * Cancel a chat session. | 取消对话会话。
462
+ * @docs en:https://www.coze.com/docs/developer_guides/cancel_chat?_lang=en
463
+ * @docs zh:https://www.coze.cn/docs/developer_guides/cancel_chat?_lang=zh
464
+ * @param conversation_id - Required The ID of the conversation. | 会话 ID。
465
+ * @param chat_id - Required The ID of the chat. | 对话 ID。
466
+ * @returns The data of the canceled chat. | 取消的对话数据。
467
+ */ async cancel(conversation_id, chat_id, options) {
468
+ const apiUrl = '/v3/chat/cancel';
469
+ const payload = {
470
+ conversation_id,
471
+ chat_id
472
+ };
473
+ const result = await this._client.post(apiUrl, payload, false, options);
474
+ return result.data;
475
+ }
476
+ /**
477
+ * Submit tool outputs for a chat session. | 提交对话会话的工具输出。
478
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_submit_tool_outputs?_lang=en
479
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_submit_tool_outputs?_lang=zh
480
+ * @param params - Required Parameters for submitting tool outputs. | 提交工具输出的参数。
481
+ * @param params.conversation_id - Required The ID of the conversation. | 会话 ID。
482
+ * @param params.chat_id - Required The ID of the chat. | 对话 ID。
483
+ * @param params.tool_outputs - Required The outputs of the tool. | 工具的输出。
484
+ * @param params.stream - Optional Whether to use streaming response. | 是否使用流式响应。
485
+ * @returns The data of the submitted tool outputs or a stream of chat data. | 提交的工具输出数据或对话数据流。
486
+ */ async *submitToolOutputs(params, options) {
487
+ const { conversation_id, chat_id, ...rest } = params;
488
+ const apiUrl = `/v3/chat/submit_tool_outputs?conversation_id=${params.conversation_id}&chat_id=${params.chat_id}`;
489
+ const payload = {
490
+ ...rest
491
+ };
492
+ if (false === params.stream) {
493
+ const response = await this._client.post(apiUrl, payload, false, options);
494
+ return response.data;
495
+ }
496
+ {
497
+ const result = await this._client.post(apiUrl, payload, true, options);
498
+ for await (const message of result)if ("done" === message.event) {
499
+ const ret = {
500
+ event: message.event,
501
+ data: '[DONE]'
502
+ };
503
+ yield ret;
504
+ } else try {
505
+ const ret = {
506
+ event: message.event,
507
+ data: JSON.parse(message.data)
508
+ };
509
+ yield ret;
510
+ } catch (error) {
511
+ throw new CozeError(`Could not parse message into JSON:${message.data}`);
512
+ }
513
+ }
514
+ }
515
+ constructor(...args){
516
+ super(...args), this.messages = new Messages(this._client);
517
+ }
518
+ }
519
+ var chat_ChatEventType = /*#__PURE__*/ function(ChatEventType) {
520
+ ChatEventType["CONVERSATION_CHAT_CREATED"] = "conversation.chat.created";
521
+ ChatEventType["CONVERSATION_CHAT_IN_PROGRESS"] = "conversation.chat.in_progress";
522
+ ChatEventType["CONVERSATION_CHAT_COMPLETED"] = "conversation.chat.completed";
523
+ ChatEventType["CONVERSATION_CHAT_FAILED"] = "conversation.chat.failed";
524
+ ChatEventType["CONVERSATION_CHAT_REQUIRES_ACTION"] = "conversation.chat.requires_action";
525
+ ChatEventType["CONVERSATION_MESSAGE_DELTA"] = "conversation.message.delta";
526
+ ChatEventType["CONVERSATION_MESSAGE_COMPLETED"] = "conversation.message.completed";
527
+ ChatEventType["CONVERSATION_AUDIO_DELTA"] = "conversation.audio.delta";
528
+ ChatEventType["DONE"] = "done";
529
+ ChatEventType["ERROR"] = "error";
530
+ return ChatEventType;
531
+ }({});
532
+ class messages_Messages extends APIResource {
533
+ /**
534
+ * Create a message and add it to the specified conversation. | 创建一条消息,并将其添加到指定的会话中。
535
+ * @docs en: https://www.coze.com/docs/developer_guides/create_message?_lang=en
536
+ * @docs zh: https://www.coze.cn/docs/developer_guides/create_message?_lang=zh
537
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
538
+ * @param params - Required The parameters for creating a message | 创建消息所需的参数
539
+ * @param params.role - Required The entity that sent this message. Possible values: user, assistant. | 发送这条消息的实体。取值:user, assistant。
540
+ * @param params.content - Required The content of the message. | 消息的内容。
541
+ * @param params.content_type - Required The type of the message content. | 消息内容的类型。
542
+ * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
543
+ * @returns Information about the new message. | 消息详情。
544
+ */ async create(conversation_id, params, options) {
545
+ const apiUrl = `/v1/conversation/message/create?conversation_id=${conversation_id}`;
546
+ const response = await this._client.post(apiUrl, params, false, options);
547
+ return response.data;
548
+ }
549
+ /**
550
+ * Modify a message, supporting the modification of message content, additional content, and message type. | 修改一条消息,支持修改消息内容、附加内容和消息类型。
551
+ * @docs en: https://www.coze.com/docs/developer_guides/modify_message?_lang=en
552
+ * @docs zh: https://www.coze.cn/docs/developer_guides/modify_message?_lang=zh
553
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
554
+ * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
555
+ * @param params - Required The parameters for modifying a message | 修改消息所需的参数
556
+ * @param params.meta_data - Optional Additional information when modifying a message. | 修改消息时的附加消息。
557
+ * @param params.content - Optional The content of the message. | 消息的内容。
558
+ * @param params.content_type - Optional The type of the message content. | 消息内容的类型。
559
+ * @returns Information about the modified message. | 消息详情。
560
+ */ // eslint-disable-next-line max-params
561
+ async update(conversation_id, message_id, params, options) {
562
+ const apiUrl = `/v1/conversation/message/modify?conversation_id=${conversation_id}&message_id=${message_id}`;
563
+ const response = await this._client.post(apiUrl, params, false, options);
564
+ return response.message;
565
+ }
566
+ /**
567
+ * Get the detailed information of specified message. | 查看指定消息的详细信息。
568
+ * @docs en: https://www.coze.com/docs/developer_guides/retrieve_message?_lang=en
569
+ * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_message?_lang=zh
570
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
571
+ * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
572
+ * @returns Information about the message. | 消息详情。
573
+ */ async retrieve(conversation_id, message_id, options) {
574
+ const apiUrl = `/v1/conversation/message/retrieve?conversation_id=${conversation_id}&message_id=${message_id}`;
575
+ const response = await this._client.get(apiUrl, null, false, options);
576
+ return response.data;
577
+ }
578
+ /**
579
+ * List messages in a conversation. | 列出会话中的消息。
580
+ * @docs en: https://www.coze.com/docs/developer_guides/message_list?_lang=en
581
+ * @docs zh: https://www.coze.cn/docs/developer_guides/message_list?_lang=zh
582
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
583
+ * @param params - Optional The parameters for listing messages | 列出消息所需的参数
584
+ * @param params.order - Optional The order of the messages. | 消息的顺序。
585
+ * @param params.chat_id - Optional The ID of the chat. | 聊天 ID。
586
+ * @param params.before_id - Optional The ID of the message before which to list. | 列出此消息之前的消息 ID。
587
+ * @param params.after_id - Optional The ID of the message after which to list. | 列出此消息之后的消息 ID。
588
+ * @param params.limit - Optional The maximum number of messages to return. | 返回的最大消息数。
589
+ * @returns A list of messages. | 消息列表。
590
+ */ async list(conversation_id, params, options) {
591
+ const apiUrl = `/v1/conversation/message/list?conversation_id=${conversation_id}`;
592
+ const response = await this._client.post(apiUrl, params, false, options);
593
+ return response;
594
+ }
595
+ /**
596
+ * Call the API to delete a message within a specified conversation. | 调用接口在指定会话中删除消息。
597
+ * @docs en: https://www.coze.com/docs/developer_guides/delete_message?_lang=en
598
+ * @docs zh: https://www.coze.cn/docs/developer_guides/delete_message?_lang=zh
599
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
600
+ * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
601
+ * @returns Details of the deleted message. | 已删除的消息详情。
602
+ */ async delete(conversation_id, message_id, options) {
603
+ const apiUrl = `/v1/conversation/message/delete?conversation_id=${conversation_id}&message_id=${message_id}`;
604
+ const response = await this._client.post(apiUrl, void 0, false, options);
605
+ return response.data;
606
+ }
607
+ }
608
+ class Conversations extends APIResource {
609
+ /**
610
+ * Create a conversation. Conversation is an interaction between an agent and a user, including one or more messages. | 调用接口创建一个会话。
611
+ * @docs en: https://www.coze.com/docs/developer_guides/create_conversation?_lang=en
612
+ * @docs zh: https://www.coze.cn/docs/developer_guides/create_conversation?_lang=zh
613
+ * @param params - Required The parameters for creating a conversation | 创建会话所需的参数
614
+ * @param params.messages - Optional Messages in the conversation. | 会话中的消息内容。
615
+ * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
616
+ * @param params.bot_id - Optional Bind and isolate conversation on different bots. | 绑定和隔离不同Bot的会话。
617
+ * @returns Information about the created conversation. | 会话的基础信息。
618
+ */ async create(params, options) {
619
+ const apiUrl = '/v1/conversation/create';
620
+ const response = await this._client.post(apiUrl, params, false, options);
621
+ return response.data;
622
+ }
623
+ /**
624
+ * Get the information of specific conversation. | 通过会话 ID 查看会话信息。
625
+ * @docs en: https://www.coze.com/docs/developer_guides/retrieve_conversation?_lang=en
626
+ * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_conversation?_lang=zh
627
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
628
+ * @returns Information about the conversation. | 会话的基础信息。
629
+ */ async retrieve(conversation_id, options) {
630
+ const apiUrl = `/v1/conversation/retrieve?conversation_id=${conversation_id}`;
631
+ const response = await this._client.get(apiUrl, null, false, options);
632
+ return response.data;
633
+ }
634
+ /**
635
+ * List all conversations. | 列出 Bot 下所有会话。
636
+ * @param params
637
+ * @param params.bot_id - Required Bot ID. | Bot ID。
638
+ * @param params.page_num - Optional The page number. | 页码,默认值为 1。
639
+ * @param params.page_size - Optional The number of conversations per page. | 每页的会话数量,默认值为 50。
640
+ * @returns Information about the conversations. | 会话的信息。
641
+ */ async list(params, options) {
642
+ const apiUrl = '/v1/conversations';
643
+ const response = await this._client.get(apiUrl, params, false, options);
644
+ return response.data;
645
+ }
646
+ /**
647
+ * Clear a conversation. | 清空会话。
648
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
649
+ * @returns Information about the conversation session. | 会话的会话 ID。
650
+ */ async clear(conversation_id, options) {
651
+ const apiUrl = `/v1/conversations/${conversation_id}/clear`;
652
+ const response = await this._client.post(apiUrl, null, false, options);
653
+ return response.data;
654
+ }
655
+ constructor(...args){
656
+ super(...args), this.messages = new messages_Messages(this._client);
657
+ }
658
+ }
659
+ function bind(fn, thisArg) {
660
+ return function() {
661
+ return fn.apply(thisArg, arguments);
662
+ };
663
+ }
664
+ // utils is a library of generic helper functions non-specific to axios
665
+ const { toString: utils_toString } = Object.prototype;
666
+ const { getPrototypeOf } = Object;
667
+ const kindOf = ((cache)=>(thing)=>{
668
+ const str = utils_toString.call(thing);
669
+ return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
670
+ })(Object.create(null));
671
+ const kindOfTest = (type)=>{
672
+ type = type.toLowerCase();
673
+ return (thing)=>kindOf(thing) === type;
406
674
  };
675
+ const typeOfTest = (type)=>(thing)=>typeof thing === type;
407
676
  /**
408
- * Determines whether a string ends with the characters of a specified string
677
+ * Determine if a value is an Array
409
678
  *
410
- * @param {String} str
411
- * @param {String} searchString
412
- * @param {Number} [position= 0]
679
+ * @param {Object} val The value to test
413
680
  *
414
- * @returns {boolean}
415
- */ const endsWith = (str, searchString, position)=>{
416
- str = String(str);
417
- if (void 0 === position || position > str.length) position = str.length;
418
- position -= searchString.length;
419
- const lastIndex = str.indexOf(searchString, position);
420
- return -1 !== lastIndex && lastIndex === position;
421
- };
681
+ * @returns {boolean} True if value is an Array, otherwise false
682
+ */ const { isArray } = Array;
422
683
  /**
423
- * Returns new array from array like object or null if failed
684
+ * Determine if a value is undefined
424
685
  *
425
- * @param {*} [thing]
686
+ * @param {*} val The value to test
426
687
  *
427
- * @returns {?Array}
428
- */ const toArray = (thing)=>{
429
- if (!thing) return null;
430
- if (isArray(thing)) return thing;
431
- let i = thing.length;
432
- if (!isNumber(i)) return null;
433
- const arr = new Array(i);
434
- while(i-- > 0)arr[i] = thing[i];
435
- return arr;
436
- };
688
+ * @returns {boolean} True if the value is undefined, otherwise false
689
+ */ const isUndefined = typeOfTest('undefined');
437
690
  /**
438
- * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
439
- * thing passed in is an instance of Uint8Array
691
+ * Determine if a value is a Buffer
440
692
  *
441
- * @param {TypedArray}
693
+ * @param {*} val The value to test
442
694
  *
443
- * @returns {Array}
444
- */ // eslint-disable-next-line func-names
445
- const isTypedArray = ((TypedArray)=>(thing)=>TypedArray && thing instanceof TypedArray)('undefined' != typeof Uint8Array && getPrototypeOf(Uint8Array));
695
+ * @returns {boolean} True if value is a Buffer, otherwise false
696
+ */ function isBuffer(val) {
697
+ return null !== val && !isUndefined(val) && null !== val.constructor && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
698
+ }
446
699
  /**
447
- * For each entry in the object, call the function with the key and value.
700
+ * Determine if a value is an ArrayBuffer
448
701
  *
449
- * @param {Object<any, any>} obj - The object to iterate over.
450
- * @param {Function} fn - The function to call for each entry.
702
+ * @param {*} val The value to test
451
703
  *
452
- * @returns {void}
453
- */ const forEachEntry = (obj, fn)=>{
454
- const generator = obj && obj[Symbol.iterator];
455
- const iterator = generator.call(obj);
456
- let result;
457
- while((result = iterator.next()) && !result.done){
458
- const pair = result.value;
459
- fn.call(obj, pair[0], pair[1]);
460
- }
461
- };
704
+ * @returns {boolean} True if value is an ArrayBuffer, otherwise false
705
+ */ const isArrayBuffer = kindOfTest('ArrayBuffer');
462
706
  /**
463
- * It takes a regular expression and a string, and returns an array of all the matches
707
+ * Determine if a value is a view on an ArrayBuffer
464
708
  *
465
- * @param {string} regExp - The regular expression to match against.
466
- * @param {string} str - The string to search.
709
+ * @param {*} val The value to test
467
710
  *
468
- * @returns {Array<boolean>}
469
- */ const matchAll = (regExp, str)=>{
470
- let matches;
471
- const arr = [];
472
- while(null !== (matches = regExp.exec(str)))arr.push(matches);
473
- return arr;
474
- };
475
- /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ const isHTMLForm = kindOfTest('HTMLFormElement');
476
- const toCamelCase = (str)=>str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function(m, p1, p2) {
477
- return p1.toUpperCase() + p2;
478
- });
479
- /* Creating a function that will check if an object has a property. */ const utils_hasOwnProperty = (({ hasOwnProperty })=>(obj, prop)=>hasOwnProperty.call(obj, prop))(Object.prototype);
711
+ * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
712
+ */ function isArrayBufferView(val) {
713
+ let result;
714
+ result = 'undefined' != typeof ArrayBuffer && ArrayBuffer.isView ? ArrayBuffer.isView(val) : val && val.buffer && isArrayBuffer(val.buffer);
715
+ return result;
716
+ }
480
717
  /**
481
- * Determine if a value is a RegExp object
718
+ * Determine if a value is a String
482
719
  *
483
720
  * @param {*} val The value to test
484
721
  *
485
- * @returns {boolean} True if value is a RegExp object, otherwise false
486
- */ const isRegExp = kindOfTest('RegExp');
487
- const reduceDescriptors = (obj, reducer)=>{
488
- const descriptors = Object.getOwnPropertyDescriptors(obj);
489
- const reducedDescriptors = {};
490
- forEach(descriptors, (descriptor, name)=>{
491
- let ret;
492
- if (false !== (ret = reducer(descriptor, name, obj))) reducedDescriptors[name] = ret || descriptor;
493
- });
494
- Object.defineProperties(obj, reducedDescriptors);
495
- };
722
+ * @returns {boolean} True if value is a String, otherwise false
723
+ */ const isString = typeOfTest('string');
496
724
  /**
497
- * Makes all methods read-only
498
- * @param {Object} obj
499
- */ const freezeMethods = (obj)=>{
500
- reduceDescriptors(obj, (descriptor, name)=>{
501
- // skip restricted props in strict mode
502
- if (isFunction(obj) && -1 !== [
503
- 'arguments',
504
- 'caller',
505
- 'callee'
506
- ].indexOf(name)) return false;
507
- const value = obj[name];
508
- if (!isFunction(value)) return;
509
- descriptor.enumerable = false;
510
- if ('writable' in descriptor) {
511
- descriptor.writable = false;
512
- return;
513
- }
514
- if (!descriptor.set) descriptor.set = ()=>{
515
- throw Error('Can not rewrite read-only method \'' + name + '\'');
516
- };
517
- });
518
- };
519
- const toObjectSet = (arrayOrString, delimiter)=>{
520
- const obj = {};
521
- const define = (arr)=>{
522
- arr.forEach((value)=>{
523
- obj[value] = true;
524
- });
525
- };
526
- isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
527
- return obj;
528
- };
529
- const noop = ()=>{};
530
- const toFiniteNumber = (value, defaultValue)=>null != value && Number.isFinite(value = +value) ? value : defaultValue;
531
- const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
532
- const DIGIT = '0123456789';
533
- const ALPHABET = {
534
- DIGIT,
535
- ALPHA,
536
- ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
537
- };
538
- const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT)=>{
539
- let str = '';
540
- const { length } = alphabet;
541
- while(size--)str += alphabet[Math.random() * length | 0];
542
- return str;
543
- };
725
+ * Determine if a value is a Function
726
+ *
727
+ * @param {*} val The value to test
728
+ * @returns {boolean} True if value is a Function, otherwise false
729
+ */ const isFunction = typeOfTest('function');
544
730
  /**
545
- * If the thing is a FormData object, return true, otherwise return false.
731
+ * Determine if a value is a Number
546
732
  *
547
- * @param {unknown} thing - The thing to check.
733
+ * @param {*} val The value to test
548
734
  *
549
- * @returns {boolean}
550
- */ function isSpecCompliantForm(thing) {
551
- return !!(thing && isFunction(thing.append) && 'FormData' === thing[Symbol.toStringTag] && thing[Symbol.iterator]);
552
- }
553
- const toJSONObject = (obj)=>{
554
- const stack = new Array(10);
735
+ * @returns {boolean} True if value is a Number, otherwise false
736
+ */ const isNumber = typeOfTest('number');
737
+ /**
738
+ * Determine if a value is an Object
739
+ *
740
+ * @param {*} thing The value to test
741
+ *
742
+ * @returns {boolean} True if value is an Object, otherwise false
743
+ */ const isObject = (thing)=>null !== thing && 'object' == typeof thing;
744
+ /**
745
+ * Determine if a value is a Boolean
746
+ *
747
+ * @param {*} thing The value to test
748
+ * @returns {boolean} True if value is a Boolean, otherwise false
749
+ */ const isBoolean = (thing)=>true === thing || false === thing;
750
+ /**
751
+ * Determine if a value is a plain Object
752
+ *
753
+ * @param {*} val The value to test
754
+ *
755
+ * @returns {boolean} True if value is a plain Object, otherwise false
756
+ */ const utils_isPlainObject = (val)=>{
757
+ if ('object' !== kindOf(val)) return false;
758
+ const prototype = getPrototypeOf(val);
759
+ return (null === prototype || prototype === Object.prototype || null === Object.getPrototypeOf(prototype)) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
760
+ };
761
+ /**
762
+ * Determine if a value is a Date
763
+ *
764
+ * @param {*} val The value to test
765
+ *
766
+ * @returns {boolean} True if value is a Date, otherwise false
767
+ */ const isDate = kindOfTest('Date');
768
+ /**
769
+ * Determine if a value is a File
770
+ *
771
+ * @param {*} val The value to test
772
+ *
773
+ * @returns {boolean} True if value is a File, otherwise false
774
+ */ const isFile = kindOfTest('File');
775
+ /**
776
+ * Determine if a value is a Blob
777
+ *
778
+ * @param {*} val The value to test
779
+ *
780
+ * @returns {boolean} True if value is a Blob, otherwise false
781
+ */ const isBlob = kindOfTest('Blob');
782
+ /**
783
+ * Determine if a value is a FileList
784
+ *
785
+ * @param {*} val The value to test
786
+ *
787
+ * @returns {boolean} True if value is a File, otherwise false
788
+ */ const utils_isFileList = kindOfTest('FileList');
789
+ /**
790
+ * Determine if a value is a Stream
791
+ *
792
+ * @param {*} val The value to test
793
+ *
794
+ * @returns {boolean} True if value is a Stream, otherwise false
795
+ */ const utils_isStream = (val)=>isObject(val) && isFunction(val.pipe);
796
+ /**
797
+ * Determine if a value is a FormData
798
+ *
799
+ * @param {*} thing The value to test
800
+ *
801
+ * @returns {boolean} True if value is an FormData, otherwise false
802
+ */ const utils_isFormData = (thing)=>{
803
+ let kind;
804
+ return thing && ('function' == typeof FormData && thing instanceof FormData || isFunction(thing.append) && ('formdata' === (kind = kindOf(thing)) || // detect form-data instance
805
+ 'object' === kind && isFunction(thing.toString) && '[object FormData]' === thing.toString()));
806
+ };
807
+ /**
808
+ * Determine if a value is a URLSearchParams object
809
+ *
810
+ * @param {*} val The value to test
811
+ *
812
+ * @returns {boolean} True if value is a URLSearchParams object, otherwise false
813
+ */ const isURLSearchParams = kindOfTest('URLSearchParams');
814
+ const [isReadableStream, isRequest, isResponse, isHeaders] = [
815
+ 'ReadableStream',
816
+ 'Request',
817
+ 'Response',
818
+ 'Headers'
819
+ ].map(kindOfTest);
820
+ /**
821
+ * Trim excess whitespace off the beginning and end of a string
822
+ *
823
+ * @param {String} str The String to trim
824
+ *
825
+ * @returns {String} The String freed of excess whitespace
826
+ */ const trim = (str)=>str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
827
+ /**
828
+ * Iterate over an Array or an Object invoking a function for each item.
829
+ *
830
+ * If `obj` is an Array callback will be called passing
831
+ * the value, index, and complete array for each item.
832
+ *
833
+ * If 'obj' is an Object callback will be called passing
834
+ * the value, key, and complete object for each property.
835
+ *
836
+ * @param {Object|Array} obj The object to iterate
837
+ * @param {Function} fn The callback to invoke for each item
838
+ *
839
+ * @param {Boolean} [allOwnKeys = false]
840
+ * @returns {any}
841
+ */ function forEach(obj, fn, { allOwnKeys = false } = {}) {
842
+ // Don't bother if no value provided
843
+ if (null == obj) return;
844
+ let i;
845
+ let l;
846
+ // Force an array if not already something iterable
847
+ if ('object' != typeof obj) /*eslint no-param-reassign:0*/ obj = [
848
+ obj
849
+ ];
850
+ if (isArray(obj)) // Iterate over array values
851
+ for(i = 0, l = obj.length; i < l; i++)fn.call(null, obj[i], i, obj);
852
+ else {
853
+ // Iterate over object keys
854
+ const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
855
+ const len = keys.length;
856
+ let key;
857
+ for(i = 0; i < len; i++){
858
+ key = keys[i];
859
+ fn.call(null, obj[key], key, obj);
860
+ }
861
+ }
862
+ }
863
+ function findKey(obj, key) {
864
+ key = key.toLowerCase();
865
+ const keys = Object.keys(obj);
866
+ let i = keys.length;
867
+ let _key;
868
+ while(i-- > 0){
869
+ _key = keys[i];
870
+ if (key === _key.toLowerCase()) return _key;
871
+ }
872
+ return null;
873
+ }
874
+ const _global = (()=>{
875
+ /*eslint no-undef:0*/ if ("undefined" != typeof globalThis) return globalThis;
876
+ return "undefined" != typeof self ? self : 'undefined' != typeof window ? window : global;
877
+ })();
878
+ const isContextDefined = (context)=>!isUndefined(context) && context !== _global;
879
+ /**
880
+ * Accepts varargs expecting each argument to be an object, then
881
+ * immutably merges the properties of each object and returns result.
882
+ *
883
+ * When multiple objects contain the same key the later object in
884
+ * the arguments list will take precedence.
885
+ *
886
+ * Example:
887
+ *
888
+ * ```js
889
+ * var result = merge({foo: 123}, {foo: 456});
890
+ * console.log(result.foo); // outputs 456
891
+ * ```
892
+ *
893
+ * @param {Object} obj1 Object to merge
894
+ *
895
+ * @returns {Object} Result of all merge properties
896
+ */ function utils_merge() {
897
+ const { caseless } = isContextDefined(this) && this || {};
898
+ const result = {};
899
+ const assignValue = (val, key)=>{
900
+ const targetKey = caseless && findKey(result, key) || key;
901
+ if (utils_isPlainObject(result[targetKey]) && utils_isPlainObject(val)) result[targetKey] = utils_merge(result[targetKey], val);
902
+ else if (utils_isPlainObject(val)) result[targetKey] = utils_merge({}, val);
903
+ else if (isArray(val)) result[targetKey] = val.slice();
904
+ else result[targetKey] = val;
905
+ };
906
+ for(let i = 0, l = arguments.length; i < l; i++)arguments[i] && forEach(arguments[i], assignValue);
907
+ return result;
908
+ }
909
+ /**
910
+ * Extends object a by mutably adding to it the properties of object b.
911
+ *
912
+ * @param {Object} a The object to be extended
913
+ * @param {Object} b The object to copy properties from
914
+ * @param {Object} thisArg The object to bind function to
915
+ *
916
+ * @param {Boolean} [allOwnKeys]
917
+ * @returns {Object} The resulting value of object a
918
+ */ const extend = (a, b, thisArg, { allOwnKeys } = {})=>{
919
+ forEach(b, (val, key)=>{
920
+ if (thisArg && isFunction(val)) a[key] = bind(val, thisArg);
921
+ else a[key] = val;
922
+ }, {
923
+ allOwnKeys
924
+ });
925
+ return a;
926
+ };
927
+ /**
928
+ * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
929
+ *
930
+ * @param {string} content with BOM
931
+ *
932
+ * @returns {string} content value without BOM
933
+ */ const stripBOM = (content)=>{
934
+ if (0xFEFF === content.charCodeAt(0)) content = content.slice(1);
935
+ return content;
936
+ };
937
+ /**
938
+ * Inherit the prototype methods from one constructor into another
939
+ * @param {function} constructor
940
+ * @param {function} superConstructor
941
+ * @param {object} [props]
942
+ * @param {object} [descriptors]
943
+ *
944
+ * @returns {void}
945
+ */ const inherits = (constructor, superConstructor, props, descriptors)=>{
946
+ constructor.prototype = Object.create(superConstructor.prototype, descriptors);
947
+ constructor.prototype.constructor = constructor;
948
+ Object.defineProperty(constructor, 'super', {
949
+ value: superConstructor.prototype
950
+ });
951
+ props && Object.assign(constructor.prototype, props);
952
+ };
953
+ /**
954
+ * Resolve object with deep prototype chain to a flat object
955
+ * @param {Object} sourceObj source object
956
+ * @param {Object} [destObj]
957
+ * @param {Function|Boolean} [filter]
958
+ * @param {Function} [propFilter]
959
+ *
960
+ * @returns {Object}
961
+ */ const toFlatObject = (sourceObj, destObj, filter, propFilter)=>{
962
+ let props;
963
+ let i;
964
+ let prop;
965
+ const merged = {};
966
+ destObj = destObj || {};
967
+ // eslint-disable-next-line no-eq-null,eqeqeq
968
+ if (null == sourceObj) return destObj;
969
+ do {
970
+ props = Object.getOwnPropertyNames(sourceObj);
971
+ i = props.length;
972
+ while(i-- > 0){
973
+ prop = props[i];
974
+ if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
975
+ destObj[prop] = sourceObj[prop];
976
+ merged[prop] = true;
977
+ }
978
+ }
979
+ sourceObj = false !== filter && getPrototypeOf(sourceObj);
980
+ }while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
981
+ return destObj;
982
+ };
983
+ /**
984
+ * Determines whether a string ends with the characters of a specified string
985
+ *
986
+ * @param {String} str
987
+ * @param {String} searchString
988
+ * @param {Number} [position= 0]
989
+ *
990
+ * @returns {boolean}
991
+ */ const endsWith = (str, searchString, position)=>{
992
+ str = String(str);
993
+ if (void 0 === position || position > str.length) position = str.length;
994
+ position -= searchString.length;
995
+ const lastIndex = str.indexOf(searchString, position);
996
+ return -1 !== lastIndex && lastIndex === position;
997
+ };
998
+ /**
999
+ * Returns new array from array like object or null if failed
1000
+ *
1001
+ * @param {*} [thing]
1002
+ *
1003
+ * @returns {?Array}
1004
+ */ const toArray = (thing)=>{
1005
+ if (!thing) return null;
1006
+ if (isArray(thing)) return thing;
1007
+ let i = thing.length;
1008
+ if (!isNumber(i)) return null;
1009
+ const arr = new Array(i);
1010
+ while(i-- > 0)arr[i] = thing[i];
1011
+ return arr;
1012
+ };
1013
+ /**
1014
+ * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
1015
+ * thing passed in is an instance of Uint8Array
1016
+ *
1017
+ * @param {TypedArray}
1018
+ *
1019
+ * @returns {Array}
1020
+ */ // eslint-disable-next-line func-names
1021
+ const isTypedArray = ((TypedArray)=>(thing)=>TypedArray && thing instanceof TypedArray)('undefined' != typeof Uint8Array && getPrototypeOf(Uint8Array));
1022
+ /**
1023
+ * For each entry in the object, call the function with the key and value.
1024
+ *
1025
+ * @param {Object<any, any>} obj - The object to iterate over.
1026
+ * @param {Function} fn - The function to call for each entry.
1027
+ *
1028
+ * @returns {void}
1029
+ */ const forEachEntry = (obj, fn)=>{
1030
+ const generator = obj && obj[Symbol.iterator];
1031
+ const iterator = generator.call(obj);
1032
+ let result;
1033
+ while((result = iterator.next()) && !result.done){
1034
+ const pair = result.value;
1035
+ fn.call(obj, pair[0], pair[1]);
1036
+ }
1037
+ };
1038
+ /**
1039
+ * It takes a regular expression and a string, and returns an array of all the matches
1040
+ *
1041
+ * @param {string} regExp - The regular expression to match against.
1042
+ * @param {string} str - The string to search.
1043
+ *
1044
+ * @returns {Array<boolean>}
1045
+ */ const matchAll = (regExp, str)=>{
1046
+ let matches;
1047
+ const arr = [];
1048
+ while(null !== (matches = regExp.exec(str)))arr.push(matches);
1049
+ return arr;
1050
+ };
1051
+ /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ const isHTMLForm = kindOfTest('HTMLFormElement');
1052
+ const toCamelCase = (str)=>str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function(m, p1, p2) {
1053
+ return p1.toUpperCase() + p2;
1054
+ });
1055
+ /* Creating a function that will check if an object has a property. */ const utils_hasOwnProperty = (({ hasOwnProperty })=>(obj, prop)=>hasOwnProperty.call(obj, prop))(Object.prototype);
1056
+ /**
1057
+ * Determine if a value is a RegExp object
1058
+ *
1059
+ * @param {*} val The value to test
1060
+ *
1061
+ * @returns {boolean} True if value is a RegExp object, otherwise false
1062
+ */ const isRegExp = kindOfTest('RegExp');
1063
+ const reduceDescriptors = (obj, reducer)=>{
1064
+ const descriptors = Object.getOwnPropertyDescriptors(obj);
1065
+ const reducedDescriptors = {};
1066
+ forEach(descriptors, (descriptor, name)=>{
1067
+ let ret;
1068
+ if (false !== (ret = reducer(descriptor, name, obj))) reducedDescriptors[name] = ret || descriptor;
1069
+ });
1070
+ Object.defineProperties(obj, reducedDescriptors);
1071
+ };
1072
+ /**
1073
+ * Makes all methods read-only
1074
+ * @param {Object} obj
1075
+ */ const freezeMethods = (obj)=>{
1076
+ reduceDescriptors(obj, (descriptor, name)=>{
1077
+ // skip restricted props in strict mode
1078
+ if (isFunction(obj) && -1 !== [
1079
+ 'arguments',
1080
+ 'caller',
1081
+ 'callee'
1082
+ ].indexOf(name)) return false;
1083
+ const value = obj[name];
1084
+ if (!isFunction(value)) return;
1085
+ descriptor.enumerable = false;
1086
+ if ('writable' in descriptor) {
1087
+ descriptor.writable = false;
1088
+ return;
1089
+ }
1090
+ if (!descriptor.set) descriptor.set = ()=>{
1091
+ throw Error('Can not rewrite read-only method \'' + name + '\'');
1092
+ };
1093
+ });
1094
+ };
1095
+ const toObjectSet = (arrayOrString, delimiter)=>{
1096
+ const obj = {};
1097
+ const define = (arr)=>{
1098
+ arr.forEach((value)=>{
1099
+ obj[value] = true;
1100
+ });
1101
+ };
1102
+ isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
1103
+ return obj;
1104
+ };
1105
+ const noop = ()=>{};
1106
+ const toFiniteNumber = (value, defaultValue)=>null != value && Number.isFinite(value = +value) ? value : defaultValue;
1107
+ const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
1108
+ const DIGIT = '0123456789';
1109
+ const ALPHABET = {
1110
+ DIGIT,
1111
+ ALPHA,
1112
+ ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
1113
+ };
1114
+ const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT)=>{
1115
+ let str = '';
1116
+ const { length } = alphabet;
1117
+ while(size--)str += alphabet[Math.random() * length | 0];
1118
+ return str;
1119
+ };
1120
+ /**
1121
+ * If the thing is a FormData object, return true, otherwise return false.
1122
+ *
1123
+ * @param {unknown} thing - The thing to check.
1124
+ *
1125
+ * @returns {boolean}
1126
+ */ function isSpecCompliantForm(thing) {
1127
+ return !!(thing && isFunction(thing.append) && 'FormData' === thing[Symbol.toStringTag] && thing[Symbol.iterator]);
1128
+ }
1129
+ const toJSONObject = (obj)=>{
1130
+ const stack = new Array(10);
555
1131
  const visit = (source, i)=>{
556
1132
  if (isObject(source)) {
557
1133
  if (stack.indexOf(source) >= 0) return;
@@ -598,7 +1174,7 @@ const asap = 'undefined' != typeof queueMicrotask ? queueMicrotask.bind(_global)
598
1174
  isNumber,
599
1175
  isBoolean,
600
1176
  isObject,
601
- isPlainObject,
1177
+ isPlainObject: utils_isPlainObject,
602
1178
  isReadableStream,
603
1179
  isRequest,
604
1180
  isResponse,
@@ -1796,7 +2372,7 @@ const headersToObject = (thing)=>thing instanceof AxiosHeaders ? {
1796
2372
  * @param {Object} config2
1797
2373
  *
1798
2374
  * @returns {Object} New object resulting from merging config2 to config1
1799
- */ function mergeConfig(config1, config2) {
2375
+ */ function mergeConfig_mergeConfig(config1, config2) {
1800
2376
  // eslint-disable-next-line no-param-reassign
1801
2377
  config2 = config2 || {};
1802
2378
  const config = {};
@@ -1866,7 +2442,7 @@ const headersToObject = (thing)=>thing instanceof AxiosHeaders ? {
1866
2442
  return config;
1867
2443
  }
1868
2444
  /* ESM default export */ const resolveConfig = (config)=>{
1869
- const newConfig = mergeConfig({}, config);
2445
+ const newConfig = mergeConfig_mergeConfig({}, config);
1870
2446
  let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig;
1871
2447
  newConfig.headers = headers = AxiosHeaders.from(headers);
1872
2448
  newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer);
@@ -2458,960 +3034,393 @@ const Axios_validators = helpers_validator.validators;
2458
3034
  try {
2459
3035
  if (err.stack) {
2460
3036
  if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) err.stack += '\n' + stack;
2461
- } else err.stack = stack;
2462
- } catch (e) {
2463
- // ignore the case where "stack" is an un-writable property
2464
- }
2465
- }
2466
- throw err;
2467
- }
2468
- }
2469
- _request(configOrUrl, config) {
2470
- /*eslint no-param-reassign:0*/ // Allow for axios('example/url'[, config]) a la fetch API
2471
- if ('string' == typeof configOrUrl) {
2472
- config = config || {};
2473
- config.url = configOrUrl;
2474
- } else config = configOrUrl || {};
2475
- config = mergeConfig(this.defaults, config);
2476
- const { transitional, paramsSerializer, headers } = config;
2477
- if (void 0 !== transitional) helpers_validator.assertOptions(transitional, {
2478
- silentJSONParsing: Axios_validators.transitional(Axios_validators.boolean),
2479
- forcedJSONParsing: Axios_validators.transitional(Axios_validators.boolean),
2480
- clarifyTimeoutError: Axios_validators.transitional(Axios_validators.boolean)
2481
- }, false);
2482
- if (null != paramsSerializer) {
2483
- if (utils.isFunction(paramsSerializer)) config.paramsSerializer = {
2484
- serialize: paramsSerializer
2485
- };
2486
- else helpers_validator.assertOptions(paramsSerializer, {
2487
- encode: Axios_validators.function,
2488
- serialize: Axios_validators.function
2489
- }, true);
2490
- }
2491
- // Set config.method
2492
- config.method = (config.method || this.defaults.method || 'get').toLowerCase();
2493
- // Flatten headers
2494
- let contextHeaders = headers && utils.merge(headers.common, headers[config.method]);
2495
- headers && utils.forEach([
2496
- 'delete',
2497
- 'get',
2498
- 'head',
2499
- 'post',
2500
- 'put',
2501
- 'patch',
2502
- 'common'
2503
- ], (method)=>{
2504
- delete headers[method];
2505
- });
2506
- config.headers = AxiosHeaders.concat(contextHeaders, headers);
2507
- // filter out skipped interceptors
2508
- const requestInterceptorChain = [];
2509
- let synchronousRequestInterceptors = true;
2510
- this.interceptors.request.forEach(function(interceptor) {
2511
- if ('function' == typeof interceptor.runWhen && false === interceptor.runWhen(config)) return;
2512
- synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
2513
- requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
2514
- });
2515
- const responseInterceptorChain = [];
2516
- this.interceptors.response.forEach(function(interceptor) {
2517
- responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
2518
- });
2519
- let promise;
2520
- let i = 0;
2521
- let len;
2522
- if (!synchronousRequestInterceptors) {
2523
- const chain = [
2524
- dispatchRequest.bind(this),
2525
- void 0
2526
- ];
2527
- chain.unshift.apply(chain, requestInterceptorChain);
2528
- chain.push.apply(chain, responseInterceptorChain);
2529
- len = chain.length;
2530
- promise = Promise.resolve(config);
2531
- while(i < len)promise = promise.then(chain[i++], chain[i++]);
2532
- return promise;
2533
- }
2534
- len = requestInterceptorChain.length;
2535
- let newConfig = config;
2536
- i = 0;
2537
- while(i < len){
2538
- const onFulfilled = requestInterceptorChain[i++];
2539
- const onRejected = requestInterceptorChain[i++];
2540
- try {
2541
- newConfig = onFulfilled(newConfig);
2542
- } catch (error) {
2543
- onRejected.call(this, error);
2544
- break;
2545
- }
2546
- }
2547
- try {
2548
- promise = dispatchRequest.call(this, newConfig);
2549
- } catch (error) {
2550
- return Promise.reject(error);
2551
- }
2552
- i = 0;
2553
- len = responseInterceptorChain.length;
2554
- while(i < len)promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
2555
- return promise;
2556
- }
2557
- getUri(config) {
2558
- config = mergeConfig(this.defaults, config);
2559
- const fullPath = buildFullPath(config.baseURL, config.url);
2560
- return buildURL(fullPath, config.params, config.paramsSerializer);
2561
- }
2562
- }
2563
- // Provide aliases for supported request methods
2564
- utils.forEach([
2565
- 'delete',
2566
- 'get',
2567
- 'head',
2568
- 'options'
2569
- ], function(method) {
2570
- /*eslint func-names:0*/ Axios_Axios.prototype[method] = function(url, config) {
2571
- return this.request(mergeConfig(config || {}, {
2572
- method,
2573
- url,
2574
- data: (config || {}).data
2575
- }));
2576
- };
2577
- });
2578
- utils.forEach([
2579
- 'post',
2580
- 'put',
2581
- 'patch'
2582
- ], function(method) {
2583
- /*eslint func-names:0*/ function generateHTTPMethod(isForm) {
2584
- return function(url, data, config) {
2585
- return this.request(mergeConfig(config || {}, {
2586
- method,
2587
- headers: isForm ? {
2588
- 'Content-Type': 'multipart/form-data'
2589
- } : {},
2590
- url,
2591
- data
2592
- }));
2593
- };
2594
- }
2595
- Axios_Axios.prototype[method] = generateHTTPMethod();
2596
- Axios_Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
2597
- });
2598
- /* ESM default export */ const Axios = Axios_Axios;
2599
- /**
2600
- * A `CancelToken` is an object that can be used to request cancellation of an operation.
2601
- *
2602
- * @param {Function} executor The executor function.
2603
- *
2604
- * @returns {CancelToken}
2605
- */ class CancelToken_CancelToken {
2606
- constructor(executor){
2607
- if ('function' != typeof executor) throw new TypeError('executor must be a function.');
2608
- let resolvePromise;
2609
- this.promise = new Promise(function(resolve) {
2610
- resolvePromise = resolve;
2611
- });
2612
- const token = this;
2613
- // eslint-disable-next-line func-names
2614
- this.promise.then((cancel)=>{
2615
- if (!token._listeners) return;
2616
- let i = token._listeners.length;
2617
- while(i-- > 0)token._listeners[i](cancel);
2618
- token._listeners = null;
2619
- });
2620
- // eslint-disable-next-line func-names
2621
- this.promise.then = (onfulfilled)=>{
2622
- let _resolve;
2623
- // eslint-disable-next-line func-names
2624
- const promise = new Promise((resolve)=>{
2625
- token.subscribe(resolve);
2626
- _resolve = resolve;
2627
- }).then(onfulfilled);
2628
- promise.cancel = function() {
2629
- token.unsubscribe(_resolve);
2630
- };
2631
- return promise;
2632
- };
2633
- executor(function(message, config, request) {
2634
- if (token.reason) // Cancellation has already been requested
2635
- return;
2636
- token.reason = new CanceledError(message, config, request);
2637
- resolvePromise(token.reason);
2638
- });
2639
- }
2640
- /**
2641
- * Throws a `CanceledError` if cancellation has been requested.
2642
- */ throwIfRequested() {
2643
- if (this.reason) throw this.reason;
2644
- }
2645
- /**
2646
- * Subscribe to the cancel signal
2647
- */ subscribe(listener) {
2648
- if (this.reason) {
2649
- listener(this.reason);
2650
- return;
2651
- }
2652
- if (this._listeners) this._listeners.push(listener);
2653
- else this._listeners = [
2654
- listener
2655
- ];
2656
- }
2657
- /**
2658
- * Unsubscribe from the cancel signal
2659
- */ unsubscribe(listener) {
2660
- if (!this._listeners) return;
2661
- const index = this._listeners.indexOf(listener);
2662
- if (-1 !== index) this._listeners.splice(index, 1);
2663
- }
2664
- toAbortSignal() {
2665
- const controller = new AbortController();
2666
- const abort = (err)=>{
2667
- controller.abort(err);
2668
- };
2669
- this.subscribe(abort);
2670
- controller.signal.unsubscribe = ()=>this.unsubscribe(abort);
2671
- return controller.signal;
2672
- }
2673
- /**
2674
- * Returns an object that contains a new `CancelToken` and a function that, when called,
2675
- * cancels the `CancelToken`.
2676
- */ static source() {
2677
- let cancel;
2678
- const token = new CancelToken_CancelToken(function(c) {
2679
- cancel = c;
2680
- });
2681
- return {
2682
- token,
2683
- cancel
2684
- };
2685
- }
2686
- }
2687
- /* ESM default export */ const CancelToken = CancelToken_CancelToken;
2688
- /**
2689
- * Syntactic sugar for invoking a function and expanding an array for arguments.
2690
- *
2691
- * Common use case would be to use `Function.prototype.apply`.
2692
- *
2693
- * ```js
2694
- * function f(x, y, z) {}
2695
- * var args = [1, 2, 3];
2696
- * f.apply(null, args);
2697
- * ```
2698
- *
2699
- * With `spread` this example can be re-written.
2700
- *
2701
- * ```js
2702
- * spread(function(x, y, z) {})([1, 2, 3]);
2703
- * ```
2704
- *
2705
- * @param {Function} callback
2706
- *
2707
- * @returns {Function}
2708
- */ function spread(callback) {
2709
- return function(arr) {
2710
- return callback.apply(null, arr);
2711
- };
2712
- }
2713
- /**
2714
- * Determines whether the payload is an error thrown by Axios
2715
- *
2716
- * @param {*} payload The value to test
2717
- *
2718
- * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
2719
- */ function isAxiosError(payload) {
2720
- return utils.isObject(payload) && true === payload.isAxiosError;
2721
- }
2722
- const HttpStatusCode = {
2723
- Continue: 100,
2724
- SwitchingProtocols: 101,
2725
- Processing: 102,
2726
- EarlyHints: 103,
2727
- Ok: 200,
2728
- Created: 201,
2729
- Accepted: 202,
2730
- NonAuthoritativeInformation: 203,
2731
- NoContent: 204,
2732
- ResetContent: 205,
2733
- PartialContent: 206,
2734
- MultiStatus: 207,
2735
- AlreadyReported: 208,
2736
- ImUsed: 226,
2737
- MultipleChoices: 300,
2738
- MovedPermanently: 301,
2739
- Found: 302,
2740
- SeeOther: 303,
2741
- NotModified: 304,
2742
- UseProxy: 305,
2743
- Unused: 306,
2744
- TemporaryRedirect: 307,
2745
- PermanentRedirect: 308,
2746
- BadRequest: 400,
2747
- Unauthorized: 401,
2748
- PaymentRequired: 402,
2749
- Forbidden: 403,
2750
- NotFound: 404,
2751
- MethodNotAllowed: 405,
2752
- NotAcceptable: 406,
2753
- ProxyAuthenticationRequired: 407,
2754
- RequestTimeout: 408,
2755
- Conflict: 409,
2756
- Gone: 410,
2757
- LengthRequired: 411,
2758
- PreconditionFailed: 412,
2759
- PayloadTooLarge: 413,
2760
- UriTooLong: 414,
2761
- UnsupportedMediaType: 415,
2762
- RangeNotSatisfiable: 416,
2763
- ExpectationFailed: 417,
2764
- ImATeapot: 418,
2765
- MisdirectedRequest: 421,
2766
- UnprocessableEntity: 422,
2767
- Locked: 423,
2768
- FailedDependency: 424,
2769
- TooEarly: 425,
2770
- UpgradeRequired: 426,
2771
- PreconditionRequired: 428,
2772
- TooManyRequests: 429,
2773
- RequestHeaderFieldsTooLarge: 431,
2774
- UnavailableForLegalReasons: 451,
2775
- InternalServerError: 500,
2776
- NotImplemented: 501,
2777
- BadGateway: 502,
2778
- ServiceUnavailable: 503,
2779
- GatewayTimeout: 504,
2780
- HttpVersionNotSupported: 505,
2781
- VariantAlsoNegotiates: 506,
2782
- InsufficientStorage: 507,
2783
- LoopDetected: 508,
2784
- NotExtended: 510,
2785
- NetworkAuthenticationRequired: 511
2786
- };
2787
- Object.entries(HttpStatusCode).forEach(([key, value])=>{
2788
- HttpStatusCode[value] = key;
2789
- });
2790
- /* ESM default export */ const helpers_HttpStatusCode = HttpStatusCode;
2791
- /**
2792
- * Create an instance of Axios
2793
- *
2794
- * @param {Object} defaultConfig The default config for the instance
2795
- *
2796
- * @returns {Axios} A new instance of Axios
2797
- */ function createInstance(defaultConfig) {
2798
- const context = new Axios(defaultConfig);
2799
- const instance = bind(Axios.prototype.request, context);
2800
- // Copy axios.prototype to instance
2801
- utils.extend(instance, Axios.prototype, context, {
2802
- allOwnKeys: true
2803
- });
2804
- // Copy context to instance
2805
- utils.extend(instance, context, null, {
2806
- allOwnKeys: true
2807
- });
2808
- // Factory for creating new instances
2809
- instance.create = function(instanceConfig) {
2810
- return createInstance(mergeConfig(defaultConfig, instanceConfig));
2811
- };
2812
- return instance;
2813
- }
2814
- // Create the default instance to be exported
2815
- const axios = createInstance(defaults);
2816
- // Expose Axios class to allow class inheritance
2817
- axios.Axios = Axios;
2818
- // Expose Cancel & CancelToken
2819
- axios.CanceledError = CanceledError;
2820
- axios.CancelToken = CancelToken;
2821
- axios.isCancel = isCancel;
2822
- axios.VERSION = VERSION;
2823
- axios.toFormData = toFormData;
2824
- // Expose AxiosError class
2825
- axios.AxiosError = core_AxiosError;
2826
- // alias for CanceledError for backward compatibility
2827
- axios.Cancel = axios.CanceledError;
2828
- // Expose all/spread
2829
- axios.all = function(promises) {
2830
- return Promise.all(promises);
2831
- };
2832
- axios.spread = spread;
2833
- // Expose isAxiosError
2834
- axios.isAxiosError = isAxiosError;
2835
- // Expose mergeConfig
2836
- axios.mergeConfig = mergeConfig;
2837
- axios.AxiosHeaders = AxiosHeaders;
2838
- axios.formToJSON = (thing)=>formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
2839
- axios.getAdapter = adapters_adapters.getAdapter;
2840
- axios.HttpStatusCode = helpers_HttpStatusCode;
2841
- axios.default = axios;
2842
- // this module should only have a default export
2843
- /* ESM default export */ const lib_axios = axios;
2844
- // This module is intended to unwrap Axios default export as named.
2845
- // Keep top-level export same with static properties
2846
- // so that it can keep same with es module or cjs
2847
- const { Axios: axios_Axios, AxiosError: axios_AxiosError, CanceledError: axios_CanceledError, isCancel: axios_isCancel, CancelToken: axios_CancelToken, VERSION: axios_VERSION, all: axios_all, Cancel, isAxiosError: axios_isAxiosError, spread: axios_spread, toFormData: axios_toFormData, AxiosHeaders: axios_AxiosHeaders, HttpStatusCode: axios_HttpStatusCode, formToJSON, getAdapter, mergeConfig: axios_mergeConfig } = lib_axios;
2848
- // EXTERNAL MODULE: os (ignored)
2849
- var os_ignored_ = __webpack_require__("?e2b1");
2850
- // EXTERNAL MODULE: crypto (ignored)
2851
- __webpack_require__("?c628");
2852
- // EXTERNAL MODULE: jsonwebtoken (ignored)
2853
- __webpack_require__("?9452");
2854
- class APIResource {
2855
- constructor(client){
2856
- this._client = client;
2857
- }
2858
- }
2859
- /* eslint-disable @typescript-eslint/no-namespace */ class Bots extends APIResource {
2860
- /**
2861
- * Create a new agent. | 调用接口创建一个新的智能体。
2862
- * @docs en:https://www.coze.com/docs/developer_guides/create_bot?_lang=en
2863
- * @docs zh:https://www.coze.cn/docs/developer_guides/create_bot?_lang=zh
2864
- * @param params - Required The parameters for creating a bot. | 创建 Bot 的参数。
2865
- * @param params.space_id - Required The Space ID of the space where the agent is located. | Bot 所在的空间的 Space ID。
2866
- * @param params.name - Required The name of the agent. It should be 1 to 20 characters long. | Bot 的名称。
2867
- * @param params.description - Optional The description of the agent. It can be 0 to 500 characters long. | Bot 的描述信息。
2868
- * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
2869
- * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
2870
- * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
2871
- * @returns Information about the created bot. | 创建的 Bot 信息。
2872
- */ async create(params, options) {
2873
- const apiUrl = '/v1/bot/create';
2874
- const result = await this._client.post(apiUrl, params, false, options);
2875
- return result.data;
2876
- }
2877
- /**
2878
- * Update the configuration of an agent. | 调用接口修改智能体的配置。
2879
- * @docs en:https://www.coze.com/docs/developer_guides/update_bot?_lang=en
2880
- * @docs zh:https://www.coze.cn/docs/developer_guides/update_bot?_lang=zh
2881
- * @param params - Required The parameters for updating a bot. | 修改 Bot 的参数。
2882
- * @param params.bot_id - Required The ID of the agent that the API interacts with. | 待修改配置的智能体ID。
2883
- * @param params.name - Optional The name of the agent. | Bot 的名称。
2884
- * @param params.description - Optional The description of the agent. | Bot 的描述信息。
2885
- * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
2886
- * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
2887
- * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
2888
- * @param params.knowledge - Optional Knowledge configurations of the agent. | Bot 的知识库配置。
2889
- * @returns Undefined | 无返回值
2890
- */ async update(params, options) {
2891
- const apiUrl = '/v1/bot/update';
2892
- const result = await this._client.post(apiUrl, params, false, options);
2893
- return result.data;
2894
- }
2895
- /**
2896
- * Get the agents published as API service. | 调用接口查看指定空间发布到 Agent as API 渠道的智能体列表。
2897
- * @docs en:https://www.coze.com/docs/developer_guides/published_bots_list?_lang=en
2898
- * @docs zh:https://www.coze.cn/docs/developer_guides/published_bots_list?_lang=zh
2899
- * @param params - Required The parameters for listing bots. | 列出 Bot 的参数。
2900
- * @param params.space_id - Required The ID of the space. | Bot 所在的空间的 Space ID。
2901
- * @param params.page_size - Optional Pagination size. | 分页大小。
2902
- * @param params.page_index - Optional Page number for paginated queries. | 分页查询时的页码。
2903
- * @returns List of published bots. | 已发布的 Bot 列表。
2904
- */ async list(params, options) {
2905
- const apiUrl = '/v1/space/published_bots_list';
2906
- const result = await this._client.get(apiUrl, params, false, options);
2907
- return result.data;
2908
- }
2909
- /**
2910
- * Publish the specified agent as an API service. | 调用接口创建一个新的智能体。
2911
- * @docs en:https://www.coze.com/docs/developer_guides/publish_bot?_lang=en
2912
- * @docs zh:https://www.coze.cn/docs/developer_guides/publish_bot?_lang=zh
2913
- * @param params - Required The parameters for publishing a bot. | 发布 Bot 的参数。
2914
- * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要发布的智能体ID。
2915
- * @param params.connector_ids - Required The list of publishing channel IDs for the agent. | 智能体的发布渠道 ID 列表。
2916
- * @returns Undefined | 无返回值
2917
- */ async publish(params, options) {
2918
- const apiUrl = '/v1/bot/publish';
2919
- const result = await this._client.post(apiUrl, params, false, options);
2920
- return result.data;
2921
- }
2922
- /**
2923
- * Get the configuration information of the agent. | 获取指定智能体的配置信息。
2924
- * @docs en:https://www.coze.com/docs/developer_guides/get_metadata?_lang=en
2925
- * @docs zh:https://www.coze.cn/docs/developer_guides/get_metadata?_lang=zh
2926
- * @param params - Required The parameters for retrieving a bot. | 获取 Bot 的参数。
2927
- * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要查看的智能体ID。
2928
- * @returns Information about the bot. | Bot 的配置信息。
2929
- */ async retrieve(params, options) {
2930
- const apiUrl = '/v1/bot/get_online_info';
2931
- const result = await this._client.get(apiUrl, params, false, options);
2932
- return result.data;
2933
- }
2934
- }
2935
- /* eslint-disable security/detect-object-injection */ /* eslint-disable @typescript-eslint/no-explicit-any */ function safeJsonParse(jsonString) {
2936
- let defaultValue = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : '';
2937
- try {
2938
- return JSON.parse(jsonString);
2939
- } catch (error) {
2940
- return defaultValue;
2941
- }
2942
- }
2943
- function sleep(ms) {
2944
- return new Promise((resolve)=>{
2945
- setTimeout(resolve, ms);
2946
- });
2947
- }
2948
- function isBrowser() {
2949
- return 'undefined' != typeof window;
2950
- }
2951
- function esm_isPlainObject(obj) {
2952
- if ('object' != typeof obj || null === obj) return false;
2953
- const proto = Object.getPrototypeOf(obj);
2954
- if (null === proto) return true;
2955
- let baseProto = proto;
2956
- while(null !== Object.getPrototypeOf(baseProto))baseProto = Object.getPrototypeOf(baseProto);
2957
- return proto === baseProto;
2958
- }
2959
- function esm_mergeConfig() {
2960
- for(var _len = arguments.length, objects = new Array(_len), _key = 0; _key < _len; _key++)objects[_key] = arguments[_key];
2961
- return objects.reduce((result, obj)=>{
2962
- if (void 0 === obj) return result || {};
2963
- for(const key in obj)if (Object.prototype.hasOwnProperty.call(obj, key)) {
2964
- if (esm_isPlainObject(obj[key]) && !Array.isArray(obj[key])) result[key] = esm_mergeConfig(result[key] || {}, obj[key]);
2965
- else result[key] = obj[key];
2966
- }
2967
- return result;
2968
- }, {});
2969
- }
2970
- function isPersonalAccessToken(token) {
2971
- return null == token ? void 0 : token.startsWith('pat_');
2972
- }
2973
- /* eslint-disable max-params */ class CozeError extends Error {
2974
- }
2975
- class APIError extends CozeError {
2976
- static makeMessage(status, errorBody, message, headers) {
2977
- if (!errorBody && message) return message;
2978
- if (errorBody) {
2979
- const list = [];
2980
- const { code, msg, error } = errorBody;
2981
- if (code) list.push(`code: ${code}`);
2982
- if (msg) list.push(`msg: ${msg}`);
2983
- if ((null == error ? void 0 : error.detail) && msg !== error.detail) list.push(`detail: ${error.detail}`);
2984
- const logId = (null == error ? void 0 : error.logid) || (null == headers ? void 0 : headers['x-tt-logid']);
2985
- if (logId) list.push(`logid: ${logId}`);
2986
- const help_doc = null == error ? void 0 : error.help_doc;
2987
- if (help_doc) list.push(`help doc: ${help_doc}`);
2988
- return list.join(', ');
2989
- }
2990
- if (status) return `http status code: ${status} (no body)`;
2991
- return '(no status code or body)';
2992
- }
2993
- static generate(status, errorResponse, message, headers) {
2994
- if (!status) return new APIConnectionError({
2995
- cause: castToError(errorResponse)
2996
- });
2997
- const error = errorResponse;
2998
- // https://www.coze.cn/docs/developer_guides/coze_error_codes
2999
- if (400 === status || (null == error ? void 0 : error.code) === 4000) return new BadRequestError(status, error, message, headers);
3000
- if (401 === status || (null == error ? void 0 : error.code) === 4100) return new AuthenticationError(status, error, message, headers);
3001
- if (403 === status || (null == error ? void 0 : error.code) === 4101) return new PermissionDeniedError(status, error, message, headers);
3002
- if (404 === status || (null == error ? void 0 : error.code) === 4200) return new NotFoundError(status, error, message, headers);
3003
- if (429 === status || (null == error ? void 0 : error.code) === 4013) return new RateLimitError(status, error, message, headers);
3004
- if (408 === status) return new TimeoutError(status, error, message, headers);
3005
- if (502 === status) return new GatewayError(status, error, message, headers);
3006
- if (status >= 500) return new InternalServerError(status, error, message, headers);
3007
- return new APIError(status, error, message, headers);
3008
- }
3009
- constructor(status, error, message, headers){
3010
- var _error_error, _error_error1;
3011
- super(`${APIError.makeMessage(status, error, message, headers)}`);
3012
- this.status = status;
3013
- this.headers = headers;
3014
- this.logid = null == headers ? void 0 : headers['x-tt-logid'];
3015
- // this.error = error;
3016
- this.code = null == error ? void 0 : error.code;
3017
- this.msg = null == error ? void 0 : error.msg;
3018
- this.detail = null == error ? void 0 : null === (_error_error = error.error) || void 0 === _error_error ? void 0 : _error_error.detail;
3019
- this.help_doc = null == error ? void 0 : null === (_error_error1 = error.error) || void 0 === _error_error1 ? void 0 : _error_error1.help_doc;
3020
- this.rawError = error;
3021
- }
3022
- }
3023
- class APIConnectionError extends APIError {
3024
- constructor({ message, cause }){
3025
- super(void 0, void 0, message || 'Connection error.', void 0), this.status = void 0;
3026
- // if (cause) {
3027
- // this.cause = cause;
3028
- // }
3029
- }
3030
- }
3031
- class APIUserAbortError extends APIError {
3032
- constructor(message){
3033
- super(void 0, void 0, message || 'Request was aborted.', void 0), this.name = 'UserAbortError', this.status = void 0;
3034
- }
3035
- }
3036
- class BadRequestError extends APIError {
3037
- constructor(...args){
3038
- super(...args), this.name = 'BadRequestError', this.status = 400;
3039
- }
3040
- }
3041
- class AuthenticationError extends APIError {
3042
- constructor(...args){
3043
- super(...args), this.name = 'AuthenticationError', this.status = 401;
3044
- }
3045
- }
3046
- class PermissionDeniedError extends APIError {
3047
- constructor(...args){
3048
- super(...args), this.name = 'PermissionDeniedError', this.status = 403;
3049
- }
3050
- }
3051
- class NotFoundError extends APIError {
3052
- constructor(...args){
3053
- super(...args), this.name = 'NotFoundError', this.status = 404;
3054
- }
3055
- }
3056
- class TimeoutError extends APIError {
3057
- constructor(...args){
3058
- super(...args), this.name = 'TimeoutError', this.status = 408;
3059
- }
3060
- }
3061
- class RateLimitError extends APIError {
3062
- constructor(...args){
3063
- super(...args), this.name = 'RateLimitError', this.status = 429;
3064
- }
3065
- }
3066
- class InternalServerError extends APIError {
3067
- constructor(...args){
3068
- super(...args), this.name = 'InternalServerError', this.status = 500;
3069
- }
3070
- }
3071
- class GatewayError extends APIError {
3072
- constructor(...args){
3073
- super(...args), this.name = 'GatewayError', this.status = 502;
3074
- }
3075
- }
3076
- const castToError = (err)=>{
3077
- if (err instanceof Error) return err;
3078
- return new Error(err);
3079
- };
3080
- class Messages extends APIResource {
3081
- /**
3082
- * Get the list of messages in a chat. | 获取对话中的消息列表。
3083
- * @docs en:https://www.coze.com/docs/developer_guides/chat_message_list?_lang=en
3084
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_message_list?_lang=zh
3085
- * @param conversation_id - Required The ID of the conversation. | 会话 ID。
3086
- * @param chat_id - Required The ID of the chat. | 对话 ID。
3087
- * @returns An array of chat messages. | 对话消息数组。
3088
- */ async list(conversation_id, chat_id, options) {
3089
- const apiUrl = `/v3/chat/message/list?conversation_id=${conversation_id}&chat_id=${chat_id}`;
3090
- const result = await this._client.get(apiUrl, void 0, false, options);
3091
- return result.data;
3092
- }
3093
- }
3094
- const uuid = ()=>(Math.random() * new Date().getTime()).toString();
3095
- const handleAdditionalMessages = (additional_messages)=>null == additional_messages ? void 0 : additional_messages.map((i)=>({
3096
- ...i,
3097
- content: 'object' == typeof i.content ? JSON.stringify(i.content) : i.content
3098
- }));
3099
- class Chat extends APIResource {
3100
- /**
3101
- * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
3102
- * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
3103
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
3104
- * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
3105
- * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
3106
- * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
3107
- * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
3108
- * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义变量。
3109
- * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
3110
- * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
3111
- * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
3112
- * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
3113
- * @returns The data of the created chat. | 创建的对话数据。
3114
- */ async create(params, options) {
3115
- if (!params.user_id) params.user_id = uuid();
3116
- const { conversation_id, ...rest } = params;
3117
- const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
3118
- const payload = {
3119
- ...rest,
3120
- additional_messages: handleAdditionalMessages(params.additional_messages),
3121
- stream: false
3122
- };
3123
- const result = await this._client.post(apiUrl, payload, false, options);
3124
- return result.data;
3125
- }
3126
- /**
3127
- * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
3128
- * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
3129
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
3130
- * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
3131
- * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
3132
- * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
3133
- * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
3134
- * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
3135
- * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
3136
- * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
3137
- * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
3138
- * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
3139
- * @returns
3140
- */ async createAndPoll(params, options) {
3141
- if (!params.user_id) params.user_id = uuid();
3142
- const { conversation_id, ...rest } = params;
3143
- const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
3144
- const payload = {
3145
- ...rest,
3146
- additional_messages: handleAdditionalMessages(params.additional_messages),
3147
- stream: false
3148
- };
3149
- const result = await this._client.post(apiUrl, payload, false, options);
3150
- const chatId = result.data.id;
3151
- const conversationId = result.data.conversation_id;
3152
- let chat;
3153
- while(true){
3154
- await sleep(100);
3155
- chat = await this.retrieve(conversationId, chatId);
3156
- if ('completed' === chat.status || 'failed' === chat.status || 'requires_action' === chat.status) break;
3157
- }
3158
- const messageList = await this.messages.list(conversationId, chatId);
3159
- return {
3160
- chat,
3161
- messages: messageList
3162
- };
3163
- }
3164
- /**
3165
- * Call the Chat API to send messages to a published Coze agent with streaming response. | 调用此接口发起一次对话,支持流式响应。
3166
- * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
3167
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
3168
- * @param params - Required The parameters for streaming a chat session. | 流式会话的参数。
3169
- * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
3170
- * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
3171
- * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
3172
- * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
3173
- * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
3174
- * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
3175
- * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
3176
- * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
3177
- * @returns A stream of chat data. | 对话数据流。
3178
- */ async *stream(params, options) {
3179
- if (!params.user_id) params.user_id = uuid();
3180
- const { conversation_id, ...rest } = params;
3181
- const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
3182
- const payload = {
3183
- ...rest,
3184
- additional_messages: handleAdditionalMessages(params.additional_messages),
3185
- stream: true
3186
- };
3187
- const result = await this._client.post(apiUrl, payload, true, options);
3188
- for await (const message of result)if ("done" === message.event) {
3189
- const ret = {
3190
- event: message.event,
3191
- data: '[DONE]'
3192
- };
3193
- yield ret;
3194
- } else try {
3195
- const ret = {
3196
- event: message.event,
3197
- data: JSON.parse(message.data)
3198
- };
3199
- yield ret;
3200
- } catch (error) {
3201
- throw new CozeError(`Could not parse message into JSON:${message.data}`);
3202
- }
3203
- }
3204
- /**
3205
- * Get the detailed information of the chat. | 查看对话的详细信息。
3206
- * @docs en:https://www.coze.com/docs/developer_guides/retrieve_chat?_lang=en
3207
- * @docs zh:https://www.coze.cn/docs/developer_guides/retrieve_chat?_lang=zh
3208
- * @param conversation_id - Required The ID of the conversation. | 会话 ID。
3209
- * @param chat_id - Required The ID of the chat. | 对话 ID。
3210
- * @returns The data of the retrieved chat. | 检索到的对话数据。
3211
- */ async retrieve(conversation_id, chat_id, options) {
3212
- const apiUrl = `/v3/chat/retrieve?conversation_id=${conversation_id}&chat_id=${chat_id}`;
3213
- const result = await this._client.post(apiUrl, void 0, false, options);
3214
- return result.data;
3215
- }
3216
- /**
3217
- * Cancel a chat session. | 取消对话会话。
3218
- * @docs en:https://www.coze.com/docs/developer_guides/cancel_chat?_lang=en
3219
- * @docs zh:https://www.coze.cn/docs/developer_guides/cancel_chat?_lang=zh
3220
- * @param conversation_id - Required The ID of the conversation. | 会话 ID。
3221
- * @param chat_id - Required The ID of the chat. | 对话 ID。
3222
- * @returns The data of the canceled chat. | 取消的对话数据。
3223
- */ async cancel(conversation_id, chat_id, options) {
3224
- const apiUrl = '/v3/chat/cancel';
3225
- const payload = {
3226
- conversation_id,
3227
- chat_id
3228
- };
3229
- const result = await this._client.post(apiUrl, payload, false, options);
3230
- return result.data;
3231
- }
3232
- /**
3233
- * Submit tool outputs for a chat session. | 提交对话会话的工具输出。
3234
- * @docs en:https://www.coze.com/docs/developer_guides/chat_submit_tool_outputs?_lang=en
3235
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_submit_tool_outputs?_lang=zh
3236
- * @param params - Required Parameters for submitting tool outputs. | 提交工具输出的参数。
3237
- * @param params.conversation_id - Required The ID of the conversation. | 会话 ID。
3238
- * @param params.chat_id - Required The ID of the chat. | 对话 ID。
3239
- * @param params.tool_outputs - Required The outputs of the tool. | 工具的输出。
3240
- * @param params.stream - Optional Whether to use streaming response. | 是否使用流式响应。
3241
- * @returns The data of the submitted tool outputs or a stream of chat data. | 提交的工具输出数据或对话数据流。
3242
- */ async *submitToolOutputs(params, options) {
3243
- const { conversation_id, chat_id, ...rest } = params;
3244
- const apiUrl = `/v3/chat/submit_tool_outputs?conversation_id=${params.conversation_id}&chat_id=${params.chat_id}`;
3245
- const payload = {
3246
- ...rest
3247
- };
3248
- if (false === params.stream) {
3249
- const response = await this._client.post(apiUrl, payload, false, options);
3250
- return response.data;
3037
+ } else err.stack = stack;
3038
+ } catch (e) {
3039
+ // ignore the case where "stack" is an un-writable property
3040
+ }
3041
+ }
3042
+ throw err;
3251
3043
  }
3252
- {
3253
- const result = await this._client.post(apiUrl, payload, true, options);
3254
- for await (const message of result)if ("done" === message.event) {
3255
- const ret = {
3256
- event: message.event,
3257
- data: '[DONE]'
3258
- };
3259
- yield ret;
3260
- } else try {
3261
- const ret = {
3262
- event: message.event,
3263
- data: JSON.parse(message.data)
3264
- };
3265
- yield ret;
3044
+ }
3045
+ _request(configOrUrl, config) {
3046
+ /*eslint no-param-reassign:0*/ // Allow for axios('example/url'[, config]) a la fetch API
3047
+ if ('string' == typeof configOrUrl) {
3048
+ config = config || {};
3049
+ config.url = configOrUrl;
3050
+ } else config = configOrUrl || {};
3051
+ config = mergeConfig_mergeConfig(this.defaults, config);
3052
+ const { transitional, paramsSerializer, headers } = config;
3053
+ if (void 0 !== transitional) helpers_validator.assertOptions(transitional, {
3054
+ silentJSONParsing: Axios_validators.transitional(Axios_validators.boolean),
3055
+ forcedJSONParsing: Axios_validators.transitional(Axios_validators.boolean),
3056
+ clarifyTimeoutError: Axios_validators.transitional(Axios_validators.boolean)
3057
+ }, false);
3058
+ if (null != paramsSerializer) {
3059
+ if (utils.isFunction(paramsSerializer)) config.paramsSerializer = {
3060
+ serialize: paramsSerializer
3061
+ };
3062
+ else helpers_validator.assertOptions(paramsSerializer, {
3063
+ encode: Axios_validators.function,
3064
+ serialize: Axios_validators.function
3065
+ }, true);
3066
+ }
3067
+ // Set config.method
3068
+ config.method = (config.method || this.defaults.method || 'get').toLowerCase();
3069
+ // Flatten headers
3070
+ let contextHeaders = headers && utils.merge(headers.common, headers[config.method]);
3071
+ headers && utils.forEach([
3072
+ 'delete',
3073
+ 'get',
3074
+ 'head',
3075
+ 'post',
3076
+ 'put',
3077
+ 'patch',
3078
+ 'common'
3079
+ ], (method)=>{
3080
+ delete headers[method];
3081
+ });
3082
+ config.headers = AxiosHeaders.concat(contextHeaders, headers);
3083
+ // filter out skipped interceptors
3084
+ const requestInterceptorChain = [];
3085
+ let synchronousRequestInterceptors = true;
3086
+ this.interceptors.request.forEach(function(interceptor) {
3087
+ if ('function' == typeof interceptor.runWhen && false === interceptor.runWhen(config)) return;
3088
+ synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
3089
+ requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
3090
+ });
3091
+ const responseInterceptorChain = [];
3092
+ this.interceptors.response.forEach(function(interceptor) {
3093
+ responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
3094
+ });
3095
+ let promise;
3096
+ let i = 0;
3097
+ let len;
3098
+ if (!synchronousRequestInterceptors) {
3099
+ const chain = [
3100
+ dispatchRequest.bind(this),
3101
+ void 0
3102
+ ];
3103
+ chain.unshift.apply(chain, requestInterceptorChain);
3104
+ chain.push.apply(chain, responseInterceptorChain);
3105
+ len = chain.length;
3106
+ promise = Promise.resolve(config);
3107
+ while(i < len)promise = promise.then(chain[i++], chain[i++]);
3108
+ return promise;
3109
+ }
3110
+ len = requestInterceptorChain.length;
3111
+ let newConfig = config;
3112
+ i = 0;
3113
+ while(i < len){
3114
+ const onFulfilled = requestInterceptorChain[i++];
3115
+ const onRejected = requestInterceptorChain[i++];
3116
+ try {
3117
+ newConfig = onFulfilled(newConfig);
3266
3118
  } catch (error) {
3267
- throw new CozeError(`Could not parse message into JSON:${message.data}`);
3119
+ onRejected.call(this, error);
3120
+ break;
3268
3121
  }
3269
3122
  }
3123
+ try {
3124
+ promise = dispatchRequest.call(this, newConfig);
3125
+ } catch (error) {
3126
+ return Promise.reject(error);
3127
+ }
3128
+ i = 0;
3129
+ len = responseInterceptorChain.length;
3130
+ while(i < len)promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
3131
+ return promise;
3270
3132
  }
3271
- constructor(...args){
3272
- super(...args), this.messages = new Messages(this._client);
3133
+ getUri(config) {
3134
+ config = mergeConfig_mergeConfig(this.defaults, config);
3135
+ const fullPath = buildFullPath(config.baseURL, config.url);
3136
+ return buildURL(fullPath, config.params, config.paramsSerializer);
3273
3137
  }
3274
3138
  }
3275
- var chat_ChatEventType = /*#__PURE__*/ function(ChatEventType) {
3276
- ChatEventType["CONVERSATION_CHAT_CREATED"] = "conversation.chat.created";
3277
- ChatEventType["CONVERSATION_CHAT_IN_PROGRESS"] = "conversation.chat.in_progress";
3278
- ChatEventType["CONVERSATION_CHAT_COMPLETED"] = "conversation.chat.completed";
3279
- ChatEventType["CONVERSATION_CHAT_FAILED"] = "conversation.chat.failed";
3280
- ChatEventType["CONVERSATION_CHAT_REQUIRES_ACTION"] = "conversation.chat.requires_action";
3281
- ChatEventType["CONVERSATION_MESSAGE_DELTA"] = "conversation.message.delta";
3282
- ChatEventType["CONVERSATION_MESSAGE_COMPLETED"] = "conversation.message.completed";
3283
- ChatEventType["CONVERSATION_AUDIO_DELTA"] = "conversation.audio.delta";
3284
- ChatEventType["DONE"] = "done";
3285
- ChatEventType["ERROR"] = "error";
3286
- return ChatEventType;
3287
- }({});
3288
- class messages_Messages extends APIResource {
3289
- /**
3290
- * Create a message and add it to the specified conversation. | 创建一条消息,并将其添加到指定的会话中。
3291
- * @docs en: https://www.coze.com/docs/developer_guides/create_message?_lang=en
3292
- * @docs zh: https://www.coze.cn/docs/developer_guides/create_message?_lang=zh
3293
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3294
- * @param params - Required The parameters for creating a message | 创建消息所需的参数
3295
- * @param params.role - Required The entity that sent this message. Possible values: user, assistant. | 发送这条消息的实体。取值:user, assistant。
3296
- * @param params.content - Required The content of the message. | 消息的内容。
3297
- * @param params.content_type - Required The type of the message content. | 消息内容的类型。
3298
- * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
3299
- * @returns Information about the new message. | 消息详情。
3300
- */ async create(conversation_id, params, options) {
3301
- const apiUrl = `/v1/conversation/message/create?conversation_id=${conversation_id}`;
3302
- const response = await this._client.post(apiUrl, params, false, options);
3303
- return response.data;
3304
- }
3305
- /**
3306
- * Modify a message, supporting the modification of message content, additional content, and message type. | 修改一条消息,支持修改消息内容、附加内容和消息类型。
3307
- * @docs en: https://www.coze.com/docs/developer_guides/modify_message?_lang=en
3308
- * @docs zh: https://www.coze.cn/docs/developer_guides/modify_message?_lang=zh
3309
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3310
- * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
3311
- * @param params - Required The parameters for modifying a message | 修改消息所需的参数
3312
- * @param params.meta_data - Optional Additional information when modifying a message. | 修改消息时的附加消息。
3313
- * @param params.content - Optional The content of the message. | 消息的内容。
3314
- * @param params.content_type - Optional The type of the message content. | 消息内容的类型。
3315
- * @returns Information about the modified message. | 消息详情。
3316
- */ // eslint-disable-next-line max-params
3317
- async update(conversation_id, message_id, params, options) {
3318
- const apiUrl = `/v1/conversation/message/modify?conversation_id=${conversation_id}&message_id=${message_id}`;
3319
- const response = await this._client.post(apiUrl, params, false, options);
3320
- return response.message;
3321
- }
3322
- /**
3323
- * Get the detailed information of specified message. | 查看指定消息的详细信息。
3324
- * @docs en: https://www.coze.com/docs/developer_guides/retrieve_message?_lang=en
3325
- * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_message?_lang=zh
3326
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3327
- * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
3328
- * @returns Information about the message. | 消息详情。
3329
- */ async retrieve(conversation_id, message_id, options) {
3330
- const apiUrl = `/v1/conversation/message/retrieve?conversation_id=${conversation_id}&message_id=${message_id}`;
3331
- const response = await this._client.get(apiUrl, null, false, options);
3332
- return response.data;
3139
+ // Provide aliases for supported request methods
3140
+ utils.forEach([
3141
+ 'delete',
3142
+ 'get',
3143
+ 'head',
3144
+ 'options'
3145
+ ], function(method) {
3146
+ /*eslint func-names:0*/ Axios_Axios.prototype[method] = function(url, config) {
3147
+ return this.request(mergeConfig_mergeConfig(config || {}, {
3148
+ method,
3149
+ url,
3150
+ data: (config || {}).data
3151
+ }));
3152
+ };
3153
+ });
3154
+ utils.forEach([
3155
+ 'post',
3156
+ 'put',
3157
+ 'patch'
3158
+ ], function(method) {
3159
+ /*eslint func-names:0*/ function generateHTTPMethod(isForm) {
3160
+ return function(url, data, config) {
3161
+ return this.request(mergeConfig_mergeConfig(config || {}, {
3162
+ method,
3163
+ headers: isForm ? {
3164
+ 'Content-Type': 'multipart/form-data'
3165
+ } : {},
3166
+ url,
3167
+ data
3168
+ }));
3169
+ };
3333
3170
  }
3334
- /**
3335
- * List messages in a conversation. | 列出会话中的消息。
3336
- * @docs en: https://www.coze.com/docs/developer_guides/message_list?_lang=en
3337
- * @docs zh: https://www.coze.cn/docs/developer_guides/message_list?_lang=zh
3338
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3339
- * @param params - Optional The parameters for listing messages | 列出消息所需的参数
3340
- * @param params.order - Optional The order of the messages. | 消息的顺序。
3341
- * @param params.chat_id - Optional The ID of the chat. | 聊天 ID。
3342
- * @param params.before_id - Optional The ID of the message before which to list. | 列出此消息之前的消息 ID。
3343
- * @param params.after_id - Optional The ID of the message after which to list. | 列出此消息之后的消息 ID。
3344
- * @param params.limit - Optional The maximum number of messages to return. | 返回的最大消息数。
3345
- * @returns A list of messages. | 消息列表。
3346
- */ async list(conversation_id, params, options) {
3347
- const apiUrl = `/v1/conversation/message/list?conversation_id=${conversation_id}`;
3348
- const response = await this._client.post(apiUrl, params, false, options);
3349
- return response;
3171
+ Axios_Axios.prototype[method] = generateHTTPMethod();
3172
+ Axios_Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
3173
+ });
3174
+ /* ESM default export */ const Axios = Axios_Axios;
3175
+ /**
3176
+ * A `CancelToken` is an object that can be used to request cancellation of an operation.
3177
+ *
3178
+ * @param {Function} executor The executor function.
3179
+ *
3180
+ * @returns {CancelToken}
3181
+ */ class CancelToken_CancelToken {
3182
+ constructor(executor){
3183
+ if ('function' != typeof executor) throw new TypeError('executor must be a function.');
3184
+ let resolvePromise;
3185
+ this.promise = new Promise(function(resolve) {
3186
+ resolvePromise = resolve;
3187
+ });
3188
+ const token = this;
3189
+ // eslint-disable-next-line func-names
3190
+ this.promise.then((cancel)=>{
3191
+ if (!token._listeners) return;
3192
+ let i = token._listeners.length;
3193
+ while(i-- > 0)token._listeners[i](cancel);
3194
+ token._listeners = null;
3195
+ });
3196
+ // eslint-disable-next-line func-names
3197
+ this.promise.then = (onfulfilled)=>{
3198
+ let _resolve;
3199
+ // eslint-disable-next-line func-names
3200
+ const promise = new Promise((resolve)=>{
3201
+ token.subscribe(resolve);
3202
+ _resolve = resolve;
3203
+ }).then(onfulfilled);
3204
+ promise.cancel = function() {
3205
+ token.unsubscribe(_resolve);
3206
+ };
3207
+ return promise;
3208
+ };
3209
+ executor(function(message, config, request) {
3210
+ if (token.reason) // Cancellation has already been requested
3211
+ return;
3212
+ token.reason = new CanceledError(message, config, request);
3213
+ resolvePromise(token.reason);
3214
+ });
3350
3215
  }
3351
3216
  /**
3352
- * Call the API to delete a message within a specified conversation. | 调用接口在指定会话中删除消息。
3353
- * @docs en: https://www.coze.com/docs/developer_guides/delete_message?_lang=en
3354
- * @docs zh: https://www.coze.cn/docs/developer_guides/delete_message?_lang=zh
3355
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3356
- * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
3357
- * @returns Details of the deleted message. | 已删除的消息详情。
3358
- */ async delete(conversation_id, message_id, options) {
3359
- const apiUrl = `/v1/conversation/message/delete?conversation_id=${conversation_id}&message_id=${message_id}`;
3360
- const response = await this._client.post(apiUrl, void 0, false, options);
3361
- return response.data;
3217
+ * Throws a `CanceledError` if cancellation has been requested.
3218
+ */ throwIfRequested() {
3219
+ if (this.reason) throw this.reason;
3362
3220
  }
3363
- }
3364
- class Conversations extends APIResource {
3365
3221
  /**
3366
- * Create a conversation. Conversation is an interaction between an agent and a user, including one or more messages. | 调用接口创建一个会话。
3367
- * @docs en: https://www.coze.com/docs/developer_guides/create_conversation?_lang=en
3368
- * @docs zh: https://www.coze.cn/docs/developer_guides/create_conversation?_lang=zh
3369
- * @param params - Required The parameters for creating a conversation | 创建会话所需的参数
3370
- * @param params.messages - Optional Messages in the conversation. | 会话中的消息内容。
3371
- * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
3372
- * @param params.bot_id - Optional Bind and isolate conversation on different bots. | 绑定和隔离不同Bot的会话。
3373
- * @returns Information about the created conversation. | 会话的基础信息。
3374
- */ async create(params, options) {
3375
- const apiUrl = '/v1/conversation/create';
3376
- const response = await this._client.post(apiUrl, params, false, options);
3377
- return response.data;
3222
+ * Subscribe to the cancel signal
3223
+ */ subscribe(listener) {
3224
+ if (this.reason) {
3225
+ listener(this.reason);
3226
+ return;
3227
+ }
3228
+ if (this._listeners) this._listeners.push(listener);
3229
+ else this._listeners = [
3230
+ listener
3231
+ ];
3378
3232
  }
3379
3233
  /**
3380
- * Get the information of specific conversation. | 通过会话 ID 查看会话信息。
3381
- * @docs en: https://www.coze.com/docs/developer_guides/retrieve_conversation?_lang=en
3382
- * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_conversation?_lang=zh
3383
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3384
- * @returns Information about the conversation. | 会话的基础信息。
3385
- */ async retrieve(conversation_id, options) {
3386
- const apiUrl = `/v1/conversation/retrieve?conversation_id=${conversation_id}`;
3387
- const response = await this._client.get(apiUrl, null, false, options);
3388
- return response.data;
3234
+ * Unsubscribe from the cancel signal
3235
+ */ unsubscribe(listener) {
3236
+ if (!this._listeners) return;
3237
+ const index = this._listeners.indexOf(listener);
3238
+ if (-1 !== index) this._listeners.splice(index, 1);
3389
3239
  }
3390
- /**
3391
- * List all conversations. | 列出 Bot 下所有会话。
3392
- * @param params
3393
- * @param params.bot_id - Required Bot ID. | Bot ID。
3394
- * @param params.page_num - Optional The page number. | 页码,默认值为 1。
3395
- * @param params.page_size - Optional The number of conversations per page. | 每页的会话数量,默认值为 50。
3396
- * @returns Information about the conversations. | 会话的信息。
3397
- */ async list(params, options) {
3398
- const apiUrl = '/v1/conversations';
3399
- const response = await this._client.get(apiUrl, params, false, options);
3400
- return response.data;
3240
+ toAbortSignal() {
3241
+ const controller = new AbortController();
3242
+ const abort = (err)=>{
3243
+ controller.abort(err);
3244
+ };
3245
+ this.subscribe(abort);
3246
+ controller.signal.unsubscribe = ()=>this.unsubscribe(abort);
3247
+ return controller.signal;
3401
3248
  }
3402
3249
  /**
3403
- * Clear a conversation. | 清空会话。
3404
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3405
- * @returns Information about the conversation session. | 会话的会话 ID。
3406
- */ async clear(conversation_id, options) {
3407
- const apiUrl = `/v1/conversations/${conversation_id}/clear`;
3408
- const response = await this._client.post(apiUrl, null, false, options);
3409
- return response.data;
3410
- }
3411
- constructor(...args){
3412
- super(...args), this.messages = new messages_Messages(this._client);
3250
+ * Returns an object that contains a new `CancelToken` and a function that, when called,
3251
+ * cancels the `CancelToken`.
3252
+ */ static source() {
3253
+ let cancel;
3254
+ const token = new CancelToken_CancelToken(function(c) {
3255
+ cancel = c;
3256
+ });
3257
+ return {
3258
+ token,
3259
+ cancel
3260
+ };
3413
3261
  }
3414
3262
  }
3263
+ /* ESM default export */ const CancelToken = CancelToken_CancelToken;
3264
+ /**
3265
+ * Syntactic sugar for invoking a function and expanding an array for arguments.
3266
+ *
3267
+ * Common use case would be to use `Function.prototype.apply`.
3268
+ *
3269
+ * ```js
3270
+ * function f(x, y, z) {}
3271
+ * var args = [1, 2, 3];
3272
+ * f.apply(null, args);
3273
+ * ```
3274
+ *
3275
+ * With `spread` this example can be re-written.
3276
+ *
3277
+ * ```js
3278
+ * spread(function(x, y, z) {})([1, 2, 3]);
3279
+ * ```
3280
+ *
3281
+ * @param {Function} callback
3282
+ *
3283
+ * @returns {Function}
3284
+ */ function spread(callback) {
3285
+ return function(arr) {
3286
+ return callback.apply(null, arr);
3287
+ };
3288
+ }
3289
+ /**
3290
+ * Determines whether the payload is an error thrown by Axios
3291
+ *
3292
+ * @param {*} payload The value to test
3293
+ *
3294
+ * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
3295
+ */ function isAxiosError(payload) {
3296
+ return utils.isObject(payload) && true === payload.isAxiosError;
3297
+ }
3298
+ const HttpStatusCode = {
3299
+ Continue: 100,
3300
+ SwitchingProtocols: 101,
3301
+ Processing: 102,
3302
+ EarlyHints: 103,
3303
+ Ok: 200,
3304
+ Created: 201,
3305
+ Accepted: 202,
3306
+ NonAuthoritativeInformation: 203,
3307
+ NoContent: 204,
3308
+ ResetContent: 205,
3309
+ PartialContent: 206,
3310
+ MultiStatus: 207,
3311
+ AlreadyReported: 208,
3312
+ ImUsed: 226,
3313
+ MultipleChoices: 300,
3314
+ MovedPermanently: 301,
3315
+ Found: 302,
3316
+ SeeOther: 303,
3317
+ NotModified: 304,
3318
+ UseProxy: 305,
3319
+ Unused: 306,
3320
+ TemporaryRedirect: 307,
3321
+ PermanentRedirect: 308,
3322
+ BadRequest: 400,
3323
+ Unauthorized: 401,
3324
+ PaymentRequired: 402,
3325
+ Forbidden: 403,
3326
+ NotFound: 404,
3327
+ MethodNotAllowed: 405,
3328
+ NotAcceptable: 406,
3329
+ ProxyAuthenticationRequired: 407,
3330
+ RequestTimeout: 408,
3331
+ Conflict: 409,
3332
+ Gone: 410,
3333
+ LengthRequired: 411,
3334
+ PreconditionFailed: 412,
3335
+ PayloadTooLarge: 413,
3336
+ UriTooLong: 414,
3337
+ UnsupportedMediaType: 415,
3338
+ RangeNotSatisfiable: 416,
3339
+ ExpectationFailed: 417,
3340
+ ImATeapot: 418,
3341
+ MisdirectedRequest: 421,
3342
+ UnprocessableEntity: 422,
3343
+ Locked: 423,
3344
+ FailedDependency: 424,
3345
+ TooEarly: 425,
3346
+ UpgradeRequired: 426,
3347
+ PreconditionRequired: 428,
3348
+ TooManyRequests: 429,
3349
+ RequestHeaderFieldsTooLarge: 431,
3350
+ UnavailableForLegalReasons: 451,
3351
+ InternalServerError: 500,
3352
+ NotImplemented: 501,
3353
+ BadGateway: 502,
3354
+ ServiceUnavailable: 503,
3355
+ GatewayTimeout: 504,
3356
+ HttpVersionNotSupported: 505,
3357
+ VariantAlsoNegotiates: 506,
3358
+ InsufficientStorage: 507,
3359
+ LoopDetected: 508,
3360
+ NotExtended: 510,
3361
+ NetworkAuthenticationRequired: 511
3362
+ };
3363
+ Object.entries(HttpStatusCode).forEach(([key, value])=>{
3364
+ HttpStatusCode[value] = key;
3365
+ });
3366
+ /* ESM default export */ const helpers_HttpStatusCode = HttpStatusCode;
3367
+ /**
3368
+ * Create an instance of Axios
3369
+ *
3370
+ * @param {Object} defaultConfig The default config for the instance
3371
+ *
3372
+ * @returns {Axios} A new instance of Axios
3373
+ */ function createInstance(defaultConfig) {
3374
+ const context = new Axios(defaultConfig);
3375
+ const instance = bind(Axios.prototype.request, context);
3376
+ // Copy axios.prototype to instance
3377
+ utils.extend(instance, Axios.prototype, context, {
3378
+ allOwnKeys: true
3379
+ });
3380
+ // Copy context to instance
3381
+ utils.extend(instance, context, null, {
3382
+ allOwnKeys: true
3383
+ });
3384
+ // Factory for creating new instances
3385
+ instance.create = function(instanceConfig) {
3386
+ return createInstance(mergeConfig_mergeConfig(defaultConfig, instanceConfig));
3387
+ };
3388
+ return instance;
3389
+ }
3390
+ // Create the default instance to be exported
3391
+ const axios = createInstance(defaults);
3392
+ // Expose Axios class to allow class inheritance
3393
+ axios.Axios = Axios;
3394
+ // Expose Cancel & CancelToken
3395
+ axios.CanceledError = CanceledError;
3396
+ axios.CancelToken = CancelToken;
3397
+ axios.isCancel = isCancel;
3398
+ axios.VERSION = VERSION;
3399
+ axios.toFormData = toFormData;
3400
+ // Expose AxiosError class
3401
+ axios.AxiosError = core_AxiosError;
3402
+ // alias for CanceledError for backward compatibility
3403
+ axios.Cancel = axios.CanceledError;
3404
+ // Expose all/spread
3405
+ axios.all = function(promises) {
3406
+ return Promise.all(promises);
3407
+ };
3408
+ axios.spread = spread;
3409
+ // Expose isAxiosError
3410
+ axios.isAxiosError = isAxiosError;
3411
+ // Expose mergeConfig
3412
+ axios.mergeConfig = mergeConfig_mergeConfig;
3413
+ axios.AxiosHeaders = AxiosHeaders;
3414
+ axios.formToJSON = (thing)=>formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
3415
+ axios.getAdapter = adapters_adapters.getAdapter;
3416
+ axios.HttpStatusCode = helpers_HttpStatusCode;
3417
+ axios.default = axios;
3418
+ // this module should only have a default export
3419
+ /* ESM default export */ const lib_axios = axios;
3420
+ // This module is intended to unwrap Axios default export as named.
3421
+ // Keep top-level export same with static properties
3422
+ // so that it can keep same with es module or cjs
3423
+ const { Axios: axios_Axios, AxiosError: axios_AxiosError, CanceledError: axios_CanceledError, isCancel: axios_isCancel, CancelToken: axios_CancelToken, VERSION: axios_VERSION, all: axios_all, Cancel, isAxiosError: axios_isAxiosError, spread: axios_spread, toFormData: axios_toFormData, AxiosHeaders: axios_AxiosHeaders, HttpStatusCode: axios_HttpStatusCode, formToJSON, getAdapter, mergeConfig: axios_mergeConfig } = lib_axios;
3415
3424
  class Files extends APIResource {
3416
3425
  /**
3417
3426
  * Upload files to Coze platform. | 调用接口上传文件到扣子。
@@ -3574,7 +3583,7 @@ class Documents extends APIResource {
3574
3583
  * @returns ListDocumentData | 知识库文件列表
3575
3584
  */ list(params, options) {
3576
3585
  const apiUrl = '/open_api/knowledge/document/list';
3577
- const response = this._client.get(apiUrl, params, false, esm_mergeConfig(options, {
3586
+ const response = this._client.get(apiUrl, params, false, mergeConfig(options, {
3578
3587
  headers: documents_headers
3579
3588
  }));
3580
3589
  return response;
@@ -3592,7 +3601,7 @@ class Documents extends APIResource {
3592
3601
  * @returns DocumentInfo[] | 已上传文件的基本信息
3593
3602
  */ async create(params, options) {
3594
3603
  const apiUrl = '/open_api/knowledge/document/create';
3595
- const response = await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3604
+ const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
3596
3605
  headers: documents_headers
3597
3606
  }));
3598
3607
  return response.document_infos;
@@ -3608,7 +3617,7 @@ class Documents extends APIResource {
3608
3617
  * @returns void | 无返回
3609
3618
  */ async delete(params, options) {
3610
3619
  const apiUrl = '/open_api/knowledge/document/delete';
3611
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3620
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3612
3621
  headers: documents_headers
3613
3622
  }));
3614
3623
  }
@@ -3624,7 +3633,7 @@ class Documents extends APIResource {
3624
3633
  * @returns void | 无返回
3625
3634
  */ async update(params, options) {
3626
3635
  const apiUrl = '/open_api/knowledge/document/update';
3627
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3636
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3628
3637
  headers: documents_headers
3629
3638
  }));
3630
3639
  }
@@ -3652,7 +3661,7 @@ class documents_Documents extends APIResource {
3652
3661
  * @returns ListDocumentData | 知识库文件列表
3653
3662
  */ list(params, options) {
3654
3663
  const apiUrl = '/open_api/knowledge/document/list';
3655
- const response = this._client.get(apiUrl, params, false, esm_mergeConfig(options, {
3664
+ const response = this._client.get(apiUrl, params, false, mergeConfig(options, {
3656
3665
  headers: documents_documents_headers
3657
3666
  }));
3658
3667
  return response;
@@ -3668,7 +3677,7 @@ class documents_Documents extends APIResource {
3668
3677
  * @returns DocumentInfo[] | 已上传文件的基本信息
3669
3678
  */ async create(params, options) {
3670
3679
  const apiUrl = '/open_api/knowledge/document/create';
3671
- const response = await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3680
+ const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
3672
3681
  headers: documents_documents_headers
3673
3682
  }));
3674
3683
  return response.document_infos;
@@ -3682,7 +3691,7 @@ class documents_Documents extends APIResource {
3682
3691
  * @returns void | 无返回
3683
3692
  */ async delete(params, options) {
3684
3693
  const apiUrl = '/open_api/knowledge/document/delete';
3685
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3694
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3686
3695
  headers: documents_documents_headers
3687
3696
  }));
3688
3697
  }
@@ -3696,7 +3705,7 @@ class documents_Documents extends APIResource {
3696
3705
  * @returns void | 无返回
3697
3706
  */ async update(params, options) {
3698
3707
  const apiUrl = '/open_api/knowledge/document/update';
3699
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3708
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3700
3709
  headers: documents_documents_headers
3701
3710
  }));
3702
3711
  }
@@ -3760,7 +3769,7 @@ class Speech extends APIResource {
3760
3769
  * @returns Speech synthesis data
3761
3770
  */ async create(params, options) {
3762
3771
  const apiUrl = '/v1/audio/speech';
3763
- const response = await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3772
+ const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
3764
3773
  responseType: 'arraybuffer'
3765
3774
  }));
3766
3775
  return response;
@@ -3773,23 +3782,26 @@ class Rooms extends APIResource {
3773
3782
  return response.data;
3774
3783
  }
3775
3784
  }
3776
- class esm_Audio extends APIResource {
3785
+ class audio_Audio extends APIResource {
3777
3786
  constructor(...args){
3778
3787
  super(...args), this.rooms = new Rooms(this._client), this.voices = new Voices(this._client), this.speech = new Speech(this._client);
3779
3788
  }
3780
3789
  }
3781
- var package_namespaceObject = JSON.parse('{"name":"@coze/api","version":"1.0.15","description":"Official Coze Node.js SDK for seamless AI integration into your applications | 扣子官方 Node.js SDK,助您轻松集成 AI 能力到应用中","keywords":["coze","ai","nodejs","sdk","chatbot","typescript"],"homepage":"https://github.com/coze-dev/coze-js/tree/main/packages/coze-js","bugs":{"url":"https://github.com/coze-dev/coze-js/issues"},"repository":{"type":"git","url":"https://github.com/coze-dev/coze-js.git","directory":"packages/coze-js"},"license":"MIT","author":"Leeight <leeight@gmail.com>","type":"module","exports":{".":{"require":"./dist/cjs/index.cjs","import":"./dist/esm/index.js","types":"./dist/types/index.d.ts"}},"main":"dist/cjs/index.cjs","module":"dist/esm/index.js","browser":{"crypto":false,"os":false,"jsonwebtoken":false},"types":"dist/types/index.d.ts","files":["dist","LICENSE","README.md","!**/*.tsbuildinfo"],"scripts":{"build":"rm -rf dist && rslib build","format":"prettier --write .","lint":"eslint ./ --cache --quiet","prepublishOnly":"npm run build","start":"rm -rf dist && rslib build -w","test":"vitest","test:cov":"vitest --coverage --run"},"dependencies":{"jsonwebtoken":"^9.0.2"},"devDependencies":{"@coze-infra/eslint-config":"workspace:*","@coze-infra/ts-config":"workspace:*","@coze-infra/vitest-config":"workspace:*","@rslib/core":"0.0.18","@swc/core":"^1.3.14","@types/jsonwebtoken":"^9.0.0","@types/node":"^20","@types/uuid":"^9.0.1","@types/whatwg-fetch":"^0.0.33","@vitest/coverage-v8":"~2.1.4","axios":"^1.7.7","typescript":"^5.5.3","vitest":"~2.1.4"},"peerDependencies":{"axios":"^1.7.1"}}'); // CONCATENATED MODULE: ./src/version.ts
3782
- const { version: esm_version } = package_namespaceObject;
3790
+ // EXTERNAL MODULE: os (ignored)
3791
+ var os_ignored_ = __webpack_require__("?9050");
3792
+ var os_ignored_default = /*#__PURE__*/ __webpack_require__.n(os_ignored_);
3793
+ var package_namespaceObject = JSON.parse('{"name":"@coze/api","version":"1.0.16-beta.1","description":"Official Coze Node.js SDK for seamless AI integration into your applications | 扣子官方 Node.js SDK,助您轻松集成 AI 能力到应用中","keywords":["coze","ai","nodejs","sdk","chatbot","typescript"],"homepage":"https://github.com/coze-dev/coze-js/tree/main/packages/coze-js","bugs":{"url":"https://github.com/coze-dev/coze-js/issues"},"repository":{"type":"git","url":"https://github.com/coze-dev/coze-js.git","directory":"packages/coze-js"},"license":"MIT","author":"Leeight <leeight@gmail.com>","type":"module","main":"src/index.ts","browser":{"crypto":false,"os":false,"jsonwebtoken":false},"types":"src/index.ts","files":["dist","LICENSE","README.md"],"scripts":{"build":"rm -rf dist && rslib build","format":"prettier --write .","lint":"eslint ./ --cache --quiet","start":"rm -rf dist && rslib build -w","test":"vitest","test:cov":"vitest --coverage --run"},"dependencies":{"jsonwebtoken":"^9.0.2"},"devDependencies":{"@coze-infra/eslint-config":"workspace:*","@coze-infra/ts-config":"workspace:*","@coze-infra/vitest-config":"workspace:*","@rslib/core":"0.0.18","@swc/core":"^1.3.14","@types/jsonwebtoken":"^9.0.0","@types/node":"^20","@types/uuid":"^9.0.1","@types/whatwg-fetch":"^0.0.33","@vitest/coverage-v8":"~2.1.4","axios":"^1.7.7","typescript":"^5.5.3","vitest":"~2.1.4"},"peerDependencies":{"axios":"^1.7.1"},"cozePublishConfig":{"exports":{".":{"require":"./dist/cjs/index.cjs","import":"./dist/esm/index.js","types":"./dist/types/index.d.ts"}},"main":"dist/cjs/index.cjs","module":"dist/esm/index.js","types":"dist/types/index.d.ts"}}'); // CONCATENATED MODULE: ../coze-js/src/version.ts
3794
+ const { version: version_version } = package_namespaceObject;
3783
3795
  const getEnv = ()=>{
3784
3796
  const nodeVersion = process.version.slice(1); // Remove 'v' prefix
3785
3797
  const { platform } = process;
3786
3798
  let osName = platform.toLowerCase();
3787
- let osVersion = os_ignored_.release();
3799
+ let osVersion = os_ignored_default().release();
3788
3800
  if ('darwin' === platform) {
3789
3801
  osName = 'macos';
3790
3802
  // Try to parse the macOS version
3791
3803
  try {
3792
- const darwinVersion = os_ignored_.release().split('.');
3804
+ const darwinVersion = os_ignored_default().release().split('.');
3793
3805
  if (darwinVersion.length >= 2) {
3794
3806
  const majorVersion = parseInt(darwinVersion[0], 10);
3795
3807
  if (!isNaN(majorVersion) && majorVersion >= 9) {
@@ -3802,10 +3814,10 @@ const getEnv = ()=>{
3802
3814
  }
3803
3815
  } else if ('win32' === platform) {
3804
3816
  osName = 'windows';
3805
- osVersion = os_ignored_.release();
3817
+ osVersion = os_ignored_default().release();
3806
3818
  } else if ('linux' === platform) {
3807
3819
  osName = 'linux';
3808
- osVersion = os_ignored_.release();
3820
+ osVersion = os_ignored_default().release();
3809
3821
  }
3810
3822
  return {
3811
3823
  osName,
@@ -3815,12 +3827,12 @@ const getEnv = ()=>{
3815
3827
  };
3816
3828
  const getUserAgent = ()=>{
3817
3829
  const { nodeVersion, osName, osVersion } = getEnv();
3818
- return `coze-js/${esm_version} node/${nodeVersion} ${osName}/${osVersion}`.toLowerCase();
3830
+ return `coze-js/${version_version} node/${nodeVersion} ${osName}/${osVersion}`.toLowerCase();
3819
3831
  };
3820
3832
  const getNodeClientUserAgent = ()=>{
3821
3833
  const { osVersion, nodeVersion, osName } = getEnv();
3822
3834
  const ua = {
3823
- version: esm_version,
3835
+ version: version_version,
3824
3836
  lang: 'node',
3825
3837
  lang_version: nodeVersion,
3826
3838
  os_name: osName,
@@ -3828,15 +3840,17 @@ const getNodeClientUserAgent = ()=>{
3828
3840
  };
3829
3841
  return JSON.stringify(ua);
3830
3842
  };
3831
- /* eslint-disable @typescript-eslint/no-explicit-any */ const esm_handleError = (error)=>{
3843
+ /* eslint-disable @typescript-eslint/no-explicit-any */ const fetcher_handleError = (error)=>{
3832
3844
  if (!error.isAxiosError && (!error.code || !error.message)) return new CozeError(`Unexpected error: ${error.message}`);
3833
3845
  if ('ECONNABORTED' === error.code && error.message.includes('timeout') || 'ETIMEDOUT' === error.code) {
3834
3846
  var _error_response;
3835
3847
  return new TimeoutError(408, void 0, `Request timed out: ${error.message}`, null === (_error_response = error.response) || void 0 === _error_response ? void 0 : _error_response.headers);
3836
3848
  }
3837
3849
  if ('ERR_CANCELED' === error.code) return new APIUserAbortError(error.message);
3838
- var _error_response1, _error_response2, _error_response3;
3839
- return APIError.generate((null === (_error_response1 = error.response) || void 0 === _error_response1 ? void 0 : _error_response1.status) || 500, null === (_error_response2 = error.response) || void 0 === _error_response2 ? void 0 : _error_response2.data, error.message, null === (_error_response3 = error.response) || void 0 === _error_response3 ? void 0 : _error_response3.headers);
3850
+ else {
3851
+ var _error_response1, _error_response2, _error_response3;
3852
+ return error_APIError.generate((null === (_error_response1 = error.response) || void 0 === _error_response1 ? void 0 : _error_response1.status) || 500, null === (_error_response2 = error.response) || void 0 === _error_response2 ? void 0 : _error_response2.data, error.message, null === (_error_response3 = error.response) || void 0 === _error_response3 ? void 0 : _error_response3.headers);
3853
+ }
3840
3854
  };
3841
3855
  async function fetchAPI(url) {
3842
3856
  let options = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
@@ -3852,7 +3866,7 @@ async function fetchAPI(url) {
3852
3866
  adapter: options.isStreaming ? 'fetch' : void 0,
3853
3867
  ...options
3854
3868
  }).catch((error)=>{
3855
- throw esm_handleError(error);
3869
+ throw fetcher_handleError(error);
3856
3870
  });
3857
3871
  return {
3858
3872
  async *stream () {
@@ -3890,7 +3904,7 @@ async function fetchAPI(url) {
3890
3904
  buffer = lines[lines.length - 1]; // Keep the last incomplete line in the buffer
3891
3905
  }
3892
3906
  } catch (error) {
3893
- esm_handleError(error);
3907
+ fetcher_handleError(error);
3894
3908
  }
3895
3909
  },
3896
3910
  json: ()=>response.data,
@@ -3914,8 +3928,8 @@ function isAxiosStatic(instance) {
3914
3928
  }
3915
3929
  /**
3916
3930
  * default coze base URL is api.coze.com
3917
- */ const COZE_COM_BASE_URL = 'https://api.coze.com';
3918
- /* eslint-disable max-params */ class APIClient {
3931
+ */ const constant_COZE_COM_BASE_URL = 'https://api.coze.com';
3932
+ /* eslint-disable max-params */ class core_APIClient {
3919
3933
  async getToken() {
3920
3934
  if ('function' == typeof this.token) return await this.token();
3921
3935
  return this.token;
@@ -3925,11 +3939,11 @@ function isAxiosStatic(instance) {
3925
3939
  const headers = {
3926
3940
  authorization: `Bearer ${token}`
3927
3941
  };
3928
- if (!isBrowser()) {
3942
+ if (!utils_isBrowser()) {
3929
3943
  headers['User-Agent'] = getUserAgent();
3930
3944
  headers['X-Coze-Client-User-Agent'] = getNodeClientUserAgent();
3931
3945
  }
3932
- const config = esm_mergeConfig(this.axiosOptions, options, {
3946
+ const config = mergeConfig(this.axiosOptions, options, {
3933
3947
  headers
3934
3948
  });
3935
3949
  config.method = method;
@@ -3953,7 +3967,7 @@ function isAxiosStatic(instance) {
3953
3967
  if (contentType && contentType.includes('application/json')) {
3954
3968
  const result = await json();
3955
3969
  const { code, msg } = result;
3956
- if (0 !== code && void 0 !== code) throw APIError.generate(response.status, result, msg, response.headers);
3970
+ if (0 !== code && void 0 !== code) throw error_APIError.generate(response.status, result, msg, response.headers);
3957
3971
  }
3958
3972
  return stream();
3959
3973
  }
@@ -3961,7 +3975,7 @@ function isAxiosStatic(instance) {
3961
3975
  {
3962
3976
  const result = await json();
3963
3977
  const { code, msg } = result;
3964
- if (0 !== code && void 0 !== code) throw APIError.generate(response.status, result, msg, response.headers);
3978
+ if (0 !== code && void 0 !== code) throw error_APIError.generate(response.status, result, msg, response.headers);
3965
3979
  return result;
3966
3980
  }
3967
3981
  }
@@ -3993,31 +4007,35 @@ function isAxiosStatic(instance) {
3993
4007
  }
3994
4008
  constructor(config){
3995
4009
  this._config = config;
3996
- this.baseURL = config.baseURL || COZE_COM_BASE_URL;
4010
+ this.baseURL = config.baseURL || constant_COZE_COM_BASE_URL;
3997
4011
  this.token = config.token;
3998
4012
  this.axiosOptions = config.axiosOptions || {};
3999
4013
  this.axiosInstance = config.axiosInstance;
4000
4014
  this.debug = config.debug || false;
4001
4015
  this.allowPersonalAccessTokenInBrowser = config.allowPersonalAccessTokenInBrowser || false;
4002
4016
  this.headers = config.headers;
4003
- if (isBrowser() && 'function' != typeof this.token && isPersonalAccessToken(this.token) && !this.allowPersonalAccessTokenInBrowser) throw new CozeError('Browser environments do not support authentication using Personal Access Token (PAT) by default.\nas it may expose secret API keys. \n\nPlease use OAuth2.0 authentication mechanism. see:\nhttps://www.coze.com/docs/developer_guides/oauth_apps?_lang=en \n\nIf you need to force use, please set the `allowPersonalAccessTokenInBrowser` option to `true`. \n\ne.g new CozeAPI({ token, allowPersonalAccessTokenInBrowser: true });\n\n');
4004
- }
4005
- }
4006
- APIClient.APIError = APIError;
4007
- APIClient.BadRequestError = BadRequestError;
4008
- APIClient.AuthenticationError = AuthenticationError;
4009
- APIClient.PermissionDeniedError = PermissionDeniedError;
4010
- APIClient.NotFoundError = NotFoundError;
4011
- APIClient.RateLimitError = RateLimitError;
4012
- APIClient.InternalServerError = InternalServerError;
4013
- APIClient.GatewayError = GatewayError;
4014
- APIClient.TimeoutError = TimeoutError;
4015
- APIClient.UserAbortError = APIUserAbortError;
4016
- class CozeAPI extends APIClient {
4017
+ if (utils_isBrowser() && 'function' != typeof this.token && isPersonalAccessToken(this.token) && !this.allowPersonalAccessTokenInBrowser) throw new CozeError('Browser environments do not support authentication using Personal Access Token (PAT) by default.\nas it may expose secret API keys. \n\nPlease use OAuth2.0 authentication mechanism. see:\nhttps://www.coze.com/docs/developer_guides/oauth_apps?_lang=en \n\nIf you need to force use, please set the `allowPersonalAccessTokenInBrowser` option to `true`. \n\ne.g new CozeAPI({ token, allowPersonalAccessTokenInBrowser: true });\n\n');
4018
+ }
4019
+ }
4020
+ core_APIClient.APIError = error_APIError;
4021
+ core_APIClient.BadRequestError = BadRequestError;
4022
+ core_APIClient.AuthenticationError = AuthenticationError;
4023
+ core_APIClient.PermissionDeniedError = PermissionDeniedError;
4024
+ core_APIClient.NotFoundError = NotFoundError;
4025
+ core_APIClient.RateLimitError = RateLimitError;
4026
+ core_APIClient.InternalServerError = InternalServerError;
4027
+ core_APIClient.GatewayError = GatewayError;
4028
+ core_APIClient.TimeoutError = TimeoutError;
4029
+ core_APIClient.UserAbortError = APIUserAbortError;
4030
+ // EXTERNAL MODULE: crypto (ignored)
4031
+ __webpack_require__("?666e");
4032
+ // EXTERNAL MODULE: jsonwebtoken (ignored)
4033
+ __webpack_require__("?79fd");
4034
+ class CozeAPI extends core_APIClient {
4017
4035
  constructor(...args){
4018
4036
  super(...args), this.bots = new Bots(this), this.chat = new Chat(this), this.conversations = new Conversations(this), this.files = new Files(this), /**
4019
4037
  * @deprecated
4020
- */ this.knowledge = new Knowledge(this), this.datasets = new Datasets(this), this.workflows = new Workflows(this), this.workspaces = new WorkSpaces(this), this.audio = new esm_Audio(this);
4038
+ */ this.knowledge = new Knowledge(this), this.datasets = new Datasets(this), this.workflows = new Workflows(this), this.workspaces = new WorkSpaces(this), this.audio = new audio_Audio(this);
4021
4039
  }
4022
4040
  }
4023
4041
  /**
@@ -9249,7 +9267,7 @@ var setPrototypeOf = setPrototypeOf$2, _Object$setPrototypeOf = getDefaultExport
9249
9267
  }, stringPad = {
9250
9268
  start: createMethod(!1),
9251
9269
  end: createMethod(!0)
9252
- }, userAgent = engineUserAgent, stringPadWebkitBug = /Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(userAgent), $$F = _export, $padEnd = stringPad.end, WEBKIT_BUG$1 = stringPadWebkitBug;
9270
+ }, index_esm_min_userAgent = engineUserAgent, stringPadWebkitBug = /Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(index_esm_min_userAgent), $$F = _export, $padEnd = stringPad.end, WEBKIT_BUG$1 = stringPadWebkitBug;
9253
9271
  $$F({
9254
9272
  target: "String",
9255
9273
  proto: !0,
@@ -38402,7 +38420,7 @@ var VERTC = _createClass(function e() {
38402
38420
  + * @param milliseconds The time to sleep in milliseconds
38403
38421
  + * @throws {Error} If milliseconds is negative
38404
38422
  + * @returns Promise that resolves after the specified duration
38405
- + */ const utils_sleep = (milliseconds)=>{
38423
+ + */ const src_utils_sleep = (milliseconds)=>{
38406
38424
  if (milliseconds < 0) throw new Error('Sleep duration must be non-negative');
38407
38425
  return new Promise((resolve)=>setTimeout(resolve, milliseconds));
38408
38426
  };