## Overview

Wrapper of the TDVC library for BAF.

## Use cases

-   Check Liveness Reflection
-   Check Motion Control
-   Capture of faces

## Recommendations

Use a modern phone with a good camera having the definition of not less than 8 megapixels.
The capture must be made in a well-lighted room. A document must be located at the uniform background.

## Limitations

This component works on phones and desktops in the Chrome browser, Firefox, Safari, Mi Browser

## Installation

The component is supplied as a TGZ archive. Also, for the tdvc-onboarding library to work, the tdvc library is required, which is also supplied as an archive. Move the archives to your project's root folder and add the following lines to your package.json in the dependencies section:

```
"@tdvc/face-onboarding": "file:tdvc-face-onboarding-{version}.tgz"
```

This component contains JS, CSS files which require the mandatory import into your project.

Import the library and css to your project.

```javascript
import TDVOnboarding from '@tdvc/face-onboarding';
import '@tdvc/face-onboarding/dist/css/style.css';
```

For the component to work, the opencv.js script is required. After installing the package, move the "networks" folder from /node_modules/@tdvc/face-onboarding/ to the "public" folder of your project.

## Initialization

The component provides two modules: registration and authorization. To use the component, create an instance of the TDVOnboarding module you need. Each module accepts configuration object as parameters. Below is a description of configuration:

### Fields configurable via the configuration object

**baseUrl** (string) - URL address of API. If you pass the value "/", then requests will be sent to the host on which the web component is deployed. **Required**.

**integrationId** (string) - integration ID. **Required**.

**mountElement** (string) - ID of an element on the page where the component will be integrated. **Required**.

**applicantId** (string) - ID of applicant for registration or authorization.

> Please note that the configuration must only have one of two fields: applicantId or applicantFields.

**checkIceCandidateTimeout** (number) - time to wait for a response from ICE candidate in milliseconds. Default 3000 milliseconds. The minimum value is 1000 ms.

**language** (string) - current interface language, if no value is specified, `“en”` will be used by default.

**locales** (Locales) - object with custom locales for changing texts. For ease of use, we recommend writing one file with locales and using it in all configurations of the component. If no value is specified, the default object will be used.

The accepted value is an object with the following content:

