trust-mfa-sdk
Version:
TrustJS - Blockchain-powered MFA verification SDK. Trust is the only way.
1,398 lines (1,350 loc) • 138 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('@stripe/react-stripe-js')) :
typeof define === 'function' && define.amd ? define(['exports', 'react', '@stripe/react-stripe-js'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.TrustJS = {}, global.React, global.reactStripeJs));
})(this, (function (exports, require$$0, reactStripeJs) { 'use strict';
function _arrayLikeToArray(r, a) {
(null == a || a > r.length) && (a = r.length);
for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
return n;
}
function _arrayWithHoles(r) {
if (Array.isArray(r)) return r;
}
function _assertThisInitialized(e) {
if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return e;
}
function asyncGeneratorStep(n, t, e, r, o, a, c) {
try {
var i = n[a](c),
u = i.value;
} catch (n) {
return void e(n);
}
i.done ? t(u) : Promise.resolve(u).then(r, o);
}
function _asyncToGenerator(n) {
return function () {
var t = this,
e = arguments;
return new Promise(function (r, o) {
var a = n.apply(t, e);
function _next(n) {
asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
}
function _throw(n) {
asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
}
_next(void 0);
});
};
}
function _callSuper(t, o, e) {
return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
}
function _classCallCheck(a, n) {
if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
}
function _construct(t, e, r) {
if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments);
var o = [null];
o.push.apply(o, e);
var p = new (t.bind.apply(t, o))();
return r && _setPrototypeOf(p, r.prototype), p;
}
function _defineProperties(e, r) {
for (var t = 0; t < r.length; t++) {
var o = r[t];
o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o);
}
}
function _createClass(e, r, t) {
return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", {
writable: false
}), e;
}
function _defineProperty(e, r, t) {
return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
value: t,
enumerable: true,
configurable: true,
writable: true
}) : e[r] = t, e;
}
function _getPrototypeOf(t) {
return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) {
return t.__proto__ || Object.getPrototypeOf(t);
}, _getPrototypeOf(t);
}
function _inherits(t, e) {
if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function");
t.prototype = Object.create(e && e.prototype, {
constructor: {
value: t,
writable: true,
configurable: true
}
}), Object.defineProperty(t, "prototype", {
writable: false
}), e && _setPrototypeOf(t, e);
}
function _isNativeFunction(t) {
try {
return -1 !== Function.toString.call(t).indexOf("[native code]");
} catch (n) {
return "function" == typeof t;
}
}
function _isNativeReflectConstruct() {
try {
var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
} catch (t) {}
return (_isNativeReflectConstruct = function () {
return !!t;
})();
}
function _iterableToArrayLimit(r, l) {
var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
if (null != t) {
var e,
n,
i,
u,
a = [],
f = true,
o = false;
try {
if (i = (t = t.call(r)).next, 0 === l) ; else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
} catch (r) {
o = true, n = r;
} finally {
try {
if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
} finally {
if (o) throw n;
}
}
return a;
}
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function ownKeys(e, r) {
var t = Object.keys(e);
if (Object.getOwnPropertySymbols) {
var o = Object.getOwnPropertySymbols(e);
r && (o = o.filter(function (r) {
return Object.getOwnPropertyDescriptor(e, r).enumerable;
})), t.push.apply(t, o);
}
return t;
}
function _objectSpread2(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys(Object(t), true).forEach(function (r) {
_defineProperty(e, r, t[r]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
});
}
return e;
}
function _possibleConstructorReturn(t, e) {
if (e && ("object" == typeof e || "function" == typeof e)) return e;
if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined");
return _assertThisInitialized(t);
}
function _regenerator() {
/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
var e,
t,
r = "function" == typeof Symbol ? Symbol : {},
n = r.iterator || "@@iterator",
o = r.toStringTag || "@@toStringTag";
function i(r, n, o, i) {
var c = n && n.prototype instanceof Generator ? n : Generator,
u = Object.create(c.prototype);
return _regeneratorDefine(u, "_invoke", function (r, n, o) {
var i,
c,
u,
f = 0,
p = o || [],
y = false,
G = {
p: 0,
n: 0,
v: e,
a: d,
f: d.bind(e, 4),
d: function (t, r) {
return i = t, c = 0, u = e, G.n = r, a;
}
};
function d(r, n) {
for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) {
var o,
i = p[t],
d = G.p,
l = i[2];
r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0));
}
if (o || r > 1) return a;
throw y = true, n;
}
return function (o, p, l) {
if (f > 1) throw TypeError("Generator is already running");
for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) {
i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u);
try {
if (f = 2, i) {
if (c || (o = "next"), t = i[o]) {
if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object");
if (!t.done) return t;
u = t.value, c < 2 && (c = 0);
} else 1 === c && (t = i.return) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1);
i = e;
} else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break;
} catch (t) {
i = e, c = 1, u = t;
} finally {
f = 1;
}
}
return {
value: t,
done: y
};
};
}(r, o, i), true), u;
}
var a = {};
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
t = Object.getPrototypeOf;
var c = [][n] ? t(t([][n]())) : (_regeneratorDefine(t = {}, n, function () {
return this;
}), t),
u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c);
function f(e) {
return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e;
}
return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine(u), _regeneratorDefine(u, o, "Generator"), _regeneratorDefine(u, n, function () {
return this;
}), _regeneratorDefine(u, "toString", function () {
return "[object Generator]";
}), (_regenerator = function () {
return {
w: i,
m: f
};
})();
}
function _regeneratorDefine(e, r, n, t) {
var i = Object.defineProperty;
try {
i({}, "", {});
} catch (e) {
i = 0;
}
_regeneratorDefine = function (e, r, n, t) {
function o(r, n) {
_regeneratorDefine(e, r, function (e) {
return this._invoke(r, n, e);
});
}
r ? i ? i(e, r, {
value: n,
enumerable: !t,
configurable: !t,
writable: !t
}) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2));
}, _regeneratorDefine(e, r, n, t);
}
function _regeneratorValues(e) {
if (null != e) {
var t = e["function" == typeof Symbol && Symbol.iterator || "@@iterator"],
r = 0;
if (t) return t.call(e);
if ("function" == typeof e.next) return e;
if (!isNaN(e.length)) return {
next: function () {
return e && r >= e.length && (e = void 0), {
value: e && e[r++],
done: !e
};
}
};
}
throw new TypeError(typeof e + " is not iterable");
}
function _setPrototypeOf(t, e) {
return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
return t.__proto__ = e, t;
}, _setPrototypeOf(t, e);
}
function _slicedToArray(r, e) {
return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
}
function _toPrimitive(t, r) {
if ("object" != typeof t || !t) return t;
var e = t[Symbol.toPrimitive];
if (void 0 !== e) {
var i = e.call(t, r);
if ("object" != typeof i) return i;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r ? String : Number)(t);
}
function _toPropertyKey(t) {
var i = _toPrimitive(t, "string");
return "symbol" == typeof i ? i : i + "";
}
function _unsupportedIterableToArray(r, a) {
if (r) {
if ("string" == typeof r) return _arrayLikeToArray(r, a);
var t = {}.toString.call(r).slice(8, -1);
return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
}
}
function _wrapNativeSuper(t) {
var r = "function" == typeof Map ? new Map() : void 0;
return _wrapNativeSuper = function (t) {
if (null === t || !_isNativeFunction(t)) return t;
if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function");
if (void 0 !== r) {
if (r.has(t)) return r.get(t);
r.set(t, Wrapper);
}
function Wrapper() {
return _construct(t, arguments, _getPrototypeOf(this).constructor);
}
return Wrapper.prototype = Object.create(t.prototype, {
constructor: {
value: Wrapper,
enumerable: false,
writable: true,
configurable: true
}
}), _setPrototypeOf(Wrapper, t);
}, _wrapNativeSuper(t);
}
var V3_URL = 'https://js.stripe.com/v3';
var V3_URL_REGEX = /^https:\/\/js\.stripe\.com\/v3\/?(\?.*)?$/;
var EXISTING_SCRIPT_MESSAGE = 'loadStripe.setLoadParameters was called but an existing Stripe.js script already exists in the document; existing script parameters will be used';
var findScript = function findScript() {
var scripts = document.querySelectorAll("script[src^=\"".concat(V3_URL, "\"]"));
for (var i = 0; i < scripts.length; i++) {
var script = scripts[i];
if (!V3_URL_REGEX.test(script.src)) {
continue;
}
return script;
}
return null;
};
var injectScript = function injectScript(params) {
var queryString = '';
var script = document.createElement('script');
script.src = "".concat(V3_URL).concat(queryString);
var headOrBody = document.head || document.body;
if (!headOrBody) {
throw new Error('Expected document.body not to be null. Stripe.js requires a <body> element.');
}
headOrBody.appendChild(script);
return script;
};
var registerWrapper = function registerWrapper(stripe, startTime) {
if (!stripe || !stripe._registerWrapper) {
return;
}
stripe._registerWrapper({
name: 'stripe-js',
version: "2.4.0",
startTime: startTime
});
};
var stripePromise = null;
var onErrorListener = null;
var onLoadListener = null;
var onError = function onError(reject) {
return function () {
reject(new Error('Failed to load Stripe.js'));
};
};
var onLoad = function onLoad(resolve, reject) {
return function () {
if (window.Stripe) {
resolve(window.Stripe);
} else {
reject(new Error('Stripe.js not available'));
}
};
};
var loadScript = function loadScript(params) {
// Ensure that we only attempt to load Stripe.js at most once
if (stripePromise !== null) {
return stripePromise;
}
stripePromise = new Promise(function (resolve, reject) {
if (typeof window === 'undefined' || typeof document === 'undefined') {
// Resolve to null when imported server side. This makes the module
// safe to import in an isomorphic code base.
resolve(null);
return;
}
if (window.Stripe) {
resolve(window.Stripe);
return;
}
try {
var script = findScript();
if (script && params) ; else if (!script) {
script = injectScript(params);
} else if (script && onLoadListener !== null && onErrorListener !== null) {
var _script$parentNode;
// remove event listeners
script.removeEventListener('load', onLoadListener);
script.removeEventListener('error', onErrorListener); // if script exists, but we are reloading due to an error,
// reload script to trigger 'load' event
(_script$parentNode = script.parentNode) === null || _script$parentNode === void 0 ? void 0 : _script$parentNode.removeChild(script);
script = injectScript(params);
}
onLoadListener = onLoad(resolve, reject);
onErrorListener = onError(reject);
script.addEventListener('load', onLoadListener);
script.addEventListener('error', onErrorListener);
} catch (error) {
reject(error);
return;
}
}); // Resets stripePromise on error
return stripePromise["catch"](function (error) {
stripePromise = null;
return Promise.reject(error);
});
};
var initStripe = function initStripe(maybeStripe, args, startTime) {
if (maybeStripe === null) {
return null;
}
var stripe = maybeStripe.apply(undefined, args);
registerWrapper(stripe, startTime);
return stripe;
}; // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
var stripePromise$1;
var loadCalled = false;
var getStripePromise = function getStripePromise() {
if (stripePromise$1) {
return stripePromise$1;
}
stripePromise$1 = loadScript(null)["catch"](function (error) {
// clear cache on error
stripePromise$1 = null;
return Promise.reject(error);
});
return stripePromise$1;
}; // Execute our own script injection after a tick to give users time to do their
// own script injection.
Promise.resolve().then(function () {
return getStripePromise();
})["catch"](function (error) {
if (!loadCalled) {
console.warn(error);
}
});
var loadStripe = function loadStripe() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
loadCalled = true;
var startTime = Date.now(); // if previous attempts are unsuccessful, will re-load script
return getStripePromise().then(function (maybeStripe) {
return initStripe(maybeStripe, args, startTime);
});
};
var TrustJSError = /*#__PURE__*/function (_Error) {
function TrustJSError(message) {
var _this;
var code = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var details = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
_classCallCheck(this, TrustJSError);
_this = _callSuper(this, TrustJSError, [message]);
_this.name = 'TrustJSError';
_this.code = code;
_this.details = details;
_this.timestamp = new Date().toISOString();
// Maintain proper stack trace
if (Error.captureStackTrace) {
Error.captureStackTrace(_this, TrustJSError);
}
return _this;
}
_inherits(TrustJSError, _Error);
return _createClass(TrustJSError, [{
key: "toJSON",
value: function toJSON() {
return {
name: this.name,
message: this.message,
code: this.code,
details: this.details,
timestamp: this.timestamp,
stack: this.stack
};
}
}]);
}(/*#__PURE__*/_wrapNativeSuper(Error));
var ValidationError = /*#__PURE__*/function (_TrustJSError) {
function ValidationError(message) {
var _this2;
var field = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
_classCallCheck(this, ValidationError);
_this2 = _callSuper(this, ValidationError, [message, 'VALIDATION_ERROR', {
field: field
}]);
_this2.name = 'ValidationError';
return _this2;
}
_inherits(ValidationError, _TrustJSError);
return _createClass(ValidationError);
}(TrustJSError);
var PaymentError = /*#__PURE__*/function (_TrustJSError2) {
function PaymentError(message) {
var _this3;
var paymentIntentId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
_classCallCheck(this, PaymentError);
_this3 = _callSuper(this, PaymentError, [message, 'PAYMENT_ERROR', {
paymentIntentId: paymentIntentId
}]);
_this3.name = 'PaymentError';
return _this3;
}
_inherits(PaymentError, _TrustJSError2);
return _createClass(PaymentError);
}(TrustJSError);
var MfaError = /*#__PURE__*/function (_TrustJSError3) {
function MfaError(message) {
var _this4;
var orderId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
_classCallCheck(this, MfaError);
_this4 = _callSuper(this, MfaError, [message, 'MFA_ERROR', {
orderId: orderId
}]);
_this4.name = 'MfaError';
return _this4;
}
_inherits(MfaError, _TrustJSError3);
return _createClass(MfaError);
}(TrustJSError);
var NetworkError = /*#__PURE__*/function (_TrustJSError4) {
function NetworkError(message) {
var _this5;
var endpoint = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var status = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
_classCallCheck(this, NetworkError);
_this5 = _callSuper(this, NetworkError, [message, 'NETWORK_ERROR', {
endpoint: endpoint,
status: status
}]);
_this5.name = 'NetworkError';
return _this5;
}
_inherits(NetworkError, _TrustJSError4);
return _createClass(NetworkError);
}(TrustJSError);
var ConfigurationError = /*#__PURE__*/function (_TrustJSError5) {
function ConfigurationError(message) {
var _this6;
var configKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
_classCallCheck(this, ConfigurationError);
_this6 = _callSuper(this, ConfigurationError, [message, 'CONFIGURATION_ERROR', {
configKey: configKey
}]);
_this6.name = 'ConfigurationError';
return _this6;
}
_inherits(ConfigurationError, _TrustJSError5);
return _createClass(ConfigurationError);
}(TrustJSError);
function validateConfig(config) {
var errors = [];
if (!config) {
return {
valid: false,
errors: ['Configuration object is required']
};
}
if (!config.publishableKey) {
errors.push('publishableKey is required');
} else if (!config.publishableKey.startsWith('pk_')) {
errors.push('publishableKey must start with "pk_"');
}
if (!config.merchantId) {
errors.push('merchantId is required');
} else if (typeof config.merchantId !== 'string' || config.merchantId.length < 3) {
errors.push('merchantId must be a string with at least 3 characters');
}
if (config.apiUrl && !isValidUrl(config.apiUrl)) {
errors.push('apiUrl must be a valid URL');
}
if (config.mfaThreshold && (!isNumber(config.mfaThreshold) || config.mfaThreshold < 0)) {
errors.push('mfaThreshold must be a positive number');
}
return {
valid: errors.length === 0,
errors: errors
};
}
function validateAmount(amount) {
if (!amount) return false;
var num = parseFloat(amount);
return !isNaN(num) && num > 0 && num <= 999999.99;
}
function validateOrderId(orderId) {
if (!orderId) return false;
if (typeof orderId !== 'string') return false;
if (orderId.length < 3 || orderId.length > 100) return false;
// Allow alphanumeric, dashes, underscores
return /^[a-zA-Z0-9_-]+$/.test(orderId);
}
function validateEmail(email) {
if (!email) return false;
var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
function validateOtp(otp) {
if (!otp) return false;
if (typeof otp !== 'string') return false;
if (otp.length !== 6) return false;
return /^\d{6}$/.test(otp);
}
// Helper functions
function isValidUrl(string) {
try {
new URL(string);
return true;
} catch (_) {
return false;
}
}
function isNumber(value) {
return typeof value === 'number' && !isNaN(value);
}
var PaymentManager = /*#__PURE__*/function () {
function PaymentManager(config, apiClient) {
_classCallCheck(this, PaymentManager);
this.config = config;
this.apiClient = apiClient;
}
return _createClass(PaymentManager, [{
key: "createPayment",
value: function () {
var _createPayment = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(options) {
var amount, orderId, _options$currency, currency, _options$customer, customer, response, _t;
return _regenerator().w(function (_context) {
while (1) switch (_context.p = _context.n) {
case 0:
amount = options.amount, orderId = options.orderId, _options$currency = options.currency, currency = _options$currency === void 0 ? 'usd' : _options$currency, _options$customer = options.customer, customer = _options$customer === void 0 ? {} : _options$customer; // Validate inputs
if (validateAmount(amount)) {
_context.n = 1;
break;
}
throw new TrustJSError('Invalid amount provided');
case 1:
if (validateOrderId(orderId)) {
_context.n = 2;
break;
}
throw new TrustJSError('Invalid orderId provided');
case 2:
_context.p = 2;
console.log('🔍 PaymentManager: Creating payment intent', {
orderId: orderId,
amount: amount
});
_context.n = 3;
return this.apiClient.post('/create-payment-intent', {
merchantId: this.config.merchantId,
orderId: orderId,
amount: parseFloat(amount),
currency: currency,
customer: customer,
mfaThreshold: this.config.mfaThreshold
});
case 3:
response = _context.v;
console.log('🔍 PaymentManager: Payment intent created', response);
return _context.a(2, _objectSpread2(_objectSpread2({}, response), {}, {
orderId: orderId,
amount: amount,
currency: currency,
customer: customer
}));
case 4:
_context.p = 4;
_t = _context.v;
console.error('PaymentManager: Payment creation failed', _t);
throw new TrustJSError("Payment creation failed: ".concat(_t.message));
case 5:
return _context.a(2);
}
}, _callee, this, [[2, 4]]);
}));
function createPayment(_x) {
return _createPayment.apply(this, arguments);
}
return createPayment;
}()
}, {
key: "getPaymentStatus",
value: function () {
var _getPaymentStatus = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(paymentIntentId) {
var _t2;
return _regenerator().w(function (_context2) {
while (1) switch (_context2.p = _context2.n) {
case 0:
_context2.p = 0;
_context2.n = 1;
return this.apiClient.get("/payment/".concat(paymentIntentId, "/status"));
case 1:
return _context2.a(2, _context2.v);
case 2:
_context2.p = 2;
_t2 = _context2.v;
throw new TrustJSError("Failed to get payment status: ".concat(_t2.message));
case 3:
return _context2.a(2);
}
}, _callee2, this, [[0, 2]]);
}));
function getPaymentStatus(_x2) {
return _getPaymentStatus.apply(this, arguments);
}
return getPaymentStatus;
}()
}, {
key: "cancelPayment",
value: function () {
var _cancelPayment = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(paymentIntentId) {
var _t3;
return _regenerator().w(function (_context3) {
while (1) switch (_context3.p = _context3.n) {
case 0:
_context3.p = 0;
_context3.n = 1;
return this.apiClient.post("/payment/".concat(paymentIntentId, "/cancel"));
case 1:
return _context3.a(2, _context3.v);
case 2:
_context3.p = 2;
_t3 = _context3.v;
throw new TrustJSError("Failed to cancel payment: ".concat(_t3.message));
case 3:
return _context3.a(2);
}
}, _callee3, this, [[0, 2]]);
}));
function cancelPayment(_x3) {
return _cancelPayment.apply(this, arguments);
}
return cancelPayment;
}()
}]);
}();
var MfaManager = /*#__PURE__*/function () {
function MfaManager(config, apiClient) {
_classCallCheck(this, MfaManager);
this.config = config;
this.apiClient = apiClient;
this.otpCache = new Map();
}
return _createClass(MfaManager, [{
key: "sendOtp",
value: function () {
var _sendOtp = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(orderId) {
var amount,
response,
_args = arguments,
_t;
return _regenerator().w(function (_context) {
while (1) switch (_context.p = _context.n) {
case 0:
amount = _args.length > 1 && _args[1] !== undefined ? _args[1] : 0;
_context.p = 1;
console.log('🔍 MfaManager: Sending OTP for order', orderId);
_context.n = 2;
return this.apiClient.post('/send-otp', {
merchantId: this.config.merchantId,
orderId: orderId,
amount: amount,
method: 'terminal' // For development, shows in terminal
});
case 2:
response = _context.v;
if (!response.success) {
_context.n = 3;
break;
}
console.log('🔍 MfaManager: OTP sent successfully');
return _context.a(2, response);
case 3:
throw new TrustJSError(response.message || 'Failed to send OTP');
case 4:
_context.n = 6;
break;
case 5:
_context.p = 5;
_t = _context.v;
console.error('MfaManager: OTP send failed', _t);
throw new TrustJSError("OTP send failed: ".concat(_t.message));
case 6:
return _context.a(2);
}
}, _callee, this, [[1, 5]]);
}));
function sendOtp(_x) {
return _sendOtp.apply(this, arguments);
}
return sendOtp;
}()
}, {
key: "verifyCode",
value: function () {
var _verifyCode = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(orderId, code) {
var response, _t2;
return _regenerator().w(function (_context2) {
while (1) switch (_context2.p = _context2.n) {
case 0:
if (!(!code || code.length !== 6)) {
_context2.n = 1;
break;
}
throw new TrustJSError('Invalid OTP code format');
case 1:
_context2.p = 1;
console.log('🔍 MfaManager: Verifying OTP', {
orderId: orderId,
code: code
});
_context2.n = 2;
return this.apiClient.post('/verify-otp', {
merchantId: this.config.merchantId,
orderId: orderId,
otp: code
});
case 2:
response = _context2.v;
console.log('🔍 MfaManager: OTP verification response', response);
if (!response.success) {
_context2.n = 3;
break;
}
// Cache successful verification
this.otpCache.set(orderId, {
verified: true,
timestamp: Date.now(),
mfaReceipt: response.mfaReceipt
});
return _context2.a(2, response);
case 3:
throw new TrustJSError(response.message || 'OTP verification failed');
case 4:
_context2.n = 6;
break;
case 5:
_context2.p = 5;
_t2 = _context2.v;
console.error('MfaManager: OTP verification failed', _t2);
throw new TrustJSError("OTP verification failed: ".concat(_t2.message));
case 6:
return _context2.a(2);
}
}, _callee2, this, [[1, 5]]);
}));
function verifyCode(_x2, _x3) {
return _verifyCode.apply(this, arguments);
}
return verifyCode;
}()
}, {
key: "isVerified",
value: function isVerified(orderId) {
var cached = this.otpCache.get(orderId);
if (!cached) return false;
// Check if verification is still valid (5 minutes)
var isExpired = Date.now() - cached.timestamp > 5 * 60 * 1000;
if (isExpired) {
this.otpCache["delete"](orderId);
return false;
}
return cached.verified;
}
}, {
key: "clearCache",
value: function clearCache(orderId) {
if (orderId) {
this.otpCache["delete"](orderId);
} else {
this.otpCache.clear();
}
}
}]);
}();
var ApiClient = /*#__PURE__*/function () {
function ApiClient(config) {
_classCallCheck(this, ApiClient);
this.config = config;
this.baseURL = config.apiUrl;
this.timeout = config.timeout || 30000;
this.retries = config.retries || 3;
}
return _createClass(ApiClient, [{
key: "request",
value: function () {
var _request = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(method, endpoint) {
var _this = this;
var data,
options,
url,
config,
lastError,
_loop,
_ret,
attempt,
_args2 = arguments;
return _regenerator().w(function (_context2) {
while (1) switch (_context2.n) {
case 0:
data = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : null;
options = _args2.length > 3 && _args2[3] !== undefined ? _args2[3] : {};
url = "".concat(this.baseURL, "/api").concat(endpoint);
config = _objectSpread2({
method: method,
headers: _objectSpread2({
'Content-Type': 'application/json',
'User-Agent': 'TrustJS/1.0.0'
}, options.headers)
}, options);
if (data) {
config.body = JSON.stringify(data);
}
_loop = /*#__PURE__*/_regenerator().m(function _loop() {
var controller, timeoutId, response, errorText, result, delay, _t;
return _regenerator().w(function (_context) {
while (1) switch (_context.p = _context.n) {
case 0:
_context.p = 0;
console.log("\uD83D\uDD0D ApiClient: ".concat(method, " ").concat(url, " (attempt ").concat(attempt, "/").concat(_this.retries, ")"));
controller = new AbortController();
timeoutId = setTimeout(function () {
return controller.abort();
}, _this.timeout);
config.signal = controller.signal;
_context.n = 1;
return fetch(url, config);
case 1:
response = _context.v;
clearTimeout(timeoutId);
console.log("\uD83D\uDD0D ApiClient: Response ".concat(response.status));
if (response.ok) {
_context.n = 3;
break;
}
_context.n = 2;
return response.text();
case 2:
errorText = _context.v;
throw new TrustJSError("HTTP ".concat(response.status, ": ").concat(errorText));
case 3:
_context.n = 4;
return response.json();
case 4:
result = _context.v;
console.log('🔍 ApiClient: Success', result);
return _context.a(2, {
v: result
});
case 5:
_context.p = 5;
_t = _context.v;
lastError = _t;
console.error("\uD83D\uDD0D ApiClient: Attempt ".concat(attempt, " failed"), _t.message);
if (!(attempt === _this.retries)) {
_context.n = 6;
break;
}
return _context.a(2, 0);
case 6:
// Exponential backoff
delay = Math.min(1000 * Math.pow(2, attempt - 1), 5000);
_context.n = 7;
return new Promise(function (resolve) {
return setTimeout(resolve, delay);
});
case 7:
return _context.a(2);
}
}, _loop, null, [[0, 5]]);
});
attempt = 1;
case 1:
if (!(attempt <= this.retries)) {
_context2.n = 5;
break;
}
return _context2.d(_regeneratorValues(_loop()), 2);
case 2:
_ret = _context2.v;
if (!(_ret === 0)) {
_context2.n = 3;
break;
}
return _context2.a(3, 5);
case 3:
if (!_ret) {
_context2.n = 4;
break;
}
return _context2.a(2, _ret.v);
case 4:
attempt++;
_context2.n = 1;
break;
case 5:
throw new TrustJSError("API request failed after ".concat(this.retries, " attempts: ").concat(lastError.message));
case 6:
return _context2.a(2);
}
}, _callee, this);
}));
function request(_x, _x2) {
return _request.apply(this, arguments);
}
return request;
}()
}, {
key: "get",
value: function () {
var _get = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(endpoint) {
var params,
query,
url,
_args3 = arguments;
return _regenerator().w(function (_context3) {
while (1) switch (_context3.n) {
case 0:
params = _args3.length > 1 && _args3[1] !== undefined ? _args3[1] : {};
query = new URLSearchParams(params).toString();
url = query ? "".concat(endpoint, "?").concat(query) : endpoint;
return _context3.a(2, this.request('GET', url));
}
}, _callee2, this);
}));
function get(_x3) {
return _get.apply(this, arguments);
}
return get;
}()
}, {
key: "post",
value: function () {
var _post = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(endpoint, data) {
return _regenerator().w(function (_context4) {
while (1) switch (_context4.n) {
case 0:
return _context4.a(2, this.request('POST', endpoint, data));
}
}, _callee3, this);
}));
function post(_x4, _x5) {
return _post.apply(this, arguments);
}
return post;
}()
}, {
key: "put",
value: function () {
var _put = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(endpoint, data) {
return _regenerator().w(function (_context5) {
while (1) switch (_context5.n) {
case 0:
return _context5.a(2, this.request('PUT', endpoint, data));
}
}, _callee4, this);
}));
function put(_x6, _x7) {
return _put.apply(this, arguments);
}
return put;
}()
}, {
key: "delete",
value: function () {
var _delete2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5(endpoint) {
return _regenerator().w(function (_context6) {
while (1) switch (_context6.n) {
case 0:
return _context6.a(2, this.request('DELETE', endpoint));
}
}, _callee5, this);
}));
function _delete(_x8) {
return _delete2.apply(this, arguments);
}
return _delete;
}()
}, {
key: "updateConfig",
value: function updateConfig(newConfig) {
this.config = _objectSpread2(_objectSpread2({}, this.config), newConfig);
this.baseURL = this.config.apiUrl;
}
}, {
key: "destroy",
value: function destroy() {
// Cleanup any pending requests
console.log('🔍 ApiClient: Destroyed');
}
}]);
}();
var TrustJS = /*#__PURE__*/function () {
function TrustJS(config) {
_classCallCheck(this, TrustJS);
// Validate configuration
var validation = validateConfig(config);
if (!validation.valid) {
throw new ValidationError("Invalid TrustJS configuration: ".concat(validation.errors.join(', ')));
}
this.config = _objectSpread2({
apiUrl: 'https://api.trustjs.dev',
environment: 'production',
theme: 'dark',
mfaThreshold: 500,
enableBlockchain: true,
enableAnalytics: true,
timeout: 30000,
retries: 3
}, config);
// Initialize managers
this.apiClient = new ApiClient(this.config);
this.paymentManager = new PaymentManager(this.config, this.apiClient);
this.mfaManager = new MfaManager(this.config, this.apiClient);
// Initialize Stripe
this.stripePromise = loadStripe(this.config.publishableKey);
// Event listeners
this.listeners = new Map();
console.log('🔒 TrustJS initialized:', {
version: this.getVersion(),
environment: this.config.environment,
merchantId: this.config.merchantId
});
}
// Version info
return _createClass(TrustJS, [{
key: "getVersion",
value: function getVersion() {
return '1.0.0';
}
// Event system
}, {
key: "on",
value: function on(event, callback) {
var _this = this;
if (!this.listeners.has(event)) {
this.listeners.set(event, []);
}
this.listeners.get(event).push(callback);
return function () {
return _this.off(event, callback);
};
}
}, {
key: "off",
value: function off(event, callback) {
var callbacks = this.listeners.get(event);
if (callbacks) {
var index = callbacks.indexOf(callback);
if (index > -1) {
callbacks.splice(index, 1);
}
}
}
}, {
key: "emit",
value: function emit(event, data) {
var callbacks = this.listeners.get(event) || [];
callbacks.forEach(function (callback) {
try {
callback(data);
} catch (error) {
console.error("TrustJS event handler error for '".concat(event, "':"), error);
}
});
}
// Main payment method
}, {
key: "createPayment",
value: function () {
var _createPayment = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(options) {
var result, _t;
return _regenerator().w(function (_context) {
while (1) switch (_context.p = _context.n) {
case 0:
_context.p = 0;
if (validateAmount(options.amount)) {
_context.n = 1;
break;
}
throw new ValidationError('Invalid amount');
case 1:
if (validateOrderId(options.orderId)) {
_context.n = 2;
break;
}
throw new ValidationError('Invalid orderId');
case 2:
this.emit('payment:started', {
orderId: options.orderId
});
_context.n = 3;
return this.paymentManager.createPayment(options);
case 3:
result = _context.v;
this.emit('payment:created', result);
return _context.a(2, result);
case 4:
_context.p = 4;
_t = _context.v;
this.emit('payment:error', {
error: _t,
orderId: options.orderId
});
throw _t;
case 5:
return _context.a(2);
}
}, _callee, this, [[0, 4]]);
}));
function createPayment(_x) {
return _createPayment.apply(this, arguments);
}
return createPayment;
}() // MFA verification
}, {
key: "verifyMfa",
value: function () {
var _verifyMfa = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(orderId, code) {
var result, _t2;
return _regenerator().w(function (_context2) {
while (1) switch (_context2.p = _context2.n) {
case 0:
_context2.p = 0;
this.emit('mfa:started', {
orderId: orderId
});
_context2.n = 1;
return this.mfaManager.verifyCode(orderId, code);
case 1:
result = _context2.v;
this.emit('mfa:verified', {
orderId: orderId,
result: result
});
return _context2.a(2, result);
case 2:
_context2.p = 2;
_t2 = _context2.v;
this.emit('mfa:error', {
error: _t2,
orderId: orderId
});
throw _t2;
case 3:
return _context2.a(2);
}
}, _callee2, this, [[0, 2]]);
}));
function verifyMfa(_x2, _x3) {
return _verifyMfa.apply(this, arguments);
}
return verifyMfa;
}() // Complete payment
}, {
key: "confirmPayment",
value: function () {
var _confirmPayment = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(clientSecret, paymentMethodId) {
var stripe, result, _t3;
return _regenerator().w(function (_context3) {
while (1) switch (_context3.p = _context3.n) {
case 0:
_context3.p = 0;
_context3.n = 1;
return this.stripePromise;
case 1:
stripe = _context3.v;
if (stripe) {
_context3.n = 2;
break;
}
throw new TrustJSError('Stripe failed to load');
case 2:
this.emit('payment:confirming', {
clientSecret: clientSecret
});
_context3.n = 3;
return stripe.confirmCardPayment(clientSecret, {
payment_method: paymentMethodId
});
case 3:
result = _context3.v;
if (!result.error) {
_context3.n = 4;
break;
}
throw new TrustJSError("Payment confirmation failed: ".concat(result.error.message));
case 4:
this.emit('payment:confirmed', result.paymentIntent);
return _context3.a(2, result.paymentIntent);
case 5:
_context3.p = 5;
_t3 = _context3.v;
this.emit('payment:confirmation_error', {
error: _t3,
clientSecret: clientSecret
});
throw _t3;
case 6:
return _context3.a(2);
}
}, _callee3, this, [[0, 5]]);
}));
function confirmPayment(_x4, _x5) {
return _confirmPayment.apply(this, arguments);
}
return confirmPayment;
}() // Analytics
}, {
key: "getAnalytics",
value: function () {
var _getAnalytics = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4() {
var options,
_args4 = arguments,
_t4;
return _regenerator().w(function (_context4) {
while (1) switch (_context4.p = _context4.n) {
case 0:
options = _args4.length > 0 && _args4[0] !== undefined ? _args4[0] : {};
_context4.p = 1;
_context4.n = 2;
return this.apiClient.get('/analytics', {
timeRange: options.timeRange || '7d',
merchantId: this.config.merchantId
});
case 2:
return _context4.a(2, _context4.v);
case 3: