@privateid/ultrapass-web-sdk 1.3.1 → 1.3.2-1300478

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 (216) hide show
  1. package/README.md +75 -75
  2. package/dist/apiUtils.d.ts +46 -46
  3. package/dist/apiUtils.js +922 -922
  4. package/dist/application/index.d.ts +7 -7
  5. package/dist/application/index.js +27 -27
  6. package/dist/application/modules/core/document/DocumentService.d.ts +22 -22
  7. package/dist/application/modules/core/document/DocumentService.js +254 -254
  8. package/dist/application/modules/core/document/document.constants.d.ts +15 -15
  9. package/dist/application/modules/core/document/document.constants.js +21 -21
  10. package/dist/application/modules/core/document/document.domain.d.ts +7 -7
  11. package/dist/application/modules/core/document/document.domain.js +1 -1
  12. package/dist/application/modules/core/document/document.types.d.ts +17 -17
  13. package/dist/application/modules/core/document/document.types.js +1 -1
  14. package/dist/application/modules/core/document/document.utils.d.ts +3 -3
  15. package/dist/application/modules/core/document/document.utils.js +58 -58
  16. package/dist/application/modules/core/document/index.d.ts +3 -3
  17. package/dist/application/modules/core/document/index.js +1 -1
  18. package/dist/application/modules/core/face/FaceService.d.ts +33 -33
  19. package/dist/application/modules/core/face/FaceService.js +228 -221
  20. package/dist/application/modules/core/face/FaceService.js.map +1 -1
  21. package/dist/application/modules/core/face/face.constants.d.ts +53 -53
  22. package/dist/application/modules/core/face/face.constants.js +53 -53
  23. package/dist/application/modules/core/face/face.domain.d.ts +10 -10
  24. package/dist/application/modules/core/face/face.domain.js +1 -1
  25. package/dist/application/modules/core/face/face.types.d.ts +41 -38
  26. package/dist/application/modules/core/face/face.types.js +1 -1
  27. package/dist/application/modules/core/face/face.utils.d.ts +15 -15
  28. package/dist/application/modules/core/face/face.utils.js +101 -101
  29. package/dist/application/modules/core/face/index.d.ts +3 -3
  30. package/dist/application/modules/core/face/index.js +1 -1
  31. package/dist/application/modules/global/shared.constants.d.ts +2 -2
  32. package/dist/application/modules/global/shared.constants.js +2 -2
  33. package/dist/application/modules/global/shared.utils.d.ts +25 -25
  34. package/dist/application/modules/global/shared.utils.js +100 -100
  35. package/dist/application/modules/global/shared.utils.js.map +1 -1
  36. package/dist/application/modules/internal/feature-flag/LDFeatureFlagService.d.ts +9 -0
  37. package/dist/application/modules/internal/feature-flag/LDFeatureFlagService.js +32 -0
  38. package/dist/application/modules/internal/feature-flag/LDFeatureFlagService.js.map +1 -0
  39. package/dist/application/modules/internal/feature-flag/feature-flag-init.d.ts +11 -0
  40. package/dist/application/modules/internal/feature-flag/feature-flag-init.js +24 -0
  41. package/dist/application/modules/internal/feature-flag/feature-flag-init.js.map +1 -0
  42. package/dist/application/modules/internal/feature-flag/feature-flag.domain.d.ts +10 -0
  43. package/dist/application/modules/internal/feature-flag/feature-flag.domain.js +7 -0
  44. package/dist/application/modules/internal/feature-flag/feature-flag.domain.js.map +1 -0
  45. package/dist/application/modules/internal/feature-flag/featureFlagInit.d.ts +11 -0
  46. package/dist/application/modules/internal/feature-flag/featureFlagInit.js +44 -0
  47. package/dist/application/modules/internal/feature-flag/featureFlagInit.js.map +1 -0
  48. package/dist/application/modules/internal/feature-flag/index.d.ts +2 -0
  49. package/dist/application/modules/internal/feature-flag/index.js +3 -0
  50. package/dist/application/modules/internal/feature-flag/index.js.map +1 -0
  51. package/dist/application/modules/internal/shared/index.d.ts +2 -0
  52. package/dist/application/modules/internal/shared/index.js +3 -0
  53. package/dist/application/modules/internal/shared/index.js.map +1 -0
  54. package/dist/application/modules/internal/shared/shared.constants.d.ts +2 -0
  55. package/dist/application/modules/internal/shared/shared.constants.js +3 -0
  56. package/dist/application/modules/internal/shared/shared.constants.js.map +1 -0
  57. package/dist/application/modules/internal/shared/shared.utils.d.ts +44 -0
  58. package/dist/application/modules/internal/shared/shared.utils.js +204 -0
  59. package/dist/application/modules/internal/shared/shared.utils.js.map +1 -0
  60. package/dist/application/modules/internal/wasm-orchestrator/WasmOrchestratorService.d.ts +28 -0
  61. package/dist/application/modules/internal/wasm-orchestrator/WasmOrchestratorService.js +380 -0
  62. package/dist/application/modules/internal/wasm-orchestrator/WasmOrchestratorService.js.map +1 -0
  63. package/dist/application/modules/internal/wasm-orchestrator/index.d.ts +6 -0
  64. package/dist/application/modules/internal/wasm-orchestrator/index.js +9 -0
  65. package/dist/application/modules/internal/wasm-orchestrator/index.js.map +1 -0
  66. package/dist/application/modules/internal/wasm-orchestrator/wasm-orchestrator.constants.d.ts +28 -0
  67. package/dist/application/modules/internal/wasm-orchestrator/wasm-orchestrator.constants.js +35 -0
  68. package/dist/application/modules/internal/wasm-orchestrator/wasm-orchestrator.constants.js.map +1 -0
  69. package/dist/application/modules/internal/wasm-orchestrator/wasm-orchestrator.domain.d.ts +51 -0
  70. package/dist/application/modules/internal/wasm-orchestrator/wasm-orchestrator.domain.js +2 -0
  71. package/dist/application/modules/internal/wasm-orchestrator/wasm-orchestrator.domain.js.map +1 -0
  72. package/dist/application/modules/internal/wasm-orchestrator/wasm-orchestrator.types.d.ts +142 -0
  73. package/dist/application/modules/internal/wasm-orchestrator/wasm-orchestrator.types.js +2 -0
  74. package/dist/application/modules/internal/wasm-orchestrator/wasm-orchestrator.types.js.map +1 -0
  75. package/dist/application/modules/internal/wasm-orchestrator/wasm-orchestrator.utils.d.ts +86 -0
  76. package/dist/application/modules/internal/wasm-orchestrator/wasm-orchestrator.utils.js +201 -0
  77. package/dist/application/modules/internal/wasm-orchestrator/wasm-orchestrator.utils.js.map +1 -0
  78. package/dist/application/modules/support/camera/CameraServiceFactory.d.ts +10 -10
  79. package/dist/application/modules/support/camera/CameraServiceFactory.js +33 -33
  80. package/dist/application/modules/support/camera/CameraServiceFactory.js.map +1 -1
  81. package/dist/application/modules/support/camera/camera.constants.d.ts +9 -9
  82. package/dist/application/modules/support/camera/camera.constants.js +48 -48
  83. package/dist/application/modules/support/camera/camera.domain.d.ts +15 -15
  84. package/dist/application/modules/support/camera/camera.domain.js +1 -1
  85. package/dist/application/modules/support/camera/camera.types.d.ts +42 -42
  86. package/dist/application/modules/support/camera/camera.types.js +10 -10
  87. package/dist/application/modules/support/camera/camera.utils.d.ts +157 -157
  88. package/dist/application/modules/support/camera/camera.utils.js +623 -623
  89. package/dist/application/modules/support/camera/index.d.ts +24 -24
  90. package/dist/application/modules/support/camera/index.js +27 -27
  91. package/dist/application/modules/support/camera/services/BaseCameraService.d.ts +41 -41
  92. package/dist/application/modules/support/camera/services/BaseCameraService.js +278 -278
  93. package/dist/application/modules/support/camera/services/DesktopCameraService.d.ts +5 -5
  94. package/dist/application/modules/support/camera/services/DesktopCameraService.js +46 -46
  95. package/dist/application/modules/support/camera/services/FirefoxCameraService.d.ts +5 -5
  96. package/dist/application/modules/support/camera/services/FirefoxCameraService.js +46 -46
  97. package/dist/application/modules/support/camera/services/MacSafariCameraService.d.ts +5 -5
  98. package/dist/application/modules/support/camera/services/MacSafariCameraService.js +47 -47
  99. package/dist/application/modules/support/camera/services/MobileCameraService.d.ts +5 -5
  100. package/dist/application/modules/support/camera/services/MobileCameraService.js +133 -133
  101. package/dist/application/modules/support/engine/EngineService.d.ts +15 -0
  102. package/dist/application/modules/support/engine/EngineService.js +106 -0
  103. package/dist/application/modules/support/engine/EngineService.js.map +1 -0
  104. package/dist/application/modules/support/engine/engine.constants.d.ts +33 -0
  105. package/dist/application/modules/support/engine/engine.constants.js +35 -0
  106. package/dist/application/modules/support/engine/engine.constants.js.map +1 -0
  107. package/dist/application/modules/support/engine/engine.domain.d.ts +23 -0
  108. package/dist/application/modules/support/engine/engine.domain.js +2 -0
  109. package/dist/application/modules/support/engine/engine.domain.js.map +1 -0
  110. package/dist/application/modules/support/engine/engine.types.d.ts +32 -0
  111. package/dist/application/modules/support/engine/engine.types.js +2 -0
  112. package/dist/application/modules/support/engine/engine.types.js.map +1 -0
  113. package/dist/application/modules/support/engine/engine.utils.d.ts +65 -0
  114. package/dist/application/modules/support/engine/engine.utils.js +135 -0
  115. package/dist/application/modules/support/engine/engine.utils.js.map +1 -0
  116. package/dist/application/modules/support/engine/index.d.ts +3 -0
  117. package/dist/application/modules/support/engine/index.js +2 -0
  118. package/dist/application/modules/support/engine/index.js.map +1 -0
  119. package/dist/application/modules/support/permissions/PermissionsService.d.ts +55 -55
  120. package/dist/application/modules/support/permissions/PermissionsService.js +183 -183
  121. package/dist/application/modules/support/permissions/index.d.ts +4 -4
  122. package/dist/application/modules/support/permissions/index.js +2 -2
  123. package/dist/application/modules/support/permissions/permission.utils.d.ts +6 -6
  124. package/dist/application/modules/support/permissions/permission.utils.js +33 -33
  125. package/dist/application/modules/support/permissions/permissions.domain.d.ts +6 -6
  126. package/dist/application/modules/support/permissions/permissions.domain.js +1 -1
  127. package/dist/application/modules/support/permissions/permissions.types.d.ts +9 -9
  128. package/dist/application/modules/support/permissions/permissions.types.js +1 -1
  129. package/dist/application/modules/support/wasm/WasmService.d.ts +25 -25
  130. package/dist/application/modules/support/wasm/WasmService.js +156 -155
  131. package/dist/application/modules/support/wasm/WasmService.js.map +1 -1
  132. package/dist/application/modules/support/wasm/index.d.ts +6 -6
  133. package/dist/application/modules/support/wasm/index.js +8 -8
  134. package/dist/application/modules/support/wasm/wasm.constants.d.ts +78 -78
  135. package/dist/application/modules/support/wasm/wasm.constants.js +86 -86
  136. package/dist/application/modules/support/wasm/wasm.domain.d.ts +52 -52
  137. package/dist/application/modules/support/wasm/wasm.domain.js +1 -1
  138. package/dist/application/modules/support/wasm/wasm.types.d.ts +119 -118
  139. package/dist/application/modules/support/wasm/wasm.types.js +1 -1
  140. package/dist/application/modules/support/wasm/wasm.utils.d.ts +88 -88
  141. package/dist/application/modules/support/wasm/wasm.utils.js +243 -243
  142. package/dist/application/modules/support/wasm-orchestrator/WasmOrchestratorService.d.ts +28 -0
  143. package/dist/application/modules/support/wasm-orchestrator/WasmOrchestratorService.js +324 -0
  144. package/dist/application/modules/support/wasm-orchestrator/WasmOrchestratorService.js.map +1 -0
  145. package/dist/application/modules/support/wasm-orchestrator/index.d.ts +6 -0
  146. package/dist/application/modules/support/wasm-orchestrator/index.js +9 -0
  147. package/dist/application/modules/support/wasm-orchestrator/index.js.map +1 -0
  148. package/dist/application/modules/support/wasm-orchestrator/wasm-orchestrator.constants.d.ts +36 -0
  149. package/dist/application/modules/support/wasm-orchestrator/wasm-orchestrator.constants.js +44 -0
  150. package/dist/application/modules/support/wasm-orchestrator/wasm-orchestrator.constants.js.map +1 -0
  151. package/dist/application/modules/support/wasm-orchestrator/wasm-orchestrator.domain.d.ts +47 -0
  152. package/dist/application/modules/support/wasm-orchestrator/wasm-orchestrator.domain.js +2 -0
  153. package/dist/application/modules/support/wasm-orchestrator/wasm-orchestrator.domain.js.map +1 -0
  154. package/dist/application/modules/support/wasm-orchestrator/wasm-orchestrator.types.d.ts +136 -0
  155. package/dist/application/modules/support/wasm-orchestrator/wasm-orchestrator.types.js +2 -0
  156. package/dist/application/modules/support/wasm-orchestrator/wasm-orchestrator.types.js.map +1 -0
  157. package/dist/application/modules/support/wasm-orchestrator/wasm-orchestrator.utils.d.ts +91 -0
  158. package/dist/application/modules/support/wasm-orchestrator/wasm-orchestrator.utils.js +250 -0
  159. package/dist/application/modules/support/wasm-orchestrator/wasm-orchestrator.utils.js.map +1 -0
  160. package/dist/application/workers/index.d.ts +42 -42
  161. package/dist/application/workers/index.js +8 -8
  162. package/dist/application/workers/wasm/WasmWorkerService.d.ts +66 -0
  163. package/dist/application/workers/wasm/WasmWorkerService.js +801 -0
  164. package/dist/application/workers/wasm/WasmWorkerService.js.map +1 -0
  165. package/dist/application/workers/wasm/index.d.ts +4 -0
  166. package/dist/application/workers/wasm/index.js +9 -0
  167. package/dist/application/workers/wasm/index.js.map +1 -0
  168. package/dist/application/workers/wasm/wasm-worker.constants.d.ts +5 -0
  169. package/dist/application/workers/wasm/wasm-worker.constants.js +6 -0
  170. package/dist/application/workers/wasm/wasm-worker.constants.js.map +1 -0
  171. package/dist/application/workers/wasm/wasm-worker.domain.d.ts +99 -0
  172. package/dist/application/workers/wasm/wasm-worker.domain.js +2 -0
  173. package/dist/application/workers/wasm/wasm-worker.domain.js.map +1 -0
  174. package/dist/application/workers/wasm/wasm-worker.types.d.ts +88 -0
  175. package/dist/application/workers/wasm/wasm-worker.types.js +2 -0
  176. package/dist/application/workers/wasm/wasm-worker.types.js.map +1 -0
  177. package/dist/application/workers/wasm/wasm-worker.utils.d.ts +10 -0
  178. package/dist/application/workers/wasm/wasm-worker.utils.js +130 -0
  179. package/dist/application/workers/wasm/wasm-worker.utils.js.map +1 -0
  180. package/dist/buildConfig.d.ts +3 -0
  181. package/dist/buildConfig.js +7 -0
  182. package/dist/buildConfig.js.map +1 -0
  183. package/dist/cameraUtils.d.ts +77 -77
  184. package/dist/cameraUtils.js +361 -361
  185. package/dist/constants.d.ts +9 -9
  186. package/dist/constants.js +13 -13
  187. package/dist/createCallback.d.ts +56 -56
  188. package/dist/createCallback.js +332 -331
  189. package/dist/createCallback.js.map +1 -1
  190. package/dist/dbUtils.d.ts +14 -14
  191. package/dist/dbUtils.js +148 -148
  192. package/dist/envUtils.d.ts +4 -4
  193. package/dist/envUtils.js +16 -16
  194. package/dist/faceModule.d.ts +196 -196
  195. package/dist/faceModule.js +978 -978
  196. package/dist/featureFlagInit.d.ts +11 -0
  197. package/dist/featureFlagInit.js +44 -0
  198. package/dist/featureFlagInit.js.map +1 -0
  199. package/dist/index.d.ts +38 -38
  200. package/dist/index.js +82 -82
  201. package/dist/main.d.ts +30 -30
  202. package/dist/main.js +84 -84
  203. package/dist/types.d.ts +139 -139
  204. package/dist/types.js +77 -77
  205. package/dist/utils.d.ts +84 -84
  206. package/dist/utils.js +580 -580
  207. package/package.json +102 -102
  208. package/wasm/ultra/nosimd/{25.11.13-1357710 → 26.01.08-1300478}/privid_fhe_uber.js +18 -18
  209. package/wasm/ultra/nosimd/{25.11.13-1357710 → 26.01.08-1300478}/privid_fhe_uber.wasm +0 -0
  210. package/wasm/ultra/nosimd/version.json +2 -2
  211. package/wasm/ultra/simd/{25.11.13-1357710 → 26.01.08-1300478}/privid_fhe_uber.js +18 -18
  212. package/wasm/ultra/simd/{25.11.13-1357710 → 26.01.08-1300478}/privid_fhe_uber.wasm +0 -0
  213. package/wasm/ultra/simd/version.json +2 -2
  214. package/workers/comlink.min.js +7 -7
  215. package/workers/comlink.min.js.map +1 -1
  216. package/workers/wasm.worker.js +936 -924