```javascript
const en = {
    Login: {
        Authorization: 'Authorization',
        Registration: 'Registration',
        LoginButton: 'Continue',
        InvalidEmail: 'Invalid email format',
        MaxLengthField: 'Maximum field length is 150 characters',
        IsRequired: 'This field is required',
        firstName: 'First name',
        lastName: 'Last name',
        phone: 'Phone',
        email: 'Email',
        referenceId: 'ReferenceId',
        WrongPhone: 'Wrong phone number',
        CheckApplicant: 'Applicant verification',
    },
    Register: {
        Header: 'Registration',
        RegisterDescription1: 'Registering as ',
        RegisterDescription2: 'Please complete the registration',
        RegisterButton: 'Register',
        BackToLoginButton: 'Back',
        EstimateVideo: 'Checking the image quality',
        Update: 'Update',
        Processing: 'Processing in progress',
        LoadVideoForm: 'Connecting the camera',
        CheckApplicant: 'Applicant verification',
    },
    Authorize: {
        Header: 'Authorization',
        AuthorizeDescription1: 'Authorizing as ',
        AuthorizeDescription2: 'Please complete the authorization',
        AuthorizeButton: 'Log in',
        BackToLoginButton: 'Back',
        EstimateVideo: 'Checking the image quality',
        Update: 'Update',
        Processing: 'Processing in progress',
        LoadVideoForm: 'Connecting the camera',
    },
    Errors: {
        MessageCode: 'Message code: ',
        NoComponentIdError: 'Integration ID not specified in the component configuration',
        NoBaseUrlErrorError: 'Base URL of server not specified in the component configuration',
        AntispoofingValidationError: 'Liveness check failed',
        RegistrationMatchingFailed: 'An applicant with such biometrics already exists',
        AuthorizationMatchingFailed: 'No applicant with this biometric was found',
        LowImageQuality: 'Poor image quality',
        NoFacesFound: 'No face found in the image',
        SomeError: 'An error occurred, please try again later',
        FacesDontBelongApplicant: 'Face matching check failed',
        IDontSeeYou: 'You are not visible',
        MoveFaceOnCenter: 'Please position yourself so that your face is in the center of the circle on the screen',
        FaceOutsideFrame: 'Please position yourself so that your face is in the center of the on the screen',
        LookAtCamera: 'Please, turn your face to the camera',
        LittleFace: 'Move closer to the camera',
        BigFace: 'Move further away from the camera',
        SlowEnternet: 'Your internet connection is slow. Image quality assessment may take long',
        InCorrectCamera: 'The selected camera is not available or does not meet the minimum requirements',
        NoCamera: 'No cameras available',
        NoPermission:
            'Permission to access the camera is not obtained. For further work, allow access to the camera in your browser settings',
        MoreFaces: 'Many faces in the frame',
        SafariError: 'Unfortunately, your browser is temporarily not supported at the moment',
        BackToLoginButton: 'Back',
        ApplicantNotFound: 'Applicant not found',
        ApplicantAlreadyExist: 'This user already exists',
        Update: 'Update',
        ServerError: 'The server is temporarily unavailable',
        ServerConfigError: 'Error on the server',
        LoadScriptError: "Couldn't download scripts required for detector operation",
        ApplicantBlocked: 'The applicant is blocked',
        ApplicantUnconfirmed: 'The applicant is unconfirmed',
        MCCrossMatchError: 'Facial substitution detected',
        LRCrossMatchError: 'Facial substitution detected',
        BlackListError: 'The applicant is on the black list',
        RiskError: 'During validation, the risk triggered',
        "Face profile wasn't saved": "Face profile wasn't saved",
        'Face profiles not found': 'Face profiles not found',
        'Face authorization was failed': 'Face authorization was failed',
        'A face was missing or disappeared from the frame when recording liveness reflection video':
            'A face was missing or disappeared from the frame when recording liveness reflection video',
        'Invalid endeavor info': 'Invalid endeavor info',
        'Endeavor liveness reflection info obtain error': 'Error receiving liveness reflection information',
        'Endeavor external link not equal to applicant': 'Applicant ID consistency error',
        'Endeavor is not calculated': 'Error recording video liveness reflection',
        'Endeavor liveness reflection confidence info is null': 'Error calculating liveness reflection',
        'Endeavor liveness reflection confidence value is null': 'Error calculating liveness reflection',
        'Failed to obtain template from liveness reflection reference image':
            'No face in the frame when recording video reflection',
        'Failed to obtain template from motion control reference image':
            'No face in the frame when recording motion control video',
        'Endeavor id is null when required': 'Endeavor id is null when required',
        'No faces found on image': 'No faces found on image',
        'Multiple faces found on image': 'Multiple faces found on image',
        'Multiple faces or strong face movement spotted when recording liveness reflection video':
            'Multiple faces or strong face movement spotted when recording liveness reflection video',
        'Error when perform cross matching': 'Error when perform cross matching',
        'Error on the server': 'Error on the server',
        'Liveness reflection video is not captured': 'Liveness reflection video is not captured',
        'Liveness reflection video reference template is not captured':
            'Liveness reflection video reference template is not captured',
        'Motion control video is not captured': 'Motion control video is not captured',
        'Motion control video reference template is not captured':
            'Motion control video reference template is not captured',
        NotSupportedMediaDevicesError: 'Media Devices API not supported',
        AbortAccessToCameraError: 'Aborted access to camera',
        DocumentIsNotFullyActiveError: 'HTML document is not fully active',
        NotAllowedAccessToCameraError: 'Not allowed access to camera',
        NotFoundCameraError: 'No camera was found',
        NotReadableCameraError: 'The camera is unavailable because it is already in use by another process',
        OverconstrainedCameraError: 'No camera satisfying the constraints of the system is found',
        CameraSecurityError: 'The HTML document does not meet the minimum security requirements for camera use',
        ApplicantIdWithApplicationFieldsError:
            'Configuration error Only one of the two configuration fields must be passed: applicationFields or applicantId',
        NoEnabledApplicationFieldsError:
            'Configuration error. At least one enabled field in applicationFields is required',
        NoPrimaryApplicationFieldsError: 'Configuration error. One primary field is required in applicationFields',
        NoPrimaryEnabledApplicationFieldsError:
            'Configuration error. The primary field in applicationFields must be enabled',
        SeveralPrimaryEnabledApplicationFieldsError:
            'Configuration error. Only one primary field is required in applicationFields',
        CameraIdWithCameraSelectorError:
            'Configuration error. If the cameraId parameter is passed, then the showCameraSelect parameter must be false',
        InvalidMotionControlAttemptCountError:
            'Configuration error. The motionControl.attemptsCount field must be greater than zero',
        EnabledMotionControlWithoutFaceModelError:
            'Configuration error. If faceModelSettings.modelEnabled is false, then motionControl.enabled must also be false',
        TimeToStartRecordLessThenOneSecondError:
            'Configuration error. The timeToStartRecord value must be at least 1000ms',
        NoIceCandidatesError:
            'Configuration error. At least one ICE candidate must be specified in the component settings on the server',
        IceCandidateTimeoutLessThenOneSecondError:
            'Configuration error. The checkIceCandidateTimeout value must be at least 1000ms',
        FailedFetchOfConfiguration: 'Failed to retrieve component settings',
        NotSupportedApiError: 'Your browser does not support the required function',
        NoVideoTrackError: 'There is no data about the video stream from the camera',
        NoCameraCapabilitiesInfoError:
            'Information about possible camera settings does not contain the required parameters',
        MediaStreamIsUndefinedError: 'There is no video stream data',
        TransportError: 'An unexpected error occurred while running the check',
        NotSupportedVideoFormatError: "This browser haven't supported needed video mime type",
        ExceedMaxMessageSizeError: 'The maximum message size has been exceeded',
        NoRequiredConfigurationFieldsError: 'The settings received from the server do not contain the required data',
        VideoStreamResolutionIsUndefinedError: 'The resolution of the video stream is not defined',
        InvalidVideoStreamResolutionValueError:
            'The resolution of the video stream contains invalid values, the width or height of the video stream cannot be equal to 0',
        InvalidVideoPreviewResolutionValueError:
            'The resolution of the video preview contains invalid values, the width or height of the video preview cannot be equal to 0',
        InvalidFrameDataForDetectionError: 'Incorrect frame data for face detection',
        CaptureFaceBestshotTimeoutError: 'Frame collection waiting time exceeded',
        InvalidMotionControlPatternError: 'Invalid Motion Control pattern',
        NoSupportedVideoCodecError: 'The video codec supported by the system is not detected',
        InitializationProcessingVideoStremWorkerError: 'Error initializing the video frame processing service',
        WaitResponseWorkerTimeoutError: 'The waiting time for a response from the worker has expired',
        BrowserNotSupportedWorkerApi: "This browser doesn't support Worker API",
        DeepfakeValidationError: 'Deepfake check failed',
        CameraFpsNotDefinedError: 'The frame rate of the video stream is not defined',
        TransmissionTimeoutError: 'The waiting time for a response from the server has been exceeded',
        InvalidFacesAmountOnFrameError: 'No face or too many faces found',
        InvalidMessageFormatError: 'Invalid message format',
        120004: 'FPS too low. Please try again',
        120005: 'Error on the server. Please try again',
        120006: 'Error on the server. Please try again',
        120007: 'Error on the server. Please try again',
        120008: 'Error on the server. Please try again',
        120009: 'Please check the quality of your internet connection and try again',
        120044: 'No reference frames found',
        120052: 'Error on the server. Please try again',
        120053: 'Error on the server. Please try again',
        120054: 'Error on the server. Please try again',
        120055: 'Error while sending a message via DataChannel',
        120057: 'Error in obtaining Motion Control pattern',
        120060: 'Error on the server. Please try again',
        120061: 'No face or multiple faces detected while taking reference image. Please try again',
        170001: 'No active ICE candidates detected',
        180001: 'Invalid websocket message format',
        180002: 'Failed to retrieve component settings',
        180003: 'Requesting a video recording of an unsupported type',
        180004: 'There was an error on the server while recording video',
        180005: 'Video processing time has exceeded the limit',
        180006: 'Error in operation of WebSocket connection',
        190002: 'The connection to the server was closed due to an internal error or exceeding the waiting time.',
        190003: 'The size of data sent to the server exceeds the allowed size',
        190004: 'The check failed due to facial movement',
        1100001: 'The device does not support WebGL technology',
        1100004: 'The device does not meet the requirements necessary to start the detector',
        1100005: 'No face detector in the system',
        1300001: 'Poor connection quality, the connection to the server does not meet the necessary requirements',
        1300002: 'An error occurred when establishing the connection',
    },
    Success: {
        Register: 'Registration completed successfully',
        Authorize: 'Authorization completed successfully',
    },

    CheckPosition: 'Checking position',
    LoadModels: 'Loading models',
    LoadingStage: 'Loading the current stage',
    Continue: 'Continue',
    TimerBeforeRun: 'Before recording starts',
    ConnectWebRTC: 'Establish WebRTC connection to the server',
    HandleResult: 'Processing the result',
    GoToNextStage: 'Moving on to the next stage',
    DontMove: "Please don't move",
    SendingDataToServer: 'Sending data to the server',
    CheckingWebcamOperation: 'Check the webcam for proper operation and image quality',

    MotionControl: {
        DescriptionBlock: {
            Header: 'Checking Motion Control',
            Description:
                'To pass the inspection successfully, you need to perform several actions. First, you need to determine the initial position of the face. To do this, fix the face in a position that is convenient for you and so that the mask is displayed for a few seconds while the counter is filling up under the player. After determining the starting position, you need to perform a number of actions in the order generated by the system. Actions are commands: turn your head to the right/left, raise your head, approach/move away.  The action is considered completed when the frame around the face changes its color.',
        },
        AttemptFailed: 'Motion Control attempt failed',
        Command: {
            TurnLeft: 'Turn left',
            TurnRight: 'Turn right',
            TurnUp: 'Lift your chin up while continuing to look at the screen',
            LookAtCenter: 'Look into the camera',
            Closer: 'Move closer to the camera',
            Farther: 'Move further away from the camera',
            Normal: 'Return to the original position',
        },
    },
};
```

