@incodetech/core 2.0.0-alpha.2 → 2.0.0-alpha.3

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 (134) hide show
  1. package/package.json +4 -1
  2. package/.turbo/turbo-build.log +0 -33
  3. package/.turbo/turbo-coverage.log +0 -22
  4. package/.turbo/turbo-format.log +0 -6
  5. package/.turbo/turbo-lint$colon$fix.log +0 -77
  6. package/.turbo/turbo-lint.log +0 -95
  7. package/.turbo/turbo-test.log +0 -870
  8. package/.turbo/turbo-typecheck.log +0 -5
  9. package/coverage/base.css +0 -224
  10. package/coverage/block-navigation.js +0 -87
  11. package/coverage/favicon.png +0 -0
  12. package/coverage/index.html +0 -221
  13. package/coverage/prettify.css +0 -1
  14. package/coverage/prettify.js +0 -2
  15. package/coverage/sort-arrow-sprite.png +0 -0
  16. package/coverage/sorter.js +0 -210
  17. package/coverage/src/camera/cameraService.ts.html +0 -580
  18. package/coverage/src/camera/cameraServices.ts.html +0 -163
  19. package/coverage/src/camera/cameraStateMachine.ts.html +0 -877
  20. package/coverage/src/camera/index.html +0 -146
  21. package/coverage/src/email/emailActor.ts.html +0 -130
  22. package/coverage/src/email/emailManager.ts.html +0 -1366
  23. package/coverage/src/email/emailStateMachine.ts.html +0 -1186
  24. package/coverage/src/email/index.html +0 -146
  25. package/coverage/src/flow/flowActor.ts.html +0 -124
  26. package/coverage/src/flow/flowAnalyzer.ts.html +0 -196
  27. package/coverage/src/flow/flowManager.ts.html +0 -790
  28. package/coverage/src/flow/flowServices.ts.html +0 -124
  29. package/coverage/src/flow/flowStateMachine.ts.html +0 -631
  30. package/coverage/src/flow/index.html +0 -221
  31. package/coverage/src/flow/moduleLoader.ts.html +0 -304
  32. package/coverage/src/flow/orchestratedFlowManager.ts.html +0 -778
  33. package/coverage/src/flow/orchestratedFlowStateMachine.ts.html +0 -1060
  34. package/coverage/src/http/api.ts.html +0 -355
  35. package/coverage/src/http/endpoints.ts.html +0 -136
  36. package/coverage/src/http/index.html +0 -131
  37. package/coverage/src/index.html +0 -116
  38. package/coverage/src/phone/index.html +0 -146
  39. package/coverage/src/phone/phoneActor.ts.html +0 -130
  40. package/coverage/src/phone/phoneManager.ts.html +0 -1459
  41. package/coverage/src/phone/phoneStateMachine.ts.html +0 -1351
  42. package/coverage/src/recordings/index.html +0 -116
  43. package/coverage/src/recordings/recordingsRepository.ts.html +0 -229
  44. package/coverage/src/selfie/index.html +0 -191
  45. package/coverage/src/selfie/selfieActor.ts.html +0 -136
  46. package/coverage/src/selfie/selfieErrorUtils.ts.html +0 -283
  47. package/coverage/src/selfie/selfieManager.ts.html +0 -988
  48. package/coverage/src/selfie/selfieStateMachine.ts.html +0 -2497
  49. package/coverage/src/selfie/selfieUploadService.ts.html +0 -328
  50. package/coverage/src/selfie/types.ts.html +0 -394
  51. package/coverage/src/setup.ts.html +0 -598
  52. package/src/camera/cameraActor.ts +0 -21
  53. package/src/camera/cameraService.test.ts +0 -437
  54. package/src/camera/cameraService.ts +0 -165
  55. package/src/camera/cameraServices.test.ts +0 -66
  56. package/src/camera/cameraServices.ts +0 -26
  57. package/src/camera/cameraStateMachine.test.ts +0 -602
  58. package/src/camera/cameraStateMachine.ts +0 -264
  59. package/src/camera/index.ts +0 -5
  60. package/src/camera/types.ts +0 -17
  61. package/src/device/getBrowser.ts +0 -31
  62. package/src/device/getDeviceClass.ts +0 -29
  63. package/src/device/index.ts +0 -2
  64. package/src/email/__mocks__/emailMocks.ts +0 -59
  65. package/src/email/emailActor.ts +0 -15
  66. package/src/email/emailManager.test.ts +0 -573
  67. package/src/email/emailManager.ts +0 -427
  68. package/src/email/emailServices.ts +0 -66
  69. package/src/email/emailStateMachine.test.ts +0 -741
  70. package/src/email/emailStateMachine.ts +0 -367
  71. package/src/email/index.ts +0 -39
  72. package/src/email/types.ts +0 -60
  73. package/src/events/addEvent.ts +0 -20
  74. package/src/events/types.ts +0 -7
  75. package/src/flow/__mocks__/flowMocks.ts +0 -84
  76. package/src/flow/flowActor.ts +0 -13
  77. package/src/flow/flowAnalyzer.test.ts +0 -266
  78. package/src/flow/flowAnalyzer.ts +0 -37
  79. package/src/flow/flowCompletionService.ts +0 -21
  80. package/src/flow/flowManager.test.ts +0 -560
  81. package/src/flow/flowManager.ts +0 -235
  82. package/src/flow/flowServices.test.ts +0 -109
  83. package/src/flow/flowServices.ts +0 -13
  84. package/src/flow/flowStateMachine.test.ts +0 -334
  85. package/src/flow/flowStateMachine.ts +0 -182
  86. package/src/flow/index.ts +0 -21
  87. package/src/flow/moduleLoader.test.ts +0 -136
  88. package/src/flow/moduleLoader.ts +0 -73
  89. package/src/flow/orchestratedFlowManager.test.ts +0 -240
  90. package/src/flow/orchestratedFlowManager.ts +0 -231
  91. package/src/flow/orchestratedFlowStateMachine.test.ts +0 -199
  92. package/src/flow/orchestratedFlowStateMachine.ts +0 -325
  93. package/src/flow/types.ts +0 -434
  94. package/src/http/__mocks__/api.ts +0 -88
  95. package/src/http/api.test.ts +0 -231
  96. package/src/http/api.ts +0 -90
  97. package/src/http/endpoints.ts +0 -17
  98. package/src/index.ts +0 -33
  99. package/src/permissions/index.ts +0 -2
  100. package/src/permissions/permissionServices.ts +0 -31
  101. package/src/permissions/types.ts +0 -3
  102. package/src/phone/__mocks__/phoneMocks.ts +0 -71
  103. package/src/phone/index.ts +0 -39
  104. package/src/phone/phoneActor.ts +0 -15
  105. package/src/phone/phoneManager.test.ts +0 -393
  106. package/src/phone/phoneManager.ts +0 -458
  107. package/src/phone/phoneServices.ts +0 -98
  108. package/src/phone/phoneStateMachine.test.ts +0 -918
  109. package/src/phone/phoneStateMachine.ts +0 -422
  110. package/src/phone/types.ts +0 -83
  111. package/src/recordings/recordingsRepository.test.ts +0 -87
  112. package/src/recordings/recordingsRepository.ts +0 -48
  113. package/src/recordings/streamingEvents.ts +0 -10
  114. package/src/selfie/__mocks__/selfieMocks.ts +0 -26
  115. package/src/selfie/index.ts +0 -14
  116. package/src/selfie/selfieActor.ts +0 -17
  117. package/src/selfie/selfieErrorUtils.test.ts +0 -116
  118. package/src/selfie/selfieErrorUtils.ts +0 -66
  119. package/src/selfie/selfieManager.test.ts +0 -297
  120. package/src/selfie/selfieManager.ts +0 -301
  121. package/src/selfie/selfieServices.ts +0 -362
  122. package/src/selfie/selfieStateMachine.test.ts +0 -283
  123. package/src/selfie/selfieStateMachine.ts +0 -804
  124. package/src/selfie/selfieUploadService.test.ts +0 -90
  125. package/src/selfie/selfieUploadService.ts +0 -81
  126. package/src/selfie/types.ts +0 -103
  127. package/src/session/index.ts +0 -5
  128. package/src/session/sessionService.ts +0 -78
  129. package/src/setup.test.ts +0 -61
  130. package/src/setup.ts +0 -171
  131. package/tsconfig.json +0 -13
  132. package/tsdown.config.ts +0 -22
  133. package/vitest.config.ts +0 -37
  134. package/vitest.setup.ts +0 -135
