@telnyx/react-voice-commons-sdk 0.1.2 → 0.1.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.
Files changed (55) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/README.md +469 -483
  3. package/ios/CallKitBridge.swift +2 -7
  4. package/lib/callkit/callkit-coordinator.d.ts +110 -117
  5. package/lib/callkit/callkit-coordinator.js +664 -727
  6. package/lib/callkit/callkit.d.ts +41 -41
  7. package/lib/callkit/callkit.js +252 -242
  8. package/lib/callkit/index.js +15 -47
  9. package/lib/callkit/use-callkit.d.ts +19 -19
  10. package/lib/callkit/use-callkit.js +270 -310
  11. package/lib/context/TelnyxVoiceContext.d.ts +9 -9
  12. package/lib/context/TelnyxVoiceContext.js +10 -13
  13. package/lib/hooks/use-callkit-coordinator.d.ts +9 -17
  14. package/lib/hooks/use-callkit-coordinator.js +45 -50
  15. package/lib/hooks/useAppReadyNotifier.js +13 -15
  16. package/lib/hooks/useAppStateHandler.d.ts +6 -11
  17. package/lib/hooks/useAppStateHandler.js +95 -110
  18. package/lib/hooks/useNetworkStateHandler.d.ts +0 -0
  19. package/lib/hooks/useNetworkStateHandler.js +0 -0
  20. package/lib/index.d.ts +3 -21
  21. package/lib/index.js +50 -201
  22. package/lib/internal/CallKitHandler.d.ts +6 -6
  23. package/lib/internal/CallKitHandler.js +96 -104
  24. package/lib/internal/callkit-manager.d.ts +57 -57
  25. package/lib/internal/callkit-manager.js +299 -316
  26. package/lib/internal/calls/call-state-controller.d.ts +73 -86
  27. package/lib/internal/calls/call-state-controller.js +263 -307
  28. package/lib/internal/session/session-manager.d.ts +71 -75
  29. package/lib/internal/session/session-manager.js +360 -424
  30. package/lib/internal/user-defaults-helpers.js +49 -39
  31. package/lib/internal/voice-pn-bridge.d.ts +114 -12
  32. package/lib/internal/voice-pn-bridge.js +212 -5
  33. package/lib/models/call-state.d.ts +46 -44
  34. package/lib/models/call-state.js +70 -68
  35. package/lib/models/call.d.ts +161 -133
  36. package/lib/models/call.js +454 -382
  37. package/lib/models/config.d.ts +11 -18
  38. package/lib/models/config.js +37 -35
  39. package/lib/models/connection-state.d.ts +10 -10
  40. package/lib/models/connection-state.js +16 -16
  41. package/lib/telnyx-voice-app.d.ts +28 -28
  42. package/lib/telnyx-voice-app.js +513 -480
  43. package/lib/telnyx-voip-client.d.ts +167 -167
  44. package/lib/telnyx-voip-client.js +385 -390
  45. package/package.json +115 -104
  46. package/src/callkit/callkit-coordinator.ts +830 -846
  47. package/src/hooks/useNetworkStateHandler.ts +0 -0
  48. package/src/internal/calls/call-state-controller.ts +407 -384
  49. package/src/internal/session/session-manager.ts +483 -467
  50. package/src/internal/voice-pn-bridge.ts +266 -18
  51. package/src/models/call-state.ts +105 -98
  52. package/src/models/call.ts +502 -388
  53. package/src/telnyx-voice-app.tsx +788 -690
  54. package/src/telnyx-voip-client.ts +551 -539
  55. package/src/types/telnyx-sdk.d.ts +93 -79
