@braze/web-sdk
Version:
Braze SDK for web sites and other JS platforms.
394 lines (393 loc) • 11.1 kB
JavaScript
import qt from "../models/backend-errors.js";
import ve from "../models/braze-event.js";
import {
convertMsToSeconds as L,
convertSecondsToMs as Xt,
} from "../util/date-utils.js";
import c from "../common/event-logger.js";
import { isArray as z, isEqual as ii } from "../util/code-utils.js";
import { logger as N, EventTypes as d } from "../../shared-lib/index.js";
import { STORAGE_KEYS as s } from "./storage-manager.js";
import h from "../util/request-header-utils.js";
import {
LAST_REQUEST_TO_ENDPOINT_MS_AGO_DEFAULT as $t,
MAX_RETRY_COUNT_PER_REQUEST as Kt,
} from "../common/constants.js";
import { getAlias as Ht } from "./utils.js";
import { readResponseHeaders as Yt } from "../util/net.js";
export default class Pt {
constructor(t, e, i, s, r, n, o, a, h, u, l, c) {
(this.an = t),
(this.C = e),
(this.Ra = i),
(this.Cs = s),
(this.T = r),
(this.B = n),
(this.un = o),
(this.Pa = a),
(this.Oa = h),
(this.Ta = u),
(this.appVersion = l),
(this.au = c),
(this.du = (t) => (null == t ? "" : `${t} `)),
(this.an = t),
(this.C = e),
(this.Ra = i),
(this.Cs = s),
(this.T = r),
(this.B = n),
(this.un = o),
(this.Pa = a),
(this.Oa = h),
(this.Ta = u),
(this.appVersion = l),
(this.au = c),
(this.fu = ["npm"]);
}
H(t, e = !1, i = !1) {
const r = this.an.ve(!i),
n = r.$r(),
o = this.C.ft(s.gt.ic);
ii(o, n) || (t.device = n),
(t.api_key = this.un),
(t.time = L(new Date().valueOf(), !0));
const a = this.C.ft(s.gt.vu) || [],
h = this.C.ft(s.gt.pu) || "";
this.fu.length > 0 &&
(!ii(a, this.fu) || h !== this.T.St()) &&
(t.sdk_metadata = this.fu),
(t.sdk_version = this.Oa),
this.Ta && (t.sdk_flavor = this.Ta),
(t.app_version = this.appVersion),
(t.app_version_code = this.au),
(t.device_id = r.id);
const u = this.Cs.getUserId();
if ((e && null !== u && (t.user_id = u), !u && !this.Ra.wh())) {
const e = Ht(this.C);
e && (t.alias = e);
}
return t;
}
st(t, e, i) {
const s = e.auth_error,
r = e.error;
if (!s && !r) return !0;
if (s) {
let e;
this.Ra.Hh();
const r = { errorCode: s.error_code };
for (const t of i)
z(t) && "X-Braze-Auth-Signature" === t[0] && (r.signature = t[1]);
t.respond_with && t.respond_with.user_id
? (r.userId = t.respond_with.user_id)
: t.user_id && (r.userId = t.user_id);
const n = s.reason;
return (
n
? ((r.reason = n), (e = `due to ${n}`))
: (e = `with error code ${s.error_code}.`),
this.Ra.wh() ||
(e +=
' Please use the "enableSdkAuthentication" initialization option to enable authentication.'),
N.error(`SDK Authentication failed ${e}`),
this.Ru(t.events || [], t.attributes || []),
this.Ra.Bh(r),
!1
);
}
if (r) {
let i,
s = r;
switch (s) {
case qt.gu:
return (
(i = "Received successful response with empty body."),
c.ut(d.bu, { e: i }),
N.info(i),
!1
);
case qt.qu:
return (
(i = "Received successful response with invalid JSON"),
c.ut(d.bu, { e: i + ": " + e.response }),
N.info(i),
!1
);
case qt.Au:
s = `The API key "${t.api_key}" is invalid for the baseUrl ${this.Pa}`;
break;
case qt.Du:
s =
"Sorry, we are not currently accepting your requests. If you think this is in error, please contact us.";
break;
case qt.ku:
s = "No device identifier. Please contact support@braze.com";
}
N.error("Backend error: " + s);
}
return !1;
}
Tu(t, e, i, s) {
return !!((t && 0 !== t.length) || (e && 0 !== e.length) || i || s);
}
yu(t, e, i, s, r = !1) {
const n = [],
o = (t) => t || "",
a = o(this.Cs.getUserId());
let u = this.Nr(t, e);
const l = [],
c = [];
let d,
f = null;
if (i.length > 0) {
const t = [];
for (const e of i) {
if (((d = e.$r()), this.Ra.wh())) {
if (a && !d.user_id) {
f || (f = {}), f.events || (f.events = []), f.events.push(d);
continue;
}
if (o(d.user_id) !== a) {
c.push(d);
continue;
}
}
t.push(d);
}
t.length > 0 && (u.events = t);
}
if (s.length > 0) {
const t = [];
for (const e of s)
e && (this.Ra.wh() && o(e.user_id) !== a ? l.push(e) : t.push(e));
t.length > 0 && (u.attributes = t);
}
if ((this.Ru(c, l), (u = this.H(u, !1, r)), f)) {
f = this.H(f, !1, r);
const t = { requestData: f, headers: this.J(f, h.O.Nu) };
n.push(t);
}
if (u && !this.Tu(u.events, u.attributes, t, e)) return f ? n : null;
const m = { requestData: u, headers: this.J(u, h.O.Nu) };
return n.push(m), n;
}
Ru(t, e) {
if (t) {
const e = [];
for (const i of t) {
const t = ve.fromJson(i);
(t.time = Xt(t.time)), e.push(t);
}
this.C.Vo(e);
}
if (e) for (const t of e) this.C.wu(t);
}
et(t, e) {
let i = "HTTP error ";
null != t && (i += t + " "), (i += e), N.error(i);
}
zr(t) {
return c.ut(d.Cu, { n: t });
}
Nr(t, e, i) {
const s = {};
t && (s.feed = !0), e && (s.triggers = !0);
const r = null != i ? i : this.Cs.getUserId();
if ((r && (s.user_id = r), !s.user_id && !this.Ra.wh())) {
const t = Ht(this.C);
t && (s.alias = t);
}
return (s.config = { config_time: this.B.Et() }), { respond_with: s };
}
Su(t) {
const e = new Date().valueOf();
let i = $t.toString();
const s = h.Bu(this.C, t);
if (-1 !== s) {
i = (e - s).toString();
}
return i;
}
J(t, e, i = !1) {
const s = [["X-Braze-Api-Key", this.un]],
r = this.Su(e);
s.push(["X-Braze-Last-Req-Ms-Ago", r]);
const n = h.zu(this.C, e).toString();
s.push(["X-Braze-Req-Attempt", n]);
let o = !1;
if (
(null != t.respond_with &&
t.respond_with.triggers &&
(s.push(["X-Braze-TriggersRequest", "true"]), (o = !0)),
null != t.respond_with &&
t.respond_with.feed &&
(s.push(["X-Braze-FeedRequest", "true"]), (o = !0)),
e === h.O.gi)
) {
s.push(["X-Braze-ContentCardsRequest", "true"]);
let t = h.zu(this.C, h.O.gi);
(t && !i) || ((t = 1), h.ju(this.C, h.O.gi, t));
const e = Math.max(0, t - 1);
s.push(["BRAZE-SYNC-RETRY-COUNT", e.toString()]), (o = !0);
}
if (
(e === h.O.Le &&
(s.push(["X-Braze-FeatureFlagsRequest", "true"]), (o = !0)),
o && s.push(["X-Braze-DataRequest", "true"]),
this.Ra.wh())
) {
const t = this.Ra.jh();
null != t && s.push(["X-Braze-Auth-Signature", t]);
}
return s;
}
Mu(t, e, i, s) {
window.setTimeout(() => {
N.info(`Retrying rate limited ${this.du(s)}SDK request.`),
this.V(e, i, s);
}, t);
}
V(t, e, i, r) {
if (!this.Xu(i))
return (
N.info(`${this.du(i)}SDK request being rate limited.`),
void ("function" == typeof r && r())
);
const n = this.$u();
if (!n.Fu)
return (
N.info(
`${this.du(
i,
)}SDK request being rate limited. Request will be retried in ${Math.trunc(
n.Lu / 1e3,
)} seconds.`,
),
void this.Mu(n.Lu, t, e, i)
);
this.C.Bt(s.gt.Eu, new Date().valueOf());
const o = t.device;
o && o.os_version instanceof Promise
? o.os_version.then((i) => {
(t.device.os_version = i), e(n.Ku);
})
: e(n.Ku);
}
Iu(t) {
const e = t ? Yt(t) : null;
if (!e || !e["retry-after"]) return null;
const i = e["retry-after"];
if (isNaN(i) && !isNaN(Date.parse(i)))
return { type: "date", value: Date.parse(i) };
if (!isNaN(parseFloat(i.toString())))
return { type: "timestamp", value: 1e3 * parseFloat(i.toString()) };
{
const t =
"Received unexpected value for retry-after header in /sync response";
c.ut(d.bu, { e: t + ": " + i });
}
return null;
}
rt(t, e, i, s, r, n) {
if (h.zu(this.C, i) >= Kt) return;
let o;
n = n || 0;
const a = this.Iu(t);
r();
const u = (t) => {
const r = window.setTimeout(() => {
e();
}, t);
s(r), h.Pu(this.C, i);
};
if (a && !isNaN(a.value)) {
switch (a.type) {
case "date":
(o = a.value - new Date().getTime() + n), o < 0 && e();
break;
case "timestamp":
o = a.value + n;
}
u(o);
} else n ? u(n) : h.wi(this.C, i);
}
Uu(t) {
var e;
null === (e = this.C) || void 0 === e || e.Bt(s.gt.xu, t);
}
Hu(t, e) {
let i = this.Ou();
null == i && (i = {}), (i[t] = e), this.C.Bt(s.gt.Gu, i);
}
_u() {
var t;
return null === (t = this.C) || void 0 === t ? void 0 : t.ft(s.gt.xu);
}
Ou() {
var t;
return null === (t = this.C) || void 0 === t ? void 0 : t.ft(s.gt.Gu);
}
Wu(t, e, i, s, r = "") {
let n;
if (r) {
const t = this.Ou();
n = null == t || isNaN(t[r]) ? e : t[r];
} else (n = this._u()), (null == n || isNaN(n)) && (n = e);
const o = (t - s) / 1e3;
return (n = Math.min(n + o / i, e)), n;
}
Yu(t, e) {
return Math.max(0, (1 - t) * e * 1e3);
}
Ju(t, e = "") {
var i, r, n, o, a;
const u = { Fu: !0, Ku: -1, Lu: 0 };
if ((null == t && (t = !0), !t && !e)) return u;
let l,
c,
d = null;
if (t) d = null === (i = this.C) || void 0 === i ? void 0 : i.ft(s.gt.Eu);
else {
const t = h.Qu(this.C);
if (null == t || null == t[e]) return u;
d = t[e];
}
if (null == d || isNaN(d)) return u;
if (
(t
? ((l =
(null === (r = this.B) || void 0 === r ? void 0 : r.Vu()) || -1),
(c = (null === (n = this.B) || void 0 === n ? void 0 : n.Zu()) || -1))
: ((l =
(null === (o = this.B) || void 0 === o ? void 0 : o.tl(e)) || -1),
(c =
(null === (a = this.B) || void 0 === a ? void 0 : a.el(e)) || -1)),
-1 === l || -1 === c)
)
return u;
const f = new Date().valueOf();
let m = this.Wu(f, l, c, d, e);
return m < 1
? ((u.Fu = !1), (u.Lu = this.Yu(m, c)), u)
: ((m = Math.trunc(m) - 1),
(u.Ku = m),
t ? this.Uu(m) : this.Hu(e, m),
u);
}
$u() {
return this.Ju(!0);
}
Xu(t) {
const e = this.Ju(!1, t);
return !(e && !e.Fu);
}
it() {
this.Ra.it();
}
Z() {
return this.Pa;
}
addSdkMetadata(t) {
for (const e of t) -1 === this.fu.indexOf(e) && this.fu.push(e);
}
}