**callbacks** (TBLCallback) - object with callback hooks. Available next hooks:

-   **onValidate** ((data: any) => void) - the function that will be called after validation response received.

-   **onError** ((message: string, code: string) => void) - the function that will be called on error.

-   **onBack** (() => void) - a function that will be called after the back button is pressed.

-   **onUpdate** (() => void) - a function that will be called after the update button is pressed.

-   **onMotion** ((type: 'left' | 'right' | 'up' | 'closer' | 'farther' | 'return', result: boolean | undefined) => void) - a function that will be called before and after each Motion control pattern. If the result variable is undefined, then the function was called at the beginning of the pattern, otherwise at the end.

-   **onMounted** (() => void) - a callback-function which will be called on the component mounted. This function doesn't return a value.

-   **onStartValidation** (() => void) - callback function that will be called before sending a validation attempt request

-   **onIdentifyApplicantStatus**: (applicant: {applicantId: string, status: number}) => void - a function that will be called after determining the status of the applicant.

-   **onGetReferenceImages**: (referenceImages: string[]) => void; - a function that is called after receiving a reference frames and which allows you to receive this frames as a base64 string

### Fields that are taken from the server by default and can be overwritten through the client

**clientServerConnectionSettings** (ClientServerConnectionSettings) - an object containing video recording and face bestshots capture settings.

-   **videoRecordingApi** ('VideoRecordingApi.MEDIA_RECORDER' | 'VideoRecordingApi.WEB_CODEC') - the tool that will be used to encode the video. The WebCodec option involves encoding video using the browser's WebCodec API, which allows direct manipulation of video frames. This provides more stable encoder performance and advanced debugging capabilities for the resulting data, but the API may not be supported by older devices. The MediaRecorder option involves encoding video using the browser's MediaRecorder API. This API has extensive support, but it encodes video without metadata, which makes debugging analysis difficult and does not allow you to rewind video files. By default VideoRecordingApi.MEDIA_RECORDER.

-   **videoBitrate** (number) - the number of bits per second that will be used when encoding video. The higher the bitrate, the larger the final video will be and the higher its quality will be. By default 1 000 000.

-   **idealVideoKeyFrameCountPerSecond** (number) - a keyframe is a frame used by the decoder to decode all frames until the next keyframe. The more frequently keyframes occur, the less RAM and CPU the server will consume, but the larger the video size will be. By default 3.

-   **requiredReferenceFrameCount** (number) - a reference frame is a frame selected by a web component based on the angles of rotation of the face and its sharpness. The server analyzes the frames received from the component and selects the best one in terms of quality as the best shot. The higher the number of reference frames, the higher the load on the server for processing them, but the higher the probability of obtaining the best frame with c best algorithm results. By default 10.

-   **referenceFrameQuality** (number) - the parameter responsible for the quality of reference frames sent to the server. The lower the quality, the smaller the size of the reference frame, but the lower the quality algorithm score. By default 90.

-   **switchToMediaRecoderApiAsFallback** (boolean) - if the WebCodec API is not supported by the client device, video encoding will be performed using the MediaRecorder API. By default false.

