santoid-sdk 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 (57) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +259 -107
  3. package/api/AbstractService.d.ts +21 -0
  4. package/api/AbstractService.js +32 -0
  5. package/api/FaceMatchService.d.ts +9 -0
  6. package/api/FaceMatchService.js +15 -0
  7. package/api/TypificationService.d.ts +46 -0
  8. package/api/TypificationService.js +15 -0
  9. package/browser/liveness/index.js +1 -1
  10. package/liveness/index.d.ts +1 -3
  11. package/liveness/index.js +2 -19
  12. package/liveness/methods/livenessDetection/Service.d.ts +28 -0
  13. package/liveness/methods/livenessDetection/Service.js +130 -0
  14. package/liveness/methods/livenessDetection/index.d.ts +15 -0
  15. package/liveness/methods/livenessDetection/index.js +46 -0
  16. package/liveness/methods/uploadIdentificationDocument/Service.d.ts +62 -0
  17. package/liveness/methods/uploadIdentificationDocument/Service.js +134 -0
  18. package/liveness/methods/uploadIdentificationDocument/index.d.ts +24 -0
  19. package/liveness/methods/uploadIdentificationDocument/index.js +26 -0
  20. package/liveness/utils/getNextFrame.d.ts +6 -5
  21. package/liveness/utils/getNextFrame.js +24 -19
  22. package/liveness/utils/index.d.ts +2 -2
  23. package/node/liveness/index.d.ts +1 -3
  24. package/node/liveness/index.js +2 -19
  25. package/node/liveness/methods/livenessDetection/Service.d.ts +6 -0
  26. package/node/liveness/methods/livenessDetection/Service.js +20 -0
  27. package/node/liveness/methods/livenessDetection/index.d.ts +13 -0
  28. package/node/liveness/methods/livenessDetection/index.js +46 -0
  29. package/node/liveness/methods/uploadIdentificationDocument/Service.d.ts +4 -0
  30. package/node/liveness/methods/uploadIdentificationDocument/Service.js +19 -0
  31. package/node/liveness/methods/uploadIdentificationDocument/index.d.ts +25 -0
  32. package/node/liveness/methods/uploadIdentificationDocument/index.js +28 -0
  33. package/node/liveness/utils/index.d.ts +2 -2
  34. package/package.json +3 -3
  35. package/utils/error.d.ts +24 -0
  36. package/utils/error.js +27 -0
  37. package/utils/index.d.ts +7 -0
  38. package/utils/index.js +44 -0
  39. package/utils/types.d.ts +25 -14
  40. package/utils/websocket.d.ts +18 -0
  41. package/utils/websocket.js +57 -0
  42. package/liveness/methods/livenessDetection.d.ts +0 -6
  43. package/liveness/methods/livenessDetection.js +0 -129
  44. package/liveness/methods/uploadIdentificationDocument.d.ts +0 -91
  45. package/liveness/methods/uploadIdentificationDocument.js +0 -238
  46. package/liveness/utils/types.d.ts +0 -5
  47. package/liveness/utils/types.js +0 -17
  48. package/liveness/utils/websocket.d.ts +0 -3
  49. package/liveness/utils/websocket.js +0 -34
  50. package/node/liveness/methods/livenessDetection.d.ts +0 -6
  51. package/node/liveness/methods/livenessDetection.js +0 -114
  52. package/node/liveness/methods/uploadIdentificationDocument.d.ts +0 -91
  53. package/node/liveness/methods/uploadIdentificationDocument.js +0 -239
  54. package/node/liveness/utils/types.d.ts +0 -6
  55. package/node/liveness/utils/types.js +0 -17
  56. package/node/liveness/utils/websocket.d.ts +0 -5
  57. package/node/liveness/utils/websocket.js +0 -39
