@authme/util 2.3.1-rc.3 → 2.4.6

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.
package/index.cjs CHANGED
@@ -11,15 +11,22 @@ require('core-js/modules/es.typed-array.sort.js');
11
11
  require('core-js/modules/es.typed-array.to-locale-string.js');
12
12
  require('core-js/modules/es.promise.js');
13
13
  require('core-js/modules/es.regexp.exec.js');
14
+ require('core-js/modules/es.regexp.to-string.js');
14
15
  require('core-js/modules/web.dom-collections.iterator.js');
16
+ require('core-js/modules/es.object.assign.js');
17
+ require('core-js/modules/es.number.parse-int.js');
18
+ var jwt_decode = require('jwt-decode');
19
+ require('core-js/modules/es.string.match.js');
20
+ require('core-js/modules/es.string.replace.js');
15
21
  require('core-js/modules/web.url-search-params.js');
16
22
  require('core-js/modules/es.string.search.js');
17
- require('core-js/modules/es.string.match.js');
18
- require('core-js/modules/es.array.sort.js');
23
+ require('core-js/modules/es.typed-array.uint32-array.js');
19
24
  require('core-js/modules/es.array.includes.js');
20
25
  require('core-js/modules/es.string.includes.js');
21
- var lottie = require('lottie-web');
22
- require('core-js/modules/es.string.replace.js');
26
+ var fileSaver = require('file-saver');
27
+ var JSZip = require('jszip');
28
+ var Lottie = require('lottie-web');
29
+ require('core-js/modules/es.array.sort.js');
23
30
  require('core-js/modules/es.parse-int.js');
24
31
  require('core-js/modules/es.string.trim.js');
25
32
  require('core-js/modules/es.string.starts-with.js');
@@ -27,23 +34,34 @@ require('core-js/modules/es.symbol.description.js');
27
34
 
28
35
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
29
36
 
30
- var lottie__default = /*#__PURE__*/_interopDefaultLegacy(lottie);
37
+ var jwt_decode__default = /*#__PURE__*/_interopDefaultLegacy(jwt_decode);
38
+ var JSZip__default = /*#__PURE__*/_interopDefaultLegacy(JSZip);
39
+ var Lottie__default = /*#__PURE__*/_interopDefaultLegacy(Lottie);
31
40
 
32
41
  const GLOBAL_KEY = '_AuthmeConfig';
42
+ const _storage = {};
43
+ exports.STORAGE_KEY = void 0;
44
+ (function (STORAGE_KEY) {
45
+ STORAGE_KEY["LOADING_LOTTIE"] = "loadingLottie";
46
+ STORAGE_KEY["OCR_IDCARD_RESULT_FORMAT"] = "ocrIdcardResultFormat";
47
+ STORAGE_KEY["ENABLE_EVENT_TRACKING"] = "enableEventTracking";
48
+ STORAGE_KEY["EVENT_TRACK_URL"] = "eventTrackUrl";
49
+ STORAGE_KEY["API_BASE_URL"] = "apiBaseUrl";
50
+ })(exports.STORAGE_KEY || (exports.STORAGE_KEY = {}));
33
51
  function getItem(key) {
34
- return window[GLOBAL_KEY][key];
52
+ return _storage[GLOBAL_KEY][key];
35
53
  }
36
54
  function setItem(key, val) {
37
- if (!window[GLOBAL_KEY]) {
38
- window[GLOBAL_KEY] = {};
55
+ if (!_storage[GLOBAL_KEY]) {
56
+ _storage[GLOBAL_KEY] = {};
39
57
  }
40
- return window[GLOBAL_KEY][key] = val;
58
+ return _storage[GLOBAL_KEY][key] = val;
41
59
  }
42
60
  function removeItem(key) {
43
- return delete window[GLOBAL_KEY][key];
61
+ return delete _storage[GLOBAL_KEY][key];
44
62
  }
45
63
  function clear() {
46
- window[GLOBAL_KEY] = {};
64
+ _storage[GLOBAL_KEY] = {};
47
65
  }
48
66
  const Storage = {
49
67
  getItem,
@@ -67,6 +85,18 @@ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
67
85
  PERFORMANCE OF THIS SOFTWARE.
68
86
  ***************************************************************************** */
69
87
 
88
+ function __rest(s, e) {
89
+ var t = {};
90
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
91
+ t[p] = s[p];
92
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
93
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
94
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
95
+ t[p[i]] = s[p[i]];
96
+ }
97
+ return t;
98
+ }
99
+
70
100
  function __awaiter(thisArg, _arguments, P, generator) {
71
101
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
72
102
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -113,6 +143,188 @@ function __asyncValues(o) {
113
143
  function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
114
144
  }
115
145
 
146
+ class AuthmeError {
147
+ constructor(code, cause = null) {
148
+ this._cause = null;
149
+ this._code = null;
150
+ this._code = code;
151
+ this._cause = cause;
152
+ }
153
+ get message() {
154
+ return '[Authme SDK Error] Code: ' + this.code;
155
+ }
156
+ setCode(code) {
157
+ this._code = code;
158
+ }
159
+ get code() {
160
+ return this._code;
161
+ }
162
+ get cause() {
163
+ return this._cause;
164
+ }
165
+ }
166
+ exports.ErrorCode = void 0;
167
+ (function (ErrorCode) {
168
+ // 1XX for engine
169
+ ErrorCode[ErrorCode["BROWSER_NOT_SUPPORT"] = 100] = "BROWSER_NOT_SUPPORT";
170
+ ErrorCode[ErrorCode["ENGINE_INIT_ERROR"] = 101] = "ENGINE_INIT_ERROR";
171
+ ErrorCode[ErrorCode["ENGINE_MODULE_IS_INITIALIZING"] = 102] = "ENGINE_MODULE_IS_INITIALIZING";
172
+ ErrorCode[ErrorCode["ENGINE_MODULE_INIT_ERROR"] = 103] = "ENGINE_MODULE_INIT_ERROR";
173
+ ErrorCode[ErrorCode["RECOGNITION_NOT_AVAILABLE"] = 104] = "RECOGNITION_NOT_AVAILABLE";
174
+ ErrorCode[ErrorCode["RECOGNITION_ERROR"] = 105] = "RECOGNITION_ERROR";
175
+ ErrorCode[ErrorCode["INVALID_AUTH_ERROR"] = 106] = "INVALID_AUTH_ERROR";
176
+ ErrorCode[ErrorCode["SCREEN_RESOLUTION_TOO_LOW"] = 107] = "SCREEN_RESOLUTION_TOO_LOW";
177
+ ErrorCode[ErrorCode["SCREEN_SIZE_CHANGED"] = 108] = "SCREEN_SIZE_CHANGED";
178
+ // 2 for LIVENESS
179
+ ErrorCode[ErrorCode["LIVENESS_NOT_PASSED"] = 201] = "LIVENESS_NOT_PASSED";
180
+ // 3 for ID-Recognition
181
+ ErrorCode[ErrorCode["ID_RECOGNITION_CONFIRM_INFO_ERROR"] = 301] = "ID_RECOGNITION_CONFIRM_INFO_ERROR";
182
+ ErrorCode[ErrorCode["ID_RECOGNITION_TIMEOUT"] = 302] = "ID_RECOGNITION_TIMEOUT";
183
+ // 4 for Anti-fraud
184
+ ErrorCode[ErrorCode["ID_RECOGNITION_ANTI_FRAUD_NOT_PASSED"] = 401] = "ID_RECOGNITION_ANTI_FRAUD_NOT_PASSED";
185
+ // 9 for common
186
+ ErrorCode[ErrorCode["SDK_INTERNAL_ERROR"] = 900] = "SDK_INTERNAL_ERROR";
187
+ ErrorCode[ErrorCode["NETWORK_ERROR"] = 901] = "NETWORK_ERROR";
188
+ ErrorCode[ErrorCode["HTTP_ERROR_RESPONSE"] = 902] = "HTTP_ERROR_RESPONSE";
189
+ ErrorCode[ErrorCode["USER_CANCEL"] = 903] = "USER_CANCEL";
190
+ ErrorCode[ErrorCode["CAMERA_NOT_SUPPORT"] = 904] = "CAMERA_NOT_SUPPORT";
191
+ ErrorCode[ErrorCode["SERVER_ERROR"] = 905] = "SERVER_ERROR";
192
+ ErrorCode[ErrorCode["EVENT_NAME_WRONG"] = 906] = "EVENT_NAME_WRONG";
193
+ })(exports.ErrorCode || (exports.ErrorCode = {}));
194
+
195
+ function decodeToken(token) {
196
+ const decoded = jwt_decode__default["default"](token);
197
+ const {
198
+ exp,
199
+ iat
200
+ } = decoded;
201
+ return {
202
+ payload: decoded,
203
+ exp: typeof exp === 'number' ? exp : 0,
204
+ iat: typeof iat === 'number' ? iat : 0
205
+ };
206
+ }
207
+
208
+ function getDeviceInfo() {
209
+ const userAgent = window.navigator.userAgent;
210
+ const deviceType = getDeviceType(userAgent);
211
+ const browserType = getBrowserType(userAgent);
212
+ return `${deviceType} (${browserType})`;
213
+ }
214
+ function getDeviceType(userAgent) {
215
+ if (userAgent.match(/iPad/i) || userAgent.match(/iPhone/i)) {
216
+ return 'iPad/iPhone';
217
+ } else if (userAgent.match(/Android/i)) {
218
+ return 'Android';
219
+ } else if (userAgent.match(/Windows Phone/i)) {
220
+ return 'Windows Phone';
221
+ } else if (userAgent.match(/Windows NT/i)) {
222
+ return 'Windows PC';
223
+ } else if (userAgent.match(/Mac OS/i)) {
224
+ return 'Mac';
225
+ } else if (userAgent.match(/Linux/i)) {
226
+ return 'Linux';
227
+ } else {
228
+ return 'Unknown Device';
229
+ }
230
+ }
231
+ function getBrowserType(userAgent) {
232
+ if (userAgent.match(/Chrome/i)) {
233
+ return 'Chrome';
234
+ } else if (userAgent.match(/Firefox/i)) {
235
+ return 'Firefox';
236
+ } else if (userAgent.match(/Edge/i)) {
237
+ return 'Edge';
238
+ } else if (userAgent.match(/Safari/i)) {
239
+ return 'Safari';
240
+ } else if (userAgent.match(/MSIE/i) || userAgent.match(/Trident/i)) {
241
+ return 'IE';
242
+ } else {
243
+ return 'Unknown Browser';
244
+ }
245
+ }
246
+ function getSystemInfo() {
247
+ const userAgent = window.navigator.userAgent;
248
+ const os = getOs(userAgent);
249
+ const osVersion = getOsVersion(userAgent);
250
+ return `${os} (${osVersion})`;
251
+ }
252
+ function getOs(userAgent) {
253
+ if (userAgent.match(/Windows NT 10/i)) {
254
+ return 'Windows 10';
255
+ } else if (userAgent.match(/Windows NT 6.3/i)) {
256
+ return 'Windows 8.1';
257
+ } else if (userAgent.match(/Windows NT 6.2/i)) {
258
+ return 'Windows 8';
259
+ } else if (userAgent.match(/Windows NT 6.1/i)) {
260
+ return 'Windows 7';
261
+ } else if (userAgent.match(/Windows NT 6.0/i)) {
262
+ return 'Windows Vista';
263
+ } else if (userAgent.match(/Windows NT 5.1/i)) {
264
+ return 'Windows XP';
265
+ } else if (userAgent.match(/Windows NT 5.0/i)) {
266
+ return 'Windows 2000';
267
+ } else if (userAgent.match(/Mac/i)) {
268
+ return 'Mac OS';
269
+ } else if (userAgent.match(/Linux/i)) {
270
+ return 'Linux';
271
+ } else {
272
+ return 'Unknown OS';
273
+ }
274
+ }
275
+ function getOsVersion(userAgent) {
276
+ if (userAgent.match(/Windows NT/i)) {
277
+ const matches = userAgent.match(/Windows NT ([\d\\.]+)/i);
278
+ if (matches) {
279
+ return matches[1];
280
+ } else {
281
+ return '';
282
+ }
283
+ }
284
+ if (userAgent.match(/Mac/i)) {
285
+ const matches = userAgent.match(/Mac OS X ([\d_.]+)/i);
286
+ if (matches) {
287
+ return matches[1].replace(/_/g, '.');
288
+ } else {
289
+ return '';
290
+ }
291
+ } else if (userAgent.match(/Android/i)) {
292
+ const matches = userAgent.match(/Android ([\d.]+)/i);
293
+ if (matches) {
294
+ return matches[1];
295
+ } else {
296
+ return '';
297
+ }
298
+ } else {
299
+ return '';
300
+ }
301
+ }
302
+
303
+ class State {
304
+ constructor(initialValue = null) {
305
+ this._value = initialValue;
306
+ }
307
+ getValue() {
308
+ return this._value;
309
+ }
310
+ setValue(newValue) {
311
+ this._value = newValue;
312
+ }
313
+ }
314
+ function useState(initialValue = null, subscription) {
315
+ const state = new State(initialValue);
316
+ function getValue() {
317
+ return state.getValue();
318
+ }
319
+ function setValue(newValue) {
320
+ if (subscription && newValue !== state.getValue()) {
321
+ subscription.next(newValue);
322
+ }
323
+ state.setValue(newValue);
324
+ }
325
+ return [getValue, setValue];
326
+ }
327
+
116
328
  function dataURItoBlob(dataURI) {
117
329
  // convert base64/URLEncoded data component to raw binary data held in a string
118
330
  const byteString = atob(dataURI.split(',')[1]);
@@ -164,7 +376,9 @@ function retryPromiseWithCondition(promiseFactory, conditionFactory) {
164
376
  const res = yield promiseFactory();
165
377
  return res;
166
378
  } catch (e) {
167
- console.error(e);
379
+ if ((e === null || e === void 0 ? void 0 : e._code) === exports.ErrorCode.SERVER_ERROR) {
380
+ throw e;
381
+ }
168
382
  const retry = yield conditionFactory(e);
169
383
  if (retry) {
170
384
  return retryPromiseWithCondition(promiseFactory, conditionFactory);
@@ -187,59 +401,418 @@ function isMobile() {
187
401
  return !!(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test(a.substr(0, 4)) || /Android|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent));
188
402
  }(navigator.userAgent || navigator.vendor || window.opera);
189
403
  }
190
-
191
- class AuthmeError {
192
- constructor(code, cause = null) {
193
- this._cause = null;
194
- this._code = null;
195
- this._code = code;
196
- this._cause = cause;
404
+ function splitResult(result) {
405
+ if (result.address) {
406
+ const originAddress = result.address;
407
+ const address1Index = checkCity(originAddress);
408
+ result.address1 = address1Index === -1 ? '' : originAddress.slice(0, 3);
409
+ const address2 = address1Index === -1 ? originAddress : originAddress.slice(3);
410
+ const address2Index = checkZone(address2);
411
+ result.address2 = address2Index === -1 ? '' : address2.slice(0, address2Index + 1);
412
+ result.address3 = address2Index === -1 ? address2 : address2.slice(address2Index + 1);
197
413
  }
198
- get message() {
199
- return '[Authme SDK Error] Code: ' + this.code;
414
+ if (result.dateOfBirth) {
415
+ const splitDateOfBirth = result.dateOfBirth.split('-');
416
+ const dateOfBirthY = (+splitDateOfBirth[0] - 1911).toString();
417
+ result.dateOfBirthY = dateOfBirthY.length < 3 ? '0' + dateOfBirthY : dateOfBirthY;
418
+ result.dateOfBirthM = splitDateOfBirth[1];
419
+ result.dateOfBirthD = splitDateOfBirth[2];
200
420
  }
201
- setCode(code) {
202
- this._code = code;
421
+ if (result.dateOfIssue) {
422
+ const splitDateOfIssue = result.dateOfIssue.split('-');
423
+ const dateOfIssueY = (+splitDateOfIssue[0] - 1911).toString();
424
+ result.dateOfIssueY = dateOfIssueY.length < 3 ? '0' + dateOfIssueY : dateOfIssueY;
425
+ result.dateOfIssueM = splitDateOfIssue[1];
426
+ result.dateOfIssueD = splitDateOfIssue[2];
203
427
  }
204
- get code() {
205
- return this._code;
428
+ return result;
429
+ }
430
+ function checkCity(address) {
431
+ const citys = ['臺北市', '臺中市', '基隆市', '臺南市', '高雄市', '新北市', '宜蘭縣', '桃園市', '嘉義市', '新竹縣', '苗栗縣', '南投縣', '彰化縣', '新竹市', '雲林縣', '嘉義縣', '屏東縣', '花蓮縣', '臺東縣', '金門縣', '澎湖縣', '連江縣', '臺中縣', '臺南縣', '高雄縣'];
432
+ for (const city of citys) {
433
+ if (address.indexOf(city) !== -1) {
434
+ return address.indexOf(city);
435
+ }
206
436
  }
207
- get cause() {
208
- return this._cause;
437
+ return -1;
438
+ }
439
+ function checkZone(address) {
440
+ const zones = ['鄉', '鎮', '市', '區'];
441
+ for (const zone of zones) {
442
+ if (address.indexOf(zone) !== -1) {
443
+ return address.indexOf(zone);
444
+ }
209
445
  }
446
+ return -1;
447
+ }
448
+ function notEmpty(value) {
449
+ return typeof value !== 'undefined' && value !== null && value !== '';
450
+ }
451
+ function combineResult(result) {
452
+ const {
453
+ address1,
454
+ address2,
455
+ address3,
456
+ dateOfBirthY,
457
+ dateOfBirthM,
458
+ dateOfBirthD,
459
+ dateOfIssueY,
460
+ dateOfIssueM,
461
+ dateOfIssueD
462
+ } = result,
463
+ others = __rest(result, ["address1", "address2", "address3", "dateOfBirthY", "dateOfBirthM", "dateOfBirthD", "dateOfIssueY", "dateOfIssueM", "dateOfIssueD"]);
464
+ // 由於呼叫函數的情境包含 confirmOCRResult,
465
+ // confirmOCRResult 並不會知道目前是什麼卡片類型,
466
+ // 所以會以分割出的欄位來判斷是否進行欄位合併與覆寫。
467
+ const newResult = Object.assign({}, others);
468
+ if ([address1, address2, address3].every(notEmpty)) {
469
+ newResult.address = `${address1}${address2}${address3}`;
470
+ }
471
+ if ([dateOfBirthY, dateOfBirthM, dateOfBirthD].every(notEmpty)) {
472
+ newResult.dateOfBirth = `${1911 + Number.parseInt(dateOfBirthY || '0')}-${dateOfBirthM}-${dateOfBirthD}`;
473
+ }
474
+ if ([dateOfIssueY, dateOfIssueM, dateOfIssueD].every(notEmpty)) {
475
+ newResult.dateOfIssue = `${1911 + Number.parseInt(dateOfIssueY || '0')}-${dateOfIssueM}-${dateOfIssueD}`;
476
+ }
477
+ return newResult;
478
+ }
479
+ const isIphone14proOrProMax = () => {
480
+ const isIphone = () => {
481
+ return /iPhone|iPad|iPod/i.test(navigator.userAgent);
482
+ };
483
+ return isIphone() && (screen.width === 430 && screen.height === 932 || screen.width === 393 && screen.height === 852);
484
+ };
485
+
486
+ function fileSaverService() {
487
+ const filesQueue = [];
488
+ function pushFile(file) {
489
+ filesQueue.push(file);
490
+ }
491
+ function popAllFiles() {
492
+ filesQueue.splice(0, filesQueue.length);
493
+ }
494
+ function saveFiles(fileName, json) {
495
+ return __awaiter(this, void 0, void 0, function* () {
496
+ const zip = new JSZip__default["default"]();
497
+ filesQueue.forEach(fileItem => {
498
+ zip.file(fileItem.name, fileItem.file);
499
+ });
500
+ if (json) zip.file('data.json', JSON.stringify(json));
501
+ const content = yield zip.generateAsync({
502
+ type: 'blob'
503
+ });
504
+ fileSaver.saveAs(content, `${fileName}.zip`);
505
+ popAllFiles();
506
+ });
507
+ }
508
+ return {
509
+ pushFile,
510
+ saveFiles
511
+ };
210
512
  }
211
- exports.ErrorCode = void 0;
212
- (function (ErrorCode) {
213
- // 1XX for engine
214
- ErrorCode[ErrorCode["BROWSER_NOT_SUPPORT"] = 100] = "BROWSER_NOT_SUPPORT";
215
- ErrorCode[ErrorCode["ENGINE_INIT_ERROR"] = 101] = "ENGINE_INIT_ERROR";
216
- ErrorCode[ErrorCode["ENGINE_MODULE_IS_INITIALIZING"] = 102] = "ENGINE_MODULE_IS_INITIALIZING";
217
- ErrorCode[ErrorCode["ENGINE_MODULE_INIT_ERROR"] = 103] = "ENGINE_MODULE_INIT_ERROR";
218
- ErrorCode[ErrorCode["RECOGNITION_NOT_AVAILABLE"] = 104] = "RECOGNITION_NOT_AVAILABLE";
219
- ErrorCode[ErrorCode["RECOGNITION_ERROR"] = 105] = "RECOGNITION_ERROR";
220
- ErrorCode[ErrorCode["INVALID_AUTH_ERROR"] = 106] = "INVALID_AUTH_ERROR";
221
- ErrorCode[ErrorCode["SCREEN_RESOLUTION_TOO_LOW"] = 107] = "SCREEN_RESOLUTION_TOO_LOW";
222
- ErrorCode[ErrorCode["SCREEN_SIZE_CHANGED"] = 108] = "SCREEN_SIZE_CHANGED";
223
- // 2 for LIVENESS
224
- ErrorCode[ErrorCode["LIVENESS_NOT_PASSED"] = 201] = "LIVENESS_NOT_PASSED";
225
- // 3 for ID-Recognition
226
- ErrorCode[ErrorCode["ID_RECOGNITION_CONFIRM_INFO_ERROR"] = 301] = "ID_RECOGNITION_CONFIRM_INFO_ERROR";
227
- ErrorCode[ErrorCode["ID_RECOGNITION_TIMEOUT"] = 302] = "ID_RECOGNITION_TIMEOUT";
228
- // 4 for Anti-fraud
229
- ErrorCode[ErrorCode["ID_RECOGNITION_ANTI_FRAUD_NOT_PASSED"] = 401] = "ID_RECOGNITION_ANTI_FRAUD_NOT_PASSED";
230
- // 9 for common
231
- ErrorCode[ErrorCode["SDK_INTERNAL_ERROR"] = 900] = "SDK_INTERNAL_ERROR";
232
- ErrorCode[ErrorCode["NETWORK_ERROR"] = 901] = "NETWORK_ERROR";
233
- ErrorCode[ErrorCode["HTTP_ERROR_RESPONSE"] = 902] = "HTTP_ERROR_RESPONSE";
234
- ErrorCode[ErrorCode["USER_CANCEL"] = 903] = "USER_CANCEL";
235
- ErrorCode[ErrorCode["CAMERA_NOT_SUPPORT"] = 904] = "CAMERA_NOT_SUPPORT";
236
- })(exports.ErrorCode || (exports.ErrorCode = {}));
237
513
 
514
+ const {
515
+ saveFiles,
516
+ pushFile
517
+ } = fileSaverService();
518
+ exports.RUN_FUNCTION_NAME = void 0;
519
+ (function (RUN_FUNCTION_NAME) {
520
+ RUN_FUNCTION_NAME["RECOGNITION"] = "service.recognition";
521
+ RUN_FUNCTION_NAME["ANTI_FARUD_RECOGNITION"] = "antiFraudInstance.recognition";
522
+ RUN_FUNCTION_NAME["API_REQUEST"] = "api.request";
523
+ })(exports.RUN_FUNCTION_NAME || (exports.RUN_FUNCTION_NAME = {}));
238
524
  function debugLog(message, ...others) {
239
525
  if (new URLSearchParams(location.search).get('authme-debug') === 'true') {
240
526
  console.log(message, ...others);
241
527
  }
242
528
  }
529
+ function generateUniqueId(length = 32) {
530
+ if (length <= 0) {
531
+ throw new Error('Length should be a positive integer.');
532
+ }
533
+ // 定義可能的字元
534
+ const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
535
+ const charactersLength = characters.length;
536
+ const randomValues = new Uint32Array(length);
537
+ // 使用window.crypto.getRandomValues取得真正的隨機值
538
+ window.crypto.getRandomValues(randomValues);
539
+ let result = '';
540
+ for (let i = 0; i < length; i++) {
541
+ result += characters[randomValues[i] % charactersLength];
542
+ }
543
+ return result;
544
+ }
545
+ function debugTools() {
546
+ const debugMode = new URLSearchParams(location.search).get('authme-debug') === 'true';
547
+ const debugModeUI = new URLSearchParams(location.search).get('authme-debug-info') === 'true';
548
+ const shouldGetDebugImage = new URLSearchParams(location.search).get('authme-debug-get-image') === 'true';
549
+ const debugLogs = [];
550
+ const logInfo = {
551
+ userAgent: navigator.userAgent,
552
+ token: '',
553
+ message: ''
554
+ };
555
+ let currentRoundId = generateUniqueId(8);
556
+ let currentType = null;
557
+ const interiaTimeObj = {};
558
+ function pushNewDebugLog(logParams) {
559
+ var _a;
560
+ if (!debugMode) return;
561
+ const now = new Date();
562
+ const _logParams = JSON.parse(JSON.stringify(logParams));
563
+ if (_logParams.result) {
564
+ (_a = _logParams.result) === null || _a === void 0 ? true : delete _a.imageData;
565
+ }
566
+ const newDebugLog = Object.assign(Object.assign({
567
+ dateTime: now.toLocaleString(),
568
+ roundId: currentRoundId,
569
+ type: currentType !== null && currentType !== void 0 ? currentType : undefined
570
+ }, _logParams), {
571
+ time: now.getTime(),
572
+ _id: generateUniqueId()
573
+ });
574
+ debugLogs.push(newDebugLog);
575
+ return newDebugLog;
576
+ }
577
+ function pushNewDebugImage(image, log, options) {
578
+ var _a, _b;
579
+ if (!debugMode) return;
580
+ const newLog = pushNewDebugLog(log);
581
+ const recognitionFunctions = [exports.RUN_FUNCTION_NAME.ANTI_FARUD_RECOGNITION, exports.RUN_FUNCTION_NAME.RECOGNITION];
582
+ const currentRoundRecognitionResultItem = debugLogs.find(item => item.roundId === (newLog === null || newLog === void 0 ? void 0 : newLog.roundId) && item.status === 'run-end' && (item.runFunction ? recognitionFunctions.includes(item.runFunction) : false));
583
+ const imageStatus = (_a = currentRoundRecognitionResultItem === null || currentRoundRecognitionResultItem === void 0 ? void 0 : currentRoundRecognitionResultItem.result) === null || _a === void 0 ? void 0 : _a.eStatus;
584
+ pushFile({
585
+ name: `${(_b = options === null || options === void 0 ? void 0 : options.prefix) !== null && _b !== void 0 ? _b : ''}${newLog === null || newLog === void 0 ? void 0 : newLog.time}-${newLog === null || newLog === void 0 ? void 0 : newLog._id}${imageStatus ? `__${imageStatus}` : ''}.jpeg`,
586
+ file: image
587
+ });
588
+ }
589
+ function functionLogging(func, logParams) {
590
+ return new Promise((resolve, reject) => {
591
+ pushNewDebugLog(Object.assign(Object.assign({}, logParams), {
592
+ status: 'run-start'
593
+ }));
594
+ func().then(result => {
595
+ pushNewDebugLog(Object.assign(Object.assign({}, logParams), {
596
+ status: 'run-end',
597
+ roundId: currentRoundId,
598
+ result
599
+ }));
600
+ resolve(result);
601
+ }).catch(error => {
602
+ pushNewDebugLog(Object.assign(Object.assign({}, logParams), {
603
+ status: 'run-error',
604
+ roundId: currentRoundId,
605
+ result: error
606
+ }));
607
+ reject(error);
608
+ });
609
+ });
610
+ }
611
+ function renderDebugTips() {
612
+ if (document.getElementById('debug-tips')) {
613
+ return;
614
+ }
615
+ const debugTips = document.createElement('div');
616
+ debugTips.style.position = 'fixed';
617
+ debugTips.style.top = '50px';
618
+ debugTips.style.right = '0';
619
+ debugTips.style.zIndex = '999';
620
+ debugTips.innerHTML = 'Debug Mode';
621
+ debugTips.style.color = 'red';
622
+ debugTips.style.fontWeight = 'bold';
623
+ debugTips.setAttribute('id', 'debug-tips');
624
+ document.body.appendChild(debugTips);
625
+ }
626
+ function renderDebugUI() {
627
+ if (document.getElementById('debug-ui')) {
628
+ return;
629
+ }
630
+ const debugUI = document.createElement('div');
631
+ debugUI.style.position = 'fixed';
632
+ debugUI.style.top = '0';
633
+ debugUI.style.right = '0';
634
+ debugUI.style.zIndex = '777';
635
+ debugUI.style.backgroundColor = 'black';
636
+ debugUI.style.color = 'white';
637
+ debugUI.style.padding = '10px';
638
+ debugUI.style.paddingRight = '150px';
639
+ debugUI.style.fontSize = '12px';
640
+ debugUI.style.opacity = '0.7';
641
+ debugUI.style.boxSizing = 'border-box';
642
+ debugUI.style.width = '100%';
643
+ debugUI.style.maxHeight = '50vh';
644
+ debugUI.style.overflow = 'auto';
645
+ debugUI.setAttribute('id', 'debug-ui');
646
+ const closeUI = document.createElement('button');
647
+ closeUI.style.position = 'fixed';
648
+ closeUI.style.top = '0';
649
+ closeUI.style.right = '100px';
650
+ closeUI.innerHTML = 'close';
651
+ closeUI.addEventListener('click', () => {
652
+ debugUI.style.display = 'none';
653
+ });
654
+ debugUI.appendChild(closeUI);
655
+ const accordionUI = document.createElement('button');
656
+ accordionUI.style.position = 'fixed';
657
+ accordionUI.style.top = '0';
658
+ accordionUI.style.right = '0';
659
+ accordionUI.innerHTML = '收合/展開';
660
+ accordionUI.addEventListener('click', () => {
661
+ if (debugUI.style.maxHeight === '50vh') {
662
+ debugUI.style.maxHeight = '5vh';
663
+ } else {
664
+ debugUI.style.maxHeight = '50vh';
665
+ }
666
+ });
667
+ debugUI.appendChild(accordionUI);
668
+ document.body.appendChild(debugUI);
669
+ }
670
+ function setTimeStart(behavior) {
671
+ if (!debugModeUI) {
672
+ return;
673
+ }
674
+ const dStart = new Date();
675
+ const nStart = dStart.getTime();
676
+ if (interiaTimeObj && interiaTimeObj[behavior]) {
677
+ console.error('debugmode: setTimeStart duplicate', behavior);
678
+ return false;
679
+ }
680
+ interiaTimeObj[behavior] = {
681
+ behavior,
682
+ start: nStart / 1000,
683
+ duration: 0,
684
+ end: 0
685
+ };
686
+ // console.log(interiaTimeObj[behavior])
687
+ renderTimeInfo(behavior);
688
+ return interiaTimeObj[behavior];
689
+ }
690
+ function setTimeEnd(behavior) {
691
+ if (!debugModeUI) {
692
+ return;
693
+ }
694
+ const dEnd = new Date();
695
+ const nEnd = dEnd.getTime();
696
+ if (!interiaTimeObj[behavior]) {
697
+ console.error('debugmode: setTimeEnd not found', behavior);
698
+ return false;
699
+ }
700
+ interiaTimeObj[behavior].end = nEnd / 1000;
701
+ interiaTimeObj[behavior].duration = interiaTimeObj[behavior].end - interiaTimeObj[behavior].start;
702
+ // console.log(interiaTimeObj[behavior])
703
+ renderTimeInfo(behavior);
704
+ return interiaTimeObj[behavior];
705
+ }
706
+ function setTimeDuration(behavior) {
707
+ const ts = Date.now();
708
+ setTimeStart(`${behavior}_${ts}`);
709
+ return {
710
+ end: () => {
711
+ setTimeEnd(`${behavior}_${ts}`);
712
+ }
713
+ };
714
+ }
715
+ function renderTimeInfo(behavior) {
716
+ const dom = document.querySelector(`#debug-ui-${behavior}`);
717
+ const info = `{"behavior":<span style="color:green;">"${behavior}"</span>, "start": ${interiaTimeObj[behavior].start}, "duration": ${interiaTimeObj[behavior].duration}, "end": ${interiaTimeObj[behavior].end}}`;
718
+ // const info = `<span style="color:green;">${behavior}</span>: Duration: ${interiaTimeObj[behavior].duration}s`;
719
+ if (dom) {
720
+ dom.innerHTML = info;
721
+ return;
722
+ }
723
+ const debugUI = document.getElementById('debug-ui');
724
+ const div = document.createElement('div');
725
+ div.setAttribute('class', 'debug-ui-item');
726
+ div.setAttribute('id', `debug-ui-${behavior}`);
727
+ div.innerHTML = info;
728
+ debugUI.appendChild(div);
729
+ }
730
+ function functionRunTime() {
731
+ const arr = [];
732
+ const items = document.querySelectorAll('.debug-ui-item');
733
+ items.forEach(item => {
734
+ arr.push(JSON.parse(item.innerText));
735
+ });
736
+ return arr;
737
+ }
738
+ if (debugMode) {
739
+ renderDebugTips();
740
+ // setRequestLoggingFunc(functionLogging)
741
+ }
742
+
743
+ if (debugModeUI) {
744
+ console.log('debugModeUI Init');
745
+ renderDebugUI();
746
+ }
747
+ function saveDebugImage({
748
+ getDebugImageData,
749
+ data,
750
+ width,
751
+ height,
752
+ result,
753
+ type
754
+ }) {
755
+ return __awaiter(this, void 0, void 0, function* () {
756
+ if (!debugMode || !shouldGetDebugImage) return;
757
+ const debugImage = yield getDebugImageData(data);
758
+ // 創建一個虛擬的 canvas
759
+ const canvas = document.createElement('canvas');
760
+ const ctx = canvas.getContext('2d');
761
+ // 設置 canvas 的尺寸
762
+ canvas.width = width;
763
+ canvas.height = height;
764
+ // 使用 Uint8ClampedArray 將圖像數據繪製到 canvas 上
765
+ const imgData = ctx === null || ctx === void 0 ? void 0 : ctx.createImageData(width, height);
766
+ if (imgData) {
767
+ imgData.data.set(debugImage);
768
+ ctx === null || ctx === void 0 ? void 0 : ctx.putImageData(imgData, 0, 0);
769
+ canvas.toBlob(blob => {
770
+ if (blob) {
771
+ pushNewDebugImage(blob, {
772
+ result: result,
773
+ status: 'recognition',
774
+ type: type
775
+ }, {
776
+ prefix: 'debugImage_'
777
+ });
778
+ }
779
+ }, 'image/jpeg');
780
+ }
781
+ });
782
+ }
783
+ return {
784
+ debugMode,
785
+ debugModeUI,
786
+ pushNewDebugLog,
787
+ getDebugLogs: () => debugLogs,
788
+ getDebugLogsLength: () => debugLogs.length,
789
+ modifyDeubgLog: (index, logParams) => {
790
+ if (!debugMode) return;
791
+ debugLogs[index] = Object.assign(Object.assign({}, debugLogs[index]), logParams);
792
+ },
793
+ downloadDebugLogs: () => {
794
+ if (!debugMode) return;
795
+ saveFiles(`debugLog${new Date().getTime().toString()}`, {
796
+ info: logInfo,
797
+ logs: debugLogs,
798
+ functionRunTime: functionRunTime()
799
+ });
800
+ },
801
+ functionLogging,
802
+ nextDebugRound: type => {
803
+ if (!debugMode) return;
804
+ currentRoundId = generateUniqueId(8);
805
+ if (type) currentType = type;
806
+ },
807
+ modifyDebugType: type => {
808
+ if (!debugMode) return;
809
+ currentType = type;
810
+ },
811
+ pushNewDebugImage,
812
+ setTimeDuration: setTimeDuration,
813
+ saveDebugImage
814
+ };
815
+ }
243
816
 
244
817
  exports.TIME_UNIT = void 0;
245
818
  (function (TIME_UNIT) {
@@ -344,24 +917,58 @@ function cropByRatio(width, height, ratio) {
344
917
  };
345
918
  }
346
919
 
347
- function startSpinner(text) {
920
+ function startSpinner(text, backgroundOpaque) {
921
+ const loadingLottie = Storage.getItem(exports.STORAGE_KEY.LOADING_LOTTIE);
348
922
  const body = document.querySelector('.authme-container');
923
+ if (loadingLottie) {
924
+ const loadingSDKOuter = document.createElement('div');
925
+ const loadingSDKContent = document.createElement('div');
926
+ const loadingSDKText = document.createElement('div');
927
+ loadingSDKOuter.classList.add('authme-loading-sdk-outer');
928
+ loadingSDKContent.classList.add('authme-loading-sdk-content');
929
+ loadingSDKOuter.appendChild(loadingSDKContent);
930
+ Lottie__default["default"].loadAnimation({
931
+ container: loadingSDKContent,
932
+ renderer: 'svg',
933
+ loop: true,
934
+ autoplay: true,
935
+ name: 'spinner-loading',
936
+ animationData: loadingLottie
937
+ });
938
+ body === null || body === void 0 ? void 0 : body.appendChild(loadingSDKOuter);
939
+ if (text) {
940
+ loadingSDKText.classList.add('authme-loading-sdk-text');
941
+ loadingSDKText.textContent = text;
942
+ loadingSDKContent.appendChild(loadingSDKText);
943
+ }
944
+ if (backgroundOpaque) {
945
+ loadingSDKOuter.classList.add('authme-loading-sdk-outer--opaque');
946
+ }
947
+ return;
948
+ }
349
949
  const spinnerOuter = document.createElement('div');
350
- spinnerOuter.className = 'loading-outer';
351
950
  const spinner = document.createElement('div');
352
- spinner.className = 'loading';
353
951
  const spinnerText = document.createElement('div');
354
952
  spinnerOuter.appendChild(spinner);
953
+ spinnerOuter.className = 'loading-outer';
954
+ spinner.className = 'loading';
355
955
  if (text) {
356
956
  spinnerText.className = 'loading-text';
357
957
  spinnerText.textContent = text;
358
958
  spinnerOuter.appendChild(spinnerText);
359
959
  }
960
+ if (backgroundOpaque) {
961
+ spinnerOuter.classList.add('loading-outer--opaque');
962
+ }
360
963
  body === null || body === void 0 ? void 0 : body.appendChild(spinnerOuter);
361
964
  }
362
965
  function stopSpinner() {
966
+ const loadingLottie = Storage.getItem(exports.STORAGE_KEY.LOADING_LOTTIE);
363
967
  const body = document.querySelector('.authme-container');
364
- const spinner = document.querySelector('.loading-outer');
968
+ if (loadingLottie) {
969
+ Lottie__default["default"].destroy('spinner-loading');
970
+ }
971
+ const spinner = loadingLottie ? document.querySelector('.authme-loading-sdk-outer') : document.querySelector('.loading-outer');
365
972
  if (spinner) {
366
973
  body === null || body === void 0 ? void 0 : body.removeChild(spinner);
367
974
  }
@@ -373,7 +980,7 @@ exports.Icon = void 0;
373
980
  Icon["PictureIcon"] = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAYAAACOEfKtAAA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zLSdbKKmfE/sVyt3hWRMyOTP9IY8TDNpjNp948aNR+JvoLxNLoVyVxkfXuoRAMsquJ5pO9WJMV/+BXhVoOu5bLX0iP2QkL5z586WDRs2pD2vGoiDKSbMkkTVAQ6POW3VC/7PxX5C8GlLbwYKriOgSuyiSoyqanQYdH2315b2sBn9EQCRe/fubS8pKalPtSLjEQehCnjbMl90yT+N984mErIoIalDJ9SUCJmd31WVnPnRrFc9VAdMu6qqaqfZbN6SzKETHo9nlDqHPlijVCIOAIE/xK6Kh04sU3kRJH/sSfgIAPmi0rEn7/S6uz+UmS7HIhIAWa+Q3Lh69WpQpgkywJSOPQHC6NL7KN0ZHIENINifUSMNEEt1YYdB6JjXm9zxeWk/eAfUCCViUOWkZNbpABDX/NppW+MN2mD+rnDJyjl4J4JwBrvk7cIa1KH0OxA5r9MOJqLI5SIB4sJBMsR5K+roJxZhk5bouBjr8DFJM/TKpL87XGwcSpZM2DGETa8yT7Axahmeh506ixPJmqyItJ0fGPbSGr5cVgmgTI+kGXXpNSPvDNpRSKt1aZHK8XfIBOkWpkCo3OwL1ZiD8pb4x9+Fx7rzKGjsTpXqWKT3AEaouQui44kQmXqkl7gIMnaGKpTP/lRC1oTSi4Hwfg7dkkgncRFkjMAIwqoMoabUkUnCiQCZJI1FxgkUAXNrJMnboMBnsYyAxpNQKaB0DHIY5Ck1zbFwEpRMBlDAZM80aXnkkUceeSzif3+l5taU5LriAAAAAElFTkSuQmCC";
374
981
  })(exports.Icon || (exports.Icon = {}));
375
982
 
376
- function showErrorMessage(text, showRetryBtn, callback) {
983
+ function showErrorMessage(text, showRetryBtn, callback, buttonText, _titleText) {
377
984
  return __awaiter(this, void 0, void 0, function* () {
378
985
  const target = document.querySelector('.authme-container');
379
986
  if (!target) {
@@ -392,7 +999,40 @@ function showErrorMessage(text, showRetryBtn, callback) {
392
999
  if (showRetryBtn) {
393
1000
  const retryText = document.createElement('div');
394
1001
  retryText.className = 'retry-text';
395
- retryText.textContent = '重試';
1002
+ retryText.textContent = buttonText !== null && buttonText !== void 0 ? buttonText : '重試';
1003
+ errorMessagePanel.appendChild(retryText);
1004
+ if (callback) {
1005
+ retryText.addEventListener('click', e => {
1006
+ callback(e, {
1007
+ hideErrorMessage
1008
+ });
1009
+ });
1010
+ }
1011
+ }
1012
+ target === null || target === void 0 ? void 0 : target.appendChild(errorMessagePanel);
1013
+ });
1014
+ }
1015
+ function showErrorMessageEventName(text, showRetryBtn, callback, buttonText, titleText) {
1016
+ return __awaiter(this, void 0, void 0, function* () {
1017
+ const target = document.querySelector('.authme-container');
1018
+ if (!target) {
1019
+ return;
1020
+ }
1021
+ const errorMessagePanel = document.createElement('div');
1022
+ errorMessagePanel.classList.add('error-message-panel');
1023
+ errorMessagePanel.classList.add('event-name');
1024
+ const errorText = document.createElement('div');
1025
+ errorText.className = 'error-text';
1026
+ errorText.textContent = text;
1027
+ const title = document.createElement('div');
1028
+ title.className = 'error-title';
1029
+ title.textContent = titleText !== null && titleText !== void 0 ? titleText : 'error';
1030
+ errorMessagePanel.appendChild(title);
1031
+ errorMessagePanel.appendChild(errorText);
1032
+ if (showRetryBtn) {
1033
+ const retryText = document.createElement('div');
1034
+ retryText.className = 'retry-text';
1035
+ retryText.textContent = buttonText !== null && buttonText !== void 0 ? buttonText : '重試';
396
1036
  errorMessagePanel.appendChild(retryText);
397
1037
  if (callback) {
398
1038
  retryText.addEventListener('click', e => {
@@ -411,27 +1051,29 @@ function hideErrorMessage() {
411
1051
  body === null || body === void 0 ? void 0 : body.removeChild(errorMessagePanel);
412
1052
  }
413
1053
  }
414
- function asyncShowErrorMessage(text, showRetryBtn) {
1054
+ function asyncShowErrorMessage(text, showRetryBtn, options) {
1055
+ var _a;
415
1056
  return __awaiter(this, void 0, void 0, function* () {
1057
+ const _showErrorMessage = (_a = options === null || options === void 0 ? void 0 : options.showErrorMessageHandler) !== null && _a !== void 0 ? _a : showErrorMessage;
416
1058
  return new Promise((res, rej) => {
1059
+ var _a;
417
1060
  const callback = () => {
418
1061
  res(true);
419
1062
  hideErrorMessage();
420
1063
  };
421
- showErrorMessage(text, showRetryBtn, callback);
1064
+ _showErrorMessage(text, showRetryBtn, (_a = options === null || options === void 0 ? void 0 : options.callback) !== null && _a !== void 0 ? _a : callback, options === null || options === void 0 ? void 0 : options.buttonText, options === null || options === void 0 ? void 0 : options.titleText);
422
1065
  });
423
1066
  });
424
1067
  }
425
1068
  function asyncOnLineShowErrorMessage(text, showRetryBtn) {
426
1069
  return __awaiter(this, void 0, void 0, function* () {
427
1070
  return new Promise((res, rej) => {
428
- const callback = () => {
1071
+ showErrorMessage(text, showRetryBtn, (_, tools) => {
429
1072
  if (window.navigator.onLine) {
430
1073
  res(true);
431
- hideErrorMessage();
1074
+ tools === null || tools === void 0 ? void 0 : tools.hideErrorMessage();
432
1075
  }
433
- };
434
- showErrorMessage(text, showRetryBtn, callback);
1076
+ });
435
1077
  });
436
1078
  });
437
1079
  }
@@ -499,7 +1141,10 @@ var BROWSER_CAMERA_ERRORS;
499
1141
  BROWSER_CAMERA_ERRORS["NO_CAMERA"] = "NO_CAMERA";
500
1142
  BROWSER_CAMERA_ERRORS["NOT_ALLOWED_ERROR"] = "NotAllowedError";
501
1143
  BROWSER_CAMERA_ERRORS["NOT_FOUND_ERROR"] = "NotFoundError";
1144
+ BROWSER_CAMERA_ERRORS["NOT_READABLE_ERROR"] = "NotReadableError";
1145
+ BROWSER_CAMERA_ERRORS["ABORT_ERROR"] = "AbortError";
502
1146
  })(BROWSER_CAMERA_ERRORS || (BROWSER_CAMERA_ERRORS = {}));
1147
+ let stream;
503
1148
  const videoConstraintsFactory = (isPC, facingMode) => {
504
1149
  return isPC ? {
505
1150
  video: {
@@ -580,6 +1225,43 @@ function arrayFromAsync(asyncIterable) {
580
1225
  return result;
581
1226
  });
582
1227
  }
1228
+ function switchCamera(deviceId, video) {
1229
+ return __awaiter(this, void 0, void 0, function* () {
1230
+ try {
1231
+ if (stream) {
1232
+ stream.getTracks().forEach(track => track.stop());
1233
+ }
1234
+ const constraints = {
1235
+ video: {
1236
+ // 推測依然需要使用 width & height 的限制條件,
1237
+ // 否則即使是高解析度相機,也有可能拿到低解析度的圖片。(待驗證)
1238
+ width: {
1239
+ min: 1280,
1240
+ ideal: 1920,
1241
+ max: 1920
1242
+ },
1243
+ height: {
1244
+ min: 720,
1245
+ ideal: 1080,
1246
+ max: 1080
1247
+ },
1248
+ focusMode: 'auto',
1249
+ deviceId: deviceId
1250
+ }
1251
+ };
1252
+ stream = yield navigator.mediaDevices.getUserMedia(constraints);
1253
+ video.srcObject = stream;
1254
+ yield video.play();
1255
+ // Note: Fix Safari 15 video not showing bug
1256
+ video.srcObject = null;
1257
+ setTimeout(() => {
1258
+ video.srcObject = stream;
1259
+ }, 10);
1260
+ } catch (e) {
1261
+ throw new AuthmeError(exports.ErrorCode.CAMERA_NOT_SUPPORT, e);
1262
+ }
1263
+ });
1264
+ }
583
1265
  function _requestCamera(video, facingMode) {
584
1266
  var _a;
585
1267
  return __awaiter(this, void 0, void 0, function* () {
@@ -654,39 +1336,14 @@ function _requestCamera(video, facingMode) {
654
1336
  if (!deviceId) {
655
1337
  throw BROWSER_CAMERA_ERRORS.NO_CAMERA;
656
1338
  }
657
- const constraints = {
658
- video: {
659
- // 推測依然需要使用 width & height 的限制條件,
660
- // 否則即使是高解析度相機,也有可能拿到低解析度的圖片。(待驗證)
661
- width: {
662
- min: 1280,
663
- ideal: 1920,
664
- max: 1920
665
- },
666
- height: {
667
- min: 720,
668
- ideal: 1080,
669
- max: 1080
670
- },
671
- focusMode: 'auto',
672
- deviceId: {
673
- exact: deviceId
674
- }
675
- }
1339
+ if (stream) {
1340
+ stream.getTracks().forEach(track => track.stop());
1341
+ }
1342
+ yield switchCamera(deviceId, video);
1343
+ return {
1344
+ facingMode: firstDevice.meta.facingMode,
1345
+ deviceMetas: deviceMetas
676
1346
  };
677
- debugLog('camera info', {
678
- firstDevice,
679
- deviceMetas
680
- });
681
- const stream = yield navigator.mediaDevices.getUserMedia(constraints);
682
- video.srcObject = stream;
683
- yield video.play();
684
- // Note: Fix Safari 15 video not showing bug
685
- video.srcObject = null;
686
- setTimeout(() => {
687
- video.srcObject = stream;
688
- }, 10);
689
- return firstDevice.meta.facingMode;
690
1347
  });
691
1348
  }
692
1349
  function isOverconstrainedError(error) {
@@ -720,6 +1377,15 @@ function requestCamera({
720
1377
  showMessage(translate('camera.error.notFound'));
721
1378
  throw new AuthmeError(exports.ErrorCode.CAMERA_NOT_SUPPORT, error);
722
1379
  }
1380
+ if ((error === null || error === void 0 ? void 0 : error.name) === BROWSER_CAMERA_ERRORS.NOT_READABLE_ERROR || (error === null || error === void 0 ? void 0 : error.name) === BROWSER_CAMERA_ERRORS.ABORT_ERROR) {
1381
+ showMessage(translate('camera.error.notFound'));
1382
+ /* NOT_READABLE_ERROR,ABORT_ERROR 這兩個錯誤是用戶授權了,但在呼叫裝置時出現錯誤,
1383
+ * 常發生在APP webview ,例如: 手機開啟 web 使用 sdk,儘管在 webview 層級上授權了,但手機在設定層級沒有授權 app 使用相機,會導致此問題。
1384
+ * 但每個 android 手機的在這方面的實作不一致,不是每個手機在這種情況下都會拋出錯誤。
1385
+ * 參考 https://developer.mozilla.org/zh-CN/docs/Web/API/MediaDevices/getUserMedia#notreadableerror
1386
+ */
1387
+ throw new AuthmeError(exports.ErrorCode.CAMERA_NOT_SUPPORT, error);
1388
+ }
723
1389
  if (isOverconstrainedError(error)) {
724
1390
  showMessage(translate('camera.error.lowResolution'));
725
1391
  throw new AuthmeError(exports.ErrorCode.CAMERA_NOT_SUPPORT, error);
@@ -1654,25 +2320,27 @@ const sdk_loading = () => ({
1654
2320
  });
1655
2321
 
1656
2322
  function startLoadingSDK(text) {
2323
+ const loadingLottie = Storage.getItem(exports.STORAGE_KEY.LOADING_LOTTIE);
1657
2324
  const body = document.body;
1658
2325
  const loadingSDKOuter = document.createElement('div');
1659
2326
  const loadingSDKContent = document.createElement('div');
1660
2327
  loadingSDKOuter.classList.add('authme-loading-sdk-outer');
1661
2328
  loadingSDKContent.classList.add('authme-loading-sdk-content');
1662
2329
  loadingSDKOuter.appendChild(loadingSDKContent);
1663
- lottie__default["default"].loadAnimation({
2330
+ Lottie__default["default"].loadAnimation({
1664
2331
  container: loadingSDKContent,
1665
2332
  renderer: 'svg',
1666
2333
  loop: true,
1667
2334
  autoplay: true,
1668
- name: 'tutorial',
1669
- animationData: sdk_loading()
2335
+ name: 'init-sdk-loading',
2336
+ animationData: loadingLottie ? loadingLottie : sdk_loading()
1670
2337
  });
1671
2338
  body === null || body === void 0 ? void 0 : body.appendChild(loadingSDKOuter);
1672
2339
  }
1673
2340
  function stopLoadingSDK() {
1674
2341
  const body = document.body;
1675
2342
  const loadingSDKOuter = document.querySelector('.authme-loading-sdk-outer');
2343
+ Lottie__default["default"].destroy('init-sdk-loading');
1676
2344
  if (loadingSDKOuter) {
1677
2345
  body === null || body === void 0 ? void 0 : body.removeChild(loadingSDKOuter);
1678
2346
  }
@@ -1713,15 +2381,46 @@ function RGBToLottieColor(color) {
1713
2381
  return color.map(c => c / 255);
1714
2382
  }
1715
2383
 
2384
+ const QUEUE_LENGTH = 10;
2385
+ const requstQueue = [];
2386
+ function pushRequest(request) {
2387
+ if (requstQueue.length > QUEUE_LENGTH - 1) {
2388
+ requstQueue.shift();
2389
+ }
2390
+ requstQueue.push(request);
2391
+ }
2392
+ function clearRequest() {
2393
+ requstQueue.splice(0, requstQueue.length);
2394
+ }
2395
+ function backgroundRequest(request) {
2396
+ const requestPromise = request();
2397
+ requestPromise.catch(err => {
2398
+ if (err._code === exports.ErrorCode.NETWORK_ERROR) {
2399
+ pushRequest(request);
2400
+ }
2401
+ });
2402
+ }
2403
+ window.ononline = () => {
2404
+ const tasks = [...requstQueue];
2405
+ clearRequest();
2406
+ tasks.forEach(request => {
2407
+ backgroundRequest(request);
2408
+ });
2409
+ };
2410
+
1716
2411
  var name = "@authme/util";
1717
- var version$1 = "2.3.1-rc.3";
2412
+ var version$1 = "2.4.6";
1718
2413
  var peerDependencies = {
1719
2414
  "core-js": "^3.6.0"
1720
2415
  };
2416
+ var devDependencies = {
2417
+ "@types/file-saver": "^2.0.5"
2418
+ };
1721
2419
  var packageInfo = {
1722
2420
  name: name,
1723
2421
  version: version$1,
1724
- peerDependencies: peerDependencies
2422
+ peerDependencies: peerDependencies,
2423
+ devDependencies: devDependencies
1725
2424
  };
1726
2425
 
1727
2426
  var _a;
@@ -1737,21 +2436,28 @@ exports.UintArrayToBlob = UintArrayToBlob;
1737
2436
  exports.asyncOnLineShowErrorMessage = asyncOnLineShowErrorMessage;
1738
2437
  exports.asyncShowErrorMessage = asyncShowErrorMessage;
1739
2438
  exports.asyncShowPopup = asyncShowPopup;
2439
+ exports.backgroundRequest = backgroundRequest;
1740
2440
  exports.checkOnlineStatus = checkOnlineStatus;
1741
2441
  exports.clearCanvas = clearCanvas;
1742
2442
  exports.colorStringToRGB = colorStringToRGB;
1743
2443
  exports.colorToRGB = colorToRGB;
2444
+ exports.combineResult = combineResult;
1744
2445
  exports.cropByRatio = cropByRatio;
1745
2446
  exports.dataURItoBlob = dataURItoBlob;
1746
2447
  exports.debugLog = debugLog;
2448
+ exports.debugTools = debugTools;
2449
+ exports.decodeToken = decodeToken;
1747
2450
  exports.getCanvasSize = getCanvasSize;
1748
2451
  exports.getCssVariable = getCssVariable;
2452
+ exports.getDeviceInfo = getDeviceInfo;
1749
2453
  exports.getImageData = getImageData;
2454
+ exports.getSystemInfo = getSystemInfo;
1750
2455
  exports.getUserAgent = getUserAgent;
1751
2456
  exports.hexToRGB = hexToRGB;
1752
2457
  exports.hideElement = hideElement;
1753
2458
  exports.hideErrorMessage = hideErrorMessage;
1754
2459
  exports.hidePopup = hidePopup;
2460
+ exports.isIphone14proOrProMax = isIphone14proOrProMax;
1755
2461
  exports.isMobile = isMobile;
1756
2462
  exports.isMobileOrTablet = isMobileOrTablet;
1757
2463
  exports.requestCamera = requestCamera;
@@ -1759,11 +2465,15 @@ exports.resize = resize;
1759
2465
  exports.retryPromiseWithCondition = retryPromiseWithCondition;
1760
2466
  exports.showElement = showElement;
1761
2467
  exports.showErrorMessage = showErrorMessage;
2468
+ exports.showErrorMessageEventName = showErrorMessageEventName;
1762
2469
  exports.showPopup = showPopup;
2470
+ exports.splitResult = splitResult;
1763
2471
  exports.startLoadingSDK = startLoadingSDK;
1764
2472
  exports.startSpinner = startSpinner;
1765
2473
  exports.stopLoadingSDK = stopLoadingSDK;
1766
2474
  exports.stopSpinner = stopSpinner;
2475
+ exports.switchCamera = switchCamera;
2476
+ exports.useState = useState;
1767
2477
  exports.version = version;
1768
2478
  exports.videoConstraintsFactory = videoConstraintsFactory;
1769
2479
  exports.waitTime = waitTime;