overcentric
Version:
Overcentric watches your website, product, and users - and tells you what matters and what to do about it.
76 lines (75 loc) • 3.12 kB
JavaScript
// Compute normalized hostname once when the module loads
const normalizedHostname = typeof window !== 'undefined' ? window.location.hostname.replace(/^www\./, '') : '';
// Returns the company block, or null when there's nothing worth sending.
// Additive: null → payload is byte-identical to a no-company event.
function buildCompanyBlock(company) {
if (!company)
return null;
const id = company.id || undefined;
const name = company.name || undefined;
const website = company.website || undefined;
if (!id && !name && !website)
return null;
return {
...(id && { company_id: id }),
...(name && { company_name: name }),
...(website && { company_website: website }),
};
}
export function sendEvent(projectId, basePath, event, identity) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('POST', `${basePath}/events`, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve();
}
else {
reject(new Error(`HTTP Error: ${xhr.status} ${xhr.statusText}`));
}
};
xhr.onerror = () => reject(new Error('Network Error'));
// Only present on the $identify event, when a company was passed to
// identify() AND the user is identified. Company assignment is a
// one-time link, so it rides identify() only — not every subsequent
// event. Guarded in try/catch so a malformed company object can never
// break event sending.
let companyBlock = null;
try {
if (event.eventName === '$identify' && identity && identity.uniqueIdentifier) {
companyBlock = buildCompanyBlock(identity.company);
}
}
catch (e) {
companyBlock = null;
}
const payload = {
event: {
name: event.eventName,
properties: event.properties,
project_id: projectId,
device_id: event.deviceId,
session_id: event.sessionId,
context: event.context,
url: window.location.href,
hostname: normalizedHostname,
...(document.referrer && { referrer: document.referrer }),
screen_width: window.screen.width,
screen_height: window.screen.height
},
...(identity && identity.uniqueIdentifier && {
identity: {
project_id: projectId,
unique_identifier: identity.uniqueIdentifier,
email: identity.email,
name: identity.name
}
}),
// Only present when a company was passed to identify(); a no-company
// event serializes exactly as before.
...(companyBlock && { company: companyBlock })
};
xhr.send(JSON.stringify(payload));
});
}