@coze/realtime-api 1.0.4 → 1.0.5

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,480 +102,1038 @@ __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, cause }){
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
  };
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;
409
682
  /**
410
- * Determines whether a string ends with the characters of a specified string
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)=>{
556
- const stack = new Array(10);
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)=>{
1136
+ const stack = new Array(10);
557
1137
  const visit = (source, i)=>{
558
1138
  if (isObject(source)) {
559
1139
  if (stack.indexOf(source) >= 0) return;
@@ -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),
@@ -2550,870 +3130,303 @@ const Axios_validators = helpers_validator.validators;
2550
3130
  promise = dispatchRequest.call(this, newConfig);
2551
3131
  } catch (error) {
2552
3132
  return Promise.reject(error);
2553
- }
2554
- i = 0;
2555
- len = responseInterceptorChain.length;
2556
- while(i < len)promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
2557
- return promise;
2558
- }
2559
- getUri(config) {
2560
- config = mergeConfig(this.defaults, config);
2561
- const fullPath = buildFullPath(config.baseURL, config.url);
2562
- return buildURL(fullPath, config.params, config.paramsSerializer);
2563
- }
2564
- }
2565
- // Provide aliases for supported request methods
2566
- utils.forEach([
2567
- 'delete',
2568
- 'get',
2569
- 'head',
2570
- 'options'
2571
- ], function(method) {
2572
- /*eslint func-names:0*/ Axios_Axios.prototype[method] = function(url, config) {
2573
- return this.request(mergeConfig(config || {}, {
2574
- method,
2575
- url,
2576
- data: (config || {}).data
2577
- }));
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;
3335
- }
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;
3133
+ }
3134
+ i = 0;
3135
+ len = responseInterceptorChain.length;
3136
+ while(i < len)promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
3137
+ return promise;
3352
3138
  }
3353
- /**
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;
3139
+ getUri(config) {
3140
+ config = mergeConfig_mergeConfig(this.defaults, config);
3141
+ const fullPath = buildFullPath(config.baseURL, config.url);
3142
+ return buildURL(fullPath, config.params, config.paramsSerializer);
3364
3143
  }
3365
3144
  }
3366
- class Conversations extends APIResource {
3367
- /**
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;
3145
+ // Provide aliases for supported request methods
3146
+ utils.forEach([
3147
+ 'delete',
3148
+ 'get',
3149
+ 'head',
3150
+ 'options'
3151
+ ], function(method) {
3152
+ /*eslint func-names:0*/ Axios_Axios.prototype[method] = function(url, config) {
3153
+ return this.request(mergeConfig_mergeConfig(config || {}, {
3154
+ method,
3155
+ url,
3156
+ data: (config || {}).data
3157
+ }));
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
+ };
3176
+ }
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
+ });
3380
3221
  }
3381
3222
  /**
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;
3223
+ * Throws a `CanceledError` if cancellation has been requested.
3224
+ */ throwIfRequested() {
3225
+ if (this.reason) throw this.reason;
3391
3226
  }
3392
3227
  /**
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;
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
+ ];
3403
3238
  }
3404
3239
  /**
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;
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);
3412
3245
  }
3413
- constructor(...args){
3414
- super(...args), this.messages = new messages_Messages(this._client);
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;
3254
+ }
3255
+ /**
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. | 调用接口上传文件到扣子。
@@ -3576,7 +3589,7 @@ class Documents extends APIResource {
3576
3589
  * @returns ListDocumentData | 知识库文件列表
3577
3590
  */ list(params, options) {
3578
3591
  const apiUrl = '/open_api/knowledge/document/list';
3579
- const response = this._client.get(apiUrl, params, false, esm_mergeConfig(options, {
3592
+ const response = this._client.get(apiUrl, params, false, mergeConfig(options, {
3580
3593
  headers: documents_headers
3581
3594
  }));
3582
3595
  return response;
@@ -3594,7 +3607,7 @@ class Documents extends APIResource {
3594
3607
  * @returns DocumentInfo[] | 已上传文件的基本信息
3595
3608
  */ async create(params, options) {
3596
3609
  const apiUrl = '/open_api/knowledge/document/create';
3597
- const response = await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3610
+ const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
3598
3611
  headers: documents_headers
3599
3612
  }));
3600
3613
  return response.document_infos;
@@ -3610,7 +3623,7 @@ class Documents extends APIResource {
3610
3623
  * @returns void | 无返回
3611
3624
  */ async delete(params, options) {
3612
3625
  const apiUrl = '/open_api/knowledge/document/delete';
3613
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3626
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3614
3627
  headers: documents_headers
3615
3628
  }));
3616
3629
  }
@@ -3626,7 +3639,7 @@ class Documents extends APIResource {
3626
3639
  * @returns void | 无返回
3627
3640
  */ async update(params, options) {
3628
3641
  const apiUrl = '/open_api/knowledge/document/update';
3629
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3642
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3630
3643
  headers: documents_headers
3631
3644
  }));
3632
3645
  }
@@ -3654,7 +3667,7 @@ class documents_Documents extends APIResource {
3654
3667
  * @returns ListDocumentData | 知识库文件列表
3655
3668
  */ async list(params, options) {
3656
3669
  const apiUrl = '/open_api/knowledge/document/list';
3657
- const response = await this._client.get(apiUrl, params, false, esm_mergeConfig(options, {
3670
+ const response = await this._client.get(apiUrl, params, false, mergeConfig(options, {
3658
3671
  headers: documents_documents_headers
3659
3672
  }));
3660
3673
  return response;
@@ -3670,7 +3683,7 @@ class documents_Documents extends APIResource {
3670
3683
  * @returns DocumentInfo[] | 已上传文件的基本信息
3671
3684
  */ async create(params, options) {
3672
3685
  const apiUrl = '/open_api/knowledge/document/create';
3673
- const response = await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3686
+ const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
3674
3687
  headers: documents_documents_headers
3675
3688
  }));
3676
3689
  return response.document_infos;
@@ -3684,7 +3697,7 @@ class documents_Documents extends APIResource {
3684
3697
  * @returns void | 无返回
3685
3698
  */ async delete(params, options) {
3686
3699
  const apiUrl = '/open_api/knowledge/document/delete';
3687
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3700
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3688
3701
  headers: documents_documents_headers
3689
3702
  }));
3690
3703
  }
@@ -3698,7 +3711,7 @@ class documents_Documents extends APIResource {
3698
3711
  * @returns void | 无返回
3699
3712
  */ async update(params, options) {
3700
3713
  const apiUrl = '/open_api/knowledge/document/update';
3701
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3714
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3702
3715
  headers: documents_documents_headers
3703
3716
  }));
3704
3717
  }
