livevoice-sdk-react-native 2.0.1 → 3.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.
Files changed (207) hide show
  1. package/README.md +105 -66
  2. package/android/build.gradle +5 -4
  3. package/android/src/main/java/io/livevoice/react/LiveVoiceModule.kt +122 -188
  4. package/android/src/main/java/io/livevoice/react/__SDK.kt +2 -2
  5. package/ios/LiveVoiceRNBridge.swift +362 -0
  6. package/ios/LiveVoiceSdkReactNative.mm +187 -158
  7. package/ios/__SDK.h +1 -1
  8. package/ios/livevoice_spm_backport.rb +202 -0
  9. package/lib/module/components/BrandingView.js +58 -39
  10. package/lib/module/components/BrandingView.js.map +1 -1
  11. package/lib/module/components/ChannelView.js +355 -44
  12. package/lib/module/components/ChannelView.js.map +1 -1
  13. package/lib/module/components/ErrorView.js +5 -6
  14. package/lib/module/components/ErrorView.js.map +1 -1
  15. package/lib/module/components/LiveVoiceSpinner.js +81 -0
  16. package/lib/module/components/LiveVoiceSpinner.js.map +1 -0
  17. package/lib/module/components/LiveVoiceView.js +311 -133
  18. package/lib/module/components/LiveVoiceView.js.map +1 -1
  19. package/lib/module/components/PasswordPrompt.js +165 -0
  20. package/lib/module/components/PasswordPrompt.js.map +1 -0
  21. package/lib/module/components/PlayButtonView.js +180 -244
  22. package/lib/module/components/PlayButtonView.js.map +1 -1
  23. package/lib/module/components/ReconnectingView.js +31 -53
  24. package/lib/module/components/ReconnectingView.js.map +1 -1
  25. package/lib/module/icons/branding-ios.png +0 -0
  26. package/lib/module/icons/camera-off-android.png +0 -0
  27. package/lib/module/icons/camera-off-android@2x.png +0 -0
  28. package/lib/module/icons/camera-off-android@3x.png +0 -0
  29. package/lib/module/icons/cpu-android.png +0 -0
  30. package/lib/module/icons/cpu-android@2x.png +0 -0
  31. package/lib/module/icons/cpu-android@3x.png +0 -0
  32. package/lib/module/icons/cpu-ios.png +0 -0
  33. package/lib/module/icons/cpu-ios@2x.png +0 -0
  34. package/lib/module/icons/cpu-ios@3x.png +0 -0
  35. package/lib/module/icons/lock-android.png +0 -0
  36. package/lib/module/icons/lock-android@2x.png +0 -0
  37. package/lib/module/icons/lock-android@3x.png +0 -0
  38. package/lib/module/icons/lock-ios.png +0 -0
  39. package/lib/module/icons/lock-ios@2x.png +0 -0
  40. package/lib/module/icons/lock-ios@3x.png +0 -0
  41. package/lib/module/icons/mic-off-android.png +0 -0
  42. package/lib/module/icons/mic-off-android@2x.png +0 -0
  43. package/lib/module/icons/mic-off-android@3x.png +0 -0
  44. package/lib/module/icons/mic-slash-ios.png +0 -0
  45. package/lib/module/icons/mic-slash-ios@2x.png +0 -0
  46. package/lib/module/icons/mic-slash-ios@3x.png +0 -0
  47. package/lib/module/icons/video-slash-ios.png +0 -0
  48. package/lib/module/icons/video-slash-ios@2x.png +0 -0
  49. package/lib/module/icons/video-slash-ios@3x.png +0 -0
  50. package/lib/module/index.js +11 -6
  51. package/lib/module/index.js.map +1 -1
  52. package/lib/module/sdk/Bridge.js +236 -0
  53. package/lib/module/sdk/Bridge.js.map +1 -0
  54. package/lib/module/sdk/Event.js +160 -0
  55. package/lib/module/sdk/Event.js.map +1 -0
  56. package/lib/module/sdk/Lifecycle.js +331 -0
  57. package/lib/module/sdk/Lifecycle.js.map +1 -0
  58. package/lib/module/sdk/LiveVoiceSdk.js +262 -268
  59. package/lib/module/sdk/LiveVoiceSdk.js.map +1 -1
  60. package/lib/module/sdk/LiveVoiceState.js +208 -40
  61. package/lib/module/sdk/LiveVoiceState.js.map +1 -1
  62. package/lib/module/sdk/LogEntries.js +99 -0
  63. package/lib/module/sdk/LogEntries.js.map +1 -0
  64. package/lib/module/sdk/Models.js +2 -0
  65. package/lib/module/{util/UIState.js.map → sdk/Models.js.map} +1 -1
  66. package/lib/module/{util/PlayingState.js → sdk/NativeSdkVersions.js} +9 -8
  67. package/lib/module/sdk/NativeSdkVersions.js.map +1 -0
  68. package/lib/module/sdk/Observables.js +391 -0
  69. package/lib/module/sdk/Observables.js.map +1 -0
  70. package/lib/module/sdk/Passwords.js +298 -0
  71. package/lib/module/sdk/Passwords.js.map +1 -0
  72. package/lib/module/sdk/Playback.js +35 -0
  73. package/lib/module/sdk/Playback.js.map +1 -0
  74. package/lib/module/specs/NativeLiveVoiceSdk.js.map +1 -1
  75. package/lib/module/util/Colors.js +2 -1
  76. package/lib/module/util/Colors.js.map +1 -1
  77. package/lib/module/util/Translations.js +34 -11
  78. package/lib/module/util/Translations.js.map +1 -1
  79. package/lib/module/util/freeze.js +26 -0
  80. package/lib/module/util/freeze.js.map +1 -0
  81. package/lib/module/util/logger.js +79 -41
  82. package/lib/module/util/logger.js.map +1 -1
  83. package/lib/typescript/src/components/BrandingView.d.ts +4 -0
  84. package/lib/typescript/src/components/BrandingView.d.ts.map +1 -1
  85. package/lib/typescript/src/components/ChannelView.d.ts +29 -3
  86. package/lib/typescript/src/components/ChannelView.d.ts.map +1 -1
  87. package/lib/typescript/src/components/ErrorView.d.ts +5 -3
  88. package/lib/typescript/src/components/ErrorView.d.ts.map +1 -1
  89. package/lib/typescript/src/components/LiveVoiceSpinner.d.ts +16 -0
  90. package/lib/typescript/src/components/LiveVoiceSpinner.d.ts.map +1 -0
  91. package/lib/typescript/src/components/LiveVoiceView.d.ts +81 -21
  92. package/lib/typescript/src/components/LiveVoiceView.d.ts.map +1 -1
  93. package/lib/typescript/src/components/PasswordPrompt.d.ts +13 -0
  94. package/lib/typescript/src/components/PasswordPrompt.d.ts.map +1 -0
  95. package/lib/typescript/src/components/PlayButtonView.d.ts +12 -329
  96. package/lib/typescript/src/components/PlayButtonView.d.ts.map +1 -1
  97. package/lib/typescript/src/components/ReconnectingView.d.ts +6 -3
  98. package/lib/typescript/src/components/ReconnectingView.d.ts.map +1 -1
  99. package/lib/typescript/src/index.d.ts +15 -6
  100. package/lib/typescript/src/index.d.ts.map +1 -1
  101. package/lib/typescript/src/sdk/Bridge.d.ts +36 -0
  102. package/lib/typescript/src/sdk/Bridge.d.ts.map +1 -0
  103. package/lib/typescript/src/sdk/Event.d.ts +97 -0
  104. package/lib/typescript/src/sdk/Event.d.ts.map +1 -0
  105. package/lib/typescript/src/sdk/Lifecycle.d.ts +191 -0
  106. package/lib/typescript/src/sdk/Lifecycle.d.ts.map +1 -0
  107. package/lib/typescript/src/sdk/LiveVoiceSdk.d.ts +195 -190
  108. package/lib/typescript/src/sdk/LiveVoiceSdk.d.ts.map +1 -1
  109. package/lib/typescript/src/sdk/LiveVoiceState.d.ts +77 -9
  110. package/lib/typescript/src/sdk/LiveVoiceState.d.ts.map +1 -1
  111. package/lib/typescript/src/sdk/LogEntries.d.ts +28 -0
  112. package/lib/typescript/src/sdk/LogEntries.d.ts.map +1 -0
  113. package/lib/typescript/src/sdk/Models.d.ts +114 -0
  114. package/lib/typescript/src/sdk/Models.d.ts.map +1 -0
  115. package/lib/typescript/src/sdk/NativeSdkVersions.d.ts +6 -0
  116. package/lib/typescript/src/sdk/NativeSdkVersions.d.ts.map +1 -0
  117. package/lib/typescript/src/sdk/Observables.d.ts +123 -0
  118. package/lib/typescript/src/sdk/Observables.d.ts.map +1 -0
  119. package/lib/typescript/src/sdk/Passwords.d.ts +72 -0
  120. package/lib/typescript/src/sdk/Passwords.d.ts.map +1 -0
  121. package/lib/typescript/src/sdk/Playback.d.ts +9 -0
  122. package/lib/typescript/src/sdk/Playback.d.ts.map +1 -0
  123. package/lib/typescript/src/specs/NativeLiveVoiceSdk.d.ts +34 -31
  124. package/lib/typescript/src/specs/NativeLiveVoiceSdk.d.ts.map +1 -1
  125. package/lib/typescript/src/util/Colors.d.ts.map +1 -1
  126. package/lib/typescript/src/util/Translations.d.ts +30 -8
  127. package/lib/typescript/src/util/Translations.d.ts.map +1 -1
  128. package/lib/typescript/src/util/freeze.d.ts +6 -0
  129. package/lib/typescript/src/util/freeze.d.ts.map +1 -0
  130. package/lib/typescript/src/util/logger.d.ts +17 -7
  131. package/lib/typescript/src/util/logger.d.ts.map +1 -1
  132. package/livevoice-sdk-react-native.podspec +29 -4
  133. package/package.json +12 -9
  134. package/src/components/BrandingView.tsx +42 -55
  135. package/src/components/ChannelView.tsx +329 -38
  136. package/src/components/ErrorView.tsx +9 -12
  137. package/src/components/LiveVoiceSpinner.tsx +87 -0
  138. package/src/components/LiveVoiceView.tsx +319 -201
  139. package/src/components/PasswordPrompt.tsx +144 -0
  140. package/src/components/PlayButtonView.tsx +165 -269
  141. package/src/components/ReconnectingView.tsx +28 -81
  142. package/src/icons/branding-ios.png +0 -0
  143. package/src/icons/camera-off-android.png +0 -0
  144. package/src/icons/camera-off-android@2x.png +0 -0
  145. package/src/icons/camera-off-android@3x.png +0 -0
  146. package/src/icons/cpu-android.png +0 -0
  147. package/src/icons/cpu-android@2x.png +0 -0
  148. package/src/icons/cpu-android@3x.png +0 -0
  149. package/src/icons/cpu-ios.png +0 -0
  150. package/src/icons/cpu-ios@2x.png +0 -0
  151. package/src/icons/cpu-ios@3x.png +0 -0
  152. package/src/icons/lock-android.png +0 -0
  153. package/src/icons/lock-android@2x.png +0 -0
  154. package/src/icons/lock-android@3x.png +0 -0
  155. package/src/icons/lock-ios.png +0 -0
  156. package/src/icons/lock-ios@2x.png +0 -0
  157. package/src/icons/lock-ios@3x.png +0 -0
  158. package/src/icons/mic-off-android.png +0 -0
  159. package/src/icons/mic-off-android@2x.png +0 -0
  160. package/src/icons/mic-off-android@3x.png +0 -0
  161. package/src/icons/mic-slash-ios.png +0 -0
  162. package/src/icons/mic-slash-ios@2x.png +0 -0
  163. package/src/icons/mic-slash-ios@3x.png +0 -0
  164. package/src/icons/video-slash-ios.png +0 -0
  165. package/src/icons/video-slash-ios@2x.png +0 -0
  166. package/src/icons/video-slash-ios@3x.png +0 -0
  167. package/src/index.tsx +92 -6
  168. package/src/sdk/Bridge.ts +259 -0
  169. package/src/sdk/Event.ts +187 -0
  170. package/src/sdk/Lifecycle.ts +366 -0
  171. package/src/sdk/LiveVoiceSdk.ts +285 -309
  172. package/src/sdk/LiveVoiceState.ts +230 -60
  173. package/src/sdk/LogEntries.ts +88 -0
  174. package/src/sdk/Models.ts +129 -0
  175. package/src/{util/PlayingState.ts → sdk/NativeSdkVersions.ts} +7 -6
  176. package/src/sdk/Observables.ts +414 -0
  177. package/src/sdk/Passwords.ts +286 -0
  178. package/src/sdk/Playback.ts +30 -0
  179. package/src/specs/NativeLiveVoiceSdk.ts +42 -38
  180. package/src/util/Colors.ts +2 -1
  181. package/src/util/Translations.ts +34 -12
  182. package/src/util/freeze.ts +23 -0
  183. package/src/util/logger.ts +79 -52
  184. package/lib/module/components/AudioOutputSwitchView.js +0 -138
  185. package/lib/module/components/AudioOutputSwitchView.js.map +0 -1
  186. package/lib/module/components/index.js +0 -24
  187. package/lib/module/components/index.js.map +0 -1
  188. package/lib/module/icons/mic.png +0 -0
  189. package/lib/module/util/ForegroundServiceConfig.js +0 -38
  190. package/lib/module/util/ForegroundServiceConfig.js.map +0 -1
  191. package/lib/module/util/PlayingState.js.map +0 -1
  192. package/lib/module/util/UIState.js +0 -4
  193. package/lib/typescript/src/components/AudioOutputSwitchView.d.ts +0 -6
  194. package/lib/typescript/src/components/AudioOutputSwitchView.d.ts.map +0 -1
  195. package/lib/typescript/src/components/index.d.ts +0 -9
  196. package/lib/typescript/src/components/index.d.ts.map +0 -1
  197. package/lib/typescript/src/util/ForegroundServiceConfig.d.ts +0 -19
  198. package/lib/typescript/src/util/ForegroundServiceConfig.d.ts.map +0 -1
  199. package/lib/typescript/src/util/PlayingState.d.ts +0 -7
  200. package/lib/typescript/src/util/PlayingState.d.ts.map +0 -1
  201. package/lib/typescript/src/util/UIState.d.ts +0 -86
  202. package/lib/typescript/src/util/UIState.d.ts.map +0 -1
  203. package/src/components/AudioOutputSwitchView.tsx +0 -146
  204. package/src/components/index.tsx +0 -21
  205. package/src/icons/mic.png +0 -0
  206. package/src/util/ForegroundServiceConfig.tsx +0 -42
  207. package/src/util/UIState.ts +0 -106
