diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 0000000..4507c13 --- /dev/null +++ b/.eslintignore @@ -0,0 +1,6 @@ +node_modules/ +.vscode/ +bulk_data/ +coverage/ +data/ +examples/ diff --git a/.eslintrc.js b/.eslintrc.js index c78eed4..ecc7ab3 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -1,185 +1,206 @@ module.exports = { + "extends": ["airbnb-base"], "env": { - "node": true - }, - "extends": "eslint:recommended", - "parserOptions": { - "ecmaVersion": 2017 + "node": true, + "mocha": true, + "es6": true, + "mongo": true }, "rules": { + "no-unused-vars": "warn", + "no-var" : "off", + "func-names": "off", + "consistent-return": "off", + "prefer-rest-params": "off", + "radix": "off", + "prefer-spread": "off", + "no-plusplus": "off", + "camelcase": "off", + "no-use-before-define": "off", + "no-lonely-if": "off", + "no-restricted-syntax": "off", + "vars-on-top": "off", + "no-param-reassign": "off", + "max-len": "off", + "guard-for-in": "off", + "no-underscore-dangle": "off", + "no-bitwise": "off", + "no-mixed-operators": "off", + "object-shorthand": "off", + //reassess till here ==== "block-spacing": [ - "error", - "always" - ], - "brace-style": [ - "error", - "stroustrup" - ], - "comma-spacing": [ - "error", - { - "before": false, - "after": true - } - ], - "comma-style": [ - "error", - "last" - ], - "computed-property-spacing": [ - "error", - "never" - ], - "curly": [ - "error", - "all" - ], - "eol-last": "off", - "func-call-spacing": [ - "error", - "never" - ], - "indent": [ - "error", - 4 - ], - "key-spacing": [ - "error", - { - "beforeColon": false, - "afterColon": true - } - ], - "keyword-spacing": [ - "error", - { - "before": true, - "after": true - } - ], - "lines-between-class-members": [ - "error", - "always" - ], - "no-multi-spaces": [ - "error" - ], - "no-trailing-spaces": [ - "error", - { - "ignoreComments": true - } - ], - "no-whitespace-before-property": [ - "error" - ], - "object-curly-newline": [ - "error", - { - "multiline": true, - "consistent": true - } - ], - "object-property-newline": [ - "error", - { - "allowAllPropertiesOnSameLine": true - } - ], - "semi": [ - "error", - "always" - ], - "semi-style": [ - "error", - "last" - ], - "space-before-blocks": [ - "error", - "always" - ], - "space-before-function-paren": [ - "error", - "never" - ], - "space-in-parens": [ - "error", - "never" - ], - "space-infix-ops": [ - "error" - ], - "space-unary-ops": [ - "error", - { - "words": true, - "nonwords": false - } - ], - "switch-colon-spacing": [ - "error" - ], - "unicode-bom": [ - "error", - "never" - ], - "linebreak-style": [ - "error", - "unix" - ], - "no-useless-escape": "off", - "quotes": "off", - "valid-jsdoc": [ - "error", - { - "requireReturn": false - } - ], - "require-jsdoc": [ - "error", - { - "require": { - "FunctionDeclaration": true, - "MethodDefinition": true, - "ClassDeclaration": true, - "ArrowFunctionExpression": true, - "FunctionExpression": false - } - } - ], - "no-console": [ - "error" - ], - "dot-notation": [ - "error" - ], - "eqeqeq": [ - "error", - "always" - ], - "no-alert": [ - "error" - ], - "no-caller": [ - "error" - ], - "no-eval": [ - "error" - ], - "no-extend-native": [ - "error" - ], - "no-iterator": [ - "error" - ], - "no-loop-func": [ - "error" - ], - "no-shadow": [ - "error" - ] + "error", + "always" + ], + "brace-style": [ + "error", + "stroustrup" + ], + "comma-spacing": [ + "error", + { + "before": false, + "after": true + } + ], + "comma-style": [ + "error", + "last" + ], + "computed-property-spacing": [ + "error", + "never" + ], + "curly": [ + "error", + "all" + ], + "eol-last": "off", + "func-call-spacing": [ + "error", + "never" + ], + "indent": [ + "error", + 4 + ], + "key-spacing": [ + "error", + { + "beforeColon": false, + "afterColon": true + } + ], + "keyword-spacing": [ + "error", + { + "before": true, + "after": true + } + ], + "lines-between-class-members": [ + "error", + "always" + ], + "no-multi-spaces": [ + "error" + ], + "no-trailing-spaces": [ + "error", + { + "ignoreComments": true + } + ], + "no-whitespace-before-property": [ + "error" + ], + "object-curly-newline": [ + "error", + { + "multiline": true, + "consistent": true + } + ], + "object-property-newline": [ + "error", + { + "allowAllPropertiesOnSameLine": true + } + ], + "semi": [ + "error", + "always" + ], + "semi-style": [ + "error", + "last" + ], + "space-before-blocks": [ + "error", + "always" + ], + "space-before-function-paren": [ + "error", + "never" + ], + "space-in-parens": [ + "error", + "never" + ], + "space-infix-ops": [ + "error" + ], + "space-unary-ops": [ + "error", + { + "words": true, + "nonwords": false + } + ], + "switch-colon-spacing": [ + "error" + ], + "unicode-bom": [ + "error", + "never" + ], + "linebreak-style": [ + "error", + "unix" + ], + "no-useless-escape": "off", + "quotes": "off", + "valid-jsdoc": [ + "error", + { + "requireReturn": false + } + ], + "require-jsdoc": [ + "error", + { + "require": { + "FunctionDeclaration": true, + "MethodDefinition": true, + "ClassDeclaration": true, + "ArrowFunctionExpression": true, + "FunctionExpression": false + } + } + ], + "no-console": [ + "error" + ], + "dot-notation": [ + "error" + ], + "eqeqeq": [ + "error", + "always" + ], + "no-alert": [ + "error" + ], + "no-caller": [ + "error" + ], + "no-eval": [ + "error" + ], + "no-extend-native": [ + "error" + ], + "no-iterator": [ + "error" + ], + "no-loop-func": [ + "error" + ], + "no-shadow": [ + "error" + ] }, - "overrides": [ + "overrides": [ { "files": [ "test/**/*.js", @@ -194,4 +215,4 @@ module.exports = { } } ] -}; \ No newline at end of file + }; \ No newline at end of file diff --git a/index.js b/index.js index 5083a2f..8744ab5 100644 --- a/index.js +++ b/index.js @@ -1 +1 @@ -module.exports = require("./lib/countly.js"); \ No newline at end of file +module.exports = require("./lib/countly"); \ No newline at end of file diff --git a/lib/countly-bulk-user.js b/lib/countly-bulk-user.js index 8bea0bb..b15bd84 100644 --- a/lib/countly-bulk-user.js +++ b/lib/countly-bulk-user.js @@ -46,22 +46,21 @@ var cc = require("./countly-common"); * user.begin_session().add_event({key:"Test", count:1}) */ function CountlyBulkUser(conf) { - "use strict"; - var sessionStart = 0, - maxKeyLength = 128, - maxValueSize = 256, - maxSegmentationValues = 30, - maxBreadcrumbCount = 100, - maxStackTraceLinesPerThread = 30, - maxStackTraceLineLength = 200, - lastParams = {}; + var sessionStart = 0; + var maxKeyLength = 128; + var maxValueSize = 256; + var maxSegmentationValues = 30; + var maxBreadcrumbCount = 100; + var maxStackTraceLinesPerThread = 30; + var maxStackTraceLineLength = 200; + var lastParams = {}; /** * Array with list of available features that you can require consent for */ var features = ["sessions", "events", "views", "crashes", "attribution", "users", "star-rating", "location", "apm", "feedback", "remote-config"]; - //create object to store consents + // create object to store consents var consents = {}; for (var feat = 0; feat < features.length; feat++) { consents[features[feat]] = {}; @@ -107,22 +106,22 @@ function CountlyBulkUser(conf) { for (var i in groupedFeatures) { if (!consents[i]) { if (typeof groupedFeatures[i] === "string") { - consents[i] = {features: [groupedFeatures[i]]}; + consents[i] = { features: [groupedFeatures[i]] }; } else if (groupedFeatures[i] && groupedFeatures[i].constructor === Array && groupedFeatures[i].length) { - consents[i] = {features: groupedFeatures[i]}; + consents[i] = { features: groupedFeatures[i] }; } else { - cc.log(cc.logLevelEnums.WARNING, "group_features, Incorrect feature list for " + i + " value: " + groupedFeatures[i]); + cc.log(cc.logLevelEnums.WARNING, `group_features, Incorrect feature list for ${i} value: ${groupedFeatures[i]}`); } } else { - cc.log(cc.logLevelEnums.WARNING, "group_features, Feature name " + i + " is already reserved"); + cc.log(cc.logLevelEnums.WARNING, `group_features, Feature name ${i} is already reserved`); } } } else { - cc.log(cc.logLevelEnums.WARNING, "group_features, Incorrect features: " + groupedFeatures); + cc.log(cc.logLevelEnums.WARNING, `group_features, Incorrect features: ${groupedFeatures}`); } }; @@ -133,21 +132,21 @@ function CountlyBulkUser(conf) { */ this.check_consent = function(feature) { if (!conf.require_consent) { - //we don't need to have specific consents - cc.log(cc.logLevelEnums.INFO, "check_consent, Require consent is off. Giving consent for : [ " + feature + " ] feature."); + // we don't need to have specific consents + cc.log(cc.logLevelEnums.INFO, `check_consent, Require consent is off. Giving consent for : [ ${feature} ] feature.`); return true; } if (consents[feature] && consents[feature].optin) { - cc.log(cc.logLevelEnums.INFO, "check_consent, Giving consent for : [ " + feature + " ] feature."); + cc.log(cc.logLevelEnums.INFO, `check_consent, Giving consent for : [ ${feature} ] feature.`); return true; } if (consents[feature] && !consents[feature].optin) { - cc.log(cc.logLevelEnums.ERROR, "check_consent, User is not optin. Consent refused for : [ " + feature + " ] feature."); + cc.log(cc.logLevelEnums.ERROR, `check_consent, User is not optin. Consent refused for : [ ${feature} ] feature.`); return false; } - else { - cc.log(cc.logLevelEnums.WARNING, "check_consent, No feature available for " + feature); - } + + cc.log(cc.logLevelEnums.WARNING, `check_consent, No feature available for ${feature}`); + return false; }; @@ -156,7 +155,7 @@ function CountlyBulkUser(conf) { * @param {string|array} feature - name of the feature, possible values, "sessions","events","views","crashes","attribution","users" or customly provided through {@link CountlyBulkUser.group_features} */ this.add_consent = function(feature) { - cc.log(cc.logLevelEnums.INFO, "add_consent, Adding consent for " + feature); + cc.log(cc.logLevelEnums.INFO, `add_consent, Adding consent for ${feature}`); if (feature.constructor === Array) { for (var i = 0; i < feature.length; i++) { this.add_consent(feature[i]); @@ -165,11 +164,11 @@ function CountlyBulkUser(conf) { else if (consents[feature]) { if (consents[feature].features) { consents[feature].optin = true; - //this is added group, let's iterate through sub features + // this is added group, let's iterate through sub features this.add_consent(consents[feature].features); } else { - //this is core feature + // this is core feature if (consents[feature].optin !== true) { consents[feature].optin = true; updateConsent(); @@ -187,17 +186,16 @@ function CountlyBulkUser(conf) { } } else { - cc.log(cc.logLevelEnums.WARNING, "add_consent, No feature available for " + feature); + cc.log(cc.logLevelEnums.WARNING, `add_consent, No feature available for ${feature}`); } }; - /** * Remove consent for specific feature, meaning, user opted out to track that data (either core feature of from custom feature group) * @param {string|array} feature - name of the feature, possible values, "sessions","events","views","crashes","attribution","users" or custom provided through {@link CountlyBulkUser.group_features} */ this.remove_consent = function(feature) { - cc.log(cc.logLevelEnums.INFO, "remove_consent, Removing consent for " + feature); + cc.log(cc.logLevelEnums.INFO, `remove_consent, Removing consent for ${feature}`); this.remove_consent_internal(feature, true); }; @@ -207,7 +205,7 @@ function CountlyBulkUser(conf) { * @param {Boolean} enforceConsentUpdate - regulates if a request will be sent to the server or not. If true, removing consents will send a request to the server and if false, consents will be removed without a request */ this.remove_consent_internal = function(feature, enforceConsentUpdate) { - //if true updateConsent will execute when possible + // if true updateConsent will execute when possible enforceConsentUpdate = enforceConsentUpdate || false; if (feature.constructor === Array) { for (var i = 0; i < feature.length; i++) { @@ -216,33 +214,31 @@ function CountlyBulkUser(conf) { } else if (consents[feature]) { if (consents[feature].features) { - //this is added group, let's iterate through sub features + // this is added group, let's iterate through sub features this.remove_consent_internal(consents[feature].features, enforceConsentUpdate); } else { consents[feature].optin = false; - //this is core feature + // this is core feature if (enforceConsentUpdate && consents[feature].optin !== false) { - updateConsent(); } } cc.log(cc.logLevelEnums.DEBUG, "remove_consent, Consent removal triggered."); - } else { - cc.log(cc.logLevelEnums.WARNING, "remove_consent, No feature available for " + feature); + cc.log(cc.logLevelEnums.WARNING, `remove_consent, No feature available for ${feature}`); } }; var consentTimer; var updateConsent = function() { if (consentTimer) { - //delay syncing consents + // delay syncing consents clearTimeout(consentTimer); consentTimer = null; } - consentTimer = setTimeout(function() { + consentTimer = setTimeout(() => { var consentMessage = {}; for (var i = 0; i < features.length; i++) { if (consents[features[i]].optin === true) { @@ -252,7 +248,7 @@ function CountlyBulkUser(conf) { consentMessage[features[i]] = false; } } - conf.server.add_bulk_request({consent: JSON.stringify(consentMessage)}); + conf.server.add_bulk_request({ consent: JSON.stringify(consentMessage) }); cc.log(cc.logLevelEnums.DEBUG, "Consent update request has been sent to the queue."); }, 1000); }; @@ -271,11 +267,11 @@ function CountlyBulkUser(conf) { * @param {number} seconds - how long did the session last in seconds * @param {number} timestamp - timestamp when session started * @returns {module:lib/countly-bulk-user} instance - **/ + * */ this.begin_session = function(metrics, seconds, timestamp) { if (this.check_consent("sessions")) { var bulk = []; - var query = prepareQuery({begin_session: 1, metrics: metrics}); + var query = prepareQuery({ begin_session: 1, metrics }); if (this.check_consent("location")) { if (conf.country_code) { query.country_code = conf.country_code; @@ -333,12 +329,12 @@ function CountlyBulkUser(conf) { * @param {number=} event.timestamp - timestamp when event occurred * @param {Object=} event.segmentation - object with segments key /values * @returns {module:lib/countly-bulk-user} instance - **/ + * */ this.add_event = function(event) { - cc.log('Trying to add the event: [ ' + event.key + ' ]'); - //initially no consent is given + cc.log(`Trying to add the event: [ ${event.key} ]`); + // initially no consent is given var respectiveConsent = false; - //to match the internal events and their respective required consents. Sets respectiveConsent to true if the consent is given + // to match the internal events and their respective required consents. Sets respectiveConsent to true if the consent is given switch (event.key) { case cc.internalEventKeyEnums.NPS: respectiveConsent = this.check_consent('feedback'); @@ -386,7 +382,7 @@ function CountlyBulkUser(conf) { * @param {number=} user.byear - user's birth year used to calculate current age * @param {Object=} user.custom - object with custom key value properties you want to save with user * @returns {module:lib/countly-bulk-user} instance - **/ + * */ this.user_details = function(user) { if (this.check_consent("users")) { user.name = cc.truncateSingleValue(user.name, conf.maxValueSize, "user_details"); @@ -399,7 +395,7 @@ function CountlyBulkUser(conf) { user.byear = cc.truncateSingleValue(user.byear, conf.maxValueSize, "user_details"); user.custom = cc.truncateObject(user.custom, conf.maxKeyLength, conf.maxValueSize, conf.maxSegmentationValues, "user_details"); var props = ["name", "username", "email", "organization", "phone", "picture", "gender", "byear", "custom"]; - var query = prepareQuery({user_details: cc.getProperties(user, props)}); + var query = prepareQuery({ user_details: cc.getProperties(user, props) }); conf.server.add_request(query); } return this; @@ -411,7 +407,7 @@ function CountlyBulkUser(conf) { * @param {string=} campaign_user_id - id of user's clicked on campaign link, if you have one or provide null * @param {number=} timestamp - timestamp of the conversion * @returns {module:lib/countly-bulk-user} instance - **/ + * */ this.report_conversion = function(campaign_id, campaign_user_id, timestamp) { if (this.check_consent("attribution")) { var query = prepareQuery(); @@ -449,19 +445,19 @@ function CountlyBulkUser(conf) { * @param {boolean=} viewSegments.bounce - true if user bounced having only one view and without much interaction with the app * @param {boolean=} viewSegments.{any} - provide any other key value pairs to store with view * @returns {module:lib/countly-bulk-user} instance - **/ + * */ this.report_view = function(view_name, timestamp, duration, viewSegments) { view_name = cc.truncateSingleValue(view_name, conf.maxValueSize, "report_view"); if (this.check_consent("views")) { var event = { - "key": cc.internalEventKeyEnums.VIEW, - "dur": duration, - "count": 1, - "segmentation": { - "name": view_name, - "visit": 1, - } + key: cc.internalEventKeyEnums.VIEW, + dur: duration, + count: 1, + segmentation: { + name: view_name, + visit: 1, + }, }; if (viewSegments) { @@ -472,7 +468,7 @@ function CountlyBulkUser(conf) { } } - var query = prepareQuery({events: [event]}); + var query = prepareQuery({ events: [event] }); if (timestamp) { query.timestamp = timestamp; } @@ -496,7 +492,7 @@ function CountlyBulkUser(conf) { * @param {string=} feedback.comment - user's comment * @param {number=} timestamp - timestamp when feedback was acquired * @returns {module:lib/countly-bulk-user} instance - **/ + * */ this.report_feedback = function(feedback, timestamp) { if (this.check_consent("star-rating") || this.check_consent("feedback")) { if (!feedback.widget_id) { @@ -512,7 +508,7 @@ function CountlyBulkUser(conf) { var event = { key: cc.internalEventKeyEnums.STAR_RATING, count: 1, - segmentation: {} + segmentation: {}, }; if (timestamp) { event.timestamp = timestamp; @@ -566,35 +562,35 @@ function CountlyBulkUser(conf) { * Report crash * @param {Object} crash - object containing information about crash and state of device * @param {string} crash._os - Platform/OS of the device, - * @param {string} crash._os_version - Platform's/OS version - * @param {string=} crash._manufacture - manufacture of the device - * @param {string=} crash._device - device model - * @param {string=} crash._resolution - device resolution - * @param {string} crash._app_version - version of the app that crashed - * @param {string=} crash._cpu - type of cpu used on device (for ios will be based on device) - * @param {string=} crash._opengl - version of open gl supported - * @param {number=} crash._ram_current - used amount of ram at the time of crash in megabytes - * @param {number=} crash._ram_total - total available amount of ram in megabytes - * @param {number=} crash._disk_current - used amount of disk space at the time of crash in megabytes - * @param {number=} crash._disk_total - total amount of disk space in megabytes + * @param {string} crash._os_version - Platform's/OS version + * @param {string=} crash._manufacture - manufacture of the device + * @param {string=} crash._device - device model + * @param {string=} crash._resolution - device resolution + * @param {string} crash._app_version - version of the app that crashed + * @param {string=} crash._cpu - type of cpu used on device (for ios will be based on device) + * @param {string=} crash._opengl - version of open gl supported + * @param {number=} crash._ram_current - used amount of ram at the time of crash in megabytes + * @param {number=} crash._ram_total - total available amount of ram in megabytes + * @param {number=} crash._disk_current - used amount of disk space at the time of crash in megabytes + * @param {number=} crash._disk_total - total amount of disk space in megabytes * @param {number=} crash._bat - battery level from 0 to 100 - * @param {string=} crash._orientation - orientation in which device was held, landscape, portrait, etc - * @param {boolean=} crash._root - true if device is rooted/jailbroken, false or not provided if not - * @param {boolean=} crash._online - true if device is connected to the internet (WiFi or 3G), false or not provided if not connected - * @param {boolean=} crash._muted - true if volume is off, device is in muted state - * @param {boolean=} crash._background - true if app was in background when it crashed - * @param {string=} crash._name - identfiiable name of the crash if provided by OS/Platform, else will use first line of stack - * @param {string} crash._error - error stack, can provide multiple separated by blank new lines - * @param {boolean=} crash._nonfatal - true if handled exception, false or not provided if unhandled crash - * @param {string=} crash._logs - some additional logs provided, if any - * @param {number=} crash._run - running time since app start in seconds until crash - * @param {string=} crash._custom - custom key values to record with crash report, like versions of other libraries and frameworks used, etc. + * @param {string=} crash._orientation - orientation in which device was held, landscape, portrait, etc + * @param {boolean=} crash._root - true if device is rooted/jailbroken, false or not provided if not + * @param {boolean=} crash._online - true if device is connected to the internet (WiFi or 3G), false or not provided if not connected + * @param {boolean=} crash._muted - true if volume is off, device is in muted state + * @param {boolean=} crash._background - true if app was in background when it crashed + * @param {string=} crash._name - identfiiable name of the crash if provided by OS/Platform, else will use first line of stack + * @param {string} crash._error - error stack, can provide multiple separated by blank new lines + * @param {boolean=} crash._nonfatal - true if handled exception, false or not provided if unhandled crash + * @param {string=} crash._logs - some additional logs provided, if any + * @param {number=} crash._run - running time since app start in seconds until crash + * @param {string=} crash._custom - custom key values to record with crash report, like versions of other libraries and frameworks used, etc. * @param {number} timestamp - when crash happened * @returns {module:lib/countly-bulk-user} instance - **/ + * */ this.report_crash = function(crash, timestamp) { if (this.check_consent("crashes")) { - var query = prepareQuery({crash: crash}); + var query = prepareQuery({ crash: crash }); if (timestamp) { query.timestamp = timestamp; } @@ -646,7 +642,7 @@ function CountlyBulkUser(conf) { * user.custom_push_unique("selected_category", "IT"); * //send all custom property modified data to server * user.custom_save(); - **/ + * */ this.custom_set = function(key, value) { key = cc.truncateSingleValue(key, conf.maxKeyLength, "custom_set"); value = cc.truncateSingleValue(value, conf.maxValueSize, "custom_set"); @@ -658,7 +654,7 @@ function CountlyBulkUser(conf) { * @param {string} key - name of the property to attach to user * @param {string|number} value - value to store under provided property * @returns {module:lib/countly-bulk-user} instance - **/ + * */ this.custom_set_once = function(key, value) { key = cc.truncateSingleValue(key, conf.maxKeyLength, "custom_set_once"); value = cc.truncateSingleValue(value, conf.maxValueSize, "custom_set_once"); @@ -669,7 +665,7 @@ function CountlyBulkUser(conf) { * Unset's/delete's user's custom property * @param {string} key - name of the property to delete * @returns {module:lib/countly-bulk-user} instance - **/ + * */ this.custom_unset = function(key) { key = cc.truncateSingleValue(key, conf.maxKeyLength, "custom_unset"); customData[key] = ""; @@ -679,7 +675,7 @@ function CountlyBulkUser(conf) { * Increment value under the key of this user's custom properties by one * @param {string} key - name of the property to attach to user * @returns {module:lib/countly-bulk-user} instance - **/ + * */ this.custom_increment = function(key) { key = cc.truncateSingleValue(key, conf.maxKeyLength, "custom_increment"); change_custom_property(key, 1, "$inc"); @@ -690,7 +686,7 @@ function CountlyBulkUser(conf) { * @param {string} key - name of the property to attach to user * @param {number} value - value by which to increment server value * @returns {module:lib/countly-bulk-user} instance - **/ + * */ this.custom_increment_by = function(key, value) { key = cc.truncateSingleValue(key, conf.maxKeyLength, "custom_increment_by"); value = cc.truncateSingleValue(value, conf.maxValueSize, "custom_increment_by"); @@ -702,7 +698,7 @@ function CountlyBulkUser(conf) { * @param {string} key - name of the property to attach to user * @param {number} value - value by which to multiply server value * @returns {module:lib/countly-bulk-user} instance - **/ + * */ this.custom_multiply = function(key, value) { key = cc.truncateSingleValue(key, conf.maxKeyLength, "custom_multiply"); value = cc.truncateSingleValue(value, conf.maxValueSize, "custom_multiply"); @@ -714,7 +710,7 @@ function CountlyBulkUser(conf) { * @param {string} key - name of the property to attach to user * @param {number} value - value which to compare to server's value and store maximal value of both provided * @returns {module:lib/countly-bulk-user} instance - **/ + * */ this.custom_max = function(key, value) { key = cc.truncateSingleValue(key, conf.maxKeyLength, "custom_max"); value = cc.truncateSingleValue(value, conf.maxValueSize, "custom_max"); @@ -726,7 +722,7 @@ function CountlyBulkUser(conf) { * @param {string} key - name of the property to attach to user * @param {number} value - value which to compare to server's value and store minimal value of both provided * @returns {module:lib/countly-bulk-user} instance - **/ + * */ this.custom_min = function(key, value) { key = cc.truncateSingleValue(key, conf.maxKeyLength, "custom_min"); value = cc.truncateSingleValue(value, conf.maxValueSize, "custom_min"); @@ -738,7 +734,7 @@ function CountlyBulkUser(conf) { * @param {string} key - name of the property to attach to user * @param {string|number} value - value which to add to array * @returns {module:lib/countly-bulk-user} instance - **/ + * */ this.custom_push = function(key, value) { key = cc.truncateSingleValue(key, conf.maxKeyLength, "custom_push"); value = cc.truncateSingleValue(value, conf.maxValueSize, "custom_push"); @@ -750,7 +746,7 @@ function CountlyBulkUser(conf) { * @param {string} key - name of the property to attach to user * @param {string|number} value - value which to add to array * @returns {module:lib/countly-bulk-user} instance - **/ + * */ this.custom_push_unique = function(key, value) { key = cc.truncateSingleValue(key, conf.maxKeyLength, "custom_push_unique"); value = cc.truncateSingleValue(value, conf.maxValueSize, "custom_push_unique"); @@ -762,7 +758,7 @@ function CountlyBulkUser(conf) { * @param {string} key - name of the property * @param {string|number} value - value which to remove from array * @returns {module:lib/countly-bulk-user} instance - **/ + * */ this.custom_pull = function(key, value) { key = cc.truncateSingleValue(key, conf.maxKeyLength, "custom_pull"); value = cc.truncateSingleValue(value, conf.maxValueSize, "custom_pull"); @@ -772,10 +768,10 @@ function CountlyBulkUser(conf) { /** * Save changes made to user's custom properties object and send them to server * @returns {module:lib/countly-bulk-user} instance - **/ + * */ this.custom_save = function() { if (this.check_consent("users")) { - var query = prepareQuery({user_details: {custom: customData}}); + var query = prepareQuery({ user_details: { custom: customData } }); conf.server.add_request(query); } customData = {}; @@ -797,8 +793,6 @@ function CountlyBulkUser(conf) { } return query; } - - } module.exports = CountlyBulkUser; diff --git a/lib/countly-bulk.js b/lib/countly-bulk.js index db38e27..7114a84 100644 --- a/lib/countly-bulk.js +++ b/lib/countly-bulk.js @@ -18,14 +18,13 @@ * server.add_request({begin_session:1, metrics:{_os:"Linux"}, device_id:"users_device_id", events:[{key:"Test", count:1}]}); */ -var fs = require("fs"), - path = require("path"), - http = require("http"), - https = require("https"), - cluster = require("cluster"), - cc = require("./countly-common"), - BulkUser = require("./countly-bulk-user"); - +var fs = require("fs"); +var path = require("path"); +var http = require("http"); +var https = require("https"); +var cluster = require("cluster"); +var cc = require("./countly-common"); +var BulkUser = require("./countly-bulk-user"); /** * @lends module:lib/countly-bulk @@ -57,26 +56,24 @@ var fs = require("fs"), * }); */ function CountlyBulk(conf) { - "use strict"; - var SDK_VERSION = "21.11.0"; var SDK_NAME = "javascript_native_nodejs_bulk"; var empty_queue_callback = null; - var initiated = false, - lastMsTs = 0, - apiPath = "/i/bulk", - failTimeout = 0, - empty_count = 0, - readyToProcess = true, - maxKeyLength = 128, - maxValueSize = 256, - maxSegmentationValues = 30, - maxBreadcrumbCount = 100, - maxStackTraceLinesPerThread = 30, - maxStackTraceLineLength = 200, - __data = {}; + var initiated = false; + var lastMsTs = 0; + var apiPath = "/i/bulk"; + var failTimeout = 0; + var empty_count = 0; + var readyToProcess = true; + var maxKeyLength = 128; + var maxValueSize = 256; + var maxSegmentationValues = 30; + var maxBreadcrumbCount = 100; + var maxStackTraceLinesPerThread = 30; + var maxStackTraceLineLength = 200; + var __data = {}; cc.debugBulk = conf.debug || false; if (!conf.app_key) { @@ -108,7 +105,6 @@ function CountlyBulk(conf) { conf.maxStackTraceLinesPerThread = conf.max_stack_trace_lines_per_thread || maxStackTraceLinesPerThread; conf.maxStackTraceLineLength = conf.max_stack_trace_line_length || maxStackTraceLineLength; - var mainDir = path.resolve(__dirname, conf.storage_path); if (conf.persist_queue) { try { @@ -117,7 +113,7 @@ function CountlyBulk(conf) { } } catch (ex) { - //problem creating directory + // problem creating directory // eslint-disable-next-line no-console console.log(ex.stack); } @@ -135,7 +131,7 @@ function CountlyBulk(conf) { * server.add_request({app_key:"somekey", devide_id:"someid", events:"[{'key':'val','count':1}]", begin_session:1}); * @param {Object} query - object with key/values which will be used as query string parameters * @returns {module:lib/countly-bulk} instance - **/ + * */ this.add_request = function(query) { query = cc.truncateObject(query, self.maxKeyLength, self.maxValueSize, self.maxSegmentationValues, "add_request", self.debug); if (cluster.isMaster) { @@ -148,13 +144,13 @@ function CountlyBulk(conf) { query.app_key = conf.app_key; } - if ((query.timestamp + "").length !== 13 && (query.timestamp + "").length !== 10) { + if ((`${query.timestamp}`).length !== 13 && (`${query.timestamp}`).length !== 10) { cc.log(cc.logLevelEnums.ERROR, "add_request, incorrect timestamp format", query); } query.sdk_name = SDK_NAME; query.sdk_version = SDK_VERSION; query.timestamp = query.timestamp || getMsTimestamp(); - var date = new Date((query.timestamp + "").length === 13 ? query.timestamp : parseInt(query.timestamp) * 1000); + var date = new Date((`${query.timestamp}`).length === 13 ? query.timestamp : parseInt(query.timestamp) * 1000); query.hour = query.hour || date.getHours(); query.dow = query.dow || date.getDay(); @@ -163,7 +159,7 @@ function CountlyBulk(conf) { storeSet("cly_req_queue", requestQueue); } else { - process.send({ cly_bulk: {cly_queue: query} }); + process.send({ cly_bulk: { cly_queue: query } }); } return this; }; @@ -179,7 +175,7 @@ function CountlyBulk(conf) { * server.add_bulk_request([{app_key:"somekey", devide_id:"someid", begin_session:1}, {app_key:"somekey", devide_id:"someid", events:"[{'key':'val','count':1}]"}]); * @param {Array} requests - array with multiple request objects that can be provided with {@link CountlyBulk.add_request} * @returns {module:lib/countly-bulk} instance - **/ + * */ this.add_bulk_request = function(requests) { if (cluster.isMaster) { var query; @@ -194,14 +190,14 @@ function CountlyBulk(conf) { query.app_key = conf.app_key; } - if ((query.timestamp + "").length !== 13 && (query.timestamp + "").length !== 10) { + if ((`${query.timestamp}`).length !== 13 && (`${query.timestamp}`).length !== 10) { cc.log(cc.logLevelEnums.ERROR, "add_bulk_request, incorrect timestamp format", query); } query.sdk_name = SDK_NAME; query.sdk_version = SDK_VERSION; query.timestamp = query.timestamp || getMsTimestamp(); - var date = new Date((query.timestamp + "").length === 13 ? query.timestamp : parseInt(query.timestamp) * 1000); + var date = new Date((`${query.timestamp}`).length === 13 ? query.timestamp : parseInt(query.timestamp) * 1000); query.hour = query.hour || date.getHours(); query.dow = query.dow || date.getDay(); cc.log(cc.logLevelEnums.INFO, "add_bulk_request, adding bulk request", query); @@ -210,7 +206,7 @@ function CountlyBulk(conf) { storeSet("cly_req_queue", requestQueue); } else { - process.send({ cly_bulk: {cly_bulk_queue: requests} }); + process.send({ cly_bulk: { cly_bulk_queue: requests } }); } return this; }; @@ -233,7 +229,7 @@ function CountlyBulk(conf) { * @param {Object=} event.segmentation - object with segments key /values * @param {number=} event.timestamp - timestamp when event occurred * @returns {module:lib/countly-bulk} instance - **/ + * */ this.add_event = function(device_id, event) { if (!device_id) { cc.log(cc.logLevelEnums.ERROR, "add_event, device_id is missing"); @@ -253,7 +249,7 @@ function CountlyBulk(conf) { var props = ["key", "count", "sum", "dur", "segmentation", "timestamp"]; var e = cc.getProperties(event, props); e.timestamp = e.timestamp || getMsTimestamp(); - var date = new Date((e.timestamp + "").length === 13 ? e.timestamp : parseInt(e.timestamp) * 1000); + var date = new Date((`${e.timestamp}`).length === 13 ? e.timestamp : parseInt(e.timestamp) * 1000); e.hour = date.getHours(); e.dow = date.getDay(); cc.log(cc.logLevelEnums.INFO, "add_event, Adding event: ", event); @@ -264,7 +260,7 @@ function CountlyBulk(conf) { storeSet("cly_bulk_event", eventQueue); } else { - process.send({ cly_bulk: {device_id: device_id, event: event} }); + process.send({ cly_bulk: { device_id: device_id, event: event } }); } return this; }; @@ -280,7 +276,7 @@ function CountlyBulk(conf) { * debug: true * }); * server.start(); - **/ + * */ this.start = function(callback) { if (cluster.isMaster) { if (!initiated) { @@ -302,7 +298,7 @@ function CountlyBulk(conf) { * debug: true * }); * server.stop(); - **/ + * */ this.stop = function() { initiated = false; return this; @@ -319,7 +315,7 @@ function CountlyBulk(conf) { * }); * server.add_request({device_id:"id", app_key:"key", begin_session:1}); * server.queue_size(); //should return 1 - **/ + * */ this.queue_size = function() { var eventCount = 0; for (var i in eventQueue) { @@ -343,7 +339,7 @@ function CountlyBulk(conf) { * debug: true * }); * var user = server.add_user({device_id:"my_device_id"}); - **/ + * */ this.add_user = function(userConf) { userConf = cc.truncateObject(userConf, self.maxKeyLength, self.maxValueSize, self.maxSegmentationValues, "add_user", self.debug); userConf.server = this; @@ -365,18 +361,18 @@ function CountlyBulk(conf) { */ function heartBeat() { var isEmpty = true; - //process event queue + // process event queue var eventChanges = false; for (var device_id in eventQueue) { if (eventQueue[device_id].length > 0) { eventChanges = true; if (eventQueue[device_id].length <= conf.max_events) { - self.add_request({device_id: device_id, events: eventQueue[device_id]}); + self.add_request({ device_id: device_id, events: eventQueue[device_id] }); eventQueue[device_id] = []; } else { var events = eventQueue[device_id].splice(0, conf.max_events); - self.add_request({device_id: device_id, events: events}); + self.add_request({ device_id: device_id, events: events }); } } } @@ -385,27 +381,27 @@ function CountlyBulk(conf) { storeSet("cly_bulk_event", eventQueue); } - //process request queue into bulk requests + // process request queue into bulk requests if (requestQueue.length > 0) { isEmpty = false; if (requestQueue.length <= conf.bulk_size) { - toBulkRequestQueue({app_key: conf.app_key, requests: JSON.stringify(requestQueue)}); + toBulkRequestQueue({ app_key: conf.app_key, requests: JSON.stringify(requestQueue) }); requestQueue = []; } else { var requests = requestQueue.splice(0, conf.bulk_size); - toBulkRequestQueue({app_key: conf.app_key, requests: JSON.stringify(requests)}); + toBulkRequestQueue({ app_key: conf.app_key, requests: JSON.stringify(requests) }); } storeSet("cly_req_queue", requestQueue); } - //process bulk request queue + // process bulk request queue if (bulkQueue.length > 0 && readyToProcess && cc.getTimestamp() > failTimeout) { isEmpty = false; readyToProcess = false; var params = bulkQueue.shift(); cc.log(cc.logLevelEnums.DEBUG, "Processing request", params); - makeRequest(params, function(err, res) { + makeRequest(params, (err, res) => { cc.log(cc.logLevelEnums.DEBUG, "Request Finished", res, err); if (err) { bulkQueue.unshift(res); @@ -431,7 +427,6 @@ function CountlyBulk(conf) { } } - /** * Get unique timestamp in miliseconds * @returns {number} miliseconds timestamp @@ -455,7 +450,7 @@ function CountlyBulk(conf) { function parseUrl(url) { var serverOptions = { host: "localhost", - port: 80 + port: 80, }; if (url.indexOf("https") === 0) { serverOptions.port = 443; @@ -478,12 +473,11 @@ function CountlyBulk(conf) { function prepareParams(params) { var str = []; for (var i in params) { - str.push(i + "=" + encodeURIComponent(params[i])); + str.push(`${i}=${encodeURIComponent(params[i])}`); } return str.join("&"); } - /** * Making HTTP request * @param {Object} params - key value object with URL params @@ -498,8 +492,8 @@ function CountlyBulk(conf) { var options = { host: serverOptions.host, port: serverOptions.port, - path: apiPath + "?" + data, - method: "GET" + path: `${apiPath}?${data}`, + method: "GET", }; if (data.length >= 2000) { @@ -514,7 +508,7 @@ function CountlyBulk(conf) { options.path = apiPath; options.headers = { "Content-Type": "application/x-www-form-urlencoded", - "Content-Length": Buffer.byteLength(data) + "Content-Length": Buffer.byteLength(data), }; } if (typeof conf.http_options === "function") { @@ -524,13 +518,13 @@ function CountlyBulk(conf) { if (conf.url.indexOf("https") === 0) { protocol = https; } - var req = protocol.request(options, function(res) { + var req = protocol.request(options, (res) => { var str = ""; - res.on("data", function(chunk) { + res.on("data", (chunk) => { str += chunk; }); - res.on("end", function() { + res.on("end", () => { // checks result field, JSON format and status code if (cc.isResponseValid(res.statusCode, str)) { callback(false, params); @@ -545,7 +539,7 @@ function CountlyBulk(conf) { req.write(data); } - req.on("error", function(err) { + req.on("error", (err) => { cc.log(cc.logLevelEnums.ERROR, "Connection failed.", err); if (typeof callback === "function") { callback(true, params); @@ -563,7 +557,6 @@ function CountlyBulk(conf) { } } - /** * Handle messages from forked workers * @param {Object} msg - message from worker @@ -590,28 +583,28 @@ function CountlyBulk(conf) { var readFile = function(key) { var data; if (conf.persist_queue) { - var dir = path.resolve(__dirname, conf.storage_path + "__" + key + ".json"); + var dir = path.resolve(__dirname, `${conf.storage_path}__${key}.json`); - //try reading data file + // try reading data file try { data = fs.readFileSync(dir); } catch (ex) { - //ther was no file, probably new init + // there was no file, probably new init data = null; } try { - //trying to parse json string + // trying to parse json string data = JSON.parse(data); } catch (ex) { - //problem parsing, corrupted file? + // problem parsing, corrupted file? // eslint-disable-next-line no-console console.log(ex.stack); - //backup corrupted file data - fs.writeFile(path.resolve(__dirname, conf.storage_path + "__" + key + "." + cc.getTimestamp() + Math.random() + ".json"), data, function() {}); - //start with new clean object + // backup corrupted file data + fs.writeFile(path.resolve(__dirname, `${conf.storage_path}__${key}.${cc.getTimestamp()}${Math.random()}.json`), data, () => {}); + // start with new clean object data = null; } } @@ -630,8 +623,8 @@ function CountlyBulk(conf) { var writeFile = function(key, value, callback) { var ob = {}; ob[key] = value; - var dir = path.resolve(__dirname, conf.storage_path + "__" + key + ".json"); - fs.writeFile(dir, JSON.stringify(ob), function(err) { + var dir = path.resolve(__dirname, `${conf.storage_path}__${key}.json`); + fs.writeFile(dir, JSON.stringify(ob), (err) => { if (err) { // eslint-disable-next-line no-console console.log(err); @@ -640,7 +633,7 @@ function CountlyBulk(conf) { callback(err); } if (asyncWriteQueue.length) { - setTimeout(function() { + setTimeout(() => { var arr = asyncWriteQueue.shift(); writeFile(arr[0], arr[1], arr[2]); }, 0); @@ -687,21 +680,21 @@ function CountlyBulk(conf) { return __data[key]; }; - //listen to current workers + // listen to current workers if (cluster.workers) { for (var id in cluster.workers) { cluster.workers[id].on("message", handleWorkerMessage); } } - //handle future workers - cluster.on("fork", function(worker) { + // handle future workers + cluster.on("fork", (worker) => { worker.on("message", handleWorkerMessage); }); - var requestQueue = storeGet("cly_req_queue", []), - eventQueue = storeGet("cly_bulk_event", {}), - bulkQueue = storeGet("cly_bulk_queue", []); + var requestQueue = storeGet("cly_req_queue", []); + var eventQueue = storeGet("cly_bulk_event", {}); + var bulkQueue = storeGet("cly_bulk_queue", []); } module.exports = CountlyBulk; diff --git a/lib/countly-common.js b/lib/countly-common.js index 4d0212b..34397a9 100644 --- a/lib/countly-common.js +++ b/lib/countly-common.js @@ -3,7 +3,7 @@ */ var cc = { - //debug value from Countly + // debug value from Countly debug: false, debugBulk: false, debugBulkUser: false, @@ -40,7 +40,7 @@ var cc = { VIEW: '[CLY]_view', ORIENTATION: '[CLY]_orientation', PUSH_ACTION: '[CLY]_push_action', - ACTION: '[CLY]_action' + ACTION: '[CLY]_action', }, /** @@ -99,7 +99,7 @@ var cc = { newStr = str.substring(0, limit); if ((this.debug || this.debugBulk || this.debugBulkUser) && typeof console !== "undefined") { // eslint-disable-next-line no-console - console.log(errorLog + ", Key: [" + str + "] is longer than accepted length. It will be truncated."); + console.log(`${errorLog}, Key: [${str}] is longer than accepted length. It will be truncated.`); } } } @@ -140,7 +140,7 @@ var cc = { */ generateUUID: function generateUUID() { var d = new Date().getTime(); - var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) { + var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { var r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c === "x" ? r : (r & 0x3 | 0x8)).toString(16); @@ -174,7 +174,7 @@ var cc = { console.info(level + message, Array.prototype.slice.call(args).join("\n")); } else { - //default log level is DEBUG + // default log level is DEBUG level = this.logLevelEnums.DEBUG; // eslint-disable-next-line no-console console.debug(level + message, Array.prototype.slice.call(args).join("\n")); @@ -196,16 +196,15 @@ var cc = { return false; } - //Try to parse JSON + // Try to parse JSON try { - return JSON.parse(str).result ? true : false; + return !!JSON.parse(str).result; } catch (e) { this.log("Http response is in the wrong format.", e); return false; } - } + }, }; - module.exports = cc; \ No newline at end of file diff --git a/lib/countly.js b/lib/countly.js index 5c575f7..5645a8c 100644 --- a/lib/countly.js +++ b/lib/countly.js @@ -1,7 +1,7 @@ -/************ +/** ********** * Countly NodeJS SDK * https://github.com/Countly/countly-sdk-nodejs -************/ +*********** */ /** * Countly object to manage the internal queue and send requests to Countly server. More information on {@link http://resources.count.ly/docs/countly-sdk-for-nodejs} @@ -20,73 +20,70 @@ * Countly.begin_session(); */ -var fs = require("fs"), - os = require("os"), - path = require("path"), - http = require("http"), - https = require("https"), - cluster = require("cluster"), - cc = require("./countly-common"), - Bulk = require("./countly-bulk"); +var fs = require("fs"); +var os = require("os"); +var path = require("path"); +var http = require("http"); +var https = require("https"); +var cluster = require("cluster"); +var cc = require("./countly-common"); +var Bulk = require("./countly-bulk"); var Countly = {}; Countly.Bulk = Bulk; (function() { - "use strict"; - var SDK_VERSION = "21.11.0"; var SDK_NAME = "javascript_native_nodejs"; - var inited = false, - sessionStarted = false, - platform, - apiPath = "/i", - readPath = "/o/sdk", - beatInterval = 500, - queueSize = 1000, - requestQueue = [], - eventQueue = [], - remoteConfigs = {}, - crashLogs = [], - timedEvents = {}, - crashSegments = null, - autoExtend = true, - lastBeat, - storedDuration = 0, - lastView = null, - lastViewTime = 0, - lastMsTs = 0, - lastViewStoredDuration = 0, - failTimeout = 0, - failTimeoutAmount = 60, - sessionUpdate = 60, - maxEventBatch = 100, - readyToProcess = true, - trackTime = true, - metrics = {}, - lastParams = {}, - startTime, - maxKeyLength = 128, - maxValueSize = 256, - maxSegmentationValues = 30, - maxBreadcrumbCount = 100, - maxStackTraceLinesPerThread = 30, - maxStackTraceLineLength = 200, - __data = {}; + var inited = false; + var sessionStarted = false; + var platform; + var apiPath = "/i"; + var readPath = "/o/sdk"; + var beatInterval = 500; + var queueSize = 1000; + var requestQueue = []; + var eventQueue = []; + var remoteConfigs = {}; + var crashLogs = []; + var timedEvents = {}; + var crashSegments = null; + var autoExtend = true; + var lastBeat; + var storedDuration = 0; + var lastView = null; + var lastViewTime = 0; + var lastMsTs = 0; + var lastViewStoredDuration = 0; + var failTimeout = 0; + var failTimeoutAmount = 60; + var sessionUpdate = 60; + var maxEventBatch = 100; + var readyToProcess = true; + var trackTime = true; + var metrics = {}; + var lastParams = {}; + var startTime; + var maxKeyLength = 128; + var maxValueSize = 256; + var maxSegmentationValues = 30; + var maxBreadcrumbCount = 100; + var maxStackTraceLinesPerThread = 30; + var maxStackTraceLineLength = 200; + var __data = {}; /** * Array with list of available features that you can require consent for */ Countly.features = ["sessions", "events", "views", "crashes", "attribution", "users", "location", "star-rating", "apm", "feedback", "remote-config"]; - //create object to store consents + // create object to store consents var consents = {}; for (var feat = 0; feat < Countly.features.length; feat++) { consents[Countly.features[feat]] = {}; } - /** * Initialize Countly object * @param {Object} conf - Countly initialization {@link Init} object with configuration options @@ -178,7 +175,7 @@ Countly.Bulk = Bulk; } } catch (ex) { - //problem creating dir + // problem creating dir // eslint-disable-next-line no-console console.log(ex.stack); } @@ -195,14 +192,14 @@ Countly.Bulk = Bulk; eventQueue = storeGet("cly_event", []); remoteConfigs = storeGet("cly_remote_configs", {}); heartBeat(); - //listen to current workers + // listen to current workers if (cluster.workers) { for (var id in cluster.workers) { cluster.workers[id].on("message", handleWorkerMessage); } } - //handle future workers - cluster.on("fork", function(worker) { + // handle future workers + cluster.on("fork", (worker) => { worker.on("message", handleWorkerMessage); }); if (Countly.remote_config) { @@ -213,7 +210,6 @@ Countly.Bulk = Bulk; } }; - /** * WARNING!!! * Should be used only for testing purposes!!! @@ -256,18 +252,18 @@ Countly.Bulk = Bulk; maxStackTraceLineLength = 200; __data = {}; - //cc DEBUG + // cc DEBUG cc.debug = false; cc.debugBulk = false; cc.debugBulkUser = false; - //CONSENTS + // CONSENTS consents = {}; for (var a = 0; a < Countly.features.length; a++) { consents[Countly.features[a]] = {}; } - //device_id + // device_id Countly.device_id = undefined; Countly.remote_config = undefined; Countly.require_consent = false; @@ -285,7 +281,6 @@ Countly.Bulk = Bulk; asyncWriteLock = false; asyncWriteQueue = []; - }; /** @@ -309,22 +304,22 @@ Countly.Bulk = Bulk; if (!consents[i]) { cc.log(cc.logLevelEnums.INFO, "group_features, Trying to group the features"); if (typeof features[i] === "string") { - consents[i] = {features: [features[i]]}; + consents[i] = { features: [features[i]] }; } else if (features[i] && features[i].constructor === Array && features[i].length) { - consents[i] = {features: features[i]}; + consents[i] = { features: features[i] }; } else { - cc.log(cc.logLevelEnums.WARNING, "group_features, Incorrect feature list for " + i + " value: " + features[i]); + cc.log(cc.logLevelEnums.WARNING, `group_features, Incorrect feature list for ${i} value: ${features[i]}`); } } else { - cc.log(cc.logLevelEnums.WARNING, "group_features, Feature name " + i + " is already reserved"); + cc.log(cc.logLevelEnums.WARNING, `group_features, Feature name ${i} is already reserved`); } } } else { - cc.log(cc.logLevelEnums.ERROR, "group_features, Incorrect features: " + features); + cc.log(cc.logLevelEnums.ERROR, `group_features, Incorrect features: ${features}`); } }; @@ -335,21 +330,21 @@ Countly.Bulk = Bulk; */ Countly.check_consent = function(feature) { if (!Countly.require_consent) { - //we don't need to have specific consents - cc.log(cc.logLevelEnums.INFO, "check_consent, Require consent is off. Giving consent for : [ " + feature + " ] feature."); + // we don't need to have specific consents + cc.log(cc.logLevelEnums.INFO, `check_consent, Require consent is off. Giving consent for : [ ${feature} ] feature.`); return true; } if (consents[feature] && consents[feature].optin) { - cc.log(cc.logLevelEnums.INFO, "check_consent, Giving consent for : [ " + feature + " ] feature."); + cc.log(cc.logLevelEnums.INFO, `check_consent, Giving consent for : [ ${feature} ] feature.`); return true; } if (consents[feature] && !consents[feature].optin) { - cc.log(cc.logLevelEnums.ERROR, "check_consent, User is not optin. Consent refused for : [ " + feature + " ] feature."); + cc.log(cc.logLevelEnums.ERROR, `check_consent, User is not optin. Consent refused for : [ ${feature} ] feature.`); return false; } - else { - cc.log(cc.logLevelEnums.ERROR, "check_consent, No feature available for " + feature); - } + + cc.log(cc.logLevelEnums.ERROR, `check_consent, No feature available for ${feature}`); + return false; }; @@ -361,7 +356,7 @@ Countly.Bulk = Bulk; if (!Countly.require_consent) { cc.log(cc.logLevelEnums.INFO, "check_any_consent, require_consent is off, no consent is necessary."); - //we don't need to have consents + // we don't need to have consents return true; } for (var i in consents) { @@ -389,7 +384,7 @@ Countly.Bulk = Bulk; * @param {string|array} feature - name of the feature, possible values, "sessions","events","views","crashes","attribution","users" or customly provided through {@link Countly.group_features} */ Countly.add_consent = function(feature) { - cc.log(cc.logLevelEnums.INFO, "add_consent, Adding consent for " + feature); + cc.log(cc.logLevelEnums.INFO, `add_consent, Adding consent for ${feature}`); if (feature.constructor === Array) { for (var i = 0; i < feature.length; i++) { Countly.add_consent(feature[i]); @@ -398,15 +393,15 @@ Countly.Bulk = Bulk; else if (consents[feature]) { if (consents[feature].features) { consents[feature].optin = true; - //this is added group, let's iterate through sub features + // this is added group, let's iterate through sub features Countly.add_consent(consents[feature].features); } else { - //this is core feature + // this is core feature if (consents[feature].optin !== true) { consents[feature].optin = true; updateConsent(); - setTimeout(function() { + setTimeout(() => { if (feature === "sessions" && lastParams.begin_session) { Countly.begin_session.apply(Countly, lastParams.begin_session); lastParams.begin_session = null; @@ -425,17 +420,16 @@ Countly.Bulk = Bulk; } } else { - cc.log(cc.logLevelEnums.WARNING, "add_consent, No feature available for " + feature); + cc.log(cc.logLevelEnums.WARNING, `add_consent, No feature available for ${feature}`); } }; - /** * Remove consent for specific feature, meaning, user opted out to track that data (either core feature of from custom feature group) * @param {string|array} feature - name of the feature, possible values, "sessions","events","views","crashes","attribution","users" or custom provided through {@link Countly.group_features} */ Countly.remove_consent = function(feature) { - cc.log(cc.logLevelEnums.INFO, "remove_consent, Removing consent for " + feature); + cc.log(cc.logLevelEnums.INFO, `remove_consent, Removing consent for ${feature}`); Countly.remove_consent_internal(feature, true); }; @@ -445,7 +439,7 @@ Countly.Bulk = Bulk; * @param {Boolean} enforceConsentUpdate - regulates if a request will be sent to the server or not. If true, removing consents will send a request to the server and if false, consents will be removed without a request */ Countly.remove_consent_internal = function(feature, enforceConsentUpdate) { - //if true updateConsent will execute when possible + // if true updateConsent will execute when possible enforceConsentUpdate = enforceConsentUpdate || false; if (feature.constructor === Array) { for (var i = 0; i < feature.length; i++) { @@ -454,33 +448,31 @@ Countly.Bulk = Bulk; } else if (consents[feature]) { if (consents[feature].features) { - //this is added group, let's iterate through sub features + // this is added group, let's iterate through sub features Countly.remove_consent_internal(consents[feature].features, enforceConsentUpdate); - } else { consents[feature].optin = false; - //this is core feature + // this is core feature if (enforceConsentUpdate && consents[feature].optin !== false) { updateConsent(); } } cc.log(cc.logLevelEnums.DEBUG, "remove_consent, Consent removal triggered."); - } else { - cc.log(cc.logLevelEnums.WARNING, "remove_consent, No feature available for " + feature); + cc.log(cc.logLevelEnums.WARNING, `remove_consent, No feature available for ${feature}`); } }; var consentTimer; var updateConsent = function() { if (consentTimer) { - //delay syncing consents + // delay syncing consents clearTimeout(consentTimer); consentTimer = null; } - consentTimer = setTimeout(function() { + consentTimer = setTimeout(() => { var consentMessage = {}; for (var i = 0; i < Countly.features.length; i++) { if (consents[Countly.features[i]].optin === true) { @@ -490,12 +482,11 @@ Countly.Bulk = Bulk; consentMessage[Countly.features[i]] = false; } } - toRequestQueue({consent: JSON.stringify(consentMessage)}); + toRequestQueue({ consent: JSON.stringify(consentMessage) }); cc.log(cc.logLevelEnums.DEBUG, "Consent update request has been sent to the queue."); }, 1000); }; - /** * Start session * @param {boolean} noHeartBeat - true if you don't want to use internal heartbeat to manage session @@ -507,7 +498,7 @@ Countly.Bulk = Bulk; cc.log(cc.logLevelEnums.INFO, "begin_session, Session started"); lastBeat = cc.getTimestamp(); sessionStarted = true; - autoExtend = (noHeartBeat) ? false : true; + autoExtend = !(noHeartBeat); var req = {}; req.begin_session = 1; req.metrics = JSON.stringify(getMetrics()); @@ -527,7 +518,7 @@ Countly.Bulk = Bulk; if (Countly.check_consent("sessions")) { if (sessionStarted) { cc.log(cc.logLevelEnums.INFO, "session_duration, Session extended", sec); - toRequestQueue({session_duration: sec}); + toRequestQueue({ session_duration: sec }); } } }; @@ -543,7 +534,7 @@ Countly.Bulk = Bulk; cc.log(cc.logLevelEnums.INFO, "end_session, Ending session"); reportViewDuration(); sessionStarted = false; - toRequestQueue({end_session: 1, session_duration: sec}); + toRequestQueue({ end_session: 1, session_duration: sec }); } } }; @@ -552,23 +543,23 @@ Countly.Bulk = Bulk; * Change current user/device id * @param {string} newId - new user/device ID to use * @param {boolean=} merge - move data from old ID to new ID on server - **/ + * */ Countly.change_id = function(newId, merge) { newId = cc.truncateSingleValue(newId, Countly.maxValueSize, "change_id", Countly.debug); if (cluster.isMaster) { if (Countly.device_id !== newId) { if (!merge) { - //empty event queue + // empty event queue if (eventQueue.length > 0) { toRequestQueue({ events: JSON.stringify(eventQueue) }); eventQueue = []; storeSet("cly_event", eventQueue); } - //end current session + // end current session Countly.end_session(); - //clear timed events + // clear timed events timedEvents = {}; - //clear all consents + // clear all consents Countly.remove_consent_internal(Countly.features, false); } var oldId = Countly.device_id; @@ -577,14 +568,14 @@ Countly.Bulk = Bulk; cc.log(cc.logLevelEnums.INFO, "change_id, Changing ID"); if (merge) { if (Countly.check_any_consent()) { - toRequestQueue({old_device_id: oldId}); + toRequestQueue({ old_device_id: oldId }); } else { lastParams.change_id = arguments; } } else { - //start new session for new id + // start new session for new id Countly.begin_session(!autoExtend); } if (Countly.remote_config) { @@ -597,7 +588,7 @@ Countly.Bulk = Bulk; } } else { - process.send({ cly: {change_id: newId, merge: merge} }); + process.send({ cly: { change_id: newId, merge } }); } }; @@ -609,12 +600,12 @@ Countly.Bulk = Bulk; * @param {number=} event.sum - sum to report with event (if any) * @param {number=} event.dur - duration to report with event (if any) * @param {Object=} event.segmentation - object with segments key /values - **/ + * */ Countly.add_event = function(event) { - cc.log('Trying to add the event: [ ' + event.key + ' ]'); - //initially no consent is given + cc.log(`Trying to add the event: [ ${event.key} ]`); + // initially no consent is given var respectiveConsent = false; - //to match the internal events and their respective required consents. Sets respectiveConsent to true if the consent is given + // to match the internal events and their respective required consents. Sets respectiveConsent to true if the consent is given switch (event.key) { case cc.internalEventKeyEnums.NPS: respectiveConsent = Countly.check_consent('feedback'); @@ -639,9 +630,8 @@ Countly.Bulk = Bulk; break; default: respectiveConsent = Countly.check_consent('events'); - } - //if consent is given adds event to the queue + // if consent is given adds event to the queue if (respectiveConsent) { add_cly_events(event); } @@ -673,21 +663,21 @@ Countly.Bulk = Bulk; storeSet("cly_event", eventQueue); } else { - process.send({ cly: {event: event} }); + process.send({ cly: { event } }); } } /** * Start timed event, which will fill in duration property upon ending automatically * @param {string} key - event name that will be used as key property - **/ + * */ Countly.start_event = function(key) { key = cc.truncateSingleValue(key, Countly.maxKeyLength, "start_event", Countly.debug); if (timedEvents[key]) { - cc.log(cc.logLevelEnums.INFO, "start_event, Timed event with key " + key + " already started"); + cc.log(cc.logLevelEnums.INFO, `start_event, Timed event with key ${key} already started`); return; } - cc.log(cc.logLevelEnums.INFO, "start_event, Timer for timed event with key " + key + " starting"); + cc.log(cc.logLevelEnums.INFO, `start_event, Timer for timed event with key ${key} starting`); timedEvents[key] = cc.getTimestamp(); }; @@ -695,22 +685,22 @@ Countly.Bulk = Bulk; /** * End timed event * @param {string|Object} event - event key if string or Countly event same as passed to {@link Countly.add_event} - **/ + * */ Countly.end_event = function(event) { if (typeof event === "string") { event = cc.truncateSingleValue(event, Countly.maxKeyLength, "end_event", Countly.debug); - event = {key: event}; + event = { key: event }; } if (!event.key) { cc.log(cc.logLevelEnums.ERROR, "end_event, Event must have key property"); return; } if (!timedEvents[event.key]) { - cc.log(cc.logLevelEnums.WARNING, "end_event, Timed event with key " + event.key + " was not started"); + cc.log(cc.logLevelEnums.WARNING, `end_event, Timed event with key ${event.key} was not started`); return; } event.key = cc.truncateSingleValue(event.key, Countly.maxKeyLength, "end_event"); - cc.log(cc.logLevelEnums.INFO, "end_event, Timer for timed event with key " + event.key + " stopping"); + cc.log(cc.logLevelEnums.INFO, `end_event, Timer for timed event with key ${event.key} stopping`); event.dur = cc.getTimestamp() - timedEvents[event.key]; Countly.add_event(event); @@ -729,7 +719,7 @@ Countly.Bulk = Bulk; * @param {string=} user.gender - M value for male and F value for femail * @param {number=} user.byear - user's birth year used to calculate current age * @param {Object=} user.custom - object with custom key value properties you want to save with user - **/ + * */ Countly.user_details = function(user) { cc.log(cc.logLevelEnums.DEBUG, "user_details, Adding userdetails: ", user); if (Countly.check_consent("users")) { @@ -743,11 +733,11 @@ Countly.Bulk = Bulk; user.gender = cc.truncateSingleValue(user.gender, Countly.maxValueSize, "user_details", Countly.debug); user.byear = cc.truncateSingleValue(user.byear, Countly.maxValueSize, "user_details", Countly.debug); user.custom = cc.truncateObject(user.custom, Countly.maxKeyLength, Countly.maxValueSize, Countly.maxSegmentationValues, "user_details"); - toRequestQueue({user_details: JSON.stringify(cc.getProperties(user, props))}); + toRequestQueue({ user_details: JSON.stringify(cc.getProperties(user, props)) }); } }; - /************************** + /** ************************ * Modifying custom property values of user details * Possible modification commands * - inc, to increment existing value by provided value @@ -758,7 +748,7 @@ Countly.Bulk = Bulk; * - push, creates an array property, if property does not exist, and adds value to array * - pull, to remove value from array property * - addToSet, creates an array property, if property does not exist, and adds unique value to array, only if it does not yet exist in array - **************************/ + ************************* */ var customData = {}; var change_custom_property = function(key, value, mod) { key = cc.truncateSingleValue(key, Countly.maxKeyLength, "change_custom_property", Countly.debug); @@ -799,8 +789,8 @@ Countly.Bulk = Bulk; * Sets user's custom property value * @param {string} key - name of the property to attach to user * @param {string|number} value - value to store under provided property - **/ - set: function(key, value) { + * */ + set(key, value) { key = cc.truncateSingleValue(key, Countly.maxKeyLength, "set", Countly.debug); value = cc.truncateSingleValue(value, Countly.maxValueSize, "set", Countly.debug); customData[key] = value; @@ -809,8 +799,8 @@ Countly.Bulk = Bulk; * Sets user's custom property value only if it was not set before * @param {string} key - name of the property to attach to user * @param {string|number} value - value to store under provided property - **/ - set_once: function(key, value) { + * */ + set_once(key, value) { key = cc.truncateSingleValue(key, Countly.maxKeyLength, "set_once", Countly.debug); value = cc.truncateSingleValue(value, Countly.maxValueSize, "set_once", Countly.debug); change_custom_property(key, value, "$setOnce"); @@ -818,16 +808,16 @@ Countly.Bulk = Bulk; /** * Unset's/delete's user's custom property * @param {string} key - name of the property to delete - **/ - unset: function(key) { + * */ + unset(key) { key = cc.truncateSingleValue(key, Countly.maxKeyLength, "unset", Countly.debug); customData[key] = ""; }, /** * Increment value under the key of this user's custom properties by one * @param {string} key - name of the property to attach to user - **/ - increment: function(key) { + * */ + increment(key) { key = cc.truncateSingleValue(key, Countly.maxKeyLength, "increment", Countly.debug); change_custom_property(key, 1, "$inc"); }, @@ -835,8 +825,8 @@ Countly.Bulk = Bulk; * Increment value under the key of this user's custom properties by provided value * @param {string} key - name of the property to attach to user * @param {number} value - value by which to increment server value - **/ - increment_by: function(key, value) { + * */ + increment_by(key, value) { key = cc.truncateSingleValue(key, Countly.maxKeyLength, "increment_by", Countly.debug); value = cc.truncateSingleValue(value, Countly.maxValueSize, "increment_by", Countly.debug); change_custom_property(key, value, "$inc"); @@ -845,8 +835,8 @@ Countly.Bulk = Bulk; * Multiply value under the key of this user's custom properties by provided value * @param {string} key - name of the property to attach to user * @param {number} value - value by which to multiply server value - **/ - multiply: function(key, value) { + * */ + multiply(key, value) { key = cc.truncateSingleValue(key, Countly.maxKeyLength, "multiply", Countly.debug); value = cc.truncateSingleValue(value, Countly.maxValueSize, "multiply", Countly.debug); change_custom_property(key, value, "$mul"); @@ -855,8 +845,8 @@ Countly.Bulk = Bulk; * Save maximal value under the key of this user's custom properties * @param {string} key - name of the property to attach to user * @param {number} value - value which to compare to server's value and store maximal value of both provided - **/ - max: function(key, value) { + * */ + max(key, value) { key = cc.truncateSingleValue(key, Countly.maxKeyLength, "max", Countly.debug); value = cc.truncateSingleValue(value, Countly.maxValueSize, "max", Countly.debug); change_custom_property(key, value, "$max"); @@ -865,8 +855,8 @@ Countly.Bulk = Bulk; * Save minimal value under the key of this user's custom properties * @param {string} key - name of the property to attach to user * @param {number} value - value which to compare to server's value and store minimal value of both provided - **/ - min: function(key, value) { + * */ + min(key, value) { key = cc.truncateSingleValue(key, Countly.maxKeyLength, "min", Countly.debug); value = cc.truncateSingleValue(value, Countly.maxValueSize, "min", Countly.debug); change_custom_property(key, value, "$min"); @@ -875,8 +865,8 @@ Countly.Bulk = Bulk; * Add value to array under the key of this user's custom properties. If property is not an array, it will be converted to array * @param {string} key - name of the property to attach to user * @param {string|number} value - value which to add to array - **/ - push: function(key, value) { + * */ + push(key, value) { key = cc.truncateSingleValue(key, Countly.maxKeyLength, "push", Countly.debug); value = cc.truncateSingleValue(value, Countly.maxValueSize, "push", Countly.debug); change_custom_property(key, value, "$push"); @@ -885,8 +875,8 @@ Countly.Bulk = Bulk; * Add value to array under the key of this user's custom properties, storing only unique values. If property is not an array, it will be converted to array * @param {string} key - name of the property to attach to user * @param {string|number} value - value which to add to array - **/ - push_unique: function(key, value) { + * */ + push_unique(key, value) { key = cc.truncateSingleValue(key, Countly.maxKeyLength, "push_unique", Countly.debug); value = cc.truncateSingleValue(value, Countly.maxValueSize, "push_unique", Countly.debug); change_custom_property(key, value, "$addToSet"); @@ -895,42 +885,40 @@ Countly.Bulk = Bulk; * Remove value from array under the key of this user's custom properties * @param {string} key - name of the property * @param {string|number} value - value which to remove from array - **/ - pull: function(key, value) { + * */ + pull(key, value) { key = cc.truncateSingleValue(key, Countly.maxKeyLength, "pull", Countly.debug); value = cc.truncateSingleValue(value, Countly.maxValueSize, "pull", Countly.debug); change_custom_property(key, value, "$pull"); }, /** * Save changes made to user's custom properties object and send them to server - **/ - save: function() { + * */ + save() { if (Countly.check_consent("users")) { - toRequestQueue({user_details: JSON.stringify({custom: customData})}); + toRequestQueue({ user_details: JSON.stringify({ custom: customData }) }); } customData = {}; - } + }, }; /** * Report user conversion to the server (when user signup or made a purchase, or whatever your conversion is) * @param {string} campaign_id - id of campaign, the last part of the countly campaign link * @param {string=} campaign_user_id - id of user's clicked on campaign link, if you have one - **/ + * */ Countly.report_conversion = function(campaign_id, campaign_user_id) { if (Countly.check_consent("attribution")) { if (campaign_id && campaign_user_id) { campaign_id = cc.truncateSingleValue(campaign_id, Countly.maxValueSize, "report_conversion", Countly.debug); campaign_user_id = cc.truncateSingleValue(campaign_user_id, Countly.maxValueSize, "report_conversion", Countly.debug); - toRequestQueue({campaign_id: campaign_id, campaign_user: campaign_user_id}); + toRequestQueue({ campaign_id: campaign_id, campaign_user: campaign_user_id }); cc.log(cc.logLevelEnums.INFO, "report_conversion, Conversion reported"); - } else if (campaign_id) { campaign_id = cc.truncateSingleValue(campaign_id, Countly.maxValueSize, "report_conversion", Countly.debug); - toRequestQueue({campaign_id: campaign_id}); + toRequestQueue({ campaign_id: campaign_id }); cc.log(cc.logLevelEnums.INFO, "report_conversion, Conversion reported"); - } else { cc.log(cc.logLevelEnums.ERROR, "report_conversion, No campaign data found"); @@ -948,7 +936,7 @@ Countly.Bulk = Bulk; * @param {number} feedback.rating - user's rating * @param {string=} feedback.email - user's email * @param {string=} feedback.comment - user's comment - **/ + * */ Countly.report_feedback = function(feedback) { if (Countly.check_consent("star-rating") || Countly.check_consent("feedback")) { if (!feedback.widget_id) { @@ -964,7 +952,7 @@ Countly.Bulk = Bulk; var event = { key: cc.internalEventKeyEnums.STAR_RATING, count: 1, - segmentation: {} + segmentation: {}, }; event.segmentation = cc.getProperties(feedback, props); if (!event.segmentation.app_version) { @@ -979,31 +967,31 @@ Countly.Bulk = Bulk; /** * Automatically track javascript errors that happen on the nodejs process * @param {string=} segments - additional key value pairs you want to provide with error report, like versions of libraries used, etc. - **/ + * */ Countly.track_errors = function(segments) { cc.log(cc.logLevelEnums.INFO, "track_errors, Tracking errors"); crashSegments = segments; - process.on("uncaughtException", function(err) { + process.on("uncaughtException", (err) => { recordError(err, false); if (cluster.isMaster) { forceStore(); } // eslint-disable-next-line no-console - console.error((new Date()).toUTCString() + " uncaughtException:", err.message); + console.error(`${(new Date()).toUTCString()} uncaughtException:`, err.message); // eslint-disable-next-line no-console console.error(err.stack); process.exit(1); }); - process.on('unhandledRejection', function(reason) { - var err = new Error('Unhandled rejection (reason: ' + (reason && reason.stack ? reason.stack : reason) + ').'); + process.on('unhandledRejection', (reason) => { + var err = new Error(`Unhandled rejection (reason: ${reason && reason.stack ? reason.stack : reason}).`); recordError(err, false); if (cluster.isMaster) { forceStore(); } // eslint-disable-next-line no-console - console.error((new Date()).toUTCString() + " unhandledRejection:", err.message); + console.error(`${(new Date()).toUTCString()} unhandledRejection:`, err.message); // eslint-disable-next-line no-console console.error(err.stack); }); @@ -1013,7 +1001,7 @@ Countly.Bulk = Bulk; * Log an exception that you catched through try and catch block and handled yourself and just want to report it to server * @param {Object} err - error exception object provided in catch block * @param {string=} segments - additional key value pairs you want to provide with error report, like versions of libraries used, etc. - **/ + * */ Countly.log_error = function(err, segments) { cc.log(cc.logLevelEnums.INFO, "log_error, Logging error"); @@ -1023,18 +1011,16 @@ Countly.Bulk = Bulk; /** * Add new line in the log of breadcrumbs of what was done did, will be included together with error report * @param {string} record - any text describing an action - **/ + * */ Countly.add_log = function(record) { if (Countly.check_consent("crashes")) { record = cc.truncateSingleValue(record, Countly.maxValueSize, "add_log", Countly.debug); if (crashLogs.length > Countly.maxBreadcrumbCount) { crashLogs.shift(); cc.log(cc.logLevelEnums.DEBUG, "add_log, Breadcrumbs overflowed. Erasing the oldest:"); - } crashLogs.push(record); cc.log(cc.logLevelEnums.INFO, "add_log, Added breadcrumb to:"); - } }; @@ -1043,11 +1029,11 @@ Countly.Bulk = Bulk; * @param {array=} keys - Array of keys to fetch, if not provided will fetch all keys * @param {array=} omit_keys - Array of keys to omit, if provided will fetch all keys except provided ones * @param {function=} callback - Callback to notify with first param error and second param remote config object - **/ + * */ Countly.fetch_remote_config = function(keys, omit_keys, callback) { if (Countly.check_consent("remote-config")) { var request = { - method: "fetch_remote_config" + method: "fetch_remote_config", }; if (Countly.check_consent("sessions")) { request.metrics = JSON.stringify(getMetrics()); @@ -1071,27 +1057,26 @@ Countly.Bulk = Bulk; } } prepareRequest(request); - makeRequest(Countly.url, readPath, request, function(err, params, responseText) { + makeRequest(Countly.url, readPath, request, (err, params, responseText) => { try { var configs = JSON.parse(responseText); if (request.keys || request.omit_keys) { - //we merge config + // we merge config for (var i in configs) { remoteConfigs[i] = configs[i]; } } else { - //we replace config + // we replace config remoteConfigs = configs; } if (cluster.isMaster) { storeSet("cly_remote_configs", remoteConfigs); cc.log(cc.logLevelEnums.INFO, "fetch_remote_config, Fetched remote config"); - } } catch (ex) { - //silent catch + // silent catch } if (typeof callback === "function") { callback(err, remoteConfigs); @@ -1110,22 +1095,20 @@ Countly.Bulk = Bulk; * Get Remote config object or specific value for provided key * @param {string=} key - if provided, will return value for key, or return whole object * @returns {varies} remote config value - **/ + * */ Countly.get_remote_config = function(key) { if (typeof key !== "undefined") { cc.log(cc.logLevelEnums.INFO, "get_remote_config, Got remote config key"); return remoteConfigs[key]; - } cc.log(cc.logLevelEnums.INFO, "get_remote_config, Got remote config"); return remoteConfigs; }; - /** * Stop tracking duration time for this user/device - **/ + * */ Countly.stop_time = function() { cc.log(cc.logLevelEnums.INFO, "stop_time, Stopping time"); @@ -1136,7 +1119,7 @@ Countly.Bulk = Bulk; /** * Start tracking duration time for this user/device, by default it is automatically if you scalled (@link begin_session) - **/ + * */ Countly.start_time = function() { cc.log(cc.logLevelEnums.INFO, "start_time, Starting time"); @@ -1150,7 +1133,7 @@ Countly.Bulk = Bulk; * Track which parts of application user visits * @param {string=} name - optional name of the view * @param {object=} viewSegments - optional key value object with segments to report with the view - **/ + * */ Countly.track_view = function(name, viewSegments) { cc.log(cc.logLevelEnums.INFO, "track_view, Tracking view"); @@ -1163,9 +1146,9 @@ Countly.Bulk = Bulk; getMetrics(); } var segments = { - "name": name, - "visit": 1, - "segment": platform + name, + visit: 1, + segment: platform, }; if (viewSegments) { @@ -1178,11 +1161,11 @@ Countly.Bulk = Bulk; } } - //track pageview + // track pageview if (Countly.check_consent("views")) { add_cly_events({ - "key": cc.internalEventKeyEnums.VIEW, - "segmentation": segments + key: cc.internalEventKeyEnums.VIEW, + segmentation: segments, }); } else { @@ -1195,7 +1178,7 @@ Countly.Bulk = Bulk; * Track which parts of application user visits. Alias of {@link track_view} method for compatability with Web SDK * @param {string=} name - optional name of the view * @param {object=} viewSegments - optional key value object with segments to report with the view - **/ + * */ Countly.track_pageview = function(name, viewSegments) { Countly.track_view(name, viewSegments); }; @@ -1238,8 +1221,8 @@ Countly.Bulk = Bulk; Countly.report_app_start = function() { cc.log(cc.logLevelEnums.INFO, "report_app_start, Reporting app start"); - //do on next tick to allow synchronous code to load - process.nextTick(function() { + // do on next tick to allow synchronous code to load + process.nextTick(() => { var start = Math.floor(process.uptime() * 1000); var end = Date.now(); Countly.report_trace({ @@ -1248,8 +1231,8 @@ Countly.Bulk = Bulk; stz: start, etz: end, app_metrics: { - duration: end - start - } + duration: end - start, + }, }); }); }; @@ -1258,7 +1241,7 @@ Countly.Bulk = Bulk; * Make raw request with provided parameters * @example Countly.request({app_key:"somekey", devide_id:"someid", events:"[{'key':'val','count':1}]", begin_session:1}); * @param {Object} request - object with key/values which will be used as request parameters - **/ + * */ Countly.request = function(request) { request = cc.truncateObject(request, Countly.maxKeyLength, Countly.maxValueSize, Countly.maxSegmentationValues, "request", Countly.debug); @@ -1270,16 +1253,15 @@ Countly.Bulk = Bulk; requestQueue.push(request); storeSet("cly_queue", requestQueue); cc.log(cc.logLevelEnums.INFO, "request, Making a raw request"); - } else { - process.send({ cly: {request: request} }); + process.send({ cly: { request: request } }); } }; /** * PRIVATE METHODS - **/ + * */ /** * Report duration of how long user was on this view @@ -1290,16 +1272,16 @@ Countly.Bulk = Bulk; getMetrics(); } var segments = { - "name": lastView, - "segment": platform + name: lastView, + segment: platform, }; - //track pageview + // track pageview if (Countly.check_consent("views")) { add_cly_events({ - "key": cc.internalEventKeyEnums.VIEW, - "dur": cc.getTimestamp() - lastViewTime, - "segmentation": segments + key: cc.internalEventKeyEnums.VIEW, + dur: cc.getTimestamp() - lastViewTime, + segmentation: segments, }); } lastView = null; @@ -1356,7 +1338,7 @@ Countly.Bulk = Bulk; storeSet("cly_queue", requestQueue); } else { - process.send({ cly: {cly_queue: request} }); + process.send({ cly: { cly_queue: request } }); } } @@ -1364,7 +1346,7 @@ Countly.Bulk = Bulk; * Making request making and data processing loop */ function heartBeat() { - //extend session if needed + // extend session if needed if (sessionStarted && autoExtend && trackTime) { var last = cc.getTimestamp(); if (last - lastBeat > sessionUpdate) { @@ -1373,25 +1355,25 @@ Countly.Bulk = Bulk; } } - //process event queue + // process event queue if (eventQueue.length > 0) { if (eventQueue.length <= maxEventBatch) { - toRequestQueue({events: JSON.stringify(eventQueue)}); + toRequestQueue({ events: JSON.stringify(eventQueue) }); eventQueue = []; } else { var events = eventQueue.splice(0, maxEventBatch); - toRequestQueue({events: JSON.stringify(events)}); + toRequestQueue({ events: JSON.stringify(events) }); } storeSet("cly_event", eventQueue); } - //process request queue with event queue + // process request queue with event queue if (requestQueue.length > 0 && readyToProcess && cc.getTimestamp() > failTimeout) { readyToProcess = false; var params = requestQueue.shift(); cc.log(cc.logLevelEnums.DEBUG, "Processing request", params); - makeRequest(Countly.url, apiPath, params, function(err, res) { + makeRequest(Countly.url, apiPath, params, (err, res) => { cc.log(cc.logLevelEnums.DEBUG, "Request Finished", res, err); if (err) { requestQueue.unshift(res); @@ -1414,7 +1396,6 @@ Countly.Bulk = Bulk; return storeGet("cly_id", null) || cc.generateUUID(); } - /** * Get metrics of the browser or config object * @returns {Object} Metrics object @@ -1422,14 +1403,13 @@ Countly.Bulk = Bulk; function getMetrics() { var m = JSON.parse(JSON.stringify(metrics)); - //getting app version + // getting app version m._app_version = m._app_version || Countly.app_version; m._os = m._os || os.type(); m._os_version = m._os_version || os.release(); platform = os.type(); - cc.log(cc.logLevelEnums.DEBUG, "Got metrics", m); return m; } @@ -1465,48 +1445,47 @@ Countly.Bulk = Bulk; } else { if (typeof err.name !== "undefined") { - error += err.name + ":"; + error += `${err.name}:`; } if (typeof err.message !== "undefined") { - error += err.message + "\n"; + error += `${err.message}\n`; } if (typeof err.fileName !== "undefined") { - error += "in " + err.fileName + "\n"; + error += `in ${err.fileName}\n`; } if (typeof err.lineNumber !== "undefined") { - error += "on " + err.lineNumber; + error += `on ${err.lineNumber}`; } if (typeof err.columnNumber !== "undefined") { - error += ":" + err.columnNumber; + error += `:${err.columnNumber}`; } } } else { - error = err + ""; + error = `${err}`; } segments = cc.truncateObject(segments, Countly.maxKeyLength, Countly.maxValueSize, Countly.maxSegmentationValues, "record_error", Countly.debug); - //character limit check + // character limit check if (error.length > (Countly.maxStackTraceLineLength * Countly.maxStackTraceLinesPerThread)) { - cc.log("Error stack is too long will be truncated"); - //convert error into an array split from each newline + // convert error into an array split from each newline var splittedError = error.split("\n"); - //trim the array if it is too long + // trim the array if it is too long if (splittedError.length > Countly.maxStackTraceLinesPerThread) { splittedError = splittedError.splice(0, Countly.maxStackTraceLinesPerThread); } - //trim each line to a given limit + // trim each line to a given limit for (var i = 0, len = splittedError.length; i < len; i++) { if (splittedError[i].length > Countly.maxStackTraceLineLength) { splittedError[i] = splittedError[i].substring(0, Countly.maxStackTraceLineLength); } } - //turn modified array back into error string + // turn modified array back into error string error = splittedError.join("\n"); } - nonfatal = (nonfatal) ? true : false; + nonfatal = !!(nonfatal); var m = getMetrics(); - var ob = {_os: m._os, _os_version: m._os_version, _error: error, _app_version: m._app_version, _run: cc.getTimestamp() - startTime}; + var ob = { _os: m._os, _os_version: m._os_version, _error: error, _app_version: m._app_version, _run: cc.getTimestamp() - startTime }; ob._not_os_specific = true; ob._javascript = true; @@ -1521,7 +1500,7 @@ Countly.Bulk = Bulk; ob._custom = segments; } - toRequestQueue({crash: JSON.stringify(ob)}); + toRequestQueue({ crash: JSON.stringify(ob) }); } } @@ -1541,8 +1520,8 @@ Countly.Bulk = Bulk; var options = { host: serverOptions.host, port: serverOptions.port, - path: api + "?" + data, - method: "GET" + path: `${api}?${data}`, + method: "GET", }; if (data.length >= 2000 || Countly.force_post) { @@ -1554,7 +1533,7 @@ Countly.Bulk = Bulk; options.path = api; options.headers = { "Content-Type": "application/x-www-form-urlencoded", - "Content-Length": Buffer.byteLength(data) + "Content-Length": Buffer.byteLength(data), }; } @@ -1565,12 +1544,12 @@ Countly.Bulk = Bulk; if (url.indexOf("https") === 0) { protocol = https; } - var req = protocol.request(options, function(res) { + var req = protocol.request(options, (res) => { var str = ""; - res.on("data", function(chunk) { + res.on("data", (chunk) => { str += chunk; }); - res.on("end", function() { + res.on("end", () => { // checks result field, JSON format and status code if (cc.isResponseValid(res.statusCode, str)) { callback(false, params, str); @@ -1585,7 +1564,7 @@ Countly.Bulk = Bulk; req.write(data); } - req.on("error", function(err) { + req.on("error", (err) => { cc.log(cc.logLevelEnums.ERROR, "Connection failed.", err); if (typeof callback === "function") { callback(true, params); @@ -1611,12 +1590,11 @@ Countly.Bulk = Bulk; function prepareParams(params) { var str = []; for (var i in params) { - str.push(i + "=" + encodeURIComponent(params[i])); + str.push(`${i}=${encodeURIComponent(params[i])}`); } return str.join("&"); } - /** * Parsing host and port information from url * @param {String} url - url to which request will be made @@ -1625,7 +1603,7 @@ Countly.Bulk = Bulk; function parseUrl(url) { var serverOptions = { host: "localhost", - port: 80 + port: 80, }; if (Countly.url.indexOf("https") === 0) { serverOptions.port = 443; @@ -1667,29 +1645,29 @@ Countly.Bulk = Bulk; * @returns {varies} value in file */ var readFile = function(key) { - var dir = path.resolve(__dirname, Countly.storage_path + "__" + key + ".json"); + var dir = path.resolve(__dirname, `${Countly.storage_path}__${key}.json`); - //try reading data file + // try reading data file var data; try { data = fs.readFileSync(dir); } catch (ex) { - //there was no file, probably new init + // there was no file, probably new init data = null; } try { - //trying to parse json string + // trying to parse json string data = JSON.parse(data); } catch (ex) { - //problem parsing, corrupted file? + // problem parsing, corrupted file? // eslint-disable-next-line no-console console.log(ex.stack); - //backup corrupted file data - fs.writeFile(path.resolve(__dirname, Countly.storage_path + "__" + key + "." + cc.getTimestamp() + Math.random() + ".json"), data, function() {}); - //start with new clean object + // backup corrupted file data + fs.writeFile(path.resolve(__dirname, `${Countly.storage_path}__${key}.${cc.getTimestamp()}${Math.random()}.json`), data, () => {}); + // start with new clean object data = null; } return data; @@ -1700,14 +1678,14 @@ Countly.Bulk = Bulk; */ var forceStore = function() { for (var i in __data) { - var dir = path.resolve(__dirname, Countly.storage_path + "__" + i + ".json"); + var dir = path.resolve(__dirname, `${Countly.storage_path}__${i}.json`); var ob = {}; ob[i] = __data[i]; try { fs.writeFileSync(dir, JSON.stringify(ob)); } catch (ex) { - //tried to save whats possible + // tried to save whats possible // eslint-disable-next-line no-console console.log(ex.stack); } @@ -1726,8 +1704,8 @@ Countly.Bulk = Bulk; var writeFile = function(key, value, callback) { var ob = {}; ob[key] = value; - var dir = path.resolve(__dirname, Countly.storage_path + "__" + key + ".json"); - fs.writeFile(dir, JSON.stringify(ob), function(err) { + var dir = path.resolve(__dirname, `${Countly.storage_path}__${key}.json`); + fs.writeFile(dir, JSON.stringify(ob), (err) => { if (err) { // eslint-disable-next-line no-console console.log(err); @@ -1736,7 +1714,7 @@ Countly.Bulk = Bulk; callback(err); } if (asyncWriteQueue.length) { - setTimeout(function() { + setTimeout(() => { var arr = asyncWriteQueue.shift(); writeFile(arr[0], arr[1], arr[2]); }, 0); diff --git a/package.json b/package.json index 127f161..163cada 100644 --- a/package.json +++ b/package.json @@ -9,8 +9,10 @@ "test": "test" }, "scripts": { + "lint": "eslint **/*.js", + "lint:fix": "npm run lint -- --fix", "docs": "node_modules/.bin/jsdoc lib/countly.js lib/countly-bulk.js lib/countly-bulk-user.js README.md -c jsdoc_conf.json -d docs", - "pretest": "eslint --ignore-path .gitignore .", + "pretest": "eslint --ignore-path .eslintignore .", "test": "mocha --timeout 180000 test/tests_*.js --exit --allow-uncaught" }, "repository": { @@ -30,7 +32,9 @@ "homepage": "https://count.ly/", "dependencies": {}, "devDependencies": { - "eslint": "*", + "eslint": "^6.8.0", + "eslint-config-airbnb-base": "^14.1.0", + "eslint-plugin-import": "^2.20.1", "mocha": "*", "jsdoc": "*", "docdash": "*" diff --git a/test/helpers/helper_functions.js b/test/helpers/helper_functions.js index 18a09b7..fbb09bc 100644 --- a/test/helpers/helper_functions.js +++ b/test/helpers/helper_functions.js @@ -1,34 +1,34 @@ /* eslint-disable no-unused-vars */ -var path = require("path"), - assert = require("assert"), - fs = require("fs"), - Countly = require("../../lib/countly.js"); +var path = require("path"); +var assert = require("assert"); +var fs = require("fs"); +var Countly = require("../../lib/countly"); -//paths for convenience +// paths for convenience var dir = path.resolve(__dirname, "../../"); -var idDir = (dir + "/data/__cly_id.json"); -var eventDir = (dir + "/data/__cly_event.json"); -var reqDir = (dir + "/data/__cly_queue.json"); -//timeout variables +var idDir = (`${dir}/data/__cly_id.json`); +var eventDir = (`${dir}/data/__cly_event.json`); +var reqDir = (`${dir}/data/__cly_queue.json`); +// timeout variables var sWait = 50; var mWait = 3000; var lWait = 10000; -//parsing event queue +// parsing event queue function readEventQueue() { var a = JSON.parse(fs.readFileSync(eventDir, "utf-8")).cly_event; return a; } -//parsing request queue +// parsing request queue function readRequestQueue() { var a = JSON.parse(fs.readFileSync(reqDir, "utf-8")).cly_queue; return a; } -//queue files clearing logic +// queue files clearing logic function clearStorage() { - //Resets Countly + // Resets Countly Countly.halt(true); - //clean storages + // clean storages if (fs.existsSync(idDir)) { fs.unlinkSync(idDir); } @@ -46,32 +46,32 @@ function clearStorage() { * @param {Number} time - Expected time for timed event duration */ function eventValidator(eventObject, eventQueue, time) { - //key key is mandatory + // key key is mandatory assert.equal(eventObject.key, eventQueue.key); - //check if count key exists. If it does add a test + // check if count key exists. If it does add a test if (typeof eventObject.count !== 'undefined') { assert.equal(eventObject.count, eventQueue.count); } - //check if sum key exists. If it does add a test + // check if sum key exists. If it does add a test if (typeof eventObject.sum !== 'undefined') { assert.equal(eventObject.sum, eventQueue.sum); } - //check if dur key exists or if it is a timed event. If it is one of those add a test + // check if dur key exists or if it is a timed event. If it is one of those add a test if (typeof eventObject.dur !== 'undefined' || typeof time !== 'undefined') { - //set expected duration + // set expected duration if (typeof time !== 'undefined') { eventObject.dur = time; } assert.equal(eventObject.dur, eventQueue.dur); } - //check if segmentation exists. If it is add test(s) + // check if segmentation exists. If it is add test(s) if (typeof eventObject.segmentation !== 'undefined') { - //loop through segmentation keys and create tets + // loop through segmentation keys and create tets for (var key in eventObject.segmentation) { assert.equal(eventObject.segmentation[key], eventQueue.segmentation[key]); } } - //common parameter validation + // common parameter validation assert.ok(typeof eventQueue.timestamp !== 'undefined'); assert.ok(typeof eventQueue.hour !== 'undefined'); assert.ok(typeof eventQueue.dow !== 'undefined'); @@ -120,14 +120,14 @@ function crashRequestValidator(validator, nonfatal) { * @param {String} id - Initial ID if changed */ function sessionRequestValidator(beginSs, endSs, time, id) { - //begin_session + // begin_session requestBaseParamValidator(beginSs, id); var metrics = JSON.parse(beginSs.metrics); assert.ok(metrics._os); assert.ok(metrics._os_version); assert.ok(metrics._app_version); assert.equal(1, beginSs.begin_session); - //end_session + // end_session if (typeof endSs !== 'undefined') { requestBaseParamValidator(endSs); assert.equal(1, endSs.end_session); @@ -177,7 +177,7 @@ function viewEventValidator(name, viewObj, time) { } assert.ok(viewObj.segmentation.segment); } -//exports +// exports module.exports = { clearStorage, sWait, @@ -189,5 +189,5 @@ module.exports = { crashRequestValidator, sessionRequestValidator, userDetailRequestValidator, - viewEventValidator + viewEventValidator, }; \ No newline at end of file diff --git a/test/tests_consents.js b/test/tests_consents.js index 9731b6b..057f5d7 100644 --- a/test/tests_consents.js +++ b/test/tests_consents.js @@ -1,10 +1,9 @@ -/* global describe, it, */ -var assert = require("assert"), - fs = require("fs"), - hp = require("./helpers/helper_functions"), - Countly = require("../lib/countly.js"); +var assert = require("assert"); +var fs = require("fs"); +var hp = require("./helpers/helper_functions"); +var Countly = require("../lib/countly"); -//standard init for tests +// standard init for tests function initMain() { Countly.init({ app_key: "YOUR_APP_KEY", @@ -12,58 +11,58 @@ function initMain() { require_consent: true, interval: 10000, device_id: "György Ligeti", - max_events: -1 + max_events: -1, }); } -//gathered events to add +// gathered events to add function events() { Countly.add_event({ - "key": "a", - "count": 1, - "segmentation": { - "custom key": "custom value" - } + key: "a", + count: 1, + segmentation: { + "custom key": "custom value", + }, }); Countly.add_event({ - "key": "[CLY]_view", - "count": 1, - "segmentation": { - "custom key": "custom value" - } + key: "[CLY]_view", + count: 1, + segmentation: { + "custom key": "custom value", + }, }); Countly.add_event({ - "key": "[CLY]_nps", - "count": 1, - "segmentation": { - "custom key": "custom value" - } + key: "[CLY]_nps", + count: 1, + segmentation: { + "custom key": "custom value", + }, }); Countly.add_event({ - "key": "[CLY]_survey", - "count": 1, - "segmentation": { - "custom key": "custom value" - } + key: "[CLY]_survey", + count: 1, + segmentation: { + "custom key": "custom value", + }, }); Countly.add_event({ - "key": "[CLY]_star_rating", - "count": 1, - "segmentation": { - "custom key": "custom value" - } + key: "[CLY]_star_rating", + count: 1, + segmentation: { + "custom key": "custom value", + }, }); Countly.add_event({ - "key": "[CLY]_orientation", - "count": 1, - "segmentation": { - "custom key": "custom value" - } + key: "[CLY]_orientation", + count: 1, + segmentation: { + "custom key": "custom value", + }, }); } -//tests -describe("Internal event consent tests", function() { - it("Only custom event should be sent to the queue", function(done) { +// tests +describe("Internal event consent tests", () => { + it("Only custom event should be sent to the queue", (done) => { hp.clearStorage(); initMain(); Countly.add_consent(["events"]); @@ -75,7 +74,7 @@ describe("Internal event consent tests", function() { done(); }, hp.sWait); }); - it("All but custom event should be sent to the queue", function(done) { + it("All but custom event should be sent to the queue", (done) => { hp.clearStorage(); initMain(); Countly.add_consent(["sessions", "views", "users", "star-rating", "apm", "feedback"]); @@ -91,7 +90,7 @@ describe("Internal event consent tests", function() { done(); }, hp.mWait); }); - it("Non-merge ID change should reset all consents", function(done) { + it("Non-merge ID change should reset all consents", (done) => { hp.clearStorage(); initMain(); Countly.add_consent(["sessions", "views", "users", "star-rating", "apm", "feedback"]); @@ -102,7 +101,7 @@ describe("Internal event consent tests", function() { done(); }, hp.sWait); }); - it("Merge ID change should not reset consents", function(done) { + it("Merge ID change should not reset consents", (done) => { hp.clearStorage(); initMain(); Countly.add_consent(["sessions", "views", "users", "star-rating", "apm", "feedback"]); diff --git a/test/tests_crashes.js b/test/tests_crashes.js index 7f44e36..2adedb5 100644 --- a/test/tests_crashes.js +++ b/test/tests_crashes.js @@ -1,25 +1,25 @@ /* eslint-disable no-console */ -/* global describe, it, runthis */ -var Countly = require("../lib/countly"), - hp = require("./helpers/helper_functions"); +/* global runthis */ +var Countly = require("../lib/countly"); +var hp = require("./helpers/helper_functions"); -//init function +// init function function initMain() { Countly.init({ app_key: "YOUR_APP_KEY", url: "https://try.count.ly", interval: 10000, - max_events: -1 + max_events: -1, }); } -describe("Crash tests", function() { - it("Validate handled error logic", function(done) { - //clear previous data +describe("Crash tests", () => { + it("Validate handled error logic", (done) => { + // clear previous data hp.clearStorage(); - //initialize SDK + // initialize SDK initMain(); - //error logic + // error logic Countly.track_errors(); try { runthis(); @@ -27,25 +27,25 @@ describe("Crash tests", function() { catch (ex) { Countly.log_error(ex); } - //read event queue + // read event queue setTimeout(() => { var req = hp.readRequestQueue()[0]; hp.crashRequestValidator(req, true); done(); }, hp.sWait); }); - //This needs two steps, first creating an error and second checking the logs without erasing, otherwise error would halt the test - describe("Unhandled Error logic", function() { - it("Create unhandled rejection", function() { - //clear previous data + // This needs two steps, first creating an error and second checking the logs without erasing, otherwise error would halt the test + describe("Unhandled Error logic", () => { + it("Create unhandled rejection", () => { + // clear previous data hp.clearStorage(); - //initialize SDK + // initialize SDK initMain(); - //send emitter + // send emitter Countly.track_errors(); process.emit('unhandledRejection'); }); - it("Validate unhandled rejection recording", function(done) { + it("Validate unhandled rejection recording", (done) => { setTimeout(() => { var req = hp.readRequestQueue()[0]; hp.crashRequestValidator(req, false); @@ -54,4 +54,3 @@ describe("Crash tests", function() { }); }); }); - diff --git a/test/tests_events.js b/test/tests_events.js index 045d8db..4377398 100644 --- a/test/tests_events.js +++ b/test/tests_events.js @@ -1,62 +1,61 @@ /* eslint-disable no-console */ -/* global describe, it, */ -var Countly = require("../lib/countly"), - hp = require("./helpers/helper_functions"); +var Countly = require("../lib/countly"); +var hp = require("./helpers/helper_functions"); -//init function +// init function function initMain() { Countly.init({ app_key: "YOUR_APP_KEY", url: "https://try.count.ly", interval: 10000, - max_events: -1 + max_events: -1, }); } -//an event object to use +// an event object to use var eventObj = { - "key": "in_app_purchase", - "count": 3, - "sum": 2.97, - "dur": 1000, - "segmentation": { - "app_version": "1.0", - "country": "Turkey" - } + key: "in_app_purchase", + count: 3, + sum: 2.97, + dur: 1000, + segmentation: { + app_version: "1.0", + country: "Turkey", + }, }; // a timed event object var timedEventObj = { - "key": "timed", - "count": 1, - "segmentation": { - "app_version": "1.0", - "country": "Turkey" - } + key: "timed", + count: 1, + segmentation: { + app_version: "1.0", + country: "Turkey", + }, }; -describe("Events tests", function() { - it("Record and check custom event", function(done) { - //clear previous data +describe("Events tests", () => { + it("Record and check custom event", (done) => { + // clear previous data hp.clearStorage(); - //initialize SDK + // initialize SDK initMain(); - //send custom event + // send custom event Countly.add_event(eventObj); - //read event queue + // read event queue setTimeout(() => { var event = hp.readEventQueue()[0]; hp.eventValidator(eventObj, event); done(); }, hp.sWait); }); - it("Record and check timed events", function(done) { - //clear previous data + it("Record and check timed events", (done) => { + // clear previous data hp.clearStorage(); - //initialize SDK + // initialize SDK initMain(); - //send timed event + // send timed event Countly.start_event("timed"); setTimeout(() => { Countly.end_event(timedEventObj); - //read event queue + // read event queue setTimeout(() => { var event = hp.readEventQueue()[0]; hp.eventValidator(timedEventObj, event, (hp.mWait / 1000)); @@ -64,5 +63,4 @@ describe("Events tests", function() { }, hp.sWait); }, hp.mWait); }); - }); diff --git a/test/tests_http_response_success.js b/test/tests_http_response_success.js index 7b3a0d6..9ab575b 100644 --- a/test/tests_http_response_success.js +++ b/test/tests_http_response_success.js @@ -1,55 +1,54 @@ -/* global describe, it, */ var assert = require("assert"); var cc = require("../lib/countly-common"); -//unit tests for isResponseValid -describe("Response success suite", ()=>{ - it("Check if correct response parameters returns true", ()=>{ +// unit tests for isResponseValid +describe("Response success suite", () => { + it("Check if correct response parameters returns true", () => { var str = '{"result": "Success"}'; var result = cc.isResponseValid(200, str); assert.ok(result); }); - it("Check if wrong response that includes result in it returns false", ()=>{ + it("Check if wrong response that includes result in it returns false", () => { var str = '{"endResult": "Success"}'; var result = cc.isResponseValid(200, str); assert.equal(result, false); }); - it("Check if wrong response that does not include result in it returns false", ()=>{ + it("Check if wrong response that does not include result in it returns false", () => { var str = '{"end": "Success"}'; var result = cc.isResponseValid(200, str); assert.equal(result, false); }); - it("Check if wrong statusCode greater than 300 returns false", ()=>{ + it("Check if wrong statusCode greater than 300 returns false", () => { var str = '{"result": "Success"}'; var result = cc.isResponseValid(400, str); assert.equal(result, false); }); - it("Check if wrong statusCode less than 200 returns false", ()=>{ + it("Check if wrong statusCode less than 200 returns false", () => { var str = '{"result": "Success"}'; var result = cc.isResponseValid(100, str); assert.equal(result, false); }); - it("Check if wrong statusCode 300 returns false", ()=>{ + it("Check if wrong statusCode 300 returns false", () => { var str = '{"result": "Success"}'; var result = cc.isResponseValid(300, str); assert.equal(result, false); }); - it("Check if non Success value at result field returns true", ()=>{ + it("Check if non Success value at result field returns true", () => { var str = '{"result": "Sth"}'; var result = cc.isResponseValid(200, str); assert.equal(result, true); }); - it("Check if there is no statusCode it returns false", ()=>{ + it("Check if there is no statusCode it returns false", () => { var str = '{"result": "Success"}'; var result = cc.isResponseValid({}.a, str); assert.equal(result, false); }); - it("Check if just string/non-object returns false", ()=>{ + it("Check if just string/non-object returns false", () => { var str = "RESULT"; var result = cc.isResponseValid(200, str); assert.equal(result, false); }); - it("Check if empty response returns false", ()=>{ + it("Check if empty response returns false", () => { var res = {}; var str = ""; var result = cc.isResponseValid(res, str); diff --git a/test/tests_internal_limits.js b/test/tests_internal_limits.js index 3ea5cfa..5d38307 100644 --- a/test/tests_internal_limits.js +++ b/test/tests_internal_limits.js @@ -1,69 +1,66 @@ /* eslint-disable no-console */ -/* global describe, it, */ -var assert = require("assert"), - Countly = require("../lib/countly.js"), - hp = require("./helpers/helper_functions"), - cc = require("../lib/countly-common"); +var assert = require("assert"); +var Countly = require("../lib/countly"); +var hp = require("./helpers/helper_functions"); +var cc = require("../lib/countly-common"); -//standard init for tests +// standard init for tests function initLimitsMain() { Countly.init({ app_key: "YOUR_APP_KEY", url: "https://try.count.ly", interval: 10000, max_events: -1, - max_key_length: 8, //set maximum key length here - max_value_size: 8, //set maximum value length here - max_segmentation_values: 3, //set maximum segmentation number here - max_breadcrumb_count: 2, //set maximum number of logs that will be stored before erasing old ones - max_stack_trace_lines_per_thread: 3, //set maximum number of lines for stack trace - max_stack_trace_line_length: 10 //set maximum length of a line for stack trace + max_key_length: 8, // set maximum key length here + max_value_size: 8, // set maximum value length here + max_segmentation_values: 3, // set maximum segmentation number here + max_breadcrumb_count: 2, // set maximum number of logs that will be stored before erasing old ones + max_stack_trace_lines_per_thread: 3, // set maximum number of lines for stack trace + max_stack_trace_line_length: 10, // set maximum length of a line for stack trace }); } - - -//Integration tests with countly initialized -describe("Testing internal limits", function() { - describe("Testing truncation functions", function() { - it("truncateSingleValue: Check if the string is truncated", function() { +// Integration tests with countly initialized +describe("Testing internal limits", () => { + describe("Testing truncation functions", () => { + it("truncateSingleValue: Check if the string is truncated", () => { var newStr = cc.truncateSingleValue("123456789", 3, "test"); assert.equal(newStr, "123"); }); - it("truncateSingleValue: Check if the number is truncated", function() { + it("truncateSingleValue: Check if the number is truncated", () => { var newStr = cc.truncateSingleValue(123456789, 3, "test"); assert.equal(newStr, 123); }); - it("truncateSingleValue: Check if the object is returned unchanged", function() { - var object = {"123456789": 5}; + it("truncateSingleValue: Check if the object is returned unchanged", () => { + var object = { 123456789: 5 }; var obj = cc.truncateSingleValue(object, 3, "test"); assert.equal(object, obj); }); // Integration tests for truncateObjectValue: - it("truncateObject: Check if string key and value is truncated", function() { - var newObj = cc.truncateObject({"123456789": "123456789"}, 3, 5, 2, "test"); + it("truncateObject: Check if string key and value is truncated", () => { + var newObj = cc.truncateObject({ 123456789: "123456789" }, 3, 5, 2, "test"); assert.equal(newObj['123'], '12345'); }); - it("truncateObject: Check if number key and value is truncated", function() { - var newObj = cc.truncateObject({123456789: 123456789}, 3, 5, 2, "test"); + it("truncateObject: Check if number key and value is truncated", () => { + var newObj = cc.truncateObject({ 123456789: 123456789 }, 3, 5, 2, "test"); assert.equal(newObj['123'], '12345'); }); - it("truncateObject: Check if object value is kept as is", function() { - var newObj = cc.truncateObject({123456789: { 'a': 'aa'}}, 3, 5, 2, "test"); + it("truncateObject: Check if object value is kept as is", () => { + var newObj = cc.truncateObject({ 123456789: { a: 'aa' } }, 3, 5, 2, "test"); assert.equal(newObj['123'].a, 'aa'); }); - it("truncateObject: Check if segments are truncated", function() { - var newObj = cc.truncateObject({"a": "aa", "b": "bb", "c": "cc" }, 3, 5, 2, "test"); + it("truncateObject: Check if segments are truncated", () => { + var newObj = cc.truncateObject({ a: "aa", b: "bb", c: "cc" }, 3, 5, 2, "test"); assert.equal(Object.keys(newObj).length, 2); }); }); - it("1. Check custom event truncation", function(done) { - //clear storage + it("1. Check custom event truncation", (done) => { + // clear storage hp.clearStorage(); - //init Countly + // init Countly initLimitsMain(); - //send event + // send event Countly.add_event({ key: "Enter your key here", count: 1, @@ -76,7 +73,7 @@ describe("Testing internal limits", function() { }, }); setTimeout(() => { - //read event queue + // read event queue var event = hp.readEventQueue()[0]; assert.equal(event.key, "Enter yo"); assert.ok(event.segmentation["key of 3"]); @@ -89,16 +86,16 @@ describe("Testing internal limits", function() { }, hp.sWait); }); - it("2. Check countly view event truncation", function(done) { - //clear storage + it("2. Check countly view event truncation", (done) => { + // clear storage hp.clearStorage(); - //init Countly + // init Countly initLimitsMain(); - //page view + // page view Countly.track_pageview("a very long page name"); - //test + // test setTimeout(() => { - //read event queue + // read event queue var event = hp.readEventQueue()[0]; assert.equal(event.key, "[CLY]_vi"); assert.equal(event.segmentation.name, "a very l"); @@ -110,12 +107,12 @@ describe("Testing internal limits", function() { done(); }, hp.sWait); }); - it("3. Check breadcrumbs and error truncation", function(done) { - //clear storage + it("3. Check breadcrumbs and error truncation", (done) => { + // clear storage hp.clearStorage(); - //init Countly + // init Countly initLimitsMain(); - //add log + // add log Countly.add_log("log1"); Countly.add_log("log2"); Countly.add_log("log3"); @@ -123,14 +120,14 @@ describe("Testing internal limits", function() { Countly.add_log("log5 too many"); Countly.add_log("log6"); Countly.add_log("log7"); - //and log error to see them all + // and log error to see them all var error = { stack: "Lorem ipsum dolor sit amet,\n consectetur adipiscing elit, sed do eiusmod tempor\n incididunt ut labore et dolore magna\n aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\n Duis aute irure dolor in reprehenderit in voluptate\n velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia\n deserunt mollit anim id\n est laborum.", }; Countly.log_error(error); - //test + // test setTimeout(() => { - //read event queue + // read event queue var req = hp.readRequestQueue()[0]; assert.ok(req.crash); assert.ok(req.app_key); @@ -153,23 +150,23 @@ describe("Testing internal limits", function() { done(); }, hp.sWait); }); - it("4. Check user details truncation", function(done) { - //clear storage + it("4. Check user details truncation", (done) => { + // clear storage hp.clearStorage(); - //init Countly + // init Countly initLimitsMain(); - //add user details + // add user details Countly.user_details({ name: "Gottlob Frege", username: "Grundgesetze", email: "test@isatest.com", organization: "Bialloblotzsky", phone: "+4555999423", - //Web URL pointing to user picture + // Web URL pointing to user picture picture: "https://ih0.redbubble.net/image.276305970.7419/flat,550x550,075,f.u3.jpg", gender: "M", - byear: 1848, //birth year + byear: 1848, // birth year custom: { "SEGkey 1st one": "SEGVal 1st one", "SEGkey 2st one": "SEGVal 2st one", @@ -178,9 +175,9 @@ describe("Testing internal limits", function() { "SEGkey 5st one": "SEGVal 5st one", }, }); - //test + // test setTimeout(() => { - //read event queue + // read event queue var req = hp.readRequestQueue()[0]; assert.ok(req.user_details); assert.ok(req.app_key); @@ -207,25 +204,25 @@ describe("Testing internal limits", function() { done(); }, hp.sWait); }); - it("5. Check custom properties truncation", function(done) { - //clear storage + it("5. Check custom properties truncation", (done) => { + // clear storage hp.clearStorage(); - //init Countly + // init Countly initLimitsMain(); - //add custom properties - Countly.userData.set("name of a character", "Bertrand Arthur William Russell"); //set custom property - Countly.userData.set_once("A galaxy far far away", "Called B48FF"); //set custom property only if property does not exist - Countly.userData.increment_by("byear", 123456789012345); //increment value in key by provided value - Countly.userData.multiply("byear", 2345678901234567); //multiply value in key by provided value - Countly.userData.max("byear", 3456789012345678); //save max value between current and provided - Countly.userData.min("byear", 4567890123456789); //save min value between current and provided - Countly.userData.push("gender", "II Fernando Valdez"); //add value to key as array element - Countly.userData.push_unique("gender", "III Fernando Valdez"); //add value to key as array element, but only store unique values in array - Countly.userData.pull("gender", "III Fernando Valdez"); //remove value from array under property with key as name + // add custom properties + Countly.userData.set("name of a character", "Bertrand Arthur William Russell"); // set custom property + Countly.userData.set_once("A galaxy far far away", "Called B48FF"); // set custom property only if property does not exist + Countly.userData.increment_by("byear", 123456789012345); // increment value in key by provided value + Countly.userData.multiply("byear", 2345678901234567); // multiply value in key by provided value + Countly.userData.max("byear", 3456789012345678); // save max value between current and provided + Countly.userData.min("byear", 4567890123456789); // save min value between current and provided + Countly.userData.push("gender", "II Fernando Valdez"); // add value to key as array element + Countly.userData.push_unique("gender", "III Fernando Valdez"); // add value to key as array element, but only store unique values in array + Countly.userData.pull("gender", "III Fernando Valdez"); // remove value from array under property with key as name Countly.userData.save(); - //test + // test setTimeout(() => { - //read event queue + // read event queue var req = hp.readRequestQueue()[0]; assert.ok(req.user_details); assert.ok(req.app_key); @@ -236,28 +233,25 @@ describe("Testing internal limits", function() { assert.ok(req.hour); assert.ok(req.dow); var details = JSON.parse(req.user_details).custom; - //set + // set assert.equal(details['name of '], 'Bertrand'); - //set_once + // set_once assert.equal(details['A galaxy'].$setOnce, 'Called B'); - //increment_by + // increment_by assert.equal(details.byear.$inc, '12345678'); - //multiply + // multiply assert.equal(details.byear.$mul, '23456789'); - //max + // max assert.equal(details.byear.$max, '34567890'); - //min + // min assert.equal(details.byear.$min, '45678901'); - //push + // push assert.equal(details.gender.$push[0], 'II Ferna'); - //push_unique + // push_unique assert.equal(details.gender.$addToSet[0], 'III Fern'); - //pull + // pull assert.equal(details.gender.$pull[0], 'III Fern'); done(); }, hp.sWait); }); }); - - - diff --git a/test/tests_sessions.js b/test/tests_sessions.js index a479289..2893cc7 100644 --- a/test/tests_sessions.js +++ b/test/tests_sessions.js @@ -1,23 +1,22 @@ /* eslint-disable no-console */ -/* global describe, it, */ -var Countly = require("../lib/countly"), - hp = require("./helpers/helper_functions"); +var Countly = require("../lib/countly"); +var hp = require("./helpers/helper_functions"); -//init function +// init function function initMain() { Countly.init({ app_key: "YOUR_APP_KEY", url: "https://try.count.ly", - max_events: -1 + max_events: -1, }); } -describe("Sessions tests", function() { - it("Start session and validate the request queue", function(done) { - //clear previous data +describe("Sessions tests", () => { + it("Start session and validate the request queue", (done) => { + // clear previous data hp.clearStorage(); - //initialize SDK + // initialize SDK initMain(); - //send session calls + // send session calls Countly.begin_session(); setTimeout(() => { var beg = hp.readRequestQueue()[0]; @@ -25,12 +24,12 @@ describe("Sessions tests", function() { done(); }, hp.sWait); }); - it("Start and end session and validate the request queue", function(done) { - //clear previous data + it("Start and end session and validate the request queue", (done) => { + // clear previous data hp.clearStorage(); - //initialize SDK + // initialize SDK initMain(); - //send session calls + // send session calls Countly.begin_session(); setTimeout(() => { Countly.end_session(); @@ -43,4 +42,3 @@ describe("Sessions tests", function() { }, hp.mWait); }); }); - diff --git a/test/tests_user_details.js b/test/tests_user_details.js index 2bd29ea..9e859ec 100644 --- a/test/tests_user_details.js +++ b/test/tests_user_details.js @@ -1,41 +1,40 @@ /* eslint-disable no-console */ -/* global describe, it, */ -var Countly = require("../lib/countly"), - hp = require("./helpers/helper_functions"); +var Countly = require("../lib/countly"); +var hp = require("./helpers/helper_functions"); -//init function +var userDetailObj = { + name: "Barturiana Sosinsiava", + username: "bar2rawwen", + email: "test@test.com", + organization: "Dukely", + phone: "+123456789", + picture: "https://ps.timg.com/profile_images/52237/011_n_400x400.jpg", + gender: "Non-binary", + byear: 1987, // birth year + custom: { + "key1 segment": "value1 segment", + "key2 segment": "value2 segment", + }, +}; +// init function function initMain() { Countly.init({ app_key: "YOUR_APP_KEY", url: "https://try.count.ly", interval: 10000, - max_events: -1 + max_events: -1, }); } -var userDetailObj = { - "name": "Barturiana Sosinsiava", - "username": "bar2rawwen", - "email": "test@test.com", - "organization": "Dukely", - "phone": "+123456789", - "picture": "https://ps.timg.com/profile_images/52237/011_n_400x400.jpg", - "gender": "Non-binary", - "byear": 1987, //birth year - "custom": { - "key1 segment": "value1 segment", - "key2 segment": "value2 segment", - } -}; -describe("User details tests", function() { - it("Record and validate all user details", function(done) { - //clear previous data +describe("User details tests", () => { + it("Record and validate all user details", (done) => { + // clear previous data hp.clearStorage(); - //initialize SDK + // initialize SDK initMain(); - //send user details + // send user details Countly.user_details(userDetailObj); - //read event queue + // read event queue setTimeout(() => { var req = hp.readRequestQueue()[0]; hp.userDetailRequestValidator(userDetailObj, req); @@ -43,4 +42,3 @@ describe("User details tests", function() { }, hp.sWait); }); }); - diff --git a/test/tests_views.js b/test/tests_views.js index 860d066..664f3ca 100644 --- a/test/tests_views.js +++ b/test/tests_views.js @@ -1,79 +1,76 @@ /* eslint-disable no-console */ -/* global describe, it, */ -var Countly = require("../lib/countly"), - hp = require("./helpers/helper_functions"); +var Countly = require("../lib/countly"); +var hp = require("./helpers/helper_functions"); -//init function +var pageNameOne = "test view page name1"; +var pageNameTwo = "test view page name2"; +// init function function initMain() { Countly.init({ app_key: "YOUR_APP_KEY", url: "https://try.count.ly", interval: 10000, - max_events: -1 + max_events: -1, }); } -var pageNameOne = "test view page name1"; -var pageNameTwo = "test view page name2"; -describe("View test", function() { - it("Record and validate page views", function(done) { - //clear previous data +describe("View test", () => { + it("Record and validate page views", (done) => { + // clear previous data hp.clearStorage(); - //initialize SDK + // initialize SDK initMain(); - //send track view + // send track view Countly.track_view(pageNameOne); - //read event queue + // read event queue setTimeout(() => { var event = hp.readEventQueue()[0]; hp.viewEventValidator(pageNameOne, event); done(); }, hp.sWait); }); - it("Record and validate timed page views with same name", function(done) { - //clear previous data + it("Record and validate timed page views with same name", (done) => { + // clear previous data hp.clearStorage(); - //initialize SDK + // initialize SDK initMain(); Countly.track_view(pageNameOne); setTimeout(() => { - //send track view + // send track view Countly.track_view(pageNameOne); - //read event queue + // read event queue setTimeout(() => { var event = hp.readEventQueue(); - //start view + // start view hp.viewEventValidator(pageNameOne, event[0]); - //end view with recording duration + // end view with recording duration hp.viewEventValidator(pageNameOne, event[1], (hp.mWait / 1000)); - //start second view + // start second view hp.viewEventValidator(pageNameOne, event[2]); done(); }, hp.sWait); }, hp.mWait); }); - it("Record and validate timed page views with same name", function(done) { - //clear previous data + it("Record and validate timed page views with same name", (done) => { + // clear previous data hp.clearStorage(); - //initialize SDK + // initialize SDK initMain(); Countly.track_view(pageNameOne); setTimeout(() => { - //send track view + // send track view Countly.track_view(pageNameTwo); - //read event queue + // read event queue setTimeout(() => { var event = hp.readEventQueue(); - //start view + // start view hp.viewEventValidator(pageNameOne, event[0]); - //end view with recording duration + // end view with recording duration hp.viewEventValidator(pageNameOne, event[1], (hp.mWait / 1000)); - //start second view + // start second view hp.viewEventValidator(pageNameTwo, event[2]); done(); }, hp.sWait); }, hp.mWait); }); - }); -