@coze/realtime-api 0.0.2 → 0.0.4

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.
@@ -0,0 +1 @@
1
+ /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coze/realtime-api",
3
- "version": "0.0.2",
3
+ "version": "0.0.4",
4
4
  "description": "Coze Realtime API",
5
5
  "homepage": "https://github.com/coze-dev/coze-js/packages/realtime-api",
6
6
  "repository": {
@@ -12,42 +12,50 @@
12
12
  "author": "jackshen <jackshen310@gmail.com>",
13
13
  "type": "module",
14
14
  "exports": {
15
- ".": "./dist/index.js"
15
+ ".": {
16
+ "require": "./dist/cjs/index.cjs",
17
+ "import": "./dist/esm/index.js",
18
+ "types": "./dist/types/index.d.ts"
19
+ }
16
20
  },
17
- "main": "dist/index.js",
18
- "types": "dist/index.d.ts",
21
+ "main": "dist/cjs/index.cjs",
22
+ "module": "dist/esm/index.js",
23
+ "typings": "dist/types/index.d.ts",
19
24
  "files": [
20
25
  "dist",
21
26
  "assets",
22
27
  "LICENSE",
28
+ "!**/*.tsbuildinfo",
23
29
  "README.md"
24
30
  ],
25
31
  "scripts": {
26
- "build": "rm -rf dist && tsc -b tsconfig.build.json",
27
- "buildAll": "npm run build && cd examples/realtime-console && npm run build",
28
- "demo": "npm run build && cd examples/realtime-console && npm run start",
32
+ "build": "rm -rf ./dist && rslib build",
33
+ "buildAll": "npm run build && cd ../../examples/realtime-console && npm run build",
34
+ "demo": "npm run start & cd ../../examples/realtime-console && npm run start",
29
35
  "format": "prettier --write .",
30
36
  "lint": "eslint ./ --cache --quiet",
31
37
  "prepublishOnly": "npm run build",
32
- "start": "rm -rf dist && tsc -b -w tsconfig.build.json",
33
- "test": "jest --coverage --config=jest.config.cjs ./test/*"
38
+ "start": "rm -rf dist && rslib build -w",
39
+ "test": "vitest",
40
+ "test:cov": "vitest --coverage --run"
34
41
  },
35
42
  "dependencies": {
36
- "@coze/api": "1.0.0",
43
+ "@coze/api": "1.0.8",
37
44
  "@volcengine/rtc": "^4.62.1"
38
45
  },
39
46
  "devDependencies": {
40
47
  "@coze-infra/eslint-config": "workspace:*",
41
48
  "@coze-infra/ts-config": "workspace:*",
49
+ "@coze-infra/vitest-config": "workspace:*",
50
+ "@rslib/core": "0.0.18",
42
51
  "@swc/core": "^1.3.14",
43
- "@types/jest": "^29.2.2",
44
52
  "@types/node": "^20",
45
53
  "@types/uuid": "^9.0.1",
46
54
  "@types/whatwg-fetch": "^0.0.33",
55
+ "@vitest/coverage-v8": "~2.1.4",
47
56
  "axios": "^1.7.7",
48
- "jest": "^29.3.0",
49
- "ts-jest": "^29.0.3",
50
- "typescript": "^5.5.3"
57
+ "typescript": "^5.5.3",
58
+ "vitest": "~2.1.4"
51
59
  },
52
60
  "peerDependencies": {
53
61
  "axios": "^1.7.1"
package/dist/client.js DELETED
@@ -1,205 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.EngineClient = void 0;
27
- const rtc_1 = __importStar(require("@volcengine/rtc"));
28
- const event_handler_1 = require("./event-handler");
29
- const error_1 = require("./error");
30
- class EngineClient extends event_handler_1.RealtimeEventHandler {
31
- constructor(appId, debug = false, isTestEnv = false) {
32
- super(debug);
33
- this.joinUserId = '';
34
- if (isTestEnv) {
35
- rtc_1.default.setParameter('ICE_CONFIG_REQUEST_URLS', ['rtc-test.bytedance.com']);
36
- }
37
- this.engine = rtc_1.default.createEngine(appId);
38
- this.handleMessage = this.handleMessage.bind(this);
39
- this.handleUserJoin = this.handleUserJoin.bind(this);
40
- this.handleUserLeave = this.handleUserLeave.bind(this);
41
- this.handleEventError = this.handleEventError.bind(this);
42
- // Debug only
43
- this.handleLocalAudioPropertiesReport =
44
- this.handleLocalAudioPropertiesReport.bind(this);
45
- this.handleRemoteAudioPropertiesReport =
46
- this.handleRemoteAudioPropertiesReport.bind(this);
47
- }
48
- bindEngineEvents() {
49
- this.engine.on(rtc_1.default.events.onUserMessageReceived, this.handleMessage);
50
- this.engine.on(rtc_1.default.events.onUserJoined, this.handleUserJoin);
51
- this.engine.on(rtc_1.default.events.onUserLeave, this.handleUserLeave);
52
- this.engine.on(rtc_1.default.events.onError, this.handleEventError);
53
- if (this._debug) {
54
- this.engine.on(rtc_1.default.events.onLocalAudioPropertiesReport, this.handleLocalAudioPropertiesReport);
55
- this.engine.on(rtc_1.default.events.onRemoteAudioPropertiesReport, this.handleRemoteAudioPropertiesReport);
56
- }
57
- }
58
- removeEventListener() {
59
- this.engine.off(rtc_1.default.events.onUserMessageReceived, this.handleMessage);
60
- this.engine.off(rtc_1.default.events.onUserJoined, this.handleUserJoin);
61
- this.engine.off(rtc_1.default.events.onUserLeave, this.handleUserLeave);
62
- this.engine.off(rtc_1.default.events.onError, this.handleEventError);
63
- if (this._debug) {
64
- this.engine.off(rtc_1.default.events.onLocalAudioPropertiesReport, this.handleLocalAudioPropertiesReport);
65
- this.engine.off(rtc_1.default.events.onRemoteAudioPropertiesReport, this.handleRemoteAudioPropertiesReport);
66
- }
67
- }
68
- handleMessage(event) {
69
- try {
70
- const message = JSON.parse(event.message);
71
- this.dispatch(`server.${message.event_type}`, message);
72
- }
73
- catch (e) {
74
- this.dispatch('client.error', {
75
- message: `Failed to parse message: ${event.message}`,
76
- error: e,
77
- });
78
- }
79
- }
80
- handleEventError(e) {
81
- this.dispatch('client.error', e);
82
- }
83
- handleUserJoin(event) {
84
- this.joinUserId = event.userInfo.userId;
85
- this.dispatch('server.bot.join', event);
86
- }
87
- handleUserLeave(event) {
88
- this.dispatch('server.bot.leave', event);
89
- }
90
- async joinRoom(options) {
91
- const { token, roomId, uid, audioMutedDefault = false } = options;
92
- try {
93
- await this.engine.joinRoom(token, roomId, {
94
- userId: uid,
95
- }, {
96
- isAutoPublish: !audioMutedDefault,
97
- isAutoSubscribeAudio: true,
98
- isAutoSubscribeVideo: false,
99
- });
100
- }
101
- catch (e) {
102
- if (e instanceof Error) {
103
- throw new error_1.RealtimeAPIError(error_1.RealtimeError.CONNECTION_ERROR, e.message);
104
- }
105
- throw new error_1.RealtimeAPIError(error_1.RealtimeError.CONNECTION_ERROR, 'Unknown error');
106
- }
107
- }
108
- async getDevices() {
109
- const devices = await rtc_1.default.enumerateDevices();
110
- return {
111
- audioInputs: devices.filter(i => i.deviceId && i.kind === 'audioinput'),
112
- };
113
- }
114
- async createLocalStream() {
115
- const devices = await this.getDevices();
116
- if (!devices.audioInputs.length) {
117
- throw new error_1.RealtimeAPIError(error_1.RealtimeError.DEVICE_ACCESS_ERROR, 'Failed to get devices');
118
- }
119
- await this.engine.startAudioCapture(devices.audioInputs[0].deviceId);
120
- }
121
- async disconnect() {
122
- try {
123
- await this.engine.stopAudioCapture();
124
- await this.engine.unpublishStream(rtc_1.MediaType.AUDIO);
125
- await this.engine.leaveRoom();
126
- this.removeEventListener();
127
- }
128
- catch (e) {
129
- this.dispatch('client.error', e);
130
- throw e;
131
- }
132
- }
133
- async changeAudioState(isMicOn) {
134
- try {
135
- if (isMicOn) {
136
- await this.engine.publishStream(rtc_1.MediaType.AUDIO);
137
- }
138
- else {
139
- await this.engine.unpublishStream(rtc_1.MediaType.AUDIO);
140
- }
141
- }
142
- catch (e) {
143
- this.dispatch('client.error', e);
144
- throw e;
145
- }
146
- }
147
- async stop() {
148
- try {
149
- const result = await this.engine.sendUserMessage(this.joinUserId, JSON.stringify({
150
- id: 'event_1',
151
- event_type: 'conversation.chat.cancel',
152
- data: {},
153
- }));
154
- this._log(`interrupt ${this.joinUserId} ${result}`);
155
- }
156
- catch (e) {
157
- this.dispatch('client.error', e);
158
- throw e;
159
- }
160
- }
161
- async sendMessage(message) {
162
- try {
163
- const result = await this.engine.sendUserMessage(this.joinUserId, JSON.stringify(message));
164
- this._log(`sendMessage ${this.joinUserId} ${JSON.stringify(message)} ${result}`);
165
- }
166
- catch (e) {
167
- this.dispatch('client.error', e);
168
- throw e;
169
- }
170
- }
171
- enableAudioPropertiesReport(config) {
172
- this.engine.enableAudioPropertiesReport(config);
173
- }
174
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
175
- handleLocalAudioPropertiesReport(event) {
176
- var _a, _b;
177
- if (this._debug && ((_b = (_a = event[0]) === null || _a === void 0 ? void 0 : _a.audioPropertiesInfo) === null || _b === void 0 ? void 0 : _b.linearVolume) > 0) {
178
- console.log('handleLocalAudioPropertiesReport', event);
179
- }
180
- }
181
- handleRemoteAudioPropertiesReport(event) {
182
- if (this._debug) {
183
- console.log('handleRemoteAudioPropertiesReport', event);
184
- }
185
- }
186
- async startAudioPlaybackDeviceTest() {
187
- try {
188
- await this.engine.startAudioPlaybackDeviceTest('audio-test.wav', 200);
189
- }
190
- catch (e) {
191
- this.dispatch('client.error', e);
192
- throw e;
193
- }
194
- }
195
- stopAudioPlaybackDeviceTest() {
196
- try {
197
- this.engine.stopAudioPlaybackDeviceTest();
198
- }
199
- catch (e) {
200
- this.dispatch('client.error', e);
201
- throw e;
202
- }
203
- }
204
- }
205
- exports.EngineClient = EngineClient;
package/dist/error.js DELETED
@@ -1,36 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RealtimeAPIError = exports.ErrorMessages = exports.RealtimeError = void 0;
4
- var RealtimeError;
5
- (function (RealtimeError) {
6
- RealtimeError["DEVICE_ACCESS_ERROR"] = "DEVICE_ACCESS_ERROR";
7
- RealtimeError["STREAM_CREATION_ERROR"] = "STREAM_CREATION_ERROR";
8
- RealtimeError["CONNECTION_ERROR"] = "CONNECTION_ERROR";
9
- RealtimeError["DISCONNECTION_ERROR"] = "DISCONNECTION_ERROR";
10
- RealtimeError["INTERRUPT_ERROR"] = "INTERRUPT_ERROR";
11
- RealtimeError["EVENT_HANDLER_ERROR"] = "EVENT_HANDLER_ERROR";
12
- RealtimeError["PERMISSION_DENIED"] = "PERMISSION_DENIED";
13
- RealtimeError["NETWORK_ERROR"] = "NETWORK_ERROR";
14
- RealtimeError["INVALID_STATE"] = "INVALID_STATE";
15
- RealtimeError["CREATE_ROOM_ERROR"] = "CREATE_ROOM_ERROR";
16
- })(RealtimeError || (exports.RealtimeError = RealtimeError = {}));
17
- exports.ErrorMessages = {
18
- [RealtimeError.DEVICE_ACCESS_ERROR]: 'Failed to get devices',
19
- [RealtimeError.STREAM_CREATION_ERROR]: 'Failed to create local stream',
20
- [RealtimeError.CONNECTION_ERROR]: 'Failed to connect',
21
- [RealtimeError.DISCONNECTION_ERROR]: 'Failed to disconnect',
22
- [RealtimeError.INTERRUPT_ERROR]: 'Failed to interrupt',
23
- [RealtimeError.EVENT_HANDLER_ERROR]: 'Event handler not found',
24
- [RealtimeError.PERMISSION_DENIED]: 'Permission denied for requested operation',
25
- [RealtimeError.NETWORK_ERROR]: 'Network connection error occurred',
26
- [RealtimeError.INVALID_STATE]: 'Operation invalid in current state',
27
- [RealtimeError.CREATE_ROOM_ERROR]: 'Failed to create room',
28
- };
29
- class RealtimeAPIError extends Error {
30
- constructor(code, message) {
31
- super(`[${code}] ${message}`);
32
- this.code = code;
33
- this.name = 'RealtimeAPIError';
34
- }
35
- }
36
- exports.RealtimeAPIError = RealtimeAPIError;
@@ -1,106 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RealtimeEventHandler = exports.EventNames = void 0;
4
- const error_1 = require("./error");
5
- var EventNames;
6
- (function (EventNames) {
7
- /**
8
- * en: All events
9
- * zh: 所有事件
10
- */
11
- EventNames["ALL"] = "realtime.event";
12
- /**
13
- * en: All client events
14
- * zh: 所有客户端事件
15
- */
16
- EventNames["ALL_CLIENT"] = "client.*";
17
- /**
18
- * en: All server events
19
- * zh: 所有服务端事件
20
- */
21
- EventNames["ALL_SERVER"] = "server.*";
22
- /**
23
- * en: Client connected
24
- * zh: 客户端连接
25
- */
26
- EventNames["CONNECTED"] = "client.connected";
27
- /**
28
- * en: Client interrupted
29
- * zh: 客户端中断
30
- */
31
- EventNames["INTERRUPTED"] = "client.interrupted";
32
- /**
33
- * en: Client disconnected
34
- * zh: 客户端断开
35
- */
36
- EventNames["DISCONNECTED"] = "client.disconnected";
37
- /**
38
- * en: Client audio unmuted
39
- * zh: 客户端音频未静音
40
- */
41
- EventNames["AUDIO_UNMUTED"] = "client.audio.unmuted";
42
- /**
43
- * en: Client audio muted
44
- * zh: 客户端音频静音
45
- */
46
- EventNames["AUDIO_MUTED"] = "client.audio.muted";
47
- /**
48
- * en: Client error
49
- * zh: 客户端错误
50
- */
51
- EventNames["ERROR"] = "client.error";
52
- })(EventNames || (exports.EventNames = EventNames = {}));
53
- class RealtimeEventHandler {
54
- constructor(debug = false) {
55
- this.eventHandlers = {};
56
- this._debug = debug;
57
- }
58
- clearEventHandlers() {
59
- this.eventHandlers = {};
60
- }
61
- on(eventName, callback) {
62
- this._log(`on ${eventName} event`);
63
- this.eventHandlers[eventName] = this.eventHandlers[eventName] || [];
64
- this.eventHandlers[eventName].push(callback);
65
- return callback;
66
- }
67
- off(eventName, callback) {
68
- this._log(`off ${eventName} event`);
69
- const handlers = this.eventHandlers[eventName] || [];
70
- if (callback) {
71
- const index = handlers.indexOf(callback);
72
- if (index === -1) {
73
- throw new error_1.RealtimeAPIError(error_1.RealtimeError.EVENT_HANDLER_ERROR, `Could not turn off specified event listener for "${eventName}": not found as a listener`);
74
- }
75
- handlers.splice(index, 1);
76
- }
77
- else {
78
- delete this.eventHandlers[eventName];
79
- }
80
- }
81
- // eslint-disable-next-line max-params
82
- _dispatchToHandlers(eventName, event, handlers, prefix) {
83
- for (const handler of handlers) {
84
- if (!prefix || eventName.startsWith(prefix)) {
85
- handler(eventName, event);
86
- }
87
- }
88
- }
89
- dispatch(eventName, event) {
90
- this._log(`dispatch ${eventName} event`);
91
- const handlers = (this.eventHandlers[eventName] || []).slice();
92
- this._dispatchToHandlers(eventName, event, handlers);
93
- const allHandlers = (this.eventHandlers[EventNames.ALL] || []).slice();
94
- this._dispatchToHandlers(eventName, event, allHandlers);
95
- const allClientHandlers = (this.eventHandlers[EventNames.ALL_CLIENT] || []).slice();
96
- this._dispatchToHandlers(eventName, event, allClientHandlers, 'client.');
97
- const allServerHandlers = (this.eventHandlers[EventNames.ALL_SERVER] || []).slice();
98
- this._dispatchToHandlers(eventName, event, allServerHandlers, 'server.');
99
- }
100
- _log(message) {
101
- if (this._debug) {
102
- console.log(`[RealtimeClient] ${message}`);
103
- }
104
- }
105
- }
106
- exports.RealtimeEventHandler = RealtimeEventHandler;
package/dist/index.js DELETED
@@ -1,223 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.EventNames = exports.RealtimeError = exports.RealtimeAPIError = exports.RealtimeClient = exports.RealtimeUtils = void 0;
27
- const api_1 = require("@coze/api");
28
- const RealtimeUtils = __importStar(require("./utils"));
29
- exports.RealtimeUtils = RealtimeUtils;
30
- const event_handler_1 = require("./event-handler");
31
- Object.defineProperty(exports, "EventNames", { enumerable: true, get: function () { return event_handler_1.EventNames; } });
32
- const error_1 = require("./error");
33
- Object.defineProperty(exports, "RealtimeAPIError", { enumerable: true, get: function () { return error_1.RealtimeAPIError; } });
34
- Object.defineProperty(exports, "RealtimeError", { enumerable: true, get: function () { return error_1.RealtimeError; } });
35
- const client_1 = require("./client");
36
- class RealtimeClient extends event_handler_1.RealtimeEventHandler {
37
- /**
38
- * Constructor for initializing a RealtimeClient instance.
39
- *
40
- * 构造函数,初始化RealtimeClient实例。
41
- *
42
- * @param config
43
- * @param config.accessToken - Required, Access Token. |
44
- * 必填,Access Token。
45
- * @param config.botId - Required, Bot Id. |
46
- * 必填,Bot Id。
47
- * @param config.voiceId - Optional, Voice Id. |
48
- * 可选,音色Id。
49
- * @param config.conversationId - Optional, Conversation Id. |
50
- * 可选,会话Id。
51
- * @param config.baseURL - Optional, defaults to "https://api.coze.cn". |
52
- * 可选,默认值为 "https://api.coze.cn"。
53
- * @param config.debug - Optional, defaults to false.
54
- * 可选,默认值为 false。
55
- * @param config.allowPersonalAccessTokenInBrowser
56
- * - Optional, whether to allow personal access tokens in browser environment. |
57
- * 可选,是否允许在浏览器环境中使用个人访问令牌。
58
- * @param config.audioMutedDefault - Optional, whether audio is muted by default, defaults to false. |
59
- * 可选,默认是否静音,默认值为 false。
60
- */
61
- constructor(config) {
62
- var _a;
63
- super(config.debug);
64
- this._client = null;
65
- this._roomInfo = null;
66
- this.isConnected = false;
67
- this._isTestEnv = false;
68
- this._config = config;
69
- const defaultBaseURL = (_a = this._config.baseURL) !== null && _a !== void 0 ? _a : 'https://api.coze.cn';
70
- this._config.baseURL = defaultBaseURL;
71
- // init api
72
- this._api = new api_1.CozeAPI({
73
- token: this._config.accessToken,
74
- baseURL: defaultBaseURL,
75
- allowPersonalAccessTokenInBrowser: this._config.allowPersonalAccessTokenInBrowser,
76
- });
77
- this._isTestEnv = defaultBaseURL !== 'https://api.coze.cn';
78
- }
79
- /**
80
- * en: Establish a connection to the Coze API and join the room
81
- *
82
- * zh: 建立与 Coze API 的连接并加入房间
83
- */
84
- async connect() {
85
- var _a, _b;
86
- const { botId, conversationId, voiceId } = this._config;
87
- let roomInfo;
88
- try {
89
- // Step1 get token
90
- roomInfo = await this._api.audio.rooms.create({
91
- bot_id: botId,
92
- conversation_id: conversationId,
93
- voice_id: voiceId && voiceId.length > 0 ? voiceId : undefined,
94
- connector_id: (_a = this._config.connectorId) !== null && _a !== void 0 ? _a : '999',
95
- });
96
- }
97
- catch (error) {
98
- this.dispatch(event_handler_1.EventNames.ERROR, error);
99
- throw new error_1.RealtimeAPIError(error_1.RealtimeError.CREATE_ROOM_ERROR, error instanceof Error ? error.message : 'Unknown error');
100
- }
101
- this._roomInfo = roomInfo;
102
- // Step2 create engine
103
- this._client = new client_1.EngineClient(roomInfo.app_id, this._config.debug, this._isTestEnv);
104
- // Step3 bind engine events
105
- this._client.bindEngineEvents();
106
- this._client.on(event_handler_1.EventNames.ALL, (eventName, data) => {
107
- this.dispatch(eventName, data);
108
- });
109
- // Step4 join room
110
- await this._client.joinRoom({
111
- token: roomInfo.token,
112
- roomId: roomInfo.room_id,
113
- uid: roomInfo.uid,
114
- audioMutedDefault: (_b = this._config.audioMutedDefault) !== null && _b !== void 0 ? _b : false,
115
- });
116
- // Step5 create local stream
117
- await this._client.createLocalStream();
118
- // step6 set connected and dispatch connected event
119
- this.isConnected = true;
120
- this.dispatch(event_handler_1.EventNames.CONNECTED, {
121
- roomId: roomInfo.room_id,
122
- uid: roomInfo.uid,
123
- token: roomInfo.token,
124
- appId: roomInfo.app_id,
125
- });
126
- this._log('dispatch client.connected event');
127
- }
128
- /**
129
- * en: Interrupt the current conversation
130
- *
131
- * zh: 中断当前对话
132
- */
133
- async interrupt() {
134
- var _a;
135
- await ((_a = this._client) === null || _a === void 0 ? void 0 : _a.stop());
136
- this.dispatch(event_handler_1.EventNames.INTERRUPTED, {});
137
- this._log('dispatch client.interrupted event');
138
- }
139
- /**
140
- * en: Disconnect from the current session
141
- *
142
- * zh: 断开与当前会话的连接
143
- */
144
- async disconnect() {
145
- var _a;
146
- await ((_a = this._client) === null || _a === void 0 ? void 0 : _a.disconnect());
147
- this.isConnected = false;
148
- this.dispatch(event_handler_1.EventNames.DISCONNECTED, {});
149
- }
150
- /**
151
- * en: Send a message to the bot
152
- *
153
- * zh: 发送消息给Bot
154
- */
155
- async sendMessage(message) {
156
- var _a;
157
- await ((_a = this._client) === null || _a === void 0 ? void 0 : _a.sendMessage(message));
158
- const eventType = typeof message.event_type === 'string'
159
- ? message.event_type
160
- : 'unknown_event';
161
- this.dispatch(`client.${eventType}`, message);
162
- }
163
- /**
164
- * en: Enable or disable audio
165
- *
166
- * zh: 启用或禁用音频
167
- */
168
- async setAudioEnable(isEnable) {
169
- var _a;
170
- await ((_a = this._client) === null || _a === void 0 ? void 0 : _a.changeAudioState(isEnable));
171
- if (isEnable) {
172
- this.dispatch(event_handler_1.EventNames.AUDIO_UNMUTED, {});
173
- }
174
- else {
175
- this.dispatch(event_handler_1.EventNames.AUDIO_MUTED, {});
176
- }
177
- }
178
- /**
179
- * en: Enable audio properties reporting (debug mode only)
180
- *
181
- * zh: 启用音频属性报告(仅限调试模式)
182
- */
183
- enableAudioPropertiesReport(config) {
184
- var _a;
185
- if (this._config.debug) {
186
- (_a = this._client) === null || _a === void 0 ? void 0 : _a.enableAudioPropertiesReport(config);
187
- return true;
188
- }
189
- else {
190
- console.warn('enableAudioPropertiesReport is not supported in non-debug mode');
191
- return false;
192
- }
193
- }
194
- /**
195
- * en: Start audio playback device test (debug mode only)
196
- *
197
- * zh: 开始音频播放设备测试(仅限调试模式)
198
- */
199
- async startAudioPlaybackDeviceTest() {
200
- var _a;
201
- if (this._config.debug) {
202
- await ((_a = this._client) === null || _a === void 0 ? void 0 : _a.startAudioPlaybackDeviceTest());
203
- }
204
- else {
205
- console.warn('startAudioPlaybackDeviceTest is not supported in non-debug mode');
206
- }
207
- }
208
- /**
209
- * en: Stop audio playback device test (debug mode only)
210
- *
211
- * zh: 停止音频播放设备测试(仅限调试模式)
212
- */
213
- stopAudioPlaybackDeviceTest() {
214
- var _a;
215
- if (this._config.debug) {
216
- (_a = this._client) === null || _a === void 0 ? void 0 : _a.stopAudioPlaybackDeviceTest();
217
- }
218
- else {
219
- console.warn('stopAudioPlaybackDeviceTest is not supported in non-debug mode');
220
- }
221
- }
222
- }
223
- exports.RealtimeClient = RealtimeClient;