@chordcommerce/analytics
Version:
Chord Commerce event tracking
82 lines (81 loc) • 3.23 kB
JavaScript
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());
});
};
const getApi = () => window.segmentConsent;
/**
* Waits for the Segment consent API to be populated with retry logic.
*/
const waitForApi = (maxRetries = 10, baseDelay = 100) => __awaiter(void 0, void 0, void 0, function* () {
let attempt = 0;
const checkAndWait = () => __awaiter(void 0, void 0, void 0, function* () {
const api = getApi();
if (api &&
typeof api === 'object' &&
api.customPreferences &&
typeof api.customPreferences === 'object' &&
Object.keys(api.customPreferences).length > 0) {
return api;
}
if (attempt < maxRetries) {
const delay = baseDelay * Math.pow(2, attempt);
yield new Promise((resolve) => {
setTimeout(resolve, delay);
});
attempt++;
return checkAndWait();
}
return null;
});
return checkAndWait();
});
/**
* Returns whether the user can currently be tracked.
*/
const userCanBeTracked = () => __awaiter(void 0, void 0, void 0, function* () {
const api = yield waitForApi();
return (!!api &&
!!(api.customPreferences.functional &&
api.customPreferences.marketingAndAnalytics));
});
/**
* Returns the user's current consent configuration.
*/
const getCurrentConsent = () => __awaiter(void 0, void 0, void 0, function* () {
const api = yield waitForApi();
if (!api)
return {};
return {
consentCategories: Object.assign(Object.assign({}, api.customPreferences), api.destinationPreferences),
};
});
/**
* Handles subsequent changes to consent configuration.
*/
const handleConsentUpdates = (updateCdpConsent) => {
document.addEventListener('chord-cdp:consent-updated', () => __awaiter(void 0, void 0, void 0, function* () {
updateCdpConsent(yield getCurrentConsent());
}));
};
export const segmentConsentAdapter = () => {
return {
getCurrentConsent,
handleConsentUpdates,
userCanBeTracked,
getCategories: () => {
const api = getApi();
if (!(api === null || api === void 0 ? void 0 : api.customPreferences))
return {};
return Object.assign(Object.assign({}, api.customPreferences), api.destinationPreferences);
},
isConsentReady: () => {
const api = getApi();
return !!((api === null || api === void 0 ? void 0 : api.customPreferences) && Object.keys(api.customPreferences).length > 0);
},
};
};