@coze/realtime-api 0.0.3 → 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.
package/dist/index.js DELETED
@@ -1,258 +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
- * @param config.connectorId - Required, Connector Id. |
61
- * 必填,渠道 Id。
62
- * @param config.suppressStationaryNoise - Optional, suppress stationary noise, defaults to false. |
63
- * 可选,默认是否抑制静态噪声,默认值为 false。
64
- * @param config.suppressNonStationaryNoise - Optional, suppress non-stationary noise, defaults to false. |
65
- * 可选,默认是否抑制非静态噪声,默认值为 false。
66
- */
67
- constructor(config) {
68
- var _a;
69
- super(config.debug);
70
- this._client = null;
71
- this._roomInfo = null;
72
- this.isConnected = false;
73
- this._isTestEnv = false;
74
- this._config = config;
75
- const defaultBaseURL = (_a = this._config.baseURL) !== null && _a !== void 0 ? _a : 'https://api.coze.cn';
76
- this._config.baseURL = defaultBaseURL;
77
- // init api
78
- this._api = new api_1.CozeAPI({
79
- token: this._config.accessToken,
80
- baseURL: defaultBaseURL,
81
- allowPersonalAccessTokenInBrowser: this._config.allowPersonalAccessTokenInBrowser,
82
- });
83
- this._isTestEnv = defaultBaseURL !== 'https://api.coze.cn';
84
- }
85
- /**
86
- * en: Establish a connection to the Coze API and join the room
87
- *
88
- * zh: 建立与 Coze API 的连接并加入房间
89
- */
90
- async connect() {
91
- var _a;
92
- const { botId, conversationId, voiceId } = this._config;
93
- let roomInfo;
94
- try {
95
- // Step1 get token
96
- roomInfo = await this._api.audio.rooms.create({
97
- bot_id: botId,
98
- conversation_id: conversationId,
99
- voice_id: voiceId && voiceId.length > 0 ? voiceId : undefined,
100
- connector_id: this._config.connectorId,
101
- });
102
- }
103
- catch (error) {
104
- this.dispatch(event_handler_1.EventNames.ERROR, error);
105
- throw new error_1.RealtimeAPIError(error_1.RealtimeError.CREATE_ROOM_ERROR, error instanceof Error ? error.message : 'Unknown error');
106
- }
107
- this._roomInfo = roomInfo;
108
- // Step2 create engine
109
- this._client = new client_1.EngineClient(roomInfo.app_id, this._config.debug, this._isTestEnv);
110
- // Step3 bind engine events
111
- this._client.bindEngineEvents();
112
- this._client.on(event_handler_1.EventNames.ALL, (eventName, data) => {
113
- this.dispatch(eventName, data);
114
- });
115
- if (this._config.suppressStationaryNoise) {
116
- await this._client.enableAudioNoiseReduction();
117
- this.dispatch(event_handler_1.EventNames.SUPPRESS_STATIONARY_NOISE, {});
118
- }
119
- if (this._config.suppressNonStationaryNoise) {
120
- await this._client.initAIAnsExtension();
121
- this._client.changeAIAnsExtension(true);
122
- this.dispatch(event_handler_1.EventNames.SUPPRESS_NON_STATIONARY_NOISE, {});
123
- }
124
- // Step4 join room
125
- await this._client.joinRoom({
126
- token: roomInfo.token,
127
- roomId: roomInfo.room_id,
128
- uid: roomInfo.uid,
129
- audioMutedDefault: (_a = this._config.audioMutedDefault) !== null && _a !== void 0 ? _a : false,
130
- });
131
- // Step5 create local stream
132
- await this._client.createLocalStream();
133
- // step6 set connected and dispatch connected event
134
- this.isConnected = true;
135
- this.dispatch(event_handler_1.EventNames.CONNECTED, {
136
- roomId: roomInfo.room_id,
137
- uid: roomInfo.uid,
138
- token: roomInfo.token,
139
- appId: roomInfo.app_id,
140
- });
141
- this._log('dispatch client.connected event');
142
- }
143
- /**
144
- * en: Interrupt the current conversation
145
- *
146
- * zh: 中断当前对话
147
- */
148
- async interrupt() {
149
- var _a;
150
- await ((_a = this._client) === null || _a === void 0 ? void 0 : _a.stop());
151
- this.dispatch(event_handler_1.EventNames.INTERRUPTED, {});
152
- this._log('dispatch client.interrupted event');
153
- }
154
- /**
155
- * en: Disconnect from the current session
156
- *
157
- * zh: 断开与当前会话的连接
158
- */
159
- async disconnect() {
160
- var _a;
161
- await ((_a = this._client) === null || _a === void 0 ? void 0 : _a.disconnect());
162
- this.isConnected = false;
163
- this.dispatch(event_handler_1.EventNames.DISCONNECTED, {});
164
- }
165
- /**
166
- * en: Send a message to the bot
167
- *
168
- * zh: 发送消息给Bot
169
- */
170
- async sendMessage(message) {
171
- var _a;
172
- await ((_a = this._client) === null || _a === void 0 ? void 0 : _a.sendMessage(message));
173
- const eventType = typeof message.event_type === 'string'
174
- ? message.event_type
175
- : 'unknown_event';
176
- this.dispatch(`client.${eventType}`, message);
177
- }
178
- /**
179
- * en: Enable or disable audio
180
- *
181
- * zh: 启用或禁用音频
182
- */
183
- async setAudioEnable(isEnable) {
184
- var _a;
185
- await ((_a = this._client) === null || _a === void 0 ? void 0 : _a.changeAudioState(isEnable));
186
- if (isEnable) {
187
- this.dispatch(event_handler_1.EventNames.AUDIO_UNMUTED, {});
188
- }
189
- else {
190
- this.dispatch(event_handler_1.EventNames.AUDIO_MUTED, {});
191
- }
192
- }
193
- /**
194
- * en: Enable audio properties reporting (debug mode only)
195
- *
196
- * zh: 启用音频属性报告(仅限调试模式)
197
- */
198
- enableAudioPropertiesReport(config) {
199
- var _a;
200
- if (this._config.debug) {
201
- (_a = this._client) === null || _a === void 0 ? void 0 : _a.enableAudioPropertiesReport(config);
202
- return true;
203
- }
204
- else {
205
- console.warn('enableAudioPropertiesReport is not supported in non-debug mode');
206
- return false;
207
- }
208
- }
209
- /**
210
- * en: Start audio playback device test (debug mode only)
211
- *
212
- * zh: 开始音频播放设备测试(仅限调试模式)
213
- */
214
- async startAudioPlaybackDeviceTest() {
215
- var _a;
216
- if (this._config.debug) {
217
- await ((_a = this._client) === null || _a === void 0 ? void 0 : _a.startAudioPlaybackDeviceTest());
218
- }
219
- else {
220
- console.warn('startAudioPlaybackDeviceTest is not supported in non-debug mode');
221
- }
222
- }
223
- /**
224
- * en: Stop audio playback device test (debug mode only)
225
- *
226
- * zh: 停止音频播放设备测试(仅限调试模式)
227
- */
228
- stopAudioPlaybackDeviceTest() {
229
- var _a;
230
- if (this._config.debug) {
231
- (_a = this._client) === null || _a === void 0 ? void 0 : _a.stopAudioPlaybackDeviceTest();
232
- }
233
- else {
234
- console.warn('stopAudioPlaybackDeviceTest is not supported in non-debug mode');
235
- }
236
- }
237
- /**
238
- * en: Set the audio input device
239
- *
240
- * zh: 设置音频输入设备
241
- */
242
- async setAudioInputDevice(deviceId) {
243
- var _a;
244
- await ((_a = this._client) === null || _a === void 0 ? void 0 : _a.setAudioInputDevice(deviceId));
245
- this.dispatch(event_handler_1.EventNames.AUDIO_INPUT_DEVICE_CHANGED, { deviceId });
246
- }
247
- /**
248
- * en: Set the audio output device
249
- *
250
- * zh: 设置音频输出设备
251
- */
252
- async setAudioOutputDevice(deviceId) {
253
- var _a;
254
- await ((_a = this._client) === null || _a === void 0 ? void 0 : _a.setAudioOutputDevice(deviceId));
255
- this.dispatch(event_handler_1.EventNames.AUDIO_OUTPUT_DEVICE_CHANGED, { deviceId });
256
- }
257
- }
258
- exports.RealtimeClient = RealtimeClient;
package/dist/utils.js DELETED
@@ -1,40 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.getAudioDevices = exports.checkPermission = exports.sleep = void 0;
7
- const rtc_1 = __importDefault(require("@volcengine/rtc"));
8
- /**
9
- + * Delays execution for the specified duration
10
- + * @param milliseconds The time to sleep in milliseconds
11
- + * @throws {Error} If milliseconds is negative
12
- + * @returns Promise that resolves after the specified duration
13
- + */
14
- const sleep = (milliseconds) => {
15
- if (milliseconds < 0) {
16
- throw new Error('Sleep duration must be non-negative');
17
- }
18
- return new Promise(resolve => setTimeout(resolve, milliseconds));
19
- };
20
- exports.sleep = sleep;
21
- /**
22
- * Check microphone permission,return boolean
23
- */
24
- const checkPermission = async () => (await rtc_1.default.enableDevices({ audio: true, video: false })).audio;
25
- exports.checkPermission = checkPermission;
26
- /**
27
- * Get audio devices
28
- * @returns Promise<AudioDevices> Object containing arrays of audio input and output devices
29
- */
30
- const getAudioDevices = async () => {
31
- const devices = await rtc_1.default.enumerateDevices();
32
- if (!(devices === null || devices === void 0 ? void 0 : devices.length)) {
33
- return { audioInputs: [], audioOutputs: [] };
34
- }
35
- return {
36
- audioInputs: devices.filter(i => i.deviceId && i.kind === 'audioinput'),
37
- audioOutputs: devices.filter(i => i.deviceId && i.kind === 'audiooutput'),
38
- };
39
- };
40
- exports.getAudioDevices = getAudioDevices;
File without changes
File without changes
File without changes
File without changes