-   **transmissionWaitTimeout**: (number) - transmissionWaitTimeout: 10_000. By default 10000,

**livenessTransport** ('LivenessTransport.WEB_SOCKET' | 'LivenessTransport.WEB_RTC') - this setting allows you to select the type of communication between the client and the server (WebRTC, WebSocket) when passing checks on liveness.

**fingerprintWaitTime** (number) - this setting allows you to set the maximum waiting time for data collection to generate a fingerprint of device (Default is 2000 ms). Data that has not been received during this time will not be included in the fingerprint.

**faceModelSettings** (FaceDetectorSettings) - object with face mesh settings.

-   **modelEnabled** (boolean) - flag including a face mesh.

    > Please note that if you turn this option off, Motion Control will no longer be available. Also, Liveness Reflection video recording will start after a certain time. The default is true.

-   **timeToStartRecord** (number) - time in milliseconds after which Liveness Reflection recording will start if the face mesh is turned off.

-   **angleСalculation** (AngleСalculationSettings) - object containing parameters used in calculations of head position angles.

    -   **angles** (object) - values in degrees at which the system considers that the head is turned/lift up to a certain side. If none of the thresholds is reached, the head is considered to be in neutral position.

        -   **left** (number) - The threshold in degrees at which the system will assume that the head is turned to the left. By default is 15.
        -   **right** (number) - The threshold in degrees at which the system will assume that the head is turned to the right. By default is 15.
        -   **up** (number) - The threshold in degrees at which the system will assume that the head is lift up. By default is 25.

    -   **focalLength** (number) - The value used in angles calculation to convert the coordinates of the detected face from pixels to world coordinates. By default is 2500.

**cameraSettings** (CameraSettings) - object with camera settings.

-   **showCameraSelect** (boolean) - flag allowing camera selection.

-   **cameraResolution** ('CameraResolutions.FULL_HD' | 'CameraResolutions.HD' | 'CameraResolutions.SD') - A parameter indicating the "ideal" video resolution. The "FULL_HD" key means 1920x1080 resolution, the "HD" key means 1280x720 resolution, and the "SD" key means 640x360 resolution. This setting does not indicate the exact resolution of the video stream, but only indicates the resolution that the browser will aim for. The default value is "HD".

-   **cameraId** (string) - ID of the camera to be used.

-   **autoSubmit** (boolean) - flag that allowing to skip the UI render of camera selection stage and proceed to the next stage.

-   **permissionInBrowserTimeout** (number | undefined) - the waiting time for permission to access the camera in the browser after which an error will be generated. It is measured in milliseconds. By default, 30,000 milliseconds. If you need to disable error generation, set the value to undefined or 0.

**motionControl** (MotionControlSettings) - object with Motion Control settings. The following fields are available:

-   **enabled** (boolean) - flag enabling Motion Control.

-   **attemptsCount** (number) - number of attempts a user can take to complete Motion Control.

-   **order** (number) - order of checks.

    > If the value matches the “order” value in the “livenessReflection” object, the Liveness Reflection will be checked first.

-   **description** (StageDescriptionSettings) - object containing settings for describing the stage.

    -   **enabled** (boolean) - flag allowing rendering of scene description

    -   **autoSubmit** (AutoSubmitSettings) - object containing settings for automatic transition to the stage

        -   **enabled** (boolean) - flag allowing automatic transition to the stage

        -   **timer** (number) - The time interval after which the transition will be executed, if the user does not make the transition. The value must be greater than 0. Default value is 30000 ms. It is not recommended to exceed the value of 45000ms.

-   **facePositionValidation** (FacePositionValidation) - An object containing parameters for checking the face position during initial positioning before Motion Control. This check will be performed only when face detection is enabled.

    -   **enabled** (boolean) - flag that enables checking of face position.
    -   **allowableAccuracyError** (number) - numeric value of the difference in distance between the key points of the face in the initial position and the keypoints of the face, exceeding which will stop the test and show an error to the user. Default is 20.

-   **faceBorder** (MotionControlFaceBorderSettings) - object containing parameters for displaying the face frame for Liveness Reflection.

    -   **autodetected** (FaceBorderAutodetectedModeSettings) - object containing settings for dynamic face frame, which will be calculated from the face detected by the detector.

        -   **enabled** (boolean) - If enabled, the size and position of the face frame will be calculated based on the face detection.
        -   **frameCheckLimit** (number) - The required number of frames that must pass the presence and correctness of the face position to show the face border.
        -   **availableDeviation** (number) - Permissible difference in the distance between the key points of the face at the start of the test and the current position
        -   **framePadding** (object) - Adjusts the allowable detection area relative to the frame size to avoid detecting faces that are far from the center or do not fall entirely within the frame.

            -   **horizontal** (number) -horizontal indents from frame borders in percent relative to the frame size. By default is 10.
            -   **vertical** (number) - vertical indents from frame borders in percent relative to the frame size. By default is 10.

        -   **faceSize** (object) -

            -   **min** (Resolution) - Minimum acceptable face size for stable operation of the detector.
                -   **width** (number) - Width of face in pixels. By default is 120.
                -   **height** (number) - Height of face in pixels. By default is 140.
            -   **max** (Resolution) - Maximum allowable face size for stable operation of the detector
                -   **width** (number) - Width of face in pixels. By default is 360.
                -   **height** (number) - Height of face in pixels. By default is 520.

    -   **faceWidthCoefficients** (FaceWidthCoefficients) - An object containing face width coefficients relative to the maximum allowable camera resolution. From the obtained width the height is calculated by the formula: width \* 3/2.

        -   **fullHd** (number) - coefficient for Full HD resolution. Default is 20.
        -   **hd** (number) - coefficient for HD resolution. Default is 24.
        -   **sd** (number) - coefficient for SD resolution. Default is 33.

    -   **patternCoefficients** (FaceBorderMotionControlPatternCoefficients) - object containing coefficients that affect the size of the face frame.

        -   **closer** (number) - default is 0.8,
        -   **farther** (number) - default is 1.2,

    -   **allowableAccuracyError** (FaceBorderAllowableAccuracyError) - object that contains values for calculating the size error between the detected face and the face frame. The values are in percent from 1 to 100 and the recommended ratio is 2/3.
        **x** (number) - default is 20,
        **y** (number) - default is 30,

