@telnyx/react-voice-commons-sdk 0.1.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.
Files changed (73) hide show
  1. package/TelnyxVoiceCommons.podspec +32 -0
  2. package/ios/CallKitBridge.m +44 -0
  3. package/ios/CallKitBridge.swift +879 -0
  4. package/ios/README.md +211 -0
  5. package/ios/VoicePnBridge.m +31 -0
  6. package/ios/VoicePnBridge.swift +87 -0
  7. package/lib/callkit/callkit-coordinator.d.ts +126 -0
  8. package/lib/callkit/callkit-coordinator.js +728 -0
  9. package/lib/callkit/callkit.d.ts +49 -0
  10. package/lib/callkit/callkit.js +262 -0
  11. package/lib/callkit/index.d.ts +4 -0
  12. package/lib/callkit/index.js +15 -0
  13. package/lib/callkit/use-callkit-coordinator.d.ts +21 -0
  14. package/lib/callkit/use-callkit-coordinator.js +53 -0
  15. package/lib/callkit/use-callkit.d.ts +28 -0
  16. package/lib/callkit/use-callkit.js +279 -0
  17. package/lib/context/TelnyxVoiceContext.d.ts +18 -0
  18. package/lib/context/TelnyxVoiceContext.js +18 -0
  19. package/lib/hooks/use-callkit-coordinator.d.ts +13 -0
  20. package/lib/hooks/use-callkit-coordinator.js +48 -0
  21. package/lib/hooks/useAppReadyNotifier.d.ts +9 -0
  22. package/lib/hooks/useAppReadyNotifier.js +25 -0
  23. package/lib/hooks/useAppStateHandler.d.ts +16 -0
  24. package/lib/hooks/useAppStateHandler.js +105 -0
  25. package/lib/index.d.ts +24 -0
  26. package/lib/index.js +66 -0
  27. package/lib/internal/CallKitHandler.d.ts +17 -0
  28. package/lib/internal/CallKitHandler.js +110 -0
  29. package/lib/internal/callkit-manager.d.ts +69 -0
  30. package/lib/internal/callkit-manager.js +326 -0
  31. package/lib/internal/calls/call-state-controller.d.ts +92 -0
  32. package/lib/internal/calls/call-state-controller.js +294 -0
  33. package/lib/internal/session/session-manager.d.ts +87 -0
  34. package/lib/internal/session/session-manager.js +385 -0
  35. package/lib/internal/user-defaults-helpers.d.ts +10 -0
  36. package/lib/internal/user-defaults-helpers.js +69 -0
  37. package/lib/internal/voice-pn-bridge.d.ts +14 -0
  38. package/lib/internal/voice-pn-bridge.js +5 -0
  39. package/lib/models/call-state.d.ts +61 -0
  40. package/lib/models/call-state.js +87 -0
  41. package/lib/models/call.d.ts +145 -0
  42. package/lib/models/call.js +372 -0
  43. package/lib/models/config.d.ts +64 -0
  44. package/lib/models/config.js +92 -0
  45. package/lib/models/connection-state.d.ts +34 -0
  46. package/lib/models/connection-state.js +50 -0
  47. package/lib/telnyx-voice-app.d.ts +48 -0
  48. package/lib/telnyx-voice-app.js +486 -0
  49. package/lib/telnyx-voip-client.d.ts +184 -0
  50. package/lib/telnyx-voip-client.js +386 -0
  51. package/package.json +104 -0
  52. package/src/callkit/callkit-coordinator.ts +846 -0
  53. package/src/callkit/callkit.ts +322 -0
  54. package/src/callkit/index.ts +4 -0
  55. package/src/callkit/use-callkit.ts +345 -0
  56. package/src/context/TelnyxVoiceContext.tsx +33 -0
  57. package/src/hooks/use-callkit-coordinator.ts +60 -0
  58. package/src/hooks/useAppReadyNotifier.ts +25 -0
  59. package/src/hooks/useAppStateHandler.ts +134 -0
  60. package/src/index.ts +56 -0
  61. package/src/internal/CallKitHandler.tsx +149 -0
  62. package/src/internal/callkit-manager.ts +335 -0
  63. package/src/internal/calls/call-state-controller.ts +384 -0
  64. package/src/internal/session/session-manager.ts +467 -0
  65. package/src/internal/user-defaults-helpers.ts +58 -0
  66. package/src/internal/voice-pn-bridge.ts +18 -0
  67. package/src/models/call-state.ts +98 -0
  68. package/src/models/call.ts +388 -0
  69. package/src/models/config.ts +125 -0
  70. package/src/models/connection-state.ts +50 -0
  71. package/src/telnyx-voice-app.tsx +690 -0
  72. package/src/telnyx-voip-client.ts +475 -0
  73. package/src/types/telnyx-sdk.d.ts +79 -0
