onfido-sdk-ui
Version:
JavaScript SDK view layer for Onfido identity verification
358 lines (357 loc) • 12.5 kB
JavaScript
var V = Object.defineProperty;
var R = (e, n, i) => n in e ? V(e, n, { enumerable: !0, configurable: !0, writable: !0, value: i }) : e[n] = i;
var y = (e, n, i) => (R(e, typeof n != "symbol" ? n + "" : n, i), i);
class B {
constructor() {
this.eventListener = {};
}
addEventListener(n, i) {
return this.eventListener[n] = this.eventListener[n] || [], this.eventListener[n].push(i), this;
}
removeEventListener(n, i) {
const r = this.eventListener[n];
if (r) {
let o;
for (; (o = r.indexOf(i)) !== -1; )
r.splice(o, 1);
}
}
trigger(n, i) {
(this.eventListener[n] || []).forEach((r) => {
r == null || r(i);
});
}
}
const a = [];
for (let e = 0; e < 256; ++e)
a.push((e + 256).toString(16).slice(1));
function O(e, n = 0) {
return (a[e[n + 0]] + a[e[n + 1]] + a[e[n + 2]] + a[e[n + 3]] + "-" + a[e[n + 4]] + a[e[n + 5]] + "-" + a[e[n + 6]] + a[e[n + 7]] + "-" + a[e[n + 8]] + a[e[n + 9]] + "-" + a[e[n + 10]] + a[e[n + 11]] + a[e[n + 12]] + a[e[n + 13]] + a[e[n + 14]] + a[e[n + 15]]).toLowerCase();
}
let k;
const W = new Uint8Array(16);
function M() {
if (!k) {
if (typeof crypto > "u" || !crypto.getRandomValues)
throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
k = crypto.getRandomValues.bind(crypto);
}
return k(W);
}
const P = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), I = { randomUUID: P };
function G(e, n, i) {
var o;
e = e || {};
const r = e.random ?? ((o = e.rng) == null ? void 0 : o.call(e)) ?? M();
if (r.length < 16)
throw new Error("Random bytes length must be >= 16");
if (r[6] = r[6] & 15 | 64, r[8] = r[8] & 63 | 128, n) {
if (i = i || 0, i < 0 || i + 16 > n.length)
throw new RangeError(`UUID byte range ${i}:${i + 15} is out of buffer bounds`);
for (let s = 0; s < 16; ++s)
n[i + s] = r[s];
return n;
}
return O(r);
}
function _(e, n, i) {
return I.randomUUID && !n && !e ? I.randomUUID() : G(e, n, i);
}
var t;
(function(e) {
e.MicrophonePermissionDenied = "MicrophonePermissionDenied", e.CameraPermissionDenied = "CameraPermissionDenied", e.PermissionsUnavailable = "PermissionsUnavailable", e.CameraNotDetected = "CameraNotDetected", e.CameraException = "CameraException", e.FailedToWriteToDisk = "FailedToWriteToDisk", e.InvalidImageData = "InvalidImageData", e.WorkflowTaskAbandoned = "WorkflowTaskAbandoned", e.WorkflowTaskError = "WorkflowTaskError", e.BiometricTokenRetrievalException = "BiometricTokenRetrievalException", e.WorkflowBiometricTokenStorageException = "WorkflowBiometricTokenStorageException", e.CrossDeviceRestartError = "CrossDeviceRestartError", e.CrossDeviceDesktopError = "CrossDeviceDesktopError", e.CrossDeviceVerificationInvalidError = "CrossDeviceVerificationInvalidError", e.CrossDeviceVerificationAbortError = "CrossDeviceVerificationAbortError", e.InvalidToken = "InvalidToken", e.ExpiredToken = "ExpiredToken", e.ExpiredTrial = "ExpiredTrial", e.NetworkException = "NetworkException", e.UploadError = "UploadError", e.InitialisationInvalid = "InitialisationInvalid", e.SdkVersionInsufficient = "SdkVersionInsufficient", e.UnsupportedError = "UnsupportedError", e.UnsupportedFeatureError = "UnsupportedFeatureError", e.InvalidSdkParameter = "InvalidSdkParameter", e.FeaturesNotAuthorized = "FeaturesNotAuthorized", e.MissingSteps = "MissingSteps", e.DuplicateStep = "DuplicateStep", e.WelcomeMustBeFirstStep = "WelcomeMustBeFirstStep", e.WorkflowVersionMismatch = "WorkflowVersionMismatch", e.WorkflowInputError = "WorkflowInputError", e.MissingLogoCobrandingParameter = "MissingLogoCobrandingParameter", e.InvalidCustomTranslations = "InvalidCustomTranslations", e.InvalidCountryCode = "InvalidCountryCode", e.InvalidDocumentFormatAndCountryCombination = "InvalidDocumentFormatAndCountryCombination", e.InvalidDocumentTypeException = "InvalidDocumentTypeException", e.InvalidDocumentTitle = "InvalidDocumentTitle", e.DuplicateGenericDocument = "DuplicateGenericDocument", e.NfcInputNotAvailable = "NfcInputNotAvailable", e.AppTerminated = "AppTerminated", e.GenericException = "GenericException", e.GeoBlocked = "GeoBlocked", e.ModuleLoadError = "ModuleLoadError";
})(t || (t = {}));
var D;
(function(e) {
e.UserExit = "UserExit", e.ConsentDenied = "ConsentDenied", e.RequiredNfcNotCompleted = "RequiredNfcNotCompleted";
})(D || (D = {}));
var b;
(function(e) {
e.AppInBackground = "AppInBackground", e.AppInactive = "AppInactive";
})(b || (b = {}));
var C;
(function(e) {
e.AppBackInForeground = "AppBackInForeground", e.AppBackToActive = "AppBackToActive";
})(C || (C = {}));
t.CrossDeviceRestartError;
t.CrossDeviceDesktopError;
t.CrossDeviceVerificationInvalidError;
t.CrossDeviceVerificationAbortError;
const T = {
type: "invalid_token",
message: "The token is invalid.",
level: "external"
/* EXTERNAL */
// does not exist in analytics types
};
t.WorkflowTaskAbandoned;
t.WorkflowInputError;
t.ExpiredToken;
t.ExpiredTrial;
t.GeoBlocked;
t.PermissionsUnavailable;
t.GenericException;
t.UnsupportedError;
t.UnsupportedFeatureError;
t.InitialisationInvalid;
t.SdkVersionInsufficient;
t.CameraNotDetected;
t.NetworkException;
t.ModuleLoadError;
class h extends Error {
constructor({
type: n,
message: i,
level: r,
exception: o,
stack: s,
body: l,
httpCode: d,
analyticsError: c
}) {
super(i), this.name = "SdkError", this.type = n, this.level = r, this.exception = o, this.body = l, this.httpCode = d, this.analyticsError = c, s && (this.stack = s);
}
encode() {
return {
name: this.name,
type: this.type,
message: this.message,
level: this.level,
stack: this.stack,
exception: this.exception,
body: this.body,
httpCode: this.httpCode,
analyticsError: this.analyticsError
};
}
static decode(n) {
return n.name === "SdkError" ? new h({
type: n.type,
message: n.message,
level: n.level,
exception: n.exception,
stack: n.stack,
body: n.body,
httpCode: n.httpCode,
analyticsError: n.analyticsError
}) : n;
}
}
const q = (e) => {
const { payload: n, urls: i } = e;
return {
sub: e.sub,
type: e.iss === "studio" ? "studio" : "sdk",
enterpriseFeatures: e.enterprise_features,
urls: {
authUrl: i.auth_url,
detectDocumentUrl: i.detect_document_url,
hostedSdkUrl: i.hosted_sdk_url,
syncUrl: i.sync_url,
onfidoApiUrl: i.onfido_api_url,
telephonyUrl: i.telephony_url,
crossDeviceUrl: i.cross_device_url
},
exp: e.exp,
payload: {
applicantUuid: n.app,
applicationId: n.application_id,
clientUuid: n.client_uuid,
isSandbox: n.is_sandbox,
isTrial: n.is_trial
}
};
}, z = (e) => {
if (!e)
throw new h(T);
try {
return q(JSON.parse(atob(e.split(".")[1])));
} catch {
throw new h(T);
}
}, A = "14", U = "fallback", $ = "0.0.0";
var v = /* @__PURE__ */ ((e) => (e.Npm = "Npm", e.Evergreen = "Evergreen", e))(v || {}), u = /* @__PURE__ */ ((e) => (e.Started = "Started", e.Error = "Error", e.Retry = "Retry", e.Fallback = "Fallback", e.Completed = "Completed", e))(u || {});
const g = (e) => e === U ? $ : L(e), H = (e) => `v${(e || A).replace(/^v/, "")}`, L = (e) => `${e || A}`.replace(/^v/g, ""), K = (e) => e.charAt(0).toUpperCase() + e.slice(1), f = (e, n, i = {}, r, o) => {
var s, l;
try {
if ("token" in e) {
const d = e.token, c = z(d);
let m = "Light";
(s = e.theme) != null && s.name && (m = K((l = e.theme) == null ? void 0 : l.name));
const N = e.language || "en-GB";
let x = [];
"steps" in e && (x = e.steps.map((p) => typeof p == "object" && "type" in p ? p.type : p)), fetch(`${c.urls.onfidoApiUrl}/v4/sdk/analytics`, {
method: "POST",
// @ts-ignore wip
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${d}`,
"x-onfido-sdk-platform": "web",
"x-onfido-sdk-version": g(
i == null ? void 0 : i.version
)
},
body: JSON.stringify({
context: {
device: {
deviceType: "Desktop",
hardware: {},
os: {
deviceLanguages: []
},
browser: {
userAgent: navigator.userAgent
}
},
runtimeInfo: {
client: {
clientId: c.payload.clientUuid
},
identifiers: {
sessionId: _(),
applicantId: c.payload.applicantUuid
},
appInfo: {
referrer: ""
},
emittedAt: (/* @__PURE__ */ new Date()).toISOString(),
crossDevice: !1
},
sdkInfo: {
library: {
sdk: "Web",
version: g(
(i == null ? void 0 : i.version) || U
),
pinnedVersion: g(e.version),
variant: "Bundled",
analyticsLibraryVersion: "0.0.141"
}
},
configuration: {
analytics: {
loggingLevel: []
},
callback: {},
ui: {
themeConfigured: m
},
orchestration: {
steps: x
},
languageInformation: {
displayedLocaleCode: N
},
clientDomain: location == null ? void 0 : location.href,
scriptHostname: "sdk.onfido.com"
},
dynamicRuntimeInfo: []
},
events: [
{
...n,
errorInfo: r,
duration: o,
eventMetadata: {
runtimeId: _(),
generatedAt: (/* @__PURE__ */ new Date()).toISOString()
}
}
]
})
}).catch(() => {
});
}
} catch {
}
};
window.OnfidoDistribution = { name: "NPM" };
class j extends B {
constructor() {
super(...arguments);
y(this, "_handle");
y(this, "_handleSetCallbacks", []);
}
_setHandle(i) {
this._handle = i, this._handleSetCallbacks.forEach((r) => r(i)), this._handleSetCallbacks = [], Object.entries(this.eventListener).forEach(([r, o]) => {
i.addEventListener(r, o);
}), this.eventListener = {};
}
addEventListener(i, r) {
return this._handle ? (this._handle.addEventListener(i, r), this) : super.addEventListener(i, r);
}
removeEventListener(i, r) {
if (this._handle)
return this._handle.removeEventListener(i, r), this;
super.removeEventListener(i, r);
}
async tearDown() {
var i;
if (this._handle)
await ((i = this._handle) == null ? void 0 : i.tearDown());
else
return this._handleSetCallbacks.push(() => {
this.tearDown();
}), Promise.resolve();
}
get version() {
var i;
return (i = this._handle) == null ? void 0 : i.version;
}
}
const E = {
init(e) {
const n = new j(), i = L(e.version), r = e.sdkUrl || `https://sdk.onfido.com/${H(e.version)}/Onfido.js`;
return f(
e,
{
identifier: "LoaderStateEvent",
state: u.Started,
loaderSource: v.Npm
},
{
version: i
}
), import(/* webpackIgnore: true */ /* @vite-ignore */ r).then((o) => {
f(
e,
{
identifier: "LoaderStateEvent",
state: u.Completed,
loaderSource: v.Npm
},
{
version: i
}
);
const { Onfido: s } = o;
n._setHandle(s.init(e));
}).catch((o) => {
var s;
f(
e,
{
identifier: "LoaderStateEvent",
state: u.Error,
loaderSource: v.Npm
},
{
version: i
},
{
message: o == null ? void 0 : o.message
}
), n.trigger("error", { error: o }), (s = e.onError) == null || s.call(e, o);
}), n;
}
};
Object.defineProperty(E, "environment", {
get: () => window == null ? void 0 : window.Onfido.environment,
set: (e) => {
window.Onfido = window.Onfido || {}, window.Onfido.environment = e;
}
});
const Y = E;
export {
Y as Onfido
};