@@ -1,924 +1,936 @@
1
- /* eslint-disable no-eval */
2
- /* eslint-disable default-param-last */
3
- /* eslint-disable no-undef */
4
- /* eslint-disable no-underscore-dangle */
5
- // importScripts('https://unpkg.com/comlink/dist/umd/comlink.js');
6
-
7
- importScripts('./comlink.min.js');
8
-
9
- var wasmPrivModules;
10
- let apiUrl;
11
- let sesstionToken;
12
- let publicKey;
13
- let debugType;
14
- let inputPtr;
15
- let imageInputSize;
16
- let barCodePtr;
17
- let privid_wasm_result = null;
18
- let privid_wasm_error = null;
19
- let wasmSession = null;
20
- let setCache = true;
21
- let checkWasmLoaded = false;
22
- let antispoofVersion;
23
- const ModuleName = 'ultra';
24
- const cdnUrl = 'https://ultra-wasm.devel.privateid.com'; // Devel
25
- // const cdnUrl = 'https://ultra-wasm.privateid.com/wasm'; // Prod
26
- let useCdnLink = true;
27
-
28
- const createImageArguments = (imageData, width, height) => {};
29
-
30
- const createStringArguments = () => {};
31
-
32
- const printLogs = (message, data, type = 'LOG') => {
33
- console.log('FROM_SDK_WORKER', message, data);
34
- const errorLogs = ['1', '2', '3', '901', '902', '903'];
35
- const warningLogs = ['2', '3', '902', '903'];
36
- const allLogs = ['3', '903'];
37
-
38
- if (type === 'ERROR' && errorLogs.includes('3')) {
39
- console.error('DEBUG_SDK_WASM_WORKER', message, data);
40
- } else if (type === 'WARN' && warningLogs.includes('3')) {
41
- console.warn('DEBUG_SDK_WASM_WORKER', message, data);
42
- } else if (type === 'LOG' && allLogs.includes('3')) {
43
- console.log('DEBUG_SDK_WASM_WORKER', message, data);
44
- }
45
- };
46
-
47
- const isLoad = (
48
- simd,
49
- url,
50
- session_token,
51
- public_key,
52
- debug_type,
53
- cacheConfig = true,
54
- timeout = 5000,
55
- useCdn = false,
56
- shouldRegenerateSession,
57
- failureCb,
58
- usageScenario,
59
- cache_content,
60
- ) =>
61
- new Promise(async (resolve, reject) => {
62
- apiUrl = url;
63
- sesstionToken = session_token;
64
- publicKey = public_key;
65
- useCdnLink = useCdn;
66
- privid_wasm_error = failureCb;
67
- if (debug_type) {
68
- debugType = debug_type;
69
- }
70
- let timeoutSession = 5000;
71
- if (timeout) {
72
- timeoutSession = timeout;
73
- }
74
- setCache = cacheConfig;
75
-
76
- printLogs(`data: `, { simd, url, session_token, public_key, debug_type, cache_content });
77
-
78
- const modulePath = simd ? 'simd' : 'nosimd';
79
- const moduleName = 'privid_fhe_uber';
80
- const cachedModule = await readKey(ModuleName);
81
- // const fetchdVersion = await fetchdWasmVersion.json();
82
- const fetchdWasmVersion = await (await fetch(`../wasm/${ModuleName}/${modulePath}/version.json`)).json();
83
-
84
- printLogs(
85
- `versions: cached:
86
- ${cachedModule ? cachedModule?.version.toString() : 'no cached wasm'},
87
- fetched:
88
- ${fetchdWasmVersion ? fetchdWasmVersion.version.toString() : 'no fetched version'})
89
- modulePath: ${modulePath}`,
90
- '',
91
- );
92
-
93
- const loadFromPackage = async () => {
94
- printLogs(`fetched version: `, fetchdWasmVersion);
95
- wasmPrivModules = await loadWasmModule(modulePath, moduleName, true, `${fetchdWasmVersion.version}`);
96
- printLogs(`ULTRA MODULE: `, wasmPrivModules);
97
- if (!checkWasmLoaded) {
98
- await initializeWasmSession(
99
- url,
100
- sesstionToken,
101
- publicKey,
102
- debugType,
103
- timeoutSession,
104
- usageScenario,
105
- cache_content,
106
- );
107
- checkWasmLoaded = true;
108
- }
109
- resolve('Loaded');
110
- };
111
-
112
- if (
113
- cachedModule &&
114
- cachedModule.version &&
115
- fetchdWasmVersion &&
116
- fetchdWasmVersion.version &&
117
- cachedModule.version.toString() === fetchdWasmVersion?.version.toString()
118
- ) {
119
- printLogs(`same version confirmed`, '');
120
- printLogs(`PRIVMODULES LOADED?: `, wasmPrivModules);
121
- if (!wasmPrivModules) {
122
- const { cachedWasm, cachedScript } = cachedModule;
123
-
124
- if (cachedWasm && cachedScript) {
125
- eval(cachedScript);
126
- wasmPrivModules = await createTFLiteModule({ wasmBinary: cachedWasm });
127
- printLogs(`ULTRA MODULE `, wasmPrivModules);
128
- if (!checkWasmLoaded) {
129
- await initializeWasmSession(
130
- url,
131
- sesstionToken,
132
- publicKey,
133
- debugType,
134
- timeoutSession,
135
- usageScenario,
136
- cache_content,
137
- );
138
- checkWasmLoaded = true;
139
- }
140
- printLogs(`WASM MODULES: `, wasmPrivModules);
141
- } else {
142
- await loadFromPackage();
143
- }
144
- } else if (wasmPrivModules && shouldRegenerateSession) {
145
- wasmSession = null;
146
- await initializeWasmSession(
147
- url,
148
- sesstionToken,
149
- publicKey,
150
- debugType,
151
- timeoutSession,
152
- usageScenario,
153
- cache_content,
154
- );
155
- } else {
156
- await loadFromPackage();
157
- }
158
- resolve('Cache Loaded');
159
- } else {
160
- await loadFromPackage();
161
- }
162
- });
163
-
164
- function flatten(arrays, TypedArray) {
165
- const arr = new TypedArray(arrays.reduce((n, a) => n + a.length, 0));
166
- let i = 0;
167
- arrays.forEach((a) => {
168
- arr.set(a, i);
169
- i += a.length;
170
- });
171
- return arr;
172
- }
173
-
174
- const ultraEnroll = async (imageData, simd, config, cb) => {
175
- privid_wasm_result = cb;
176
-
177
- if (!wasmPrivModules) {
178
- await isLoad(simd, apiUrl, sesstionToken, publicKey, debugType);
179
- }
180
-
181
- const imageInputSize = imageData.data.length * imageData.data.BYTES_PER_ELEMENT;
182
- const imageInputPtr = wasmPrivModules._malloc(imageInputSize);
183
- wasmPrivModules.HEAPU8.set(new Uint8Array(imageData.data), imageInputPtr);
184
- const resultFirstPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
185
- const resultLenPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
186
- const encoder = new TextEncoder();
187
- const config_bytes = encoder.encode(`${config}`);
188
- const configInputSize = config_bytes.length;
189
- const configInputPtr = wasmPrivModules._malloc(configInputSize);
190
- const bestImageFirstPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
191
- const bestImageLenPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
192
- wasmPrivModules.HEAP8.set(config_bytes, configInputPtr / config_bytes.BYTES_PER_ELEMENT);
193
- printLogs(`config: `, config);
194
- try {
195
- wasmPrivModules._privid_user_enroll(
196
- wasmSession /* session pointer */,
197
- configInputPtr,
198
- configInputSize,
199
- imageInputPtr /* input images */,
200
- imageData.width /* width of one image */,
201
- imageData.height /* height of one image */,
202
- resultFirstPtr /* operation result output buffer */,
203
- resultLenPtr /* operation result buffer length */,
204
- );
205
- } catch (e) {
206
- printLogs(`Error: `, e, 'ERROR');
207
- }
208
-
209
- // let bestImage = null;
210
-
211
- // const [outputBufferSize] = new Uint32Array(wasmPrivModules.HEAPU8.buffer, bestImageLenPtr, 1);
212
-
213
- // if (outputBufferSize > 0) {
214
- // let outputBufferSecPtr = null;
215
- // [outputBufferSecPtr] = new Uint32Array(wasmPrivModules.HEAPU8.buffer, bestImageFirstPtr, 1);
216
- // const outputBufferPtr = new Uint8Array(wasmPrivModules.HEAPU8.buffer, outputBufferSecPtr, outputBufferSize);
217
- // const outputBuffer = Uint8ClampedArray.from(outputBufferPtr);
218
- // const outputBufferData = outputBufferSize > 0 ? outputBuffer : null;
219
- // bestImage = { imageData: outputBufferData, width: imageData.width, height: imageData.height };
220
- // wasmPrivModules._free(outputBufferPtr);
221
- // }
222
-
223
- wasmPrivModules._free(imageInputPtr);
224
- wasmPrivModules._free(resultFirstPtr);
225
- wasmPrivModules._free(resultLenPtr);
226
- wasmPrivModules._free(configInputPtr);
227
- wasmPrivModules._free(bestImageFirstPtr);
228
- wasmPrivModules._free(bestImageLenPtr);
229
- // return bestImage;
230
- };
231
-
232
- const ultraAgeEstimate = async (originalImages, simd, config, cb) => {
233
- privid_wasm_result = cb;
234
- if (!wasmPrivModules) {
235
- await isLoad(simd, apiUrl, sesstionToken, publicKey, debugType);
236
- }
237
- const imageInput = flatten(
238
- originalImages.map((x) => x.data),
239
- Uint8Array,
240
- );
241
- const encoder = new TextEncoder();
242
- const config_bytes = encoder.encode(`${config}`);
243
- const configInputSize = config.length;
244
- const configInputPtr = wasmPrivModules._malloc(configInputSize);
245
- wasmPrivModules.HEAP8.set(config_bytes, configInputPtr / config_bytes.BYTES_PER_ELEMENT);
246
- const imageInputSize = imageInput.length * imageInput.BYTES_PER_ELEMENT;
247
- const imageInputPtr = wasmPrivModules._malloc(imageInputSize);
248
-
249
- wasmPrivModules.HEAP8.set(imageInput, imageInputPtr / imageInput.BYTES_PER_ELEMENT);
250
- const resultFirstPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
251
-
252
- // create a pointer to interger to hold the length of the output buffer
253
- const resultLenPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
254
- printLogs(`Config: `, config);
255
- try {
256
- await wasmPrivModules._privid_estimate_age(
257
- wasmSession /* session pointer */,
258
- configInputPtr,
259
- configInputSize,
260
- imageInputPtr /* input images */,
261
- originalImages[0].width /* width of one image */,
262
- originalImages[0].height /* height of one image */,
263
- resultFirstPtr /* operation result output buffer */,
264
- resultLenPtr /* operation result buffer length */,
265
- );
266
- } catch (e) {
267
- printLogs(`Error: `, e, 'ERROR');
268
- }
269
- wasmPrivModules._free(imageInputPtr);
270
- wasmPrivModules._free(configInputPtr);
271
- wasmPrivModules._free(resultFirstPtr);
272
- wasmPrivModules._free(resultLenPtr);
273
- };
274
-
275
- const ultraPredict = async (originalImages, simd, config, cb) => {
276
- privid_wasm_result = cb;
277
- if (!wasmPrivModules) {
278
- await isLoad(simd, apiUrl, sesstionToken, publicKey, debugType);
279
- }
280
-
281
- const numImages = originalImages.length;
282
- const imageInput = flatten(
283
- originalImages.map((x) => x.data),
284
- Uint8Array,
285
- );
286
- // const version = wasmPrivModules._get_version();
287
-
288
- const encoder = new TextEncoder();
289
- const config_bytes = encoder.encode(`${config}`);
290
-
291
- const configInputSize = config.length;
292
- const configInputPtr = wasmPrivModules._malloc(configInputSize);
293
- wasmPrivModules.HEAP8.set(config_bytes, configInputPtr / config_bytes.BYTES_PER_ELEMENT);
294
-
295
- const imageInputSize = imageInput.length * imageInput.BYTES_PER_ELEMENT;
296
- const imageInputPtr = wasmPrivModules._malloc(imageInputSize);
297
-
298
- wasmPrivModules.HEAP8.set(imageInput, imageInputPtr / imageInput.BYTES_PER_ELEMENT);
299
-
300
- const resultFirstPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
301
- // create a pointer to interger to hold the length of the output buffer
302
- const resultLenPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
303
- printLogs(`Config:`, config);
304
-
305
- try {
306
- await wasmPrivModules._privid_user_predict(
307
- wasmSession /* session pointer */,
308
- configInputPtr,
309
- configInputSize,
310
- imageInputPtr /* input images */,
311
- originalImages[0].width /* width of one image */,
312
- originalImages[0].height /* height of one image */,
313
- resultFirstPtr /* operation result output buffer */,
314
- resultLenPtr /* operation result buffer length */,
315
- );
316
- } catch (e) {
317
- printLogs(`Error: `, e, 'ERROR');
318
- }
319
-
320
- wasmPrivModules._free(imageInputPtr);
321
- wasmPrivModules._free(configInputPtr);
322
- wasmPrivModules._free(resultFirstPtr);
323
- wasmPrivModules._free(resultLenPtr);
324
- };
325
-
326
- function readKey(key) {
327
- if (!indexedDB) return Promise.reject(new Error('IndexedDB not available'));
328
-
329
- return new Promise((resolve, reject) => {
330
- const open = indexedDB.open('/privid-wasm', 21);
331
-
332
- open.onerror = function () {
333
- resolve(false);
334
- };
335
-
336
- open.onupgradeneeded = function () {
337
- open.result.createObjectStore('/privid-wasm');
338
- };
339
-
340
- open.onsuccess = function () {
341
- const db = open.result;
342
- const tx = db.transaction('/privid-wasm', 'readwrite');
343
- const store = tx.objectStore('/privid-wasm');
344
- const getKey = store.get(key);
345
-
346
- getKey.onsuccess = function () {
347
- resolve(getKey.result);
348
- };
349
-
350
- tx.onerror = function () {
351
- reject(tx.error);
352
- };
353
-
354
- tx.oncomplete = function () {
355
- try {
356
- db.close();
357
- } catch (e) {
358
- //
359
- printLogs(`Error readKey: `, e, 'ERROR');
360
- }
361
- };
362
- };
363
- });
364
- }
365
-
366
- function putKey(key, cachedWasm, cachedScript, version) {
367
- if (!indexedDB) return Promise.reject(new Error('IndexedDB not available'));
368
-
369
- return new Promise((resolve, reject) => {
370
- const open = indexedDB.open('/privid-wasm', 21);
371
-
372
- open.onerror = function () {
373
- resolve(false);
374
- };
375
-
376
- open.onupgradeneeded = function () {
377
- open.result.createObjectStore('/privid-wasm');
378
- };
379
-
380
- open.onsuccess = function () {
381
- const db = open.result;
382
- const tx = db.transaction('/privid-wasm', 'readwrite');
383
- const store = tx.objectStore('/privid-wasm');
384
- const getKey = store.put({ cachedWasm, cachedScript, version }, key);
385
-
386
- getKey.onsuccess = function () {
387
- resolve('saved');
388
- };
389
-
390
- tx.onerror = function () {
391
- reject(tx.error);
392
- };
393
-
394
- tx.oncomplete = function () {
395
- try {
396
- db.close();
397
- } catch (e) {
398
- //
399
- printLogs(`Error putKey: `, e, 'ERROR');
400
- }
401
- };
402
- };
403
- });
404
- }
405
-
406
- // async function setCacheConfiguration() {
407
- // const db = indexedDB.open('test');
408
- // db.onerror = function () {
409
- // printLogs(`Private browser no cache`, '');
410
- // };
411
- // db.onsuccess = async function () {
412
- // const cacheObj = JSON.stringify({ cache_type: setCache ? 'basic' : 'nocache' });
413
- // const encoder = new TextEncoder();
414
- // const cache_config_bytes = encoder.encode(`${cacheObj}`);
415
-
416
- // const cacheInputSize = cacheObj.length;
417
- // const cacheInputPtr = wasmPrivModules._malloc(cacheInputSize);
418
-
419
- // wasmPrivModules.HEAP8.set(cache_config_bytes, cacheInputPtr / cache_config_bytes.BYTES_PER_ELEMENT);
420
- // await wasmPrivModules._privid_set_configuration(wasmSession, cacheInputPtr, cacheInputSize);
421
- // wasmPrivModules._free(cacheInputPtr);
422
- // };
423
- // }
424
-
425
- /**
426
- * @brief A closure to create a string buffer arguments that can be used with wasm calls
427
- * for a given javascript value.
428
- * This is suitable for native calls that have string input arguments represented with contigious
429
- * string_buffer,sizeofbuffer arguments.
430
- * If the 'text' argument is null or undefined or NaN then the arguments generated are [null,0]
431
- * @usage
432
- *
433
- var url_args= buffer_args(url);
434
- var key_args= buffer_args(key);
435
- var session_out_ptr = output_ptr();
436
- const s_result = wasmPrivModules._privid_initialize_session(
437
- ...key_args.args(),
438
- ...url_args.args(),
439
- debug_type,
440
- session_out_ptr.outer_ptr(),
441
- );
442
- url_args.free();
443
- key_args.free();
444
- //get
445
- var session = session_out_ptr.inner_ptr();
446
- *
447
- * when .free() is called the closure can be reused to create a buffer for the same string with which, it was created with
448
- * over and over again.
449
- */
450
- const buffer_args = function (text) {
451
- let strInputtPtr = null;
452
- let strInputSize = 0;
453
- let argsv = [];
454
- return {
455
- args: () => {
456
- do {
457
- if (argsv.length > 0) break;
458
- argsv = [null, 0];
459
- if (text === null) break;
460
- if (text === undefined) break;
461
- // eslint-disable-next-line use-isnan
462
- if (text === NaN) break;
463
- const str = `${text}`;
464
- const encoder = new TextEncoder();
465
- const bytes = encoder.encode(str);
466
- strInputSize = bytes.length * bytes.BYTES_PER_ELEMENT;
467
- strInputtPtr = wasmPrivModules._malloc(strInputSize);
468
- wasmPrivModules.HEAP8.set(bytes, strInputtPtr / bytes.BYTES_PER_ELEMENT);
469
- argsv = [strInputtPtr, strInputSize];
470
- } while (false);
471
- return argsv;
472
- },
473
- free: () => {
474
- if (strInputtPtr) {
475
- wasmPrivModules._free(strInputtPtr);
476
- strInputtPtr = null;
477
- strInputSize = 0;
478
- argsv = [];
479
- }
480
- },
481
- };
482
- };
483
-
484
- /**
485
- * @brief A closure to create an output 32bits pointer closure.
486
- * This is usefull for allocating a native address and pass it to the
487
- * 'wasmPrivModules' so it can return in the address of a buffer (or an object like session)
488
- * that was allocated inside the wasm. This typically, correspond to
489
- * an argument of type void** (marked output argument) to pass to a native wasm
490
- * call.
491
- * @usage var myoutput_ptr = output_ptr();
492
- * when passing the output pointer to the 'wasmPrivModules' module use
493
- * wasmPrivModules.nativecall(myoutput_ptr.outer_ptr());
494
- * Then pull out the the allocated buffer by the wasm call this way:
495
- * @code
496
- * my_buffer_or_structure = myoutput_ptr.inner_ptr();
497
- * @note It is the responsability of the caller to free the pointer returned by this inner_ptr()
498
- */
499
- const output_ptr = function () {
500
- let out_ptr = null;
501
- let in_ptr = null;
502
- const free_ptr = (ptr) => {
503
- if (ptr) {
504
- wasmPrivModules._free(ptr);
505
- // eslint-disable-next-line no-param-reassign
506
- ptr = null;
507
- }
508
- };
509
- return {
510
- /**
511
- * @brief Allocates a pointer to contain the result and return it,
512
- * if the container is already created it will be returned
513
- */
514
- outer_ptr: () => {
515
- // TODO: may be used SharedArrayBuffer() instead
516
- // allocate memory the expected pointer (outer pointer or container)
517
- if (!out_ptr) out_ptr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
518
- return out_ptr;
519
- },
520
- /**
521
- * @brief Creates a javascript Uint32Array pointer to contain the result pointed by outer_ptr and return it,
522
- * It is the responsability of the caller to free the pointer returned by this function
523
- */
524
- inner_ptr: () => {
525
- // If we did not allocate yet the output buffer return null
526
- if (!out_ptr) return null;
527
- // if we already have our inner pointer for this closure return it
528
- if (in_ptr) return in_ptr;
529
- // Access the outer pointer as an arry of uint32 which conatin a single cell
530
- // whose value is the pointer allocated in the wasm module (inner pointer of the output param)
531
- // and return it
532
- [in_ptr] = new Uint32Array(wasmPrivModules.HEAPU8.buffer, out_ptr, 1);
533
- return in_ptr;
534
- },
535
- };
536
- };
537
-
538
- async function ultraCompareEmbeddings(encryptedEmbeddingsA, encryptedEmbeddingsB, config, cb) {
539
- try {
540
- privid_wasm_result = cb;
541
- if (!wasmPrivModules) {
542
- await isLoad(simd, apiUrl, sesstionToken, publicKey, debugType);
543
- }
544
-
545
- const encoder = new TextEncoder();
546
- const config_bytes = encoder.encode(`${config}`);
547
-
548
- const configInputSize = config.length;
549
- const configInputPtr = wasmPrivModules._malloc(configInputSize);
550
- wasmPrivModules.HEAP8.set(config_bytes, configInputPtr / config_bytes.BYTES_PER_ELEMENT);
551
-
552
- const embeddingA_bytes = encoder.encode(`${encryptedEmbeddingsA}`);
553
- const embeddingOneSize = encryptedEmbeddingsA.length;
554
- const embeddingOnePtr = wasmPrivModules._malloc(embeddingOneSize);
555
- wasmPrivModules.HEAP8.set(embeddingA_bytes, embeddingOnePtr / embeddingA_bytes.BYTES_PER_ELEMENT);
556
-
557
- const embeddingB_bytes = encoder.encode(`${encryptedEmbeddingsB}`);
558
- const embeddingTwoSize = encryptedEmbeddingsB.length;
559
- const embeddingTwoPtr = wasmPrivModules._malloc(embeddingTwoSize);
560
- wasmPrivModules.HEAP8.set(embeddingB_bytes, embeddingTwoPtr / embeddingB_bytes.BYTES_PER_ELEMENT);
561
-
562
- const resultFirstPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
563
- // create a pointer to interger to hold the length of the output buffer
564
- const resultLenPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
565
-
566
- const result = await wasmPrivModules._privid_compare_embeddings(
567
- wasmSession /* session pointer */,
568
- configInputPtr,
569
- configInputSize,
570
- embeddingOnePtr /* 1st embedding (encrypted string) */,
571
- embeddingOneSize /* 1st embedding size */,
572
- embeddingTwoPtr /* 2nd embedding (encrypted string) */,
573
- embeddingTwoSize /* 2nd embedding size */,
574
- resultFirstPtr /* operation result output buffer */,
575
- resultLenPtr /* operation result buffer length */,
576
- );
577
-
578
- wasmPrivModules._free(embeddingOnePtr);
579
- wasmPrivModules._free(embeddingTwoPtr);
580
- wasmPrivModules._free(configInputPtr);
581
- wasmPrivModules._free(resultFirstPtr);
582
- wasmPrivModules._free(resultLenPtr);
583
-
584
- return result;
585
- } catch (e) {
586
- printLogs(`Compare embeddings: `, e, 'ERROR');
587
- }
588
- }
589
-
590
- async function ultraDocumentOcr(imageInput, config, cb) {
591
- try {
592
- privid_wasm_result = cb;
593
- if (!wasmPrivModules) {
594
- await isLoad(simd, apiUrl, sesstionToken, publicKey, debugType);
595
- }
596
-
597
- const encoder = new TextEncoder();
598
- const config_bytes = encoder.encode(`${config}`);
599
- const input_Image_bytes = encoder.encode(`${imageInput}`);
600
-
601
- const configInputSize = config.length;
602
- const configInputPtr = wasmPrivModules._malloc(configInputSize);
603
- wasmPrivModules.HEAP8.set(config_bytes, configInputPtr / config_bytes.BYTES_PER_ELEMENT);
604
-
605
- const imageInputSize = imageInput.length;
606
- const imageInputPtr = wasmPrivModules._malloc(imageInputSize);
607
-
608
- wasmPrivModules.HEAP8.set(input_Image_bytes, imageInputPtr / input_Image_bytes.BYTES_PER_ELEMENT);
609
-
610
- const resultFirstPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
611
- // create a pointer to interger to hold the length of the output buffer
612
- const resultLenPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
613
- printLogs(`Document OCR Config: `, config);
614
-
615
- try {
616
- await wasmPrivModules._privid_doc_ocr_front_enc(
617
- wasmSession /* session pointer */,
618
- configInputPtr,
619
- configInputSize,
620
- imageInputPtr /* input images */,
621
- imageInputSize /* size of one image */,
622
- resultFirstPtr /* operation result output buffer */,
623
- resultLenPtr /* operation result buffer length */,
624
- );
625
- } catch (e) {
626
- printLogs(`Error: `, e, 'ERROR');
627
- }
628
-
629
- wasmPrivModules._free(imageInputPtr);
630
- wasmPrivModules._free(configInputPtr);
631
- wasmPrivModules._free(resultFirstPtr);
632
- wasmPrivModules._free(resultLenPtr);
633
- } catch (e) {
634
- printLogs(`Compare embeddings: `, e, 'ERROR');
635
- }
636
- }
637
-
638
- async function initializeWasmSession(
639
- url,
640
- session_token,
641
- public_key,
642
- debug_type,
643
- timeout = 5000,
644
- usageScenario,
645
- cache_content = '',
646
- ) {
647
- if (!wasmSession) {
648
- printLogs(`initSession: ${url}, ${session_token}, ${public_key} `);
649
- const session_out_ptr = output_ptr();
650
- const settings = {
651
- ...url,
652
- session_token,
653
- public_key,
654
- debug_level: debug_type ? parseInt(debugType) : 0,
655
- custom_settings: { usage_scenario: usageScenario, cache_content },
656
- };
657
-
658
- printLogs(`Settings:`, settings);
659
- const settings_args = buffer_args(JSON.stringify(settings));
660
-
661
- const s_result = wasmPrivModules._privid_initialize_session(...settings_args.args(), session_out_ptr.outer_ptr());
662
- settings_args.free();
663
-
664
- const isLoadedModels = wasmPrivModules._privid_check_models();
665
-
666
- printLogs(`Loaded Models: `, isLoadedModels);
667
- if (s_result) {
668
- printLogs(`Session initialized successfully`, '');
669
- } else {
670
- printLogs(`Session initialization Failed`, '', 'ERROR');
671
- return;
672
- }
673
-
674
- wasmSession = session_out_ptr.inner_ptr();
675
- printLogs(`wasm session: `, wasmSession);
676
- // if (setCache) {
677
- // await setCacheConfiguration();
678
- // }
679
- }
680
- }
681
-
682
- const loadWasmModule = async (modulePath, moduleName, saveCache, version) => {
683
- const wasm = await fetchResource(
684
- `${cdnUrl}/${ModuleName}/${modulePath}/${version}/${moduleName}.wasm`,
685
- `../wasm/${ModuleName}/${modulePath}/${version}/${moduleName}.wasm`,
686
- );
687
- const script = await fetchResource(
688
- `${cdnUrl}/${ModuleName}/${modulePath}/${version}/${moduleName}.js`,
689
- `../wasm/${ModuleName}/${modulePath}/${version}/${moduleName}.js`,
690
- );
691
- const scriptBuffer = await script.text();
692
- const buffer = await wasm.arrayBuffer();
693
-
694
- printLogs(`SCRIPT. BUFFER': `, { scriptBuffer, buffer });
695
- eval(scriptBuffer);
696
- const module = await createTFLiteModule({ wasmBinary: buffer });
697
- printLogs(`Module: `, module);
698
- if (saveCache) {
699
- const version = module.UTF8ToString(module._privid_get_version());
700
- await putKey('ultra', buffer, scriptBuffer, version);
701
- }
702
- return module;
703
- };
704
-
705
- async function fetchResource(cdnUrl, localUrl) {
706
- try {
707
- printLogs(`LOADING RESOURCE`, '');
708
- if (useCdnLink) {
709
- const response = await fetch(cdnUrl);
710
- printLogs(`Response: `, response);
711
- return response;
712
- } else {
713
- const response = await fetch(localUrl);
714
- return response;
715
- }
716
- } catch (error) {
717
- console.error(`Error fetching resource from CDN. Falling back to local path. Error: ${error}`);
718
- return fetch(localUrl);
719
- }
720
- }
721
-
722
- const pkiEncrypt = async (payload, config = JSON.stringify({})) => {
723
- const encoder = new TextEncoder();
724
- const payloadBytes = encoder.encode(`${payload}`);
725
- const payloadInputSize = payloadBytes.length;
726
- const payloadInputPtr = wasmPrivModules._malloc(payloadInputSize);
727
-
728
- const resultFirstPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
729
- // create a pointer to interger to hold the length of the output buffer
730
- const resultLenPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
731
- wasmPrivModules.HEAP8.set(payloadBytes, payloadInputPtr / payloadBytes.BYTES_PER_ELEMENT);
732
- printLogs(`Payload: `, payload, debugType);
733
- let res = null;
734
-
735
- const config_bytes = encoder.encode(`${config}`);
736
-
737
- const configInputSize = config.length;
738
- const configInputPtr = wasmPrivModules._malloc(configInputSize);
739
- wasmPrivModules.HEAP8.set(config_bytes, configInputPtr / config_bytes.BYTES_PER_ELEMENT);
740
-
741
- try {
742
- res = wasmPrivModules._privid_encrypt_payload(
743
- wasmSession /* session pointer */,
744
- configInputPtr,
745
- configInputSize,
746
- payloadInputPtr,
747
- payloadInputSize,
748
- resultFirstPtr /* operation result output buffer */,
749
- resultLenPtr /* operation result buffer length */,
750
- );
751
- } catch (e) {
752
- printLogs(`Error: `, e, 'ERROR');
753
- }
754
-
755
- printLogs(`Result: `, res);
756
-
757
- const [outputBufferSizes] = new Uint32Array(wasmPrivModules.HEAPU8.buffer, resultLenPtr, 1);
758
-
759
- if (outputBufferSizes > 0) {
760
- // de-reference & copy the data from pointer to integer in integer array of one element
761
- const outputBufferSize = new Uint32Array(wasmPrivModules.HEAPU8.buffer, resultLenPtr, 1)[0];
762
- const outputBufferSecPtr = new Uint32Array(wasmPrivModules.HEAPU8.buffer, resultFirstPtr, 1)[0];
763
- const outputBufferPtr = new Uint8Array(wasmPrivModules.HEAPU8.buffer, outputBufferSecPtr, outputBufferSize);
764
-
765
- var decoder = new TextDecoder('utf8');
766
- var dec = decoder.decode(outputBufferPtr);
767
- dec.replace(/\0/g, '');
768
- dec.replace(' ', '');
769
- function removeNullBytes(str) {
770
- return str
771
- .split('')
772
- .filter((char) => char.codePointAt(0))
773
- .join('');
774
- }
775
- let parsedDec = JSON.stringify(removeNullBytes(dec));
776
- printLogs(`Parsed: `, parsedDec);
777
- let isObject = JSON.parse(parsedDec);
778
- printLogs(`Is object? `, isObject);
779
- return JSON.parse(isObject);
780
- }
781
-
782
- return { error: true };
783
- };
784
-
785
- const ultraScanFrontDocument = async (imageInput, simd, config, cb) => {
786
- privid_wasm_result = cb;
787
- if (!wasmPrivModules) {
788
- await isLoad(simd, apiUrl, sesstionToken, publicKey);
789
- }
790
-
791
- const encoder = new TextEncoder();
792
- const config_bytes = encoder.encode(`${config}`);
793
-
794
- const configInputSize = config.length;
795
- const configInputPtr = wasmPrivModules._malloc(configInputSize);
796
- wasmPrivModules.HEAP8.set(config_bytes, configInputPtr / config_bytes.BYTES_PER_ELEMENT);
797
-
798
- const imageInputSize = imageInput.data.length * imageInput.data.BYTES_PER_ELEMENT;
799
- const imageInputPtr = wasmPrivModules._malloc(imageInputSize);
800
- wasmPrivModules.HEAPU8.set(new Uint8Array(imageInput.data), imageInputPtr);
801
-
802
- const resultFirstPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
803
- const resultLenPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
804
- printLogs(`Config: `, {
805
- wasmSession /* session pointer */,
806
- configInputPtr,
807
- configInputSize,
808
- imageInputPtr /* input images */,
809
- width: imageInput.width /* width of one image */,
810
- height: imageInput.height /* height of one image */,
811
- resultFirstPtr /* operation result output buffer */,
812
- resultLenPtr,
813
- });
814
-
815
- try {
816
- await wasmPrivModules._privid_doc_scan_front(
817
- wasmSession /* session pointer */,
818
- configInputPtr,
819
- configInputSize,
820
- imageInputPtr /* input images */,
821
- imageInput.width /* width of one image */,
822
- imageInput.height /* height of one image */,
823
- resultFirstPtr /* operation result output buffer */,
824
- resultLenPtr /* operation result buffer length */,
825
- );
826
- } catch (e) {
827
- printLogs(`Error: `, e, 'ERROR');
828
- }
829
-
830
- wasmPrivModules._free(imageInputPtr);
831
- wasmPrivModules._free(configInputPtr);
832
- wasmPrivModules._free(resultFirstPtr);
833
- wasmPrivModules._free(resultLenPtr);
834
- };
835
-
836
- const ultraScanBackDocument = async (imageInput, simd, config, cb) => {
837
- privid_wasm_result = cb;
838
- if (!wasmPrivModules) {
839
- await isLoad(simd, apiUrl, sesstionToken, publicKey, debugType);
840
- }
841
-
842
- printLogs(`Extra config: `, config);
843
- const encoder = new TextEncoder();
844
- const config_bytes = encoder.encode(`${config}`);
845
-
846
- const configInputSize = config.length;
847
- const configInputPtr = wasmPrivModules._malloc(configInputSize);
848
-
849
- wasmPrivModules.HEAP8.set(config_bytes, configInputPtr / config_bytes.BYTES_PER_ELEMENT);
850
-
851
- printLogs(`Image Input `, imageInput);
852
- const imageInputSize = imageInput?.data?.length * imageInput?.data?.BYTES_PER_ELEMENT;
853
- const imageInputPtr = wasmPrivModules._malloc(imageInputSize);
854
- printLogs(`Input image Size:`, imageInputSize);
855
- wasmPrivModules.HEAPU8.set(new Uint8Array(imageInput.data), imageInputPtr);
856
- // wasmPrivModules.HEAP8.set(imageInput, imageInputPtr / imageInput?.data?.BYTES_PER_ELEMENT);
857
-
858
- const resultFirstPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
859
- // create a pointer to interger to hold the length of the output buffer
860
- const resultLenPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
861
- printLogs(`Config: `, {
862
- configInputPtr,
863
- configInputSize,
864
- imageInputPtr /* input images */,
865
- width: imageInput.width /* width of one image */,
866
- height: imageInput.height /* height of one image */,
867
- resultFirstPtr /* operation result output buffer */,
868
- resultLenPtr /* operation result buffer length */,
869
- });
870
-
871
- try {
872
- await wasmPrivModules._privid_doc_scan_back(
873
- wasmSession /* session pointer */,
874
- configInputPtr,
875
- configInputSize,
876
- imageInputPtr /* input images */,
877
- imageInput.width /* width of one image */,
878
- imageInput.height /* height of one image */,
879
- resultFirstPtr /* operation result output buffer */,
880
- resultLenPtr /* operation result buffer length */,
881
- );
882
- } catch (e) {
883
- printLogs(`Error: `, e, 'ERROR');
884
- }
885
-
886
- wasmPrivModules._free(imageInputPtr);
887
- wasmPrivModules._free(configInputPtr);
888
- wasmPrivModules._free(resultFirstPtr);
889
- wasmPrivModules._free(resultLenPtr);
890
- };
891
-
892
- const checkIfModelsLoaded = () => {
893
- try {
894
- const isLoaded = wasmPrivModules._privid_check_models();
895
- return isLoaded;
896
- } catch (e) {
897
- printLogs(`Error: `, e, 'ERROR');
898
- return 0;
899
- }
900
- };
901
-
902
- const freeMemory = () => {
903
- try {
904
- const isLoaded = wasmPrivModules._privid_free_memory();
905
- return isLoaded;
906
- } catch (e) {
907
- printLogs(`Error: `, e, 'ERROR');
908
- return 0;
909
- }
910
- };
911
-
912
- Comlink.expose({
913
- ultraEnroll,
914
- ultraPredict,
915
- ultraAgeEstimate,
916
- ultraCompareEmbeddings,
917
- isLoad,
918
- pkiEncrypt,
919
- checkIfModelsLoaded,
920
- ultraScanBackDocument,
921
- ultraScanFrontDocument,
922
- ultraDocumentOcr,
923
- freeMemory,
924
- });
1
+ /* eslint-disable no-eval */
2
+ /* eslint-disable default-param-last */
3
+ /* eslint-disable no-undef */
4
+ /* eslint-disable no-underscore-dangle */
5
+ // importScripts('https://unpkg.com/comlink/dist/umd/comlink.js');
6
+
7
+ importScripts('./comlink.min.js');
8
+
9
+ var wasmPrivModules;
10
+ let apiUrl;
11
+ let sesstionToken;
12
+ let publicKey;
13
+ let debugType;
14
+ let inputPtr;
15
+ let imageInputSize;
16
+ let barCodePtr;
17
+ let privid_wasm_result = null;
18
+ let privid_wasm_error = null;
19
+ let privid_wasm_progress = null;
20
+ let wasmSession = null;
21
+ let setCache = true;
22
+ let checkWasmLoaded = false;
23
+ let antispoofVersion;
24
+ const ModuleName = 'ultra';
25
+ const cdnUrl = 'https://ultra-wasm.devel.privateid.com'; // Devel
26
+ // const cdnUrl = 'https://ultra-wasm.privateid.com/wasm'; // Prod
27
+ let useCdnLink = true;
28
+
29
+ const createImageArguments = (imageData, width, height) => {};
30
+
31
+ const createStringArguments = () => {};
32
+
33
+ const printLogs = (message, data, type = 'LOG') => {
34
+ console.log('FROM_SDK_WORKER', message, data);
35
+ const errorLogs = ['1', '2', '3', '901', '902', '903'];
36
+ const warningLogs = ['2', '3', '902', '903'];
37
+ const allLogs = ['3', '903'];
38
+
39
+ if (type === 'ERROR' && errorLogs.includes('3')) {
40
+ console.error('DEBUG_SDK_WASM_WORKER', message, data);
41
+ } else if (type === 'WARN' && warningLogs.includes('3')) {
42
+ console.warn('DEBUG_SDK_WASM_WORKER', message, data);
43
+ } else if (type === 'LOG' && allLogs.includes('3')) {
44
+ console.log('DEBUG_SDK_WASM_WORKER', message, data);
45
+ }
46
+ };
47
+
48
+ const isLoad = (
49
+ simd,
50
+ url,
51
+ session_token,
52
+ public_key,
53
+ debug_type,
54
+ cacheConfig = true,
55
+ timeout = 5000,
56
+ useCdn = false,
57
+ shouldRegenerateSession,
58
+ failureCb,
59
+ usageScenario,
60
+ cache_content,
61
+ progressCb,
62
+ ) =>
63
+ new Promise(async (resolve, reject) => {
64
+ apiUrl = url;
65
+ sesstionToken = session_token;
66
+ publicKey = public_key;
67
+ useCdnLink = useCdn;
68
+ privid_wasm_error = failureCb;
69
+ privid_wasm_progress = progressCb;
70
+
71
+ if (debug_type) {
72
+ debugType = debug_type;
73
+ }
74
+
75
+ let timeoutSession = 5000;
76
+ if (timeout) {
77
+ timeoutSession = timeout;
78
+ }
79
+ setCache = cacheConfig;
80
+
81
+ printLogs(`data: `, { simd, url, session_token, public_key, debug_type, cache_content });
82
+
83
+ const modulePath = simd ? 'simd' : 'nosimd';
84
+ const moduleName = 'privid_fhe_uber';
85
+ const cachedModule = await readKey(ModuleName);
86
+ // const fetchdVersion = await fetchdWasmVersion.json();
87
+ const fetchdWasmVersion = await (await fetch(`../wasm/${ModuleName}/${modulePath}/version.json`)).json();
88
+
89
+ printLogs(
90
+ `versions: cached:
91
+ ${cachedModule ? cachedModule?.version.toString() : 'no cached wasm'},
92
+ fetched:
93
+ ${fetchdWasmVersion ? fetchdWasmVersion.version.toString() : 'no fetched version'})
94
+ modulePath: ${modulePath}`,
95
+ '',
96
+ );
97
+
98
+ const loadFromPackage = async () => {
99
+ printLogs(`fetched version: `, fetchdWasmVersion);
100
+ wasmPrivModules = await loadWasmModule(modulePath, moduleName, true, `${fetchdWasmVersion.version}`);
101
+ printLogs(`ULTRA MODULE: `, wasmPrivModules);
102
+ if (!checkWasmLoaded) {
103
+ await initializeWasmSession(
104
+ url,
105
+ sesstionToken,
106
+ publicKey,
107
+ debugType,
108
+ timeoutSession,
109
+ usageScenario,
110
+ cache_content,
111
+ );
112
+ checkWasmLoaded = true;
113
+ }
114
+ resolve('Loaded');
115
+ };
116
+
117
+ if (
118
+ cachedModule &&
119
+ cachedModule.version &&
120
+ fetchdWasmVersion &&
121
+ fetchdWasmVersion.version &&
122
+ cachedModule.version.toString() === fetchdWasmVersion?.version.toString()
123
+ ) {
124
+ printLogs(`same version confirmed`, '');
125
+ printLogs(`PRIVMODULES LOADED?: `, wasmPrivModules);
126
+ if (!wasmPrivModules) {
127
+ const { cachedWasm, cachedScript } = cachedModule;
128
+
129
+ if (cachedWasm && cachedScript) {
130
+ eval(cachedScript);
131
+ wasmPrivModules = await createTFLiteModule({ wasmBinary: cachedWasm });
132
+ printLogs(`ULTRA MODULE `, wasmPrivModules);
133
+ if (!checkWasmLoaded) {
134
+ await initializeWasmSession(
135
+ url,
136
+ sesstionToken,
137
+ publicKey,
138
+ debugType,
139
+ timeoutSession,
140
+ usageScenario,
141
+ cache_content,
142
+ );
143
+ checkWasmLoaded = true;
144
+ }
145
+ printLogs(`WASM MODULES: `, wasmPrivModules);
146
+ } else {
147
+ await loadFromPackage();
148
+ }
149
+ } else if (wasmPrivModules && shouldRegenerateSession) {
150
+ wasmSession = null;
151
+ await initializeWasmSession(
152
+ url,
153
+ sesstionToken,
154
+ publicKey,
155
+ debugType,
156
+ timeoutSession,
157
+ usageScenario,
158
+ cache_content,
159
+ );
160
+ } else {
161
+ await loadFromPackage();
162
+ }
163
+ resolve('Cache Loaded');
164
+ } else {
165
+ await loadFromPackage();
166
+ }
167
+ });
168
+
169
+ function flatten(arrays, TypedArray) {
170
+ const arr = new TypedArray(arrays.reduce((n, a) => n + a.length, 0));
171
+ let i = 0;
172
+ arrays.forEach((a) => {
173
+ arr.set(a, i);
174
+ i += a.length;
175
+ });
176
+ return arr;
177
+ }
178
+
179
+ const ultraEnroll = async (imageData, simd, config, cb) => {
180
+ privid_wasm_result = cb;
181
+
182
+ if (!wasmPrivModules) {
183
+ await isLoad(simd, apiUrl, sesstionToken, publicKey, debugType);
184
+ }
185
+
186
+ const imageInputSize = imageData.data.length * imageData.data.BYTES_PER_ELEMENT;
187
+ const imageInputPtr = wasmPrivModules._malloc(imageInputSize);
188
+ wasmPrivModules.HEAPU8.set(new Uint8Array(imageData.data), imageInputPtr);
189
+ const resultFirstPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
190
+ const resultLenPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
191
+ const encoder = new TextEncoder();
192
+ const config_bytes = encoder.encode(`${config}`);
193
+ const configInputSize = config_bytes.length;
194
+ const configInputPtr = wasmPrivModules._malloc(configInputSize);
195
+ const bestImageFirstPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
196
+ const bestImageLenPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
197
+ wasmPrivModules.HEAP8.set(config_bytes, configInputPtr / config_bytes.BYTES_PER_ELEMENT);
198
+ printLogs(`config: `, config);
199
+ try {
200
+ wasmPrivModules._privid_user_enroll(
201
+ wasmSession /* session pointer */,
202
+ configInputPtr,
203
+ configInputSize,
204
+ imageInputPtr /* input images */,
205
+ imageData.width /* width of one image */,
206
+ imageData.height /* height of one image */,
207
+ resultFirstPtr /* operation result output buffer */,
208
+ resultLenPtr /* operation result buffer length */,
209
+ );
210
+ } catch (e) {
211
+ printLogs(`Error: `, e, 'ERROR');
212
+ }
213
+
214
+ // let bestImage = null;
215
+
216
+ // const [outputBufferSize] = new Uint32Array(wasmPrivModules.HEAPU8.buffer, bestImageLenPtr, 1);
217
+
218
+ // if (outputBufferSize > 0) {
219
+ // let outputBufferSecPtr = null;
220
+ // [outputBufferSecPtr] = new Uint32Array(wasmPrivModules.HEAPU8.buffer, bestImageFirstPtr, 1);
221
+ // const outputBufferPtr = new Uint8Array(wasmPrivModules.HEAPU8.buffer, outputBufferSecPtr, outputBufferSize);
222
+ // const outputBuffer = Uint8ClampedArray.from(outputBufferPtr);
223
+ // const outputBufferData = outputBufferSize > 0 ? outputBuffer : null;
224
+ // bestImage = { imageData: outputBufferData, width: imageData.width, height: imageData.height };
225
+ // wasmPrivModules._free(outputBufferPtr);
226
+ // }
227
+
228
+ wasmPrivModules._free(imageInputPtr);
229
+ wasmPrivModules._free(resultFirstPtr);
230
+ wasmPrivModules._free(resultLenPtr);
231
+ wasmPrivModules._free(configInputPtr);
232
+ wasmPrivModules._free(bestImageFirstPtr);
233
+ wasmPrivModules._free(bestImageLenPtr);
234
+ // return bestImage;
235
+ };
236
+
237
+ const ultraAgeEstimate = async (originalImages, simd, config, cb, onAntiSpoofProgress) => {
238
+ privid_wasm_result = cb;
239
+
240
+ if (onAntiSpoofProgress) {
241
+ privid_wasm_progress = onAntiSpoofProgress;
242
+ }
243
+
244
+ if (!wasmPrivModules) {
245
+ await isLoad(simd, apiUrl, sesstionToken, publicKey, debugType);
246
+ }
247
+ const imageInput = flatten(
248
+ originalImages.map((x) => x.data),
249
+ Uint8Array,
250
+ );
251
+ const encoder = new TextEncoder();
252
+ const config_bytes = encoder.encode(config);
253
+ const configInputSize = config.length;
254
+ const configInputPtr = wasmPrivModules._malloc(configInputSize);
255
+ wasmPrivModules.HEAP8.set(config_bytes, configInputPtr / config_bytes.BYTES_PER_ELEMENT);
256
+ const imageInputSize = imageInput.length * imageInput.BYTES_PER_ELEMENT;
257
+ const imageInputPtr = wasmPrivModules._malloc(imageInputSize);
258
+
259
+ wasmPrivModules.HEAP8.set(imageInput, imageInputPtr / imageInput.BYTES_PER_ELEMENT);
260
+ const resultFirstPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
261
+
262
+ // create a pointer to interger to hold the length of the output buffer
263
+ const resultLenPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
264
+ printLogs(`Config: `, config);
265
+
266
+ try {
267
+ await wasmPrivModules._privid_estimate_age(
268
+ wasmSession /* session pointer */,
269
+ configInputPtr,
270
+ configInputSize,
271
+ imageInputPtr /* input images */,
272
+ originalImages[0].width /* width of one image */,
273
+ originalImages[0].height /* height of one image */,
274
+ resultFirstPtr /* operation result output buffer */,
275
+ resultLenPtr /* operation result buffer length */,
276
+ privid_wasm_progress /* anti-spoof progress callback (global variable) */,
277
+ );
278
+ } catch (e) {
279
+ printLogs(`Error: `, e, 'ERROR');
280
+ }
281
+ wasmPrivModules._free(imageInputPtr);
282
+ wasmPrivModules._free(configInputPtr);
283
+ wasmPrivModules._free(resultFirstPtr);
284
+ wasmPrivModules._free(resultLenPtr);
285
+ };
286
+
287
+ const ultraPredict = async (originalImages, simd, config, cb) => {
288
+ privid_wasm_result = cb;
289
+ if (!wasmPrivModules) {
290
+ await isLoad(simd, apiUrl, sesstionToken, publicKey, debugType);
291
+ }
292
+
293
+ const numImages = originalImages.length;
294
+ const imageInput = flatten(
295
+ originalImages.map((x) => x.data),
296
+ Uint8Array,
297
+ );
298
+ // const version = wasmPrivModules._get_version();
299
+
300
+ const encoder = new TextEncoder();
301
+ const config_bytes = encoder.encode(`${config}`);
302
+
303
+ const configInputSize = config.length;
304
+ const configInputPtr = wasmPrivModules._malloc(configInputSize);
305
+ wasmPrivModules.HEAP8.set(config_bytes, configInputPtr / config_bytes.BYTES_PER_ELEMENT);
306
+
307
+ const imageInputSize = imageInput.length * imageInput.BYTES_PER_ELEMENT;
308
+ const imageInputPtr = wasmPrivModules._malloc(imageInputSize);
309
+
310
+ wasmPrivModules.HEAP8.set(imageInput, imageInputPtr / imageInput.BYTES_PER_ELEMENT);
311
+
312
+ const resultFirstPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
313
+ // create a pointer to interger to hold the length of the output buffer
314
+ const resultLenPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
315
+ printLogs(`Config:`, config);
316
+
317
+ try {
318
+ await wasmPrivModules._privid_user_predict(
319
+ wasmSession /* session pointer */,
320
+ configInputPtr,
321
+ configInputSize,
322
+ imageInputPtr /* input images */,
323
+ originalImages[0].width /* width of one image */,
324
+ originalImages[0].height /* height of one image */,
325
+ resultFirstPtr /* operation result output buffer */,
326
+ resultLenPtr /* operation result buffer length */,
327
+ );
328
+ } catch (e) {
329
+ printLogs(`Error: `, e, 'ERROR');
330
+ }
331
+
332
+ wasmPrivModules._free(imageInputPtr);
333
+ wasmPrivModules._free(configInputPtr);
334
+ wasmPrivModules._free(resultFirstPtr);
335
+ wasmPrivModules._free(resultLenPtr);
336
+ };
337
+
338
+ function readKey(key) {
339
+ if (!indexedDB) return Promise.reject(new Error('IndexedDB not available'));
340
+
341
+ return new Promise((resolve, reject) => {
342
+ const open = indexedDB.open('/privid-wasm', 21);
343
+
344
+ open.onerror = function () {
345
+ resolve(false);
346
+ };
347
+
348
+ open.onupgradeneeded = function () {
349
+ open.result.createObjectStore('/privid-wasm');
350
+ };
351
+
352
+ open.onsuccess = function () {
353
+ const db = open.result;
354
+ const tx = db.transaction('/privid-wasm', 'readwrite');
355
+ const store = tx.objectStore('/privid-wasm');
356
+ const getKey = store.get(key);
357
+
358
+ getKey.onsuccess = function () {
359
+ resolve(getKey.result);
360
+ };
361
+
362
+ tx.onerror = function () {
363
+ reject(tx.error);
364
+ };
365
+
366
+ tx.oncomplete = function () {
367
+ try {
368
+ db.close();
369
+ } catch (e) {
370
+ //
371
+ printLogs(`Error readKey: `, e, 'ERROR');
372
+ }
373
+ };
374
+ };
375
+ });
376
+ }
377
+
378
+ function putKey(key, cachedWasm, cachedScript, version) {
379
+ if (!indexedDB) return Promise.reject(new Error('IndexedDB not available'));
380
+
381
+ return new Promise((resolve, reject) => {
382
+ const open = indexedDB.open('/privid-wasm', 21);
383
+
384
+ open.onerror = function () {
385
+ resolve(false);
386
+ };
387
+
388
+ open.onupgradeneeded = function () {
389
+ open.result.createObjectStore('/privid-wasm');
390
+ };
391
+
392
+ open.onsuccess = function () {
393
+ const db = open.result;
394
+ const tx = db.transaction('/privid-wasm', 'readwrite');
395
+ const store = tx.objectStore('/privid-wasm');
396
+ const getKey = store.put({ cachedWasm, cachedScript, version }, key);
397
+
398
+ getKey.onsuccess = function () {
399
+ resolve('saved');
400
+ };
401
+
402
+ tx.onerror = function () {
403
+ reject(tx.error);
404
+ };
405
+
406
+ tx.oncomplete = function () {
407
+ try {
408
+ db.close();
409
+ } catch (e) {
410
+ //
411
+ printLogs(`Error putKey: `, e, 'ERROR');
412
+ }
413
+ };
414
+ };
415
+ });
416
+ }
417
+
418
+ // async function setCacheConfiguration() {
419
+ // const db = indexedDB.open('test');
420
+ // db.onerror = function () {
421
+ // printLogs(`Private browser no cache`, '');
422
+ // };
423
+ // db.onsuccess = async function () {
424
+ // const cacheObj = JSON.stringify({ cache_type: setCache ? 'basic' : 'nocache' });
425
+ // const encoder = new TextEncoder();
426
+ // const cache_config_bytes = encoder.encode(`${cacheObj}`);
427
+
428
+ // const cacheInputSize = cacheObj.length;
429
+ // const cacheInputPtr = wasmPrivModules._malloc(cacheInputSize);
430
+
431
+ // wasmPrivModules.HEAP8.set(cache_config_bytes, cacheInputPtr / cache_config_bytes.BYTES_PER_ELEMENT);
432
+ // await wasmPrivModules._privid_set_configuration(wasmSession, cacheInputPtr, cacheInputSize);
433
+ // wasmPrivModules._free(cacheInputPtr);
434
+ // };
435
+ // }
436
+
437
+ /**
438
+ * @brief A closure to create a string buffer arguments that can be used with wasm calls
439
+ * for a given javascript value.
440
+ * This is suitable for native calls that have string input arguments represented with contigious
441
+ * string_buffer,sizeofbuffer arguments.
442
+ * If the 'text' argument is null or undefined or NaN then the arguments generated are [null,0]
443
+ * @usage
444
+ *
445
+ var url_args= buffer_args(url);
446
+ var key_args= buffer_args(key);
447
+ var session_out_ptr = output_ptr();
448
+ const s_result = wasmPrivModules._privid_initialize_session(
449
+ ...key_args.args(),
450
+ ...url_args.args(),
451
+ debug_type,
452
+ session_out_ptr.outer_ptr(),
453
+ );
454
+ url_args.free();
455
+ key_args.free();
456
+ //get
457
+ var session = session_out_ptr.inner_ptr();
458
+ *
459
+ * when .free() is called the closure can be reused to create a buffer for the same string with which, it was created with
460
+ * over and over again.
461
+ */
462
+ const buffer_args = function (text) {
463
+ let strInputtPtr = null;
464
+ let strInputSize = 0;
465
+ let argsv = [];
466
+ return {
467
+ args: () => {
468
+ do {
469
+ if (argsv.length > 0) break;
470
+ argsv = [null, 0];
471
+ if (text === null) break;
472
+ if (text === undefined) break;
473
+ // eslint-disable-next-line use-isnan
474
+ if (text === NaN) break;
475
+ const str = `${text}`;
476
+ const encoder = new TextEncoder();
477
+ const bytes = encoder.encode(str);
478
+ strInputSize = bytes.length * bytes.BYTES_PER_ELEMENT;
479
+ strInputtPtr = wasmPrivModules._malloc(strInputSize);
480
+ wasmPrivModules.HEAP8.set(bytes, strInputtPtr / bytes.BYTES_PER_ELEMENT);
481
+ argsv = [strInputtPtr, strInputSize];
482
+ } while (false);
483
+ return argsv;
484
+ },
485
+ free: () => {
486
+ if (strInputtPtr) {
487
+ wasmPrivModules._free(strInputtPtr);
488
+ strInputtPtr = null;
489
+ strInputSize = 0;
490
+ argsv = [];
491
+ }
492
+ },
493
+ };
494
+ };
495
+
496
+ /**
497
+ * @brief A closure to create an output 32bits pointer closure.
498
+ * This is usefull for allocating a native address and pass it to the
499
+ * 'wasmPrivModules' so it can return in the address of a buffer (or an object like session)
500
+ * that was allocated inside the wasm. This typically, correspond to
501
+ * an argument of type void** (marked output argument) to pass to a native wasm
502
+ * call.
503
+ * @usage var myoutput_ptr = output_ptr();
504
+ * when passing the output pointer to the 'wasmPrivModules' module use
505
+ * wasmPrivModules.nativecall(myoutput_ptr.outer_ptr());
506
+ * Then pull out the the allocated buffer by the wasm call this way:
507
+ * @code
508
+ * my_buffer_or_structure = myoutput_ptr.inner_ptr();
509
+ * @note It is the responsability of the caller to free the pointer returned by this inner_ptr()
510
+ */
511
+ const output_ptr = function () {
512
+ let out_ptr = null;
513
+ let in_ptr = null;
514
+ const free_ptr = (ptr) => {
515
+ if (ptr) {
516
+ wasmPrivModules._free(ptr);
517
+ // eslint-disable-next-line no-param-reassign
518
+ ptr = null;
519
+ }
520
+ };
521
+ return {
522
+ /**
523
+ * @brief Allocates a pointer to contain the result and return it,
524
+ * if the container is already created it will be returned
525
+ */
526
+ outer_ptr: () => {
527
+ // TODO: may be used SharedArrayBuffer() instead
528
+ // allocate memory the expected pointer (outer pointer or container)
529
+ if (!out_ptr) out_ptr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
530
+ return out_ptr;
531
+ },
532
+ /**
533
+ * @brief Creates a javascript Uint32Array pointer to contain the result pointed by outer_ptr and return it,
534
+ * It is the responsability of the caller to free the pointer returned by this function
535
+ */
536
+ inner_ptr: () => {
537
+ // If we did not allocate yet the output buffer return null
538
+ if (!out_ptr) return null;
539
+ // if we already have our inner pointer for this closure return it
540
+ if (in_ptr) return in_ptr;
541
+ // Access the outer pointer as an arry of uint32 which conatin a single cell
542
+ // whose value is the pointer allocated in the wasm module (inner pointer of the output param)
543
+ // and return it
544
+ [in_ptr] = new Uint32Array(wasmPrivModules.HEAPU8.buffer, out_ptr, 1);
545
+ return in_ptr;
546
+ },
547
+ };
548
+ };
549
+
550
+ async function ultraCompareEmbeddings(encryptedEmbeddingsA, encryptedEmbeddingsB, config, cb) {
551
+ try {
552
+ privid_wasm_result = cb;
553
+ if (!wasmPrivModules) {
554
+ await isLoad(simd, apiUrl, sesstionToken, publicKey, debugType);
555
+ }
556
+
557
+ const encoder = new TextEncoder();
558
+ const config_bytes = encoder.encode(`${config}`);
559
+
560
+ const configInputSize = config.length;
561
+ const configInputPtr = wasmPrivModules._malloc(configInputSize);
562
+ wasmPrivModules.HEAP8.set(config_bytes, configInputPtr / config_bytes.BYTES_PER_ELEMENT);
563
+
564
+ const embeddingA_bytes = encoder.encode(`${encryptedEmbeddingsA}`);
565
+ const embeddingOneSize = encryptedEmbeddingsA.length;
566
+ const embeddingOnePtr = wasmPrivModules._malloc(embeddingOneSize);
567
+ wasmPrivModules.HEAP8.set(embeddingA_bytes, embeddingOnePtr / embeddingA_bytes.BYTES_PER_ELEMENT);
568
+
569
+ const embeddingB_bytes = encoder.encode(`${encryptedEmbeddingsB}`);
570
+ const embeddingTwoSize = encryptedEmbeddingsB.length;
571
+ const embeddingTwoPtr = wasmPrivModules._malloc(embeddingTwoSize);
572
+ wasmPrivModules.HEAP8.set(embeddingB_bytes, embeddingTwoPtr / embeddingB_bytes.BYTES_PER_ELEMENT);
573
+
574
+ const resultFirstPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
575
+ // create a pointer to interger to hold the length of the output buffer
576
+ const resultLenPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
577
+
578
+ const result = await wasmPrivModules._privid_compare_embeddings(
579
+ wasmSession /* session pointer */,
580
+ configInputPtr,
581
+ configInputSize,
582
+ embeddingOnePtr /* 1st embedding (encrypted string) */,
583
+ embeddingOneSize /* 1st embedding size */,
584
+ embeddingTwoPtr /* 2nd embedding (encrypted string) */,
585
+ embeddingTwoSize /* 2nd embedding size */,
586
+ resultFirstPtr /* operation result output buffer */,
587
+ resultLenPtr /* operation result buffer length */,
588
+ );
589
+
590
+ wasmPrivModules._free(embeddingOnePtr);
591
+ wasmPrivModules._free(embeddingTwoPtr);
592
+ wasmPrivModules._free(configInputPtr);
593
+ wasmPrivModules._free(resultFirstPtr);
594
+ wasmPrivModules._free(resultLenPtr);
595
+
596
+ return result;
597
+ } catch (e) {
598
+ printLogs(`Compare embeddings: `, e, 'ERROR');
599
+ }
600
+ }
601
+
602
+ async function ultraDocumentOcr(imageInput, config, cb) {
603
+ try {
604
+ privid_wasm_result = cb;
605
+ if (!wasmPrivModules) {
606
+ await isLoad(simd, apiUrl, sesstionToken, publicKey, debugType);
607
+ }
608
+
609
+ const encoder = new TextEncoder();
610
+ const config_bytes = encoder.encode(`${config}`);
611
+ const input_Image_bytes = encoder.encode(`${imageInput}`);
612
+
613
+ const configInputSize = config.length;
614
+ const configInputPtr = wasmPrivModules._malloc(configInputSize);
615
+ wasmPrivModules.HEAP8.set(config_bytes, configInputPtr / config_bytes.BYTES_PER_ELEMENT);
616
+
617
+ const imageInputSize = imageInput.length;
618
+ const imageInputPtr = wasmPrivModules._malloc(imageInputSize);
619
+
620
+ wasmPrivModules.HEAP8.set(input_Image_bytes, imageInputPtr / input_Image_bytes.BYTES_PER_ELEMENT);
621
+
622
+ const resultFirstPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
623
+ // create a pointer to interger to hold the length of the output buffer
624
+ const resultLenPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
625
+ printLogs(`Document OCR Config: `, config);
626
+
627
+ try {
628
+ await wasmPrivModules._privid_doc_ocr_front_enc(
629
+ wasmSession /* session pointer */,
630
+ configInputPtr,
631
+ configInputSize,
632
+ imageInputPtr /* input images */,
633
+ imageInputSize /* size of one image */,
634
+ resultFirstPtr /* operation result output buffer */,
635
+ resultLenPtr /* operation result buffer length */,
636
+ );
637
+ } catch (e) {
638
+ printLogs(`Error: `, e, 'ERROR');
639
+ }
640
+
641
+ wasmPrivModules._free(imageInputPtr);
642
+ wasmPrivModules._free(configInputPtr);
643
+ wasmPrivModules._free(resultFirstPtr);
644
+ wasmPrivModules._free(resultLenPtr);
645
+ } catch (e) {
646
+ printLogs(`Compare embeddings: `, e, 'ERROR');
647
+ }
648
+ }
649
+
650
+ async function initializeWasmSession(
651
+ url,
652
+ session_token,
653
+ public_key,
654
+ debug_type,
655
+ timeout = 5000,
656
+ usageScenario,
657
+ cache_content = '',
658
+ ) {
659
+ if (!wasmSession) {
660
+ printLogs(`initSession: ${url}, ${session_token}, ${public_key} `);
661
+ const session_out_ptr = output_ptr();
662
+ const settings = {
663
+ ...url,
664
+ session_token,
665
+ public_key,
666
+ debug_level: debug_type ? parseInt(debugType) : 0,
667
+ custom_settings: { usage_scenario: usageScenario, cache_content },
668
+ };
669
+
670
+ printLogs(`Settings:`, settings);
671
+ const settings_args = buffer_args(JSON.stringify(settings));
672
+
673
+ const s_result = wasmPrivModules._privid_initialize_session(...settings_args.args(), session_out_ptr.outer_ptr());
674
+ settings_args.free();
675
+
676
+ const isLoadedModels = wasmPrivModules._privid_check_models();
677
+
678
+ printLogs(`Loaded Models: `, isLoadedModels);
679
+ if (s_result) {
680
+ printLogs(`Session initialized successfully`, '');
681
+ } else {
682
+ printLogs(`Session initialization Failed`, '', 'ERROR');
683
+ return;
684
+ }
685
+
686
+ wasmSession = session_out_ptr.inner_ptr();
687
+ printLogs(`wasm session: `, wasmSession);
688
+ // if (setCache) {
689
+ // await setCacheConfiguration();
690
+ // }
691
+ }
692
+ }
693
+
694
+ const loadWasmModule = async (modulePath, moduleName, saveCache, version) => {
695
+ const wasm = await fetchResource(
696
+ `${cdnUrl}/${ModuleName}/${modulePath}/${version}/${moduleName}.wasm`,
697
+ `../wasm/${ModuleName}/${modulePath}/${version}/${moduleName}.wasm`,
698
+ );
699
+ const script = await fetchResource(
700
+ `${cdnUrl}/${ModuleName}/${modulePath}/${version}/${moduleName}.js`,
701
+ `../wasm/${ModuleName}/${modulePath}/${version}/${moduleName}.js`,
702
+ );
703
+ const scriptBuffer = await script.text();
704
+ const buffer = await wasm.arrayBuffer();
705
+
706
+ printLogs(`SCRIPT. BUFFER': `, { scriptBuffer, buffer });
707
+ eval(scriptBuffer);
708
+ const module = await createTFLiteModule({ wasmBinary: buffer });
709
+ printLogs(`Module: `, module);
710
+ if (saveCache) {
711
+ const version = module.UTF8ToString(module._privid_get_version());
712
+ await putKey('ultra', buffer, scriptBuffer, version);
713
+ }
714
+ return module;
715
+ };
716
+
717
+ async function fetchResource(cdnUrl, localUrl) {
718
+ try {
719
+ printLogs(`LOADING RESOURCE`, '');
720
+ if (useCdnLink) {
721
+ const response = await fetch(cdnUrl);
722
+ printLogs(`Response: `, response);
723
+ return response;
724
+ } else {
725
+ const response = await fetch(localUrl);
726
+ return response;
727
+ }
728
+ } catch (error) {
729
+ console.error(`Error fetching resource from CDN. Falling back to local path. Error: ${error}`);
730
+ return fetch(localUrl);
731
+ }
732
+ }
733
+
734
+ const pkiEncrypt = async (payload, config = JSON.stringify({})) => {
735
+ const encoder = new TextEncoder();
736
+ const payloadBytes = encoder.encode(`${payload}`);
737
+ const payloadInputSize = payloadBytes.length;
738
+ const payloadInputPtr = wasmPrivModules._malloc(payloadInputSize);
739
+
740
+ const resultFirstPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
741
+ // create a pointer to interger to hold the length of the output buffer
742
+ const resultLenPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
743
+ wasmPrivModules.HEAP8.set(payloadBytes, payloadInputPtr / payloadBytes.BYTES_PER_ELEMENT);
744
+ printLogs(`Payload: `, payload, debugType);
745
+ let res = null;
746
+
747
+ const config_bytes = encoder.encode(`${config}`);
748
+
749
+ const configInputSize = config.length;
750
+ const configInputPtr = wasmPrivModules._malloc(configInputSize);
751
+ wasmPrivModules.HEAP8.set(config_bytes, configInputPtr / config_bytes.BYTES_PER_ELEMENT);
752
+
753
+ try {
754
+ res = wasmPrivModules._privid_encrypt_payload(
755
+ wasmSession /* session pointer */,
756
+ configInputPtr,
757
+ configInputSize,
758
+ payloadInputPtr,
759
+ payloadInputSize,
760
+ resultFirstPtr /* operation result output buffer */,
761
+ resultLenPtr /* operation result buffer length */,
762
+ );
763
+ } catch (e) {
764
+ printLogs(`Error: `, e, 'ERROR');
765
+ }
766
+
767
+ printLogs(`Result: `, res);
768
+
769
+ const [outputBufferSizes] = new Uint32Array(wasmPrivModules.HEAPU8.buffer, resultLenPtr, 1);
770
+
771
+ if (outputBufferSizes > 0) {
772
+ // de-reference & copy the data from pointer to integer in integer array of one element
773
+ const outputBufferSize = new Uint32Array(wasmPrivModules.HEAPU8.buffer, resultLenPtr, 1)[0];
774
+ const outputBufferSecPtr = new Uint32Array(wasmPrivModules.HEAPU8.buffer, resultFirstPtr, 1)[0];
775
+ const outputBufferPtr = new Uint8Array(wasmPrivModules.HEAPU8.buffer, outputBufferSecPtr, outputBufferSize);
776
+
777
+ var decoder = new TextDecoder('utf8');
778
+ var dec = decoder.decode(outputBufferPtr);
779
+ dec.replace(/\0/g, '');
780
+ dec.replace(' ', '');
781
+ function removeNullBytes(str) {
782
+ return str
783
+ .split('')
784
+ .filter((char) => char.codePointAt(0))
785
+ .join('');
786
+ }
787
+ let parsedDec = JSON.stringify(removeNullBytes(dec));
788
+ printLogs(`Parsed: `, parsedDec);
789
+ let isObject = JSON.parse(parsedDec);
790
+ printLogs(`Is object? `, isObject);
791
+ return JSON.parse(isObject);
792
+ }
793
+
794
+ return { error: true };
795
+ };
796
+
797
+ const ultraScanFrontDocument = async (imageInput, simd, config, cb) => {
798
+ privid_wasm_result = cb;
799
+ if (!wasmPrivModules) {
800
+ await isLoad(simd, apiUrl, sesstionToken, publicKey);
801
+ }
802
+
803
+ const encoder = new TextEncoder();
804
+ const config_bytes = encoder.encode(`${config}`);
805
+
806
+ const configInputSize = config.length;
807
+ const configInputPtr = wasmPrivModules._malloc(configInputSize);
808
+ wasmPrivModules.HEAP8.set(config_bytes, configInputPtr / config_bytes.BYTES_PER_ELEMENT);
809
+
810
+ const imageInputSize = imageInput.data.length * imageInput.data.BYTES_PER_ELEMENT;
811
+ const imageInputPtr = wasmPrivModules._malloc(imageInputSize);
812
+ wasmPrivModules.HEAPU8.set(new Uint8Array(imageInput.data), imageInputPtr);
813
+
814
+ const resultFirstPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
815
+ const resultLenPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
816
+ printLogs(`Config: `, {
817
+ wasmSession /* session pointer */,
818
+ configInputPtr,
819
+ configInputSize,
820
+ imageInputPtr /* input images */,
821
+ width: imageInput.width /* width of one image */,
822
+ height: imageInput.height /* height of one image */,
823
+ resultFirstPtr /* operation result output buffer */,
824
+ resultLenPtr,
825
+ });
826
+
827
+ try {
828
+ await wasmPrivModules._privid_doc_scan_front(
829
+ wasmSession /* session pointer */,
830
+ configInputPtr,
831
+ configInputSize,
832
+ imageInputPtr /* input images */,
833
+ imageInput.width /* width of one image */,
834
+ imageInput.height /* height of one image */,
835
+ resultFirstPtr /* operation result output buffer */,
836
+ resultLenPtr /* operation result buffer length */,
837
+ );
838
+ } catch (e) {
839
+ printLogs(`Error: `, e, 'ERROR');
840
+ }
841
+
842
+ wasmPrivModules._free(imageInputPtr);
843
+ wasmPrivModules._free(configInputPtr);
844
+ wasmPrivModules._free(resultFirstPtr);
845
+ wasmPrivModules._free(resultLenPtr);
846
+ };
847
+
848
+ const ultraScanBackDocument = async (imageInput, simd, config, cb) => {
849
+ privid_wasm_result = cb;
850
+ if (!wasmPrivModules) {
851
+ await isLoad(simd, apiUrl, sesstionToken, publicKey, debugType);
852
+ }
853
+
854
+ printLogs(`Extra config: `, config);
855
+ const encoder = new TextEncoder();
856
+ const config_bytes = encoder.encode(`${config}`);
857
+
858
+ const configInputSize = config.length;
859
+ const configInputPtr = wasmPrivModules._malloc(configInputSize);
860
+
861
+ wasmPrivModules.HEAP8.set(config_bytes, configInputPtr / config_bytes.BYTES_PER_ELEMENT);
862
+
863
+ printLogs(`Image Input `, imageInput);
864
+ const imageInputSize = imageInput?.data?.length * imageInput?.data?.BYTES_PER_ELEMENT;
865
+ const imageInputPtr = wasmPrivModules._malloc(imageInputSize);
866
+ printLogs(`Input image Size:`, imageInputSize);
867
+ wasmPrivModules.HEAPU8.set(new Uint8Array(imageInput.data), imageInputPtr);
868
+ // wasmPrivModules.HEAP8.set(imageInput, imageInputPtr / imageInput?.data?.BYTES_PER_ELEMENT);
869
+
870
+ const resultFirstPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
871
+ // create a pointer to interger to hold the length of the output buffer
872
+ const resultLenPtr = wasmPrivModules._malloc(Int32Array.BYTES_PER_ELEMENT);
873
+ printLogs(`Config: `, {
874
+ configInputPtr,
875
+ configInputSize,
876
+ imageInputPtr /* input images */,
877
+ width: imageInput.width /* width of one image */,
878
+ height: imageInput.height /* height of one image */,
879
+ resultFirstPtr /* operation result output buffer */,
880
+ resultLenPtr /* operation result buffer length */,
881
+ });
882
+
883
+ try {
884
+ await wasmPrivModules._privid_doc_scan_back(
885
+ wasmSession /* session pointer */,
886
+ configInputPtr,
887
+ configInputSize,
888
+ imageInputPtr /* input images */,
889
+ imageInput.width /* width of one image */,
890
+ imageInput.height /* height of one image */,
891
+ resultFirstPtr /* operation result output buffer */,
892
+ resultLenPtr /* operation result buffer length */,
893
+ );
894
+ } catch (e) {
895
+ printLogs(`Error: `, e, 'ERROR');
896
+ }
897
+
898
+ wasmPrivModules._free(imageInputPtr);
899
+ wasmPrivModules._free(configInputPtr);
900
+ wasmPrivModules._free(resultFirstPtr);
901
+ wasmPrivModules._free(resultLenPtr);
902
+ };
903
+
904
+ const checkIfModelsLoaded = () => {
905
+ try {
906
+ const isLoaded = wasmPrivModules._privid_check_models();
907
+ return isLoaded;
908
+ } catch (e) {
909
+ printLogs(`Error: `, e, 'ERROR');
910
+ return 0;
911
+ }
912
+ };
913
+
914
+ const freeMemory = () => {
915
+ try {
916
+ const isLoaded = wasmPrivModules._privid_free_memory();
917
+ return isLoaded;
918
+ } catch (e) {
919
+ printLogs(`Error: `, e, 'ERROR');
920
+ return 0;
921
+ }
922
+ };
923
+
924
+ Comlink.expose({
925
+ ultraEnroll,
926
+ ultraPredict,
927
+ ultraAgeEstimate,
928
+ ultraCompareEmbeddings,
929
+ isLoad,
930
+ pkiEncrypt,
931
+ checkIfModelsLoaded,
932
+ ultraScanBackDocument,
933
+ ultraScanFrontDocument,
934
+ ultraDocumentOcr,
935
+ freeMemory,
936
+ });