-   **imagesHints** (ImagesHints) - object containing parameters for additional graphical Motion Control hints.

    -   **enabled** (boolean) - Enable/disable display of hints. Note that if the images are not in the specified path or failed to retrieve them from the server, nothing will be displayed.
    -   **resourcesPath** (string) - The main part of the image path, not including the file name and format. In the specified path, the folder should contain 6 GIF images with names:

        -   center.gif - played when the user has to return to the starting position,
        -   up.gif - played for the “Up” pattern,
        -   closer.gif is played for the “Closer” pattern,
        -   farther.gif plays for the “Farther” pattern,
        -   left.gif plays for the “Left” pattern,
        -   right.gif plays for the “Right” pattern,

        To get a sample GIF image, please contact us. Please note that the use of our GIF images in production is prohibited.

-   **overlay** (OverlaySettings) - object containing overlay parameters for Motion Control

    -   **backgroundColor** (RGBAColor) - Overlay background color
        -   **r** (number) - valid values from 0 to 255. Default value is 255
        -   **g** (number) - valid values from 0 to 255. Default value is 255
        -   **b** (number) - valid values from 0 to 255. Default value is 255,
        -   **alpha** (number) - valid values from 0 to 1. Default value is 0.5.

-   **timer** (MotionControlTimers) - object containing time intervals for internal Motion Control actions
    -   **beforeStart** (number) - waiting time before start Motion Control. Default value is 1000 ms.
    -   **betweenCommand** (number) - waiting time before proceeding to check the next command. Default value is 250 ms,
    -   **checkFacePosition** (number) - command check frequency. Default value is 250 ms,
    -   **cancelCheckCommand** (number) - maximum time interval for which one Motion Contro command should be executed. Default value is 5000 ms.

**faceBestshotSettings** (FaceBestshotSettings) - object with taking face bestshot settings. The following fields are available:

-   **faceBorder** (FaceBorderSettings) - object containing parameters for displaying the face frame for taking face bestshot frame.

    -   **autodetected** (FaceBorderAutodetectedModeSettings) - object containing settings for dynamic face frame, which will be calculated from the face detected by the detector.

        -   **enabled** (boolean) - If enabled, the size and position of the face frame will be calculated based on the face detection.
        -   **frameCheckLimit** (number) - The required number of frames that must pass the presence and correctness of the face position to show the face border.
        -   **availableDeviation** (number) - Permissible difference in the distance between the key points of the face at the start of the test and the current position
        -   **framePadding** (object) - Adjusts the allowable detection area relative to the frame size to avoid detecting faces that are far from the center or do not fall entirely within the frame.

            -   **horizontal** (number) -horizontal indents from frame borders in percent relative to the frame size. By default is 10.
            -   **vertical** (number) - vertical indents from frame borders in percent relative to the frame size. By default is 10.

        -   **faceSize** (object) -
            -   **min** (Resolution) - Minimum acceptable face size for stable operation of the detector.
                -   **width** (number) - Width of face in pixels. By default is 120.
                -   **height** (number) - Height of face in pixels. By default is 140.
            -   **max** (Resolution) - Maximum allowable face size for stable operation of the detector
                -   **width** (number) - Width of face in pixels. By default is 360.
                -   **height** (number) - Height of face in pixels. By default is 520.

    -   **faceWidthCoefficients** (FaceWidthCoefficients) - An object containing face width coefficients relative to the maximum allowable camera resolution. From the obtained width the height is calculated by the formula: width \* 3/2.

        -   **fullHd** (number) - coefficient for Full HD resolution. Default is 20.
        -   **hd** (number) - coefficient for HD resolution. Default is 24.
        -   **sd** (number) - coefficient for SD resolution. Default is 33.

    -   **allowableAccuracyError** (FaceBorderAllowableAccuracyError) - object that contains values for calculating the size error between the detected face and the face frame. The values are in percent from 1 to 100 and the recommended ratio is 2/3.
        **x** (number) - default is 20,
        **y** (number) - default is 30,

-   **facePositionValidation** (FacePositionValidation) - An object containing parameters for checking the face position during initial positioning before taking face bestshots. This check will be performed only when face detection is enabled.

    -   **enabled** (boolean) - flag that enables checking of face position.
    -   **allowableAccuracyError** (number) - numeric value of the difference in distance between the key points of the face in the initial position and the keypoints of the face, exceeding which will stop the test and show an error to the user. Default is 20.

-   **overlay** (OverlaySettings) - object containing overlay parameters for taking face bestshot

    -   **backgroundColor** (RGBAColor) - Overlay background color
        -   **r** (number) - valid values from 0 to 255. Default value is 255
        -   **g** (number) - valid values from 0 to 255. Default value is 255
        -   **b** (number) - valid values from 0 to 255. Default value is 255,
        -   **alpha** (number) - valid values from 0 to 1. Default value is 0.5.

**autoSubmit** (boolean) - flag that allows automatic sending of a check request after all checks have been passed.

**applicantFields** (ApplicantFields) - setting up applicant fields that should be displayed during registration or authorization. The values of these fields will be sent to the request to create an applicant. The primary field determines by which key the applicant will be searched in the database.

> Note that there must be only one primary field and it must be enabled. The accepted value is an object with the following content:

```javascript
applicantFields: {
    firstName: { enabled: false, primary: false },
    lastName: { enabled: false, primary: false },
    phone: { enabled: false, primary: false },
    email: { enabled: true, primary: true },
    referenceId: { enabled: false, primary: false },
};
```

