/******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 6524:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ CheckoutEventNames: () => (/* binding */ CheckoutEventNames),
/* harmony export */ CheckoutEventsPaymentMethodCardTypes: () => (/* binding */ CheckoutEventsPaymentMethodCardTypes),
/* harmony export */ CheckoutEventsPaymentMethodTypes: () => (/* binding */ CheckoutEventsPaymentMethodTypes),
/* harmony export */ CheckoutEventsStatus: () => (/* binding */ CheckoutEventsStatus),
/* harmony export */ CheckoutEventsTimePeriodInterval: () => (/* binding */ CheckoutEventsTimePeriodInterval),
/* harmony export */ getPaddleInstance: () => (/* binding */ getPaddleInstance),
/* harmony export */ initializePaddle: () => (/* binding */ initializePaddle)
/* harmony export */ });
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 _defineProperty(e, r, t) {
return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
value: t,
enumerable: !0,
configurable: !0,
writable: !0
}) : e[r] = t, e;
}
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), !0).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 _objectWithoutProperties(e, t) {
if (null == e) return {};
var o,
r,
i = _objectWithoutPropertiesLoose(e, t);
if (Object.getOwnPropertySymbols) {
var s = Object.getOwnPropertySymbols(e);
for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]);
}
return i;
}
function _objectWithoutPropertiesLoose(r, e) {
if (null == r) return {};
var t = {};
for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
if (e.includes(n)) continue;
t[n] = r[n];
}
return t;
}
function _regeneratorRuntime() {
_regeneratorRuntime = function () {
return e;
};
var t,
e = {},
r = Object.prototype,
n = r.hasOwnProperty,
o = Object.defineProperty || function (t, e, r) {
t[e] = r.value;
},
i = "function" == typeof Symbol ? Symbol : {},
a = i.iterator || "@@iterator",
c = i.asyncIterator || "@@asyncIterator",
u = i.toStringTag || "@@toStringTag";
function define(t, e, r) {
return Object.defineProperty(t, e, {
value: r,
enumerable: !0,
configurable: !0,
writable: !0
}), t[e];
}
try {
define({}, "");
} catch (t) {
define = function (t, e, r) {
return t[e] = r;
};
}
function wrap(t, e, r, n) {
var i = e && e.prototype instanceof Generator ? e : Generator,
a = Object.create(i.prototype),
c = new Context(n || []);
return o(a, "_invoke", {
value: makeInvokeMethod(t, r, c)
}), a;
}
function tryCatch(t, e, r) {
try {
return {
type: "normal",
arg: t.call(e, r)
};
} catch (t) {
return {
type: "throw",
arg: t
};
}
}
e.wrap = wrap;
var h = "suspendedStart",
l = "suspendedYield",
f = "executing",
s = "completed",
y = {};
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
var p = {};
define(p, a, function () {
return this;
});
var d = Object.getPrototypeOf,
v = d && d(d(values([])));
v && v !== r && n.call(v, a) && (p = v);
var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);
function defineIteratorMethods(t) {
["next", "throw", "return"].forEach(function (e) {
define(t, e, function (t) {
return this._invoke(e, t);
});
});
}
function AsyncIterator(t, e) {
function invoke(r, o, i, a) {
var c = tryCatch(t[r], t, o);
if ("throw" !== c.type) {
var u = c.arg,
h = u.value;
return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) {
invoke("next", t, i, a);
}, function (t) {
invoke("throw", t, i, a);
}) : e.resolve(h).then(function (t) {
u.value = t, i(u);
}, function (t) {
return invoke("throw", t, i, a);
});
}
a(c.arg);
}
var r;
o(this, "_invoke", {
value: function (t, n) {
function callInvokeWithMethodAndArg() {
return new e(function (e, r) {
invoke(t, n, e, r);
});
}
return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
}
});
}
function makeInvokeMethod(e, r, n) {
var o = h;
return function (i, a) {
if (o === f) throw Error("Generator is already running");
if (o === s) {
if ("throw" === i) throw a;
return {
value: t,
done: !0
};
}
for (n.method = i, n.arg = a;;) {
var c = n.delegate;
if (c) {
var u = maybeInvokeDelegate(c, n);
if (u) {
if (u === y) continue;
return u;
}
}
if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) {
if (o === h) throw o = s, n.arg;
n.dispatchException(n.arg);
} else "return" === n.method && n.abrupt("return", n.arg);
o = f;
var p = tryCatch(e, r, n);
if ("normal" === p.type) {
if (o = n.done ? s : l, p.arg === y) continue;
return {
value: p.arg,
done: n.done
};
}
"throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg);
}
};
}
function maybeInvokeDelegate(e, r) {
var n = r.method,
o = e.iterator[n];
if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y;
var i = tryCatch(o, e.iterator, r.arg);
if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y;
var a = i.arg;
return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y);
}
function pushTryEntry(t) {
var e = {
tryLoc: t[0]
};
1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);
}
function resetTryEntry(t) {
var e = t.completion || {};
e.type = "normal", delete e.arg, t.completion = e;
}
function Context(t) {
this.tryEntries = [{
tryLoc: "root"
}], t.forEach(pushTryEntry, this), this.reset(!0);
}
function values(e) {
if (e || "" === e) {
var r = e[a];
if (r) return r.call(e);
if ("function" == typeof e.next) return e;
if (!isNaN(e.length)) {
var o = -1,
i = function next() {
for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next;
return next.value = t, next.done = !0, next;
};
return i.next = i;
}
}
throw new TypeError(typeof e + " is not iterable");
}
return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", {
value: GeneratorFunctionPrototype,
configurable: !0
}), o(GeneratorFunctionPrototype, "constructor", {
value: GeneratorFunction,
configurable: !0
}), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) {
var e = "function" == typeof t && t.constructor;
return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name));
}, e.mark = function (t) {
return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t;
}, e.awrap = function (t) {
return {
__await: t
};
}, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {
return this;
}), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {
void 0 === i && (i = Promise);
var a = new AsyncIterator(wrap(t, r, n, o), i);
return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {
return t.done ? t.value : a.next();
});
}, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () {
return this;
}), define(g, "toString", function () {
return "[object Generator]";
}), e.keys = function (t) {
var e = Object(t),
r = [];
for (var n in e) r.push(n);
return r.reverse(), function next() {
for (; r.length;) {
var t = r.pop();
if (t in e) return next.value = t, next.done = !1, next;
}
return next.done = !0, next;
};
}, e.values = values, Context.prototype = {
constructor: Context,
reset: function (e) {
if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t);
},
stop: function () {
this.done = !0;
var t = this.tryEntries[0].completion;
if ("throw" === t.type) throw t.arg;
return this.rval;
},
dispatchException: function (e) {
if (this.done) throw e;
var r = this;
function handle(n, o) {
return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o;
}
for (var o = this.tryEntries.length - 1; o >= 0; --o) {
var i = this.tryEntries[o],
a = i.completion;
if ("root" === i.tryLoc) return handle("end");
if (i.tryLoc <= this.prev) {
var c = n.call(i, "catchLoc"),
u = n.call(i, "finallyLoc");
if (c && u) {
if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
} else if (c) {
if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
} else {
if (!u) throw Error("try statement without catch or finally");
if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
}
}
}
},
abrupt: function (t, e) {
for (var r = this.tryEntries.length - 1; r >= 0; --r) {
var o = this.tryEntries[r];
if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) {
var i = o;
break;
}
}
i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);
var a = i ? i.completion : {};
return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a);
},
complete: function (t, e) {
if ("throw" === t.type) throw t.arg;
return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y;
},
finish: function (t) {
for (var e = this.tryEntries.length - 1; e >= 0; --e) {
var r = this.tryEntries[e];
if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;
}
},
catch: function (t) {
for (var e = this.tryEntries.length - 1; e >= 0; --e) {
var r = this.tryEntries[e];
if (r.tryLoc === t) {
var n = r.completion;
if ("throw" === n.type) {
var o = n.arg;
resetTryEntry(r);
}
return o;
}
}
throw Error("illegal catch attempt");
},
delegateYield: function (e, r, n) {
return this.delegate = {
iterator: values(e),
resultName: r,
nextLoc: n
}, "next" === this.method && (this.arg = t), y;
}
}, e;
}
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 || "default");
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 + "";
}
var Versions = {
CLASSIC: 'classic',
V1: 'v1'
};
var DefaultVersion = Versions.V1;
var PaddleClassicCDNUrl = 'https://cdn.paddle.com/paddle/paddle.js';
var PaddleBillingCDNUrl = 'https://cdn.paddle.com/paddle/v2/paddle.js';
var PaddleClassicInfo = {
url: PaddleClassicCDNUrl
};
var PaddleBillingV1Info = {
url: PaddleBillingCDNUrl
};
function findScript(cdnUrl) {
return document.querySelector("script[src=\"".concat(cdnUrl, "\"]")) || undefined;
}
function injectScript(src) {
var script = document.createElement('script');
script.src = src;
var headOrBody = document.head || document.body;
if (!headOrBody) {
throw new Error('Cannot inject Paddle.js. It needs a
or element.');
}
headOrBody.appendChild(script);
return script;
}
var promiseMap = {
classic: undefined,
v1: undefined
};
var VersionToPaddleMap = {
classic: 'PaddleClassic',
v1: 'PaddleBillingV1'
};
function loadFromCDN(version) {
var _getCDNInfoBasedOnVer;
var cdnUrl = (_getCDNInfoBasedOnVer = getCDNInfoBasedOnVersion(version)) === null || _getCDNInfoBasedOnVer === void 0 ? void 0 : _getCDNInfoBasedOnVer.url;
if (!cdnUrl) {
return;
}
// Return promise on re-renders
var existingPromise = promiseMap[version];
var paddleInstanceName = VersionToPaddleMap[version];
if (existingPromise !== undefined) {
return existingPromise;
}
promiseMap[version] = new Promise(function (resolve, reject) {
if (typeof window === 'undefined') {
// Return undefined in a server side environment
resolve(undefined);
return;
}
// Return Paddle instance if it is already initialized
if (window[paddleInstanceName] || window.Paddle) {
resolve(window[paddleInstanceName] || window.Paddle);
return;
}
try {
// Inject if paddle.js script tag is not found
var script = findScript(cdnUrl);
if (!script) {
script = injectScript(cdnUrl);
}
// Wait for `load` event before returning
script.addEventListener('load', function () {
if (window[paddleInstanceName] || window.Paddle) {
resolve(window[paddleInstanceName] || window.Paddle);
} else {
reject(new Error('Paddle.js not available'));
}
});
// Show an error if loading fails
script.addEventListener('error', function () {
reject(new Error("Failed to load Paddle.js - ".concat(version)));
});
} catch (error) {
reject(error);
return;
}
});
return promiseMap[version];
}
function getCDNInfoBasedOnVersion(version) {
if (version === Versions.CLASSIC) {
return PaddleClassicInfo;
}
if (version === Versions.V1) {
return PaddleBillingV1Info;
} else {
console.error('[Paddle] Unknown Paddle Version');
return;
}
}
var _excluded = ["environment", "version"],
_excluded2 = ["environment", "version"];
function initializePaddleBillingV1(options, paddle) {
var environment = options.environment;
options.version;
var rest = _objectWithoutProperties(options, _excluded);
try {
if (environment) {
paddle.Environment.set(environment);
}
if (paddle.Initialized) {
paddle.Update(_objectSpread2({}, rest));
} else {
paddle.Initialize(_objectSpread2({}, rest));
}
} catch (e) {
console.warn('[Paddle] Paddle Initialization failed. Please check the inputs', e);
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function initializePaddleClassic(options, paddle) {
var environment = options.environment;
options.version;
var rest = _objectWithoutProperties(options, _excluded2);
try {
if (environment) {
paddle.Environment.set(environment);
}
paddle.Setup(_objectSpread2({}, rest));
} catch (e) {
console.warn('[Paddle] Paddle Initialization failed. Please check the inputs', e);
}
}
// Note: The enums in this file is only for `src`. Typescript will also need it added to the `types` directory for usage.
var CheckoutEventNames;
(function (CheckoutEventNames) {
CheckoutEventNames["CHECKOUT_LOADED"] = "checkout.loaded";
CheckoutEventNames["CHECKOUT_CLOSED"] = "checkout.closed";
CheckoutEventNames["CHECKOUT_UPDATED"] = "checkout.updated";
CheckoutEventNames["CHECKOUT_COMPLETED"] = "checkout.completed";
CheckoutEventNames["CHECKOUT_ERROR"] = "checkout.error";
CheckoutEventNames["CHECKOUT_FAILED"] = "checkout.failed";
CheckoutEventNames["CHECKOUT_ITEMS_UPDATED"] = "checkout.items.updated";
CheckoutEventNames["CHECKOUT_ITEMS_REMOVED"] = "checkout.items.removed";
CheckoutEventNames["CHECKOUT_CUSTOMER_CREATED"] = "checkout.customer.created";
CheckoutEventNames["CHECKOUT_CUSTOMER_UPDATED"] = "checkout.customer.updated";
CheckoutEventNames["CHECKOUT_CUSTOMER_REMOVED"] = "checkout.customer.removed";
CheckoutEventNames["CHECKOUT_PAYMENT_SELECTED"] = "checkout.payment.selected";
CheckoutEventNames["CHECKOUT_PAYMENT_INITIATED"] = "checkout.payment.initiated";
CheckoutEventNames["CHECKOUT_PAYMENT_FAILED"] = "checkout.payment.failed";
CheckoutEventNames["CHECKOUT_DISCOUNT_APPLIED"] = "checkout.discount.applied";
CheckoutEventNames["CHECKOUT_DISCOUNT_REMOVED"] = "checkout.discount.removed";
})(CheckoutEventNames || (CheckoutEventNames = {}));
var CheckoutEventsTimePeriodInterval;
(function (CheckoutEventsTimePeriodInterval) {
CheckoutEventsTimePeriodInterval["DAY"] = "day";
CheckoutEventsTimePeriodInterval["WEEK"] = "week";
CheckoutEventsTimePeriodInterval["MONTH"] = "month";
CheckoutEventsTimePeriodInterval["YEAR"] = "year";
})(CheckoutEventsTimePeriodInterval || (CheckoutEventsTimePeriodInterval = {}));
var CheckoutEventsPaymentMethodTypes;
(function (CheckoutEventsPaymentMethodTypes) {
CheckoutEventsPaymentMethodTypes["ALIPAY"] = "alipay";
CheckoutEventsPaymentMethodTypes["APPLE_PAY"] = "apple-pay";
CheckoutEventsPaymentMethodTypes["CARD"] = "card";
CheckoutEventsPaymentMethodTypes["GOOGLE_PAY"] = "google-pay";
CheckoutEventsPaymentMethodTypes["IDEAL"] = "ideal";
CheckoutEventsPaymentMethodTypes["PAYPAL"] = "paypal";
CheckoutEventsPaymentMethodTypes["WIRE_TRANSFER"] = "wire-transfer";
CheckoutEventsPaymentMethodTypes["NONE"] = "none";
})(CheckoutEventsPaymentMethodTypes || (CheckoutEventsPaymentMethodTypes = {}));
var CheckoutEventsPaymentMethodCardTypes;
(function (CheckoutEventsPaymentMethodCardTypes) {
CheckoutEventsPaymentMethodCardTypes["AMERICAN_EXPRESS"] = "american_express";
CheckoutEventsPaymentMethodCardTypes["DINERS_CLUB"] = "diners_club";
CheckoutEventsPaymentMethodCardTypes["DISCOVER"] = "discover";
CheckoutEventsPaymentMethodCardTypes["JCB"] = "jcb";
CheckoutEventsPaymentMethodCardTypes["MADA"] = "mada";
CheckoutEventsPaymentMethodCardTypes["MAESTRO"] = "maestro";
CheckoutEventsPaymentMethodCardTypes["MASTER_CARD"] = "mastercard";
CheckoutEventsPaymentMethodCardTypes["UNION_PAY"] = "union_pay";
CheckoutEventsPaymentMethodCardTypes["VISA"] = "visa";
CheckoutEventsPaymentMethodCardTypes["UNKNOWN"] = "unknown";
})(CheckoutEventsPaymentMethodCardTypes || (CheckoutEventsPaymentMethodCardTypes = {}));
var CheckoutEventsStatus;
(function (CheckoutEventsStatus) {
CheckoutEventsStatus["DRAFT"] = "draft";
CheckoutEventsStatus["READY"] = "ready";
CheckoutEventsStatus["COMPLETED"] = "completed";
CheckoutEventsStatus["BILLED"] = "billed";
CheckoutEventsStatus["canceled"] = "canceled";
CheckoutEventsStatus["PAST_DUE"] = "past_due";
})(CheckoutEventsStatus || (CheckoutEventsStatus = {}));
function initializePaddle(_x) {
return _initializePaddle.apply(this, arguments);
}
function _initializePaddle() {
_initializePaddle = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(options) {
var requestedVersion, paddle;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
requestedVersion = (options === null || options === void 0 ? void 0 : options.version) || DefaultVersion;
_context.next = 3;
return loadFromCDN(requestedVersion);
case 3:
paddle = _context.sent;
if (!paddle) {
_context.next = 9;
break;
}
if (options) {
if (requestedVersion === Versions.V1) {
initializePaddleBillingV1(options, paddle);
} else if (requestedVersion === Versions.CLASSIC) {
initializePaddleClassic(options, paddle);
}
}
return _context.abrupt("return", paddle);
case 9:
console.error('[Paddle] Error Loading Paddle');
return _context.abrupt("return");
case 11:
case "end":
return _context.stop();
}
}, _callee);
}));
return _initializePaddle.apply(this, arguments);
}
function getPaddleInstance() {
var version = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : DefaultVersion;
if (version === Versions.V1) {
return window.PaddleBillingV1 || window.Paddle;
} else if (version === Versions.CLASSIC) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return window.PaddleClassic || window.Paddle;
} else {
console.error('[Paddle] Unknown Paddle Version');
return;
}
}
/***/ }),
/***/ 243:
/***/ ((module) => {
module.exports = ""
/***/ }),
/***/ 7202:
/***/ ((module) => {
module.exports = ""
/***/ }),
/***/ 6222:
/***/ ((module) => {
module.exports = ""
/***/ }),
/***/ 8945:
/***/ ((module) => {
module.exports = ""
/***/ }),
/***/ 4144:
/***/ ((module) => {
module.exports = ""
/***/ }),
/***/ 1615:
/***/ ((module) => {
module.exports = ""
/***/ }),
/***/ 9038:
/***/ ((module) => {
module.exports = ""
/***/ }),
/***/ 1133:
/***/ ((module) => {
module.exports = ""
/***/ }),
/***/ 2588:
/***/ ((module) => {
module.exports = ""
/***/ }),
/***/ 4827:
/***/ ((module) => {
module.exports = ""
/***/ }),
/***/ 2858:
/***/ ((module) => {
module.exports = ""
/***/ }),
/***/ 2672:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ApiClient = void 0;
exports.toApiError = toApiError;
const axios_1 = __webpack_require__(6425);
const invoke_1 = __webpack_require__(9927);
class ApiClient {
/**
* Creates new user account and sends SMS access code.
* @throws
* - **409** Email is already registered
* - **400** Invalid email, password or country_code
* - **429** Too many failed request attempts
* - **500** Unhandled server error
*/
register(request) {
const { recaptchaToken } = request, data = __rest(request, ["recaptchaToken"]);
return (0, invoke_1.invoke)({
method: "POST",
url: "/v1/auth/register",
data,
headers: {
"X-Recaptcha-Token": recaptchaToken,
},
responseCodes: {
200: "OK",
409: "Email is already registered",
400: {
"clientName.invalid": "Invalid X-Client-Name header",
"clientName.missing": "Missing X-Client-Name header",
"": "Invalid email, password or country_code",
},
401: {
"recaptcha.token.invalid": "Invalid reCaptcha token (X-Recaptcha-Token header) OR Invalid reCaptcha action (not REGISTER)",
"recaptcha.token.missing": "Missing reCaptcha token (X-Recaptcha-Token header)",
},
429: "Too many failed request attempts",
500: "Unhandled server error",
},
});
}
/**
* Finds user account and sends SMS access code.
* @param email User's email
* @param password Strong password, must comply with Janrain settings
* @throws
* - **400** Invalid email or password
* - **429** Too many failed request attempts
* - **500** Unhandled server error
**/
login(request) {
const { recaptchaToken } = request, data = __rest(request, ["recaptchaToken"]);
return (0, invoke_1.invoke)({
method: "POST",
url: "/v3/auth/login",
data,
headers: {
"x-recaptcha-token": recaptchaToken,
},
responseCodes: {
200: "OK",
400: {
"clientName.invalid": "Invalid X-Client-Name header",
"clientName.missing": "Missing X-Client-Name header",
"": "Invalid email or password",
},
401: {
"recaptcha.token.invalid": "Invalid reCaptcha token (X-Recaptcha-Token header) OR Invalid reCaptcha action (not LOGIN)",
"recaptcha.token.missing": "Missing reCaptcha token (X-Recaptcha-Token header)",
},
429: "Too many failed request attempts",
500: "Unhandled server error",
},
});
}
// /**
// * Provide email address in URL parameter to check if it was registered already.
// * @throws
// * - **404** Email not found
// * - **429** Too many failed request attempts
// * - **500** Unhandled server error
// */
// registrationCheck(request: RegistrationCheckRequest): Promise {
// return invoke({
// method: "GET",
// url: "/v1/auth/registrationCheck",
// data: request,
// responseCodes: {
// 200: "Email is registered",
// 404: "Email not found",
// 429: "Too many failed request attempts",
// 500: "Unhandled server error",
// },
// })
// }
// /**
// * Returns a Firebase custom token for a specific user. Only available to Admin accounts.
// * @throws
// * - **400** Invalid verification code
// * - **403** Requesting user does not have Admin permissions
// * - **429** Too many failed request attempts
// * - **500** Unhandled server error
// **/
// impersonate(request: ImpersonateRequest): Promise {
// return invoke({
// method: "POST",
// url: "/v1/auth/impersonate",
// data: request,
// responseCodes: {
// 200: "OK",
// 400: "Invalid consumer ID, or invalid account ID, or both are supplied at the same time",
// 403: "Requesting user does not have Admin permissions",
// 429: "Too many failed request attempts",
// 500: "Unhandled server error",
// },
// })
// }
/**
* Returns Firebase auth token in exchange for SMS access code.
* @param verification_code 6-digit SMS code. For development purposes always "861789"
* @throws
* - **400** Invalid verification code
* - **429** Too many failed request attempts
* - **500** Unhandled server error
**/
twoFactorVerify(request) {
return (0, invoke_1.invoke)({
method: "POST",
url: "/v1/auth/twoFactorVerify",
data: request,
responseCodes: {
200: "OK",
400: "Invalid verification code",
429: "Too many failed request attempts",
500: "Unhandled server error",
},
});
}
/**
* Sends a new SMS access code
* @throws
* - **429** Too many failed request attempts
* - **500** Unhandled server error
**/
twoFactorResend() {
return (0, invoke_1.invoke)({
method: "POST",
url: "/v1/auth/twoFactorResend",
data: {},
responseCodes: {
200: "OK",
429: "Too many failed request attempts",
500: "Unhandled server error",
},
});
}
/**
* Allows to set a new phone number for SMS verification.
* @throws
* - **404** Phone number not provided or not found in Janrain
* - **409** Two-factor auth is already configured for this account.
* - **429** Too many failed request attempts
* - **500** Unhandled server error
**/
twoFactorSetup(request) {
return (0, invoke_1.invoke)({
method: "POST",
url: "/v1/auth/twoFactorSetup",
data: request,
responseCodes: {
200: "OK",
404: "Phone number not provided or not found in Janrain",
409: "Two-factor auth is already configured for this account.",
429: "Too many failed request attempts",
500: "Unhandled server error",
},
});
}
/**
* Completes two factor verification setup and returns Firebase auth token.
* @param verification_code 6-digit SMS code. For development purposes always "861789"
* @throws
* - **400** Incorrect verification code
* - **429** Too many failed request attempts
* - **500** Unhandled server error
* */
twoFactorCompleteSetup(request) {
return (0, invoke_1.invoke)({
method: "POST",
url: "/v1/auth/twoFactorCompleteSetup",
data: request,
responseCodes: {
200: "OK",
400: "Incorrect verification code",
429: "Too many failed request attempts",
500: "Unhandled server error",
},
});
}
initiatePhoneReset(req) {
return (0, invoke_1.invoke)({
method: "POST",
url: "/v1/auth/initiatePhoneReset",
data: req,
responseCodes: {
200: "Email was sent, or account was not found",
500: "Unhandled server error",
},
});
}
completePhoneReset(req) {
return (0, invoke_1.invoke)({
method: "PUT",
url: "/v1/auth/phone",
data: req,
responseCodes: {
200: "New phone was set",
400: "Phone is invalid",
403: "Authorization code is expired or invalid",
500: "Unhandled server error",
},
});
}
forgotPassword(_a) {
var { locale } = _a, data = __rest(_a, ["locale"]);
return (0, invoke_1.invoke)({
method: "POST",
url: "/v1/auth/forgotPassword",
headers: {
"x-locale": locale,
},
data,
responseCodes: {
200: "Email was sent, or account was not found",
500: "Unhandled server error",
},
});
}
completeForgotPassword(req) {
return (0, invoke_1.invoke)({
method: "PUT",
url: "/v1/auth/password",
data: req,
responseCodes: {
200: "New password was set",
400: "Password does not match the requirements",
403: "Authorization code is expired or invalid",
500: "Unhandled server error",
},
});
}
optin({ consumerId }) {
return (0, invoke_1.invoke)({
method: "POST",
url: `/v2/auth/user/${consumerId}/optin`,
responseCodes: {
204: "OK",
/**
* {
* "message": "The requested entity was not found",
* "reason": "entity.id.notFound"
* }
*/
404: "Double opt-in expired",
},
});
}
registerLead(req) {
if (req.answers) {
delete req.segmantaSessionId;
return this.registerLeadWithoutSegmanta(req);
}
delete req.answers;
return this.registerLeadWithSegmanta(req);
}
registerLeadWithSegmanta(_a) {
var { recaptchaToken } = _a, data = __rest(_a, ["recaptchaToken"]);
return (0, invoke_1.invoke)({
method: "POST",
url: `/v3/auth/register/lead`,
headers: {
"X-Recaptcha-Token": recaptchaToken,
},
data,
responseCodes: {
200: "OK",
201: "OK", // record was created
400: "Validation Error",
401: "Unauthorized",
// 404 The Segmanta session ID was not found.
// That could mean that the webhook was rejected or it didn't reach us.
// Normally, client should make several retries and fall back to the scenario when the user should register from a scratch
// {
// "message": "Segmanta session not found",
// "reason": "segmantaSession.notFound"
// }
404: "Not found",
409: "Conflict",
422: "Unprocessable Content",
},
});
}
registerLeadWithoutSegmanta(_a) {
var { recaptchaToken } = _a, data = __rest(_a, ["recaptchaToken"]);
return (0, invoke_1.invoke)({
method: "PUT",
url: `/v3/auth/register/lead/v5`,
headers: {
"X-Recaptcha-Token": recaptchaToken,
},
data,
responseCodes: {
200: "OK",
201: "OK", // record was created
400: "Validation Error",
401: "Unauthorized",
// 404 The Segmanta session ID was not found.
// That could mean that the webhook was rejected or it didn't reach us.
// Normally, client should make several retries and fall back to the scenario when the user should register from a scratch
// {
// "message": "Segmanta session not found",
// "reason": "segmantaSession.notFound"
// }
404: "Not found",
409: "Conflict",
422: "Unprocessable Content",
},
});
}
supportedCountries() {
return (0, invoke_1.invoke)({
method: "GET",
url: "/v2/auth/supportedCountries",
responseCodes: {
200: "OK",
},
});
}
terms({ countryCode, languageCode }) {
return (0, invoke_1.invoke)({
method: "GET",
url: `/v2/auth/terms/country/${countryCode}/language/${languageCode}`,
responseCodes: {
201: "OK",
400: "Validation Error",
},
});
}
onboarding(_a) {
var { accountId } = _a, data = __rest(_a, ["accountId"]);
return (0, invoke_1.invoke)({
method: "POST",
url: `/v2/questionnaires/users/${accountId}/ONBOARDING/v5/`,
data,
responseCodes: {
201: "OK",
},
});
}
getSubscription({ consumerId }) {
return (0, invoke_1.invoke)({
method: "GET",
url: `/v1/payments/consumers/${consumerId}/subscriptions/paddle`,
});
}
setSubscription(_a) {
var { consumerId } = _a, data = __rest(_a, ["consumerId"]);
return (0, invoke_1.invoke)({
method: "PUT",
url: `/v1/payments/consumers/${consumerId}/subscriptions/paddle`,
data,
});
}
updateSubscription(_a) {
var { consumerId } = _a, data = __rest(_a, ["consumerId"]);
return (0, invoke_1.invoke)({
method: "PATCH",
url: `/v1/payments/consumers/${consumerId}/subscriptions/paddle`,
data,
});
}
/**
* For LEAD accounts refreshes OTP and returns the necessary data to create Paddle subscription.
* Accounts in a non-LEAD state are treated as not found (404).
*/
refreshToken(_a) {
var { token, recaptchaToken } = _a, data = __rest(_a, ["token", "recaptchaToken"]);
return (0, invoke_1.invoke)({
method: "POST",
url: `/v3/auth/registration/${token}/refresh`,
data,
headers: {
"X-Recaptcha-Token": recaptchaToken,
},
});
}
}
exports.ApiClient = ApiClient;
function toApiError(err) {
var _a;
if ((0, axios_1.isAxiosError)(err)) {
const err2 = (_a = err.response) === null || _a === void 0 ? void 0 : _a.data;
if (err2) {
return err2;
}
}
return {};
}
/***/ }),
/***/ 9927:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.invoke = invoke;
exports.invoke2 = invoke2;
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-empty-function */
/* eslint-disable @typescript-eslint/no-var-requires */
const axios_1 = __importDefault(__webpack_require__(6425));
const config_1 = __webpack_require__(7028);
const auth_1 = __webpack_require__(2220);
const firebase_1 = __webpack_require__(51);
const base = config_1.config.apiUrl;
const LocalTimeZone = (() => {
try {
return Intl.DateTimeFormat().resolvedOptions().timeZone;
}
catch (_a) {
return undefined;
}
})();
const storage = typeof localStorage !== "undefined" ? localStorage : { getItem() { }, setItem() { } };
let DeviceID = storage["deviceId"];
if (!DeviceID) {
DeviceID = crypto.randomUUID();
storage["deviceId"] = DeviceID;
}
function getAuthToken() {
if (firebase_1.firebaseUser) {
return firebase_1.firebaseUser.getIdToken();
}
return (0, auth_1.getAuth)();
}
function invoke(req) {
return __awaiter(this, void 0, void 0, function* () {
const res = yield invoke2(req);
return res.data;
});
}
function invoke2(_a) {
return __awaiter(this, arguments, void 0, function* ({ method, url, data, headers, base: base2, validateStatus, }) {
url = `${base2 !== null && base2 !== void 0 ? base2 : base}${url}`;
const auth = yield getAuthToken();
const req = Object.assign(Object.assign({ method,
url }, (validateStatus ? { validateStatus } : {})), { data, headers: Object.assign({ "Content-Type": "application/json", Authorization: auth ? `Bearer ${auth}` : undefined, access_token: config_1.config.apiAccessToken || undefined, "X-Client-Name": "SSC-website", DeviceID, DeviceType: "browser", LocalTimeZone, "X-Client-Version": "1.0.1", "X-Request-ID": crypto.randomUUID(), "X-Request-Time": new Date().toJSON() }, headers) });
console.log(req);
const res = yield (0, axios_1.default)(req);
// if (res.status !== 200) {
// const msg = responseCodes?.[res.status]
// ? `${responseCodes?.[res.status]} (code: ${res.status})`
// : `Unhandled server error ${res.status}`
// console.warn(method, url, data, msg, res.data)
// throw new Error(msg)
// }
console.log(res.data);
if (res.data.token) {
(0, auth_1.setAuth)(res.data.token);
}
return res;
});
}
/***/ }),
/***/ 9358:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.api2 = exports.Api2Client = void 0;
const axios_1 = __importDefault(__webpack_require__(6425));
const config_1 = __webpack_require__(7028);
const apiInfo_1 = __webpack_require__(4187);
/**
* SSC API Endpoints
* Ecaas API
* Allows managing accounts on Janrain and BC
**/
class Api2Client {
login(req) {
return invoke(apiInfo_1.apiInfo.login, req);
}
register(req) {
return invoke(apiInfo_1.apiInfo.register, req);
}
forgotPassword(req) {
return invoke(apiInfo_1.apiInfo.forgotPassword, req);
}
resetPassword(req) {
return invoke(apiInfo_1.apiInfo.resetPassword, req);
}
updateProfile(req) {
return invoke(apiInfo_1.apiInfo.updateProfile, req);
}
updatePassword(req) {
return invoke(apiInfo_1.apiInfo.updatePassword, req);
}
updatePhoneNumber(req) {
return invoke(apiInfo_1.apiInfo.updatePhoneNumber, req);
}
setPhoneNumber(req) {
return invoke(apiInfo_1.apiInfo.setPhoneNumber, req);
}
updatePhoneNative(req) {
return invoke(apiInfo_1.apiInfo.updatePhoneNative, req);
}
submitReview(req) {
return invoke(apiInfo_1.apiInfo.submitReview, req);
}
updateJanrainBmtTrait(req) {
return invoke(apiInfo_1.apiInfo.updateJanrainBmtTrait, req);
}
janrainEmailCheck(req) {
return invoke(apiInfo_1.apiInfo.janrainEmailCheck, req);
}
getCustomerJanrainAttributesFromBigC() {
return invoke(apiInfo_1.apiInfo.getCustomerJanrainAttributesFromBigC);
}
getReviews(req) {
return invoke({
method: "GET",
endpoint: `${config_1.config.bazaarvoiceUrl}/data/reviews.json`,
}, null, verifyBazaarvoiceRequest(req));
}
getStats(req) {
return invoke({
method: "GET",
endpoint: `${config_1.config.bazaarvoiceUrl}/data/statistics.json`,
}, null, verifyBazaarvoiceRequest(req));
}
}
exports.Api2Client = Api2Client;
function verifyBazaarvoiceRequest(req) {
if (!req.apiversion) {
req.apiversion = "5.4";
}
if (!req.passkey) {
req.passkey = config_1.config.bazaarvoicePasskey;
}
return req;
}
function invoke(info, data, params) {
return __awaiter(this, void 0, void 0, function* () {
const res = yield (0, axios_1.default)({
method: info.method,
url: info.endpoint,
headers: info.headers,
data,
params,
});
return res.data;
});
}
exports.api2 = new Api2Client();
/***/ }),
/***/ 4187:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.apiInfo = void 0;
const config_1 = __webpack_require__(7028);
exports.apiInfo = {
login: {
method: "POST",
endpoint: "https://ecaas-services-stage.azure-api.net/account/authenticate",
headers: {
"Content-Type": "application/json",
},
},
register: {
method: "POST",
endpoint: "https://ecaas-services.azure-api.net/account/create",
headers: {
"Content-Type": "application/json",
},
},
forgotPassword: {
method: "POST",
endpoint: "https://ecaas-services.azure-api.net/account/forgot-password",
headers: {
"Content-Type": "application/json",
},
},
resetPassword: {
method: "POST",
endpoint: "https://ecaas-services.azure-api.net/account/reset-password",
headers: {
"Content-Type": "application/json",
},
},
updateProfile: {
method: "POST",
endpoint: "https://ecaas-services.azure-api.net/account/update",
headers: {
"Content-Type": "application/json",
},
},
updatePassword: {
method: "POST",
endpoint: "https://ecaas-services.azure-api.net/account/update-password",
headers: {
"Content-Type": "application/json",
},
},
updatePhoneNumber: {
method: "POST",
endpoint: "https://px-lumi-bigcommerce-np.azure-api.net/change-phone-number/oauth/forgot_password_native",
headers: {
"Content-Type": "application/json",
},
},
setPhoneNumber: {
method: "POST",
endpoint: "https://px-lumi-bigcommerce-np.azure-api.net/change-phone-number/oauth/forgot_password_native",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
},
updatePhoneNative: {
method: "POST",
endpoint: "https://px-lumi-bigcommerce.azure-api.net/change-phone-number/oauth/token",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
},
getCustomerJanrainAttributesFromBigC: {
method: "GET",
endpoint: "https://px-lumi-bigcommerce.azure-api.net/api/stores/pvhrvuxqgv/v3/customers/attribute-values",
headers: {
"Content-Type": "application/json",
"X-Auth-Token": "authToken",
"Ocp-Apim-Subscription-Key": "{APIMSubscriptionKey}",
},
},
submitReview: {
method: "POST",
endpoint: `${config_1.config.bazaarvoiceUrl}/data/submitreview.json`,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
},
updateJanrainBmtTrait: {
method: "POST",
endpoint: "https://px-lumi-bigcommerce.azure-api.net/janrain-consumer-profile/",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Ocp-Apim-Subscription-Key": "{apimSubscriptionKey}",
},
},
janrainEmailCheck: {
method: "POST",
endpoint: "https://px-lumi-bigcommerce.azure-api.net/janrain-entity-find",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Ocp-Apim-Subscription-Key": "{APIMSubscriptionKey}",
},
},
};
/***/ }),
/***/ 5022:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const consts_1 = __webpack_require__(8066);
const auth_1 = __webpack_require__(2220);
const autoStopVideoPlaybacks_1 = __webpack_require__(894);
const counter_1 = __webpack_require__(1700);
const detect_1 = __webpack_require__(957);
const env_1 = __webpack_require__(3143);
const getGeoFeed_1 = __webpack_require__(7539);
const getTerms_1 = __webpack_require__(1741);
const onetrust_1 = __webpack_require__(9312);
const pgDataLayer_1 = __webpack_require__(7350);
const segment_1 = __webpack_require__(1685);
const toggle_1 = __webpack_require__(2166);
const togglePassword_1 = __webpack_require__(5391);
const user_1 = __webpack_require__(6441);
const blog_1 = __webpack_require__(7839);
const blogArticle_1 = __webpack_require__(4237);
const blogCategory_1 = __webpack_require__(3207);
const blogContributor_1 = __webpack_require__(8294);
const cancelFlow_1 = __webpack_require__(9101);
const changePhone1_1 = __webpack_require__(2072);
const changePhone2_1 = __webpack_require__(8873);
const doubleOptin_1 = __webpack_require__(78);
const finalizeAccount_1 = __webpack_require__(5986);
const fullSurvey_1 = __webpack_require__(6740);
const login1_1 = __webpack_require__(6263);
const login2_1 = __webpack_require__(1634);
const manageSubscriptionAccount_1 = __webpack_require__(9562);
const manageSubscriptionSignIn_1 = __webpack_require__(239);
const manageSubscriptionSignInVerify_1 = __webpack_require__(9630);
const masterTheChaos_1 = __webpack_require__(5304);
const masterTheChaosConfirmation_1 = __webpack_require__(4137);
const otpEndingPagePaddleCheckout_1 = __webpack_require__(1626);
const paymentLink_1 = __webpack_require__(6253);
const question_1 = __webpack_require__(6199);
const register1_1 = __webpack_require__(8251);
const register2_1 = __webpack_require__(4377);
const resetPassword1_1 = __webpack_require__(9854);
const resetPassword2_1 = __webpack_require__(9955);
const reviews_1 = __webpack_require__(8182);
const sleepAssessment_1 = __webpack_require__(4362);
const surveyEndingPage_1 = __webpack_require__(6345);
const termsOfUse_1 = __webpack_require__(8090);
const welcomeSurvey_1 = __webpack_require__(2125);
console.log("main");
(0, detect_1.detect)();
void (0, segment_1.addUserIdToPgDataLayer)();
hookUpGtmEvents();
(0, segment_1.hookUpSegmentEvents)();
hookUpPages();
setH2ScrollToMid();
switchToRelativeUrlsOnStaging();
makeTablesScrollable();
(0, togglePassword_1.togglePassword)();
hookUpSignInSignOut();
void replaceFooterLinks();
void (0, counter_1.counter)();
(0, autoStopVideoPlaybacks_1.autoStopVideoPlaybacks)();
function hookUpPages() {
console.log("hookUpPages");
const path = location.pathname;
if (path === consts_1.paths.register1) {
void (0, register1_1.register1)();
}
if (path === consts_1.paths.register2) {
(0, register2_1.register2)();
}
if (path === consts_1.paths.login1) {
(0, login1_1.login1)();
}
if (path === consts_1.paths.login2) {
(0, login2_1.login2)();
}
if (path === consts_1.paths.changePhone1) {
(0, changePhone1_1.changePhone1)();
}
if (path === consts_1.enPaths.changePhone2 && navigator.language.startsWith("es")) {
location.href = consts_1.esPaths.changePhone2;
return;
}
if (path === consts_1.paths.changePhone2) {
void (0, changePhone2_1.changePhone2)();
}
if (path === consts_1.paths.reviews) {
void (0, reviews_1.reviews)();
}
if (path === consts_1.paths.welcomeSurvey) {
void (0, welcomeSurvey_1.welcomeSurvey)();
}
if (path === consts_1.paths.resetPassword1) {
(0, resetPassword1_1.resetPassword1)();
}
if (path === consts_1.enPaths.resetPassword2 && navigator.language.startsWith("es")) {
location.href = consts_1.esPaths.resetPassword2 + document.location.search;
return;
}
if (path === consts_1.paths.resetPassword2) {
(0, resetPassword2_1.resetPassword2)();
}
if (path === consts_1.paths.blog) {
(0, blog_1.blog)();
}
if (path === consts_1.paths.doubleOptin) {
void (0, doubleOptin_1.doubleOptin)();
}
if (path === consts_1.paths.finalizeAccount) {
void (0, finalizeAccount_1.finalizeAccount)();
}
if (path === consts_1.paths.fullSurvey || path === consts_1.paths.fullSurvey2025) {
void (0, fullSurvey_1.fullSurvey)();
}
if (path === consts_1.paths.cancelFlow) {
void (0, cancelFlow_1.cancelFlow)();
}
if (path === consts_1.paths.manageSubscriptionSignIn) {
void (0, manageSubscriptionSignIn_1.manageSubscriptionSignIn)();
}
if (path === consts_1.paths.manageSubscriptionSignInVerify) {
(0, manageSubscriptionSignInVerify_1.manageSubscriptionSignInVerify)();
}
if (path === consts_1.paths.manageSubscriptionAccount) {
void (0, manageSubscriptionAccount_1.manageSubscriptionAccount)();
}
if (path === consts_1.paths.paymentLink) {
void (0, paymentLink_1.paymentLink)();
}
if (path === consts_1.paths.termsOfUse) {
void (0, termsOfUse_1.termsOfUse)();
}
if (path === consts_1.paths.masterTheChaos) {
void (0, masterTheChaos_1.masterTheChaos)();
}
if (path === consts_1.paths.masterTheChaosConfirmation) {
void (0, masterTheChaosConfirmation_1.masterTheChaosConfirmation)();
}
if (consts_1.paths.otpEndingPages.test(path)) {
void (0, otpEndingPagePaddleCheckout_1.otpEndingPagePaddleCheckout)();
}
if (consts_1.paths.surveyEndingPage.test(path)) {
(0, surveyEndingPage_1.surveyEndingPage)();
}
if (consts_1.paths.blogCategory.test(path)) {
(0, blogCategory_1.blogCategory)();
}
if (consts_1.paths.blogContributor.test(path)) {
(0, blogContributor_1.blogContributor)();
}
if (consts_1.paths.blogArticle.test(path)) {
(0, blogArticle_1.blogArticle)();
}
if (consts_1.paths.sleepAssessment.test(path)) {
void (0, sleepAssessment_1.sleepAssessment)();
}
// if (path === paths.surveyEndingPageMetaMain) {
// surveyEndingPageMetaMain()
// }
(0, question_1.question)();
}
// function surveyEndingPageMetaMain() {
// console.log("surveyEndingPageMetaMain")
// document.querySelectorAll("a").forEach(a => {
// if (a.href.includes("app.adjust.com")) {
// const btn = document.createElement("button")
// btn.type = "button"
// btn.textContent = a.textContent
// btn.addEventListener("touchend", () => {
// window.open(a.href, "_blank")
// })
// a.parentElement!.insertBefore(btn, a)
// const btn2 = document.createElement("button")
// btn2.type = "button"
// btn2.textContent = a.textContent
// btn2.addEventListener("click", () => {
// window.open(a.href, "_blank")
// })
// a.parentElement!.insertBefore(btn2, a)
// }
// })
// }
function triggerGtmAndTiktokEvent(category, action, label) {
(0, pgDataLayer_1.dataLayerPush)(category, action, label);
// triggerTiktokEvent(category, action, label)
}
function hookupGtmEventsForElement(el, suffix) {
const category = el.getAttribute(`data-category${suffix}`);
const action = el.getAttribute(`data-action${suffix}`);
const label = el.getAttribute(`data-label${suffix}`);
const labelSuffix = el.getAttribute(`data-label-suffix${suffix}`) || "";
// const label = `${label2 ?? ""}${labelSuffix ?? ""}`
const labelSelected = el.getAttribute(`data-label-selected${suffix}`);
const labelDeselected = el.getAttribute(`data-label-deselected${suffix}`);
if (!category && !action && !label && !labelSelected && !labelDeselected) {
return;
}
if (!category || !action || (!label && !labelSelected && !labelDeselected)) {
console.warn("Missing data attributes on element", el);
return;
}
el.addEventListener("click", e => {
if (label) {
triggerGtmAndTiktokEvent(category, action, `${label}${labelSuffix}`);
}
if (!labelSelected && !labelDeselected) {
return;
}
const input = e.target;
// Ignore double events from span and checkboxes
if (!input.matches("input"))
return;
const checked = input.checked;
if (labelSelected && checked) {
triggerGtmAndTiktokEvent(category, action, `${labelSelected}${labelSuffix}`);
}
if (labelDeselected && !checked) {
triggerGtmAndTiktokEvent(category, action, `${labelDeselected}${labelSuffix}`);
}
});
}
function hookUpGtmEvents() {
document.querySelectorAll(".js-event-click").forEach(el => {
hookupGtmEventsForElement(el, "");
hookupGtmEventsForElement(el, "2");
});
}
function setH2ScrollToMid() {
const h2s = document.querySelectorAll("h2:not([data-scroll])");
h2s.forEach(h2 => {
h2.setAttribute("data-scroll", "mid");
});
}
function switchToRelativeUrlsOnStaging() {
if (env_1.env === "prod")
return;
document.querySelectorAll("a").forEach(el => {
const href = el.href;
if (!href.startsWith("https://www.smartsleepcoach.com"))
return;
const newHref = href.replace("https://www.smartsleepcoach.com", "");
console.log("switching to relative url", href, newHref);
el.href = newHref;
});
}
function hookUpSignInSignOut() {
var _a;
(_a = document.querySelector(".signout_link")) === null || _a === void 0 ? void 0 : _a.addEventListener("click", () => {
(0, user_1.setUser)(null);
(0, auth_1.setAuth)(null);
showSignInSignOut();
location.href = "/";
});
showSignInSignOut();
}
function showSignInSignOut() {
const loggedIn = !!(0, user_1.getUser)();
(0, toggle_1.toggle)(".signin_link", !loggedIn);
(0, toggle_1.toggle)(".signout_link", loggedIn);
}
function makeTablesScrollable() {
document.querySelectorAll(".w-richtext table").forEach(el => {
var _a;
(_a = el.closest(".w-embed")) === null || _a === void 0 ? void 0 : _a.classList.add("hscroll");
});
}
function replaceFooterLinks() {
return __awaiter(this, void 0, void 0, function* () {
var _a;
const geofeed = yield (0, getGeoFeed_1.getGeoFeed)();
if (!geofeed)
return;
const terms = yield (0, getTerms_1.getTerms)();
if (!terms)
return;
function replaceLink(selector, newHref) {
if (!newHref)
return;
document.querySelectorAll(selector).forEach(a => {
if (a.href === newHref)
return;
console.debug("Updating href", a.href, newHref);
a.href = newHref;
});
}
(0, toggle_1.toggle)(".footerlinks-notice", geofeed.country === "US" && ["FL", "TX"].includes(geofeed.state));
(0, toggle_1.toggle)(".footerlinks-healthdata", geofeed.country === "US");
(0, toggle_1.toggle)(".footerlinks-donotsell", ["US", "CA"].includes(geofeed.country));
if (geofeed.country === "CA") {
document.querySelectorAll(".footerlinks-donotsell").forEach(el => {
el.innerText = "Opt Out of Targeted Advertising";
});
}
replaceLink(".footerlinks-terms", terms.termsLinks.termsAndConditions.url);
replaceLink(".footerlinks-terms2", terms.termsLinks.termsAndConditions.url);
// replaceLink(".pg-brands", terms.legalLinks.pgBrands)
replaceLink(".footerlinks-cookies", `${terms.legalLinks.privacyPolicy}/#cookies`);
replaceLink(".footerlinks-privacy", terms.legalLinks.privacyPolicy);
if (terms.legalLinks.privacyChoices) {
replaceLink(".footerlinks-privacychoices", terms.legalLinks.privacyChoices);
if (geofeed.continent === "EU") {
document.querySelectorAll(".footerlinks-privacychoices").forEach(el => {
el.innerText = "My Data";
});
}
}
else if (terms.legalLinks.myData) {
replaceLink(".footerlinks-privacychoices", terms.legalLinks.myData);
document.querySelectorAll(".footerlinks-privacychoices").forEach(el => {
el.innerText = "My Data";
});
}
replaceLink(".footerlinks-healthdata", terms.legalLinks.consumerHealthDataPrivacy);
const btnCookieConsent = document.querySelector(".btnOneTrust");
if (!btnCookieConsent)
return;
const countryInfo = onetrust_1.oneTrustCountryInfo[geofeed.country];
(0, toggle_1.toggle)(".btnonetrust-wrap", countryInfo && !["US", "CA", "AU", "NZ"].includes(geofeed.country));
if (!countryInfo)
return;
const cookieConsentText = (_a = onetrust_1.cookieConsentTranslations[`${countryInfo.language} ${countryInfo.country}`]) !== null && _a !== void 0 ? _a : onetrust_1.cookieConsentTranslations[countryInfo.language];
if (!cookieConsentText)
return;
btnCookieConsent.value = cookieConsentText;
});
}
/***/ }),
/***/ 7028:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.planKeys = exports.config = void 0;
const configProd_1 = __webpack_require__(349);
const configStaging_1 = __webpack_require__(2663);
const env_1 = __webpack_require__(3143);
exports.config = env_1.env === "prod" ? configProd_1.configProd : env_1.env === "dev" ? configStaging_1.configDev : configStaging_1.configStaging; //configDev
exports.planKeys = ["_1month", "_3months", "_12months"];
/***/ }),
/***/ 349:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.configProd = void 0;
const singleGtm = true; // location.search.includes("pocGTM")
exports.configProd = {
// apiUrl: "https://api.pg.com/innovationmanagement/testing/v1/lumimobileapp",
apiUrl: "https://api.gcp.pgcloud.com/brandbuilding/consumer/ssc",
apiAccessToken: "COkNZsoFBGjXTwTX4qEhiBchdobLzE8wyf7jV7AW1TWbiGOQ",
bazaarvoicePasskey: "cadk6wNM1YU5pfEoaaeXZXUzcRLl9wLx6SdCYaaVHTZdA",
bazaarvoiceUrl: "https://api.bazaarvoice.com",
bazaarvoiceProductId: "Pampers_SSC_SmartSleepCoachSubscription",
starsUrl: "https://store-pvhrvuxqgv.mybigcommerce.com/content/img/stars/",
pgSiteEnvironment: "Prod",
pgGoogleAnalyticsLocal: "UA-4805734-181",
pgGoogleAnalyticsReportingView: "193263390",
pgConsentOverlayID: "b3fb142f-1dfb-4159-8e77-48576bc3bc61",
pgFacebookRemarketingID: "1167152113492400",
pgSegment: "r8XGrCquIqVYMkWRxeYyh843bWuyoGC4",
recaptchaSiteKey: "6Ld_PN8nAAAAAMfXhAFfAosf4UwlDfXYJ3mUMw8G",
// new: gtmId: "GTM-TMLVZWQ8", //"GTM-N94XXFB",
gtmId: singleGtm ? "GTM-PQB4L4QL" : "GTM-TMLVZWQ8",
enableGeoFeed: true,
paddleEnvironment: undefined, // when not set it's production
paddleToken: "live_1e2d95f59f794b8540939ef349c",
paddlePriceId: "pri_01j91hz4jkn33pbn03vnagn2xh",
paddlePriceIds: {
_1month: "pri_01jayr6xsest2451mty3zs5dqa",
_3months: "pri_01jayra83vk8cfatnx81202reg",
_12months: "pri_01j91hz4jkn33pbn03vnagn2xh",
},
paddlePriceIdSets: {
dst6: {
_1month: "pri_01jjkn25q192ez2r82snz507p4",
_3months: "pri_01jjkn4h1vwh8e87g426whddk5",
_12months: "pri_01jjkn0a67zr1wryxrh869avjs",
},
bsnt: {
_1month: "pri_01jjkn6zkm4g2nfyxknsqp0783",
_3months: "pri_01jjkn7nc2zd8at2s58hwyy1rs",
_12months: "pri_01jjkn5zvexm0jwjtfj33t72tm",
},
fst: {
_1month: "pri_01jkan9wsaydr09kep3xyxymk0",
_3months: "pri_01jkanar8qe7yt1p2jm8cse7ha",
_12months: "pri_01jkanbgw57rx3s6hedd187bhr",
},
hmnz: {
_1month: "pri_01jt3n713ryee7b9ac64pwxdet",
_3months: "pri_01jt3n5hgpt6fg0w137g1bns8d",
_12months: "pri_01jt3n3zdy3bqfn3d90jvqr53x",
},
},
paddlePortalUrl: "https://customer-portal.paddle.com/login/cpl_01j0qwvr29st3xd3p1jpj5ptkn",
masterTheChaosPriceIds: {
amtc: "pri_01jv4bb3b4pawrwqfn2a963wwb",
aamtc: "pri_01jv4beme2j0cczrpqr7j0w06g",
bmtc: "pri_01jv4bbztp36xajw19hdxg9449",
bbmtc: "pri_01jv4bdcs8ktnch7ja1z2meryz",
},
};
/***/ }),
/***/ 2663:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.configDev = exports.configStaging = void 0;
// const pocGtm = location.search.includes("pocGTM")
exports.configStaging = {
// apiUrl: "https://apiqa.gcp.pgcloud.com/brandbuilding/consumer/ssc" is also supported
apiUrl: "https://apidev.gcp.pgcloud.com/brandbuilding/consumer/ssc",
apiAccessToken: "EVUkrarlkl1QweL7dPdOFGDEKFyGT4KT",
bazaarvoicePasskey: "cayvJ62u3ELqBkmuvrVNySlCyYOlhUmHOPSiz375HmRdQ",
bazaarvoiceUrl: "https://stg.api.bazaarvoice.com",
bazaarvoiceProductId: "E00000002",
starsUrl: "https://store-pvhrvuxqgv.mybigcommerce.com/content/img/stars/",
pgSiteEnvironment: "Staging",
pgGoogleAnalyticsLocal: "UA-38384539-1",
pgGoogleAnalyticsReportingView: "68911582",
pgConsentOverlayID: "b3fb142f-1dfb-4159-8e77-48576bc3bc61-test",
pgFacebookRemarketingID: "416520069746220",
pgSegment: "7o62Z8AH7ui9tGXesqlADGffTgzXmsrp",
recaptchaSiteKey: "6LfNNt8nAAAAAAQ9QcrAy2VmmOUEYQOTKUEWSWTe",
gtmId: "GTM-PQB4L4QL", // : "GTM-TW27C3WG",
enableGeoFeed: true,
paddleEnvironment: "sandbox",
paddleToken: "test_972fd45c16f9068dcb595e1885a",
paddlePriceId: "pri_01j0qx6056ks1d36hdn4m0p33e",
firebase: {
apiKey: "AIzaSyBMQfOzQlXRyS_AB1Tp_IN6AK-Mq9Zok2U",
authDomain: "babycare-lumismart-dev-629b.firebaseapp.com",
projectId: "babycare-lumismart-dev-629b",
storageBucket: "babycare-lumismart-dev-629b.appspot.com",
messagingSenderId: "1098780561668",
appId: "1:1098780561668:web:44bea19a80305d9ce70051",
measurementId: "G-6FZQNPP5JR",
},
paddlePriceIds: {
_1month: "pri_01jays0h611xkdv932bkd6f9c9",
_3months: "pri_01jays6wy189v4v830a6wvfz2n",
_12months: "pri_01j0qx6056ks1d36hdn4m0p33e",
},
paddlePriceIdSets: {
dst6: {
_1month: "pri_01jjknmf30p0btnsxmky8snm05",
_3months: "pri_01jjknn86rwz7qhjcta6hg32cz",
_12months: "pri_01jjknp0asw45f2q24bwc92p4h",
},
bsnt: {
_1month: "pri_01jjknhhb2pgz8r4jjq1dpn36g",
_3months: "pri_01jjknjhnfkxezyjfhr5m2f0hf",
_12months: "pri_01jjknkhd8nczpg2tty1q8cgn4",
},
fst: {
_1month: "pri_01jkankjbrcw256t0c6ms9dmcr",
_3months: "pri_01jkanmdd44dep0zdk0bxe6951",
_12months: "pri_01jkannemr7v0jxqbdjyrmkf88",
},
hmnz: {
_1month: "pri_01jt3mxap62qxf0aaz8wxrchn5",
_3months: "pri_01jt3mw69k6y7gpbaankfpg9fa",
_12months: "pri_01jt3mttd39zw9eawpwqdecpc5",
},
},
paddlePortalUrl: "https://sandbox-customer-portal.paddle.com/login/cpl_01j08ksw75b55xkj9tmzgnwcdk",
masterTheChaosPriceIds: {
amtc: "pri_01jsy9vmh4rmac0t9qqqtv7t5m",
aamtc: "pri_01jtna3fska5zk2rp2pf5vc0e1",
bmtc: "pri_01jsy9w8qjag5jn7ybdwt113xj",
bbmtc: "pri_01jtjj0nj0h6qrc5j0hkx1e381",
},
};
exports.configDev = Object.assign(Object.assign({}, exports.configStaging), {
// apiUrl: "https://api-k8s.dev.sleepcoach.site/v1",
apiUrl: "https://api.sleepcoach.dev", recaptchaSiteKey: "6Ld7vaUnAAAAALLxarGAewhpmq1rdz1EJ4Fg_n5s", firebase: {
apiKey: "AIzaSyDhpyJ18wJCcfH9yB8y_0IBeFtJlDOPEUI",
authDomain: "lumismart-dev.firebaseapp.com",
projectId: "lumismart-dev",
storageBucket: "lumismart-dev.appspot.com",
messagingSenderId: "574989815147",
appId: "1:574989815147:web:f62c47ac1dca3d9950502e",
measurementId: "G-1ZTHZRLFT2",
} });
/***/ }),
/***/ 8066:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.passwordRegex = exports.paths = exports.esPaths = exports.enPaths = exports.localePathPrefix = exports.locale = void 0;
exports.locale = /^\/es((\/.*)|($))/.test(location.pathname) ? "es" : "en";
exports.localePathPrefix = exports.locale === "es" ? "/es" : "";
exports.enPaths = {
login1: `/sign-in`,
login2: `/sign-in-verification`,
welcome: `/sign-in-welcome`,
register1: `/sign-up`,
register2: `/phone-verification`,
changePhone1: `/change-phone-number`,
changePhone2: `/set-phone-number`,
resetPassword1: `/reset-password`,
resetPassword2: `/set-password`,
reviews: `/reviews`,
welcomeSurvey: `/welcome-questionnaire`,
blog: `/blog`,
doubleOptin: `/double-opt-in`,
surveyEndingPageMetaMain: `/survey-ending-page/meta-main`,
surveyEndingPageTikTok: `/survey-ending-page/tiktok`,
surveyEndingPageWeb2App: `/survey-ending-page/web2app`,
surveyMeta: `/sleep-assessment/meta`,
surveyMetaB: `/sleep-assessment/meta-b`,
finalizeAccount: `/finalize-account`,
fullSurvey: `/survey/full-survey-poc`,
fullSurvey2025: `/survey/full-survey-2025`,
otpEndingPageWeb2App: `/otp-ending-pages/otp-web2app`,
otpEndingPageCheckoutPaddle: `/otp-ending-pages/checkout-paddle`,
cancelFlow: `/cancel-flow`,
manageSubscriptionSignIn: "/manage-subscription/sign-in",
manageSubscriptionSignInVerify: "/manage-subscription/sign-in-verify",
manageSubscriptionAccount: "/manage-subscription/account",
paymentLink: `/payment-link`,
termsOfUse: `/terms-of-use`,
masterTheChaos: "/master-the-chaos",
masterTheChaosConfirmation: "/master-the-chaos-confirmation",
otpEndingPagePaddleCheckout: /\/otp-ending-pages\/.*paddle(.*)/,
otpEndingPages: /\/otp-ending-pages\/(.*)/,
surveyEndingPage: /\/survey-ending-page\/(.*)/,
blogCategory: /\/blog\/tag\/(.*)/,
blogContributor: /\/blog\/contributors\/(.*)/,
blogArticle: /\/blog\/(.*)\/(.*)/,
sleepAssessment: /\/sleep-assessment\/(.*)/,
};
exports.esPaths = Object.assign(Object.assign({}, Object.fromEntries(Object.entries(exports.enPaths).map(([key, value]) => (typeof value === "string" ? [key, `/es${value}`] : [key, value])))), { finalizeAccount: `/es/finaliza-cuenta`, login2: "/es/verificacion-de-inicio-de-sesion", register2: "/es/verificacion-telefonica", changePhone1: "/es/cambio-de-telefono", changePhone2: "/es/nuevo-numero-de-telefono", resetPassword1: "/es/restablecer-contrasena", resetPassword2: "/es/establecer-contrasena", doubleOptin: "/es/double-opt-in" });
exports.paths = exports.locale === "es" ? exports.esPaths : exports.enPaths;
// export const testPaths = {
// testChangePhone1: "/testpages/phone-change-step-1-2",
// testChangePhone2: "/testpages/phone-change-step-2-2",
// }
// ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d\!\@\#\$\%\^\&\*\(\)]{8,}$
// Minimum 8 characters, at least 1 lowercase letter, 1 uppercase letter and 1 number
exports.passwordRegex = /(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}/;
// (?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}
/***/ }),
/***/ 8021:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
// source: https://tokyoadjust.notion.site/tokyoadjust/Adjust-Web-to-App-Campaign-solution-ver1-1-EN-1af379383ae147d2b187b44ee53457cd
//
//
// Please note that the tracker with fallback_click needs to be added behind the button to handle the redirection in this case.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getFbPid = getFbPid;
exports.getFbcid = getFbcid;
exports.getTtpid = getTtpid;
const pgDataLayer_1 = __webpack_require__(7350);
const sleep_1 = __webpack_require__(9879);
/*
https://www.smartsleepcoach.com/sleep-assessment/meta?
adj_tracker=vt03x6r&
campaign_name={{campaign.name}}&
campaign_id={{campaign.id}}&
adgroup_name={{adset.name}}&
adgroup_id={{adset.id}}&
ad_name={{ad.name}}&
ad_id={{ad.id}}&
cid=1
https://www.smartsleepcoach.com/sleep-assessment/meta?
utm_source={{site_source_name}}&
utm_medium={{campaign.id}}&
utm_campaign={{adset.id}}&
utm_content={{ad.id}}&
adj_tracker=vt03x6r&
cid=1
*/
// p0=adj_tracker
// p1=campaign_name
// p2=campaign_id
// p3=adgroup_name
// p4=adgroup_id
// p5=ad_name
// p6=ad_id
const trackImmediatly = true;
// build a new URL with parameters p0-p6, fbclid and fbpaid
function buildURL({ adj_tracker, campaign_name, campaign_id, adgroup_name, adgroup_id, ad_name, ad_id, fbclid, fbpid, }) {
if (!adj_tracker && !fbclid) {
return null;
}
const tracker_token = adj_tracker || "vt03x6r";
let campaign, adgroup, creative;
if (campaign_name || campaign_id) {
campaign = campaign_name + "(" + campaign_id + ")";
}
else {
campaign = "";
}
if (adgroup_name || adgroup_id) {
adgroup = adgroup_name + "(" + adgroup_id + ")";
}
else {
adgroup = "";
}
if (ad_name || ad_id) {
creative = ad_name + "(" + ad_id + ")";
}
else {
creative = "";
}
if (!fbclid) {
fbclid = "";
}
if (!fbpid) {
fbpid = "";
}
// build a tracker URL
const params = { campaign, adgroup, creative, fbclid, fbpid };
const newURL = "https://app.adjust.com/" +
tracker_token +
"?" +
Object.keys(params)
.map(key => key + "=" + encodeURIComponent(params[key]))
.join("&");
return newURL;
}
//get fbpid from Cookie written by Facebook Pixel
function getFbPid() {
const fbp = document.cookie.match(/(^|;) ?_fbp=([^;]*)(;|$)/);
if (fbp) {
return fbp[2];
}
return null;
}
function getFbcid() {
const fbc = document.cookie.match(/(^|;) ?_fbc=([^;]*)(;|$)/);
if (fbc) {
return fbc[2];
}
return null;
}
/** Tiktok pixel */
function getTtpid() {
const ttp = document.cookie.match(/(^|;) ?_ttp=([^;]*)(;|$)/);
if (ttp) {
return ttp[2];
}
return null;
}
// get query string, and parse it with URLSearchParams
const urlParams = new URLSearchParams(window.location.search);
function buildUrlFromCustom() {
var _a, _b, _c;
//p0 = urlParams.get("p0") and fallback to "default"
const url = buildURL({
adj_tracker: urlParams.get("adj_tracker"),
campaign_name: (_a = urlParams.get("campaign_name")) !== null && _a !== void 0 ? _a : "",
campaign_id: urlParams.get("utm_medium") || urlParams.get("campaign_id"),
adgroup_name: (_b = urlParams.get("adgroup_name")) !== null && _b !== void 0 ? _b : "",
adgroup_id: urlParams.get("utm_campaign") || urlParams.get("adgroup_id"),
ad_name: (_c = urlParams.get("ad_name")) !== null && _c !== void 0 ? _c : "",
ad_id: urlParams.get("utm_content") || urlParams.get("ad_id"),
fbpid: getFbPid(),
fbclid: urlParams.get("fbclid"),
});
return url;
}
const url = buildUrlFromCustom();
if (url) {
(0, pgDataLayer_1.dataLayerPush)("adjust_pageview", location.href, url);
}
if (!trackImmediatly && url) {
sessionStorage.setItem("adjustTrackerUrl", url);
}
function main() {
if (!trackImmediatly)
return;
const url = buildUrlFromCustom();
if (!url)
return;
window.addEventListener("DOMContentLoaded", () => __awaiter(this, void 0, void 0, function* () {
if (!getFbPid()) {
console.log("no fbpid, giving it another chance");
yield (0, sleep_1.sleep)(100);
}
console.log("no fbpid, tracking and will try again soon");
track();
let waitCount = 0;
if (!getFbPid()) {
console.log("waiting for fbpid");
while (!getFbPid() && waitCount < 100) {
yield (0, sleep_1.sleep)(500);
waitCount++;
}
if (!getFbPid()) {
console.log("fbpid not found, giving up");
return;
}
console.log("fbpid found, tracking again");
track();
}
}));
function track() {
const url = buildUrlFromCustom();
if (!url)
return;
const img = document.createElement("img");
img.src = `${url}&redirect=none`;
img.style.opacity = "0";
img.style.position = "absolute";
img.style.top = "0";
img.style.left = "0";
img.style.zIndex = "-1000";
img.style.width = "1px";
img.style.height = "1px";
// img.addEventListener("error", () => {
// console.warn("error loading adjust tracker image")
// const category = "error"
// const action = "adjust_tracker_load_error"
// const label = url
// dataLayerPush(category, action, label)
// })
document.body.appendChild(img);
(0, pgDataLayer_1.dataLayerPush)("adjust_track", location.href, url);
}
}
if (!trackImmediatly) {
// add links
window.addEventListener("DOMContentLoaded", function () {
const url = sessionStorage.getItem("adjustTrackerUrl");
if (!url) {
return;
}
const elements = document.querySelectorAll(".adjusttracker");
for (let i = 0; i < elements.length; i++) {
console.info("updating adjust tracker", i);
elements[i].setAttribute("href", url);
}
});
}
main();
// Set Adjust tracker ( `fallback_click`) created from Adjust dash to the CTA button in the HTML with `class` code.
// Example: If you want to separate the CTA button for iOS and Android, set up two buttons.
// ```jsx
// iOSCTAbutton
// AndroidCTAbutton
// ```
/*
https://app.adjust.com/vt03x6r?campaign=fredy_test(123456789)&adgroup=adsetname(adsetid)&creative=creativename(adid)&fbclid=8&fbpid=
*/
// setInterval(() => {
// console.log(new Date().toJSON(), "fbpid", getFbPid())
// }, 500)
/***/ }),
/***/ 6752:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.api = void 0;
const ApiClient_1 = __webpack_require__(2672);
exports.api = new ApiClient_1.ApiClient();
console.log(exports.api);
/***/ }),
/***/ 5861:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.appendQueryString = appendQueryString;
function appendQueryString(url, params) {
const urlObj = new URL(url);
for (const [key, value] of Object.entries(params)) {
urlObj.searchParams.set(key, String(value));
}
return urlObj.toString();
}
/***/ }),
/***/ 2220:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getAuth = getAuth;
exports.setAuth = setAuth;
function getAuth() {
const v = localStorage.getItem("auth");
if (!v)
return null;
try {
return v;
}
catch (err) {
console.warn("getAuth", err);
return null;
}
}
function setAuth(v) {
if (!v) {
localStorage.removeItem("auth");
return;
}
localStorage.setItem("auth", v);
}
/***/ }),
/***/ 894:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
/* eslint-disable @typescript-eslint/no-floating-promises */
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable no-var */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.autoStopVideoPlaybacks = autoStopVideoPlaybacks;
const win = window;
if (typeof win.Webflow === "undefined") {
win.Webflow = [];
}
function autoStopVideoPlaybacks() {
/*
* Webflow Slider Events: Trigger an event on navigation of Webflow's slider components.
* @license MIT
* @author Neal White - http://www.cohesive.cc
*
* https://github.com/cohesivecc/webflow-events-slider
*/
Webflow.push(() => {
var namespace = ".w-slider";
function slideChangeEvent(evt) {
var slider;
if ($(evt.target).is(namespace)) {
slider = $(evt.target);
}
else {
slider = $(evt.target).closest(namespace);
}
if (slider) {
$(slider).trigger("slider-event", $(slider).data(namespace));
}
}
var tap_selector = $.map([".w-slider-arrow-left", ".w-slider-arrow-right", ".w-slider-dot"], function (s) {
return namespace + " " + s;
}).join(", ");
// listeners
$(document)
.off("tap" + namespace, tap_selector, slideChangeEvent)
.on("tap" + namespace, tap_selector, slideChangeEvent);
$(document)
.off("swipe" + namespace, namespace, slideChangeEvent)
.on("swipe" + namespace, namespace, slideChangeEvent);
// initial slide - manually trigger the event
$(namespace + ":visible").each(function (i, s) {
slideChangeEvent({ target: s });
});
});
Webflow.push(() => {
// listen for all sliders on the page - .w-slider is Webflow's default class for slider components
$(document).on("slider-event", ".w-slider", function (e, data) {
data.slides.toArray().forEach((t, i) => {
var _a;
const video = (_a = $(t).find("video")) === null || _a === void 0 ? void 0 : _a[0];
if (!video)
return;
if (i === data.index) {
if (!video.paused)
return;
console.log("playing video", video);
video.play();
return;
}
if (video.paused)
return;
console.log("pausing video", video);
video.pause();
});
});
// OR - listen for events from a specific subset of sliders
// $(document).on("slider-event", ".trackable-slider", function (e, data) {
// console.log({ e, data })
// })
});
}
/***/ }),
/***/ 8043:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.checkEmailTypos = checkEmailTypos;
const knownDomains = ["gmail.com", "hotmail.com", "yahoo.com", "outlook.com", "icloud.com"];
function checkEmailTypos(email) {
const [localPart, domain] = email.split("@");
if (!domain) {
return email;
}
if (knownDomains.includes(domain.toLowerCase())) {
return email;
}
const closestDomain = findClosestDomain(domain.toLowerCase(), knownDomains);
if (closestDomain) {
return `${localPart}@${closestDomain}`;
}
return email;
}
function findClosestDomain(domain, knownDomains) {
let closestDomain = null;
let minDistance = 2;
for (const knownDomain of knownDomains) {
const distance = levenshteinDistance(domain, knownDomain);
if (distance <= minDistance) {
minDistance = distance;
closestDomain = knownDomain;
}
}
return closestDomain;
}
function levenshteinDistance(a, b) {
const matrix = [];
for (let i = 0; i <= b.length; i++) {
matrix[i] = [i];
}
for (let j = 0; j <= a.length; j++) {
matrix[0][j] = j;
}
for (let i = 1; i <= b.length; i++) {
for (let j = 1; j <= a.length; j++) {
if (b.charAt(i - 1) === a.charAt(j - 1)) {
matrix[i][j] = matrix[i - 1][j - 1];
}
else {
matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, Math.min(matrix[i][j - 1] + 1, matrix[i - 1][j] + 1));
}
}
}
return matrix[b.length][a.length];
}
/***/ }),
/***/ 1700:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.counter = counter;
const counter2_1 = __webpack_require__(8916);
const sleep_1 = __webpack_require__(9879);
function counter() {
return __awaiter(this, void 0, void 0, function* () {
const interval = location.href.includes("devquick") ? 5 * 1000 : 22 * 1000;
const startCount = 524356;
const start = new Date(2023, 10, 15).getTime();
const end = new Date(2025, 0, 1).getTime();
const totalSpan = end - start;
const max = startCount + Math.floor((end - start) / interval);
console.log({ max, totalSpan, start, end, interval });
const wrapper = document.querySelector(".parents-num-num");
if (!wrapper)
return;
const now = new Date().getTime();
const passed = now - start;
let count = max - Math.floor((totalSpan - passed) / interval);
const animate = (0, counter2_1.counter2)(wrapper); // location.href.includes("counter2") ? counter2(wrapper) : counter1(wrapper)
yield animate(count.toLocaleString());
yield (0, sleep_1.sleep)(7000);
count++;
while (wrapper) {
const now = new Date().getTime();
yield animate(count.toLocaleString());
const took = new Date().getTime() - now;
yield (0, sleep_1.sleep)(Math.max(interval - took, 100));
count++;
}
});
}
/***/ }),
/***/ 8916:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.counter2 = counter2;
/* eslint-disable @typescript-eslint/no-non-null-assertion */
const nextFrame_1 = __webpack_require__(26);
const sleep_1 = __webpack_require__(9879);
function counter2(el) {
styles();
let value = "";
function reset(x) {
value = x;
el.innerHTML = `
`;
}
function animate(x) {
return __awaiter(this, void 0, void 0, function* () {
if (!value) {
reset(x);
}
value = x;
yield (0, nextFrame_1.nextFrame)();
const resetEls = [];
const el2 = el.querySelector(`.digits2 .digits2-current`);
if (el2.innerText === x)
return;
el2.className = "digits2-above";
const el3 = el.querySelector(`.digits2 .digits2-below`);
if (el3.innerText === x)
return;
el3.innerText = x;
el3.className = "digits2-current";
const el4 = el.querySelector(`.digits2 .digits2-placeholder`);
el4.innerText = x;
resetEls.push(el2);
yield (0, sleep_1.sleep)(1000);
el2.className = "digits2-above2";
yield (0, sleep_1.sleep)(2000);
el2.className = "digits2-below";
yield (0, nextFrame_1.nextFrame)();
});
}
return animate;
}
let stylesAdded = false;
function styles() {
var _a;
if (stylesAdded)
return;
stylesAdded = true;
const style = document.createElement("style");
style.textContent = `
.parents-num-num {
display: inline-block;
position: relative;
overflow: hidden;
vertical-align: bottom;
}
.digits2 {
display: inline-block;
height: 2.4em;
padding-right: 2px;
}
.digits2-placeholder {
visibility: hidden;
}
.digits2-current {
transition: all 1s ease-out;
position: absolute;
top: 1.2em;
}
.digits2-below {
top: 2.4em;
position: absolute;
}
.digits2-above {
top: 0;
position: absolute;
opacity: 0.7;
transform: scale(0.9);
transition: all 1s ease-out;
}
.digits2-above2 {
top: 0;
position: absolute;
opacity: 0;
transform: scale(0.9);
transition: all 2s ease-out;
}
`;
(_a = document.head) === null || _a === void 0 ? void 0 : _a.appendChild(style);
}
/***/ }),
/***/ 957:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.detect = detect;
exports.isIos = isIos;
exports.isAndroid = isAndroid;
function detect() {
if (/(ipad)|(iphone)|(ipod)/i.test(navigator.userAgent))
return "ios";
if (/(android)/i.test(navigator.userAgent))
return "android";
return "unknown";
}
const os = detect();
document.body.classList.add(os);
function isIos() {
return os === "ios";
}
function isAndroid() {
return os === "android";
}
/***/ }),
/***/ 4150:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.disableForm = disableForm;
exports.enableForm = enableForm;
exports.setFormDisabled = setFormDisabled;
function disableForm(form) {
setFormDisabled(form, true);
}
function enableForm(form) {
setFormDisabled(form, false);
}
function setFormDisabled(form, disabled) {
form.querySelectorAll("input[type=submit]").forEach(el => {
el.disabled = disabled;
el.classList.toggle("disabled", disabled);
});
}
/***/ }),
/***/ 3143:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.env = void 0;
// TODO: remove staging
// "staging.smartsleepcoach.com",
const host = location === null || location === void 0 ? void 0 : location.host;
const isProdDomain = ["www.smartsleepcoach.com", "smartsleepcoach.com"].includes(host);
const dev = typeof location === "undefined" || (!isProdDomain && (location === null || location === void 0 ? void 0 : location.hash.includes("dev")));
exports.env = dev ? "dev" : isProdDomain ? "prod" : "staging";
/***/ }),
/***/ 51:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.firebaseUser = void 0;
exports.getFirebaseConsumerId = getFirebaseConsumerId;
exports.initFirebase = initFirebase;
exports.getFirebaseToken = getFirebaseToken;
const config_1 = __webpack_require__(7028);
function loadFirebase() {
if (window.firebasePromise)
return window.firebasePromise;
window.firebasePromise = new Promise(resolve => {
window.firebasePromiseResolve = resolve;
const script = document.createElement("script");
script.type = "module";
script.innerHTML = `
import * as app from 'https://www.gstatic.com/firebasejs/11.0.1/firebase-app.js'
import * as analytics from 'https://www.gstatic.com/firebasejs/11.0.1/firebase-analytics.js'
import * as auth from 'https://www.gstatic.com/firebasejs/11.0.1/firebase-auth.js'
const firebase = { app, auth, analytics }
window.firebase = firebase
console.log("firebase loaded", firebase)
window.firebasePromiseResolve?.(firebase)
`;
document.body.appendChild(script);
});
return window.firebasePromise;
}
let _initFirebasePromise = null;
exports.firebaseUser = null;
function getFirebaseConsumerId() {
return __awaiter(this, void 0, void 0, function* () {
if (!exports.firebaseUser)
return null;
const idToken = yield exports.firebaseUser.getIdTokenResult();
const consumerId = idToken.claims.consumer_id;
return consumerId;
});
}
function _initFirebase() {
return __awaiter(this, void 0, void 0, function* () {
if (!config_1.config.firebase)
return null;
const firebase = yield loadFirebase();
if (!firebase)
return null;
const firebaseApp = firebase.app.initializeApp(config_1.config.firebase);
firebase.analytics.getAnalytics(firebaseApp); // TODO: check if this is needed
const auth = firebase.auth.getAuth();
auth.onAuthStateChanged(user => {
console.log("onAuthStateChanged", user);
exports.firebaseUser = user;
});
yield auth.authStateReady();
return firebase;
});
}
function initFirebase() {
if (_initFirebasePromise)
return _initFirebasePromise;
_initFirebasePromise = _initFirebase();
return _initFirebasePromise;
}
function getFirebaseToken(token) {
return __awaiter(this, void 0, void 0, function* () {
const firebase = yield initFirebase();
if (!firebase)
return null;
const auth = firebase.auth.getAuth();
const res = yield firebase.auth.signInWithCustomToken(auth, token);
return res;
});
}
/***/ }),
/***/ 7539:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getGeoFeed = getGeoFeed;
const config_1 = __webpack_require__(7028);
const consts_1 = __webpack_require__(8066);
const enableGeoFeed = config_1.config.enableGeoFeed;
// const geoFeedExpirationMs = 1000 * 60 * 60 * 24
// window._geoFeed = loadGeoFeed() ?? undefined
// // TODO: TEMP
const countryOverride = new URLSearchParams(location.search).get("countryOverride");
let allowCountries = null;
if (consts_1.paths.otpEndingPagePaddleCheckout.test(location.pathname)) {
allowCountries = ["US", "CA"];
}
function getGeoFeed() {
return __awaiter(this, void 0, void 0, function* () {
if (!enableGeoFeed)
return null;
if (window._geoFeed !== undefined) {
return window._geoFeed;
}
if (!window.whenGeofeed) {
window.whenGeofeed = new Promise(resolve => {
window.geofeed = res => {
var _a, _b;
if (countryOverride) {
console.log("countryOverride", countryOverride);
res = Object.assign(Object.assign({}, (res !== null && res !== void 0 ? res : {})), { country: countryOverride });
}
if (allowCountries && !allowCountries.includes((_a = res === null || res === void 0 ? void 0 : res.country) !== null && _a !== void 0 ? _a : "")) {
console.warn("GeoFeed country not allowed", res === null || res === void 0 ? void 0 : res.country, allowCountries);
res = { country: "US" };
}
window._geoFeed = res !== null && res !== void 0 ? res : null;
if ((res === null || res === void 0 ? void 0 : res.country) && window.PGdataLayer) {
window.PGdataLayer.user = Object.assign(Object.assign({}, ((_b = window.PGdataLayer.user) !== null && _b !== void 0 ? _b : {})), { country: res === null || res === void 0 ? void 0 : res.country });
}
resolve(res);
// string two digit continent code EU, NA, OC, AS, SA, AF
// string two digit ISO country code
// string two digit state code
};
triggerGeoFeed();
});
}
return window.whenGeofeed;
});
}
function triggerGeoFeed() {
// Call geo-location JSON service
const json = document.createElement("script");
json.setAttribute("src", "https://geolocation.onetrust.com/cookieconsentpub/v1/geo/location/geofeed");
document.head.appendChild(json);
}
// export function loadGeoFeed(): IGeoFeed | null {
// const v = localStorage.getItem("geofeed")
// if (!v) return null
// try {
// const v2 = JSON.parse(v) as IGeoFeed
// if ((v2.since ?? 0) + geoFeedExpirationMs < Date.now()) {
// return null
// }
// return v2
// } catch (err) {
// console.warn("loadGeoFeed", err)
// return null
// }
// }
// export function saveGeoFeed(v: IGeoFeed | null) {
// if (!v) {
// localStorage.removeItem("geofeed")
// return
// }
// v.since = Date.now()
// localStorage.setItem("geofeed", JSON.stringify(v))
// }
/***/ }),
/***/ 7089:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getQueryParam = getQueryParam;
function getQueryParam(name) {
return new URLSearchParams(location.search).get(name);
}
/***/ }),
/***/ 1741:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getSupportedCountries = getSupportedCountries;
exports.getTerms = getTerms;
const api_1 = __webpack_require__(6752);
const getGeoFeed_1 = __webpack_require__(7539);
let _supportedCountries = undefined;
function getSupportedCountries() {
return __awaiter(this, void 0, void 0, function* () {
if (_supportedCountries)
return _supportedCountries;
_supportedCountries = yield api_1.api.supportedCountries();
return _supportedCountries;
});
}
const cache = {};
function getTerms() {
return __awaiter(this, void 0, void 0, function* () {
var _a;
const geoFeed = yield (0, getGeoFeed_1.getGeoFeed)();
if (!geoFeed)
return null;
let countryCode = (_a = geoFeed === null || geoFeed === void 0 ? void 0 : geoFeed.country) !== null && _a !== void 0 ? _a : "US";
const supportedCountries = yield getSupportedCountries();
const supportedCountry = supportedCountries.find(t => t.countryCode === countryCode);
if (!supportedCountry) {
countryCode = "US";
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const language = navigator.language || navigator.userLanguage || "";
const languageCode = language.split("-")[0];
const key = `${countryCode}-${languageCode}`;
if (cache[key])
return cache[key];
const terms = yield api_1.api.terms({ countryCode, languageCode }).catch(err => {
console.warn(err);
return null;
});
if (terms) {
cache[key] = terms;
}
return terms;
});
}
/***/ }),
/***/ 1546:
/***/ (function(__unused_webpack_module, exports) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.intlTelInputUtilsScript = void 0;
exports.loadIntlTelInput = loadIntlTelInput;
exports.intlTelInputUtilsScript = "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/18.1.8/js/utils.min.js";
function loadScript(src) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
const script = document.createElement("script");
script.src = src;
script.onload = () => resolve();
script.onerror = () => reject();
document.head.appendChild(script);
});
});
}
function loadCss(src) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
const link = document.createElement("link");
link.rel = "stylesheet";
link.type = "text/css";
link.href = src;
link.onload = () => resolve();
link.onerror = () => reject();
document.head.appendChild(link);
});
});
}
function _loadIntlTelInput() {
return __awaiter(this, void 0, void 0, function* () {
void loadCss("https://cdn.jsdelivr.net/npm/intl-tel-input@18.1.1/build/css/intlTelInput.css");
yield loadScript("https://cdn.jsdelivr.net/npm/intl-tel-input@18.1.1/build/js/intlTelInput.min.js");
return window.intlTelInput;
});
}
let p = null;
function loadIntlTelInput() {
if (p)
return p;
p = _loadIntlTelInput();
return p;
}
/***/ }),
/***/ 26:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.nextFrame = nextFrame;
function nextFrame() {
return new Promise(resolve => requestAnimationFrame(resolve));
}
/***/ }),
/***/ 9312:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.cookieConsentTranslations = exports.oneTrustCountryInfo = void 0;
exports.initOnetrust = initOnetrust;
const getGeoFeed_1 = __webpack_require__(7539);
exports.oneTrustCountryInfo = {
RS: {
country: "Serbian/Serbia/Srbija",
cookieCompliance: "GDPR",
countryCode: "RS",
language: "Serbian",
languageCode: "sr",
},
AD: { country: "Andorra", cookieCompliance: "GDPR", countryCode: "AD", language: "English", languageCode: "en" },
AL: { country: "Albania", cookieCompliance: "GDPR", countryCode: "AL", language: "Albanian", languageCode: "sq" },
UA: { country: "Ukraine", cookieCompliance: "GDPR", countryCode: "UA", language: "Ukrainian", languageCode: "uk" },
CY: {
country: "Cyprus/Republic of Cyprus",
cookieCompliance: "GDPR",
countryCode: "CY",
language: "English",
languageCode: "en",
},
IS: { country: "Iceland", cookieCompliance: "GDPR", countryCode: "IS", language: "English", languageCode: "en" },
LI: {
country: "Liechtenstein",
cookieCompliance: "GDPR",
countryCode: "LI",
language: "German",
languageCode: "de",
},
LU: { country: "Luxembourg", cookieCompliance: "GDPR", countryCode: "LU", language: "English", languageCode: "en" },
MT: { country: "Malta", cookieCompliance: "GDPR", countryCode: "MT", language: "English", languageCode: "en" },
SM: { country: "San Marino", cookieCompliance: "GDPR", countryCode: "SM", language: "English", languageCode: "en" },
XK: {
country: "Kosovo (Republic of)",
cookieCompliance: "GDPR",
countryCode: "XK",
language: "Serbian",
languageCode: "sr",
},
BG: { country: "Bulgaria", cookieCompliance: "GDPR", countryCode: "BG", language: "Bulgarian", languageCode: "bg" },
HR: { country: "Croatia", cookieCompliance: "GDPR", countryCode: "HR", language: "Croatian", languageCode: "hr" },
CZ: {
country: "Czech/Czech Republic",
cookieCompliance: "GDPR",
countryCode: "CZ",
language: "Czech",
languageCode: "cs",
},
EE: { country: "Estonia", cookieCompliance: "GDPR", countryCode: "EE", language: "Estonian", languageCode: "et" },
FI: { country: "Finland", cookieCompliance: "GDPR", countryCode: "FI", language: "Finnish", languageCode: "fi" },
IL: { country: "Israel", cookieCompliance: "GDPR", countryCode: "IL", language: "Hebrew", languageCode: "he" },
HU: { country: "Hungary", cookieCompliance: "GDPR", countryCode: "HU", language: "Hungarian", languageCode: "hu" },
LV: { country: "Latvia", cookieCompliance: "GDPR", countryCode: "LV", language: "Latvian", languageCode: "lv" },
LT: {
country: "Lithuania",
cookieCompliance: "GDPR",
countryCode: "LT",
language: "Lithuanian",
languageCode: "lt",
},
NO: { country: "Norway", cookieCompliance: "GDPR", countryCode: "NO", language: "Norwegian", languageCode: "no" },
PL: { country: "Poland", cookieCompliance: "GDPR", countryCode: "PL", language: "Polish", languageCode: "pl" },
PT: {
country: "Portugal",
cookieCompliance: "GDPR",
countryCode: "PT",
language: "Portuguese",
languageCode: "pt",
},
RO: { country: "Romania", cookieCompliance: "GDPR", countryCode: "RO", language: "Romanian", languageCode: "ro" },
SK: { country: "Slovak", cookieCompliance: "GDPR", countryCode: "SK", language: "Slovak", languageCode: "sk" },
SI: { country: "Slovenia", cookieCompliance: "GDPR", countryCode: "SI", language: "Slovenian", languageCode: "sl" },
SE: { country: "Sweden", cookieCompliance: "GDPR", countryCode: "SE", language: "Swedish", languageCode: "sv" },
MC: { country: "Monaco", cookieCompliance: "GDPR", countryCode: "MC", language: "French", languageCode: "fr" },
DE: { country: "Germany", cookieCompliance: "GDPR", countryCode: "DE", language: "German", languageCode: "de-de" },
AT: { country: "Austria", cookieCompliance: "GDPR", countryCode: "AT", language: "German", languageCode: "de-at" },
CH: {
country: "Switzerland",
cookieCompliance: "GDPR",
countryCode: "CH",
language: "German",
languageCode: "de-ch",
},
NL: { country: "Netherlands", cookieCompliance: "GDPR", countryCode: "NL", language: "Dutch", languageCode: "nl" },
IT: { country: "Italy", cookieCompliance: "GDPR", countryCode: "IT", language: "Italian", languageCode: "it" },
GB: { country: "UK", cookieCompliance: "GDPR", countryCode: "GB", language: "English", languageCode: "en-gb" },
GI: { country: "Gibraltar", cookieCompliance: "GDPR", countryCode: "GI", language: "English", languageCode: "en" },
IE: { country: "Ireland", cookieCompliance: "GDPR", countryCode: "IE", language: "English", languageCode: "en-ie" },
TR: { country: "Turkey", cookieCompliance: "GDPR", countryCode: "TR", language: "Turkish", languageCode: "tr" },
GR: { country: "Greece", cookieCompliance: "GDPR", countryCode: "GR", language: "Greek", languageCode: "el" },
ES: { country: "Spain", cookieCompliance: "GDPR", countryCode: "ES", language: "Spanish", languageCode: "es" },
BE: { country: "Belgium", cookieCompliance: "GDPR", countryCode: "BE", language: "Dutch", languageCode: "nl" },
DK: { country: "Denmark", cookieCompliance: "GDPR", countryCode: "DK", language: "Danish", languageCode: "da" },
FR: { country: "France", cookieCompliance: "GDPR", countryCode: "FR", language: "French", languageCode: "fr" },
US: { country: "US", cookieCompliance: "CCPA", countryCode: "US", language: "English", languageCode: "en" },
PR: {
country: "Puerto Rico",
cookieCompliance: "CCPA",
countryCode: "PR",
language: "Spanish",
languageCode: "es",
},
BR: {
country: "Brazil",
cookieCompliance: "LGPD",
countryCode: "BR",
language: "Portuguese",
languageCode: "pt-br",
},
ID: {
country: "Indonesia",
cookieCompliance: "AMA",
countryCode: "ID",
language: "Indonesian",
languageCode: "id",
},
SG: {
country: "Singapore",
cookieCompliance: "AMA",
countryCode: "SG",
language: "English",
languageCode: "en-sg",
},
PH: {
country: "Philippines",
cookieCompliance: "AMA",
countryCode: "PH",
language: "English",
languageCode: "en-ph",
},
TH: { country: "Thailand", cookieCompliance: "AMA", countryCode: "TH", language: "Thai", languageCode: "th" },
KR: { country: "South Korea", cookieCompliance: "AMA", countryCode: "KR", language: "Korean", languageCode: "ko" },
ZA: {
country: "SouthAfrica",
cookieCompliance: "AMA",
countryCode: "ZA",
language: "English",
languageCode: "en-za",
},
NG: { country: "Nigeria", cookieCompliance: "AMA", countryCode: "NG", language: "English", languageCode: "en-ng" },
AE: { country: "UAE", cookieCompliance: "AMA", countryCode: "AE", language: "Arabic", languageCode: "ar" },
VN: { country: "Vietnam", cookieCompliance: "AMA", countryCode: "VN", language: "Vietnamese", languageCode: "vi" },
IN: { country: "India", cookieCompliance: "AMA", countryCode: "IN", language: "English", languageCode: "en-in" },
MX: {
country: "Mexico",
cookieCompliance: "LFPDPPP",
countryCode: "MX",
language: "Spanish",
languageCode: "es-mx",
},
CO: {
country: "Colombia",
cookieCompliance: "HDCO",
countryCode: "CO",
language: "Spanish",
languageCode: "es-co",
},
CA: { country: "Canada", cookieCompliance: "CA", countryCode: "CA", language: "English", languageCode: "en-ca" },
EC: {
country: "Ecuador",
cookieCompliance: "LOPDP",
countryCode: "EC",
language: "Spanish",
languageCode: "es-ec",
},
};
exports.cookieConsentTranslations = {
Bulgarian: "Съгласие за „бисквитки“",
Czech: "Souhlas pro soubory cookies",
German: "Meine Cookie Auswahl",
Finnish: "Evästesuostumus",
French: "Gestion des cookies",
Greek: "Συγκατάθεση στη χρήση cookies",
Croatian: "Pristanak na kolačiće",
Hungarian: "Sütik elfogadása",
Hebrew: "הסכמה לשימוש בעוגיות",
Dutch: "Beheer cookies",
Norwegian: "Cookiesamtykke",
Polish: "Zgoda na pliki cookie",
Romanian: "Consimțământ Cookie-uri",
Swedish: "Cookiemedgivande",
Turkish: "Çerez Onayı",
Spanish: "Consentimiento de cookies",
Portuguese: "Consentimento de cookies",
Italian: "Consenso per i cookie",
Slovack: "Súhlas pre súbory cookies",
Danish: "tilladelse af cookies",
Flemish: "Belgium would use FR and Dutch",
Ukrainian: "Згода на обробку cookies",
Latvian: "Sīkdatņu Piekrisanu",
Estonian: "Küpsiste Nõusolek",
Slovenian: "Piškotki Soglasje",
Lithuanian: "Slapukus Sutikimą",
Albanian: "Pëlqimi i cookie-t",
Macedonian: "Согласност за колаче",
Serbian: "Управљање колачићима",
Russian: "Согласие на обработку cookies",
Indonesian: "Persetujuan Cookie",
Thai: "การให้ความยินยอมสำหรับคุกกี้",
Korean: "쿠키 동의",
Arabic: "وافقة على ملفات تعريف الارتباط", // (UAE)
Vietnamese: "Chấp thuận Cookie",
"Portuguese Brazil": "Consentimento de Cookie",
};
function initOnetrust() {
return __awaiter(this, void 0, void 0, function* () {
const geofeed = yield (0, getGeoFeed_1.getGeoFeed)();
if (!(geofeed === null || geofeed === void 0 ? void 0 : geofeed.country))
return;
const countryInfo = exports.oneTrustCountryInfo[geofeed.country];
if (!countryInfo)
return;
window.PGdataLayer.GTM.ConsentOverlayLanguage = countryInfo.languageCode || "en";
window.PGdataLayer.GTM.SitePrivacyProtection = countryInfo.cookieCompliance;
window.PGdataLayer.GTM.SiteCountry = geofeed.country;
// window.addEventListener("DOMContentLoaded", () => {
// const div = document.createElement("div")
// div.innerHTML = ``
// document.body.appendChild(div)
// })
});
}
/***/ }),
/***/ 3074:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.initPaddle = initPaddle;
exports.triggerSegmentEvent = triggerSegmentEvent;
exports.handlePaddleEvent = handlePaddleEvent;
exports.isCheckoutCompletedEvent = isCheckoutCompletedEvent;
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-non-null-assertion */
const paddle_js_1 = __webpack_require__(6524);
const config_1 = __webpack_require__(7028);
const adjust_1 = __webpack_require__(8021);
const getGeoFeed_1 = __webpack_require__(7539);
const pgDataLayer_1 = __webpack_require__(7350);
const registerLead_1 = __webpack_require__(2517);
const segment_1 = __webpack_require__(1685);
function initPaddle(_a) {
return __awaiter(this, arguments, void 0, function* ({ pwCustomerEmail, frameTarget, onPaddleEvent, }) {
const config2 = config_1.config;
yield (0, segment_1.ifSegmentReady)();
const paddle = yield (0, paddle_js_1.initializePaddle)(Object.assign(Object.assign({ environment: config2.paddleEnvironment, token: config2.paddleToken }, (pwCustomerEmail ? { pwCustomer: { email: pwCustomerEmail } } : {})), { eventCallback: onPaddleEvent, checkout: {
settings: Object.assign(Object.assign({ displayMode: "inline" }, (frameTarget ? { frameTarget } : {})), { frameInitialHeight: 450, frameStyle: "width: 100%; min-width: 312px; background-color: transparent; border: none;" }),
} }));
return paddle;
});
}
function triggerSegmentEvent(e, geoFeed) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, _65, _66, _67, _68, _69, _70, _71, _72, _73, _74, _75, _76, _77, _78, _79, _80, _81, _82, _83, _84, _85, _86, _87, _88, _89, _90, _91, _92, _93, _94, _95, _96, _97, _98, _99, _100, _101, _102, _103, _104, _105, _106, _107, _108, _109, _110, _111, _112, _113, _114, _115, _116, _117, _118, _119, _120, _121, _122, _123, _124, _125, _126, _127, _128, _129, _130, _131, _132, _133, _134, _135, _136, _137, _138, _139, _140, _141, _142, _143, _144, _145, _146, _147, _148, _149, _150, _151, _152, _153, _154, _155, _156, _157, _158, _159, _160, _161, _162, _163, _164, _165, _166, _167, _168, _169, _170, _171, _172, _173, _174, _175, _176, _177, _178, _179, _180, _181, _182, _183, _184, _185, _186, _187, _188, _189, _190, _191, _192, _193, _194, _195, _196, _197, _198, _199, _200, _201, _202, _203, _204, _205, _206, _207, _208, _209, _210, _211, _212, _213, _214, _215, _216, _217, _218, _219, _220, _221, _222, _223, _224, _225, _226, _227, _228, _229, _230, _231, _232, _233, _234, _235, _236, _237, _238, _239, _240, _241, _242, _243, _244, _245, _246;
try {
const { data, type, code, detail, documentation_url, error, errors } = e;
const transaction_id = data === null || data === void 0 ? void 0 : data.transaction_id;
const user2 = (0, registerLead_1.getRegisterLead)();
const user_id = user2 === null || user2 === void 0 ? void 0 : user2.consumerId;
const fbc = (0, adjust_1.getFbcid)();
const fbp = (0, adjust_1.getFbPid)();
const map = {
"checkout.loaded": {
name: "Checkout Loaded",
user_id,
fbc,
fbp,
postal_code: (_b = (_a = data === null || data === void 0 ? void 0 : data.customer) === null || _a === void 0 ? void 0 : _a.address) === null || _b === void 0 ? void 0 : _b.postal_code,
country: (_d = (_c = data === null || data === void 0 ? void 0 : data.customer) === null || _c === void 0 ? void 0 : _c.address) === null || _d === void 0 ? void 0 : _d.country_code,
checkout_id: data === null || data === void 0 ? void 0 : data.id,
transaction_id: data === null || data === void 0 ? void 0 : data.transaction_id,
checkout_status: data === null || data === void 0 ? void 0 : data.status,
paddle_customer_id: data === null || data === void 0 ? void 0 : data.customer.id,
price_id: (_e = data === null || data === void 0 ? void 0 : data.items[0]) === null || _e === void 0 ? void 0 : _e.price_id,
product_id: (_f = data === null || data === void 0 ? void 0 : data.items[0]) === null || _f === void 0 ? void 0 : _f.product.id,
product_name: (_g = data === null || data === void 0 ? void 0 : data.items[0]) === null || _g === void 0 ? void 0 : _g.product.name,
billing_cycle_interval: (_j = (_h = data === null || data === void 0 ? void 0 : data.items[0]) === null || _h === void 0 ? void 0 : _h.billing_cycle) === null || _j === void 0 ? void 0 : _j.interval,
billing_cycle_frequency: (_l = (_k = data === null || data === void 0 ? void 0 : data.items[0]) === null || _k === void 0 ? void 0 : _k.billing_cycle) === null || _l === void 0 ? void 0 : _l.frequency,
trial_period_interval: (_o = (_m = data === null || data === void 0 ? void 0 : data.items[0]) === null || _m === void 0 ? void 0 : _m.trial_period) === null || _o === void 0 ? void 0 : _o.interval,
trial_period_frequency: (_q = (_p = data === null || data === void 0 ? void 0 : data.items[0]) === null || _p === void 0 ? void 0 : _p.trial_period) === null || _q === void 0 ? void 0 : _q.frequency,
value: (_r = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _r === void 0 ? void 0 : _r.subtotal,
price_subtotal: (_s = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _s === void 0 ? void 0 : _s.subtotal,
price_discount: (_t = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _t === void 0 ? void 0 : _t.discount,
price_balance: (_u = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _u === void 0 ? void 0 : _u.balance,
price_total: (_v = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _v === void 0 ? void 0 : _v.total,
price_name: (_w = data === null || data === void 0 ? void 0 : data.items[0]) === null || _w === void 0 ? void 0 : _w.price_name,
currency: data === null || data === void 0 ? void 0 : data.currency_code,
payment_method: data === null || data === void 0 ? void 0 : data.payment.method_details.type,
discount_id: (_x = data === null || data === void 0 ? void 0 : data.discount) === null || _x === void 0 ? void 0 : _x.id,
discount_code: (_y = data === null || data === void 0 ? void 0 : data.discount) === null || _y === void 0 ? void 0 : _y.code,
},
"checkout.completed": {
name: "Order Completed",
user_id,
fbc,
fbp,
first_name: user2 === null || user2 === void 0 ? void 0 : user2.nickname,
email: user2 === null || user2 === void 0 ? void 0 : user2.email,
state: geoFeed === null || geoFeed === void 0 ? void 0 : geoFeed.state,
postal_code: (_0 = (_z = data === null || data === void 0 ? void 0 : data.customer) === null || _z === void 0 ? void 0 : _z.address) === null || _0 === void 0 ? void 0 : _0.postal_code,
country: (_2 = (_1 = data === null || data === void 0 ? void 0 : data.customer) === null || _1 === void 0 ? void 0 : _1.address) === null || _2 === void 0 ? void 0 : _2.country_code,
checkout_id: data === null || data === void 0 ? void 0 : data.id,
transaction_id: data === null || data === void 0 ? void 0 : data.transaction_id,
checkout_status: data === null || data === void 0 ? void 0 : data.status,
paddle_customer_id: data === null || data === void 0 ? void 0 : data.customer.id,
price_id: (_3 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _3 === void 0 ? void 0 : _3.price_id,
product_id: (_4 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _4 === void 0 ? void 0 : _4.product.id,
product_name: (_5 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _5 === void 0 ? void 0 : _5.product.name,
billing_cycle_interval: (_7 = (_6 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _6 === void 0 ? void 0 : _6.billing_cycle) === null || _7 === void 0 ? void 0 : _7.interval,
billing_cycle_frequency: (_9 = (_8 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _8 === void 0 ? void 0 : _8.billing_cycle) === null || _9 === void 0 ? void 0 : _9.frequency,
trial_period_interval: (_11 = (_10 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _10 === void 0 ? void 0 : _10.trial_period) === null || _11 === void 0 ? void 0 : _11.interval,
trial_period_frequency: (_13 = (_12 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _12 === void 0 ? void 0 : _12.trial_period) === null || _13 === void 0 ? void 0 : _13.frequency,
value: (_14 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _14 === void 0 ? void 0 : _14.subtotal,
price_subtotal: (_15 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _15 === void 0 ? void 0 : _15.subtotal,
price_discount: (_16 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _16 === void 0 ? void 0 : _16.discount,
price_balance: (_17 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _17 === void 0 ? void 0 : _17.balance,
price_total: (_18 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _18 === void 0 ? void 0 : _18.total,
price_name: (_19 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _19 === void 0 ? void 0 : _19.price_name,
currency: data === null || data === void 0 ? void 0 : data.currency_code,
payment_method: data === null || data === void 0 ? void 0 : data.payment.method_details.type,
discount_id: (_20 = data === null || data === void 0 ? void 0 : data.discount) === null || _20 === void 0 ? void 0 : _20.id,
discount_code: (_21 = data === null || data === void 0 ? void 0 : data.discount) === null || _21 === void 0 ? void 0 : _21.code,
// Standard segment props https://segment.com/docs/connections/spec/ecommerce/v2/#order-completed
// checkout_id: "fksdjfsdjfisjf9sdfjsd9f",
order_id: data === null || data === void 0 ? void 0 : data.transaction_id,
// affiliation: "Google Store",
// total: 27.5,
// subtotal: 22.5,
revenue: (_22 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _22 === void 0 ? void 0 : _22.subtotal,
// shipping: 3,
tax: (_23 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _23 === void 0 ? void 0 : _23.tax,
subtotal: (_24 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _24 === void 0 ? void 0 : _24.subtotal,
// price_discount: data?.recurring_totals?.discount,
// price_balance: data?.recurring_totals?.balance,
total: (_25 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _25 === void 0 ? void 0 : _25.total,
discount: (_26 = data === null || data === void 0 ? void 0 : data.discount) === null || _26 === void 0 ? void 0 : _26.code,
// coupon: "hasbros",
// currency: "USD",
products: [
{
product_id: (_27 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _27 === void 0 ? void 0 : _27.price_id,
sku: (_28 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _28 === void 0 ? void 0 : _28.price_id,
name: (_29 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _29 === void 0 ? void 0 : _29.price_name,
price: (_30 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _30 === void 0 ? void 0 : _30.subtotal,
quantity: 1,
// category: "Games",
// url: "https://www.example.com/product/path",
// image_url: "https:///www.example.com/product/path.jpg",
},
],
},
"checkout.updated": {
name: "Checkout Updated",
user_id,
fbc,
fbp,
postal_code: (_32 = (_31 = data === null || data === void 0 ? void 0 : data.customer) === null || _31 === void 0 ? void 0 : _31.address) === null || _32 === void 0 ? void 0 : _32.postal_code,
country: (_34 = (_33 = data === null || data === void 0 ? void 0 : data.customer) === null || _33 === void 0 ? void 0 : _33.address) === null || _34 === void 0 ? void 0 : _34.country_code,
checkout_id: data === null || data === void 0 ? void 0 : data.id,
transaction_id: data === null || data === void 0 ? void 0 : data.transaction_id,
checkout_status: data === null || data === void 0 ? void 0 : data.status,
paddle_customer_id: data === null || data === void 0 ? void 0 : data.customer.id,
price_id: (_35 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _35 === void 0 ? void 0 : _35.price_id,
product_id: (_36 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _36 === void 0 ? void 0 : _36.product.id,
product_name: (_37 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _37 === void 0 ? void 0 : _37.product.name,
billing_cycle_interval: (_39 = (_38 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _38 === void 0 ? void 0 : _38.billing_cycle) === null || _39 === void 0 ? void 0 : _39.interval,
billing_cycle_frequency: (_41 = (_40 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _40 === void 0 ? void 0 : _40.billing_cycle) === null || _41 === void 0 ? void 0 : _41.frequency,
trial_period_interval: (_43 = (_42 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _42 === void 0 ? void 0 : _42.trial_period) === null || _43 === void 0 ? void 0 : _43.interval,
trial_period_frequency: (_45 = (_44 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _44 === void 0 ? void 0 : _44.trial_period) === null || _45 === void 0 ? void 0 : _45.frequency,
value: (_46 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _46 === void 0 ? void 0 : _46.subtotal,
price_subtotal: (_47 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _47 === void 0 ? void 0 : _47.subtotal,
price_discount: (_48 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _48 === void 0 ? void 0 : _48.discount,
price_balance: (_49 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _49 === void 0 ? void 0 : _49.balance,
price_total: (_50 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _50 === void 0 ? void 0 : _50.total,
price_name: (_51 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _51 === void 0 ? void 0 : _51.price_name,
currency: data === null || data === void 0 ? void 0 : data.currency_code,
payment_method: data === null || data === void 0 ? void 0 : data.payment.method_details.type,
discount_id: (_52 = data === null || data === void 0 ? void 0 : data.discount) === null || _52 === void 0 ? void 0 : _52.id,
discount_code: (_53 = data === null || data === void 0 ? void 0 : data.discount) === null || _53 === void 0 ? void 0 : _53.code,
},
"checkout.warning": {
name: "Checkout Warning",
user_id,
fbc,
fbp,
postal_code: (_55 = (_54 = data === null || data === void 0 ? void 0 : data.customer) === null || _54 === void 0 ? void 0 : _54.address) === null || _55 === void 0 ? void 0 : _55.postal_code,
country: (_57 = (_56 = data === null || data === void 0 ? void 0 : data.customer) === null || _56 === void 0 ? void 0 : _56.address) === null || _57 === void 0 ? void 0 : _57.country_code,
type: type,
code: code,
detail: detail,
documentation_url: documentation_url,
errors_field: errors === null || errors === void 0 ? void 0 : errors.map(t => t.field).join(),
errors_message: errors === null || errors === void 0 ? void 0 : errors.map(t => t.message).join(),
},
"checkout.error": {
name: "Checkout Error",
user_id,
fbc,
fbp,
postal_code: (_59 = (_58 = data === null || data === void 0 ? void 0 : data.customer) === null || _58 === void 0 ? void 0 : _58.address) === null || _59 === void 0 ? void 0 : _59.postal_code,
country: (_61 = (_60 = data === null || data === void 0 ? void 0 : data.customer) === null || _60 === void 0 ? void 0 : _60.address) === null || _61 === void 0 ? void 0 : _61.country_code,
type: error === null || error === void 0 ? void 0 : error.type,
code: error === null || error === void 0 ? void 0 : error.code,
detail: error === null || error === void 0 ? void 0 : error.detail,
documentation_url: error === null || error === void 0 ? void 0 : error.documentation_url,
},
"checkout.payment.selected": {
name: "Checkout Payment Selected",
user_id,
fbc,
fbp,
postal_code: (_63 = (_62 = data === null || data === void 0 ? void 0 : data.customer) === null || _62 === void 0 ? void 0 : _62.address) === null || _63 === void 0 ? void 0 : _63.postal_code,
country: (_65 = (_64 = data === null || data === void 0 ? void 0 : data.customer) === null || _64 === void 0 ? void 0 : _64.address) === null || _65 === void 0 ? void 0 : _65.country_code,
checkout_id: data === null || data === void 0 ? void 0 : data.id,
transaction_id: transaction_id,
checkout_status: data === null || data === void 0 ? void 0 : data.status,
paddle_customer_id: data === null || data === void 0 ? void 0 : data.customer.id,
price_id: (_66 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _66 === void 0 ? void 0 : _66.price_id,
product_id: (_67 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _67 === void 0 ? void 0 : _67.product.id,
product_name: (_68 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _68 === void 0 ? void 0 : _68.product.name,
billing_cycle_interval: (_70 = (_69 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _69 === void 0 ? void 0 : _69.billing_cycle) === null || _70 === void 0 ? void 0 : _70.interval,
billing_cycle_frequency: (_72 = (_71 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _71 === void 0 ? void 0 : _71.billing_cycle) === null || _72 === void 0 ? void 0 : _72.frequency,
trial_period_interval: (_74 = (_73 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _73 === void 0 ? void 0 : _73.trial_period) === null || _74 === void 0 ? void 0 : _74.interval,
trial_period_frequency: (_76 = (_75 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _75 === void 0 ? void 0 : _75.trial_period) === null || _76 === void 0 ? void 0 : _76.frequency,
value: (_77 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _77 === void 0 ? void 0 : _77.subtotal,
price_subtotal: (_78 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _78 === void 0 ? void 0 : _78.subtotal,
price_discount: (_79 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _79 === void 0 ? void 0 : _79.discount,
price_balance: (_80 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _80 === void 0 ? void 0 : _80.balance,
price_total: (_81 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _81 === void 0 ? void 0 : _81.total,
price_name: (_82 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _82 === void 0 ? void 0 : _82.price_name,
currency: data === null || data === void 0 ? void 0 : data.currency_code,
payment_method: data === null || data === void 0 ? void 0 : data.payment.method_details.type,
discount_id: (_83 = data === null || data === void 0 ? void 0 : data.discount) === null || _83 === void 0 ? void 0 : _83.id,
discount_code: (_84 = data === null || data === void 0 ? void 0 : data.discount) === null || _84 === void 0 ? void 0 : _84.code,
},
"checkout.customer.created": {
name: "Paddle Customer Created",
user_id,
fbc,
fbp,
postal_code: (_86 = (_85 = data === null || data === void 0 ? void 0 : data.customer) === null || _85 === void 0 ? void 0 : _85.address) === null || _86 === void 0 ? void 0 : _86.postal_code,
country: (_88 = (_87 = data === null || data === void 0 ? void 0 : data.customer) === null || _87 === void 0 ? void 0 : _87.address) === null || _88 === void 0 ? void 0 : _88.country_code,
checkout_id: data === null || data === void 0 ? void 0 : data.id,
transaction_id: transaction_id,
checkout_status: data === null || data === void 0 ? void 0 : data.status,
paddle_customer_id: data === null || data === void 0 ? void 0 : data.customer.id,
price_id: (_89 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _89 === void 0 ? void 0 : _89.price_id,
product_id: (_90 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _90 === void 0 ? void 0 : _90.product.id,
product_name: (_91 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _91 === void 0 ? void 0 : _91.product.name,
billing_cycle_interval: (_93 = (_92 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _92 === void 0 ? void 0 : _92.billing_cycle) === null || _93 === void 0 ? void 0 : _93.interval,
billing_cycle_frequency: (_95 = (_94 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _94 === void 0 ? void 0 : _94.billing_cycle) === null || _95 === void 0 ? void 0 : _95.frequency,
trial_period_interval: (_97 = (_96 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _96 === void 0 ? void 0 : _96.trial_period) === null || _97 === void 0 ? void 0 : _97.interval,
trial_period_frequency: (_99 = (_98 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _98 === void 0 ? void 0 : _98.trial_period) === null || _99 === void 0 ? void 0 : _99.frequency,
value: (_100 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _100 === void 0 ? void 0 : _100.subtotal,
price_subtotal: (_101 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _101 === void 0 ? void 0 : _101.subtotal,
price_discount: (_102 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _102 === void 0 ? void 0 : _102.discount,
price_balance: (_103 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _103 === void 0 ? void 0 : _103.balance,
price_total: (_104 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _104 === void 0 ? void 0 : _104.total,
price_name: (_105 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _105 === void 0 ? void 0 : _105.price_name,
currency: data === null || data === void 0 ? void 0 : data.currency_code,
payment_method: data === null || data === void 0 ? void 0 : data.payment.method_details.type,
discount_id: (_106 = data === null || data === void 0 ? void 0 : data.discount) === null || _106 === void 0 ? void 0 : _106.id,
discount_code: (_107 = data === null || data === void 0 ? void 0 : data.discount) === null || _107 === void 0 ? void 0 : _107.code,
},
"checkout.customer.updated": {
name: "Paddle Customer Updated",
user_id,
fbc,
fbp,
postal_code: (_109 = (_108 = data === null || data === void 0 ? void 0 : data.customer) === null || _108 === void 0 ? void 0 : _108.address) === null || _109 === void 0 ? void 0 : _109.postal_code,
country: (_111 = (_110 = data === null || data === void 0 ? void 0 : data.customer) === null || _110 === void 0 ? void 0 : _110.address) === null || _111 === void 0 ? void 0 : _111.country_code,
checkout_id: data === null || data === void 0 ? void 0 : data.id,
transaction_id: transaction_id,
checkout_status: data === null || data === void 0 ? void 0 : data.status,
paddle_customer_id: data === null || data === void 0 ? void 0 : data.customer.id,
price_id: (_112 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _112 === void 0 ? void 0 : _112.price_id,
product_id: (_113 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _113 === void 0 ? void 0 : _113.product.id,
product_name: (_114 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _114 === void 0 ? void 0 : _114.product.name,
billing_cycle_interval: (_116 = (_115 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _115 === void 0 ? void 0 : _115.billing_cycle) === null || _116 === void 0 ? void 0 : _116.interval,
billing_cycle_frequency: (_118 = (_117 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _117 === void 0 ? void 0 : _117.billing_cycle) === null || _118 === void 0 ? void 0 : _118.frequency,
trial_period_interval: (_120 = (_119 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _119 === void 0 ? void 0 : _119.trial_period) === null || _120 === void 0 ? void 0 : _120.interval,
trial_period_frequency: (_122 = (_121 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _121 === void 0 ? void 0 : _121.trial_period) === null || _122 === void 0 ? void 0 : _122.frequency,
value: (_123 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _123 === void 0 ? void 0 : _123.subtotal,
price_subtotal: (_124 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _124 === void 0 ? void 0 : _124.subtotal,
price_discount: (_125 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _125 === void 0 ? void 0 : _125.discount,
price_balance: (_126 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _126 === void 0 ? void 0 : _126.balance,
price_total: (_127 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _127 === void 0 ? void 0 : _127.total,
price_name: (_128 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _128 === void 0 ? void 0 : _128.price_name,
currency: data === null || data === void 0 ? void 0 : data.currency_code,
payment_method: data === null || data === void 0 ? void 0 : data.payment.method_details.type,
discount_id: (_129 = data === null || data === void 0 ? void 0 : data.discount) === null || _129 === void 0 ? void 0 : _129.id,
discount_code: (_130 = data === null || data === void 0 ? void 0 : data.discount) === null || _130 === void 0 ? void 0 : _130.code,
},
"checkout.customer.removed": {
name: "Paddle Customer Removed",
user_id,
fbc,
fbp,
postal_code: (_132 = (_131 = data === null || data === void 0 ? void 0 : data.customer) === null || _131 === void 0 ? void 0 : _131.address) === null || _132 === void 0 ? void 0 : _132.postal_code,
country: (_134 = (_133 = data === null || data === void 0 ? void 0 : data.customer) === null || _133 === void 0 ? void 0 : _133.address) === null || _134 === void 0 ? void 0 : _134.country_code,
checkout_id: data === null || data === void 0 ? void 0 : data.id,
transaction_id: transaction_id,
checkout_status: data === null || data === void 0 ? void 0 : data.status,
paddle_customer_id: data === null || data === void 0 ? void 0 : data.customer.id,
price_id: (_135 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _135 === void 0 ? void 0 : _135.price_id,
product_id: (_136 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _136 === void 0 ? void 0 : _136.product.id,
product_name: (_137 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _137 === void 0 ? void 0 : _137.product.name,
billing_cycle_interval: (_139 = (_138 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _138 === void 0 ? void 0 : _138.billing_cycle) === null || _139 === void 0 ? void 0 : _139.interval,
billing_cycle_frequency: (_141 = (_140 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _140 === void 0 ? void 0 : _140.billing_cycle) === null || _141 === void 0 ? void 0 : _141.frequency,
trial_period_interval: (_143 = (_142 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _142 === void 0 ? void 0 : _142.trial_period) === null || _143 === void 0 ? void 0 : _143.interval,
trial_period_frequency: (_145 = (_144 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _144 === void 0 ? void 0 : _144.trial_period) === null || _145 === void 0 ? void 0 : _145.frequency,
value: (_146 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _146 === void 0 ? void 0 : _146.subtotal,
price_subtotal: (_147 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _147 === void 0 ? void 0 : _147.subtotal,
price_discount: (_148 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _148 === void 0 ? void 0 : _148.discount,
price_balance: (_149 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _149 === void 0 ? void 0 : _149.balance,
price_total: (_150 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _150 === void 0 ? void 0 : _150.total,
price_name: (_151 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _151 === void 0 ? void 0 : _151.price_name,
currency: data === null || data === void 0 ? void 0 : data.currency_code,
payment_method: data === null || data === void 0 ? void 0 : data.payment.method_details.type,
discount_id: (_152 = data === null || data === void 0 ? void 0 : data.discount) === null || _152 === void 0 ? void 0 : _152.id,
discount_code: (_153 = data === null || data === void 0 ? void 0 : data.discount) === null || _153 === void 0 ? void 0 : _153.code,
},
"checkout.payment.initiated": {
name: "Checkout Payment Initiated",
user_id,
fbc,
fbp,
postal_code: (_155 = (_154 = data === null || data === void 0 ? void 0 : data.customer) === null || _154 === void 0 ? void 0 : _154.address) === null || _155 === void 0 ? void 0 : _155.postal_code,
country: (_157 = (_156 = data === null || data === void 0 ? void 0 : data.customer) === null || _156 === void 0 ? void 0 : _156.address) === null || _157 === void 0 ? void 0 : _157.country_code,
checkout_id: data === null || data === void 0 ? void 0 : data.id,
transaction_id: transaction_id,
checkout_status: data === null || data === void 0 ? void 0 : data.status,
paddle_customer_id: data === null || data === void 0 ? void 0 : data.customer.id,
price_id: (_158 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _158 === void 0 ? void 0 : _158.price_id,
product_id: (_159 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _159 === void 0 ? void 0 : _159.product.id,
product_name: (_160 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _160 === void 0 ? void 0 : _160.product.name,
billing_cycle_interval: (_162 = (_161 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _161 === void 0 ? void 0 : _161.billing_cycle) === null || _162 === void 0 ? void 0 : _162.interval,
billing_cycle_frequency: (_164 = (_163 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _163 === void 0 ? void 0 : _163.billing_cycle) === null || _164 === void 0 ? void 0 : _164.frequency,
trial_period_interval: (_166 = (_165 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _165 === void 0 ? void 0 : _165.trial_period) === null || _166 === void 0 ? void 0 : _166.interval,
trial_period_frequency: (_168 = (_167 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _167 === void 0 ? void 0 : _167.trial_period) === null || _168 === void 0 ? void 0 : _168.frequency,
value: (_169 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _169 === void 0 ? void 0 : _169.subtotal,
price_subtotal: (_170 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _170 === void 0 ? void 0 : _170.subtotal,
price_discount: (_171 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _171 === void 0 ? void 0 : _171.discount,
price_balance: (_172 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _172 === void 0 ? void 0 : _172.balance,
price_total: (_173 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _173 === void 0 ? void 0 : _173.total,
price_name: (_174 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _174 === void 0 ? void 0 : _174.price_name,
currency: data === null || data === void 0 ? void 0 : data.currency_code,
payment_method: data === null || data === void 0 ? void 0 : data.payment.method_details.type,
discount_id: (_175 = data === null || data === void 0 ? void 0 : data.discount) === null || _175 === void 0 ? void 0 : _175.id,
discount_code: (_176 = data === null || data === void 0 ? void 0 : data.discount) === null || _176 === void 0 ? void 0 : _176.code,
},
"checkout.payment.failed": {
name: "Checkout Payment Failed",
user_id,
fbc,
fbp,
postal_code: (_178 = (_177 = data === null || data === void 0 ? void 0 : data.customer) === null || _177 === void 0 ? void 0 : _177.address) === null || _178 === void 0 ? void 0 : _178.postal_code,
country: (_180 = (_179 = data === null || data === void 0 ? void 0 : data.customer) === null || _179 === void 0 ? void 0 : _179.address) === null || _180 === void 0 ? void 0 : _180.country_code,
checkout_id: data === null || data === void 0 ? void 0 : data.id,
transaction_id: transaction_id,
checkout_status: data === null || data === void 0 ? void 0 : data.status,
paddle_customer_id: data === null || data === void 0 ? void 0 : data.customer.id,
price_id: (_181 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _181 === void 0 ? void 0 : _181.price_id,
product_id: (_182 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _182 === void 0 ? void 0 : _182.product.id,
product_name: (_183 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _183 === void 0 ? void 0 : _183.product.name,
billing_cycle_interval: (_185 = (_184 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _184 === void 0 ? void 0 : _184.billing_cycle) === null || _185 === void 0 ? void 0 : _185.interval,
billing_cycle_frequency: (_187 = (_186 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _186 === void 0 ? void 0 : _186.billing_cycle) === null || _187 === void 0 ? void 0 : _187.frequency,
trial_period_interval: (_189 = (_188 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _188 === void 0 ? void 0 : _188.trial_period) === null || _189 === void 0 ? void 0 : _189.interval,
trial_period_frequency: (_191 = (_190 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _190 === void 0 ? void 0 : _190.trial_period) === null || _191 === void 0 ? void 0 : _191.frequency,
value: (_192 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _192 === void 0 ? void 0 : _192.subtotal,
price_subtotal: (_193 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _193 === void 0 ? void 0 : _193.subtotal,
price_discount: (_194 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _194 === void 0 ? void 0 : _194.discount,
price_balance: (_195 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _195 === void 0 ? void 0 : _195.balance,
price_total: (_196 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _196 === void 0 ? void 0 : _196.total,
price_name: (_197 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _197 === void 0 ? void 0 : _197.price_name,
currency: data === null || data === void 0 ? void 0 : data.currency_code,
payment_method: data === null || data === void 0 ? void 0 : data.payment.method_details.type,
discount_id: (_198 = data === null || data === void 0 ? void 0 : data.discount) === null || _198 === void 0 ? void 0 : _198.id,
discount_code: (_199 = data === null || data === void 0 ? void 0 : data.discount) === null || _199 === void 0 ? void 0 : _199.code,
},
"checkout.discount.applied": {
name: "Checkout Discount Applied",
user_id,
fbc,
fbp,
postal_code: (_201 = (_200 = data === null || data === void 0 ? void 0 : data.customer) === null || _200 === void 0 ? void 0 : _200.address) === null || _201 === void 0 ? void 0 : _201.postal_code,
country: (_203 = (_202 = data === null || data === void 0 ? void 0 : data.customer) === null || _202 === void 0 ? void 0 : _202.address) === null || _203 === void 0 ? void 0 : _203.country_code,
checkout_id: data === null || data === void 0 ? void 0 : data.id,
transaction_id: transaction_id,
checkout_status: data === null || data === void 0 ? void 0 : data.status,
paddle_customer_id: data === null || data === void 0 ? void 0 : data.customer.id,
price_id: (_204 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _204 === void 0 ? void 0 : _204.price_id,
product_id: (_205 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _205 === void 0 ? void 0 : _205.product.id,
product_name: (_206 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _206 === void 0 ? void 0 : _206.product.name,
billing_cycle_interval: (_208 = (_207 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _207 === void 0 ? void 0 : _207.billing_cycle) === null || _208 === void 0 ? void 0 : _208.interval,
billing_cycle_frequency: (_210 = (_209 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _209 === void 0 ? void 0 : _209.billing_cycle) === null || _210 === void 0 ? void 0 : _210.frequency,
trial_period_interval: (_212 = (_211 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _211 === void 0 ? void 0 : _211.trial_period) === null || _212 === void 0 ? void 0 : _212.interval,
trial_period_frequency: (_214 = (_213 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _213 === void 0 ? void 0 : _213.trial_period) === null || _214 === void 0 ? void 0 : _214.frequency,
value: (_215 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _215 === void 0 ? void 0 : _215.subtotal,
price_subtotal: (_216 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _216 === void 0 ? void 0 : _216.subtotal,
price_discount: (_217 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _217 === void 0 ? void 0 : _217.discount,
price_balance: (_218 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _218 === void 0 ? void 0 : _218.balance,
price_total: (_219 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _219 === void 0 ? void 0 : _219.total,
price_name: (_220 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _220 === void 0 ? void 0 : _220.price_name,
currency: data === null || data === void 0 ? void 0 : data.currency_code,
payment_method: data === null || data === void 0 ? void 0 : data.payment.method_details.type,
discount_id: (_221 = data === null || data === void 0 ? void 0 : data.discount) === null || _221 === void 0 ? void 0 : _221.id,
discount_code: (_222 = data === null || data === void 0 ? void 0 : data.discount) === null || _222 === void 0 ? void 0 : _222.code,
},
"checkout.discount.removed": {
name: "Checkout Discount Removed",
user_id,
fbc,
fbp,
postal_code: (_224 = (_223 = data === null || data === void 0 ? void 0 : data.customer) === null || _223 === void 0 ? void 0 : _223.address) === null || _224 === void 0 ? void 0 : _224.postal_code,
country: (_226 = (_225 = data === null || data === void 0 ? void 0 : data.customer) === null || _225 === void 0 ? void 0 : _225.address) === null || _226 === void 0 ? void 0 : _226.country_code,
checkout_id: data === null || data === void 0 ? void 0 : data.id,
transaction_id: transaction_id,
checkout_status: data === null || data === void 0 ? void 0 : data.status,
paddle_customer_id: data === null || data === void 0 ? void 0 : data.customer.id,
price_id: (_227 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _227 === void 0 ? void 0 : _227.price_id,
product_id: (_228 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _228 === void 0 ? void 0 : _228.product.id,
product_name: (_229 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _229 === void 0 ? void 0 : _229.product.name,
billing_cycle_interval: (_231 = (_230 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _230 === void 0 ? void 0 : _230.billing_cycle) === null || _231 === void 0 ? void 0 : _231.interval,
billing_cycle_frequency: (_233 = (_232 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _232 === void 0 ? void 0 : _232.billing_cycle) === null || _233 === void 0 ? void 0 : _233.frequency,
trial_period_interval: (_235 = (_234 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _234 === void 0 ? void 0 : _234.trial_period) === null || _235 === void 0 ? void 0 : _235.interval,
trial_period_frequency: (_237 = (_236 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _236 === void 0 ? void 0 : _236.trial_period) === null || _237 === void 0 ? void 0 : _237.frequency,
value: (_238 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _238 === void 0 ? void 0 : _238.subtotal,
price_subtotal: (_239 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _239 === void 0 ? void 0 : _239.subtotal,
price_discount: (_240 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _240 === void 0 ? void 0 : _240.discount,
price_balance: (_241 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _241 === void 0 ? void 0 : _241.balance,
price_total: (_242 = data === null || data === void 0 ? void 0 : data.recurring_totals) === null || _242 === void 0 ? void 0 : _242.total,
price_name: (_243 = data === null || data === void 0 ? void 0 : data.items[0]) === null || _243 === void 0 ? void 0 : _243.price_name,
currency: data === null || data === void 0 ? void 0 : data.currency_code,
payment_method: data === null || data === void 0 ? void 0 : data.payment.method_details.type,
discount_id: (_244 = data === null || data === void 0 ? void 0 : data.discount) === null || _244 === void 0 ? void 0 : _244.id,
discount_code: (_245 = data === null || data === void 0 ? void 0 : data.discount) === null || _245 === void 0 ? void 0 : _245.code,
},
};
const e2 = map[(_246 = e.name) !== null && _246 !== void 0 ? _246 : ""];
if (!e2) {
return;
}
const { name } = e2, rest = __rest(e2, ["name"]);
analytics.track(name, rest);
}
catch (e) {
console.warn("Segment tracking of paddle event failed", e);
}
}
function handlePaddleEvent(e) {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
console.log("Paddle event", e);
const geoFeed = yield (0, getGeoFeed_1.getGeoFeed)();
const priceId = (_b = (_a = e.data) === null || _a === void 0 ? void 0 : _a.items[0]) === null || _b === void 0 ? void 0 : _b.price_id;
const currencyCode = (_c = e.data) === null || _c === void 0 ? void 0 : _c.currency_code;
const transactionId = (_d = e.data) === null || _d === void 0 ? void 0 : _d.transaction_id;
if (priceId || currencyCode) {
window.PGdataLayer.ecomm = {
transaction: { id: transactionId, currency_code: currencyCode },
products: ((_f = (_e = e.data) === null || _e === void 0 ? void 0 : _e.items) !== null && _f !== void 0 ? _f : []).map(t => ({
quantity: t.quantity,
name: t.price_name,
price_id: t.price_id,
})),
};
}
const postalCode = (_j = (_h = (_g = e.data) === null || _g === void 0 ? void 0 : _g.customer) === null || _h === void 0 ? void 0 : _h.address) === null || _j === void 0 ? void 0 : _j.postal_code;
if (postalCode) {
window.PGdataLayer.user = Object.assign(Object.assign({}, ((_k = window.PGdataLayer.user) !== null && _k !== void 0 ? _k : {})), { postalCode });
const segment = yield (0, segment_1.ifSegmentReady)();
if (segment && isCheckoutCompletedEvent(e)) {
segment.identify({
address: { postalCode, country: (_o = (_m = (_l = e.data) === null || _l === void 0 ? void 0 : _l.customer) === null || _m === void 0 ? void 0 : _m.address) === null || _o === void 0 ? void 0 : _o.country_code },
});
}
}
triggerSegmentEvent(e, geoFeed);
if (isCheckoutCompletedEvent(e)) {
(0, pgDataLayer_1.dataLayerPush)("event_bin_action", "event_buy_now_checkout_complete", `checkout_completed_${window.location.pathname.split("/").at(-1)}`, (_q = (_p = e.data) === null || _p === void 0 ? void 0 : _p.recurring_totals) === null || _q === void 0 ? void 0 : _q.subtotal);
}
});
}
function isCheckoutCompletedEvent(e) {
return e.name === "checkout.completed";
}
/***/ }),
/***/ 6758:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.parseJwt = parseJwt;
function parseJwt(token) {
const base64Url = token.split(".")[1];
const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
const jsonPayload = decodeURIComponent(window
.atob(base64)
.split("")
.map(function (c) {
return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
})
.join(""));
return JSON.parse(jsonPayload);
}
/***/ }),
/***/ 7350:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
var _a, _b;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.dataLayerPush = void 0;
exports.initPgDataLayer = initPgDataLayer;
exports.dataLayerPush2 = dataLayerPush2;
/* eslint-disable @typescript-eslint/no-explicit-any */
const config_1 = __webpack_require__(7028);
const registerLead_1 = __webpack_require__(2517);
const { pgSiteEnvironment, pgGoogleAnalyticsLocal, pgGoogleAnalyticsReportingView, pgConsentOverlayID, pgFacebookRemarketingID, pgSegment, } = config_1.config;
const lead = (0, registerLead_1.getRegisterLead)();
const user = lead ? { email: lead === null || lead === void 0 ? void 0 : lead.email, firstName: lead === null || lead === void 0 ? void 0 : lead.nickname, id: lead === null || lead === void 0 ? void 0 : lead.consumerId } : null;
const pgDataLayer = (_a = window === null || window === void 0 ? void 0 : window.PGdataLayer) !== null && _a !== void 0 ? _a : Object.assign({ GTM: {
SiteTouchpoint: "46984",
SiteBrand: "Pampers",
SiteLanguage: "English",
SitePlatform: "Multibrand.com",
SiteEnvironment: pgSiteEnvironment,
SiteHost: "Webflow",
SiteTechnicalAgency: "Zemingo",
SiteStatus: "Live",
SiteLocalContainer: "GTM-PQB4L4QL", // "GTM-KQNZ2P2",
GoogleAnalyticsLocal: pgGoogleAnalyticsLocal,
GoogleAnalyticsBrand: "",
GoogleAnalyticsGA4MeasurementID: "G-LL0W59K01B", // "G-WHN3KE0SQY"
GoogleAnalyticsSiteSpeedSampleRate: "high",
GoogleAnalyticsReportingView: pgGoogleAnalyticsReportingView,
ConsentOverlay: "OneTrust",
ConsentOverlayID: pgConsentOverlayID,
SitePrivacyProtection: "CCPA",
FacebookConnectAppID: "924059352110555", //"1402968366699773",
FacebookConnectLocale: "en_US",
FacebookRemarketingID: pgFacebookRemarketingID,
BINPlatform: "Webflow",
Segment: pgSegment,
Segmanta: "true",
SiteCurrency: "USD",
GoogleAnalyticsEETransOnEvent: "TRUE",
GoogleAnalyticsAllowLinker: "TRUE",
GoogleAnalyticsOptimizeContainerID: "",
} }, (user ? { user } : {}));
function initPgDataLayer() {
if (!window)
return;
if (!window.PGdataLayer) {
window.PGdataLayer = pgDataLayer;
}
if (!window.dataLayerPush) {
window.dataLayerPush = exports.dataLayerPush;
}
}
exports.dataLayerPush = (_b = window === null || window === void 0 ? void 0 : window.dataLayerPush) !== null && _b !== void 0 ? _b : ((category, action, label, value = 0, interaction = false) => {
if (!window.dataLayer) {
window.dataLayer = [];
}
window.dataLayer.push({
event: "customEvent",
GAeventCategory: category,
GAeventAction: action,
GAeventLabel: label,
GAeventValue: value,
GAeventNonInteraction: interaction,
});
});
function dataLayerPush2(_a) {
var { category, action, label, value = 0, interaction = false } = _a, rest = __rest(_a, ["category", "action", "label", "value", "interaction"]);
if (!window.dataLayer) {
window.dataLayer = [];
}
window.dataLayer.push(Object.assign({ event: "customEvent", GAeventCategory: category, GAeventAction: action, GAeventLabel: label, GAeventValue: value, GAeventNonInteraction: interaction }, rest));
}
// initPgDataLayer()
/***/ }),
/***/ 8542:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getPricingPreview = getPricingPreview;
const config_1 = __webpack_require__(7028);
const getGeoFeed_1 = __webpack_require__(7539);
function getPricingPreview(_a) {
return __awaiter(this, arguments, void 0, function* ({ paddle, priceSetId, discountRate }) {
var _b, _c;
const paddlePriceIds = (_b = config_1.config.paddlePriceIdSets[priceSetId !== null && priceSetId !== void 0 ? priceSetId : ""]) !== null && _b !== void 0 ? _b : config_1.config.paddlePriceIds;
const items = config_1.planKeys.map(key => ({ priceId: paddlePriceIds[key], quantity: 1 }));
const geoFeed = yield (0, getGeoFeed_1.getGeoFeed)();
const previewRes = yield paddle.PricePreview({
items,
address: {
countryCode: (_c = geoFeed === null || geoFeed === void 0 ? void 0 : geoFeed.country) !== null && _c !== void 0 ? _c : "US",
},
});
console.log("PricePreview", previewRes);
const formatPrice = (price, opts) => {
let s = previewRes.data.details.lineItems[0].formattedTotals.discount.replace("0.00", price.toFixed(2));
if (previewRes.data.currencyCode === "CAD" && !(opts === null || opts === void 0 ? void 0 : opts.short)) {
s = s.replace("$", "CA$");
}
return s;
};
const terms = [1, 3, 12];
const dayTerms = [30, 90, 365];
let i = -1;
const plan1Price = +previewRes.data.details.lineItems[0].totals.subtotal / 100;
const res = { items: {}, res: previewRes, reqItems: items, formatPrice };
for (const playKey of config_1.planKeys) {
i++;
const lineItem = previewRes.data.details.lineItems[i];
const term = terms[i];
const dayTerm = dayTerms[i];
const price = +lineItem.totals.subtotal / 100;
const monthlyPrice = price / term;
const priceInPlan1 = plan1Price * term;
const discountRateOld = 1 - price / priceInPlan1;
const priceBeforeDiscount = price / (1 - discountRateOld);
res.items[playKey] = {
monthlyPrice,
price,
monthlyPriceFormatted: formatPrice(monthlyPrice),
priceFormatted: formatPrice(price),
priceDay: price / dayTerm,
priceDayFormatted: formatPrice(price / dayTerm),
priceFormatted2: lineItem.formattedTotals.total,
zeroFormatted: formatPrice(0),
lineItem,
reqItem: items[i],
priceBeforeDiscount,
discountRateFormatted: `${(discountRate * 100).toFixed(0)}%`,
discountRateFormattedOld: `${(discountRateOld * 100).toFixed(0)}%`,
discountAmount: priceBeforeDiscount - price,
};
}
return res;
});
}
/***/ }),
/***/ 3481:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.loadRecaptcha = loadRecaptcha;
const config_1 = __webpack_require__(7028);
function loadScript(src) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
const script = document.createElement("script");
script.src = src;
script.onload = () => resolve();
script.onerror = () => reject();
document.head.appendChild(script);
});
});
}
function _loadRecaptcha(siteKey) {
return __awaiter(this, void 0, void 0, function* () {
yield loadScript(`https://www.google.com/recaptcha/enterprise.js?render=${siteKey !== null && siteKey !== void 0 ? siteKey : config_1.config.recaptchaSiteKey}`);
yield new Promise(resolve => grecaptcha.enterprise.ready(resolve));
return grecaptcha;
});
}
let p = null;
function loadRecaptcha(siteKey) {
if (p)
return p;
p = _loadRecaptcha(siteKey);
return p;
}
/***/ }),
/***/ 2517:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getRegisterLead = getRegisterLead;
exports.setRegisterLead = setRegisterLead;
exports.getPaddleEventData = getPaddleEventData;
exports.setPaddleEventData = setPaddleEventData;
exports.updatePgDataLayerUser = updatePgDataLayerUser;
function getRegisterLead() {
const user = localStorage.getItem("registerLead");
if (!user)
return null;
try {
return JSON.parse(user);
}
catch (err) {
console.warn("registerLead", err);
return null;
}
}
function setRegisterLead(user) {
if (!user) {
localStorage.removeItem("registerLead");
return;
}
localStorage.setItem("registerLead", JSON.stringify(user));
}
function getPaddleEventData() {
const user = localStorage.getItem("paddleEventData");
if (!user)
return null;
try {
return JSON.parse(user);
}
catch (err) {
console.warn("paddleEventData", err);
return null;
}
}
function setPaddleEventData(v) {
if (!v) {
localStorage.removeItem("paddleEventData");
return;
}
localStorage.setItem("paddleEventData", JSON.stringify(v));
}
function updatePgDataLayerUser() {
var _a;
const lead = getRegisterLead();
const user = lead ? { email: lead === null || lead === void 0 ? void 0 : lead.email, firstName: lead === null || lead === void 0 ? void 0 : lead.nickname, id: lead === null || lead === void 0 ? void 0 : lead.consumerId } : null;
if (!user)
return;
window.PGdataLayer.user = Object.assign(Object.assign({}, ((_a = window.PGdataLayer.user) !== null && _a !== void 0 ? _a : {})), user);
}
/***/ }),
/***/ 1685:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.whenSegmentReady = whenSegmentReady;
exports.ifSegmentReady = ifSegmentReady;
exports.addUserIdToPgDataLayer = addUserIdToPgDataLayer;
exports.setSegmentEventOnTrigger = setSegmentEventOnTrigger;
exports.hookUpSegmentEvents = hookUpSegmentEvents;
const sleep_1 = __webpack_require__(9879);
/* eslint-disable @typescript-eslint/no-explicit-any */
function whenSegmentReady() {
return new Promise(resolve => {
var _a, _b;
const win = window;
if (!((_a = win.analytics) === null || _a === void 0 ? void 0 : _a.ready)) {
win.analytics = (_b = win.analytics) !== null && _b !== void 0 ? _b : [];
win.analytics.push(["ready", () => { var _a; return resolve((_a = window.analytics) !== null && _a !== void 0 ? _a : null); }]);
return;
}
window.analytics.ready(() => { var _a; return resolve((_a = window.analytics) !== null && _a !== void 0 ? _a : null); });
});
}
function ifSegmentReady(timeout = 1000) {
return Promise.race([whenSegmentReady(), (0, sleep_1.sleep)(timeout)]);
}
function addUserIdToPgDataLayer() {
return __awaiter(this, void 0, void 0, function* () {
var _a;
const analytics = yield whenSegmentReady();
if (!analytics)
return;
const id = analytics.user().id() || analytics.user().anonymousId();
if (!id)
return;
if (!window.PGdataLayer)
return;
window.PGdataLayer.user = Object.assign(Object.assign({}, ((_a = window.PGdataLayer.user) !== null && _a !== void 0 ? _a : {})), { id });
});
}
let _onTrigger = null;
function setSegmentEventOnTrigger(onTrigger) {
_onTrigger = onTrigger;
}
function hookUpSegmentEvents() {
document.querySelectorAll("[data-segment-event-name]").forEach(el => {
const eventName = el.getAttribute("data-segment-event-name");
el.addEventListener("click", () => __awaiter(this, void 0, void 0, function* () {
const props1 = {};
el.getAttributeNames()
.map(t => /^data-segment-event-prop-(.*)$/.exec(t))
.forEach(re => {
if (!re)
return;
props1[re[1]] = el.getAttribute(re[0]);
});
const e = { eventName, props: props1 };
_onTrigger === null || _onTrigger === void 0 ? void 0 : _onTrigger(e);
console.log("segment event", e.eventName, e.props);
const analytics = yield whenSegmentReady();
if (!analytics)
return;
analytics.track(e.eventName, e.props);
}));
});
}
/***/ }),
/***/ 8805:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.skeleton = skeleton;
function skeleton() {
addStyle();
const skeletonElements = Array.from(document.querySelectorAll("[ms-code-skeleton]"));
skeletonElements.forEach(element => {
// Create a skeleton div
const skeletonDiv = document.createElement("div");
skeletonDiv.classList.add("skeleton-loader");
// Add the skeleton div to the current element
element.style.position = "relative";
element.appendChild(skeletonDiv);
});
function destroy() {
const skeletonElements = Array.from(document.querySelectorAll("[ms-code-skeleton]"));
skeletonElements.forEach(element => {
// Remove the skeleton loader div after delay
const skeletonDiv = element.querySelector(".skeleton-loader");
if (!skeletonDiv)
return;
element.removeChild(skeletonDiv);
});
}
return destroy;
}
let styleAdded = false;
function addStyle() {
if (styleAdded)
return;
styleAdded = true;
_addStyle(`
.skeleton-loader {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
border-radius: inherit; /* Inherit the border-radius of the parent element */
background: linear-gradient(to right, #f6f7f8 25%, #e0e0e0 50%, #f6f7f8 75%);
background-size: 200% 100%; /* Increase the size of the background image */
z-index: 1; /* Make sure the skeleton loader is on top of the content */
animation: skeleton 1s infinite linear;
}
@keyframes skeleton {
0% { background-position: -100% 0; }
100% { background-position: 100% 0; }
}
[ms-code-skeleton] {
background-clip: padding-box;
}
`);
}
function _addStyle(style) {
const styleElement = document.createElement("style");
styleElement.textContent = style;
document.head.appendChild(styleElement);
}
/***/ }),
/***/ 9879:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.sleep = sleep;
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
/***/ }),
/***/ 1421:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.stars = void 0;
const star0_svg_1 = __importDefault(__webpack_require__(243));
const star1_svg_1 = __importDefault(__webpack_require__(7202));
const star2_svg_1 = __importDefault(__webpack_require__(8945));
const star3_svg_1 = __importDefault(__webpack_require__(4144));
const star4_svg_1 = __importDefault(__webpack_require__(1615));
const star5_svg_1 = __importDefault(__webpack_require__(9038));
const star6_svg_1 = __importDefault(__webpack_require__(1133));
const star7_svg_1 = __importDefault(__webpack_require__(2588));
const star8_svg_1 = __importDefault(__webpack_require__(4827));
const star9_svg_1 = __importDefault(__webpack_require__(2858));
const star10_svg_1 = __importDefault(__webpack_require__(6222));
exports.stars = [star0_svg_1.default, star1_svg_1.default, star2_svg_1.default, star3_svg_1.default, star4_svg_1.default, star5_svg_1.default, star6_svg_1.default, star7_svg_1.default, star8_svg_1.default, star9_svg_1.default, star10_svg_1.default];
/***/ }),
/***/ 497:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.timer = timer;
const sleep_1 = __webpack_require__(9879);
function timer(el, { startTime, totalSeconds, onChange, }) {
const minutesElement = el.querySelector(".timer-minutes");
const secondsElement = el.querySelector(".timer-seconds");
if (!minutesElement || !secondsElement) {
console.warn("timer: minutesElement or secondsElement not found");
return;
}
if (!startTime) {
startTime = new Date();
}
let lastLeft = null;
function updateTimerEl(left) {
const minutes = Math.floor(left / 60);
const seconds = left % 60;
minutesElement.textContent = String(minutes).padStart(2, "0");
secondsElement.textContent = String(seconds).padStart(2, "0");
}
function updateTimer() {
const passed = Math.floor((new Date().getTime() - startTime.getTime()) / 1000);
let left = totalSeconds - passed;
if (left <= 0) {
left = 0;
}
if (left === lastLeft)
return;
updateTimerEl(left);
lastLeft = left;
onChange === null || onChange === void 0 ? void 0 : onChange(left);
}
let _stop = false;
function startTimer() {
return __awaiter(this, void 0, void 0, function* () {
updateTimer();
while (!_stop) {
yield (0, sleep_1.sleep)(200);
updateTimer();
if (lastLeft === 0)
return;
}
});
}
void startTimer();
return {
stop() {
_stop = true;
},
};
}
/***/ }),
/***/ 2166:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.toggle = toggle;
exports.toggleOpacity = toggleOpacity;
function toggle(el, visible, opts) {
let el2 = el;
if (typeof el2 === "string") {
el2 = document.querySelector(el2);
}
if (!el2) {
if (!(opts === null || opts === void 0 ? void 0 : opts.noWarn)) {
console.debug("can't find element", el);
}
return;
}
el2.style.display = visible ? ((opts === null || opts === void 0 ? void 0 : opts.flex) ? "flex" : "block") : "none";
}
function toggleOpacity(el, visible, opts) {
let el2 = el;
if (typeof el2 === "string") {
el2 = document.querySelector(el2);
}
if (!el2) {
if (!(opts === null || opts === void 0 ? void 0 : opts.noWarn)) {
console.debug("can't find element", el);
}
return;
}
el2.style.opacity = visible ? "1" : "0";
}
/***/ }),
/***/ 5391:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.togglePassword = togglePassword;
/* eslint-disable @typescript-eslint/no-non-null-assertion */
function togglePassword() {
document.querySelectorAll(".text-field-wrapper .w-tab-menu").forEach(btn => {
btn.addEventListener("click", transform);
//flag of whether or not it is a password field or text field
let isPassword = true;
//this function will toggle the input between being a password or a text input
function transform() {
//copy the element itself, its html source, and value text to a variable
let myInput = btn.closest(".text-field-wrapper").querySelector("input");
const oldHtml = myInput.outerHTML;
const text = myInput.value;
let newHtml;
if (isPassword) {
//replace "password" with "text" in the html if it is a password field
newHtml = oldHtml.replace(/password/g, "text");
}
else {
//replace "text" with "password" if it is a text field
newHtml = oldHtml.replace(/text/g, "password");
}
//update the html
myInput.outerHTML = newHtml;
//restore the text value
myInput = btn.closest(".text-field-wrapper").querySelector("input");
myInput.value = text;
//toggle the isPassword flag
isPassword = !isPassword;
}
});
}
/***/ }),
/***/ 6441:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getUser = getUser;
exports.setUser = setUser;
function getUser() {
const user = localStorage.getItem("user");
if (!user)
return null;
try {
return JSON.parse(user);
}
catch (err) {
console.warn("getUser", err);
return null;
}
}
function setUser(user) {
if (!user) {
localStorage.removeItem("user");
return;
}
localStorage.setItem("user", JSON.stringify(user));
}
/***/ }),
/***/ 7839:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.blog = blog;
/* eslint-disable @typescript-eslint/no-non-null-assertion */
function blog() {
var _a;
console.log("blog");
const lists = Array.from(document.querySelectorAll(".articles"));
const articles = lists.flatMap(list => Array.from(list.querySelectorAll(".article")));
const articlesByDate = articles.sort((a, b) => {
var _a, _b;
const x = (_a = a.getAttribute("data-date")) !== null && _a !== void 0 ? _a : "";
const y = (_b = b.getAttribute("data-date")) !== null && _b !== void 0 ? _b : "";
return y.localeCompare(x);
});
document.querySelector(".all-articles").append(...articlesByDate);
const filters = Array.from(document.querySelectorAll(".cat-checkbox-2 input"));
const filterNames = {};
filters.forEach(el => {
var _a, _b;
el.addEventListener("change", filterByCategories);
filterNames[(_a = el.getAttribute("data-cat")) !== null && _a !== void 0 ? _a : ""] = (_b = el.closest(".cat-checkbox-2").textContent) !== null && _b !== void 0 ? _b : "";
});
(_a = document.querySelector("form[name=wf-form-cat-filters]")) === null || _a === void 0 ? void 0 : _a.addEventListener("submit", e => {
e.preventDefault();
e.stopPropagation();
});
articles.forEach(article => {
var _a, _b;
const cat = (_a = article.getAttribute("data-cat")) !== null && _a !== void 0 ? _a : "";
const tagsEl = article.querySelector(".tags-target");
tagsEl.textContent = tagsEl.textContent.replace("{{cat-name}}", (_b = filterNames[cat]) !== null && _b !== void 0 ? _b : "");
});
}
function filterByCategories() {
const categories = Array.from(document.querySelectorAll(".cat-checkbox-2 input:checked")).map(el => { var _a; return (_a = el.getAttribute("data-cat")) !== null && _a !== void 0 ? _a : ""; });
const articles = Array.from(document.querySelectorAll(".article"));
if (categories.length === 0) {
articles.forEach(article => {
article.classList.remove("hide");
});
return;
}
articles.forEach(article => {
var _a;
const articleCategory = (_a = article.getAttribute("data-cat")) !== null && _a !== void 0 ? _a : "";
const show = categories.includes(articleCategory);
article.classList.toggle("hide", !show);
});
}
/***/ }),
/***/ 4237:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.blogArticle = blogArticle;
exports.getRelatedItems = getRelatedItems;
exports.setRelatedItems = setRelatedItems;
/* eslint-disable @typescript-eslint/no-non-null-assertion */
/* eslint-disable @typescript-eslint/no-explicit-any */
function blogArticle() {
document.querySelectorAll(".blogwidget__wrapper").forEach(el => {
el.removeAttribute("role");
});
const titleEl = document.querySelector(".blog_title");
const mainImageEl = document.querySelector(".mainimg");
const shareIconsEl = document.querySelector(".share-icons");
if (!titleEl || !mainImageEl || !shareIconsEl)
return;
const prms = {
url: location.href,
media: mainImageEl.src,
description: titleEl.textContent,
};
const url = `https://pinterest.com/pin/create/button/?${new URLSearchParams(prms).toString()}`;
console.log("pinterest url", url);
const div = document.createElement("div");
div.innerHTML = `
`;
shareIconsEl.appendChild(div.firstElementChild);
relatedItems();
}
function relatedItems() {
const container = document.querySelector(".section.related .all-articles");
if (!container) {
return;
}
const filterNames = {};
const filters = Array.from(document.querySelectorAll(".cat-checkbox-2 input"));
filters.forEach(el => {
var _a, _b;
filterNames[(_a = el.getAttribute("data-cat")) !== null && _a !== void 0 ? _a : ""] = (_b = el.closest(".cat-checkbox-2").textContent) !== null && _b !== void 0 ? _b : "";
});
const articles = Array.from(document.querySelectorAll(".section.related .articles > .article"));
const relatedItems = getRelatedItems();
const path = location.pathname;
let indexes = relatedItems[path];
if (!indexes || indexes.some(t => t >= articles.length)) {
indexes = randomInts({ count: 3, max: articles.length - 1 });
}
const articles2 = [];
for (const index of indexes) {
articles2.push(articles[index]);
}
articles2.forEach(article => {
var _a, _b;
const cat = (_a = article.getAttribute("data-cat")) !== null && _a !== void 0 ? _a : "";
const tagsEl = article.querySelector(".tags-target");
tagsEl.textContent = tagsEl.textContent.replace("{{cat-name}}", (_b = filterNames[cat]) !== null && _b !== void 0 ? _b : "");
});
articles2.forEach(article => {
container.appendChild(article);
});
relatedItems[path] = indexes;
setRelatedItems(relatedItems);
}
function getRelatedItems() {
const v = sessionStorage.getItem("relatedItems");
if (!v)
return {};
try {
return JSON.parse(v);
}
catch (err) {
console.warn("getRelatedItems", err);
return {};
}
}
function setRelatedItems(v) {
if (!v) {
sessionStorage.removeItem("relatedItems");
return;
}
sessionStorage.setItem("relatedItems", JSON.stringify(v));
}
function randomInts({ count, max }) {
if (max + 1 < count)
return [];
const set = new Set();
while (set.size < count) {
set.add(randomInt(0, max));
}
return Array.from(set);
}
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
/***/ }),
/***/ 3207:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.blogCategory = blogCategory;
/* eslint-disable @typescript-eslint/no-non-null-assertion */
const consts_1 = __webpack_require__(8066);
function blogCategory() {
var _a, _b, _c;
console.log("blogCategory");
const catName = (_a = document.querySelector(".page-heading").textContent) !== null && _a !== void 0 ? _a : "";
const category = (_c = (_b = consts_1.paths.blogCategory.exec(location.pathname)) === null || _b === void 0 ? void 0 : _b[1]) !== null && _c !== void 0 ? _c : "";
if (!category) {
return;
}
Array.from(document.querySelectorAll(`.bloggrid_list[data-cat=${category}]`)).forEach(el => {
el.classList.remove("hide-list");
Array.from(el.children).forEach(article => {
const tagsEl = article.querySelector(".tags-target");
tagsEl.textContent = tagsEl.textContent.replace("{{cat-name}}", catName);
// tagsEl.href = `/blog/tag/${category}`
});
});
}
/***/ }),
/***/ 8294:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.blogContributor = blogContributor;
/* eslint-disable @typescript-eslint/no-non-null-assertion */
function blogContributor() {
var _a;
console.log("blogContributor");
const lists = Array.from(document.querySelectorAll(".articles"));
const articles = lists.flatMap(list => Array.from(list.querySelectorAll(".article")));
const articlesByDate = articles.sort((a, b) => {
var _a, _b;
const x = (_a = a.getAttribute("data-date")) !== null && _a !== void 0 ? _a : "";
const y = (_b = b.getAttribute("data-date")) !== null && _b !== void 0 ? _b : "";
return y.localeCompare(x);
});
document.querySelector(".all-articles").append(...articlesByDate);
const filters = Array.from(document.querySelectorAll(".cat-checkbox-2 input"));
const filterNames = {};
filters.forEach(el => {
var _a, _b;
el.addEventListener("change", filterByCategories);
filterNames[(_a = el.getAttribute("data-cat")) !== null && _a !== void 0 ? _a : ""] = (_b = el.closest(".cat-checkbox-2").textContent) !== null && _b !== void 0 ? _b : "";
});
(_a = document.querySelector("form[name=wf-form-cat-filters]")) === null || _a === void 0 ? void 0 : _a.addEventListener("submit", e => {
e.preventDefault();
e.stopPropagation();
});
articles.forEach(article => {
var _a, _b;
const cat = (_a = article.getAttribute("data-cat")) !== null && _a !== void 0 ? _a : "";
const tagsEl = article.querySelector(".tags-target");
tagsEl.textContent = tagsEl.textContent.replace("{{cat-name}}", (_b = filterNames[cat]) !== null && _b !== void 0 ? _b : "");
// tagsEl.href = `/blog/tag/${cat}`
});
}
function filterByCategories() {
const categories = Array.from(document.querySelectorAll(".cat-checkbox-2 input:checked")).map(el => { var _a; return (_a = el.getAttribute("data-cat")) !== null && _a !== void 0 ? _a : ""; });
const articles = Array.from(document.querySelectorAll(".article"));
if (categories.length === 0) {
articles.forEach(article => {
article.classList.remove("hide");
});
return;
}
articles.forEach(article => {
var _a;
const articleCategory = (_a = article.getAttribute("data-cat")) !== null && _a !== void 0 ? _a : "";
const show = categories.includes(articleCategory);
article.classList.toggle("hide", !show);
});
}
/***/ }),
/***/ 9101:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.cancelFlow = cancelFlow;
/* eslint-disable @typescript-eslint/no-explicit-any */
const paddle_1 = __webpack_require__(3074);
function cancelFlow() {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b;
const email = (_a = new URLSearchParams(location.search).get("email")) !== null && _a !== void 0 ? _a : undefined;
const paddle = yield (0, paddle_1.initPaddle)({
onPaddleEvent: (e) => __awaiter(this, void 0, void 0, function* () {
yield (0, paddle_1.handlePaddleEvent)(e);
if ((0, paddle_1.isCheckoutCompletedEvent)(e)) {
console.log("checkout completed", e);
}
}),
pwCustomerEmail: email,
frameTarget: "checkout-container",
});
console.log({ email });
(_b = document.querySelector(".cancel_button_test")) === null || _b === void 0 ? void 0 : _b.addEventListener("click", () => __awaiter(this, void 0, void 0, function* () {
yield (paddle === null || paddle === void 0 ? void 0 : paddle.Retain.initCancellationFlow({ pwCustomer: { email } }));
}));
});
}
/***/ }),
/***/ 2072:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.changePhone1 = changePhone1;
/* eslint-disable @typescript-eslint/no-non-null-assertion */
const api_1 = __webpack_require__(6752);
const disableForm_1 = __webpack_require__(4150);
const pgDataLayer_1 = __webpack_require__(7350);
const toggle_1 = __webpack_require__(2166);
const extractErrorMessage_1 = __webpack_require__(6395);
function onSubmit(e) {
return __awaiter(this, void 0, void 0, function* () {
e.preventDefault();
e.stopPropagation();
const form = e.target;
const email = form.elements.namedItem("email-address").value;
let err = null;
try {
(0, disableForm_1.disableForm)(form);
yield api_1.api.initiatePhoneReset({ email });
}
catch (e) {
err = e;
}
if (err) {
console.warn(err);
(0, pgDataLayer_1.dataLayerPush)("error_event", "change_phone_error", (0, extractErrorMessage_1.extractErrorMessage)(e));
}
(0, disableForm_1.enableForm)(form);
(0, toggle_1.toggle)("#success_message", !err);
(0, toggle_1.toggle)("#error_message", !!err);
(0, toggle_1.toggle)(form, false);
});
}
function changePhone1() {
console.log("changePhone1");
const form = document.querySelector(`form[name=wf-form-Change-phone-number]`);
form.addEventListener("submit", onSubmit);
}
/***/ }),
/***/ 8873:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.changePhone2 = changePhone2;
/* eslint-disable @typescript-eslint/no-non-null-assertion */
const consts_1 = __webpack_require__(8066);
const api_1 = __webpack_require__(6752);
const disableForm_1 = __webpack_require__(4150);
const intlTelInput_1 = __webpack_require__(1546);
const pgDataLayer_1 = __webpack_require__(7350);
const toggle_1 = __webpack_require__(2166);
const extractErrorMessage_1 = __webpack_require__(6395);
function onSubmit(e) {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b;
e.preventDefault();
e.stopPropagation();
const form = e.target;
const phoneInput = form.elements.namedItem("new-phone-number");
const phone = (_b = (_a = window.intlTelInputGlobals.getInstance(phoneInput)) === null || _a === void 0 ? void 0 : _a.getNumber()) !== null && _b !== void 0 ? _b : phoneInput.value;
const code = new URLSearchParams(location.search).get("code");
let err = null;
try {
(0, disableForm_1.disableForm)(form);
yield api_1.api.completePhoneReset({ phone, code });
}
catch (e) {
err = e;
(0, pgDataLayer_1.dataLayerPush)("error_event", "change_phone_error", (0, extractErrorMessage_1.extractErrorMessage)(e));
}
if (err) {
console.warn(err);
}
(0, disableForm_1.enableForm)(form);
(0, toggle_1.toggle)("#success_message", !err);
(0, toggle_1.toggle)("#error_message", !!err);
(0, toggle_1.toggle)(form, false);
});
}
function changePhone2() {
return __awaiter(this, void 0, void 0, function* () {
console.log("changePhone2");
const code = new URLSearchParams(location.search).get("code");
if (!code) {
console.log("no code in url");
location.href = consts_1.paths.changePhone1;
return;
}
const form = document.querySelector(`form[name=wf-form-New-Phone-Number]`);
form.addEventListener("submit", onSubmit);
const intlTelInput = yield (0, intlTelInput_1.loadIntlTelInput)();
const input = form.elements.namedItem("new-phone-number");
intlTelInput(input, { utilsScript: intlTelInput_1.intlTelInputUtilsScript });
});
}
/***/ }),
/***/ 78:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.doubleOptin = doubleOptin;
const api_1 = __webpack_require__(6752);
const toggle_1 = __webpack_require__(2166);
function doubleOptin() {
return __awaiter(this, void 0, void 0, function* () {
console.log("doubleOptin");
const waitEl = document.querySelector(".optin-wait");
const thanksEl = document.querySelector(".optin-thanks");
const expiredEl = document.querySelector(".optin-expired");
(0, toggle_1.toggle)(waitEl, true);
(0, toggle_1.toggle)(thanksEl, false);
(0, toggle_1.toggle)(expiredEl, false);
const consumerId = new URLSearchParams(location.search).get("id");
if (!consumerId) {
console.error("consumerId not found");
(0, toggle_1.toggle)(waitEl, false);
(0, toggle_1.toggle)(thanksEl, false);
(0, toggle_1.toggle)(expiredEl, true);
return;
}
try {
const res = yield api_1.api.optin({ consumerId });
console.log("optin res", res);
(0, toggle_1.toggle)(waitEl, false);
(0, toggle_1.toggle)(thanksEl, true);
(0, toggle_1.toggle)(expiredEl, false);
}
catch (err) {
console.error("optin err", err);
(0, toggle_1.toggle)(waitEl, false);
(0, toggle_1.toggle)(thanksEl, false);
(0, toggle_1.toggle)(expiredEl, true);
}
});
}
/***/ }),
/***/ 6395:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.extractErrorMessage = extractErrorMessage;
const axios_1 = __webpack_require__(6425);
function extractErrorMessage(e) {
var _a;
if ((0, axios_1.isAxiosError)(e) && e.response) {
return `${e.response.status}: ${((_a = e.response.data) === null || _a === void 0 ? void 0 : _a.message) || e.response.data}`;
}
return e.message || String(e);
}
/***/ }),
/***/ 5986:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.finalizeAccount = finalizeAccount;
const axios_1 = __webpack_require__(6425);
const config_1 = __webpack_require__(7028);
const consts_1 = __webpack_require__(8066);
const adjust_1 = __webpack_require__(8021);
const api_1 = __webpack_require__(6752);
const checkEmailTypos_1 = __webpack_require__(8043);
const getGeoFeed_1 = __webpack_require__(7539);
const getTerms_1 = __webpack_require__(1741);
const pgDataLayer_1 = __webpack_require__(7350);
const recaptcha_1 = __webpack_require__(3481);
const registerLead_1 = __webpack_require__(2517);
const segment_1 = __webpack_require__(1685);
const sleep_1 = __webpack_require__(9879);
const toggle_1 = __webpack_require__(2166);
const question_1 = __webpack_require__(6199);
/* eslint-disable @typescript-eslint/no-non-null-assertion */
function finalizeAccount() {
return __awaiter(this, void 0, void 0, function* () {
const form = Array.from(document.querySelectorAll("#email-form,#email-form-2")).filter(t => t.offsetParent)[0];
(0, pgDataLayer_1.dataLayerPush)("event_survey_action", "event_survey_complete", "web2app-survey-done-finalize-account");
form.addEventListener("submit", onSubmit);
const submitButton = form.querySelector("button[type=submit],input[type=submit]");
if (submitButton) {
submitButton.disabled = !form.checkValidity();
submitButton.classList.toggle("disabled", !form.checkValidity());
form.querySelectorAll("input[required],select[required],textarea[required]").forEach(el => {
el.addEventListener("input", () => {
submitButton.disabled = !form.checkValidity();
submitButton.classList.toggle("disabled", !form.checkValidity());
});
el.addEventListener("change", () => {
submitButton.disabled = !form.checkValidity();
submitButton.classList.toggle("disabled", !form.checkValidity());
});
});
}
yield replaceRegistrationTerms();
});
}
let emailChecked = false;
function onSubmit(e) {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b, _c, _d, _e, _f;
const form = e.target;
e.preventDefault();
e.stopPropagation();
const ep = new URLSearchParams(location.search).get("ending_page") || "otp-web2app";
const endingPage = `${consts_1.localePathPrefix}/otp-ending-pages/${ep}`;
const segmantaSessionId = new URLSearchParams(location.search).get("sessionId");
const name = (_a = form.querySelector("#name-2")) === null || _a === void 0 ? void 0 : _a.value;
const email = (_b = form.querySelector("#email-2")) === null || _b === void 0 ? void 0 : _b.value;
const fixedEmail = (0, checkEmailTypos_1.checkEmailTypos)(email);
if (fixedEmail !== email) {
console.warn("Email typo found", { email, fixedEmail });
(0, toggle_1.toggle)(".check-email-error", true);
if (!emailChecked) {
emailChecked = true;
return;
}
}
Array.from(form.querySelectorAll("input,button")).forEach(t => (t.disabled = true));
(0, toggle_1.toggle)(".gray-overlay", true);
const recaptchaSiteKey = config_1.config.recaptchaSiteKey;
const grecaptcha = yield (0, recaptcha_1.loadRecaptcha)(recaptchaSiteKey);
const recaptchaToken = yield grecaptcha.enterprise.execute(
// temp use dev key for staging
recaptchaSiteKey, { action: "REGISTER_LEAD" });
const consentInput = Array.from(form.querySelectorAll(".consent-checkbox input,.consent-checkbox-2 input")).filter(t => t.offsetParent)[0];
const consent = consentInput === null || consentInput === void 0 ? void 0 : consentInput.checked;
let error = null;
try {
const terms = yield (0, getTerms_1.getTerms)();
const lead = (0, registerLead_1.getRegisterLead)();
const req = {
recaptchaToken,
email,
nickname: name,
countryCode: (_c = terms === null || terms === void 0 ? void 0 : terms.countryCode) !== null && _c !== void 0 ? _c : null,
segmantaSessionId,
optIns: consent !== undefined ? [{ type: "EMAIL", value: consent }] : [],
answers: lead === null || lead === void 0 ? void 0 : lead.answers,
};
const res = yield api_1.api.registerLead(req);
(0, registerLead_1.setRegisterLead)(Object.assign(Object.assign({}, req), res));
sessionStorage.setItem("registerLeadCode", res.code);
if (res.consumerId) {
const traits = getTraits();
traits.email = req === null || req === void 0 ? void 0 : req.email;
traits.firstName = req === null || req === void 0 ? void 0 : req.nickname;
traits.country = req === null || req === void 0 ? void 0 : req.countryCode;
traits.paddle_flow = location.href.includes("paddle");
traits.opted_in_to_email = consent !== null && consent !== void 0 ? consent : true;
// eslint-disable-next-line @typescript-eslint/no-floating-promises
const segment = yield (0, segment_1.ifSegmentReady)();
if (segment) {
segment.identify(res.consumerId, traits);
}
else {
console.warn("Segment not ready");
}
if (window.PGdataLayer) {
window.PGdataLayer.user = Object.assign(Object.assign({}, ((_d = window.PGdataLayer.user) !== null && _d !== void 0 ? _d : {})), { id: res.consumerId });
}
}
if (window.PGdataLayer) {
window.PGdataLayer.user = Object.assign(Object.assign({}, ((_e = window.PGdataLayer.user) !== null && _e !== void 0 ? _e : {})), { email, firstName: name });
}
(0, pgDataLayer_1.dataLayerPush)("event_crm_action", "event_profile_register_complete", "web2app-account-registered-otp-displayed");
location.href = `${endingPage}${location.search}`;
console.log(res);
}
catch (err) {
console.warn(err);
error = err;
}
if (error) {
const status = (0, axios_1.isAxiosError)(error) ? (_f = error.response) === null || _f === void 0 ? void 0 : _f.status : null;
if ((0, axios_1.isAxiosError)(error) && status === 404) {
const q = new URLSearchParams(location.search);
if (!q.get("retry")) {
(0, toggle_1.toggle)(".gray-overlay", false);
(0, toggle_1.toggle)(form, false);
(0, toggle_1.toggle)(form.closest(".w-form").querySelector(".w-form-done"), !error);
(0, toggle_1.toggle)(form.closest(".w-form").querySelector(".w-form-fail"), !!error);
(0, pgDataLayer_1.dataLayerPush)("event_crm_action", "event_profile_register_submit_error", "web2app-finalize-account-page-will-reload");
console.log("reloading page in 5 seconds");
yield (0, sleep_1.sleep)(5000);
const q = new URLSearchParams(location.search);
q.set("retry", "1");
location.href = `${location.pathname}?${q.toString()}`;
return;
}
}
const q = new URLSearchParams(location.search);
q.set("fail", `${status || 1}`);
location.href = `${endingPage}?${q.toString()}`;
}
});
}
function replaceRegistrationTerms() {
return __awaiter(this, void 0, void 0, function* () {
const geofeed = yield (0, getGeoFeed_1.getGeoFeed)();
const country = geofeed === null || geofeed === void 0 ? void 0 : geofeed.country;
(0, toggle_1.toggle)(".otp-legaltext-us", country === "US");
(0, toggle_1.toggle)(".otp-legaltext-nonus", country !== "US");
const terms = yield (0, getTerms_1.getTerms)();
if (!terms)
return;
const termsEl = document.querySelector(".otp-legaltext-txt");
if (!termsEl) {
console.warn("No terms element");
return;
}
const termsLinkTemplate = termsEl.querySelector("a");
if (!termsLinkTemplate) {
console.warn("No terms link template");
return;
}
const html = generateHtmlWithLinks(terms.registrationTermsText, terms.termsLinks, termsLinkTemplate);
termsEl.innerHTML = html;
const emailOptin = terms.optIns.find(t => t.type === "EMAIL");
if (emailOptin) {
document.querySelectorAll(".consent-checkbox,.consent-checkbox-2").forEach(checkboxEl => {
checkboxEl.title = emailOptin.title;
(0, toggle_1.toggle)(checkboxEl, true, { flex: true });
const html = generateHtmlWithLinks(emailOptin.text, terms.termsLinks, termsLinkTemplate);
checkboxEl.querySelectorAll(".consent-txt,.checkbox-label-2").forEach(el => {
el.innerHTML = html;
});
});
}
});
}
function generateHtmlWithLinks(html, links, linkTemplate) {
Object.entries(links).forEach(([key, value]) => {
const link = linkTemplate.cloneNode(true);
link.href = value.url;
link.textContent = value.text;
html = html.replace(new RegExp(`\\$${key}`, "g"), link.outerHTML);
});
html = html.replace(/\n/g, "
");
return html;
}
function getTraits() {
// const registerLead = getRegisterLead()
const survey = (0, question_1.getFilledSurvey)();
if (!survey)
return {};
const traits = {
gbraid: survey.gbraid,
wbraid: survey.wbraid,
gclid: survey.gclid,
gad_source: survey.gad_source,
fbc: survey.fbclid,
ttclid: survey.ttclid,
fbp: (0, adjust_1.getFbPid)(),
ttp: (0, adjust_1.getTtpid)(),
};
// for (const key of Object.keys(survey)) {
// if (!survey[key]) continue
// const trait = traitMap[key.replace("whySmartSleepCoach_", "")]
// if (!trait) continue
// if (!traits[trait.name]) {
// traits[trait.name] = trait.value
// continue
// }
// traits[trait.name] = `${traits[trait.name]},${trait.value}`
// }
const params = new URLSearchParams(location.search);
const barriers = params.get("barriersToBetterSleep");
if (barriers) {
traits["help_needed_web"] = barriers;
}
const parentGoal = params.get("parentGoal");
if (parentGoal) {
traits["parent_goal"] = parentGoal;
}
return traits;
}
// const traitMap: Record = {
// GetMyBabyToSleepThroughTheNight: { name: "help_needed_web", value: "Night wakings" },
// MakeBedtimeLessStressful: { name: "help_needed_web", value: "Bedtime struggles" },
// CreateAScheduleWeCanStickTo: { name: "help_needed_web", value: "Early wakeups" },
// EncourageLongerMorePredictableNaps: { name: "help_needed_web", value: "Inconsistent naps" },
// LearnAndBuildHealthySleepHabits: { name: "help_needed_web", value: "Newborn healthy sleep habits" },
// }
/***/ }),
/***/ 6740:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.fullSurvey = fullSurvey;
const consts_1 = __webpack_require__(8066);
const getGeoFeed_1 = __webpack_require__(7539);
const registerLead_1 = __webpack_require__(2517);
/* eslint-disable @typescript-eslint/no-non-null-assertion */
function fullSurvey() {
return __awaiter(this, void 0, void 0, function* () {
const form = document.querySelector("form[data-form=multistep]");
if (!form)
return;
const btnSubmit = form.querySelector("[data-form='submit-btn']");
// this is to prevent multi-step.js from submitting the form
btnSubmit.setAttribute("data-form", "submit-btn2");
btnSubmit.style.display = "";
// btnSubmit.insertAdjacentElement("afterend", btnSubmit2)
const getFormData = () => {
const obj = {};
form.querySelectorAll("input,select").forEach(el => {
const name = el.name; //getAttribute("data-name") as string
if (el.tagName === "INPUT" && el.type === "radio") {
if (el.checked) {
obj[name] = el.value;
}
return;
}
if (el.tagName === "INPUT" && el.type === "checkbox") {
if (el.checked) {
obj[name] = el.id;
}
return;
}
obj[name] = el.value;
return;
});
return obj;
};
// btnSubmit2.addEventListener("click", e => {
// console.log("btnSubmit2 click")
// e.preventDefault()
// e.stopPropagation()
// const obj = getFormData()
// console.log(obj)
// })
document.querySelectorAll(".last-step-video").forEach(el => {
el.addEventListener("ended", () => {
void doSubmit();
});
});
btnSubmit.addEventListener("click", (e) => __awaiter(this, void 0, void 0, function* () {
console.log("btnSubmit click");
e.preventDefault();
e.stopPropagation();
void doSubmit();
}));
function doSubmit() {
return __awaiter(this, void 0, void 0, function* () {
var _a;
const obj = getFormData();
Array.from(new URLSearchParams(location.search).keys()).forEach(key => {
var _a;
const v = (_a = /^whySmartSleepCoach_(.*)$/.exec(key)) === null || _a === void 0 ? void 0 : _a[1];
if (v) {
obj["whySmartSleepCoach"] = v;
}
});
console.log(obj);
const answers = {};
for (const [key, value] of Object.entries(obj)) {
let key2 = key;
let value2 = value;
if (value === "on") {
const [k1, k2] = key.split("---");
if (k1 && k2) {
key2 = k1;
value2 = k2;
}
}
if (!key2)
continue;
if (!answers[key2]) {
answers[key2] = { answers: [] };
}
answers[key2].answers.push(value2);
}
console.log(answers);
const lead = (_a = (0, registerLead_1.getRegisterLead)()) !== null && _a !== void 0 ? _a : {};
(0, registerLead_1.setRegisterLead)(Object.assign(Object.assign({}, lead), { answers }));
localStorage.setItem("registerLeadAnswers", JSON.stringify(answers));
const geo = yield (0, getGeoFeed_1.getGeoFeed)();
const q = new URLSearchParams(location.search);
const endingPage = (geo === null || geo === void 0 ? void 0 : geo.country) === "US" ? "ssc-main-w2a-paddle" : "ssc-main-w2a";
q.set("ending_page", endingPage);
location.href = `${consts_1.paths.finalizeAccount}?${q.toString()}`;
});
}
});
}
/***/ }),
/***/ 6263:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.login1 = login1;
/* eslint-disable @typescript-eslint/no-non-null-assertion */
const config_1 = __webpack_require__(7028);
const api_1 = __webpack_require__(6752);
const disableForm_1 = __webpack_require__(4150);
const recaptcha_1 = __webpack_require__(3481);
const toggle_1 = __webpack_require__(2166);
const user_1 = __webpack_require__(6441);
const getQueryParam_1 = __webpack_require__(7089);
/** /sign-in */
function onSubmit(e) {
return __awaiter(this, void 0, void 0, function* () {
e.preventDefault();
e.stopPropagation();
const form = e.target;
const email = form.elements.namedItem("Email-Address").value;
const password = form.elements.namedItem("Password").value;
const grecaptcha = yield (0, recaptcha_1.loadRecaptcha)();
const recaptchaToken = yield grecaptcha.enterprise.execute(config_1.config.recaptchaSiteKey, { action: "LOGIN" });
let err = null;
try {
(0, disableForm_1.disableForm)(form);
const res = yield api_1.api.login({ recaptchaToken, email, password });
(0, user_1.setUser)(res);
}
catch (e) {
console.warn(e);
err = e;
}
(0, toggle_1.toggle)("#success_message", !err);
(0, toggle_1.toggle)(form, !!err);
(0, toggle_1.toggle)(".errormsg", !!err);
(0, disableForm_1.enableForm)(form);
if (err) {
return;
}
const url = (0, getQueryParam_1.getQueryParam)("redirect") || form.getAttribute("redirect");
if (!url) {
console.error("redirect url not found");
return;
}
location.href = url;
});
}
function login1() {
console.log("login1");
const form = document.querySelector(`form[name=wf-form-sign-in-form]`);
form.addEventListener("submit", onSubmit);
void (0, recaptcha_1.loadRecaptcha)();
}
/***/ }),
/***/ 1634:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.login2 = login2;
/* eslint-disable @typescript-eslint/no-non-null-assertion */
const api_1 = __webpack_require__(6752);
const disableForm_1 = __webpack_require__(4150);
function login2() {
const form = document.querySelector(`form[name=wf-form-Phone-Verification]`);
form.addEventListener("submit", verifyLogin);
}
function verifyLogin(e) {
return __awaiter(this, void 0, void 0, function* () {
e.preventDefault();
e.stopPropagation();
const form = e.target;
const verification_code = form.elements.namedItem("SMS_Code").value;
let err = null;
try {
(0, disableForm_1.disableForm)(form);
yield api_1.api.twoFactorVerify({ verification_code });
}
catch (e) {
err = e;
}
if (err) {
console.warn(err);
}
(0, disableForm_1.enableForm)(form);
});
}
/***/ }),
/***/ 9562:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.manageSubscriptionAccount = manageSubscriptionAccount;
const config_1 = __webpack_require__(7028);
const configProd_1 = __webpack_require__(349);
const consts_1 = __webpack_require__(8066);
const api_1 = __webpack_require__(6752);
const auth_1 = __webpack_require__(2220);
const env_1 = __webpack_require__(3143);
const firebase_1 = __webpack_require__(51);
const paddle_1 = __webpack_require__(3074);
const parseJwt_1 = __webpack_require__(6758);
const pricing_1 = __webpack_require__(8542);
const segment_1 = __webpack_require__(1685);
const toggle_1 = __webpack_require__(2166);
function manageSubscriptionAccount() {
return __awaiter(this, void 0, void 0, function* () {
let subscription = null;
let consumerId = null;
const planEls = {
_1month: document.querySelector(".plan-1month"),
_3months: document.querySelector(".plan-3month"),
_12months: document.querySelector(".plan-12month"),
};
const changePlanModalEl = document.querySelector(".plans_modal");
const changePlanConfirmModalEl = document.querySelector(".plans_modal_confirm");
const changePlanConfirmModal_okButton = changePlanConfirmModalEl.querySelector(".plans_modal-confirm");
const changePlanConfirm_cancelButton = changePlanConfirmModalEl.querySelector(".plans_modal-cancel");
const changePlanAlreadySubscribedModal = document.querySelector(".plans_modal_alreadysub");
const changePlanAlreadySubscribedModal_selectADifferentOption = changePlanAlreadySubscribedModal.querySelector(".plans_modal-confirm");
const changePlanAlreadySubscribedModal_imHappyWithThisPlan = changePlanAlreadySubscribedModal.querySelector(".plans_modal-cancel");
const changePlanSuccessMessageEl = document.querySelector(".sub-change-success-message");
yield main();
function main() {
return __awaiter(this, void 0, void 0, function* () {
console.log("manageSubscriptionAccount");
const enableChangePlan = location.hash.includes("enableChangePlan");
if (enableChangePlan) {
(0, toggle_1.toggle)(".change-subscription", true);
}
(0, segment_1.setSegmentEventOnTrigger)(e => {
var _a, _b, _c, _d, _e, _f;
const props2 = getSegmentEventProps(e.eventName, {
subscription_status: (_a = subscription === null || subscription === void 0 ? void 0 : subscription.subscription) === null || _a === void 0 ? void 0 : _a.status,
subscription_id: (_b = subscription === null || subscription === void 0 ? void 0 : subscription.subscription) === null || _b === void 0 ? void 0 : _b.id,
price_id: (_c = subscription === null || subscription === void 0 ? void 0 : subscription.subscription) === null || _c === void 0 ? void 0 : _c.items[0].price.id,
price_name: (_d = subscription === null || subscription === void 0 ? void 0 : subscription.subscription) === null || _d === void 0 ? void 0 : _d.items[0].price.name,
product_id: (_e = subscription === null || subscription === void 0 ? void 0 : subscription.subscription) === null || _e === void 0 ? void 0 : _e.items[0].product.id,
product_name: (_f = subscription === null || subscription === void 0 ? void 0 : subscription.subscription) === null || _f === void 0 ? void 0 : _f.items[0].product.name,
});
const props = Object.assign(Object.assign({}, e.props), props2);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
e.props = props;
return props;
});
document.querySelectorAll(".paddle-link").forEach(el => {
el.href = config_1.config.paddlePortalUrl;
});
const q = new URLSearchParams(location.search);
const token = q.get("token");
if (token) {
const firebase = yield (0, firebase_1.initFirebase)();
yield (firebase === null || firebase === void 0 ? void 0 : firebase.auth.getAuth().signOut());
(0, auth_1.setAuth)(token);
// const q = new URLSearchParams(location.search)
// q.delete("token")
// const qq = q.size ? "?" + q.toString() : ""
// history.replaceState(null, "", location.pathname + qq)
}
subscription = yield initSubscription();
const noRedirect = location.hash.includes("noRedirect");
if (!subscription && !noRedirect) {
console.warn("subscription not found, redirecting to login");
location.href = `${consts_1.paths.manageSubscriptionSignIn}?redirect=${location.pathname}`;
return;
}
yield initPrices();
const changePlanForm = document.querySelector("#email-form-3");
changePlanForm.addEventListener("submit", (e) => __awaiter(this, void 0, void 0, function* () {
e.preventDefault();
e.stopPropagation();
const currentPlan = getUserCurrentPlan();
const plan = getSelectedPlan();
if (!plan) {
console.warn("selected plan not found");
return;
}
if (plan === currentPlan) {
changePlanAlreadySubscribedModal.style.display = "flex";
return;
}
if (!consumerId) {
console.warn("consumerId not found");
return;
}
changePlanConfirmModalEl.style.display = "flex";
}));
changePlanConfirmModal_okButton.addEventListener("click", () => __awaiter(this, void 0, void 0, function* () {
const plan = getSelectedPlan();
if (!plan) {
console.warn("selected plan not found");
return;
}
if (!consumerId) {
console.warn("consumerId not found");
return;
}
const priceId = config_1.config.paddlePriceIds[plan];
const res = yield api_1.api.updateSubscription({ consumerId, priceId });
console.log("updateSubscription", res);
changePlanConfirmModalEl.style.display = "none";
changePlanModalEl.style.display = "none";
changePlanSuccessMessageEl.style.display = "block";
}));
changePlanConfirm_cancelButton.addEventListener("click", () => __awaiter(this, void 0, void 0, function* () {
changePlanConfirmModalEl.style.display = "none";
}));
changePlanAlreadySubscribedModal_selectADifferentOption.addEventListener("click", () => __awaiter(this, void 0, void 0, function* () {
changePlanAlreadySubscribedModal.style.display = "none";
}));
changePlanAlreadySubscribedModal_imHappyWithThisPlan.addEventListener("click", () => __awaiter(this, void 0, void 0, function* () {
changePlanAlreadySubscribedModal.style.display = "none";
changePlanModalEl.style.display = "none";
}));
const plan = getUserCurrentPlan();
console.log("plan", plan);
if (!plan)
return;
selectPlan(plan);
});
}
function getSelectedPlan() {
var _a;
return (_a = config_1.planKeys.find(t => planEls[t].classList.contains("is-active-inputactive"))) !== null && _a !== void 0 ? _a : null;
}
function selectPlan(newPlan) {
for (const plan of config_1.planKeys) {
const planEl = planEls[plan];
if (newPlan === plan) {
planEl.classList.add("is-active-inputactive");
planEl.querySelector("input[type=radio]").checked = true;
continue;
}
planEl.classList.remove("is-active-inputactive");
}
}
function getUserCurrentPlan() {
var _a, _b;
const items = (_b = (_a = subscription === null || subscription === void 0 ? void 0 : subscription.subscription) === null || _a === void 0 ? void 0 : _a.items) !== null && _b !== void 0 ? _b : [];
const paddlePriceIds = {
_1month: [config_1.config.paddlePriceIds._1month, ...Object.values(config_1.config.paddlePriceIdSets).map(t => t._1month)],
_3months: [config_1.config.paddlePriceIds._3months, ...Object.values(config_1.config.paddlePriceIdSets).map(t => t._3months)],
_12months: [
config_1.config.paddlePriceIds._12months,
...Object.values(config_1.config.paddlePriceIdSets).map(t => t._12months),
],
};
if (env_1.env !== "prod") {
paddlePriceIds._1month.push(configProd_1.configProd.paddlePriceIds._1month, ...Object.values(config_1.config.paddlePriceIdSets).map(t => t._1month));
paddlePriceIds._3months.push(configProd_1.configProd.paddlePriceIds._3months, ...Object.values(configProd_1.configProd.paddlePriceIdSets).map(t => t._3months));
paddlePriceIds._12months.push(configProd_1.configProd.paddlePriceIds._12months, ...Object.values(configProd_1.configProd.paddlePriceIdSets).map(t => t._12months));
}
if (items.find(t => paddlePriceIds._1month.includes(t.price.id)))
return "_1month";
if (items.find(t => paddlePriceIds._3months.includes(t.price.id)))
return "_3months";
if (items.find(t => paddlePriceIds._12months.includes(t.price.id)))
return "_12months";
return null;
}
function getConsumerId() {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b;
yield (0, firebase_1.initFirebase)();
if (firebase_1.firebaseUser) {
const consumerId = yield (0, firebase_1.getFirebaseConsumerId)();
return consumerId;
}
const token = (0, auth_1.getAuth)();
if (!token)
return null;
const jwt = (0, parseJwt_1.parseJwt)(token);
const consumerId = (_a = jwt.consumer_id) !== null && _a !== void 0 ? _a : (_b = jwt.claims) === null || _b === void 0 ? void 0 : _b.consumer_id;
return consumerId;
});
}
function initSubscription() {
return __awaiter(this, void 0, void 0, function* () {
consumerId = yield getConsumerId();
if (!consumerId) {
console.warn("consumerId not found");
return null;
}
const res = yield api_1.api.getSubscription({ consumerId });
console.log(res);
return res;
});
}
function initPrices() {
return __awaiter(this, void 0, void 0, function* () {
const paddle = yield (0, paddle_1.initPaddle)({
frameTarget: "checkout-container",
onPaddleEvent: (e) => __awaiter(this, void 0, void 0, function* () {
yield (0, paddle_1.handlePaddleEvent)(e);
if ((0, paddle_1.isCheckoutCompletedEvent)(e)) {
console.log("checkout completed", e);
}
}),
});
if (!paddle) {
console.warn("paddle not found");
return;
}
const pricingPreview = yield (0, pricing_1.getPricingPreview)({ paddle, discountRate: 0.5 });
console.log("PricePreview", pricingPreview);
for (const planKey of config_1.planKeys) {
const planEl = planEls[planKey];
const monthlyEl = planEl.querySelector(".plan-monthlyprice");
const billedEl = planEl.querySelector(".plan-billed");
const discountEl = planEl.querySelector(".plan-discount");
const item = pricingPreview.items[planKey];
if (monthlyEl)
monthlyEl.textContent = item.monthlyPriceFormatted;
if (billedEl)
billedEl.textContent = item.priceFormatted;
if (discountEl)
discountEl.textContent = item.discountRateFormattedOld;
}
});
}
});
}
function getSegmentEventProps(name, { subscription_status, subscription_id, price_id, price_name, product_id, product_name, error_type, path, platform, }) {
const map = {
cancel_subscription_clicked: {
subscription_status,
subscription_id,
price_id,
price_name,
product_id,
product_name,
// flow_type,
},
cancel_flow_answer_submit: {
subscription_status,
subscription_id,
price_id,
price_name,
product_id,
product_name,
// question_type,
// question_title,
// answer_submitted,
// flow_type,
},
cancel_subscription_confirmed: {
subscription_status,
subscription_id,
price_id,
price_name,
product_id,
product_name,
// flow_type,
},
request_refund_clicked: {
subscription_status,
subscription_id,
price_id,
price_name,
product_id,
product_name,
// flow_type,
},
refund_flow_answer_submit: {
subscription_status,
subscription_id,
price_id,
price_name,
product_id,
product_name,
// flow_type,
},
refund_request_confirmed: {
subscription_status,
subscription_id,
price_id,
price_name,
product_id,
product_name,
// flow_type,
},
change_subscription_clicked: {
subscription_status,
subscription_id,
price_id,
price_name,
product_id,
product_name,
},
change_subscription_plan_selected: {
subscription_status,
subscription_id,
price_id,
price_name,
product_id,
product_name,
// plan_selected,
},
change_subscription_update_plan_clicked: {
subscription_status,
subscription_id,
price_id,
price_name,
product_id,
product_name,
// plan_selected,
},
change_subscription_popup_clicked: {
subscription_status,
subscription_id,
price_id,
price_name,
product_id,
product_name,
// popup_headline,
// popup_submission,
},
subscription_changed_paddle: {
subscription_status,
subscription_id,
price_id,
price_name,
product_id,
product_name,
// changed_from,
// changed_to,
// on_free_trial_period,
},
change_subscription_faq_expanded: {
subscription_status,
subscription_id,
price_id,
price_name,
product_id,
product_name,
// question,
},
change_subscription_click_x: {
subscription_status,
subscription_id,
price_id,
price_name,
product_id,
product_name,
},
manage_subscription_faq_expanded: {
subscription_status,
subscription_id,
price_id,
price_name,
product_id,
product_name,
// question,
},
signin_email_password_error: {
error_type,
path,
platform,
},
signin_verification_error: {
error_type,
path,
platform,
},
signed_in_web: {
path,
},
};
return map[name];
}
/***/ }),
/***/ 239:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.manageSubscriptionSignIn = manageSubscriptionSignIn;
const config_1 = __webpack_require__(7028);
const consts_1 = __webpack_require__(8066);
const api_1 = __webpack_require__(6752);
const auth_1 = __webpack_require__(2220);
const disableForm_1 = __webpack_require__(4150);
const firebase_1 = __webpack_require__(51);
const getQueryParam_1 = __webpack_require__(7089);
const recaptcha_1 = __webpack_require__(3481);
const toggle_1 = __webpack_require__(2166);
const user_1 = __webpack_require__(6441);
function manageSubscriptionSignIn() {
return __awaiter(this, void 0, void 0, function* () {
console.log("login1");
const form = document.querySelector(`form[name=wf-form-Log-in-Form-1]`);
form.addEventListener("submit", onSubmit);
void (0, recaptcha_1.loadRecaptcha)();
yield (0, firebase_1.initFirebase)();
});
}
function onSubmit(e) {
return __awaiter(this, void 0, void 0, function* () {
e.preventDefault();
e.stopPropagation();
const form = e.target;
const email = form.elements.namedItem("Form-10-Email-2").value;
const password = form.elements.namedItem("Form-10-Password-2").value;
const noCaptcha = location.hash.includes("noCaptcha");
let recaptchaToken = "";
if (!noCaptcha) {
const grecaptcha = yield (0, recaptcha_1.loadRecaptcha)();
recaptchaToken = yield grecaptcha.enterprise.execute(config_1.config.recaptchaSiteKey, { action: "LOGIN" });
}
let err = null;
let res = null;
try {
(0, disableForm_1.disableForm)(form);
res = yield api_1.api.login({ recaptchaToken, email, password });
(0, user_1.setUser)(res);
}
catch (e) {
console.warn(e);
err = e;
}
(0, toggle_1.toggle)("#success_message", !err);
(0, toggle_1.toggle)(form, !!err);
(0, toggle_1.toggle)(".error-message", !!err);
(0, disableForm_1.enableForm)(form);
const nextPageUrl = (0, getQueryParam_1.getQueryParam)("redirect") || form.getAttribute("redirect") || consts_1.paths.manageSubscriptionAccount;
const q = new URLSearchParams();
if (nextPageUrl) {
q.append("redirect", nextPageUrl);
}
const qq = q.size ? `?${q.toString()}` : "";
// let auth: string | null = null
if (res === null || res === void 0 ? void 0 : res.apiToken) {
const userCredential = yield (0, firebase_1.getFirebaseToken)(res.apiToken);
console.log("userCredential", userCredential);
location.href = nextPageUrl;
return;
}
if (res === null || res === void 0 ? void 0 : res.authToken) {
(0, auth_1.setAuth)(res.authToken);
location.href = `${consts_1.paths.manageSubscriptionSignInVerify}${qq}`;
return;
}
console.warn("no token found");
// let requiresVerify = res?.authToken && !res?.apiToken
// if (err && isAxiosError(err)) {
// if (err.response?.data?.reason === "credentials.phone.required") {
// requiresVerify = true
// }
// }
// if (requiresVerify) {
// location.href = `${paths.manageSubscriptionSignInVerify}${qq}${location.hash}`
// return
// }
// if (err) {
// return
// }
// if (noRedirect) {
// return
// }
// location.href = `${nextPageUrl}${location.hash}`
});
}
/***/ }),
/***/ 9630:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.manageSubscriptionSignInVerify = manageSubscriptionSignInVerify;
/* eslint-disable @typescript-eslint/no-non-null-assertion */
const api_1 = __webpack_require__(6752);
const disableForm_1 = __webpack_require__(4150);
const firebase_1 = __webpack_require__(51);
const getQueryParam_1 = __webpack_require__(7089);
const toggle_1 = __webpack_require__(2166);
const user_1 = __webpack_require__(6441);
function manageSubscriptionSignInVerify() {
var _a;
const form = document.querySelector(`form[name=wf-form-Log-in-Form-1]`);
form.addEventListener("submit", verifyLogin);
(_a = document.querySelector(`.resend-code`)) === null || _a === void 0 ? void 0 : _a.addEventListener("click", (e) => __awaiter(this, void 0, void 0, function* () {
e.preventDefault();
e.stopPropagation();
yield api_1.api.twoFactorResend();
}));
}
function verifyLogin(e) {
return __awaiter(this, void 0, void 0, function* () {
e.preventDefault();
e.stopPropagation();
const form = e.target;
const verification_code = form.elements.namedItem("Form-10-Email-2").value;
let err;
try {
(0, disableForm_1.disableForm)(form);
const res = yield api_1.api.twoFactorVerify({ verification_code });
const user = (0, user_1.getUser)();
(0, user_1.setUser)(Object.assign(Object.assign({}, user), { apiToken: res.token }));
yield (0, firebase_1.getFirebaseToken)(res.token);
}
catch (e) {
console.warn(e);
err = e;
}
(0, disableForm_1.enableForm)(form);
if (err) {
(0, toggle_1.toggle)(".error-message", !!err);
return;
}
const url = (0, getQueryParam_1.getQueryParam)("redirect") || form.getAttribute("redirect") || "/";
location.href = url;
});
}
/***/ }),
/***/ 5304:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.masterTheChaos = masterTheChaos;
const paddle_1 = __webpack_require__(3074);
const registerLead_1 = __webpack_require__(2517);
const timer_1 = __webpack_require__(497);
const toggle_1 = __webpack_require__(2166);
const consts_1 = __webpack_require__(8066);
const skeleton_1 = __webpack_require__(8805);
const config_1 = __webpack_require__(7028);
function masterTheChaos() {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b, _c;
const onLoadFinished = (0, skeleton_1.skeleton)();
const paddleFrameTarget = "checkout_container";
const priceIds = config_1.config.masterTheChaosPriceIds;
const priceSetId = new URLSearchParams(location.search).get("pid") || "bmtc";
const priceSetId2 = priceSetId === "amtc" ? "aamtc" : priceSetId === "bmtc" ? "bbmtc" : null;
const priceId = priceIds[priceSetId];
const priceId2 = priceIds[priceSetId2] || null;
const timerEl = document.querySelector(".timer-wrapper:not(.w-condition-invisible)");
if (timerEl) {
let timerStart = sessionStorage.getItem("timerStart");
if (!timerStart) {
timerStart = new Date().toISOString();
sessionStorage.setItem("timerStart", timerStart);
}
const startTime = new Date(timerStart);
const totalSeconds = 10 * 60;
(0, timer_1.timer)(timerEl, {
startTime,
totalSeconds,
onChange: seconds => {
if (seconds === 0 && priceSetId2 && priceSetId !== priceSetId2) {
const url = new URL(location.href);
url.searchParams.set("pid", priceSetId2);
location.replace(url.toString());
}
if (seconds === 0) {
document.body.classList.add("timer-0");
}
},
});
}
const paddle = yield (0, paddle_1.initPaddle)({
frameTarget: paddleFrameTarget,
onPaddleEvent: (e) => __awaiter(this, void 0, void 0, function* () {
(0, registerLead_1.setPaddleEventData)(e);
if ((0, paddle_1.isCheckoutCompletedEvent)(e)) {
console.log("checkout completed", e);
yield onCheckoutCompleted(e);
return;
}
yield (0, paddle_1.handlePaddleEvent)(e);
}),
});
if (!paddle) {
console.warn("Paddle failed to initialize");
return;
}
const previewRes = yield paddle.PricePreview({
items: [{ priceId, quantity: 1 }, ...(priceId2 ? [{ priceId: priceId2, quantity: 1 }] : [])],
address: {
countryCode: "US",
},
});
console.log("PricePreview", previewRes);
const priceFormatted = previewRes.data.details.lineItems[0].formattedTotals.total;
document.querySelectorAll("[data-fid=guide_price]").forEach(el => {
el.innerText = priceFormatted;
});
const price2Formatted = (_c = (_b = (_a = previewRes.data.details.lineItems[1]) === null || _a === void 0 ? void 0 : _a.formattedTotals) === null || _b === void 0 ? void 0 : _b.total) !== null && _c !== void 0 ? _c : priceFormatted;
document.querySelectorAll("[data-fid=guide_strikethrough_price]").forEach(el => {
el.innerText = price2Formatted;
});
paddle.Checkout.open({
items: [{ priceId, quantity: 1 }],
settings: {
showAddTaxId: false,
variant: "one-page",
successUrl: new URL(consts_1.paths.masterTheChaosConfirmation, location.href).toString(),
showAddDiscounts: false,
},
});
onLoadFinished();
function onCheckoutCompleted(e) {
return __awaiter(this, void 0, void 0, function* () {
onLoadFinished();
console.log("Checkout completed");
if (e) {
if (!(0, paddle_1.isCheckoutCompletedEvent)(e)) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
e = Object.assign(Object.assign({}, e), { name: "checkout.completed" });
}
yield (0, paddle_1.handlePaddleEvent)(e);
}
(0, toggle_1.toggle)(".timer-wrapper-new", false);
});
}
});
}
/***/ }),
/***/ 4137:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.masterTheChaosConfirmation = masterTheChaosConfirmation;
const consts_1 = __webpack_require__(8066);
const paddle_1 = __webpack_require__(3074);
const registerLead_1 = __webpack_require__(2517);
function masterTheChaosConfirmation() {
return __awaiter(this, void 0, void 0, function* () {
const e = (0, registerLead_1.getPaddleEventData)();
if (!e || !(0, paddle_1.isCheckoutCompletedEvent)(e)) {
console.log("no checkout", e);
location.href = consts_1.paths.masterTheChaos;
return;
}
});
}
/***/ }),
/***/ 1626:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports._goalMap = void 0;
exports.otpEndingPagePaddleCheckout = otpEndingPagePaddleCheckout;
const axios_1 = __webpack_require__(6425);
const config_1 = __webpack_require__(7028);
const api_1 = __webpack_require__(6752);
const appendQueryString_1 = __webpack_require__(5861);
const paddle_1 = __webpack_require__(3074);
const pricing_1 = __webpack_require__(8542);
const recaptcha_1 = __webpack_require__(3481);
const registerLead_1 = __webpack_require__(2517);
const segment_1 = __webpack_require__(1685);
const sleep_1 = __webpack_require__(9879);
const timer_1 = __webpack_require__(497);
const toggle_1 = __webpack_require__(2166);
const otpEndingPageWeb2App_1 = __webpack_require__(6515);
const pgDataLayer_1 = __webpack_require__(7350);
const consts_1 = __webpack_require__(8066);
const skeleton_1 = __webpack_require__(8805);
const getGeoFeed_1 = __webpack_require__(7539);
function otpEndingPagePaddleCheckout() {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b, _c, _d, _e, _f;
const dr = new URLSearchParams(location.search).get("dr");
const discountRate = dr === "humanz" ? 0.8 : 0.5;
const path = location.pathname;
const isPaddleEnabled = consts_1.paths.otpEndingPagePaddleCheckout.test(path);
const onLoadFinished = (0, skeleton_1.skeleton)();
const url = new URL(location.href);
const priceSetId = new URLSearchParams(location.search).get("pid") || (dr === "humanz" ? "hmnz" : null);
const fail = new URLSearchParams(location.search).get("fail");
const container2 = document.querySelector(".section_paddle:not(.w-condition-invisible)");
const pricingWrapOriginal = container2.querySelector(".pricing-wrap-clone");
const pricingWrapInsert = container2.querySelector(".pricing-wrap-insert");
if (pricingWrapOriginal && pricingWrapInsert) {
const pricingSectionClone = pricingWrapOriginal.cloneNode(true);
Array.from(pricingSectionClone.querySelectorAll("input[name=plan]")).forEach(el => {
el.name = "plan2";
});
Array.from(pricingSectionClone.querySelectorAll(".modal_component")).forEach(el => {
el.remove();
});
Array.from(pricingSectionClone.querySelectorAll(".plan-button")).forEach(el => {
el.addEventListener("click", () => {
var _a;
(_a = pricingWrapOriginal.querySelector(".plan-button")) === null || _a === void 0 ? void 0 : _a.click();
});
});
pricingWrapInsert.appendChild(pricingSectionClone);
}
toggleMomDadImages(container2, url.searchParams);
(0, otpEndingPageWeb2App_1.updateChildName)();
const promocode = url.searchParams.get("promocode");
const promocodeExists = url.searchParams.has("promocode");
const goalEl = container2.querySelector(".otp-goal");
const parentGoalEl = container2.querySelector(".otp-parentgoal");
const params = new URLSearchParams(location.search);
const showPricePerMonth = params.get("period") === "ppm";
const goalMap = (_a = window.goalMap) !== null && _a !== void 0 ? _a : exports._goalMap;
const parentGoalMap = (_b = window.parentGoalMap) !== null && _b !== void 0 ? _b : _parentGoalMap;
const goal = (_c = goalMap[params.get("barriersToBetterSleep")]) !== null && _c !== void 0 ? _c : goalMapEs[params.get("barriersToBetterSleep")];
const parentGoal = (_d = parentGoalMap[params.get("parentGoal")]) !== null && _d !== void 0 ? _d : parentGoalMapEs[params.get("parentGoal")];
if (goalEl && goal)
goalEl.textContent = goal;
if (parentGoalEl && parentGoal)
parentGoalEl.textContent = parentGoal;
const token = url.searchParams.get("token");
if (token) {
try {
const grecaptcha = yield (0, recaptcha_1.loadRecaptcha)();
const recaptchaToken = yield grecaptcha.enterprise.execute(config_1.config.recaptchaSiteKey, {
action: "REGISTER_LEAD",
});
const res = yield api_1.api.refreshToken({ token, recaptchaToken });
console.log("verifyToken", res);
const x = (_e = (0, registerLead_1.getRegisterLead)()) !== null && _e !== void 0 ? _e : {};
(0, registerLead_1.setRegisterLead)(Object.assign(Object.assign({}, x), res));
(0, registerLead_1.updatePgDataLayerUser)();
if (res.code) {
sessionStorage.setItem("registerLeadCode", res.code);
}
url.searchParams.delete("token");
history.replaceState({}, document.title, url);
(0, pgDataLayer_1.dataLayerPush)("event_bin_action", "event_checkout_now", "retargeting-checkout-page-token-success");
}
catch (e) {
console.error("refreshToken failed", e);
(0, pgDataLayer_1.dataLayerPush)("event_bin_action", "event_checkout_now", "retargeting-checkout-page-token-error");
}
}
yield (0, otpEndingPageWeb2App_1.otpEndingPageWeb2App)();
yield (0, segment_1.ifSegmentReady)();
// const enableSuccessUrl = location.href.includes("meta-w2a-paddle") || location.href.includes("tiktok-w2a-paddle")
// const excludeApplePay = false
const enableSuccessUrl = [
"meta-w2a-paddle",
"tiktok-w2a-paddle",
"humanz-w2a-paddle",
"pampersapp-w2a-paddle",
].some(t => location.href.includes(t));
const successUrl = enableSuccessUrl ? (0, appendQueryString_1.appendQueryString)(location.href, { success: true }) : undefined;
const isSuccessPage = location.href.includes("success=true");
console.log("otpEndingPagePaddleCheckout", { enableSuccessUrl, successUrl, isSuccessPage });
const timerEl = document.querySelector(".timer-wrapper:not(.w-condition-invisible)");
if (timerEl) {
let timerStart = sessionStorage.getItem("timerStart");
if (!timerStart) {
timerStart = new Date().toISOString();
sessionStorage.setItem("timerStart", timerStart);
}
const startTime = new Date(timerStart);
const totalSeconds = 10 * 60;
(0, timer_1.timer)(timerEl, {
startTime,
totalSeconds,
onChange: seconds => {
if (seconds === 0 && priceSetId !== "fst") {
const url = new URL(location.href);
url.searchParams.set("pid", "fst");
location.replace(url.toString());
}
},
});
}
if (fail) {
console.log("Received fail param", fail);
const geofeed = yield (0, getGeoFeed_1.getGeoFeed)();
const lead = Object.assign({}, ((_f = (0, registerLead_1.getRegisterLead)()) !== null && _f !== void 0 ? _f : {}));
delete lead.recaptchaToken;
const url = location.href;
document.querySelectorAll(".textarealogs").forEach(el => {
el.value = JSON.stringify({ fail, url, geofeed, lead }, null, 2);
});
yield onCheckoutCompleted(null);
return;
}
if (!isPaddleEnabled) {
console.log("Paddle not enabled for this page");
yield onCheckoutCompleted(null);
return;
}
if (enableSuccessUrl && isSuccessPage) {
console.log("Success page");
yield onCheckoutCompleted((0, registerLead_1.getPaddleEventData)());
return;
}
const alreadyCheckedOut = sessionStorage.alreadyCheckedOut === "true";
if (alreadyCheckedOut) {
console.log("Already checked out, skipping Paddle");
yield onCheckoutCompleted(null);
return;
}
// const geoFeed = await getGeoFeed()
// if (geoFeed?.country !== "US") {
// console.log("Skipping paddle, not in US")
// await onCheckoutCompleted(null)
// return
// }
const checkoutContainer = container2.querySelector(".checkout_container");
const paddleFrameTarget = Array.from(checkoutContainer.classList).find(t => t.startsWith("checkout_container_"));
const paddle = yield (0, paddle_1.initPaddle)({
frameTarget: paddleFrameTarget,
onPaddleEvent: (e) => __awaiter(this, void 0, void 0, function* () {
(0, registerLead_1.setPaddleEventData)(e);
if ((0, paddle_1.isCheckoutCompletedEvent)(e)) {
if (enableSuccessUrl) {
return;
}
console.log("checkout completed", e);
yield onCheckoutCompleted(e);
return;
}
yield (0, paddle_1.handlePaddleEvent)(e);
}),
});
if (!paddle) {
console.warn("Paddle failed to initialize");
return;
}
function onCheckoutCompleted(e) {
return __awaiter(this, void 0, void 0, function* () {
var _a;
console.log("Checkout completed");
onLoadFinished();
if (e) {
if (!(0, paddle_1.isCheckoutCompletedEvent)(e)) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
e = Object.assign(Object.assign({}, e), { name: "checkout.completed" });
}
yield (0, segment_1.ifSegmentReady)(5000);
yield (0, paddle_1.handlePaddleEvent)(e);
}
(0, toggle_1.toggle)(container2.querySelector(".payment-details"), false);
(0, toggle_1.toggle)(container2.querySelector(".otp-num-wrapper-paddle"), true);
(0, toggle_1.toggle)(container2.querySelector(".paddle-v2-content"), false);
(0, toggle_1.toggle)(container2.querySelector(".otp-checkmarks"), false);
(0, toggle_1.toggle)(container2.querySelector(".otp-header"), false);
container2.querySelectorAll(".pricing-wrap-clone").forEach(el => {
(0, toggle_1.toggle)(el, false);
});
(0, toggle_1.toggle)(".timer-component", false);
(_a = container2.querySelector(".otp-num-wrapper-paddle")) === null || _a === void 0 ? void 0 : _a.scrollIntoView({ block: "center" });
const lead = (0, registerLead_1.getRegisterLead)();
if (lead.status === "COMPLETE") {
(0, toggle_1.toggle)(container2.querySelector(".step3-otp-container"), false);
container2.querySelectorAll(".step3-otp-title").forEach(el => {
el.innerHTML =
consts_1.locale === "es"
? `Y tu contraseña.
¿No puedes recordar tu contraseña? Vaya a Restablecer Contraseña`
: `And your password.
Can't remember your password? go to www.smartsleepcoach.com/reset-password`;
});
}
if (!(e === null || e === void 0 ? void 0 : e.data))
return;
const consumerId = lead.consumerId;
const res = yield setSubscriptionWithRetry({ consumerId, transactionId: e.data.transaction_id });
console.log("setSubscription", res);
sessionStorage.alreadyCheckedOut = "true";
});
}
function initSelectPlanForm({ onPlanChanged }) {
var _a, _b, _c, _d, _e, _f;
for (const planKey of config_1.planKeys) {
const planPricing = pricingPreview.items[planKey];
const planEl = planEls[planKey];
planEl.forEach(planEl => {
const strikethroughEl = planEl.querySelector("[data-fid=strikethrough_price]");
const plan_price_arrow = planEl.querySelector("[data-fid=plan_price_arrow]");
const percent_off_plus = planEl.querySelector("[data-fid=percent_off_plus]");
const discountPercentEl = planEl.querySelector("[data-fid=discount_percent]");
const hasDiscount = planPricing.priceBeforeDiscount > planPricing.price;
if (strikethroughEl)
(0, toggle_1.toggle)(strikethroughEl, hasDiscount);
if (plan_price_arrow)
(0, toggle_1.toggle)(plan_price_arrow, hasDiscount);
if (percent_off_plus)
(0, toggle_1.toggle)(percent_off_plus, hasDiscount);
if (strikethroughEl) {
strikethroughEl.textContent = pricingPreview.formatPrice(planPricing.priceBeforeDiscount);
}
if (discountPercentEl === null || discountPercentEl === void 0 ? void 0 : discountPercentEl.textContent) {
discountPercentEl.textContent = planPricing.discountRateFormattedOld;
}
// document.querySelectorAll(".modal-discount-percent").forEach(el => {
// if (!el.textContent) return
// el.textContent = planPricing.discountRateFormatted
// })
});
}
// const strikePrices = {
// _1month: planEls._1month[0].querySelector(".price-day")?.textContent,
// _3months: planEls._3months[0].querySelector(".price-day")?.textContent,
// _12months: planEls._12months[0].querySelector(".price-day")?.textContent,
// }
// const strikePrices2 = {
// _1month: planEls._1month[0].querySelector(".plan-price.strikethrough")?.textContent,
// _3months: planEls._3months[0].querySelector(".plan-price.strikethrough")?.textContent,
// _12months: planEls._12months[0].querySelector(".plan-price.strikethrough")?.textContent,
// }
const planTitles = {
_1month: (_a = planEls._1month[0].querySelector(".plan-t")) === null || _a === void 0 ? void 0 : _a.textContent,
_3months: (_b = planEls._3months[0].querySelector(".plan-t")) === null || _b === void 0 ? void 0 : _b.textContent,
_12months: (_c = planEls._12months[0].querySelector(".plan-t")) === null || _c === void 0 ? void 0 : _c.textContent,
};
const planTitles2 = {
_1month: (_d = planEls._1month[0].querySelector(".plan-t")) === null || _d === void 0 ? void 0 : _d.getAttribute("data-subscription-modal-text"),
_3months: (_e = planEls._3months[0].querySelector(".plan-t")) === null || _e === void 0 ? void 0 : _e.getAttribute("data-subscription-modal-text"),
_12months: (_f = planEls._12months[0].querySelector(".plan-t")) === null || _f === void 0 ? void 0 : _f.getAttribute("data-subscription-modal-text"),
};
for (const [planKey, planElGroup] of Object.entries(planEls)) {
for (const planEl of planElGroup) {
const radioEl = planEl.querySelector("input[type=radio]");
radioEl.addEventListener("click", e => {
console.log(e);
Object.entries(planEls).forEach(([planKey2, planElGroup2]) => {
planElGroup2.forEach(planEl2 => {
var _a, _b;
const active = planKey2 === planKey;
planEl2.classList.toggle("is-active-inputactive", active);
const radioEl2 = planEl2.querySelector("input[type=radio]");
if (radioEl2.checked !== active) {
console.log(radioEl2, radioEl2.checked, active);
radioEl2.checked = active;
(_b = (_a = radioEl2
.closest(".w-radio")) === null || _a === void 0 ? void 0 : _a.querySelector(".w-radio-input")) === null || _b === void 0 ? void 0 : _b.classList.toggle("w--redirected-checked", active);
}
});
});
onPlanChanged(planKey);
});
const priceMonth = planEl.querySelector(".price-month");
// const priceDay = planEl.querySelector(".price-day")
const price_per_day = planEl.querySelector("[data-fid='price_per_day']");
const price_per_day_integer = planEl.querySelector("[data-fid='price_per_day_integer']");
const price_per_day_decimals = planEl.querySelector("[data-fid='price_per_day_decimals']");
const previewItem = pricingPreview.items[planKey];
const pricePerPeriod = pricingPreview.formatPrice(showPricePerMonth ? previewItem.monthlyPrice : previewItem.priceDay);
const pricePerPeriodShort = pricingPreview.formatPrice(showPricePerMonth ? previewItem.monthlyPrice : previewItem.priceDay, { short: true });
const res = /^(.*[0-9,.]+)[,.]\b([0-9][0-9])$/.exec(pricePerPeriodShort);
const pricePerPeriodInteger = res === null || res === void 0 ? void 0 : res[1];
const pricePerPeriodDecimals = res === null || res === void 0 ? void 0 : res[2];
if (priceMonth)
priceMonth.textContent = previewItem.priceFormatted;
if (price_per_day) {
price_per_day.textContent = pricePerPeriod;
}
if (price_per_day_integer && pricePerPeriodInteger) {
price_per_day_integer.textContent = pricePerPeriodInteger;
}
if (price_per_day_decimals && pricePerPeriodDecimals) {
price_per_day_decimals.textContent = pricePerPeriodDecimals;
}
if (showPricePerMonth) {
planEl.querySelectorAll("[data-fid='per_period_pricing']").forEach(el => {
el.innerText = consts_1.locale === "es" ? "por mes" : "per month";
});
}
}
}
changePlanFormEls.forEach(form => {
form.addEventListener("submit", (e) => __awaiter(this, void 0, void 0, function* () {
e.preventDefault();
e.stopPropagation();
const plan = getSelectedPlan();
if (!plan) {
console.warn("selected plan not found");
return;
}
}));
});
function getSelectedPlan() {
var _a;
if (!changePlanFormEls)
return null;
const key = (_a = config_1.planKeys.find(t => changePlanFormEls[0].querySelector(`.otp-plan-${t}.is-active-inputactive`))) !== null && _a !== void 0 ? _a : null;
return key;
}
return { planTitles, planTitles2 };
}
if (priceSetId) {
container2.classList.add(`pid-${priceSetId}`);
}
const pricingPreview = yield (0, pricing_1.getPricingPreview)({ paddle, priceSetId, discountRate });
console.log(pricingPreview);
const priceDayStrikeEl = Array.from(container2.querySelectorAll(".price-breakdown-day .price-day-strike"));
const priceDayEl = Array.from(container2.querySelectorAll(".price-breakdown-day .price-day"));
const pricePeriodTxtEl = Array.from(container2.querySelectorAll(".price-breakdown-day .price-period-txt"));
const pricePeriodEl = Array.from(container2.querySelectorAll(".price-breakdown-day .price-period"));
const changePlanFormEls = Array.from(container2.querySelectorAll(".plan-form"));
const planEls = {
_1month: Array.from(changePlanFormEls.map(el => el.querySelector(".otp-plan-1month"))),
_3months: Array.from(changePlanFormEls.map(el => el.querySelector(".otp-plan-3month"))),
_12months: Array.from(changePlanFormEls.map(el => el.querySelector(".otp-plan-1year"))),
};
const changePlanForm = initSelectPlanForm({
onPlanChanged: changePlanV3,
});
function changePlanV3(plan) {
priceDayStrikeEl.forEach(el => {
el.textContent = pricingPreview.formatPrice(pricingPreview.items[plan].priceBeforeDiscount);
});
pricePeriodEl.forEach(el => {
el.textContent = pricingPreview.items[plan].priceFormatted;
});
pricePeriodTxtEl.forEach(el => {
el.innerHTML =
plan === "_1month"
? "Billed monthly at "
: plan === "_3months"
? "Billed quarterly at "
: "Billed yearly at ";
});
priceDayEl.forEach(el => (el.textContent = pricingPreview.items[plan].priceDayFormatted));
container2.querySelectorAll(".regular-period-price").forEach(el => {
var _a;
el.textContent = (_a = changePlanForm.planTitles2[plan]) !== null && _a !== void 0 ? _a : "";
});
container2.querySelectorAll(".modal-payment-elements [data-fid=strikethrough_price]").forEach(el => {
el.textContent = el.textContent =
priceSetId === "fst"
? pricingPreview.formatPrice(pricingPreview.items[plan].price)
: pricingPreview.formatPrice(pricingPreview.items[plan].priceBeforeDiscount);
});
container2.querySelectorAll(".modal-payment-elements [data-fid=discount_amount]").forEach(el => {
el.textContent = pricingPreview.formatPrice(pricingPreview.items[plan].discountAmount);
});
container2.querySelectorAll(".modal-payment-elements [data-fid=discount_percent]").forEach(el => {
el.textContent = pricingPreview.items[plan].discountRateFormattedOld;
});
const pricingPreviewItem = pricingPreview.items[plan];
const hasDiscount = pricingPreviewItem.priceBeforeDiscount > pricingPreviewItem.price;
container2
.querySelectorAll(".modal-payment-elements [data-fid=intro_discount_line]")
.forEach(el => {
(0, toggle_1.toggle)(el, hasDiscount, { flex: true });
});
// Object.entries(planEls).forEach(([planKey, els]) => {
// els.forEach(el => {
// const radioEl = el.querySelector("input[type=radio]")
// if (!radioEl) return
// const checked = plan === planKey
// if (checked !== radioEl.checked) {
// radioEl.checked = checked
// }
// })
// })
if (!paddle)
return;
paddle.Checkout.updateItems([pricingPreviewItem.reqItem]);
}
// const user = getUser()
// const email = window.PGdataLayer?.user?.email
const user2 = (0, registerLead_1.getRegisterLead)();
const email = user2 === null || user2 === void 0 ? void 0 : user2.email;
const consumerId = user2 === null || user2 === void 0 ? void 0 : user2.consumerId;
const allowedPaymentMethods = null;
// [
// "apple_pay",
// "google_pay",
// "ideal",
// "card",
// "alipay",
// "bancontact",
// "paypal",
// // "saved_payment_methods",
// ]
paddle.Checkout.open(Object.assign(Object.assign({ discountCode: promocode || null, items: [pricingPreview.items._3months.reqItem], settings: Object.assign(Object.assign({ showAddTaxId: false, variant: "one-page", showAddDiscounts: promocodeExists }, (successUrl ? { successUrl } : {})), (allowedPaymentMethods ? { allowedPaymentMethods } : {})) }, (email ? { customer: { email } } : {})), (consumerId ? { customData: { consumerId } } : {})));
changePlanV3("_3months");
onLoadFinished();
});
}
// https://smart-sleep-coach.webflow.io/otp-ending-pages/avisar-test-2
function setSubscriptionWithRetry(req) {
return __awaiter(this, void 0, void 0, function* () {
let attempt = 0;
const maxAttempts = 3;
while (attempt < maxAttempts) {
attempt++;
const isLastAttempt = attempt === maxAttempts;
const res = yield api_1.api.setSubscription(req).catch(err => {
var _a, _b;
if (!isLastAttempt && (0, axios_1.isAxiosError)(err)) {
const data = ((_b = (_a = err.response) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : {});
if (data.reason === "transaction.noSubscriptionId") {
return "transaction.noSubscriptionId";
}
}
throw err;
});
if (res === "transaction.noSubscriptionId") {
console.log("No subscription ID, retrying");
yield (0, sleep_1.sleep)(2000);
continue;
}
return res;
}
});
}
function toggleMomDadImages(container, params) {
const role = params.get("whatIsMyRole");
const showDad = role === "Dad" || params.has("whySmartSleepCoach_EncourageLongerMorePredictableNaps");
const showMom = role === "Mom" || params.has("whySmartSleepCoach_GetMyBabyToSleepThroughTheNight") || !showDad;
(0, toggle_1.toggleOpacity)(container.querySelector(".dad-image"), showDad);
(0, toggle_1.toggleOpacity)(container.querySelector(".mom-image"), showMom);
}
exports._goalMap = {
"Multiple wake-ups at night": "Reduce wakeups",
"Can’t fall asleep alone": "Simplify bedtime",
"Early riser": "Fix early wakings",
"Refuses to nap": "Consistent naps",
"Takes short naps": "Consistent naps",
"Healthy sleep habits": "Healthy habits",
"Simplify Bedtime": "Simplify bedtime",
"Consistent Naps": "Consistent naps",
"Healthy Sleep Habits": "Healthy habits",
"Reduce Wakeups": "Reduce wakeups",
"Make Bedtime Easier": "Easier Bedtime",
"Fix Early Wakings": "Fix Early wakings",
"Create a Steady Routine": "Steady Routine",
"Set Healthy Sleep Habits": "Healthy habits",
};
/**( NOT IN USE yet) */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
// const whySmartSleepCoachMap = {
// "Fall asleep at bedtime": "Simplify Bedtime",
// "Sleep through the night": "Reduce Wakeups",
// "Reduce early wakeups": "Fix Early Wakings",
// "Consistent nap routine": "Consistent Naps",
// "Build healthy sleep habits": "Set Healthy Sleep Habits",
// }
const _parentGoalMap = {
"Reduce my sleep deprivation": "Better parent sleep",
"Create a consistent routine": "Consistent routine",
"Boost my baby's mood and behavior": "Happier baby",
"Minimize nighttime disruptions for my family": "Peaceful nights",
"Support my baby's long-term growth": "Healthy development",
"Be a more rested, engaged parent": "Rested and engaged",
"All of the above": "Better sleep for all",
};
const goalMapEs = {
"Reducir los despertares": "Reducir despertares",
"Hacer que la hora de dormir sea más fácil": "Hora de dormir fácil",
"Corregir los despertares tempranos": "Sin madrugones",
"Crear una rutina constante": "Rutina estable",
};
const parentGoalMapEs = {
"Reducir mi privación de sueño": "Finalmente dormirás",
"Crear una rutina consistente": "Rutina consistente",
"Mejorar el estado de ánimo y comportamiento de mi bebé": "Bebé más feliz",
"Minimizar las interrupciones nocturnas para mi familia": "Noches tranquilas",
"Fomentar el desarollo a largo plazo de mi bebé": "Desarrollo saludable",
"Ser un(a) padre/madre más descansado/a y comprometido/a": "Descanso y energía",
};
/***/ }),
/***/ 6515:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.otpEndingPageWeb2App = otpEndingPageWeb2App;
exports.updateChildName = updateChildName;
/* eslint-disable @typescript-eslint/no-non-null-assertion */
const env_1 = __webpack_require__(3143);
const pgDataLayer_1 = __webpack_require__(7350);
const registerLead_1 = __webpack_require__(2517);
const toggle_1 = __webpack_require__(2166);
const surveyEndingPage_1 = __webpack_require__(6345);
/**
* 1. timer-component w-condition-invisible - when visible - implement timer
* 2. section_paddle / section_paddle_v2 - use the visibile container
* 3.
*/
function otpEndingPageWeb2App() {
return __awaiter(this, void 0, void 0, function* () {
var _a;
updateChildName();
// const container = document.querySelector(".otp.section:not(.w-condition-invisible)")!
const q = new URLSearchParams(location.search);
const fail = q.get("fail");
(0, surveyEndingPage_1.surveyEndingPage)();
let registerLeadCode = sessionStorage.getItem("registerLeadCode");
if (!registerLeadCode && env_1.env === "staging") {
registerLeadCode = "123456";
}
if (registerLeadCode) {
document.querySelectorAll(".otp-num,.otp-number").forEach(otpNumEl => {
//console.log()
otpNumEl.textContent = registerLeadCode;
const input = document.createElement("input");
input.style.display = "none";
input.value = registerLeadCode;
otpNumEl.parentElement.appendChild(input);
otpNumEl.addEventListener("click", () => __awaiter(this, void 0, void 0, function* () {
try {
input.select();
input.setSelectionRange(0, 99999); // For mobile devices
yield navigator.clipboard.writeText(input.value);
}
catch (err) {
console.warn(err);
}
}));
});
}
const email = (_a = (0, registerLead_1.getRegisterLead)()) === null || _a === void 0 ? void 0 : _a.email;
if (email) {
document.querySelectorAll(".otp-email").forEach(emailEl => {
emailEl.textContent = email;
});
}
if (fail) {
document.querySelectorAll(".otp-default").forEach(t => (0, toggle_1.toggle)(t, false));
document.querySelectorAll(".otp-onerror").forEach(t => {
t.style.display = "flex";
});
(0, pgDataLayer_1.dataLayerPush)("event_crm_action", "event_profile_register_submit_error", `web2app-otp-ending-page-with-error-${fail}`);
return;
}
(0, pgDataLayer_1.dataLayerPush)("event_crm_action", "event_profile_register_complete", "web2app-account-registered-otp-displayed");
// Select the text field
});
}
function updateChildName() {
const q = new URLSearchParams(location.search);
const childName = q.get("childName");
if (!childName) {
return;
}
document.querySelectorAll(".otp-childname").forEach(t => {
t.textContent = childName;
});
}
/***/ }),
/***/ 6253:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.paymentLink = paymentLink;
const paddle_1 = __webpack_require__(3074);
function paymentLink() {
return __awaiter(this, void 0, void 0, function* () {
yield (0, paddle_1.initPaddle)({ frameTarget: null });
});
}
/***/ }),
/***/ 6199:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
/* eslint-disable @typescript-eslint/no-non-null-assertion */
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.question = question;
exports.setFilledSurvey = setFilledSurvey;
exports.setFilledSurveyInStorage = setFilledSurveyInStorage;
exports.getFilledSurvey = getFilledSurvey;
exports.getFilledSurveyFromStorage = getFilledSurveyFromStorage;
exports.getFilledSurveyFromQuery = getFilledSurveyFromQuery;
const getGeoFeed_1 = __webpack_require__(7539);
const welcomeSurvey_1 = __webpack_require__(2125);
function onSubmit(e) {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b, _c;
console.log("register form submit", e);
e.preventDefault();
e.stopPropagation();
const form = e.target;
const submitter = e.submitter;
const buttonAnswer = submitter.getAttribute("data-button-answer");
const questionId = form.id;
const answers = {};
Array.from(form.querySelectorAll("input[type=checkbox]"))
.filter(t => t.checked)
.map(t => t.id)
.forEach(id => {
answers[id] = true;
});
if (buttonAnswer) {
answers[buttonAnswer] = true;
}
if (isCustomSurvey(form)) {
const valid = !!Object.keys(answers).length;
(_a = form.querySelector(".selectanswer-text")) === null || _a === void 0 ? void 0 : _a.classList.toggle("opacity1", !valid);
if (!valid)
return;
}
let sid = (_b = form.elements.namedItem("segmantaid")) === null || _b === void 0 ? void 0 : _b.value;
const geofeed = yield (0, getGeoFeed_1.getGeoFeed)();
if ((geofeed === null || geofeed === void 0 ? void 0 : geofeed.country) !== "US") {
const sidNonUs = (_c = document.querySelector("[name=segmantaid-nonus]")) === null || _c === void 0 ? void 0 : _c.value;
if (sidNonUs) {
sid = sidNonUs;
}
}
const surveyFromQuery = getFilledSurveyFromQuery();
setFilledSurvey(Object.assign(Object.assign(Object.assign({}, surveyFromQuery), { sid, questionId }), answers));
console.log("filledSurvey", getFilledSurvey());
const noiframe = new URLSearchParams(location.search).get("noiframe") || "2";
// if (
// !noiframe &&
// (window.location.pathname === paths.surveyMetaB || window.location.pathname === paths.surveyMeta)
// ) {
// noiframe = "2"
// }
if (noiframe === "1") {
console.log("noiframe detected redirecting directly to segmanta");
const url = yield (0, welcomeSurvey_1.getSegmantaRedirectUrl)();
console.log("redirectToSegmanta", url);
location.href = url;
return;
}
if (noiframe === "2") {
console.log("noiframe detected redirecting to segmanta custom domain");
const url = (yield (0, welcomeSurvey_1.getSegmantaRedirectUrl)()).replace("pgsurveys.segmanta.com", "s.smartsleepcoach.com");
console.log("redirectToSegmantaCustomDomain", url);
location.href = url;
return;
}
const url = form.getAttribute("redirect");
if (!url) {
console.error("redirect url not found");
return;
}
location.href = url;
});
}
function updateForm(form) {
var _a;
const show = !!form.querySelector("input[type=checkbox]:checked");
form.querySelector("input[type=submit]").classList.toggle("formsubmit-show", show);
if (isCustomSurvey(form)) {
// form.querySelector("input[type=submit]")!.classList.toggle("active", show)
if (show) {
(_a = form.querySelector(".selectanswer-text")) === null || _a === void 0 ? void 0 : _a.classList.remove("opacity1");
}
}
}
function question() {
hookUpQuestionForms();
onFsRichTextLoaded(hookUpQuestionForms);
}
function isCustomSurvey(form) {
return !!form.closest(".dt3-form,.dt2-form");
}
function hookUpQuestionForms() {
const forms = Array.from(document.querySelectorAll(`form[data-name=question]`));
for (const form of forms) {
if (form._question)
continue;
form._question = true;
form.addEventListener("submit", onSubmit);
updateForm(form);
form.querySelectorAll("input[type=checkbox]").forEach(el => {
el.addEventListener("change", () => {
updateForm(form);
});
});
form.querySelectorAll("[data-button-answer]").forEach(el => {
el.addEventListener("click", (e) => __awaiter(this, void 0, void 0, function* () {
yield onSubmit({
target: form,
submitter: el,
preventDefault: () => e.preventDefault(),
stopPropagation: () => e.stopPropagation(),
});
}));
});
console.log("hooked up question form", form.id);
}
}
const storageKey = "filledSurvey";
function setFilledSurvey(answers) {
setFilledSurveyInStorage(localStorage, answers);
}
function setFilledSurveyInStorage(storage, answers) {
storage.setItem(storageKey, JSON.stringify(answers));
}
function getFilledSurvey() {
return getFilledSurveyFromStorage(localStorage);
}
function getFilledSurveyFromStorage(storage) {
const v = storage.getItem(storageKey);
if (!v)
return null;
try {
const obj = JSON.parse(v);
if (typeof obj !== "object")
return null;
return obj;
}
catch (err) {
console.warn(err);
return null;
}
}
function getFilledSurveyFromQuery() {
const query = new URLSearchParams(location.search);
const entries = Array.from(query.entries());
if (!entries.length)
return null;
const x = {};
Array.from(query.entries()).forEach(([key, value]) => {
x[key] = value;
});
return x;
}
function onFsRichTextLoaded(cb) {
window.fsAttributes = window.fsAttributes || [];
window.fsAttributes.push(["richtext", cb]);
}
/***/ }),
/***/ 8251:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.register1 = register1;
/* eslint-disable @typescript-eslint/no-non-null-assertion */
// TODO:
// remove original code from signup page
// validate emails in realtime
// check captcha?
const ApiClient_1 = __webpack_require__(2672);
const config_1 = __webpack_require__(7028);
const api_1 = __webpack_require__(6752);
const disableForm_1 = __webpack_require__(4150);
const intlTelInput_1 = __webpack_require__(1546);
const recaptcha_1 = __webpack_require__(3481);
const toggle_1 = __webpack_require__(2166);
const register1Form = {
email: "Email-Address",
password: "Password",
name: "First-Name",
phone: "Phone-Number",
};
function onSubmit(e) {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b;
console.log("register form submit", e);
e.preventDefault();
e.stopPropagation();
const form = e.target;
const passwordInput = form.elements.namedItem("Password");
const email = form.elements.namedItem("Email-Address").value;
const password = passwordInput.value;
const nickname = form.elements.namedItem("First-Name").value;
const phoneInput = form.elements.namedItem("Phone-Number");
const phone_number = (_b = (_a = window.intlTelInputGlobals.getInstance(phoneInput)) === null || _a === void 0 ? void 0 : _a.getNumber()) !== null && _b !== void 0 ? _b : phoneInput.value;
const grecaptcha = yield (0, recaptcha_1.loadRecaptcha)();
const recaptchaToken = yield grecaptcha.enterprise.execute(config_1.config.recaptchaSiteKey, { action: "REGISTER" });
let err = null;
console.log({ recaptchaToken, email, password, nickname, phone_number });
try {
(0, disableForm_1.disableForm)(form);
const res = yield api_1.api.register({ recaptchaToken, email, password, nickname, phone_number });
console.log(res);
(0, disableForm_1.enableForm)(form);
}
catch (e) {
err = e;
console.warn(e);
}
const apiError = (0, ApiClient_1.toApiError)(err);
(0, disableForm_1.enableForm)(form);
(0, toggle_1.toggle)("#success_message", !err);
(0, toggle_1.toggle)("#error_message", !!err);
(0, toggle_1.toggle)(form, false);
if (err) {
if (apiError === null || apiError === void 0 ? void 0 : apiError.message) {
document.querySelector("#error_message").textContent = apiError.message;
}
(0, disableForm_1.enableForm)(form);
return;
}
const url = form.getAttribute("redirect");
if (!url) {
console.error("redirect url not found");
return;
}
location.href = url;
});
}
function register1() {
return __awaiter(this, void 0, void 0, function* () {
const form = document.querySelector("form[name=wf-form-Sign-Up]");
form.addEventListener("submit", onSubmit);
const input = form.elements.namedItem("Phone-Number");
const steps = [".step_1", ".step_2", ".step_3", ".step_4"];
const nextButtons = [".step_1 .button_next", ".step_2 .button_next", ".step_3 .button_next"];
const prevButtons = [".step_2 .button_previous", ".step_3 .button_previous", ".step_4 .button_previous"];
let currentStep = 0;
init();
void (0, recaptcha_1.loadRecaptcha)();
const intlTelInput = yield (0, intlTelInput_1.loadIntlTelInput)();
intlTelInput(input, { utilsScript: intlTelInput_1.intlTelInputUtilsScript });
function init() {
showStep();
nextButtons.forEach((btn, i) => {
$(btn).on("click", () => {
if (validateStep(steps[i])) {
currentStep++;
showStep();
}
});
});
prevButtons.forEach(btn => {
$(btn).on("click", () => {
currentStep--;
showStep();
});
});
$("input").on("focus", e => {
$(e.currentTarget).css("border", "1px solid #f1f1f1");
$(e.currentTarget).next(".tooltip").hide();
});
}
function showStep() {
steps.forEach((step, index) => {
$(step).toggle(index === currentStep);
});
}
function validateStep(step) {
let isValid = true;
const inputs = $(step).find("input[required]").toArray();
for (const el of inputs) {
const input = $(el);
const value = input.val().trim();
let err = "";
if (!value) {
err = "This field is required";
}
if (!err && el.name === register1Form.email && !isEmailValid(value)) {
err = "Please enter a valid email address";
}
if (err) {
isValid = false;
input.css("border", "1px solid red");
const tooltip = input.next(".tooltip");
if (tooltip.length === 0) {
input.after(`${err}
`);
continue;
}
tooltip.show();
continue;
}
input.css("border", "1px solid #f1f1f1");
input.next(".tooltip").hide();
}
return isValid;
}
});
}
// //attach a click handler to the button to make it transform when clicked, via our transform() function below
// document.querySelector("[data-transform]")?.addEventListener("click", transform)
// //flag of whether or not it is a password field or text field
// const isPassword = true
// //this function will toggle the input between being a password or a text input
// function transform() {
// //copy the element itself, its html source, and value text to a variable
// var myInput = document.querySelector("[data-show]")
// var oldHtml = myInput.outerHTML
// var text = myInput.value
// if (isPassword) {
// //replace "password" with "text" in the html if it is a password field
// var newHtml = oldHtml.replace(/password/g, "text")
// } else {
// //replace "text" with "password" if it is a text field
// newHtml = oldHtml.replace(/text/g, "password")
// }
// //update the html
// myInput.outerHTML = newHtml
// //restore the text value
// myInput = document.querySelector("[data-show]")
// myInput.value = text
// //toggle the isPassword flag
// isPassword = !isPassword
// }
function isEmailValid(email) {
const re = /\S+@\S+\.\S+/;
return re.test(email);
}
/***/ }),
/***/ 4377:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.onSubmit = onSubmit;
exports.register2 = register2;
exports.resendCode = resendCode;
/* eslint-disable @typescript-eslint/no-non-null-assertion */
const ApiClient_1 = __webpack_require__(2672);
const consts_1 = __webpack_require__(8066);
const api_1 = __webpack_require__(6752);
const disableForm_1 = __webpack_require__(4150);
const getQueryParam_1 = __webpack_require__(7089);
const toggle_1 = __webpack_require__(2166);
/** /phone-verification */
function onSubmit(e) {
return __awaiter(this, void 0, void 0, function* () {
e.preventDefault();
e.stopPropagation();
const form = e.target;
const verification_code = form.elements.namedItem("SMS_Code").value;
let err = null;
try {
(0, disableForm_1.disableForm)(form);
const res = yield api_1.api.twoFactorVerify({ verification_code });
console.log(res);
}
catch (e) {
err = e;
console.warn(err);
}
const apiError = (0, ApiClient_1.toApiError)(err);
(0, disableForm_1.enableForm)(form);
(0, toggle_1.toggle)("#success_message", !err);
(0, toggle_1.toggle)("#error_message", !!err);
(0, toggle_1.toggle)(form, false);
if (err) {
if (apiError === null || apiError === void 0 ? void 0 : apiError.message) {
document.querySelector("#error_message").textContent = apiError.message;
}
(0, disableForm_1.enableForm)(form);
return;
}
const url = (0, getQueryParam_1.getQueryParam)("redirect") || form.getAttribute("redirect");
if (!url) {
console.error("redirect url not found, defaulting to welcome page");
}
location.href = url || consts_1.paths.welcome;
});
}
function register2() {
const form = document.querySelector("form[name=wf-form-Phone-Verification]");
form.addEventListener("submit", onSubmit);
const btnResendCode = document.querySelector("#resendCode");
btnResendCode.addEventListener("click", resendCode);
}
function resendCode() {
return __awaiter(this, void 0, void 0, function* () {
yield api_1.api.twoFactorResend();
});
}
/***/ }),
/***/ 9854:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.resetPassword1 = resetPassword1;
/* eslint-disable @typescript-eslint/no-non-null-assertion */
const api_1 = __webpack_require__(6752);
const disableForm_1 = __webpack_require__(4150);
const toggle_1 = __webpack_require__(2166);
const pgDataLayer_1 = __webpack_require__(7350);
const extractErrorMessage_1 = __webpack_require__(6395);
const consts_1 = __webpack_require__(8066);
function onSubmit(e) {
return __awaiter(this, void 0, void 0, function* () {
e.preventDefault();
e.stopPropagation();
const form = e.target;
const email = form.elements.namedItem("email-address-2").value;
let err = null;
try {
(0, disableForm_1.disableForm)(form);
yield api_1.api.forgotPassword({ email, locale: consts_1.locale === "es" ? "es-US" : "en-US" });
}
catch (e) {
err = e;
(0, pgDataLayer_1.dataLayerPush)("error_event", "password_reset_error", (0, extractErrorMessage_1.extractErrorMessage)(e));
}
(0, disableForm_1.enableForm)(form);
(0, toggle_1.toggle)("#success_message", !err);
(0, toggle_1.toggle)("#error_message", !!err);
(0, toggle_1.toggle)(form, false);
});
}
function resetPassword1() {
console.log("resetPassword1");
const form = document.querySelector(`form[name=wf-form-reset-password]`);
form.addEventListener("submit", onSubmit);
}
/***/ }),
/***/ 9955:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.resetPassword2 = resetPassword2;
/* eslint-disable @typescript-eslint/no-non-null-assertion */
const axios_1 = __webpack_require__(6425);
const consts_1 = __webpack_require__(8066);
const api_1 = __webpack_require__(6752);
const disableForm_1 = __webpack_require__(4150);
const sleep_1 = __webpack_require__(9879);
const toggle_1 = __webpack_require__(2166);
const pgDataLayer_1 = __webpack_require__(7350);
const extractErrorMessage_1 = __webpack_require__(6395);
function onSubmit(e) {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b;
e.preventDefault();
e.stopPropagation();
const form = e.target;
const passwordInput = form.elements.namedItem("Password");
const password = passwordInput.value;
const confirmPasswordInput = form.elements.namedItem("Password-confirm");
const confirmPassword = confirmPasswordInput.value;
const code = new URLSearchParams(location.search).get("code");
let err = null;
if (confirmPassword !== password) {
confirmPasswordInput.setCustomValidity("Passwords do not match");
confirmPasswordInput.reportValidity();
yield (0, sleep_1.sleep)(2000);
confirmPasswordInput.setCustomValidity("");
return;
}
try {
(0, disableForm_1.disableForm)(form);
yield api_1.api.completeForgotPassword({ password, code });
}
catch (e) {
err = e;
if ((0, axios_1.isAxiosError)(e)) {
if (((_a = e.response) === null || _a === void 0 ? void 0 : _a.status) === 400) {
err = "Password does not match the requirements";
}
else if (((_b = e.response) === null || _b === void 0 ? void 0 : _b.status) === 403) {
err = `Authorization code is expired or invalid
Click here to try again`;
}
}
(0, pgDataLayer_1.dataLayerPush)("error_event", "password_reset_error", (0, extractErrorMessage_1.extractErrorMessage)(e));
}
(0, disableForm_1.enableForm)(form);
(0, toggle_1.toggle)("#success_message", !err);
if (typeof err === "string") {
const errMsgEl = document.querySelector("#error_message .field-label-copy");
if (errMsgEl) {
errMsgEl.innerHTML = err;
}
}
(0, toggle_1.toggle)("#error_message", !!err);
(0, toggle_1.toggle)(form, false);
});
}
function resetPassword2() {
console.log("resetPassword2");
const code = new URLSearchParams(location.search).get("code");
if (!code) {
console.log("no code in url");
location.href = consts_1.paths.resetPassword1;
return;
}
const form = document.querySelector(`form[name=wf-form-change-password-2]`);
form.addEventListener("submit", onSubmit);
}
/***/ }),
/***/ 8182:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.reviews = reviews;
/* eslint-disable @typescript-eslint/no-non-null-assertion */
const Api2Client_1 = __webpack_require__(9358);
const config_1 = __webpack_require__(7028);
const stars_1 = __webpack_require__(1421);
const user_1 = __webpack_require__(6441);
// import { submitReview } from "./submitReview"
let offset = 0;
const sorts = { ratingDesc: "Rating:desc", ratingAsc: "Rating:asc", recent: "SubmissionTime:desc" };
const dateTimeFormat = new Intl.DateTimeFormat("en-US");
function reviews() {
return __awaiter(this, void 0, void 0, function* () {
const btnWriteAReview = document.querySelector("#btnWriteAReview");
btnWriteAReview === null || btnWriteAReview === void 0 ? void 0 : btnWriteAReview.addEventListener("click", e => {
const user = (0, user_1.getUser)();
if (user) {
return;
}
e.preventDefault();
e.stopPropagation();
location.href = "/sign-in?redirect=/reviews";
});
const rbRecent = document.querySelector("#MostRecent");
const rbRatingDesc = document.querySelector("#HighestToLowest");
const rbRatingAsc = document.querySelector("#LowestToHighest");
const rbSorts = [rbRecent, rbRatingDesc, rbRatingAsc];
rbRecent.value = sorts.recent;
rbRatingDesc.value = sorts.ratingDesc;
rbRatingAsc.value = sorts.ratingAsc;
const btnSeeMore = document.querySelector("a.ssc_button.w-button");
const template = document.querySelector(".bv-reviews__content");
const container = template.parentElement;
btnSeeMore === null || btnSeeMore === void 0 ? void 0 : btnSeeMore.addEventListener("click", seeMoreReviews);
rbSorts.forEach(el => el.addEventListener("change", e => sortBy(e.target.value)));
const ratingInputsWrapper = document.querySelector("#StarWrapper");
if (ratingInputsWrapper) {
const ratingInputs = Array.from(ratingInputsWrapper.querySelectorAll("input"));
ratingInputs[0].setCustomValidity("Please choose a star rating");
ratingInputs.forEach(el => el.addEventListener("change", () => {
ratingInputs[0].setCustomValidity("");
}));
}
let sort = getSort();
if (!sort) {
sort = sorts.ratingDesc;
rbRatingDesc.checked = true;
}
yield Promise.all([seeMoreReviews(), stats()]);
function getSort() {
var _a;
return (_a = rbSorts.find(t => t.checked)) === null || _a === void 0 ? void 0 : _a.value;
}
function stats() {
return __awaiter(this, void 0, void 0, function* () {
const res = yield Api2Client_1.api2.getStats({
filter: `productId:${config_1.config.bazaarvoiceProductId}`,
passkey: config_1.config.bazaarvoicePasskey,
apiversion: "5.4",
stats: "Reviews",
});
const avgStarsEl = document.querySelector(".rating_container_average .starhtml");
avgStarsEl.textContent = "";
avgStarsEl.append(renderStars(res.Results[0].ProductStatistics.ReviewStatistics.AverageOverallRating));
document.querySelector(".bv-reviews__final-rating").textContent =
res.Results[0].ProductStatistics.ReviewStatistics.AverageOverallRating.toFixed(1);
document.querySelector(".rating_container_average .usercountspan").textContent = `${res.Results[0].ProductStatistics.ReviewStatistics.TotalReviewCount}`;
});
}
function seeMoreReviews() {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b;
const res = yield Api2Client_1.api2.getReviews({
passkey: config_1.config.bazaarvoicePasskey,
filter: `ProductId:${config_1.config.bazaarvoiceProductId}`,
limit: 5,
Offset: offset,
apiversion: "5.4",
Sort: sort,
});
if (offset === 0) {
container.innerHTML = "";
}
for (const review of res.Results) {
const el = template.cloneNode(true);
el.querySelector(".bv-reviews__content-left .bv-reviews__name").textContent = review.UserNickname;
el.querySelector(".bv-reviews__content-right .bv-reviews__title").textContent = review.Title;
el.querySelector(".bv-reviews__text-input").textContent = review.ReviewText;
el.querySelector(".bv-reviews__date").textContent = dateTimeFormat.format(new Date(review.SubmissionTime));
el.querySelector(".rating_container_single .starhtml").textContent = "";
el.querySelector(".rating_container_single .starhtml").append(renderStars(review.Rating));
const toggleModal = () => {
const modal = el.querySelector(".b_auth_modal");
if (!modal)
return;
modal.style.display = modal.style.display === "block" ? "none" : "block";
};
(_a = el.querySelector(".b_auth")) === null || _a === void 0 ? void 0 : _a.addEventListener("click", toggleModal);
(_b = el.querySelector(".modal_close-button")) === null || _b === void 0 ? void 0 : _b.addEventListener("click", toggleModal);
container.append(el);
}
offset += res.Results.length;
if (offset >= res.TotalResults && btnSeeMore) {
btnSeeMore.style.display = "none";
}
});
}
function sortBy(s) {
return __awaiter(this, void 0, void 0, function* () {
offset = 0;
sort = s;
yield seeMoreReviews();
});
}
// submitReview()
});
}
function renderStars(v) {
const div = document.createElement("div");
for (let i = 0; i < 5; i++) {
let vv;
if (v >= i + 1) {
console.log("star");
vv = 10;
}
else if (v > i) {
vv = Math.ceil((i ? v % i : v) * 10);
}
else {
vv = 0;
}
const img = $(stars_1.stars[vv])[0];
img.classList.add("star-svg");
// document.createElement("img")
// img.src = `${config.starsUrl}star${vv}.svg`
div.append(img);
}
return div;
}
/***/ }),
/***/ 4362:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.sleepAssessment = sleepAssessment;
const consts_1 = __webpack_require__(8066);
const getGeoFeed_1 = __webpack_require__(7539);
const question_1 = __webpack_require__(6199);
const welcomeSurvey_1 = __webpack_require__(2125);
function sleepAssessment() {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b, _c;
const dt4El = document.querySelector(".section-dt4:not(.w-condition-invisible)");
if (!dt4El)
return;
let sid = (_a = dt4El.querySelector("input[name=segmantaid]")) === null || _a === void 0 ? void 0 : _a.value;
const geofeed = yield (0, getGeoFeed_1.getGeoFeed)();
if (!["US", "CA"].includes((_b = geofeed === null || geofeed === void 0 ? void 0 : geofeed.country) !== null && _b !== void 0 ? _b : "")) {
const sidNonUs = (_c = document.querySelector("[name=segmantaid-nonus]")) === null || _c === void 0 ? void 0 : _c.value;
if (sidNonUs) {
sid = sidNonUs;
}
}
const dt4Buttons = Array.from(dt4El.querySelectorAll("[data-fid='quiz_answer_img']"));
dt4Buttons.forEach(btn => {
btn.addEventListener("click", (e) => __awaiter(this, void 0, void 0, function* () {
e.preventDefault();
e.stopPropagation();
// const questionId = form.id
const id = btn.id;
const answers = {
[id]: true,
};
const surveyFromQuery = (0, question_1.getFilledSurveyFromQuery)();
(0, question_1.setFilledSurvey)(Object.assign(Object.assign(Object.assign({}, surveyFromQuery), { sid }), answers));
const q = new URLSearchParams(location.search);
const isWebflowSurvey = q.has("webflow-survey");
if (isWebflowSurvey) {
const survey = (0, welcomeSurvey_1.getFinalFilledSurvey)();
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const _a = Object.assign({}, survey), { sid } = _a, rest = __rest(_a, ["sid"]);
Object.entries(rest).forEach(([key, value]) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
q.set(key, value);
});
q.delete("webflow-survey");
console.log("webflow survey detected - redirecting");
location.href = `${consts_1.paths.fullSurvey2025}?${q.toString()}`;
return;
}
console.log("noiframe detected redirecting to segmanta custom domain");
const url = (yield (0, welcomeSurvey_1.getSegmantaRedirectUrl)()).replace("pgsurveys.segmanta.com", "s.smartsleepcoach.com");
console.log("redirectToSegmantaCustomDomain", url);
location.href = url;
return;
}));
});
});
}
/***/ }),
/***/ 6345:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.surveyEndingPage = surveyEndingPage;
const detect_1 = __webpack_require__(957);
const question_1 = __webpack_require__(6199);
function surveyEndingPage() {
console.log("surveyEndingPage");
restoreParams();
replaceDownloadLinksOnRevisit();
}
function restoreParams() {
const q = new URLSearchParams(location.search);
if (q.get("restore_params") !== "1")
return;
const survey = (0, question_1.getFilledSurvey)();
if (!survey)
return;
Object.entries(survey).forEach(([key, value]) => {
if (!q.get(key)) {
q.set(key, value);
}
});
q.delete("restore_params");
Array.from(q.keys()).forEach(key => {
const key2 = key.toLowerCase();
//"SsCid"
if ([
"utm_",
"fbclid",
"ttclid",
"sccid",
"childName",
"barriersToBetterSleep",
"childBirthDate",
"parentGoal",
"gbraid",
"wbraid",
"gclid",
"gad_source",
"sessionId",
"fail",
"retry",
"whySmartSleepCoach",
"whatIsMyRole",
"pid",
"period",
].some(t => key2.startsWith(t.toLowerCase()))) {
return;
}
q.delete(key);
});
if (!q.size)
return;
const newUrl = `${location.pathname}?${q.toString()}`;
history.pushState(null, "", newUrl);
// location.href = newUrl
}
let pageLoadedFromBfCache = false;
function isVisited() {
return !!sessionStorage.getItem("visitedSurveyEndingPage") || pageLoadedFromBfCache;
}
function setVisited() {
sessionStorage.setItem("visitedSurveyEndingPage", "1");
}
function replaceDownloadLinksOnRevisit() {
window.addEventListener("pageshow", e => {
console.log(e);
if (e.persisted) {
pageLoadedFromBfCache = true;
}
_replaceDownloadLinksOnRevisit();
});
}
function _replaceDownloadLinksOnRevisit() {
const visited = isVisited();
if (visited) {
if (!(0, detect_1.isIos)() && !(0, detect_1.isAndroid)()) {
console.log("survey ending page was visited, but not replacing download links because ios or android is not detected");
return;
}
console.log("survey ending page was visited, replacing download links to direct");
document.querySelectorAll("a[href]").forEach(a => {
if (!a.href.includes("app.adjust.com"))
return;
const ios = "https://apps.apple.com/app/smart-sleep-coach-by-pampers/id1616824897";
const android = "https://play.google.com/store/apps/details?id=com.pg.smartsleepcoach";
const href = (0, detect_1.isIos)() ? ios : (0, detect_1.isAndroid)() ? android : null;
if (!href)
return;
a.href = href;
});
return;
}
console.log("marking survey ending page as visited");
setVisited();
}
/***/ }),
/***/ 8090:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.termsOfUse = termsOfUse;
const getTerms_1 = __webpack_require__(1741);
function termsOfUse() {
return __awaiter(this, void 0, void 0, function* () {
const res = yield (0, getTerms_1.getTerms)();
if (!res)
return;
document.querySelectorAll("[data-fid=linkTermsAndConditions]").forEach(link => {
link.innerText = res.legalLinks.termsAndConditions;
link.href = res.legalLinks.termsAndConditions;
});
document.querySelectorAll("[data-fid=linkPrivacyPolicy]").forEach(link => {
link.innerText = res.legalLinks.privacyPolicy;
link.href = res.legalLinks.privacyPolicy;
});
document.querySelectorAll("[data-fid=linkUnsubscribe]").forEach(link => {
link.innerText = res.termsLinks.unsubscribe.text;
link.href = res.termsLinks.unsubscribe.url;
});
});
}
/***/ }),
/***/ 2125:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.welcomeSurvey = welcomeSurvey;
exports.getSegmantaRedirectUrl = getSegmantaRedirectUrl;
exports.getFinalFilledSurvey = getFinalFilledSurvey;
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-non-null-assertion */
const detect_1 = __webpack_require__(957);
const pgDataLayer_1 = __webpack_require__(7350);
const segment_1 = __webpack_require__(1685);
const question_1 = __webpack_require__(6199);
const defaultSid = "296n19";
function welcomeSurvey() {
return __awaiter(this, void 0, void 0, function* () {
const iframe = document.querySelector("#iFrameResizer0");
const survey = getFinalFilledSurvey();
if (!survey.sid) {
survey.sid = defaultSid;
}
const { sid } = survey;
const blockedSids = Array.from(document.querySelectorAll(".android-blocked-sids .w-dyn-item")).map(t => t.textContent);
if ((0, detect_1.isAndroid)() && blockedSids.includes(sid)) {
console.log("Blocked sid and android detected, showing overlay", sid);
document.querySelector(".android-screen").style.display = "block";
return null;
}
if (!iframe) {
console.error("segmanta iframe not found");
return;
}
const url = yield getSegmantaSurveyUrl(survey);
iframe.src = url;
});
}
function getSegmantaRedirectUrl() {
return __awaiter(this, void 0, void 0, function* () {
const survey = getFinalFilledSurvey();
const url = yield getSegmantaSurveyUrl(survey);
return url;
});
}
function getFinalFilledSurvey() {
const survey = Object.assign(Object.assign({}, (0, question_1.getFilledSurveyFromStorage)(localStorage)), (0, question_1.getFilledSurveyFromQuery)());
if (!survey.sid) {
survey.sid = defaultSid;
}
return survey;
}
// declare global {
// let analytics: {
// identify(userId: string, opts?: unknown): Promise
// user(): { anonymousId(): string }
// }
// }
function getSegmantaSurveyUrl(survey) {
return __awaiter(this, void 0, void 0, function* () {
var _a;
const _b = Object.assign({}, survey), { sid } = _b, rest = __rest(_b, ["sid"]);
const bannerSurveryIds = (((_a = document.querySelector(".offer-banner-survey-id")) === null || _a === void 0 ? void 0 : _a.innerText) || "")
.split(",")
.map(t => t.trim());
const banner = document.querySelector(".offer-banner");
if (banner && bannerSurveryIds.includes(sid)) {
banner.classList.add("offer-banner-show");
}
const query = new URLSearchParams(rest);
const analytics = yield (0, segment_1.ifSegmentReady)();
if (analytics) {
const segmentaAnonymousId = analytics.user().anonymousId();
query.append("ajs_aid", segmentaAnonymousId);
}
else {
(0, pgDataLayer_1.dataLayerPush)("event_informational_action", "event_button_click", "start-survey-no-segment-id-error");
}
const url = `https://pgsurveys.segmanta.com/${sid}?${query.toString()}`;
return url;
});
}
// if (survey) {
// setFilledSurveyInStorage(sessionStorage, survey)
// // history.replaceState(null, "", location.pathname)
// }
// if (!survey) {
// survey = getFilledSurveyFromStorage(sessionStorage)
// }
// const query = new URLSearchParams(location.search)
// // const survey = getFilledSurvey()
// let surveyId = query.get("sid") || survey?.sid
// if (
// !surveyId ||
// typeof surveyId !== "string" ||
// surveyId.length > 50 ||
// encodeURIComponent(surveyId) !== surveyId
// ) {
// console.error("Invalid surveyId", surveyId)
// surveyId = "296n19"
// }
// query.delete("sid")
/***/ }),
/***/ 6425:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
// Axios v1.7.7 Copyright (c) 2024 Matt Zabriskie and contributors
function bind(fn, thisArg) {
return function wrap() {
return fn.apply(thisArg, arguments);
};
}
// utils is a library of generic helper functions non-specific to axios
const {toString} = Object.prototype;
const {getPrototypeOf} = Object;
const kindOf = (cache => thing => {
const str = toString.call(thing);
return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
})(Object.create(null));
const kindOfTest = (type) => {
type = type.toLowerCase();
return (thing) => kindOf(thing) === type
};
const typeOfTest = type => thing => typeof thing === type;
/**
* Determine if a value is an Array
*
* @param {Object} val The value to test
*
* @returns {boolean} True if value is an Array, otherwise false
*/
const {isArray} = Array;
/**
* Determine if a value is undefined
*
* @param {*} val The value to test
*
* @returns {boolean} True if the value is undefined, otherwise false
*/
const isUndefined = typeOfTest('undefined');
/**
* Determine if a value is a Buffer
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Buffer, otherwise false
*/
function isBuffer(val) {
return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
&& isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
}
/**
* Determine if a value is an ArrayBuffer
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is an ArrayBuffer, otherwise false
*/
const isArrayBuffer = kindOfTest('ArrayBuffer');
/**
* Determine if a value is a view on an ArrayBuffer
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
*/
function isArrayBufferView(val) {
let result;
if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
result = ArrayBuffer.isView(val);
} else {
result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));
}
return result;
}
/**
* Determine if a value is a String
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a String, otherwise false
*/
const isString = typeOfTest('string');
/**
* Determine if a value is a Function
*
* @param {*} val The value to test
* @returns {boolean} True if value is a Function, otherwise false
*/
const isFunction = typeOfTest('function');
/**
* Determine if a value is a Number
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Number, otherwise false
*/
const isNumber = typeOfTest('number');
/**
* Determine if a value is an Object
*
* @param {*} thing The value to test
*
* @returns {boolean} True if value is an Object, otherwise false
*/
const isObject = (thing) => thing !== null && typeof thing === 'object';
/**
* Determine if a value is a Boolean
*
* @param {*} thing The value to test
* @returns {boolean} True if value is a Boolean, otherwise false
*/
const isBoolean = thing => thing === true || thing === false;
/**
* Determine if a value is a plain Object
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a plain Object, otherwise false
*/
const isPlainObject = (val) => {
if (kindOf(val) !== 'object') {
return false;
}
const prototype = getPrototypeOf(val);
return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
};
/**
* Determine if a value is a Date
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Date, otherwise false
*/
const isDate = kindOfTest('Date');
/**
* Determine if a value is a File
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a File, otherwise false
*/
const isFile = kindOfTest('File');
/**
* Determine if a value is a Blob
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Blob, otherwise false
*/
const isBlob = kindOfTest('Blob');
/**
* Determine if a value is a FileList
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a File, otherwise false
*/
const isFileList = kindOfTest('FileList');
/**
* Determine if a value is a Stream
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Stream, otherwise false
*/
const isStream = (val) => isObject(val) && isFunction(val.pipe);
/**
* Determine if a value is a FormData
*
* @param {*} thing The value to test
*
* @returns {boolean} True if value is an FormData, otherwise false
*/
const isFormData = (thing) => {
let kind;
return thing && (
(typeof FormData === 'function' && thing instanceof FormData) || (
isFunction(thing.append) && (
(kind = kindOf(thing)) === 'formdata' ||
// detect form-data instance
(kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]')
)
)
)
};
/**
* Determine if a value is a URLSearchParams object
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a URLSearchParams object, otherwise false
*/
const isURLSearchParams = kindOfTest('URLSearchParams');
const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest);
/**
* Trim excess whitespace off the beginning and end of a string
*
* @param {String} str The String to trim
*
* @returns {String} The String freed of excess whitespace
*/
const trim = (str) => str.trim ?
str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
/**
* Iterate over an Array or an Object invoking a function for each item.
*
* If `obj` is an Array callback will be called passing
* the value, index, and complete array for each item.
*
* If 'obj' is an Object callback will be called passing
* the value, key, and complete object for each property.
*
* @param {Object|Array} obj The object to iterate
* @param {Function} fn The callback to invoke for each item
*
* @param {Boolean} [allOwnKeys = false]
* @returns {any}
*/
function forEach(obj, fn, {allOwnKeys = false} = {}) {
// Don't bother if no value provided
if (obj === null || typeof obj === 'undefined') {
return;
}
let i;
let l;
// Force an array if not already something iterable
if (typeof obj !== 'object') {
/*eslint no-param-reassign:0*/
obj = [obj];
}
if (isArray(obj)) {
// Iterate over array values
for (i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
} else {
// Iterate over object keys
const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
const len = keys.length;
let key;
for (i = 0; i < len; i++) {
key = keys[i];
fn.call(null, obj[key], key, obj);
}
}
}
function findKey(obj, key) {
key = key.toLowerCase();
const keys = Object.keys(obj);
let i = keys.length;
let _key;
while (i-- > 0) {
_key = keys[i];
if (key === _key.toLowerCase()) {
return _key;
}
}
return null;
}
const _global = (() => {
/*eslint no-undef:0*/
if (typeof globalThis !== "undefined") return globalThis;
return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : __webpack_require__.g)
})();
const isContextDefined = (context) => !isUndefined(context) && context !== _global;
/**
* Accepts varargs expecting each argument to be an object, then
* immutably merges the properties of each object and returns result.
*
* When multiple objects contain the same key the later object in
* the arguments list will take precedence.
*
* Example:
*
* ```js
* var result = merge({foo: 123}, {foo: 456});
* console.log(result.foo); // outputs 456
* ```
*
* @param {Object} obj1 Object to merge
*
* @returns {Object} Result of all merge properties
*/
function merge(/* obj1, obj2, obj3, ... */) {
const {caseless} = isContextDefined(this) && this || {};
const result = {};
const assignValue = (val, key) => {
const targetKey = caseless && findKey(result, key) || key;
if (isPlainObject(result[targetKey]) && isPlainObject(val)) {
result[targetKey] = merge(result[targetKey], val);
} else if (isPlainObject(val)) {
result[targetKey] = merge({}, val);
} else if (isArray(val)) {
result[targetKey] = val.slice();
} else {
result[targetKey] = val;
}
};
for (let i = 0, l = arguments.length; i < l; i++) {
arguments[i] && forEach(arguments[i], assignValue);
}
return result;
}
/**
* Extends object a by mutably adding to it the properties of object b.
*
* @param {Object} a The object to be extended
* @param {Object} b The object to copy properties from
* @param {Object} thisArg The object to bind function to
*
* @param {Boolean} [allOwnKeys]
* @returns {Object} The resulting value of object a
*/
const extend = (a, b, thisArg, {allOwnKeys}= {}) => {
forEach(b, (val, key) => {
if (thisArg && isFunction(val)) {
a[key] = bind(val, thisArg);
} else {
a[key] = val;
}
}, {allOwnKeys});
return a;
};
/**
* Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
*
* @param {string} content with BOM
*
* @returns {string} content value without BOM
*/
const stripBOM = (content) => {
if (content.charCodeAt(0) === 0xFEFF) {
content = content.slice(1);
}
return content;
};
/**
* Inherit the prototype methods from one constructor into another
* @param {function} constructor
* @param {function} superConstructor
* @param {object} [props]
* @param {object} [descriptors]
*
* @returns {void}
*/
const inherits = (constructor, superConstructor, props, descriptors) => {
constructor.prototype = Object.create(superConstructor.prototype, descriptors);
constructor.prototype.constructor = constructor;
Object.defineProperty(constructor, 'super', {
value: superConstructor.prototype
});
props && Object.assign(constructor.prototype, props);
};
/**
* Resolve object with deep prototype chain to a flat object
* @param {Object} sourceObj source object
* @param {Object} [destObj]
* @param {Function|Boolean} [filter]
* @param {Function} [propFilter]
*
* @returns {Object}
*/
const toFlatObject = (sourceObj, destObj, filter, propFilter) => {
let props;
let i;
let prop;
const merged = {};
destObj = destObj || {};
// eslint-disable-next-line no-eq-null,eqeqeq
if (sourceObj == null) return destObj;
do {
props = Object.getOwnPropertyNames(sourceObj);
i = props.length;
while (i-- > 0) {
prop = props[i];
if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
destObj[prop] = sourceObj[prop];
merged[prop] = true;
}
}
sourceObj = filter !== false && getPrototypeOf(sourceObj);
} while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
return destObj;
};
/**
* Determines whether a string ends with the characters of a specified string
*
* @param {String} str
* @param {String} searchString
* @param {Number} [position= 0]
*
* @returns {boolean}
*/
const endsWith = (str, searchString, position) => {
str = String(str);
if (position === undefined || position > str.length) {
position = str.length;
}
position -= searchString.length;
const lastIndex = str.indexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
};
/**
* Returns new array from array like object or null if failed
*
* @param {*} [thing]
*
* @returns {?Array}
*/
const toArray = (thing) => {
if (!thing) return null;
if (isArray(thing)) return thing;
let i = thing.length;
if (!isNumber(i)) return null;
const arr = new Array(i);
while (i-- > 0) {
arr[i] = thing[i];
}
return arr;
};
/**
* Checking if the Uint8Array exists and if it does, it returns a function that checks if the
* thing passed in is an instance of Uint8Array
*
* @param {TypedArray}
*
* @returns {Array}
*/
// eslint-disable-next-line func-names
const isTypedArray = (TypedArray => {
// eslint-disable-next-line func-names
return thing => {
return TypedArray && thing instanceof TypedArray;
};
})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));
/**
* For each entry in the object, call the function with the key and value.
*
* @param {Object} obj - The object to iterate over.
* @param {Function} fn - The function to call for each entry.
*
* @returns {void}
*/
const forEachEntry = (obj, fn) => {
const generator = obj && obj[Symbol.iterator];
const iterator = generator.call(obj);
let result;
while ((result = iterator.next()) && !result.done) {
const pair = result.value;
fn.call(obj, pair[0], pair[1]);
}
};
/**
* It takes a regular expression and a string, and returns an array of all the matches
*
* @param {string} regExp - The regular expression to match against.
* @param {string} str - The string to search.
*
* @returns {Array}
*/
const matchAll = (regExp, str) => {
let matches;
const arr = [];
while ((matches = regExp.exec(str)) !== null) {
arr.push(matches);
}
return arr;
};
/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
const isHTMLForm = kindOfTest('HTMLFormElement');
const toCamelCase = str => {
return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,
function replacer(m, p1, p2) {
return p1.toUpperCase() + p2;
}
);
};
/* Creating a function that will check if an object has a property. */
const hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype);
/**
* Determine if a value is a RegExp object
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a RegExp object, otherwise false
*/
const isRegExp = kindOfTest('RegExp');
const reduceDescriptors = (obj, reducer) => {
const descriptors = Object.getOwnPropertyDescriptors(obj);
const reducedDescriptors = {};
forEach(descriptors, (descriptor, name) => {
let ret;
if ((ret = reducer(descriptor, name, obj)) !== false) {
reducedDescriptors[name] = ret || descriptor;
}
});
Object.defineProperties(obj, reducedDescriptors);
};
/**
* Makes all methods read-only
* @param {Object} obj
*/
const freezeMethods = (obj) => {
reduceDescriptors(obj, (descriptor, name) => {
// skip restricted props in strict mode
if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) {
return false;
}
const value = obj[name];
if (!isFunction(value)) return;
descriptor.enumerable = false;
if ('writable' in descriptor) {
descriptor.writable = false;
return;
}
if (!descriptor.set) {
descriptor.set = () => {
throw Error('Can not rewrite read-only method \'' + name + '\'');
};
}
});
};
const toObjectSet = (arrayOrString, delimiter) => {
const obj = {};
const define = (arr) => {
arr.forEach(value => {
obj[value] = true;
});
};
isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
return obj;
};
const noop = () => {};
const toFiniteNumber = (value, defaultValue) => {
return value != null && Number.isFinite(value = +value) ? value : defaultValue;
};
const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
const DIGIT = '0123456789';
const ALPHABET = {
DIGIT,
ALPHA,
ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
};
const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {
let str = '';
const {length} = alphabet;
while (size--) {
str += alphabet[Math.random() * length|0];
}
return str;
};
/**
* If the thing is a FormData object, return true, otherwise return false.
*
* @param {unknown} thing - The thing to check.
*
* @returns {boolean}
*/
function isSpecCompliantForm(thing) {
return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]);
}
const toJSONObject = (obj) => {
const stack = new Array(10);
const visit = (source, i) => {
if (isObject(source)) {
if (stack.indexOf(source) >= 0) {
return;
}
if(!('toJSON' in source)) {
stack[i] = source;
const target = isArray(source) ? [] : {};
forEach(source, (value, key) => {
const reducedValue = visit(value, i + 1);
!isUndefined(reducedValue) && (target[key] = reducedValue);
});
stack[i] = undefined;
return target;
}
}
return source;
};
return visit(obj, 0);
};
const isAsyncFn = kindOfTest('AsyncFunction');
const isThenable = (thing) =>
thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch);
// original code
// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34
const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
if (setImmediateSupported) {
return setImmediate;
}
return postMessageSupported ? ((token, callbacks) => {
_global.addEventListener("message", ({source, data}) => {
if (source === _global && data === token) {
callbacks.length && callbacks.shift()();
}
}, false);
return (cb) => {
callbacks.push(cb);
_global.postMessage(token, "*");
}
})(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);
})(
typeof setImmediate === 'function',
isFunction(_global.postMessage)
);
const asap = typeof queueMicrotask !== 'undefined' ?
queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate);
// *********************
var utils$1 = {
isArray,
isArrayBuffer,
isBuffer,
isFormData,
isArrayBufferView,
isString,
isNumber,
isBoolean,
isObject,
isPlainObject,
isReadableStream,
isRequest,
isResponse,
isHeaders,
isUndefined,
isDate,
isFile,
isBlob,
isRegExp,
isFunction,
isStream,
isURLSearchParams,
isTypedArray,
isFileList,
forEach,
merge,
extend,
trim,
stripBOM,
inherits,
toFlatObject,
kindOf,
kindOfTest,
endsWith,
toArray,
forEachEntry,
matchAll,
isHTMLForm,
hasOwnProperty,
hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection
reduceDescriptors,
freezeMethods,
toObjectSet,
toCamelCase,
noop,
toFiniteNumber,
findKey,
global: _global,
isContextDefined,
ALPHABET,
generateString,
isSpecCompliantForm,
toJSONObject,
isAsyncFn,
isThenable,
setImmediate: _setImmediate,
asap
};
/**
* Create an Error with the specified message, config, error code, request and response.
*
* @param {string} message The error message.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [config] The config.
* @param {Object} [request] The request.
* @param {Object} [response] The response.
*
* @returns {Error} The created error.
*/
function AxiosError(message, code, config, request, response) {
Error.call(this);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
this.stack = (new Error()).stack;
}
this.message = message;
this.name = 'AxiosError';
code && (this.code = code);
config && (this.config = config);
request && (this.request = request);
if (response) {
this.response = response;
this.status = response.status ? response.status : null;
}
}
utils$1.inherits(AxiosError, Error, {
toJSON: function toJSON() {
return {
// Standard
message: this.message,
name: this.name,
// Microsoft
description: this.description,
number: this.number,
// Mozilla
fileName: this.fileName,
lineNumber: this.lineNumber,
columnNumber: this.columnNumber,
stack: this.stack,
// Axios
config: utils$1.toJSONObject(this.config),
code: this.code,
status: this.status
};
}
});
const prototype$1 = AxiosError.prototype;
const descriptors = {};
[
'ERR_BAD_OPTION_VALUE',
'ERR_BAD_OPTION',
'ECONNABORTED',
'ETIMEDOUT',
'ERR_NETWORK',
'ERR_FR_TOO_MANY_REDIRECTS',
'ERR_DEPRECATED',
'ERR_BAD_RESPONSE',
'ERR_BAD_REQUEST',
'ERR_CANCELED',
'ERR_NOT_SUPPORT',
'ERR_INVALID_URL'
// eslint-disable-next-line func-names
].forEach(code => {
descriptors[code] = {value: code};
});
Object.defineProperties(AxiosError, descriptors);
Object.defineProperty(prototype$1, 'isAxiosError', {value: true});
// eslint-disable-next-line func-names
AxiosError.from = (error, code, config, request, response, customProps) => {
const axiosError = Object.create(prototype$1);
utils$1.toFlatObject(error, axiosError, function filter(obj) {
return obj !== Error.prototype;
}, prop => {
return prop !== 'isAxiosError';
});
AxiosError.call(axiosError, error.message, code, config, request, response);
axiosError.cause = error;
axiosError.name = error.name;
customProps && Object.assign(axiosError, customProps);
return axiosError;
};
// eslint-disable-next-line strict
var httpAdapter = null;
/**
* Determines if the given thing is a array or js object.
*
* @param {string} thing - The object or array to be visited.
*
* @returns {boolean}
*/
function isVisitable(thing) {
return utils$1.isPlainObject(thing) || utils$1.isArray(thing);
}
/**
* It removes the brackets from the end of a string
*
* @param {string} key - The key of the parameter.
*
* @returns {string} the key without the brackets.
*/
function removeBrackets(key) {
return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key;
}
/**
* It takes a path, a key, and a boolean, and returns a string
*
* @param {string} path - The path to the current key.
* @param {string} key - The key of the current object being iterated over.
* @param {string} dots - If true, the key will be rendered with dots instead of brackets.
*
* @returns {string} The path to the current key.
*/
function renderKey(path, key, dots) {
if (!path) return key;
return path.concat(key).map(function each(token, i) {
// eslint-disable-next-line no-param-reassign
token = removeBrackets(token);
return !dots && i ? '[' + token + ']' : token;
}).join(dots ? '.' : '');
}
/**
* If the array is an array and none of its elements are visitable, then it's a flat array.
*
* @param {Array} arr - The array to check
*
* @returns {boolean}
*/
function isFlatArray(arr) {
return utils$1.isArray(arr) && !arr.some(isVisitable);
}
const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) {
return /^is[A-Z]/.test(prop);
});
/**
* Convert a data object to FormData
*
* @param {Object} obj
* @param {?Object} [formData]
* @param {?Object} [options]
* @param {Function} [options.visitor]
* @param {Boolean} [options.metaTokens = true]
* @param {Boolean} [options.dots = false]
* @param {?Boolean} [options.indexes = false]
*
* @returns {Object}
**/
/**
* It converts an object into a FormData object
*
* @param {Object} obj - The object to convert to form data.
* @param {string} formData - The FormData object to append to.
* @param {Object} options
*
* @returns
*/
function toFormData(obj, formData, options) {
if (!utils$1.isObject(obj)) {
throw new TypeError('target must be an object');
}
// eslint-disable-next-line no-param-reassign
formData = formData || new (FormData)();
// eslint-disable-next-line no-param-reassign
options = utils$1.toFlatObject(options, {
metaTokens: true,
dots: false,
indexes: false
}, false, function defined(option, source) {
// eslint-disable-next-line no-eq-null,eqeqeq
return !utils$1.isUndefined(source[option]);
});
const metaTokens = options.metaTokens;
// eslint-disable-next-line no-use-before-define
const visitor = options.visitor || defaultVisitor;
const dots = options.dots;
const indexes = options.indexes;
const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
const useBlob = _Blob && utils$1.isSpecCompliantForm(formData);
if (!utils$1.isFunction(visitor)) {
throw new TypeError('visitor must be a function');
}
function convertValue(value) {
if (value === null) return '';
if (utils$1.isDate(value)) {
return value.toISOString();
}
if (!useBlob && utils$1.isBlob(value)) {
throw new AxiosError('Blob is not supported. Use a Buffer instead.');
}
if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) {
return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);
}
return value;
}
/**
* Default visitor.
*
* @param {*} value
* @param {String|Number} key
* @param {Array} path
* @this {FormData}
*
* @returns {boolean} return true to visit the each prop of the value recursively
*/
function defaultVisitor(value, key, path) {
let arr = value;
if (value && !path && typeof value === 'object') {
if (utils$1.endsWith(key, '{}')) {
// eslint-disable-next-line no-param-reassign
key = metaTokens ? key : key.slice(0, -2);
// eslint-disable-next-line no-param-reassign
value = JSON.stringify(value);
} else if (
(utils$1.isArray(value) && isFlatArray(value)) ||
((utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value))
)) {
// eslint-disable-next-line no-param-reassign
key = removeBrackets(key);
arr.forEach(function each(el, index) {
!(utils$1.isUndefined(el) || el === null) && formData.append(
// eslint-disable-next-line no-nested-ternary
indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'),
convertValue(el)
);
});
return false;
}
}
if (isVisitable(value)) {
return true;
}
formData.append(renderKey(path, key, dots), convertValue(value));
return false;
}
const stack = [];
const exposedHelpers = Object.assign(predicates, {
defaultVisitor,
convertValue,
isVisitable
});
function build(value, path) {
if (utils$1.isUndefined(value)) return;
if (stack.indexOf(value) !== -1) {
throw Error('Circular reference detected in ' + path.join('.'));
}
stack.push(value);
utils$1.forEach(value, function each(el, key) {
const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(
formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers
);
if (result === true) {
build(el, path ? path.concat(key) : [key]);
}
});
stack.pop();
}
if (!utils$1.isObject(obj)) {
throw new TypeError('data must be an object');
}
build(obj);
return formData;
}
/**
* It encodes a string by replacing all characters that are not in the unreserved set with
* their percent-encoded equivalents
*
* @param {string} str - The string to encode.
*
* @returns {string} The encoded string.
*/
function encode$1(str) {
const charMap = {
'!': '%21',
"'": '%27',
'(': '%28',
')': '%29',
'~': '%7E',
'%20': '+',
'%00': '\x00'
};
return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
return charMap[match];
});
}
/**
* It takes a params object and converts it to a FormData object
*
* @param {Object} params - The parameters to be converted to a FormData object.
* @param {Object} options - The options object passed to the Axios constructor.
*
* @returns {void}
*/
function AxiosURLSearchParams(params, options) {
this._pairs = [];
params && toFormData(params, this, options);
}
const prototype = AxiosURLSearchParams.prototype;
prototype.append = function append(name, value) {
this._pairs.push([name, value]);
};
prototype.toString = function toString(encoder) {
const _encode = encoder ? function(value) {
return encoder.call(this, value, encode$1);
} : encode$1;
return this._pairs.map(function each(pair) {
return _encode(pair[0]) + '=' + _encode(pair[1]);
}, '').join('&');
};
/**
* It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their
* URI encoded counterparts
*
* @param {string} val The value to be encoded.
*
* @returns {string} The encoded value.
*/
function encode(val) {
return encodeURIComponent(val).
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%20/g, '+').
replace(/%5B/gi, '[').
replace(/%5D/gi, ']');
}
/**
* Build a URL by appending params to the end
*
* @param {string} url The base of the url (e.g., http://www.google.com)
* @param {object} [params] The params to be appended
* @param {?object} options
*
* @returns {string} The formatted url
*/
function buildURL(url, params, options) {
/*eslint no-param-reassign:0*/
if (!params) {
return url;
}
const _encode = options && options.encode || encode;
const serializeFn = options && options.serialize;
let serializedParams;
if (serializeFn) {
serializedParams = serializeFn(params, options);
} else {
serializedParams = utils$1.isURLSearchParams(params) ?
params.toString() :
new AxiosURLSearchParams(params, options).toString(_encode);
}
if (serializedParams) {
const hashmarkIndex = url.indexOf("#");
if (hashmarkIndex !== -1) {
url = url.slice(0, hashmarkIndex);
}
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
}
return url;
}
class InterceptorManager {
constructor() {
this.handlers = [];
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
*
* @return {Number} An ID used to remove interceptor later
*/
use(fulfilled, rejected, options) {
this.handlers.push({
fulfilled,
rejected,
synchronous: options ? options.synchronous : false,
runWhen: options ? options.runWhen : null
});
return this.handlers.length - 1;
}
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*
* @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
*/
eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
}
/**
* Clear all interceptors from the stack
*
* @returns {void}
*/
clear() {
if (this.handlers) {
this.handlers = [];
}
}
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*
* @returns {void}
*/
forEach(fn) {
utils$1.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
}
});
}
}
var InterceptorManager$1 = InterceptorManager;
var transitionalDefaults = {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
};
var URLSearchParams$1 = typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;
var FormData$1 = typeof FormData !== 'undefined' ? FormData : null;
var Blob$1 = typeof Blob !== 'undefined' ? Blob : null;
var platform$1 = {
isBrowser: true,
classes: {
URLSearchParams: URLSearchParams$1,
FormData: FormData$1,
Blob: Blob$1
},
protocols: ['http', 'https', 'file', 'blob', 'url', 'data']
};
const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';
const _navigator = typeof navigator === 'object' && navigator || undefined;
/**
* Determine if we're running in a standard browser environment
*
* This allows axios to run in a web worker, and react-native.
* Both environments support XMLHttpRequest, but not fully standard globals.
*
* web workers:
* typeof window -> undefined
* typeof document -> undefined
*
* react-native:
* navigator.product -> 'ReactNative'
* nativescript
* navigator.product -> 'NativeScript' or 'NS'
*
* @returns {boolean}
*/
const hasStandardBrowserEnv = hasBrowserEnv &&
(!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0);
/**
* Determine if we're running in a standard browser webWorker environment
*
* Although the `isStandardBrowserEnv` method indicates that
* `allows axios to run in a web worker`, the WebWorker will still be
* filtered out due to its judgment standard
* `typeof window !== 'undefined' && typeof document !== 'undefined'`.
* This leads to a problem when axios post `FormData` in webWorker
*/
const hasStandardBrowserWebWorkerEnv = (() => {
return (
typeof WorkerGlobalScope !== 'undefined' &&
// eslint-disable-next-line no-undef
self instanceof WorkerGlobalScope &&
typeof self.importScripts === 'function'
);
})();
const origin = hasBrowserEnv && window.location.href || 'http://localhost';
var utils = /*#__PURE__*/Object.freeze({
__proto__: null,
hasBrowserEnv: hasBrowserEnv,
hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv,
hasStandardBrowserEnv: hasStandardBrowserEnv,
navigator: _navigator,
origin: origin
});
var platform = {
...utils,
...platform$1
};
function toURLEncodedForm(data, options) {
return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({
visitor: function(value, key, path, helpers) {
if (platform.isNode && utils$1.isBuffer(value)) {
this.append(key, value.toString('base64'));
return false;
}
return helpers.defaultVisitor.apply(this, arguments);
}
}, options));
}
/**
* It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
*
* @param {string} name - The name of the property to get.
*
* @returns An array of strings.
*/
function parsePropPath(name) {
// foo[x][y][z]
// foo.x.y.z
// foo-x-y-z
// foo x y z
return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map(match => {
return match[0] === '[]' ? '' : match[1] || match[0];
});
}
/**
* Convert an array to an object.
*
* @param {Array} arr - The array to convert to an object.
*
* @returns An object with the same keys and values as the array.
*/
function arrayToObject(arr) {
const obj = {};
const keys = Object.keys(arr);
let i;
const len = keys.length;
let key;
for (i = 0; i < len; i++) {
key = keys[i];
obj[key] = arr[key];
}
return obj;
}
/**
* It takes a FormData object and returns a JavaScript object
*
* @param {string} formData The FormData object to convert to JSON.
*
* @returns {Object | null} The converted object.
*/
function formDataToJSON(formData) {
function buildPath(path, value, target, index) {
let name = path[index++];
if (name === '__proto__') return true;
const isNumericKey = Number.isFinite(+name);
const isLast = index >= path.length;
name = !name && utils$1.isArray(target) ? target.length : name;
if (isLast) {
if (utils$1.hasOwnProp(target, name)) {
target[name] = [target[name], value];
} else {
target[name] = value;
}
return !isNumericKey;
}
if (!target[name] || !utils$1.isObject(target[name])) {
target[name] = [];
}
const result = buildPath(path, value, target[name], index);
if (result && utils$1.isArray(target[name])) {
target[name] = arrayToObject(target[name]);
}
return !isNumericKey;
}
if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
const obj = {};
utils$1.forEachEntry(formData, (name, value) => {
buildPath(parsePropPath(name), value, obj, 0);
});
return obj;
}
return null;
}
/**
* It takes a string, tries to parse it, and if it fails, it returns the stringified version
* of the input
*
* @param {any} rawValue - The value to be stringified.
* @param {Function} parser - A function that parses a string into a JavaScript object.
* @param {Function} encoder - A function that takes a value and returns a string.
*
* @returns {string} A stringified version of the rawValue.
*/
function stringifySafely(rawValue, parser, encoder) {
if (utils$1.isString(rawValue)) {
try {
(parser || JSON.parse)(rawValue);
return utils$1.trim(rawValue);
} catch (e) {
if (e.name !== 'SyntaxError') {
throw e;
}
}
}
return (encoder || JSON.stringify)(rawValue);
}
const defaults = {
transitional: transitionalDefaults,
adapter: ['xhr', 'http', 'fetch'],
transformRequest: [function transformRequest(data, headers) {
const contentType = headers.getContentType() || '';
const hasJSONContentType = contentType.indexOf('application/json') > -1;
const isObjectPayload = utils$1.isObject(data);
if (isObjectPayload && utils$1.isHTMLForm(data)) {
data = new FormData(data);
}
const isFormData = utils$1.isFormData(data);
if (isFormData) {
return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
}
if (utils$1.isArrayBuffer(data) ||
utils$1.isBuffer(data) ||
utils$1.isStream(data) ||
utils$1.isFile(data) ||
utils$1.isBlob(data) ||
utils$1.isReadableStream(data)
) {
return data;
}
if (utils$1.isArrayBufferView(data)) {
return data.buffer;
}
if (utils$1.isURLSearchParams(data)) {
headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
return data.toString();
}
let isFileList;
if (isObjectPayload) {
if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
return toURLEncodedForm(data, this.formSerializer).toString();
}
if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
const _FormData = this.env && this.env.FormData;
return toFormData(
isFileList ? {'files[]': data} : data,
_FormData && new _FormData(),
this.formSerializer
);
}
}
if (isObjectPayload || hasJSONContentType ) {
headers.setContentType('application/json', false);
return stringifySafely(data);
}
return data;
}],
transformResponse: [function transformResponse(data) {
const transitional = this.transitional || defaults.transitional;
const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
const JSONRequested = this.responseType === 'json';
if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
return data;
}
if (data && utils$1.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {
const silentJSONParsing = transitional && transitional.silentJSONParsing;
const strictJSONParsing = !silentJSONParsing && JSONRequested;
try {
return JSON.parse(data);
} catch (e) {
if (strictJSONParsing) {
if (e.name === 'SyntaxError') {
throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);
}
throw e;
}
}
}
return data;
}],
/**
* A timeout in milliseconds to abort a request. If set to 0 (default) a
* timeout is not created.
*/
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
env: {
FormData: platform.classes.FormData,
Blob: platform.classes.Blob
},
validateStatus: function validateStatus(status) {
return status >= 200 && status < 300;
},
headers: {
common: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': undefined
}
}
};
utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => {
defaults.headers[method] = {};
});
var defaults$1 = defaults;
// RawAxiosHeaders whose duplicates are ignored by node
// c.f. https://nodejs.org/api/http.html#http_message_headers
const ignoreDuplicateOf = utils$1.toObjectSet([
'age', 'authorization', 'content-length', 'content-type', 'etag',
'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
'last-modified', 'location', 'max-forwards', 'proxy-authorization',
'referer', 'retry-after', 'user-agent'
]);
/**
* Parse headers into an object
*
* ```
* Date: Wed, 27 Aug 2014 08:58:49 GMT
* Content-Type: application/json
* Connection: keep-alive
* Transfer-Encoding: chunked
* ```
*
* @param {String} rawHeaders Headers needing to be parsed
*
* @returns {Object} Headers parsed into an object
*/
var parseHeaders = rawHeaders => {
const parsed = {};
let key;
let val;
let i;
rawHeaders && rawHeaders.split('\n').forEach(function parser(line) {
i = line.indexOf(':');
key = line.substring(0, i).trim().toLowerCase();
val = line.substring(i + 1).trim();
if (!key || (parsed[key] && ignoreDuplicateOf[key])) {
return;
}
if (key === 'set-cookie') {
if (parsed[key]) {
parsed[key].push(val);
} else {
parsed[key] = [val];
}
} else {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
});
return parsed;
};
const $internals = Symbol('internals');
function normalizeHeader(header) {
return header && String(header).trim().toLowerCase();
}
function normalizeValue(value) {
if (value === false || value == null) {
return value;
}
return utils$1.isArray(value) ? value.map(normalizeValue) : String(value);
}
function parseTokens(str) {
const tokens = Object.create(null);
const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
let match;
while ((match = tokensRE.exec(str))) {
tokens[match[1]] = match[2];
}
return tokens;
}
const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {
if (utils$1.isFunction(filter)) {
return filter.call(this, value, header);
}
if (isHeaderNameFilter) {
value = header;
}
if (!utils$1.isString(value)) return;
if (utils$1.isString(filter)) {
return value.indexOf(filter) !== -1;
}
if (utils$1.isRegExp(filter)) {
return filter.test(value);
}
}
function formatHeader(header) {
return header.trim()
.toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
return char.toUpperCase() + str;
});
}
function buildAccessors(obj, header) {
const accessorName = utils$1.toCamelCase(' ' + header);
['get', 'set', 'has'].forEach(methodName => {
Object.defineProperty(obj, methodName + accessorName, {
value: function(arg1, arg2, arg3) {
return this[methodName].call(this, header, arg1, arg2, arg3);
},
configurable: true
});
});
}
class AxiosHeaders {
constructor(headers) {
headers && this.set(headers);
}
set(header, valueOrRewrite, rewrite) {
const self = this;
function setHeader(_value, _header, _rewrite) {
const lHeader = normalizeHeader(_header);
if (!lHeader) {
throw new Error('header name must be a non-empty string');
}
const key = utils$1.findKey(self, lHeader);
if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {
self[key || _header] = normalizeValue(_value);
}
}
const setHeaders = (headers, _rewrite) =>
utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
setHeaders(header, valueOrRewrite);
} else if(utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
setHeaders(parseHeaders(header), valueOrRewrite);
} else if (utils$1.isHeaders(header)) {
for (const [key, value] of header.entries()) {
setHeader(value, key, rewrite);
}
} else {
header != null && setHeader(valueOrRewrite, header, rewrite);
}
return this;
}
get(header, parser) {
header = normalizeHeader(header);
if (header) {
const key = utils$1.findKey(this, header);
if (key) {
const value = this[key];
if (!parser) {
return value;
}
if (parser === true) {
return parseTokens(value);
}
if (utils$1.isFunction(parser)) {
return parser.call(this, value, key);
}
if (utils$1.isRegExp(parser)) {
return parser.exec(value);
}
throw new TypeError('parser must be boolean|regexp|function');
}
}
}
has(header, matcher) {
header = normalizeHeader(header);
if (header) {
const key = utils$1.findKey(this, header);
return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
}
return false;
}
delete(header, matcher) {
const self = this;
let deleted = false;
function deleteHeader(_header) {
_header = normalizeHeader(_header);
if (_header) {
const key = utils$1.findKey(self, _header);
if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
delete self[key];
deleted = true;
}
}
}
if (utils$1.isArray(header)) {
header.forEach(deleteHeader);
} else {
deleteHeader(header);
}
return deleted;
}
clear(matcher) {
const keys = Object.keys(this);
let i = keys.length;
let deleted = false;
while (i--) {
const key = keys[i];
if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
delete this[key];
deleted = true;
}
}
return deleted;
}
normalize(format) {
const self = this;
const headers = {};
utils$1.forEach(this, (value, header) => {
const key = utils$1.findKey(headers, header);
if (key) {
self[key] = normalizeValue(value);
delete self[header];
return;
}
const normalized = format ? formatHeader(header) : String(header).trim();
if (normalized !== header) {
delete self[header];
}
self[normalized] = normalizeValue(value);
headers[normalized] = true;
});
return this;
}
concat(...targets) {
return this.constructor.concat(this, ...targets);
}
toJSON(asStrings) {
const obj = Object.create(null);
utils$1.forEach(this, (value, header) => {
value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value);
});
return obj;
}
[Symbol.iterator]() {
return Object.entries(this.toJSON())[Symbol.iterator]();
}
toString() {
return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n');
}
get [Symbol.toStringTag]() {
return 'AxiosHeaders';
}
static from(thing) {
return thing instanceof this ? thing : new this(thing);
}
static concat(first, ...targets) {
const computed = new this(first);
targets.forEach((target) => computed.set(target));
return computed;
}
static accessor(header) {
const internals = this[$internals] = (this[$internals] = {
accessors: {}
});
const accessors = internals.accessors;
const prototype = this.prototype;
function defineAccessor(_header) {
const lHeader = normalizeHeader(_header);
if (!accessors[lHeader]) {
buildAccessors(prototype, _header);
accessors[lHeader] = true;
}
}
utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
return this;
}
}
AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);
// reserved names hotfix
utils$1.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => {
let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`
return {
get: () => value,
set(headerValue) {
this[mapped] = headerValue;
}
}
});
utils$1.freezeMethods(AxiosHeaders);
var AxiosHeaders$1 = AxiosHeaders;
/**
* Transform the data for a request or a response
*
* @param {Array|Function} fns A single function or Array of functions
* @param {?Object} response The response object
*
* @returns {*} The resulting transformed data
*/
function transformData(fns, response) {
const config = this || defaults$1;
const context = response || config;
const headers = AxiosHeaders$1.from(context.headers);
let data = context.data;
utils$1.forEach(fns, function transform(fn) {
data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
});
headers.normalize();
return data;
}
function isCancel(value) {
return !!(value && value.__CANCEL__);
}
/**
* A `CanceledError` is an object that is thrown when an operation is canceled.
*
* @param {string=} message The message.
* @param {Object=} config The config.
* @param {Object=} request The request.
*
* @returns {CanceledError} The created error.
*/
function CanceledError(message, config, request) {
// eslint-disable-next-line no-eq-null,eqeqeq
AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);
this.name = 'CanceledError';
}
utils$1.inherits(CanceledError, AxiosError, {
__CANCEL__: true
});
/**
* Resolve or reject a Promise based on response status.
*
* @param {Function} resolve A function that resolves the promise.
* @param {Function} reject A function that rejects the promise.
* @param {object} response The response.
*
* @returns {object} The response.
*/
function settle(resolve, reject, response) {
const validateStatus = response.config.validateStatus;
if (!response.status || !validateStatus || validateStatus(response.status)) {
resolve(response);
} else {
reject(new AxiosError(
'Request failed with status code ' + response.status,
[AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
response.config,
response.request,
response
));
}
}
function parseProtocol(url) {
const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
return match && match[1] || '';
}
/**
* Calculate data maxRate
* @param {Number} [samplesCount= 10]
* @param {Number} [min= 1000]
* @returns {Function}
*/
function speedometer(samplesCount, min) {
samplesCount = samplesCount || 10;
const bytes = new Array(samplesCount);
const timestamps = new Array(samplesCount);
let head = 0;
let tail = 0;
let firstSampleTS;
min = min !== undefined ? min : 1000;
return function push(chunkLength) {
const now = Date.now();
const startedAt = timestamps[tail];
if (!firstSampleTS) {
firstSampleTS = now;
}
bytes[head] = chunkLength;
timestamps[head] = now;
let i = tail;
let bytesCount = 0;
while (i !== head) {
bytesCount += bytes[i++];
i = i % samplesCount;
}
head = (head + 1) % samplesCount;
if (head === tail) {
tail = (tail + 1) % samplesCount;
}
if (now - firstSampleTS < min) {
return;
}
const passed = startedAt && now - startedAt;
return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
};
}
/**
* Throttle decorator
* @param {Function} fn
* @param {Number} freq
* @return {Function}
*/
function throttle(fn, freq) {
let timestamp = 0;
let threshold = 1000 / freq;
let lastArgs;
let timer;
const invoke = (args, now = Date.now()) => {
timestamp = now;
lastArgs = null;
if (timer) {
clearTimeout(timer);
timer = null;
}
fn.apply(null, args);
};
const throttled = (...args) => {
const now = Date.now();
const passed = now - timestamp;
if ( passed >= threshold) {
invoke(args, now);
} else {
lastArgs = args;
if (!timer) {
timer = setTimeout(() => {
timer = null;
invoke(lastArgs);
}, threshold - passed);
}
}
};
const flush = () => lastArgs && invoke(lastArgs);
return [throttled, flush];
}
const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
let bytesNotified = 0;
const _speedometer = speedometer(50, 250);
return throttle(e => {
const loaded = e.loaded;
const total = e.lengthComputable ? e.total : undefined;
const progressBytes = loaded - bytesNotified;
const rate = _speedometer(progressBytes);
const inRange = loaded <= total;
bytesNotified = loaded;
const data = {
loaded,
total,
progress: total ? (loaded / total) : undefined,
bytes: progressBytes,
rate: rate ? rate : undefined,
estimated: rate && total && inRange ? (total - loaded) / rate : undefined,
event: e,
lengthComputable: total != null,
[isDownloadStream ? 'download' : 'upload']: true
};
listener(data);
}, freq);
};
const progressEventDecorator = (total, throttled) => {
const lengthComputable = total != null;
return [(loaded) => throttled[0]({
lengthComputable,
total,
loaded
}), throttled[1]];
};
const asyncDecorator = (fn) => (...args) => utils$1.asap(() => fn(...args));
var isURLSameOrigin = platform.hasStandardBrowserEnv ?
// Standard browser envs have full support of the APIs needed to test
// whether the request URL is of the same origin as current location.
(function standardBrowserEnv() {
const msie = platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent);
const urlParsingNode = document.createElement('a');
let originURL;
/**
* Parse a URL to discover its components
*
* @param {String} url The URL to be parsed
* @returns {Object}
*/
function resolveURL(url) {
let href = url;
if (msie) {
// IE needs attribute set twice to normalize properties
urlParsingNode.setAttribute('href', href);
href = urlParsingNode.href;
}
urlParsingNode.setAttribute('href', href);
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
return {
href: urlParsingNode.href,
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
host: urlParsingNode.host,
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
hostname: urlParsingNode.hostname,
port: urlParsingNode.port,
pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
urlParsingNode.pathname :
'/' + urlParsingNode.pathname
};
}
originURL = resolveURL(window.location.href);
/**
* Determine if a URL shares the same origin as the current location
*
* @param {String} requestURL The URL to test
* @returns {boolean} True if URL shares the same origin, otherwise false
*/
return function isURLSameOrigin(requestURL) {
const parsed = (utils$1.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
return (parsed.protocol === originURL.protocol &&
parsed.host === originURL.host);
};
})() :
// Non standard browser envs (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return function isURLSameOrigin() {
return true;
};
})();
var cookies = platform.hasStandardBrowserEnv ?
// Standard browser envs support document.cookie
{
write(name, value, expires, path, domain, secure) {
const cookie = [name + '=' + encodeURIComponent(value)];
utils$1.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString());
utils$1.isString(path) && cookie.push('path=' + path);
utils$1.isString(domain) && cookie.push('domain=' + domain);
secure === true && cookie.push('secure');
document.cookie = cookie.join('; ');
},
read(name) {
const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
return (match ? decodeURIComponent(match[3]) : null);
},
remove(name) {
this.write(name, '', Date.now() - 86400000);
}
}
:
// Non-standard browser env (web workers, react-native) lack needed support.
{
write() {},
read() {
return null;
},
remove() {}
};
/**
* Determines whether the specified URL is absolute
*
* @param {string} url The URL to test
*
* @returns {boolean} True if the specified URL is absolute, otherwise false
*/
function isAbsoluteURL(url) {
// A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL).
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
// by any combination of letters, digits, plus, period, or hyphen.
return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
}
/**
* Creates a new URL by combining the specified URLs
*
* @param {string} baseURL The base URL
* @param {string} relativeURL The relative URL
*
* @returns {string} The combined URL
*/
function combineURLs(baseURL, relativeURL) {
return relativeURL
? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '')
: baseURL;
}
/**
* Creates a new URL by combining the baseURL with the requestedURL,
* only when the requestedURL is not already an absolute URL.
* If the requestURL is absolute, this function returns the requestedURL untouched.
*
* @param {string} baseURL The base URL
* @param {string} requestedURL Absolute or relative URL to combine
*
* @returns {string} The combined full path
*/
function buildFullPath(baseURL, requestedURL) {
if (baseURL && !isAbsoluteURL(requestedURL)) {
return combineURLs(baseURL, requestedURL);
}
return requestedURL;
}
const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing;
/**
* Config-specific merge-function which creates a new config-object
* by merging two configuration objects together.
*
* @param {Object} config1
* @param {Object} config2
*
* @returns {Object} New object resulting from merging config2 to config1
*/
function mergeConfig(config1, config2) {
// eslint-disable-next-line no-param-reassign
config2 = config2 || {};
const config = {};
function getMergedValue(target, source, caseless) {
if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) {
return utils$1.merge.call({caseless}, target, source);
} else if (utils$1.isPlainObject(source)) {
return utils$1.merge({}, source);
} else if (utils$1.isArray(source)) {
return source.slice();
}
return source;
}
// eslint-disable-next-line consistent-return
function mergeDeepProperties(a, b, caseless) {
if (!utils$1.isUndefined(b)) {
return getMergedValue(a, b, caseless);
} else if (!utils$1.isUndefined(a)) {
return getMergedValue(undefined, a, caseless);
}
}
// eslint-disable-next-line consistent-return
function valueFromConfig2(a, b) {
if (!utils$1.isUndefined(b)) {
return getMergedValue(undefined, b);
}
}
// eslint-disable-next-line consistent-return
function defaultToConfig2(a, b) {
if (!utils$1.isUndefined(b)) {
return getMergedValue(undefined, b);
} else if (!utils$1.isUndefined(a)) {
return getMergedValue(undefined, a);
}
}
// eslint-disable-next-line consistent-return
function mergeDirectKeys(a, b, prop) {
if (prop in config2) {
return getMergedValue(a, b);
} else if (prop in config1) {
return getMergedValue(undefined, a);
}
}
const mergeMap = {
url: valueFromConfig2,
method: valueFromConfig2,
data: valueFromConfig2,
baseURL: defaultToConfig2,
transformRequest: defaultToConfig2,
transformResponse: defaultToConfig2,
paramsSerializer: defaultToConfig2,
timeout: defaultToConfig2,
timeoutMessage: defaultToConfig2,
withCredentials: defaultToConfig2,
withXSRFToken: defaultToConfig2,
adapter: defaultToConfig2,
responseType: defaultToConfig2,
xsrfCookieName: defaultToConfig2,
xsrfHeaderName: defaultToConfig2,
onUploadProgress: defaultToConfig2,
onDownloadProgress: defaultToConfig2,
decompress: defaultToConfig2,
maxContentLength: defaultToConfig2,
maxBodyLength: defaultToConfig2,
beforeRedirect: defaultToConfig2,
transport: defaultToConfig2,
httpAgent: defaultToConfig2,
httpsAgent: defaultToConfig2,
cancelToken: defaultToConfig2,
socketPath: defaultToConfig2,
responseEncoding: defaultToConfig2,
validateStatus: mergeDirectKeys,
headers: (a, b) => mergeDeepProperties(headersToObject(a), headersToObject(b), true)
};
utils$1.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) {
const merge = mergeMap[prop] || mergeDeepProperties;
const configValue = merge(config1[prop], config2[prop], prop);
(utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
});
return config;
}
var resolveConfig = (config) => {
const newConfig = mergeConfig({}, config);
let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig;
newConfig.headers = headers = AxiosHeaders$1.from(headers);
newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer);
// HTTP basic authentication
if (auth) {
headers.set('Authorization', 'Basic ' +
btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : ''))
);
}
let contentType;
if (utils$1.isFormData(data)) {
if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
headers.setContentType(undefined); // Let the browser set it
} else if ((contentType = headers.getContentType()) !== false) {
// fix semicolon duplication issue for ReactNative FormData implementation
const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : [];
headers.setContentType([type || 'multipart/form-data', ...tokens].join('; '));
}
}
// Add xsrf header
// This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native.
if (platform.hasStandardBrowserEnv) {
withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));
if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) {
// Add xsrf header
const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
if (xsrfValue) {
headers.set(xsrfHeaderName, xsrfValue);
}
}
}
return newConfig;
};
const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';
var xhrAdapter = isXHRAdapterSupported && function (config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
const _config = resolveConfig(config);
let requestData = _config.data;
const requestHeaders = AxiosHeaders$1.from(_config.headers).normalize();
let {responseType, onUploadProgress, onDownloadProgress} = _config;
let onCanceled;
let uploadThrottled, downloadThrottled;
let flushUpload, flushDownload;
function done() {
flushUpload && flushUpload(); // flush events
flushDownload && flushDownload(); // flush events
_config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
_config.signal && _config.signal.removeEventListener('abort', onCanceled);
}
let request = new XMLHttpRequest();
request.open(_config.method.toUpperCase(), _config.url, true);
// Set the request timeout in MS
request.timeout = _config.timeout;
function onloadend() {
if (!request) {
return;
}
// Prepare the response
const responseHeaders = AxiosHeaders$1.from(
'getAllResponseHeaders' in request && request.getAllResponseHeaders()
);
const responseData = !responseType || responseType === 'text' || responseType === 'json' ?
request.responseText : request.response;
const response = {
data: responseData,
status: request.status,
statusText: request.statusText,
headers: responseHeaders,
config,
request
};
settle(function _resolve(value) {
resolve(value);
done();
}, function _reject(err) {
reject(err);
done();
}, response);
// Clean up request
request = null;
}
if ('onloadend' in request) {
// Use onloadend if available
request.onloadend = onloadend;
} else {
// Listen for ready state to emulate onloadend
request.onreadystatechange = function handleLoad() {
if (!request || request.readyState !== 4) {
return;
}
// The request errored out and we didn't get a response, this will be
// handled by onerror instead
// With one exception: request that using file: protocol, most browsers
// will return status as 0 even though it's a successful request
if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
return;
}
// readystate handler is calling before onerror or ontimeout handlers,
// so we should call onloadend on the next 'tick'
setTimeout(onloadend);
};
}
// Handle browser request cancellation (as opposed to a manual cancellation)
request.onabort = function handleAbort() {
if (!request) {
return;
}
reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
// Clean up request
request = null;
};
// Handle low level network errors
request.onerror = function handleError() {
// Real errors are hidden from us by the browser
// onerror should only fire if it's a network error
reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request));
// Clean up request
request = null;
};
// Handle timeout
request.ontimeout = function handleTimeout() {
let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';
const transitional = _config.transitional || transitionalDefaults;
if (_config.timeoutErrorMessage) {
timeoutErrorMessage = _config.timeoutErrorMessage;
}
reject(new AxiosError(
timeoutErrorMessage,
transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
config,
request));
// Clean up request
request = null;
};
// Remove Content-Type if data is undefined
requestData === undefined && requestHeaders.setContentType(null);
// Add headers to the request
if ('setRequestHeader' in request) {
utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
request.setRequestHeader(key, val);
});
}
// Add withCredentials to request if needed
if (!utils$1.isUndefined(_config.withCredentials)) {
request.withCredentials = !!_config.withCredentials;
}
// Add responseType to request if needed
if (responseType && responseType !== 'json') {
request.responseType = _config.responseType;
}
// Handle progress if needed
if (onDownloadProgress) {
([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true));
request.addEventListener('progress', downloadThrottled);
}
// Not all browsers support upload events
if (onUploadProgress && request.upload) {
([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress));
request.upload.addEventListener('progress', uploadThrottled);
request.upload.addEventListener('loadend', flushUpload);
}
if (_config.cancelToken || _config.signal) {
// Handle cancellation
// eslint-disable-next-line func-names
onCanceled = cancel => {
if (!request) {
return;
}
reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);
request.abort();
request = null;
};
_config.cancelToken && _config.cancelToken.subscribe(onCanceled);
if (_config.signal) {
_config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled);
}
}
const protocol = parseProtocol(_config.url);
if (protocol && platform.protocols.indexOf(protocol) === -1) {
reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));
return;
}
// Send the request
request.send(requestData || null);
});
};
const composeSignals = (signals, timeout) => {
const {length} = (signals = signals ? signals.filter(Boolean) : []);
if (timeout || length) {
let controller = new AbortController();
let aborted;
const onabort = function (reason) {
if (!aborted) {
aborted = true;
unsubscribe();
const err = reason instanceof Error ? reason : this.reason;
controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));
}
};
let timer = timeout && setTimeout(() => {
timer = null;
onabort(new AxiosError(`timeout ${timeout} of ms exceeded`, AxiosError.ETIMEDOUT));
}, timeout);
const unsubscribe = () => {
if (signals) {
timer && clearTimeout(timer);
timer = null;
signals.forEach(signal => {
signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort);
});
signals = null;
}
};
signals.forEach((signal) => signal.addEventListener('abort', onabort));
const {signal} = controller;
signal.unsubscribe = () => utils$1.asap(unsubscribe);
return signal;
}
};
var composeSignals$1 = composeSignals;
const streamChunk = function* (chunk, chunkSize) {
let len = chunk.byteLength;
if (!chunkSize || len < chunkSize) {
yield chunk;
return;
}
let pos = 0;
let end;
while (pos < len) {
end = pos + chunkSize;
yield chunk.slice(pos, end);
pos = end;
}
};
const readBytes = async function* (iterable, chunkSize) {
for await (const chunk of readStream(iterable)) {
yield* streamChunk(chunk, chunkSize);
}
};
const readStream = async function* (stream) {
if (stream[Symbol.asyncIterator]) {
yield* stream;
return;
}
const reader = stream.getReader();
try {
for (;;) {
const {done, value} = await reader.read();
if (done) {
break;
}
yield value;
}
} finally {
await reader.cancel();
}
};
const trackStream = (stream, chunkSize, onProgress, onFinish) => {
const iterator = readBytes(stream, chunkSize);
let bytes = 0;
let done;
let _onFinish = (e) => {
if (!done) {
done = true;
onFinish && onFinish(e);
}
};
return new ReadableStream({
async pull(controller) {
try {
const {done, value} = await iterator.next();
if (done) {
_onFinish();
controller.close();
return;
}
let len = value.byteLength;
if (onProgress) {
let loadedBytes = bytes += len;
onProgress(loadedBytes);
}
controller.enqueue(new Uint8Array(value));
} catch (err) {
_onFinish(err);
throw err;
}
},
cancel(reason) {
_onFinish(reason);
return iterator.return();
}
}, {
highWaterMark: 2
})
};
const isFetchSupported = typeof fetch === 'function' && typeof Request === 'function' && typeof Response === 'function';
const isReadableStreamSupported = isFetchSupported && typeof ReadableStream === 'function';
// used only inside the fetch adapter
const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ?
((encoder) => (str) => encoder.encode(str))(new TextEncoder()) :
async (str) => new Uint8Array(await new Response(str).arrayBuffer())
);
const test = (fn, ...args) => {
try {
return !!fn(...args);
} catch (e) {
return false
}
};
const supportsRequestStream = isReadableStreamSupported && test(() => {
let duplexAccessed = false;
const hasContentType = new Request(platform.origin, {
body: new ReadableStream(),
method: 'POST',
get duplex() {
duplexAccessed = true;
return 'half';
},
}).headers.has('Content-Type');
return duplexAccessed && !hasContentType;
});
const DEFAULT_CHUNK_SIZE = 64 * 1024;
const supportsResponseStream = isReadableStreamSupported &&
test(() => utils$1.isReadableStream(new Response('').body));
const resolvers = {
stream: supportsResponseStream && ((res) => res.body)
};
isFetchSupported && (((res) => {
['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {
!resolvers[type] && (resolvers[type] = utils$1.isFunction(res[type]) ? (res) => res[type]() :
(_, config) => {
throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config);
});
});
})(new Response));
const getBodyLength = async (body) => {
if (body == null) {
return 0;
}
if(utils$1.isBlob(body)) {
return body.size;
}
if(utils$1.isSpecCompliantForm(body)) {
const _request = new Request(platform.origin, {
method: 'POST',
body,
});
return (await _request.arrayBuffer()).byteLength;
}
if(utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) {
return body.byteLength;
}
if(utils$1.isURLSearchParams(body)) {
body = body + '';
}
if(utils$1.isString(body)) {
return (await encodeText(body)).byteLength;
}
};
const resolveBodyLength = async (headers, body) => {
const length = utils$1.toFiniteNumber(headers.getContentLength());
return length == null ? getBodyLength(body) : length;
};
var fetchAdapter = isFetchSupported && (async (config) => {
let {
url,
method,
data,
signal,
cancelToken,
timeout,
onDownloadProgress,
onUploadProgress,
responseType,
headers,
withCredentials = 'same-origin',
fetchOptions
} = resolveConfig(config);
responseType = responseType ? (responseType + '').toLowerCase() : 'text';
let composedSignal = composeSignals$1([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
let request;
const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
composedSignal.unsubscribe();
});
let requestContentLength;
try {
if (
onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' &&
(requestContentLength = await resolveBodyLength(headers, data)) !== 0
) {
let _request = new Request(url, {
method: 'POST',
body: data,
duplex: "half"
});
let contentTypeHeader;
if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {
headers.setContentType(contentTypeHeader);
}
if (_request.body) {
const [onProgress, flush] = progressEventDecorator(
requestContentLength,
progressEventReducer(asyncDecorator(onUploadProgress))
);
data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);
}
}
if (!utils$1.isString(withCredentials)) {
withCredentials = withCredentials ? 'include' : 'omit';
}
// Cloudflare Workers throws when credentials are defined
// see https://github.com/cloudflare/workerd/issues/902
const isCredentialsSupported = "credentials" in Request.prototype;
request = new Request(url, {
...fetchOptions,
signal: composedSignal,
method: method.toUpperCase(),
headers: headers.normalize().toJSON(),
body: data,
duplex: "half",
credentials: isCredentialsSupported ? withCredentials : undefined
});
let response = await fetch(request);
const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');
if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) {
const options = {};
['status', 'statusText', 'headers'].forEach(prop => {
options[prop] = response[prop];
});
const responseContentLength = utils$1.toFiniteNumber(response.headers.get('content-length'));
const [onProgress, flush] = onDownloadProgress && progressEventDecorator(
responseContentLength,
progressEventReducer(asyncDecorator(onDownloadProgress), true)
) || [];
response = new Response(
trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
flush && flush();
unsubscribe && unsubscribe();
}),
options
);
}
responseType = responseType || 'text';
let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config);
!isStreamResponse && unsubscribe && unsubscribe();
return await new Promise((resolve, reject) => {
settle(resolve, reject, {
data: responseData,
headers: AxiosHeaders$1.from(response.headers),
status: response.status,
statusText: response.statusText,
config,
request
});
})
} catch (err) {
unsubscribe && unsubscribe();
if (err && err.name === 'TypeError' && /fetch/i.test(err.message)) {
throw Object.assign(
new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request),
{
cause: err.cause || err
}
)
}
throw AxiosError.from(err, err && err.code, config, request);
}
});
const knownAdapters = {
http: httpAdapter,
xhr: xhrAdapter,
fetch: fetchAdapter
};
utils$1.forEach(knownAdapters, (fn, value) => {
if (fn) {
try {
Object.defineProperty(fn, 'name', {value});
} catch (e) {
// eslint-disable-next-line no-empty
}
Object.defineProperty(fn, 'adapterName', {value});
}
});
const renderReason = (reason) => `- ${reason}`;
const isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false;
var adapters = {
getAdapter: (adapters) => {
adapters = utils$1.isArray(adapters) ? adapters : [adapters];
const {length} = adapters;
let nameOrAdapter;
let adapter;
const rejectedReasons = {};
for (let i = 0; i < length; i++) {
nameOrAdapter = adapters[i];
let id;
adapter = nameOrAdapter;
if (!isResolvedHandle(nameOrAdapter)) {
adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
if (adapter === undefined) {
throw new AxiosError(`Unknown adapter '${id}'`);
}
}
if (adapter) {
break;
}
rejectedReasons[id || '#' + i] = adapter;
}
if (!adapter) {
const reasons = Object.entries(rejectedReasons)
.map(([id, state]) => `adapter ${id} ` +
(state === false ? 'is not supported by the environment' : 'is not available in the build')
);
let s = length ?
(reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) :
'as no adapter specified';
throw new AxiosError(
`There is no suitable adapter to dispatch the request ` + s,
'ERR_NOT_SUPPORT'
);
}
return adapter;
},
adapters: knownAdapters
};
/**
* Throws a `CanceledError` if cancellation has been requested.
*
* @param {Object} config The config that is to be used for the request
*
* @returns {void}
*/
function throwIfCancellationRequested(config) {
if (config.cancelToken) {
config.cancelToken.throwIfRequested();
}
if (config.signal && config.signal.aborted) {
throw new CanceledError(null, config);
}
}
/**
* Dispatch a request to the server using the configured adapter.
*
* @param {object} config The config that is to be used for the request
*
* @returns {Promise} The Promise to be fulfilled
*/
function dispatchRequest(config) {
throwIfCancellationRequested(config);
config.headers = AxiosHeaders$1.from(config.headers);
// Transform request data
config.data = transformData.call(
config,
config.transformRequest
);
if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
config.headers.setContentType('application/x-www-form-urlencoded', false);
}
const adapter = adapters.getAdapter(config.adapter || defaults$1.adapter);
return adapter(config).then(function onAdapterResolution(response) {
throwIfCancellationRequested(config);
// Transform response data
response.data = transformData.call(
config,
config.transformResponse,
response
);
response.headers = AxiosHeaders$1.from(response.headers);
return response;
}, function onAdapterRejection(reason) {
if (!isCancel(reason)) {
throwIfCancellationRequested(config);
// Transform response data
if (reason && reason.response) {
reason.response.data = transformData.call(
config,
config.transformResponse,
reason.response
);
reason.response.headers = AxiosHeaders$1.from(reason.response.headers);
}
}
return Promise.reject(reason);
});
}
const VERSION = "1.7.7";
const validators$1 = {};
// eslint-disable-next-line func-names
['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {
validators$1[type] = function validator(thing) {
return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
};
});
const deprecatedWarnings = {};
/**
* Transitional option validator
*
* @param {function|boolean?} validator - set to false if the transitional option has been removed
* @param {string?} version - deprecated version / removed since version
* @param {string?} message - some message with additional info
*
* @returns {function}
*/
validators$1.transitional = function transitional(validator, version, message) {
function formatMessage(opt, desc) {
return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : '');
}
// eslint-disable-next-line func-names
return (value, opt, opts) => {
if (validator === false) {
throw new AxiosError(
formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
AxiosError.ERR_DEPRECATED
);
}
if (version && !deprecatedWarnings[opt]) {
deprecatedWarnings[opt] = true;
// eslint-disable-next-line no-console
console.warn(
formatMessage(
opt,
' has been deprecated since v' + version + ' and will be removed in the near future'
)
);
}
return validator ? validator(value, opt, opts) : true;
};
};
/**
* Assert object's properties type
*
* @param {object} options
* @param {object} schema
* @param {boolean?} allowUnknown
*
* @returns {object}
*/
function assertOptions(options, schema, allowUnknown) {
if (typeof options !== 'object') {
throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
}
const keys = Object.keys(options);
let i = keys.length;
while (i-- > 0) {
const opt = keys[i];
const validator = schema[opt];
if (validator) {
const value = options[opt];
const result = value === undefined || validator(value, opt, options);
if (result !== true) {
throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);
}
continue;
}
if (allowUnknown !== true) {
throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);
}
}
}
var validator = {
assertOptions,
validators: validators$1
};
const validators = validator.validators;
/**
* Create a new instance of Axios
*
* @param {Object} instanceConfig The default config for the instance
*
* @return {Axios} A new instance of Axios
*/
class Axios {
constructor(instanceConfig) {
this.defaults = instanceConfig;
this.interceptors = {
request: new InterceptorManager$1(),
response: new InterceptorManager$1()
};
}
/**
* Dispatch a request
*
* @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
* @param {?Object} config
*
* @returns {Promise} The Promise to be fulfilled
*/
async request(configOrUrl, config) {
try {
return await this._request(configOrUrl, config);
} catch (err) {
if (err instanceof Error) {
let dummy;
Error.captureStackTrace ? Error.captureStackTrace(dummy = {}) : (dummy = new Error());
// slice off the Error: ... line
const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, '') : '';
try {
if (!err.stack) {
err.stack = stack;
// match without the 2 top stack lines
} else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) {
err.stack += '\n' + stack;
}
} catch (e) {
// ignore the case where "stack" is an un-writable property
}
}
throw err;
}
}
_request(configOrUrl, config) {
/*eslint no-param-reassign:0*/
// Allow for axios('example/url'[, config]) a la fetch API
if (typeof configOrUrl === 'string') {
config = config || {};
config.url = configOrUrl;
} else {
config = configOrUrl || {};
}
config = mergeConfig(this.defaults, config);
const {transitional, paramsSerializer, headers} = config;
if (transitional !== undefined) {
validator.assertOptions(transitional, {
silentJSONParsing: validators.transitional(validators.boolean),
forcedJSONParsing: validators.transitional(validators.boolean),
clarifyTimeoutError: validators.transitional(validators.boolean)
}, false);
}
if (paramsSerializer != null) {
if (utils$1.isFunction(paramsSerializer)) {
config.paramsSerializer = {
serialize: paramsSerializer
};
} else {
validator.assertOptions(paramsSerializer, {
encode: validators.function,
serialize: validators.function
}, true);
}
}
// Set config.method
config.method = (config.method || this.defaults.method || 'get').toLowerCase();
// Flatten headers
let contextHeaders = headers && utils$1.merge(
headers.common,
headers[config.method]
);
headers && utils$1.forEach(
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
(method) => {
delete headers[method];
}
);
config.headers = AxiosHeaders$1.concat(contextHeaders, headers);
// filter out skipped interceptors
const requestInterceptorChain = [];
let synchronousRequestInterceptors = true;
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
return;
}
synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
});
const responseInterceptorChain = [];
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
});
let promise;
let i = 0;
let len;
if (!synchronousRequestInterceptors) {
const chain = [dispatchRequest.bind(this), undefined];
chain.unshift.apply(chain, requestInterceptorChain);
chain.push.apply(chain, responseInterceptorChain);
len = chain.length;
promise = Promise.resolve(config);
while (i < len) {
promise = promise.then(chain[i++], chain[i++]);
}
return promise;
}
len = requestInterceptorChain.length;
let newConfig = config;
i = 0;
while (i < len) {
const onFulfilled = requestInterceptorChain[i++];
const onRejected = requestInterceptorChain[i++];
try {
newConfig = onFulfilled(newConfig);
} catch (error) {
onRejected.call(this, error);
break;
}
}
try {
promise = dispatchRequest.call(this, newConfig);
} catch (error) {
return Promise.reject(error);
}
i = 0;
len = responseInterceptorChain.length;
while (i < len) {
promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
}
return promise;
}
getUri(config) {
config = mergeConfig(this.defaults, config);
const fullPath = buildFullPath(config.baseURL, config.url);
return buildURL(fullPath, config.params, config.paramsSerializer);
}
}
// Provide aliases for supported request methods
utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, config) {
return this.request(mergeConfig(config || {}, {
method,
url,
data: (config || {}).data
}));
};
});
utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
/*eslint func-names:0*/
function generateHTTPMethod(isForm) {
return function httpMethod(url, data, config) {
return this.request(mergeConfig(config || {}, {
method,
headers: isForm ? {
'Content-Type': 'multipart/form-data'
} : {},
url,
data
}));
};
}
Axios.prototype[method] = generateHTTPMethod();
Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
});
var Axios$1 = Axios;
/**
* A `CancelToken` is an object that can be used to request cancellation of an operation.
*
* @param {Function} executor The executor function.
*
* @returns {CancelToken}
*/
class CancelToken {
constructor(executor) {
if (typeof executor !== 'function') {
throw new TypeError('executor must be a function.');
}
let resolvePromise;
this.promise = new Promise(function promiseExecutor(resolve) {
resolvePromise = resolve;
});
const token = this;
// eslint-disable-next-line func-names
this.promise.then(cancel => {
if (!token._listeners) return;
let i = token._listeners.length;
while (i-- > 0) {
token._listeners[i](cancel);
}
token._listeners = null;
});
// eslint-disable-next-line func-names
this.promise.then = onfulfilled => {
let _resolve;
// eslint-disable-next-line func-names
const promise = new Promise(resolve => {
token.subscribe(resolve);
_resolve = resolve;
}).then(onfulfilled);
promise.cancel = function reject() {
token.unsubscribe(_resolve);
};
return promise;
};
executor(function cancel(message, config, request) {
if (token.reason) {
// Cancellation has already been requested
return;
}
token.reason = new CanceledError(message, config, request);
resolvePromise(token.reason);
});
}
/**
* Throws a `CanceledError` if cancellation has been requested.
*/
throwIfRequested() {
if (this.reason) {
throw this.reason;
}
}
/**
* Subscribe to the cancel signal
*/
subscribe(listener) {
if (this.reason) {
listener(this.reason);
return;
}
if (this._listeners) {
this._listeners.push(listener);
} else {
this._listeners = [listener];
}
}
/**
* Unsubscribe from the cancel signal
*/
unsubscribe(listener) {
if (!this._listeners) {
return;
}
const index = this._listeners.indexOf(listener);
if (index !== -1) {
this._listeners.splice(index, 1);
}
}
toAbortSignal() {
const controller = new AbortController();
const abort = (err) => {
controller.abort(err);
};
this.subscribe(abort);
controller.signal.unsubscribe = () => this.unsubscribe(abort);
return controller.signal;
}
/**
* Returns an object that contains a new `CancelToken` and a function that, when called,
* cancels the `CancelToken`.
*/
static source() {
let cancel;
const token = new CancelToken(function executor(c) {
cancel = c;
});
return {
token,
cancel
};
}
}
var CancelToken$1 = CancelToken;
/**
* Syntactic sugar for invoking a function and expanding an array for arguments.
*
* Common use case would be to use `Function.prototype.apply`.
*
* ```js
* function f(x, y, z) {}
* var args = [1, 2, 3];
* f.apply(null, args);
* ```
*
* With `spread` this example can be re-written.
*
* ```js
* spread(function(x, y, z) {})([1, 2, 3]);
* ```
*
* @param {Function} callback
*
* @returns {Function}
*/
function spread(callback) {
return function wrap(arr) {
return callback.apply(null, arr);
};
}
/**
* Determines whether the payload is an error thrown by Axios
*
* @param {*} payload The value to test
*
* @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
*/
function isAxiosError(payload) {
return utils$1.isObject(payload) && (payload.isAxiosError === true);
}
const HttpStatusCode = {
Continue: 100,
SwitchingProtocols: 101,
Processing: 102,
EarlyHints: 103,
Ok: 200,
Created: 201,
Accepted: 202,
NonAuthoritativeInformation: 203,
NoContent: 204,
ResetContent: 205,
PartialContent: 206,
MultiStatus: 207,
AlreadyReported: 208,
ImUsed: 226,
MultipleChoices: 300,
MovedPermanently: 301,
Found: 302,
SeeOther: 303,
NotModified: 304,
UseProxy: 305,
Unused: 306,
TemporaryRedirect: 307,
PermanentRedirect: 308,
BadRequest: 400,
Unauthorized: 401,
PaymentRequired: 402,
Forbidden: 403,
NotFound: 404,
MethodNotAllowed: 405,
NotAcceptable: 406,
ProxyAuthenticationRequired: 407,
RequestTimeout: 408,
Conflict: 409,
Gone: 410,
LengthRequired: 411,
PreconditionFailed: 412,
PayloadTooLarge: 413,
UriTooLong: 414,
UnsupportedMediaType: 415,
RangeNotSatisfiable: 416,
ExpectationFailed: 417,
ImATeapot: 418,
MisdirectedRequest: 421,
UnprocessableEntity: 422,
Locked: 423,
FailedDependency: 424,
TooEarly: 425,
UpgradeRequired: 426,
PreconditionRequired: 428,
TooManyRequests: 429,
RequestHeaderFieldsTooLarge: 431,
UnavailableForLegalReasons: 451,
InternalServerError: 500,
NotImplemented: 501,
BadGateway: 502,
ServiceUnavailable: 503,
GatewayTimeout: 504,
HttpVersionNotSupported: 505,
VariantAlsoNegotiates: 506,
InsufficientStorage: 507,
LoopDetected: 508,
NotExtended: 510,
NetworkAuthenticationRequired: 511,
};
Object.entries(HttpStatusCode).forEach(([key, value]) => {
HttpStatusCode[value] = key;
});
var HttpStatusCode$1 = HttpStatusCode;
/**
* Create an instance of Axios
*
* @param {Object} defaultConfig The default config for the instance
*
* @returns {Axios} A new instance of Axios
*/
function createInstance(defaultConfig) {
const context = new Axios$1(defaultConfig);
const instance = bind(Axios$1.prototype.request, context);
// Copy axios.prototype to instance
utils$1.extend(instance, Axios$1.prototype, context, {allOwnKeys: true});
// Copy context to instance
utils$1.extend(instance, context, null, {allOwnKeys: true});
// Factory for creating new instances
instance.create = function create(instanceConfig) {
return createInstance(mergeConfig(defaultConfig, instanceConfig));
};
return instance;
}
// Create the default instance to be exported
const axios = createInstance(defaults$1);
// Expose Axios class to allow class inheritance
axios.Axios = Axios$1;
// Expose Cancel & CancelToken
axios.CanceledError = CanceledError;
axios.CancelToken = CancelToken$1;
axios.isCancel = isCancel;
axios.VERSION = VERSION;
axios.toFormData = toFormData;
// Expose AxiosError class
axios.AxiosError = AxiosError;
// alias for CanceledError for backward compatibility
axios.Cancel = axios.CanceledError;
// Expose all/spread
axios.all = function all(promises) {
return Promise.all(promises);
};
axios.spread = spread;
// Expose isAxiosError
axios.isAxiosError = isAxiosError;
// Expose mergeConfig
axios.mergeConfig = mergeConfig;
axios.AxiosHeaders = AxiosHeaders$1;
axios.formToJSON = thing => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing);
axios.getAdapter = adapters.getAdapter;
axios.HttpStatusCode = HttpStatusCode$1;
axios.default = axios;
module.exports = axios;
//# sourceMappingURL=axios.cjs.map
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/ /* webpack/runtime/define property getters */
/******/ (() => {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = (exports, definition) => {
/******/ for(var key in definition) {
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ }
/******/ }
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/global */
/******/ (() => {
/******/ __webpack_require__.g = (function() {
/******/ if (typeof globalThis === 'object') return globalThis;
/******/ try {
/******/ return this || new Function('return this')();
/******/ } catch (e) {
/******/ if (typeof window === 'object') return window;
/******/ }
/******/ })();
/******/ })();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ (() => {
/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ })();
/******/
/******/ /* webpack/runtime/make namespace object */
/******/ (() => {
/******/ // define __esModule on exports
/******/ __webpack_require__.r = (exports) => {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ })();
/******/
/************************************************************************/
/******/
/******/ // startup
/******/ // Load entry module and return exports
/******/ // This entry module is referenced by other modules so it can't be inlined
/******/ var __webpack_exports__ = __webpack_require__(5022);
/******/
/******/ })()
;