@relaxwork/verto 0.0.0-stage → 1.0.0

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/README.md CHANGED
@@ -1,3 +1,188 @@
1
- # Temporary Holding Version
1
+ # @relax/verto
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 一个符合 FreeSWITCH Verto JSON-RPC 规范的 TypeScript 客户端。它提供浏览器原生 WebSocket 和 WebRTC 的封装,但不绑定 React、Vue、Svelte 或任何 UI 框架,适合在组件、状态管理器和原生页面中复用。
4
+
5
+ 当前包是纯 ESM,构建产物包含 JavaScript 和 TypeScript 声明文件。
6
+
7
+ ## 安装
8
+
9
+ ```bash
10
+ pnpm add @relax/verto
11
+ ```
12
+
13
+ ## 环境要求
14
+
15
+ - 浏览器需要支持 WebSocket、RTCPeerConnection 和 MediaStreamTrack。
16
+ - 应用需要从 HTTPS 或 localhost 获取麦克风/摄像头权限。
17
+ - SSR、Node 测试和自定义 WebSocket 环境必须通过 transportConfig.socketFactory 注入 WebSocket。
18
+ - 非浏览器环境必须通过 peerConnectionFactory 注入 RTCPeerConnection。
19
+
20
+ 库不会主动调用 getUserMedia。应用应先获取本地媒体轨道,再通过 call 的 tracks 参数或 VertoCall.addTrack 传入。
21
+
22
+ ## 最小示例
23
+
24
+ ```ts
25
+ import { Verto } from 'verto';
26
+
27
+ const localStream = await navigator.mediaDevices.getUserMedia({
28
+ audio: true,
29
+ video: true,
30
+ });
31
+
32
+ const verto = new Verto({
33
+ transportConfig: {
34
+ socketUrl: 'wss://pbx.example.com:8082',
35
+ login: '1000@example.com',
36
+ passwd: 'secret',
37
+ },
38
+ rtcConfig: {
39
+ iceServers: [{ urls: 'stun:stun.l.google.com:19302' }],
40
+ },
41
+ });
42
+
43
+ verto.on('error', (error) => console.error('Verto error', error));
44
+ verto.on('invite', (call) => {
45
+ call.on('track', (track) => {
46
+ const remoteAudio = document.querySelector('#remote-audio');
47
+ if (remoteAudio instanceof HTMLAudioElement) {
48
+ const stream =
49
+ remoteAudio.srcObject instanceof MediaStream
50
+ ? remoteAudio.srcObject
51
+ : new MediaStream();
52
+ stream.addTrack(track);
53
+ remoteAudio.srcObject = stream;
54
+ void remoteAudio.play();
55
+ }
56
+ });
57
+
58
+ // 业务确认接听后应调用 answer。
59
+ void call.answer(localStream.getTracks());
60
+ });
61
+
62
+ await verto.login();
63
+
64
+ const call = verto.call(localStream.getTracks(), '1001', {
65
+ caller_id_name: 'Web client',
66
+ caller_id_number: '1000',
67
+ });
68
+
69
+ call.on('track', (track) => {
70
+ // 将远端轨道绑定到 audio/video 元素。
71
+ console.log('remote track', track.kind);
72
+ });
73
+
74
+ call.on('bye', () => {
75
+ console.log('call ended');
76
+ });
77
+ ```
78
+
79
+ ## API
80
+
81
+ ### Verto
82
+
83
+ Verto 是应用使用的顶层客户端。
84
+
85
+ - login(): Promise<Record<string, unknown>> 建立登录会话。
86
+ - call(tracks, destination, options?): VertoCall 发起呼叫。
87
+ - getCall(id): VertoCall | undefined 获取指定会话。
88
+ - activeCalls: readonly VertoCall[] 获取当前会话快照。
89
+ - isLogged(): boolean 判断是否已经登录。
90
+ - sessionId: string | undefined 获取 FreeSWITCH 返回的 sessid。
91
+ - logout(): void 结束会话并关闭 WebSocket。
92
+ - destroy(): void 释放会话和所有监听器。
93
+
94
+ Verto 事件:
95
+
96
+ - invite: 收到来电时触发,参数为 VertoCall。
97
+ - message: 收到任意 Verto JSON-RPC 通知时触发,参数为 { method, params }。
98
+ - error: 传输或会话发生错误时触发。
99
+
100
+ ### VertoCall
101
+
102
+ - onAnswer(sdp?): Promise<void> 和 onMedia(sdp?): Promise<void> 处理远端 SDP。
103
+ - answer(tracks?): Promise<void> 接听来电并发送 verto.answer。
104
+ - hangup(params?): Promise<void> 挂断并发送 verto.bye。
105
+ - addTrack(track): RTCRtpSender 添加本地媒体轨道。
106
+ - getStats(): Promise<RTCStatsReport> 获取 WebRTC 统计信息。
107
+ - dtmf(input): Promise<unknown> 发送 DTMF。
108
+ - hold(params?), unhold(params?), toggleHold(params?) 处理保持/恢复。
109
+ - clear(): void 本地关闭会话。
110
+
111
+ VertoCall 事件:
112
+
113
+ - track: 收到远端 MediaStreamTrack。
114
+ - answer: 远端回答处理完成。
115
+ - media: 收到远端媒体协商消息。
116
+ - bye: 会话结束。
117
+ - hold / unhold: 保持状态变化。
118
+ - error: 会话或 WebRTC 错误。
119
+
120
+ ### 事件订阅
121
+
122
+ 所有主要对象都继承 VertoBase,提供以下方法:
123
+
124
+ ```ts
125
+ const id = verto.on('error', handler);
126
+ verto.off('error', id);
127
+ // 也可以使用 subscribeEvent / unsubscribeEvent。
128
+ ```
129
+
130
+ 订阅返回稳定 ID,组件卸载时应调用 off 或 unsubscribeEvent,避免重复监听。
131
+
132
+ ### JSON-RPC 传输
133
+
134
+ JsonRpcClient 是公开导出的底层 JSON-RPC 2.0 客户端,可用于需要直接调用 FreeSWITCH 方法的场景。
135
+
136
+ ```ts
137
+ const result = await client.call('some.method', { key: 'value' });
138
+ ```
139
+
140
+ 客户端会在连接建立前排队请求,连接异常时自动指数退避重连,并在认证错误 -32000 时使用 transportConfig 中的 login/passwd 自动登录后重试原请求。设置 reconnect: false 可关闭自动重连。
141
+
142
+ Node 或 SSR 示例:
143
+
144
+ ```ts
145
+ const verto = new Verto({
146
+ transportConfig: {
147
+ socketUrl: 'wss://pbx.example.com:8082',
148
+ socketFactory: (url) => new MyWebSocket(url),
149
+ },
150
+ peerConnectionFactory: (config) => new MyPeerConnection(config),
151
+ });
152
+ ```
153
+
154
+ ## React、Vue、Svelte 接入建议
155
+
156
+ 库本身不管理组件状态。建议在组件挂载时创建或接收 Verto 实例,保存订阅 ID,在卸载时移除监听:
157
+
158
+ ```ts
159
+ const subscriptionId = call.on('track', setRemoteTrack);
160
+ // cleanup
161
+ call.off('track', subscriptionId);
162
+ ```
163
+
164
+ 远端音视频元素的渲染、通话按钮和状态管理由 UI 层决定;VertoCall 只提供协议状态和媒体轨道事件。
165
+
166
+ ## FreeSWITCH 侧配置
167
+
168
+ 请确保 FreeSWITCH 已启用 mod_verto,并在 WSS 端口、证书、用户认证和 ICE/STUN/TURN 配置上与前端环境匹配。Verto JSON-RPC 方法名和 dialogParams 由库按协议发送,业务侧只需提供目标号码、认证信息和媒体轨道。
169
+
170
+ ## 示例
171
+
172
+ demo为 react 接入示例
173
+
174
+ ## 本地开发
175
+
176
+ ```bash
177
+ pnpm install
178
+ pnpm run build
179
+ pnpm run lint
180
+ pnpm run test
181
+ ```
182
+
183
+ watch 模式:
184
+
185
+ ```bash
186
+ pnpm run dev
187
+ pnpm run test:watch
188
+ ```
package/dist/base.d.ts ADDED
@@ -0,0 +1,68 @@
1
+ /** Verto 对象事件监听器。 */
2
+ export type EventListener<T> = (data: T) => void;
3
+ type EventName<Events extends object> = Extract<keyof Events, string>;
4
+ /**
5
+ * Creates a UUID without importing a Node-only module.
6
+ *
7
+ * Verto is commonly used from browser bundles and from SSR applications, so
8
+ * the implementation only reads globalThis.crypto when it is available.
9
+ */
10
+ export declare function generateGUID(): string;
11
+ /**
12
+ * Small framework-neutral event emitter used by the RPC, RTC and call layers.
13
+ *
14
+ * Subscriptions return an ID, which makes cleanup straightforward in React,
15
+ * Vue, Svelte and plain DOM applications alike.
16
+ */
17
+ export declare class VertoBase<Events extends object = Record<string, unknown>> {
18
+ private readonly eventHandlers;
19
+ readonly debug: boolean;
20
+ /**
21
+ * 创建一个可订阅事件的基础对象。
22
+ *
23
+ * @param debug 是否输出事件调试日志。
24
+ */
25
+ constructor(debug?: boolean);
26
+ /**
27
+ * 订阅事件。
28
+ *
29
+ * @param name 事件名称,具体可用事件由对象的事件类型决定。
30
+ * @param handler 事件回调,参数类型与事件对应。
31
+ * @returns 订阅 ID,调用 unsubscribeEvent 或 off 时使用。
32
+ */
33
+ subscribeEvent<Name extends EventName<Events>>(name: Name, handler: EventListener<Events[Name]>): string;
34
+ /**
35
+ * 订阅事件的简写形式。
36
+ *
37
+ * @param name 事件名称。
38
+ * @param handler 事件回调。
39
+ * @returns 订阅 ID。
40
+ */
41
+ on<Name extends EventName<Events>>(name: Name, handler: EventListener<Events[Name]>): string;
42
+ /**
43
+ * 移除事件订阅。
44
+ *
45
+ * @param name 事件名称。
46
+ * @param handlerId 要移除的订阅 ID;省略时移除该事件的全部订阅。
47
+ */
48
+ unsubscribeEvent<Name extends EventName<Events>>(name: Name, handlerId?: string): void;
49
+ /**
50
+ * 移除事件订阅的简写形式。
51
+ *
52
+ * @param name 事件名称。
53
+ * @param handlerId 要移除的订阅 ID;省略时移除该事件的全部订阅。
54
+ */
55
+ off<Name extends EventName<Events>>(name: Name, handlerId?: string): void;
56
+ /**
57
+ * 向当前对象派发事件。
58
+ *
59
+ * 此方法主要供库内部使用;应用层通常应使用 on 或 subscribeEvent。
60
+ *
61
+ * @param name 事件名称。
62
+ * @param data 事件载荷。
63
+ */
64
+ dispatchEvent<Name extends EventName<Events>>(name: Name, data: Events[Name]): void;
65
+ /** 移除当前对象注册的全部事件监听器。 */
66
+ removeAllListeners(): void;
67
+ }
68
+ export {};
@@ -0,0 +1,239 @@
1
+ import { VertoBase } from './base.js';
2
+ import { JsonRpcClient, type JsonRpcClientParams, type JsonRpcParams } from './json-rpc.js';
3
+ import { CallDirection } from './rtc.js';
4
+ export { generateGUID, VertoBase } from './base.js';
5
+ export { JsonRpcClient, JsonRpcError, type JsonRpcClientParams, type JsonRpcParams, type JsonRpcRequest, type WebSocketFactory, type WebSocketLike, } from './json-rpc.js';
6
+ export { CallDirection, VertoRtc, type VertoRtcEvents, type VertoRtcOptions } from './rtc.js';
7
+ /** FreeSWITCH Verto JSON-RPC 方法名常量。 */
8
+ export declare const VertoMessage: {
9
+ readonly Invite: 'verto.invite';
10
+ readonly Answer: 'verto.answer';
11
+ readonly Bye: 'verto.bye';
12
+ readonly Media: 'verto.media';
13
+ readonly Attach: 'verto.attach';
14
+ readonly Modify: 'verto.modify';
15
+ readonly Subscribe: 'verto.subscribe';
16
+ readonly Unsubscribe: 'verto.unsubscribe';
17
+ readonly Info: 'verto.info';
18
+ readonly Display: 'verto.display';
19
+ readonly ClientReady: 'verto.clientReady';
20
+ readonly Broadcast: 'verto.broadcast';
21
+ };
22
+ export interface VertoCallOptions extends Record<string, unknown> {
23
+ /** 发起方号码,通常显示在对端来电信息中。 */
24
+ caller_id_number?: string;
25
+ /** 发起方显示名称。 */
26
+ caller_id_name?: string;
27
+ /** 被叫号码的显示值;实际呼叫目标由 call 的 destination 参数决定。 */
28
+ callee_id_number?: string;
29
+ /** 被叫方显示名称。 */
30
+ callee_id_name?: string;
31
+ }
32
+ /** 创建 Verto 客户端时使用的配置。 */
33
+ export interface VertoOptions {
34
+ /** Verto WebSocket 地址、认证信息和 JSON-RPC 传输选项。 */
35
+ transportConfig: JsonRpcClientParams;
36
+ /** RTCPeerConnection 配置,例如 FreeSWITCH 部署所需的 STUN/TURN servers。 */
37
+ rtcConfig?: RTCConfiguration;
38
+ /** 是否输出调试日志,默认 false。 */
39
+ debug?: boolean;
40
+ /** 等待 ICE 收集完成的时间,单位为毫秒,默认 3000。 */
41
+ iceTimeout?: number;
42
+ /** iceTimeout 的旧版拼写,供旧项目兼容。 */
43
+ ice_timeout?: number;
44
+ /** 自定义 PeerConnection 工厂,适用于 SSR、Node 或测试环境。 */
45
+ peerConnectionFactory?: (configuration: RTCConfiguration) => RTCPeerConnection;
46
+ }
47
+ /** VertoCall 可订阅的事件及其回调参数。 */
48
+ export interface VertoCallEvents {
49
+ /** 收到远端音频或视频轨道。 */
50
+ track: MediaStreamTrack;
51
+ /** 收到并应用远端 answer 后触发,无事件数据。 */
52
+ answer: undefined;
53
+ /** 收到并应用远端媒体 SDP 后触发,无事件数据。 */
54
+ media: undefined;
55
+ /** 会话被本地或远端清理时触发,参数为当前会话。 */
56
+ bye: VertoCall;
57
+ /** FreeSWITCH 确认呼叫进入 held 状态时触发。 */
58
+ hold: VertoCall;
59
+ /** FreeSWITCH 确认呼叫离开 held 状态时触发。 */
60
+ unhold: VertoCall;
61
+ /** 会话信令或 WebRTC 操作失败时触发。 */
62
+ error: Error;
63
+ }
64
+ /** Verto 客户端可订阅的事件及其回调参数。 */
65
+ export interface VertoEvents {
66
+ /** 收到来电邀请时触发,参数为可接听的 VertoCall。 */
67
+ invite: VertoCall;
68
+ /** 收到任意服务端 Verto 通知时触发。 */
69
+ message: {
70
+ method: string;
71
+ params: JsonRpcParams;
72
+ };
73
+ /** 客户端发生错误时触发。 */
74
+ error: Error;
75
+ }
76
+ /** FreeSWITCH 保持状态修改响应。 */
77
+ export interface HoldResponse {
78
+ /** 当前保持状态,held 表示已保持。 */
79
+ holdState?: string;
80
+ }
81
+ /** 表示一个 Verto dialog 及其关联的 WebRTC 媒体会话。 */
82
+ export declare class VertoCall extends VertoBase<VertoCallEvents> {
83
+ private readonly rtc;
84
+ private readonly rpc;
85
+ private cleared;
86
+ /** FreeSWITCH 为该 dialog 分配或客户端生成的唯一 ID。 */
87
+ readonly id: string;
88
+ /** 创建呼叫时附加的 caller/callee 信息。 */
89
+ readonly options: VertoCallOptions;
90
+ /** 当前会话是来电还是去电。 */
91
+ readonly direction: CallDirection;
92
+ /** 最近一次 hold 操作确认后的保持状态。 */
93
+ holdStatus: boolean;
94
+ /**
95
+ * 创建 VertoCall。通常由 Verto.call() 或收到 invite 事件时创建。
96
+ *
97
+ * @param configuration RTCPeerConnection 配置。
98
+ * @param rpc 与 FreeSWITCH 通信的 JSON-RPC 客户端。
99
+ * @param destination 去电目标号码;省略时按来电处理。
100
+ * @param id dialog ID;省略时自动生成 UUID。
101
+ * @param options 呼叫显示信息及需要附加到 dialogParams 的字段。
102
+ * @param iceTimeout ICE gathering 等待时间,单位为毫秒。
103
+ * @param debug 是否输出调试日志。
104
+ * @param peerConnectionFactory 可选的 RTCPeerConnection 工厂。
105
+ */
106
+ constructor(configuration: RTCConfiguration | undefined, rpc: JsonRpcClient, destination?: string, id?: string, options?: VertoCallOptions, iceTimeout?: number, debug?: boolean, peerConnectionFactory?: (configuration: RTCConfiguration) => RTCPeerConnection);
107
+ private sendSdp;
108
+ /**
109
+ * 获取当前 PeerConnection 的统计信息。
110
+ *
111
+ * @returns 浏览器提供的 WebRTC 统计报告。
112
+ */
113
+ getStats(): Promise<RTCStatsReport>;
114
+ /**
115
+ * 接收并应用 FreeSWITCH 返回的 answer SDP。
116
+ *
117
+ * @param sdp 远端 answer SDP;不传时只派发 answer 事件。
118
+ */
119
+ onAnswer(sdp?: string): Promise<void>;
120
+ /**
121
+ * 接收并应用新的远端媒体 SDP。
122
+ *
123
+ * @param sdp 远端 answer SDP。
124
+ */
125
+ onMedia(sdp?: string): Promise<void>;
126
+ /**
127
+ * 向当前会话添加一条本地媒体轨道。
128
+ *
129
+ * @param track 由 getUserMedia 等方式获取的音频或视频轨道。
130
+ * @returns 对应的 RTCRtpSender。
131
+ */
132
+ addTrack(track: MediaStreamTrack): RTCRtpSender;
133
+ /**
134
+ * 暂存来电 offer;Verto 客户端收到 verto.invite 时会自动调用。
135
+ *
136
+ * @param sdp FreeSWITCH 推送的 offer SDP。
137
+ */
138
+ preSdp(sdp: string): void;
139
+ /**
140
+ * 接听来电并发送 Verto answer。
141
+ *
142
+ * @param tracks 接听时发送到对端的本地媒体轨道,可传空数组接听纯音频/无本地媒体会话。
143
+ * @returns SDP 协商及发送流程完成后的 Promise。
144
+ */
145
+ answer(tracks?: readonly MediaStreamTrack[]): Promise<void>;
146
+ /**
147
+ * 向 FreeSWITCH 发送挂断请求并清理本地 PeerConnection。
148
+ *
149
+ * @param params 附加到 verto.bye 请求的顶层参数。
150
+ */
151
+ hangup(params?: JsonRpcParams): Promise<void>;
152
+ /** 仅在本地清理会话,不向 FreeSWITCH 发送 verto.bye。 */
153
+ clear(): void;
154
+ /**
155
+ * 发送 DTMF 按键。
156
+ *
157
+ * @param input 要发送的按键,例如 0-9、* 或 #。
158
+ * @returns FreeSWITCH 的 JSON-RPC 响应。
159
+ */
160
+ dtmf(input: string | number): Promise<unknown>;
161
+ /**
162
+ * 请求将当前呼叫置为保持状态。
163
+ *
164
+ * @param params 附加到 dialogParams 的 FreeSWITCH 专属参数。
165
+ */
166
+ hold(params?: JsonRpcParams): Promise<HoldResponse>;
167
+ /**
168
+ * 请求恢复当前已保持的呼叫。
169
+ *
170
+ * @param params 附加到 dialogParams 的 FreeSWITCH 专属参数。
171
+ */
172
+ unhold(params?: JsonRpcParams): Promise<HoldResponse>;
173
+ /**
174
+ * 请求切换当前呼叫的保持状态。
175
+ *
176
+ * @param params 附加到 dialogParams 的 FreeSWITCH 专属参数。
177
+ */
178
+ toggleHold(params?: JsonRpcParams): Promise<HoldResponse>;
179
+ private modifyHold;
180
+ }
181
+ /** 与 UI 框架无关的 FreeSWITCH Verto 客户端。 */
182
+ export declare class Verto extends VertoBase<VertoEvents> {
183
+ private readonly calls;
184
+ private readonly rpc;
185
+ private readonly options;
186
+ private loggedIn;
187
+ private currentSessionId?;
188
+ /**
189
+ * 创建 Verto 客户端。
190
+ *
191
+ * 构造时不会立即打开 WebSocket;首次 login 或 JSON-RPC 请求时才连接。
192
+ *
193
+ * @param options WebSocket 登录、WebRTC 和调试配置。
194
+ */
195
+ constructor(options: VertoOptions);
196
+ private handleMessage;
197
+ /**
198
+ * 登录 FreeSWITCH Verto 会话。
199
+ *
200
+ * @returns 服务端登录响应;成功后 isLogged() 返回 true。
201
+ * @throws 连接或认证失败时 Promise reject。
202
+ */
203
+ login(): Promise<Record<string, unknown>>;
204
+ /**
205
+ * 创建并登记一个去电会话。
206
+ *
207
+ * @param tracks 本次呼叫发送的本地媒体轨道,通常来自 getUserMedia。
208
+ * @param destination FreeSWITCH 可路由的目标号码或用户标识。
209
+ * @param options caller/callee 显示信息及附加 dialogParams。
210
+ * @returns 新建的会话;通过 track、bye、error 等事件监听状态变化。
211
+ *
212
+ * @example
213
+ * const call = verto.call(stream.getTracks(), '1001');
214
+ * call.on('track', (track) => attachRemoteTrack(track));
215
+ */
216
+ call(tracks: readonly MediaStreamTrack[], destination: string, options?: VertoCallOptions): VertoCall;
217
+ private registerCall;
218
+ /**
219
+ * 获取指定 dialog 的会话对象。
220
+ *
221
+ * @param id VertoCall.id。
222
+ * @returns 活动会话;不存在或已结束时返回 undefined。
223
+ */
224
+ getCall(id: string): VertoCall | undefined;
225
+ /** 返回活动会话数组的只读快照。 */
226
+ get activeCalls(): readonly VertoCall[];
227
+ /** 当前客户端是否已成功登录。 */
228
+ isLogged(): boolean;
229
+ /** 最近一次登录响应中的 sessid;服务端未返回时为 undefined。 */
230
+ get sessionId(): string | undefined;
231
+ /**
232
+ * 挂断所有活动会话并关闭 WebSocket。
233
+ *
234
+ * 关闭后的客户端不可再次登录;需要重新连接时请创建新的 Verto 实例。
235
+ */
236
+ logout(): void;
237
+ /** 释放客户端拥有的会话、传输和事件监听器。 */
238
+ destroy(): void;
239
+ }