clevertap-web-sdk
Version:
<p align="center"> <img src="https://github.com/CleverTap/clevertap-ios-sdk/blob/master/docs/images/clevertap-logo.png" width = "50%"/> </p>
1,586 lines (1,362 loc) • 628 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.clevertap = factory());
})(this, (function () { 'use strict';
var id = 0;
function _classPrivateFieldLooseKey(name) {
return "__private_" + id++ + "_" + name;
}
function _classPrivateFieldLooseBase(receiver, privateKey) {
if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) {
throw new TypeError("attempted to use private field on non-instance");
}
return receiver;
}
const TARGET_DOMAIN = 'clevertap-prod.com';
const TARGET_PROTOCOL = 'https:';
const DEFAULT_REGION = 'eu1';
var _accountId = _classPrivateFieldLooseKey("accountId");
var _region = _classPrivateFieldLooseKey("region");
var _targetDomain = _classPrivateFieldLooseKey("targetDomain");
var _dcSdkversion = _classPrivateFieldLooseKey("dcSdkversion");
var _token = _classPrivateFieldLooseKey("token");
class Account {
constructor() {
let {
id
} = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let region = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
let targetDomain = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : TARGET_DOMAIN;
let token = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '';
Object.defineProperty(this, _accountId, {
writable: true,
value: void 0
});
Object.defineProperty(this, _region, {
writable: true,
value: ''
});
Object.defineProperty(this, _targetDomain, {
writable: true,
value: TARGET_DOMAIN
});
Object.defineProperty(this, _dcSdkversion, {
writable: true,
value: ''
});
Object.defineProperty(this, _token, {
writable: true,
value: ''
});
this.id = id;
if (region) {
this.region = region;
}
if (targetDomain) {
this.targetDomain = targetDomain;
}
if (token) {
this.token = token;
}
}
get id() {
return _classPrivateFieldLooseBase(this, _accountId)[_accountId];
}
set id(accountId) {
_classPrivateFieldLooseBase(this, _accountId)[_accountId] = accountId;
}
get region() {
return _classPrivateFieldLooseBase(this, _region)[_region];
}
set region(region) {
_classPrivateFieldLooseBase(this, _region)[_region] = region;
}
get dcSDKVersion() {
return _classPrivateFieldLooseBase(this, _dcSdkversion)[_dcSdkversion];
}
set dcSDKVersion(dcSDKVersion) {
_classPrivateFieldLooseBase(this, _dcSdkversion)[_dcSdkversion] = dcSDKVersion;
}
get targetDomain() {
return _classPrivateFieldLooseBase(this, _targetDomain)[_targetDomain];
}
set targetDomain(targetDomain) {
_classPrivateFieldLooseBase(this, _targetDomain)[_targetDomain] = targetDomain;
}
get token() {
return _classPrivateFieldLooseBase(this, _token)[_token];
}
set token(token) {
_classPrivateFieldLooseBase(this, _token)[_token] = token;
}
get finalTargetDomain() {
if (this.region) {
return "".concat(this.region, ".").concat(this.targetDomain);
} else {
if (this.targetDomain === TARGET_DOMAIN) {
return "".concat(DEFAULT_REGION, ".").concat(this.targetDomain);
}
return this.targetDomain;
}
}
get dataPostPEURL() {
return "".concat(TARGET_PROTOCOL, "//").concat(this.finalTargetDomain, "/defineVars");
}
get dataPostURL() {
return "".concat(TARGET_PROTOCOL, "//").concat(this.finalTargetDomain, "/a?t=96");
}
get recorderURL() {
return "".concat(TARGET_PROTOCOL, "//").concat(this.finalTargetDomain, "/r?r=1");
}
get emailURL() {
return "".concat(TARGET_PROTOCOL, "//").concat(this.finalTargetDomain, "/e?r=1");
}
}
const unsupportedKeyCharRegex = new RegExp('^\\s+|\\\.|\:|\\\$|\'|\"|\\\\|\\s+$', 'g');
const unsupportedValueCharRegex = new RegExp("^\\s+|\'|\"|\\\\|\\s+$", 'g');
const singleQuoteRegex = new RegExp('\'', 'g');
const CLEAR = 'clear';
const CHARGED_ID = 'Charged ID';
const CHARGEDID_COOKIE_NAME = 'WZRK_CHARGED_ID';
const GCOOKIE_NAME = 'WZRK_G';
const KCOOKIE_NAME = 'WZRK_K';
const CAMP_COOKIE_NAME = 'WZRK_CAMP';
const CAMP_COOKIE_G = 'WZRK_CAMP_G'; // cookie for storing campaign details against guid
const SCOOKIE_PREFIX = 'WZRK_S';
const SCOOKIE_EXP_TIME_IN_SECS = 60 * 20; // 20 mins
const EV_COOKIE = 'WZRK_EV';
const META_COOKIE = 'WZRK_META';
const PR_COOKIE = 'WZRK_PR';
const ACCOUNT_ID = 'WZRK_ACCOUNT_ID';
const ARP_COOKIE = 'WZRK_ARP';
const LCOOKIE_NAME = 'WZRK_L';
const GLOBAL = 'global'; // used for email unsubscribe also
const DISPLAY = 'display';
const WEBPUSH_LS_KEY = 'WZRK_WPR';
const OPTOUT_KEY = 'optOut';
const CT_OPTOUT_KEY = 'ct_optout';
const OPTOUT_COOKIE_ENDSWITH = ':OO';
const USEIP_KEY = 'useIP';
const LRU_CACHE = 'WZRK_X';
const LRU_CACHE_SIZE = 100;
const IS_OUL = 'isOUL';
const EVT_PUSH = 'push';
const EVT_PING = 'ping';
const COOKIE_EXPIRY = 86400 * 365; // 1 Year in seconds
const MAX_TRIES = 200; // API tries
const FIRST_PING_FREQ_IN_MILLIS = 2 * 60 * 1000; // 2 mins
const CONTINUOUS_PING_FREQ_IN_MILLIS = 5 * 60 * 1000; // 5 mins
const GROUP_SUBSCRIPTION_REQUEST_ID = '2';
const categoryLongKey = 'cUsY';
const WZRK_PREFIX = 'wzrk_';
const WZRK_ID = 'wzrk_id';
const NOTIFICATION_VIEWED = 'Notification Viewed';
const NOTIFICATION_CLICKED = 'Notification Clicked';
const FIRE_PUSH_UNREGISTERED = 'WZRK_FPU';
const PUSH_SUBSCRIPTION_DATA = 'WZRK_PSD'; // PUSH SUBSCRIPTION DATA FOR REGISTER/UNREGISTER TOKEN
const COMMAND_INCREMENT = '$incr';
const COMMAND_DECREMENT = '$decr';
const COMMAND_SET = '$set';
const COMMAND_ADD = '$add';
const COMMAND_REMOVE = '$remove';
const COMMAND_DELETE = '$delete';
const WEBINBOX_CONFIG = 'WZRK_INBOX_CONFIG';
const WEBINBOX = 'WZRK_INBOX';
const MAX_INBOX_MSG = 15;
const VARIABLES = 'WZRK_PE';
const PUSH_DELAY_MS = 1000;
const MAX_DELAY_FREQUENCY = 1000 * 60 * 10;
const WZRK_FETCH = 'wzrk_fetch';
const WEBPUSH_CONFIG = 'WZRK_PUSH_CONFIG';
const APPLICATION_SERVER_KEY_RECEIVED = 'WZRK_APPLICATION_SERVER_KEY_RECIEVED';
const WEBPUSH_CONFIG_RECEIVED = 'WZRK_WEB_PUSH_CONFIG_RECEIVED';
const NOTIFICATION_PUSH_METHOD_DEFERRED = 'WZRK_NOTIFICATION_PUSH_DEFERRED';
const VAPID_MIGRATION_PROMPT_SHOWN = 'vapid_migration_prompt_shown';
const NOTIF_LAST_TIME = 'notif_last_time';
const TIMER_FOR_NOTIF_BADGE_UPDATE = 300;
const OLD_SOFT_PROMPT_SELCTOR_ID = 'wzrk_wrapper';
const NEW_SOFT_PROMPT_SELCTOR_ID = 'pnWrapper';
const POPUP_LOADING = 'WZRK_POPUP_LOADING';
const CUSTOM_HTML_PREVIEW = 'ctCustomHtmlPreview';
const WEB_NATIVE_TEMPLATES = {
KV_PAIR: 1,
BANNER: 2,
CAROUSEL: 3,
VISUAL_BUILDER: 4,
CUSTOM_HTML: 5,
JSON: 6
};
const WEB_NATIVE_DISPLAY_VISUAL_EDITOR_TYPES = {
HTML: 'html',
FORM: 'form',
JSON: 'json'
};
const CAMPAIGN_TYPES = {
EXIT_INTENT: 1,
WEB_NATIVE_DISPLAY: 2,
FOOTER_NOTIFICATION: 0,
FOOTER_NOTIFICATION_2: null
};
const SYSTEM_EVENTS = ['Stayed', 'UTM Visited', 'App Launched', 'Notification Sent', NOTIFICATION_VIEWED, NOTIFICATION_CLICKED];
const KEYS_TO_ENCRYPT = [KCOOKIE_NAME, LRU_CACHE, PR_COOKIE];
const ACTION_TYPES = {
OPEN_LINK: 'url',
OPEN_LINK_AND_CLOSE: 'urlCloseNotification'
};
const isString = input => {
return typeof input === 'string' || input instanceof String;
};
const isObject = input => {
// TODO: refine
return Object.prototype.toString.call(input) === '[object Object]';
};
const isDateObject = input => {
return typeof input === 'object' && input instanceof Date;
};
const isObjectEmpty = obj => {
for (const prop in obj) {
if (obj.hasOwnProperty(prop)) {
return false;
}
}
return true;
};
const isConvertibleToNumber = n => {
return !isNaN(parseFloat(n)) && isFinite(n);
};
const isNumber = n => {
return /^-?[\d.]+(?:e-?\d+)?$/.test(n) && typeof n === 'number';
};
const isValueValid = value => {
if (value === null || value === undefined || value === 'undefined') {
return false;
}
return true;
};
const removeUnsupportedChars = (o, logger) => {
// keys can't be greater than 1024 chars, values can't be greater than 1024 chars
if (typeof o === 'object') {
for (const key in o) {
if (o.hasOwnProperty(key)) {
const sanitizedVal = removeUnsupportedChars(o[key], logger);
let sanitizedKey;
sanitizedKey = sanitize(key, unsupportedKeyCharRegex);
if (sanitizedKey.length > 1024) {
sanitizedKey = sanitizedKey.substring(0, 1024);
logger.reportError(520, sanitizedKey + '... length exceeded 1024 chars. Trimmed.');
}
delete o[key];
o[sanitizedKey] = sanitizedVal;
}
}
} else {
let val;
if (isString(o)) {
val = sanitize(o, unsupportedValueCharRegex);
if (val.length > 1024) {
val = val.substring(0, 1024);
logger.reportError(521, val + '... length exceeded 1024 chars. Trimmed.');
}
} else {
val = o;
}
return val;
}
return o;
};
const sanitize = (input, regex) => {
return input.replace(regex, '');
};
const getToday = () => {
const today = new Date();
return today.getFullYear() + '' + today.getMonth() + '' + today.getDay();
};
const getNow = () => {
return Math.floor(new Date().getTime() / 1000);
};
const convertToWZRKDate = dateObj => {
return '$D_' + Math.round(dateObj.getTime() / 1000);
};
const setDate = dt => {
// expecting yyyymmdd format either as a number or a string
if (isDateValid(dt)) {
return '$D_' + dt;
}
};
const isDateValid = date => {
const matches = /^(\d{4})(\d{2})(\d{2})$/.exec(date);
if (matches == null) return false;
const d = matches[3];
const m = matches[2] - 1;
const y = matches[1];
const composedDate = new Date(y, m, d); // eslint-disable-next-line eqeqeq
return composedDate.getDate() == d && composedDate.getMonth() == m && composedDate.getFullYear() == y;
};
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
var cryptoJs$1 = {exports: {}};
function commonjsRequire(path) {
throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
}
var core$1 = {exports: {}};
var core = core$1.exports;
var hasRequiredCore;
function requireCore() {
if (hasRequiredCore) return core$1.exports;
hasRequiredCore = 1;
(function (module, exports) {
(function (root, factory) {
{
// CommonJS
module.exports = factory();
}
})(core, function () {
/*globals window, global, require*/
/**
* CryptoJS core components.
*/
var CryptoJS = CryptoJS || function (Math, undefined$1) {
var crypto; // Native crypto from window (Browser)
if (typeof window !== 'undefined' && window.crypto) {
crypto = window.crypto;
} // Native crypto in web worker (Browser)
if (typeof self !== 'undefined' && self.crypto) {
crypto = self.crypto;
} // Native crypto from worker
if (typeof globalThis !== 'undefined' && globalThis.crypto) {
crypto = globalThis.crypto;
} // Native (experimental IE 11) crypto from window (Browser)
if (!crypto && typeof window !== 'undefined' && window.msCrypto) {
crypto = window.msCrypto;
} // Native crypto from global (NodeJS)
if (!crypto && typeof commonjsGlobal !== 'undefined' && commonjsGlobal.crypto) {
crypto = commonjsGlobal.crypto;
} // Native crypto import via require (NodeJS)
if (!crypto && typeof commonjsRequire === 'function') {
try {
crypto = require('crypto');
} catch (err) {}
}
/*
* Cryptographically secure pseudorandom number generator
*
* As Math.random() is cryptographically not safe to use
*/
var cryptoSecureRandomInt = function () {
if (crypto) {
// Use getRandomValues method (Browser)
if (typeof crypto.getRandomValues === 'function') {
try {
return crypto.getRandomValues(new Uint32Array(1))[0];
} catch (err) {}
} // Use randomBytes method (NodeJS)
if (typeof crypto.randomBytes === 'function') {
try {
return crypto.randomBytes(4).readInt32LE();
} catch (err) {}
}
}
throw new Error('Native crypto module could not be used to get secure random number.');
};
/*
* Local polyfill of Object.create
*/
var create = Object.create || function () {
function F() {}
return function (obj) {
var subtype;
F.prototype = obj;
subtype = new F();
F.prototype = null;
return subtype;
};
}();
/**
* CryptoJS namespace.
*/
var C = {};
/**
* Library namespace.
*/
var C_lib = C.lib = {};
/**
* Base object for prototypal inheritance.
*/
var Base = C_lib.Base = function () {
return {
/**
* Creates a new object that inherits from this object.
*
* @param {Object} overrides Properties to copy into the new object.
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* field: 'value',
*
* method: function () {
* }
* });
*/
extend: function (overrides) {
// Spawn
var subtype = create(this); // Augment
if (overrides) {
subtype.mixIn(overrides);
} // Create default initializer
if (!subtype.hasOwnProperty('init') || this.init === subtype.init) {
subtype.init = function () {
subtype.$super.init.apply(this, arguments);
};
} // Initializer's prototype is the subtype object
subtype.init.prototype = subtype; // Reference supertype
subtype.$super = this;
return subtype;
},
/**
* Extends this object and runs the init method.
* Arguments to create() will be passed to init().
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var instance = MyType.create();
*/
create: function () {
var instance = this.extend();
instance.init.apply(instance, arguments);
return instance;
},
/**
* Initializes a newly created object.
* Override this method to add some logic when your objects are created.
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* init: function () {
* // ...
* }
* });
*/
init: function () {},
/**
* Copies properties into this object.
*
* @param {Object} properties The properties to mix in.
*
* @example
*
* MyType.mixIn({
* field: 'value'
* });
*/
mixIn: function (properties) {
for (var propertyName in properties) {
if (properties.hasOwnProperty(propertyName)) {
this[propertyName] = properties[propertyName];
}
} // IE won't copy toString using the loop above
if (properties.hasOwnProperty('toString')) {
this.toString = properties.toString;
}
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = instance.clone();
*/
clone: function () {
return this.init.prototype.extend(this);
}
};
}();
/**
* An array of 32-bit words.
*
* @property {Array} words The array of 32-bit words.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var WordArray = C_lib.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of 32-bit words.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.create();
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined$1) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 4;
}
},
/**
* Converts this word array to a string.
*
* @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
*
* @return {string} The stringified word array.
*
* @example
*
* var string = wordArray + '';
* var string = wordArray.toString();
* var string = wordArray.toString(CryptoJS.enc.Utf8);
*/
toString: function (encoder) {
return (encoder || Hex).stringify(this);
},
/**
* Concatenates a word array to this word array.
*
* @param {WordArray} wordArray The word array to append.
*
* @return {WordArray} This word array.
*
* @example
*
* wordArray1.concat(wordArray2);
*/
concat: function (wordArray) {
// Shortcuts
var thisWords = this.words;
var thatWords = wordArray.words;
var thisSigBytes = this.sigBytes;
var thatSigBytes = wordArray.sigBytes; // Clamp excess bits
this.clamp(); // Concat
if (thisSigBytes % 4) {
// Copy one byte at a time
for (var i = 0; i < thatSigBytes; i++) {
var thatByte = thatWords[i >>> 2] >>> 24 - i % 4 * 8 & 0xff;
thisWords[thisSigBytes + i >>> 2] |= thatByte << 24 - (thisSigBytes + i) % 4 * 8;
}
} else {
// Copy one word at a time
for (var j = 0; j < thatSigBytes; j += 4) {
thisWords[thisSigBytes + j >>> 2] = thatWords[j >>> 2];
}
}
this.sigBytes += thatSigBytes; // Chainable
return this;
},
/**
* Removes insignificant bits.
*
* @example
*
* wordArray.clamp();
*/
clamp: function () {
// Shortcuts
var words = this.words;
var sigBytes = this.sigBytes; // Clamp
words[sigBytes >>> 2] &= 0xffffffff << 32 - sigBytes % 4 * 8;
words.length = Math.ceil(sigBytes / 4);
},
/**
* Creates a copy of this word array.
*
* @return {WordArray} The clone.
*
* @example
*
* var clone = wordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone.words = this.words.slice(0);
return clone;
},
/**
* Creates a word array filled with random bytes.
*
* @param {number} nBytes The number of random bytes to generate.
*
* @return {WordArray} The random word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.random(16);
*/
random: function (nBytes) {
var words = [];
for (var i = 0; i < nBytes; i += 4) {
words.push(cryptoSecureRandomInt());
}
return new WordArray.init(words, nBytes);
}
});
/**
* Encoder namespace.
*/
var C_enc = C.enc = {};
/**
* Hex encoding strategy.
*/
var Hex = C_enc.Hex = {
/**
* Converts a word array to a hex string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The hex string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.enc.Hex.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes; // Convert
var hexChars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = words[i >>> 2] >>> 24 - i % 4 * 8 & 0xff;
hexChars.push((bite >>> 4).toString(16));
hexChars.push((bite & 0x0f).toString(16));
}
return hexChars.join('');
},
/**
* Converts a hex string to a word array.
*
* @param {string} hexStr The hex string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Hex.parse(hexString);
*/
parse: function (hexStr) {
// Shortcut
var hexStrLength = hexStr.length; // Convert
var words = [];
for (var i = 0; i < hexStrLength; i += 2) {
words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << 24 - i % 8 * 4;
}
return new WordArray.init(words, hexStrLength / 2);
}
};
/**
* Latin1 encoding strategy.
*/
var Latin1 = C_enc.Latin1 = {
/**
* Converts a word array to a Latin1 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Latin1 string.
*
* @static
*
* @example
*
* var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes; // Convert
var latin1Chars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = words[i >>> 2] >>> 24 - i % 4 * 8 & 0xff;
latin1Chars.push(String.fromCharCode(bite));
}
return latin1Chars.join('');
},
/**
* Converts a Latin1 string to a word array.
*
* @param {string} latin1Str The Latin1 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
*/
parse: function (latin1Str) {
// Shortcut
var latin1StrLength = latin1Str.length; // Convert
var words = [];
for (var i = 0; i < latin1StrLength; i++) {
words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << 24 - i % 4 * 8;
}
return new WordArray.init(words, latin1StrLength);
}
};
/**
* UTF-8 encoding strategy.
*/
var Utf8 = C_enc.Utf8 = {
/**
* Converts a word array to a UTF-8 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-8 string.
*
* @static
*
* @example
*
* var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
*/
stringify: function (wordArray) {
try {
return decodeURIComponent(escape(Latin1.stringify(wordArray)));
} catch (e) {
throw new Error('Malformed UTF-8 data');
}
},
/**
* Converts a UTF-8 string to a word array.
*
* @param {string} utf8Str The UTF-8 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
*/
parse: function (utf8Str) {
return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
}
};
/**
* Abstract buffered block algorithm template.
*
* The property blockSize must be implemented in a concrete subtype.
*
* @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
*/
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
/**
* Resets this block algorithm's data buffer to its initial state.
*
* @example
*
* bufferedBlockAlgorithm.reset();
*/
reset: function () {
// Initial values
this._data = new WordArray.init();
this._nDataBytes = 0;
},
/**
* Adds new data to this block algorithm's buffer.
*
* @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
*
* @example
*
* bufferedBlockAlgorithm._append('data');
* bufferedBlockAlgorithm._append(wordArray);
*/
_append: function (data) {
// Convert string to WordArray, else assume WordArray already
if (typeof data == 'string') {
data = Utf8.parse(data);
} // Append
this._data.concat(data);
this._nDataBytes += data.sigBytes;
},
/**
* Processes available data blocks.
*
* This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
*
* @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
*
* @return {WordArray} The processed data.
*
* @example
*
* var processedData = bufferedBlockAlgorithm._process();
* var processedData = bufferedBlockAlgorithm._process(!!'flush');
*/
_process: function (doFlush) {
var processedWords; // Shortcuts
var data = this._data;
var dataWords = data.words;
var dataSigBytes = data.sigBytes;
var blockSize = this.blockSize;
var blockSizeBytes = blockSize * 4; // Count blocks ready
var nBlocksReady = dataSigBytes / blockSizeBytes;
if (doFlush) {
// Round up to include partial blocks
nBlocksReady = Math.ceil(nBlocksReady);
} else {
// Round down to include only full blocks,
// less the number of blocks that must remain in the buffer
nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
} // Count words ready
var nWordsReady = nBlocksReady * blockSize; // Count bytes ready
var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); // Process blocks
if (nWordsReady) {
for (var offset = 0; offset < nWordsReady; offset += blockSize) {
// Perform concrete-algorithm logic
this._doProcessBlock(dataWords, offset);
} // Remove processed words
processedWords = dataWords.splice(0, nWordsReady);
data.sigBytes -= nBytesReady;
} // Return processed words
return new WordArray.init(processedWords, nBytesReady);
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = bufferedBlockAlgorithm.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone._data = this._data.clone();
return clone;
},
_minBufferSize: 0
});
/**
* Abstract hasher template.
*
* @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
*/
C_lib.Hasher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*/
cfg: Base.extend(),
/**
* Initializes a newly created hasher.
*
* @param {Object} cfg (Optional) The configuration options to use for this hash computation.
*
* @example
*
* var hasher = CryptoJS.algo.SHA256.create();
*/
init: function (cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg); // Set initial values
this.reset();
},
/**
* Resets this hasher to its initial state.
*
* @example
*
* hasher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this); // Perform concrete-hasher logic
this._doReset();
},
/**
* Updates this hasher with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {Hasher} This hasher.
*
* @example
*
* hasher.update('message');
* hasher.update(wordArray);
*/
update: function (messageUpdate) {
// Append
this._append(messageUpdate); // Update the hash
this._process(); // Chainable
return this;
},
/**
* Finalizes the hash computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The hash.
*
* @example
*
* var hash = hasher.finalize();
* var hash = hasher.finalize('message');
* var hash = hasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Final message update
if (messageUpdate) {
this._append(messageUpdate);
} // Perform concrete-hasher logic
var hash = this._doFinalize();
return hash;
},
blockSize: 512 / 32,
/**
* Creates a shortcut function to a hasher's object interface.
*
* @param {Hasher} hasher The hasher to create a helper for.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
*/
_createHelper: function (hasher) {
return function (message, cfg) {
return new hasher.init(cfg).finalize(message);
};
},
/**
* Creates a shortcut function to the HMAC's object interface.
*
* @param {Hasher} hasher The hasher to use in this HMAC helper.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
*/
_createHmacHelper: function (hasher) {
return function (message, key) {
return new C_algo.HMAC.init(hasher, key).finalize(message);
};
}
});
/**
* Algorithm namespace.
*/
var C_algo = C.algo = {};
return C;
}(Math);
return CryptoJS;
});
})(core$1, core$1.exports);
return core$1.exports;
}
var x64Core$1 = {exports: {}};
var x64Core = x64Core$1.exports;
var hasRequiredX64Core;
function requireX64Core() {
if (hasRequiredX64Core) return x64Core$1.exports;
hasRequiredX64Core = 1;
(function (module, exports) {
(function (root, factory) {
{
// CommonJS
module.exports = factory(requireCore());
}
})(x64Core, function (CryptoJS) {
(function (undefined$1) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var X32WordArray = C_lib.WordArray;
/**
* x64 namespace.
*/
var C_x64 = C.x64 = {};
/**
* A 64-bit word.
*/
C_x64.Word = Base.extend({
/**
* Initializes a newly created 64-bit word.
*
* @param {number} high The high 32 bits.
* @param {number} low The low 32 bits.
*
* @example
*
* var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607);
*/
init: function (high, low) {
this.high = high;
this.low = low;
}
/**
* Bitwise NOTs this word.
*
* @return {X64Word} A new x64-Word object after negating.
*
* @example
*
* var negated = x64Word.not();
*/
// not: function () {
// var high = ~this.high;
// var low = ~this.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise ANDs this word with the passed word.
*
* @param {X64Word} word The x64-Word to AND with this word.
*
* @return {X64Word} A new x64-Word object after ANDing.
*
* @example
*
* var anded = x64Word.and(anotherX64Word);
*/
// and: function (word) {
// var high = this.high & word.high;
// var low = this.low & word.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise ORs this word with the passed word.
*
* @param {X64Word} word The x64-Word to OR with this word.
*
* @return {X64Word} A new x64-Word object after ORing.
*
* @example
*
* var ored = x64Word.or(anotherX64Word);
*/
// or: function (word) {
// var high = this.high | word.high;
// var low = this.low | word.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise XORs this word with the passed word.
*
* @param {X64Word} word The x64-Word to XOR with this word.
*
* @return {X64Word} A new x64-Word object after XORing.
*
* @example
*
* var xored = x64Word.xor(anotherX64Word);
*/
// xor: function (word) {
// var high = this.high ^ word.high;
// var low = this.low ^ word.low;
// return X64Word.create(high, low);
// },
/**
* Shifts this word n bits to the left.
*
* @param {number} n The number of bits to shift.
*
* @return {X64Word} A new x64-Word object after shifting.
*
* @example
*
* var shifted = x64Word.shiftL(25);
*/
// shiftL: function (n) {
// if (n < 32) {
// var high = (this.high << n) | (this.low >>> (32 - n));
// var low = this.low << n;
// } else {
// var high = this.low << (n - 32);
// var low = 0;
// }
// return X64Word.create(high, low);
// },
/**
* Shifts this word n bits to the right.
*
* @param {number} n The number of bits to shift.
*
* @return {X64Word} A new x64-Word object after shifting.
*
* @example
*
* var shifted = x64Word.shiftR(7);
*/
// shiftR: function (n) {
// if (n < 32) {
// var low = (this.low >>> n) | (this.high << (32 - n));
// var high = this.high >>> n;
// } else {
// var low = this.high >>> (n - 32);
// var high = 0;
// }
// return X64Word.create(high, low);
// },
/**
* Rotates this word n bits to the left.
*
* @param {number} n The number of bits to rotate.
*
* @return {X64Word} A new x64-Word object after rotating.
*
* @example
*
* var rotated = x64Word.rotL(25);
*/
// rotL: function (n) {
// return this.shiftL(n).or(this.shiftR(64 - n));
// },
/**
* Rotates this word n bits to the right.
*
* @param {number} n The number of bits to rotate.
*
* @return {X64Word} A new x64-Word object after rotating.
*
* @example
*
* var rotated = x64Word.rotR(7);
*/
// rotR: function (n) {
// return this.shiftR(n).or(this.shiftL(64 - n));
// },
/**
* Adds this word with the passed word.
*
* @param {X64Word} word The x64-Word to add with this word.
*
* @return {X64Word} A new x64-Word object after adding.
*
* @example
*
* var added = x64Word.add(anotherX64Word);
*/
// add: function (word) {
// var low = (this.low + word.low) | 0;
// var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0;
// var high = (this.high + word.high + carry) | 0;
// return X64Word.create(high, low);
// }
});
/**
* An array of 64-bit words.
*
* @property {Array} words The array of CryptoJS.x64.Word objects.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
C_x64.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of CryptoJS.x64.Word objects.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.x64.WordArray.create();
*
* var wordArray = CryptoJS.x64.WordArray.create([
* CryptoJS.x64.Word.create(0x00010203, 0x04050607),
* CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
* ]);
*
* var wordArray = CryptoJS.x64.WordArray.create([
* CryptoJS.x64.Word.create(0x00010203, 0x04050607),
* CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
* ], 10);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined$1) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 8;
}
},
/**
* Converts this 64-bit word array to a 32-bit word array.
*
* @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array.
*
* @example
*
* var x32WordArray = x64WordArray.toX32();
*/
toX32: function () {
// Shortcuts
var x64Words = this.words;
var x64WordsLength = x64Words.length; // Convert
var x32Words = [];
for (var i = 0; i < x64WordsLength; i++) {
var x64Word = x64Words[i];
x32Words.push(x64Word.high);
x32Words.push(x64Word.low);
}
return X32WordArray.create(x32Words, this.sigBytes);
},
/**
* Creates a copy of this word array.
*
* @return {X64WordArray} The clone.
*
* @example
*
* var clone = x64WordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this); // Clone "words" array
var words = clone.words = this.words.slice(0); // Clone each X64Word object
var wordsLength = words.length;
for (var i = 0; i < wordsLength; i++) {
words[i] = words[i].clone();
}
return clone;
}
});
})();
return CryptoJS;
});
})(x64Core$1, x64Core$1.exports);
return x64Core$1.exports;
}
var libTypedarrays$1 = {exports: {}};
var libTypedarrays = libTypedarrays$1.exports;
var hasRequiredLibTypedarrays;
function requireLibTypedarrays() {
if (hasRequiredLibTypedarrays) return libTypedarrays$1.exports;
hasRequiredLibTypedarrays = 1;
(function (module, exports) {
(function (root, factory) {
{
// CommonJS
module.exports = factory(requireCore());
}
})(libTypedarrays, function (CryptoJS) {
(function () {
// Check if typed arrays are supported
if (typeof ArrayBuffer != 'function') {
return;
} // Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray; // Reference original init
var superInit = WordArray.init; // Augment WordArray.init to handle typed arrays
var subInit = WordArray.init = function (typedArray) {
// Convert buffers to uint8
if (typedArray instanceof ArrayBuffer) {
typedArray = new Uint8Array(typedArray);
} // Convert other array views to uint8
if (typedArray instanceof Int8Array || typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray || typedArray instanceof Int16Array || typedArray instanceof Uint16Array || typedArray instanceof Int32Array || typedArray instanceof Uint32Array || typedArray instanceof Float32Array || typedArray instanceof Float64Array) {
typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
} // Handle Uint8Array
if (typedArray instanceof Uint8Array) {
// Shortcut
var typedArrayByteLength = typedArray.byteLength; // Extract bytes
var words = [];
for (var i = 0; i < typedArrayByteLength; i++) {
words[i >>> 2] |= typedArray[i] << 24 - i % 4 * 8;
} // Initialize this word array
superInit.call(this, words, typedArrayByteLength);
} else {
// Else call normal init
superInit.apply(this, arguments);
}
};
subInit.prototype = WordArray;
})();
return CryptoJS.lib.WordArray;
});
})(libTypedarrays$1, libTypedarrays$1.exports);
return libTypedarrays$1.exports;
}
var encUtf16$1 = {exports: {}};
var encUtf16 = encUtf16$1.exports;
var hasRequiredEncUtf16;
function requireEncUtf16() {
if (hasRequiredEncUtf16) return encUtf16$1.exports;
hasRequiredEncUtf16 = 1;
(function (module, exports) {
(function (root, factory) {
{
// CommonJS
module.exports = factory(requireCore());
}
})(encUtf16, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* UTF-16 BE encoding strategy.
*/
C_enc.Utf16 = C_enc.Utf16BE = {
/**
* Converts a word array to a UTF-16 BE string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-16 BE string.
*
* @static
*
* @example
*
* var utf16String = CryptoJS.enc.Utf16.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes; // Convert
var utf16Chars = [];
for (var i = 0; i < sigBytes; i += 2) {
var codePoint = words[i >>> 2] >>> 16 - i % 4 * 8 & 0xffff;
utf16Chars.push(String.fromCharCode(codePoint));
}
return utf16Chars.join('');
},
/**
* Converts a UTF-16 BE string to a word array.
*
* @param {string} utf16Str The UTF-16 BE string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf16.parse(utf16String);
*/
parse: function (utf16Str) {
//