package/README.md CHANGED
@@ -1,483 +1,469 @@
1
- # Telnyx React Native Voice SDK Demo
2
-
3
- A comprehensive demo application showcasing the **@telnyx/react-voice-commons-sdk** library - a high-level, state-agnostic, drop-in module for the Telnyx React Native SDK that simplifies WebRTC voice calling integration.
4
-
5
- ## Overview
6
-
7
- This demo app demonstrates how to integrate the `@telnyx/react-voice-commons-sdk` library to create a fully functional VoIP calling application with native call UI support, push notifications, and background handling.
8
-
9
- ### Key Features Demonstrated
10
-
11
- - **TelnyxVoiceApp Integration**: Automatic lifecycle management and push notification handling
12
- - **Native Call UI**: CallKit (iOS) and ConnectionService (Android) integration
13
- - **Background Handling**: Seamless app state transitions and background call processing
14
- - **Push Notifications**: Firebase (Android) and APNs (iOS) integration
15
- - **Reactive State Management**: RxJS-based state streams for real-time UI updates
16
- - **Modern UI Components**: Built with NativeWind v4 and react-native-reusables
17
- - **Dark/Light Mode**: Persistent theme support with system navigation bar matching
18
-
19
- ## About @telnyx/react-voice-commons-sdk
20
-
21
- The `@telnyx/react-voice-commons-sdk` library provides:
22
-
23
- - **Headless Operation**: Core library that can establish and manage call state programmatically
24
- - **Reactive Streams**: All state exposed via RxJS observables for easy integration
25
- - **Simplified API**: Single facade class (`TelnyxVoipClient`) that hides underlying complexity
26
- - **Automatic Lifecycle Management**: Background/foreground handling with `TelnyxVoiceApp` component
27
- - **Call State Management**: Central state machine for managing multiple calls
28
- - **Session Management**: Automatic connection lifecycle with reconnection logic
29
- - **Push Notification Support**: Built-in handling for background push notifications
30
- - **TypeScript Support**: Full TypeScript definitions for better developer experience
31
-
32
- ## Integration Guide
33
-
34
- ### Basic Setup
35
-
36
- The demo shows how to integrate the library using the `TelnyxVoiceApp` component for automatic lifecycle management:
37
-
38
- ```tsx
39
- import { TelnyxVoiceApp, createTelnyxVoipClient } from '@telnyx/react-voice-commons-sdk';
40
-
41
- // Create the VoIP client instance
42
- const voipClient = createTelnyxVoipClient({
43
- enableAppStateManagement: true, // Optional: Enable automatic app state management (default: true)
44
- debug: true, // Optional: Enable debug logging
45
- });
46
-
47
- export default function App() {
48
- return (
49
- <TelnyxVoiceApp voipClient={voipClient} enableAutoReconnect={false} debug={true}>
50
- <YourAppContent />
51
- </TelnyxVoiceApp>
52
- );
53
- }
54
- ```
55
-
56
- ### Core Components Used in Demo
57
-
58
- #### 1. VoIP Client Configuration
59
-
60
- ```tsx
61
- const voipClient = createTelnyxVoipClient({
62
- enableAppStateManagement: true, // Optional: Enable automatic app state management (default: true)
63
- debug: true, // Optional: Enable debug logging
64
- });
65
- ```
66
-
67
- **Configuration Options Explained:**
68
-
69
- - **`enableAppStateManagement: true`** - **Optional (default: true)**: Enables automatic background/foreground app state management. When enabled, the library automatically disconnects when the app goes to background (unless there's an active call) and handles reconnection logic. Set to `false` if you want to handle app lifecycle manually.
70
- - **`debug: true`** - **Optional**: Enables detailed logging for connection states, call transitions, and push notification processing. Useful for development and troubleshooting.
71
-
72
- #### 2. TelnyxVoiceApp Wrapper
73
-
74
- The `TelnyxVoiceApp` component handles:
75
-
76
- - Automatic background/foreground lifecycle management
77
- - Push notification processing from terminated state
78
- - Login state management with automatic reconnection
79
- - Background client management for push notifications
80
-
81
- #### 3. Reactive State Management
82
-
83
- ```tsx
84
- // Listen to connection state
85
- voipClient.connectionState$.subscribe((state) => {
86
- console.log('Connection state:', state);
87
- });
88
-
89
- // Listen to active calls
90
- voipClient.calls$.subscribe((calls) => {
91
- console.log('Active calls:', calls);
92
- });
93
-
94
- // Handle individual call state
95
- call.callState$.subscribe((state) => {
96
- console.log('Call state:', state);
97
- });
98
- ```
99
-
100
- #### 4. Call Management
101
-
102
- ```tsx
103
- // Make a call
104
- const call = await voipClient.newCall('1234567890');
105
-
106
- // Answer incoming call
107
- await call.answer();
108
-
109
- // Control call
110
- await call.mute();
111
- await call.hold();
112
- await call.hangup();
113
- ```
114
-
115
- ### Authentication & Persistent Storage
116
-
117
- The library supports both credential-based and token-based authentication with automatic persistence for seamless reconnection.
118
-
119
- #### Authentication Methods
120
-
121
- ##### 1. Credential-Based Authentication
122
-
123
- ```tsx
124
- import { createCredentialConfig } from '@telnyx/react-voice-commons-sdk';
125
-
126
- const config = createCredentialConfig('your_sip_username', 'your_sip_password', {
127
- debug: true,
128
- pushNotificationDeviceToken: 'your_device_token',
129
- });
130
-
131
- await voipClient.login(config);
132
- ```
133
-
134
- ##### 2. Token-Based Authentication
135
-
136
- ```tsx
137
- import { createTokenConfig } from '@telnyx/react-voice-commons-sdk';
138
-
139
- const config = createTokenConfig('your_jwt_token', {
140
- debug: true,
141
- pushNotificationDeviceToken: 'your_device_token',
142
- });
143
-
144
- await voipClient.loginWithToken(config);
145
- ```
146
-
147
- #### Automatic Storage & Reconnection
148
-
149
- The library automatically stores authentication data securely for seamless reconnection. **You don't need to manually manage these storage keys** - the library handles everything internally.
150
-
151
- ##### Internal Storage (Managed Automatically)
152
-
153
- The library uses these AsyncStorage keys internally:
154
-
155
- - `@telnyx_username` - SIP username (credential auth)
156
- - `@telnyx_password` - SIP password (credential auth)
157
- - `@credential_token` - JWT authentication token (token auth)
158
- - `@push_token` - Push notification device token
159
-
160
- **Note**: These are managed automatically by the library. You only need to call `login()` once, and the library will handle storage and future reconnections.
161
-
162
- ##### Auto-Reconnection
163
-
164
- ```tsx
165
- // Automatically reconnects using internally stored credentials or token
166
- const success = await voipClient.loginFromStoredConfig();
167
-
168
- if (!success) {
169
- // No stored authentication data found, show login UI
170
- console.log('Please log in again');
171
- }
172
- ```
173
-
174
- **When Auto-Reconnection Happens:**
175
-
176
- - App launches from background/terminated state
177
- - Push notification received while disconnected
178
- - Network reconnection after connectivity loss
179
- - App state changes (foreground/background transitions)
180
-
181
- **Demo App Note**: The demo app's `TelnyxLoginForm` component does additional storage for UI convenience (pre-filling the login form). This is separate from the library's internal authentication storage and is not required for production apps.
182
-
183
- ##### Manual Storage Management (Advanced Use Only)
184
-
185
- If you need to clear stored authentication data manually:
186
-
187
- ```tsx
188
- import AsyncStorage from '@react-native-async-storage/async-storage';
189
-
190
- // Clear all Telnyx authentication data
191
- await AsyncStorage.multiRemove([
192
- '@telnyx_username',
193
- '@telnyx_password',
194
- '@credential_token',
195
- '@push_token',
196
- ]);
197
- ```
198
-
199
- **Important**: This is typically not needed. The library manages authentication storage automatically. Only use this for advanced scenarios like implementing a "logout" feature that clears all stored data.
200
-
201
- ### Native Integration
202
-
203
- The demo app shows complete native integration for both platforms. These integrations are required for production apps using the library.
204
-
205
- #### Android Integration
206
-
207
- ##### 1. MainActivity Setup
208
-
209
- Your app's MainActivity should extend `TelnyxMainActivity` for automatic push notification handling:
210
-
211
- ```kotlin
212
- // In your app's MainActivity.kt
213
- import com.telnyx.react_voice_commons.TelnyxMainActivity
214
-
215
- class MainActivity : TelnyxMainActivity() {
216
- // Your app-specific code
217
-
218
- override fun onHandleIntent(intent: Intent) {
219
- super.onHandleIntent(intent)
220
- // Handle any additional intent processing
221
- }
222
- }
223
- ```
224
-
225
- The `TelnyxMainActivity` provides:
226
-
227
- - Automatic push notification intent handling
228
- - Call action processing (Answer/Decline from notifications)
229
- - Proper lifecycle management for VoIP functionality
230
- - Integration with `VoicePnManager` for push notification state
231
-
232
- ##### 2. Push Notification Setup
233
-
234
- 1. Place `google-services.json` in the project root
235
- 2. Register background message handler:
236
-
237
- ```tsx
238
- import messaging from '@react-native-firebase/messaging';
239
- import { TelnyxVoiceApp } from '@telnyx/react-voice-commons-sdk';
240
-
241
- messaging().setBackgroundMessageHandler(async (remoteMessage) => {
242
- await TelnyxVoiceApp.handleBackgroundPush(remoteMessage.data);
243
- });
244
- ```
245
-
246
- #### iOS Integration
247
-
248
- ##### 1. AppDelegate Setup
249
-
250
- Your AppDelegate only needs to implement `PKPushRegistryDelegate` for VoIP push notifications. CallKit integration is automatically handled by CallBridge:
251
-
252
- ```swift
253
- import PushKit
254
- import TelnyxVoiceCommons
255
-
256
- @UIApplicationMain
257
- public class AppDelegate: ExpoAppDelegate, PKPushRegistryDelegate {
258
-
259
- public override func application(
260
- _ application: UIApplication,
261
- didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
262
- ) -> Bool {
263
- // Your existing setup...
264
-
265
- // Initialize VoIP push registry via react-voice-commons
266
- TelnyxVoipPushHandler.initializeVoipRegistration()
267
-
268
- return super.application(application, didFinishLaunchingWithOptions: launchOptions)
269
- }
270
-
271
- // MARK: - VoIP Push Notifications
272
- public func pushRegistry(_ registry: PKPushRegistry, didUpdate pushCredentials: PKPushCredentials, for type: PKPushType) {
273
- TelnyxVoipPushHandler.shared.handleVoipTokenUpdate(pushCredentials, type: type)
274
- }
275
-
276
- public func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, for type: PKPushType, completion: @escaping () -> Void) {
277
- TelnyxVoipPushHandler.shared.handleVoipPush(payload, type: type, completion: completion)
278
- }
279
- }
280
- ```
281
-
282
- **Note**: CallKit integration (CXProvider, CXProviderDelegate, audio session management) is automatically handled by the internal CallBridge component. You don't need to implement any CallKit delegate methods manually.
283
-
284
- ##### 2. VoIP Push Certificate Setup
285
-
286
- - Configure VoIP push certificates in your Apple Developer account
287
- - The `TelnyxVoipPushHandler` automatically handles token registration and push processing
288
- - CallKit integration is automatically managed by CallBridge - no manual setup required
289
-
290
- #### Key Native Features Integrated
291
-
292
- 1. **Push Notification Handling**: Both platforms handle background push notifications properly
293
- 2. **Native Call UI**: CallKit (iOS, managed by CallBridge) and ConnectionService (Android) integration
294
- 3. **Audio Session Management**: Automatic audio session handling for VoIP calls via CallBridge
295
- 4. **Background Processing**: Seamless app state transitions and background call handling
296
- 5. **Intent Processing**: Android intent handling for notification actions (Answer/Decline)
297
- 6. **Token Management**: Automatic push token registration and updates
298
-
299
- ## Running the Demo Application
300
-
301
- ### Prerequisites
302
-
303
- - Node.js and npm
304
- - Expo CLI
305
- - iOS development: Xcode
306
- - Android development: Android Studio
307
-
308
- ### Installation and Setup
309
-
310
- 1. **Remove global Expo CLI** (if previously installed):
311
-
312
- ```bash
313
- npm uninstall -g expo
314
- ```
315
-
316
- 2. **Install dependencies** (including local Expo):
317
-
318
- ```bash
319
- npm install
320
- ```
321
-
322
- 3. **Run Expo install** to ensure all dependencies are properly configured:
323
-
324
- ```bash
325
- npx expo install
326
- ```
327
-
328
- 4. **Configure Firebase for Android**:
329
- - Download the `google-services.json` file from your Firebase project
330
- - Place it in the root directory of the project
331
-
332
- 5. **Prebuild the project**:
333
-
334
- ```bash
335
- npx expo prebuild
336
- ```
337
-
338
- 6. **Install iOS dependencies** (required for iOS):
339
- ```bash
340
- cd ios && pod install && cd ..
341
- ```
342
-
343
- ### Running the Application
344
-
345
- 1. **Start Metro bundler** (in a separate terminal):
346
-
347
- ```bash
348
- npx expo start --clear --reset-cache
349
- ```
350
-
351
- 2. **Run on iOS**:
352
-
353
- ```bash
354
- npx expo run:ios
355
- ```
356
-
357
- 3. **Run on Android**:
358
- ```bash
359
- npx expo run:android
360
- ```
361
-
362
- > **Note**: Make sure you have the necessary development environment set up for iOS (Xcode) or Android (Android Studio) before running the respective commands.
363
-
364
- ### Demo App Features
365
-
366
- Once running, the demo app provides:
367
-
368
- - **Login Form**: Enter your Telnyx SIP credentials or token
369
- - **Dialer Interface**: Make outgoing calls with a native dialer UI
370
- - **Call Management**: Answer, decline, hold, mute, and transfer calls
371
- - **Native Call UI**: Integrated CallKit (iOS) and ConnectionService (Android)
372
- - **Push Notifications**: Receive calls when app is in background or terminated
373
- - **Multiple Call Support**: Handle multiple simultaneous calls
374
- - **Background Handling**: Seamless app state transitions
375
-
376
- ### Configuration
377
-
378
- The demo app includes debug logging enabled by default:
379
-
380
- ```tsx
381
- // Enable debug logging for the Telnyx SDK
382
- if (__DEV__) {
383
- log.setLevel('debug');
384
- (global as any).__TELNYX_DEBUG__ = true;
385
- }
386
- ```
387
-
388
- This provides detailed logging for:
389
-
390
- - Connection state changes
391
- - Call state transitions
392
- - Push notification processing
393
- - Background lifecycle events
394
-
395
- ## Troubleshooting
396
-
397
- ### iOS Connection Issues (First Run)
398
-
399
- If you encounter network connection errors on iOS:
400
-
401
- ```bash
402
- # Try clearing cache and resetting
403
- npx expo start --clear --reset-cache
404
-
405
- # Or use tunnel mode
406
- npx expo start --tunnel
407
-
408
- # Or specify host explicitly
409
- npx expo start --host lan
410
- ```
411
-
412
- ### iOS VoIP Push Notification Issues
413
-
414
- If you see VoIP-related crashes on iOS, ensure your AppDelegate.swift includes the VoIP push notification delegate methods. The project includes these by default, but if you encounter issues, rebuild the iOS project:
415
-
416
- ```bash
417
- npx expo prebuild --platform ios --clean
418
- npx expo run:ios
419
- ```
420
-
421
- ### Common Integration Issues
422
-
423
- #### Double Login
424
-
425
- Ensure you're not calling login methods manually when using `TelnyxVoiceApp` with auto-reconnection enabled.
426
-
427
- #### Background Disconnection
428
-
429
- Check if `enableAutoReconnect` is set appropriately for your use case in the `TelnyxVoiceApp` configuration.
430
-
431
- #### Push Notifications Not Working
432
-
433
- - **Android**:
434
- - Verify `google-services.json` is in the correct location and Firebase is properly configured
435
- - Ensure your MainActivity extends `TelnyxMainActivity`
436
- - Check that `VoicePnManager` is properly handling push actions
437
- - **iOS**:
438
- - Ensure VoIP push certificates are configured in your Apple Developer account
439
- - Verify AppDelegate implements `PKPushRegistryDelegate` and delegates to `TelnyxVoipPushHandler`
440
- - Check that `TelnyxVoipPushHandler.initializeVoipRegistration()` is called in `didFinishLaunchingWithOptions`
441
- - **Both**: Check that background message handlers are properly registered
442
-
443
- #### Native Integration Issues
444
-
445
- - **Android**: Ensure MainActivity extends `TelnyxMainActivity` for proper intent handling
446
- - **iOS**: Verify AppDelegate implements `PKPushRegistryDelegate` and delegates to `TelnyxVoipPushHandler`
447
- - **CallKit**: On iOS, CallKit integration is automatically handled by CallBridge - no manual setup required
448
-
449
- #### Audio Issues
450
-
451
- - **iOS**: Audio session management is automatically handled by CallBridge
452
- - **Android**: Verify ConnectionService is properly configured for audio routing
453
- - **Both**: Ensure proper audio permissions are granted
454
-
455
- #### Memory Leaks
456
-
457
- Ensure you're unsubscribing from RxJS observables in your React components:
458
-
459
- ```tsx
460
- useEffect(() => {
461
- const subscription = voipClient.connectionState$.subscribe(handleStateChange);
462
- return () => subscription.unsubscribe();
463
- }, []);
464
- }, []);
465
- ```
466
-
467
- ## Documentation
468
-
469
- For complete API documentation and advanced usage patterns, see the [TelnyxVoiceApp Documentation](./react-voice-commons-sdk/TELNYX_VOICE_APP.md).
470
-
471
- ## Contributing
472
-
473
- When contributing to this demo or the underlying library:
474
-
475
- 1. Maintain compatibility with both iOS and Android platforms
476
- 2. Add comprehensive tests for new features
477
- 3. Update documentation for any API changes
478
- 4. Follow the existing code style and patterns
479
- 5. Test with both foreground and background scenarios
480
-
481
- ## License
482
-
483
- MIT License - see LICENSE file for details.
1
+ # Telnyx React Voice Commons SDK
2
+
3
+ A high-level, state-agnostic, drop-in module for the Telnyx React Native SDK that simplifies WebRTC voice calling integration. This library provides a comprehensive solution for building VoIP applications with native call UI support, push notifications, and seamless background handling.
4
+
5
+ ### Key Features
6
+
7
+ - **TelnyxVoiceApp Integration**: Automatic lifecycle management and push notification handling
8
+ - **Native Call UI**: CallKit (iOS) and ConnectionService (Android) integration
9
+ - **Background Handling**: Seamless app state transitions and background call processing
10
+ - **Push Notifications**: Firebase (Android) and APNs (iOS) integration
11
+ - **Reactive State Management**: RxJS-based state streams for real-time UI updates
12
+ - **TypeScript Support**: Full TypeScript definitions for better developer experience
13
+ - **Cross-Platform**: Built for both iOS and Android with React Native
14
+
15
+ ## About @telnyx/react-voice-commons-sdk
16
+
17
+ The `@telnyx/react-voice-commons-sdk` library provides:
18
+
19
+ - **Headless Operation**: Core library that can establish and manage call state programmatically
20
+ - **Reactive Streams**: All state exposed via RxJS observables for easy integration
21
+ - **Simplified API**: Single facade class (`TelnyxVoipClient`) that hides underlying complexity
22
+ - **Automatic Lifecycle Management**: Background/foreground handling with `TelnyxVoiceApp` component
23
+ - **Call State Management**: Central state machine for managing multiple calls
24
+ - **Session Management**: Automatic connection lifecycle with reconnection logic
25
+ - **Push Notification Support**: Built-in handling for background push notifications
26
+ - **TypeScript Support**: Full TypeScript definitions for better developer experience
27
+
28
+ ## Integration Guide
29
+
30
+ ### Basic Setup
31
+
32
+ Integrate the library using the `TelnyxVoiceApp` component for automatic lifecycle management:
33
+
34
+ ```tsx
35
+ import { TelnyxVoiceApp, createTelnyxVoipClient } from '@telnyx/react-voice-commons-sdk';
36
+
37
+ // Create the VoIP client instance
38
+ const voipClient = createTelnyxVoipClient({
39
+ enableAppStateManagement: true, // Optional: Enable automatic app state management (default: true)
40
+ debug: true, // Optional: Enable debug logging
41
+ });
42
+
43
+ export default function App() {
44
+ return (
45
+ <TelnyxVoiceApp voipClient={voipClient} enableAutoReconnect={false} debug={true}>
46
+ <YourAppContent />
47
+ </TelnyxVoiceApp>
48
+ );
49
+ }
50
+ ```
51
+
52
+ ### Core Components
53
+
54
+ #### 1. VoIP Client Configuration
55
+
56
+ ```tsx
57
+ const voipClient = createTelnyxVoipClient({
58
+ enableAppStateManagement: true, // Optional: Enable automatic app state management (default: true)
59
+ debug: true, // Optional: Enable debug logging
60
+ });
61
+ ```
62
+
63
+ **Configuration Options Explained:**
64
+
65
+ - **`enableAppStateManagement: true`** - **Optional (default: true)**: Enables automatic background/foreground app state management. When enabled, the library automatically disconnects when the app goes to background (unless there's an active call) and handles reconnection logic. Set to `false` if you want to handle app lifecycle manually.
66
+ - **`debug: true`** - **Optional**: Enables detailed logging for connection states, call transitions, and push notification processing. Useful for development and troubleshooting.
67
+
68
+ #### 2. TelnyxVoiceApp Wrapper
69
+
70
+ The `TelnyxVoiceApp` component handles:
71
+
72
+ - Automatic background/foreground lifecycle management
73
+ - Push notification processing from terminated state
74
+ - Login state management with automatic reconnection
75
+ - Background client management for push notifications
76
+
77
+ #### 3. Reactive State Management
78
+
79
+ ```tsx
80
+ // Listen to connection state
81
+ voipClient.connectionState$.subscribe((state) => {
82
+ console.log('Connection state:', state);
83
+ });
84
+
85
+ // Listen to active calls
86
+ voipClient.calls$.subscribe((calls) => {
87
+ console.log('Active calls:', calls);
88
+ });
89
+
90
+ // Handle individual call state
91
+ call.callState$.subscribe((state) => {
92
+ console.log('Call state:', state);
93
+ });
94
+ ```
95
+
96
+ #### 4. Call Management
97
+
98
+ ```tsx
99
+ // Make a call
100
+ const call = await voipClient.newCall('1234567890');
101
+
102
+ // Answer incoming call
103
+ await call.answer();
104
+
105
+ // Control call
106
+ await call.mute();
107
+ await call.hold();
108
+ await call.hangup();
109
+ ```
110
+
111
+ ### Authentication & Persistent Storage
112
+
113
+ The library supports both credential-based and token-based authentication with automatic persistence for seamless reconnection.
114
+
115
+ #### Authentication Methods
116
+
117
+ ##### 1. Credential-Based Authentication
118
+
119
+ ```tsx
120
+ import { createCredentialConfig } from '@telnyx/react-voice-commons-sdk';
121
+
122
+ const config = createCredentialConfig('your_sip_username', 'your_sip_password', {
123
+ debug: true,
124
+ pushNotificationDeviceToken: 'your_device_token',
125
+ });
126
+
127
+ await voipClient.login(config);
128
+ ```
129
+
130
+ ##### 2. Token-Based Authentication
131
+
132
+ ```tsx
133
+ import { createTokenConfig } from '@telnyx/react-voice-commons-sdk';
134
+
135
+ const config = createTokenConfig('your_jwt_token', {
136
+ debug: true,
137
+ pushNotificationDeviceToken: 'your_device_token',
138
+ });
139
+
140
+ await voipClient.loginWithToken(config);
141
+ ```
142
+
143
+ #### Automatic Storage & Reconnection
144
+
145
+ The library automatically stores authentication data securely for seamless reconnection. **You don't need to manually manage these storage keys** - the library handles everything internally.
146
+
147
+ ##### Internal Storage (Managed Automatically)
148
+
149
+ The library uses these AsyncStorage keys internally:
150
+
151
+ - `@telnyx_username` - SIP username (credential auth)
152
+ - `@telnyx_password` - SIP password (credential auth)
153
+ - `@credential_token` - JWT authentication token (token auth)
154
+ - `@push_token` - Push notification device token
155
+
156
+ **Note**: These are managed automatically by the library. You only need to call `login()` once, and the library will handle storage and future reconnections.
157
+
158
+ ##### Auto-Reconnection
159
+
160
+ ```tsx
161
+ // Automatically reconnects using internally stored credentials or token
162
+ const success = await voipClient.loginFromStoredConfig();
163
+
164
+ if (!success) {
165
+ // No stored authentication data found, show login UI
166
+ console.log('Please log in again');
167
+ }
168
+ ```
169
+
170
+ **When Auto-Reconnection Happens:**
171
+
172
+ - App launches from background/terminated state
173
+ - Push notification received while disconnected
174
+ - Network reconnection after connectivity loss
175
+ - App state changes (foreground/background transitions)
176
+
177
+ **Demo App Note**: When using the library in a demo application, the `TelnyxLoginForm` component may do additional storage for UI convenience (pre-filling login forms). This is separate from the library's internal authentication storage and is not required for production apps.
178
+
179
+ ##### Manual Storage Management (Advanced Use Only)
180
+
181
+ If you need to clear stored authentication data manually:
182
+
183
+ ```tsx
184
+ import AsyncStorage from '@react-native-async-storage/async-storage';
185
+
186
+ // Clear all Telnyx authentication data
187
+ await AsyncStorage.multiRemove([
188
+ '@telnyx_username',
189
+ '@telnyx_password',
190
+ '@credential_token',
191
+ '@push_token',
192
+ ]);
193
+ ```
194
+
195
+ **Important**: This is typically not needed. The library manages authentication storage automatically. Only use this for advanced scenarios like implementing a "logout" feature that clears all stored data.
196
+
197
+ ### Native Integration
198
+
199
+ The library provides complete native integration for both platforms. These integrations are required for production apps using the library.
200
+
201
+ #### Android Integration
202
+
203
+ ##### 1. MainActivity Setup
204
+
205
+ Your app's MainActivity should extend `TelnyxMainActivity` for automatic push notification handling:
206
+
207
+ ```kotlin
208
+ // In your app's MainActivity.kt
209
+ import com.telnyx.react_voice_commons.TelnyxMainActivity
210
+
211
+ class MainActivity : TelnyxMainActivity() {
212
+ // Your app-specific code
213
+
214
+ override fun onHandleIntent(intent: Intent) {
215
+ super.onHandleIntent(intent)
216
+ // Handle any additional intent processing
217
+ }
218
+ }
219
+ ```
220
+
221
+ The `TelnyxMainActivity` provides:
222
+
223
+ - Automatic push notification intent handling
224
+ - Call action processing (Answer/Decline from notifications)
225
+ - Proper lifecycle management for VoIP functionality
226
+ - Integration with `VoicePnManager` for push notification state
227
+
228
+ ##### 2. Push Notification Setup
229
+
230
+ 1. Place `google-services.json` in the project root
231
+ 2. Register background message handler:
232
+
233
+ ```tsx
234
+ import messaging from '@react-native-firebase/messaging';
235
+ import { TelnyxVoiceApp } from '@telnyx/react-voice-commons-sdk';
236
+
237
+ messaging().setBackgroundMessageHandler(async (remoteMessage) => {
238
+ await TelnyxVoiceApp.handleBackgroundPush(remoteMessage.data);
239
+ });
240
+ ```
241
+
242
+ #### iOS Integration
243
+
244
+ ##### 1. AppDelegate Setup
245
+
246
+ Your AppDelegate only needs to implement `PKPushRegistryDelegate` for VoIP push notifications. CallKit integration is automatically handled by CallBridge:
247
+
248
+ ```swift
249
+ import PushKit
250
+ import TelnyxVoiceCommons
251
+
252
+ @UIApplicationMain
253
+ public class AppDelegate: ExpoAppDelegate, PKPushRegistryDelegate {
254
+
255
+ public override func application(
256
+ _ application: UIApplication,
257
+ didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
258
+ ) -> Bool {
259
+ // Your existing setup...
260
+
261
+ // Initialize VoIP push registry via react-voice-commons
262
+ TelnyxVoipPushHandler.initializeVoipRegistration()
263
+
264
+ return super.application(application, didFinishLaunchingWithOptions: launchOptions)
265
+ }
266
+
267
+ // MARK: - VoIP Push Notifications
268
+ public func pushRegistry(_ registry: PKPushRegistry, didUpdate pushCredentials: PKPushCredentials, for type: PKPushType) {
269
+ TelnyxVoipPushHandler.shared.handleVoipTokenUpdate(pushCredentials, type: type)
270
+ }
271
+
272
+ public func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, for type: PKPushType, completion: @escaping () -> Void) {
273
+ TelnyxVoipPushHandler.shared.handleVoipPush(payload, type: type, completion: completion)
274
+ }
275
+ }
276
+ ```
277
+
278
+ **Note**: CallKit integration (CXProvider, CXProviderDelegate, audio session management) is automatically handled by the internal CallBridge component. You don't need to implement any CallKit delegate methods manually.
279
+
280
+ ##### 2. VoIP Push Certificate Setup
281
+
282
+ - Configure VoIP push certificates in your Apple Developer account
283
+ - The `TelnyxVoipPushHandler` automatically handles token registration and push processing
284
+ - CallKit integration is automatically managed by CallBridge - no manual setup required
285
+
286
+ #### Key Native Features Integrated
287
+
288
+ 1. **Push Notification Handling**: Both platforms handle background push notifications properly
289
+ 2. **Native Call UI**: CallKit (iOS, managed by CallBridge) and ConnectionService (Android) integration
290
+ 3. **Audio Session Management**: Automatic audio session handling for VoIP calls via CallBridge
291
+ 4. **Background Processing**: Seamless app state transitions and background call handling
292
+ 5. **Intent Processing**: Android intent handling for notification actions (Answer/Decline)
293
+ 6. **Token Management**: Automatic push token registration and updates
294
+
295
+ ## Running the Demo Application
296
+
297
+ ### Prerequisites
298
+
299
+ - Node.js and npm
300
+ - Expo CLI
301
+ - iOS development: Xcode
302
+ - Android development: Android Studio
303
+
304
+ ### Installation and Setup
305
+
306
+ 1. **Remove global Expo CLI** (if previously installed):
307
+
308
+ ```bash
309
+ npm uninstall -g expo
310
+ ```
311
+
312
+ 2. **Install dependencies** (including local Expo):
313
+
314
+ ```bash
315
+ npm install
316
+ ```
317
+
318
+ 3. **Run Expo install** to ensure all dependencies are properly configured:
319
+
320
+ ```bash
321
+ npx expo install
322
+ ```
323
+
324
+ 4. **Configure Firebase for Android**:
325
+ - Download the `google-services.json` file from your Firebase project
326
+ - Place it in the root directory of the project
327
+
328
+ 5. **Prebuild the project**:
329
+
330
+ ```bash
331
+ npx expo prebuild
332
+ ```
333
+
334
+ 6. **Install iOS dependencies** (required for iOS):
335
+ ```bash
336
+ cd ios && pod install && cd ..
337
+ ```
338
+
339
+ ### Running the Application
340
+
341
+ 1. **Start Metro bundler** (in a separate terminal):
342
+
343
+ ```bash
344
+ npx expo start --clear --reset-cache
345
+ ```
346
+
347
+ 2. **Run on iOS**:
348
+
349
+ ```bash
350
+ npx expo run:ios
351
+ ```
352
+
353
+ 3. **Run on Android**:
354
+ ```bash
355
+ npx expo run:android
356
+ ```
357
+
358
+ > **Note**: Make sure you have the necessary development environment set up for iOS (Xcode) or Android (Android Studio) before running the respective commands.
359
+
360
+ ### Demo App Features
361
+
362
+ Once running, the demo app provides:
363
+
364
+ - **Login Form**: Enter your Telnyx SIP credentials or token
365
+ - **Dialer Interface**: Make outgoing calls with a native dialer UI
366
+ - **Call Management**: Answer, decline, hold, mute, and transfer calls
367
+ - **Native Call UI**: Integrated CallKit (iOS) and ConnectionService (Android)
368
+ - **Push Notifications**: Receive calls when app is in background or terminated
369
+ - **Multiple Call Support**: Handle multiple simultaneous calls
370
+ - **Background Handling**: Seamless app state transitions
371
+
372
+ ### Configuration
373
+
374
+ The demo app includes debug logging enabled by default:
375
+
376
+ ```tsx
377
+ // Enable debug logging for the Telnyx SDK
378
+ if (__DEV__) {
379
+ log.setLevel('debug');
380
+ (global as any).__TELNYX_DEBUG__ = true;
381
+ }
382
+ ```
383
+
384
+ This provides detailed logging for:
385
+
386
+ - Connection state changes
387
+ - Call state transitions
388
+ - Push notification processing
389
+ - Background lifecycle events
390
+
391
+ ## Troubleshooting
392
+
393
+ ### iOS Connection Issues (First Run)
394
+
395
+ If you encounter network connection errors on iOS:
396
+
397
+ ```bash
398
+ # Try clearing cache and resetting
399
+ npx expo start --clear --reset-cache
400
+
401
+ # Or use tunnel mode
402
+ npx expo start --tunnel
403
+
404
+ # Or specify host explicitly
405
+ npx expo start --host lan
406
+ ```
407
+
408
+ ### iOS VoIP Push Notification Issues
409
+
410
+ If you see VoIP-related crashes on iOS, ensure your AppDelegate.swift includes the VoIP push notification delegate methods. The project includes these by default, but if you encounter issues, rebuild the iOS project:
411
+
412
+ ```bash
413
+ npx expo prebuild --platform ios --clean
414
+ npx expo run:ios
415
+ ```
416
+
417
+ ### Common Integration Issues
418
+
419
+ #### Double Login
420
+
421
+ Ensure you're not calling login methods manually when using `TelnyxVoiceApp` with auto-reconnection enabled.
422
+
423
+ #### Background Disconnection
424
+
425
+ Check if `enableAutoReconnect` is set appropriately for your use case in the `TelnyxVoiceApp` configuration.
426
+
427
+ #### Push Notifications Not Working
428
+
429
+ - **Android**:
430
+ - Verify `google-services.json` is in the correct location and Firebase is properly configured
431
+ - Ensure your MainActivity extends `TelnyxMainActivity`
432
+ - Check that `VoicePnManager` is properly handling push actions
433
+ - **iOS**:
434
+ - Ensure VoIP push certificates are configured in your Apple Developer account
435
+ - Verify AppDelegate implements `PKPushRegistryDelegate` and delegates to `TelnyxVoipPushHandler`
436
+ - Check that `TelnyxVoipPushHandler.initializeVoipRegistration()` is called in `didFinishLaunchingWithOptions`
437
+ - **Both**: Check that background message handlers are properly registered
438
+
439
+ #### Native Integration Issues
440
+
441
+ - **Android**: Ensure MainActivity extends `TelnyxMainActivity` for proper intent handling
442
+ - **iOS**: Verify AppDelegate implements `PKPushRegistryDelegate` and delegates to `TelnyxVoipPushHandler`
443
+ - **CallKit**: On iOS, CallKit integration is automatically handled by CallBridge - no manual setup required
444
+
445
+ #### Audio Issues
446
+
447
+ - **iOS**: Audio session management is automatically handled by CallBridge
448
+ - **Android**: Verify ConnectionService is properly configured for audio routing
449
+ - **Both**: Ensure proper audio permissions are granted
450
+
451
+ #### Memory Leaks
452
+
453
+ Ensure you're unsubscribing from RxJS observables in your React components:
454
+
455
+ ```tsx
456
+ useEffect(() => {
457
+ const subscription = voipClient.connectionState$.subscribe(handleStateChange);
458
+ return () => subscription.unsubscribe();
459
+ }, []);
460
+ }, []);
461
+ ```
462
+
463
+ ## Documentation
464
+
465
+ For complete API documentation and advanced usage patterns, see the [TelnyxVoiceApp Documentation](./react-voice-commons-sdk/TELNYX_VOICE_APP.md).
466
+
467
+ ## License
468
+
469
+ MIT License - see LICENSE file for details.