@@ -1,301 +0,0 @@
1
- import {
2
- type CreateApiOptions,
3
- createManager,
4
- type ManagerSnapshot,
5
- } from '@incodetech/infra';
6
- import {
7
- type CreateSelfieActorOptions,
8
- createSelfieActor,
9
- } from './selfieActor';
10
- import type { CameraStream } from './selfieServices';
11
- import type { SelfieMachine } from './selfieStateMachine';
12
- import type { DetectionStatus, PermissionStatus } from './types';
13
-
14
- /** Internal snapshot type for the selfie state machine */
15
- type SelfieSnapshot = ManagerSnapshot<SelfieMachine>;
16
-
17
- type CaptureStatus =
18
- | 'initializing'
19
- | 'detecting'
20
- | 'capturing'
21
- | 'uploading'
22
- | 'uploadError'
23
- | 'success';
24
-
25
- /** Selfie manager is waiting to be started */
26
- type SelfieIdleState = {
27
- status: 'idle';
28
- };
29
-
30
- /** Checking camera permissions (when no tutorial) */
31
- type SelfieLoadingState = {
32
- status: 'loading';
33
- };
34
-
35
- /** Showing selfie tutorial */
36
- type SelfieTutorialState = {
37
- status: 'tutorial';
38
- };
39
-
40
- /** Handling camera permissions */
41
- type SelfiePermissionsState = {
42
- status: 'permissions';
43
- /** Current permission sub-state: initial, requesting, denied, or learnMore */
44
- permissionStatus: PermissionStatus;
45
- };
46
-
47
- /** Camera is ready for selfie capture */
48
- type SelfieCaptureState = {
49
- status: 'capture';
50
- /** Current capture sub-state */
51
- captureStatus: CaptureStatus;
52
- /** The active camera stream */
53
- stream: CameraStream | undefined;
54
- /** Current face detection status */
55
- detectionStatus: DetectionStatus;
56
- /** Latest frame processed in the detection loop (for UI debug rendering) */
57
- debugFrame: ImageData | undefined;
58
- /** Number of capture attempts remaining */
59
- attemptsRemaining: number;
60
- /** Error message from failed upload */
61
- uploadError: string | undefined;
62
- };
63
-
64
- /** Selfie capture completed successfully */
65
- type SelfieFinishedState = {
66
- status: 'finished';
67
- };
68
-
69
- /** User closed the selfie flow */
70
- type SelfieClosedState = {
71
- status: 'closed';
72
- };
73
-
74
- /** An error occurred during the flow */
75
- type SelfieErrorState = {
76
- status: 'error';
77
- /** The error message */
78
- error: string;
79
- };
80
-
81
- /** Union of all possible selfie states */
82
- export type SelfieState =
83
- | SelfieIdleState
84
- | SelfieLoadingState
85
- | SelfieTutorialState
86
- | SelfiePermissionsState
87
- | SelfieCaptureState
88
- | SelfieFinishedState
89
- | SelfieClosedState
90
- | SelfieErrorState;
91
-
92
- function getPermissionStatus(
93
- snapshot: SelfieSnapshot,
94
- ): PermissionStatus | undefined {
95
- if (!snapshot.matches('permissions')) {
96
- return undefined;
97
- }
98
-
99
- if (snapshot.matches({ permissions: 'idle' })) {
100
- return 'idle';
101
- }
102
-
103
- if (snapshot.matches({ permissions: 'learnMore' })) {
104
- return 'learnMore';
105
- }
106
-
107
- if (snapshot.matches({ permissions: 'requesting' })) {
108
- return 'requesting';
109
- }
110
-
111
- if (snapshot.matches({ permissions: 'denied' })) {
112
- return 'denied';
113
- }
114
-
115
- return undefined;
116
- }
117
-
118
- function getCaptureStatus(snapshot: SelfieSnapshot): CaptureStatus | undefined {
119
- if (snapshot.matches({ capture: 'initializing' })) return 'initializing';
120
- if (snapshot.matches({ capture: 'detecting' })) return 'detecting';
121
- if (snapshot.matches({ capture: 'capturing' })) return 'capturing';
122
- if (snapshot.matches({ capture: 'capturingManual' })) return 'capturing';
123
- if (snapshot.matches({ capture: 'uploading' })) return 'uploading';
124
- if (snapshot.matches({ capture: 'uploadError' })) return 'uploadError';
125
- if (snapshot.matches({ capture: 'success' })) return 'success';
126
- return undefined;
127
- }
128
-
129
- function mapState(snapshot: SelfieSnapshot): SelfieState {
130
- const { context } = snapshot;
131
-
132
- if (snapshot.matches('idle')) {
133
- return { status: 'idle' };
134
- }
135
-
136
- if (snapshot.matches('loading')) {
137
- return { status: 'loading' };
138
- }
139
-
140
- if (snapshot.matches('tutorial')) {
141
- return {
142
- status: 'tutorial',
143
- };
144
- }
145
-
146
- if (snapshot.matches('closed')) {
147
- return { status: 'closed' };
148
- }
149
-
150
- if (snapshot.matches('permissions')) {
151
- const permissionStatus = getPermissionStatus(snapshot);
152
- if (permissionStatus === undefined) {
153
- return { status: 'permissions', permissionStatus: 'idle' };
154
- }
155
- return {
156
- status: 'permissions',
157
- permissionStatus,
158
- };
159
- }
160
-
161
- if (snapshot.matches('capture')) {
162
- const captureStatus = getCaptureStatus(snapshot);
163
- return {
164
- status: 'capture',
165
- captureStatus: captureStatus ?? 'initializing',
166
- stream: context.stream,
167
- detectionStatus: context.detectionStatus,
168
- debugFrame: context.debugFrame,
169
- attemptsRemaining: context.attemptsRemaining,
170
- uploadError: context.uploadError,
171
- };
172
- }
173
-
174
- if (snapshot.matches('finished')) {
175
- return { status: 'finished' };
176
- }
177
-
178
- if (snapshot.matches('error')) {
179
- return {
180
- status: 'error',
181
- error: context.error ?? 'Unknown error',
182
- };
183
- }
184
-
185
- return { status: 'idle' };
186
- }
187
-
188
- function createApi({ actor }: CreateApiOptions<SelfieMachine>) {
189
- return {
190
- /**
191
- * Starts the selfie flow.
192
- * Goes to `tutorial` if showTutorial is true, otherwise to `loading`.
193
- * Requires setup() to have been called with a token first.
194
- */
195
- load() {
196
- actor.send({ type: 'LOAD' });
197
- },
198
-
199
- /**
200
- * Advances to the next step.
201
- * From `tutorial` → permissions or capture (based on permission status).
202
- * From `capture` → finished.
203
- */
204
- nextStep() {
205
- actor.send({ type: 'NEXT_STEP' });
206
- },
207
-
208
- /**
209
- * Requests camera permission via getUserMedia.
210
- * Only effective when in `permissions.idle` or `permissions.learnMore` state.
211
- */
212
- requestPermission() {
213
- actor.send({ type: 'REQUEST_PERMISSION' });
214
- },
215
-
216
- /**
217
- * Navigates to the "learn more" permission screen.
218
- * Only effective when in `permissions.idle` state.
219
- */
220
- goToLearnMore() {
221
- actor.send({ type: 'GO_TO_LEARN_MORE' });
222
- },
223
-
224
- /**
225
- * Goes back from "learn more" to the initial permission screen.
226
- * Only effective when in `permissions.learnMore` state.
227
- */
228
- back() {
229
- actor.send({ type: 'BACK' });
230
- },
231
-
232
- /**
233
- * Closes the selfie flow and transitions to `closed` state.
234
- * Can be called from any state.
235
- */
236
- close() {
237
- actor.send({ type: 'QUIT' });
238
- },
239
-
240
- /**
241
- * Resets the selfie manager to its initial `idle` state.
242
- * Can be called from `finished` or `error` states.
243
- */
244
- reset() {
245
- actor.send({ type: 'RESET' });
246
- },
247
-
248
- /**
249
- * Retries the capture after an upload error.
250
- * Only effective when in `capture.uploadError` state and `attemptsRemaining > 0`.
251
- * If no attempts remaining, the transition is blocked.
252
- */
253
- retryCapture() {
254
- actor.send({ type: 'RETRY_CAPTURE' });
255
- },
256
-
257
- /**
258
- * Captures a selfie in manual capture mode.
259
- * Only effective when in `capture.detecting` state and `detectionStatus === 'manualCapture'`.
260
- */
261
- capture() {
262
- actor.send({ type: 'MANUAL_CAPTURE' });
263
- },
264
- };
265
- }
266
-
267
- /**
268
- * Creates a selfie manager instance for handling selfie capture flow.
269
- *
270
- * The selfie manager provides:
271
- * - State management with statuses: `idle`, `loading`, `tutorial`, `permissions`, `capture`, `finished`, `closed`, `error`
272
- * - Permission handling with nested states: `idle`, `requesting`, `denied`, `learnMore`
273
- * - Capture handling with nested states: `initializing`, `startingRecorder`, `recordingActive`, `detecting`, `capturing`, `uploading`, `uploadError`, `success`
274
- * - Camera stream access when in `capture` state
275
- * - Detection status feedback during face detection
276
- * - Attempt tracking with `attemptsRemaining`
277
- *
278
- * @param options - Configuration for the selfie actor
279
- * @param options.config - The selfie module configuration from the flow
280
- * @returns A manager instance with state subscription, API methods, and lifecycle controls
281
- *
282
- * @example
283
- * ```ts
284
- * const selfieManager = createSelfieManager({ config: selfieConfig });
285
- *
286
- * selfieManager.subscribe((state) => {
287
- * if (state.status === 'capture') {
288
- * console.log('Camera ready:', state.stream);
289
- * console.log('Detection status:', state.detectionStatus);
290
- * }
291
- * });
292
- *
293
- * selfieManager.load();
294
- * ```
295
- */
296
- export function createSelfieManager(options: CreateSelfieActorOptions) {
297
- const actor = createSelfieActor(options);
298
- return createManager({ actor, mapState, createApi });
299
- }
300
-
301
- export type SelfieManager = ReturnType<typeof createSelfieManager>;
@@ -1,362 +0,0 @@
1
- import {
2
- type CameraStream,
3
- type FaceCoordinates,
4
- FaceDetectionProvider,
5
- type IncodeCanvas,
6
- type IRecordingCapability,
7
- OpenViduRecordingProvider,
8
- type RecordingConnectionEvents,
9
- requestCameraAccess,
10
- type StreamCanvasCapture,
11
- StreamCanvasProcessingSession,
12
- stopCameraStream,
13
- WasmUtilProvider,
14
- } from '@incodetech/infra';
15
- import { addEvent } from '../events/addEvent';
16
- import {
17
- createRecordingSession,
18
- startRecording,
19
- stopRecording as stopRecordingApi,
20
- } from '../recordings/recordingsRepository';
21
- import { streamingEvents } from '../recordings/streamingEvents';
22
- import type { DetectionStatus, RecordingSession, SelfieConfig } from './types';
23
-
24
- export { type UploadSelfieParams, uploadSelfie } from './selfieUploadService';
25
-
26
- export const CAMERA_CONSTRAINTS: MediaStreamConstraints = {
27
- video: {
28
- facingMode: 'user',
29
- height: { ideal: 480 },
30
- width: { ideal: 640 },
31
- },
32
- audio: false,
33
- };
34
- export type { CameraStream } from '@incodetech/infra';
35
-
36
- export function stopStream(stream: CameraStream): void {
37
- stopCameraStream(stream);
38
- }
39
-
40
- export type SelfieCameraInitResult = {
41
- stream: CameraStream;
42
- provider: FaceDetectionProvider;
43
- };
44
-
45
- export async function initializeCamera(
46
- config: SelfieConfig,
47
- ): Promise<SelfieCameraInitResult> {
48
- const provider = new FaceDetectionProvider();
49
- await provider.initialize({
50
- autocaptureInterval: config.autoCaptureTimeout * 1000,
51
- });
52
-
53
- provider.setChecksEnabled({
54
- lenses: config.validateLenses,
55
- mask: config.validateFaceMask,
56
- closedEyes: config.validateClosedEyes,
57
- headWear: config.validateHeadCover,
58
- occlusion: false,
59
- });
60
-
61
- const stream = await requestCameraAccess({
62
- video: CAMERA_CONSTRAINTS.video,
63
- });
64
-
65
- return { stream, provider };
66
- }
67
-
68
- export type EncryptSelfieImageParams = {
69
- canvas: IncodeCanvas;
70
- };
71
-
72
- /**
73
- * Encrypts the provided selfie image using WASM.
74
- */
75
- export async function encryptSelfieImage({
76
- canvas,
77
- }: EncryptSelfieImageParams): Promise<string> {
78
- const base64Image = canvas.getBase64Image();
79
- if (!base64Image) {
80
- throw new Error('Canvas image is empty or null');
81
- }
82
- const wasmProvider = await WasmUtilProvider.getInstance();
83
- return wasmProvider.encryptImage(base64Image);
84
- }
85
-
86
- export type DetectionCallback = (status: DetectionStatus) => void;
87
-
88
- export type StartDetectionParams = {
89
- config: SelfieConfig;
90
- capturer: StreamCanvasCapture;
91
- onUpdate: DetectionCallback;
92
- onSuccess: (canvas: IncodeCanvas, faceCoordinates?: FaceCoordinates) => void;
93
- onFrame?: (frame: ImageData) => void;
94
- provider: FaceDetectionProvider;
95
- };
96
-
97
- /**
98
- * Starts WASM-backed face detection and streams detection statuses via callbacks.
99
- * Requires `setup({ wasm: ... })` to have been called before.
100
- */
101
- export type StartDetectionResult = {
102
- cleanup: () => void;
103
- reset: () => void;
104
- };
105
-
106
- export function startDetection(
107
- params: StartDetectionParams,
108
- ): StartDetectionResult {
109
- let lastStatus: DetectionStatus | undefined;
110
- let session: StreamCanvasProcessingSession | undefined;
111
- const { provider } = params;
112
-
113
- const setStatus = (status: DetectionStatus): void => {
114
- if (session?.isDisposed() === true) {
115
- return;
116
- }
117
- if (lastStatus === status) {
118
- return;
119
- }
120
- lastStatus = status;
121
- params.onUpdate(status);
122
- };
123
-
124
- const stopDetectionLoop = (): void => {
125
- session?.dispose();
126
- };
127
-
128
- const reset = (): void => {
129
- provider.reset();
130
- };
131
-
132
- const cleanup = (): void => {
133
- stopDetectionLoop();
134
- };
135
-
136
- void (async () => {
137
- try {
138
- provider.setCallbacks({
139
- onFarAway: () => setStatus('tooFar'),
140
- onTooClose: () => setStatus('tooClose'),
141
- onTooManyFaces: () => setStatus('tooManyFaces'),
142
- onNoFace: () => setStatus('idle'),
143
- onCenterFace: () => setStatus('centerFace'),
144
- onGetReady: () => setStatus('getReady'),
145
- onGetReadyFinished: () => setStatus('getReadyFinished'),
146
- onDark: () => {
147
- if (params.config.validateBrightness) {
148
- setStatus('dark');
149
- }
150
- },
151
- onBlur: () => setStatus('blur'),
152
- onFaceAngle: () => setStatus('faceAngle'),
153
- onLenses: () => {
154
- if (params.config.validateLenses) {
155
- setStatus('lenses');
156
- }
157
- },
158
- onMask: () => {
159
- if (params.config.validateFaceMask) {
160
- setStatus('faceMask');
161
- }
162
- },
163
- onEyesClosed: () => {
164
- if (params.config.validateClosedEyes) {
165
- setStatus('eyesClosed');
166
- }
167
- },
168
- onHeadWear: () => {
169
- if (params.config.validateHeadCover) {
170
- setStatus('headWear');
171
- }
172
- },
173
- onFaceOccluded: () => {},
174
- onSwitchToManualCapture: () => {
175
- setStatus('manualCapture');
176
- stopDetectionLoop();
177
- },
178
- onCapture: (canvas: IncodeCanvas, faceCoordinates: FaceCoordinates) => {
179
- setStatus('success');
180
- params.onSuccess(canvas, faceCoordinates);
181
- cleanup();
182
- },
183
- });
184
- setStatus('detecting');
185
- session = new StreamCanvasProcessingSession({
186
- capturer: params.capturer,
187
- provider,
188
- onFrame: params.onFrame,
189
- });
190
- } catch {
191
- setStatus('error');
192
- cleanup();
193
- }
194
- })();
195
-
196
- return { cleanup, reset };
197
- }
198
-
199
- function buildResolutionFromStream(stream: MediaStream): string | undefined {
200
- const track = stream.getVideoTracks()[0];
201
- if (!track) {
202
- return undefined;
203
- }
204
- const settings = track.getSettings();
205
- const width = settings.width;
206
- const height = settings.height;
207
- if (typeof width === 'number' && typeof height === 'number') {
208
- return `${width}x${height}`;
209
- }
210
- return undefined;
211
- }
212
-
213
- export type StartRecordingParams = {
214
- config: SelfieConfig;
215
- stream: CameraStream;
216
- existing?: RecordingSession;
217
- };
218
-
219
- export async function startRecordingSession(
220
- params: StartRecordingParams,
221
- ): Promise<RecordingSession | undefined> {
222
- if (params.config.enableFaceRecording !== true) {
223
- return undefined;
224
- }
225
- if (params.existing) {
226
- return params.existing;
227
- }
228
-
229
- const provider: IRecordingCapability =
230
- params.config.recording?.capability ?? new OpenViduRecordingProvider();
231
-
232
- const clonedStream = params.stream.clone();
233
- const hasAudio = clonedStream.getAudioTracks().length > 0;
234
- const resolution = buildResolutionFromStream(clonedStream);
235
-
236
- const session = await createRecordingSession('selfie');
237
-
238
- const events: RecordingConnectionEvents = {
239
- onSessionConnected: (sessionId) => {
240
- addEvent({
241
- code: streamingEvents.strSessionDidConnect,
242
- payload: {
243
- message: 'Recording session connected',
244
- sessionId,
245
- },
246
- });
247
- },
248
- onSessionDisconnected: (sessionId) => {
249
- addEvent({
250
- code: streamingEvents.strSessionDidDisconnect,
251
- payload: {
252
- message: 'Recording session disconnected',
253
- sessionId,
254
- },
255
- });
256
- },
257
- onSessionException: (event) => {
258
- addEvent({
259
- code: streamingEvents.strSessionDidFailWithError,
260
- payload: {
261
- message: 'Recording session failed due to an error',
262
- eventName: event.name,
263
- type: 'OpenViduException',
264
- errorMessage: event.message,
265
- sessionId: event.sessionId,
266
- },
267
- });
268
- },
269
- onPublisherCreated: (p) => {
270
- addEvent({
271
- code: streamingEvents.strStreamPublisherCreated,
272
- payload: {
273
- message: 'Recording publisher created',
274
- sessionId: p.sessionId,
275
- streamId: p.streamId,
276
- },
277
- });
278
- },
279
- onPublisherError: (p) => {
280
- addEvent({
281
- code: streamingEvents.strStreamPublisherDidFailWithError,
282
- payload: {
283
- message: 'Recording publisher failed due to an error',
284
- sessionId: p.sessionId,
285
- streamId: p.streamId,
286
- error: {
287
- message: p.message ?? 'Unknown error',
288
- },
289
- },
290
- });
291
- },
292
- };
293
-
294
- const connection = await provider.connect({
295
- sessionToken: session.token,
296
- stream: clonedStream,
297
- events,
298
- });
299
-
300
- await startRecording({
301
- videoRecordingId: session.videoRecordingId,
302
- type: 'selfie',
303
- resolution,
304
- hasAudio,
305
- });
306
-
307
- addEvent({
308
- code: streamingEvents.strStreamVideoCaptureStart,
309
- payload: {
310
- message: 'Recording capture started',
311
- resolution,
312
- videoRecordingId: session.videoRecordingId,
313
- sessionId: session.sessionId,
314
- streamId: connection.publisher.getStreamId(),
315
- },
316
- });
317
-
318
- return {
319
- token: session.token,
320
- sessionId: session.sessionId,
321
- videoRecordingId: session.videoRecordingId,
322
- connection,
323
- resolution,
324
- hasAudio,
325
- };
326
- }
327
-
328
- export function stopRecording(session: RecordingSession): void {
329
- void (async () => {
330
- try {
331
- addEvent({
332
- code: streamingEvents.strStreamVideoCaptureStop,
333
- payload: {
334
- message: 'Recording capture stopped',
335
- videoRecordingId: session.videoRecordingId,
336
- sessionId: session.sessionId,
337
- streamId: session.connection.publisher.getStreamId(),
338
- },
339
- });
340
-
341
- await stopRecordingApi(session.videoRecordingId);
342
-
343
- addEvent({
344
- code: streamingEvents.strStreamPublisherDestroyed,
345
- payload: {
346
- message: 'Recording publisher destroyed',
347
- sessionId: session.sessionId,
348
- streamId: session.connection.publisher.getStreamId(),
349
- },
350
- });
351
- } finally {
352
- await session.connection.disconnect();
353
- addEvent({
354
- code: streamingEvents.strSessionDidDisconnect,
355
- payload: {
356
- message: 'Recording session disconnected',
357
- sessionId: session.sessionId,
358
- },
359
- });
360
- }
361
- })();
362
- }