Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

snowplow-tracker-core

Package Overview
Dependencies
Maintainers
1
Versions
35
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

snowplow-tracker-core - npm Package Compare versions

Comparing version 0.4.0 to 0.5.0-beta1

.tscache/default/hashes/base64.ts-e05e381eaa2f7a18f19352b7eee645bf

20

index.js

@@ -1,16 +0,4 @@

/*
* JavaScript tracker core for Snowplow: index.js
*
* Copyright (c) 2014 Snowplow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
module.exports = require('./lib/core');
"use strict";
var core_1 = require("./lib/core");
exports.trackerCore = core_1.trackerCore;
//# sourceMappingURL=index.js.map

107

lib/base64.js

@@ -1,82 +0,25 @@

/*
* Copyright (c) 2013 Kevin van Zonneveld (http://kvz.io)
* and Contributors (http://phpjs.org/authors)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
(function() {
var object = typeof exports !== 'undefined' ? exports : this; // For eventual node.js environment support
function base64_encode(data) {
// discuss at: http://phpjs.org/functions/base64_encode/
// original by: Tyler Akins (http://rumkin.com)
// improved by: Bayron Guevara
// improved by: Thunder.m
// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// improved by: Rafał Kukawski (http://kukawski.pl)
// bugfixed by: Pellentesque Malesuada
// example 1: base64_encode('Kevin van Zonneveld');
// returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
// example 2: base64_encode('a');
// returns 2: 'YQ=='
// example 3: base64_encode('✓ à la mode');
// returns 3: '4pyTIMOgIGxhIG1vZGU='
var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
ac = 0,
enc = '',
tmp_arr = [];
if (!data) {
return data;
}
data = unescape(encodeURIComponent(data));
do {
// pack three octets into four hexets
o1 = data.charCodeAt(i++);
o2 = data.charCodeAt(i++);
o3 = data.charCodeAt(i++);
bits = o1 << 16 | o2 << 8 | o3;
h1 = bits >> 18 & 0x3f;
h2 = bits >> 12 & 0x3f;
h3 = bits >> 6 & 0x3f;
h4 = bits & 0x3f;
// use hexets to index into b64, and append result to encoded string
tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
} while (i < data.length);
enc = tmp_arr.join('');
var r = data.length % 3;
return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
}
object.base64encode = base64_encode;
}());
"use strict";
function base64encode(data) {
var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc, tmp_arr = [];
if (!data) {
return data;
}
data = unescape(encodeURIComponent(data));
do {
o1 = data.charCodeAt(i++);
o2 = data.charCodeAt(i++);
o3 = data.charCodeAt(i++);
bits = o1 << 16 | o2 << 8 | o3;
h1 = bits >> 18 & 0x3f;
h2 = bits >> 12 & 0x3f;
h3 = bits >> 6 & 0x3f;
h4 = bits & 0x3f;
tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
} while (i < data.length);
enc = tmp_arr.join('');
var r = data.length % 3;
return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
}
exports.base64encode = base64encode;
//# sourceMappingURL=base64.js.map

@@ -1,687 +0,320 @@

/*
* JavaScript tracker core for Snowplow: core.js
*
* Copyright (c) 2014 Snowplow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
var payload = require('./payload.js');
"use strict";
var uuid = require('uuid');
/**
* Create a tracker core object
*
* @param boolean base64 Whether to base 64 encode contexts and unstructured event JSONs
* @param callback function Function applied to every payload dictionary object
* @return object Tracker core
*/
var payload = require('./payload');
function getTimestamp(tstamp) {
if (tstamp == null) {
return { type: 'dtm', value: new Date().getTime() };
}
else if (typeof tstamp === 'number') {
return { type: 'dtm', value: tstamp };
}
else if (tstamp.type === 'ttm') {
return { type: 'ttm', value: tstamp.value };
}
else {
return { type: 'dtm', value: (tstamp.value || new Date().getTime()) };
}
}
function trackerCore(base64, callback) {
// base 64 encoding should default to true
if (typeof base64 === 'undefined') {
base64 = true;
}
// Dictionary of key-value pairs which get added to every payload, e.g. tracker version
var payloadPairs = {};
/**
* Set a persistent key-value pair to be added to every payload
*
* @param string key Field name
* @param string value Field value
*/
function addPayloadPair(key, value) {
payloadPairs[key] = value;
}
/**
* Returns a copy of a JSON with undefined and null properties removed
*
* @param object eventJson JSON to clean
* @param object exemptFields Set of fields which should not be removed even if empty
* @return object A cleaned copy of eventJson
*/
function removeEmptyProperties(eventJson, exemptFields) {
var ret = {};
exemptFields = exemptFields || {};
for (var k in eventJson) {
if (exemptFields[k] || (eventJson[k] !== null && typeof eventJson[k] !== 'undefined')) {
ret[k] = eventJson[k];
}
}
return ret;
}
/**
* Wraps an array of custom contexts in a self-describing JSON
*
* @param array contexts Array of custom context self-describing JSONs
* @return object Outer JSON
*/
function completeContexts(contexts) {
if (contexts) {
return {
schema: 'iglu:com.snowplowanalytics.snowplow/contexts/jsonschema/1-0-1',
data: contexts
};
}
}
/**
* Gets called by every trackXXX method
* Adds context and payloadPairs name-value pairs to the payload
* Applies the callback to the built payload
*
* @param sb object Payload
* @param array contexts Custom contexts relating to the event
* @param number tstamp Timestamp of the event
* @return object Payload after the callback is applied
*/
function track(sb, context, tstamp) {
sb.addDict(payloadPairs);
sb.add('eid', uuid.v4());
sb.add('dtm', tstamp || new Date().getTime());
if (context) {
sb.addJson('cx', 'co', completeContexts(context));
}
if (typeof callback === 'function') {
callback(sb);
}
return sb;
}
/**
* Log an unstructured event
*
* @param object eventJson Contains the properties and schema location for the event
* @param array context Custom contexts relating to the event
* @param number tstamp Timestamp of the event
* @return object Payload
*/
function trackUnstructEvent(properties, context, tstamp) {
var sb = payload.payloadBuilder(base64);
var ueJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/unstruct_event/jsonschema/1-0-0',
data: properties
};
sb.add('e', 'ue');
sb.addJson('ue_px', 'ue_pr', ueJson);
return track(sb, context, tstamp);
}
return {
/**
* Turn base 64 encoding on or off
*
* @param boolean encode key Field name
*/
setBase64Encoding: function (encode) {
base64 = encode;
},
addPayloadPair: addPayloadPair,
/**
* Merges a dictionary into payloadPairs
*
* @param object dict Dictionary to add
*/
addPayloadDict: function (dict) {
for (var key in dict) {
if (dict.hasOwnProperty(key)) {
payloadPairs[key] = dict[key];
}
}
},
/**
* Replace payloadPairs with a new dictionary
*
* @param object dict New dictionary
*/
resetPayloadPairs: function (dict) {
payloadPairs = payload.isJson(dict) ? dict : {};
},
/**
* Set the tracker version
*
* @param string version
*/
setTrackerVersion: function (version) {
addPayloadPair('tv', version);
},
/**
* Set the tracker namespace
*
* @param string name
*/
setTrackerNamespace: function (name) {
addPayloadPair('tna', name);
},
/**
* Set the application ID
*
* @param string appId
*/
setAppId: function (appId) {
addPayloadPair('aid', appId);
},
/**
* Set the platform
*
* @param string value
*/
setPlatform: function (value) {
addPayloadPair('p', value);
},
/**
* Set the user ID
*
* @param string userId
*/
setUserId: function (userId) {
addPayloadPair('uid', userId);
},
/**
* Set the screen resolution
*
* @param number width
* @param number height
*/
setScreenResolution: function (width, height) {
addPayloadPair('res', width + 'x' + height);
},
/**
* Set the viewport dimensions
*
* @param number width
* @param number height
*/
setViewport: function (width, height) {
addPayloadPair('vp', width + 'x' + height);
},
/**
* Set the color depth
*
* @param number depth
*/
setColorDepth: function (depth) {
addPayloadPair('cd', depth);
},
/**
* Set the timezone
*
* @param string timezone
*/
setTimezone: function (timezone) {
addPayloadPair('tz', timezone);
},
/**
* Set the language
*
* @param string lang
*/
setLang: function (lang) {
addPayloadPair('lang', lang);
},
/**
* Set the IP address
*
* @param string appId
*/
setIpAddress: function (ip) {
addPayloadPair('ip', ip);
},
trackUnstructEvent: trackUnstructEvent,
/**
* Log the page view / visit
*
* @param string customTitle The user-defined page title to attach to this page view
* @param array context Custom contexts relating to the event
* @param number tstamp Timestamp of the event
* @return object Payload
*/
trackPageView: function (pageUrl, pageTitle, referrer, context, tstamp) {
var sb = payload.payloadBuilder(base64);
sb.add('e', 'pv'); // 'pv' for Page View
sb.add('url', pageUrl);
sb.add('page', pageTitle);
sb.add('refr', referrer);
return track(sb, context, tstamp);
},
/**
* Log that a user is still viewing a given page
* by sending a page ping.
*
* @param string pageTitle The page title to attach to this page ping
* @param minxoffset Minimum page x offset seen in the last ping period
* @param maxXOffset Maximum page x offset seen in the last ping period
* @param minYOffset Minimum page y offset seen in the last ping period
* @param maxYOffset Maximum page y offset seen in the last ping period
* @param array context Custom contexts relating to the event
* @param number tstamp Timestamp of the event
* @return object Payload
*/
trackPagePing: function (pageUrl, pageTitle, referrer, minXOffset, maxXOffset, minYOffset, maxYOffset, context, tstamp) {
var sb = payload.payloadBuilder(base64);
sb.add('e', 'pp'); // 'pp' for Page Ping
sb.add('url', pageUrl);
sb.add('page', pageTitle);
sb.add('refr', referrer);
sb.add('pp_mix', minXOffset);
sb.add('pp_max', maxXOffset);
sb.add('pp_miy', minYOffset);
sb.add('pp_may', maxYOffset);
return track(sb, context, tstamp);
},
/**
* Track a structured event
*
* @param string category The name you supply for the group of objects you want to track
* @param string action A string that is uniquely paired with each category, and commonly used to define the type of user interaction for the web object
* @param string label (optional) An optional string to provide additional dimensions to the event data
* @param string property (optional) Describes the object or the action performed on it, e.g. quantity of item added to basket
* @param int|float|string value (optional) An integer that you can use to provide numerical data about the user event
* @param array Custom contexts relating to the event
* @param number tstamp Timestamp of the event
* @return object Payload
*/
trackStructEvent: function (category, action, label, property, value, context, tstamp) {
var sb = payload.payloadBuilder(base64);
sb.add('e', 'se'); // 'se' for Structured Event
sb.add('se_ca', category);
sb.add('se_ac', action);
sb.add('se_la', label);
sb.add('se_pr', property);
sb.add('se_va', value);
return track(sb, context, tstamp);
},
/**
* Track an ecommerce transaction
*
* @param string orderId Required. Internal unique order id number for this transaction.
* @param string affiliation Optional. Partner or store affiliation.
* @param string total Required. Total amount of the transaction.
* @param string tax Optional. Tax amount of the transaction.
* @param string shipping Optional. Shipping charge for the transaction.
* @param string city Optional. City to associate with transaction.
* @param string state Optional. State to associate with transaction.
* @param string country Optional. Country to associate with transaction.
* @param string currency Optional. Currency to associate with this transaction.
* @param array context Optional. Context relating to the event.
* @param number tstamp Optional. Timestamp of the event
* @return object Payload
*/
trackEcommerceTransaction: function (orderId, affiliation, totalValue, taxValue, shipping, city, state, country, currency, context, tstamp) {
var sb = payload.payloadBuilder(base64);
sb.add('e', 'tr'); // 'tr' for Transaction
sb.add("tr_id", orderId);
sb.add("tr_af", affiliation);
sb.add("tr_tt", totalValue);
sb.add("tr_tx", taxValue);
sb.add("tr_sh", shipping);
sb.add("tr_ci", city);
sb.add("tr_st", state);
sb.add("tr_co", country);
sb.add("tr_cu", currency);
return track(sb, context, tstamp);
},
/**
* Track an ecommerce transaction item
*
* @param string orderId Required Order ID of the transaction to associate with item.
* @param string sku Required. Item's SKU code.
* @param string name Optional. Product name.
* @param string category Optional. Product category.
* @param string price Required. Product price.
* @param string quantity Required. Purchase quantity.
* @param string currency Optional. Product price currency.
* @param array context Optional. Context relating to the event.
* @param number tstamp Optional. Timestamp of the event
* @return object Payload
*/
trackEcommerceTransactionItem: function (orderId, sku, name, category, price, quantity, currency, context, tstamp) {
var sb = payload.payloadBuilder(base64);
sb.add("e", "ti"); // 'tr' for Transaction Item
sb.add("ti_id", orderId);
sb.add("ti_sk", sku);
sb.add("ti_nm", name);
sb.add("ti_ca", category);
sb.add("ti_pr", price);
sb.add("ti_qu", quantity);
sb.add("ti_cu", currency);
return track(sb, context, tstamp);
},
/**
* Track a screen view unstructured event
*
* @param string name The name of the screen
* @param string id The ID of the screen
* @param number tstamp Timestamp of the event
* @return object Payload
*/
trackScreenView: function (name, id, context, tstamp) {
return trackUnstructEvent({
schema: 'iglu:com.snowplowanalytics.snowplow/screen_view/jsonschema/1-0-0',
data: removeEmptyProperties({
name: name,
id: id
})
}, context, tstamp);
},
/**
* Log the link or click with the server
*
* @param string targetUrl
* @param string elementId
* @param array elementClasses
* @param string elementTarget
* @param string elementContent innerHTML of the link
* @param array context Custom contexts relating to the event
* @param number tstamp Timestamp of the event
* @return object Payload
*/
trackLinkClick: function (targetUrl, elementId, elementClasses, elementTarget, elementContent, context, tstamp) {
var eventJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/link_click/jsonschema/1-0-1',
data: removeEmptyProperties({
targetUrl: targetUrl,
elementId: elementId,
elementClasses: elementClasses,
elementTarget: elementTarget,
elementContent: elementContent
}),
};
return trackUnstructEvent(eventJson, context, tstamp);
},
/**
* Track an ad being served
*
* @param string impressionId Identifier for a particular ad impression
* @param string costModel The cost model. 'cpa', 'cpc', or 'cpm'
* @param number cost Cost
* @param string bannerId Identifier for the ad banner displayed
* @param string zoneId Identifier for the ad zone
* @param string advertiserId Identifier for the advertiser
* @param string campaignId Identifier for the campaign which the banner belongs to
* @param array Custom contexts relating to the event
* @param number tstamp Timestamp of the event
* @return object Payload
*/
trackAdImpression: function(impressionId, costModel, cost, targetUrl, bannerId, zoneId, advertiserId, campaignId, context, tstamp) {
var eventJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/ad_impression/jsonschema/1-0-0',
data: removeEmptyProperties({
impressionId: impressionId,
costModel: costModel,
cost: cost,
targetUrl: targetUrl,
bannerId: bannerId,
zoneId: zoneId,
advertiserId: advertiserId,
campaignId: campaignId
})
};
return trackUnstructEvent(eventJson, context, tstamp);
},
/**
* Track an ad being clicked
*
* @param string clickId Identifier for the ad click
* @param string costModel The cost model. 'cpa', 'cpc', or 'cpm'
* @param number cost Cost
* @param string targetUrl (required) The link's target URL
* @param string bannerId Identifier for the ad banner displayed
* @param string zoneId Identifier for the ad zone
* @param string impressionId Identifier for a particular ad impression
* @param string advertiserId Identifier for the advertiser
* @param string campaignId Identifier for the campaign which the banner belongs to
* @param array Custom contexts relating to the event
* @param number tstamp Timestamp of the event
* @return object Payload
*/
trackAdClick: function (targetUrl, clickId, costModel, cost, bannerId, zoneId, impressionId, advertiserId, campaignId, context, tstamp) {
var eventJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/ad_click/jsonschema/1-0-0',
data: removeEmptyProperties({
targetUrl: targetUrl,
clickId: clickId,
costModel: costModel,
cost: cost,
bannerId: bannerId,
zoneId: zoneId,
impressionId: impressionId,
advertiserId: advertiserId,
campaignId: campaignId
})
};
return trackUnstructEvent(eventJson, context, tstamp);
},
/**
* Track an ad conversion event
*
* @param string conversionId Identifier for the ad conversion event
* @param number cost Cost
* @param string category The name you supply for the group of objects you want to track
* @param string action A string that is uniquely paired with each category
* @param string property Describes the object of the conversion or the action performed on it
* @param number initialValue Revenue attributable to the conversion at time of conversion
* @param string advertiserId Identifier for the advertiser
* @param string costModel The cost model. 'cpa', 'cpc', or 'cpm'
* @param string campaignId Identifier for the campaign which the banner belongs to
* @param array Custom contexts relating to the event
* @param number tstamp Timestamp of the event
* @return object Payload
*/
trackAdConversion: function (conversionId, costModel, cost, category, action, property, initialValue, advertiserId, campaignId, context, tstamp) {
var eventJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/ad_conversion/jsonschema/1-0-0',
data: removeEmptyProperties({
conversionId: conversionId,
costModel: costModel,
cost: cost,
category: category,
action: action,
property: property,
initialValue: initialValue,
advertiserId: advertiserId,
campaignId: campaignId
})
};
return trackUnstructEvent(eventJson, context, tstamp);
},
/**
* Track a social event
*
* @param string action Social action performed
* @param string network Social network
* @param string target Object of the social action e.g. the video liked, the tweet retweeted
* @param array Custom contexts relating to the event
* @param number tstamp Timestamp of the event
* @return object Payload
*/
trackSocialInteraction: function (action, network, target, context, tstamp) {
var eventJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/social_interaction/jsonschema/1-0-0',
data: removeEmptyProperties({
action: action,
network: network,
target: target
})
};
return trackUnstructEvent(eventJson, context, tstamp);
},
/**
* Track an add-to-cart event
*
* @param string sku Required. Item's SKU code.
* @param string name Optional. Product name.
* @param string category Optional. Product category.
* @param string unitPrice Optional. Product price.
* @param string quantity Required. Quantity added.
* @param string currency Optional. Product price currency.
* @param array context Optional. Context relating to the event.
* @param number tstamp Optional. Timestamp of the event
* @return object Payload
*/
trackAddToCart: function (sku, name, category, unitPrice, quantity, currency, context, tstamp) {
return trackUnstructEvent({
schema: 'iglu:com.snowplowanalytics.snowplow/add_to_cart/jsonschema/1-0-0',
data: removeEmptyProperties({
sku: sku,
name: name,
category: category,
unitPrice: unitPrice,
quantity: quantity,
currency: currency
})
}, context, tstamp);
},
/**
* Track a remove-from-cart event
*
* @param string sku Required. Item's SKU code.
* @param string name Optional. Product name.
* @param string category Optional. Product category.
* @param string unitPrice Optional. Product price.
* @param string quantity Required. Quantity removed.
* @param string currency Optional. Product price currency.
* @param array context Optional. Context relating to the event.
* @param number tstamp Optional. Timestamp of the event
* @return object Payload
*/
trackRemoveFromCart: function (sku, name, category, unitPrice, quantity, currency, context, tstamp) {
return trackUnstructEvent({
schema: 'iglu:com.snowplowanalytics.snowplow/remove_from_cart/jsonschema/1-0-0',
data: removeEmptyProperties({
sku: sku,
name: name,
category: category,
unitPrice: unitPrice,
quantity: quantity,
currency: currency
})
}, context, tstamp);
},
/**
* Track the value of a form field changing
*
* @param string formId The parent form ID
* @param string elementId ID of the changed element
* @param string nodeName "INPUT", "TEXTAREA", or "SELECT"
* @param string type Type of the changed element if its type is "INPUT"
* @param array elementClasses List of classes of the changed element
* @param string value The new value of the changed element
* @param array context Optional. Context relating to the event.
* @param number tstamp Optional. Timestamp of the event
* @return object Payload
*/
trackFormChange: function(formId, elementId, nodeName, type, elementClasses, value, context, tstamp) {
return trackUnstructEvent({
schema: 'iglu:com.snowplowanalytics.snowplow/change_form/jsonschema/1-0-0',
data: removeEmptyProperties({
formId: formId,
elementId: elementId,
nodeName: nodeName,
type: type,
elementClasses: elementClasses,
value: value
}, {'value': true})
}, context, tstamp);
},
/**
* Track a form submission event
*
* @param string formId ID of the form
* @param array formClasses Classes of the form
* @param array elements Mutable elements within the form
* @param array context Optional. Context relating to the event.
* @param number tstamp Optional. Timestamp of the event
* @return object Payload
*/
trackFormSubmission: function(formId, formClasses, elements, context, tstamp) {
return trackUnstructEvent({
schema: 'iglu:com.snowplowanalytics.snowplow/submit_form/jsonschema/1-0-0',
data: removeEmptyProperties({
formId: formId,
formClasses: formClasses,
elements: elements
})
}, context, tstamp);
},
/**
* Track an internal search event
*
* @param array terms Search terms
* @param object filters Search filters
* @param totalResults Number of results
* @param pageResults Number of results displayed on page
* @param array context Optional. Context relating to the event.
* @param number tstamp Optional. Timestamp of the event
* @return object Payload
*/
trackSiteSearch: function(terms, filters, totalResults, pageResults, context, tstamp) {
return trackUnstructEvent({
schema: 'iglu:com.snowplowanalytics.snowplow/site_search/jsonschema/1-0-0',
data: removeEmptyProperties({
terms: terms,
filters: filters,
totalResults: totalResults,
pageResults: pageResults
})
}, context, tstamp);
}
};
};
module.exports = trackerCore;
if (typeof base64 === 'undefined') {
base64 = true;
}
var payloadPairs = {};
function addPayloadPair(key, value) {
payloadPairs[key] = value;
}
function removeEmptyProperties(eventJson, exemptFields) {
var ret = {};
exemptFields = exemptFields || {};
for (var k in eventJson) {
if (exemptFields[k] || (eventJson[k] !== null && typeof eventJson[k] !== 'undefined')) {
ret[k] = eventJson[k];
}
}
return ret;
}
function completeContexts(contexts) {
if (contexts && contexts.length) {
return {
schema: 'iglu:com.snowplowanalytics.snowplow/contexts/jsonschema/1-0-0',
data: contexts
};
}
}
function track(sb, context, tstamp) {
sb.addDict(payloadPairs);
sb.add('eid', uuid.v4());
var timestamp = getTimestamp(tstamp);
sb.add(timestamp.type, timestamp.value.toString());
var wrappedContexts = completeContexts(context);
if (wrappedContexts !== undefined) {
sb.addJson('cx', 'co', wrappedContexts);
}
if (typeof callback === 'function') {
callback(sb);
}
return sb;
}
function trackSelfDescribingEvent(properties, context, tstamp) {
var sb = payload.payloadBuilder(base64);
var ueJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/unstruct_event/jsonschema/1-0-0',
data: properties
};
sb.add('e', 'ue');
sb.addJson('ue_px', 'ue_pr', ueJson);
return track(sb, context, tstamp);
}
return {
setBase64Encoding: function (encode) {
base64 = encode;
},
addPayloadPair: addPayloadPair,
addPayloadDict: function (dict) {
for (var key in dict) {
if (dict.hasOwnProperty(key)) {
payloadPairs[key] = dict[key];
}
}
},
resetPayloadPairs: function (dict) {
payloadPairs = payload.isJson(dict) ? dict : {};
},
setTrackerVersion: function (version) {
addPayloadPair('tv', version);
},
setTrackerNamespace: function (name) {
addPayloadPair('tna', name);
},
setAppId: function (appId) {
addPayloadPair('aid', appId);
},
setPlatform: function (value) {
addPayloadPair('p', value);
},
setUserId: function (userId) {
addPayloadPair('uid', userId);
},
setScreenResolution: function (width, height) {
addPayloadPair('res', width + 'x' + height);
},
setViewport: function (width, height) {
addPayloadPair('vp', width + 'x' + height);
},
setColorDepth: function (depth) {
addPayloadPair('cd', depth);
},
setTimezone: function (timezone) {
addPayloadPair('tz', timezone);
},
setLang: function (lang) {
addPayloadPair('lang', lang);
},
setIpAddress: function (ip) {
addPayloadPair('ip', ip);
},
trackUnstructEvent: trackSelfDescribingEvent,
trackSelfDescribingEvent: trackSelfDescribingEvent,
trackPageView: function (pageUrl, pageTitle, referrer, context, tstamp) {
var sb = payload.payloadBuilder(base64);
sb.add('e', 'pv');
sb.add('url', pageUrl);
sb.add('page', pageTitle);
sb.add('refr', referrer);
return track(sb, context, tstamp);
},
trackPagePing: function (pageUrl, pageTitle, referrer, minXOffset, maxXOffset, minYOffset, maxYOffset, context, tstamp) {
var sb = payload.payloadBuilder(base64);
sb.add('e', 'pp');
sb.add('url', pageUrl);
sb.add('page', pageTitle);
sb.add('refr', referrer);
sb.add('pp_mix', minXOffset.toString());
sb.add('pp_max', maxXOffset.toString());
sb.add('pp_miy', minYOffset.toString());
sb.add('pp_may', maxYOffset.toString());
return track(sb, context, tstamp);
},
trackStructEvent: function (category, action, label, property, value, context, tstamp) {
var sb = payload.payloadBuilder(base64);
sb.add('e', 'se');
sb.add('se_ca', category);
sb.add('se_ac', action);
sb.add('se_la', label);
sb.add('se_pr', property);
sb.add('se_va', (value == null ? undefined : value.toString()));
return track(sb, context, tstamp);
},
trackEcommerceTransaction: function (orderId, affiliation, totalValue, taxValue, shipping, city, state, country, currency, context, tstamp) {
var sb = payload.payloadBuilder(base64);
sb.add('e', 'tr');
sb.add("tr_id", orderId);
sb.add("tr_af", affiliation);
sb.add("tr_tt", totalValue);
sb.add("tr_tx", taxValue);
sb.add("tr_sh", shipping);
sb.add("tr_ci", city);
sb.add("tr_st", state);
sb.add("tr_co", country);
sb.add("tr_cu", currency);
return track(sb, context, tstamp);
},
trackEcommerceTransactionItem: function (orderId, sku, name, category, price, quantity, currency, context, tstamp) {
var sb = payload.payloadBuilder(base64);
sb.add("e", "ti");
sb.add("ti_id", orderId);
sb.add("ti_sk", sku);
sb.add("ti_nm", name);
sb.add("ti_ca", category);
sb.add("ti_pr", price);
sb.add("ti_qu", quantity);
sb.add("ti_cu", currency);
return track(sb, context, tstamp);
},
trackScreenView: function (name, id, context, tstamp) {
return trackSelfDescribingEvent({
schema: 'iglu:com.snowplowanalytics.snowplow/screen_view/jsonschema/1-0-0',
data: removeEmptyProperties({
name: name,
id: id
})
}, context, tstamp);
},
trackLinkClick: function (targetUrl, elementId, elementClasses, elementTarget, elementContent, context, tstamp) {
var eventJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/link_click/jsonschema/1-0-1',
data: removeEmptyProperties({
targetUrl: targetUrl,
elementId: elementId,
elementClasses: elementClasses,
elementTarget: elementTarget,
elementContent: elementContent
})
};
return trackSelfDescribingEvent(eventJson, context, tstamp);
},
trackAdImpression: function (impressionId, costModel, cost, targetUrl, bannerId, zoneId, advertiserId, campaignId, context, tstamp) {
var eventJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/ad_impression/jsonschema/1-0-0',
data: removeEmptyProperties({
impressionId: impressionId,
costModel: costModel,
cost: cost,
targetUrl: targetUrl,
bannerId: bannerId,
zoneId: zoneId,
advertiserId: advertiserId,
campaignId: campaignId
})
};
return trackSelfDescribingEvent(eventJson, context, tstamp);
},
trackAdClick: function (targetUrl, clickId, costModel, cost, bannerId, zoneId, impressionId, advertiserId, campaignId, context, tstamp) {
var eventJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/ad_click/jsonschema/1-0-0',
data: removeEmptyProperties({
targetUrl: targetUrl,
clickId: clickId,
costModel: costModel,
cost: cost,
bannerId: bannerId,
zoneId: zoneId,
impressionId: impressionId,
advertiserId: advertiserId,
campaignId: campaignId
})
};
return trackSelfDescribingEvent(eventJson, context, tstamp);
},
trackAdConversion: function (conversionId, costModel, cost, category, action, property, initialValue, advertiserId, campaignId, context, tstamp) {
var eventJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/ad_conversion/jsonschema/1-0-0',
data: removeEmptyProperties({
conversionId: conversionId,
costModel: costModel,
cost: cost,
category: category,
action: action,
property: property,
initialValue: initialValue,
advertiserId: advertiserId,
campaignId: campaignId
})
};
return trackSelfDescribingEvent(eventJson, context, tstamp);
},
trackSocialInteraction: function (action, network, target, context, tstamp) {
var eventJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/social_interaction/jsonschema/1-0-0',
data: removeEmptyProperties({
action: action,
network: network,
target: target
})
};
return trackSelfDescribingEvent(eventJson, context, tstamp);
},
trackAddToCart: function (sku, name, category, unitPrice, quantity, currency, context, tstamp) {
return trackSelfDescribingEvent({
schema: 'iglu:com.snowplowanalytics.snowplow/add_to_cart/jsonschema/1-0-0',
data: removeEmptyProperties({
sku: sku,
name: name,
category: category,
unitPrice: unitPrice,
quantity: quantity,
currency: currency
})
}, context, tstamp);
},
trackRemoveFromCart: function (sku, name, category, unitPrice, quantity, currency, context, tstamp) {
return trackSelfDescribingEvent({
schema: 'iglu:com.snowplowanalytics.snowplow/remove_from_cart/jsonschema/1-0-0',
data: removeEmptyProperties({
sku: sku,
name: name,
category: category,
unitPrice: unitPrice,
quantity: quantity,
currency: currency
})
}, context, tstamp);
},
trackFormChange: function (formId, elementId, nodeName, type, elementClasses, value, context, tstamp) {
return trackSelfDescribingEvent({
schema: 'iglu:com.snowplowanalytics.snowplow/change_form/jsonschema/1-0-0',
data: removeEmptyProperties({
formId: formId,
elementId: elementId,
nodeName: nodeName,
type: type,
elementClasses: elementClasses,
value: value
}, { value: true })
}, context, tstamp);
},
trackFormSubmission: function (formId, formClasses, elements, context, tstamp) {
return trackSelfDescribingEvent({
schema: 'iglu:com.snowplowanalytics.snowplow/submit_form/jsonschema/1-0-0',
data: removeEmptyProperties({
formId: formId,
formClasses: formClasses,
elements: elements
})
}, context, tstamp);
},
trackSiteSearch: function (terms, filters, totalResults, pageResults, context, tstamp) {
return trackSelfDescribingEvent({
schema: 'iglu:com.snowplowanalytics.snowplow/site_search/jsonschema/1-0-0',
data: removeEmptyProperties({
terms: terms,
filters: filters,
totalResults: totalResults,
pageResults: pageResults
})
}, context, tstamp);
}
};
}
exports.trackerCore = trackerCore;
//# sourceMappingURL=core.js.map