**showMetrics** (boolean) - flag enabling display of WebRTC connection metrics: FPS and network **(WebRTC only)**.

**obtainReferenceFrame** (boolean) - flag enabling obtaining a reference frame for video.

**networksPath** (string) - a parameter indicating where FaceMesh models will be loaded from. The default value is **'/networks/'**.

### styling

To change styles, create your own css file, replace the necessary styles in it and import the file in your code. For convenience, the archive contains a css file with the described classes.

## Examples

Registration component initialization examples:

```javascript
import TDVOnboarding from '@tdvc/face-onboarding';
import '@tdvc/face-onboarding/dist/css/style.css';

const lib = new TDVOnboarding.Register({
    baseUrl: '/',
    integrationId: '295cb5c3-8d4f-4247-abc9-04de26548499',
    mountElement: 'app',
    callbacks: {
        onValidate(data) {
            console.log('onValidate callback', data);
        },
        onError(message, code) {
            console.log('onError callback', message, code);
        },
        onBack() {
            console.log('onBack callback');
        },
        onUpdate() {
            console.log('onUpdate callback');
        },
    },
});
```

```javascript
import TDVOnboarding, { ComponentSettingsFromClient } from '@tdvc/face-onboarding';
import { CameraResolutions } from '@tdvc/face-onboarding/dist/class/camera/const';
import { LivenessTransport } from '@tdvc/face-onboarding/dist/types';
import '@tdvc/face-onboarding/dist/css/style.css';

const config: ComponentSettingsFromClient = {
    baseUrl: '/',
    integrationId: '295cb5c3-8d4f-4247-abc9-04de26548499',
    mountElement: 'app',
    networksPath: '/networks/',
    language: 'en',
    locales,
    obtainReferenceFrame: true,
    livenessTransport: LivenessTransport.WEB_SOCKET,
    fingerprintWaitTime: 2000,
    checkIceCandidateTimeout: 3000,
    showMetrics: true,
    autoSubmit: true,
    callbacks: {
        onValidate(data) {
            console.log('onValidate callback', data);
        },
        onError(message, code) {
            console.log('onError callback', message, code);
        },
        onBack() {
            console.log('onBack callback');
        },
        onMotion(type, currentAttemptNumber, result) {
            console.log('onMotion callback', type, currentAttemptNumber, result);
        },
        onUpdate() {
            console.log('onUpdate callback');
        },
        onMounted() {
            console.log('onMounted callback');
        },
        onStartValidation(){
            console.log('onStartValidation callback');
        }
    },
    clientServerConnectionSettings: {
        videoRecordingApi: VideoRecordingApi.MEDIA_RECORDER,
        videoBitrate: 1000000,
        idealVideoKeyFrameCountPerSecond: 3,
        requiredReferenceFrameCount: 10,
        referenceFrameQuality: 90,
        switchToMediaRecoderApiAsFallback: false,
    },
    cameraSettings: {
        showCameraSelect: true,
        cameraResolution: CameraResolutions.HD,
        cameraId: undefined,
        autoSubmit: false,
    },
    faceModelSettings: {
        modelEnabled: true,
        timeToStartRecord: 10000,
        angleСalculation: {
            angles: {
                left: 15,
                right: 15,
                up: 25,
            },
            focalLength: 2500,
        },
    },
    motionControl: {
        order: 1,
        enabled: true,
        attemptsCount: 3,
        imagesHints: {
            enabled: false,
            resourcesPath: '/images/motion_control_gif_hint/',
        },
        description: {
            enabled: true,
            autoSubmit: {
                enabled: false,
                timer: 30000,
            },
        },
        faceBorder: {
            autodetected: {
                enabled: true,
                frameCheckLimit: 60,
                availableDeviation: 20,
                framePadding: {
                    horizontal: 10,
                    vertical: 10,
                },
                faceSize: {
                    min: {
                        width: 120,
                        height: 140,
                    },
                    max: {
                        width: 360,
                        height: 520,
                    },
                },
            },
            allowableAccuracyError: {
                x: 20,
                y: 30,
            },
            patternCoefficients: {
                closer: 1.2,
                farther: 0.8,
            },
            faceWidthCoefficients: {
                fullHd: 20,
                hd: 24,
                sd: 33,
            },
        },
        overlay: {
            backgroundColor: {
                alpha: 0.5,
                r: 255,
                g: 255,
                b: 255,
            },
        },
        timer: {
            beforeStart: 1000,
            betweenCommand: 250,
            cancelCheckCommand: 5000,
            checkFacePosition: 250,
        },
    },
    faceBestshotSettings: {
        faceBorder: {
            autodetected: {
                enabled: true,
                frameCheckLimit: 60,
                availableDeviation: 20,
                framePadding: {
                    horizontal: 10,
                    vertical: 10,
                },
                faceSize: {
                    min: {
                        width: 120,
                        height: 140,
                    },
                    max: {
                        width: 360,
                        height: 520,
                    },
                },
            },
            allowableAccuracyError: {
                x: 20,
                y: 30,
            },
            faceWidthCoefficients: {
                fullHd: 20,
                hd: 24,
                sd: 33,
            },
        },
        facePositionValidation: {
            allowableAccuracyError: 20,
            enabled: true,
        },
        overlay: {
            backgroundColor: {
                alpha: 0.5,
                r: 255,
                g: 255,
                b: 255,
            },
        },
    }
}

const lib = new TDVOnboarding.Register(config);
```

## Version table

Version compatibility table:

