You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@unomi.apache.org by js...@apache.org on 2025/04/02 16:29:26 UTC
(unomi-tracker) branch main updated: UNOMI-891: accurate types (#22)
This is an automated email from the ASF dual-hosted git repository.
jsinovassinnaik pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/unomi-tracker.git
The following commit(s) were added to refs/heads/main by this push:
new 6e9089a UNOMI-891: accurate types (#22)
6e9089a is described below
commit 6e9089a7573815cb5464b229be65012d95906d08
Author: Gautier Ben Aïm <48...@users.noreply.github.com>
AuthorDate: Wed Apr 2 18:29:21 2025 +0200
UNOMI-891: accurate types (#22)
---
dist/apache-unomi-tracker.cjs.js | 279 +++++++++++++++++++++++++----------
dist/apache-unomi-tracker.cjs.js.map | 2 +-
dist/apache-unomi-tracker.d.ts | 210 +++++++++++++++-----------
dist/apache-unomi-tracker.esm.js | 279 +++++++++++++++++++++++++----------
dist/apache-unomi-tracker.esm.js.map | 2 +-
dist/apache-unomi-tracker.umd.js | 279 +++++++++++++++++++++++++----------
dist/apache-unomi-tracker.umd.js.map | 2 +-
dist/types.d.ts | 120 +++++++++++++++
package.json | 2 +-
src/apache-unomi-tracker.js | 220 +++++++++++++++++----------
src/global.d.ts | 8 +
src/types.ts | 132 +++++++++++++++++
12 files changed, 1125 insertions(+), 410 deletions(-)
diff --git a/dist/apache-unomi-tracker.cjs.js b/dist/apache-unomi-tracker.cjs.js
index dc4b4a0..4abc338 100644
--- a/dist/apache-unomi-tracker.cjs.js
+++ b/dist/apache-unomi-tracker.cjs.js
@@ -31,12 +31,45 @@ function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
+/** @import { AjaxOptions, DigitalData, UnomiEvent, Personalization, PersonalizationCallback, Variant, UnomiObject, UnomiProperties } from "./types" */
+
var useTracker = function useTracker() {
var wem = {
+ digitalData:
+ /** @type {DigitalData} */
+
+ /** @type {unknown} */
+ undefined,
+ trackerProfileIdCookieName: 'wem-profile-id',
+ trackerSessionIdCookieName: 'wem-session-id',
+ browserGeneratedSessionSuffix: '',
+ disableTrackedConditionsListeners: false,
+ activateWem: true,
+ contextServerCookieName: 'context-profile-id',
+ contextServerUrl: '',
+ timeoutInMilliseconds: 1500,
+ formNamesToWatch:
+ /** @type {string[]} */
+ [],
+ eventsPrevented:
+ /** @type {string[]} */
+ [],
+
+ /** @type {string | null} */
+ sessionID: null,
+ fallback: false,
+
+ /** @type {any} */
+ cxs: undefined,
+ DOMLoaded: false,
+
+ /** @type {string | undefined} */
+ contextLoaded: undefined,
+
/**
* This function initialize the tracker
*
- * @param {object} digitalData config of the tracker
+ * @param {DigitalData} digitalData config of the tracker
* @returns {undefined}
*/
initTracker: function initTracker(digitalData) {
@@ -44,7 +77,7 @@ var useTracker = function useTracker() {
wem.trackerProfileIdCookieName = wem.digitalData.wemInitConfig.trackerProfileIdCookieName ? wem.digitalData.wemInitConfig.trackerProfileIdCookieName : 'wem-profile-id';
wem.trackerSessionIdCookieName = wem.digitalData.wemInitConfig.trackerSessionIdCookieName ? wem.digitalData.wemInitConfig.trackerSessionIdCookieName : 'wem-session-id';
wem.browserGeneratedSessionSuffix = wem.digitalData.wemInitConfig.browserGeneratedSessionSuffix ? wem.digitalData.wemInitConfig.browserGeneratedSessionSuffix : '';
- wem.disableTrackedConditionsListeners = wem.digitalData.wemInitConfig.disableTrackedConditionsListeners;
+ wem.disableTrackedConditionsListeners = wem.digitalData.wemInitConfig.disableTrackedConditionsListeners || false;
wem.activateWem = wem.digitalData.wemInitConfig.activateWem;
var _wem$digitalData$wemI = wem.digitalData.wemInitConfig,
contextServerUrl = _wem$digitalData$wemI.contextServerUrl,
@@ -70,7 +103,7 @@ var useTracker = function useTracker() {
* This function start the tracker by loading the context in the page
* Note: that the tracker will start once the current DOM is complete loaded, using listener on current document: DOMContentLoaded
*
- * @param {object[]} digitalDataOverrides optional, list of digitalData extensions, they will be merged with original digitalData before context loading
+ * @param {Array<Partial<DigitalData>>} [digitalDataOverrides] optional, list of digitalData extensions, they will be merged with original digitalData before context loading
* @returns {undefined}
*/
startTracker: function startTracker() {
@@ -151,7 +184,7 @@ var useTracker = function useTracker() {
/**
* get the current loaded context from Unomi, will be accessible only after loadContext() have been performed
- * @returns {object} loaded context
+ * @returns {any} loaded context
*/
getLoadedContext: function getLoadedContext() {
return wem.cxs;
@@ -180,9 +213,9 @@ var useTracker = function useTracker() {
/**
* This function will register a personalization
*
- * @param {object} personalization the personalization object
- * @param {object} variants the variants
- * @param {boolean} [ajax] Deprecated: Ajax rendering is not supported anymore
+ * @param {Personalization} personalization the personalization object
+ * @param {Record<string, Variant>} variants the variants
+ * @param {boolean} [ajax] Deprecated: Ajax rendering is not supported anymore (ignored)
* @param {function} [resultCallback] the callback to be executed after personalization resolved
* @returns {undefined}
*/
@@ -221,10 +254,15 @@ var useTracker = function useTracker() {
resultCallback(successfulFilters, selectedFilter);
} else {
if (selectedFilter) {
- var targetFilters = document.getElementById(target).children;
+ var targetFilters =
+ /** @type {HTMLElement} */
+ document.getElementById(target).children;
for (var fIndex in targetFilters) {
- var filter = targetFilters.item(fIndex);
+ // @ts-expect-error The indexing is unsafe
+ var filter =
+ /** @type {HTMLElement | null} */
+ targetFilters.item(fIndex);
if (filter) {
filter.style.display = filter.id === selectedFilter.content ? '' : 'none';
@@ -234,10 +272,12 @@ var useTracker = function useTracker() {
if (selectedFilter.event) {
// we now add control group information to event if the user is in the control group.
if (inControlGroup) {
- console.debug('[WEM] Profile is in control group for target: ' + target + ', adding to personalization event...');
- selectedFilter.event.target.properties.inControlGroup = true;
+ console.debug('[WEM] Profile is in control group for target: ' + target + ', adding to personalization event...'); // @ts-expect-error The properties are not defined
+
+ selectedFilter.event.target.properties.inControlGroup = true; // @ts-expect-error The properties are not defined
if (selectedFilter.event.target.properties.variants) {
+ // @ts-expect-error The properties are not defined
selectedFilter.event.target.properties.variants.forEach(function (variant) {
return variant.inControlGroup = true;
});
@@ -254,10 +294,15 @@ var useTracker = function useTracker() {
wem._dispatchJSExperienceDisplayedEvent(selectedFilter.event);
}
} else {
- var elements = document.getElementById(target).children;
+ var elements =
+ /** @type {HTMLElement} */
+ document.getElementById(target).children;
for (var eIndex in elements) {
- var el = elements.item(eIndex);
+ // @ts-expect-error The indexing is unsafe
+ var el =
+ /** @type {HTMLElement} */
+ elements.item(eIndex);
el.style.display = 'none';
}
}
@@ -269,11 +314,11 @@ var useTracker = function useTracker() {
* This function will register an optimization test or A/B test
*
* @param {string} optimizationTestNodeId the optimization test node id
- * @param {string} goalId the associated goal Id
- * @param {string} containerId the HTML container Id
- * @param {object} variants the variants
- * @param {boolean} [ajax] Deprecated: Ajax rendering is not supported anymore
- * @param {object} [variantsTraffic] the associated traffic allocation
+ * @param {string} goalId the associated goal Id (unused)
+ * @param {string} containerId the HTML container Id (unused)
+ * @param {Record<string, Variant>} variants the variants
+ * @param {boolean} [ajax] Deprecated: Ajax rendering is not supported anymore (unused)
+ * @param {Record<string, number>} [variantsTraffic] the associated traffic allocation
* @return {undefined}
*/
registerOptimizationTest: function registerOptimizationTest(optimizationTestNodeId, goalId, containerId, variants, ajax, variantsTraffic) {
@@ -309,12 +354,18 @@ var useTracker = function useTracker() {
}
if (wem.storageAvailable('sessionStorage')) {
- sessionStorage.setItem(optimizationTestNodeId, selectedVariantId);
+ sessionStorage.setItem(optimizationTestNodeId,
+ /** @type {string} */
+ selectedVariantId);
} else {
- wem.setCookie('selectedVariantId', selectedVariantId, 1);
+ wem.setCookie('selectedVariantId',
+ /** @type {string} */
+ selectedVariantId, 1);
}
- var variant = variants[selectedVariantId]; // spread event to unomi
+ var variant = variants[
+ /** @type {string} */
+ selectedVariantId]; // spread event to unomi
if (variant.event) {
wem._registerEvent(wem._completeEvent(variant.event));
@@ -327,6 +378,8 @@ var useTracker = function useTracker() {
window.optimizedContentAreas[optimizationTestNodeId].selectedVariant = selectedVariantId;
} // display the good variant
+ /** @type {HTMLElement} */
+
document.getElementById(variants[selectedVariantId].content).style.display = '';
}
@@ -350,6 +403,8 @@ var useTracker = function useTracker() {
console.log('Context already requested by', wem.contextLoaded);
return;
}
+ /** @type {Record<string, unknown>} */
+
var jsonData = {
requiredProfileProperties: wem.digitalData.wemInitConfig.requiredProfileProperties,
@@ -384,6 +439,7 @@ var useTracker = function useTracker() {
// Use text/plain to avoid CORS preflight
jsonData: jsonData,
dataType: 'application/json',
+ // @ts-expect-error This parameter does not exist
invalidate: invalidate,
success: wem._onSuccess,
error: function error() {
@@ -393,12 +449,13 @@ var useTracker = function useTracker() {
wem.contextLoaded = Error().stack;
console.info('[WEM] context loading...');
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function will send an event to Apache Unomi
- * @param {object} event The event object to send, you can build it using wem.buildEvent(eventType, target, source)
- * @param {function} successCallback optional, will be executed in case of success
- * @param {function} errorCallback optional, will be executed in case of error
+ * @param {UnomiEvent} event The event object to send, you can build it using wem.buildEvent(eventType, target, source)
+ * @param {(xhr: XMLHttpRequest) => void} [successCallback] optional, will be executed in case of success
+ * @param {(xhr: XMLHttpRequest) => void} [errorCallback] optional, will be executed in case of error
* @return {undefined}
*/
collectEvent: function collectEvent(event) {
@@ -408,13 +465,14 @@ var useTracker = function useTracker() {
events: [event]
}, successCallback, errorCallback);
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function will send the events to Apache Unomi
*
- * @param {object} events Javascript object { events: [event1, event2] }
- * @param {function} successCallback optional, will be executed in case of success
- * @param {function} errorCallback optional, will be executed in case of error
+ * @param {{ sessionId?: string, events: Array<UnomiEvent> }} events Javascript object { events: [event1, event2] }
+ * @param {(xhr: XMLHttpRequest) => void} [successCallback] optional, will be executed in case of success
+ * @param {(xhr: XMLHttpRequest) => void} [errorCallback] optional, will be executed in case of error
* @return {undefined}
*/
collectEvents: function collectEvents(events) {
@@ -440,11 +498,12 @@ var useTracker = function useTracker() {
error: errorCallback
});
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function will build an event of type click and send it to Apache Unomi
*
- * @param {object} event javascript
+ * @param {Event & { target: HTMLElement & { name: string }}} event javascript
* @param {function} [successCallback] optional, will be executed if case of success
* @param {function} [errorCallback] optional, will be executed if case of error
* @return {undefined}
@@ -485,20 +544,23 @@ var useTracker = function useTracker() {
}
}
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function will build an event of type video and send it to Apache Unomi
*
- * @param {object} event javascript
- * @param {function} [successCallback] optional, will be executed if case of success
- * @param {function} [errorCallback] optional, will be executed if case of error
+ * @param {Event} event javascript
+ * @param {(xhr: XMLHttpRequest) => void} [successCallback] optional, will be executed if case of success
+ * @param {(xhr: XMLHttpRequest) => void} [errorCallback] optional, will be executed if case of error
* @return {undefined}
*/
sendVideoEvent: function sendVideoEvent(event) {
var successCallback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
var errorCallback = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
console.debug('[WEM] catching video event');
- var videoEvent = wem.buildEvent('video', wem.buildTarget(event.target.id, 'video', {
+ var videoEvent = wem.buildEvent('video', wem.buildTarget(
+ /** @type {HTMLElement} */
+ event.target.id, 'video', {
action: event.type
}), wem.buildSourcePage());
wem.collectEvent(videoEvent, function (xhr) {
@@ -530,16 +592,18 @@ var useTracker = function useTracker() {
wem.removeCookie(wem.trackerProfileIdCookieName);
wem.cxs = undefined;
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function return the basic structure for an event, it must be adapted to your need
*
* @param {string} eventType The name of your event
- * @param {object} [target] The target object for your event can be build with wem.buildTarget(targetId, targetType, targetProperties)
- * @param {object} [source] The source object for your event can be build with wem.buildSource(sourceId, sourceType, sourceProperties)
- * @returns {object} the event
+ * @param {UnomiEvent["target"]} [target] The target object for your event can be build with wem.buildTarget(targetId, targetType, targetProperties)
+ * @param {UnomiEvent["source"]} [source] The source object for your event can be build with wem.buildSource(sourceId, sourceType, sourceProperties)
+ * @returns {UnomiEvent} the event
*/
buildEvent: function buildEvent(eventType, target, source) {
+ /** @type {UnomiEvent} */
var event = {
eventType: eventType,
scope: wem.digitalData.scope
@@ -560,8 +624,8 @@ var useTracker = function useTracker() {
* This function return an event of type form
*
* @param {string} formName The HTML name of id of the form to use in the target of the event
- * @param {HTMLFormElement} form optional HTML form element, if provided will be used to extract the form fields and populate the form event
- * @returns {object} the form event
+ * @param {HTMLFormElement} [form] optional HTML form element, if provided will be used to extract the form fields and populate the form event
+ * @returns {UnomiEvent} the form event
*/
buildFormEvent: function buildFormEvent(formName) {
var form = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
@@ -571,6 +635,14 @@ var useTracker = function useTracker() {
};
return formEvent;
},
+
+ /**
+ * @param {string} formName form name
+ * @param {HTMLFormElement} form form
+ * @param {string} term term
+ * @param {string} language language
+ * @returns {UnomiEvent} event
+ */
buildSearchEvent: function buildSearchEvent(formName, form, term, language) {
var searchEvent = wem.buildEvent('search', wem.buildTarget(formName, 'search'), wem.buildSourcePage());
searchEvent.flattenedProperties = {
@@ -580,49 +652,54 @@ var useTracker = function useTracker() {
originForm: formName,
language: language || 'en',
keyword: term,
+ // @ts-expect-error There is no way this is properly defined
origin: searchEvent.source.properties.pageInfo.pagePath
};
return searchEvent;
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function return the source object for a source of type page
*
- * @returns {object} the target page
+ * @returns {UnomiEvent["target"]} the target page
*/
buildTargetPage: function buildTargetPage() {
return wem.buildTarget(wem.digitalData.page.pageInfo.pageID, 'page', wem.digitalData.page);
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function return the source object for a source of type page
*
- * @returns {object} the source page
+ * @returns {UnomiEvent["source"]} the source page
*/
buildSourcePage: function buildSourcePage() {
return wem.buildSource(wem.digitalData.page.pageInfo.pageID, 'page', wem.digitalData.page);
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function return the basic structure for the target of your event
*
* @param {string} targetId The ID of the target
* @param {string} targetType The type of the target
- * @param {object} [targetProperties] The optional properties of the target
- * @returns {object} the target
+ * @param {UnomiProperties} [targetProperties] The optional properties of the target
+ * @returns {UnomiEvent["target"]} the target
*/
buildTarget: function buildTarget(targetId, targetType) {
var targetProperties = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
return wem._buildObject(targetId, targetType, targetProperties);
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function return the basic structure for the source of your event
*
* @param {string} sourceId The ID of the source
* @param {string} sourceType The type of the source
- * @param {object} [sourceProperties] The optional properties of the source
- * @returns {object} the source
+ * @param {UnomiProperties} [sourceProperties] The optional properties of the source
+ * @returns {UnomiEvent["source"]} the source
*/
buildSource: function buildSource(sourceId, sourceType) {
var sourceProperties = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
@@ -660,7 +737,7 @@ var useTracker = function useTracker() {
* This is an utility function to get a cookie
*
* @param {string} cookieName name of the cookie to get
- * @returns {string} the value of the first cookie with the corresponding name or null if not found
+ * @returns {string | null} the value of the first cookie with the corresponding name or null if not found
*/
getCookie: function getCookie(cookieName) {
var name = cookieName + '=';
@@ -695,7 +772,7 @@ var useTracker = function useTracker() {
/**
* This is an utility function to execute AJAX call
*
- * @param {object} options options of the request
+ * @param {AjaxOptions} options options of the request
* @return {undefined}
*/
ajax: function ajax(options) {
@@ -785,7 +862,7 @@ var useTracker = function useTracker() {
/**
* This is an utility function to check if the local storage is available or not
- * @param {string} type the type of storage to test
+ * @param {"sessionStorage" | "localStorage"} type the type of storage to test
* @returns {boolean} true in case storage is available, false otherwise
*/
storageAvailable: function storageAvailable(type) {
@@ -833,7 +910,7 @@ var useTracker = function useTracker() {
* This is an utility function to get current url parameter value
*
* @param {string} name, the name of the parameter
- * @returns {string} the value of the parameter
+ * @returns {string | null} the value of the parameter
*/
getUrlParameter: function getUrlParameter(name) {
name = name.replace(/[[]/, '\\[').replace(/[\]]/, '\\]');
@@ -845,7 +922,7 @@ var useTracker = function useTracker() {
/**
* convert the passed query string into JS object.
* @param {string} searchString The URL query string
- * @returns {object} converted URL params
+ * @returns {Record<string, Array<string | undefined> | string | undefined> | null} converted URL params
*/
convertUrlParametersToObj: function convertUrlParametersToObj(searchString) {
if (!searchString) {
@@ -877,7 +954,9 @@ var useTracker = function useTracker() {
}
return result;
- }, {});
+ },
+ /** @type Record<string, Array<string | undefined> | string | undefined> */
+ {});
},
/*************************************/
@@ -890,7 +969,7 @@ var useTracker = function useTracker() {
* Used to override the default digitalData values,
* the result will impact directly the current instance wem.digitalData
*
- * @param {object[]} digitalDataOverrides list of overrides
+ * @param {Array<Partial<DigitalData>>} [digitalDataOverrides] list of overrides
* @private
* @return {undefined}
*/
@@ -984,6 +1063,7 @@ var useTracker = function useTracker() {
var click = document.getElementById(clickIdName) || document.getElementById(wem._resolveId(clickIdName)) ? document.getElementById(clickIdName) || document.getElementById(wem._resolveId(clickIdName)) : document.getElementsByName(clickIdName)[0];
if (click) {
+ // @ts-expect-error The types will never match
click.addEventListener('click', wem.sendClickEvent);
console.debug('[WEM] Watching click ' + clickIdName);
} else {
@@ -1046,11 +1126,12 @@ var useTracker = function useTracker() {
/**
* build and dispatch JavaScript event in current HTML document for the given Unomi event (perso/opti)
* @private
- * @param {object} experienceUnomiEvent perso/opti Unomi event
+ * @param {UnomiEvent} experienceUnomiEvent perso/opti Unomi event
* @return {undefined}
*/
_dispatchJSExperienceDisplayedEvent: function _dispatchJSExperienceDisplayedEvent(experienceUnomiEvent) {
if (!wem.fallback && experienceUnomiEvent && experienceUnomiEvent.target && experienceUnomiEvent.target.properties && experienceUnomiEvent.target.properties.variants && experienceUnomiEvent.target.properties.variants.length > 0) {
+ /** @type {Record<string, string | undefined>} */
var typeMapper = {
optimizationTestEvent: 'optimization',
personalizationEvent: 'personalization'
@@ -1062,6 +1143,8 @@ var useTracker = function useTracker() {
try {
for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
var variant = _step4.value;
+
+ /** @type {any} */
var jsEventDetail = {
id: variant.id,
name: variant.systemName,
@@ -1121,9 +1204,9 @@ var useTracker = function useTracker() {
* Check if event is incomplete and complete what is missing:
* - source: if missing, use the current source page
* - scope: if missing, use the current scope
- * @param {object} event, the event to be checked
+ * @param {UnomiEvent} event, the event to be checked
* @private
- * @return {object} the complete event
+ * @return {UnomiEvent} the complete event
*/
_completeEvent: function _completeEvent(event) {
if (!event.source) {
@@ -1149,7 +1232,7 @@ var useTracker = function useTracker() {
* in case the context is already loaded (check: wem.getLoadedContext()), then you should use: wem.collectEvent(s) functions
*
* @private
- * @param {object} event the Unomi event to be registered
+ * @param {UnomiEvent} event the Unomi event to be registered
* @param {boolean} unshift optional, if true, the event will be added at the beginning of the list otherwise at the end of the list. (default: false)
* @return {undefined}
*/
@@ -1162,7 +1245,9 @@ var useTracker = function useTracker() {
return;
}
} else {
- wem.digitalData = {};
+ wem.digitalData =
+ /** @type {DigitalData} */
+ {};
}
wem.digitalData.events = wem.digitalData.events || [];
@@ -1173,11 +1258,12 @@ var useTracker = function useTracker() {
wem.digitalData.events.push(event);
}
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function allow for registering callback that will be executed once the context is loaded.
- * @param {function} onLoadCallback the callback to be executed
- * @param {string} name optional name for the call, used mostly for logging the execution
+ * @param {(...args: unknown[]) => void} onLoadCallback the callback to be executed
+ * @param {string} [name] optional name for the call, used mostly for logging the execution
* @param {number} priority optional priority to execute the callbacks in a specific order
* (default: 5, to leave room for the tracker default callback(s))
* @private
@@ -1209,7 +1295,9 @@ var useTracker = function useTracker() {
}
} else {
console.debug('[WEM] Trying to register context load callback, but no digitalData conf found, creating it and registering the callback: ' + (name ? name : 'Callback without name'));
- wem.digitalData = {};
+ wem.digitalData =
+ /** @type {DigitalData} */
+ {};
if (onLoadCallback) {
wem.digitalData.loadCallbacks = [];
@@ -1224,8 +1312,8 @@ var useTracker = function useTracker() {
/**
* Internal function for personalization specific callbacks (used for HTML dom manipulation once we get the context loaded)
- * @param {object} personalization the personalization
- * @param {function} callback the callback
+ * @param {Personalization} personalization the personalization
+ * @param {PersonalizationCallback} callback the callback
* @private
* @return {undefined}
*/
@@ -1242,7 +1330,9 @@ var useTracker = function useTracker() {
});
}
} else {
- wem.digitalData = {};
+ wem.digitalData =
+ /** @type {DigitalData} */
+ {};
wem.digitalData.personalizationCallback = wem.digitalData.personalizationCallback || [];
wem.digitalData.personalizationCallback.push({
personalization: personalization,
@@ -1250,17 +1340,20 @@ var useTracker = function useTracker() {
});
}
},
+ // eslint-disable-next-line valid-jsdoc
/**
* Build a simple Unomi object
* @param {string} itemId the itemId of the object
* @param {string} itemType the itemType of the object
- * @param {object} properties optional properties for the object
+ * @param {UnomiProperties} [properties] optional properties for the object
* @private
- * @return {object} the built Unomi JSON object
+ * @return {UnomiObject} the built Unomi JSON object
*/
_buildObject: function _buildObject(itemId, itemType) {
var properties = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
+
+ /** @type {UnomiObject} */
var object = {
scope: wem.digitalData.scope,
itemId: itemId,
@@ -1362,8 +1455,14 @@ var useTracker = function useTracker() {
if (search && search != '') {
// parse parameters
- var queryParams = [],
- param;
+ var queryParams =
+ /** @type {string[] & Record<string, string>} */
+
+ /** @type {unknown} */
+ [],
+
+ /** @type {string[]} */
+ param;
var queryParamPairs = search.slice(1).split('&');
for (var i = 0; i < queryParamPairs.length; i++) {
@@ -1394,13 +1493,15 @@ var useTracker = function useTracker() {
* this listener will automatically send the form event to Unomi, by parsing the HTML form data.
* (NOTE: the form listener only work for know forms to be watch due to tracked conditions)
*
- * @param {object} event the original HTML form submition event for the watch form.
+ * @param {SubmitEvent} event the original HTML form submition event for the watch form.
* @private
* @return {undefined}
*/
_formSubmitEventListener: function _formSubmitEventListener(event) {
console.debug('[WEM] Registering form event callback');
- var form = event.target;
+ var form =
+ /** @type {HTMLFormElement} */
+ event.target;
var formName = form.getAttribute('name') ? form.getAttribute('name') : form.getAttribute('id');
if (formName && wem.formNamesToWatch.indexOf(formName) > -1) {
@@ -1442,10 +1543,13 @@ var useTracker = function useTracker() {
* @return {object} the form data as JSON
*/
_extractFormData: function _extractFormData(form) {
+ /** @type {Record<string, string | string[]>} */
var params = {};
for (var i = 0; i < form.elements.length; i++) {
- var e = form.elements[i]; // ignore empty and undefined key (e.name)
+ var e =
+ /** @type {HTMLInputElement | HTMLSelectElement} */
+ form.elements[i]; // ignore empty and undefined key (e.name)
if (e.name) {
switch (e.nodeName) {
@@ -1461,6 +1565,7 @@ var useTracker = function useTracker() {
}
if (e.checked) {
+ /** @type {string[]} */
params[e.name].push(e.value);
}
}
@@ -1486,17 +1591,22 @@ var useTracker = function useTracker() {
break;
case 'SELECT':
- if (e.options && e.options[e.selectedIndex]) {
- if (e.multiple) {
- params[e.name] = [];
-
- for (var j = 0; j < e.options.length; j++) {
- if (e.options[j].selected) {
- params[e.name].push(e.options[j].value);
+ var s =
+ /** @type {HTMLSelectElement} */
+ e;
+
+ if (s.options && s.options[s.selectedIndex]) {
+ if (s.multiple) {
+ params[s.name] = [];
+
+ for (var j = 0; j < s.options.length; j++) {
+ if (s.options[j].selected) {
+ /** @type {string[]} */
+ params[s.name].push(s.options[j].value);
}
}
} else {
- params[e.name] = e.options[e.selectedIndex].value;
+ params[s.name] = s.options[s.selectedIndex].value;
}
}
@@ -1518,17 +1628,19 @@ var useTracker = function useTracker() {
if (wem.digitalData.sourceLocalIdentifierMap) {
var source = Object.keys(wem.digitalData.sourceLocalIdentifierMap).filter(function (source) {
return id.indexOf(source) > 0;
- });
+ }); // @ts-expect-error This code is broken, source is an array
+
return source ? id.replace(source, wem.digitalData.sourceLocalIdentifierMap[source]) : id;
}
return id;
},
+ // eslint-disable-next-line valid-jsdoc
/**
* Enable or disable tracking in current page
* @param {boolean} enable true will enable the tracking feature, otherwise they will be disabled
- * @param {function} callback an optional callback that can be used to perform additional logic based on enabling/disabling results
+ * @param {(enable: boolean) => void} [callback] an optional callback that can be used to perform additional logic based on enabling/disabling results
* @private
* @return {undefined}
*/
@@ -1560,10 +1672,11 @@ var useTracker = function useTracker() {
/**
* Utility function used to merge two JSON object together (arrays are concat for example)
- * @param {object} source the source object for merge
- * @param {object} target the target object for merge
+ * @template T
+ * @param {any} source the source object for merge
+ * @param {T} target the target object for merge
* @private
- * @return {object} the merged results
+ * @return {T} the merged results
*/
_deepMergeObjects: function _deepMergeObjects(source, target) {
if (!wem._isObject(target) || !wem._isObject(source)) {
@@ -1571,14 +1684,18 @@ var useTracker = function useTracker() {
}
Object.keys(source).forEach(function (key) {
+ // @ts-expect-error target cannot be indexed by key
var targetValue = target[key];
var sourceValue = source[key]; // concat arrays || merge objects || add new props
if (Array.isArray(targetValue) && Array.isArray(sourceValue)) {
+ // @ts-expect-error target cannot be indexed by key
target[key] = targetValue.concat(sourceValue);
} else if (wem._isObject(targetValue) && wem._isObject(sourceValue)) {
+ // @ts-expect-error target cannot be indexed by key
target[key] = wem._deepMergeObjects(sourceValue, Object.assign({}, targetValue));
} else {
+ // @ts-expect-error target cannot be indexed by key
target[key] = sourceValue;
}
});
diff --git a/dist/apache-unomi-tracker.cjs.js.map b/dist/apache-unomi-tracker.cjs.js.map
index 77972c0..21b7e7f 100644
--- a/dist/apache-unomi-tracker.cjs.js.map
+++ b/dist/apache-unomi-tracker.cjs.js.map
@@ -1 +1 @@
-{"version":3,"file":"apache-unomi-tracker.cjs.js","sources":["../src/apache-unomi-tracker.js"],"sourcesContent":["/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the [...]
\ No newline at end of file
+{"version":3,"file":"apache-unomi-tracker.cjs.js","sources":["../src/apache-unomi-tracker.js"],"sourcesContent":["/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the [...]
\ No newline at end of file
diff --git a/dist/apache-unomi-tracker.d.ts b/dist/apache-unomi-tracker.d.ts
index 2e9a537..8f42724 100644
--- a/dist/apache-unomi-tracker.d.ts
+++ b/dist/apache-unomi-tracker.d.ts
@@ -1,24 +1,43 @@
export function useTracker(): {
+ digitalData: DigitalData;
+ trackerProfileIdCookieName: string;
+ trackerSessionIdCookieName: string;
+ browserGeneratedSessionSuffix: string;
+ disableTrackedConditionsListeners: boolean;
+ activateWem: boolean;
+ contextServerCookieName: string;
+ contextServerUrl: string;
+ timeoutInMilliseconds: number;
+ formNamesToWatch: string[];
+ eventsPrevented: string[];
+ /** @type {string | null} */
+ sessionID: string | null;
+ fallback: boolean;
+ /** @type {any} */
+ cxs: any;
+ DOMLoaded: boolean;
+ /** @type {string | undefined} */
+ contextLoaded: string | undefined;
/**
* This function initialize the tracker
*
- * @param {object} digitalData config of the tracker
+ * @param {DigitalData} digitalData config of the tracker
* @returns {undefined}
*/
- initTracker: (digitalData: object) => undefined;
+ initTracker: (digitalData: DigitalData) => undefined;
/**
* This function start the tracker by loading the context in the page
* Note: that the tracker will start once the current DOM is complete loaded, using listener on current document: DOMContentLoaded
*
- * @param {object[]} digitalDataOverrides optional, list of digitalData extensions, they will be merged with original digitalData before context loading
+ * @param {Array<Partial<DigitalData>>} [digitalDataOverrides] optional, list of digitalData extensions, they will be merged with original digitalData before context loading
* @returns {undefined}
*/
- startTracker: (digitalDataOverrides?: object[]) => undefined;
+ startTracker: (digitalDataOverrides?: Array<Partial<DigitalData>>) => undefined;
/**
* get the current loaded context from Unomi, will be accessible only after loadContext() have been performed
- * @returns {object} loaded context
+ * @returns {any} loaded context
*/
- getLoadedContext: () => object;
+ getLoadedContext: () => any;
/**
* In case Unomi contains rules related to HTML forms in the current page.
* The logic is simple, in case a rule exists in Unomi targeting a form event within the current webpage path
@@ -36,25 +55,25 @@ export function useTracker(): {
/**
* This function will register a personalization
*
- * @param {object} personalization the personalization object
- * @param {object} variants the variants
- * @param {boolean} [ajax] Deprecated: Ajax rendering is not supported anymore
+ * @param {Personalization} personalization the personalization object
+ * @param {Record<string, Variant>} variants the variants
+ * @param {boolean} [ajax] Deprecated: Ajax rendering is not supported anymore (ignored)
* @param {function} [resultCallback] the callback to be executed after personalization resolved
* @returns {undefined}
*/
- registerPersonalizationObject: (personalization: object, variants: object, ajax?: boolean, resultCallback?: Function) => undefined;
+ registerPersonalizationObject: (personalization: Personalization, variants: Record<string, Variant>, ajax?: boolean, resultCallback?: Function) => undefined;
/**
* This function will register an optimization test or A/B test
*
* @param {string} optimizationTestNodeId the optimization test node id
- * @param {string} goalId the associated goal Id
- * @param {string} containerId the HTML container Id
- * @param {object} variants the variants
- * @param {boolean} [ajax] Deprecated: Ajax rendering is not supported anymore
- * @param {object} [variantsTraffic] the associated traffic allocation
+ * @param {string} goalId the associated goal Id (unused)
+ * @param {string} containerId the HTML container Id (unused)
+ * @param {Record<string, Variant>} variants the variants
+ * @param {boolean} [ajax] Deprecated: Ajax rendering is not supported anymore (unused)
+ * @param {Record<string, number>} [variantsTraffic] the associated traffic allocation
* @return {undefined}
*/
- registerOptimizationTest: (optimizationTestNodeId: string, goalId: string, containerId: string, variants: object, ajax?: boolean, variantsTraffic?: object) => undefined;
+ registerOptimizationTest: (optimizationTestNodeId: string, goalId: string, containerId: string, variants: Record<string, Variant>, ajax?: boolean, variantsTraffic?: Record<string, number>) => undefined;
/**
* This function is used to load the current context in the page
*
@@ -67,39 +86,46 @@ export function useTracker(): {
loadContext: (skipEvents?: boolean, invalidate?: boolean, forceReload?: boolean) => undefined;
/**
* This function will send an event to Apache Unomi
- * @param {object} event The event object to send, you can build it using wem.buildEvent(eventType, target, source)
- * @param {function} successCallback optional, will be executed in case of success
- * @param {function} errorCallback optional, will be executed in case of error
+ * @param {UnomiEvent} event The event object to send, you can build it using wem.buildEvent(eventType, target, source)
+ * @param {(xhr: XMLHttpRequest) => void} [successCallback] optional, will be executed in case of success
+ * @param {(xhr: XMLHttpRequest) => void} [errorCallback] optional, will be executed in case of error
* @return {undefined}
*/
- collectEvent: (event: object, successCallback?: Function, errorCallback?: Function) => undefined;
+ collectEvent: (event: UnomiEvent, successCallback?: (xhr: XMLHttpRequest) => void, errorCallback?: (xhr: XMLHttpRequest) => void) => undefined;
/**
* This function will send the events to Apache Unomi
*
- * @param {object} events Javascript object { events: [event1, event2] }
- * @param {function} successCallback optional, will be executed in case of success
- * @param {function} errorCallback optional, will be executed in case of error
+ * @param {{ sessionId?: string, events: Array<UnomiEvent> }} events Javascript object { events: [event1, event2] }
+ * @param {(xhr: XMLHttpRequest) => void} [successCallback] optional, will be executed in case of success
+ * @param {(xhr: XMLHttpRequest) => void} [errorCallback] optional, will be executed in case of error
* @return {undefined}
*/
- collectEvents: (events: object, successCallback?: Function, errorCallback?: Function) => undefined;
+ collectEvents: (events: {
+ sessionId?: string;
+ events: Array<UnomiEvent>;
+ }, successCallback?: (xhr: XMLHttpRequest) => void, errorCallback?: (xhr: XMLHttpRequest) => void) => undefined;
/**
* This function will build an event of type click and send it to Apache Unomi
*
- * @param {object} event javascript
+ * @param {Event & { target: HTMLElement & { name: string }}} event javascript
* @param {function} [successCallback] optional, will be executed if case of success
* @param {function} [errorCallback] optional, will be executed if case of error
* @return {undefined}
*/
- sendClickEvent: (event: object, successCallback?: Function, errorCallback?: Function) => undefined;
+ sendClickEvent: (event: Event & {
+ target: HTMLElement & {
+ name: string;
+ };
+ }, successCallback?: Function, errorCallback?: Function) => undefined;
/**
* This function will build an event of type video and send it to Apache Unomi
*
- * @param {object} event javascript
- * @param {function} [successCallback] optional, will be executed if case of success
- * @param {function} [errorCallback] optional, will be executed if case of error
+ * @param {Event} event javascript
+ * @param {(xhr: XMLHttpRequest) => void} [successCallback] optional, will be executed if case of success
+ * @param {(xhr: XMLHttpRequest) => void} [errorCallback] optional, will be executed if case of error
* @return {undefined}
*/
- sendVideoEvent: (event: object, successCallback?: Function, errorCallback?: Function) => undefined;
+ sendVideoEvent: (event: Event, successCallback?: (xhr: XMLHttpRequest) => void, errorCallback?: (xhr: XMLHttpRequest) => void) => undefined;
/**
* This function will invalidate the Apache Unomi session and profile,
* by removing the associated cookies, set the loaded context to undefined
@@ -111,50 +137,57 @@ export function useTracker(): {
* This function return the basic structure for an event, it must be adapted to your need
*
* @param {string} eventType The name of your event
- * @param {object} [target] The target object for your event can be build with wem.buildTarget(targetId, targetType, targetProperties)
- * @param {object} [source] The source object for your event can be build with wem.buildSource(sourceId, sourceType, sourceProperties)
- * @returns {object} the event
+ * @param {UnomiEvent["target"]} [target] The target object for your event can be build with wem.buildTarget(targetId, targetType, targetProperties)
+ * @param {UnomiEvent["source"]} [source] The source object for your event can be build with wem.buildSource(sourceId, sourceType, sourceProperties)
+ * @returns {UnomiEvent} the event
*/
- buildEvent: (eventType: string, target?: object, source?: object) => object;
+ buildEvent: (eventType: string, target?: UnomiEvent["target"], source?: UnomiEvent["source"]) => UnomiEvent;
/**
* This function return an event of type form
*
* @param {string} formName The HTML name of id of the form to use in the target of the event
- * @param {HTMLFormElement} form optional HTML form element, if provided will be used to extract the form fields and populate the form event
- * @returns {object} the form event
+ * @param {HTMLFormElement} [form] optional HTML form element, if provided will be used to extract the form fields and populate the form event
+ * @returns {UnomiEvent} the form event
+ */
+ buildFormEvent: (formName: string, form?: HTMLFormElement) => UnomiEvent;
+ /**
+ * @param {string} formName form name
+ * @param {HTMLFormElement} form form
+ * @param {string} term term
+ * @param {string} language language
+ * @returns {UnomiEvent} event
*/
- buildFormEvent: (formName: string, form?: HTMLFormElement) => object;
- buildSearchEvent: (formName: any, form: any, term: any, language: any) => object;
+ buildSearchEvent: (formName: string, form: HTMLFormElement, term: string, language: string) => UnomiEvent;
/**
* This function return the source object for a source of type page
*
- * @returns {object} the target page
+ * @returns {UnomiEvent["target"]} the target page
*/
- buildTargetPage: () => object;
+ buildTargetPage: () => UnomiEvent["target"];
/**
* This function return the source object for a source of type page
*
- * @returns {object} the source page
+ * @returns {UnomiEvent["source"]} the source page
*/
- buildSourcePage: () => object;
+ buildSourcePage: () => UnomiEvent["source"];
/**
* This function return the basic structure for the target of your event
*
* @param {string} targetId The ID of the target
* @param {string} targetType The type of the target
- * @param {object} [targetProperties] The optional properties of the target
- * @returns {object} the target
+ * @param {UnomiProperties} [targetProperties] The optional properties of the target
+ * @returns {UnomiEvent["target"]} the target
*/
- buildTarget: (targetId: string, targetType: string, targetProperties?: object) => object;
+ buildTarget: (targetId: string, targetType: string, targetProperties?: UnomiProperties) => UnomiEvent["target"];
/**
* This function return the basic structure for the source of your event
*
* @param {string} sourceId The ID of the source
* @param {string} sourceType The type of the source
- * @param {object} [sourceProperties] The optional properties of the source
- * @returns {object} the source
+ * @param {UnomiProperties} [sourceProperties] The optional properties of the source
+ * @returns {UnomiEvent["source"]} the source
*/
- buildSource: (sourceId: string, sourceType: string, sourceProperties?: object) => object;
+ buildSource: (sourceId: string, sourceType: string, sourceProperties?: UnomiProperties) => UnomiEvent["source"];
/*************************************/
/*************************************/
/**
@@ -170,9 +203,9 @@ export function useTracker(): {
* This is an utility function to get a cookie
*
* @param {string} cookieName name of the cookie to get
- * @returns {string} the value of the first cookie with the corresponding name or null if not found
+ * @returns {string | null} the value of the first cookie with the corresponding name or null if not found
*/
- getCookie: (cookieName: string) => string;
+ getCookie: (cookieName: string) => string | null;
/**
* This is an utility function to remove a cookie
*
@@ -183,10 +216,10 @@ export function useTracker(): {
/**
* This is an utility function to execute AJAX call
*
- * @param {object} options options of the request
+ * @param {AjaxOptions} options options of the request
* @return {undefined}
*/
- ajax: (options: object) => undefined;
+ ajax: (options: AjaxOptions) => undefined;
/**
* This is an utility function to generate a new UUID
*
@@ -195,10 +228,10 @@ export function useTracker(): {
generateGuid: () => string;
/**
* This is an utility function to check if the local storage is available or not
- * @param {string} type the type of storage to test
+ * @param {"sessionStorage" | "localStorage"} type the type of storage to test
* @returns {boolean} true in case storage is available, false otherwise
*/
- storageAvailable: (type: string) => boolean;
+ storageAvailable: (type: "sessionStorage" | "localStorage") => boolean;
/**
* Dispatch a JavaScript event in current HTML document
*
@@ -220,26 +253,26 @@ export function useTracker(): {
* This is an utility function to get current url parameter value
*
* @param {string} name, the name of the parameter
- * @returns {string} the value of the parameter
+ * @returns {string | null} the value of the parameter
*/
- getUrlParameter: (name: string) => string;
+ getUrlParameter: (name: string) => string | null;
/**
* convert the passed query string into JS object.
* @param {string} searchString The URL query string
- * @returns {object} converted URL params
+ * @returns {Record<string, Array<string | undefined> | string | undefined> | null} converted URL params
*/
- convertUrlParametersToObj: (searchString: string) => object;
+ convertUrlParametersToObj: (searchString: string) => Record<string, Array<string | undefined> | string | undefined> | null;
/*************************************/
/*************************************/
/**
* Used to override the default digitalData values,
* the result will impact directly the current instance wem.digitalData
*
- * @param {object[]} digitalDataOverrides list of overrides
+ * @param {Array<Partial<DigitalData>>} [digitalDataOverrides] list of overrides
* @private
* @return {undefined}
*/
- _handleDigitalDataOverrides: (digitalDataOverrides: object[]) => undefined;
+ _handleDigitalDataOverrides: (digitalDataOverrides?: Array<Partial<DigitalData>>) => undefined;
/**
* Check for tracked conditions in the current loaded context, and attach listeners for the known tracked condition types:
* - formEventCondition
@@ -266,10 +299,10 @@ export function useTracker(): {
/**
* build and dispatch JavaScript event in current HTML document for the given Unomi event (perso/opti)
* @private
- * @param {object} experienceUnomiEvent perso/opti Unomi event
+ * @param {UnomiEvent} experienceUnomiEvent perso/opti Unomi event
* @return {undefined}
*/
- _dispatchJSExperienceDisplayedEvent: (experienceUnomiEvent: object) => undefined;
+ _dispatchJSExperienceDisplayedEvent: (experienceUnomiEvent: UnomiEvent) => undefined;
/**
* Filter events in digitalData.events that would have the property: event.properties.doNotSendToUnomi
* The effect is directly stored in a new version of wem.digitalData.events
@@ -281,11 +314,11 @@ export function useTracker(): {
* Check if event is incomplete and complete what is missing:
* - source: if missing, use the current source page
* - scope: if missing, use the current scope
- * @param {object} event, the event to be checked
+ * @param {UnomiEvent} event, the event to be checked
* @private
- * @return {object} the complete event
+ * @return {UnomiEvent} the complete event
*/
- _completeEvent: (event: object) => object;
+ _completeEvent: (event: UnomiEvent) => UnomiEvent;
/**
* Register an event in the wem.digitalData.events.
* Registered event, will be sent automatically during the context loading process.
@@ -294,38 +327,38 @@ export function useTracker(): {
* in case the context is already loaded (check: wem.getLoadedContext()), then you should use: wem.collectEvent(s) functions
*
* @private
- * @param {object} event the Unomi event to be registered
+ * @param {UnomiEvent} event the Unomi event to be registered
* @param {boolean} unshift optional, if true, the event will be added at the beginning of the list otherwise at the end of the list. (default: false)
* @return {undefined}
*/
- _registerEvent: (event: object, unshift?: boolean) => undefined;
+ _registerEvent: (event: UnomiEvent, unshift?: boolean) => undefined;
/**
* This function allow for registering callback that will be executed once the context is loaded.
- * @param {function} onLoadCallback the callback to be executed
- * @param {string} name optional name for the call, used mostly for logging the execution
+ * @param {(...args: unknown[]) => void} onLoadCallback the callback to be executed
+ * @param {string} [name] optional name for the call, used mostly for logging the execution
* @param {number} priority optional priority to execute the callbacks in a specific order
* (default: 5, to leave room for the tracker default callback(s))
* @private
* @return {undefined}
*/
- _registerCallback: (onLoadCallback: Function, name?: string, priority?: number) => undefined;
+ _registerCallback: (onLoadCallback: (...args: unknown[]) => void, name?: string, priority?: number) => undefined;
/**
* Internal function for personalization specific callbacks (used for HTML dom manipulation once we get the context loaded)
- * @param {object} personalization the personalization
- * @param {function} callback the callback
+ * @param {Personalization} personalization the personalization
+ * @param {PersonalizationCallback} callback the callback
* @private
* @return {undefined}
*/
- _registerPersonalizationCallback: (personalization: object, callback: Function) => undefined;
+ _registerPersonalizationCallback: (personalization: Personalization, callback: PersonalizationCallback) => undefined;
/**
* Build a simple Unomi object
* @param {string} itemId the itemId of the object
* @param {string} itemType the itemType of the object
- * @param {object} properties optional properties for the object
+ * @param {UnomiProperties} [properties] optional properties for the object
* @private
- * @return {object} the built Unomi JSON object
+ * @return {UnomiObject} the built Unomi JSON object
*/
- _buildObject: (itemId: string, itemType: string, properties?: object) => object;
+ _buildObject: (itemId: string, itemType: string, properties?: UnomiProperties) => UnomiObject;
/**
* Main callback used once the Ajax context request succeed
* @param {XMLHttpRequest} xhr the request
@@ -358,11 +391,11 @@ export function useTracker(): {
* this listener will automatically send the form event to Unomi, by parsing the HTML form data.
* (NOTE: the form listener only work for know forms to be watch due to tracked conditions)
*
- * @param {object} event the original HTML form submition event for the watch form.
+ * @param {SubmitEvent} event the original HTML form submition event for the watch form.
* @private
* @return {undefined}
*/
- _formSubmitEventListener: (event: object) => undefined;
+ _formSubmitEventListener: (event: SubmitEvent) => undefined;
/**
* Utility function to extract data from an HTML form.
*
@@ -381,19 +414,20 @@ export function useTracker(): {
/**
* Enable or disable tracking in current page
* @param {boolean} enable true will enable the tracking feature, otherwise they will be disabled
- * @param {function} callback an optional callback that can be used to perform additional logic based on enabling/disabling results
+ * @param {(enable: boolean) => void} [callback] an optional callback that can be used to perform additional logic based on enabling/disabling results
* @private
* @return {undefined}
*/
- _enableWem: (enable: boolean, callback?: Function) => undefined;
+ _enableWem: (enable: boolean, callback?: (enable: boolean) => void) => undefined;
/**
* Utility function used to merge two JSON object together (arrays are concat for example)
- * @param {object} source the source object for merge
- * @param {object} target the target object for merge
+ * @template T
+ * @param {any} source the source object for merge
+ * @param {T} target the target object for merge
* @private
- * @return {object} the merged results
+ * @return {T} the merged results
*/
- _deepMergeObjects: (source: object, target: object) => object;
+ _deepMergeObjects: <T>(source: any, target: T) => T;
/**
* Utility function used to check if the given variable is a JavaScript object.
* @param {*} obj the variable to check
@@ -402,3 +436,11 @@ export function useTracker(): {
*/
_isObject: (obj: any) => boolean;
};
+import type { DigitalData } from "./types";
+import type { Personalization } from "./types";
+import type { Variant } from "./types";
+import type { UnomiEvent } from "./types";
+import type { UnomiProperties } from "./types";
+import type { AjaxOptions } from "./types";
+import type { PersonalizationCallback } from "./types";
+import type { UnomiObject } from "./types";
diff --git a/dist/apache-unomi-tracker.esm.js b/dist/apache-unomi-tracker.esm.js
index cb8170a..1f7d1d2 100644
--- a/dist/apache-unomi-tracker.esm.js
+++ b/dist/apache-unomi-tracker.esm.js
@@ -23,12 +23,45 @@ function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
+/** @import { AjaxOptions, DigitalData, UnomiEvent, Personalization, PersonalizationCallback, Variant, UnomiObject, UnomiProperties } from "./types" */
+
var useTracker = function useTracker() {
var wem = {
+ digitalData:
+ /** @type {DigitalData} */
+
+ /** @type {unknown} */
+ undefined,
+ trackerProfileIdCookieName: 'wem-profile-id',
+ trackerSessionIdCookieName: 'wem-session-id',
+ browserGeneratedSessionSuffix: '',
+ disableTrackedConditionsListeners: false,
+ activateWem: true,
+ contextServerCookieName: 'context-profile-id',
+ contextServerUrl: '',
+ timeoutInMilliseconds: 1500,
+ formNamesToWatch:
+ /** @type {string[]} */
+ [],
+ eventsPrevented:
+ /** @type {string[]} */
+ [],
+
+ /** @type {string | null} */
+ sessionID: null,
+ fallback: false,
+
+ /** @type {any} */
+ cxs: undefined,
+ DOMLoaded: false,
+
+ /** @type {string | undefined} */
+ contextLoaded: undefined,
+
/**
* This function initialize the tracker
*
- * @param {object} digitalData config of the tracker
+ * @param {DigitalData} digitalData config of the tracker
* @returns {undefined}
*/
initTracker: function initTracker(digitalData) {
@@ -36,7 +69,7 @@ var useTracker = function useTracker() {
wem.trackerProfileIdCookieName = wem.digitalData.wemInitConfig.trackerProfileIdCookieName ? wem.digitalData.wemInitConfig.trackerProfileIdCookieName : 'wem-profile-id';
wem.trackerSessionIdCookieName = wem.digitalData.wemInitConfig.trackerSessionIdCookieName ? wem.digitalData.wemInitConfig.trackerSessionIdCookieName : 'wem-session-id';
wem.browserGeneratedSessionSuffix = wem.digitalData.wemInitConfig.browserGeneratedSessionSuffix ? wem.digitalData.wemInitConfig.browserGeneratedSessionSuffix : '';
- wem.disableTrackedConditionsListeners = wem.digitalData.wemInitConfig.disableTrackedConditionsListeners;
+ wem.disableTrackedConditionsListeners = wem.digitalData.wemInitConfig.disableTrackedConditionsListeners || false;
wem.activateWem = wem.digitalData.wemInitConfig.activateWem;
var _wem$digitalData$wemI = wem.digitalData.wemInitConfig,
contextServerUrl = _wem$digitalData$wemI.contextServerUrl,
@@ -62,7 +95,7 @@ var useTracker = function useTracker() {
* This function start the tracker by loading the context in the page
* Note: that the tracker will start once the current DOM is complete loaded, using listener on current document: DOMContentLoaded
*
- * @param {object[]} digitalDataOverrides optional, list of digitalData extensions, they will be merged with original digitalData before context loading
+ * @param {Array<Partial<DigitalData>>} [digitalDataOverrides] optional, list of digitalData extensions, they will be merged with original digitalData before context loading
* @returns {undefined}
*/
startTracker: function startTracker() {
@@ -143,7 +176,7 @@ var useTracker = function useTracker() {
/**
* get the current loaded context from Unomi, will be accessible only after loadContext() have been performed
- * @returns {object} loaded context
+ * @returns {any} loaded context
*/
getLoadedContext: function getLoadedContext() {
return wem.cxs;
@@ -172,9 +205,9 @@ var useTracker = function useTracker() {
/**
* This function will register a personalization
*
- * @param {object} personalization the personalization object
- * @param {object} variants the variants
- * @param {boolean} [ajax] Deprecated: Ajax rendering is not supported anymore
+ * @param {Personalization} personalization the personalization object
+ * @param {Record<string, Variant>} variants the variants
+ * @param {boolean} [ajax] Deprecated: Ajax rendering is not supported anymore (ignored)
* @param {function} [resultCallback] the callback to be executed after personalization resolved
* @returns {undefined}
*/
@@ -213,10 +246,15 @@ var useTracker = function useTracker() {
resultCallback(successfulFilters, selectedFilter);
} else {
if (selectedFilter) {
- var targetFilters = document.getElementById(target).children;
+ var targetFilters =
+ /** @type {HTMLElement} */
+ document.getElementById(target).children;
for (var fIndex in targetFilters) {
- var filter = targetFilters.item(fIndex);
+ // @ts-expect-error The indexing is unsafe
+ var filter =
+ /** @type {HTMLElement | null} */
+ targetFilters.item(fIndex);
if (filter) {
filter.style.display = filter.id === selectedFilter.content ? '' : 'none';
@@ -226,10 +264,12 @@ var useTracker = function useTracker() {
if (selectedFilter.event) {
// we now add control group information to event if the user is in the control group.
if (inControlGroup) {
- console.debug('[WEM] Profile is in control group for target: ' + target + ', adding to personalization event...');
- selectedFilter.event.target.properties.inControlGroup = true;
+ console.debug('[WEM] Profile is in control group for target: ' + target + ', adding to personalization event...'); // @ts-expect-error The properties are not defined
+
+ selectedFilter.event.target.properties.inControlGroup = true; // @ts-expect-error The properties are not defined
if (selectedFilter.event.target.properties.variants) {
+ // @ts-expect-error The properties are not defined
selectedFilter.event.target.properties.variants.forEach(function (variant) {
return variant.inControlGroup = true;
});
@@ -246,10 +286,15 @@ var useTracker = function useTracker() {
wem._dispatchJSExperienceDisplayedEvent(selectedFilter.event);
}
} else {
- var elements = document.getElementById(target).children;
+ var elements =
+ /** @type {HTMLElement} */
+ document.getElementById(target).children;
for (var eIndex in elements) {
- var el = elements.item(eIndex);
+ // @ts-expect-error The indexing is unsafe
+ var el =
+ /** @type {HTMLElement} */
+ elements.item(eIndex);
el.style.display = 'none';
}
}
@@ -261,11 +306,11 @@ var useTracker = function useTracker() {
* This function will register an optimization test or A/B test
*
* @param {string} optimizationTestNodeId the optimization test node id
- * @param {string} goalId the associated goal Id
- * @param {string} containerId the HTML container Id
- * @param {object} variants the variants
- * @param {boolean} [ajax] Deprecated: Ajax rendering is not supported anymore
- * @param {object} [variantsTraffic] the associated traffic allocation
+ * @param {string} goalId the associated goal Id (unused)
+ * @param {string} containerId the HTML container Id (unused)
+ * @param {Record<string, Variant>} variants the variants
+ * @param {boolean} [ajax] Deprecated: Ajax rendering is not supported anymore (unused)
+ * @param {Record<string, number>} [variantsTraffic] the associated traffic allocation
* @return {undefined}
*/
registerOptimizationTest: function registerOptimizationTest(optimizationTestNodeId, goalId, containerId, variants, ajax, variantsTraffic) {
@@ -301,12 +346,18 @@ var useTracker = function useTracker() {
}
if (wem.storageAvailable('sessionStorage')) {
- sessionStorage.setItem(optimizationTestNodeId, selectedVariantId);
+ sessionStorage.setItem(optimizationTestNodeId,
+ /** @type {string} */
+ selectedVariantId);
} else {
- wem.setCookie('selectedVariantId', selectedVariantId, 1);
+ wem.setCookie('selectedVariantId',
+ /** @type {string} */
+ selectedVariantId, 1);
}
- var variant = variants[selectedVariantId]; // spread event to unomi
+ var variant = variants[
+ /** @type {string} */
+ selectedVariantId]; // spread event to unomi
if (variant.event) {
wem._registerEvent(wem._completeEvent(variant.event));
@@ -319,6 +370,8 @@ var useTracker = function useTracker() {
window.optimizedContentAreas[optimizationTestNodeId].selectedVariant = selectedVariantId;
} // display the good variant
+ /** @type {HTMLElement} */
+
document.getElementById(variants[selectedVariantId].content).style.display = '';
}
@@ -342,6 +395,8 @@ var useTracker = function useTracker() {
console.log('Context already requested by', wem.contextLoaded);
return;
}
+ /** @type {Record<string, unknown>} */
+
var jsonData = {
requiredProfileProperties: wem.digitalData.wemInitConfig.requiredProfileProperties,
@@ -376,6 +431,7 @@ var useTracker = function useTracker() {
// Use text/plain to avoid CORS preflight
jsonData: jsonData,
dataType: 'application/json',
+ // @ts-expect-error This parameter does not exist
invalidate: invalidate,
success: wem._onSuccess,
error: function error() {
@@ -385,12 +441,13 @@ var useTracker = function useTracker() {
wem.contextLoaded = Error().stack;
console.info('[WEM] context loading...');
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function will send an event to Apache Unomi
- * @param {object} event The event object to send, you can build it using wem.buildEvent(eventType, target, source)
- * @param {function} successCallback optional, will be executed in case of success
- * @param {function} errorCallback optional, will be executed in case of error
+ * @param {UnomiEvent} event The event object to send, you can build it using wem.buildEvent(eventType, target, source)
+ * @param {(xhr: XMLHttpRequest) => void} [successCallback] optional, will be executed in case of success
+ * @param {(xhr: XMLHttpRequest) => void} [errorCallback] optional, will be executed in case of error
* @return {undefined}
*/
collectEvent: function collectEvent(event) {
@@ -400,13 +457,14 @@ var useTracker = function useTracker() {
events: [event]
}, successCallback, errorCallback);
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function will send the events to Apache Unomi
*
- * @param {object} events Javascript object { events: [event1, event2] }
- * @param {function} successCallback optional, will be executed in case of success
- * @param {function} errorCallback optional, will be executed in case of error
+ * @param {{ sessionId?: string, events: Array<UnomiEvent> }} events Javascript object { events: [event1, event2] }
+ * @param {(xhr: XMLHttpRequest) => void} [successCallback] optional, will be executed in case of success
+ * @param {(xhr: XMLHttpRequest) => void} [errorCallback] optional, will be executed in case of error
* @return {undefined}
*/
collectEvents: function collectEvents(events) {
@@ -432,11 +490,12 @@ var useTracker = function useTracker() {
error: errorCallback
});
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function will build an event of type click and send it to Apache Unomi
*
- * @param {object} event javascript
+ * @param {Event & { target: HTMLElement & { name: string }}} event javascript
* @param {function} [successCallback] optional, will be executed if case of success
* @param {function} [errorCallback] optional, will be executed if case of error
* @return {undefined}
@@ -477,20 +536,23 @@ var useTracker = function useTracker() {
}
}
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function will build an event of type video and send it to Apache Unomi
*
- * @param {object} event javascript
- * @param {function} [successCallback] optional, will be executed if case of success
- * @param {function} [errorCallback] optional, will be executed if case of error
+ * @param {Event} event javascript
+ * @param {(xhr: XMLHttpRequest) => void} [successCallback] optional, will be executed if case of success
+ * @param {(xhr: XMLHttpRequest) => void} [errorCallback] optional, will be executed if case of error
* @return {undefined}
*/
sendVideoEvent: function sendVideoEvent(event) {
var successCallback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
var errorCallback = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
console.debug('[WEM] catching video event');
- var videoEvent = wem.buildEvent('video', wem.buildTarget(event.target.id, 'video', {
+ var videoEvent = wem.buildEvent('video', wem.buildTarget(
+ /** @type {HTMLElement} */
+ event.target.id, 'video', {
action: event.type
}), wem.buildSourcePage());
wem.collectEvent(videoEvent, function (xhr) {
@@ -522,16 +584,18 @@ var useTracker = function useTracker() {
wem.removeCookie(wem.trackerProfileIdCookieName);
wem.cxs = undefined;
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function return the basic structure for an event, it must be adapted to your need
*
* @param {string} eventType The name of your event
- * @param {object} [target] The target object for your event can be build with wem.buildTarget(targetId, targetType, targetProperties)
- * @param {object} [source] The source object for your event can be build with wem.buildSource(sourceId, sourceType, sourceProperties)
- * @returns {object} the event
+ * @param {UnomiEvent["target"]} [target] The target object for your event can be build with wem.buildTarget(targetId, targetType, targetProperties)
+ * @param {UnomiEvent["source"]} [source] The source object for your event can be build with wem.buildSource(sourceId, sourceType, sourceProperties)
+ * @returns {UnomiEvent} the event
*/
buildEvent: function buildEvent(eventType, target, source) {
+ /** @type {UnomiEvent} */
var event = {
eventType: eventType,
scope: wem.digitalData.scope
@@ -552,8 +616,8 @@ var useTracker = function useTracker() {
* This function return an event of type form
*
* @param {string} formName The HTML name of id of the form to use in the target of the event
- * @param {HTMLFormElement} form optional HTML form element, if provided will be used to extract the form fields and populate the form event
- * @returns {object} the form event
+ * @param {HTMLFormElement} [form] optional HTML form element, if provided will be used to extract the form fields and populate the form event
+ * @returns {UnomiEvent} the form event
*/
buildFormEvent: function buildFormEvent(formName) {
var form = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
@@ -563,6 +627,14 @@ var useTracker = function useTracker() {
};
return formEvent;
},
+
+ /**
+ * @param {string} formName form name
+ * @param {HTMLFormElement} form form
+ * @param {string} term term
+ * @param {string} language language
+ * @returns {UnomiEvent} event
+ */
buildSearchEvent: function buildSearchEvent(formName, form, term, language) {
var searchEvent = wem.buildEvent('search', wem.buildTarget(formName, 'search'), wem.buildSourcePage());
searchEvent.flattenedProperties = {
@@ -572,49 +644,54 @@ var useTracker = function useTracker() {
originForm: formName,
language: language || 'en',
keyword: term,
+ // @ts-expect-error There is no way this is properly defined
origin: searchEvent.source.properties.pageInfo.pagePath
};
return searchEvent;
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function return the source object for a source of type page
*
- * @returns {object} the target page
+ * @returns {UnomiEvent["target"]} the target page
*/
buildTargetPage: function buildTargetPage() {
return wem.buildTarget(wem.digitalData.page.pageInfo.pageID, 'page', wem.digitalData.page);
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function return the source object for a source of type page
*
- * @returns {object} the source page
+ * @returns {UnomiEvent["source"]} the source page
*/
buildSourcePage: function buildSourcePage() {
return wem.buildSource(wem.digitalData.page.pageInfo.pageID, 'page', wem.digitalData.page);
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function return the basic structure for the target of your event
*
* @param {string} targetId The ID of the target
* @param {string} targetType The type of the target
- * @param {object} [targetProperties] The optional properties of the target
- * @returns {object} the target
+ * @param {UnomiProperties} [targetProperties] The optional properties of the target
+ * @returns {UnomiEvent["target"]} the target
*/
buildTarget: function buildTarget(targetId, targetType) {
var targetProperties = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
return wem._buildObject(targetId, targetType, targetProperties);
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function return the basic structure for the source of your event
*
* @param {string} sourceId The ID of the source
* @param {string} sourceType The type of the source
- * @param {object} [sourceProperties] The optional properties of the source
- * @returns {object} the source
+ * @param {UnomiProperties} [sourceProperties] The optional properties of the source
+ * @returns {UnomiEvent["source"]} the source
*/
buildSource: function buildSource(sourceId, sourceType) {
var sourceProperties = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
@@ -652,7 +729,7 @@ var useTracker = function useTracker() {
* This is an utility function to get a cookie
*
* @param {string} cookieName name of the cookie to get
- * @returns {string} the value of the first cookie with the corresponding name or null if not found
+ * @returns {string | null} the value of the first cookie with the corresponding name or null if not found
*/
getCookie: function getCookie(cookieName) {
var name = cookieName + '=';
@@ -687,7 +764,7 @@ var useTracker = function useTracker() {
/**
* This is an utility function to execute AJAX call
*
- * @param {object} options options of the request
+ * @param {AjaxOptions} options options of the request
* @return {undefined}
*/
ajax: function ajax(options) {
@@ -777,7 +854,7 @@ var useTracker = function useTracker() {
/**
* This is an utility function to check if the local storage is available or not
- * @param {string} type the type of storage to test
+ * @param {"sessionStorage" | "localStorage"} type the type of storage to test
* @returns {boolean} true in case storage is available, false otherwise
*/
storageAvailable: function storageAvailable(type) {
@@ -825,7 +902,7 @@ var useTracker = function useTracker() {
* This is an utility function to get current url parameter value
*
* @param {string} name, the name of the parameter
- * @returns {string} the value of the parameter
+ * @returns {string | null} the value of the parameter
*/
getUrlParameter: function getUrlParameter(name) {
name = name.replace(/[[]/, '\\[').replace(/[\]]/, '\\]');
@@ -837,7 +914,7 @@ var useTracker = function useTracker() {
/**
* convert the passed query string into JS object.
* @param {string} searchString The URL query string
- * @returns {object} converted URL params
+ * @returns {Record<string, Array<string | undefined> | string | undefined> | null} converted URL params
*/
convertUrlParametersToObj: function convertUrlParametersToObj(searchString) {
if (!searchString) {
@@ -869,7 +946,9 @@ var useTracker = function useTracker() {
}
return result;
- }, {});
+ },
+ /** @type Record<string, Array<string | undefined> | string | undefined> */
+ {});
},
/*************************************/
@@ -882,7 +961,7 @@ var useTracker = function useTracker() {
* Used to override the default digitalData values,
* the result will impact directly the current instance wem.digitalData
*
- * @param {object[]} digitalDataOverrides list of overrides
+ * @param {Array<Partial<DigitalData>>} [digitalDataOverrides] list of overrides
* @private
* @return {undefined}
*/
@@ -976,6 +1055,7 @@ var useTracker = function useTracker() {
var click = document.getElementById(clickIdName) || document.getElementById(wem._resolveId(clickIdName)) ? document.getElementById(clickIdName) || document.getElementById(wem._resolveId(clickIdName)) : document.getElementsByName(clickIdName)[0];
if (click) {
+ // @ts-expect-error The types will never match
click.addEventListener('click', wem.sendClickEvent);
console.debug('[WEM] Watching click ' + clickIdName);
} else {
@@ -1038,11 +1118,12 @@ var useTracker = function useTracker() {
/**
* build and dispatch JavaScript event in current HTML document for the given Unomi event (perso/opti)
* @private
- * @param {object} experienceUnomiEvent perso/opti Unomi event
+ * @param {UnomiEvent} experienceUnomiEvent perso/opti Unomi event
* @return {undefined}
*/
_dispatchJSExperienceDisplayedEvent: function _dispatchJSExperienceDisplayedEvent(experienceUnomiEvent) {
if (!wem.fallback && experienceUnomiEvent && experienceUnomiEvent.target && experienceUnomiEvent.target.properties && experienceUnomiEvent.target.properties.variants && experienceUnomiEvent.target.properties.variants.length > 0) {
+ /** @type {Record<string, string | undefined>} */
var typeMapper = {
optimizationTestEvent: 'optimization',
personalizationEvent: 'personalization'
@@ -1054,6 +1135,8 @@ var useTracker = function useTracker() {
try {
for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
var variant = _step4.value;
+
+ /** @type {any} */
var jsEventDetail = {
id: variant.id,
name: variant.systemName,
@@ -1113,9 +1196,9 @@ var useTracker = function useTracker() {
* Check if event is incomplete and complete what is missing:
* - source: if missing, use the current source page
* - scope: if missing, use the current scope
- * @param {object} event, the event to be checked
+ * @param {UnomiEvent} event, the event to be checked
* @private
- * @return {object} the complete event
+ * @return {UnomiEvent} the complete event
*/
_completeEvent: function _completeEvent(event) {
if (!event.source) {
@@ -1141,7 +1224,7 @@ var useTracker = function useTracker() {
* in case the context is already loaded (check: wem.getLoadedContext()), then you should use: wem.collectEvent(s) functions
*
* @private
- * @param {object} event the Unomi event to be registered
+ * @param {UnomiEvent} event the Unomi event to be registered
* @param {boolean} unshift optional, if true, the event will be added at the beginning of the list otherwise at the end of the list. (default: false)
* @return {undefined}
*/
@@ -1154,7 +1237,9 @@ var useTracker = function useTracker() {
return;
}
} else {
- wem.digitalData = {};
+ wem.digitalData =
+ /** @type {DigitalData} */
+ {};
}
wem.digitalData.events = wem.digitalData.events || [];
@@ -1165,11 +1250,12 @@ var useTracker = function useTracker() {
wem.digitalData.events.push(event);
}
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function allow for registering callback that will be executed once the context is loaded.
- * @param {function} onLoadCallback the callback to be executed
- * @param {string} name optional name for the call, used mostly for logging the execution
+ * @param {(...args: unknown[]) => void} onLoadCallback the callback to be executed
+ * @param {string} [name] optional name for the call, used mostly for logging the execution
* @param {number} priority optional priority to execute the callbacks in a specific order
* (default: 5, to leave room for the tracker default callback(s))
* @private
@@ -1201,7 +1287,9 @@ var useTracker = function useTracker() {
}
} else {
console.debug('[WEM] Trying to register context load callback, but no digitalData conf found, creating it and registering the callback: ' + (name ? name : 'Callback without name'));
- wem.digitalData = {};
+ wem.digitalData =
+ /** @type {DigitalData} */
+ {};
if (onLoadCallback) {
wem.digitalData.loadCallbacks = [];
@@ -1216,8 +1304,8 @@ var useTracker = function useTracker() {
/**
* Internal function for personalization specific callbacks (used for HTML dom manipulation once we get the context loaded)
- * @param {object} personalization the personalization
- * @param {function} callback the callback
+ * @param {Personalization} personalization the personalization
+ * @param {PersonalizationCallback} callback the callback
* @private
* @return {undefined}
*/
@@ -1234,7 +1322,9 @@ var useTracker = function useTracker() {
});
}
} else {
- wem.digitalData = {};
+ wem.digitalData =
+ /** @type {DigitalData} */
+ {};
wem.digitalData.personalizationCallback = wem.digitalData.personalizationCallback || [];
wem.digitalData.personalizationCallback.push({
personalization: personalization,
@@ -1242,17 +1332,20 @@ var useTracker = function useTracker() {
});
}
},
+ // eslint-disable-next-line valid-jsdoc
/**
* Build a simple Unomi object
* @param {string} itemId the itemId of the object
* @param {string} itemType the itemType of the object
- * @param {object} properties optional properties for the object
+ * @param {UnomiProperties} [properties] optional properties for the object
* @private
- * @return {object} the built Unomi JSON object
+ * @return {UnomiObject} the built Unomi JSON object
*/
_buildObject: function _buildObject(itemId, itemType) {
var properties = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
+
+ /** @type {UnomiObject} */
var object = {
scope: wem.digitalData.scope,
itemId: itemId,
@@ -1354,8 +1447,14 @@ var useTracker = function useTracker() {
if (search && search != '') {
// parse parameters
- var queryParams = [],
- param;
+ var queryParams =
+ /** @type {string[] & Record<string, string>} */
+
+ /** @type {unknown} */
+ [],
+
+ /** @type {string[]} */
+ param;
var queryParamPairs = search.slice(1).split('&');
for (var i = 0; i < queryParamPairs.length; i++) {
@@ -1386,13 +1485,15 @@ var useTracker = function useTracker() {
* this listener will automatically send the form event to Unomi, by parsing the HTML form data.
* (NOTE: the form listener only work for know forms to be watch due to tracked conditions)
*
- * @param {object} event the original HTML form submition event for the watch form.
+ * @param {SubmitEvent} event the original HTML form submition event for the watch form.
* @private
* @return {undefined}
*/
_formSubmitEventListener: function _formSubmitEventListener(event) {
console.debug('[WEM] Registering form event callback');
- var form = event.target;
+ var form =
+ /** @type {HTMLFormElement} */
+ event.target;
var formName = form.getAttribute('name') ? form.getAttribute('name') : form.getAttribute('id');
if (formName && wem.formNamesToWatch.indexOf(formName) > -1) {
@@ -1434,10 +1535,13 @@ var useTracker = function useTracker() {
* @return {object} the form data as JSON
*/
_extractFormData: function _extractFormData(form) {
+ /** @type {Record<string, string | string[]>} */
var params = {};
for (var i = 0; i < form.elements.length; i++) {
- var e = form.elements[i]; // ignore empty and undefined key (e.name)
+ var e =
+ /** @type {HTMLInputElement | HTMLSelectElement} */
+ form.elements[i]; // ignore empty and undefined key (e.name)
if (e.name) {
switch (e.nodeName) {
@@ -1453,6 +1557,7 @@ var useTracker = function useTracker() {
}
if (e.checked) {
+ /** @type {string[]} */
params[e.name].push(e.value);
}
}
@@ -1478,17 +1583,22 @@ var useTracker = function useTracker() {
break;
case 'SELECT':
- if (e.options && e.options[e.selectedIndex]) {
- if (e.multiple) {
- params[e.name] = [];
-
- for (var j = 0; j < e.options.length; j++) {
- if (e.options[j].selected) {
- params[e.name].push(e.options[j].value);
+ var s =
+ /** @type {HTMLSelectElement} */
+ e;
+
+ if (s.options && s.options[s.selectedIndex]) {
+ if (s.multiple) {
+ params[s.name] = [];
+
+ for (var j = 0; j < s.options.length; j++) {
+ if (s.options[j].selected) {
+ /** @type {string[]} */
+ params[s.name].push(s.options[j].value);
}
}
} else {
- params[e.name] = e.options[e.selectedIndex].value;
+ params[s.name] = s.options[s.selectedIndex].value;
}
}
@@ -1510,17 +1620,19 @@ var useTracker = function useTracker() {
if (wem.digitalData.sourceLocalIdentifierMap) {
var source = Object.keys(wem.digitalData.sourceLocalIdentifierMap).filter(function (source) {
return id.indexOf(source) > 0;
- });
+ }); // @ts-expect-error This code is broken, source is an array
+
return source ? id.replace(source, wem.digitalData.sourceLocalIdentifierMap[source]) : id;
}
return id;
},
+ // eslint-disable-next-line valid-jsdoc
/**
* Enable or disable tracking in current page
* @param {boolean} enable true will enable the tracking feature, otherwise they will be disabled
- * @param {function} callback an optional callback that can be used to perform additional logic based on enabling/disabling results
+ * @param {(enable: boolean) => void} [callback] an optional callback that can be used to perform additional logic based on enabling/disabling results
* @private
* @return {undefined}
*/
@@ -1552,10 +1664,11 @@ var useTracker = function useTracker() {
/**
* Utility function used to merge two JSON object together (arrays are concat for example)
- * @param {object} source the source object for merge
- * @param {object} target the target object for merge
+ * @template T
+ * @param {any} source the source object for merge
+ * @param {T} target the target object for merge
* @private
- * @return {object} the merged results
+ * @return {T} the merged results
*/
_deepMergeObjects: function _deepMergeObjects(source, target) {
if (!wem._isObject(target) || !wem._isObject(source)) {
@@ -1563,14 +1676,18 @@ var useTracker = function useTracker() {
}
Object.keys(source).forEach(function (key) {
+ // @ts-expect-error target cannot be indexed by key
var targetValue = target[key];
var sourceValue = source[key]; // concat arrays || merge objects || add new props
if (Array.isArray(targetValue) && Array.isArray(sourceValue)) {
+ // @ts-expect-error target cannot be indexed by key
target[key] = targetValue.concat(sourceValue);
} else if (wem._isObject(targetValue) && wem._isObject(sourceValue)) {
+ // @ts-expect-error target cannot be indexed by key
target[key] = wem._deepMergeObjects(sourceValue, Object.assign({}, targetValue));
} else {
+ // @ts-expect-error target cannot be indexed by key
target[key] = sourceValue;
}
});
diff --git a/dist/apache-unomi-tracker.esm.js.map b/dist/apache-unomi-tracker.esm.js.map
index fb04288..14655b2 100644
--- a/dist/apache-unomi-tracker.esm.js.map
+++ b/dist/apache-unomi-tracker.esm.js.map
@@ -1 +1 @@
-{"version":3,"file":"apache-unomi-tracker.esm.js","sources":["../src/apache-unomi-tracker.js"],"sourcesContent":["/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the [...]
\ No newline at end of file
+{"version":3,"file":"apache-unomi-tracker.esm.js","sources":["../src/apache-unomi-tracker.js"],"sourcesContent":["/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the [...]
\ No newline at end of file
diff --git a/dist/apache-unomi-tracker.umd.js b/dist/apache-unomi-tracker.umd.js
index 8d9434e..c7605fe 100644
--- a/dist/apache-unomi-tracker.umd.js
+++ b/dist/apache-unomi-tracker.umd.js
@@ -1678,12 +1678,45 @@
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
+ /** @import { AjaxOptions, DigitalData, UnomiEvent, Personalization, PersonalizationCallback, Variant, UnomiObject, UnomiProperties } from "./types" */
+
var useTracker = function useTracker() {
var wem = {
+ digitalData:
+ /** @type {DigitalData} */
+
+ /** @type {unknown} */
+ undefined,
+ trackerProfileIdCookieName: 'wem-profile-id',
+ trackerSessionIdCookieName: 'wem-session-id',
+ browserGeneratedSessionSuffix: '',
+ disableTrackedConditionsListeners: false,
+ activateWem: true,
+ contextServerCookieName: 'context-profile-id',
+ contextServerUrl: '',
+ timeoutInMilliseconds: 1500,
+ formNamesToWatch:
+ /** @type {string[]} */
+ [],
+ eventsPrevented:
+ /** @type {string[]} */
+ [],
+
+ /** @type {string | null} */
+ sessionID: null,
+ fallback: false,
+
+ /** @type {any} */
+ cxs: undefined,
+ DOMLoaded: false,
+
+ /** @type {string | undefined} */
+ contextLoaded: undefined,
+
/**
* This function initialize the tracker
*
- * @param {object} digitalData config of the tracker
+ * @param {DigitalData} digitalData config of the tracker
* @returns {undefined}
*/
initTracker: function initTracker(digitalData) {
@@ -1691,7 +1724,7 @@
wem.trackerProfileIdCookieName = wem.digitalData.wemInitConfig.trackerProfileIdCookieName ? wem.digitalData.wemInitConfig.trackerProfileIdCookieName : 'wem-profile-id';
wem.trackerSessionIdCookieName = wem.digitalData.wemInitConfig.trackerSessionIdCookieName ? wem.digitalData.wemInitConfig.trackerSessionIdCookieName : 'wem-session-id';
wem.browserGeneratedSessionSuffix = wem.digitalData.wemInitConfig.browserGeneratedSessionSuffix ? wem.digitalData.wemInitConfig.browserGeneratedSessionSuffix : '';
- wem.disableTrackedConditionsListeners = wem.digitalData.wemInitConfig.disableTrackedConditionsListeners;
+ wem.disableTrackedConditionsListeners = wem.digitalData.wemInitConfig.disableTrackedConditionsListeners || false;
wem.activateWem = wem.digitalData.wemInitConfig.activateWem;
var _wem$digitalData$wemI = wem.digitalData.wemInitConfig,
contextServerUrl = _wem$digitalData$wemI.contextServerUrl,
@@ -1717,7 +1750,7 @@
* This function start the tracker by loading the context in the page
* Note: that the tracker will start once the current DOM is complete loaded, using listener on current document: DOMContentLoaded
*
- * @param {object[]} digitalDataOverrides optional, list of digitalData extensions, they will be merged with original digitalData before context loading
+ * @param {Array<Partial<DigitalData>>} [digitalDataOverrides] optional, list of digitalData extensions, they will be merged with original digitalData before context loading
* @returns {undefined}
*/
startTracker: function startTracker() {
@@ -1798,7 +1831,7 @@
/**
* get the current loaded context from Unomi, will be accessible only after loadContext() have been performed
- * @returns {object} loaded context
+ * @returns {any} loaded context
*/
getLoadedContext: function getLoadedContext() {
return wem.cxs;
@@ -1827,9 +1860,9 @@
/**
* This function will register a personalization
*
- * @param {object} personalization the personalization object
- * @param {object} variants the variants
- * @param {boolean} [ajax] Deprecated: Ajax rendering is not supported anymore
+ * @param {Personalization} personalization the personalization object
+ * @param {Record<string, Variant>} variants the variants
+ * @param {boolean} [ajax] Deprecated: Ajax rendering is not supported anymore (ignored)
* @param {function} [resultCallback] the callback to be executed after personalization resolved
* @returns {undefined}
*/
@@ -1868,10 +1901,15 @@
resultCallback(successfulFilters, selectedFilter);
} else {
if (selectedFilter) {
- var targetFilters = document.getElementById(target).children;
+ var targetFilters =
+ /** @type {HTMLElement} */
+ document.getElementById(target).children;
for (var fIndex in targetFilters) {
- var filter = targetFilters.item(fIndex);
+ // @ts-expect-error The indexing is unsafe
+ var filter =
+ /** @type {HTMLElement | null} */
+ targetFilters.item(fIndex);
if (filter) {
filter.style.display = filter.id === selectedFilter.content ? '' : 'none';
@@ -1881,10 +1919,12 @@
if (selectedFilter.event) {
// we now add control group information to event if the user is in the control group.
if (inControlGroup) {
- console.debug('[WEM] Profile is in control group for target: ' + target + ', adding to personalization event...');
- selectedFilter.event.target.properties.inControlGroup = true;
+ console.debug('[WEM] Profile is in control group for target: ' + target + ', adding to personalization event...'); // @ts-expect-error The properties are not defined
+
+ selectedFilter.event.target.properties.inControlGroup = true; // @ts-expect-error The properties are not defined
if (selectedFilter.event.target.properties.variants) {
+ // @ts-expect-error The properties are not defined
selectedFilter.event.target.properties.variants.forEach(function (variant) {
return variant.inControlGroup = true;
});
@@ -1901,10 +1941,15 @@
wem._dispatchJSExperienceDisplayedEvent(selectedFilter.event);
}
} else {
- var elements = document.getElementById(target).children;
+ var elements =
+ /** @type {HTMLElement} */
+ document.getElementById(target).children;
for (var eIndex in elements) {
- var el = elements.item(eIndex);
+ // @ts-expect-error The indexing is unsafe
+ var el =
+ /** @type {HTMLElement} */
+ elements.item(eIndex);
el.style.display = 'none';
}
}
@@ -1916,11 +1961,11 @@
* This function will register an optimization test or A/B test
*
* @param {string} optimizationTestNodeId the optimization test node id
- * @param {string} goalId the associated goal Id
- * @param {string} containerId the HTML container Id
- * @param {object} variants the variants
- * @param {boolean} [ajax] Deprecated: Ajax rendering is not supported anymore
- * @param {object} [variantsTraffic] the associated traffic allocation
+ * @param {string} goalId the associated goal Id (unused)
+ * @param {string} containerId the HTML container Id (unused)
+ * @param {Record<string, Variant>} variants the variants
+ * @param {boolean} [ajax] Deprecated: Ajax rendering is not supported anymore (unused)
+ * @param {Record<string, number>} [variantsTraffic] the associated traffic allocation
* @return {undefined}
*/
registerOptimizationTest: function registerOptimizationTest(optimizationTestNodeId, goalId, containerId, variants, ajax, variantsTraffic) {
@@ -1956,12 +2001,18 @@
}
if (wem.storageAvailable('sessionStorage')) {
- sessionStorage.setItem(optimizationTestNodeId, selectedVariantId);
+ sessionStorage.setItem(optimizationTestNodeId,
+ /** @type {string} */
+ selectedVariantId);
} else {
- wem.setCookie('selectedVariantId', selectedVariantId, 1);
+ wem.setCookie('selectedVariantId',
+ /** @type {string} */
+ selectedVariantId, 1);
}
- var variant = variants[selectedVariantId]; // spread event to unomi
+ var variant = variants[
+ /** @type {string} */
+ selectedVariantId]; // spread event to unomi
if (variant.event) {
wem._registerEvent(wem._completeEvent(variant.event));
@@ -1974,6 +2025,8 @@
window.optimizedContentAreas[optimizationTestNodeId].selectedVariant = selectedVariantId;
} // display the good variant
+ /** @type {HTMLElement} */
+
document.getElementById(variants[selectedVariantId].content).style.display = '';
}
@@ -1997,6 +2050,8 @@
console.log('Context already requested by', wem.contextLoaded);
return;
}
+ /** @type {Record<string, unknown>} */
+
var jsonData = {
requiredProfileProperties: wem.digitalData.wemInitConfig.requiredProfileProperties,
@@ -2031,6 +2086,7 @@
// Use text/plain to avoid CORS preflight
jsonData: jsonData,
dataType: 'application/json',
+ // @ts-expect-error This parameter does not exist
invalidate: invalidate,
success: wem._onSuccess,
error: function error() {
@@ -2040,12 +2096,13 @@
wem.contextLoaded = Error().stack;
console.info('[WEM] context loading...');
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function will send an event to Apache Unomi
- * @param {object} event The event object to send, you can build it using wem.buildEvent(eventType, target, source)
- * @param {function} successCallback optional, will be executed in case of success
- * @param {function} errorCallback optional, will be executed in case of error
+ * @param {UnomiEvent} event The event object to send, you can build it using wem.buildEvent(eventType, target, source)
+ * @param {(xhr: XMLHttpRequest) => void} [successCallback] optional, will be executed in case of success
+ * @param {(xhr: XMLHttpRequest) => void} [errorCallback] optional, will be executed in case of error
* @return {undefined}
*/
collectEvent: function collectEvent(event) {
@@ -2055,13 +2112,14 @@
events: [event]
}, successCallback, errorCallback);
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function will send the events to Apache Unomi
*
- * @param {object} events Javascript object { events: [event1, event2] }
- * @param {function} successCallback optional, will be executed in case of success
- * @param {function} errorCallback optional, will be executed in case of error
+ * @param {{ sessionId?: string, events: Array<UnomiEvent> }} events Javascript object { events: [event1, event2] }
+ * @param {(xhr: XMLHttpRequest) => void} [successCallback] optional, will be executed in case of success
+ * @param {(xhr: XMLHttpRequest) => void} [errorCallback] optional, will be executed in case of error
* @return {undefined}
*/
collectEvents: function collectEvents(events) {
@@ -2087,11 +2145,12 @@
error: errorCallback
});
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function will build an event of type click and send it to Apache Unomi
*
- * @param {object} event javascript
+ * @param {Event & { target: HTMLElement & { name: string }}} event javascript
* @param {function} [successCallback] optional, will be executed if case of success
* @param {function} [errorCallback] optional, will be executed if case of error
* @return {undefined}
@@ -2132,20 +2191,23 @@
}
}
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function will build an event of type video and send it to Apache Unomi
*
- * @param {object} event javascript
- * @param {function} [successCallback] optional, will be executed if case of success
- * @param {function} [errorCallback] optional, will be executed if case of error
+ * @param {Event} event javascript
+ * @param {(xhr: XMLHttpRequest) => void} [successCallback] optional, will be executed if case of success
+ * @param {(xhr: XMLHttpRequest) => void} [errorCallback] optional, will be executed if case of error
* @return {undefined}
*/
sendVideoEvent: function sendVideoEvent(event) {
var successCallback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
var errorCallback = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
console.debug('[WEM] catching video event');
- var videoEvent = wem.buildEvent('video', wem.buildTarget(event.target.id, 'video', {
+ var videoEvent = wem.buildEvent('video', wem.buildTarget(
+ /** @type {HTMLElement} */
+ event.target.id, 'video', {
action: event.type
}), wem.buildSourcePage());
wem.collectEvent(videoEvent, function (xhr) {
@@ -2177,16 +2239,18 @@
wem.removeCookie(wem.trackerProfileIdCookieName);
wem.cxs = undefined;
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function return the basic structure for an event, it must be adapted to your need
*
* @param {string} eventType The name of your event
- * @param {object} [target] The target object for your event can be build with wem.buildTarget(targetId, targetType, targetProperties)
- * @param {object} [source] The source object for your event can be build with wem.buildSource(sourceId, sourceType, sourceProperties)
- * @returns {object} the event
+ * @param {UnomiEvent["target"]} [target] The target object for your event can be build with wem.buildTarget(targetId, targetType, targetProperties)
+ * @param {UnomiEvent["source"]} [source] The source object for your event can be build with wem.buildSource(sourceId, sourceType, sourceProperties)
+ * @returns {UnomiEvent} the event
*/
buildEvent: function buildEvent(eventType, target, source) {
+ /** @type {UnomiEvent} */
var event = {
eventType: eventType,
scope: wem.digitalData.scope
@@ -2207,8 +2271,8 @@
* This function return an event of type form
*
* @param {string} formName The HTML name of id of the form to use in the target of the event
- * @param {HTMLFormElement} form optional HTML form element, if provided will be used to extract the form fields and populate the form event
- * @returns {object} the form event
+ * @param {HTMLFormElement} [form] optional HTML form element, if provided will be used to extract the form fields and populate the form event
+ * @returns {UnomiEvent} the form event
*/
buildFormEvent: function buildFormEvent(formName) {
var form = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
@@ -2218,6 +2282,14 @@
};
return formEvent;
},
+
+ /**
+ * @param {string} formName form name
+ * @param {HTMLFormElement} form form
+ * @param {string} term term
+ * @param {string} language language
+ * @returns {UnomiEvent} event
+ */
buildSearchEvent: function buildSearchEvent(formName, form, term, language) {
var searchEvent = wem.buildEvent('search', wem.buildTarget(formName, 'search'), wem.buildSourcePage());
searchEvent.flattenedProperties = {
@@ -2227,49 +2299,54 @@
originForm: formName,
language: language || 'en',
keyword: term,
+ // @ts-expect-error There is no way this is properly defined
origin: searchEvent.source.properties.pageInfo.pagePath
};
return searchEvent;
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function return the source object for a source of type page
*
- * @returns {object} the target page
+ * @returns {UnomiEvent["target"]} the target page
*/
buildTargetPage: function buildTargetPage() {
return wem.buildTarget(wem.digitalData.page.pageInfo.pageID, 'page', wem.digitalData.page);
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function return the source object for a source of type page
*
- * @returns {object} the source page
+ * @returns {UnomiEvent["source"]} the source page
*/
buildSourcePage: function buildSourcePage() {
return wem.buildSource(wem.digitalData.page.pageInfo.pageID, 'page', wem.digitalData.page);
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function return the basic structure for the target of your event
*
* @param {string} targetId The ID of the target
* @param {string} targetType The type of the target
- * @param {object} [targetProperties] The optional properties of the target
- * @returns {object} the target
+ * @param {UnomiProperties} [targetProperties] The optional properties of the target
+ * @returns {UnomiEvent["target"]} the target
*/
buildTarget: function buildTarget(targetId, targetType) {
var targetProperties = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
return wem._buildObject(targetId, targetType, targetProperties);
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function return the basic structure for the source of your event
*
* @param {string} sourceId The ID of the source
* @param {string} sourceType The type of the source
- * @param {object} [sourceProperties] The optional properties of the source
- * @returns {object} the source
+ * @param {UnomiProperties} [sourceProperties] The optional properties of the source
+ * @returns {UnomiEvent["source"]} the source
*/
buildSource: function buildSource(sourceId, sourceType) {
var sourceProperties = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
@@ -2307,7 +2384,7 @@
* This is an utility function to get a cookie
*
* @param {string} cookieName name of the cookie to get
- * @returns {string} the value of the first cookie with the corresponding name or null if not found
+ * @returns {string | null} the value of the first cookie with the corresponding name or null if not found
*/
getCookie: function getCookie(cookieName) {
var name = cookieName + '=';
@@ -2342,7 +2419,7 @@
/**
* This is an utility function to execute AJAX call
*
- * @param {object} options options of the request
+ * @param {AjaxOptions} options options of the request
* @return {undefined}
*/
ajax: function ajax(options) {
@@ -2432,7 +2509,7 @@
/**
* This is an utility function to check if the local storage is available or not
- * @param {string} type the type of storage to test
+ * @param {"sessionStorage" | "localStorage"} type the type of storage to test
* @returns {boolean} true in case storage is available, false otherwise
*/
storageAvailable: function storageAvailable(type) {
@@ -2480,7 +2557,7 @@
* This is an utility function to get current url parameter value
*
* @param {string} name, the name of the parameter
- * @returns {string} the value of the parameter
+ * @returns {string | null} the value of the parameter
*/
getUrlParameter: function getUrlParameter(name) {
name = name.replace(/[[]/, '\\[').replace(/[\]]/, '\\]');
@@ -2492,7 +2569,7 @@
/**
* convert the passed query string into JS object.
* @param {string} searchString The URL query string
- * @returns {object} converted URL params
+ * @returns {Record<string, Array<string | undefined> | string | undefined> | null} converted URL params
*/
convertUrlParametersToObj: function convertUrlParametersToObj(searchString) {
if (!searchString) {
@@ -2524,7 +2601,9 @@
}
return result;
- }, {});
+ },
+ /** @type Record<string, Array<string | undefined> | string | undefined> */
+ {});
},
/*************************************/
@@ -2537,7 +2616,7 @@
* Used to override the default digitalData values,
* the result will impact directly the current instance wem.digitalData
*
- * @param {object[]} digitalDataOverrides list of overrides
+ * @param {Array<Partial<DigitalData>>} [digitalDataOverrides] list of overrides
* @private
* @return {undefined}
*/
@@ -2631,6 +2710,7 @@
var click = document.getElementById(clickIdName) || document.getElementById(wem._resolveId(clickIdName)) ? document.getElementById(clickIdName) || document.getElementById(wem._resolveId(clickIdName)) : document.getElementsByName(clickIdName)[0];
if (click) {
+ // @ts-expect-error The types will never match
click.addEventListener('click', wem.sendClickEvent);
console.debug('[WEM] Watching click ' + clickIdName);
} else {
@@ -2693,11 +2773,12 @@
/**
* build and dispatch JavaScript event in current HTML document for the given Unomi event (perso/opti)
* @private
- * @param {object} experienceUnomiEvent perso/opti Unomi event
+ * @param {UnomiEvent} experienceUnomiEvent perso/opti Unomi event
* @return {undefined}
*/
_dispatchJSExperienceDisplayedEvent: function _dispatchJSExperienceDisplayedEvent(experienceUnomiEvent) {
if (!wem.fallback && experienceUnomiEvent && experienceUnomiEvent.target && experienceUnomiEvent.target.properties && experienceUnomiEvent.target.properties.variants && experienceUnomiEvent.target.properties.variants.length > 0) {
+ /** @type {Record<string, string | undefined>} */
var typeMapper = {
optimizationTestEvent: 'optimization',
personalizationEvent: 'personalization'
@@ -2709,6 +2790,8 @@
try {
for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
var variant = _step4.value;
+
+ /** @type {any} */
var jsEventDetail = {
id: variant.id,
name: variant.systemName,
@@ -2768,9 +2851,9 @@
* Check if event is incomplete and complete what is missing:
* - source: if missing, use the current source page
* - scope: if missing, use the current scope
- * @param {object} event, the event to be checked
+ * @param {UnomiEvent} event, the event to be checked
* @private
- * @return {object} the complete event
+ * @return {UnomiEvent} the complete event
*/
_completeEvent: function _completeEvent(event) {
if (!event.source) {
@@ -2796,7 +2879,7 @@
* in case the context is already loaded (check: wem.getLoadedContext()), then you should use: wem.collectEvent(s) functions
*
* @private
- * @param {object} event the Unomi event to be registered
+ * @param {UnomiEvent} event the Unomi event to be registered
* @param {boolean} unshift optional, if true, the event will be added at the beginning of the list otherwise at the end of the list. (default: false)
* @return {undefined}
*/
@@ -2809,7 +2892,9 @@
return;
}
} else {
- wem.digitalData = {};
+ wem.digitalData =
+ /** @type {DigitalData} */
+ {};
}
wem.digitalData.events = wem.digitalData.events || [];
@@ -2820,11 +2905,12 @@
wem.digitalData.events.push(event);
}
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function allow for registering callback that will be executed once the context is loaded.
- * @param {function} onLoadCallback the callback to be executed
- * @param {string} name optional name for the call, used mostly for logging the execution
+ * @param {(...args: unknown[]) => void} onLoadCallback the callback to be executed
+ * @param {string} [name] optional name for the call, used mostly for logging the execution
* @param {number} priority optional priority to execute the callbacks in a specific order
* (default: 5, to leave room for the tracker default callback(s))
* @private
@@ -2856,7 +2942,9 @@
}
} else {
console.debug('[WEM] Trying to register context load callback, but no digitalData conf found, creating it and registering the callback: ' + (name ? name : 'Callback without name'));
- wem.digitalData = {};
+ wem.digitalData =
+ /** @type {DigitalData} */
+ {};
if (onLoadCallback) {
wem.digitalData.loadCallbacks = [];
@@ -2871,8 +2959,8 @@
/**
* Internal function for personalization specific callbacks (used for HTML dom manipulation once we get the context loaded)
- * @param {object} personalization the personalization
- * @param {function} callback the callback
+ * @param {Personalization} personalization the personalization
+ * @param {PersonalizationCallback} callback the callback
* @private
* @return {undefined}
*/
@@ -2889,7 +2977,9 @@
});
}
} else {
- wem.digitalData = {};
+ wem.digitalData =
+ /** @type {DigitalData} */
+ {};
wem.digitalData.personalizationCallback = wem.digitalData.personalizationCallback || [];
wem.digitalData.personalizationCallback.push({
personalization: personalization,
@@ -2897,17 +2987,20 @@
});
}
},
+ // eslint-disable-next-line valid-jsdoc
/**
* Build a simple Unomi object
* @param {string} itemId the itemId of the object
* @param {string} itemType the itemType of the object
- * @param {object} properties optional properties for the object
+ * @param {UnomiProperties} [properties] optional properties for the object
* @private
- * @return {object} the built Unomi JSON object
+ * @return {UnomiObject} the built Unomi JSON object
*/
_buildObject: function _buildObject(itemId, itemType) {
var properties = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
+
+ /** @type {UnomiObject} */
var object = {
scope: wem.digitalData.scope,
itemId: itemId,
@@ -3009,8 +3102,14 @@
if (search && search != '') {
// parse parameters
- var queryParams = [],
- param;
+ var queryParams =
+ /** @type {string[] & Record<string, string>} */
+
+ /** @type {unknown} */
+ [],
+
+ /** @type {string[]} */
+ param;
var queryParamPairs = search.slice(1).split('&');
for (var i = 0; i < queryParamPairs.length; i++) {
@@ -3041,13 +3140,15 @@
* this listener will automatically send the form event to Unomi, by parsing the HTML form data.
* (NOTE: the form listener only work for know forms to be watch due to tracked conditions)
*
- * @param {object} event the original HTML form submition event for the watch form.
+ * @param {SubmitEvent} event the original HTML form submition event for the watch form.
* @private
* @return {undefined}
*/
_formSubmitEventListener: function _formSubmitEventListener(event) {
console.debug('[WEM] Registering form event callback');
- var form = event.target;
+ var form =
+ /** @type {HTMLFormElement} */
+ event.target;
var formName = form.getAttribute('name') ? form.getAttribute('name') : form.getAttribute('id');
if (formName && wem.formNamesToWatch.indexOf(formName) > -1) {
@@ -3089,10 +3190,13 @@
* @return {object} the form data as JSON
*/
_extractFormData: function _extractFormData(form) {
+ /** @type {Record<string, string | string[]>} */
var params = {};
for (var i = 0; i < form.elements.length; i++) {
- var e = form.elements[i]; // ignore empty and undefined key (e.name)
+ var e =
+ /** @type {HTMLInputElement | HTMLSelectElement} */
+ form.elements[i]; // ignore empty and undefined key (e.name)
if (e.name) {
switch (e.nodeName) {
@@ -3108,6 +3212,7 @@
}
if (e.checked) {
+ /** @type {string[]} */
params[e.name].push(e.value);
}
}
@@ -3133,17 +3238,22 @@
break;
case 'SELECT':
- if (e.options && e.options[e.selectedIndex]) {
- if (e.multiple) {
- params[e.name] = [];
-
- for (var j = 0; j < e.options.length; j++) {
- if (e.options[j].selected) {
- params[e.name].push(e.options[j].value);
+ var s =
+ /** @type {HTMLSelectElement} */
+ e;
+
+ if (s.options && s.options[s.selectedIndex]) {
+ if (s.multiple) {
+ params[s.name] = [];
+
+ for (var j = 0; j < s.options.length; j++) {
+ if (s.options[j].selected) {
+ /** @type {string[]} */
+ params[s.name].push(s.options[j].value);
}
}
} else {
- params[e.name] = e.options[e.selectedIndex].value;
+ params[s.name] = s.options[s.selectedIndex].value;
}
}
@@ -3165,17 +3275,19 @@
if (wem.digitalData.sourceLocalIdentifierMap) {
var source = Object.keys(wem.digitalData.sourceLocalIdentifierMap).filter(function (source) {
return id.indexOf(source) > 0;
- });
+ }); // @ts-expect-error This code is broken, source is an array
+
return source ? id.replace(source, wem.digitalData.sourceLocalIdentifierMap[source]) : id;
}
return id;
},
+ // eslint-disable-next-line valid-jsdoc
/**
* Enable or disable tracking in current page
* @param {boolean} enable true will enable the tracking feature, otherwise they will be disabled
- * @param {function} callback an optional callback that can be used to perform additional logic based on enabling/disabling results
+ * @param {(enable: boolean) => void} [callback] an optional callback that can be used to perform additional logic based on enabling/disabling results
* @private
* @return {undefined}
*/
@@ -3207,10 +3319,11 @@
/**
* Utility function used to merge two JSON object together (arrays are concat for example)
- * @param {object} source the source object for merge
- * @param {object} target the target object for merge
+ * @template T
+ * @param {any} source the source object for merge
+ * @param {T} target the target object for merge
* @private
- * @return {object} the merged results
+ * @return {T} the merged results
*/
_deepMergeObjects: function _deepMergeObjects(source, target) {
if (!wem._isObject(target) || !wem._isObject(source)) {
@@ -3218,14 +3331,18 @@
}
Object.keys(source).forEach(function (key) {
+ // @ts-expect-error target cannot be indexed by key
var targetValue = target[key];
var sourceValue = source[key]; // concat arrays || merge objects || add new props
if (Array.isArray(targetValue) && Array.isArray(sourceValue)) {
+ // @ts-expect-error target cannot be indexed by key
target[key] = targetValue.concat(sourceValue);
} else if (wem._isObject(targetValue) && wem._isObject(sourceValue)) {
+ // @ts-expect-error target cannot be indexed by key
target[key] = wem._deepMergeObjects(sourceValue, Object.assign({}, targetValue));
} else {
+ // @ts-expect-error target cannot be indexed by key
target[key] = sourceValue;
}
});
diff --git a/dist/apache-unomi-tracker.umd.js.map b/dist/apache-unomi-tracker.umd.js.map
index 378f851..89944c2 100644
--- a/dist/apache-unomi-tracker.umd.js.map
+++ b/dist/apache-unomi-tracker.umd.js.map
@@ -1 +1 @@
-{"version":3,"file":"apache-unomi-tracker.umd.js","sources":["../node_modules/@babel/runtime/helpers/esm/typeof.js","../node_modules/es6-crawler-detect/src/lib/crawler/provider.js","../node_modules/es6-crawler-detect/src/lib/crawler/crawlers.js","../node_modules/es6-crawler-detect/src/lib/crawler/exclusions.js","../node_modules/es6-crawler-detect/src/lib/crawler/headers.js","../node_modules/es6-crawler-detect/src/lib/crawler.js","../node_modules/es6-crawler-detect/src/index.js","../src/a [...]
\ No newline at end of file
+{"version":3,"file":"apache-unomi-tracker.umd.js","sources":["../node_modules/@babel/runtime/helpers/esm/typeof.js","../node_modules/es6-crawler-detect/src/lib/crawler/provider.js","../node_modules/es6-crawler-detect/src/lib/crawler/crawlers.js","../node_modules/es6-crawler-detect/src/lib/crawler/exclusions.js","../node_modules/es6-crawler-detect/src/lib/crawler/headers.js","../node_modules/es6-crawler-detect/src/lib/crawler.js","../node_modules/es6-crawler-detect/src/index.js","../src/a [...]
\ No newline at end of file
diff --git a/dist/types.d.ts b/dist/types.d.ts
new file mode 100644
index 0000000..c924c59
--- /dev/null
+++ b/dist/types.d.ts
@@ -0,0 +1,120 @@
+export interface DigitalData {
+ scope: string;
+ site: {
+ siteInfo: {
+ siteID: string;
+ };
+ };
+ page: {
+ pageInfo: PageInfo;
+ consentTypes: string[];
+ };
+ events: UnomiEvent[];
+ interests: unknown;
+ contextServerPublicUrl: string;
+ sourceLocalIdentifierMap: unknown;
+ wemInitConfig: {
+ contextServerUrl: string;
+ isPreview: boolean;
+ timeoutInMilliseconds: number;
+ dxUsername: string;
+ contextServerCookieName: string;
+ activateWem: boolean;
+ enableWemActionUrl: string;
+ requiredProfileProperties: string[];
+ requiredSessionProperties: string[];
+ requireSegments: boolean;
+ requireScores: boolean;
+ trackerProfileIdCookieName?: string;
+ trackerSessionIdCookieName?: string;
+ browserGeneratedSessionSuffix?: string;
+ disableTrackedConditionsListeners?: boolean;
+ };
+ personalizationCallback: Array<{
+ personalization: Personalization;
+ callback: PersonalizationCallback;
+ }>;
+ loadCallbacks?: Array<{
+ name?: string;
+ priority: number;
+ execute: (...args: unknown[]) => void;
+ }>;
+ displayedVariants?: unknown[];
+}
+export interface PageInfo {
+ pageID: string;
+ nodeType: string;
+ pageName: string;
+ pagePath: string;
+ templateName: string;
+ destinationURL: string;
+ destinationSearch: string;
+ referringURL: string;
+ language: string;
+ categories: string[];
+ tags: string[];
+ referrerHost?: string;
+ referrerQuery?: string;
+ sameDomainReferrer?: boolean;
+}
+export interface UnomiEvent {
+ eventType: string;
+ type?: string;
+ scope: string;
+ target?: UnomiObject;
+ source?: UnomiObject;
+ flattenedProperties?: Record<string, unknown>;
+ properties?: Record<string, unknown>;
+}
+export interface UnomiObject {
+ itemId: string;
+ itemType: string;
+ scope: string;
+ properties?: UnomiProperties;
+}
+export interface UnomiProperties {
+ type?: string;
+ action?: string;
+ systemName?: string;
+ displayableName?: string;
+ path?: string;
+ tags?: string[];
+ nodeType?: string;
+ inControlGroup?: boolean;
+ variants?: Variant[];
+ pageInfo?: PageInfo;
+}
+export interface Variant {
+ id: string;
+ systemName: string;
+ displayableName: string;
+ path: string;
+ tags: string[];
+ nodeType: string;
+ content: string;
+ position: number;
+ event?: UnomiEvent;
+ inControlGroup?: boolean;
+}
+export interface Personalization {
+ id: string;
+ strategyOptions: {
+ fallback: string;
+ };
+}
+export type PersonalizationCallback = (result: string[], additionalResultInfos?: AdditionalResultInfos) => void;
+export interface AdditionalResultInfos {
+ inControlGroup?: boolean;
+}
+export interface AjaxOptions {
+ type: string;
+ url: string;
+ async: boolean;
+ contentType?: string;
+ dataType?: string;
+ responseType?: XMLHttpRequestResponseType;
+ error?: (xhr: XMLHttpRequest) => void;
+ success?: (xhr: XMLHttpRequest) => void;
+ jsonData?: unknown;
+ data?: Document | XMLHttpRequestBodyInit | null;
+}
diff --git a/package.json b/package.json
index 385b280..e22a236 100644
--- a/package.json
+++ b/package.json
@@ -16,7 +16,7 @@
"dist"
],
"scripts": {
- "build": "rollup -c && tsc || true",
+ "build": "rollup -c && tsc",
"test": "node test/spec",
"pretest": "yarn run build",
"lint": "eslint --ext js,json ."
diff --git a/src/apache-unomi-tracker.js b/src/apache-unomi-tracker.js
index a997c0e..aeb6a32 100644
--- a/src/apache-unomi-tracker.js
+++ b/src/apache-unomi-tracker.js
@@ -14,15 +14,37 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
+// @ts-expect-error This module is typed starting v4, we are using v3
import { Crawler } from 'es6-crawler-detect';
+/** @import { AjaxOptions, DigitalData, UnomiEvent, Personalization, PersonalizationCallback, Variant, UnomiObject, UnomiProperties } from "./types" */
+
export const useTracker = () => {
const wem = {
+ digitalData: /** @type {DigitalData} */(/** @type {unknown} */(undefined)),
+ trackerProfileIdCookieName: 'wem-profile-id',
+ trackerSessionIdCookieName: 'wem-session-id',
+ browserGeneratedSessionSuffix: '',
+ disableTrackedConditionsListeners: false,
+ activateWem: true,
+ contextServerCookieName: 'context-profile-id',
+ contextServerUrl: '',
+ timeoutInMilliseconds: 1500,
+ formNamesToWatch: /** @type {string[]} */([]),
+ eventsPrevented: /** @type {string[]} */([]),
+ /** @type {string | null} */
+ sessionID: null,
+ fallback: false,
+ /** @type {any} */
+ cxs: undefined,
+ DOMLoaded: false,
+ /** @type {string | undefined} */
+ contextLoaded: undefined,
+
/**
* This function initialize the tracker
*
- * @param {object} digitalData config of the tracker
+ * @param {DigitalData} digitalData config of the tracker
* @returns {undefined}
*/
initTracker: function (digitalData) {
@@ -30,7 +52,7 @@ export const useTracker = () => {
wem.trackerProfileIdCookieName = wem.digitalData.wemInitConfig.trackerProfileIdCookieName ? wem.digitalData.wemInitConfig.trackerProfileIdCookieName : 'wem-profile-id';
wem.trackerSessionIdCookieName = wem.digitalData.wemInitConfig.trackerSessionIdCookieName ? wem.digitalData.wemInitConfig.trackerSessionIdCookieName : 'wem-session-id';
wem.browserGeneratedSessionSuffix = wem.digitalData.wemInitConfig.browserGeneratedSessionSuffix ? wem.digitalData.wemInitConfig.browserGeneratedSessionSuffix : '';
- wem.disableTrackedConditionsListeners = wem.digitalData.wemInitConfig.disableTrackedConditionsListeners;
+ wem.disableTrackedConditionsListeners = wem.digitalData.wemInitConfig.disableTrackedConditionsListeners || false;
wem.activateWem = wem.digitalData.wemInitConfig.activateWem;
const { contextServerUrl, timeoutInMilliseconds, contextServerCookieName } = wem.digitalData.wemInitConfig;
@@ -53,7 +75,7 @@ export const useTracker = () => {
* This function start the tracker by loading the context in the page
* Note: that the tracker will start once the current DOM is complete loaded, using listener on current document: DOMContentLoaded
*
- * @param {object[]} digitalDataOverrides optional, list of digitalData extensions, they will be merged with original digitalData before context loading
+ * @param {Array<Partial<DigitalData>>} [digitalDataOverrides] optional, list of digitalData extensions, they will be merged with original digitalData before context loading
* @returns {undefined}
*/
startTracker: function (digitalDataOverrides = undefined) {
@@ -131,7 +153,7 @@ export const useTracker = () => {
/**
* get the current loaded context from Unomi, will be accessible only after loadContext() have been performed
- * @returns {object} loaded context
+ * @returns {any} loaded context
*/
getLoadedContext: function () {
return wem.cxs;
@@ -160,9 +182,9 @@ export const useTracker = () => {
/**
* This function will register a personalization
*
- * @param {object} personalization the personalization object
- * @param {object} variants the variants
- * @param {boolean} [ajax] Deprecated: Ajax rendering is not supported anymore
+ * @param {Personalization} personalization the personalization object
+ * @param {Record<string, Variant>} variants the variants
+ * @param {boolean} [ajax] Deprecated: Ajax rendering is not supported anymore (ignored)
* @param {function} [resultCallback] the callback to be executed after personalization resolved
* @returns {undefined}
*/
@@ -200,9 +222,10 @@ export const useTracker = () => {
resultCallback(successfulFilters, selectedFilter);
} else {
if (selectedFilter) {
- var targetFilters = document.getElementById(target).children;
+ var targetFilters = /** @type {HTMLElement} */(document.getElementById(target)).children;
for (var fIndex in targetFilters) {
- var filter = targetFilters.item(fIndex);
+ // @ts-expect-error The indexing is unsafe
+ var filter = /** @type {HTMLElement | null} */(targetFilters.item(fIndex));
if (filter) {
filter.style.display = (filter.id === selectedFilter.content) ? '' : 'none';
}
@@ -211,8 +234,11 @@ export const useTracker = () => {
// we now add control group information to event if the user is in the control group.
if (inControlGroup) {
console.debug('[WEM] Profile is in control group for target: ' + target + ', adding to personalization event...');
+ // @ts-expect-error The properties are not defined
selectedFilter.event.target.properties.inControlGroup = true;
+ // @ts-expect-error The properties are not defined
if (selectedFilter.event.target.properties.variants) {
+ // @ts-expect-error The properties are not defined
selectedFilter.event.target.properties.variants.forEach(variant => variant.inControlGroup = true);
}
}
@@ -228,9 +254,10 @@ export const useTracker = () => {
wem._dispatchJSExperienceDisplayedEvent(selectedFilter.event);
}
} else {
- var elements = document.getElementById(target).children;
+ var elements = /** @type {HTMLElement} */(document.getElementById(target)).children;
for (var eIndex in elements) {
- var el = elements.item(eIndex);
+ // @ts-expect-error The indexing is unsafe
+ var el = /** @type {HTMLElement} */(elements.item(eIndex));
el.style.display = 'none';
}
}
@@ -242,11 +269,11 @@ export const useTracker = () => {
* This function will register an optimization test or A/B test
*
* @param {string} optimizationTestNodeId the optimization test node id
- * @param {string} goalId the associated goal Id
- * @param {string} containerId the HTML container Id
- * @param {object} variants the variants
- * @param {boolean} [ajax] Deprecated: Ajax rendering is not supported anymore
- * @param {object} [variantsTraffic] the associated traffic allocation
+ * @param {string} goalId the associated goal Id (unused)
+ * @param {string} containerId the HTML container Id (unused)
+ * @param {Record<string, Variant>} variants the variants
+ * @param {boolean} [ajax] Deprecated: Ajax rendering is not supported anymore (unused)
+ * @param {Record<string, number>} [variantsTraffic] the associated traffic allocation
* @return {undefined}
*/
registerOptimizationTest: function (optimizationTestNodeId, goalId, containerId, variants, ajax, variantsTraffic) {
@@ -280,11 +307,11 @@ export const useTracker = () => {
selectedVariantId = keys[keys.length * Math.random() << 0];
}
if (wem.storageAvailable('sessionStorage')) {
- sessionStorage.setItem(optimizationTestNodeId, selectedVariantId);
+ sessionStorage.setItem(optimizationTestNodeId, /** @type {string} */(selectedVariantId));
} else {
- wem.setCookie('selectedVariantId', selectedVariantId, 1);
+ wem.setCookie('selectedVariantId', /** @type {string} */(selectedVariantId), 1);
}
- const variant = variants[selectedVariantId];
+ const variant = variants[/** @type {string} */(selectedVariantId)];
// spread event to unomi
if (variant.event) {
wem._registerEvent(wem._completeEvent(variant.event));
@@ -298,7 +325,7 @@ export const useTracker = () => {
}
// display the good variant
- document.getElementById(variants[selectedVariantId].content).style.display = '';
+ /** @type {HTMLElement} */(document.getElementById(variants[selectedVariantId].content)).style.display = '';
}
},
@@ -316,6 +343,7 @@ export const useTracker = () => {
console.log('Context already requested by', wem.contextLoaded);
return;
}
+ /** @type {Record<string, unknown>} */
var jsonData = {
requiredProfileProperties: wem.digitalData.wemInitConfig.requiredProfileProperties,
requiredSessionProperties: wem.digitalData.wemInitConfig.requiredSessionProperties,
@@ -345,6 +373,7 @@ export const useTracker = () => {
contentType: 'text/plain;charset=UTF-8', // Use text/plain to avoid CORS preflight
jsonData: jsonData,
dataType: 'application/json',
+ // @ts-expect-error This parameter does not exist
invalidate: invalidate,
success: wem._onSuccess,
error: function () {
@@ -355,23 +384,25 @@ export const useTracker = () => {
console.info('[WEM] context loading...');
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function will send an event to Apache Unomi
- * @param {object} event The event object to send, you can build it using wem.buildEvent(eventType, target, source)
- * @param {function} successCallback optional, will be executed in case of success
- * @param {function} errorCallback optional, will be executed in case of error
+ * @param {UnomiEvent} event The event object to send, you can build it using wem.buildEvent(eventType, target, source)
+ * @param {(xhr: XMLHttpRequest) => void} [successCallback] optional, will be executed in case of success
+ * @param {(xhr: XMLHttpRequest) => void} [errorCallback] optional, will be executed in case of error
* @return {undefined}
*/
collectEvent: function (event, successCallback = undefined, errorCallback = undefined) {
wem.collectEvents({ events: [event] }, successCallback, errorCallback);
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function will send the events to Apache Unomi
*
- * @param {object} events Javascript object { events: [event1, event2] }
- * @param {function} successCallback optional, will be executed in case of success
- * @param {function} errorCallback optional, will be executed in case of error
+ * @param {{ sessionId?: string, events: Array<UnomiEvent> }} events Javascript object { events: [event1, event2] }
+ * @param {(xhr: XMLHttpRequest) => void} [successCallback] optional, will be executed in case of success
+ * @param {(xhr: XMLHttpRequest) => void} [errorCallback] optional, will be executed in case of error
* @return {undefined}
*/
collectEvents: function (events, successCallback = undefined, errorCallback = undefined) {
@@ -395,10 +426,11 @@ export const useTracker = () => {
});
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function will build an event of type click and send it to Apache Unomi
*
- * @param {object} event javascript
+ * @param {Event & { target: HTMLElement & { name: string }}} event javascript
* @param {function} [successCallback] optional, will be executed if case of success
* @param {function} [errorCallback] optional, will be executed if case of error
* @return {undefined}
@@ -440,17 +472,18 @@ export const useTracker = () => {
}
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function will build an event of type video and send it to Apache Unomi
*
- * @param {object} event javascript
- * @param {function} [successCallback] optional, will be executed if case of success
- * @param {function} [errorCallback] optional, will be executed if case of error
+ * @param {Event} event javascript
+ * @param {(xhr: XMLHttpRequest) => void} [successCallback] optional, will be executed if case of success
+ * @param {(xhr: XMLHttpRequest) => void} [errorCallback] optional, will be executed if case of error
* @return {undefined}
*/
sendVideoEvent: function (event, successCallback = undefined, errorCallback = undefined) {
console.debug('[WEM] catching video event');
- var videoEvent = wem.buildEvent('video', wem.buildTarget(event.target.id, 'video', { action: event.type }), wem.buildSourcePage());
+ var videoEvent = wem.buildEvent('video', wem.buildTarget(/** @type {HTMLElement} */(event.target).id, 'video', { action: event.type }), wem.buildSourcePage());
wem.collectEvent(videoEvent, function (xhr) {
console.debug('[WEM] Video event successfully collected.');
@@ -480,15 +513,17 @@ export const useTracker = () => {
wem.cxs = undefined;
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function return the basic structure for an event, it must be adapted to your need
*
* @param {string} eventType The name of your event
- * @param {object} [target] The target object for your event can be build with wem.buildTarget(targetId, targetType, targetProperties)
- * @param {object} [source] The source object for your event can be build with wem.buildSource(sourceId, sourceType, sourceProperties)
- * @returns {object} the event
+ * @param {UnomiEvent["target"]} [target] The target object for your event can be build with wem.buildTarget(targetId, targetType, targetProperties)
+ * @param {UnomiEvent["source"]} [source] The source object for your event can be build with wem.buildSource(sourceId, sourceType, sourceProperties)
+ * @returns {UnomiEvent} the event
*/
buildEvent: function (eventType, target, source) {
+ /** @type {UnomiEvent} */
var event = {
eventType: eventType,
scope: wem.digitalData.scope
@@ -509,8 +544,8 @@ export const useTracker = () => {
* This function return an event of type form
*
* @param {string} formName The HTML name of id of the form to use in the target of the event
- * @param {HTMLFormElement} form optional HTML form element, if provided will be used to extract the form fields and populate the form event
- * @returns {object} the form event
+ * @param {HTMLFormElement} [form] optional HTML form element, if provided will be used to extract the form fields and populate the form event
+ * @returns {UnomiEvent} the form event
*/
buildFormEvent: function (formName, form = undefined) {
const formEvent = wem.buildEvent('form', wem.buildTarget(formName, 'form'), wem.buildSourcePage());
@@ -519,6 +554,13 @@ export const useTracker = () => {
};
return formEvent;
},
+ /**
+ * @param {string} formName form name
+ * @param {HTMLFormElement} form form
+ * @param {string} term term
+ * @param {string} language language
+ * @returns {UnomiEvent} event
+ */
buildSearchEvent: function (formName, form, term, language) {
const searchEvent = wem.buildEvent('search', wem.buildTarget(formName, 'search'), wem.buildSourcePage());
searchEvent.flattenedProperties = {
@@ -529,47 +571,52 @@ export const useTracker = () => {
originForm: formName,
language: language || 'en',
keyword: term,
+ // @ts-expect-error There is no way this is properly defined
origin: searchEvent.source.properties.pageInfo.pagePath
};
return searchEvent;
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function return the source object for a source of type page
*
- * @returns {object} the target page
+ * @returns {UnomiEvent["target"]} the target page
*/
buildTargetPage: function () {
return wem.buildTarget(wem.digitalData.page.pageInfo.pageID, 'page', wem.digitalData.page);
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function return the source object for a source of type page
*
- * @returns {object} the source page
+ * @returns {UnomiEvent["source"]} the source page
*/
buildSourcePage: function () {
return wem.buildSource(wem.digitalData.page.pageInfo.pageID, 'page', wem.digitalData.page);
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function return the basic structure for the target of your event
*
* @param {string} targetId The ID of the target
* @param {string} targetType The type of the target
- * @param {object} [targetProperties] The optional properties of the target
- * @returns {object} the target
+ * @param {UnomiProperties} [targetProperties] The optional properties of the target
+ * @returns {UnomiEvent["target"]} the target
*/
buildTarget: function (targetId, targetType, targetProperties = undefined) {
return wem._buildObject(targetId, targetType, targetProperties);
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function return the basic structure for the source of your event
*
* @param {string} sourceId The ID of the source
* @param {string} sourceType The type of the source
- * @param {object} [sourceProperties] The optional properties of the source
- * @returns {object} the source
+ * @param {UnomiProperties} [sourceProperties] The optional properties of the source
+ * @returns {UnomiEvent["source"]} the source
*/
buildSource: function (sourceId, sourceType, sourceProperties = undefined) {
return wem._buildObject(sourceId, sourceType, sourceProperties);
@@ -603,7 +650,7 @@ export const useTracker = () => {
* This is an utility function to get a cookie
*
* @param {string} cookieName name of the cookie to get
- * @returns {string} the value of the first cookie with the corresponding name or null if not found
+ * @returns {string | null} the value of the first cookie with the corresponding name or null if not found
*/
getCookie: function (cookieName) {
var name = cookieName + '=';
@@ -634,7 +681,7 @@ export const useTracker = () => {
/**
* This is an utility function to execute AJAX call
*
- * @param {object} options options of the request
+ * @param {AjaxOptions} options options of the request
* @return {undefined}
*/
ajax: function (options) {
@@ -720,7 +767,7 @@ export const useTracker = () => {
/**
* This is an utility function to check if the local storage is available or not
- * @param {string} type the type of storage to test
+ * @param {"sessionStorage" | "localStorage"} type the type of storage to test
* @returns {boolean} true in case storage is available, false otherwise
*/
storageAvailable: function (type) {
@@ -767,7 +814,7 @@ export const useTracker = () => {
* This is an utility function to get current url parameter value
*
* @param {string} name, the name of the parameter
- * @returns {string} the value of the parameter
+ * @returns {string | null} the value of the parameter
*/
getUrlParameter: function (name) {
name = name.replace(/[[]/, '\\[').replace(/[\]]/, '\\]');
@@ -779,7 +826,7 @@ export const useTracker = () => {
/**
* convert the passed query string into JS object.
* @param {string} searchString The URL query string
- * @returns {object} converted URL params
+ * @returns {Record<string, Array<string | undefined> | string | undefined> | null} converted URL params
*/
convertUrlParametersToObj: function (searchString) {
if (!searchString) {
@@ -807,7 +854,7 @@ export const useTracker = () => {
}
return result;
- }, {}
+ }, /** @type Record<string, Array<string | undefined> | string | undefined> */({})
);
},
@@ -818,7 +865,7 @@ export const useTracker = () => {
* Used to override the default digitalData values,
* the result will impact directly the current instance wem.digitalData
*
- * @param {object[]} digitalDataOverrides list of overrides
+ * @param {Array<Partial<DigitalData>>} [digitalDataOverrides] list of overrides
* @private
* @return {undefined}
*/
@@ -898,6 +945,7 @@ export const useTracker = () => {
? (document.getElementById(clickIdName) || document.getElementById(wem._resolveId(clickIdName)))
: document.getElementsByName(clickIdName)[0];
if (click) {
+ // @ts-expect-error The types will never match
click.addEventListener('click', wem.sendClickEvent);
console.debug('[WEM] Watching click ' + clickIdName);
} else {
@@ -938,7 +986,7 @@ export const useTracker = () => {
/**
* build and dispatch JavaScript event in current HTML document for the given Unomi event (perso/opti)
* @private
- * @param {object} experienceUnomiEvent perso/opti Unomi event
+ * @param {UnomiEvent} experienceUnomiEvent perso/opti Unomi event
* @return {undefined}
*/
_dispatchJSExperienceDisplayedEvent: experienceUnomiEvent => {
@@ -949,11 +997,13 @@ export const useTracker = () => {
experienceUnomiEvent.target.properties.variants &&
experienceUnomiEvent.target.properties.variants.length > 0) {
+ /** @type {Record<string, string | undefined>} */
let typeMapper = {
optimizationTestEvent: 'optimization',
personalizationEvent: 'personalization'
};
for (const variant of experienceUnomiEvent.target.properties.variants) {
+ /** @type {any} */
let jsEventDetail = {
id: variant.id,
name: variant.systemName,
@@ -1005,9 +1055,9 @@ export const useTracker = () => {
* Check if event is incomplete and complete what is missing:
* - source: if missing, use the current source page
* - scope: if missing, use the current scope
- * @param {object} event, the event to be checked
+ * @param {UnomiEvent} event, the event to be checked
* @private
- * @return {object} the complete event
+ * @return {UnomiEvent} the complete event
*/
_completeEvent: function (event) {
if (!event.source) {
@@ -1030,7 +1080,7 @@ export const useTracker = () => {
* in case the context is already loaded (check: wem.getLoadedContext()), then you should use: wem.collectEvent(s) functions
*
* @private
- * @param {object} event the Unomi event to be registered
+ * @param {UnomiEvent} event the Unomi event to be registered
* @param {boolean} unshift optional, if true, the event will be added at the beginning of the list otherwise at the end of the list. (default: false)
* @return {undefined}
*/
@@ -1041,7 +1091,7 @@ export const useTracker = () => {
return;
}
} else {
- wem.digitalData = {};
+ wem.digitalData = /** @type {DigitalData} */({});
}
wem.digitalData.events = wem.digitalData.events || [];
@@ -1052,10 +1102,11 @@ export const useTracker = () => {
}
},
+ // eslint-disable-next-line valid-jsdoc
/**
* This function allow for registering callback that will be executed once the context is loaded.
- * @param {function} onLoadCallback the callback to be executed
- * @param {string} name optional name for the call, used mostly for logging the execution
+ * @param {(...args: unknown[]) => void} onLoadCallback the callback to be executed
+ * @param {string} [name] optional name for the call, used mostly for logging the execution
* @param {number} priority optional priority to execute the callbacks in a specific order
* (default: 5, to leave room for the tracker default callback(s))
* @private
@@ -1082,7 +1133,7 @@ export const useTracker = () => {
}
} else {
console.debug('[WEM] Trying to register context load callback, but no digitalData conf found, creating it and registering the callback: ' + (name ? name : 'Callback without name'));
- wem.digitalData = {};
+ wem.digitalData = /** @type {DigitalData} */({});
if (onLoadCallback) {
wem.digitalData.loadCallbacks = [];
wem.digitalData.loadCallbacks.push({
@@ -1096,8 +1147,8 @@ export const useTracker = () => {
/**
* Internal function for personalization specific callbacks (used for HTML dom manipulation once we get the context loaded)
- * @param {object} personalization the personalization
- * @param {function} callback the callback
+ * @param {Personalization} personalization the personalization
+ * @param {PersonalizationCallback} callback the callback
* @private
* @return {undefined}
*/
@@ -1111,21 +1162,23 @@ export const useTracker = () => {
wem.digitalData.personalizationCallback.push({ personalization: personalization, callback: callback });
}
} else {
- wem.digitalData = {};
+ wem.digitalData = /** @type {DigitalData} */({});
wem.digitalData.personalizationCallback = wem.digitalData.personalizationCallback || [];
wem.digitalData.personalizationCallback.push({ personalization: personalization, callback: callback });
}
},
+ // eslint-disable-next-line valid-jsdoc
/**
* Build a simple Unomi object
* @param {string} itemId the itemId of the object
* @param {string} itemType the itemType of the object
- * @param {object} properties optional properties for the object
+ * @param {UnomiProperties} [properties] optional properties for the object
* @private
- * @return {object} the built Unomi JSON object
+ * @return {UnomiObject} the built Unomi JSON object
*/
_buildObject: function (itemId, itemType, properties = undefined) {
+ /** @type {UnomiObject} */
var object = {
scope: wem.digitalData.scope,
itemId: itemId,
@@ -1224,7 +1277,7 @@ export const useTracker = () => {
var query = undefined;
if (search && search != '') {
// parse parameters
- var queryParams = [], param;
+ var queryParams = /** @type {string[] & Record<string, string>} */(/** @type {unknown} */([])), /** @type {string[]} */ param;
var queryParamPairs = search.slice(1).split('&');
for (var i = 0; i < queryParamPairs.length; i++) {
param = queryParamPairs[i].split('=');
@@ -1253,13 +1306,13 @@ export const useTracker = () => {
* this listener will automatically send the form event to Unomi, by parsing the HTML form data.
* (NOTE: the form listener only work for know forms to be watch due to tracked conditions)
*
- * @param {object} event the original HTML form submition event for the watch form.
+ * @param {SubmitEvent} event the original HTML form submition event for the watch form.
* @private
* @return {undefined}
*/
_formSubmitEventListener: function (event) {
console.debug('[WEM] Registering form event callback');
- var form = event.target;
+ var form = /** @type {HTMLFormElement} */(event.target);
var formName = form.getAttribute('name') ? form.getAttribute('name') : form.getAttribute('id');
if (formName && wem.formNamesToWatch.indexOf(formName) > -1) {
console.debug('[WEM] catching form ' + formName);
@@ -1302,9 +1355,10 @@ export const useTracker = () => {
* @return {object} the form data as JSON
*/
_extractFormData: function (form) {
+ /** @type {Record<string, string | string[]>} */
var params = {};
for (var i = 0; i < form.elements.length; i++) {
- var e = form.elements[i];
+ var e = /** @type {HTMLInputElement | HTMLSelectElement} */(form.elements[i]);
// ignore empty and undefined key (e.name)
if (e.name) {
switch (e.nodeName) {
@@ -1318,7 +1372,7 @@ export const useTracker = () => {
params[e.name] = [];
}
if (e.checked) {
- params[e.name].push(e.value);
+ /** @type {string[]} */(params[e.name]).push(e.value);
}
}
@@ -1337,16 +1391,17 @@ export const useTracker = () => {
}
break;
case 'SELECT':
- if (e.options && e.options[e.selectedIndex]) {
- if (e.multiple) {
- params[e.name] = [];
- for (var j = 0; j < e.options.length; j++) {
- if (e.options[j].selected) {
- params[e.name].push(e.options[j].value);
+ var s = /** @type {HTMLSelectElement} */(e);
+ if (s.options && s.options[s.selectedIndex]) {
+ if (s.multiple) {
+ params[s.name] = [];
+ for (var j = 0; j < s.options.length; j++) {
+ if (s.options[j].selected) {
+ /** @type {string[]} */(params[s.name]).push(s.options[j].value);
}
}
} else {
- params[e.name] = e.options[e.selectedIndex].value;
+ params[s.name] = s.options[s.selectedIndex].value;
}
}
break;
@@ -1367,15 +1422,17 @@ export const useTracker = () => {
var source = Object.keys(wem.digitalData.sourceLocalIdentifierMap).filter(function (source) {
return id.indexOf(source) > 0;
});
+ // @ts-expect-error This code is broken, source is an array
return source ? id.replace(source, wem.digitalData.sourceLocalIdentifierMap[source]) : id;
}
return id;
},
+ // eslint-disable-next-line valid-jsdoc
/**
* Enable or disable tracking in current page
* @param {boolean} enable true will enable the tracking feature, otherwise they will be disabled
- * @param {function} callback an optional callback that can be used to perform additional logic based on enabling/disabling results
+ * @param {(enable: boolean) => void} [callback] an optional callback that can be used to perform additional logic based on enabling/disabling results
* @private
* @return {undefined}
*/
@@ -1405,10 +1462,11 @@ export const useTracker = () => {
/**
* Utility function used to merge two JSON object together (arrays are concat for example)
- * @param {object} source the source object for merge
- * @param {object} target the target object for merge
+ * @template T
+ * @param {any} source the source object for merge
+ * @param {T} target the target object for merge
* @private
- * @return {object} the merged results
+ * @return {T} the merged results
*/
_deepMergeObjects: function (source, target) {
if (!wem._isObject(target) || !wem._isObject(source)) {
@@ -1416,15 +1474,19 @@ export const useTracker = () => {
}
Object.keys(source).forEach(key => {
+ // @ts-expect-error target cannot be indexed by key
const targetValue = target[key];
const sourceValue = source[key];
// concat arrays || merge objects || add new props
if (Array.isArray(targetValue) && Array.isArray(sourceValue)) {
+ // @ts-expect-error target cannot be indexed by key
target[key] = targetValue.concat(sourceValue);
} else if (wem._isObject(targetValue) && wem._isObject(sourceValue)) {
+ // @ts-expect-error target cannot be indexed by key
target[key] = wem._deepMergeObjects(sourceValue, Object.assign({}, targetValue));
} else {
+ // @ts-expect-error target cannot be indexed by key
target[key] = sourceValue;
}
});
diff --git a/src/global.d.ts b/src/global.d.ts
new file mode 100644
index 0000000..03e5367
--- /dev/null
+++ b/src/global.d.ts
@@ -0,0 +1,8 @@
+declare namespace globalThis {
+ // Help TypeScript with this object only available in IE 8-11
+ let XDomainRequest = XMLHttpRequest;
+
+ interface Window {
+ optimizedContentAreas: Record<string, { selectedVariant: string }>;
+ }
+}
diff --git a/src/types.ts b/src/types.ts
new file mode 100644
index 0000000..635cdd5
--- /dev/null
+++ b/src/types.ts
@@ -0,0 +1,132 @@
+export interface DigitalData {
+ scope: string;
+ site: {
+ siteInfo: {
+ siteID: string;
+ };
+ };
+ page: {
+ pageInfo: PageInfo;
+ consentTypes: string[];
+ };
+ events: UnomiEvent[];
+ interests: unknown;
+ contextServerPublicUrl: string;
+ sourceLocalIdentifierMap: unknown;
+ wemInitConfig: {
+ contextServerUrl: string;
+ isPreview: boolean;
+ timeoutInMilliseconds: number;
+ dxUsername: string;
+ contextServerCookieName: string;
+ activateWem: boolean;
+ enableWemActionUrl: string;
+ requiredProfileProperties: string[];
+ requiredSessionProperties: string[];
+ requireSegments: boolean;
+ requireScores: boolean;
+ trackerProfileIdCookieName?: string;
+ trackerSessionIdCookieName?: string;
+ browserGeneratedSessionSuffix?: string;
+ disableTrackedConditionsListeners?: boolean;
+ };
+ personalizationCallback: Array<{
+ personalization: Personalization;
+ callback: PersonalizationCallback;
+ }>;
+ loadCallbacks?: Array<{
+ name?: string;
+ priority: number;
+ execute: (...args: unknown[]) => void;
+ }>;
+ displayedVariants?: unknown[];
+}
+
+export interface PageInfo {
+ pageID: string;
+ nodeType: string;
+ pageName: string;
+ pagePath: string;
+ templateName: string;
+ destinationURL: string;
+ destinationSearch: string;
+ referringURL: string;
+ language: string;
+ categories: string[];
+ tags: string[];
+ referrerHost?: string;
+ referrerQuery?: string;
+ sameDomainReferrer?: boolean;
+}
+
+export interface UnomiEvent {
+ eventType: string;
+ type?: string;
+ scope: string;
+ target?: UnomiObject;
+ source?: UnomiObject;
+ flattenedProperties?: Record<string, unknown>;
+ properties?: Record<string, unknown>;
+}
+
+export interface UnomiObject {
+ itemId: string;
+ itemType: string;
+ scope: string;
+ properties?: UnomiProperties;
+}
+
+export interface UnomiProperties {
+ type?: string;
+ action?: string;
+ systemName?: string;
+ displayableName?: string;
+ path?: string;
+ tags?: string[];
+ nodeType?: string;
+ inControlGroup?: boolean;
+ variants?: Variant[];
+ pageInfo?: PageInfo;
+}
+
+export interface Variant {
+ id: string;
+ systemName: string;
+ displayableName: string;
+ path: string;
+ tags: string[];
+ nodeType: string;
+ content: string;
+ position: number;
+ event?: UnomiEvent;
+ inControlGroup?: boolean;
+}
+
+export interface Personalization {
+ id: string;
+ strategyOptions: {
+ fallback: string;
+ };
+}
+
+export type PersonalizationCallback = (
+ result: string[],
+ additionalResultInfos?: AdditionalResultInfos
+) => void;
+
+export interface AdditionalResultInfos {
+ inControlGroup?: boolean;
+}
+
+export interface AjaxOptions {
+ type: string;
+ url: string;
+ async: boolean;
+ contentType?: string;
+ dataType?: string;
+ responseType?: XMLHttpRequestResponseType;
+ error?: (xhr: XMLHttpRequest) => void;
+ success?: (xhr: XMLHttpRequest) => void;
+ jsonData?: unknown;
+ data?: Document | XMLHttpRequestBodyInit | null;
+}