@coze/realtime-api 1.0.4 → 1.0.5-alpha.126a93

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/index.js CHANGED
@@ -1,10 +1,17 @@
1
1
  /*! For license information please see index.js.LICENSE.txt */
2
2
  var __webpack_modules__ = {
3
- "?e272": function() {
3
+ "../../common/temp/default/node_modules/.pnpm/ws@8.18.0/node_modules/ws/browser.js": function(module) {
4
+ module.exports = function() {
5
+ throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object");
6
+ };
7
+ },
8
+ "?666e": function() {
4
9
  /* (ignored) */ },
5
- "?5742": function() {
10
+ "?79fd": function() {
6
11
  /* (ignored) */ },
7
- "?9caf": function() {
12
+ "?8dee": function() {
13
+ /* (ignored) */ },
14
+ "?9050": function() {
8
15
  /* (ignored) */ }
9
16
  };
10
17
  /************************************************************************/ // The module cache
@@ -23,7 +30,22 @@ function __webpack_require__(moduleId) {
23
30
  // Return the exports of the module
24
31
  return module.exports;
25
32
  }
26
- /************************************************************************/ // webpack/runtime/define_property_getters
33
+ /************************************************************************/ // webpack/runtime/compat_get_default_export
34
+ (()=>{
35
+ // getDefaultExport function for compatibility with non-ESM modules
36
+ __webpack_require__.n = function(module) {
37
+ var getter = module && module.__esModule ? function() {
38
+ return module['default'];
39
+ } : function() {
40
+ return module;
41
+ };
42
+ __webpack_require__.d(getter, {
43
+ a: getter
44
+ });
45
+ return getter;
46
+ };
47
+ })();
48
+ // webpack/runtime/define_property_getters
27
49
  (()=>{
28
50
  __webpack_require__.d = function(exports, definition) {
29
51
  for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) Object.defineProperty(exports, key, {
@@ -80,479 +102,1037 @@ __webpack_require__.d(src_utils_namespaceObject, {
80
102
  getAudioDevices: ()=>getAudioDevices,
81
103
  isScreenShareDevice: ()=>isScreenShareDevice,
82
104
  isScreenShareSupported: ()=>isScreenShareSupported,
83
- sleep: ()=>utils_sleep
105
+ sleep: ()=>src_utils_sleep
84
106
  });
85
- function bind(fn, thisArg) {
86
- return function() {
87
- return fn.apply(thisArg, arguments);
88
- };
107
+ class APIResource {
108
+ constructor(client){
109
+ this._client = client;
110
+ }
89
111
  }
90
- // utils is a library of generic helper functions non-specific to axios
91
- const { toString: utils_toString } = Object.prototype;
92
- const { getPrototypeOf } = Object;
93
- const kindOf = ((cache)=>(thing)=>{
94
- const str = utils_toString.call(thing);
95
- return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
96
- })(Object.create(null));
97
- const kindOfTest = (type)=>{
98
- type = type.toLowerCase();
99
- return (thing)=>kindOf(thing) === type;
100
- };
101
- const typeOfTest = (type)=>(thing)=>typeof thing === type;
102
- /**
103
- * Determine if a value is an Array
104
- *
105
- * @param {Object} val The value to test
106
- *
107
- * @returns {boolean} True if value is an Array, otherwise false
108
- */ const { isArray } = Array;
109
- /**
110
- * Determine if a value is undefined
111
- *
112
- * @param {*} val The value to test
113
- *
114
- * @returns {boolean} True if the value is undefined, otherwise false
115
- */ const isUndefined = typeOfTest('undefined');
116
- /**
117
- * Determine if a value is a Buffer
118
- *
119
- * @param {*} val The value to test
120
- *
121
- * @returns {boolean} True if value is a Buffer, otherwise false
122
- */ function isBuffer(val) {
123
- return null !== val && !isUndefined(val) && null !== val.constructor && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
112
+ /* eslint-disable @typescript-eslint/no-namespace */ class Bots extends APIResource {
113
+ /**
114
+ * Create a new agent. | 调用接口创建一个新的智能体。
115
+ * @docs en:https://www.coze.com/docs/developer_guides/create_bot?_lang=en
116
+ * @docs zh:https://www.coze.cn/docs/developer_guides/create_bot?_lang=zh
117
+ * @param params - Required The parameters for creating a bot. | 创建 Bot 的参数。
118
+ * @param params.space_id - Required The Space ID of the space where the agent is located. | Bot 所在的空间的 Space ID。
119
+ * @param params.name - Required The name of the agent. It should be 1 to 20 characters long. | Bot 的名称。
120
+ * @param params.description - Optional The description of the agent. It can be 0 to 500 characters long. | Bot 的描述信息。
121
+ * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
122
+ * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
123
+ * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
124
+ * @returns Information about the created bot. | 创建的 Bot 信息。
125
+ */ async create(params, options) {
126
+ const apiUrl = '/v1/bot/create';
127
+ const result = await this._client.post(apiUrl, params, false, options);
128
+ return result.data;
129
+ }
130
+ /**
131
+ * Update the configuration of an agent. | 调用接口修改智能体的配置。
132
+ * @docs en:https://www.coze.com/docs/developer_guides/update_bot?_lang=en
133
+ * @docs zh:https://www.coze.cn/docs/developer_guides/update_bot?_lang=zh
134
+ * @param params - Required The parameters for updating a bot. | 修改 Bot 的参数。
135
+ * @param params.bot_id - Required The ID of the agent that the API interacts with. | 待修改配置的智能体ID。
136
+ * @param params.name - Optional The name of the agent. | Bot 的名称。
137
+ * @param params.description - Optional The description of the agent. | Bot 的描述信息。
138
+ * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
139
+ * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
140
+ * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
141
+ * @param params.knowledge - Optional Knowledge configurations of the agent. | Bot 的知识库配置。
142
+ * @returns Undefined | 无返回值
143
+ */ async update(params, options) {
144
+ const apiUrl = '/v1/bot/update';
145
+ const result = await this._client.post(apiUrl, params, false, options);
146
+ return result.data;
147
+ }
148
+ /**
149
+ * Get the agents published as API service. | 调用接口查看指定空间发布到 Agent as API 渠道的智能体列表。
150
+ * @docs en:https://www.coze.com/docs/developer_guides/published_bots_list?_lang=en
151
+ * @docs zh:https://www.coze.cn/docs/developer_guides/published_bots_list?_lang=zh
152
+ * @param params - Required The parameters for listing bots. | 列出 Bot 的参数。
153
+ * @param params.space_id - Required The ID of the space. | Bot 所在的空间的 Space ID。
154
+ * @param params.page_size - Optional Pagination size. | 分页大小。
155
+ * @param params.page_index - Optional Page number for paginated queries. | 分页查询时的页码。
156
+ * @returns List of published bots. | 已发布的 Bot 列表。
157
+ */ async list(params, options) {
158
+ const apiUrl = '/v1/space/published_bots_list';
159
+ const result = await this._client.get(apiUrl, params, false, options);
160
+ return result.data;
161
+ }
162
+ /**
163
+ * Publish the specified agent as an API service. | 调用接口创建一个新的智能体。
164
+ * @docs en:https://www.coze.com/docs/developer_guides/publish_bot?_lang=en
165
+ * @docs zh:https://www.coze.cn/docs/developer_guides/publish_bot?_lang=zh
166
+ * @param params - Required The parameters for publishing a bot. | 发布 Bot 的参数。
167
+ * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要发布的智能体ID。
168
+ * @param params.connector_ids - Required The list of publishing channel IDs for the agent. | 智能体的发布渠道 ID 列表。
169
+ * @returns Undefined | 无返回值
170
+ */ async publish(params, options) {
171
+ const apiUrl = '/v1/bot/publish';
172
+ const result = await this._client.post(apiUrl, params, false, options);
173
+ return result.data;
174
+ }
175
+ /**
176
+ * Get the configuration information of the agent. | 获取指定智能体的配置信息。
177
+ * @docs en:https://www.coze.com/docs/developer_guides/get_metadata?_lang=en
178
+ * @docs zh:https://www.coze.cn/docs/developer_guides/get_metadata?_lang=zh
179
+ * @param params - Required The parameters for retrieving a bot. | 获取 Bot 的参数。
180
+ * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要查看的智能体ID。
181
+ * @returns Information about the bot. | Bot 的配置信息。
182
+ */ async retrieve(params, options) {
183
+ const apiUrl = '/v1/bot/get_online_info';
184
+ const result = await this._client.get(apiUrl, params, false, options);
185
+ return result.data;
186
+ }
124
187
  }
125
- /**
126
- * Determine if a value is an ArrayBuffer
127
- *
128
- * @param {*} val The value to test
129
- *
130
- * @returns {boolean} True if value is an ArrayBuffer, otherwise false
131
- */ const isArrayBuffer = kindOfTest('ArrayBuffer');
132
- /**
133
- * Determine if a value is a view on an ArrayBuffer
134
- *
135
- * @param {*} val The value to test
136
- *
137
- * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
138
- */ function isArrayBufferView(val) {
139
- let result;
140
- result = 'undefined' != typeof ArrayBuffer && ArrayBuffer.isView ? ArrayBuffer.isView(val) : val && val.buffer && isArrayBuffer(val.buffer);
141
- return result;
188
+ /* eslint-disable security/detect-object-injection */ /* eslint-disable @typescript-eslint/no-explicit-any */ function safeJsonParse(jsonString) {
189
+ let defaultValue = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : '';
190
+ try {
191
+ return JSON.parse(jsonString);
192
+ } catch (error) {
193
+ return defaultValue;
194
+ }
142
195
  }
143
- /**
144
- * Determine if a value is a String
145
- *
146
- * @param {*} val The value to test
147
- *
148
- * @returns {boolean} True if value is a String, otherwise false
149
- */ const isString = typeOfTest('string');
150
- /**
151
- * Determine if a value is a Function
152
- *
153
- * @param {*} val The value to test
154
- * @returns {boolean} True if value is a Function, otherwise false
155
- */ const isFunction = typeOfTest('function');
156
- /**
157
- * Determine if a value is a Number
158
- *
159
- * @param {*} val The value to test
160
- *
161
- * @returns {boolean} True if value is a Number, otherwise false
162
- */ const isNumber = typeOfTest('number');
163
- /**
164
- * Determine if a value is an Object
165
- *
166
- * @param {*} thing The value to test
167
- *
168
- * @returns {boolean} True if value is an Object, otherwise false
169
- */ const isObject = (thing)=>null !== thing && 'object' == typeof thing;
170
- /**
171
- * Determine if a value is a Boolean
172
- *
173
- * @param {*} thing The value to test
174
- * @returns {boolean} True if value is a Boolean, otherwise false
175
- */ const isBoolean = (thing)=>true === thing || false === thing;
176
- /**
177
- * Determine if a value is a plain Object
178
- *
179
- * @param {*} val The value to test
180
- *
181
- * @returns {boolean} True if value is a plain Object, otherwise false
182
- */ const isPlainObject = (val)=>{
183
- if ('object' !== kindOf(val)) return false;
184
- const prototype = getPrototypeOf(val);
185
- return (null === prototype || prototype === Object.prototype || null === Object.getPrototypeOf(prototype)) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
186
- };
187
- /**
188
- * Determine if a value is a Date
189
- *
190
- * @param {*} val The value to test
191
- *
192
- * @returns {boolean} True if value is a Date, otherwise false
193
- */ const isDate = kindOfTest('Date');
194
- /**
195
- * Determine if a value is a File
196
- *
197
- * @param {*} val The value to test
198
- *
199
- * @returns {boolean} True if value is a File, otherwise false
200
- */ const isFile = kindOfTest('File');
201
- /**
202
- * Determine if a value is a Blob
203
- *
204
- * @param {*} val The value to test
205
- *
206
- * @returns {boolean} True if value is a Blob, otherwise false
207
- */ const isBlob = kindOfTest('Blob');
208
- /**
209
- * Determine if a value is a FileList
210
- *
211
- * @param {*} val The value to test
212
- *
213
- * @returns {boolean} True if value is a File, otherwise false
214
- */ const utils_isFileList = kindOfTest('FileList');
215
- /**
216
- * Determine if a value is a Stream
217
- *
218
- * @param {*} val The value to test
219
- *
220
- * @returns {boolean} True if value is a Stream, otherwise false
221
- */ const utils_isStream = (val)=>isObject(val) && isFunction(val.pipe);
222
- /**
223
- * Determine if a value is a FormData
224
- *
225
- * @param {*} thing The value to test
226
- *
227
- * @returns {boolean} True if value is an FormData, otherwise false
228
- */ const utils_isFormData = (thing)=>{
229
- let kind;
230
- return thing && ('function' == typeof FormData && thing instanceof FormData || isFunction(thing.append) && ('formdata' === (kind = kindOf(thing)) || // detect form-data instance
231
- 'object' === kind && isFunction(thing.toString) && '[object FormData]' === thing.toString()));
232
- };
233
- /**
234
- * Determine if a value is a URLSearchParams object
235
- *
236
- * @param {*} val The value to test
237
- *
238
- * @returns {boolean} True if value is a URLSearchParams object, otherwise false
239
- */ const isURLSearchParams = kindOfTest('URLSearchParams');
240
- const [isReadableStream, isRequest, isResponse, isHeaders] = [
241
- 'ReadableStream',
242
- 'Request',
243
- 'Response',
244
- 'Headers'
245
- ].map(kindOfTest);
246
- /**
247
- * Trim excess whitespace off the beginning and end of a string
248
- *
249
- * @param {String} str The String to trim
250
- *
251
- * @returns {String} The String freed of excess whitespace
252
- */ const trim = (str)=>str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
253
- /**
254
- * Iterate over an Array or an Object invoking a function for each item.
255
- *
256
- * If `obj` is an Array callback will be called passing
257
- * the value, index, and complete array for each item.
258
- *
259
- * If 'obj' is an Object callback will be called passing
260
- * the value, key, and complete object for each property.
261
- *
262
- * @param {Object|Array} obj The object to iterate
263
- * @param {Function} fn The callback to invoke for each item
264
- *
265
- * @param {Boolean} [allOwnKeys = false]
266
- * @returns {any}
267
- */ function forEach(obj, fn, { allOwnKeys = false } = {}) {
268
- // Don't bother if no value provided
269
- if (null == obj) return;
270
- let i;
271
- let l;
272
- // Force an array if not already something iterable
273
- if ('object' != typeof obj) /*eslint no-param-reassign:0*/ obj = [
274
- obj
275
- ];
276
- if (isArray(obj)) // Iterate over array values
277
- for(i = 0, l = obj.length; i < l; i++)fn.call(null, obj[i], i, obj);
278
- else {
279
- // Iterate over object keys
280
- const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
281
- const len = keys.length;
282
- let key;
283
- for(i = 0; i < len; i++){
284
- key = keys[i];
285
- fn.call(null, obj[key], key, obj);
196
+ function utils_sleep(ms) {
197
+ return new Promise((resolve)=>{
198
+ setTimeout(resolve, ms);
199
+ });
200
+ }
201
+ function utils_isBrowser() {
202
+ return 'undefined' != typeof window;
203
+ }
204
+ function isPlainObject(obj) {
205
+ if ('object' != typeof obj || null === obj) return false;
206
+ const proto = Object.getPrototypeOf(obj);
207
+ if (null === proto) return true;
208
+ let baseProto = proto;
209
+ while(null !== Object.getPrototypeOf(baseProto))baseProto = Object.getPrototypeOf(baseProto);
210
+ return proto === baseProto;
211
+ }
212
+ function mergeConfig() {
213
+ for(var _len = arguments.length, objects = new Array(_len), _key = 0; _key < _len; _key++)objects[_key] = arguments[_key];
214
+ return objects.reduce((result, obj)=>{
215
+ if (void 0 === obj) return result || {};
216
+ for(const key in obj)if (Object.prototype.hasOwnProperty.call(obj, key)) {
217
+ if (isPlainObject(obj[key]) && !Array.isArray(obj[key])) result[key] = mergeConfig(result[key] || {}, obj[key]);
218
+ else result[key] = obj[key];
219
+ }
220
+ return result;
221
+ }, {});
222
+ }
223
+ function isPersonalAccessToken(token) {
224
+ return null == token ? void 0 : token.startsWith('pat_');
225
+ }
226
+ /* eslint-disable max-params */ class CozeError extends Error {
227
+ }
228
+ class error_APIError extends CozeError {
229
+ static makeMessage(status, errorBody, message, headers) {
230
+ if (!errorBody && message) return message;
231
+ if (errorBody) {
232
+ const list = [];
233
+ const { code, msg, error } = errorBody;
234
+ if (code) list.push(`code: ${code}`);
235
+ if (msg) list.push(`msg: ${msg}`);
236
+ if ((null == error ? void 0 : error.detail) && msg !== error.detail) list.push(`detail: ${error.detail}`);
237
+ const logId = (null == error ? void 0 : error.logid) || (null == headers ? void 0 : headers['x-tt-logid']);
238
+ if (logId) list.push(`logid: ${logId}`);
239
+ return list.join(', ');
286
240
  }
241
+ if (status) return `http status code: ${status} (no body)`;
242
+ return '(no status code or body)';
243
+ }
244
+ static generate(status, errorResponse, message, headers) {
245
+ if (!status) return new APIConnectionError({
246
+ cause: castToError(errorResponse)
247
+ });
248
+ const error = errorResponse;
249
+ // https://www.coze.cn/docs/developer_guides/coze_error_codes
250
+ if (400 === status || (null == error ? void 0 : error.code) === 4000) return new BadRequestError(status, error, message, headers);
251
+ if (401 === status || (null == error ? void 0 : error.code) === 4100) return new AuthenticationError(status, error, message, headers);
252
+ if (403 === status || (null == error ? void 0 : error.code) === 4101) return new PermissionDeniedError(status, error, message, headers);
253
+ if (404 === status || (null == error ? void 0 : error.code) === 4200) return new NotFoundError(status, error, message, headers);
254
+ if (429 === status || (null == error ? void 0 : error.code) === 4013) return new RateLimitError(status, error, message, headers);
255
+ if (408 === status) return new TimeoutError(status, error, message, headers);
256
+ if (502 === status) return new GatewayError(status, error, message, headers);
257
+ if (status >= 500) return new InternalServerError(status, error, message, headers);
258
+ return new error_APIError(status, error, message, headers);
259
+ }
260
+ constructor(status, error, message, headers){
261
+ var _error_detail, _error_error;
262
+ super(`${error_APIError.makeMessage(status, error, message, headers)}`);
263
+ this.status = status;
264
+ this.headers = headers;
265
+ this.logid = (null == error ? void 0 : null === (_error_detail = error.detail) || void 0 === _error_detail ? void 0 : _error_detail.logid) || (null == headers ? void 0 : headers['x-tt-logid']);
266
+ // this.error = error;
267
+ this.code = null == error ? void 0 : error.code;
268
+ this.msg = null == error ? void 0 : error.msg;
269
+ this.detail = null == error ? void 0 : null === (_error_error = error.error) || void 0 === _error_error ? void 0 : _error_error.detail;
270
+ this.rawError = error;
287
271
  }
288
272
  }
289
- function findKey(obj, key) {
290
- key = key.toLowerCase();
291
- const keys = Object.keys(obj);
292
- let i = keys.length;
293
- let _key;
294
- while(i-- > 0){
295
- _key = keys[i];
296
- if (key === _key.toLowerCase()) return _key;
273
+ class APIConnectionError extends error_APIError {
274
+ constructor({ message }){
275
+ super(void 0, void 0, message || 'Connection error.', void 0), this.status = void 0;
276
+ // if (cause) {
277
+ // this.cause = cause;
278
+ // }
297
279
  }
298
- return null;
299
280
  }
300
- const _global = (()=>{
301
- /*eslint no-undef:0*/ if ("undefined" != typeof globalThis) return globalThis;
302
- return "undefined" != typeof self ? self : 'undefined' != typeof window ? window : global;
303
- })();
304
- const isContextDefined = (context)=>!isUndefined(context) && context !== _global;
305
- /**
306
- * Accepts varargs expecting each argument to be an object, then
307
- * immutably merges the properties of each object and returns result.
308
- *
309
- * When multiple objects contain the same key the later object in
310
- * the arguments list will take precedence.
311
- *
312
- * Example:
313
- *
314
- * ```js
315
- * var result = merge({foo: 123}, {foo: 456});
316
- * console.log(result.foo); // outputs 456
317
- * ```
318
- *
319
- * @param {Object} obj1 Object to merge
320
- *
321
- * @returns {Object} Result of all merge properties
322
- */ function utils_merge() {
323
- const { caseless } = isContextDefined(this) && this || {};
324
- const result = {};
325
- const assignValue = (val, key)=>{
326
- const targetKey = caseless && findKey(result, key) || key;
327
- if (isPlainObject(result[targetKey]) && isPlainObject(val)) result[targetKey] = utils_merge(result[targetKey], val);
328
- else if (isPlainObject(val)) result[targetKey] = utils_merge({}, val);
329
- else if (isArray(val)) result[targetKey] = val.slice();
330
- else result[targetKey] = val;
331
- };
332
- for(let i = 0, l = arguments.length; i < l; i++)arguments[i] && forEach(arguments[i], assignValue);
333
- return result;
281
+ class APIUserAbortError extends error_APIError {
282
+ constructor(message){
283
+ super(void 0, void 0, message || 'Request was aborted.', void 0), this.name = 'UserAbortError', this.status = void 0;
284
+ }
334
285
  }
335
- /**
336
- * Extends object a by mutably adding to it the properties of object b.
337
- *
338
- * @param {Object} a The object to be extended
339
- * @param {Object} b The object to copy properties from
340
- * @param {Object} thisArg The object to bind function to
341
- *
342
- * @param {Boolean} [allOwnKeys]
343
- * @returns {Object} The resulting value of object a
344
- */ const extend = (a, b, thisArg, { allOwnKeys } = {})=>{
345
- forEach(b, (val, key)=>{
346
- if (thisArg && isFunction(val)) a[key] = bind(val, thisArg);
347
- else a[key] = val;
348
- }, {
349
- allOwnKeys
350
- });
351
- return a;
352
- };
353
- /**
354
- * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
355
- *
356
- * @param {string} content with BOM
357
- *
358
- * @returns {string} content value without BOM
359
- */ const stripBOM = (content)=>{
360
- if (0xFEFF === content.charCodeAt(0)) content = content.slice(1);
361
- return content;
362
- };
363
- /**
364
- * Inherit the prototype methods from one constructor into another
365
- * @param {function} constructor
366
- * @param {function} superConstructor
367
- * @param {object} [props]
368
- * @param {object} [descriptors]
369
- *
370
- * @returns {void}
371
- */ const inherits = (constructor, superConstructor, props, descriptors)=>{
372
- constructor.prototype = Object.create(superConstructor.prototype, descriptors);
373
- constructor.prototype.constructor = constructor;
374
- Object.defineProperty(constructor, 'super', {
375
- value: superConstructor.prototype
376
- });
377
- props && Object.assign(constructor.prototype, props);
378
- };
379
- /**
380
- * Resolve object with deep prototype chain to a flat object
381
- * @param {Object} sourceObj source object
382
- * @param {Object} [destObj]
383
- * @param {Function|Boolean} [filter]
384
- * @param {Function} [propFilter]
385
- *
386
- * @returns {Object}
387
- */ const toFlatObject = (sourceObj, destObj, filter, propFilter)=>{
388
- let props;
389
- let i;
390
- let prop;
391
- const merged = {};
392
- destObj = destObj || {};
393
- // eslint-disable-next-line no-eq-null,eqeqeq
394
- if (null == sourceObj) return destObj;
395
- do {
396
- props = Object.getOwnPropertyNames(sourceObj);
397
- i = props.length;
398
- while(i-- > 0){
399
- prop = props[i];
400
- if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
401
- destObj[prop] = sourceObj[prop];
402
- merged[prop] = true;
403
- }
404
- }
405
- sourceObj = false !== filter && getPrototypeOf(sourceObj);
406
- }while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
407
- return destObj;
286
+ class BadRequestError extends error_APIError {
287
+ constructor(...args){
288
+ super(...args), this.name = 'BadRequestError', this.status = 400;
289
+ }
290
+ }
291
+ class AuthenticationError extends error_APIError {
292
+ constructor(...args){
293
+ super(...args), this.name = 'AuthenticationError', this.status = 401;
294
+ }
295
+ }
296
+ class PermissionDeniedError extends error_APIError {
297
+ constructor(...args){
298
+ super(...args), this.name = 'PermissionDeniedError', this.status = 403;
299
+ }
300
+ }
301
+ class NotFoundError extends error_APIError {
302
+ constructor(...args){
303
+ super(...args), this.name = 'NotFoundError', this.status = 404;
304
+ }
305
+ }
306
+ class TimeoutError extends error_APIError {
307
+ constructor(...args){
308
+ super(...args), this.name = 'TimeoutError', this.status = 408;
309
+ }
310
+ }
311
+ class RateLimitError extends error_APIError {
312
+ constructor(...args){
313
+ super(...args), this.name = 'RateLimitError', this.status = 429;
314
+ }
315
+ }
316
+ class InternalServerError extends error_APIError {
317
+ constructor(...args){
318
+ super(...args), this.name = 'InternalServerError', this.status = 500;
319
+ }
320
+ }
321
+ class GatewayError extends error_APIError {
322
+ constructor(...args){
323
+ super(...args), this.name = 'GatewayError', this.status = 502;
324
+ }
325
+ }
326
+ const castToError = (err)=>{
327
+ if (err instanceof Error) return err;
328
+ return new Error(err);
408
329
  };
409
- /**
410
- * Determines whether a string ends with the characters of a specified string
330
+ class Messages extends APIResource {
331
+ /**
332
+ * Get the list of messages in a chat. | 获取对话中的消息列表。
333
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_message_list?_lang=en
334
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_message_list?_lang=zh
335
+ * @param conversation_id - Required The ID of the conversation. | 会话 ID。
336
+ * @param chat_id - Required The ID of the chat. | 对话 ID。
337
+ * @returns An array of chat messages. | 对话消息数组。
338
+ */ async list(conversation_id, chat_id, options) {
339
+ const apiUrl = `/v3/chat/message/list?conversation_id=${conversation_id}&chat_id=${chat_id}`;
340
+ const result = await this._client.get(apiUrl, void 0, false, options);
341
+ return result.data;
342
+ }
343
+ }
344
+ const uuid = ()=>(Math.random() * new Date().getTime()).toString();
345
+ const handleAdditionalMessages = (additional_messages)=>null == additional_messages ? void 0 : additional_messages.map((i)=>({
346
+ ...i,
347
+ content: 'object' == typeof i.content ? JSON.stringify(i.content) : i.content
348
+ }));
349
+ class Chat extends APIResource {
350
+ /**
351
+ * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
352
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
353
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
354
+ * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
355
+ * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
356
+ * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
357
+ * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
358
+ * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义变量。
359
+ * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
360
+ * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
361
+ * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
362
+ * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
363
+ * @returns The data of the created chat. | 创建的对话数据。
364
+ */ async create(params, options) {
365
+ if (!params.user_id) params.user_id = uuid();
366
+ const { conversation_id, ...rest } = params;
367
+ const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
368
+ const payload = {
369
+ ...rest,
370
+ additional_messages: handleAdditionalMessages(params.additional_messages),
371
+ stream: false
372
+ };
373
+ const result = await this._client.post(apiUrl, payload, false, options);
374
+ return result.data;
375
+ }
376
+ /**
377
+ * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
378
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
379
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
380
+ * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
381
+ * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
382
+ * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
383
+ * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
384
+ * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
385
+ * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
386
+ * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
387
+ * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
388
+ * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
389
+ * @returns
390
+ */ async createAndPoll(params, options) {
391
+ if (!params.user_id) params.user_id = uuid();
392
+ const { conversation_id, ...rest } = params;
393
+ const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
394
+ const payload = {
395
+ ...rest,
396
+ additional_messages: handleAdditionalMessages(params.additional_messages),
397
+ stream: false
398
+ };
399
+ const result = await this._client.post(apiUrl, payload, false, options);
400
+ const chatId = result.data.id;
401
+ const conversationId = result.data.conversation_id;
402
+ let chat;
403
+ while(true){
404
+ await utils_sleep(100);
405
+ chat = await this.retrieve(conversationId, chatId);
406
+ if ('completed' === chat.status || 'failed' === chat.status || 'requires_action' === chat.status) break;
407
+ }
408
+ const messageList = await this.messages.list(conversationId, chatId);
409
+ return {
410
+ chat,
411
+ messages: messageList
412
+ };
413
+ }
414
+ /**
415
+ * Call the Chat API to send messages to a published Coze agent with streaming response. | 调用此接口发起一次对话,支持流式响应。
416
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
417
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
418
+ * @param params - Required The parameters for streaming a chat session. | 流式会话的参数。
419
+ * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
420
+ * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
421
+ * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
422
+ * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
423
+ * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
424
+ * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
425
+ * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
426
+ * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
427
+ * @returns A stream of chat data. | 对话数据流。
428
+ */ async *stream(params, options) {
429
+ if (!params.user_id) params.user_id = uuid();
430
+ const { conversation_id, ...rest } = params;
431
+ const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
432
+ const payload = {
433
+ ...rest,
434
+ additional_messages: handleAdditionalMessages(params.additional_messages),
435
+ stream: true
436
+ };
437
+ const result = await this._client.post(apiUrl, payload, true, options);
438
+ for await (const message of result)if ("done" === message.event) {
439
+ const ret = {
440
+ event: message.event,
441
+ data: '[DONE]'
442
+ };
443
+ yield ret;
444
+ } else try {
445
+ const ret = {
446
+ event: message.event,
447
+ data: JSON.parse(message.data)
448
+ };
449
+ yield ret;
450
+ } catch (error) {
451
+ throw new CozeError(`Could not parse message into JSON:${message.data}`);
452
+ }
453
+ }
454
+ /**
455
+ * Get the detailed information of the chat. | 查看对话的详细信息。
456
+ * @docs en:https://www.coze.com/docs/developer_guides/retrieve_chat?_lang=en
457
+ * @docs zh:https://www.coze.cn/docs/developer_guides/retrieve_chat?_lang=zh
458
+ * @param conversation_id - Required The ID of the conversation. | 会话 ID。
459
+ * @param chat_id - Required The ID of the chat. | 对话 ID。
460
+ * @returns The data of the retrieved chat. | 检索到的对话数据。
461
+ */ async retrieve(conversation_id, chat_id, options) {
462
+ const apiUrl = `/v3/chat/retrieve?conversation_id=${conversation_id}&chat_id=${chat_id}`;
463
+ const result = await this._client.post(apiUrl, void 0, false, options);
464
+ return result.data;
465
+ }
466
+ /**
467
+ * Cancel a chat session. | 取消对话会话。
468
+ * @docs en:https://www.coze.com/docs/developer_guides/cancel_chat?_lang=en
469
+ * @docs zh:https://www.coze.cn/docs/developer_guides/cancel_chat?_lang=zh
470
+ * @param conversation_id - Required The ID of the conversation. | 会话 ID。
471
+ * @param chat_id - Required The ID of the chat. | 对话 ID。
472
+ * @returns The data of the canceled chat. | 取消的对话数据。
473
+ */ async cancel(conversation_id, chat_id, options) {
474
+ const apiUrl = '/v3/chat/cancel';
475
+ const payload = {
476
+ conversation_id,
477
+ chat_id
478
+ };
479
+ const result = await this._client.post(apiUrl, payload, false, options);
480
+ return result.data;
481
+ }
482
+ /**
483
+ * Submit tool outputs for a chat session. | 提交对话会话的工具输出。
484
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_submit_tool_outputs?_lang=en
485
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_submit_tool_outputs?_lang=zh
486
+ * @param params - Required Parameters for submitting tool outputs. | 提交工具输出的参数。
487
+ * @param params.conversation_id - Required The ID of the conversation. | 会话 ID。
488
+ * @param params.chat_id - Required The ID of the chat. | 对话 ID。
489
+ * @param params.tool_outputs - Required The outputs of the tool. | 工具的输出。
490
+ * @param params.stream - Optional Whether to use streaming response. | 是否使用流式响应。
491
+ * @returns The data of the submitted tool outputs or a stream of chat data. | 提交的工具输出数据或对话数据流。
492
+ */ async *submitToolOutputs(params, options) {
493
+ const { conversation_id, chat_id, ...rest } = params;
494
+ const apiUrl = `/v3/chat/submit_tool_outputs?conversation_id=${params.conversation_id}&chat_id=${params.chat_id}`;
495
+ const payload = {
496
+ ...rest
497
+ };
498
+ if (false === params.stream) {
499
+ const response = await this._client.post(apiUrl, payload, false, options);
500
+ return response.data;
501
+ }
502
+ {
503
+ const result = await this._client.post(apiUrl, payload, true, options);
504
+ for await (const message of result)if ("done" === message.event) {
505
+ const ret = {
506
+ event: message.event,
507
+ data: '[DONE]'
508
+ };
509
+ yield ret;
510
+ } else try {
511
+ const ret = {
512
+ event: message.event,
513
+ data: JSON.parse(message.data)
514
+ };
515
+ yield ret;
516
+ } catch (error) {
517
+ throw new CozeError(`Could not parse message into JSON:${message.data}`);
518
+ }
519
+ }
520
+ }
521
+ constructor(...args){
522
+ super(...args), this.messages = new Messages(this._client);
523
+ }
524
+ }
525
+ var chat_ChatEventType = /*#__PURE__*/ function(ChatEventType) {
526
+ ChatEventType["CONVERSATION_CHAT_CREATED"] = "conversation.chat.created";
527
+ ChatEventType["CONVERSATION_CHAT_IN_PROGRESS"] = "conversation.chat.in_progress";
528
+ ChatEventType["CONVERSATION_CHAT_COMPLETED"] = "conversation.chat.completed";
529
+ ChatEventType["CONVERSATION_CHAT_FAILED"] = "conversation.chat.failed";
530
+ ChatEventType["CONVERSATION_CHAT_REQUIRES_ACTION"] = "conversation.chat.requires_action";
531
+ ChatEventType["CONVERSATION_MESSAGE_DELTA"] = "conversation.message.delta";
532
+ ChatEventType["CONVERSATION_MESSAGE_COMPLETED"] = "conversation.message.completed";
533
+ ChatEventType["CONVERSATION_AUDIO_DELTA"] = "conversation.audio.delta";
534
+ ChatEventType["DONE"] = "done";
535
+ ChatEventType["ERROR"] = "error";
536
+ return ChatEventType;
537
+ }({});
538
+ class messages_Messages extends APIResource {
539
+ /**
540
+ * Create a message and add it to the specified conversation. | 创建一条消息,并将其添加到指定的会话中。
541
+ * @docs en: https://www.coze.com/docs/developer_guides/create_message?_lang=en
542
+ * @docs zh: https://www.coze.cn/docs/developer_guides/create_message?_lang=zh
543
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
544
+ * @param params - Required The parameters for creating a message | 创建消息所需的参数
545
+ * @param params.role - Required The entity that sent this message. Possible values: user, assistant. | 发送这条消息的实体。取值:user, assistant。
546
+ * @param params.content - Required The content of the message. | 消息的内容。
547
+ * @param params.content_type - Required The type of the message content. | 消息内容的类型。
548
+ * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
549
+ * @returns Information about the new message. | 消息详情。
550
+ */ async create(conversation_id, params, options) {
551
+ const apiUrl = `/v1/conversation/message/create?conversation_id=${conversation_id}`;
552
+ const response = await this._client.post(apiUrl, params, false, options);
553
+ return response.data;
554
+ }
555
+ /**
556
+ * Modify a message, supporting the modification of message content, additional content, and message type. | 修改一条消息,支持修改消息内容、附加内容和消息类型。
557
+ * @docs en: https://www.coze.com/docs/developer_guides/modify_message?_lang=en
558
+ * @docs zh: https://www.coze.cn/docs/developer_guides/modify_message?_lang=zh
559
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
560
+ * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
561
+ * @param params - Required The parameters for modifying a message | 修改消息所需的参数
562
+ * @param params.meta_data - Optional Additional information when modifying a message. | 修改消息时的附加消息。
563
+ * @param params.content - Optional The content of the message. | 消息的内容。
564
+ * @param params.content_type - Optional The type of the message content. | 消息内容的类型。
565
+ * @returns Information about the modified message. | 消息详情。
566
+ */ // eslint-disable-next-line max-params
567
+ async update(conversation_id, message_id, params, options) {
568
+ const apiUrl = `/v1/conversation/message/modify?conversation_id=${conversation_id}&message_id=${message_id}`;
569
+ const response = await this._client.post(apiUrl, params, false, options);
570
+ return response.message;
571
+ }
572
+ /**
573
+ * Get the detailed information of specified message. | 查看指定消息的详细信息。
574
+ * @docs en: https://www.coze.com/docs/developer_guides/retrieve_message?_lang=en
575
+ * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_message?_lang=zh
576
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
577
+ * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
578
+ * @returns Information about the message. | 消息详情。
579
+ */ async retrieve(conversation_id, message_id, options) {
580
+ const apiUrl = `/v1/conversation/message/retrieve?conversation_id=${conversation_id}&message_id=${message_id}`;
581
+ const response = await this._client.get(apiUrl, null, false, options);
582
+ return response.data;
583
+ }
584
+ /**
585
+ * List messages in a conversation. | 列出会话中的消息。
586
+ * @docs en: https://www.coze.com/docs/developer_guides/message_list?_lang=en
587
+ * @docs zh: https://www.coze.cn/docs/developer_guides/message_list?_lang=zh
588
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
589
+ * @param params - Optional The parameters for listing messages | 列出消息所需的参数
590
+ * @param params.order - Optional The order of the messages. | 消息的顺序。
591
+ * @param params.chat_id - Optional The ID of the chat. | 聊天 ID。
592
+ * @param params.before_id - Optional The ID of the message before which to list. | 列出此消息之前的消息 ID。
593
+ * @param params.after_id - Optional The ID of the message after which to list. | 列出此消息之后的消息 ID。
594
+ * @param params.limit - Optional The maximum number of messages to return. | 返回的最大消息数。
595
+ * @returns A list of messages. | 消息列表。
596
+ */ async list(conversation_id, params, options) {
597
+ const apiUrl = `/v1/conversation/message/list?conversation_id=${conversation_id}`;
598
+ const response = await this._client.post(apiUrl, params, false, options);
599
+ return response;
600
+ }
601
+ /**
602
+ * Call the API to delete a message within a specified conversation. | 调用接口在指定会话中删除消息。
603
+ * @docs en: https://www.coze.com/docs/developer_guides/delete_message?_lang=en
604
+ * @docs zh: https://www.coze.cn/docs/developer_guides/delete_message?_lang=zh
605
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
606
+ * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
607
+ * @returns Details of the deleted message. | 已删除的消息详情。
608
+ */ async delete(conversation_id, message_id, options) {
609
+ const apiUrl = `/v1/conversation/message/delete?conversation_id=${conversation_id}&message_id=${message_id}`;
610
+ const response = await this._client.post(apiUrl, void 0, false, options);
611
+ return response.data;
612
+ }
613
+ }
614
+ class Conversations extends APIResource {
615
+ /**
616
+ * Create a conversation. Conversation is an interaction between an agent and a user, including one or more messages. | 调用接口创建一个会话。
617
+ * @docs en: https://www.coze.com/docs/developer_guides/create_conversation?_lang=en
618
+ * @docs zh: https://www.coze.cn/docs/developer_guides/create_conversation?_lang=zh
619
+ * @param params - Required The parameters for creating a conversation | 创建会话所需的参数
620
+ * @param params.messages - Optional Messages in the conversation. | 会话中的消息内容。
621
+ * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
622
+ * @param params.bot_id - Optional Bind and isolate conversation on different bots. | 绑定和隔离不同Bot的会话。
623
+ * @returns Information about the created conversation. | 会话的基础信息。
624
+ */ async create(params, options) {
625
+ const apiUrl = '/v1/conversation/create';
626
+ const response = await this._client.post(apiUrl, params, false, options);
627
+ return response.data;
628
+ }
629
+ /**
630
+ * Get the information of specific conversation. | 通过会话 ID 查看会话信息。
631
+ * @docs en: https://www.coze.com/docs/developer_guides/retrieve_conversation?_lang=en
632
+ * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_conversation?_lang=zh
633
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
634
+ * @returns Information about the conversation. | 会话的基础信息。
635
+ */ async retrieve(conversation_id, options) {
636
+ const apiUrl = `/v1/conversation/retrieve?conversation_id=${conversation_id}`;
637
+ const response = await this._client.get(apiUrl, null, false, options);
638
+ return response.data;
639
+ }
640
+ /**
641
+ * List all conversations. | 列出 Bot 下所有会话。
642
+ * @param params
643
+ * @param params.bot_id - Required Bot ID. | Bot ID。
644
+ * @param params.page_num - Optional The page number. | 页码,默认值为 1。
645
+ * @param params.page_size - Optional The number of conversations per page. | 每页的会话数量,默认值为 50。
646
+ * @returns Information about the conversations. | 会话的信息。
647
+ */ async list(params, options) {
648
+ const apiUrl = '/v1/conversations';
649
+ const response = await this._client.get(apiUrl, params, false, options);
650
+ return response.data;
651
+ }
652
+ /**
653
+ * Clear a conversation. | 清空会话。
654
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
655
+ * @returns Information about the conversation session. | 会话的会话 ID。
656
+ */ async clear(conversation_id, options) {
657
+ const apiUrl = `/v1/conversations/${conversation_id}/clear`;
658
+ const response = await this._client.post(apiUrl, null, false, options);
659
+ return response.data;
660
+ }
661
+ constructor(...args){
662
+ super(...args), this.messages = new messages_Messages(this._client);
663
+ }
664
+ }
665
+ function bind(fn, thisArg) {
666
+ return function() {
667
+ return fn.apply(thisArg, arguments);
668
+ };
669
+ }
670
+ // utils is a library of generic helper functions non-specific to axios
671
+ const { toString: utils_toString } = Object.prototype;
672
+ const { getPrototypeOf } = Object;
673
+ const kindOf = ((cache)=>(thing)=>{
674
+ const str = utils_toString.call(thing);
675
+ return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
676
+ })(Object.create(null));
677
+ const kindOfTest = (type)=>{
678
+ type = type.toLowerCase();
679
+ return (thing)=>kindOf(thing) === type;
680
+ };
681
+ const typeOfTest = (type)=>(thing)=>typeof thing === type;
682
+ /**
683
+ * Determine if a value is an Array
411
684
  *
412
- * @param {String} str
413
- * @param {String} searchString
414
- * @param {Number} [position= 0]
685
+ * @param {Object} val The value to test
415
686
  *
416
- * @returns {boolean}
417
- */ const endsWith = (str, searchString, position)=>{
418
- str = String(str);
419
- if (void 0 === position || position > str.length) position = str.length;
420
- position -= searchString.length;
421
- const lastIndex = str.indexOf(searchString, position);
422
- return -1 !== lastIndex && lastIndex === position;
423
- };
687
+ * @returns {boolean} True if value is an Array, otherwise false
688
+ */ const { isArray } = Array;
424
689
  /**
425
- * Returns new array from array like object or null if failed
690
+ * Determine if a value is undefined
426
691
  *
427
- * @param {*} [thing]
692
+ * @param {*} val The value to test
428
693
  *
429
- * @returns {?Array}
430
- */ const toArray = (thing)=>{
431
- if (!thing) return null;
432
- if (isArray(thing)) return thing;
433
- let i = thing.length;
434
- if (!isNumber(i)) return null;
435
- const arr = new Array(i);
436
- while(i-- > 0)arr[i] = thing[i];
437
- return arr;
438
- };
694
+ * @returns {boolean} True if the value is undefined, otherwise false
695
+ */ const isUndefined = typeOfTest('undefined');
439
696
  /**
440
- * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
441
- * thing passed in is an instance of Uint8Array
697
+ * Determine if a value is a Buffer
442
698
  *
443
- * @param {TypedArray}
699
+ * @param {*} val The value to test
444
700
  *
445
- * @returns {Array}
446
- */ // eslint-disable-next-line func-names
447
- const isTypedArray = ((TypedArray)=>(thing)=>TypedArray && thing instanceof TypedArray)('undefined' != typeof Uint8Array && getPrototypeOf(Uint8Array));
701
+ * @returns {boolean} True if value is a Buffer, otherwise false
702
+ */ function isBuffer(val) {
703
+ return null !== val && !isUndefined(val) && null !== val.constructor && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
704
+ }
448
705
  /**
449
- * For each entry in the object, call the function with the key and value.
706
+ * Determine if a value is an ArrayBuffer
450
707
  *
451
- * @param {Object<any, any>} obj - The object to iterate over.
452
- * @param {Function} fn - The function to call for each entry.
708
+ * @param {*} val The value to test
453
709
  *
454
- * @returns {void}
455
- */ const forEachEntry = (obj, fn)=>{
456
- const generator = obj && obj[Symbol.iterator];
457
- const iterator = generator.call(obj);
458
- let result;
459
- while((result = iterator.next()) && !result.done){
460
- const pair = result.value;
461
- fn.call(obj, pair[0], pair[1]);
462
- }
463
- };
710
+ * @returns {boolean} True if value is an ArrayBuffer, otherwise false
711
+ */ const isArrayBuffer = kindOfTest('ArrayBuffer');
464
712
  /**
465
- * It takes a regular expression and a string, and returns an array of all the matches
713
+ * Determine if a value is a view on an ArrayBuffer
466
714
  *
467
- * @param {string} regExp - The regular expression to match against.
468
- * @param {string} str - The string to search.
715
+ * @param {*} val The value to test
469
716
  *
470
- * @returns {Array<boolean>}
471
- */ const matchAll = (regExp, str)=>{
472
- let matches;
473
- const arr = [];
474
- while(null !== (matches = regExp.exec(str)))arr.push(matches);
475
- return arr;
476
- };
477
- /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ const isHTMLForm = kindOfTest('HTMLFormElement');
478
- const toCamelCase = (str)=>str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function(m, p1, p2) {
479
- return p1.toUpperCase() + p2;
480
- });
481
- /* Creating a function that will check if an object has a property. */ const utils_hasOwnProperty = (({ hasOwnProperty })=>(obj, prop)=>hasOwnProperty.call(obj, prop))(Object.prototype);
717
+ * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
718
+ */ function isArrayBufferView(val) {
719
+ let result;
720
+ result = 'undefined' != typeof ArrayBuffer && ArrayBuffer.isView ? ArrayBuffer.isView(val) : val && val.buffer && isArrayBuffer(val.buffer);
721
+ return result;
722
+ }
482
723
  /**
483
- * Determine if a value is a RegExp object
724
+ * Determine if a value is a String
484
725
  *
485
726
  * @param {*} val The value to test
486
727
  *
487
- * @returns {boolean} True if value is a RegExp object, otherwise false
488
- */ const isRegExp = kindOfTest('RegExp');
489
- const reduceDescriptors = (obj, reducer)=>{
490
- const descriptors = Object.getOwnPropertyDescriptors(obj);
491
- const reducedDescriptors = {};
492
- forEach(descriptors, (descriptor, name)=>{
493
- let ret;
494
- if (false !== (ret = reducer(descriptor, name, obj))) reducedDescriptors[name] = ret || descriptor;
495
- });
496
- Object.defineProperties(obj, reducedDescriptors);
497
- };
728
+ * @returns {boolean} True if value is a String, otherwise false
729
+ */ const isString = typeOfTest('string');
498
730
  /**
499
- * Makes all methods read-only
500
- * @param {Object} obj
501
- */ const freezeMethods = (obj)=>{
502
- reduceDescriptors(obj, (descriptor, name)=>{
503
- // skip restricted props in strict mode
504
- if (isFunction(obj) && -1 !== [
505
- 'arguments',
506
- 'caller',
507
- 'callee'
508
- ].indexOf(name)) return false;
509
- const value = obj[name];
510
- if (!isFunction(value)) return;
511
- descriptor.enumerable = false;
512
- if ('writable' in descriptor) {
513
- descriptor.writable = false;
514
- return;
515
- }
516
- if (!descriptor.set) descriptor.set = ()=>{
517
- throw Error('Can not rewrite read-only method \'' + name + '\'');
518
- };
519
- });
520
- };
521
- const toObjectSet = (arrayOrString, delimiter)=>{
522
- const obj = {};
523
- const define = (arr)=>{
524
- arr.forEach((value)=>{
525
- obj[value] = true;
526
- });
527
- };
528
- isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
529
- return obj;
530
- };
531
- const noop = ()=>{};
532
- const toFiniteNumber = (value, defaultValue)=>null != value && Number.isFinite(value = +value) ? value : defaultValue;
533
- const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
534
- const DIGIT = '0123456789';
535
- const ALPHABET = {
536
- DIGIT,
537
- ALPHA,
538
- ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
539
- };
540
- const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT)=>{
541
- let str = '';
542
- const { length } = alphabet;
543
- while(size--)str += alphabet[Math.random() * length | 0];
544
- return str;
545
- };
731
+ * Determine if a value is a Function
732
+ *
733
+ * @param {*} val The value to test
734
+ * @returns {boolean} True if value is a Function, otherwise false
735
+ */ const isFunction = typeOfTest('function');
546
736
  /**
547
- * If the thing is a FormData object, return true, otherwise return false.
737
+ * Determine if a value is a Number
548
738
  *
549
- * @param {unknown} thing - The thing to check.
739
+ * @param {*} val The value to test
550
740
  *
551
- * @returns {boolean}
552
- */ function isSpecCompliantForm(thing) {
553
- return !!(thing && isFunction(thing.append) && 'FormData' === thing[Symbol.toStringTag] && thing[Symbol.iterator]);
554
- }
555
- const toJSONObject = (obj)=>{
741
+ * @returns {boolean} True if value is a Number, otherwise false
742
+ */ const isNumber = typeOfTest('number');
743
+ /**
744
+ * Determine if a value is an Object
745
+ *
746
+ * @param {*} thing The value to test
747
+ *
748
+ * @returns {boolean} True if value is an Object, otherwise false
749
+ */ const isObject = (thing)=>null !== thing && 'object' == typeof thing;
750
+ /**
751
+ * Determine if a value is a Boolean
752
+ *
753
+ * @param {*} thing The value to test
754
+ * @returns {boolean} True if value is a Boolean, otherwise false
755
+ */ const isBoolean = (thing)=>true === thing || false === thing;
756
+ /**
757
+ * Determine if a value is a plain Object
758
+ *
759
+ * @param {*} val The value to test
760
+ *
761
+ * @returns {boolean} True if value is a plain Object, otherwise false
762
+ */ const utils_isPlainObject = (val)=>{
763
+ if ('object' !== kindOf(val)) return false;
764
+ const prototype = getPrototypeOf(val);
765
+ return (null === prototype || prototype === Object.prototype || null === Object.getPrototypeOf(prototype)) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
766
+ };
767
+ /**
768
+ * Determine if a value is a Date
769
+ *
770
+ * @param {*} val The value to test
771
+ *
772
+ * @returns {boolean} True if value is a Date, otherwise false
773
+ */ const isDate = kindOfTest('Date');
774
+ /**
775
+ * Determine if a value is a File
776
+ *
777
+ * @param {*} val The value to test
778
+ *
779
+ * @returns {boolean} True if value is a File, otherwise false
780
+ */ const isFile = kindOfTest('File');
781
+ /**
782
+ * Determine if a value is a Blob
783
+ *
784
+ * @param {*} val The value to test
785
+ *
786
+ * @returns {boolean} True if value is a Blob, otherwise false
787
+ */ const isBlob = kindOfTest('Blob');
788
+ /**
789
+ * Determine if a value is a FileList
790
+ *
791
+ * @param {*} val The value to test
792
+ *
793
+ * @returns {boolean} True if value is a File, otherwise false
794
+ */ const utils_isFileList = kindOfTest('FileList');
795
+ /**
796
+ * Determine if a value is a Stream
797
+ *
798
+ * @param {*} val The value to test
799
+ *
800
+ * @returns {boolean} True if value is a Stream, otherwise false
801
+ */ const utils_isStream = (val)=>isObject(val) && isFunction(val.pipe);
802
+ /**
803
+ * Determine if a value is a FormData
804
+ *
805
+ * @param {*} thing The value to test
806
+ *
807
+ * @returns {boolean} True if value is an FormData, otherwise false
808
+ */ const utils_isFormData = (thing)=>{
809
+ let kind;
810
+ return thing && ('function' == typeof FormData && thing instanceof FormData || isFunction(thing.append) && ('formdata' === (kind = kindOf(thing)) || // detect form-data instance
811
+ 'object' === kind && isFunction(thing.toString) && '[object FormData]' === thing.toString()));
812
+ };
813
+ /**
814
+ * Determine if a value is a URLSearchParams object
815
+ *
816
+ * @param {*} val The value to test
817
+ *
818
+ * @returns {boolean} True if value is a URLSearchParams object, otherwise false
819
+ */ const isURLSearchParams = kindOfTest('URLSearchParams');
820
+ const [isReadableStream, isRequest, isResponse, isHeaders] = [
821
+ 'ReadableStream',
822
+ 'Request',
823
+ 'Response',
824
+ 'Headers'
825
+ ].map(kindOfTest);
826
+ /**
827
+ * Trim excess whitespace off the beginning and end of a string
828
+ *
829
+ * @param {String} str The String to trim
830
+ *
831
+ * @returns {String} The String freed of excess whitespace
832
+ */ const trim = (str)=>str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
833
+ /**
834
+ * Iterate over an Array or an Object invoking a function for each item.
835
+ *
836
+ * If `obj` is an Array callback will be called passing
837
+ * the value, index, and complete array for each item.
838
+ *
839
+ * If 'obj' is an Object callback will be called passing
840
+ * the value, key, and complete object for each property.
841
+ *
842
+ * @param {Object|Array} obj The object to iterate
843
+ * @param {Function} fn The callback to invoke for each item
844
+ *
845
+ * @param {Boolean} [allOwnKeys = false]
846
+ * @returns {any}
847
+ */ function forEach(obj, fn, { allOwnKeys = false } = {}) {
848
+ // Don't bother if no value provided
849
+ if (null == obj) return;
850
+ let i;
851
+ let l;
852
+ // Force an array if not already something iterable
853
+ if ('object' != typeof obj) /*eslint no-param-reassign:0*/ obj = [
854
+ obj
855
+ ];
856
+ if (isArray(obj)) // Iterate over array values
857
+ for(i = 0, l = obj.length; i < l; i++)fn.call(null, obj[i], i, obj);
858
+ else {
859
+ // Iterate over object keys
860
+ const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
861
+ const len = keys.length;
862
+ let key;
863
+ for(i = 0; i < len; i++){
864
+ key = keys[i];
865
+ fn.call(null, obj[key], key, obj);
866
+ }
867
+ }
868
+ }
869
+ function findKey(obj, key) {
870
+ key = key.toLowerCase();
871
+ const keys = Object.keys(obj);
872
+ let i = keys.length;
873
+ let _key;
874
+ while(i-- > 0){
875
+ _key = keys[i];
876
+ if (key === _key.toLowerCase()) return _key;
877
+ }
878
+ return null;
879
+ }
880
+ const _global = (()=>{
881
+ /*eslint no-undef:0*/ if ("undefined" != typeof globalThis) return globalThis;
882
+ return "undefined" != typeof self ? self : 'undefined' != typeof window ? window : global;
883
+ })();
884
+ const isContextDefined = (context)=>!isUndefined(context) && context !== _global;
885
+ /**
886
+ * Accepts varargs expecting each argument to be an object, then
887
+ * immutably merges the properties of each object and returns result.
888
+ *
889
+ * When multiple objects contain the same key the later object in
890
+ * the arguments list will take precedence.
891
+ *
892
+ * Example:
893
+ *
894
+ * ```js
895
+ * var result = merge({foo: 123}, {foo: 456});
896
+ * console.log(result.foo); // outputs 456
897
+ * ```
898
+ *
899
+ * @param {Object} obj1 Object to merge
900
+ *
901
+ * @returns {Object} Result of all merge properties
902
+ */ function utils_merge() {
903
+ const { caseless } = isContextDefined(this) && this || {};
904
+ const result = {};
905
+ const assignValue = (val, key)=>{
906
+ const targetKey = caseless && findKey(result, key) || key;
907
+ if (utils_isPlainObject(result[targetKey]) && utils_isPlainObject(val)) result[targetKey] = utils_merge(result[targetKey], val);
908
+ else if (utils_isPlainObject(val)) result[targetKey] = utils_merge({}, val);
909
+ else if (isArray(val)) result[targetKey] = val.slice();
910
+ else result[targetKey] = val;
911
+ };
912
+ for(let i = 0, l = arguments.length; i < l; i++)arguments[i] && forEach(arguments[i], assignValue);
913
+ return result;
914
+ }
915
+ /**
916
+ * Extends object a by mutably adding to it the properties of object b.
917
+ *
918
+ * @param {Object} a The object to be extended
919
+ * @param {Object} b The object to copy properties from
920
+ * @param {Object} thisArg The object to bind function to
921
+ *
922
+ * @param {Boolean} [allOwnKeys]
923
+ * @returns {Object} The resulting value of object a
924
+ */ const extend = (a, b, thisArg, { allOwnKeys } = {})=>{
925
+ forEach(b, (val, key)=>{
926
+ if (thisArg && isFunction(val)) a[key] = bind(val, thisArg);
927
+ else a[key] = val;
928
+ }, {
929
+ allOwnKeys
930
+ });
931
+ return a;
932
+ };
933
+ /**
934
+ * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
935
+ *
936
+ * @param {string} content with BOM
937
+ *
938
+ * @returns {string} content value without BOM
939
+ */ const stripBOM = (content)=>{
940
+ if (0xFEFF === content.charCodeAt(0)) content = content.slice(1);
941
+ return content;
942
+ };
943
+ /**
944
+ * Inherit the prototype methods from one constructor into another
945
+ * @param {function} constructor
946
+ * @param {function} superConstructor
947
+ * @param {object} [props]
948
+ * @param {object} [descriptors]
949
+ *
950
+ * @returns {void}
951
+ */ const inherits = (constructor, superConstructor, props, descriptors)=>{
952
+ constructor.prototype = Object.create(superConstructor.prototype, descriptors);
953
+ constructor.prototype.constructor = constructor;
954
+ Object.defineProperty(constructor, 'super', {
955
+ value: superConstructor.prototype
956
+ });
957
+ props && Object.assign(constructor.prototype, props);
958
+ };
959
+ /**
960
+ * Resolve object with deep prototype chain to a flat object
961
+ * @param {Object} sourceObj source object
962
+ * @param {Object} [destObj]
963
+ * @param {Function|Boolean} [filter]
964
+ * @param {Function} [propFilter]
965
+ *
966
+ * @returns {Object}
967
+ */ const toFlatObject = (sourceObj, destObj, filter, propFilter)=>{
968
+ let props;
969
+ let i;
970
+ let prop;
971
+ const merged = {};
972
+ destObj = destObj || {};
973
+ // eslint-disable-next-line no-eq-null,eqeqeq
974
+ if (null == sourceObj) return destObj;
975
+ do {
976
+ props = Object.getOwnPropertyNames(sourceObj);
977
+ i = props.length;
978
+ while(i-- > 0){
979
+ prop = props[i];
980
+ if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
981
+ destObj[prop] = sourceObj[prop];
982
+ merged[prop] = true;
983
+ }
984
+ }
985
+ sourceObj = false !== filter && getPrototypeOf(sourceObj);
986
+ }while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
987
+ return destObj;
988
+ };
989
+ /**
990
+ * Determines whether a string ends with the characters of a specified string
991
+ *
992
+ * @param {String} str
993
+ * @param {String} searchString
994
+ * @param {Number} [position= 0]
995
+ *
996
+ * @returns {boolean}
997
+ */ const endsWith = (str, searchString, position)=>{
998
+ str = String(str);
999
+ if (void 0 === position || position > str.length) position = str.length;
1000
+ position -= searchString.length;
1001
+ const lastIndex = str.indexOf(searchString, position);
1002
+ return -1 !== lastIndex && lastIndex === position;
1003
+ };
1004
+ /**
1005
+ * Returns new array from array like object or null if failed
1006
+ *
1007
+ * @param {*} [thing]
1008
+ *
1009
+ * @returns {?Array}
1010
+ */ const toArray = (thing)=>{
1011
+ if (!thing) return null;
1012
+ if (isArray(thing)) return thing;
1013
+ let i = thing.length;
1014
+ if (!isNumber(i)) return null;
1015
+ const arr = new Array(i);
1016
+ while(i-- > 0)arr[i] = thing[i];
1017
+ return arr;
1018
+ };
1019
+ /**
1020
+ * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
1021
+ * thing passed in is an instance of Uint8Array
1022
+ *
1023
+ * @param {TypedArray}
1024
+ *
1025
+ * @returns {Array}
1026
+ */ // eslint-disable-next-line func-names
1027
+ const isTypedArray = ((TypedArray)=>(thing)=>TypedArray && thing instanceof TypedArray)('undefined' != typeof Uint8Array && getPrototypeOf(Uint8Array));
1028
+ /**
1029
+ * For each entry in the object, call the function with the key and value.
1030
+ *
1031
+ * @param {Object<any, any>} obj - The object to iterate over.
1032
+ * @param {Function} fn - The function to call for each entry.
1033
+ *
1034
+ * @returns {void}
1035
+ */ const forEachEntry = (obj, fn)=>{
1036
+ const generator = obj && obj[Symbol.iterator];
1037
+ const iterator = generator.call(obj);
1038
+ let result;
1039
+ while((result = iterator.next()) && !result.done){
1040
+ const pair = result.value;
1041
+ fn.call(obj, pair[0], pair[1]);
1042
+ }
1043
+ };
1044
+ /**
1045
+ * It takes a regular expression and a string, and returns an array of all the matches
1046
+ *
1047
+ * @param {string} regExp - The regular expression to match against.
1048
+ * @param {string} str - The string to search.
1049
+ *
1050
+ * @returns {Array<boolean>}
1051
+ */ const matchAll = (regExp, str)=>{
1052
+ let matches;
1053
+ const arr = [];
1054
+ while(null !== (matches = regExp.exec(str)))arr.push(matches);
1055
+ return arr;
1056
+ };
1057
+ /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ const isHTMLForm = kindOfTest('HTMLFormElement');
1058
+ const toCamelCase = (str)=>str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function(m, p1, p2) {
1059
+ return p1.toUpperCase() + p2;
1060
+ });
1061
+ /* Creating a function that will check if an object has a property. */ const utils_hasOwnProperty = (({ hasOwnProperty })=>(obj, prop)=>hasOwnProperty.call(obj, prop))(Object.prototype);
1062
+ /**
1063
+ * Determine if a value is a RegExp object
1064
+ *
1065
+ * @param {*} val The value to test
1066
+ *
1067
+ * @returns {boolean} True if value is a RegExp object, otherwise false
1068
+ */ const isRegExp = kindOfTest('RegExp');
1069
+ const reduceDescriptors = (obj, reducer)=>{
1070
+ const descriptors = Object.getOwnPropertyDescriptors(obj);
1071
+ const reducedDescriptors = {};
1072
+ forEach(descriptors, (descriptor, name)=>{
1073
+ let ret;
1074
+ if (false !== (ret = reducer(descriptor, name, obj))) reducedDescriptors[name] = ret || descriptor;
1075
+ });
1076
+ Object.defineProperties(obj, reducedDescriptors);
1077
+ };
1078
+ /**
1079
+ * Makes all methods read-only
1080
+ * @param {Object} obj
1081
+ */ const freezeMethods = (obj)=>{
1082
+ reduceDescriptors(obj, (descriptor, name)=>{
1083
+ // skip restricted props in strict mode
1084
+ if (isFunction(obj) && -1 !== [
1085
+ 'arguments',
1086
+ 'caller',
1087
+ 'callee'
1088
+ ].indexOf(name)) return false;
1089
+ const value = obj[name];
1090
+ if (!isFunction(value)) return;
1091
+ descriptor.enumerable = false;
1092
+ if ('writable' in descriptor) {
1093
+ descriptor.writable = false;
1094
+ return;
1095
+ }
1096
+ if (!descriptor.set) descriptor.set = ()=>{
1097
+ throw Error('Can not rewrite read-only method \'' + name + '\'');
1098
+ };
1099
+ });
1100
+ };
1101
+ const toObjectSet = (arrayOrString, delimiter)=>{
1102
+ const obj = {};
1103
+ const define = (arr)=>{
1104
+ arr.forEach((value)=>{
1105
+ obj[value] = true;
1106
+ });
1107
+ };
1108
+ isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
1109
+ return obj;
1110
+ };
1111
+ const noop = ()=>{};
1112
+ const toFiniteNumber = (value, defaultValue)=>null != value && Number.isFinite(value = +value) ? value : defaultValue;
1113
+ const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
1114
+ const DIGIT = '0123456789';
1115
+ const ALPHABET = {
1116
+ DIGIT,
1117
+ ALPHA,
1118
+ ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
1119
+ };
1120
+ const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT)=>{
1121
+ let str = '';
1122
+ const { length } = alphabet;
1123
+ while(size--)str += alphabet[Math.random() * length | 0];
1124
+ return str;
1125
+ };
1126
+ /**
1127
+ * If the thing is a FormData object, return true, otherwise return false.
1128
+ *
1129
+ * @param {unknown} thing - The thing to check.
1130
+ *
1131
+ * @returns {boolean}
1132
+ */ function isSpecCompliantForm(thing) {
1133
+ return !!(thing && isFunction(thing.append) && 'FormData' === thing[Symbol.toStringTag] && thing[Symbol.iterator]);
1134
+ }
1135
+ const toJSONObject = (obj)=>{
556
1136
  const stack = new Array(10);
557
1137
  const visit = (source, i)=>{
558
1138
  if (isObject(source)) {
@@ -600,7 +1180,7 @@ const asap = 'undefined' != typeof queueMicrotask ? queueMicrotask.bind(_global)
600
1180
  isNumber,
601
1181
  isBoolean,
602
1182
  isObject,
603
- isPlainObject,
1183
+ isPlainObject: utils_isPlainObject,
604
1184
  isReadableStream,
605
1185
  isRequest,
606
1186
  isResponse,
@@ -1798,7 +2378,7 @@ const headersToObject = (thing)=>thing instanceof AxiosHeaders ? {
1798
2378
  * @param {Object} config2
1799
2379
  *
1800
2380
  * @returns {Object} New object resulting from merging config2 to config1
1801
- */ function mergeConfig(config1, config2) {
2381
+ */ function mergeConfig_mergeConfig(config1, config2) {
1802
2382
  // eslint-disable-next-line no-param-reassign
1803
2383
  config2 = config2 || {};
1804
2384
  const config = {};
@@ -1868,7 +2448,7 @@ const headersToObject = (thing)=>thing instanceof AxiosHeaders ? {
1868
2448
  return config;
1869
2449
  }
1870
2450
  /* ESM default export */ const resolveConfig = (config)=>{
1871
- const newConfig = mergeConfig({}, config);
2451
+ const newConfig = mergeConfig_mergeConfig({}, config);
1872
2452
  let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig;
1873
2453
  newConfig.headers = headers = AxiosHeaders.from(headers);
1874
2454
  newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer);
@@ -2474,7 +3054,7 @@ const Axios_validators = helpers_validator.validators;
2474
3054
  config = config || {};
2475
3055
  config.url = configOrUrl;
2476
3056
  } else config = configOrUrl || {};
2477
- config = mergeConfig(this.defaults, config);
3057
+ config = mergeConfig_mergeConfig(this.defaults, config);
2478
3058
  const { transitional, paramsSerializer, headers } = config;
2479
3059
  if (void 0 !== transitional) helpers_validator.assertOptions(transitional, {
2480
3060
  silentJSONParsing: Axios_validators.transitional(Axios_validators.boolean),
@@ -2557,7 +3137,7 @@ const Axios_validators = helpers_validator.validators;
2557
3137
  return promise;
2558
3138
  }
2559
3139
  getUri(config) {
2560
- config = mergeConfig(this.defaults, config);
3140
+ config = mergeConfig_mergeConfig(this.defaults, config);
2561
3141
  const fullPath = buildFullPath(config.baseURL, config.url);
2562
3142
  return buildURL(fullPath, config.params, config.paramsSerializer);
2563
3143
  }
@@ -2570,850 +3150,283 @@ utils.forEach([
2570
3150
  'options'
2571
3151
  ], function(method) {
2572
3152
  /*eslint func-names:0*/ Axios_Axios.prototype[method] = function(url, config) {
2573
- return this.request(mergeConfig(config || {}, {
3153
+ return this.request(mergeConfig_mergeConfig(config || {}, {
2574
3154
  method,
2575
3155
  url,
2576
3156
  data: (config || {}).data
2577
3157
  }));
2578
- };
2579
- });
2580
- utils.forEach([
2581
- 'post',
2582
- 'put',
2583
- 'patch'
2584
- ], function(method) {
2585
- /*eslint func-names:0*/ function generateHTTPMethod(isForm) {
2586
- return function(url, data, config) {
2587
- return this.request(mergeConfig(config || {}, {
2588
- method,
2589
- headers: isForm ? {
2590
- 'Content-Type': 'multipart/form-data'
2591
- } : {},
2592
- url,
2593
- data
2594
- }));
2595
- };
2596
- }
2597
- Axios_Axios.prototype[method] = generateHTTPMethod();
2598
- Axios_Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
2599
- });
2600
- /* ESM default export */ const Axios = Axios_Axios;
2601
- /**
2602
- * A `CancelToken` is an object that can be used to request cancellation of an operation.
2603
- *
2604
- * @param {Function} executor The executor function.
2605
- *
2606
- * @returns {CancelToken}
2607
- */ class CancelToken_CancelToken {
2608
- constructor(executor){
2609
- if ('function' != typeof executor) throw new TypeError('executor must be a function.');
2610
- let resolvePromise;
2611
- this.promise = new Promise(function(resolve) {
2612
- resolvePromise = resolve;
2613
- });
2614
- const token = this;
2615
- // eslint-disable-next-line func-names
2616
- this.promise.then((cancel)=>{
2617
- if (!token._listeners) return;
2618
- let i = token._listeners.length;
2619
- while(i-- > 0)token._listeners[i](cancel);
2620
- token._listeners = null;
2621
- });
2622
- // eslint-disable-next-line func-names
2623
- this.promise.then = (onfulfilled)=>{
2624
- let _resolve;
2625
- // eslint-disable-next-line func-names
2626
- const promise = new Promise((resolve)=>{
2627
- token.subscribe(resolve);
2628
- _resolve = resolve;
2629
- }).then(onfulfilled);
2630
- promise.cancel = function() {
2631
- token.unsubscribe(_resolve);
2632
- };
2633
- return promise;
2634
- };
2635
- executor(function(message, config, request) {
2636
- if (token.reason) // Cancellation has already been requested
2637
- return;
2638
- token.reason = new CanceledError(message, config, request);
2639
- resolvePromise(token.reason);
2640
- });
2641
- }
2642
- /**
2643
- * Throws a `CanceledError` if cancellation has been requested.
2644
- */ throwIfRequested() {
2645
- if (this.reason) throw this.reason;
2646
- }
2647
- /**
2648
- * Subscribe to the cancel signal
2649
- */ subscribe(listener) {
2650
- if (this.reason) {
2651
- listener(this.reason);
2652
- return;
2653
- }
2654
- if (this._listeners) this._listeners.push(listener);
2655
- else this._listeners = [
2656
- listener
2657
- ];
2658
- }
2659
- /**
2660
- * Unsubscribe from the cancel signal
2661
- */ unsubscribe(listener) {
2662
- if (!this._listeners) return;
2663
- const index = this._listeners.indexOf(listener);
2664
- if (-1 !== index) this._listeners.splice(index, 1);
2665
- }
2666
- toAbortSignal() {
2667
- const controller = new AbortController();
2668
- const abort = (err)=>{
2669
- controller.abort(err);
2670
- };
2671
- this.subscribe(abort);
2672
- controller.signal.unsubscribe = ()=>this.unsubscribe(abort);
2673
- return controller.signal;
2674
- }
2675
- /**
2676
- * Returns an object that contains a new `CancelToken` and a function that, when called,
2677
- * cancels the `CancelToken`.
2678
- */ static source() {
2679
- let cancel;
2680
- const token = new CancelToken_CancelToken(function(c) {
2681
- cancel = c;
2682
- });
2683
- return {
2684
- token,
2685
- cancel
2686
- };
2687
- }
2688
- }
2689
- /* ESM default export */ const CancelToken = CancelToken_CancelToken;
2690
- /**
2691
- * Syntactic sugar for invoking a function and expanding an array for arguments.
2692
- *
2693
- * Common use case would be to use `Function.prototype.apply`.
2694
- *
2695
- * ```js
2696
- * function f(x, y, z) {}
2697
- * var args = [1, 2, 3];
2698
- * f.apply(null, args);
2699
- * ```
2700
- *
2701
- * With `spread` this example can be re-written.
2702
- *
2703
- * ```js
2704
- * spread(function(x, y, z) {})([1, 2, 3]);
2705
- * ```
2706
- *
2707
- * @param {Function} callback
2708
- *
2709
- * @returns {Function}
2710
- */ function spread(callback) {
2711
- return function(arr) {
2712
- return callback.apply(null, arr);
2713
- };
2714
- }
2715
- /**
2716
- * Determines whether the payload is an error thrown by Axios
2717
- *
2718
- * @param {*} payload The value to test
2719
- *
2720
- * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
2721
- */ function isAxiosError(payload) {
2722
- return utils.isObject(payload) && true === payload.isAxiosError;
2723
- }
2724
- const HttpStatusCode = {
2725
- Continue: 100,
2726
- SwitchingProtocols: 101,
2727
- Processing: 102,
2728
- EarlyHints: 103,
2729
- Ok: 200,
2730
- Created: 201,
2731
- Accepted: 202,
2732
- NonAuthoritativeInformation: 203,
2733
- NoContent: 204,
2734
- ResetContent: 205,
2735
- PartialContent: 206,
2736
- MultiStatus: 207,
2737
- AlreadyReported: 208,
2738
- ImUsed: 226,
2739
- MultipleChoices: 300,
2740
- MovedPermanently: 301,
2741
- Found: 302,
2742
- SeeOther: 303,
2743
- NotModified: 304,
2744
- UseProxy: 305,
2745
- Unused: 306,
2746
- TemporaryRedirect: 307,
2747
- PermanentRedirect: 308,
2748
- BadRequest: 400,
2749
- Unauthorized: 401,
2750
- PaymentRequired: 402,
2751
- Forbidden: 403,
2752
- NotFound: 404,
2753
- MethodNotAllowed: 405,
2754
- NotAcceptable: 406,
2755
- ProxyAuthenticationRequired: 407,
2756
- RequestTimeout: 408,
2757
- Conflict: 409,
2758
- Gone: 410,
2759
- LengthRequired: 411,
2760
- PreconditionFailed: 412,
2761
- PayloadTooLarge: 413,
2762
- UriTooLong: 414,
2763
- UnsupportedMediaType: 415,
2764
- RangeNotSatisfiable: 416,
2765
- ExpectationFailed: 417,
2766
- ImATeapot: 418,
2767
- MisdirectedRequest: 421,
2768
- UnprocessableEntity: 422,
2769
- Locked: 423,
2770
- FailedDependency: 424,
2771
- TooEarly: 425,
2772
- UpgradeRequired: 426,
2773
- PreconditionRequired: 428,
2774
- TooManyRequests: 429,
2775
- RequestHeaderFieldsTooLarge: 431,
2776
- UnavailableForLegalReasons: 451,
2777
- InternalServerError: 500,
2778
- NotImplemented: 501,
2779
- BadGateway: 502,
2780
- ServiceUnavailable: 503,
2781
- GatewayTimeout: 504,
2782
- HttpVersionNotSupported: 505,
2783
- VariantAlsoNegotiates: 506,
2784
- InsufficientStorage: 507,
2785
- LoopDetected: 508,
2786
- NotExtended: 510,
2787
- NetworkAuthenticationRequired: 511
2788
- };
2789
- Object.entries(HttpStatusCode).forEach(([key, value])=>{
2790
- HttpStatusCode[value] = key;
2791
- });
2792
- /* ESM default export */ const helpers_HttpStatusCode = HttpStatusCode;
2793
- /**
2794
- * Create an instance of Axios
2795
- *
2796
- * @param {Object} defaultConfig The default config for the instance
2797
- *
2798
- * @returns {Axios} A new instance of Axios
2799
- */ function createInstance(defaultConfig) {
2800
- const context = new Axios(defaultConfig);
2801
- const instance = bind(Axios.prototype.request, context);
2802
- // Copy axios.prototype to instance
2803
- utils.extend(instance, Axios.prototype, context, {
2804
- allOwnKeys: true
2805
- });
2806
- // Copy context to instance
2807
- utils.extend(instance, context, null, {
2808
- allOwnKeys: true
2809
- });
2810
- // Factory for creating new instances
2811
- instance.create = function(instanceConfig) {
2812
- return createInstance(mergeConfig(defaultConfig, instanceConfig));
2813
- };
2814
- return instance;
2815
- }
2816
- // Create the default instance to be exported
2817
- const axios = createInstance(defaults);
2818
- // Expose Axios class to allow class inheritance
2819
- axios.Axios = Axios;
2820
- // Expose Cancel & CancelToken
2821
- axios.CanceledError = CanceledError;
2822
- axios.CancelToken = CancelToken;
2823
- axios.isCancel = isCancel;
2824
- axios.VERSION = VERSION;
2825
- axios.toFormData = toFormData;
2826
- // Expose AxiosError class
2827
- axios.AxiosError = core_AxiosError;
2828
- // alias for CanceledError for backward compatibility
2829
- axios.Cancel = axios.CanceledError;
2830
- // Expose all/spread
2831
- axios.all = function(promises) {
2832
- return Promise.all(promises);
2833
- };
2834
- axios.spread = spread;
2835
- // Expose isAxiosError
2836
- axios.isAxiosError = isAxiosError;
2837
- // Expose mergeConfig
2838
- axios.mergeConfig = mergeConfig;
2839
- axios.AxiosHeaders = AxiosHeaders;
2840
- axios.formToJSON = (thing)=>formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
2841
- axios.getAdapter = adapters_adapters.getAdapter;
2842
- axios.HttpStatusCode = helpers_HttpStatusCode;
2843
- axios.default = axios;
2844
- // this module should only have a default export
2845
- /* ESM default export */ const lib_axios = axios;
2846
- // This module is intended to unwrap Axios default export as named.
2847
- // Keep top-level export same with static properties
2848
- // so that it can keep same with es module or cjs
2849
- 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;
2850
- // EXTERNAL MODULE: os (ignored)
2851
- var os_ignored_ = __webpack_require__("?9caf");
2852
- // EXTERNAL MODULE: crypto (ignored)
2853
- __webpack_require__("?e272");
2854
- // EXTERNAL MODULE: jsonwebtoken (ignored)
2855
- __webpack_require__("?5742");
2856
- class APIResource {
2857
- constructor(client){
2858
- this._client = client;
2859
- }
2860
- }
2861
- /* eslint-disable @typescript-eslint/no-namespace */ class Bots extends APIResource {
2862
- /**
2863
- * Create a new agent. | 调用接口创建一个新的智能体。
2864
- * @docs en:https://www.coze.com/docs/developer_guides/create_bot?_lang=en
2865
- * @docs zh:https://www.coze.cn/docs/developer_guides/create_bot?_lang=zh
2866
- * @param params - Required The parameters for creating a bot. | 创建 Bot 的参数。
2867
- * @param params.space_id - Required The Space ID of the space where the agent is located. | Bot 所在的空间的 Space ID。
2868
- * @param params.name - Required The name of the agent. It should be 1 to 20 characters long. | Bot 的名称。
2869
- * @param params.description - Optional The description of the agent. It can be 0 to 500 characters long. | Bot 的描述信息。
2870
- * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
2871
- * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
2872
- * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
2873
- * @returns Information about the created bot. | 创建的 Bot 信息。
2874
- */ async create(params, options) {
2875
- const apiUrl = '/v1/bot/create';
2876
- const result = await this._client.post(apiUrl, params, false, options);
2877
- return result.data;
2878
- }
2879
- /**
2880
- * Update the configuration of an agent. | 调用接口修改智能体的配置。
2881
- * @docs en:https://www.coze.com/docs/developer_guides/update_bot?_lang=en
2882
- * @docs zh:https://www.coze.cn/docs/developer_guides/update_bot?_lang=zh
2883
- * @param params - Required The parameters for updating a bot. | 修改 Bot 的参数。
2884
- * @param params.bot_id - Required The ID of the agent that the API interacts with. | 待修改配置的智能体ID。
2885
- * @param params.name - Optional The name of the agent. | Bot 的名称。
2886
- * @param params.description - Optional The description of the agent. | Bot 的描述信息。
2887
- * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
2888
- * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
2889
- * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
2890
- * @param params.knowledge - Optional Knowledge configurations of the agent. | Bot 的知识库配置。
2891
- * @returns Undefined | 无返回值
2892
- */ async update(params, options) {
2893
- const apiUrl = '/v1/bot/update';
2894
- const result = await this._client.post(apiUrl, params, false, options);
2895
- return result.data;
2896
- }
2897
- /**
2898
- * Get the agents published as API service. | 调用接口查看指定空间发布到 Agent as API 渠道的智能体列表。
2899
- * @docs en:https://www.coze.com/docs/developer_guides/published_bots_list?_lang=en
2900
- * @docs zh:https://www.coze.cn/docs/developer_guides/published_bots_list?_lang=zh
2901
- * @param params - Required The parameters for listing bots. | 列出 Bot 的参数。
2902
- * @param params.space_id - Required The ID of the space. | Bot 所在的空间的 Space ID。
2903
- * @param params.page_size - Optional Pagination size. | 分页大小。
2904
- * @param params.page_index - Optional Page number for paginated queries. | 分页查询时的页码。
2905
- * @returns List of published bots. | 已发布的 Bot 列表。
2906
- */ async list(params, options) {
2907
- const apiUrl = '/v1/space/published_bots_list';
2908
- const result = await this._client.get(apiUrl, params, false, options);
2909
- return result.data;
2910
- }
2911
- /**
2912
- * Publish the specified agent as an API service. | 调用接口创建一个新的智能体。
2913
- * @docs en:https://www.coze.com/docs/developer_guides/publish_bot?_lang=en
2914
- * @docs zh:https://www.coze.cn/docs/developer_guides/publish_bot?_lang=zh
2915
- * @param params - Required The parameters for publishing a bot. | 发布 Bot 的参数。
2916
- * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要发布的智能体ID。
2917
- * @param params.connector_ids - Required The list of publishing channel IDs for the agent. | 智能体的发布渠道 ID 列表。
2918
- * @returns Undefined | 无返回值
2919
- */ async publish(params, options) {
2920
- const apiUrl = '/v1/bot/publish';
2921
- const result = await this._client.post(apiUrl, params, false, options);
2922
- return result.data;
2923
- }
2924
- /**
2925
- * Get the configuration information of the agent. | 获取指定智能体的配置信息。
2926
- * @docs en:https://www.coze.com/docs/developer_guides/get_metadata?_lang=en
2927
- * @docs zh:https://www.coze.cn/docs/developer_guides/get_metadata?_lang=zh
2928
- * @param params - Required The parameters for retrieving a bot. | 获取 Bot 的参数。
2929
- * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要查看的智能体ID。
2930
- * @returns Information about the bot. | Bot 的配置信息。
2931
- */ async retrieve(params, options) {
2932
- const apiUrl = '/v1/bot/get_online_info';
2933
- const result = await this._client.get(apiUrl, params, false, options);
2934
- return result.data;
2935
- }
2936
- }
2937
- /* eslint-disable security/detect-object-injection */ /* eslint-disable @typescript-eslint/no-explicit-any */ function safeJsonParse(jsonString) {
2938
- let defaultValue = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : '';
2939
- try {
2940
- return JSON.parse(jsonString);
2941
- } catch (error) {
2942
- return defaultValue;
2943
- }
2944
- }
2945
- function sleep(ms) {
2946
- return new Promise((resolve)=>{
2947
- setTimeout(resolve, ms);
2948
- });
2949
- }
2950
- function isBrowser() {
2951
- return 'undefined' != typeof window;
2952
- }
2953
- function esm_isPlainObject(obj) {
2954
- if ('object' != typeof obj || null === obj) return false;
2955
- const proto = Object.getPrototypeOf(obj);
2956
- if (null === proto) return true;
2957
- let baseProto = proto;
2958
- while(null !== Object.getPrototypeOf(baseProto))baseProto = Object.getPrototypeOf(baseProto);
2959
- return proto === baseProto;
2960
- }
2961
- function esm_mergeConfig() {
2962
- for(var _len = arguments.length, objects = new Array(_len), _key = 0; _key < _len; _key++)objects[_key] = arguments[_key];
2963
- return objects.reduce((result, obj)=>{
2964
- if (void 0 === obj) return result || {};
2965
- for(const key in obj)if (Object.prototype.hasOwnProperty.call(obj, key)) {
2966
- if (esm_isPlainObject(obj[key]) && !Array.isArray(obj[key])) result[key] = esm_mergeConfig(result[key] || {}, obj[key]);
2967
- else result[key] = obj[key];
2968
- }
2969
- return result;
2970
- }, {});
2971
- }
2972
- function isPersonalAccessToken(token) {
2973
- return null == token ? void 0 : token.startsWith('pat_');
2974
- }
2975
- /* eslint-disable max-params */ class CozeError extends Error {
2976
- }
2977
- class APIError extends CozeError {
2978
- static makeMessage(status, errorBody, message, headers) {
2979
- if (!errorBody && message) return message;
2980
- if (errorBody) {
2981
- const list = [];
2982
- const { code, msg, error } = errorBody;
2983
- if (code) list.push(`code: ${code}`);
2984
- if (msg) list.push(`msg: ${msg}`);
2985
- if ((null == error ? void 0 : error.detail) && msg !== error.detail) list.push(`detail: ${error.detail}`);
2986
- const logId = (null == error ? void 0 : error.logid) || (null == headers ? void 0 : headers['x-tt-logid']);
2987
- if (logId) list.push(`logid: ${logId}`);
2988
- const help_doc = null == error ? void 0 : error.help_doc;
2989
- if (help_doc) list.push(`help doc: ${help_doc}`);
2990
- return list.join(', ');
2991
- }
2992
- if (status) return `http status code: ${status} (no body)`;
2993
- return '(no status code or body)';
2994
- }
2995
- static generate(status, errorResponse, message, headers) {
2996
- if (!status) return new APIConnectionError({
2997
- cause: castToError(errorResponse)
2998
- });
2999
- const error = errorResponse;
3000
- // https://www.coze.cn/docs/developer_guides/coze_error_codes
3001
- if (400 === status || (null == error ? void 0 : error.code) === 4000) return new BadRequestError(status, error, message, headers);
3002
- if (401 === status || (null == error ? void 0 : error.code) === 4100) return new AuthenticationError(status, error, message, headers);
3003
- if (403 === status || (null == error ? void 0 : error.code) === 4101) return new PermissionDeniedError(status, error, message, headers);
3004
- if (404 === status || (null == error ? void 0 : error.code) === 4200) return new NotFoundError(status, error, message, headers);
3005
- if (429 === status || (null == error ? void 0 : error.code) === 4013) return new RateLimitError(status, error, message, headers);
3006
- if (408 === status) return new TimeoutError(status, error, message, headers);
3007
- if (502 === status) return new GatewayError(status, error, message, headers);
3008
- if (status >= 500) return new InternalServerError(status, error, message, headers);
3009
- return new APIError(status, error, message, headers);
3010
- }
3011
- constructor(status, error, message, headers){
3012
- var _error_error, _error_error1;
3013
- super(`${APIError.makeMessage(status, error, message, headers)}`);
3014
- this.status = status;
3015
- this.headers = headers;
3016
- this.logid = null == headers ? void 0 : headers['x-tt-logid'];
3017
- // this.error = error;
3018
- this.code = null == error ? void 0 : error.code;
3019
- this.msg = null == error ? void 0 : error.msg;
3020
- this.detail = null == error ? void 0 : null === (_error_error = error.error) || void 0 === _error_error ? void 0 : _error_error.detail;
3021
- this.help_doc = null == error ? void 0 : null === (_error_error1 = error.error) || void 0 === _error_error1 ? void 0 : _error_error1.help_doc;
3022
- this.rawError = error;
3023
- }
3024
- }
3025
- class APIConnectionError extends APIError {
3026
- constructor({ message, cause }){
3027
- super(void 0, void 0, message || 'Connection error.', void 0), this.status = void 0;
3028
- // if (cause) {
3029
- // this.cause = cause;
3030
- // }
3031
- }
3032
- }
3033
- class APIUserAbortError extends APIError {
3034
- constructor(message){
3035
- super(void 0, void 0, message || 'Request was aborted.', void 0), this.name = 'UserAbortError', this.status = void 0;
3036
- }
3037
- }
3038
- class BadRequestError extends APIError {
3039
- constructor(...args){
3040
- super(...args), this.name = 'BadRequestError', this.status = 400;
3041
- }
3042
- }
3043
- class AuthenticationError extends APIError {
3044
- constructor(...args){
3045
- super(...args), this.name = 'AuthenticationError', this.status = 401;
3046
- }
3047
- }
3048
- class PermissionDeniedError extends APIError {
3049
- constructor(...args){
3050
- super(...args), this.name = 'PermissionDeniedError', this.status = 403;
3051
- }
3052
- }
3053
- class NotFoundError extends APIError {
3054
- constructor(...args){
3055
- super(...args), this.name = 'NotFoundError', this.status = 404;
3056
- }
3057
- }
3058
- class TimeoutError extends APIError {
3059
- constructor(...args){
3060
- super(...args), this.name = 'TimeoutError', this.status = 408;
3061
- }
3062
- }
3063
- class RateLimitError extends APIError {
3064
- constructor(...args){
3065
- super(...args), this.name = 'RateLimitError', this.status = 429;
3066
- }
3067
- }
3068
- class InternalServerError extends APIError {
3069
- constructor(...args){
3070
- super(...args), this.name = 'InternalServerError', this.status = 500;
3071
- }
3072
- }
3073
- class GatewayError extends APIError {
3074
- constructor(...args){
3075
- super(...args), this.name = 'GatewayError', this.status = 502;
3076
- }
3077
- }
3078
- const castToError = (err)=>{
3079
- if (err instanceof Error) return err;
3080
- return new Error(err);
3081
- };
3082
- class Messages extends APIResource {
3083
- /**
3084
- * Get the list of messages in a chat. | 获取对话中的消息列表。
3085
- * @docs en:https://www.coze.com/docs/developer_guides/chat_message_list?_lang=en
3086
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_message_list?_lang=zh
3087
- * @param conversation_id - Required The ID of the conversation. | 会话 ID。
3088
- * @param chat_id - Required The ID of the chat. | 对话 ID。
3089
- * @returns An array of chat messages. | 对话消息数组。
3090
- */ async list(conversation_id, chat_id, options) {
3091
- const apiUrl = `/v3/chat/message/list?conversation_id=${conversation_id}&chat_id=${chat_id}`;
3092
- const result = await this._client.get(apiUrl, void 0, false, options);
3093
- return result.data;
3094
- }
3095
- }
3096
- const uuid = ()=>(Math.random() * new Date().getTime()).toString();
3097
- const handleAdditionalMessages = (additional_messages)=>null == additional_messages ? void 0 : additional_messages.map((i)=>({
3098
- ...i,
3099
- content: 'object' == typeof i.content ? JSON.stringify(i.content) : i.content
3100
- }));
3101
- class Chat extends APIResource {
3102
- /**
3103
- * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
3104
- * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
3105
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
3106
- * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
3107
- * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
3108
- * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
3109
- * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
3110
- * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义变量。
3111
- * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
3112
- * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
3113
- * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
3114
- * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
3115
- * @returns The data of the created chat. | 创建的对话数据。
3116
- */ async create(params, options) {
3117
- if (!params.user_id) params.user_id = uuid();
3118
- const { conversation_id, ...rest } = params;
3119
- const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
3120
- const payload = {
3121
- ...rest,
3122
- additional_messages: handleAdditionalMessages(params.additional_messages),
3123
- stream: false
3124
- };
3125
- const result = await this._client.post(apiUrl, payload, false, options);
3126
- return result.data;
3127
- }
3128
- /**
3129
- * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
3130
- * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
3131
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
3132
- * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
3133
- * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
3134
- * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
3135
- * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
3136
- * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
3137
- * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
3138
- * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
3139
- * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
3140
- * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
3141
- * @returns
3142
- */ async createAndPoll(params, options) {
3143
- if (!params.user_id) params.user_id = uuid();
3144
- const { conversation_id, ...rest } = params;
3145
- const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
3146
- const payload = {
3147
- ...rest,
3148
- additional_messages: handleAdditionalMessages(params.additional_messages),
3149
- stream: false
3150
- };
3151
- const result = await this._client.post(apiUrl, payload, false, options);
3152
- const chatId = result.data.id;
3153
- const conversationId = result.data.conversation_id;
3154
- let chat;
3155
- while(true){
3156
- await sleep(100);
3157
- chat = await this.retrieve(conversationId, chatId);
3158
- if ('completed' === chat.status || 'failed' === chat.status || 'requires_action' === chat.status) break;
3159
- }
3160
- const messageList = await this.messages.list(conversationId, chatId);
3161
- return {
3162
- chat,
3163
- messages: messageList
3164
- };
3165
- }
3166
- /**
3167
- * Call the Chat API to send messages to a published Coze agent with streaming response. | 调用此接口发起一次对话,支持流式响应。
3168
- * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
3169
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
3170
- * @param params - Required The parameters for streaming a chat session. | 流式会话的参数。
3171
- * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
3172
- * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
3173
- * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
3174
- * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
3175
- * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
3176
- * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
3177
- * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
3178
- * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
3179
- * @returns A stream of chat data. | 对话数据流。
3180
- */ async *stream(params, options) {
3181
- if (!params.user_id) params.user_id = uuid();
3182
- const { conversation_id, ...rest } = params;
3183
- const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
3184
- const payload = {
3185
- ...rest,
3186
- additional_messages: handleAdditionalMessages(params.additional_messages),
3187
- stream: true
3188
- };
3189
- const result = await this._client.post(apiUrl, payload, true, options);
3190
- for await (const message of result)if ("done" === message.event) {
3191
- const ret = {
3192
- event: message.event,
3193
- data: '[DONE]'
3194
- };
3195
- yield ret;
3196
- } else try {
3197
- const ret = {
3198
- event: message.event,
3199
- data: JSON.parse(message.data)
3200
- };
3201
- yield ret;
3202
- } catch (error) {
3203
- throw new CozeError(`Could not parse message into JSON:${message.data}`);
3204
- }
3205
- }
3206
- /**
3207
- * Get the detailed information of the chat. | 查看对话的详细信息。
3208
- * @docs en:https://www.coze.com/docs/developer_guides/retrieve_chat?_lang=en
3209
- * @docs zh:https://www.coze.cn/docs/developer_guides/retrieve_chat?_lang=zh
3210
- * @param conversation_id - Required The ID of the conversation. | 会话 ID。
3211
- * @param chat_id - Required The ID of the chat. | 对话 ID。
3212
- * @returns The data of the retrieved chat. | 检索到的对话数据。
3213
- */ async retrieve(conversation_id, chat_id, options) {
3214
- const apiUrl = `/v3/chat/retrieve?conversation_id=${conversation_id}&chat_id=${chat_id}`;
3215
- const result = await this._client.post(apiUrl, void 0, false, options);
3216
- return result.data;
3217
- }
3218
- /**
3219
- * Cancel a chat session. | 取消对话会话。
3220
- * @docs en:https://www.coze.com/docs/developer_guides/cancel_chat?_lang=en
3221
- * @docs zh:https://www.coze.cn/docs/developer_guides/cancel_chat?_lang=zh
3222
- * @param conversation_id - Required The ID of the conversation. | 会话 ID。
3223
- * @param chat_id - Required The ID of the chat. | 对话 ID。
3224
- * @returns The data of the canceled chat. | 取消的对话数据。
3225
- */ async cancel(conversation_id, chat_id, options) {
3226
- const apiUrl = '/v3/chat/cancel';
3227
- const payload = {
3228
- conversation_id,
3229
- chat_id
3230
- };
3231
- const result = await this._client.post(apiUrl, payload, false, options);
3232
- return result.data;
3233
- }
3234
- /**
3235
- * Submit tool outputs for a chat session. | 提交对话会话的工具输出。
3236
- * @docs en:https://www.coze.com/docs/developer_guides/chat_submit_tool_outputs?_lang=en
3237
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_submit_tool_outputs?_lang=zh
3238
- * @param params - Required Parameters for submitting tool outputs. | 提交工具输出的参数。
3239
- * @param params.conversation_id - Required The ID of the conversation. | 会话 ID。
3240
- * @param params.chat_id - Required The ID of the chat. | 对话 ID。
3241
- * @param params.tool_outputs - Required The outputs of the tool. | 工具的输出。
3242
- * @param params.stream - Optional Whether to use streaming response. | 是否使用流式响应。
3243
- * @returns The data of the submitted tool outputs or a stream of chat data. | 提交的工具输出数据或对话数据流。
3244
- */ async *submitToolOutputs(params, options) {
3245
- const { conversation_id, chat_id, ...rest } = params;
3246
- const apiUrl = `/v3/chat/submit_tool_outputs?conversation_id=${params.conversation_id}&chat_id=${params.chat_id}`;
3247
- const payload = {
3248
- ...rest
3249
- };
3250
- if (false === params.stream) {
3251
- const response = await this._client.post(apiUrl, payload, false, options);
3252
- return response.data;
3253
- }
3254
- {
3255
- const result = await this._client.post(apiUrl, payload, true, options);
3256
- for await (const message of result)if ("done" === message.event) {
3257
- const ret = {
3258
- event: message.event,
3259
- data: '[DONE]'
3260
- };
3261
- yield ret;
3262
- } else try {
3263
- const ret = {
3264
- event: message.event,
3265
- data: JSON.parse(message.data)
3266
- };
3267
- yield ret;
3268
- } catch (error) {
3269
- throw new CozeError(`Could not parse message into JSON:${message.data}`);
3270
- }
3271
- }
3272
- }
3273
- constructor(...args){
3274
- super(...args), this.messages = new Messages(this._client);
3275
- }
3276
- }
3277
- var chat_ChatEventType = /*#__PURE__*/ function(ChatEventType) {
3278
- ChatEventType["CONVERSATION_CHAT_CREATED"] = "conversation.chat.created";
3279
- ChatEventType["CONVERSATION_CHAT_IN_PROGRESS"] = "conversation.chat.in_progress";
3280
- ChatEventType["CONVERSATION_CHAT_COMPLETED"] = "conversation.chat.completed";
3281
- ChatEventType["CONVERSATION_CHAT_FAILED"] = "conversation.chat.failed";
3282
- ChatEventType["CONVERSATION_CHAT_REQUIRES_ACTION"] = "conversation.chat.requires_action";
3283
- ChatEventType["CONVERSATION_MESSAGE_DELTA"] = "conversation.message.delta";
3284
- ChatEventType["CONVERSATION_MESSAGE_COMPLETED"] = "conversation.message.completed";
3285
- ChatEventType["CONVERSATION_AUDIO_DELTA"] = "conversation.audio.delta";
3286
- ChatEventType["DONE"] = "done";
3287
- ChatEventType["ERROR"] = "error";
3288
- return ChatEventType;
3289
- }({});
3290
- class messages_Messages extends APIResource {
3291
- /**
3292
- * Create a message and add it to the specified conversation. | 创建一条消息,并将其添加到指定的会话中。
3293
- * @docs en: https://www.coze.com/docs/developer_guides/create_message?_lang=en
3294
- * @docs zh: https://www.coze.cn/docs/developer_guides/create_message?_lang=zh
3295
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3296
- * @param params - Required The parameters for creating a message | 创建消息所需的参数
3297
- * @param params.role - Required The entity that sent this message. Possible values: user, assistant. | 发送这条消息的实体。取值:user, assistant。
3298
- * @param params.content - Required The content of the message. | 消息的内容。
3299
- * @param params.content_type - Required The type of the message content. | 消息内容的类型。
3300
- * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
3301
- * @returns Information about the new message. | 消息详情。
3302
- */ async create(conversation_id, params, options) {
3303
- const apiUrl = `/v1/conversation/message/create?conversation_id=${conversation_id}`;
3304
- const response = await this._client.post(apiUrl, params, false, options);
3305
- return response.data;
3306
- }
3307
- /**
3308
- * Modify a message, supporting the modification of message content, additional content, and message type. | 修改一条消息,支持修改消息内容、附加内容和消息类型。
3309
- * @docs en: https://www.coze.com/docs/developer_guides/modify_message?_lang=en
3310
- * @docs zh: https://www.coze.cn/docs/developer_guides/modify_message?_lang=zh
3311
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3312
- * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
3313
- * @param params - Required The parameters for modifying a message | 修改消息所需的参数
3314
- * @param params.meta_data - Optional Additional information when modifying a message. | 修改消息时的附加消息。
3315
- * @param params.content - Optional The content of the message. | 消息的内容。
3316
- * @param params.content_type - Optional The type of the message content. | 消息内容的类型。
3317
- * @returns Information about the modified message. | 消息详情。
3318
- */ // eslint-disable-next-line max-params
3319
- async update(conversation_id, message_id, params, options) {
3320
- const apiUrl = `/v1/conversation/message/modify?conversation_id=${conversation_id}&message_id=${message_id}`;
3321
- const response = await this._client.post(apiUrl, params, false, options);
3322
- return response.message;
3323
- }
3324
- /**
3325
- * Get the detailed information of specified message. | 查看指定消息的详细信息。
3326
- * @docs en: https://www.coze.com/docs/developer_guides/retrieve_message?_lang=en
3327
- * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_message?_lang=zh
3328
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3329
- * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
3330
- * @returns Information about the message. | 消息详情。
3331
- */ async retrieve(conversation_id, message_id, options) {
3332
- const apiUrl = `/v1/conversation/message/retrieve?conversation_id=${conversation_id}&message_id=${message_id}`;
3333
- const response = await this._client.get(apiUrl, null, false, options);
3334
- return response.data;
3158
+ };
3159
+ });
3160
+ utils.forEach([
3161
+ 'post',
3162
+ 'put',
3163
+ 'patch'
3164
+ ], function(method) {
3165
+ /*eslint func-names:0*/ function generateHTTPMethod(isForm) {
3166
+ return function(url, data, config) {
3167
+ return this.request(mergeConfig_mergeConfig(config || {}, {
3168
+ method,
3169
+ headers: isForm ? {
3170
+ 'Content-Type': 'multipart/form-data'
3171
+ } : {},
3172
+ url,
3173
+ data
3174
+ }));
3175
+ };
3335
3176
  }
3336
- /**
3337
- * List messages in a conversation. | 列出会话中的消息。
3338
- * @docs en: https://www.coze.com/docs/developer_guides/message_list?_lang=en
3339
- * @docs zh: https://www.coze.cn/docs/developer_guides/message_list?_lang=zh
3340
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3341
- * @param params - Optional The parameters for listing messages | 列出消息所需的参数
3342
- * @param params.order - Optional The order of the messages. | 消息的顺序。
3343
- * @param params.chat_id - Optional The ID of the chat. | 聊天 ID。
3344
- * @param params.before_id - Optional The ID of the message before which to list. | 列出此消息之前的消息 ID。
3345
- * @param params.after_id - Optional The ID of the message after which to list. | 列出此消息之后的消息 ID。
3346
- * @param params.limit - Optional The maximum number of messages to return. | 返回的最大消息数。
3347
- * @returns A list of messages. | 消息列表。
3348
- */ async list(conversation_id, params, options) {
3349
- const apiUrl = `/v1/conversation/message/list?conversation_id=${conversation_id}`;
3350
- const response = await this._client.post(apiUrl, params, false, options);
3351
- return response;
3177
+ Axios_Axios.prototype[method] = generateHTTPMethod();
3178
+ Axios_Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
3179
+ });
3180
+ /* ESM default export */ const Axios = Axios_Axios;
3181
+ /**
3182
+ * A `CancelToken` is an object that can be used to request cancellation of an operation.
3183
+ *
3184
+ * @param {Function} executor The executor function.
3185
+ *
3186
+ * @returns {CancelToken}
3187
+ */ class CancelToken_CancelToken {
3188
+ constructor(executor){
3189
+ if ('function' != typeof executor) throw new TypeError('executor must be a function.');
3190
+ let resolvePromise;
3191
+ this.promise = new Promise(function(resolve) {
3192
+ resolvePromise = resolve;
3193
+ });
3194
+ const token = this;
3195
+ // eslint-disable-next-line func-names
3196
+ this.promise.then((cancel)=>{
3197
+ if (!token._listeners) return;
3198
+ let i = token._listeners.length;
3199
+ while(i-- > 0)token._listeners[i](cancel);
3200
+ token._listeners = null;
3201
+ });
3202
+ // eslint-disable-next-line func-names
3203
+ this.promise.then = (onfulfilled)=>{
3204
+ let _resolve;
3205
+ // eslint-disable-next-line func-names
3206
+ const promise = new Promise((resolve)=>{
3207
+ token.subscribe(resolve);
3208
+ _resolve = resolve;
3209
+ }).then(onfulfilled);
3210
+ promise.cancel = function() {
3211
+ token.unsubscribe(_resolve);
3212
+ };
3213
+ return promise;
3214
+ };
3215
+ executor(function(message, config, request) {
3216
+ if (token.reason) // Cancellation has already been requested
3217
+ return;
3218
+ token.reason = new CanceledError(message, config, request);
3219
+ resolvePromise(token.reason);
3220
+ });
3352
3221
  }
3353
3222
  /**
3354
- * Call the API to delete a message within a specified conversation. | 调用接口在指定会话中删除消息。
3355
- * @docs en: https://www.coze.com/docs/developer_guides/delete_message?_lang=en
3356
- * @docs zh: https://www.coze.cn/docs/developer_guides/delete_message?_lang=zh
3357
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3358
- * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
3359
- * @returns Details of the deleted message. | 已删除的消息详情。
3360
- */ async delete(conversation_id, message_id, options) {
3361
- const apiUrl = `/v1/conversation/message/delete?conversation_id=${conversation_id}&message_id=${message_id}`;
3362
- const response = await this._client.post(apiUrl, void 0, false, options);
3363
- return response.data;
3223
+ * Throws a `CanceledError` if cancellation has been requested.
3224
+ */ throwIfRequested() {
3225
+ if (this.reason) throw this.reason;
3364
3226
  }
3365
- }
3366
- class Conversations extends APIResource {
3367
3227
  /**
3368
- * Create a conversation. Conversation is an interaction between an agent and a user, including one or more messages. | 调用接口创建一个会话。
3369
- * @docs en: https://www.coze.com/docs/developer_guides/create_conversation?_lang=en
3370
- * @docs zh: https://www.coze.cn/docs/developer_guides/create_conversation?_lang=zh
3371
- * @param params - Required The parameters for creating a conversation | 创建会话所需的参数
3372
- * @param params.messages - Optional Messages in the conversation. | 会话中的消息内容。
3373
- * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
3374
- * @param params.bot_id - Optional Bind and isolate conversation on different bots. | 绑定和隔离不同Bot的会话。
3375
- * @returns Information about the created conversation. | 会话的基础信息。
3376
- */ async create(params, options) {
3377
- const apiUrl = '/v1/conversation/create';
3378
- const response = await this._client.post(apiUrl, params, false, options);
3379
- return response.data;
3228
+ * Subscribe to the cancel signal
3229
+ */ subscribe(listener) {
3230
+ if (this.reason) {
3231
+ listener(this.reason);
3232
+ return;
3233
+ }
3234
+ if (this._listeners) this._listeners.push(listener);
3235
+ else this._listeners = [
3236
+ listener
3237
+ ];
3380
3238
  }
3381
3239
  /**
3382
- * Get the information of specific conversation. | 通过会话 ID 查看会话信息。
3383
- * @docs en: https://www.coze.com/docs/developer_guides/retrieve_conversation?_lang=en
3384
- * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_conversation?_lang=zh
3385
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3386
- * @returns Information about the conversation. | 会话的基础信息。
3387
- */ async retrieve(conversation_id, options) {
3388
- const apiUrl = `/v1/conversation/retrieve?conversation_id=${conversation_id}`;
3389
- const response = await this._client.get(apiUrl, null, false, options);
3390
- return response.data;
3240
+ * Unsubscribe from the cancel signal
3241
+ */ unsubscribe(listener) {
3242
+ if (!this._listeners) return;
3243
+ const index = this._listeners.indexOf(listener);
3244
+ if (-1 !== index) this._listeners.splice(index, 1);
3391
3245
  }
3392
- /**
3393
- * List all conversations. | 列出 Bot 下所有会话。
3394
- * @param params
3395
- * @param params.bot_id - Required Bot ID. | Bot ID。
3396
- * @param params.page_num - Optional The page number. | 页码,默认值为 1。
3397
- * @param params.page_size - Optional The number of conversations per page. | 每页的会话数量,默认值为 50。
3398
- * @returns Information about the conversations. | 会话的信息。
3399
- */ async list(params, options) {
3400
- const apiUrl = '/v1/conversations';
3401
- const response = await this._client.get(apiUrl, params, false, options);
3402
- return response.data;
3246
+ toAbortSignal() {
3247
+ const controller = new AbortController();
3248
+ const abort = (err)=>{
3249
+ controller.abort(err);
3250
+ };
3251
+ this.subscribe(abort);
3252
+ controller.signal.unsubscribe = ()=>this.unsubscribe(abort);
3253
+ return controller.signal;
3403
3254
  }
3404
3255
  /**
3405
- * Clear a conversation. | 清空会话。
3406
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3407
- * @returns Information about the conversation session. | 会话的会话 ID。
3408
- */ async clear(conversation_id, options) {
3409
- const apiUrl = `/v1/conversations/${conversation_id}/clear`;
3410
- const response = await this._client.post(apiUrl, null, false, options);
3411
- return response.data;
3412
- }
3413
- constructor(...args){
3414
- super(...args), this.messages = new messages_Messages(this._client);
3256
+ * Returns an object that contains a new `CancelToken` and a function that, when called,
3257
+ * cancels the `CancelToken`.
3258
+ */ static source() {
3259
+ let cancel;
3260
+ const token = new CancelToken_CancelToken(function(c) {
3261
+ cancel = c;
3262
+ });
3263
+ return {
3264
+ token,
3265
+ cancel
3266
+ };
3415
3267
  }
3416
3268
  }
3269
+ /* ESM default export */ const CancelToken = CancelToken_CancelToken;
3270
+ /**
3271
+ * Syntactic sugar for invoking a function and expanding an array for arguments.
3272
+ *
3273
+ * Common use case would be to use `Function.prototype.apply`.
3274
+ *
3275
+ * ```js
3276
+ * function f(x, y, z) {}
3277
+ * var args = [1, 2, 3];
3278
+ * f.apply(null, args);
3279
+ * ```
3280
+ *
3281
+ * With `spread` this example can be re-written.
3282
+ *
3283
+ * ```js
3284
+ * spread(function(x, y, z) {})([1, 2, 3]);
3285
+ * ```
3286
+ *
3287
+ * @param {Function} callback
3288
+ *
3289
+ * @returns {Function}
3290
+ */ function spread(callback) {
3291
+ return function(arr) {
3292
+ return callback.apply(null, arr);
3293
+ };
3294
+ }
3295
+ /**
3296
+ * Determines whether the payload is an error thrown by Axios
3297
+ *
3298
+ * @param {*} payload The value to test
3299
+ *
3300
+ * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
3301
+ */ function isAxiosError(payload) {
3302
+ return utils.isObject(payload) && true === payload.isAxiosError;
3303
+ }
3304
+ const HttpStatusCode = {
3305
+ Continue: 100,
3306
+ SwitchingProtocols: 101,
3307
+ Processing: 102,
3308
+ EarlyHints: 103,
3309
+ Ok: 200,
3310
+ Created: 201,
3311
+ Accepted: 202,
3312
+ NonAuthoritativeInformation: 203,
3313
+ NoContent: 204,
3314
+ ResetContent: 205,
3315
+ PartialContent: 206,
3316
+ MultiStatus: 207,
3317
+ AlreadyReported: 208,
3318
+ ImUsed: 226,
3319
+ MultipleChoices: 300,
3320
+ MovedPermanently: 301,
3321
+ Found: 302,
3322
+ SeeOther: 303,
3323
+ NotModified: 304,
3324
+ UseProxy: 305,
3325
+ Unused: 306,
3326
+ TemporaryRedirect: 307,
3327
+ PermanentRedirect: 308,
3328
+ BadRequest: 400,
3329
+ Unauthorized: 401,
3330
+ PaymentRequired: 402,
3331
+ Forbidden: 403,
3332
+ NotFound: 404,
3333
+ MethodNotAllowed: 405,
3334
+ NotAcceptable: 406,
3335
+ ProxyAuthenticationRequired: 407,
3336
+ RequestTimeout: 408,
3337
+ Conflict: 409,
3338
+ Gone: 410,
3339
+ LengthRequired: 411,
3340
+ PreconditionFailed: 412,
3341
+ PayloadTooLarge: 413,
3342
+ UriTooLong: 414,
3343
+ UnsupportedMediaType: 415,
3344
+ RangeNotSatisfiable: 416,
3345
+ ExpectationFailed: 417,
3346
+ ImATeapot: 418,
3347
+ MisdirectedRequest: 421,
3348
+ UnprocessableEntity: 422,
3349
+ Locked: 423,
3350
+ FailedDependency: 424,
3351
+ TooEarly: 425,
3352
+ UpgradeRequired: 426,
3353
+ PreconditionRequired: 428,
3354
+ TooManyRequests: 429,
3355
+ RequestHeaderFieldsTooLarge: 431,
3356
+ UnavailableForLegalReasons: 451,
3357
+ InternalServerError: 500,
3358
+ NotImplemented: 501,
3359
+ BadGateway: 502,
3360
+ ServiceUnavailable: 503,
3361
+ GatewayTimeout: 504,
3362
+ HttpVersionNotSupported: 505,
3363
+ VariantAlsoNegotiates: 506,
3364
+ InsufficientStorage: 507,
3365
+ LoopDetected: 508,
3366
+ NotExtended: 510,
3367
+ NetworkAuthenticationRequired: 511
3368
+ };
3369
+ Object.entries(HttpStatusCode).forEach(([key, value])=>{
3370
+ HttpStatusCode[value] = key;
3371
+ });
3372
+ /* ESM default export */ const helpers_HttpStatusCode = HttpStatusCode;
3373
+ /**
3374
+ * Create an instance of Axios
3375
+ *
3376
+ * @param {Object} defaultConfig The default config for the instance
3377
+ *
3378
+ * @returns {Axios} A new instance of Axios
3379
+ */ function createInstance(defaultConfig) {
3380
+ const context = new Axios(defaultConfig);
3381
+ const instance = bind(Axios.prototype.request, context);
3382
+ // Copy axios.prototype to instance
3383
+ utils.extend(instance, Axios.prototype, context, {
3384
+ allOwnKeys: true
3385
+ });
3386
+ // Copy context to instance
3387
+ utils.extend(instance, context, null, {
3388
+ allOwnKeys: true
3389
+ });
3390
+ // Factory for creating new instances
3391
+ instance.create = function(instanceConfig) {
3392
+ return createInstance(mergeConfig_mergeConfig(defaultConfig, instanceConfig));
3393
+ };
3394
+ return instance;
3395
+ }
3396
+ // Create the default instance to be exported
3397
+ const axios = createInstance(defaults);
3398
+ // Expose Axios class to allow class inheritance
3399
+ axios.Axios = Axios;
3400
+ // Expose Cancel & CancelToken
3401
+ axios.CanceledError = CanceledError;
3402
+ axios.CancelToken = CancelToken;
3403
+ axios.isCancel = isCancel;
3404
+ axios.VERSION = VERSION;
3405
+ axios.toFormData = toFormData;
3406
+ // Expose AxiosError class
3407
+ axios.AxiosError = core_AxiosError;
3408
+ // alias for CanceledError for backward compatibility
3409
+ axios.Cancel = axios.CanceledError;
3410
+ // Expose all/spread
3411
+ axios.all = function(promises) {
3412
+ return Promise.all(promises);
3413
+ };
3414
+ axios.spread = spread;
3415
+ // Expose isAxiosError
3416
+ axios.isAxiosError = isAxiosError;
3417
+ // Expose mergeConfig
3418
+ axios.mergeConfig = mergeConfig_mergeConfig;
3419
+ axios.AxiosHeaders = AxiosHeaders;
3420
+ axios.formToJSON = (thing)=>formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
3421
+ axios.getAdapter = adapters_adapters.getAdapter;
3422
+ axios.HttpStatusCode = helpers_HttpStatusCode;
3423
+ axios.default = axios;
3424
+ // this module should only have a default export
3425
+ /* ESM default export */ const lib_axios = axios;
3426
+ // This module is intended to unwrap Axios default export as named.
3427
+ // Keep top-level export same with static properties
3428
+ // so that it can keep same with es module or cjs
3429
+ 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;
3417
3430
  class Files extends APIResource {
3418
3431
  /**
3419
3432
  * Upload files to Coze platform. | 调用接口上传文件到扣子。
@@ -3493,6 +3506,17 @@ class Runs extends APIResource {
3493
3506
  const response = await this._client.post(apiUrl, params, false, options);
3494
3507
  return response;
3495
3508
  }
3509
+ /**
3510
+ * Get the workflow run history | 工作流异步运行后,查看执行结果
3511
+ * @docs zh: https://www.coze.cn/open/docs/developer_guides/workflow_history
3512
+ * @param workflowId - Required The ID of the workflow. | 必选 工作流 ID。
3513
+ * @param executeId - Required The ID of the workflow execution. | 必选 工作流执行 ID。
3514
+ * @returns WorkflowExecuteHistory[] | 工作流执行历史
3515
+ */ async history(workflowId, executeId, options) {
3516
+ const apiUrl = `/v1/workflows/${workflowId}/run_histories/${executeId}`;
3517
+ const response = await this._client.get(apiUrl, void 0, false, options);
3518
+ return response.data;
3519
+ }
3496
3520
  }
3497
3521
  class WorkflowEvent {
3498
3522
  constructor(id, event, data){
@@ -3576,7 +3600,7 @@ class Documents extends APIResource {
3576
3600
  * @returns ListDocumentData | 知识库文件列表
3577
3601
  */ list(params, options) {
3578
3602
  const apiUrl = '/open_api/knowledge/document/list';
3579
- const response = this._client.get(apiUrl, params, false, esm_mergeConfig(options, {
3603
+ const response = this._client.get(apiUrl, params, false, mergeConfig(options, {
3580
3604
  headers: documents_headers
3581
3605
  }));
3582
3606
  return response;
@@ -3594,7 +3618,7 @@ class Documents extends APIResource {
3594
3618
  * @returns DocumentInfo[] | 已上传文件的基本信息
3595
3619
  */ async create(params, options) {
3596
3620
  const apiUrl = '/open_api/knowledge/document/create';
3597
- const response = await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3621
+ const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
3598
3622
  headers: documents_headers
3599
3623
  }));
3600
3624
  return response.document_infos;
@@ -3610,7 +3634,7 @@ class Documents extends APIResource {
3610
3634
  * @returns void | 无返回
3611
3635
  */ async delete(params, options) {
3612
3636
  const apiUrl = '/open_api/knowledge/document/delete';
3613
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3637
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3614
3638
  headers: documents_headers
3615
3639
  }));
3616
3640
  }
@@ -3626,7 +3650,7 @@ class Documents extends APIResource {
3626
3650
  * @returns void | 无返回
3627
3651
  */ async update(params, options) {
3628
3652
  const apiUrl = '/open_api/knowledge/document/update';
3629
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3653
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3630
3654
  headers: documents_headers
3631
3655
  }));
3632
3656
  }
@@ -3654,7 +3678,7 @@ class documents_Documents extends APIResource {
3654
3678
  * @returns ListDocumentData | 知识库文件列表
3655
3679
  */ async list(params, options) {
3656
3680
  const apiUrl = '/open_api/knowledge/document/list';
3657
- const response = await this._client.get(apiUrl, params, false, esm_mergeConfig(options, {
3681
+ const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
3658
3682
  headers: documents_documents_headers
3659
3683
  }));
3660
3684
  return response;
@@ -3670,7 +3694,7 @@ class documents_Documents extends APIResource {
3670
3694
  * @returns DocumentInfo[] | 已上传文件的基本信息
3671
3695
  */ async create(params, options) {
3672
3696
  const apiUrl = '/open_api/knowledge/document/create';
3673
- const response = await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3697
+ const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
3674
3698
  headers: documents_documents_headers
3675
3699
  }));
3676
3700
  return response.document_infos;
@@ -3684,7 +3708,7 @@ class documents_Documents extends APIResource {
3684
3708
  * @returns void | 无返回
3685
3709
  */ async delete(params, options) {
3686
3710
  const apiUrl = '/open_api/knowledge/document/delete';
3687
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3711
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3688
3712
  headers: documents_documents_headers
3689
3713
  }));
3690
3714
  }
@@ -3698,7 +3722,7 @@ class documents_Documents extends APIResource {
3698
3722
  * @returns void | 无返回
3699
3723
  */ async update(params, options) {
3700
3724
  const apiUrl = '/open_api/knowledge/document/update';
3701
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3725
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3702
3726
  headers: documents_documents_headers
3703
3727
  }));
3704
3728
  }
@@ -3820,6 +3844,8 @@ class Voices extends APIResource {
3820
3844
  * | 如果传入会基于该文本生成预览音频,否则使用默认的文本
3821
3845
  * @param params.text - Optional. Users can read this text, service will compare audio with text. Returns error if difference is too large
3822
3846
  * | 可以让用户按照该文本念诵,服务会对比音频与该文本的差异。若差异过大会返回错误
3847
+ * @param params.space_id - Optional. The space id of the voice. | 空间ID
3848
+ * @param params.description- Optional. The description of the voice. | 音色描述
3823
3849
  * @param options - Request options
3824
3850
  * @returns Clone voice data
3825
3851
  */ async clone(params, options) {
@@ -3844,6 +3870,17 @@ class Voices extends APIResource {
3844
3870
  return response.data;
3845
3871
  }
3846
3872
  }
3873
+ class Transcriptions extends APIResource {
3874
+ /**
3875
+ * ASR voice to text | ASR 语音转文本
3876
+ * @param params - Required The parameters for file upload | 上传文件所需的参数
3877
+ * @param params.file - Required The audio file to be uploaded. | 需要上传的音频文件。
3878
+ */ async create(params, options) {
3879
+ const apiUrl = '/v1/audio/transcriptions';
3880
+ const response = await this._client.post(apiUrl, axios_toFormData(params), false, options);
3881
+ return response.data;
3882
+ }
3883
+ }
3847
3884
  class Speech extends APIResource {
3848
3885
  /**
3849
3886
  * @description Speech synthesis | 语音合成
@@ -3860,7 +3897,7 @@ class Speech extends APIResource {
3860
3897
  const response = await this._client.post(apiUrl, {
3861
3898
  ...params,
3862
3899
  sample_rate: params.sample_rate || 24000
3863
- }, false, esm_mergeConfig(options, {
3900
+ }, false, mergeConfig(options, {
3864
3901
  responseType: 'arraybuffer'
3865
3902
  }));
3866
3903
  return response;
@@ -3873,9 +3910,9 @@ class Rooms extends APIResource {
3873
3910
  return response.data;
3874
3911
  }
3875
3912
  }
3876
- class esm_Audio extends APIResource {
3913
+ class audio_Audio extends APIResource {
3877
3914
  constructor(...args){
3878
- super(...args), this.rooms = new Rooms(this._client), this.voices = new Voices(this._client), this.speech = new Speech(this._client);
3915
+ super(...args), this.rooms = new Rooms(this._client), this.voices = new Voices(this._client), this.speech = new Speech(this._client), this.transcriptions = new Transcriptions(this._client);
3879
3916
  }
3880
3917
  }
3881
3918
  class Templates extends APIResource {
@@ -3892,18 +3929,716 @@ class Templates extends APIResource {
3892
3929
  return response.data;
3893
3930
  }
3894
3931
  }
3895
- var package_namespaceObject = JSON.parse('{"name":"@coze/api","version":"1.0.16","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","README.zh-CN.md"],"scripts":{"build":"rm -rf dist && rslib build","format":"prettier --write .","lint":"eslint ./ --cache --quiet","start":"rm -rf dist && rslib build -w","test":"vitest","test:cov":"vitest --coverage --run"},"dependencies":{"jsonwebtoken":"^9.0.2"},"devDependencies":{"@coze-infra/eslint-config":"workspace:*","@coze-infra/ts-config":"workspace:*","@coze-infra/vitest-config":"workspace:*","@rslib/core":"0.0.18","@swc/core":"^1.3.14","@types/jsonwebtoken":"^9.0.0","@types/node":"^20","@types/uuid":"^9.0.1","@types/whatwg-fetch":"^0.0.33","@vitest/coverage-v8":"~2.1.4","axios":"^1.7.7","typescript":"^5.5.3","vitest":"~2.1.4"},"peerDependencies":{"axios":"^1.7.1"}}'); // CONCATENATED MODULE: ./src/version.ts
3896
- const { version: esm_version } = package_namespaceObject;
3932
+ class chat_Chat extends APIResource {
3933
+ async create(botId, options) {
3934
+ const apiUrl = `/v1/chat?bot_id=${botId}`;
3935
+ return await this._client.makeWebsocket(apiUrl, options);
3936
+ }
3937
+ }
3938
+ class transcriptions_Transcriptions extends APIResource {
3939
+ async create(options) {
3940
+ const apiUrl = '/v1/audio/transcriptions';
3941
+ return await this._client.makeWebsocket(apiUrl, options);
3942
+ }
3943
+ }
3944
+ class speech_Speech extends APIResource {
3945
+ async create(options) {
3946
+ const apiUrl = '/v1/audio/speech';
3947
+ return await this._client.makeWebsocket(apiUrl, options);
3948
+ }
3949
+ }
3950
+ class websockets_audio_Audio extends APIResource {
3951
+ constructor(...args){
3952
+ super(...args), this.speech = new speech_Speech(this._client), this.transcriptions = new transcriptions_Transcriptions(this._client);
3953
+ }
3954
+ }
3955
+ // Common types (not exported)
3956
+ // Keep all existing exports but use the base types where applicable
3957
+ var types_WebsocketsEventType = /*#__PURE__*/ function(WebsocketsEventType) {
3958
+ // Common
3959
+ /** SDK error */ WebsocketsEventType["CLIENT_ERROR"] = "client_error";
3960
+ /** Connection closed */ WebsocketsEventType["CLOSED"] = "closed";
3961
+ // Error
3962
+ /** Received error event */ WebsocketsEventType["ERROR"] = "error";
3963
+ // v1/audio/speech
3964
+ /** Send text to server */ WebsocketsEventType["INPUT_TEXT_BUFFER_APPEND"] = "input_text_buffer.append";
3965
+ /** No text to send, after audio all received, can close connection */ WebsocketsEventType["INPUT_TEXT_BUFFER_COMPLETE"] = "input_text_buffer.complete";
3966
+ /** Send speech config to server */ WebsocketsEventType["SPEECH_UPDATE"] = "speech.update";
3967
+ /** Received `speech.updated` event */ WebsocketsEventType["SPEECH_UPDATED"] = "speech.updated";
3968
+ /** After speech created */ WebsocketsEventType["SPEECH_CREATED"] = "speech.created";
3969
+ /** Received `input_text_buffer.complete` event */ WebsocketsEventType["INPUT_TEXT_BUFFER_COMPLETED"] = "input_text_buffer.completed";
3970
+ /** Received `speech.update` event */ WebsocketsEventType["SPEECH_AUDIO_UPDATE"] = "speech.audio.update";
3971
+ /** All audio received, can close connection */ WebsocketsEventType["SPEECH_AUDIO_COMPLETED"] = "speech.audio.completed";
3972
+ // v1/audio/transcriptions
3973
+ /** Send audio to server */ WebsocketsEventType["INPUT_AUDIO_BUFFER_APPEND"] = "input_audio_buffer.append";
3974
+ /** No audio to send, after text all received, can close connection */ WebsocketsEventType["INPUT_AUDIO_BUFFER_COMPLETE"] = "input_audio_buffer.complete";
3975
+ /** Send transcriptions config to server */ WebsocketsEventType["TRANSCRIPTIONS_UPDATE"] = "transcriptions.update";
3976
+ /** Send `input_audio_buffer.clear` event */ WebsocketsEventType["INPUT_AUDIO_BUFFER_CLEAR"] = "input_audio_buffer.clear";
3977
+ /** After transcriptions created */ WebsocketsEventType["TRANSCRIPTIONS_CREATED"] = "transcriptions.created";
3978
+ /** Received `input_audio_buffer.complete` event */ WebsocketsEventType["INPUT_AUDIO_BUFFER_COMPLETED"] = "input_audio_buffer.completed";
3979
+ /** Received `transcriptions.update` event */ WebsocketsEventType["TRANSCRIPTIONS_MESSAGE_UPDATE"] = "transcriptions.message.update";
3980
+ /** All audio received, can close connection */ WebsocketsEventType["TRANSCRIPTIONS_MESSAGE_COMPLETED"] = "transcriptions.message.completed";
3981
+ /** Received `input_audio_buffer.cleared` event */ WebsocketsEventType["INPUT_AUDIO_BUFFER_CLEARED"] = "input_audio_buffer.cleared";
3982
+ /** Received `transcriptions.updated` event */ WebsocketsEventType["TRANSCRIPTIONS_UPDATED"] = "transcriptions.updated";
3983
+ // v1/chat
3984
+ /** Send chat config to server */ WebsocketsEventType["CHAT_UPDATE"] = "chat.update";
3985
+ /** Send tool outputs to server */ WebsocketsEventType["CONVERSATION_CHAT_SUBMIT_TOOL_OUTPUTS"] = "conversation.chat.submit_tool_outputs";
3986
+ /** After chat created */ WebsocketsEventType["CHAT_CREATED"] = "chat.created";
3987
+ /** After chat updated */ WebsocketsEventType["CHAT_UPDATED"] = "chat.updated";
3988
+ /** Audio AST completed, chat started */ WebsocketsEventType["CONVERSATION_CHAT_CREATED"] = "conversation.chat.created";
3989
+ /** Message created */ WebsocketsEventType["CONVERSATION_MESSAGE_CREATE"] = "conversation.message.create";
3990
+ /** Clear conversation */ WebsocketsEventType["CONVERSATION_CLEAR"] = "conversation.clear";
3991
+ /** Chat in progress */ WebsocketsEventType["CONVERSATION_CHAT_IN_PROGRESS"] = "conversation.chat.in_progress";
3992
+ /** Get agent text message update */ WebsocketsEventType["CONVERSATION_MESSAGE_DELTA"] = "conversation.message.delta";
3993
+ /** Need plugin submit */ WebsocketsEventType["CONVERSATION_CHAT_REQUIRES_ACTION"] = "conversation.chat.requires_action";
3994
+ /** Message completed */ WebsocketsEventType["CONVERSATION_MESSAGE_COMPLETED"] = "conversation.message.completed";
3995
+ /** Get agent audio message update */ WebsocketsEventType["CONVERSATION_AUDIO_DELTA"] = "conversation.audio.delta";
3996
+ /** Audio message completed */ WebsocketsEventType["CONVERSATION_AUDIO_COMPLETED"] = "conversation.audio.completed";
3997
+ /** All message received, can close connection */ WebsocketsEventType["CONVERSATION_CHAT_COMPLETED"] = "conversation.chat.completed";
3998
+ /** Chat failed */ WebsocketsEventType["CONVERSATION_CHAT_FAILED"] = "conversation.chat.failed";
3999
+ /** Received `conversation.cleared` event */ WebsocketsEventType["CONVERSATION_CLEARED"] = "conversation.cleared";
4000
+ return WebsocketsEventType;
4001
+ }({});
4002
+ class Websockets extends APIResource {
4003
+ constructor(...args){
4004
+ super(...args), this.audio = new websockets_audio_Audio(this._client), this.chat = new chat_Chat(this._client);
4005
+ }
4006
+ }
4007
+ // EXTERNAL MODULE: ../../common/temp/default/node_modules/.pnpm/ws@8.18.0/node_modules/ws/browser.js
4008
+ var ws_browser = __webpack_require__("../../common/temp/default/node_modules/.pnpm/ws@8.18.0/node_modules/ws/browser.js");
4009
+ var browser_default = /*#__PURE__*/ __webpack_require__.n(ws_browser);
4010
+ /*! *****************************************************************************
4011
+ Copyright (c) Microsoft Corporation. All rights reserved.
4012
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
4013
+ this file except in compliance with the License. You may obtain a copy of the
4014
+ License at http://www.apache.org/licenses/LICENSE-2.0
4015
+
4016
+ THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
4017
+ KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
4018
+ WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
4019
+ MERCHANTABLITY OR NON-INFRINGEMENT.
4020
+
4021
+ See the Apache Version 2.0 License for specific language governing permissions
4022
+ and limitations under the License.
4023
+ ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function(d, b) {
4024
+ extendStatics = Object.setPrototypeOf || ({
4025
+ __proto__: []
4026
+ }) instanceof Array && function(d, b) {
4027
+ d.__proto__ = b;
4028
+ } || function(d, b) {
4029
+ for(var p in b)if (b.hasOwnProperty(p)) d[p] = b[p];
4030
+ };
4031
+ return extendStatics(d, b);
4032
+ };
4033
+ function __extends(d, b) {
4034
+ extendStatics(d, b);
4035
+ function __() {
4036
+ this.constructor = d;
4037
+ }
4038
+ d.prototype = null === b ? Object.create(b) : (__.prototype = b.prototype, new __());
4039
+ }
4040
+ function __values(o) {
4041
+ var m = "function" == typeof Symbol && o[Symbol.iterator], i = 0;
4042
+ if (m) return m.call(o);
4043
+ return {
4044
+ next: function() {
4045
+ if (o && i >= o.length) o = void 0;
4046
+ return {
4047
+ value: o && o[i++],
4048
+ done: !o
4049
+ };
4050
+ }
4051
+ };
4052
+ }
4053
+ function __read(o, n) {
4054
+ var m = "function" == typeof Symbol && o[Symbol.iterator];
4055
+ if (!m) return o;
4056
+ var i = m.call(o), r, ar = [], e;
4057
+ try {
4058
+ while((void 0 === n || n-- > 0) && !(r = i.next()).done)ar.push(r.value);
4059
+ } catch (error) {
4060
+ e = {
4061
+ error: error
4062
+ };
4063
+ } finally{
4064
+ try {
4065
+ if (r && !r.done && (m = i["return"])) m.call(i);
4066
+ } finally{
4067
+ if (e) throw e.error;
4068
+ }
4069
+ }
4070
+ return ar;
4071
+ }
4072
+ function __spread() {
4073
+ for(var ar = [], i = 0; i < arguments.length; i++)ar = ar.concat(__read(arguments[i]));
4074
+ return ar;
4075
+ }
4076
+ var reconnecting_websocket_mjs_Event = /** @class */ function() {
4077
+ function Event1(type, target) {
4078
+ this.target = target;
4079
+ this.type = type;
4080
+ }
4081
+ return Event1;
4082
+ }();
4083
+ var reconnecting_websocket_mjs_ErrorEvent = /** @class */ function(_super) {
4084
+ __extends(ErrorEvent, _super);
4085
+ function ErrorEvent(error, target) {
4086
+ var _this = _super.call(this, 'error', target) || this;
4087
+ _this.message = error.message;
4088
+ _this.error = error;
4089
+ return _this;
4090
+ }
4091
+ return ErrorEvent;
4092
+ }(reconnecting_websocket_mjs_Event);
4093
+ var reconnecting_websocket_mjs_CloseEvent = /** @class */ function(_super) {
4094
+ __extends(CloseEvent, _super);
4095
+ function CloseEvent(code, reason, target) {
4096
+ if (void 0 === code) code = 1000;
4097
+ if (void 0 === reason) reason = '';
4098
+ var _this = _super.call(this, 'close', target) || this;
4099
+ _this.wasClean = true;
4100
+ _this.code = code;
4101
+ _this.reason = reason;
4102
+ return _this;
4103
+ }
4104
+ return CloseEvent;
4105
+ }(reconnecting_websocket_mjs_Event);
4106
+ /*!
4107
+ * Reconnecting WebSocket
4108
+ * by Pedro Ladaria <pedro.ladaria@gmail.com>
4109
+ * https://github.com/pladaria/reconnecting-websocket
4110
+ * License MIT
4111
+ */ var getGlobalWebSocket = function() {
4112
+ if ('undefined' != typeof WebSocket) // @ts-ignore
4113
+ return WebSocket;
4114
+ };
4115
+ /**
4116
+ * Returns true if given argument looks like a WebSocket class
4117
+ */ var isWebSocket = function(w) {
4118
+ return void 0 !== w && !!w && 2 === w.CLOSING;
4119
+ };
4120
+ var DEFAULT = {
4121
+ maxReconnectionDelay: 10000,
4122
+ minReconnectionDelay: 1000 + 4000 * Math.random(),
4123
+ minUptime: 5000,
4124
+ reconnectionDelayGrowFactor: 1.3,
4125
+ connectionTimeout: 4000,
4126
+ maxRetries: 1 / 0,
4127
+ maxEnqueuedMessages: 1 / 0,
4128
+ startClosed: false,
4129
+ debug: false
4130
+ };
4131
+ var reconnecting_websocket_mjs_ReconnectingWebSocket = /** @class */ function() {
4132
+ function ReconnectingWebSocket(url, protocols, options) {
4133
+ var _this = this;
4134
+ if (void 0 === options) options = {};
4135
+ this._listeners = {
4136
+ error: [],
4137
+ message: [],
4138
+ open: [],
4139
+ close: []
4140
+ };
4141
+ this._retryCount = -1;
4142
+ this._shouldReconnect = true;
4143
+ this._connectLock = false;
4144
+ this._binaryType = 'blob';
4145
+ this._closeCalled = false;
4146
+ this._messageQueue = [];
4147
+ /**
4148
+ * An event listener to be called when the WebSocket connection's readyState changes to CLOSED
4149
+ */ this.onclose = null;
4150
+ /**
4151
+ * An event listener to be called when an error occurs
4152
+ */ this.onerror = null;
4153
+ /**
4154
+ * An event listener to be called when a message is received from the server
4155
+ */ this.onmessage = null;
4156
+ /**
4157
+ * An event listener to be called when the WebSocket connection's readyState changes to OPEN;
4158
+ * this indicates that the connection is ready to send and receive data
4159
+ */ this.onopen = null;
4160
+ this._handleOpen = function(event) {
4161
+ _this._debug('open event');
4162
+ var _a = _this._options.minUptime, minUptime = void 0 === _a ? DEFAULT.minUptime : _a;
4163
+ clearTimeout(_this._connectTimeout);
4164
+ _this._uptimeTimeout = setTimeout(function() {
4165
+ return _this._acceptOpen();
4166
+ }, minUptime);
4167
+ _this._ws.binaryType = _this._binaryType;
4168
+ // send enqueued messages (messages sent before websocket open event)
4169
+ _this._messageQueue.forEach(function(message) {
4170
+ return _this._ws.send(message);
4171
+ });
4172
+ _this._messageQueue = [];
4173
+ if (_this.onopen) _this.onopen(event);
4174
+ _this._listeners.open.forEach(function(listener) {
4175
+ return _this._callEventListener(event, listener);
4176
+ });
4177
+ };
4178
+ this._handleMessage = function(event) {
4179
+ _this._debug('message event');
4180
+ if (_this.onmessage) _this.onmessage(event);
4181
+ _this._listeners.message.forEach(function(listener) {
4182
+ return _this._callEventListener(event, listener);
4183
+ });
4184
+ };
4185
+ this._handleError = function(event) {
4186
+ _this._debug('error event', event.message);
4187
+ _this._disconnect(void 0, 'TIMEOUT' === event.message ? 'timeout' : void 0);
4188
+ if (_this.onerror) _this.onerror(event);
4189
+ _this._debug('exec error listeners');
4190
+ _this._listeners.error.forEach(function(listener) {
4191
+ return _this._callEventListener(event, listener);
4192
+ });
4193
+ _this._connect();
4194
+ };
4195
+ this._handleClose = function(event) {
4196
+ _this._debug('close event');
4197
+ _this._clearTimeouts();
4198
+ if (_this._shouldReconnect) _this._connect();
4199
+ if (_this.onclose) _this.onclose(event);
4200
+ _this._listeners.close.forEach(function(listener) {
4201
+ return _this._callEventListener(event, listener);
4202
+ });
4203
+ };
4204
+ this._url = url;
4205
+ this._protocols = protocols;
4206
+ this._options = options;
4207
+ if (this._options.startClosed) this._shouldReconnect = false;
4208
+ this._connect();
4209
+ }
4210
+ Object.defineProperty(ReconnectingWebSocket, "CONNECTING", {
4211
+ get: function() {
4212
+ return 0;
4213
+ },
4214
+ enumerable: true,
4215
+ configurable: true
4216
+ });
4217
+ Object.defineProperty(ReconnectingWebSocket, "OPEN", {
4218
+ get: function() {
4219
+ return 1;
4220
+ },
4221
+ enumerable: true,
4222
+ configurable: true
4223
+ });
4224
+ Object.defineProperty(ReconnectingWebSocket, "CLOSING", {
4225
+ get: function() {
4226
+ return 2;
4227
+ },
4228
+ enumerable: true,
4229
+ configurable: true
4230
+ });
4231
+ Object.defineProperty(ReconnectingWebSocket, "CLOSED", {
4232
+ get: function() {
4233
+ return 3;
4234
+ },
4235
+ enumerable: true,
4236
+ configurable: true
4237
+ });
4238
+ Object.defineProperty(ReconnectingWebSocket.prototype, "CONNECTING", {
4239
+ get: function() {
4240
+ return ReconnectingWebSocket.CONNECTING;
4241
+ },
4242
+ enumerable: true,
4243
+ configurable: true
4244
+ });
4245
+ Object.defineProperty(ReconnectingWebSocket.prototype, "OPEN", {
4246
+ get: function() {
4247
+ return ReconnectingWebSocket.OPEN;
4248
+ },
4249
+ enumerable: true,
4250
+ configurable: true
4251
+ });
4252
+ Object.defineProperty(ReconnectingWebSocket.prototype, "CLOSING", {
4253
+ get: function() {
4254
+ return ReconnectingWebSocket.CLOSING;
4255
+ },
4256
+ enumerable: true,
4257
+ configurable: true
4258
+ });
4259
+ Object.defineProperty(ReconnectingWebSocket.prototype, "CLOSED", {
4260
+ get: function() {
4261
+ return ReconnectingWebSocket.CLOSED;
4262
+ },
4263
+ enumerable: true,
4264
+ configurable: true
4265
+ });
4266
+ Object.defineProperty(ReconnectingWebSocket.prototype, "binaryType", {
4267
+ get: function() {
4268
+ return this._ws ? this._ws.binaryType : this._binaryType;
4269
+ },
4270
+ set: function(value) {
4271
+ this._binaryType = value;
4272
+ if (this._ws) this._ws.binaryType = value;
4273
+ },
4274
+ enumerable: true,
4275
+ configurable: true
4276
+ });
4277
+ Object.defineProperty(ReconnectingWebSocket.prototype, "retryCount", {
4278
+ /**
4279
+ * Returns the number or connection retries
4280
+ */ get: function() {
4281
+ return Math.max(this._retryCount, 0);
4282
+ },
4283
+ enumerable: true,
4284
+ configurable: true
4285
+ });
4286
+ Object.defineProperty(ReconnectingWebSocket.prototype, "bufferedAmount", {
4287
+ /**
4288
+ * The number of bytes of data that have been queued using calls to send() but not yet
4289
+ * transmitted to the network. This value resets to zero once all queued data has been sent.
4290
+ * This value does not reset to zero when the connection is closed; if you keep calling send(),
4291
+ * this will continue to climb. Read only
4292
+ */ get: function() {
4293
+ var bytes = this._messageQueue.reduce(function(acc, message) {
4294
+ if ('string' == typeof message) acc += message.length; // not byte size
4295
+ else if (message instanceof Blob) acc += message.size;
4296
+ else acc += message.byteLength;
4297
+ return acc;
4298
+ }, 0);
4299
+ return bytes + (this._ws ? this._ws.bufferedAmount : 0);
4300
+ },
4301
+ enumerable: true,
4302
+ configurable: true
4303
+ });
4304
+ Object.defineProperty(ReconnectingWebSocket.prototype, "extensions", {
4305
+ /**
4306
+ * The extensions selected by the server. This is currently only the empty string or a list of
4307
+ * extensions as negotiated by the connection
4308
+ */ get: function() {
4309
+ return this._ws ? this._ws.extensions : '';
4310
+ },
4311
+ enumerable: true,
4312
+ configurable: true
4313
+ });
4314
+ Object.defineProperty(ReconnectingWebSocket.prototype, "protocol", {
4315
+ /**
4316
+ * A string indicating the name of the sub-protocol the server selected;
4317
+ * this will be one of the strings specified in the protocols parameter when creating the
4318
+ * WebSocket object
4319
+ */ get: function() {
4320
+ return this._ws ? this._ws.protocol : '';
4321
+ },
4322
+ enumerable: true,
4323
+ configurable: true
4324
+ });
4325
+ Object.defineProperty(ReconnectingWebSocket.prototype, "readyState", {
4326
+ /**
4327
+ * The current state of the connection; this is one of the Ready state constants
4328
+ */ get: function() {
4329
+ if (this._ws) return this._ws.readyState;
4330
+ return this._options.startClosed ? ReconnectingWebSocket.CLOSED : ReconnectingWebSocket.CONNECTING;
4331
+ },
4332
+ enumerable: true,
4333
+ configurable: true
4334
+ });
4335
+ Object.defineProperty(ReconnectingWebSocket.prototype, "url", {
4336
+ /**
4337
+ * The URL as resolved by the constructor
4338
+ */ get: function() {
4339
+ return this._ws ? this._ws.url : '';
4340
+ },
4341
+ enumerable: true,
4342
+ configurable: true
4343
+ });
4344
+ /**
4345
+ * Closes the WebSocket connection or connection attempt, if any. If the connection is already
4346
+ * CLOSED, this method does nothing
4347
+ */ ReconnectingWebSocket.prototype.close = function(code, reason) {
4348
+ if (void 0 === code) code = 1000;
4349
+ this._closeCalled = true;
4350
+ this._shouldReconnect = false;
4351
+ this._clearTimeouts();
4352
+ if (!this._ws) {
4353
+ this._debug('close enqueued: no ws instance');
4354
+ return;
4355
+ }
4356
+ if (this._ws.readyState === this.CLOSED) {
4357
+ this._debug('close: already closed');
4358
+ return;
4359
+ }
4360
+ this._ws.close(code, reason);
4361
+ };
4362
+ /**
4363
+ * Closes the WebSocket connection or connection attempt and connects again.
4364
+ * Resets retry counter;
4365
+ */ ReconnectingWebSocket.prototype.reconnect = function(code, reason) {
4366
+ this._shouldReconnect = true;
4367
+ this._closeCalled = false;
4368
+ this._retryCount = -1;
4369
+ if (this._ws && this._ws.readyState !== this.CLOSED) {
4370
+ this._disconnect(code, reason);
4371
+ this._connect();
4372
+ } else this._connect();
4373
+ };
4374
+ /**
4375
+ * Enqueue specified data to be transmitted to the server over the WebSocket connection
4376
+ */ ReconnectingWebSocket.prototype.send = function(data) {
4377
+ if (this._ws && this._ws.readyState === this.OPEN) {
4378
+ this._debug('send', data);
4379
+ this._ws.send(data);
4380
+ } else {
4381
+ var _a = this._options.maxEnqueuedMessages, maxEnqueuedMessages = void 0 === _a ? DEFAULT.maxEnqueuedMessages : _a;
4382
+ if (this._messageQueue.length < maxEnqueuedMessages) {
4383
+ this._debug('enqueue', data);
4384
+ this._messageQueue.push(data);
4385
+ }
4386
+ }
4387
+ };
4388
+ /**
4389
+ * Register an event handler of a specific event type
4390
+ */ ReconnectingWebSocket.prototype.addEventListener = function(type, listener) {
4391
+ if (this._listeners[type]) // @ts-ignore
4392
+ this._listeners[type].push(listener);
4393
+ };
4394
+ ReconnectingWebSocket.prototype.dispatchEvent = function(event) {
4395
+ var e_1, _a;
4396
+ var listeners = this._listeners[event.type];
4397
+ if (listeners) try {
4398
+ for(var listeners_1 = __values(listeners), listeners_1_1 = listeners_1.next(); !listeners_1_1.done; listeners_1_1 = listeners_1.next()){
4399
+ var listener = listeners_1_1.value;
4400
+ this._callEventListener(event, listener);
4401
+ }
4402
+ } catch (e_1_1) {
4403
+ e_1 = {
4404
+ error: e_1_1
4405
+ };
4406
+ } finally{
4407
+ try {
4408
+ if (listeners_1_1 && !listeners_1_1.done && (_a = listeners_1.return)) _a.call(listeners_1);
4409
+ } finally{
4410
+ if (e_1) throw e_1.error;
4411
+ }
4412
+ }
4413
+ return true;
4414
+ };
4415
+ /**
4416
+ * Removes an event listener
4417
+ */ ReconnectingWebSocket.prototype.removeEventListener = function(type, listener) {
4418
+ if (this._listeners[type]) // @ts-ignore
4419
+ this._listeners[type] = this._listeners[type].filter(function(l) {
4420
+ return l !== listener;
4421
+ });
4422
+ };
4423
+ ReconnectingWebSocket.prototype._debug = function() {
4424
+ var args = [];
4425
+ for(var _i = 0; _i < arguments.length; _i++)args[_i] = arguments[_i];
4426
+ if (this._options.debug) // not using spread because compiled version uses Symbols
4427
+ // tslint:disable-next-line
4428
+ console.log.apply(console, __spread([
4429
+ 'RWS>'
4430
+ ], args));
4431
+ };
4432
+ ReconnectingWebSocket.prototype._getNextDelay = function() {
4433
+ var _a = this._options, _b = _a.reconnectionDelayGrowFactor, reconnectionDelayGrowFactor = void 0 === _b ? DEFAULT.reconnectionDelayGrowFactor : _b, _c = _a.minReconnectionDelay, minReconnectionDelay = void 0 === _c ? DEFAULT.minReconnectionDelay : _c, _d = _a.maxReconnectionDelay, maxReconnectionDelay = void 0 === _d ? DEFAULT.maxReconnectionDelay : _d;
4434
+ var delay = 0;
4435
+ if (this._retryCount > 0) {
4436
+ delay = minReconnectionDelay * Math.pow(reconnectionDelayGrowFactor, this._retryCount - 1);
4437
+ if (delay > maxReconnectionDelay) delay = maxReconnectionDelay;
4438
+ }
4439
+ this._debug('next delay', delay);
4440
+ return delay;
4441
+ };
4442
+ ReconnectingWebSocket.prototype._wait = function() {
4443
+ var _this = this;
4444
+ return new Promise(function(resolve) {
4445
+ setTimeout(resolve, _this._getNextDelay());
4446
+ });
4447
+ };
4448
+ ReconnectingWebSocket.prototype._getNextUrl = function(urlProvider) {
4449
+ if ('string' == typeof urlProvider) return Promise.resolve(urlProvider);
4450
+ if ('function' == typeof urlProvider) {
4451
+ var url = urlProvider();
4452
+ if ('string' == typeof url) return Promise.resolve(url);
4453
+ if (!!url.then) return url;
4454
+ }
4455
+ throw Error('Invalid URL');
4456
+ };
4457
+ ReconnectingWebSocket.prototype._connect = function() {
4458
+ var _this = this;
4459
+ if (this._connectLock || !this._shouldReconnect) return;
4460
+ this._connectLock = true;
4461
+ var _a = this._options, _b = _a.maxRetries, maxRetries = void 0 === _b ? DEFAULT.maxRetries : _b, _c = _a.connectionTimeout, connectionTimeout = void 0 === _c ? DEFAULT.connectionTimeout : _c, _d = _a.WebSocket, WebSocket1 = void 0 === _d ? getGlobalWebSocket() : _d;
4462
+ if (this._retryCount >= maxRetries) {
4463
+ this._debug('max retries reached', this._retryCount, '>=', maxRetries);
4464
+ return;
4465
+ }
4466
+ this._retryCount++;
4467
+ this._debug('connect', this._retryCount);
4468
+ this._removeListeners();
4469
+ if (!isWebSocket(WebSocket1)) throw Error('No valid WebSocket class provided');
4470
+ this._wait().then(function() {
4471
+ return _this._getNextUrl(_this._url);
4472
+ }).then(function(url) {
4473
+ // close could be called before creating the ws
4474
+ if (_this._closeCalled) return;
4475
+ _this._debug('connect', {
4476
+ url: url,
4477
+ protocols: _this._protocols
4478
+ });
4479
+ _this._ws = _this._protocols ? new WebSocket1(url, _this._protocols) : new WebSocket1(url);
4480
+ _this._ws.binaryType = _this._binaryType;
4481
+ _this._connectLock = false;
4482
+ _this._addListeners();
4483
+ _this._connectTimeout = setTimeout(function() {
4484
+ return _this._handleTimeout();
4485
+ }, connectionTimeout);
4486
+ });
4487
+ };
4488
+ ReconnectingWebSocket.prototype._handleTimeout = function() {
4489
+ this._debug('timeout event');
4490
+ this._handleError(new reconnecting_websocket_mjs_ErrorEvent(Error('TIMEOUT'), this));
4491
+ };
4492
+ ReconnectingWebSocket.prototype._disconnect = function(code, reason) {
4493
+ if (void 0 === code) code = 1000;
4494
+ this._clearTimeouts();
4495
+ if (!this._ws) return;
4496
+ this._removeListeners();
4497
+ try {
4498
+ this._ws.close(code, reason);
4499
+ this._handleClose(new reconnecting_websocket_mjs_CloseEvent(code, reason, this));
4500
+ } catch (error) {
4501
+ // ignore
4502
+ }
4503
+ };
4504
+ ReconnectingWebSocket.prototype._acceptOpen = function() {
4505
+ this._debug('accept open');
4506
+ this._retryCount = 0;
4507
+ };
4508
+ ReconnectingWebSocket.prototype._callEventListener = function(event, listener) {
4509
+ if ('handleEvent' in listener) // @ts-ignore
4510
+ listener.handleEvent(event);
4511
+ else // @ts-ignore
4512
+ listener(event);
4513
+ };
4514
+ ReconnectingWebSocket.prototype._removeListeners = function() {
4515
+ if (!this._ws) return;
4516
+ this._debug('removeListeners');
4517
+ this._ws.removeEventListener('open', this._handleOpen);
4518
+ this._ws.removeEventListener('close', this._handleClose);
4519
+ this._ws.removeEventListener('message', this._handleMessage);
4520
+ // @ts-ignore
4521
+ this._ws.removeEventListener('error', this._handleError);
4522
+ };
4523
+ ReconnectingWebSocket.prototype._addListeners = function() {
4524
+ if (!this._ws) return;
4525
+ this._debug('addListeners');
4526
+ this._ws.addEventListener('open', this._handleOpen);
4527
+ this._ws.addEventListener('close', this._handleClose);
4528
+ this._ws.addEventListener('message', this._handleMessage);
4529
+ // @ts-ignore
4530
+ this._ws.addEventListener('error', this._handleError);
4531
+ };
4532
+ ReconnectingWebSocket.prototype._clearTimeouts = function() {
4533
+ clearTimeout(this._connectTimeout);
4534
+ clearTimeout(this._uptimeTimeout);
4535
+ };
4536
+ return ReconnectingWebSocket;
4537
+ }();
4538
+ /* ESM default export */ const reconnecting_websocket_mjs = reconnecting_websocket_mjs_ReconnectingWebSocket;
4539
+ class WebSocketAPI {
4540
+ // Standard WebSocket properties
4541
+ get readyState() {
4542
+ return this.rws.readyState;
4543
+ }
4544
+ // Standard WebSocket methods
4545
+ send(data) {
4546
+ return this.rws.send(JSON.stringify(data));
4547
+ }
4548
+ close(code, reason) {
4549
+ return this.rws.close(code, reason);
4550
+ }
4551
+ reconnect(code, reason) {
4552
+ return this.rws.reconnect(code, reason);
4553
+ }
4554
+ // Event listener methods
4555
+ addEventListener(type, listener) {
4556
+ this.rws.addEventListener(type, listener);
4557
+ }
4558
+ removeEventListener(type, listener) {
4559
+ this.rws.removeEventListener(type, listener);
4560
+ }
4561
+ constructor(url, options = {}){
4562
+ // Event handler methods
4563
+ this.onmessage = null;
4564
+ this.onopen = null;
4565
+ this.onclose = null;
4566
+ this.onerror = null;
4567
+ const separator = url.includes('?') ? '&' : '?';
4568
+ const { authorization } = options.headers || {};
4569
+ this.rws = new reconnecting_websocket_mjs(`${url}${separator}authorization=${authorization}`, [], {
4570
+ WebSocket: utils_isBrowser() ? window.WebSocket : class extends browser_default() {
4571
+ constructor(url2, protocols){
4572
+ super(url2, protocols, {
4573
+ headers: options.headers
4574
+ });
4575
+ }
4576
+ },
4577
+ ...options
4578
+ });
4579
+ this.rws.addEventListener('message', (event)=>{
4580
+ try {
4581
+ var _this_onmessage, _this;
4582
+ const data = JSON.parse(event.data);
4583
+ null === (_this_onmessage = (_this = this).onmessage) || void 0 === _this_onmessage || _this_onmessage.call(_this, data, event);
4584
+ } catch (error) {
4585
+ console.error('WebSocketAPI onmessage error', error);
4586
+ }
4587
+ });
4588
+ this.rws.addEventListener('open', (event)=>{
4589
+ var _this_onopen, _this;
4590
+ null === (_this_onopen = (_this = this).onopen) || void 0 === _this_onopen || _this_onopen.call(_this, event);
4591
+ });
4592
+ this.rws.addEventListener('close', (event)=>{
4593
+ var _this_onclose, _this;
4594
+ null === (_this_onclose = (_this = this).onclose) || void 0 === _this_onclose || _this_onclose.call(_this, event);
4595
+ });
4596
+ this.rws.addEventListener('error', (event)=>{
4597
+ var _event_target__req_res, _event_target__req, _event_target, _event_target__req_res1, _event_target__req1, _event_target1, _this_onerror, _this;
4598
+ const statusCode = null === (_event_target = event.target) || void 0 === _event_target ? void 0 : null === (_event_target__req = _event_target._req) || void 0 === _event_target__req ? void 0 : null === (_event_target__req_res = _event_target__req.res) || void 0 === _event_target__req_res ? void 0 : _event_target__req_res.statusCode;
4599
+ const rawHeaders = (null === (_event_target1 = event.target) || void 0 === _event_target1 ? void 0 : null === (_event_target__req1 = _event_target1._req) || void 0 === _event_target__req1 ? void 0 : null === (_event_target__req_res1 = _event_target__req1.res) || void 0 === _event_target__req_res1 ? void 0 : _event_target__req_res1.rawHeaders) || [];
4600
+ const logidIndex = rawHeaders.findIndex((header)=>'X-Tt-Logid' === header);
4601
+ const logid = -1 !== logidIndex ? rawHeaders[logidIndex + 1] : void 0;
4602
+ const error = {
4603
+ id: '0',
4604
+ event_type: types_WebsocketsEventType.ERROR,
4605
+ data: {
4606
+ code: -1,
4607
+ msg: 'WebSocket error'
4608
+ },
4609
+ detail: {
4610
+ logid
4611
+ }
4612
+ };
4613
+ if (401 === statusCode) {
4614
+ error.data.code = 401;
4615
+ error.data.msg = 'Unauthorized';
4616
+ } else if (403 === statusCode) {
4617
+ error.data.code = 403;
4618
+ error.data.msg = 'Forbidden';
4619
+ } else {
4620
+ error.data.code = 500;
4621
+ error.data.msg = String(null == event ? void 0 : event.error) || 'WebSocket error';
4622
+ }
4623
+ null === (_this_onerror = (_this = this).onerror) || void 0 === _this_onerror || _this_onerror.call(_this, error, event);
4624
+ });
4625
+ }
4626
+ }
4627
+ // EXTERNAL MODULE: os (ignored)
4628
+ var os_ignored_ = __webpack_require__("?9050");
4629
+ var os_ignored_default = /*#__PURE__*/ __webpack_require__.n(os_ignored_);
4630
+ var package_namespaceObject = JSON.parse('{"name":"@coze/api","version":"1.0.21-beta.2","description":"Official Coze Node.js SDK for seamless AI integration into your applications | 扣子官方 Node.js SDK,助您轻松集成 AI 能力到应用中","keywords":["coze","ai","nodejs","sdk","chatbot","typescript"],"homepage":"https://github.com/coze-dev/coze-js/tree/main/packages/coze-js","bugs":{"url":"https://github.com/coze-dev/coze-js/issues"},"repository":{"type":"git","url":"https://github.com/coze-dev/coze-js.git","directory":"packages/coze-js"},"license":"MIT","author":"Leeight <leeight@gmail.com>","type":"module","exports":{".":"./src/index.ts","./ws-tools":"./src/ws-tools/index.ts"},"main":"src/index.ts","module":"src/index.ts","browser":{"crypto":false,"os":false,"jsonwebtoken":false,"node-fetch":false},"typesVersions":{"*":{".":["dist/types/index.d.ts"],"ws-tools":["dist/types/ws-tools/ws-tools/index.d.ts"]}},"files":["dist","LICENSE","README.md","README.zh-CN.md"],"scripts":{"build":"rslib build","format":"prettier --write .","lint":"eslint ./ --cache --quiet","start":"rslib build -w","test":"vitest","test:cov":"vitest --coverage --run"},"dependencies":{"jsonwebtoken":"^9.0.2","node-fetch":"^2.x","reconnecting-websocket":"^4.4.0","uuid":"^10.0.0","ws":"^8.11.0"},"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/node-fetch":"^2.x","@types/uuid":"^9.0.1","@types/whatwg-fetch":"^0.0.33","@types/ws":"^8.5.1","@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"},"./ws-tools":{"require":"./dist/cjs/ws-tools/index.cjs","import":"./dist/esm/ws-tools/index.js","types":"./dist/types/ws-tools/ws-tools/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
4631
+ const { version: version_version } = package_namespaceObject;
3897
4632
  const getEnv = ()=>{
3898
4633
  const nodeVersion = process.version.slice(1); // Remove 'v' prefix
3899
4634
  const { platform } = process;
3900
4635
  let osName = platform.toLowerCase();
3901
- let osVersion = os_ignored_.release();
4636
+ let osVersion = os_ignored_default().release();
3902
4637
  if ('darwin' === platform) {
3903
4638
  osName = 'macos';
3904
4639
  // Try to parse the macOS version
3905
4640
  try {
3906
- const darwinVersion = os_ignored_.release().split('.');
4641
+ const darwinVersion = os_ignored_default().release().split('.');
3907
4642
  if (darwinVersion.length >= 2) {
3908
4643
  const majorVersion = parseInt(darwinVersion[0], 10);
3909
4644
  if (!isNaN(majorVersion) && majorVersion >= 9) {
@@ -3916,10 +4651,10 @@ const getEnv = ()=>{
3916
4651
  }
3917
4652
  } else if ('win32' === platform) {
3918
4653
  osName = 'windows';
3919
- osVersion = os_ignored_.release();
4654
+ osVersion = os_ignored_default().release();
3920
4655
  } else if ('linux' === platform) {
3921
4656
  osName = 'linux';
3922
- osVersion = os_ignored_.release();
4657
+ osVersion = os_ignored_default().release();
3923
4658
  }
3924
4659
  return {
3925
4660
  osName,
@@ -3929,12 +4664,12 @@ const getEnv = ()=>{
3929
4664
  };
3930
4665
  const getUserAgent = ()=>{
3931
4666
  const { nodeVersion, osName, osVersion } = getEnv();
3932
- return `coze-js/${esm_version} node/${nodeVersion} ${osName}/${osVersion}`.toLowerCase();
4667
+ return `coze-js/${version_version} node/${nodeVersion} ${osName}/${osVersion}`.toLowerCase();
3933
4668
  };
3934
4669
  const getNodeClientUserAgent = ()=>{
3935
4670
  const { osVersion, nodeVersion, osName } = getEnv();
3936
4671
  const ua = {
3937
- version: esm_version,
4672
+ version: version_version,
3938
4673
  lang: 'node',
3939
4674
  lang_version: nodeVersion,
3940
4675
  os_name: osName,
@@ -3983,7 +4718,7 @@ const getBrowserClientUserAgent = ()=>{
3983
4718
  browserInfo.version = (null === (_userAgent_match5 = userAgent.match(/Version\/([0-9.]+)/)) || void 0 === _userAgent_match5 ? void 0 : _userAgent_match5[1]) || 'unknown';
3984
4719
  }
3985
4720
  const ua = {
3986
- version: esm_version,
4721
+ version: version_version,
3987
4722
  browser: browserInfo.name,
3988
4723
  browser_version: browserInfo.version,
3989
4724
  os_name: osInfo.name,
@@ -3991,15 +4726,37 @@ const getBrowserClientUserAgent = ()=>{
3991
4726
  };
3992
4727
  return JSON.stringify(ua);
3993
4728
  };
3994
- /* eslint-disable @typescript-eslint/no-explicit-any */ const esm_handleError = (error)=>{
4729
+ // EXTERNAL MODULE: node-fetch (ignored)
4730
+ var node_fetch_ignored_ = __webpack_require__("?8dee");
4731
+ var node_fetch_ignored_default = /*#__PURE__*/ __webpack_require__.n(node_fetch_ignored_);
4732
+ /* eslint-disable @typescript-eslint/no-explicit-any */ const fetcher_handleError = (error)=>{
3995
4733
  if (!error.isAxiosError && (!error.code || !error.message)) return new CozeError(`Unexpected error: ${error.message}`);
3996
4734
  if ('ECONNABORTED' === error.code && error.message.includes('timeout') || 'ETIMEDOUT' === error.code) {
3997
4735
  var _error_response;
3998
4736
  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);
3999
4737
  }
4000
4738
  if ('ERR_CANCELED' === error.code) return new APIUserAbortError(error.message);
4001
- var _error_response1, _error_response2, _error_response3;
4002
- 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);
4739
+ else {
4740
+ var _error_response1, _error_response2, _error_response3;
4741
+ 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);
4742
+ }
4743
+ };
4744
+ // node-fetch is used for streaming requests
4745
+ const adapterFetch = async (options)=>{
4746
+ const response = await node_fetch_ignored_default()(options.url, {
4747
+ body: options.data,
4748
+ ...options
4749
+ });
4750
+ return {
4751
+ data: response.body,
4752
+ ...response
4753
+ };
4754
+ };
4755
+ const isSupportNativeFetch = ()=>{
4756
+ if (utils_isBrowser()) return true;
4757
+ // native fetch is supported in node 18.0.0 or higher
4758
+ const version = process.version.slice(1);
4759
+ return compareVersions(version, '18.0.0') >= 0;
4003
4760
  };
4004
4761
  async function fetchAPI(url) {
4005
4762
  let options = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
@@ -4012,10 +4769,10 @@ async function fetchAPI(url) {
4012
4769
  const response = await axiosInstance({
4013
4770
  url,
4014
4771
  responseType: options.isStreaming ? 'stream' : 'json',
4015
- adapter: options.isStreaming ? 'fetch' : void 0,
4772
+ adapter: options.isStreaming ? isSupportNativeFetch() ? 'fetch' : adapterFetch : void 0,
4016
4773
  ...options
4017
4774
  }).catch((error)=>{
4018
- throw esm_handleError(error);
4775
+ throw fetcher_handleError(error);
4019
4776
  });
4020
4777
  return {
4021
4778
  async *stream () {
@@ -4053,7 +4810,7 @@ async function fetchAPI(url) {
4053
4810
  buffer = lines[lines.length - 1]; // Keep the last incomplete line in the buffer
4054
4811
  }
4055
4812
  } catch (error) {
4056
- esm_handleError(error);
4813
+ fetcher_handleError(error);
4057
4814
  }
4058
4815
  },
4059
4816
  json: ()=>response.data,
@@ -4077,8 +4834,11 @@ function isAxiosStatic(instance) {
4077
4834
  }
4078
4835
  /**
4079
4836
  * default coze base URL is api.coze.com
4080
- */ const COZE_COM_BASE_URL = 'https://api.coze.com';
4081
- /* eslint-disable max-params */ class APIClient {
4837
+ */ const constant_COZE_COM_BASE_URL = 'https://api.coze.com';
4838
+ /**
4839
+ * default base websocket URL is wss://ws.coze.com
4840
+ */ const COZE_COM_BASE_WS_URL = 'wss://ws.coze.com';
4841
+ /* eslint-disable max-params */ class core_APIClient {
4082
4842
  async getToken() {
4083
4843
  if ('function' == typeof this.token) return await this.token();
4084
4844
  return this.token;
@@ -4088,28 +4848,50 @@ function isAxiosStatic(instance) {
4088
4848
  const headers = {
4089
4849
  authorization: `Bearer ${token}`
4090
4850
  };
4091
- if (isBrowser()) headers['X-Coze-Client-User-Agent'] = getBrowserClientUserAgent();
4851
+ if (utils_isBrowser()) headers['X-Coze-Client-User-Agent'] = getBrowserClientUserAgent();
4092
4852
  else {
4093
4853
  headers['User-Agent'] = getUserAgent();
4094
4854
  headers['X-Coze-Client-User-Agent'] = getNodeClientUserAgent();
4095
4855
  }
4096
- const config = esm_mergeConfig(this.axiosOptions, options, {
4856
+ const config = mergeConfig(this.axiosOptions, options, {
4097
4857
  headers
4858
+ }, {
4859
+ headers: this.headers || {}
4098
4860
  });
4099
4861
  config.method = method;
4100
4862
  config.data = body;
4101
4863
  return config;
4102
4864
  }
4865
+ async buildWebsocketOptions(options) {
4866
+ const token = await this.getToken();
4867
+ const headers = {
4868
+ authorization: `Bearer ${token}`
4869
+ };
4870
+ if (utils_isBrowser()) headers['X-Coze-Client-User-Agent'] = getBrowserClientUserAgent();
4871
+ else {
4872
+ headers['User-Agent'] = getUserAgent();
4873
+ headers['X-Coze-Client-User-Agent'] = getNodeClientUserAgent();
4874
+ }
4875
+ var _this__config_debug;
4876
+ const config = mergeConfig({
4877
+ debug: null !== (_this__config_debug = this._config.debug) && void 0 !== _this__config_debug && _this__config_debug
4878
+ }, this._config.websocketOptions, options, {
4879
+ headers
4880
+ }, {
4881
+ headers: this.headers || {}
4882
+ });
4883
+ return config;
4884
+ }
4103
4885
  async makeRequest(apiUrl, method, body, isStream, options) {
4104
4886
  const fullUrl = `${this.baseURL}${apiUrl}`;
4105
4887
  const fetchOptions = await this.buildOptions(method, body, options);
4106
4888
  fetchOptions.isStreaming = isStream;
4107
4889
  fetchOptions.axiosInstance = this.axiosInstance;
4108
- this.debugLog(`--- request url: ${fullUrl}`);
4109
- this.debugLog('--- request options:', fetchOptions);
4890
+ this.debugLog(null == options ? void 0 : options.debug, `--- request url: ${fullUrl}`);
4891
+ this.debugLog(null == options ? void 0 : options.debug, '--- request options:', fetchOptions);
4110
4892
  const { response, stream, json } = await fetchAPI(fullUrl, fetchOptions);
4111
- this.debugLog(`--- response status: ${response.status}`);
4112
- this.debugLog('--- response headers: ', response.headers);
4893
+ this.debugLog(null == options ? void 0 : options.debug, `--- response status: ${response.status}`);
4894
+ this.debugLog(null == options ? void 0 : options.debug, '--- response headers: ', response.headers);
4113
4895
  var _response_headers;
4114
4896
  // Taro use `header`
4115
4897
  const contentType = (null !== (_response_headers = response.headers) && void 0 !== _response_headers ? _response_headers : response.header)['content-type'];
@@ -4117,7 +4899,7 @@ function isAxiosStatic(instance) {
4117
4899
  if (contentType && contentType.includes('application/json')) {
4118
4900
  const result = await json();
4119
4901
  const { code, msg } = result;
4120
- if (0 !== code && void 0 !== code) throw APIError.generate(response.status, result, msg, response.headers);
4902
+ if (0 !== code && void 0 !== code) throw error_APIError.generate(response.status, result, msg, response.headers);
4121
4903
  }
4122
4904
  return stream();
4123
4905
  }
@@ -4125,7 +4907,7 @@ function isAxiosStatic(instance) {
4125
4907
  {
4126
4908
  const result = await json();
4127
4909
  const { code, msg } = result;
4128
- if (0 !== code && void 0 !== code) throw APIError.generate(response.status, result, msg, response.headers);
4910
+ if (0 !== code && void 0 !== code) throw error_APIError.generate(response.status, result, msg, response.headers);
4129
4911
  return result;
4130
4912
  }
4131
4913
  }
@@ -4147,41 +4929,55 @@ function isAxiosStatic(instance) {
4147
4929
  async delete(apiUrl, isStream, options) {
4148
4930
  return this.makeRequest(apiUrl, 'DELETE', void 0, isStream, options);
4149
4931
  }
4932
+ async makeWebsocket(apiUrl, options) {
4933
+ const fullUrl = `${this.baseWsURL}${apiUrl}`;
4934
+ const websocketOptions = await this.buildWebsocketOptions(options);
4935
+ this.debugLog(null == options ? void 0 : options.debug, `--- websocket url: ${fullUrl}`);
4936
+ this.debugLog(null == options ? void 0 : options.debug, '--- websocket options:', websocketOptions);
4937
+ const ws = new WebSocketAPI(fullUrl, websocketOptions);
4938
+ return ws;
4939
+ }
4150
4940
  getConfig() {
4151
4941
  return this._config;
4152
4942
  }
4153
4943
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
4154
4944
  debugLog() {
4155
- for(var _len = arguments.length, msgs = new Array(_len), _key = 0; _key < _len; _key++)msgs[_key] = arguments[_key];
4156
- if (this.debug) console.debug(...msgs);
4945
+ let forceDebug = arguments.length > 0 && void 0 !== arguments[0] && arguments[0];
4946
+ for(var _len = arguments.length, msgs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++)msgs[_key - 1] = arguments[_key];
4947
+ if (this.debug || forceDebug) console.debug(...msgs);
4157
4948
  }
4158
4949
  constructor(config){
4159
4950
  this._config = config;
4160
- this.baseURL = config.baseURL || COZE_COM_BASE_URL;
4951
+ this.baseURL = config.baseURL || constant_COZE_COM_BASE_URL;
4952
+ this.baseWsURL = config.baseWsURL || COZE_COM_BASE_WS_URL;
4161
4953
  this.token = config.token;
4162
4954
  this.axiosOptions = config.axiosOptions || {};
4163
4955
  this.axiosInstance = config.axiosInstance;
4164
4956
  this.debug = config.debug || false;
4165
4957
  this.allowPersonalAccessTokenInBrowser = config.allowPersonalAccessTokenInBrowser || false;
4166
4958
  this.headers = config.headers;
4167
- 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');
4168
- }
4169
- }
4170
- APIClient.APIError = APIError;
4171
- APIClient.BadRequestError = BadRequestError;
4172
- APIClient.AuthenticationError = AuthenticationError;
4173
- APIClient.PermissionDeniedError = PermissionDeniedError;
4174
- APIClient.NotFoundError = NotFoundError;
4175
- APIClient.RateLimitError = RateLimitError;
4176
- APIClient.InternalServerError = InternalServerError;
4177
- APIClient.GatewayError = GatewayError;
4178
- APIClient.TimeoutError = TimeoutError;
4179
- APIClient.UserAbortError = APIUserAbortError;
4180
- class CozeAPI extends APIClient {
4959
+ 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');
4960
+ }
4961
+ }
4962
+ core_APIClient.APIError = error_APIError;
4963
+ core_APIClient.BadRequestError = BadRequestError;
4964
+ core_APIClient.AuthenticationError = AuthenticationError;
4965
+ core_APIClient.PermissionDeniedError = PermissionDeniedError;
4966
+ core_APIClient.NotFoundError = NotFoundError;
4967
+ core_APIClient.RateLimitError = RateLimitError;
4968
+ core_APIClient.InternalServerError = InternalServerError;
4969
+ core_APIClient.GatewayError = GatewayError;
4970
+ core_APIClient.TimeoutError = TimeoutError;
4971
+ core_APIClient.UserAbortError = APIUserAbortError;
4972
+ // EXTERNAL MODULE: crypto (ignored)
4973
+ __webpack_require__("?666e");
4974
+ // EXTERNAL MODULE: jsonwebtoken (ignored)
4975
+ __webpack_require__("?79fd");
4976
+ class CozeAPI extends core_APIClient {
4181
4977
  constructor(...args){
4182
4978
  super(...args), this.bots = new Bots(this), this.chat = new Chat(this), this.conversations = new Conversations(this), this.files = new Files(this), /**
4183
4979
  * @deprecated
4184
- */ 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), this.templates = new Templates(this);
4980
+ */ this.knowledge = new Knowledge(this), this.datasets = new Datasets(this), this.workflows = new Workflows(this), this.workspaces = new WorkSpaces(this), this.audio = new audio_Audio(this), this.templates = new Templates(this), this.websockets = new Websockets(this);
4185
4981
  }
4186
4982
  }
4187
4983
  /**
@@ -38566,7 +39362,7 @@ var VERTC = _createClass(function e() {
38566
39362
  + * @param milliseconds The time to sleep in milliseconds
38567
39363
  + * @throws {Error} If milliseconds is negative
38568
39364
  + * @returns Promise that resolves after the specified duration
38569
- + */ const utils_sleep = (milliseconds)=>{
39365
+ + */ const src_utils_sleep = (milliseconds)=>{
38570
39366
  if (milliseconds < 0) throw new Error('Sleep duration must be non-negative');
38571
39367
  return new Promise((resolve)=>setTimeout(resolve, milliseconds));
38572
39368
  };
@@ -42298,6 +43094,9 @@ class EngineClient extends RealtimeEventHandler {
42298
43094
  throw e;
42299
43095
  }
42300
43096
  }
43097
+ getRtcEngine() {
43098
+ return this.engine;
43099
+ }
42301
43100
  // eslint-disable-next-line max-params
42302
43101
  constructor(appId, debug = false, isTestEnv = false, isSupportVideo = false, videoConfig){
42303
43102
  super(debug), this.joinUserId = '', this._AIAnsExtension = null, this._isSupportVideo = false;
@@ -42328,11 +43127,24 @@ class RealtimeClient extends RealtimeEventHandler {
42328
43127
  let roomInfo;
42329
43128
  try {
42330
43129
  // Step1 get token
43130
+ let config;
43131
+ if (this._config.videoConfig) config = isScreenShareDevice(this._config.videoConfig.videoInputDeviceId) ? {
43132
+ video_config: {
43133
+ stream_video_type: 'screen'
43134
+ }
43135
+ } : {
43136
+ video_config: {
43137
+ stream_video_type: 'main'
43138
+ }
43139
+ };
42331
43140
  roomInfo = await this._api.audio.rooms.create({
42332
43141
  bot_id: botId,
42333
- conversation_id: conversationId,
43142
+ conversation_id: conversationId || void 0,
42334
43143
  voice_id: voiceId && voiceId.length > 0 ? voiceId : void 0,
42335
- connector_id: this._config.connectorId
43144
+ connector_id: this._config.connectorId,
43145
+ uid: this._config.userId || void 0,
43146
+ workflow_id: this._config.workflowId || void 0,
43147
+ config
42336
43148
  });
42337
43149
  } catch (error) {
42338
43150
  this.dispatch(event_handler_EventNames.ERROR, error);
@@ -42483,6 +43295,14 @@ class RealtimeClient extends RealtimeEventHandler {
42483
43295
  });
42484
43296
  }
42485
43297
  /**
43298
+ * en: Get the RTC engine instance, for detail visit https://www.volcengine.com/docs/6348/104481
43299
+ *
43300
+ * zh: 获取 RTC 引擎实例,详情请访问 https://www.volcengine.com/docs/6348/104481
43301
+ */ getRtcEngine() {
43302
+ var _this__client;
43303
+ return null === (_this__client = this._client) || void 0 === _this__client ? void 0 : _this__client.getRtcEngine();
43304
+ }
43305
+ /**
42486
43306
  * Constructor for initializing a RealtimeClient instance.
42487
43307
  *
42488
43308
  * 构造函数,初始化RealtimeClient实例。
@@ -42496,6 +43316,8 @@ class RealtimeClient extends RealtimeEventHandler {
42496
43316
  * 可选,音色Id。
42497
43317
  * @param config.conversationId - Optional, Conversation Id. |
42498
43318
  * 可选,会话Id。
43319
+ * @param config.userId - Optional, User Id. |
43320
+ * 可选,用户Id。
42499
43321
  * @param config.baseURL - Optional, defaults to "https://api.coze.cn". |
42500
43322
  * 可选,默认值为 "https://api.coze.cn"。
42501
43323
  * @param config.debug - Optional, defaults to false.