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

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