@@ -1,114 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.livenessDetection = void 0;
4
- const constants_1 = require("../../../utils/constants");
5
- const websocket_1 = require("../utils/websocket");
6
- async function onWebSocketMessage(options, event) {
7
- var _a, _b, _c;
8
- const message = event.data;
9
- let messageObj;
10
- try {
11
- messageObj = JSON.parse(message);
12
- }
13
- catch (err) {
14
- console.error('Cannot parse API message', err);
15
- }
16
- if ((messageObj === null || messageObj === void 0 ? void 0 : messageObj.next_step) && !messageObj.error) {
17
- await ((_a = options.nextStepCallback) === null || _a === void 0 ? void 0 : _a.call(options, messageObj.next_step));
18
- await ((_b = options[`${messageObj.next_step}Callback`]) === null || _b === void 0 ? void 0 : _b.call(options));
19
- }
20
- if (messageObj === null || messageObj === void 0 ? void 0 : messageObj.error) {
21
- await ((_c = options.errorCallback) === null || _c === void 0 ? void 0 : _c.call(options, { code: 'wrong-position' }));
22
- }
23
- return messageObj;
24
- }
25
- async function livenessDetection(options) {
26
- var _a, _b, _c;
27
- let websocketClosedBySDK = false;
28
- let validationSuccess = false;
29
- let endCalled = false;
30
- let canSendNextBytes = true;
31
- const successFrames = {
32
- front: undefined,
33
- right: undefined,
34
- left: undefined,
35
- up: undefined,
36
- bottom: undefined,
37
- };
38
- let lastSentBytes;
39
- let currentStep = 'front';
40
- async function stopLivenessDetection(options, websocket, intervalKey) {
41
- var _a;
42
- if (intervalKey) {
43
- clearInterval(intervalKey);
44
- }
45
- if (websocket) {
46
- (0, websocket_1.disconnectFromWebSocket)(websocket);
47
- }
48
- !endCalled && await ((_a = options.endCallback) === null || _a === void 0 ? void 0 : _a.call(options));
49
- endCalled = true;
50
- websocketClosedBySDK = true;
51
- }
52
- let sendFramesIntervalKey;
53
- let websocket;
54
- try {
55
- websocket = await (0, websocket_1.connectToWebSocket)(options);
56
- await ((_a = options.nextStepCallback) === null || _a === void 0 ? void 0 : _a.call(options, 'front'));
57
- await ((_b = options.frontCallback) === null || _b === void 0 ? void 0 : _b.call(options));
58
- sendFramesIntervalKey = setInterval(async () => {
59
- try {
60
- if (canSendNextBytes) {
61
- const bytes = await options.getNextFrame();
62
- if (bytes) {
63
- websocket === null || websocket === void 0 ? void 0 : websocket.send(bytes);
64
- lastSentBytes = bytes;
65
- canSendNextBytes = false;
66
- }
67
- }
68
- }
69
- catch (err) {
70
- await stopLivenessDetection(options, websocket, sendFramesIntervalKey);
71
- }
72
- }, constants_1.SEND_FRAMES_INTERVAL_MS);
73
- websocket.on('message', async (data) => {
74
- var _a;
75
- const parsedMessage = await onWebSocketMessage(options, { data: Buffer.from(data).toString() });
76
- if (parsedMessage) {
77
- canSendNextBytes = !!(parsedMessage === null || parsedMessage === void 0 ? void 0 : parsedMessage.can_send_next_bytes);
78
- }
79
- if ((parsedMessage === null || parsedMessage === void 0 ? void 0 : parsedMessage.validation) && currentStep) {
80
- successFrames[currentStep] = lastSentBytes;
81
- }
82
- if (parsedMessage === null || parsedMessage === void 0 ? void 0 : parsedMessage.next_step) {
83
- currentStep = parsedMessage.next_step;
84
- }
85
- if (parsedMessage === null || parsedMessage === void 0 ? void 0 : parsedMessage.success) {
86
- successFrames.bottom = lastSentBytes;
87
- validationSuccess = true;
88
- await ((_a = options.successCallback) === null || _a === void 0 ? void 0 : _a.call(options, { livenessId: parsedMessage.livenessId, successFrames }));
89
- await stopLivenessDetection(options, websocket, sendFramesIntervalKey);
90
- }
91
- });
92
- websocket.on('error', async (event) => {
93
- var _a;
94
- !validationSuccess && ((_a = options.errorCallback) === null || _a === void 0 ? void 0 : _a.call(options, { code: 'internal-error' }));
95
- await stopLivenessDetection(options, websocket, sendFramesIntervalKey);
96
- });
97
- websocket.on('close', async () => {
98
- var _a;
99
- if (!websocketClosedBySDK) {
100
- !validationSuccess && ((_a = options.errorCallback) === null || _a === void 0 ? void 0 : _a.call(options, { code: 'internal-error' }));
101
- await stopLivenessDetection(options, websocket, sendFramesIntervalKey);
102
- }
103
- });
104
- return {
105
- stopLivenessDetection: async () => { await stopLivenessDetection(options, websocket, sendFramesIntervalKey); },
106
- };
107
- }
108
- catch (err) {
109
- !validationSuccess && ((_c = options.errorCallback) === null || _c === void 0 ? void 0 : _c.call(options, { code: 'internal-error' }));
110
- await stopLivenessDetection(options, websocket, sendFramesIntervalKey);
111
- throw err;
112
- }
113
- }
114
- exports.livenessDetection = livenessDetection;
@@ -1,91 +0,0 @@
1
- import { type Data } from 'ws';
2
- import { type ILivenessResults, type TNodeSDKOptions, type IBaseSDKOptions, type TCallbackFunction, type TErrorCode } from '../utils/types';
3
- type TResultStatuses = 'success' | 'error' | null;
4
- type FileType = Data;
5
- interface ITypificationResult {
6
- n_documents: number;
7
- predictOCR: Array<{
8
- typification: {
9
- document_type: string;
10
- ocr_success: boolean;
11
- typification_score: number;
12
- };
13
- ocr_error?: boolean | null;
14
- ocr_message?: {
15
- template: string;
16
- labels: any;
17
- } | null;
18
- ocr_extraction: {
19
- template: string;
20
- labels: Array<{
21
- x: number;
22
- y: number;
23
- w: number;
24
- h: number;
25
- bottomRight: number[];
26
- topLeft: number[];
27
- dataField?: string;
28
- dataFieldValue?: boolean;
29
- ocr?: string | null;
30
- ocr_score?: number;
31
- cropBase64?: string | null;
32
- serpro_query?: {
33
- serpro_data: any;
34
- search_logs: {
35
- document: string;
36
- type: string;
37
- search_time: string;
38
- status_code: number;
39
- message: string;
40
- };
41
- };
42
- validation?: Record<string, number | boolean>;
43
- }> | null;
44
- } | boolean;
45
- }>;
46
- }
47
- interface IFaceMatchResult {
48
- comparison_score: number;
49
- similarity_score: number;
50
- match: boolean;
51
- }
52
- interface IUploadIdentificationDocumentResults {
53
- uploadedDocument: FileType | null;
54
- typification: {
55
- status: TResultStatuses;
56
- results: ITypificationResult | null;
57
- loading: boolean;
58
- error: any;
59
- };
60
- liveness: {
61
- status: TResultStatuses;
62
- results: ILivenessResults<FileType | null | undefined> | null;
63
- loading: boolean;
64
- error: any;
65
- };
66
- faceMatch: {
67
- status: TResultStatuses;
68
- results: IFaceMatchResult | null;
69
- loading: boolean;
70
- error: any;
71
- };
72
- }
73
- interface IUploadIdentificationDocumentOptions extends IBaseSDKOptions {
74
- resultChangeCallback: (results?: IUploadIdentificationDocumentResults) => void | Promise<void>;
75
- successCallback: <FrameType, ResultsType = ILivenessResults<FrameType>>(results?: ResultsType) => void | Promise<void>;
76
- errorCallback?: (error?: {
77
- code: TErrorCode;
78
- details?: any;
79
- }) => void | Promise<void>;
80
- endCallback?: TCallbackFunction;
81
- }
82
- export declare function uploadIdentificationDocument(options: IUploadIdentificationDocumentOptions): {
83
- getResults: () => IUploadIdentificationDocumentResults;
84
- startDocumentUpload: (file: FileType) => Promise<void>;
85
- startLivenessDetection: (startLivenessDetectionOptions: TNodeSDKOptions) => Promise<{
86
- stopLivenessDetection: () => Promise<void>;
87
- } | undefined>;
88
- startFaceComparison: () => void;
89
- startAll: (file: FileType, startLivenessDetectionOptions: TNodeSDKOptions) => void;
90
- };
91
- export {};
@@ -1,239 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.uploadIdentificationDocument = void 0;
7
- const form_data_1 = __importDefault(require("form-data"));
8
- const axios_1 = __importDefault(require("axios"));
9
- const constants_1 = require("../../../utils/constants");
10
- const utils_1 = require("../utils");
11
- const livenessDetection_1 = require("./livenessDetection");
12
- async function typificationPredict(options, file) {
13
- var _a, _b, _c;
14
- const formData = new form_data_1.default();
15
- formData.append('track', options.track);
16
- formData.append('imageFile', file, 'imageFile.jpg');
17
- const decodedToken = (0, utils_1.tryDecodeJwt)(options.token);
18
- const domain = (_a = options.domain) !== null && _a !== void 0 ? _a : (_b = decodedToken === null || decodedToken === void 0 ? void 0 : decodedToken.claims) === null || _b === void 0 ? void 0 : _b.domain;
19
- const axiosConfig = {
20
- headers: {
21
- 'Content-Type': 'multipart/form-data',
22
- Authorization: `Bearer ${options.token}`,
23
- },
24
- };
25
- if (axiosConfig.headers && domain) {
26
- axiosConfig.headers.Domain = domain;
27
- }
28
- const response = await axios_1.default.post(`${(_c = options === null || options === void 0 ? void 0 : options.customApiUrl) !== null && _c !== void 0 ? _c : constants_1.API_GATEWAY_URL}/api/v3/typification/predict`, formData, axiosConfig);
29
- return response.data;
30
- }
31
- async function faceMatch(options, firstImage, secondImage) {
32
- var _a, _b, _c;
33
- const formData = new form_data_1.default();
34
- formData.append('track', options.track);
35
- formData.append('firstImage', firstImage, 'firstImage.jpg');
36
- formData.append('secondImage', secondImage, 'secondImage.jpg');
37
- const decodedToken = (0, utils_1.tryDecodeJwt)(options.token);
38
- const domain = (_a = options.domain) !== null && _a !== void 0 ? _a : (_b = decodedToken === null || decodedToken === void 0 ? void 0 : decodedToken.claims) === null || _b === void 0 ? void 0 : _b.domain;
39
- const axiosConfig = {
40
- params: {
41
- sensitive_data_compliance: true,
42
- },
43
- headers: {
44
- 'Content-Type': 'multipart/form-data',
45
- Authorization: `Bearer ${options.token}`,
46
- },
47
- };
48
- if (axiosConfig.headers && domain) {
49
- axiosConfig.headers.Domain = domain;
50
- }
51
- const response = await axios_1.default.post(`${(_c = options === null || options === void 0 ? void 0 : options.customApiUrl) !== null && _c !== void 0 ? _c : constants_1.API_GATEWAY_URL}/api/v1/facematch/pair`, formData, axiosConfig);
52
- return response.data;
53
- }
54
- function uploadIdentificationDocument(options) {
55
- let results = {
56
- uploadedDocument: null,
57
- typification: {
58
- status: null,
59
- results: null,
60
- loading: false,
61
- error: null,
62
- },
63
- liveness: {
64
- status: null,
65
- results: null,
66
- loading: false,
67
- error: null,
68
- },
69
- faceMatch: {
70
- status: null,
71
- results: null,
72
- loading: false,
73
- error: null,
74
- },
75
- };
76
- async function startFaceMatch(firstImage, secondImage) {
77
- var _a, _b, _c;
78
- try {
79
- updateResults({
80
- faceMatch: {
81
- status: null,
82
- results: null,
83
- loading: true,
84
- error: null,
85
- },
86
- });
87
- const faceMatchResults = await faceMatch(options, firstImage, secondImage);
88
- updateResults({
89
- faceMatch: {
90
- results: faceMatchResults,
91
- status: 'success',
92
- loading: false,
93
- error: null,
94
- },
95
- });
96
- }
97
- catch (err) {
98
- await ((_a = options.errorCallback) === null || _a === void 0 ? void 0 : _a.call(options, { code: 'face-match-error', details: (_b = err === null || err === void 0 ? void 0 : err.response) === null || _b === void 0 ? void 0 : _b.data }));
99
- updateResults({
100
- faceMatch: {
101
- results: null,
102
- status: 'error',
103
- loading: false,
104
- error: (_c = err === null || err === void 0 ? void 0 : err.response) === null || _c === void 0 ? void 0 : _c.data,
105
- },
106
- });
107
- }
108
- }
109
- function tryStartFaceMatch() {
110
- var _a;
111
- if (results.uploadedDocument &&
112
- ((_a = results.liveness.results) === null || _a === void 0 ? void 0 : _a.successFrames.front) &&
113
- !results.faceMatch.results &&
114
- !results.faceMatch.loading) {
115
- void startFaceMatch(results.uploadedDocument, results.liveness.results.successFrames.front);
116
- }
117
- }
118
- function updateUploadedDocument(file) {
119
- results.uploadedDocument = file;
120
- tryStartFaceMatch();
121
- }
122
- function updateResults(updatedResults) {
123
- var _a, _b, _c;
124
- results = Object.assign(Object.assign({}, results), updatedResults);
125
- void ((_a = options.resultChangeCallback) === null || _a === void 0 ? void 0 : _a.call(options, results));
126
- if (Object.entries(results).every(([key, value]) => key === 'uploadedDocument' || !!value.results)) {
127
- void ((_b = options.successCallback) === null || _b === void 0 ? void 0 : _b.call(options, results));
128
- void ((_c = options.endCallback) === null || _c === void 0 ? void 0 : _c.call(options));
129
- return;
130
- }
131
- if (results.faceMatch.status !== 'error') {
132
- tryStartFaceMatch();
133
- }
134
- }
135
- async function startDocumentUpload(file) {
136
- var _a, _b, _c;
137
- try {
138
- updateResults({
139
- typification: {
140
- status: null,
141
- results: null,
142
- loading: true,
143
- error: null,
144
- },
145
- });
146
- updateUploadedDocument(file);
147
- const typificationResults = await typificationPredict(options, file);
148
- updateResults({
149
- typification: {
150
- status: 'success',
151
- results: typificationResults,
152
- loading: false,
153
- error: null,
154
- },
155
- });
156
- }
157
- catch (err) {
158
- await ((_a = options.errorCallback) === null || _a === void 0 ? void 0 : _a.call(options, { code: 'typification-error', details: (_b = err === null || err === void 0 ? void 0 : err.response) === null || _b === void 0 ? void 0 : _b.data }));
159
- updateResults({
160
- typification: {
161
- status: 'error',
162
- results: null,
163
- loading: false,
164
- error: (_c = err === null || err === void 0 ? void 0 : err.response) === null || _c === void 0 ? void 0 : _c.data,
165
- },
166
- });
167
- }
168
- }
169
- async function startLivenessDetection(startLivenessDetectionOptions) {
170
- var _a, _b, _c, _d, _e;
171
- const adaptedLivenessOptions = Object.assign({}, startLivenessDetectionOptions);
172
- delete adaptedLivenessOptions.successCallback;
173
- delete adaptedLivenessOptions.errorCallback;
174
- updateResults({
175
- liveness: {
176
- results: null,
177
- status: null,
178
- loading: true,
179
- error: null,
180
- },
181
- });
182
- try {
183
- return await (0, livenessDetection_1.livenessDetection)(Object.assign(Object.assign({ domain: options.domain, customId: options.customId, customWebSocketUrl: options.customWebSocketUrl, successCallback: (livenessResults) => {
184
- var _a;
185
- void ((_a = startLivenessDetectionOptions === null || startLivenessDetectionOptions === void 0 ? void 0 : startLivenessDetectionOptions.successCallback) === null || _a === void 0 ? void 0 : _a.call(startLivenessDetectionOptions, livenessResults));
186
- updateResults({
187
- liveness: {
188
- status: 'success',
189
- results: (livenessResults),
190
- loading: false,
191
- error: null,
192
- },
193
- });
194
- }, errorCallback: async (livenessErrorDetails) => {
195
- var _a, _b;
196
- if ((livenessErrorDetails === null || livenessErrorDetails === void 0 ? void 0 : livenessErrorDetails.code) === 'wrong-position') {
197
- void ((_a = startLivenessDetectionOptions === null || startLivenessDetectionOptions === void 0 ? void 0 : startLivenessDetectionOptions.errorCallback) === null || _a === void 0 ? void 0 : _a.call(startLivenessDetectionOptions, livenessErrorDetails));
198
- }
199
- else {
200
- void ((_b = options.errorCallback) === null || _b === void 0 ? void 0 : _b.call(options, livenessErrorDetails));
201
- }
202
- updateResults({
203
- liveness: {
204
- status: 'error',
205
- results: null,
206
- loading: (livenessErrorDetails === null || livenessErrorDetails === void 0 ? void 0 : livenessErrorDetails.code) === 'wrong-position',
207
- error: livenessErrorDetails,
208
- },
209
- });
210
- } }, adaptedLivenessOptions), { token: (_a = adaptedLivenessOptions.token) !== null && _a !== void 0 ? _a : options.token, track: (_b = adaptedLivenessOptions.track) !== null && _b !== void 0 ? _b : options.track }));
211
- }
212
- catch (err) {
213
- await ((_c = options.errorCallback) === null || _c === void 0 ? void 0 : _c.call(options, { code: 'liveness-error', details: (_d = err === null || err === void 0 ? void 0 : err.response) === null || _d === void 0 ? void 0 : _d.data }));
214
- updateResults({
215
- liveness: {
216
- status: 'error',
217
- results: null,
218
- loading: false,
219
- error: (_e = err === null || err === void 0 ? void 0 : err.response) === null || _e === void 0 ? void 0 : _e.data,
220
- },
221
- });
222
- }
223
- }
224
- function startAll(file, startLivenessDetectionOptions) {
225
- void startDocumentUpload(file);
226
- void startLivenessDetection(startLivenessDetectionOptions);
227
- }
228
- function getResults() {
229
- return results;
230
- }
231
- return {
232
- getResults,
233
- startDocumentUpload,
234
- startLivenessDetection,
235
- startFaceComparison: tryStartFaceMatch,
236
- startAll,
237
- };
238
- }
239
- exports.uploadIdentificationDocument = uploadIdentificationDocument;
@@ -1,6 +0,0 @@
1
- import { type Data } from 'ws';
2
- import { type ISDKOptions } from '../../../utils/types';
3
- export type TNodeSDKOptions = ISDKOptions & {
4
- getNextFrame: () => Promise<Data | null>;
5
- };
6
- export * from '../../../utils/types';
@@ -1,17 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("../../../utils/types"), exports);
@@ -1,5 +0,0 @@
1
- import WebSocket from 'ws';
2
- import { type TNodeSDKOptions } from './types';
3
- export declare function waitForWebSocketConnection(websocket: WebSocket): Promise<void>;
4
- export declare function connectToWebSocket(options: TNodeSDKOptions): Promise<WebSocket>;
5
- export declare function disconnectFromWebSocket(websocket: WebSocket): void;
@@ -1,39 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.disconnectFromWebSocket = exports.connectToWebSocket = exports.waitForWebSocketConnection = void 0;
7
- const ws_1 = __importDefault(require("ws"));
8
- const _1 = require(".");
9
- const constants_1 = require("../../../utils/constants");
10
- async function waitForWebSocketConnection(websocket) {
11
- await new Promise((resolve) => {
12
- const intervalKey = setInterval(() => {
13
- if ([3, 1].includes(websocket.readyState)) {
14
- clearInterval(intervalKey);
15
- resolve();
16
- }
17
- }, 5);
18
- });
19
- if (websocket.readyState === 3) {
20
- throw new Error('Cannot connect to server');
21
- }
22
- }
23
- exports.waitForWebSocketConnection = waitForWebSocketConnection;
24
- async function connectToWebSocket(options) {
25
- var _a, _b;
26
- const decodedToken = (0, _1.decodeJwt)(options.token);
27
- const query = `?x_endpoint_api_userinfo=${options.token}&domain=${(_a = options.domain) !== null && _a !== void 0 ? _a : decodedToken.claims.domain}&track=${options.track}&customerRequestId=${options.customId}`;
28
- const websocket = new ws_1.default(`${(_b = options.customWebSocketUrl) !== null && _b !== void 0 ? _b : constants_1.WEBSOCKET_BASE_URL}${query}`);
29
- await waitForWebSocketConnection(websocket);
30
- return websocket;
31
- }
32
- exports.connectToWebSocket = connectToWebSocket;
33
- function disconnectFromWebSocket(websocket) {
34
- var _a;
35
- if (![2, 3].includes(websocket.readyState)) {
36
- (_a = websocket.close) === null || _a === void 0 ? void 0 : _a.call(websocket);
37
- }
38
- }
39
- exports.disconnectFromWebSocket = disconnectFromWebSocket;