@@ -1,110 +0,62 @@

/*
* JavaScript tracker core for Snowplow: payload.js
*
* Copyright (c) 2014 Snowplow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
;(function() {
var
json2 = require('JSON'),
base64 = require('./base64'),
object = typeof exports !== 'undefined' ? exports : this;
/*
* Bas64 encode data with URL and Filename Safe Alphabet (base64url)
*
* See: http://tools.ietf.org/html/rfc4648#page-7
*/
function base64urlencode(data) {
if (!data) {
return data;
}
var enc = base64.base64encode(data);
return enc.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
}
/*
* Is property a JSON?
*/
object.isJson = function (property) {
return (typeof property !== 'undefined' && property !== null &&
(property.constructor === {}.constructor || property.constructor === [].constructor));
};
/*
* Is property a non-empty JSON?
*/
object.isNonEmptyJson = function (property) {
if (!object.isJson(property)) {
return false;
}
for (var key in property) {
if (property.hasOwnProperty(key)) {
return true;
}
}
return false;
}
/**
* A helper to build a Snowplow request string from an
* an optional initial value plus a set of individual
* name-value pairs, provided using the add method.
*
* @param boolean base64Encode Whether or not JSONs should be
* Base64-URL-safe-encoded
*
* @return object The request string builder, with add, addRaw and build methods
*/
object.payloadBuilder = function (base64Encode) {
var dict = {};
var add = function (key, value) {
if (value !== undefined && value !== null && value !== '') {
dict[key] = value;
}
};
var addDict = function (dict) {
for (var key in dict) {
if (dict.hasOwnProperty(key)) {
add(key, dict[key]);
}
}
};
var addJson = function (keyIfEncoded, keyIfNotEncoded, json) {
if (object.isNonEmptyJson(json)) {
var str = json2.stringify(json);
if (base64Encode) {
add(keyIfEncoded, base64urlencode(str));
} else {
add(keyIfNotEncoded, str);
}
}
};
return {
add: add,
addDict: addDict,
addJson: addJson,
build: function () {
return dict;
}
};
};
}());
"use strict";
var base64 = require('./base64');
function base64urlencode(data) {
if (!data) {
return data;
}
var enc = base64.base64encode(data);
return enc.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
}
function isNonEmptyJson(property) {
if (!isJson(property)) {
return false;
}
for (var key in property) {
if (property.hasOwnProperty(key)) {
return true;
}
}
return false;
}
exports.isNonEmptyJson = isNonEmptyJson;
function isJson(property) {
return (typeof property !== 'undefined' && property !== null &&
(property.constructor === {}.constructor || property.constructor === [].constructor));
}
exports.isJson = isJson;
function payloadBuilder(base64Encode) {
var dict = {};
var add = function (key, value) {
if (value != null && value !== '') {
dict[key] = value;
}
};
var addDict = function (dict) {
for (var key in dict) {
if (dict.hasOwnProperty(key)) {
add(key, dict[key]);
}
}
};
var addJson = function (keyIfEncoded, keyIfNotEncoded, json) {
if (isNonEmptyJson(json)) {
var str = JSON.stringify(json);
if (base64Encode) {
add(keyIfEncoded, base64urlencode(str));
}
else {
add(keyIfNotEncoded, str);
}
}
};
return {
add: add,
addDict: addDict,
addJson: addJson,
build: function () {
return dict;
}
};
}
exports.payloadBuilder = payloadBuilder;
//# sourceMappingURL=payload.js.map
{
"name": "snowplow-tracker-core",
"version": "0.4.0",
"version": "0.5.0-beta1",
"devDependencies": {
"grunt": "^0.4.5",
"intern": "^2.0.1"
"grunt": "0.4.5",
"intern": "3.3.2",
"dts-generator": "^2.0.0",
"grunt-ts": "5.5.1",
"typescript": "2.0.6",
"@types/uuid": "^2.0.29"
},

@@ -13,2 +17,3 @@ "contributors": [

],
"types": "./main.d.ts",
"description": "Core functionality for the Snowplow JavaScript trackers (browser JavaScript; Node.js; Segment.io server-side)",

@@ -28,5 +33,4 @@ "repository": {

"dependencies": {
"JSON": "^1.0.0",
"uuid": "^1.4.1"
"uuid": "2.0.3"
}
}
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc