@idscan/onboarding
Version:
Wrapper of the IDVC library for DIVE Online.
1,459 lines (1,458 loc) • 195 kB
JavaScript
import './Wrapper.css';var global = void 0;
function getDefaultExportFromCjs(x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
}
var runtime = { exports: {} };
var hasRequiredRuntime;
function requireRuntime() {
if (hasRequiredRuntime) return runtime.exports;
hasRequiredRuntime = 1;
(function(module) {
var runtime2 = (function(exports$1) {
var Op = Object.prototype;
var hasOwn = Op.hasOwnProperty;
var defineProperty = Object.defineProperty || function(obj, key, desc) {
obj[key] = desc.value;
};
var undefined$1;
var $Symbol = typeof Symbol === "function" ? Symbol : {};
var iteratorSymbol = $Symbol.iterator || "@@iterator";
var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
function define(obj, key, value) {
Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
return obj[key];
}
try {
define({}, "");
} catch (err) {
define = function(obj, key, value) {
return obj[key] = value;
};
}
function wrap(innerFn, outerFn, self, tryLocsList) {
var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
var generator = Object.create(protoGenerator.prototype);
var context = new Context(tryLocsList || []);
defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) });
return generator;
}
exports$1.wrap = wrap;
function tryCatch(fn, obj, arg) {
try {
return { type: "normal", arg: fn.call(obj, arg) };
} catch (err) {
return { type: "throw", arg: err };
}
}
var GenStateSuspendedStart = "suspendedStart";
var GenStateSuspendedYield = "suspendedYield";
var GenStateExecuting = "executing";
var GenStateCompleted = "completed";
var ContinueSentinel = {};
function Generator() {
}
function GeneratorFunction() {
}
function GeneratorFunctionPrototype() {
}
var IteratorPrototype = {};
define(IteratorPrototype, iteratorSymbol, function() {
return this;
});
var getProto = Object.getPrototypeOf;
var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
IteratorPrototype = NativeIteratorPrototype;
}
var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
GeneratorFunction.prototype = GeneratorFunctionPrototype;
defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: true });
defineProperty(
GeneratorFunctionPrototype,
"constructor",
{ value: GeneratorFunction, configurable: true }
);
GeneratorFunction.displayName = define(
GeneratorFunctionPrototype,
toStringTagSymbol,
"GeneratorFunction"
);
function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function(method) {
define(prototype, method, function(arg) {
return this._invoke(method, arg);
});
});
}
exports$1.isGeneratorFunction = function(genFun) {
var ctor = typeof genFun === "function" && genFun.constructor;
return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can
// do is to check its .name property.
(ctor.displayName || ctor.name) === "GeneratorFunction" : false;
};
exports$1.mark = function(genFun) {
if (Object.setPrototypeOf) {
Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
} else {
genFun.__proto__ = GeneratorFunctionPrototype;
define(genFun, toStringTagSymbol, "GeneratorFunction");
}
genFun.prototype = Object.create(Gp);
return genFun;
};
exports$1.awrap = function(arg) {
return { __await: arg };
};
function AsyncIterator(generator, PromiseImpl) {
function invoke(method, arg, resolve, reject) {
var record = tryCatch(generator[method], generator, arg);
if (record.type === "throw") {
reject(record.arg);
} else {
var result = record.arg;
var value = result.value;
if (value && typeof value === "object" && hasOwn.call(value, "__await")) {
return PromiseImpl.resolve(value.__await).then(function(value2) {
invoke("next", value2, resolve, reject);
}, function(err) {
invoke("throw", err, resolve, reject);
});
}
return PromiseImpl.resolve(value).then(function(unwrapped) {
result.value = unwrapped;
resolve(result);
}, function(error) {
return invoke("throw", error, resolve, reject);
});
}
}
var previousPromise;
function enqueue(method, arg) {
function callInvokeWithMethodAndArg() {
return new PromiseImpl(function(resolve, reject) {
invoke(method, arg, resolve, reject);
});
}
return previousPromise = // If enqueue has been called before, then we want to wait until
// all previous Promises have been resolved before calling invoke,
// so that results are always delivered in the correct order. If
// enqueue has not been called before, then it is important to
// call invoke immediately, without waiting on a callback to fire,
// so that the async generator function has the opportunity to do
// any necessary setup in a predictable way. This predictability
// is why the Promise constructor synchronously invokes its
// executor callback, and why async functions synchronously
// execute code before the first await. Since we implement simple
// async functions in terms of async generators, it is especially
// important to get this right, even though it requires care.
previousPromise ? previousPromise.then(
callInvokeWithMethodAndArg,
// Avoid propagating failures to Promises returned by later
// invocations of the iterator.
callInvokeWithMethodAndArg
) : callInvokeWithMethodAndArg();
}
defineProperty(this, "_invoke", { value: enqueue });
}
defineIteratorMethods(AsyncIterator.prototype);
define(AsyncIterator.prototype, asyncIteratorSymbol, function() {
return this;
});
exports$1.AsyncIterator = AsyncIterator;
exports$1.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
if (PromiseImpl === void 0) PromiseImpl = Promise;
var iter = new AsyncIterator(
wrap(innerFn, outerFn, self, tryLocsList),
PromiseImpl
);
return exports$1.isGeneratorFunction(outerFn) ? iter : iter.next().then(function(result) {
return result.done ? result.value : iter.next();
});
};
function makeInvokeMethod(innerFn, self, context) {
var state = GenStateSuspendedStart;
return function invoke(method, arg) {
if (state === GenStateExecuting) {
throw new Error("Generator is already running");
}
if (state === GenStateCompleted) {
if (method === "throw") {
throw arg;
}
return doneResult();
}
context.method = method;
context.arg = arg;
while (true) {
var delegate = context.delegate;
if (delegate) {
var delegateResult = maybeInvokeDelegate(delegate, context);
if (delegateResult) {
if (delegateResult === ContinueSentinel) continue;
return delegateResult;
}
}
if (context.method === "next") {
context.sent = context._sent = context.arg;
} else if (context.method === "throw") {
if (state === GenStateSuspendedStart) {
state = GenStateCompleted;
throw context.arg;
}
context.dispatchException(context.arg);
} else if (context.method === "return") {
context.abrupt("return", context.arg);
}
state = GenStateExecuting;
var record = tryCatch(innerFn, self, context);
if (record.type === "normal") {
state = context.done ? GenStateCompleted : GenStateSuspendedYield;
if (record.arg === ContinueSentinel) {
continue;
}
return {
value: record.arg,
done: context.done
};
} else if (record.type === "throw") {
state = GenStateCompleted;
context.method = "throw";
context.arg = record.arg;
}
}
};
}
function maybeInvokeDelegate(delegate, context) {
var methodName = context.method;
var method = delegate.iterator[methodName];
if (method === undefined$1) {
context.delegate = null;
if (methodName === "throw" && delegate.iterator["return"]) {
context.method = "return";
context.arg = undefined$1;
maybeInvokeDelegate(delegate, context);
if (context.method === "throw") {
return ContinueSentinel;
}
}
if (methodName !== "return") {
context.method = "throw";
context.arg = new TypeError(
"The iterator does not provide a '" + methodName + "' method"
);
}
return ContinueSentinel;
}
var record = tryCatch(method, delegate.iterator, context.arg);
if (record.type === "throw") {
context.method = "throw";
context.arg = record.arg;
context.delegate = null;
return ContinueSentinel;
}
var info = record.arg;
if (!info) {
context.method = "throw";
context.arg = new TypeError("iterator result is not an object");
context.delegate = null;
return ContinueSentinel;
}
if (info.done) {
context[delegate.resultName] = info.value;
context.next = delegate.nextLoc;
if (context.method !== "return") {
context.method = "next";
context.arg = undefined$1;
}
} else {
return info;
}
context.delegate = null;
return ContinueSentinel;
}
defineIteratorMethods(Gp);
define(Gp, toStringTagSymbol, "Generator");
define(Gp, iteratorSymbol, function() {
return this;
});
define(Gp, "toString", function() {
return "[object Generator]";
});
function pushTryEntry(locs) {
var entry = { tryLoc: locs[0] };
if (1 in locs) {
entry.catchLoc = locs[1];
}
if (2 in locs) {
entry.finallyLoc = locs[2];
entry.afterLoc = locs[3];
}
this.tryEntries.push(entry);
}
function resetTryEntry(entry) {
var record = entry.completion || {};
record.type = "normal";
delete record.arg;
entry.completion = record;
}
function Context(tryLocsList) {
this.tryEntries = [{ tryLoc: "root" }];
tryLocsList.forEach(pushTryEntry, this);
this.reset(true);
}
exports$1.keys = function(val) {
var object = Object(val);
var keys = [];
for (var key in object) {
keys.push(key);
}
keys.reverse();
return function next() {
while (keys.length) {
var key2 = keys.pop();
if (key2 in object) {
next.value = key2;
next.done = false;
return next;
}
}
next.done = true;
return next;
};
};
function values(iterable) {
if (iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) {
return iteratorMethod.call(iterable);
}
if (typeof iterable.next === "function") {
return iterable;
}
if (!isNaN(iterable.length)) {
var i = -1, next = function next2() {
while (++i < iterable.length) {
if (hasOwn.call(iterable, i)) {
next2.value = iterable[i];
next2.done = false;
return next2;
}
}
next2.value = undefined$1;
next2.done = true;
return next2;
};
return next.next = next;
}
}
return { next: doneResult };
}
exports$1.values = values;
function doneResult() {
return { value: undefined$1, done: true };
}
Context.prototype = {
constructor: Context,
reset: function(skipTempReset) {
this.prev = 0;
this.next = 0;
this.sent = this._sent = undefined$1;
this.done = false;
this.delegate = null;
this.method = "next";
this.arg = undefined$1;
this.tryEntries.forEach(resetTryEntry);
if (!skipTempReset) {
for (var name in this) {
if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) {
this[name] = undefined$1;
}
}
}
},
stop: function() {
this.done = true;
var rootEntry = this.tryEntries[0];
var rootRecord = rootEntry.completion;
if (rootRecord.type === "throw") {
throw rootRecord.arg;
}
return this.rval;
},
dispatchException: function(exception) {
if (this.done) {
throw exception;
}
var context = this;
function handle(loc, caught) {
record.type = "throw";
record.arg = exception;
context.next = loc;
if (caught) {
context.method = "next";
context.arg = undefined$1;
}
return !!caught;
}
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
var record = entry.completion;
if (entry.tryLoc === "root") {
return handle("end");
}
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc");
var hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
} else if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else if (hasCatch) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
}
} else if (hasFinally) {
if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else {
throw new Error("try statement without catch or finally");
}
}
}
},
abrupt: function(type, arg) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
var finallyEntry = entry;
break;
}
}
if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) {
finallyEntry = null;
}
var record = finallyEntry ? finallyEntry.completion : {};
record.type = type;
record.arg = arg;
if (finallyEntry) {
this.method = "next";
this.next = finallyEntry.finallyLoc;
return ContinueSentinel;
}
return this.complete(record);
},
complete: function(record, afterLoc) {
if (record.type === "throw") {
throw record.arg;
}
if (record.type === "break" || record.type === "continue") {
this.next = record.arg;
} else if (record.type === "return") {
this.rval = this.arg = record.arg;
this.method = "return";
this.next = "end";
} else if (record.type === "normal" && afterLoc) {
this.next = afterLoc;
}
return ContinueSentinel;
},
finish: function(finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) {
this.complete(entry.completion, entry.afterLoc);
resetTryEntry(entry);
return ContinueSentinel;
}
}
},
"catch": function(tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if (record.type === "throw") {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
}
throw new Error("illegal catch attempt");
},
delegateYield: function(iterable, resultName, nextLoc) {
this.delegate = {
iterator: values(iterable),
resultName,
nextLoc
};
if (this.method === "next") {
this.arg = undefined$1;
}
return ContinueSentinel;
}
};
return exports$1;
})(
// If this script is executing as a CommonJS module, use module.exports
// as the regeneratorRuntime namespace. Otherwise create a new empty
// object. Either way, the resulting object will be used to initialize
// the regeneratorRuntime variable at the top of this file.
module.exports
);
try {
regeneratorRuntime = runtime2;
} catch (accidentalStrictMode) {
if (typeof globalThis === "object") {
globalThis.regeneratorRuntime = runtime2;
} else {
Function("r", "regeneratorRuntime = r")(runtime2);
}
}
})(runtime);
return runtime.exports;
}
requireRuntime();
const notEmptyString = (val) => !!val;
const isUUID = (str) => !!/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/.test(str);
const isPublicKey = (str) => str.toLowerCase().startsWith("pk_") && isUUID(str);
const isElExist = (str) => !!document.getElementById(str);
const isPackageVersionNumber = (input) => {
const regex2 = /^([1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
return regex2.test(input);
};
class WrapperError extends Error {
}
class ConfigError extends WrapperError {
constructor(name) {
super(name);
this.message = `Configuration parameter error: ${name}`;
this.name = "ConfigError";
this.header = "Configuration Error!";
this.content = name || "";
}
}
const defaultDocumentTypes = [
{
type: "DL",
steps: [
{
type: "front",
name: "Document Front",
mode: { uploader: true, video: true },
autocaptureDelay: 0,
enableDesktopNotification: false
},
{
type: "pdf",
name: "Document Back",
mode: { uploader: true, video: true },
autocaptureDelay: 0,
enableDesktopNotification: false,
enableFourCornerCapture: false
},
{
type: "face",
name: "Face",
mode: { uploader: true, video: true },
autocaptureDelay: 0,
enableDesktopNotification: false
}
]
},
{
type: "IC",
steps: [
{
type: "front",
name: "Document Front",
mode: { uploader: true, video: true },
autocaptureDelay: 0,
enableDesktopNotification: false
},
{
type: "pdf",
name: "Document Back",
mode: { uploader: true, video: true },
autocaptureDelay: 0,
enableDesktopNotification: false,
enableFourCornerCapture: true
},
{
type: "face",
name: "Face",
mode: { uploader: true, video: true },
autocaptureDelay: 0,
enableDesktopNotification: false
}
]
},
{
type: "Passport",
steps: [
// { type: 'front', name: 'Document Front', mode: { uploader: true, video: true } },
{
type: "mrz",
name: "Document Front",
mode: { uploader: true, video: true },
autocaptureDelay: 0,
enableDesktopNotification: false
},
{
type: "face",
name: "Face",
mode: { uploader: true, video: true },
autocaptureDelay: 0,
enableDesktopNotification: false
}
]
},
{
type: "PassportCard",
steps: [
{
type: "front",
name: "Document Front",
mode: { uploader: true, video: true },
autocaptureDelay: 0,
enableDesktopNotification: false
},
{
type: "mrz",
name: "Document Back",
mode: { uploader: true, video: true },
autocaptureDelay: 0,
enableDesktopNotification: false
},
{
type: "face",
name: "Face",
mode: { uploader: true, video: true },
autocaptureDelay: 0,
enableDesktopNotification: false
}
]
},
{
type: "GreenCard",
steps: [
{
type: "front",
name: "Document Front",
mode: { uploader: true, video: true },
autocaptureDelay: 0,
enableDesktopNotification: false
},
{
type: "mrz",
name: "Document Back",
mode: { uploader: true, video: true },
autocaptureDelay: 0,
enableDesktopNotification: false
},
{
type: "face",
name: "Face",
mode: { uploader: true, video: true },
autocaptureDelay: 0,
enableDesktopNotification: false
}
]
},
{
type: "EmploymentAuthorization",
steps: [
{ type: "front", name: "Document Front", mode: { uploader: true, video: true } },
{ type: "mrz", name: "Document Back", mode: { uploader: true, video: true } },
{ type: "face", name: "Face", mode: { uploader: true, video: true } }
]
}
];
const createGuid = () => crypto.randomUUID();
const getFilteredDocumentTypes = (documentTypes) => {
if (!documentTypes) {
return [];
}
return documentTypes.map((document2) => ({
...document2,
steps: document2.steps.filter((step) => step.mode ? Object.values(step.mode).some(Boolean) : true)
})).filter((document2) => document2.steps.length).map((document2) => ({
type: document2.type,
steps: document2.steps
}));
};
const prepareDocumentTypes = (settings) => {
let result;
const filteredDocuments = getFilteredDocumentTypes(settings.documentTypes);
const passportDocument2 = filteredDocuments.find((document2) => document2.type === "Passport");
if (passportDocument2) {
const mrzPassport = { type: "mrz", name: "Passport MRZ", mode: { uploader: true, video: true } };
const frontStepIndex = passportDocument2.steps.findIndex((step) => step.type === "front");
if (frontStepIndex !== -1) {
passportDocument2.steps.splice(frontStepIndex, 1, mrzPassport);
}
}
if (filteredDocuments.length === 0) {
result = defaultDocumentTypes;
} else {
result = filteredDocuments;
}
return result;
};
const getQueryParam = (param) => {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get(param);
};
const validateHOF = ({ name, value, validationFunctions }) => {
const res = validationFunctions.reduce((acc, validationFn) => acc && validationFn(value), true);
if (!res) {
throw new ConfigError(name);
}
};
const validateApplicantId = (applicantId) => {
const uuidValidationFunctions = [notEmptyString, isUUID];
const validateConfig = {
name: "applicantId",
value: applicantId,
validationFunctions: uuidValidationFunctions
};
validateHOF(validateConfig);
};
const validateWrapperConfig = ({
demoMode,
applicantId,
domainId,
domainApi,
publicKey,
el = "videoCapturingEl"
}) => {
const uuidValidationFunctions = [notEmptyString, isUUID];
const pkValidationFunctions = [notEmptyString, isPublicKey];
const elValidationFunctions = [notEmptyString, isElExist];
[
demoMode ? null : {
name: "applicantId",
value: applicantId,
validationFunctions: uuidValidationFunctions
},
{
name: "domainId",
value: domainId,
validationFunctions: uuidValidationFunctions
},
{
name: "publicKey",
value: publicKey,
validationFunctions: pkValidationFunctions
},
{
name: "el",
value: el,
validationFunctions: elValidationFunctions
},
{
name: "domainApi should not be empty",
value: domainApi,
validationFunctions: [notEmptyString]
}
].filter(Boolean).forEach((e) => validateHOF(e));
};
class Configs {
constructor(config) {
this.validate = () => {
validateWrapperConfig(this.wrapper);
};
this.wrapper = { ...config };
if (config.getApplicantIdFromURL) {
this.wrapper.applicantId = getQueryParam("requestId") || config.applicantId;
}
}
parseFromWeb(options) {
const settings = JSON.parse(options == null ? void 0 : options.jsonSettings);
if (this.isAuth || this.faceOnly) {
this.libConfig = this.faceAuthorizationConfig(settings);
} else {
settings.documentTypes = prepareDocumentTypes(settings);
this.libConfig = settings;
}
this.cssStyles = options == null ? void 0 : options.cssStyles;
this.cssVariables = options == null ? void 0 : options.cssVariables;
}
faceAuthorizationConfig(settings) {
settings.isShowDocumentTypeSelect = false;
settings.documentTypes = [
{
type: "DL",
steps: [
{ type: "face", name: "Face", mode: { uploader: true, video: true } }
]
}
];
return settings;
}
getFirstStepModeState() {
const firstStepMode = structuredClone(this.firstStepMode);
return () => firstStepMode;
}
get firstStepMode() {
var _a, _b, _c;
return (_c = (_b = (_a = this.libConfig) == null ? void 0 : _a.documentTypes[0]) == null ? void 0 : _b.steps[0]) == null ? void 0 : _c.mode;
}
set applicantId(applicantId) {
validateApplicantId(applicantId);
this.wrapper.applicantId = applicantId;
}
get applicantId() {
return this.wrapper.applicantId;
}
get domainId() {
return this.wrapper.domainId;
}
get publicKey() {
return this.wrapper.publicKey;
}
get domainApi() {
return this.wrapper.domainApi;
}
get onValidate() {
var _a, _b;
if ((_b = (_a = this.wrapper) == null ? void 0 : _a.callbacks) == null ? void 0 : _b.onValidate) {
return this.wrapper.callbacks.onValidate;
}
return () => {
};
}
get onError() {
var _a, _b;
if ((_b = (_a = this.wrapper) == null ? void 0 : _a.callbacks) == null ? void 0 : _b.onError) {
return this.wrapper.callbacks.onError;
}
return () => {
};
}
get onGetOptionsStart() {
var _a, _b;
if ((_b = (_a = this.wrapper) == null ? void 0 : _a.callbacks) == null ? void 0 : _b.onGetOptionsStart) {
return this.wrapper.callbacks.onGetOptionsStart;
}
return () => {
};
}
get onGetOptionsComplete() {
var _a, _b;
if ((_b = (_a = this.wrapper) == null ? void 0 : _a.callbacks) == null ? void 0 : _b.onGetOptionsComplete) {
return this.wrapper.callbacks.onGetOptionsComplete;
}
return () => {
};
}
set libConfig(config) {
var _a;
const prevLC = (_a = this.IDVCConfig) == null ? void 0 : _a.licenseKey;
if (this.wrapper.preferApiConfig) {
this.IDVCConfig = {
...this.IDVCConfig,
...config,
...this.wrapper.callbacks
};
} else {
this.IDVCConfig = {
...this.IDVCConfig,
...config,
...this.wrapper,
...this.wrapper.callbacks
};
}
if (prevLC) {
this.IDVCConfig.licenseKey = prevLC;
}
}
get libConfig() {
return this.IDVCConfig || {};
}
get cssStylesConfig() {
return this.cssStyles;
}
get cssVariablesConfig() {
return this.cssVariables;
}
get mountElement() {
return this.wrapper.el || "videoCapturingEl";
}
get demoMode() {
return this.wrapper.demoMode || false;
}
get isAuth() {
return this.wrapper.isAuth || false;
}
get faceOnly() {
return this.wrapper.faceOnly || false;
}
get qrCodeLinkOrigin() {
return this.wrapper.qrCodeLinkOrigin || "https://diveonline.idscan.net";
}
get IDVCDownloadVersion() {
if (isPackageVersionNumber(this.wrapper.IDVCDownloadVersion || "")) {
return this.wrapper.IDVCDownloadVersion;
}
return "latest";
}
}
class NotValidApplicant extends WrapperError {
constructor(name) {
super(name);
this.message = "This application is closed";
this.name = "NotValidApplicant";
this.header = "Request Closed";
this.content = "This application is closed";
}
}
class ValidationError extends WrapperError {
constructor(error) {
const name = error.code === "RequestValidationError" ? error.code : "ValidationError";
super(name);
this.message = error.message || "Try again later";
this.name = name;
this.setHeader(error);
this.content = error.message || "Try again later";
if (error == null ? void 0 : error.propertyErrors) {
const errorList = Object.values(error.propertyErrors).reduce((acc, errorText) => `${acc}<li class="idvc-modal__body__list__item">${errorText}</li>`, "");
this.content = `<ol class="idvc-modal__body__list">${errorList}</ol>`;
}
}
setHeader({ code = "" }) {
if (code && ["ApiError", "ValidationError", "MultipleErrors", "BadRequest"].includes(code)) {
this.header = "Something Went Wrong!";
} else {
this.header = "Data invalid";
}
}
}
class HttpError extends WrapperError {
constructor(response) {
super(response.status.toString());
const { status } = response;
let message;
switch (status) {
case 400:
message = "Bad Request";
break;
case 401:
message = "Unauthorized";
break;
case 403:
message = "Forbidden";
break;
case 404:
message = "Not Found";
break;
case 500:
message = "Server Error";
break;
default:
message = "Something Went Wrong!";
}
this.message = `Status code: ${status}. ${message}`;
this.name = "HttpError";
this.statusCode = status;
this.header = "Server Side Problems";
this.content = "Please try again later";
}
}
class RequestTimeoutError extends WrapperError {
constructor(name) {
super(name);
this.message = "This application is closed";
this.name = "RequestTimeoutError";
this.header = "Request Timeout";
this.content = "This application is closed";
}
}
const dlDocument = {
abbr3Country: "USA",
abbrCountry: "US",
address: "25805 VAN LEUVEN ST 136",
city: "LOMA LINDA",
class: "C",
country: "United States of America",
dob: "1961-01-07",
expires: "2024-01-07",
eyes: "Brown",
familyName: "GILMER",
firstName: "DARIENNE",
fullName: "DARIENNE ELIZABETH GILMER",
gender: "Female",
hair: "Black",
height: "064 IN",
id: "C3568758",
idType: "DL",
issued: "2019-01-07",
middleName: "ELIZABETH",
postalBox: null,
privateName: "ELIZABETH",
state: "CA",
template: "09",
weight: "77",
zip: "92354-0000"
};
const passportDocument = {
abbr3Country: "USA",
abbrCountry: "US",
address: null,
city: null,
class: null,
country: "United States of America",
dob: "1986-07-24",
expires: "2030-07-13",
eyes: null,
familyName: "LEVELS",
firstName: "DAVID HARRISON",
fullName: "LEVELS DAVID HARRISON",
gender: "M",
hair: null,
height: null,
id: "659328258",
idType: "PASSPORT",
issued: null,
middleName: null,
postalBox: null,
privateName: null,
state: null,
template: null,
weight: null,
zip: null
};
const base = {
validationResponseId: 0,
validationRequestId: "",
documentType: 0,
document: null,
attemptsLeft: 0,
attemptsCount: 0,
status: 0,
validationStatus: {
expired: false,
documentIsValid: false,
faceIsValid: false
},
invalidDataErrors: null,
faceSuccess: null,
documentSuccess: null,
documentHasNotExpired: null,
documentValidationTests: null,
callBackUrl: null,
notificationType: 0,
isCompleted: false
};
const createValidationResponse = (overrides = {}) => ({ ...base, ...overrides });
const success = createValidationResponse({
validationResponseId: 6223,
validationRequestId: "8151f48d-bab1-4491-037d-08d9b3c5cfec",
documentType: 1,
document: dlDocument,
validationStatus: { expired: false, documentIsValid: true, faceIsValid: true },
documentValidationTests: [
{ displayName: "DMV", name: "DMVValidation", status: 0, statusString: "Failed", reason: "Internal Server Error" },
{ displayName: "IdentiFraud", name: "IdentiFraudValidation", status: -1, statusString: "Disabled", reason: "Integration was turned off" }
]
});
createValidationResponse({
validationResponseId: 6224,
validationRequestId: "fa33df4c-7d5c-4485-037e-08d9b3c5cfec",
attemptsLeft: 19,
status: 2,
invalidDataErrors: [
{ code: "FaceDocNotDetectError", message: "The face has not been found on the document" },
{ code: "PDF417Error", message: "Unable to capture data from the back of the document" },
{ code: "OCRError", message: "Unable to capture data from the front of the document" }
]
});
createValidationResponse({
validationResponseId: 6230,
validationRequestId: "eae11ae1-1c8f-40bd-0381-08d9b3c5cfec",
documentType: 2,
document: passportDocument,
attemptsLeft: 18,
status: 1,
validationStatus: { expired: false, documentIsValid: true, faceIsValid: false }
});
createValidationResponse({
applicantId: "bb165b57-e8b1-412a-b848-2e4669da58e0",
attemptId: 71441,
documentType: 1,
attemptsCount: 5,
attemptsLeft: 5,
status: 2,
validationStatus: {
expired: null,
documentIsValid: null,
faceIsValid: true,
antiSpoofingIsValid: null
},
invalidDataErrors: [{ code: "QualityWarning", message: null }],
hasRiskEvents: true,
documentValidationTests: []
});
class FaceAuthorizationError extends WrapperError {
constructor(error) {
super("FaceAuthorizationError");
this.message = error.message || "Try again later";
this.name = "FaceAuthorizationError";
this.setHeader(error);
this.content = error.message || "Try again later";
if (error == null ? void 0 : error.propertyErrors) {
const errorList = Object.values(error.propertyErrors).reduce((acc, errorText) => `${acc}<li class="idvc-modal__body__list__item">${errorText}</li>`, "");
this.content = `<ol class="idvc-modal__body__list">${errorList}</ol>`;
}
}
setHeader({ code = "" }) {
if (code && ["ApiError", "ValidationError", "MultipleErrors", "BadRequest"].includes(code)) {
this.header = "Something Went Wrong!";
} else {
this.header = "Data invalid";
}
}
}
var ValidationStatus = /* @__PURE__ */ ((ValidationStatus2) => {
ValidationStatus2["DANGER"] = "danger";
ValidationStatus2["SUCCESS"] = "success";
ValidationStatus2["PRIMARY"] = "primary";
return ValidationStatus2;
})(ValidationStatus || {});
var ResponseStatus = /* @__PURE__ */ ((ResponseStatus2) => {
ResponseStatus2[ResponseStatus2["SUCCESS"] = 0] = "SUCCESS";
ResponseStatus2[ResponseStatus2["FAIL"] = 1] = "FAIL";
ResponseStatus2[ResponseStatus2["INVALID_DATA"] = 2] = "INVALID_DATA";
ResponseStatus2[ResponseStatus2["ERROR"] = 3] = "ERROR";
ResponseStatus2[ResponseStatus2["COMPLETE"] = 4] = "COMPLETE";
return ResponseStatus2;
})(ResponseStatus || {});
var QRCodeModalState = /* @__PURE__ */ ((QRCodeModalState2) => {
QRCodeModalState2["READY"] = "ready";
QRCodeModalState2["VALIDATING"] = "validating";
QRCodeModalState2["DONE_WITH_SUCCESS"] = "doneWithSuccess";
QRCodeModalState2["DONE_WITH_ERROR"] = "doneWithError";
return QRCodeModalState2;
})(QRCodeModalState || {});
var EmbeddedStatus = /* @__PURE__ */ ((EmbeddedStatus2) => {
EmbeddedStatus2[EmbeddedStatus2["NEVER_OPEN"] = 0] = "NEVER_OPEN";
EmbeddedStatus2[EmbeddedStatus2["OPEN"] = 1] = "OPEN";
EmbeddedStatus2[EmbeddedStatus2["CLOSED"] = 2] = "CLOSED";
EmbeddedStatus2[EmbeddedStatus2["CLOSED_FOREVER"] = 3] = "CLOSED_FOREVER";
return EmbeddedStatus2;
})(EmbeddedStatus || {});
var ClientType = /* @__PURE__ */ ((ClientType2) => {
ClientType2[ClientType2["WebLibStandalone"] = 0] = "WebLibStandalone";
ClientType2[ClientType2["WebLibDashboard"] = 1] = "WebLibDashboard";
ClientType2[ClientType2["Android"] = 2] = "Android";
ClientType2[ClientType2["Ios"] = 3] = "Ios";
return ClientType2;
})(ClientType || {});
var NotificationText = /* @__PURE__ */ ((NotificationText2) => {
NotificationText2[NotificationText2[""] = 0] = "";
NotificationText2[NotificationText2["sent via SMS"] = 1] = "sent via SMS";
NotificationText2[NotificationText2["sent via email"] = 2] = "sent via email";
NotificationText2[NotificationText2["sent via SMS or email"] = 3] = "sent via SMS or email";
return NotificationText2;
})(NotificationText || {});
var DocumentTypeIDs = /* @__PURE__ */ ((DocumentTypeIDs2) => {
DocumentTypeIDs2[DocumentTypeIDs2["DL"] = 1] = "DL";
DocumentTypeIDs2[DocumentTypeIDs2["Passport"] = 2] = "Passport";
DocumentTypeIDs2[DocumentTypeIDs2["PassportCard"] = 3] = "PassportCard";
DocumentTypeIDs2[DocumentTypeIDs2["GreenCard"] = 6] = "GreenCard";
DocumentTypeIDs2[DocumentTypeIDs2["InternationalId"] = 7] = "InternationalId";
DocumentTypeIDs2[DocumentTypeIDs2["Barcode"] = 11] = "Barcode";
DocumentTypeIDs2[DocumentTypeIDs2["FaceAuthorization"] = 10] = "FaceAuthorization";
DocumentTypeIDs2[DocumentTypeIDs2["EmploymentAuthorization"] = 9] = "EmploymentAuthorization";
return DocumentTypeIDs2;
})(DocumentTypeIDs || {});
var HttpStatus = /* @__PURE__ */ ((HttpStatus2) => {
HttpStatus2[HttpStatus2["OK"] = 200] = "OK";
HttpStatus2[HttpStatus2["Created"] = 201] = "Created";
HttpStatus2[HttpStatus2["Accepted"] = 202] = "Accepted";
HttpStatus2[HttpStatus2["NoContent"] = 204] = "NoContent";
HttpStatus2[HttpStatus2["BadRequest"] = 400] = "BadRequest";
HttpStatus2[HttpStatus2["Unauthorized"] = 401] = "Unauthorized";
HttpStatus2[HttpStatus2["PaymentRequired"] = 402] = "PaymentRequired";
HttpStatus2[HttpStatus2["Forbidden"] = 403] = "Forbidden";
HttpStatus2[HttpStatus2["NotFound"] = 404] = "NotFound";
HttpStatus2[HttpStatus2["MethodNotAllowed"] = 405] = "MethodNotAllowed";
HttpStatus2[HttpStatus2["Gone"] = 410] = "Gone";
HttpStatus2[HttpStatus2["RequestTimeout"] = 408] = "RequestTimeout";
HttpStatus2[HttpStatus2["Conflict"] = 409] = "Conflict";
HttpStatus2[HttpStatus2["PreconditionFailed"] = 412] = "PreconditionFailed";
HttpStatus2[HttpStatus2["LengthRequired"] = 411] = "LengthRequired";
HttpStatus2[HttpStatus2["PayloadTooLarge"] = 413] = "PayloadTooLarge";
HttpStatus2[HttpStatus2["RequestURITooLong"] = 414] = "RequestURITooLong";
HttpStatus2[HttpStatus2["UnsupportedMediaType"] = 415] = "UnsupportedMediaType";
HttpStatus2[HttpStatus2["RangeNotSatisfiable"] = 416] = "RangeNotSatisfiable";
HttpStatus2[HttpStatus2["ExpectationFailed"] = 417] = "ExpectationFailed";
HttpStatus2[HttpStatus2["Locked"] = 423] = "Locked";
HttpStatus2[HttpStatus2["MisdirectedRequest"] = 421] = "MisdirectedRequest";
HttpStatus2[HttpStatus2["NetworkAuthenticationRequired"] = 511] = "NetworkAuthenticationRequired";
HttpStatus2[HttpStatus2["InternalServerError"] = 500] = "InternalServerError";
HttpStatus2[HttpStatus2["NotImplemented"] = 501] = "NotImplemented";
HttpStatus2[HttpStatus2["BadGateway"] = 502] = "BadGateway";
HttpStatus2[HttpStatus2["ServiceUnavailable"] = 503] = "ServiceUnavailable";
HttpStatus2[HttpStatus2["GatewayTimeout"] = 504] = "GatewayTimeout";
HttpStatus2[HttpStatus2["HTTPVersionNotSupported"] = 505] = "HTTPVersionNotSupported";
HttpStatus2[HttpStatus2["VariantAlsoNegotiates"] = 506] = "VariantAlsoNegotiates";
HttpStatus2[HttpStatus2["InsufficientStorage"] = 507] = "InsufficientStorage";
HttpStatus2[HttpStatus2["NetworkConnectTimeoutError"] = 524] = "NetworkConnectTimeoutError";
return HttpStatus2;
})(HttpStatus || {});
class Api {
constructor(publicKey, domainApi = "https://api-dvsonline.idscan.net") {
this.idvcManifestUrl = "https://neurons.cdn.idscan.net/manifest.json";
this.HEADERS = {
"Content-Type": "application/json"
};
const baseUrl = `${domainApi}/api/v2/`;
this.baseUrl = `${baseUrl}public/`;
this.baseEmbeddedUrl = `${baseUrl}EmbeddedApp/`;
this.HEADERS.Authorization = `Bearer ${publicKey}`;
}
async checkApplicantIdIsNotClosed({
applicantId = "",
demoMode = false,
faceAuth = false,
faceOnly = false
}) {
if (demoMode) {
return true;
}
const url = `${this.baseUrl}Applicants/${applicantId}/Completed`;
const response = await fetch(url, {
method: "GET",
headers: this.HEADERS
});
if (response.ok && !faceAuth) {
throw new NotValidApplicant("request closed");
} else if (response.ok && faceAuth) {
return true;
} else if (HttpStatus.NotFound === response.status && faceAuth) {
throw new NotValidApplicant("validation not completed");
} else if (HttpStatus.NotFound === response.status && (!faceAuth || faceOnly)) {
return true;
}
if (HttpStatus.BadRequest === response.status) {
const responseData = await response.json();
throw new ValidationError(responseData);
} else {
throw new HttpError(response);
}
}
async getCurrentIdvcVersion() {
try {
const response = await fetch(this.idvcManifestUrl);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const jsonData = await response.json();
return jsonData.latestVersion;
} catch (error) {
console.error("Error fetching data:", error);
throw error;
}
}
async getOptions(integrationId) {
const url = `${this.baseUrl}Integrations/${integrationId}/Configuration`;
try {
const response = await fetch(url, {
method: "GET",
headers: this.HEADERS
});
if (response.ok) {
return await response.json();
}
throw new HttpError(response);
} catch (e) {
if (e instanceof HttpError) {
throw e;
} else {
throw new HttpError(e);
}
}
}
async validateApplicant(data, demoMode = false, isFaceAuth = false) {
if (demoMode) {
return success;
}
const url = `${this.baseUrl}Validation`;
const response = await fetch(url, {
method: "POST",
headers: this.HEADERS,
body: JSON.stringify(data)
});
if (response.ok) {
return response.json();
}
if (HttpStatus.BadRequest === response.status) {
const responseData = await response.json();
if (isFaceAuth) {
throw new FaceAuthorizationError(responseData);
}
throw new ValidationError(responseData);
} else if (HttpStatus.NotFound === response.status) {
const responseData = await response.json();
throw new FaceAuthorizationError(responseData);
} else {
throw new HttpError(response);
}
}
async forceClose(applicantId) {
const url = `${this.baseUrl}Applicants/${applicantId}/Complete`;
const response = await fetch(url, {
method: "POST",
headers: this.HEADERS
});
if (response.ok) {
return response.json();
}
if (HttpStatus.BadRequest === response.status) {
const responseData = await response.json();
throw new ValidationError(responseData);
} else {
throw new HttpError(response);
}
}
async closeEmbeddedApplication(applicantId, callback) {
let response;
try {
const embeddedUrl = `${this.baseEmbeddedUrl}Close/${applicantId}`;
response = await fetch(embeddedUrl, {
method: "POST",
headers: this.HEADERS
});
if (response.ok) {
callback();
} else {
throw new Error(`Request Error: ${response.status}`);
}
} catch (e) {
if (e instanceof HttpError) {
throw e;
} else {
throw new HttpError(response);
}
}
}
async longPollingRequest(url, init, callback) {
try {
const embeddedUrl = `${this.baseEmbeddedUrl}${url}`;
const response = await fetch(embeddedUrl, init);
if (HttpStatus.RequestTimeout === response.status || HttpStatus.NetworkConnectTimeoutError === response.status) {
throw new RequestTimeoutError("Request Timeout");
}
if (!response.ok) {
throw new Error(`Request Error: ${response.status}`);
}
const data = await response.json();
callback(data);
} catch (error) {
if (error instanceof RequestTimeoutError) {
await this.longPollingRequest(url, init, callback);
}
}
}
}
const isString = (val) => typeof val === "string";
const processingCheckMap = {
back: [DocumentTypeIDs.DL, DocumentTypeIDs.InternationalId],
mrz: [
DocumentTypeIDs.PassportCard,
DocumentTypeIDs.GreenCard,
DocumentTypeIDs.Passport,
DocumentTypeIDs.EmploymentAuthorization
],
pdf: [DocumentTypeIDs.DL, DocumentTypeIDs.InternationalId]
};
const checkBackOrSecondImageProcessing = (documentType, steps) => {
var _a;
const backStep = steps.find((step) => Object.keys(processingCheckMap).includes(step.type));
if (!backStep) {
return false;
}
const allowedDocumentTypeIDs = (_a = processingCheckMap[backStep.type]) == null ? void 0 : _a.some((id) => id === documentType);
return allowedDocumentTypeIDs ?? false;
};
const checkOcrEnabled = (documentType, steps) => {
const isPassportFront = steps.some((step) => step.type === "mrz");
if (documentType === DocumentTypeIDs.Passport && isPassportFront) {
return true;
}
const hasFrontStep = steps.find((step) => step.type === "front");
return !!hasFrontStep;
};
class Lib {
constructor() {
this.cleanBase64 = (base64EncodedImage) => {
if (!base64EncodedImage || !isString(base64EncodedImage)) return "";
const splitPattern = /:image\/\w+;base64,/;
const parts = base64EncodedImage.split(splitPattern);
if (parts.length > 0) {
return parts.at(-1) ?? "";
}
return "";
};
this.validationModel = (data) => {
var _a;
const isPassportDocument = data.documentType === DocumentTypeIDs.Passport;
const getBackData = () => {
const step = data.steps.find((item) => item.type === "pdf" || item.type === "mrz" || item.type === "back");
const trackString = (step == null ? void 0 : step.mrzText) || (step == null ? void 0 : step.trackString) || "";
if (isPassportDocument) {
return {
img: "",
trackString
};
}
return {
img: (step == null ? void 0 : step.img) || "",
trackString
};
};
const getFrontData = () => {
var _a2;
if (isPassportDocument) {
const frontPassportStep = data.steps.find((el) => el.type === "mrz");
if (frontPassportStep) {
return frontPassportStep.img;
}
}
return (_a2 = data.steps.find((el) => el.type === "front")) == null ? void 0 : _a2.img;
};
const back = getBackData();
return {
frontImageBase64: this.cleanBase64(getFrontData()),
backOrSecondImageBase64: this.cleanBase64(back == null ? void 0 : back.img),
faceImageBase64: this.cleanBase64((_a = data.steps.find((item) => item.type === "face")) == null ? void 0 : _a.img),
trackString: back.trackString,
ssn: "",
verifyFace: data.steps.some((item) => item.type === "face"),
documentType: data.documentType,
captureMethod: data.steps.reduce((acc, step) => `${acc}${Number(step.isAuto ?? false)}`, ""),
userAgent: window.navigator.userAgent,
frontEndMetadata: data.metaData,
isBackOrSecondImageProcessingEnabled: checkBackOrSecondImageProcessing(
data.documentType,
data.steps
),
isOcrEnabled: checkOcrEnabled(data.documentType, data.steps)
};
};
}
async initializeLibrary(loadIDVCFromCDN, idvcVersion, IDVCModule) {
if (!this.library) {
if (loadIDVCFromCDN) {
await this.loadFromCDN(idvcVersion);
} else if (IDVCModule) {