@@ -3820,6 +3833,8 @@ class Voices extends APIResource {
3820
3833
  * | 如果传入会基于该文本生成预览音频,否则使用默认的文本
3821
3834
  * @param params.text - Optional. Users can read this text, service will compare audio with text. Returns error if difference is too large
3822
3835
  * | 可以让用户按照该文本念诵,服务会对比音频与该文本的差异。若差异过大会返回错误
3836
+ * @param params.space_id - Optional. The space id of the voice. | 空间ID
3837
+ * @param params.description- Optional. The description of the voice. | 音色描述
3823
3838
  * @param options - Request options
3824
3839
  * @returns Clone voice data
3825
3840
  */ async clone(params, options) {
@@ -3844,6 +3859,17 @@ class Voices extends APIResource {
3844
3859
  return response.data;
3845
3860
  }
3846
3861
  }
3862
+ class Transcriptions extends APIResource {
3863
+ /**
3864
+ * ASR voice to text | ASR 语音转文本
3865
+ * @param params - Required The parameters for file upload | 上传文件所需的参数
3866
+ * @param params.file - Required The audio file to be uploaded. | 需要上传的音频文件。
3867
+ */ async create(params, options) {
3868
+ const apiUrl = '/v1/audio/transcriptions';
3869
+ const response = await this._client.post(apiUrl, axios_toFormData(params), false, options);
3870
+ return response.data;
3871
+ }
3872
+ }
3847
3873
  class Speech extends APIResource {
3848
3874
  /**
3849
3875
  * @description Speech synthesis | 语音合成
@@ -3860,7 +3886,7 @@ class Speech extends APIResource {
3860
3886
  const response = await this._client.post(apiUrl, {
3861
3887
  ...params,
3862
3888
  sample_rate: params.sample_rate || 24000
3863
- }, false, esm_mergeConfig(options, {
3889
+ }, false, mergeConfig(options, {
3864
3890
  responseType: 'arraybuffer'
3865
3891
  }));
3866
3892
  return response;
@@ -3873,9 +3899,9 @@ class Rooms extends APIResource {
3873
3899
  return response.data;
3874
3900
  }
3875
3901
  }
3876
- class esm_Audio extends APIResource {
3902
+ class audio_Audio extends APIResource {
3877
3903
  constructor(...args){
3878
- super(...args), this.rooms = new Rooms(this._client), this.voices = new Voices(this._client), this.speech = new Speech(this._client);
3904
+ 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
3905
  }
3880
3906
  }
3881
3907
  class Templates extends APIResource {
@@ -3892,18 +3918,716 @@ class Templates extends APIResource {
3892
3918
  return response.data;
3893
3919
  }
3894
3920
  }
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;
3921
+ class chat_Chat extends APIResource {
3922
+ async create(botId, options) {
3923
+ const apiUrl = `/v1/chat?bot_id=${botId}`;
3924
+ return await this._client.makeWebsocket(apiUrl, options);
3925
+ }
3926
+ }
3927
+ class transcriptions_Transcriptions extends APIResource {
3928
+ async create(options) {
3929
+ const apiUrl = '/v1/audio/transcriptions';
3930
+ return await this._client.makeWebsocket(apiUrl, options);
3931
+ }
3932
+ }
3933
+ class speech_Speech extends APIResource {
3934
+ async create(options) {
3935
+ const apiUrl = '/v1/audio/speech';
3936
+ return await this._client.makeWebsocket(apiUrl, options);
3937
+ }
3938
+ }
3939
+ class websockets_audio_Audio extends APIResource {
3940
+ constructor(...args){
3941
+ super(...args), this.speech = new speech_Speech(this._client), this.transcriptions = new transcriptions_Transcriptions(this._client);
3942
+ }
3943
+ }
3944
+ // Common types (not exported)
3945
+ // Keep all existing exports but use the base types where applicable
3946
+ var types_WebsocketsEventType = /*#__PURE__*/ function(WebsocketsEventType) {
3947
+ // Common
3948
+ /** SDK error */ WebsocketsEventType["CLIENT_ERROR"] = "client_error";
3949
+ /** Connection closed */ WebsocketsEventType["CLOSED"] = "closed";
3950
+ // Error
3951
+ /** Received error event */ WebsocketsEventType["ERROR"] = "error";
3952
+ // v1/audio/speech
3953
+ /** Send text to server */ WebsocketsEventType["INPUT_TEXT_BUFFER_APPEND"] = "input_text_buffer.append";
3954
+ /** No text to send, after audio all received, can close connection */ WebsocketsEventType["INPUT_TEXT_BUFFER_COMPLETE"] = "input_text_buffer.complete";
3955
+ /** Send speech config to server */ WebsocketsEventType["SPEECH_UPDATE"] = "speech.update";
3956
+ /** Received `speech.updated` event */ WebsocketsEventType["SPEECH_UPDATED"] = "speech.updated";
3957
+ /** After speech created */ WebsocketsEventType["SPEECH_CREATED"] = "speech.created";
3958
+ /** Received `input_text_buffer.complete` event */ WebsocketsEventType["INPUT_TEXT_BUFFER_COMPLETED"] = "input_text_buffer.completed";
3959
+ /** Received `speech.update` event */ WebsocketsEventType["SPEECH_AUDIO_UPDATE"] = "speech.audio.update";
3960
+ /** All audio received, can close connection */ WebsocketsEventType["SPEECH_AUDIO_COMPLETED"] = "speech.audio.completed";
3961
+ // v1/audio/transcriptions
3962
+ /** Send audio to server */ WebsocketsEventType["INPUT_AUDIO_BUFFER_APPEND"] = "input_audio_buffer.append";
3963
+ /** No audio to send, after text all received, can close connection */ WebsocketsEventType["INPUT_AUDIO_BUFFER_COMPLETE"] = "input_audio_buffer.complete";
3964
+ /** Send transcriptions config to server */ WebsocketsEventType["TRANSCRIPTIONS_UPDATE"] = "transcriptions.update";
3965
+ /** Send `input_audio_buffer.clear` event */ WebsocketsEventType["INPUT_AUDIO_BUFFER_CLEAR"] = "input_audio_buffer.clear";
3966
+ /** After transcriptions created */ WebsocketsEventType["TRANSCRIPTIONS_CREATED"] = "transcriptions.created";
3967
+ /** Received `input_audio_buffer.complete` event */ WebsocketsEventType["INPUT_AUDIO_BUFFER_COMPLETED"] = "input_audio_buffer.completed";
3968
+ /** Received `transcriptions.update` event */ WebsocketsEventType["TRANSCRIPTIONS_MESSAGE_UPDATE"] = "transcriptions.message.update";
3969
+ /** All audio received, can close connection */ WebsocketsEventType["TRANSCRIPTIONS_MESSAGE_COMPLETED"] = "transcriptions.message.completed";
3970
+ /** Received `input_audio_buffer.cleared` event */ WebsocketsEventType["INPUT_AUDIO_BUFFER_CLEARED"] = "input_audio_buffer.cleared";
3971
+ /** Received `transcriptions.updated` event */ WebsocketsEventType["TRANSCRIPTIONS_UPDATED"] = "transcriptions.updated";
3972
+ // v1/chat
3973
+ /** Send chat config to server */ WebsocketsEventType["CHAT_UPDATE"] = "chat.update";
3974
+ /** Send tool outputs to server */ WebsocketsEventType["CONVERSATION_CHAT_SUBMIT_TOOL_OUTPUTS"] = "conversation.chat.submit_tool_outputs";
3975
+ /** After chat created */ WebsocketsEventType["CHAT_CREATED"] = "chat.created";
3976
+ /** After chat updated */ WebsocketsEventType["CHAT_UPDATED"] = "chat.updated";
3977
+ /** Audio AST completed, chat started */ WebsocketsEventType["CONVERSATION_CHAT_CREATED"] = "conversation.chat.created";
3978
+ /** Message created */ WebsocketsEventType["CONVERSATION_MESSAGE_CREATE"] = "conversation.message.create";
3979
+ /** Clear conversation */ WebsocketsEventType["CONVERSATION_CLEAR"] = "conversation.clear";
3980
+ /** Chat in progress */ WebsocketsEventType["CONVERSATION_CHAT_IN_PROGRESS"] = "conversation.chat.in_progress";
3981
+ /** Get agent text message update */ WebsocketsEventType["CONVERSATION_MESSAGE_DELTA"] = "conversation.message.delta";
3982
+ /** Need plugin submit */ WebsocketsEventType["CONVERSATION_CHAT_REQUIRES_ACTION"] = "conversation.chat.requires_action";
3983
+ /** Message completed */ WebsocketsEventType["CONVERSATION_MESSAGE_COMPLETED"] = "conversation.message.completed";
3984
+ /** Get agent audio message update */ WebsocketsEventType["CONVERSATION_AUDIO_DELTA"] = "conversation.audio.delta";
3985
+ /** Audio message completed */ WebsocketsEventType["CONVERSATION_AUDIO_COMPLETED"] = "conversation.audio.completed";
3986
+ /** All message received, can close connection */ WebsocketsEventType["CONVERSATION_CHAT_COMPLETED"] = "conversation.chat.completed";
3987
+ /** Chat failed */ WebsocketsEventType["CONVERSATION_CHAT_FAILED"] = "conversation.chat.failed";
3988
+ /** Received `conversation.cleared` event */ WebsocketsEventType["CONVERSATION_CLEARED"] = "conversation.cleared";
3989
+ return WebsocketsEventType;
3990
+ }({});
3991
+ class Websockets extends APIResource {
3992
+ constructor(...args){
3993
+ super(...args), this.audio = new websockets_audio_Audio(this._client), this.chat = new chat_Chat(this._client);
3994
+ }
3995
+ }
3996
+ // EXTERNAL MODULE: ../../common/temp/default/node_modules/.pnpm/ws@8.18.0/node_modules/ws/browser.js
3997
+ var ws_browser = __webpack_require__("../../common/temp/default/node_modules/.pnpm/ws@8.18.0/node_modules/ws/browser.js");
3998
+ var browser_default = /*#__PURE__*/ __webpack_require__.n(ws_browser);
3999
+ /*! *****************************************************************************
4000
+ Copyright (c) Microsoft Corporation. All rights reserved.
4001
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
4002
+ this file except in compliance with the License. You may obtain a copy of the
4003
+ License at http://www.apache.org/licenses/LICENSE-2.0
4004
+
4005
+ THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
4006
+ KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
4007
+ WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
4008
+ MERCHANTABLITY OR NON-INFRINGEMENT.
4009
+
4010
+ See the Apache Version 2.0 License for specific language governing permissions
4011
+ and limitations under the License.
4012
+ ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function(d, b) {
4013
+ extendStatics = Object.setPrototypeOf || ({
4014
+ __proto__: []
4015
+ }) instanceof Array && function(d, b) {
4016
+ d.__proto__ = b;
4017
+ } || function(d, b) {
4018
+ for(var p in b)if (b.hasOwnProperty(p)) d[p] = b[p];
4019
+ };
4020
+ return extendStatics(d, b);
4021
+ };
4022
+ function __extends(d, b) {
4023
+ extendStatics(d, b);
4024
+ function __() {
4025
+ this.constructor = d;
4026
+ }
4027
+ d.prototype = null === b ? Object.create(b) : (__.prototype = b.prototype, new __());
4028
+ }
4029
+ function __values(o) {
4030
+ var m = "function" == typeof Symbol && o[Symbol.iterator], i = 0;
4031
+ if (m) return m.call(o);
4032
+ return {
4033
+ next: function() {
4034
+ if (o && i >= o.length) o = void 0;
4035
+ return {
4036
+ value: o && o[i++],
4037
+ done: !o
4038
+ };
4039
+ }
4040
+ };
4041
+ }
4042
+ function __read(o, n) {
4043
+ var m = "function" == typeof Symbol && o[Symbol.iterator];
4044
+ if (!m) return o;
4045
+ var i = m.call(o), r, ar = [], e;
4046
+ try {
4047
+ while((void 0 === n || n-- > 0) && !(r = i.next()).done)ar.push(r.value);
4048
+ } catch (error) {
4049
+ e = {
4050
+ error: error
4051
+ };
4052
+ } finally{
4053
+ try {
4054
+ if (r && !r.done && (m = i["return"])) m.call(i);
4055
+ } finally{
4056
+ if (e) throw e.error;
4057
+ }
4058
+ }
4059
+ return ar;
4060
+ }
4061
+ function __spread() {
4062
+ for(var ar = [], i = 0; i < arguments.length; i++)ar = ar.concat(__read(arguments[i]));
4063
+ return ar;
4064
+ }
4065
+ var reconnecting_websocket_mjs_Event = /** @class */ function() {
4066
+ function Event1(type, target) {
4067
+ this.target = target;
4068
+ this.type = type;
4069
+ }
4070
+ return Event1;
4071
+ }();
4072
+ var reconnecting_websocket_mjs_ErrorEvent = /** @class */ function(_super) {
4073
+ __extends(ErrorEvent, _super);
4074
+ function ErrorEvent(error, target) {
4075
+ var _this = _super.call(this, 'error', target) || this;
4076
+ _this.message = error.message;
4077
+ _this.error = error;
4078
+ return _this;
4079
+ }
4080
+ return ErrorEvent;
4081
+ }(reconnecting_websocket_mjs_Event);
4082
+ var reconnecting_websocket_mjs_CloseEvent = /** @class */ function(_super) {
4083
+ __extends(CloseEvent, _super);
4084
+ function CloseEvent(code, reason, target) {
4085
+ if (void 0 === code) code = 1000;
4086
+ if (void 0 === reason) reason = '';
4087
+ var _this = _super.call(this, 'close', target) || this;
4088
+ _this.wasClean = true;
4089
+ _this.code = code;
4090
+ _this.reason = reason;
4091
+ return _this;
4092
+ }
4093
+ return CloseEvent;
4094
+ }(reconnecting_websocket_mjs_Event);
4095
+ /*!
4096
+ * Reconnecting WebSocket
4097
+ * by Pedro Ladaria <pedro.ladaria@gmail.com>
4098
+ * https://github.com/pladaria/reconnecting-websocket
4099
+ * License MIT
4100
+ */ var getGlobalWebSocket = function() {
4101
+ if ('undefined' != typeof WebSocket) // @ts-ignore
4102
+ return WebSocket;
4103
+ };
4104
+ /**
4105
+ * Returns true if given argument looks like a WebSocket class
4106
+ */ var isWebSocket = function(w) {
4107
+ return void 0 !== w && !!w && 2 === w.CLOSING;
4108
+ };
4109
+ var DEFAULT = {
4110
+ maxReconnectionDelay: 10000,
4111
+ minReconnectionDelay: 1000 + 4000 * Math.random(),
4112
+ minUptime: 5000,
4113
+ reconnectionDelayGrowFactor: 1.3,
4114
+ connectionTimeout: 4000,
4115
+ maxRetries: 1 / 0,
4116
+ maxEnqueuedMessages: 1 / 0,
4117
+ startClosed: false,
4118
+ debug: false
4119
+ };
4120
+ var reconnecting_websocket_mjs_ReconnectingWebSocket = /** @class */ function() {
4121
+ function ReconnectingWebSocket(url, protocols, options) {
4122
+ var _this = this;
4123
+ if (void 0 === options) options = {};
4124
+ this._listeners = {
4125
+ error: [],
4126
+ message: [],
4127
+ open: [],
4128
+ close: []
4129
+ };
4130
+ this._retryCount = -1;
4131
+ this._shouldReconnect = true;
4132
+ this._connectLock = false;
4133
+ this._binaryType = 'blob';
4134
+ this._closeCalled = false;
4135
+ this._messageQueue = [];
4136
+ /**
4137
+ * An event listener to be called when the WebSocket connection's readyState changes to CLOSED
4138
+ */ this.onclose = null;
4139
+ /**
4140
+ * An event listener to be called when an error occurs
4141
+ */ this.onerror = null;
4142
+ /**
4143
+ * An event listener to be called when a message is received from the server
4144
+ */ this.onmessage = null;
4145
+ /**
4146
+ * An event listener to be called when the WebSocket connection's readyState changes to OPEN;
4147
+ * this indicates that the connection is ready to send and receive data
4148
+ */ this.onopen = null;
4149
+ this._handleOpen = function(event) {
4150
+ _this._debug('open event');
4151
+ var _a = _this._options.minUptime, minUptime = void 0 === _a ? DEFAULT.minUptime : _a;
4152
+ clearTimeout(_this._connectTimeout);
4153
+ _this._uptimeTimeout = setTimeout(function() {
4154
+ return _this._acceptOpen();
4155
+ }, minUptime);
4156
+ _this._ws.binaryType = _this._binaryType;
4157
+ // send enqueued messages (messages sent before websocket open event)
4158
+ _this._messageQueue.forEach(function(message) {
4159
+ return _this._ws.send(message);
4160
+ });
4161
+ _this._messageQueue = [];
4162
+ if (_this.onopen) _this.onopen(event);
4163
+ _this._listeners.open.forEach(function(listener) {
4164
+ return _this._callEventListener(event, listener);
4165
+ });
4166
+ };
4167
+ this._handleMessage = function(event) {
4168
+ _this._debug('message event');
4169
+ if (_this.onmessage) _this.onmessage(event);
4170
+ _this._listeners.message.forEach(function(listener) {
4171
+ return _this._callEventListener(event, listener);
4172
+ });
4173
+ };
4174
+ this._handleError = function(event) {
4175
+ _this._debug('error event', event.message);
4176
+ _this._disconnect(void 0, 'TIMEOUT' === event.message ? 'timeout' : void 0);
4177
+ if (_this.onerror) _this.onerror(event);
4178
+ _this._debug('exec error listeners');
4179
+ _this._listeners.error.forEach(function(listener) {
4180
+ return _this._callEventListener(event, listener);
4181
+ });
4182
+ _this._connect();
4183
+ };
4184
+ this._handleClose = function(event) {
4185
+ _this._debug('close event');
4186
+ _this._clearTimeouts();
4187
+ if (_this._shouldReconnect) _this._connect();
4188
+ if (_this.onclose) _this.onclose(event);
4189
+ _this._listeners.close.forEach(function(listener) {
4190
+ return _this._callEventListener(event, listener);
4191
+ });
4192
+ };
4193
+ this._url = url;
4194
+ this._protocols = protocols;
4195
+ this._options = options;
4196
+ if (this._options.startClosed) this._shouldReconnect = false;
4197
+ this._connect();
4198
+ }
4199
+ Object.defineProperty(ReconnectingWebSocket, "CONNECTING", {
4200
+ get: function() {
4201
+ return 0;
4202
+ },
4203
+ enumerable: true,
4204
+ configurable: true
4205
+ });
4206
+ Object.defineProperty(ReconnectingWebSocket, "OPEN", {
4207
+ get: function() {
4208
+ return 1;
4209
+ },
4210
+ enumerable: true,
4211
+ configurable: true
4212
+ });
4213
+ Object.defineProperty(ReconnectingWebSocket, "CLOSING", {
4214
+ get: function() {
4215
+ return 2;
4216
+ },
4217
+ enumerable: true,
4218
+ configurable: true
4219
+ });
4220
+ Object.defineProperty(ReconnectingWebSocket, "CLOSED", {
4221
+ get: function() {
4222
+ return 3;
4223
+ },
4224
+ enumerable: true,
4225
+ configurable: true
4226
+ });
4227
+ Object.defineProperty(ReconnectingWebSocket.prototype, "CONNECTING", {
4228
+ get: function() {
4229
+ return ReconnectingWebSocket.CONNECTING;
4230
+ },
4231
+ enumerable: true,
4232
+ configurable: true
4233
+ });
4234
+ Object.defineProperty(ReconnectingWebSocket.prototype, "OPEN", {
4235
+ get: function() {
4236
+ return ReconnectingWebSocket.OPEN;
4237
+ },
4238
+ enumerable: true,
4239
+ configurable: true
4240
+ });
4241
+ Object.defineProperty(ReconnectingWebSocket.prototype, "CLOSING", {
4242
+ get: function() {
4243
+ return ReconnectingWebSocket.CLOSING;
4244
+ },
4245
+ enumerable: true,
4246
+ configurable: true
4247
+ });
4248
+ Object.defineProperty(ReconnectingWebSocket.prototype, "CLOSED", {
4249
+ get: function() {
4250
+ return ReconnectingWebSocket.CLOSED;
4251
+ },
4252
+ enumerable: true,
4253
+ configurable: true
4254
+ });
4255
+ Object.defineProperty(ReconnectingWebSocket.prototype, "binaryType", {
4256
+ get: function() {
4257
+ return this._ws ? this._ws.binaryType : this._binaryType;
4258
+ },
4259
+ set: function(value) {
4260
+ this._binaryType = value;
4261
+ if (this._ws) this._ws.binaryType = value;
4262
+ },
4263
+ enumerable: true,
4264
+ configurable: true
4265
+ });
4266
+ Object.defineProperty(ReconnectingWebSocket.prototype, "retryCount", {
4267
+ /**
4268
+ * Returns the number or connection retries
4269
+ */ get: function() {
4270
+ return Math.max(this._retryCount, 0);
4271
+ },
4272
+ enumerable: true,
4273
+ configurable: true
4274
+ });
4275
+ Object.defineProperty(ReconnectingWebSocket.prototype, "bufferedAmount", {
4276
+ /**
4277
+ * The number of bytes of data that have been queued using calls to send() but not yet
4278
+ * transmitted to the network. This value resets to zero once all queued data has been sent.
4279
+ * This value does not reset to zero when the connection is closed; if you keep calling send(),
4280
+ * this will continue to climb. Read only
4281
+ */ get: function() {
4282
+ var bytes = this._messageQueue.reduce(function(acc, message) {
4283
+ if ('string' == typeof message) acc += message.length; // not byte size
4284
+ else if (message instanceof Blob) acc += message.size;
4285
+ else acc += message.byteLength;
4286
+ return acc;
4287
+ }, 0);
4288
+ return bytes + (this._ws ? this._ws.bufferedAmount : 0);
4289
+ },
4290
+ enumerable: true,
4291
+ configurable: true
4292
+ });
4293
+ Object.defineProperty(ReconnectingWebSocket.prototype, "extensions", {
4294
+ /**
4295
+ * The extensions selected by the server. This is currently only the empty string or a list of
4296
+ * extensions as negotiated by the connection
4297
+ */ get: function() {
4298
+ return this._ws ? this._ws.extensions : '';
4299
+ },
4300
+ enumerable: true,
4301
+ configurable: true
4302
+ });
4303
+ Object.defineProperty(ReconnectingWebSocket.prototype, "protocol", {
4304
+ /**
4305
+ * A string indicating the name of the sub-protocol the server selected;
4306
+ * this will be one of the strings specified in the protocols parameter when creating the
4307
+ * WebSocket object
4308
+ */ get: function() {
4309
+ return this._ws ? this._ws.protocol : '';
4310
+ },
4311
+ enumerable: true,
4312
+ configurable: true
4313
+ });
4314
+ Object.defineProperty(ReconnectingWebSocket.prototype, "readyState", {
4315
+ /**
4316
+ * The current state of the connection; this is one of the Ready state constants
4317
+ */ get: function() {
4318
+ if (this._ws) return this._ws.readyState;
4319
+ return this._options.startClosed ? ReconnectingWebSocket.CLOSED : ReconnectingWebSocket.CONNECTING;
4320
+ },
4321
+ enumerable: true,
4322
+ configurable: true
4323
+ });
4324
+ Object.defineProperty(ReconnectingWebSocket.prototype, "url", {
4325
+ /**
4326
+ * The URL as resolved by the constructor
4327
+ */ get: function() {
4328
+ return this._ws ? this._ws.url : '';
4329
+ },
4330
+ enumerable: true,
4331
+ configurable: true
4332
+ });
4333
+ /**
4334
+ * Closes the WebSocket connection or connection attempt, if any. If the connection is already
4335
+ * CLOSED, this method does nothing
4336
+ */ ReconnectingWebSocket.prototype.close = function(code, reason) {
4337
+ if (void 0 === code) code = 1000;
4338
+ this._closeCalled = true;
4339
+ this._shouldReconnect = false;
4340
+ this._clearTimeouts();
4341
+ if (!this._ws) {
4342
+ this._debug('close enqueued: no ws instance');
4343
+ return;
4344
+ }
4345
+ if (this._ws.readyState === this.CLOSED) {
4346
+ this._debug('close: already closed');
4347
+ return;
4348
+ }
4349
+ this._ws.close(code, reason);
4350
+ };
4351
+ /**
4352
+ * Closes the WebSocket connection or connection attempt and connects again.
4353
+ * Resets retry counter;
4354
+ */ ReconnectingWebSocket.prototype.reconnect = function(code, reason) {
4355
+ this._shouldReconnect = true;
4356
+ this._closeCalled = false;
4357
+ this._retryCount = -1;
4358
+ if (this._ws && this._ws.readyState !== this.CLOSED) {
4359
+ this._disconnect(code, reason);
4360
+ this._connect();
4361
+ } else this._connect();
4362
+ };
4363
+ /**
4364
+ * Enqueue specified data to be transmitted to the server over the WebSocket connection
4365
+ */ ReconnectingWebSocket.prototype.send = function(data) {
4366
+ if (this._ws && this._ws.readyState === this.OPEN) {
4367
+ this._debug('send', data);
4368
+ this._ws.send(data);
4369
+ } else {
4370
+ var _a = this._options.maxEnqueuedMessages, maxEnqueuedMessages = void 0 === _a ? DEFAULT.maxEnqueuedMessages : _a;
4371
+ if (this._messageQueue.length < maxEnqueuedMessages) {
4372
+ this._debug('enqueue', data);
4373
+ this._messageQueue.push(data);
4374
+ }
4375
+ }
4376
+ };
4377
+ /**
4378
+ * Register an event handler of a specific event type
4379
+ */ ReconnectingWebSocket.prototype.addEventListener = function(type, listener) {
4380
+ if (this._listeners[type]) // @ts-ignore
4381
+ this._listeners[type].push(listener);
4382
+ };
4383
+ ReconnectingWebSocket.prototype.dispatchEvent = function(event) {
4384
+ var e_1, _a;
4385
+ var listeners = this._listeners[event.type];
4386
+ if (listeners) try {
4387
+ for(var listeners_1 = __values(listeners), listeners_1_1 = listeners_1.next(); !listeners_1_1.done; listeners_1_1 = listeners_1.next()){
4388
+ var listener = listeners_1_1.value;
4389
+ this._callEventListener(event, listener);
4390
+ }
4391
+ } catch (e_1_1) {
4392
+ e_1 = {
4393
+ error: e_1_1
4394
+ };
4395
+ } finally{
4396
+ try {
4397
+ if (listeners_1_1 && !listeners_1_1.done && (_a = listeners_1.return)) _a.call(listeners_1);
4398
+ } finally{
4399
+ if (e_1) throw e_1.error;
4400
+ }
4401
+ }
4402
+ return true;
4403
+ };
4404
+ /**
4405
+ * Removes an event listener
4406
+ */ ReconnectingWebSocket.prototype.removeEventListener = function(type, listener) {
4407
+ if (this._listeners[type]) // @ts-ignore
4408
+ this._listeners[type] = this._listeners[type].filter(function(l) {
4409
+ return l !== listener;
4410
+ });
4411
+ };
4412
+ ReconnectingWebSocket.prototype._debug = function() {
4413
+ var args = [];
4414
+ for(var _i = 0; _i < arguments.length; _i++)args[_i] = arguments[_i];
4415
+ if (this._options.debug) // not using spread because compiled version uses Symbols
4416
+ // tslint:disable-next-line
4417
+ console.log.apply(console, __spread([
4418
+ 'RWS>'
4419
+ ], args));
4420
+ };
4421
+ ReconnectingWebSocket.prototype._getNextDelay = function() {
4422
+ 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;
4423
+ var delay = 0;
4424
+ if (this._retryCount > 0) {
4425
+ delay = minReconnectionDelay * Math.pow(reconnectionDelayGrowFactor, this._retryCount - 1);
4426
+ if (delay > maxReconnectionDelay) delay = maxReconnectionDelay;
4427
+ }
4428
+ this._debug('next delay', delay);
4429
+ return delay;
4430
+ };
4431
+ ReconnectingWebSocket.prototype._wait = function() {
4432
+ var _this = this;
4433
+ return new Promise(function(resolve) {
4434
+ setTimeout(resolve, _this._getNextDelay());
4435
+ });
4436
+ };
4437
+ ReconnectingWebSocket.prototype._getNextUrl = function(urlProvider) {
4438
+ if ('string' == typeof urlProvider) return Promise.resolve(urlProvider);
4439
+ if ('function' == typeof urlProvider) {
4440
+ var url = urlProvider();
4441
+ if ('string' == typeof url) return Promise.resolve(url);
4442
+ if (!!url.then) return url;
4443
+ }
4444
+ throw Error('Invalid URL');
4445
+ };
4446
+ ReconnectingWebSocket.prototype._connect = function() {
4447
+ var _this = this;
4448
+ if (this._connectLock || !this._shouldReconnect) return;
4449
+ this._connectLock = true;
4450
+ 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;
4451
+ if (this._retryCount >= maxRetries) {
4452
+ this._debug('max retries reached', this._retryCount, '>=', maxRetries);
4453
+ return;
4454
+ }
4455
+ this._retryCount++;
4456
+ this._debug('connect', this._retryCount);
4457
+ this._removeListeners();
4458
+ if (!isWebSocket(WebSocket1)) throw Error('No valid WebSocket class provided');
4459
+ this._wait().then(function() {
4460
+ return _this._getNextUrl(_this._url);
4461
+ }).then(function(url) {
4462
+ // close could be called before creating the ws
4463
+ if (_this._closeCalled) return;
4464
+ _this._debug('connect', {
4465
+ url: url,
4466
+ protocols: _this._protocols
4467
+ });
4468
+ _this._ws = _this._protocols ? new WebSocket1(url, _this._protocols) : new WebSocket1(url);
4469
+ _this._ws.binaryType = _this._binaryType;
4470
+ _this._connectLock = false;
4471
+ _this._addListeners();
4472
+ _this._connectTimeout = setTimeout(function() {
4473
+ return _this._handleTimeout();
4474
+ }, connectionTimeout);
4475
+ });
4476
+ };
4477
+ ReconnectingWebSocket.prototype._handleTimeout = function() {
4478
+ this._debug('timeout event');
4479
+ this._handleError(new reconnecting_websocket_mjs_ErrorEvent(Error('TIMEOUT'), this));
4480
+ };
4481
+ ReconnectingWebSocket.prototype._disconnect = function(code, reason) {
4482
+ if (void 0 === code) code = 1000;
4483
+ this._clearTimeouts();
4484
+ if (!this._ws) return;
4485
+ this._removeListeners();
4486
+ try {
4487
+ this._ws.close(code, reason);
4488
+ this._handleClose(new reconnecting_websocket_mjs_CloseEvent(code, reason, this));
4489
+ } catch (error) {
4490
+ // ignore
4491
+ }
4492
+ };
4493
+ ReconnectingWebSocket.prototype._acceptOpen = function() {
4494
+ this._debug('accept open');
4495
+ this._retryCount = 0;
4496
+ };
4497
+ ReconnectingWebSocket.prototype._callEventListener = function(event, listener) {
4498
+ if ('handleEvent' in listener) // @ts-ignore
4499
+ listener.handleEvent(event);
4500
+ else // @ts-ignore
4501
+ listener(event);
4502
+ };
4503
+ ReconnectingWebSocket.prototype._removeListeners = function() {
4504
+ if (!this._ws) return;
4505
+ this._debug('removeListeners');
4506
+ this._ws.removeEventListener('open', this._handleOpen);
4507
+ this._ws.removeEventListener('close', this._handleClose);
4508
+ this._ws.removeEventListener('message', this._handleMessage);
4509
+ // @ts-ignore
4510
+ this._ws.removeEventListener('error', this._handleError);
4511
+ };
4512
+ ReconnectingWebSocket.prototype._addListeners = function() {
4513
+ if (!this._ws) return;
4514
+ this._debug('addListeners');
4515
+ this._ws.addEventListener('open', this._handleOpen);
4516
+ this._ws.addEventListener('close', this._handleClose);
4517
+ this._ws.addEventListener('message', this._handleMessage);
4518
+ // @ts-ignore
4519
+ this._ws.addEventListener('error', this._handleError);
4520
+ };
4521
+ ReconnectingWebSocket.prototype._clearTimeouts = function() {
4522
+ clearTimeout(this._connectTimeout);
4523
+ clearTimeout(this._uptimeTimeout);
4524
+ };
4525
+ return ReconnectingWebSocket;
4526
+ }();
4527
+ /* ESM default export */ const reconnecting_websocket_mjs = reconnecting_websocket_mjs_ReconnectingWebSocket;
4528
+ class WebSocketAPI {
4529
+ // Standard WebSocket properties
4530
+ get readyState() {
4531
+ return this.rws.readyState;
4532
+ }
4533
+ // Standard WebSocket methods
4534
+ send(data) {
4535
+ return this.rws.send(JSON.stringify(data));
4536
+ }
4537
+ close(code, reason) {
4538
+ return this.rws.close(code, reason);
4539
+ }
4540
+ reconnect(code, reason) {
4541
+ return this.rws.reconnect(code, reason);
4542
+ }
4543
+ // Event listener methods
4544
+ addEventListener(type, listener) {
4545
+ this.rws.addEventListener(type, listener);
4546
+ }
4547
+ removeEventListener(type, listener) {
4548
+ this.rws.removeEventListener(type, listener);
4549
+ }
4550
+ constructor(url, options = {}){
4551
+ // Event handler methods
4552
+ this.onmessage = null;
4553
+ this.onopen = null;
4554
+ this.onclose = null;
4555
+ this.onerror = null;
4556
+ const separator = url.includes('?') ? '&' : '?';
4557
+ const { authorization } = options.headers || {};
4558
+ this.rws = new reconnecting_websocket_mjs(`${url}${separator}authorization=${authorization}`, [], {
4559
+ WebSocket: utils_isBrowser() ? window.WebSocket : class extends browser_default() {
4560
+ constructor(url2, protocols){
4561
+ super(url2, protocols, {
4562
+ headers: options.headers
4563
+ });
4564
+ }
4565
+ },
4566
+ ...options
4567
+ });
4568
+ this.rws.addEventListener('message', (event)=>{
4569
+ try {
4570
+ var _this_onmessage, _this;
4571
+ const data = JSON.parse(event.data);
4572
+ null === (_this_onmessage = (_this = this).onmessage) || void 0 === _this_onmessage || _this_onmessage.call(_this, data, event);
4573
+ } catch (error) {
4574
+ console.error('WebSocketAPI onmessage error', error);
4575
+ }
4576
+ });
4577
+ this.rws.addEventListener('open', (event)=>{
4578
+ var _this_onopen, _this;
4579
+ null === (_this_onopen = (_this = this).onopen) || void 0 === _this_onopen || _this_onopen.call(_this, event);
4580
+ });
4581
+ this.rws.addEventListener('close', (event)=>{
4582
+ var _this_onclose, _this;
4583
+ null === (_this_onclose = (_this = this).onclose) || void 0 === _this_onclose || _this_onclose.call(_this, event);
4584
+ });
4585
+ this.rws.addEventListener('error', (event)=>{
4586
+ var _event_target__req_res, _event_target__req, _event_target, _event_target__req_res1, _event_target__req1, _event_target1, _this_onerror, _this;
4587
+ 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;
4588
+ 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) || [];
4589
+ const logidIndex = rawHeaders.findIndex((header)=>'X-Tt-Logid' === header);
4590
+ const logid = -1 !== logidIndex ? rawHeaders[logidIndex + 1] : void 0;
4591
+ const error = {
4592
+ id: '0',
4593
+ event_type: types_WebsocketsEventType.ERROR,
4594
+ data: {
4595
+ code: -1,
4596
+ msg: 'WebSocket error'
4597
+ },
4598
+ detail: {
4599
+ logid
4600
+ }
4601
+ };
4602
+ if (401 === statusCode) {
4603
+ error.data.code = 401;
4604
+ error.data.msg = 'Unauthorized';
4605
+ } else if (403 === statusCode) {
4606
+ error.data.code = 403;
4607
+ error.data.msg = 'Forbidden';
4608
+ } else {
4609
+ error.data.code = 500;
4610
+ error.data.msg = String(null == event ? void 0 : event.error) || 'WebSocket error';
4611
+ }
4612
+ null === (_this_onerror = (_this = this).onerror) || void 0 === _this_onerror || _this_onerror.call(_this, error, event);
4613
+ });
4614
+ }
4615
+ }
4616
+ // EXTERNAL MODULE: os (ignored)
4617
+ var os_ignored_ = __webpack_require__("?9050");
4618
+ var os_ignored_default = /*#__PURE__*/ __webpack_require__.n(os_ignored_);
4619
+ var package_namespaceObject = JSON.parse('{"name":"@coze/api","version":"1.0.20","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"},"main":"src/index.ts","module":"src/index.ts","browser":{"crypto":false,"os":false,"jsonwebtoken":false,"node-fetch":false},"types":"src/index.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","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"}},"main":"dist/cjs/index.cjs","module":"dist/esm/index.js","types":"dist/types/index.d.ts"}}'); // CONCATENATED MODULE: ../coze-js/src/version.ts
4620
+ const { version: version_version } = package_namespaceObject;
3897
4621
  const getEnv = ()=>{
3898
4622
  const nodeVersion = process.version.slice(1); // Remove 'v' prefix
3899
4623
  const { platform } = process;
3900
4624
  let osName = platform.toLowerCase();
3901
- let osVersion = os_ignored_.release();
4625
+ let osVersion = os_ignored_default().release();
3902
4626
  if ('darwin' === platform) {
3903
4627
  osName = 'macos';
3904
4628
  // Try to parse the macOS version
3905
4629
  try {
3906
- const darwinVersion = os_ignored_.release().split('.');
4630
+ const darwinVersion = os_ignored_default().release().split('.');
3907
4631
  if (darwinVersion.length >= 2) {
3908
4632
  const majorVersion = parseInt(darwinVersion[0], 10);
3909
4633
  if (!isNaN(majorVersion) && majorVersion >= 9) {
@@ -3916,10 +4640,10 @@ const getEnv = ()=>{
3916
4640
  }
3917
4641
  } else if ('win32' === platform) {
3918
4642
  osName = 'windows';
3919
- osVersion = os_ignored_.release();
4643
+ osVersion = os_ignored_default().release();
3920
4644
  } else if ('linux' === platform) {
3921
4645
  osName = 'linux';
3922
- osVersion = os_ignored_.release();
4646
+ osVersion = os_ignored_default().release();
3923
4647
  }
3924
4648
  return {
3925
4649
  osName,
@@ -3929,12 +4653,12 @@ const getEnv = ()=>{
3929
4653
  };
3930
4654
  const getUserAgent = ()=>{
3931
4655
  const { nodeVersion, osName, osVersion } = getEnv();
3932
- return `coze-js/${esm_version} node/${nodeVersion} ${osName}/${osVersion}`.toLowerCase();
4656
+ return `coze-js/${version_version} node/${nodeVersion} ${osName}/${osVersion}`.toLowerCase();
3933
4657
  };
3934
4658
  const getNodeClientUserAgent = ()=>{
3935
4659
  const { osVersion, nodeVersion, osName } = getEnv();
3936
4660
  const ua = {
3937
- version: esm_version,
4661
+ version: version_version,
3938
4662
  lang: 'node',
3939
4663
  lang_version: nodeVersion,
3940
4664
  os_name: osName,
@@ -3983,7 +4707,7 @@ const getBrowserClientUserAgent = ()=>{
3983
4707
  browserInfo.version = (null === (_userAgent_match5 = userAgent.match(/Version\/([0-9.]+)/)) || void 0 === _userAgent_match5 ? void 0 : _userAgent_match5[1]) || 'unknown';
3984
4708
  }
3985
4709
  const ua = {
3986
- version: esm_version,
4710
+ version: version_version,
3987
4711
  browser: browserInfo.name,
3988
4712
  browser_version: browserInfo.version,
3989
4713
  os_name: osInfo.name,
@@ -3991,15 +4715,37 @@ const getBrowserClientUserAgent = ()=>{
3991
4715
  };
3992
4716
  return JSON.stringify(ua);
3993
4717
  };
3994
- /* eslint-disable @typescript-eslint/no-explicit-any */ const esm_handleError = (error)=>{
4718
+ // EXTERNAL MODULE: node-fetch (ignored)
4719
+ var node_fetch_ignored_ = __webpack_require__("?8dee");
4720
+ var node_fetch_ignored_default = /*#__PURE__*/ __webpack_require__.n(node_fetch_ignored_);
4721
+ /* eslint-disable @typescript-eslint/no-explicit-any */ const fetcher_handleError = (error)=>{
3995
4722
  if (!error.isAxiosError && (!error.code || !error.message)) return new CozeError(`Unexpected error: ${error.message}`);
3996
4723
  if ('ECONNABORTED' === error.code && error.message.includes('timeout') || 'ETIMEDOUT' === error.code) {
3997
4724
  var _error_response;
3998
4725
  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
4726
  }
4000
4727
  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);
4728
+ else {
4729
+ var _error_response1, _error_response2, _error_response3;
4730
+ 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);
4731
+ }
4732
+ };
4733
+ // node-fetch is used for streaming requests
4734
+ const adapterFetch = async (options)=>{
4735
+ const response = await node_fetch_ignored_default()(options.url, {
4736
+ body: options.data,
4737
+ ...options
4738
+ });
4739
+ return {
4740
+ data: response.body,
4741
+ ...response
4742
+ };
4743
+ };
4744
+ const isSupportNativeFetch = ()=>{
4745
+ if (utils_isBrowser()) return true;
4746
+ // native fetch is supported in node 18.0.0 or higher
4747
+ const version = process.version.slice(1);
4748
+ return compareVersions(version, '18.0.0') >= 0;
4003
4749
  };
4004
4750
  async function fetchAPI(url) {
4005
4751
  let options = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
@@ -4012,10 +4758,10 @@ async function fetchAPI(url) {
4012
4758
  const response = await axiosInstance({
4013
4759
  url,
4014
4760
  responseType: options.isStreaming ? 'stream' : 'json',
4015
- adapter: options.isStreaming ? 'fetch' : void 0,
4761
+ adapter: options.isStreaming ? isSupportNativeFetch() ? 'fetch' : adapterFetch : void 0,
4016
4762
  ...options
4017
4763
  }).catch((error)=>{
4018
- throw esm_handleError(error);
4764
+ throw fetcher_handleError(error);
4019
4765
  });
4020
4766
  return {
4021
4767
  async *stream () {
@@ -4053,7 +4799,7 @@ async function fetchAPI(url) {
4053
4799
  buffer = lines[lines.length - 1]; // Keep the last incomplete line in the buffer
4054
4800
  }
4055
4801
  } catch (error) {
4056
- esm_handleError(error);
4802
+ fetcher_handleError(error);
4057
4803
  }
4058
4804
  },
4059
4805
  json: ()=>response.data,
@@ -4077,8 +4823,11 @@ function isAxiosStatic(instance) {
4077
4823
  }
4078
4824
  /**
4079
4825
  * 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 {
4826
+ */ const constant_COZE_COM_BASE_URL = 'https://api.coze.com';
4827
+ /**
4828
+ * default base websocket URL is wss://ws.coze.com
4829
+ */ const COZE_COM_BASE_WS_URL = 'wss://ws.coze.com';
4830
+ /* eslint-disable max-params */ class core_APIClient {
4082
4831
  async getToken() {
4083
4832
  if ('function' == typeof this.token) return await this.token();
4084
4833
  return this.token;
@@ -4088,28 +4837,50 @@ function isAxiosStatic(instance) {
4088
4837
  const headers = {
4089
4838
  authorization: `Bearer ${token}`
4090
4839
  };
4091
- if (isBrowser()) headers['X-Coze-Client-User-Agent'] = getBrowserClientUserAgent();
4840
+ if (utils_isBrowser()) headers['X-Coze-Client-User-Agent'] = getBrowserClientUserAgent();
4092
4841
  else {
4093
4842
  headers['User-Agent'] = getUserAgent();
4094
4843
  headers['X-Coze-Client-User-Agent'] = getNodeClientUserAgent();
4095
4844
  }
4096
- const config = esm_mergeConfig(this.axiosOptions, options, {
4845
+ const config = mergeConfig(this.axiosOptions, options, {
4097
4846
  headers
4847
+ }, {
4848
+ headers: this.headers || {}
4098
4849
  });
4099
4850
  config.method = method;
4100
4851
  config.data = body;
4101
4852
  return config;
4102
4853
  }
4854
+ async buildWebsocketOptions(options) {
4855
+ const token = await this.getToken();
4856
+ const headers = {
4857
+ authorization: `Bearer ${token}`
4858
+ };
4859
+ if (utils_isBrowser()) headers['X-Coze-Client-User-Agent'] = getBrowserClientUserAgent();
4860
+ else {
4861
+ headers['User-Agent'] = getUserAgent();
4862
+ headers['X-Coze-Client-User-Agent'] = getNodeClientUserAgent();
4863
+ }
4864
+ var _this__config_debug;
4865
+ const config = mergeConfig({
4866
+ debug: null !== (_this__config_debug = this._config.debug) && void 0 !== _this__config_debug && _this__config_debug
4867
+ }, this._config.websocketOptions, options, {
4868
+ headers
4869
+ }, {
4870
+ headers: this.headers || {}
4871
+ });
4872
+ return config;
4873
+ }
4103
4874
  async makeRequest(apiUrl, method, body, isStream, options) {
4104
4875
  const fullUrl = `${this.baseURL}${apiUrl}`;
4105
4876
  const fetchOptions = await this.buildOptions(method, body, options);
4106
4877
  fetchOptions.isStreaming = isStream;
4107
4878
  fetchOptions.axiosInstance = this.axiosInstance;
4108
- this.debugLog(`--- request url: ${fullUrl}`);
4109
- this.debugLog('--- request options:', fetchOptions);
4879
+ this.debugLog(null == options ? void 0 : options.debug, `--- request url: ${fullUrl}`);
4880
+ this.debugLog(null == options ? void 0 : options.debug, '--- request options:', fetchOptions);
4110
4881
  const { response, stream, json } = await fetchAPI(fullUrl, fetchOptions);
4111
- this.debugLog(`--- response status: ${response.status}`);
4112
- this.debugLog('--- response headers: ', response.headers);
4882
+ this.debugLog(null == options ? void 0 : options.debug, `--- response status: ${response.status}`);
4883
+ this.debugLog(null == options ? void 0 : options.debug, '--- response headers: ', response.headers);
4113
4884
  var _response_headers;
4114
4885
  // Taro use `header`
4115
4886
  const contentType = (null !== (_response_headers = response.headers) && void 0 !== _response_headers ? _response_headers : response.header)['content-type'];
@@ -4117,7 +4888,7 @@ function isAxiosStatic(instance) {
4117
4888
  if (contentType && contentType.includes('application/json')) {
4118
4889
  const result = await json();
4119
4890
  const { code, msg } = result;
4120
- if (0 !== code && void 0 !== code) throw APIError.generate(response.status, result, msg, response.headers);
4891
+ if (0 !== code && void 0 !== code) throw error_APIError.generate(response.status, result, msg, response.headers);
4121
4892
  }
4122
4893
  return stream();
4123
4894
  }
@@ -4125,7 +4896,7 @@ function isAxiosStatic(instance) {
4125
4896
  {
4126
4897
  const result = await json();
4127
4898
  const { code, msg } = result;
4128
- if (0 !== code && void 0 !== code) throw APIError.generate(response.status, result, msg, response.headers);
4899
+ if (0 !== code && void 0 !== code) throw error_APIError.generate(response.status, result, msg, response.headers);
4129
4900
  return result;
4130
4901
  }
4131
4902
  }
@@ -4147,41 +4918,55 @@ function isAxiosStatic(instance) {
4147
4918
  async delete(apiUrl, isStream, options) {
4148
4919
  return this.makeRequest(apiUrl, 'DELETE', void 0, isStream, options);
4149
4920
  }
4921
+ async makeWebsocket(apiUrl, options) {
4922
+ const fullUrl = `${this.baseWsURL}${apiUrl}`;
4923
+ const websocketOptions = await this.buildWebsocketOptions(options);
4924
+ this.debugLog(null == options ? void 0 : options.debug, `--- websocket url: ${fullUrl}`);
4925
+ this.debugLog(null == options ? void 0 : options.debug, '--- websocket options:', websocketOptions);
4926
+ const ws = new WebSocketAPI(fullUrl, websocketOptions);
4927
+ return ws;
4928
+ }
4150
4929
  getConfig() {
4151
4930
  return this._config;
4152
4931
  }
4153
4932
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
4154
4933
  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);
4934
+ let forceDebug = arguments.length > 0 && void 0 !== arguments[0] && arguments[0];
4935
+ for(var _len = arguments.length, msgs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++)msgs[_key - 1] = arguments[_key];
4936
+ if (this.debug || forceDebug) console.debug(...msgs);
4157
4937
  }
4158
4938
  constructor(config){
4159
4939
  this._config = config;
4160
- this.baseURL = config.baseURL || COZE_COM_BASE_URL;
4940
+ this.baseURL = config.baseURL || constant_COZE_COM_BASE_URL;
4941
+ this.baseWsURL = config.baseWsURL || COZE_COM_BASE_WS_URL;
4161
4942
  this.token = config.token;
4162
4943
  this.axiosOptions = config.axiosOptions || {};
4163
4944
  this.axiosInstance = config.axiosInstance;
4164
4945
  this.debug = config.debug || false;
4165
4946
  this.allowPersonalAccessTokenInBrowser = config.allowPersonalAccessTokenInBrowser || false;
4166
4947
  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 {
4948
+ 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');
4949
+ }
4950
+ }
4951
+ core_APIClient.APIError = error_APIError;
4952
+ core_APIClient.BadRequestError = BadRequestError;
4953
+ core_APIClient.AuthenticationError = AuthenticationError;
4954
+ core_APIClient.PermissionDeniedError = PermissionDeniedError;
4955
+ core_APIClient.NotFoundError = NotFoundError;
4956
+ core_APIClient.RateLimitError = RateLimitError;
4957
+ core_APIClient.InternalServerError = InternalServerError;
4958
+ core_APIClient.GatewayError = GatewayError;
4959
+ core_APIClient.TimeoutError = TimeoutError;
4960
+ core_APIClient.UserAbortError = APIUserAbortError;
4961
+ // EXTERNAL MODULE: crypto (ignored)
4962
+ __webpack_require__("?666e");
4963
+ // EXTERNAL MODULE: jsonwebtoken (ignored)
4964
+ __webpack_require__("?79fd");
4965
+ class CozeAPI extends core_APIClient {
4181
4966
  constructor(...args){
4182
4967
  super(...args), this.bots = new Bots(this), this.chat = new Chat(this), this.conversations = new Conversations(this), this.files = new Files(this), /**
4183
4968
  * @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);
4969
+ */ 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
4970
  }
4186
4971
  }
4187
4972
  /**
@@ -38566,7 +39351,7 @@ var VERTC = _createClass(function e() {
38566
39351
  + * @param milliseconds The time to sleep in milliseconds
38567
39352
  + * @throws {Error} If milliseconds is negative
38568
39353
  + * @returns Promise that resolves after the specified duration
38569
- + */ const utils_sleep = (milliseconds)=>{
39354
+ + */ const src_utils_sleep = (milliseconds)=>{
38570
39355
  if (milliseconds < 0) throw new Error('Sleep duration must be non-negative');
38571
39356
  return new Promise((resolve)=>setTimeout(resolve, milliseconds));
38572
39357
  };
@@ -42298,6 +43083,9 @@ class EngineClient extends RealtimeEventHandler {
42298
43083
  throw e;
42299
43084
  }
42300
43085
  }
43086
+ getRtcEngine() {
43087
+ return this.engine;
43088
+ }
42301
43089
  // eslint-disable-next-line max-params
42302
43090
  constructor(appId, debug = false, isTestEnv = false, isSupportVideo = false, videoConfig){
42303
43091
  super(debug), this.joinUserId = '', this._AIAnsExtension = null, this._isSupportVideo = false;
@@ -42330,9 +43118,11 @@ class RealtimeClient extends RealtimeEventHandler {
42330
43118
  // Step1 get token
42331
43119
  roomInfo = await this._api.audio.rooms.create({
42332
43120
  bot_id: botId,
42333
- conversation_id: conversationId,
43121
+ conversation_id: conversationId || void 0,
42334
43122
  voice_id: voiceId && voiceId.length > 0 ? voiceId : void 0,
42335
- connector_id: this._config.connectorId
43123
+ connector_id: this._config.connectorId,
43124
+ uid: this._config.userId || void 0,
43125
+ workflow_id: this._config.workflowId || void 0
42336
43126
  });
42337
43127
  } catch (error) {
42338
43128
  this.dispatch(event_handler_EventNames.ERROR, error);
@@ -42483,6 +43273,14 @@ class RealtimeClient extends RealtimeEventHandler {
42483
43273
  });
42484
43274
  }
42485
43275
  /**
43276
+ * en: Get the RTC engine instance, for detail visit https://www.volcengine.com/docs/6348/104481
43277
+ *
43278
+ * zh: 获取 RTC 引擎实例,详情请访问 https://www.volcengine.com/docs/6348/104481
43279
+ */ getRtcEngine() {
43280
+ var _this__client;
43281
+ return null === (_this__client = this._client) || void 0 === _this__client ? void 0 : _this__client.getRtcEngine();
43282
+ }
43283
+ /**
42486
43284
  * Constructor for initializing a RealtimeClient instance.
42487
43285
  *
42488
43286
  * 构造函数,初始化RealtimeClient实例。
@@ -42496,6 +43294,8 @@ class RealtimeClient extends RealtimeEventHandler {
42496
43294
  * 可选,音色Id。
42497
43295
  * @param config.conversationId - Optional, Conversation Id. |
42498
43296
  * 可选,会话Id。
43297
+ * @param config.userId - Optional, User Id. |
43298
+ * 可选,用户Id。
42499
43299
  * @param config.baseURL - Optional, defaults to "https://api.coze.cn". |
42500
43300
  * 可选,默认值为 "https://api.coze.cn"。
42501
43301
  * @param config.debug - Optional, defaults to false.