@@ -0,0 +1,187 @@
1
+ //===----------------------------------------------------------------------===//
2
+ //
3
+ // This source file is part of the LiveVoice SDK project
4
+ //
5
+ // Copyright (c) LiveVoice GmbH
6
+ // Licensed under the MIT license
7
+ //
8
+ // See LICENSE for license information
9
+ //
10
+ // SPDX-License-Identifier: MIT
11
+ //
12
+ //===----------------------------------------------------------------------===//
13
+
14
+ // The joined event, its requestable languages and its linked events (bridge.md 2.9 to 2.11, 3.3).
15
+ // The lists need the custom-UI permission of the joined key, and so do their commands; native
16
+ // decides both. Their values are observed through Observables.ts.
17
+
18
+ import { awaitRevisions, record } from './Bridge';
19
+ import { invoke, usageError } from './Lifecycle';
20
+
21
+ /** An event's colours, `'#RRGGBB'`, for the light and the dark appearance. */
22
+ export type LiveVoiceBrandColors = {
23
+ light: string;
24
+ dark: string;
25
+ };
26
+
27
+ /** The joined event. */
28
+ export type LiveVoiceEvent = {
29
+ eventId: number;
30
+ name: string;
31
+ /** `null` for an event without branding. */
32
+ brandColors: LiveVoiceBrandColors | null;
33
+ };
34
+
35
+ /**
36
+ * Where a requestable language stands:
37
+ * - `requestable`: it can be requested.
38
+ * - `requested`: a request is on its way, or the server confirmed or accepted it and its channel
39
+ * has not arrived yet. Requests of other listeners count.
40
+ * - `available`: an AI translation of the channel the requests translate exists in that
41
+ * language. A channel translating another channel does not count.
42
+ * - `unavailable`: the event excludes it, because it is spoken on the channel the requests
43
+ * translate.
44
+ */
45
+ export type LiveVoiceLanguageRequestState = 'requestable' | 'requested' | 'available' | 'unavailable';
46
+
47
+ /** A language listeners can ask the event to add. */
48
+ export type LiveVoiceRequestableLanguage = {
49
+ languageCode: string;
50
+ /** The language's name in the device's language. */
51
+ localizedName: string;
52
+ /** The language's name in itself. */
53
+ autonym: string;
54
+ state: LiveVoiceLanguageRequestState;
55
+ };
56
+
57
+ /** An event linked to the joined one, to switch to with {@link switchToLinkedEvent}. */
58
+ export type LiveVoiceLinkedEvent = {
59
+ eventId: number;
60
+ name: string;
61
+ /** The event's join code; it is not secret. */
62
+ joinCode: string;
63
+ };
64
+
65
+ /**
66
+ * Asks the event to add a language and resolves once the server confirmed the request.
67
+ *
68
+ * The language shows `requested` in {@link getCurrentRequestableLanguages} shortly after, and
69
+ * what happens next shows there too. It never starts playback. Needs a `ready` connection and an
70
+ * API key that permits custom UI.
71
+ *
72
+ * @param languageCode - The `languageCode` of a language in state `requestable`.
73
+ * @throws {LiveVoiceError} `not_joined` unless the connection is `ready`; `api_key_invalid`
74
+ * without the custom-UI permission; `invalid_argument` for a code that is unknown or not
75
+ * requestable (also one already requested); `timed_out` when the server does not confirm within
76
+ * 10 seconds (the request may still exist); `network_failed`; `cancelled` when a leave, a new
77
+ * join or a switch ended it; `generic` with `detail.reason` `language_request_declined` or
78
+ * `language_request_failed`. See {@link LiveVoiceErrorCode}.
79
+ */
80
+ export async function requestLanguage(languageCode: string): Promise<void> {
81
+ await invoke('requestLanguage', { languageCode: validCode(languageCode, 'requestLanguage') });
82
+ }
83
+
84
+ /**
85
+ * Withdraws the request for a language and resolves once the server confirmed the cancellation.
86
+ *
87
+ * The language shows `requestable` in {@link getCurrentRequestableLanguages} shortly after. A
88
+ * second cancellation of the same language waits for the first. Needs a `ready` connection and
89
+ * an API key that permits custom UI.
90
+ *
91
+ * @param languageCode - The `languageCode` of a language in state `requested`.
92
+ * @throws {LiveVoiceError} `not_joined` unless the connection is `ready`; `api_key_invalid`
93
+ * without the custom-UI permission; `invalid_argument` for a code that is unknown or not
94
+ * requested; `command_in_progress` while your own request for it is still being sent; `generic`
95
+ * with `detail.reason` `language_request_resolved` when the server decided first; `timed_out`
96
+ * when the server does not confirm within 10 seconds; `network_failed`; `cancelled` when a leave,
97
+ * a new join or a switch ended it; otherwise as {@link requestLanguage}. See
98
+ * {@link LiveVoiceErrorCode}.
99
+ */
100
+ export async function cancelLanguageRequest(languageCode: string): Promise<void> {
101
+ await invoke('cancelLanguageRequest', { languageCode: validCode(languageCode, 'cancelLanguageRequest') });
102
+ }
103
+
104
+ /**
105
+ * Switches to a linked event and resolves once it is ready, with the same guarantees as
106
+ * `joinEvent`. Needs a `ready` connection and an API key that permits custom UI.
107
+ *
108
+ * When the promise resolves, the observed values already show the linked event, or the result of
109
+ * a newer call. Until then the connection is `joining` and the current event and its lists are
110
+ * `null`. After a completed switch the joined event stays valid: its `leave()` leaves the linked
111
+ * event. A leave while the switch is pending ends it with `cancelled` and leaves the event.
112
+ *
113
+ * A failed switch does not return to the previous event: the connection is `failed`, and
114
+ * `reconnect()` tries the linked event again if the error is retryable. The event is not checked
115
+ * against the linked events, so any event you have a join code for works.
116
+ *
117
+ * @param event - The event to switch to, usually one of {@link getCurrentLinkedEvents}.
118
+ * @throws {LiveVoiceError} `not_joined` when no event is ready and no switch is pending, also
119
+ * while reconnecting (the reconnect continues); `api_key_invalid` without the custom-UI
120
+ * permission; `superseded` when a newer switch or join replaced it; `cancelled` when a leave
121
+ * ended it; `timed_out` when the linked event was not ready within 30 seconds; otherwise why the
122
+ * join failed, such as `event_not_found`. See {@link LiveVoiceErrorCode}.
123
+ */
124
+ export async function switchToLinkedEvent(event: LiveVoiceLinkedEvent): Promise<void> {
125
+ if (event == null || typeof event !== 'object' ||
126
+ typeof event.eventId !== 'number' || !Number.isSafeInteger(event.eventId) || event.eventId <= 0 ||
127
+ typeof event.name !== 'string' || typeof event.joinCode !== 'string' || !event.joinCode.trim()) {
128
+ throw usageError('invalid_argument', 'switchToLinkedEvent',
129
+ 'A linked event needs a positive event id, a name and a non-empty join code.');
130
+ }
131
+ const reply = await invoke('switchToLinkedEvent', {
132
+ eventId: event.eventId,
133
+ name: event.name,
134
+ joinCode: event.joinCode,
135
+ });
136
+ // When the switch resolves, the values already show the linked event (18 item 110).
137
+ await awaitRevisions(record(reply) ? reply.revisions : undefined);
138
+ }
139
+
140
+ function validCode(languageCode: string, operation: string): string {
141
+ if (typeof languageCode !== 'string' || !languageCode.trim()) {
142
+ throw usageError('invalid_argument', operation, 'A language code is a non-empty string.');
143
+ }
144
+ return languageCode;
145
+ }
146
+
147
+ // The wire's values (bridge.md 2.9 to 2.11). Each decoder throws for a value it cannot read, so the
148
+ // last good value stays.
149
+
150
+ export function decodeEvent(wire: unknown): LiveVoiceEvent | null {
151
+ if (wire === null) return null;
152
+ if (!record(wire) || typeof wire.eventId !== 'number' || typeof wire.name !== 'string') throw new TypeError('currentEvent');
153
+ const colors = wire.brandColors;
154
+ return {
155
+ eventId: wire.eventId,
156
+ name: wire.name,
157
+ brandColors: record(colors) && typeof colors.light === 'string' && typeof colors.dark === 'string'
158
+ ? { light: colors.light, dark: colors.dark }
159
+ : null,
160
+ };
161
+ }
162
+
163
+ const languageStates: readonly string[] = ['requestable', 'requested', 'available', 'unavailable'];
164
+
165
+ export function decodeLanguages(wire: unknown): LiveVoiceRequestableLanguage[] | null {
166
+ if (wire === null) return null;
167
+ if (!Array.isArray(wire)) throw new TypeError('requestableLanguages');
168
+ return wire.filter(record).flatMap(language =>
169
+ typeof language.languageCode === 'string' && typeof language.localizedName === 'string' &&
170
+ typeof language.autonym === 'string' && typeof language.state === 'string' && languageStates.includes(language.state)
171
+ ? [{
172
+ languageCode: language.languageCode,
173
+ localizedName: language.localizedName,
174
+ autonym: language.autonym,
175
+ state: language.state as LiveVoiceLanguageRequestState,
176
+ }]
177
+ : []);
178
+ }
179
+
180
+ export function decodeLinkedEvents(wire: unknown): LiveVoiceLinkedEvent[] | null {
181
+ if (wire === null) return null;
182
+ if (!Array.isArray(wire)) throw new TypeError('linkedEvents');
183
+ return wire.filter(record).flatMap(event =>
184
+ typeof event.eventId === 'number' && typeof event.name === 'string' && typeof event.joinCode === 'string'
185
+ ? [{ eventId: event.eventId, name: event.name, joinCode: event.joinCode }]
186
+ : []);
187
+ }
@@ -0,0 +1,366 @@
1
+ //===----------------------------------------------------------------------===//
2
+ //
3
+ // This source file is part of the LiveVoice SDK project
4
+ //
5
+ // Copyright (c) LiveVoice GmbH
6
+ // Licensed under the MIT license
7
+ //
8
+ // See LICENSE for license information
9
+ //
10
+ // SPDX-License-Identifier: MIT
11
+ //
12
+ //===----------------------------------------------------------------------===//
13
+
14
+ import Native from '../specs/NativeLiveVoiceSdk';
15
+ import { logDecodeError, logInfo, LiveVoiceLogEvent, writeLogEntry } from '../util/logger';
16
+ import { awaitRevisions, errorMessage, isInitialized, record as object } from './Bridge';
17
+
18
+ /** Every {@link LiveVoiceErrorCode}, for example to check a value at runtime. */
19
+ export const liveVoiceErrorCodes = [
20
+ 'not_initialized',
21
+ 'not_joined',
22
+ 'invalid_argument',
23
+ 'superseded',
24
+ 'cancelled',
25
+ 'timed_out',
26
+ 'leave_incomplete',
27
+ 'command_in_progress',
28
+ 'api_key_invalid',
29
+ 'event_not_found',
30
+ 'event_inactive',
31
+ 'wrong_password',
32
+ 'listener_limit_reached',
33
+ 'network_failed',
34
+ 'no_network',
35
+ 'generic',
36
+ 'password_required',
37
+ 'unsupported_sdk',
38
+ 'channel_password_required',
39
+ 'channel_wrong_password',
40
+ 'channel_limit_reached',
41
+ 'channel_unavailable',
42
+ 'channel_forbidden',
43
+ 'channel_offline',
44
+ ] as const;
45
+
46
+ /**
47
+ * What went wrong, the same codes on every platform. Each call names the codes specific to it.
48
+ *
49
+ * Commands:
50
+ * - `not_initialized`: a call that needs `initialize()` was made before it resolved. Reading
51
+ * values, adding listeners and some setters work before it.
52
+ * - `invalid_argument`: an argument is malformed, or not allowed in the current state.
53
+ * - `not_joined`: the connection is not in a state the call allows; most calls need `ready`.
54
+ * - `superseded`: a newer call replaced a `joinEvent`, `reconnect` or `switchToLinkedEvent`. No
55
+ * other call fails with it.
56
+ * - `cancelled`: a leave, a newer command or a new join ended the call. Like `superseded` it
57
+ * needs no message to the user.
58
+ * - `timed_out`: no result within 30 seconds (join, switch, reconnect) or 10 seconds (a start or
59
+ * stop of playback, a subtitle start, the language calls).
60
+ * - `leave_incomplete`: local cleanup or an earlier stop has not finished within its deadline of
61
+ * 5 seconds. It comes from a leave (the event is left all the same), from a stop of playback
62
+ * while joining or failed, and from a start waiting behind an unfinished stop, which can be a
63
+ * stop in the current event. The cleanup is never abandoned; it continues.
64
+ * - `command_in_progress`: the same command is still running: an identical subtitle start, or
65
+ * the request a cancellation is meant to withdraw.
66
+ *
67
+ * Joining: `api_key_invalid` (also when the key does not permit custom UI, for a custom cell,
68
+ * `switchToLinkedEvent` and the language calls), `event_not_found`, `event_inactive`,
69
+ * `password_required` (no password was given), `wrong_password` (one was given and rejected),
70
+ * `listener_limit_reached`, `network_failed` (the connection failed or was lost, also before a
71
+ * call could reach the server), `no_network`, `unsupported_sdk` (the server requires a newer SDK,
72
+ * or the installed native SDK is not the version this package was built for), `generic` (see
73
+ * `detail.reason`).
74
+ *
75
+ * Channels and subtitles: `channel_password_required`, `channel_wrong_password`,
76
+ * `channel_limit_reached` (`detail.limitReason` is `participant` or `viewer`), `channel_offline`
77
+ * (a start of playback only; an offline channel's subtitles can be started),
78
+ * `channel_unavailable` (not part of the event, without audio, or a start of playback while
79
+ * reconnecting), `channel_forbidden`.
80
+ */
81
+ export type LiveVoiceErrorCode = typeof liveVoiceErrorCodes[number];
82
+
83
+ /** Optional details of an error. */
84
+ export type LiveVoiceErrorDetail = {
85
+ /** The HTTP status of a failed request. */
86
+ httpStatus?: number;
87
+ /** The platform's own error code. */
88
+ platformCode?: number;
89
+ /** Which limit was reached. */
90
+ limitReason?: string;
91
+ /** A finer reason within the code, such as `stop_failed`. */
92
+ reason?: string;
93
+ };
94
+
95
+ /** The codes worth trying again: the cause can go away by itself or with the user's help. */
96
+ const retryableCodes: ReadonlySet<LiveVoiceErrorCode> = new Set<LiveVoiceErrorCode>([
97
+ 'timed_out',
98
+ 'event_inactive',
99
+ 'wrong_password',
100
+ 'password_required',
101
+ 'listener_limit_reached',
102
+ 'network_failed',
103
+ 'no_network',
104
+ 'channel_password_required',
105
+ 'channel_wrong_password',
106
+ 'channel_limit_reached',
107
+ 'channel_offline',
108
+ ]);
109
+
110
+ function knownCode(value: unknown): value is LiveVoiceErrorCode {
111
+ return typeof value === 'string' && (liveVoiceErrorCodes as readonly string[]).includes(value);
112
+ }
113
+
114
+ function typedDetail(value: unknown): LiveVoiceErrorDetail {
115
+ if (!object(value)) return {};
116
+ const detail: LiveVoiceErrorDetail = {};
117
+ if (typeof value.httpStatus === 'number') detail.httpStatus = value.httpStatus;
118
+ if (typeof value.platformCode === 'number') detail.platformCode = value.platformCode;
119
+ if (typeof value.limitReason === 'string') detail.limitReason = value.limitReason;
120
+ if (typeof value.reason === 'string') detail.reason = value.reason;
121
+ return detail;
122
+ }
123
+
124
+ function wireError(value: unknown): LiveVoiceError {
125
+ if (!object(value) || !knownCode(value.code)) {
126
+ return new LiveVoiceError('generic', { detail: { reason: 'unknown_native_error' } });
127
+ }
128
+ return new LiveVoiceError(value.code, {
129
+ detail: typedDetail(value.detail),
130
+ message: typeof value.message === 'string' ? value.message : null,
131
+ });
132
+ }
133
+
134
+ /**
135
+ * The error every LiveVoice call rejects with, and the one a `failed` connection carries. Its
136
+ * `message` is localised text to show as is. Codes only a developer can fix (`invalid_argument`,
137
+ * `not_initialized`, `api_key_invalid`, `unsupported_sdk`) share a generic text; the SDK log
138
+ * explains them.
139
+ */
140
+ export class LiveVoiceError extends Error {
141
+ /** What went wrong; stable, for your own handling. */
142
+ readonly code: LiveVoiceErrorCode;
143
+ /** Whether trying again can succeed; it follows from the code. */
144
+ readonly isRetryable: boolean;
145
+ /** Optional details, `{}` when there are none. */
146
+ readonly detail: LiveVoiceErrorDetail;
147
+
148
+ /**
149
+ * Creates an error, for tests and previews.
150
+ *
151
+ * @param code - What went wrong; `isRetryable` follows from it.
152
+ * @param options - `detail`: extra information for some codes. `message`: the text to show;
153
+ * leave it out or pass `null` for the code's localised text.
154
+ */
155
+ constructor(
156
+ code: LiveVoiceErrorCode,
157
+ options: { detail?: LiveVoiceErrorDetail; message?: string | null } = {},
158
+ ) {
159
+ super(options?.message ?? (errorMessage(code) || code));
160
+ this.name = 'LiveVoiceError';
161
+ this.code = code;
162
+ this.isRetryable = retryableCodes.has(code);
163
+ this.detail = Object.freeze(typedDetail(options?.detail));
164
+ }
165
+ }
166
+
167
+ /** When the next reconnect attempt runs. */
168
+ export type LiveVoiceRetry =
169
+ | { kind: 'inProgress' }
170
+ | { kind: 'scheduled'; at: Date };
171
+
172
+ /**
173
+ * The connection to the event:
174
+ * - `idle`: nothing is joined or joining; also before `initialize()`.
175
+ * - `joining`: a join, a switch to a linked event, or the retry of a failed join is in progress.
176
+ * - `ready`: the event `eventId` is joined.
177
+ * - `reconnecting`: the connection was lost and is recovering; see `retry`. A `reconnect()` that
178
+ * times out leaves it here, and recovery continues.
179
+ * - `leaving`: a leave is running.
180
+ * - `failed`: a join, a switch or the retry of a join failed, or the joined event ended, with
181
+ * `error`. The join is kept: `reconnect()` retries it if the error is retryable, and
182
+ * `stopChannel` and `stopSubtitles` still work. It stays until that retry, a new join or a
183
+ * leave.
184
+ *
185
+ * Use it for display. To know that a call completed, await the call.
186
+ */
187
+ export type LiveVoiceConnection =
188
+ | { status: 'idle' | 'joining' | 'leaving' }
189
+ | { status: 'ready'; eventId: number }
190
+ | { status: 'reconnecting'; eventId: number; retry: LiveVoiceRetry }
191
+ | { status: 'failed'; error: LiveVoiceError };
192
+
193
+ /** What `joinEvent` joins with. */
194
+ export type LiveVoiceJoinRequest = {
195
+ /**
196
+ * The code listeners join the event with: six characters, digits and the letters
197
+ * `ABCDEFGHJKLMNPQRST`, in either case.
198
+ */
199
+ joinCode: string;
200
+ /**
201
+ * The event's password, if it has one. A password you pass is final: a wrong one fails with
202
+ * `wrong_password` without a prompt. Without one, a protected event's password comes from the
203
+ * SDK's memory, the password store, then the password provider or the built-in prompt.
204
+ */
205
+ password?: string | null;
206
+ /** Your API key, from your LiveVoice account page. */
207
+ apiKey: string;
208
+ };
209
+
210
+ /**
211
+ * The joined event `joinEvent` returns. It follows a completed switch to a linked event.
212
+ *
213
+ * Its `leave()` leaves only the join this came from, including a linked event it switched to; it
214
+ * can never leave a newer join. If a newer join replaced its join, it does nothing and resolves at
215
+ * once. Otherwise it resolves as `leaveEvent` does: the event's local cleanup has ended, and the
216
+ * observed connection is `idle` unless a newer join exists. If its join was already left, it
217
+ * waits for that leave's cleanup.
218
+ *
219
+ * `leave()` rejects with a {@link LiveVoiceError} `leave_incomplete` when the cleanup has not
220
+ * finished within 5 seconds; the event is left all the same and the cleanup continues. Another
221
+ * leave then waits for the same cleanup and can fail with `leave_incomplete` again.
222
+ */
223
+ export type LiveVoiceJoinedEvent = { leave(): Promise<void> };
224
+
225
+ export function normalizeError(error: unknown): LiveVoiceError {
226
+ if (error instanceof LiveVoiceError) return error;
227
+ const native = object(error) ? error : {};
228
+ try {
229
+ const wire: unknown = JSON.parse(typeof native.message === 'string' ? native.message : '');
230
+ if (object(wire) && typeof wire.code === 'string') return wireError(wire);
231
+ } catch { /* Non-SDK failures retain a stable fallback. */ }
232
+ return wireError(native);
233
+ }
234
+
235
+ /**
236
+ * A developer-only error the wrapper throws itself (bridge.md 3.6): its message is the generic
237
+ * text, and its explanation, a fixed sentence without argument values, goes to the SDK log as
238
+ * `LV_USAGE_ERROR`.
239
+ */
240
+ export function usageError(
241
+ code: 'invalid_argument' | 'not_initialized',
242
+ operation: string,
243
+ explanation: string,
244
+ ): LiveVoiceError {
245
+ writeLogEntry('LV_USAGE_ERROR', 'error', { code, operation, explanation });
246
+ return new LiveVoiceError(code);
247
+ }
248
+
249
+ /** The public call behind each command, for the log. */
250
+ const operations: Record<string, string> = { join: 'joinEvent', leave: 'leaveEvent' };
251
+
252
+ /**
253
+ * Runs `command` natively. Before `initialize()` it fails with `not_initialized` without reaching
254
+ * native, the only error the wrapper owns (bridge.md 3.1). A reply that is not JSON resolves as
255
+ * `undefined`: native succeeded, so the call does too.
256
+ */
257
+ export async function invoke(command: string, args: Record<string, unknown> = {}): Promise<unknown> {
258
+ if (!isInitialized()) {
259
+ throw usageError('not_initialized', operations[command] ?? command, 'Call initialize() and await it first.');
260
+ }
261
+ let reply: string;
262
+ try { reply = await Native.execute(command, JSON.stringify(args)); }
263
+ catch (error) { throw normalizeError(error); }
264
+ try { return JSON.parse(reply); }
265
+ catch {
266
+ logDecodeError('reply', command);
267
+ return undefined;
268
+ }
269
+ }
270
+
271
+ export async function join(request: LiveVoiceJoinRequest): Promise<LiveVoiceJoinedEvent> {
272
+ if (!request || typeof request.joinCode !== 'string' || !request.joinCode.trim() ||
273
+ typeof request.apiKey !== 'string' || !request.apiKey.trim() ||
274
+ (request.password != null && typeof request.password !== 'string')) {
275
+ throw usageError('invalid_argument', 'joinEvent',
276
+ 'The join request needs a non-empty join code and API key, and a password that is a string or null.');
277
+ }
278
+ logInfo(LiveVoiceLogEvent.joinRequest, { joinCode: request.joinCode, hasPassword: request.password != null });
279
+ const result = await invoke('join', { joinCode: request.joinCode, password: request.password, apiKey: request.apiKey });
280
+ if (!object(result) || typeof result.entryId !== 'string' || !result.entryId.trim()) {
281
+ logDecodeError('reply', 'join');
282
+ throw new LiveVoiceError('generic', { detail: { reason: 'invalid_join_receipt' } });
283
+ }
284
+ const { entryId } = result;
285
+ // When joinEvent() resolves, the values already show the joined event (18 item 110).
286
+ await awaitRevisions(result.revisions);
287
+ let leaving: Promise<void> | undefined;
288
+ return Object.freeze({
289
+ // When leave() resolves, the values already show what it left behind, as after a join.
290
+ leave: () => leaving ??= invoke('leave', { entryId }).then(
291
+ reply => awaitRevisions(object(reply) ? reply.revisions : undefined),
292
+ error => {
293
+ leaving = undefined;
294
+ throw error;
295
+ },
296
+ ),
297
+ });
298
+ }
299
+
300
+ export function channelId(id: number, operation: string): number {
301
+ if (!Number.isSafeInteger(id) || id <= 0) {
302
+ throw usageError('invalid_argument', operation, 'A channel id is a positive safe integer.');
303
+ }
304
+ return id;
305
+ }
306
+
307
+ /** A retry as the cache keeps it: the time in milliseconds, so every delivery gets its own `Date`. */
308
+ export type RetryValue = { kind: 'inProgress' } | { kind: 'scheduled'; at: number };
309
+
310
+ /** The connection as the cache keeps it, with the retry time in milliseconds. */
311
+ export type ConnectionValue =
312
+ | { status: 'idle' | 'joining' | 'leaving' }
313
+ | { status: 'ready'; eventId: number }
314
+ | { status: 'reconnecting'; eventId: number; retry: RetryValue }
315
+ | { status: 'failed'; error: LiveVoiceError };
316
+
317
+ /** The wire's retry, or `undefined` when it is malformed. */
318
+ export function decodeRetry(wire: unknown): RetryValue | undefined {
319
+ if (object(wire) && wire.kind === 'inProgress') return { kind: 'inProgress' };
320
+ if (object(wire) && wire.kind === 'scheduled' && typeof wire.at === 'number' && Number.isSafeInteger(wire.at)) {
321
+ return { kind: 'scheduled', at: wire.at };
322
+ }
323
+ return undefined;
324
+ }
325
+
326
+ /** A public retry, with a `Date` of its own. */
327
+ export function publicRetry(retry: RetryValue): LiveVoiceRetry {
328
+ return retry.kind === 'scheduled' ? { kind: 'scheduled', at: new Date(retry.at) } : { kind: 'inProgress' };
329
+ }
330
+
331
+ /** The wire's error as a `LiveVoiceError`; anything else becomes `generic`. */
332
+ export function decodeError(wire: unknown): LiveVoiceError {
333
+ return wireError(wire);
334
+ }
335
+
336
+ /** The wire's connection (bridge.md 2.3); throws for one it cannot read. */
337
+ export function decodeConnection(wire: unknown): ConnectionValue {
338
+ if (!object(wire)) throw new LiveVoiceError('generic');
339
+ switch (wire.status) {
340
+ case 'idle': case 'joining': case 'leaving':
341
+ return { status: wire.status };
342
+ case 'ready': case 'reconnecting': {
343
+ const eventId = wire.eventId;
344
+ if (typeof eventId !== 'number' || !Number.isSafeInteger(eventId) || eventId <= 0) throw new LiveVoiceError('generic');
345
+ if (wire.status === 'ready') return { status: 'ready', eventId };
346
+ const retry = decodeRetry(wire.retry);
347
+ if (retry === undefined) throw new LiveVoiceError('generic');
348
+ return { status: 'reconnecting', eventId, retry };
349
+ }
350
+ case 'failed':
351
+ return { status: 'failed', error: wireError(wire.error) };
352
+ default:
353
+ throw new LiveVoiceError('generic');
354
+ }
355
+ }
356
+
357
+ /**
358
+ * The public connection. A scheduled retry gets a `Date` of its own on every call, so changing one
359
+ * changes no other; every other connection is the cached value itself.
360
+ */
361
+ export function publicConnection(value: ConnectionValue): LiveVoiceConnection {
362
+ if (value.status === 'reconnecting' && value.retry.kind === 'scheduled') {
363
+ return Object.freeze({ ...value, retry: Object.freeze(publicRetry(value.retry)) });
364
+ }
365
+ return value as LiveVoiceConnection;
366
+ }