@@ -0,0 +1,384 @@
1
+ import { BehaviorSubject, Observable } from 'rxjs';
2
+ import { distinctUntilChanged, map } from 'rxjs/operators';
3
+ import { TelnyxRTC, Call as TelnyxCall, type CallOptions } from '@telnyx/react-native-voice-sdk';
4
+ import { Call } from '../../models/call';
5
+ import { TelnyxCallState } from '../../models/call-state';
6
+ import { SessionManager } from '../session/session-manager';
7
+ import { callKitCoordinator } from '../../callkit/callkit-coordinator';
8
+
9
+ /**
10
+ * Central state machine for call management.
11
+ *
12
+ * This class manages all active calls, handles call state transitions,
13
+ * and provides reactive streams for call-related state changes.
14
+ */
15
+ export class CallStateController {
16
+ private readonly _calls = new BehaviorSubject<Call[]>([]);
17
+ private readonly _callMap = new Map<string, Call>();
18
+ private _disposed = false;
19
+
20
+ // Callbacks for waiting for invite logic (used for push notifications)
21
+ private _isWaitingForInvite?: () => boolean;
22
+ private _onInviteAutoAccepted?: () => void;
23
+
24
+ constructor(private readonly _sessionManager: SessionManager) {
25
+ // Don't set up client listeners here - client doesn't exist yet
26
+ // Will be called when client is available
27
+ }
28
+
29
+ /**
30
+ * Observable stream of all current calls
31
+ */
32
+ get calls$(): Observable<Call[]> {
33
+ return this._calls.asObservable().pipe(distinctUntilChanged());
34
+ }
35
+
36
+ /**
37
+ * Observable stream of the currently active call
38
+ */
39
+ get activeCall$(): Observable<Call | null> {
40
+ return this.calls$.pipe(
41
+ map((calls) => {
42
+ // Find the first call that is not terminated (includes RINGING, CONNECTING, ACTIVE, HELD)
43
+ return (
44
+ calls.find(
45
+ (call) =>
46
+ call.currentState === TelnyxCallState.RINGING ||
47
+ call.currentState === TelnyxCallState.CONNECTING ||
48
+ call.currentState === TelnyxCallState.ACTIVE ||
49
+ call.currentState === TelnyxCallState.HELD
50
+ ) || null
51
+ );
52
+ }),
53
+ distinctUntilChanged()
54
+ );
55
+ }
56
+
57
+ /**
58
+ * Current list of calls (synchronous access)
59
+ */
60
+ get currentCalls(): Call[] {
61
+ return this._calls.value;
62
+ }
63
+
64
+ /**
65
+ * Current active call (synchronous access)
66
+ */
67
+ get currentActiveCall(): Call | null {
68
+ const calls = this.currentCalls;
69
+ return (
70
+ calls.find(
71
+ (call) =>
72
+ call.currentState === TelnyxCallState.RINGING ||
73
+ call.currentState === TelnyxCallState.CONNECTING ||
74
+ call.currentState === TelnyxCallState.ACTIVE ||
75
+ call.currentState === TelnyxCallState.HELD
76
+ ) || null
77
+ );
78
+ }
79
+
80
+ /**
81
+ * Set a call to connecting state (used for push notification calls when answered via CallKit)
82
+ * @param callId The ID of the call to set to connecting state
83
+ */
84
+ setCallConnecting(callId: string): void {
85
+ const call = this._callMap.get(callId);
86
+ if (call) {
87
+ console.log('CallStateController: Setting call to connecting state:', callId);
88
+ call.setConnecting();
89
+ } else {
90
+ console.warn('CallStateController: Could not find call to set connecting:', callId);
91
+ }
92
+ }
93
+
94
+ /**
95
+ * Find a call by its underlying Telnyx call ID
96
+ * @param telnyxCall The Telnyx call object to find
97
+ */
98
+ findCallByTelnyxCall(telnyxCall: any): Call | null {
99
+ for (const call of this._callMap.values()) {
100
+ if (call.telnyxCall === telnyxCall || call.telnyxCall.callId === telnyxCall.callId) {
101
+ return call;
102
+ }
103
+ }
104
+ return null;
105
+ }
106
+
107
+ /**
108
+ * Initialize client listeners when the Telnyx client becomes available
109
+ * This should be called by the session manager after client creation
110
+ */
111
+ initializeClientListeners(): void {
112
+ console.log('🔧 CallStateController: initializeClientListeners called');
113
+ this._setupClientListeners();
114
+
115
+ // CallKit integration now handled by CallKitCoordinator
116
+ console.log('🔧 CallStateController: Using CallKitCoordinator for CallKit integration');
117
+ }
118
+
119
+ /**
120
+ * Initiate a new outgoing call
121
+ */
122
+ async newCall(
123
+ destination: string,
124
+ callerName?: string,
125
+ callerNumber?: string,
126
+ debug: boolean = false
127
+ ): Promise<Call> {
128
+ if (this._disposed) {
129
+ throw new Error('CallStateController has been disposed');
130
+ }
131
+
132
+ if (!this._sessionManager.telnyxClient) {
133
+ throw new Error('Telnyx client not available');
134
+ }
135
+
136
+ try {
137
+ // Create the call using the Telnyx SDK
138
+ const callOptions: CallOptions = {
139
+ destinationNumber: destination,
140
+ callerIdName: callerName,
141
+ callerIdNumber: callerNumber,
142
+ };
143
+ const telnyxCall = await this._sessionManager.telnyxClient.newCall(callOptions);
144
+
145
+ // Create our wrapper Call object
146
+ const call = new Call(
147
+ telnyxCall,
148
+ telnyxCall.callId || this._generateCallId(),
149
+ destination,
150
+ false // outgoing call
151
+ );
152
+
153
+ // Add to our call tracking
154
+ this._addCall(call);
155
+
156
+ return call;
157
+ } catch (error) {
158
+ console.error('Failed to create new call:', error);
159
+ throw error;
160
+ }
161
+ }
162
+
163
+ /**
164
+ * Set callbacks for waiting for invite logic (used for push notifications)
165
+ */
166
+ setWaitingForInviteCallbacks(callbacks: {
167
+ isWaitingForInvite: () => boolean;
168
+ onInviteAutoAccepted: () => void;
169
+ }): void {
170
+ this._isWaitingForInvite = callbacks.isWaitingForInvite;
171
+ this._onInviteAutoAccepted = callbacks.onInviteAutoAccepted;
172
+ }
173
+
174
+ /**
175
+ * Dispose of the controller and clean up resources
176
+ */
177
+ dispose(): void {
178
+ if (this._disposed) {
179
+ return;
180
+ }
181
+
182
+ this._disposed = true;
183
+
184
+ // Dispose of all calls
185
+ this.currentCalls.forEach((call) => call.dispose());
186
+ this._callMap.clear();
187
+
188
+ // CallKit cleanup is now handled by CallKitCoordinator automatically
189
+
190
+ this._calls.complete();
191
+ }
192
+
193
+ /**
194
+ * Set up event listeners for the Telnyx client
195
+ */
196
+ private _setupClientListeners(): void {
197
+ console.log('🔧 CallStateController: Setting up client listeners...');
198
+
199
+ if (!this._sessionManager.telnyxClient) {
200
+ console.log('🔧 CallStateController: No telnyxClient available yet, skipping listener setup');
201
+ return;
202
+ }
203
+
204
+ console.log('🔧 CallStateController: TelnyxClient found, setting up incoming call listener');
205
+
206
+ // Listen for incoming calls
207
+ this._sessionManager.telnyxClient.on(
208
+ 'telnyx.call.incoming',
209
+ (telnyxCall: TelnyxCall, msg: any) => {
210
+ console.log('📞 CallStateController: Incoming call received:', telnyxCall.callId);
211
+ this._handleIncomingCall(telnyxCall, msg);
212
+ }
213
+ );
214
+
215
+ // Listen for other call events if needed
216
+ // this._sessionManager.telnyxClient.on('telnyx.call.stateChange', this._handleCallStateChange.bind(this));
217
+
218
+ console.log('🔧 CallStateController: Client listeners set up successfully');
219
+ }
220
+
221
+ /**
222
+ * Handle incoming call
223
+ */
224
+ private _handleIncomingCall(telnyxCall: TelnyxCall, inviteMsg?: any): void {
225
+ const callId = telnyxCall.callId || this._generateCallId();
226
+
227
+ console.log('📞 CallStateController: Handling incoming call:', callId);
228
+ console.log('📞 CallStateController: TelnyxCall object:', telnyxCall);
229
+ console.log('📞 CallStateController: Invite message:', inviteMsg);
230
+
231
+ // Check if we already have this call
232
+ if (this._callMap.has(callId)) {
233
+ console.log('Call already exists:', callId);
234
+ return;
235
+ }
236
+
237
+ // Get caller information from the invite message (preferred) or fallback to TelnyxCall
238
+ let callerNumber = 'Unknown';
239
+ let callerName = 'Unknown';
240
+
241
+ if (inviteMsg && inviteMsg.params) {
242
+ callerNumber = inviteMsg.params.caller_id_number || 'Unknown';
243
+ callerName = inviteMsg.params.caller_id_name || callerNumber;
244
+ console.log(
245
+ '📞 CallStateController: Extracted caller info from invite - Number:',
246
+ callerNumber,
247
+ 'Name:',
248
+ callerName
249
+ );
250
+ } else {
251
+ // Fallback to TelnyxCall properties
252
+ callerNumber = telnyxCall.remoteCallerIdNumber || 'Unknown';
253
+ callerName = telnyxCall.remoteCallerIdName || callerNumber;
254
+ console.log(
255
+ '📞 CallStateController: Extracted caller info from TelnyxCall - Number:',
256
+ callerNumber,
257
+ 'Name:',
258
+ callerName
259
+ );
260
+ }
261
+
262
+ // Create our wrapper Call object
263
+ const call = new Call(
264
+ telnyxCall,
265
+ callId,
266
+ callerNumber, // Use caller number as destination for incoming calls
267
+ true // incoming call
268
+ );
269
+
270
+ // Check if we're waiting for an invite (push notification scenario)
271
+ if (this._isWaitingForInvite && this._isWaitingForInvite()) {
272
+ console.log('Auto-accepting call from push notification');
273
+ call.answer().catch((error) => {
274
+ console.error('Failed to auto-accept call:', error);
275
+ });
276
+
277
+ if (this._onInviteAutoAccepted) {
278
+ this._onInviteAutoAccepted();
279
+ }
280
+ }
281
+
282
+ // Add to our call tracking - CallKit integration happens in _addCall
283
+ this._addCall(call);
284
+ }
285
+
286
+ /**
287
+ * Handle call state changes from the Telnyx client
288
+ */
289
+ private _handleCallStateChange(event: any): void {
290
+ const callId = event.callId || event.id;
291
+ const call = this._callMap.get(callId);
292
+
293
+ if (call) {
294
+ // The Call object will handle its own state updates through its listeners
295
+ console.log(`Call ${callId} state changed to ${event.state}`);
296
+ } else {
297
+ console.warn(`Received state change for unknown call: ${callId}`);
298
+ }
299
+ }
300
+
301
+ /**
302
+ * Handle call updates from notifications
303
+ */
304
+ private _handleCallUpdate(callData: any): void {
305
+ const callId = callData.id;
306
+ const call = this._callMap.get(callId);
307
+
308
+ if (call) {
309
+ // Update call state based on the notification
310
+ console.log(`Call ${callId} updated:`, callData);
311
+ } else {
312
+ console.warn(`Received update for unknown call: ${callId}`);
313
+ }
314
+ }
315
+
316
+ /**
317
+ * Add a call to our tracking
318
+ */
319
+ private _addCall(call: Call): void {
320
+ this._callMap.set(call.callId, call);
321
+
322
+ const currentCalls = this.currentCalls;
323
+ currentCalls.push(call);
324
+ this._calls.next([...currentCalls]);
325
+
326
+ // Integrate with CallKit using CallKitCoordinator
327
+ if (callKitCoordinator.isAvailable()) {
328
+ // Get the underlying TelnyxCall for CallKitCoordinator
329
+ const telnyxCall = call.telnyxCall;
330
+
331
+ // Check if this call already has CallKit integration (e.g., from push notification)
332
+ const existingCallKitUUID = callKitCoordinator.getCallKitUUID(telnyxCall);
333
+
334
+ if (existingCallKitUUID) {
335
+ console.log(
336
+ 'CallStateController: Call already has CallKit integration, skipping duplicate report:',
337
+ existingCallKitUUID
338
+ );
339
+ } else if (call.isIncoming) {
340
+ // Handle incoming call with CallKit (only if not already integrated)
341
+ console.log('CallStateController: Reporting incoming call to CallKitCoordinator');
342
+ callKitCoordinator.reportIncomingCall(telnyxCall, call.destination, call.destination);
343
+ } else {
344
+ // Handle outgoing call with CallKit
345
+ console.log('CallStateController: Starting outgoing call with CallKitCoordinator');
346
+ callKitCoordinator.startOutgoingCall(telnyxCall, call.destination, call.destination);
347
+ }
348
+ }
349
+
350
+ // Listen for call state changes - CallKitCoordinator handles this automatically
351
+ call.callState$.subscribe((state) => {
352
+ // CallKitCoordinator automatically updates CallKit via setupWebRTCCallListeners
353
+ console.log('CallStateController: Call state changed to:', state);
354
+
355
+ // Clean up when call ends
356
+ if (state === TelnyxCallState.ENDED || state === TelnyxCallState.FAILED) {
357
+ this._removeCall(call.callId);
358
+ }
359
+ });
360
+ }
361
+
362
+ /**
363
+ * Remove a call from our tracking
364
+ */
365
+ private _removeCall(callId: string): void {
366
+ const call = this._callMap.get(callId);
367
+ if (call) {
368
+ // CallKit cleanup is handled automatically by CallKitCoordinator
369
+
370
+ call.dispose();
371
+ this._callMap.delete(callId);
372
+
373
+ const currentCalls = this.currentCalls.filter((c) => c.callId !== callId);
374
+ this._calls.next(currentCalls);
375
+ }
376
+ }
377
+
378
+ /**
379
+ * Generate a unique call ID
380
+ */
381
+ private _generateCallId(): string {
382
+ return `call_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
383
+ }
384
+ }