<table>
    <tbody>
        <tr>
            <td class="center-aligned" width="400">
                <b>ServerBAF</b>
            </td>
            <td class="center-aligned" width="400">
                <b>@tdvc/face-onboarding</b>
            </td>
        </tr>
        <tr>
            <td width="400">1.14.*</td>
            <td width="400">1.14.*</td>
        </tr>
        <tr>
            <td width="400">1.13.*</td>
            <td width="400">1.13.*</td>
        </tr>
        <tr>
            <td width="400">1.12.*</td>
            <td width="400">1.12.*</td>
        </tr>
        <tr>
            <td width="400">1.10.*</td>
            <td width="400">1.10.*-1.11.*</td>
        </tr>
        <tr>
            <td width="400">1.9.*</td>
            <td width="400">1.9.*</td>
        </tr>
        <tr>
            <td width="400">1.8.*</td>
            <td width="400">1.8.*</td>
        </tr>
         <tr>
            <td width="400">1.7.0</td>
            <td width="400">1.7.0</td>
        </tr>
        <tr>
            <td width="400">1.5.0-1.7.0</td>
            <td width="400">1.6.0</td>
        </tr>
         <tr>
            <td width="400">1.5.0</td>
            <td width="400">1.5.0</td>
        </tr>
        <tr>
            <td width="400">1.3.0-1.4.0</td>
            <td width="400">1.4.0-1.4.1</td>
        </tr>
        <tr>
            <td width="400">1.3.0-1.3.1</td>
            <td width="400">1.3.1</td>
        </tr>
        <tr>
            <td width="400">1.3.0-1.3.1</td>
            <td width="400">1.3.1</td>
        </tr>
         <tr>
            <td width="400">1.2.0</td>
            <td width="400">1.2.0-1.3.0</td>
        </tr>
        <tr>
            <td width="400">1.1.0</td>
            <td width="400">1.0.0-1.1.2</td>
        </tr>
        <tr>
            <td width="400">1.0.0</td>
            <td width="400">1.0.0</td>
        </tr>
    </tbody>
</table>

## Version history

-   **1.14.0**

    -   Added video recording mode via WebCodec API
    -   The logic of collecting the best facial images has been changed
    -   Unnecessary screens with results processing between stages have been removed.
    -   Removed Livenes Reflection
    -   Motion control settings extended
    -   Fixed error codes
    -   Added camera setting permissionInBrowserTimeout

-   **1.13.1**

    -   Fixed logging of the error stack instead of the message
    -   Added processing of empty frames when receiving a bestshot
    -   Added a limit on the number of attempts to establish a connection to send logs in case of receiving multiple connection errors in a row
    -   Fixed a bug that caused spam requests to open a ws connection to send logs

-   **1.13.0**

    -   Added logic for generating a random pattern for Motion Control and selecting a pattern from a list of defined patterns on the server
    -   Removed HTTP transport for livenessTransport setting
    -   Added sending logs via WebSocket
    -   Added the onGetReferenceImages callback to get a reference image of a face before requesting validation

-   **1.12.4**

    -   Fixed a bug that caused the component to freeze after passing motion control and survivability reflection checks for iOS if an error occurred when transferring chunks of video to WebSocket.

-   **1.12.3**

    -   Fixed a bug where Motion Control GIF hints would not show up when replaying Motion Control after a Motion Control failure

-   **1.12.2**

    -   Added additional log components

-   **1.12.1**

    -   The logic of processing the status of the "Unconfirmed" applicant has been changed. The status "Unconfirmed" does not block the user's flow during registration.

-   **1.12.0**

    -   Expanded configuration options for WebRTC on par with WebSocket
    -   Fixed an issue where the default value was always used as the path to the model's resources and the value set on the server or client was ignored.

-   **1.11.3**

    -   Added additional checks for the presence of an API in the browser related to the settings and capabilities of MediaStreamTrack

-   **1.11.2**

    -   Fixed a bug where applicantId was not logged if it was passed via client-side configuration
    -   Fixed a bug where the component would freeze after passing Motion Control and Liveness Reflection checks
    -   Added additional log components

-   **1.11.1**

    -   Added `beforeStart` setting in timer for Motion Control to set the minimum Motion Control passing time. If the values ​​are less than 1000 and the Motion Control test is passed quickly with 1 action pattern, incorrect video recording may occur.
    -   Fixed a bug where video chunks would sometimes be sent in the wrong order when recording in the Firefox browser.

-   **1.11.0**

    -   Added logging of component operation to the server
    -   Updated packages related to the operation of the face recognition model
    -   Fixed re-loading opencv.js if it already exists in html document
    -   Fixed a bug that caused the web component to slow down on multiple consecutive attempts
    -   Fixed memory leak when releasing detector resources
    -   Fixed a bug because of which the onMounted callback was not called when the component initialisation was completed
    -   Added video format selection restriction for iOS, due to video rotation for webm format

-   **1.10.1**

    -   Added onIdentifyApplicantStatus callback function that will be called after determining the status of the applicant.

-   **1.10.0**

    -   Added a mode to automatically calculate the size and position of the face frame based on face detection.
    -   Added Unconfirmed status processing for the applicant
    -   Added error handling if face detector operation is not supported by the device
    -   Improved accuracy of head movement detection during inspections

-   **1.9.3**

    -   Fixed a bug where the coefficient settings did not affect the size of the face frame when taking a bestshot
    -   Added settings to stylize the face frame

-   **1.9.2**

    -   Added onStartValidation callback function that will be called before sending a validation attempt request

-   **1.9.1**

    -   Added a static method to pre-initialize the face detector from outside the component
    -   Added the ability to skip rendering the UI at the camera selection stage and move on to the next stage
    -   Added option to disable stage description display
    -   Added possibility of automatic transition from stage description by timer
    -   Fixed a bug that caused the performance of components to drop when repeatedly retrying

-   **1.9.0**

    -   Return HTTP Liveness Transport
    -   Changed logic of calculating frame size for face positioning
    -   Remove `faceSettings` field from configuration
    -   Added face frame circle configuration object for Liveness Reflection and Motion Control, in the corresponding objects (`faceBorder` in `livenessReflection` and `motionControl`).
    -   Changed the UI for Motion Control check
    -   Added additional GIF hints for Motion Control
    -   Added Motion Control overlay display settings
    -   Added time interval settings for actions within Motion Control
    -   Added an additional face position check when passing Liveness Reflection
    -   Added blocks with information about Liveness Reflection and Motion Control checks

-   **1.8.1**

    -   Added the ability to limit the time to wait for an ICE candidate response using the **_checkIceCandidateTimeout_** variable.
    -   The object for localization has been updated.
    -   Fixed a bug that caused component settings validation errors to be displayed as an error receiving settings from the server
    -   Fixed a bug that caused the component to not display an error and continue to work without switching to checks if there were no working ICE candidates.

-   **1.8.0**

    -   HTTP liveness transport replaced by WebSocket
    -   Added ability to customize the order of checks and disable Motion Control and Liveness Reflection **(WebSocket only)**
    -   Fixed a bug that causes the validation request to be executed before the server processes Liveness Reflection and Motion Control data when “autoSubmit” is enabled.
    -   Fixed a bug where face settings did not affect Motion Control checks
    -   Fixed a bug in the web component that resulted in multiple requests to access the camera in telegram.
    -   Fixed a bug that caused the component to hang on a mobile device if access to the camera was allowed in the web session, but access to the camera was denied in the application permissions.

-   **1.7.2**

    -   Added ability to overwrite component settings received from the server through client-side configs
    -   Added error display if a request to retrieve component settings fails
    -   Fixed a bug that caused “Server Error” to be displayed instead of validation error
    -   Fixed a bug that caused the component to slow down when the “Update” button was clicked multiple times

-   **1.7.1**

    -   Fixed a bug that caused the component display to break after clicking on the “Update” button when receiving error 120061

-   **1.7.0**

    -   Added configuration of business logic components on the server
    -   The configuration has been updated:
        -   The **_fingerprintWaitTime_** field has been added.
        -   **_lrsToken_** replaced on **_videoRecorderToken_**.
        -   **_lrsDecryptKey_** replaced on **_videoRecorderDecryptionKey_**
    -   Fixed a bug that caused the Liveness check don't start when setting the value to 0 for the **_timeToStartRecord_** variable.
    -   Fixed a bug that caused a processing message to be displayed and it was not possible to continue working with the component.
    -   Fixed a bug that caused the processing window to be displayed indefinitely after passing Motion Control
    -   Updated TDVC library to 1.5.3 version.
    -   Update README.md

-   **1.6.3**

    -   The configuration has been updated: the **_livenessTransport_** field has been added to the **_blConfig_** object. This setting allows you to select the type of communication between the client and the server (WebRTC or HTTP) when passing checks on liveness.
    -   Update README.md
    -   Updated TDVC library to 1.5.2 version.

-   **1.6.2**

    -   The configuration has been updated: the **_faceModelSettings_** field has been added to the **_blConfig_** object. In these settings, you can enable the use of a face grid, as well as adjust the time before recording starts. Read more in the configuration description in this file. Checking the update configuration.
    -   Update README.md
    -   Updated TDVC library to 1.5.1 version.

-   **1.6.1**

    -   Fix README.md
    -   Added missing recognition models to the "networks" folder.

-   **1.6.0**

    -   Updated TDVC library to 1.5.0 version.
    -   Deleted **_platformToken_** from **_serverConfig_**.
    -   Updated using **_TDVC.API.getApplicantByFilter_** methods. Add **_page_** and **_pageSize_** parameters.
    -   Updated using **_TDVC.API.getLRSOffer_** methods. Delete **_any_** type annotation.
    -   Added Tensowflow models in networks directory. Fix tensorflow initial and destroy.
    -   The configuration has been updated: the **_cameraSettings_** field has been added to the **_blConfig_** object. In these settings you can enable camera selection in the web component or pass cameraId. You can also specify the required video stream resolution. Update config validation.
    -   Fixed error with camera selector after Liveness Reflection.
    -   Added risk processing during registration and authorization.
    -   Added package version printing.
    -   Added text for LRS errors.
    -   Added **_onMounted_** callback. It's a callback-function which will be called on the component mounted
    -   Added **_Version compatibility table_** in README.md.
    -   Added **_networksPath_** parameter in **_serverConfig_**.

-   **1.5.0**

    -   Add size accuracy in faceSettings config
    -   Update custom-style.css file
    -   Add sending Motion Control result on server

-   **1.4.1**

    -   Update Motion Control config
    -   Add motion controll attempts count function
    -   Update config validation
    -   Update locales
    -   Update onMotion callback
    -   Fix camera changing
    -   Fix Keypoints canvas view
    -   Add face sizes settings

-   **1.4.0**

    -   Add dynamic face circle
    -   Add new callback - onBack
    -   Add new backendUrl pattern - if you pass the value "/", then requests will be sent to the host on which the web component is deployed
    -   Add OpenCV script in package
    -   Add enabled WebRTC metrics: FPS and network bitrate
    -   Fix bug with form validation
    -   Add auto submit feature
    -   Add onMotion callback
    -   Add onUpdate callback
    -   Fixed logic for checking applicant status
    -   Fix bug with WebRTC stop connection
    -   Update TDVC lib to 1.4.0 version
    -   Add new errors checking
    -   Update video angles

-   **1.3.1**

    -   Added processing of Liveness Reflection check results
    -   Add new message for face capturing
    -   Performance improvement
    -   Update TDVC lib to 1.3.1

-   **1.3.0**

    -   Add applicantID in blConfig
    -   Add locales for liveness reflection calculating
    -   Fix server error message view
    -   Update TDVC lib to 1.3.0

-   **1.2.0**

    -   Add active liveness with head turns
    -   Optimize works with backend
    -   Change applicationFields and iceServers configs
    -   Add new styles and locales
    -   Fix bugs

-   **1.1.2**

    -   Update FaceMesh lib.
    -   Fix bugs with Safari browser

-   **1.1.1**

    -   Update Liveness Reflection algorithm.
    -   Fix bugs

-   **1.1.0**

    -   First release
