From ff2457f7328a8146e80ef65b676c72ec030c2b0f Mon Sep 17 00:00:00 2001 From: JC Brand Date: Sat, 25 Feb 2017 21:34:18 +0000 Subject: [PATCH] New release 1.2.13 --- CHANGELOG.md | 2 +- Makefile | 25 +- package.json | 2 +- strophe.js | 1153 ++++++++++++++++++++++++++++++++---------------- strophe.min.js | 35 +- 5 files changed, 834 insertions(+), 383 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 32598a4d..4fbfecb6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Strophe.js Change Log -## Version 1.2.13 - Unreleased +## Version 1.2.13 - 2017-02-25 * Use almond to create the build. This means that the build itself is an AMD module and can be loaded via `require`. diff --git a/Makefile b/Makefile index 6d8de109..80e9a037 100644 --- a/Makefile +++ b/Makefile @@ -13,6 +13,8 @@ STROPHE = strophe.js STROPHE_MIN = strophe.min.js STROPHE_LIGHT = strophe-no-polyfill.js +all: doc $(STROPHE) $(STROPHE_MIN) + .PHONY: help help: @echo "Please use \`make ' where is one of the following:" @@ -21,8 +23,6 @@ help: @echo " serve Serve this directory via a webserver on port 8000." @echo " stamp-npm Install NPM dependencies and create the guard file stamp-npm which will prevent those dependencies from being installed again." -all: doc $(STROPHE_MIN) - stamp-npm: package.json npm install touch stamp-npm @@ -45,19 +45,26 @@ doc: @@echo .PHONY: release -release: $(STROPHE) $(STROPHE_MIN) $(STROPHE_LIGHT) +release: + sed -i 's/\"version\":\ \"[0-9]\+\.[0-9]\+\.[0-9]\+\"/\"version\":\ \"$(VERSION)\"/' package.json + sed -i "s/Unreleased/`date +%Y-%m-%d`/" CHANGELOG.md + make dist + make doc + +.PHONE: dist +dist: $(STROPHE) $(STROPHE_MIN) $(STROPHE_LIGHT) $(STROPHE_MIN): src node_modules Makefile - $(RJS) -o build.js insertRequire=strophe-polyfill include=strophe-polyfill out=strophe.min.js - sed -i s/@VERSION@/$(VERSION)/ strophe.min.js + $(RJS) -o build.js insertRequire=strophe-polyfill include=strophe-polyfill out=$(STROPHE_MIN) + sed -i s/@VERSION@/$(VERSION)/ $(STROPHE_MIN) $(STROPHE): src node_modules Makefile - $(RJS) -o build.js optimize=none insertRequire=strophe-polyfill include=strophe-polyfill out=strophe.js - sed -i s/@VERSION@/$(VERSION)/ strophe.js + $(RJS) -o build.js optimize=none insertRequire=strophe-polyfill include=strophe-polyfill out=$(STROPHE) + sed -i s/@VERSION@/$(VERSION)/ $(STROPHE) $(STROPHE_LIGHT): src node_modules Makefile - $(RJS) -o build.js optimize=none out=strophe.light.js - sed -i s/@VERSION@/$(VERSION)/ strophe.light.js + $(RJS) -o build.js optimize=none out=$(STROPHE_LIGHT) + sed -i s/@VERSION@/$(VERSION)/ $(STROPHE_LIGHT) .PHONY: jshint jshint: stamp-bower diff --git a/package.json b/package.json index 3bd1c7de..b83b22d7 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "strophe.js", "description": "Strophe.js is an XMPP library for JavaScript", - "version": "1.2.12", + "version": "1.2.13", "homepage": "http://strophe.im/strophejs", "repository": { "type": "git", diff --git a/strophe.js b/strophe.js index 7cb49e31..f7211798 100644 --- a/strophe.js +++ b/strophe.js @@ -17,97 +17,687 @@ */ /* jshint ignore:start */ -(function (callback) { -/* jshint ignore:end */ - -// This code was written by Tyler Akins and has been placed in the -// public domain. It would be nice if you left this header intact. -// Base64 code from Tyler Akins -- http://rumkin.com - (function (root, factory) { if (typeof define === 'function' && define.amd) { - define('strophe-base64', function () { - return factory(); - }); + //Allow using this built library as an AMD module + //in another project. That other project will only + //see this AMD call, not the internal modules in + //the closure below. + define([], factory); } else { - // Browser globals - root.Base64 = factory(); + //Browser globals case. + var wrapper = factory(); + root.Strophe = wrapper.Strophe; + root.$build = wrapper.$build; + root.$iq = wrapper.$iq; + root.$msg = wrapper.$msg; + root.$pres = wrapper.$pres; + root.SHA1 = wrapper.SHA1; + root.MD5 = wrapper.MD5; + root.b64_hmac_sha1 = wrapper.b64_hmac_sha1; + root.b64_sha1 = wrapper.b64_sha1; + root.str_hmac_sha1 = wrapper.str_hmac_sha1; + root.str_sha1 = wrapper.str_sha1; } }(this, function () { - var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + //almond, and your modules will be inlined here +/* jshint ignore:end */ +/** + * @license almond 0.3.3 Copyright jQuery Foundation and other contributors. + * Released under MIT license, http://github.com/requirejs/almond/LICENSE + */ +//Going sloppy to avoid 'use strict' string cost, but strict practices should +//be followed. +/*global setTimeout: false */ + +var requirejs, require, define; +(function (undef) { + var main, req, makeMap, handlers, + defined = {}, + waiting = {}, + config = {}, + defining = {}, + hasOwn = Object.prototype.hasOwnProperty, + aps = [].slice, + jsSuffixRegExp = /\.js$/; + + function hasProp(obj, prop) { + return hasOwn.call(obj, prop); + } - var obj = { - /** - * Encodes a string in base64 - * @param {String} input The string to encode in base64. - */ - encode: function (input) { - var output = ""; - var chr1, chr2, chr3; - var enc1, enc2, enc3, enc4; - var i = 0; - - do { - chr1 = input.charCodeAt(i++); - chr2 = input.charCodeAt(i++); - chr3 = input.charCodeAt(i++); - - enc1 = chr1 >> 2; - enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); - enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); - enc4 = chr3 & 63; - - if (isNaN(chr2)) { - enc2 = ((chr1 & 3) << 4); - enc3 = enc4 = 64; - } else if (isNaN(chr3)) { - enc4 = 64; + /** + * Given a relative module name, like ./something, normalize it to + * a real name that can be mapped to a path. + * @param {String} name the relative name + * @param {String} baseName a real name that the name arg is relative + * to. + * @returns {String} normalized name + */ + function normalize(name, baseName) { + var nameParts, nameSegment, mapValue, foundMap, lastIndex, + foundI, foundStarMap, starI, i, j, part, normalizedBaseParts, + baseParts = baseName && baseName.split("/"), + map = config.map, + starMap = (map && map['*']) || {}; + + //Adjust any relative paths. + if (name) { + name = name.split('/'); + lastIndex = name.length - 1; + + // If wanting node ID compatibility, strip .js from end + // of IDs. Have to do this here, and not in nameToUrl + // because node allows either .js or non .js to map + // to same file. + if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) { + name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, ''); + } + + // Starts with a '.' so need the baseName + if (name[0].charAt(0) === '.' && baseParts) { + //Convert baseName to array, and lop off the last part, + //so that . matches that 'directory' and not name of the baseName's + //module. For instance, baseName of 'one/two/three', maps to + //'one/two/three.js', but we want the directory, 'one/two' for + //this normalization. + normalizedBaseParts = baseParts.slice(0, baseParts.length - 1); + name = normalizedBaseParts.concat(name); + } + + //start trimDots + for (i = 0; i < name.length; i++) { + part = name[i]; + if (part === '.') { + name.splice(i, 1); + i -= 1; + } else if (part === '..') { + // If at the start, or previous value is still .., + // keep them so that when converted to a path it may + // still work when converted to a path, even though + // as an ID it is less than ideal. In larger point + // releases, may be better to just kick out an error. + if (i === 0 || (i === 1 && name[2] === '..') || name[i - 1] === '..') { + continue; + } else if (i > 0) { + name.splice(i - 1, 2); + i -= 2; + } } + } + //end trimDots - output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + - keyStr.charAt(enc3) + keyStr.charAt(enc4); - } while (i < input.length); + name = name.join('/'); + } - return output; - }, + //Apply map config if available. + if ((baseParts || starMap) && map) { + nameParts = name.split('/'); - /** - * Decodes a base64 string. - * @param {String} input The string to decode. - */ - decode: function (input) { - var output = ""; - var chr1, chr2, chr3; - var enc1, enc2, enc3, enc4; - var i = 0; + for (i = nameParts.length; i > 0; i -= 1) { + nameSegment = nameParts.slice(0, i).join("/"); + + if (baseParts) { + //Find the longest baseName segment match in the config. + //So, do joins on the biggest to smallest lengths of baseParts. + for (j = baseParts.length; j > 0; j -= 1) { + mapValue = map[baseParts.slice(0, j).join('/')]; + + //baseName segment has config, find if it has one for + //this name. + if (mapValue) { + mapValue = mapValue[nameSegment]; + if (mapValue) { + //Match, update name to the new value. + foundMap = mapValue; + foundI = i; + break; + } + } + } + } + + if (foundMap) { + break; + } + + //Check for a star map match, but just hold on to it, + //if there is a shorter segment match later in a matching + //config, then favor over this star map. + if (!foundStarMap && starMap && starMap[nameSegment]) { + foundStarMap = starMap[nameSegment]; + starI = i; + } + } + + if (!foundMap && foundStarMap) { + foundMap = foundStarMap; + foundI = starI; + } + + if (foundMap) { + nameParts.splice(0, foundI, foundMap); + name = nameParts.join('/'); + } + } + + return name; + } + + function makeRequire(relName, forceSync) { + return function () { + //A version of a require function that passes a moduleName + //value for items that may need to + //look up paths relative to the moduleName + var args = aps.call(arguments, 0); + + //If first arg is not require('string'), and there is only + //one arg, it is the array form without a callback. Insert + //a null so that the following concat is correct. + if (typeof args[0] !== 'string' && args.length === 1) { + args.push(null); + } + return req.apply(undef, args.concat([relName, forceSync])); + }; + } + + function makeNormalize(relName) { + return function (name) { + return normalize(name, relName); + }; + } + + function makeLoad(depName) { + return function (value) { + defined[depName] = value; + }; + } + + function callDep(name) { + if (hasProp(waiting, name)) { + var args = waiting[name]; + delete waiting[name]; + defining[name] = true; + main.apply(undef, args); + } + + if (!hasProp(defined, name) && !hasProp(defining, name)) { + throw new Error('No ' + name); + } + return defined[name]; + } + + //Turns a plugin!resource to [plugin, resource] + //with the plugin being undefined if the name + //did not have a plugin prefix. + function splitPrefix(name) { + var prefix, + index = name ? name.indexOf('!') : -1; + if (index > -1) { + prefix = name.substring(0, index); + name = name.substring(index + 1, name.length); + } + return [prefix, name]; + } + + //Creates a parts array for a relName where first part is plugin ID, + //second part is resource ID. Assumes relName has already been normalized. + function makeRelParts(relName) { + return relName ? splitPrefix(relName) : []; + } - // remove all characters that are not A-Z, a-z, 0-9, +, /, or = - input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); + /** + * Makes a name map, normalizing the name, and using a plugin + * for normalization if necessary. Grabs a ref to plugin + * too, as an optimization. + */ + makeMap = function (name, relParts) { + var plugin, + parts = splitPrefix(name), + prefix = parts[0], + relResourceName = relParts[1]; + + name = parts[1]; + + if (prefix) { + prefix = normalize(prefix, relResourceName); + plugin = callDep(prefix); + } - do { - enc1 = keyStr.indexOf(input.charAt(i++)); - enc2 = keyStr.indexOf(input.charAt(i++)); - enc3 = keyStr.indexOf(input.charAt(i++)); - enc4 = keyStr.indexOf(input.charAt(i++)); + //Normalize according + if (prefix) { + if (plugin && plugin.normalize) { + name = plugin.normalize(name, makeNormalize(relResourceName)); + } else { + name = normalize(name, relResourceName); + } + } else { + name = normalize(name, relResourceName); + parts = splitPrefix(name); + prefix = parts[0]; + name = parts[1]; + if (prefix) { + plugin = callDep(prefix); + } + } - chr1 = (enc1 << 2) | (enc2 >> 4); - chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); - chr3 = ((enc3 & 3) << 6) | enc4; + //Using ridiculous property names for space reasons + return { + f: prefix ? prefix + '!' + name : name, //fullName + n: name, + pr: prefix, + p: plugin + }; + }; - output = output + String.fromCharCode(chr1); + function makeConfig(name) { + return function () { + return (config && config.config && config.config[name]) || {}; + }; + } - if (enc3 != 64) { - output = output + String.fromCharCode(chr2); + handlers = { + require: function (name) { + return makeRequire(name); + }, + exports: function (name) { + var e = defined[name]; + if (typeof e !== 'undefined') { + return e; + } else { + return (defined[name] = {}); + } + }, + module: function (name) { + return { + id: name, + uri: '', + exports: defined[name], + config: makeConfig(name) + }; + } + }; + + main = function (name, deps, callback, relName) { + var cjsModule, depName, ret, map, i, relParts, + args = [], + callbackType = typeof callback, + usingExports; + + //Use name if no relName + relName = relName || name; + relParts = makeRelParts(relName); + + //Call the callback to define the module, if necessary. + if (callbackType === 'undefined' || callbackType === 'function') { + //Pull out the defined dependencies and pass the ordered + //values to the callback. + //Default to [require, exports, module] if no deps + deps = !deps.length && callback.length ? ['require', 'exports', 'module'] : deps; + for (i = 0; i < deps.length; i += 1) { + map = makeMap(deps[i], relParts); + depName = map.f; + + //Fast path CommonJS standard dependencies. + if (depName === "require") { + args[i] = handlers.require(name); + } else if (depName === "exports") { + //CommonJS module spec 1.1 + args[i] = handlers.exports(name); + usingExports = true; + } else if (depName === "module") { + //CommonJS module spec 1.1 + cjsModule = args[i] = handlers.module(name); + } else if (hasProp(defined, depName) || + hasProp(waiting, depName) || + hasProp(defining, depName)) { + args[i] = callDep(depName); + } else if (map.p) { + map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {}); + args[i] = defined[depName]; + } else { + throw new Error(name + ' missing ' + depName); } - if (enc4 != 64) { - output = output + String.fromCharCode(chr3); + } + + ret = callback ? callback.apply(defined[name], args) : undefined; + + if (name) { + //If setting exports via "module" is in play, + //favor that over return value and exports. After that, + //favor a non-undefined return value over exports use. + if (cjsModule && cjsModule.exports !== undef && + cjsModule.exports !== defined[name]) { + defined[name] = cjsModule.exports; + } else if (ret !== undef || !usingExports) { + //Use the return value from the function. + defined[name] = ret; } - } while (i < input.length); + } + } else if (name) { + //May just be an object definition for the module. Only + //worry about defining if have a module name. + defined[name] = callback; + } + }; - return output; + requirejs = require = req = function (deps, callback, relName, forceSync, alt) { + if (typeof deps === "string") { + if (handlers[deps]) { + //callback in this case is really relName + return handlers[deps](callback); + } + //Just return the module wanted. In this scenario, the + //deps arg is the module name, and second arg (if passed) + //is just the relName. + //Normalize module name, if it contains . or .. + return callDep(makeMap(deps, makeRelParts(callback)).f); + } else if (!deps.splice) { + //deps is a config object, not an array. + config = deps; + if (config.deps) { + req(config.deps, config.callback); + } + if (!callback) { + return; + } + + if (callback.splice) { + //callback is an array, which means it is a dependency list. + //Adjust args if there are dependencies + deps = callback; + callback = relName; + relName = null; + } else { + deps = undef; + } } + + //Support require(['a']) + callback = callback || function () {}; + + //If relName is a function, it is an errback handler, + //so remove it. + if (typeof relName === 'function') { + relName = forceSync; + forceSync = alt; + } + + //Simulate async callback; + if (forceSync) { + main(undef, deps, callback, relName); + } else { + //Using a non-zero value because of concern for what old browsers + //do, and latest browsers "upgrade" to 4 if lower value is used: + //http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout: + //If want a value immediately, use require('id') instead -- something + //that works in almond on the global level, but not guaranteed and + //unlikely to work in other AMD implementations. + setTimeout(function () { + main(undef, deps, callback, relName); + }, 4); + } + + return req; }; - return obj; + + /** + * Just drops the config on the floor, but returns req in case + * the config return value is used. + */ + req.config = function (cfg) { + return req(cfg); + }; + + /** + * Expose module registry for debugging and tooling + */ + requirejs._defined = defined; + + define = function (name, deps, callback) { + if (typeof name !== 'string') { + throw new Error('See almond README: incorrect module build, no module name'); + } + + //This module may not have dependencies + if (!deps.splice) { + //deps is not an array, so probably means + //an object literal or factory function for + //the value. Adjust args. + callback = deps; + deps = []; + } + + if (!hasProp(defined, name) && !hasProp(waiting, name)) { + waiting[name] = [name, deps, callback]; + } + }; + + define.amd = { + jQuery: true + }; +}()); + +define("bower_components/almond/almond.js", function(){}); + +/* + This program is distributed under the terms of the MIT license. + Please see the LICENSE file for details. + + Copyright 2006-2008, OGG, LLC +*/ +/* jshint undef: true, unused: true:, noarg: true, latedef: true */ +/* global define */ + +(function (root, factory) { + if (typeof define === 'function' && define.amd) { + define('strophe-polyfill',[], function () { + return factory(root); + }); + } else { + // Browser globals + return factory(root); + } +}(this, function (root) { + +/** Function: Function.prototype.bind + * Bind a function to an instance. + * + * This Function object extension method creates a bound method similar + * to those in Python. This means that the 'this' object will point + * to the instance you want. See + * and + * for a complete explanation. + * + * This extension already exists in some browsers (namely, Firefox 3), but + * we provide it to support those that don't. + * + * Parameters: + * (Object) obj - The object that will become 'this' in the bound function. + * (Object) argN - An option argument that will be prepended to the + * arguments given for the function call + * + * Returns: + * The bound function. + */ +if (!Function.prototype.bind) { + Function.prototype.bind = function (obj /*, arg1, arg2, ... */) { + var func = this; + var _slice = Array.prototype.slice; + var _concat = Array.prototype.concat; + var _args = _slice.call(arguments, 1); + return function () { + return func.apply(obj ? obj : this, _concat.call(_args, _slice.call(arguments, 0))); + }; + }; +} + +/** Function: Array.isArray + * This is a polyfill for the ES5 Array.isArray method. + */ +if (!Array.isArray) { + Array.isArray = function(arg) { + return Object.prototype.toString.call(arg) === '[object Array]'; + }; +} + +/** Function: Array.prototype.indexOf + * Return the index of an object in an array. + * + * This function is not supplied by some JavaScript implementations, so + * we provide it if it is missing. This code is from: + * http://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Objects:Array:indexOf + * + * Parameters: + * (Object) elt - The object to look for. + * (Integer) from - The index from which to start looking. (optional). + * + * Returns: + * The index of elt in the array or -1 if not found. + */ +if (!Array.prototype.indexOf) { + Array.prototype.indexOf = function(elt /*, from*/) { + var len = this.length; + var from = Number(arguments[1]) || 0; + from = (from < 0) ? Math.ceil(from) : Math.floor(from); + if (from < 0) { + from += len; + } + + for (; from < len; from++) { + if (from in this && this[from] === elt) { + return from; + } + } + return -1; + }; +} + +/** Function: Array.prototype.forEach + * + * This function is not available in IE < 9 + * + * See + */ +if (!Array.prototype.forEach) { + Array.prototype.forEach = function(callback, thisArg) { + var T, k; + if (this === null) { + throw new TypeError(' this is null or not defined'); + } + // 1. Let O be the result of calling toObject() passing the + // |this| value as the argument. + var O = Object(this); + // 2. Let lenValue be the result of calling the Get() internal + // method of O with the argument "length". + // 3. Let len be toUint32(lenValue). + var len = O.length >>> 0; + // 4. If isCallable(callback) is false, throw a TypeError exception. + // See: http://es5.github.com/#x9.11 + if (typeof callback !== "function") { + throw new TypeError(callback + ' is not a function'); + } + // 5. If thisArg was supplied, let T be thisArg; else let + // T be undefined. + if (arguments.length > 1) { + T = thisArg; + } + // 6. Let k be 0 + k = 0; + // 7. Repeat, while k < len + while (k < len) { + var kValue; + // a. Let Pk be ToString(k). + // This is implicit for LHS operands of the in operator + // b. Let kPresent be the result of calling the HasProperty + // internal method of O with argument Pk. + // This step can be combined with c + // c. If kPresent is true, then + if (k in O) { + // i. Let kValue be the result of calling the Get internal + // method of O with argument Pk. + kValue = O[k]; + // ii. Call the Call internal method of callback with T as + // the this value and argument list containing kValue, k, and O. + callback.call(T, kValue, k, O); + } + // d. Increase k by 1. + k++; + } + // 8. return undefined + }; +} + +// This code was written by Tyler Akins and has been placed in the +// public domain. It would be nice if you left this header intact. +// Base64 code from Tyler Akins -- http://rumkin.com +var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; +if (!root.btoa) { + root.btoa = function (input) { + /** + * Encodes a string in base64 + * @param {String} input The string to encode in base64. + */ + var output = ""; + var chr1, chr2, chr3; + var enc1, enc2, enc3, enc4; + var i = 0; + do { + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc2 = ((chr1 & 3) << 4); + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + + keyStr.charAt(enc3) + keyStr.charAt(enc4); + } while (i < input.length); + return output; + }; +} + +if (!root.atob) { + root.atob = function (input) { + /** + * Decodes a base64 string. + * @param {String} input The string to decode. + */ + var output = ""; + var chr1, chr2, chr3; + var enc1, enc2, enc3, enc4; + var i = 0; + // remove all characters that are not A-Z, a-z, 0-9, +, /, or = + input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); + do { + enc1 = keyStr.indexOf(input.charAt(i++)); + enc2 = keyStr.indexOf(input.charAt(i++)); + enc3 = keyStr.indexOf(input.charAt(i++)); + enc4 = keyStr.indexOf(input.charAt(i++)); + + chr1 = (enc1 << 2) | (enc2 >> 4); + chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); + chr3 = ((enc3 & 3) << 6) | enc4; + + output = output + String.fromCharCode(chr1); + + if (enc3 !== 64) { + output = output + String.fromCharCode(chr2); + } + if (enc4 !== 64) { + output = output + String.fromCharCode(chr3); + } + } while (i < input.length); + return output; + }; +} })); /* @@ -126,7 +716,7 @@ (function (root, factory) { if (typeof define === 'function' && define.amd) { - define('strophe-sha1', function () { + define('strophe-sha1', [],function () { return factory(); }); } else { @@ -314,21 +904,20 @@ return { * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. */ - /* * Everything that isn't used by Strophe has been stripped here! */ (function (root, factory) { if (typeof define === 'function' && define.amd) { - define('strophe-md5', function () { + define('strophe-md5',[], function () { return factory(); }); } else { // Browser globals root.MD5 = factory(); } -}(this, function (b) { +}(this, function () { /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. @@ -523,7 +1112,7 @@ return { (function (root, factory) { if (typeof define === 'function' && define.amd) { - define('strophe-utils', function () { + define('strophe-utils',[], function () { return factory(); }); } else { @@ -580,7 +1169,7 @@ return { domain = ''; path = ''; cookieObj = cookies[cookieName]; - isObj = typeof cookieObj == "object"; + isObj = typeof cookieObj === "object"; cookieValue = escape(unescape(isObj ? cookieObj.value : cookieObj)); if (isObj) { expires = cookieObj.expires ? ";expires="+cookieObj.expires : ''; @@ -603,188 +1192,33 @@ return { */ /* jshint undef: true, unused: true:, noarg: true, latedef: true */ -/* global define */ +/*global define, document, sessionStorage, setTimeout, clearTimeout, ActiveXObject, DOMParser, btoa, atob */ (function (root, factory) { if (typeof define === 'function' && define.amd) { - define('strophe-polyfill', [], function () { - return factory(); - }); - } else { - // Browser globals - return factory(); - } -}(this, function () { - -/** Function: Function.prototype.bind - * Bind a function to an instance. - * - * This Function object extension method creates a bound method similar - * to those in Python. This means that the 'this' object will point - * to the instance you want. See - * and - * for a complete explanation. - * - * This extension already exists in some browsers (namely, Firefox 3), but - * we provide it to support those that don't. - * - * Parameters: - * (Object) obj - The object that will become 'this' in the bound function. - * (Object) argN - An option argument that will be prepended to the - * arguments given for the function call - * - * Returns: - * The bound function. - */ -if (!Function.prototype.bind) { - Function.prototype.bind = function (obj /*, arg1, arg2, ... */) { - var func = this; - var _slice = Array.prototype.slice; - var _concat = Array.prototype.concat; - var _args = _slice.call(arguments, 1); - return function () { - return func.apply(obj ? obj : this, _concat.call(_args, _slice.call(arguments, 0))); - }; - }; -} - -/** Function: Array.isArray - * This is a polyfill for the ES5 Array.isArray method. - */ -if (!Array.isArray) { - Array.isArray = function(arg) { - return Object.prototype.toString.call(arg) === '[object Array]'; - }; -} - -/** Function: Array.prototype.indexOf - * Return the index of an object in an array. - * - * This function is not supplied by some JavaScript implementations, so - * we provide it if it is missing. This code is from: - * http://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Objects:Array:indexOf - * - * Parameters: - * (Object) elt - The object to look for. - * (Integer) from - The index from which to start looking. (optional). - * - * Returns: - * The index of elt in the array or -1 if not found. - */ -if (!Array.prototype.indexOf) { - Array.prototype.indexOf = function(elt /*, from*/) { - var len = this.length; - var from = Number(arguments[1]) || 0; - from = (from < 0) ? Math.ceil(from) : Math.floor(from); - if (from < 0) { - from += len; - } - - for (; from < len; from++) { - if (from in this && this[from] === elt) { - return from; - } - } - return -1; - }; - } -})); - - -/** Function: Array.prototype.forEach - * - * This function is not available in IE < 9 - * - * See - */ -if (!Array.prototype.forEach) { - Array.prototype.forEach = function(callback, thisArg) { - var T, k; - if (this === null) { - throw new TypeError(' this is null or not defined'); - } - - // 1. Let O be the result of calling toObject() passing the - // |this| value as the argument. - var O = Object(this); - // 2. Let lenValue be the result of calling the Get() internal - // method of O with the argument "length". - // 3. Let len be toUint32(lenValue). - var len = O.length >>> 0; - // 4. If isCallable(callback) is false, throw a TypeError exception. - // See: http://es5.github.com/#x9.11 - if (typeof callback !== "function") { - throw new TypeError(callback + ' is not a function'); - } - // 5. If thisArg was supplied, let T be thisArg; else let - // T be undefined. - if (arguments.length > 1) { - T = thisArg; - } - // 6. Let k be 0 - k = 0; - // 7. Repeat, while k < len - while (k < len) { - var kValue; - // a. Let Pk be ToString(k). - // This is implicit for LHS operands of the in operator - // b. Let kPresent be the result of calling the HasProperty - // internal method of O with argument Pk. - // This step can be combined with c - // c. If kPresent is true, then - if (k in O) { - // i. Let kValue be the result of calling the Get internal - // method of O with argument Pk. - kValue = O[k]; - // ii. Call the Call internal method of callback with T as - // the this value and argument list containing kValue, k, and O. - callback.call(T, kValue, k, O); - } - // d. Increase k by 1. - k++; - } - // 8. return undefined - }; -} - -/* - This program is distributed under the terms of the MIT license. - Please see the LICENSE file for details. - - Copyright 2006-2008, OGG, LLC -*/ - -/* jshint undef: true, unused: true:, noarg: true, latedef: true */ -/*global define, document, window, setTimeout, clearTimeout, ActiveXObject, DOMParser */ - -(function (root, factory) { - if (typeof define === 'function' && define.amd) { - define('strophe-core', [ + define('strophe-core',[ 'strophe-sha1', - 'strophe-base64', 'strophe-md5', - 'strophe-utils', - "strophe-polyfill" + 'strophe-utils' ], function () { return factory.apply(this, arguments); }); } else { // Browser globals - var o = factory(root.SHA1, root.Base64, root.MD5, root.stropheUtils); - window.Strophe = o.Strophe; - window.$build = o.$build; - window.$iq = o.$iq; - window.$msg = o.$msg; - window.$pres = o.$pres; - window.SHA1 = o.SHA1; - window.Base64 = o.Base64; - window.MD5 = o.MD5; - window.b64_hmac_sha1 = o.SHA1.b64_hmac_sha1; - window.b64_sha1 = o.SHA1.b64_sha1; - window.str_hmac_sha1 = o.SHA1.str_hmac_sha1; - window.str_sha1 = o.SHA1.str_sha1; + var o = factory(root.SHA1, root.MD5, root.stropheUtils); + root.Strophe = o.Strophe; + root.$build = o.$build; + root.$iq = o.$iq; + root.$msg = o.$msg; + root.$pres = o.$pres; + root.SHA1 = o.SHA1; + root.MD5 = o.MD5; + root.b64_hmac_sha1 = o.SHA1.b64_hmac_sha1; + root.b64_sha1 = o.SHA1.b64_sha1; + root.str_hmac_sha1 = o.SHA1.str_hmac_sha1; + root.str_sha1 = o.SHA1.str_sha1; } -}(this, function (SHA1, Base64, MD5, utils) { +}(this, function (SHA1, MD5, utils) { var Strophe; @@ -842,11 +1276,8 @@ function $pres(attrs) { return new Strophe.Builder("presence", attrs); } * provide a namespace for library objects, constants, and functions. */ Strophe = { - /** Constant: VERSION - * The version of the Strophe library. Unreleased builds will have - * a version of head-HASH where HASH is a partial revision. - */ - VERSION: "1.2.12", + /** Constant: VERSION */ + VERSION: "1.2.13", /** Constants: XMPP Namespace Constants * Common namespace constants from the XMPP RFCs and XEPs. @@ -921,7 +1352,7 @@ Strophe = { */ validTag: function(tag) { for (var i = 0; i < Strophe.XHTML.tags.length; i++) { - if (tag == Strophe.XHTML.tags[i]) { + if (tag === Strophe.XHTML.tags[i]) { return true; } } @@ -937,7 +1368,7 @@ Strophe = { validAttribute: function(tag, attribute) { if (typeof Strophe.XHTML.attributes[tag] !== 'undefined' && Strophe.XHTML.attributes[tag].length > 0) { for (var i = 0; i < Strophe.XHTML.attributes[tag].length; i++) { - if (attribute == Strophe.XHTML.attributes[tag][i]) { + if (attribute === Strophe.XHTML.attributes[tag][i]) { return true; } } @@ -946,7 +1377,7 @@ Strophe = { }, validCSS: function(style) { for (var i = 0; i < Strophe.XHTML.css.length; i++) { - if (style == Strophe.XHTML.css[i]) { + if (style === Strophe.XHTML.css[i]) { return true; } } @@ -1065,7 +1496,7 @@ Strophe = { var i, childNode; for (i = 0; i < elem.childNodes.length; i++) { childNode = elem.childNodes[i]; - if (childNode.nodeType == Strophe.ElementType.NORMAL && + if (childNode.nodeType === Strophe.ElementType.NORMAL && (!elemName || this.isTagEqual(childNode, elemName))) { func(childNode); } @@ -1086,7 +1517,7 @@ Strophe = { * otherwise. */ isTagEqual: function (el, name) { - return el.tagName == name; + return el.tagName === name; }, /** PrivateVariable: _xmlGenerator @@ -1190,21 +1621,21 @@ Strophe = { for (a = 1; a < arguments.length; a++) { var arg = arguments[a]; if (!arg) { continue; } - if (typeof(arg) == "string" || - typeof(arg) == "number") { + if (typeof(arg) === "string" || + typeof(arg) === "number") { node.appendChild(Strophe.xmlTextNode(arg)); - } else if (typeof(arg) == "object" && - typeof(arg.sort) == "function") { + } else if (typeof(arg) === "object" && + typeof(arg.sort) === "function") { for (i = 0; i < arg.length; i++) { var attr = arg[i]; - if (typeof(attr) == "object" && - typeof(attr.sort) == "function" && + if (typeof(attr) === "object" && + typeof(attr.sort) === "function" && attr[1] !== undefined && attr[1] !== null) { node.setAttribute(attr[0], attr[1]); } } - } else if (typeof(arg) == "object") { + } else if (typeof(arg) === "object") { for (k in arg) { if (arg.hasOwnProperty(k)) { if (arg[k] !== undefined && @@ -1282,7 +1713,7 @@ Strophe = { xmlHtmlNode: function (html) { var node; //ensure text is escaped - if (window.DOMParser) { + if (DOMParser) { var parser = new DOMParser(); node = parser.parseFromString(html, "text/xml"); } else { @@ -1306,13 +1737,12 @@ Strophe = { if (!elem) { return null; } var str = ""; - if (elem.childNodes.length === 0 && elem.nodeType == - Strophe.ElementType.TEXT) { + if (elem.childNodes.length === 0 && elem.nodeType === Strophe.ElementType.TEXT) { str += elem.nodeValue; } for (var i = 0; i < elem.childNodes.length; i++) { - if (elem.childNodes[i].nodeType == Strophe.ElementType.TEXT) { + if (elem.childNodes[i].nodeType === Strophe.ElementType.TEXT) { str += elem.childNodes[i].nodeValue; } } @@ -1334,7 +1764,7 @@ Strophe = { */ copyElement: function (elem) { var i, el; - if (elem.nodeType == Strophe.ElementType.NORMAL) { + if (elem.nodeType === Strophe.ElementType.NORMAL) { el = Strophe.xmlElement(elem.tagName); for (i = 0; i < elem.attributes.length; i++) { @@ -1345,7 +1775,7 @@ Strophe = { for (i = 0; i < elem.childNodes.length; i++) { el.appendChild(Strophe.copyElement(elem.childNodes[i])); } - } else if (elem.nodeType == Strophe.ElementType.TEXT) { + } else if (elem.nodeType === Strophe.ElementType.TEXT) { el = Strophe.xmlGenerator().createTextNode(elem.nodeValue); } return el; @@ -1366,7 +1796,7 @@ Strophe = { */ createHtml: function (elem) { var i, el, j, tag, attribute, value, css, cssAttrs, attr, cssName, cssValue; - if (elem.nodeType == Strophe.ElementType.NORMAL) { + if (elem.nodeType === Strophe.ElementType.NORMAL) { tag = elem.nodeName.toLowerCase(); // XHTML tags must be lower case. if(Strophe.XHTML.validTag(tag)) { try { @@ -1374,16 +1804,16 @@ Strophe = { for(i = 0; i < Strophe.XHTML.attributes[tag].length; i++) { attribute = Strophe.XHTML.attributes[tag][i]; value = elem.getAttribute(attribute); - if(typeof value == 'undefined' || value === null || value === '' || value === false || value === 0) { + if(typeof value === 'undefined' || value === null || value === '' || value === false || value === 0) { continue; } - if(attribute == 'style' && typeof value == 'object') { - if(typeof value.cssText != 'undefined') { + if(attribute === 'style' && typeof value === 'object') { + if(typeof value.cssText !== 'undefined') { value = value.cssText; // we're dealing with IE, need to get CSS out } } // filter out invalid css styles - if(attribute == 'style') { + if(attribute === 'style') { css = []; cssAttrs = value.split(';'); for(j = 0; j < cssAttrs.length; j++) { @@ -1415,12 +1845,12 @@ Strophe = { el.appendChild(Strophe.createHtml(elem.childNodes[i])); } } - } else if (elem.nodeType == Strophe.ElementType.FRAGMENT) { + } else if (elem.nodeType === Strophe.ElementType.FRAGMENT) { el = Strophe.xmlGenerator().createDocumentFragment(); for (i = 0; i < elem.childNodes.length; i++) { el.appendChild(Strophe.createHtml(elem.childNodes[i])); } - } else if (elem.nodeType == Strophe.ElementType.TEXT) { + } else if (elem.nodeType === Strophe.ElementType.TEXT) { el = Strophe.xmlTextNode(elem.nodeValue); } return el; @@ -1667,7 +2097,7 @@ Strophe = { result = "<" + nodeName; for (i = 0; i < elem.attributes.length; i++) { - if(elem.attributes[i].nodeName != "_realname") { + if(elem.attributes[i].nodeName !== "_realname") { result += " " + elem.attributes[i].nodeName + "='" + Strophe.xmlescape(elem.attributes[i].value) + "'"; } @@ -1767,7 +2197,7 @@ Strophe = { */ Strophe.Builder = function (name, attrs) { // Set correct namespace for jabber:client elements - if (name == "presence" || name == "message" || name == "iq") { + if (name === "presence" || name === "message" || name === "iq") { if (attrs && !attrs.xmlns) { attrs.xmlns = Strophe.NS.CLIENT; } else if (!attrs) { @@ -2079,9 +2509,9 @@ Strophe.Handler.prototype = { var elem_type = elem.getAttribute("type"); if (this.namespaceMatch(elem) && (!this.name || Strophe.isTagEqual(elem, this.name)) && - (!this.type || (Array.isArray(this.type) ? this.type.indexOf(elem_type) != -1 : elem_type == this.type)) && - (!this.id || elem.getAttribute("id") == this.id) && - (!this.from || from == this.from)) { + (!this.type || (Array.isArray(this.type) ? this.type.indexOf(elem_type) !== -1 : elem_type === this.type)) && + (!this.id || elem.getAttribute("id") === this.id) && + (!this.from || from === this.from)) { return true; } return false; @@ -2484,10 +2914,10 @@ Strophe.Connection.prototype = { getUniqueId: function(suffix) { var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random() * 16 | 0, - v = c == 'x' ? r : r & 0x3 | 0x8; + v = c === 'x' ? r : r & 0x3 | 0x8; return v.toString(16); }); - if (typeof(suffix) == "string" || typeof(suffix) == "number") { + if (typeof(suffix) === "string" || typeof(suffix) === "number") { return uuid + ":" + suffix; } else { return uuid + ""; @@ -2677,8 +3107,8 @@ Strophe.Connection.prototype = { if (this._proto instanceof Strophe.Bosh) { if (!JSON) { return false; } try { - window.sessionStorage.setItem('_strophe_', '_strophe_'); - window.sessionStorage.removeItem('_strophe_'); + sessionStorage.setItem('_strophe_', '_strophe_'); + sessionStorage.removeItem('_strophe_'); } catch (e) { return false; } @@ -2865,7 +3295,7 @@ Strophe.Connection.prototype = { that.deleteTimedHandler(timeoutHandler); } var type = stanza.getAttribute('type'); - if (type == 'error') { + if (type === 'error') { if (errback) { errback(stanza); } @@ -2924,11 +3354,11 @@ Strophe.Connection.prototype = { that.deleteTimedHandler(timeoutHandler); } var iqtype = stanza.getAttribute('type'); - if (iqtype == 'result') { + if (iqtype === 'result') { if (callback) { callback(stanza); } - } else if (iqtype == 'error') { + } else if (iqtype === 'error') { if (errback) { errback(stanza); } @@ -3239,7 +3669,7 @@ Strophe.Connection.prototype = { * connection and alerts the user's connection callback. */ _doDisconnect: function (condition) { - if (typeof this._idleTimeout == "number") { + if (typeof this._idleTimeout === "number") { clearTimeout(this._idleTimeout); } @@ -3324,7 +3754,7 @@ Strophe.Connection.prototype = { var type = elem.getAttribute("type"); var cond, conflict; - if (type !== null && type == "terminate") { + if (type !== null && type === "terminate") { // Don't process stanzas that come in after disconnect if (this.disconnecting) { return; @@ -3334,7 +3764,7 @@ Strophe.Connection.prototype = { cond = elem.getAttribute("condition"); conflict = elem.getElementsByTagName("conflict"); if (cond !== null) { - if (cond == "remote-stream-error" && conflict.length > 0) { + if (cond === "remote-stream-error" && conflict.length > 0) { cond = "conflict"; } this._changeConnectStatus(Strophe.Status.CONNFAIL, cond); @@ -3403,7 +3833,7 @@ Strophe.Connection.prototype = { try { bodyWrap = this._proto._reqToData(req); } catch (e) { - if (e != "badformat") { throw e; } + if (e !== "badformat") { throw e; } this._changeConnectStatus(Strophe.Status.CONNFAIL, 'bad-format'); this._doDisconnect('bad-format'); } @@ -3482,7 +3912,7 @@ Strophe.Connection.prototype = { higher = j; } } - if (higher != i) { + if (higher !== i) { swap = mechanisms[i]; mechanisms[i] = mechanisms[higher]; mechanisms[higher] = swap; @@ -3530,7 +3960,7 @@ Strophe.Connection.prototype = { }); if (this._sasl_mechanism.isClientFirst) { var response = this._sasl_mechanism.onChallenge(this, null); - request_auth_exchange.t(Base64.encode(response)); + request_auth_exchange.t(btoa(response)); } this.send(request_auth_exchange.tree()); mechanism_found = true; @@ -3594,13 +4024,13 @@ Strophe.Connection.prototype = { * */ _sasl_challenge_cb: function(elem) { - var challenge = Base64.decode(Strophe.getText(elem)); + var challenge = atob(Strophe.getText(elem)); var response = this._sasl_mechanism.onChallenge(this, challenge); var stanza = $build('response', { 'xmlns': Strophe.NS.SASL }); if (response !== "") { - stanza.t(Base64.encode(response)); + stanza.t(btoa(response)); } this.send(stanza.tree()); return true; @@ -3656,14 +4086,14 @@ Strophe.Connection.prototype = { _sasl_success_cb: function (elem) { if (this._sasl_data["server-signature"]) { var serverSignature; - var success = Base64.decode(Strophe.getText(elem)); + var success = atob(Strophe.getText(elem)); var attribMatch = /([a-z]+)=([^,]+)(,|$)/; var matches = success.match(attribMatch); - if (matches[1] == "v") { + if (matches[1] === "v") { serverSignature = matches[2]; } - if (serverSignature != this._sasl_data["server-signature"]) { + if (serverSignature !== this._sasl_data["server-signature"]) { // remove old handlers this.deleteHandler(this._sasl_failure_handler); this._sasl_failure_handler = null; @@ -3726,11 +4156,11 @@ Strophe.Connection.prototype = { var i, child; for (i = 0; i < elem.childNodes.length; i++) { child = elem.childNodes[i]; - if (child.nodeName == 'bind') { + if (child.nodeName === 'bind') { this.do_bind = true; } - if (child.nodeName == 'session') { + if (child.nodeName === 'session') { this.do_session = true; } } @@ -3766,7 +4196,7 @@ Strophe.Connection.prototype = { * false to remove the handler. */ _sasl_bind_cb: function (elem) { - if (elem.getAttribute("type") == "error") { + if (elem.getAttribute("type") === "error") { Strophe.info("SASL binding failed."); var conflict = elem.getElementsByTagName("conflict"), condition; if (conflict.length > 0) { @@ -3817,10 +4247,10 @@ Strophe.Connection.prototype = { * false to remove the handler. */ _sasl_session_cb: function (elem) { - if (elem.getAttribute("type") == "result") { + if (elem.getAttribute("type") === "result") { this.authenticated = true; this._changeConnectStatus(Strophe.Status.CONNECTED, null); - } else if (elem.getAttribute("type") == "error") { + } else if (elem.getAttribute("type") === "error") { Strophe.info("Session creation failed."); this._changeConnectStatus(Strophe.Status.AUTHFAIL, null); return false; @@ -3869,10 +4299,10 @@ Strophe.Connection.prototype = { * false to remove the handler. */ _auth2_cb: function (elem) { - if (elem.getAttribute("type") == "result") { + if (elem.getAttribute("type") === "result") { this.authenticated = true; this._changeConnectStatus(Strophe.Status.CONNECTED, null); - } else if (elem.getAttribute("type") == "error") { + } else if (elem.getAttribute("type") === "error") { this._changeConnectStatus(Strophe.Status.AUTHFAIL, null); this.disconnect('authentication failed'); } @@ -4003,12 +4433,12 @@ Strophe.Connection.prototype = { * * By default, all mechanisms are enabled and the priorities are * - * EXTERNAL - 60 - * OAUTHBEARER - 50 - * SCRAM-SHA1 - 40 - * DIGEST-MD5 - 30 - * PLAIN - 20 - * ANONYMOUS - 10 + * OAUTHBEARER - 60 + * SCRAM-SHA1 - 50 + * DIGEST-MD5 - 40 + * PLAIN - 30 + * ANONYMOUS - 20 + * EXTERNAL - 10 * * See: Strophe.Connection.addSupportedSASLMechanisms */ @@ -4091,7 +4521,7 @@ Strophe.SASLMechanism.prototype = { /** PrivateFunction: onChallenge * Called by protocol implementation on incoming challenge. If client is - * first (isClientFirst == true) challenge will be null on the first call. + * first (isClientFirst === true) challenge will be null on the first call. * * Parameters: * (Strophe.Connection) connection - Target Connection. @@ -4218,7 +4648,7 @@ Strophe.SASLSHA1.prototype.onChallenge = function(connection, challenge, test_cn responseText += "r=" + nonce; authMessage += responseText; - salt = Base64.decode(salt); + salt = atob(salt); salt += "\x00\x00\x00\x01"; pass = utils.utf16to8(connection.pass); @@ -4241,7 +4671,7 @@ Strophe.SASLSHA1.prototype.onChallenge = function(connection, challenge, test_cn clientKey[k] ^= clientSignature[k]; } - responseText += ",p=" + Base64.encode(SHA1.binb2str(clientKey)); + responseText += ",p=" + btoa(SHA1.binb2str(clientKey)); return responseText; }.bind(this); @@ -4378,14 +4808,17 @@ Strophe.SASLExternal.prototype.onChallenge = function(connection) { }; return { - Strophe: Strophe, - $build: $build, - $msg: $msg, - $iq: $iq, - $pres: $pres, - SHA1: SHA1, - Base64: Base64, - MD5: MD5, + 'Strophe': Strophe, + '$build': $build, + '$iq': $iq, + '$msg': $msg, + '$pres': $pres, + 'SHA1': SHA1, + 'MD5': MD5, + 'b64_hmac_sha1': SHA1.b64_hmac_sha1, + 'b64_sha1': SHA1.b64_sha1, + 'str_hmac_sha1': SHA1.str_hmac_sha1, + 'str_sha1': SHA1.str_sha1 }; })); @@ -4401,7 +4834,7 @@ return { (function (root, factory) { if (typeof define === 'function' && define.amd) { - define('strophe-bosh', ['strophe-core'], function (core) { + define('strophe-bosh',['strophe-core'], function (core) { return factory( core.Strophe, core.$build @@ -4476,7 +4909,7 @@ Strophe.Request.prototype = { var node = null; if (this.xhr.responseXML && this.xhr.responseXML.documentElement) { node = this.xhr.responseXML.documentElement; - if (node.tagName == "parsererror") { + if (node.tagName === "parsererror") { Strophe.error("invalid response received"); Strophe.error("responseText: " + this.xhr.responseText); Strophe.error("responseXML: " + @@ -4716,10 +5149,10 @@ Strophe.Bosh.prototype = { session.jid && ( typeof jid === "undefined" || jid === null || - Strophe.getBareJidFromJid(session.jid) == Strophe.getBareJidFromJid(jid) || + Strophe.getBareJidFromJid(session.jid) === Strophe.getBareJidFromJid(jid) || // If authcid is null, then it's an anonymous login, so // we compare only the domains: - ((Strophe.getNodeFromJid(jid) === null) && (Strophe.getDomainFromJid(session.jid) == jid)) + ((Strophe.getNodeFromJid(jid) === null) && (Strophe.getDomainFromJid(session.jid) === jid)) ) ) { this._conn.restored = true; @@ -4760,13 +5193,13 @@ Strophe.Bosh.prototype = { _connect_cb: function (bodyWrap) { var typ = bodyWrap.getAttribute("type"); var cond, conflict; - if (typ !== null && typ == "terminate") { + if (typ !== null && typ === "terminate") { // an error occurred cond = bodyWrap.getAttribute("condition"); Strophe.error("BOSH-Connection failed: " + cond); conflict = bodyWrap.getElementsByTagName("conflict"); if (cond !== null) { - if (cond == "remote-stream-error" && conflict.length > 0) { + if (cond === "remote-stream-error" && conflict.length > 0) { cond = "conflict"; } this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, cond); @@ -4980,7 +5413,7 @@ Strophe.Bosh.prototype = { */ _getRequestStatus: function (req, def) { var reqStatus; - if (req.xhr.readyState == 4) { + if (req.xhr.readyState === 4) { try { reqStatus = req.xhr.status; } catch (e) { @@ -4991,7 +5424,7 @@ Strophe.Bosh.prototype = { "reqStatus: " + reqStatus); } } - if (typeof(reqStatus) == "undefined") { + if (typeof(reqStatus) === "undefined") { reqStatus = typeof def === 'number' ? def : 0; } return reqStatus; @@ -5033,10 +5466,10 @@ Strophe.Bosh.prototype = { Strophe.debug("request id "+req.id+" should now be removed"); } - if (reqStatus == 200) { + if (reqStatus === 200) { // request succeeded - var reqIs0 = (this._requests[0] == req); - var reqIs1 = (this._requests[1] == req); + var reqIs0 = (this._requests[0] === req); + var reqIs1 = (this._requests[1] === req); // if request 1 finished, or request 0 finished and request // 1 is over Strophe.SECONDARY_TIMEOUT seconds old, we need to // restart the other - both will be in the first spot, as the @@ -5094,7 +5527,7 @@ Strophe.Bosh.prototype = { time_elapsed > Math.floor(Strophe.TIMEOUT * this.wait)); var secondaryTimeout = (req.dead !== null && req.timeDead() > Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait)); - var requestCompletedWithServerError = (req.xhr.readyState == 4 && + var requestCompletedWithServerError = (req.xhr.readyState === 4 && (reqStatus < 1 || reqStatus >= 500)); if (primaryTimeout || secondaryTimeout || requestCompletedWithServerError) { @@ -5152,7 +5585,7 @@ Strophe.Bosh.prototype = { }; // Implement progressive backoff for reconnects -- - // First retry (send == 1) should also be instantaneous + // First retry (send === 1) should also be instantaneous if (req.sends > 1) { // Using a cube of the retry number creates a nicely // expanding retry window @@ -5196,7 +5629,7 @@ Strophe.Bosh.prototype = { Strophe.debug("removing request"); var i; for (i = this._requests.length - 1; i >= 0; i--) { - if (req == this._requests[i]) { + if (req === this._requests[i]) { this._requests.splice(i, 1); } } @@ -5236,7 +5669,7 @@ Strophe.Bosh.prototype = { try { return req.getResponse(); } catch (e) { - if (e != "parsererror") { throw e; } + if (e !== "parsererror") { throw e; } this._conn.disconnect("strophe-parsererror"); } }, @@ -5334,7 +5767,7 @@ return Strophe; (function (root, factory) { if (typeof define === 'function' && define.amd) { - define('strophe-websocket', ['strophe-core'], function (core) { + define('strophe-websocket',['strophe-core'], function (core) { return factory( core.Strophe, core.$build @@ -5463,7 +5896,7 @@ Strophe.Websocket.prototype = { } if (text) { - errorString += " - " + condition; + errorString += " - " + text; } Strophe.error(errorString); @@ -5855,7 +6288,7 @@ return Strophe; (function(root){ if(typeof define === 'function' && define.amd){ - define("strophe", [ + define('strophe',[ "strophe-core", "strophe-bosh", "strophe-websocket" @@ -5865,31 +6298,13 @@ return Strophe; } })(this); -/* jshint ignore:start */ -if (callback) { - if(typeof define === 'function' && define.amd){ - //For backwards compatability - var n_callback = callback; - if (typeof requirejs === 'function') { - requirejs(["strophe"], function(o){ - n_callback(o.Strophe,o.$build,o.$msg,o.$iq,o.$pres); - }); - } else { - require(["strophe"], function(o){ - n_callback(o.Strophe,o.$build,o.$msg,o.$iq,o.$pres); - }); - } - }else{ - return callback(Strophe, $build, $msg, $iq, $pres); - } -} - -})(function (Strophe, build, msg, iq, pres) { - window.Strophe = Strophe; - window.$build = build; - window.$msg = msg; - window.$iq = iq; - window.$pres = pres; -}); +require(["strophe-polyfill"]); +/* jshint ignore:start */ + //The modules for your project will be inlined above + //this snippet. Ask almond to synchronously require the + //module value for 'main' here and return it as the + //value to use for the public API for the built file. + return require('strophe'); +})); /* jshint ignore:end */ diff --git a/strophe.min.js b/strophe.min.js index e51d5ea3..f709b35f 100644 --- a/strophe.min.js +++ b/strophe.min.js @@ -1,3 +1,32 @@ -/*! strophe.js v1.2.12 - built on 15-01-2017 */ -!function(a){if(function(a,b){"function"==typeof define&&define.amd?define("strophe-base64",function(){return b()}):a.Base64=b()}(this,function(){var a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",b={encode:function(b){var c,d,e,f,g,h,i,j="",k=0;do c=b.charCodeAt(k++),d=b.charCodeAt(k++),e=b.charCodeAt(k++),f=c>>2,g=(3&c)<<4|d>>4,h=(15&d)<<2|e>>6,i=63&e,isNaN(d)?(g=(3&c)<<4,h=i=64):isNaN(e)&&(i=64),j=j+a.charAt(f)+a.charAt(g)+a.charAt(h)+a.charAt(i);while(k>4,d=(15&g)<<4|h>>2,e=(3&h)<<6|i,j+=String.fromCharCode(c),64!=h&&(j+=String.fromCharCode(d)),64!=i&&(j+=String.fromCharCode(e));while(k>5]|=128<<24-d%32,a[(d+64>>9<<4)+15]=d;var g,h,i,j,k,l,m,n,o=new Array(80),p=1732584193,q=-271733879,r=-1732584194,s=271733878,t=-1009589776;for(g=0;g16&&(d=a(d,8*b.length));for(var e=new Array(16),f=new Array(16),h=0;h<16;h++)e[h]=909522486^d[h],f[h]=1549556828^d[h];var i=a(e.concat(g(c)),512+8*c.length);return a(f.concat(i),672)}function e(a,b){var c=(65535&a)+(65535&b),d=(a>>16)+(b>>16)+(c>>16);return d<<16|65535&c}function f(a,b){return a<>>32-b}function g(a){for(var b=[],c=255,d=0;d<8*a.length;d+=8)b[d>>5]|=(a.charCodeAt(d/8)&c)<<24-d%32;return b}function h(a){for(var b="",c=255,d=0;d<32*a.length;d+=8)b+=String.fromCharCode(a[d>>5]>>>24-d%32&c);return b}function i(a){for(var b,c,d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e="",f=0;f<4*a.length;f+=3)for(b=(a[f>>2]>>8*(3-f%4)&255)<<16|(a[f+1>>2]>>8*(3-(f+1)%4)&255)<<8|a[f+2>>2]>>8*(3-(f+2)%4)&255,c=0;c<4;c++)e+=8*f+6*c>32*a.length?"=":d.charAt(b>>6*(3-c)&63);return e}return{b64_hmac_sha1:function(a,b){return i(d(a,b))},b64_sha1:function(b){return i(a(g(b),8*b.length))},binb2str:h,core_hmac_sha1:d,str_hmac_sha1:function(a,b){return h(d(a,b))},str_sha1:function(b){return h(a(g(b),8*b.length))}}}),function(a,b){"function"==typeof define&&define.amd?define("strophe-md5",function(){return b()}):a.MD5=b()}(this,function(a){var b=function(a,b){var c=(65535&a)+(65535&b),d=(a>>16)+(b>>16)+(c>>16);return d<<16|65535&c},c=function(a,b){return a<>>32-b},d=function(a){for(var b=[],c=0;c<8*a.length;c+=8)b[c>>5]|=(255&a.charCodeAt(c/8))<>5]>>>c%32&255);return b},f=function(a){for(var b="0123456789abcdef",c="",d=0;d<4*a.length;d++)c+=b.charAt(a[d>>2]>>d%4*8+4&15)+b.charAt(a[d>>2]>>d%4*8&15);return c},g=function(a,d,e,f,g,h){return b(c(b(b(d,a),b(f,h)),g),e)},h=function(a,b,c,d,e,f,h){return g(b&c|~b&d,a,b,e,f,h)},i=function(a,b,c,d,e,f,h){return g(b&d|c&~d,a,b,e,f,h)},j=function(a,b,c,d,e,f,h){return g(b^c^d,a,b,e,f,h)},k=function(a,b,c,d,e,f,h){return g(c^(b|~d),a,b,e,f,h)},l=function(a,c){a[c>>5]|=128<>>9<<4)+14]=c;for(var d,e,f,g,l=1732584193,m=-271733879,n=-1732584194,o=271733878,p=0;p=0&&c<=127?d+=a.charAt(b):c>2047?(d+=String.fromCharCode(224|c>>12&15),d+=String.fromCharCode(128|c>>6&63),d+=String.fromCharCode(128|c>>0&63)):(d+=String.fromCharCode(192|c>>6&31),d+=String.fromCharCode(128|c>>0&63));return d},addCookies:function(a){var b,c,d,e,f,g,h;for(b in a||{})f="",g="",h="",c=a[b],d="object"==typeof c,e=escape(unescape(d?c.value:c)),d&&(f=c.expires?";expires="+c.expires:"",g=c.domain?";domain="+c.domain:"",h=c.path?";path="+c.path:""),document.cookie=b+"="+e+f+g+h}};return a}),function(a,b){return"function"==typeof define&&define.amd?void define("strophe-polyfill",[],function(){return b()}):b()}(this,function(){Function.prototype.bind||(Function.prototype.bind=function(a){var b=this,c=Array.prototype.slice,d=Array.prototype.concat,e=c.call(arguments,1);return function(){return b.apply(a?a:this,d.call(e,c.call(arguments,0)))}}),Array.isArray||(Array.isArray=function(a){return"[object Array]"===Object.prototype.toString.call(a)}),Array.prototype.indexOf||(Array.prototype.indexOf=function(a){var b=this.length,c=Number(arguments[1])||0;for(c=c<0?Math.ceil(c):Math.floor(c),c<0&&(c+=b);c>>0;if("function"!=typeof a)throw new TypeError(a+" is not a function");for(arguments.length>1&&(c=b),d=0;d0)for(var c=0;c/g,">"),a=a.replace(/'/g,"'"),a=a.replace(/"/g,""")},xmlunescape:function(a){return a=a.replace(/\&/g,"&"),a=a.replace(/</g,"<"),a=a.replace(/>/g,">"),a=a.replace(/'/g,"'"),a=a.replace(/"/g,'"')},xmlTextNode:function(a){return i.xmlGenerator().createTextNode(a)},xmlHtmlNode:function(a){var b;if(window.DOMParser){var c=new DOMParser;b=c.parseFromString(a,"text/xml")}else b=new ActiveXObject("Microsoft.XMLDOM"),b.async="false",b.loadXML(a);return b},getText:function(a){if(!a)return null;var b="";0===a.childNodes.length&&a.nodeType==i.ElementType.TEXT&&(b+=a.nodeValue);for(var c=0;c0&&(g=h.join("; "),c.setAttribute(f,g))}else c.setAttribute(f,g);for(b=0;b/g,"\\3e").replace(/@/g,"\\40")},unescapeNode:function(a){return"string"!=typeof a?a:a.replace(/\\20/g," ").replace(/\\22/g,'"').replace(/\\26/g,"&").replace(/\\27/g,"'").replace(/\\2f/g,"/").replace(/\\3a/g,":").replace(/\\3c/g,"<").replace(/\\3e/g,">").replace(/\\40/g,"@").replace(/\\5c/g,"\\")},getNodeFromJid:function(a){return a.indexOf("@")<0?null:a.split("@")[0]},getDomainFromJid:function(a){var b=i.getBareJidFromJid(a);if(b.indexOf("@")<0)return b;var c=b.split("@");return c.splice(0,1),c.join("@")},getResourceFromJid:function(a){var b=a.split("/");return b.length<2?null:(b.splice(0,1),b.join("/"))},getBareJidFromJid:function(a){return a?a.split("/")[0]:null},_handleError:function(a){"undefined"!=typeof a.stack&&i.fatal(a.stack),a.sourceURL?i.fatal("error: "+this.handler+" "+a.sourceURL+":"+a.line+" - "+a.name+": "+a.message):a.fileName?i.fatal("error: "+this.handler+" "+a.fileName+":"+a.lineNumber+" - "+a.name+": "+a.message):i.fatal("error: "+a.message)},log:function(a,b){},debug:function(a){this.log(this.LogLevel.DEBUG,a)},info:function(a){this.log(this.LogLevel.INFO,a)},warn:function(a){this.log(this.LogLevel.WARN,a)},error:function(a){this.log(this.LogLevel.ERROR,a)},fatal:function(a){this.log(this.LogLevel.FATAL,a)},serialize:function(a){var b;if(!a)return null;"function"==typeof a.tree&&(a=a.tree());var c,d,e=a.nodeName;for(a.getAttribute("_realname")&&(e=a.getAttribute("_realname")),b="<"+e,c=0;c0){for(b+=">",c=0;c"}b+=""}else b+="/>";return b},_requestId:0,_connectionPlugins:{},addConnectionPlugin:function(a,b){i._connectionPlugins[a]=b}},i.Builder=function(a,b){"presence"!=a&&"message"!=a&&"iq"!=a||(b&&!b.xmlns?b.xmlns=i.NS.CLIENT:b||(b={xmlns:i.NS.CLIENT})),this.nodeTree=i.xmlElement(a,b),this.node=this.nodeTree},i.Builder.prototype={tree:function(){return this.nodeTree},toString:function(){return i.serialize(this.nodeTree)},up:function(){return this.node=this.node.parentNode,this},root:function(){return this.node=this.nodeTree,this},attrs:function(a){for(var b in a)a.hasOwnProperty(b)&&(void 0===a[b]?this.node.removeAttribute(b):this.node.setAttribute(b,a[b]));return this},c:function(a,b,c){var d=i.xmlElement(a,b,c);return this.node.appendChild(d),"string"!=typeof c&&"number"!=typeof c&&(this.node=d),this},cnode:function(a){var b,c=i.xmlGenerator();try{b=void 0!==c.importNode}catch(a){b=!1}var d=b?c.importNode(a,!0):i.copyElement(a);return this.node.appendChild(d),this.node=d,this},t:function(a){var b=i.xmlTextNode(a);return this.node.appendChild(b),this},h:function(a){var b=document.createElement("body");b.innerHTML=a;for(var c=i.createHtml(b);c.childNodes.length>0;)this.node.appendChild(c.childNodes[0]);return this}},i.Handler=function(a,b,c,d,e,f,g){this.handler=a,this.ns=b,this.name=c,this.type=d,this.id=e,this.options=g||{matchBareFromJid:!1,ignoreNamespaceFragment:!1},this.options.matchBare&&(i.warn('The "matchBare" option is deprecated, use "matchBareFromJid" instead.'),this.options.matchBareFromJid=this.options.matchBare,delete this.options.matchBare),this.options.matchBareFromJid?this.from=f?i.getBareJidFromJid(f):null:this.from=f,this.user=!0},i.Handler.prototype={getNamespace:function(a){var b=a.getAttribute("xmlns");return b&&this.options.ignoreNamespaceFragment&&(b=b.split("#")[0]),b},namespaceMatch:function(a){var b=!1;if(!this.ns)return!0;var c=this;return i.forEachChild(a,null,function(a){c.getNamespace(a)===c.ns&&(b=!0)}),b=b||this.getNamespace(a)===this.ns},isMatch:function(a){var b=a.getAttribute("from");this.options.matchBareFromJid&&(b=i.getBareJidFromJid(b));var c=a.getAttribute("type");return!(!this.namespaceMatch(a)||this.name&&!i.isTagEqual(a,this.name)||this.type&&(Array.isArray(this.type)?this.type.indexOf(c)==-1:c!=this.type)||this.id&&a.getAttribute("id")!=this.id||this.from&&b!=this.from)},run:function(a){var b=null;try{b=this.handler(a)}catch(a){throw i._handleError(a),a}return b},toString:function(){return"{Handler: "+this.handler+"("+this.name+","+this.id+","+this.ns+")}"}},i.TimedHandler=function(a,b){this.period=a,this.handler=b,this.lastCalled=(new Date).getTime(),this.user=!0},i.TimedHandler.prototype={run:function(){return this.lastCalled=(new Date).getTime(),this.handler()},reset:function(){this.lastCalled=(new Date).getTime()},toString:function(){return"{TimedHandler: "+this.handler+"("+this.period+")}"}},i.Connection=function(a,b){this.service=a,this.options=b||{};var c=this.options.protocol||"";0===a.indexOf("ws:")||0===a.indexOf("wss:")||0===c.indexOf("ws")?this._proto=new i.Websocket(this):this._proto=new i.Bosh(this),this.jid="",this.domain=null,this.features=null,this._sasl_data={},this.do_session=!1,this.do_bind=!1,this.timedHandlers=[],this.handlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this.protocolErrorHandlers={HTTP:{},websocket:{}},this._idleTimeout=null,this._disconnectTimeout=null,this.authenticated=!1,this.connected=!1,this.disconnecting=!1,this.do_authentication=!0,this.paused=!1,this.restored=!1,this._data=[],this._uniqueId=0,this._sasl_success_handler=null,this._sasl_failure_handler=null,this._sasl_challenge_handler=null,this.maxRetries=5,this._idleTimeout=setTimeout(function(){this._onIdle()}.bind(this),100),d.addCookies(this.options.cookies),this.registerSASLMechanisms(this.options.mechanisms);for(var e in i._connectionPlugins)if(i._connectionPlugins.hasOwnProperty(e)){var f=i._connectionPlugins[e],g=function(){};g.prototype=f,this[e]=new g,this[e].init(this)}},i.Connection.prototype={reset:function(){this._proto._reset(),this.do_session=!1,this.do_bind=!1,this.timedHandlers=[],this.handlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this.authenticated=!1,this.connected=!1,this.disconnecting=!1,this.restored=!1,this._data=[],this._requests=[],this._uniqueId=0},pause:function(){this.paused=!0},resume:function(){this.paused=!1},getUniqueId:function(a){var b="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(a){var b=16*Math.random()|0,c="x"==a?b:3&b|8;return c.toString(16)});return"string"==typeof a||"number"==typeof a?b+":"+a:b+""},addProtocolErrorHandler:function(a,b,c){this.protocolErrorHandlers[a][b]=c},connect:function(a,b,c,d,e,f,g){this.jid=a,this.authzid=i.getBareJidFromJid(this.jid),this.authcid=g||i.getNodeFromJid(this.jid),this.pass=b,this.servtype="xmpp",this.connect_callback=c,this.disconnecting=!1,this.connected=!1,this.authenticated=!1,this.restored=!1,this.domain=i.getDomainFromJid(this.jid),this._changeConnectStatus(i.Status.CONNECTING,null),this._proto._connect(d,e,f)},attach:function(a,b,c,d,e,f,g){if(!(this._proto instanceof i.Bosh))throw{name:"StropheSessionError",message:'The "attach" method can only be used with a BOSH connection.'};this._proto._attach(a,b,c,d,e,f,g)},restore:function(a,b,c,d,e){if(!this._sessionCachingSupported())throw{name:"StropheSessionError",message:'The "restore" method can only be used with a BOSH connection.'};this._proto._restore(a,b,c,d,e)},_sessionCachingSupported:function(){if(this._proto instanceof i.Bosh){if(!JSON)return!1;try{window.sessionStorage.setItem("_strophe_","_strophe_"),window.sessionStorage.removeItem("_strophe_")}catch(a){return!1}return!0}return!1},xmlInput:function(a){},xmlOutput:function(a){},rawInput:function(a){},rawOutput:function(a){},nextValidRid:function(a){},send:function(a){if(null!==a){if("function"==typeof a.sort)for(var b=0;b=0&&this.addHandlers.splice(b,1)},registerSASLMechanisms:function(a){this.mechanisms={},a=a||[i.SASLAnonymous,i.SASLExternal,i.SASLMD5,i.SASLOAuthBearer,i.SASLPlain,i.SASLSHA1],a.forEach(this.registerSASLMechanism.bind(this))},registerSASLMechanism:function(a){this.mechanisms[a.prototype.name]=a},disconnect:function(a){if(this._changeConnectStatus(i.Status.DISCONNECTING,a),i.info("Disconnect was called because: "+a),this.connected){var b=!1;this.disconnecting=!0,this.authenticated&&(b=h({xmlns:i.NS.CLIENT,type:"unavailable"})),this._disconnectTimeout=this._addSysTimedHandler(3e3,this._onDisconnectTimeout.bind(this)),this._proto._disconnect(b)}else i.info("Disconnect was called before Strophe connected to the server"),this._proto._abortAllRequests(),this._doDisconnect()},_changeConnectStatus:function(a,b){for(var c in i._connectionPlugins)if(i._connectionPlugins.hasOwnProperty(c)){var d=this[c];if(d.statusChanged)try{d.statusChanged(a,b)}catch(a){i.error(""+c+" plugin caused an exception changing status: "+a)}}if(this.connect_callback)try{this.connect_callback(a,b)}catch(a){i._handleError(a),i.error("User connection callback caused an exception: "+a)}},_doDisconnect:function(a){"number"==typeof this._idleTimeout&&clearTimeout(this._idleTimeout),null!==this._disconnectTimeout&&(this.deleteTimedHandler(this._disconnectTimeout),this._disconnectTimeout=null),i.info("_doDisconnect was called"),this._proto._doDisconnect(),this.authenticated=!1,this.disconnecting=!1,this.restored=!1,this.handlers=[],this.timedHandlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this._changeConnectStatus(i.Status.DISCONNECTED,a),this.connected=!1},_dataRecv:function(a,b){i.info("_dataRecv called");var c=this._proto._reqToData(a);if(null!==c){this.xmlInput!==i.Connection.prototype.xmlInput&&(c.nodeName===this._proto.strip&&c.childNodes.length?this.xmlInput(c.childNodes[0]):this.xmlInput(c)),this.rawInput!==i.Connection.prototype.rawInput&&(b?this.rawInput(b):this.rawInput(i.serialize(c)));for(var d,e;this.removeHandlers.length>0;)e=this.removeHandlers.pop(),d=this.handlers.indexOf(e),d>=0&&this.handlers.splice(d,1);for(;this.addHandlers.length>0;)this.handlers.push(this.addHandlers.pop());if(this.disconnecting&&this._proto._emptyQueue())return void this._doDisconnect();var f,g,h=c.getAttribute("type");if(null!==h&&"terminate"==h){if(this.disconnecting)return;return f=c.getAttribute("condition"),g=c.getElementsByTagName("conflict"),null!==f?("remote-stream-error"==f&&g.length>0&&(f="conflict"),this._changeConnectStatus(i.Status.CONNFAIL,f)):this._changeConnectStatus(i.Status.CONNFAIL,"unknown"),void this._doDisconnect(f)}var j=this;i.forEachChild(c,null,function(a){var b,c;for(c=j.handlers,j.handlers=[],b=0;b0:d.getElementsByTagName("stream:features").length>0||d.getElementsByTagName("features").length>0,!f)return void this._proto._no_auth_received(b);var g,h,j=[],k=d.getElementsByTagName("mechanism");if(k.length>0)for(g=0;ga[d].prototype.priority&&(d=c);d!=b&&(e=a[b],a[b]=a[d],a[d]=e)}return a},_attemptSASLAuth:function(a){a=this.sortMechanismsByPriority(a||[]);var c=0,d=!1;for(c=0;c0&&(b="conflict"),this._changeConnectStatus(i.Status.AUTHFAIL,b),!1}var d,e=a.getElementsByTagName("bind");return e.length>0?(d=e[0].getElementsByTagName("jid"),void(d.length>0&&(this.jid=i.getText(d[0]),this.do_session?(this._addSysHandler(this._sasl_session_cb.bind(this),null,null,null,"_session_auth_2"),this.send(g({type:"set",id:"_session_auth_2"}).c("session",{xmlns:i.NS.SESSION}).tree())):(this.authenticated=!0,this._changeConnectStatus(i.Status.CONNECTED,null))))):(i.info("SASL binding failed."),this._changeConnectStatus(i.Status.AUTHFAIL,null),!1)},_sasl_session_cb:function(a){if("result"==a.getAttribute("type"))this.authenticated=!0,this._changeConnectStatus(i.Status.CONNECTED,null);else if("error"==a.getAttribute("type"))return i.info("Session creation failed."),this._changeConnectStatus(i.Status.AUTHFAIL,null),!1;return!1},_sasl_failure_cb:function(a){return this._sasl_success_handler&&(this.deleteHandler(this._sasl_success_handler),this._sasl_success_handler=null),this._sasl_challenge_handler&&(this.deleteHandler(this._sasl_challenge_handler),this._sasl_challenge_handler=null),this._sasl_mechanism&&this._sasl_mechanism.onFailure(),this._changeConnectStatus(i.Status.AUTHFAIL,null),!1},_auth2_cb:function(a){return"result"==a.getAttribute("type")?(this.authenticated=!0,this._changeConnectStatus(i.Status.CONNECTED,null)):"error"==a.getAttribute("type")&&(this._changeConnectStatus(i.Status.AUTHFAIL,null),this.disconnect("authentication failed")),!1},_addSysTimedHandler:function(a,b){var c=new i.TimedHandler(a,b);return c.user=!1,this.addTimeds.push(c),c},_addSysHandler:function(a,b,c,d,e){var f=new i.Handler(a,b,c,d,e);return f.user=!1,this.addHandlers.push(f),f},_onDisconnectTimeout:function(){return i.info("_onDisconnectTimeout was called"),this._changeConnectStatus(i.Status.CONNTIMEOUT,null),this._proto._onDisconnectTimeout(),this._doDisconnect(),!1},_onIdle:function(){for(var a,b,c,d;this.addTimeds.length>0;)this.timedHandlers.push(this.addTimeds.pop());for(;this.removeTimeds.length>0;)b=this.removeTimeds.pop(),a=this.timedHandlers.indexOf(b),a>=0&&this.timedHandlers.splice(a,1);var e=(new Date).getTime();for(d=[],a=0;a0&&(c="conflict"),this._conn._changeConnectStatus(a.Status.CONNFAIL,c)):this._conn._changeConnectStatus(a.Status.CONNFAIL,"unknown"),this._conn._doDisconnect(c),a.Status.CONNFAIL;this.sid||(this.sid=b.getAttribute("sid"));var f=b.getAttribute("requests");f&&(this.window=parseInt(f,10));var g=b.getAttribute("hold");g&&(this.hold=parseInt(g,10));var h=b.getAttribute("wait");h&&(this.wait=parseInt(h,10));var i=b.getAttribute("inactivity");i&&(this.inactivity=parseInt(i,10))},_disconnect:function(a){this._sendTerminate(a)},_doDisconnect:function(){this.sid=null,this.rid=Math.floor(4294967295*Math.random()),this._conn._sessionCachingSupported()&&window.sessionStorage.removeItem("strophe-bosh-session"),this._conn.nextValidRid(this.rid)},_emptyQueue:function(){return 0===this._requests.length},_callProtocolErrorHandlers:function(a){var b,c=this._getRequestStatus(a);b=this._conn.protocolErrorHandlers.HTTP[c],b&&b.call(this,c)},_hitError:function(b){this.errors++,a.warn("request errored, status: "+b+", number of errors: "+this.errors),this.errors>4&&this._conn._onDisconnectTimeout()},_no_auth_received:function(b){b=b?b.bind(this._conn):this._conn._connect_cb.bind(this._conn);var c=this._buildBody();this._requests.push(new a.Request(c.tree(),this._onRequestStateChange.bind(this,b.bind(this._conn)),c.tree().getAttribute("rid"))),this._throttledRequestHandler()},_onDisconnectTimeout:function(){this._abortAllRequests()},_abortAllRequests:function(){for(var a;this._requests.length>0;)a=this._requests.pop(),a.abort=!0,a.xhr.abort(),a.xhr.onreadystatechange=function(){}},_onIdle:function(){var b=this._conn._data;if(this._conn.authenticated&&0===this._requests.length&&0===b.length&&!this._conn.disconnecting&&(a.info("no requests during idle cycle, sending blank request"),b.push(null)),!this._conn.paused){if(this._requests.length<2&&b.length>0){for(var c=this._buildBody(),d=0;d0){var e=this._requests[0].age();null!==this._requests[0].dead&&this._requests[0].timeDead()>Math.floor(a.SECONDARY_TIMEOUT*this.wait)&&this._throttledRequestHandler(),e>Math.floor(a.TIMEOUT*this.wait)&&(a.warn("Request "+this._requests[0].id+" timed out, over "+Math.floor(a.TIMEOUT*this.wait)+" seconds since last activity"),this._throttledRequestHandler())}}},_getRequestStatus:function(b,c){var d;if(4==b.xhr.readyState)try{d=b.xhr.status}catch(b){a.error("Caught an error while retrieving a request's status, reqStatus: "+d)}return"undefined"==typeof d&&(d="number"==typeof c?c:0),d},_onRequestStateChange:function(b,c){if(a.debug("request id "+c.id+"."+c.sends+" state changed to "+c.xhr.readyState),c.abort)return void(c.abort=!1);if(4===c.xhr.readyState){var d=this._getRequestStatus(c);if(this.disconnecting&&d>=400)return this._hitError(d),void this._callProtocolErrorHandlers(c);if((d>0&&d<500||c.sends>5)&&(this._removeRequest(c),a.debug("request id "+c.id+" should now be removed")),200==d){var e=this._requests[0]==c,f=this._requests[1]==c;(f||e&&this._requests.length>0&&this._requests[0].age()>Math.floor(a.SECONDARY_TIMEOUT*this.wait))&&this._restartRequest(0),this._conn.nextValidRid(Number(c.rid)+1),a.debug("request id "+c.id+"."+c.sends+" got 200"),b(c),this.errors=0}else 0===d||d>=400&&d<600||d>=12e3?(a.error("request id "+c.id+"."+c.sends+" error "+d+" happened"),this._hitError(d),this._callProtocolErrorHandlers(c),d>=400&&d<500&&(this._conn._changeConnectStatus(a.Status.DISCONNECTING,null),this._conn._doDisconnect())):a.error("request id "+c.id+"."+c.sends+" error "+d+" happened");d>0&&d<500&&!(c.sends>5)||this._throttledRequestHandler()}},_processRequest:function(b){var c=this,d=this._requests[b],e=this._getRequestStatus(d,-1);if(d.sends>this._conn.maxRetries)return void this._conn._onDisconnectTimeout();var f=d.age(),g=!isNaN(f)&&f>Math.floor(a.TIMEOUT*this.wait),h=null!==d.dead&&d.timeDead()>Math.floor(a.SECONDARY_TIMEOUT*this.wait),i=4==d.xhr.readyState&&(e<1||e>=500);if((g||h||i)&&(h&&a.error("Request "+this._requests[b].id+" timed out (secondary), restarting"),d.abort=!0,d.xhr.abort(),d.xhr.onreadystatechange=function(){},this._requests[b]=new a.Request(d.xmlData,d.origFunc,d.rid,d.sends),d=this._requests[b]),0===d.xhr.readyState){a.debug("request id "+d.id+"."+d.sends+" posting");try{var j=this._conn.options.contentType||"text/xml; charset=utf-8";d.xhr.open("POST",this._conn.service,!this._conn.options.sync),"undefined"!=typeof d.xhr.setRequestHeader&&d.xhr.setRequestHeader("Content-Type",j),this._conn.options.withCredentials&&(d.xhr.withCredentials=!0)}catch(b){return a.error("XHR open failed."),this._conn.connected||this._conn._changeConnectStatus(a.Status.CONNFAIL,"bad-service"),void this._conn.disconnect()}var k=function(){if(d.date=new Date,c._conn.options.customHeaders){var a=c._conn.options.customHeaders;for(var b in a)a.hasOwnProperty(b)&&d.xhr.setRequestHeader(b,a[b])}d.xhr.send(d.data)};if(d.sends>1){var l=1e3*Math.min(Math.floor(a.TIMEOUT*this.wait),Math.pow(d.sends,3));setTimeout(function(){k()},l)}else k();d.sends++,this._conn.xmlOutput!==a.Connection.prototype.xmlOutput&&(d.xmlData.nodeName===this.strip&&d.xmlData.childNodes.length?this._conn.xmlOutput(d.xmlData.childNodes[0]):this._conn.xmlOutput(d.xmlData)),this._conn.rawOutput!==a.Connection.prototype.rawOutput&&this._conn.rawOutput(d.data)}else a.debug("_processRequest: "+(0===b?"first":"second")+" request has readyState of "+d.xhr.readyState)},_removeRequest:function(b){a.debug("removing request");var c;for(c=this._requests.length-1;c>=0;c--)b==this._requests[c]&&this._requests.splice(c,1);b.xhr.onreadystatechange=function(){},this._throttledRequestHandler()},_restartRequest:function(a){var b=this._requests[a];null===b.dead&&(b.dead=new Date),this._processRequest(a)},_reqToData:function(a){try{return a.getResponse()}catch(a){if("parsererror"!=a)throw a;this._conn.disconnect("strophe-parsererror")}},_sendTerminate:function(b){a.info("_sendTerminate was called");var c=this._buildBody().attrs({type:"terminate"});b&&c.cnode(b.tree());var d=new a.Request(c.tree(),this._onRequestStateChange.bind(this,this._conn._dataRecv.bind(this._conn)),c.tree().getAttribute("rid"));this._requests.push(d),this._throttledRequestHandler()},_send:function(){clearTimeout(this._conn._idleTimeout),this._throttledRequestHandler(),this._conn._idleTimeout=setTimeout(function(){this._onIdle()}.bind(this._conn),100)},_sendRestart:function(){this._throttledRequestHandler(),clearTimeout(this._conn._idleTimeout)},_throttledRequestHandler:function(){this._requests?a.debug("_throttledRequestHandler called with "+this._requests.length+" requests"):a.debug("_throttledRequestHandler called with undefined requests"),this._requests&&0!==this._requests.length&&(this._requests.length>0&&this._processRequest(0),this._requests.length>1&&Math.abs(this._requests[0].rid-this._requests[1].rid): "+d);var e=b.getAttribute("version");return"string"!=typeof e?c="Missing version in ":"1.0"!==e&&(c="Wrong version in : "+e),!c||(this._conn._changeConnectStatus(a.Status.CONNFAIL,c),this._conn._doDisconnect(),!1)},_connect_cb_wrapper:function(b){if(0===b.data.indexOf("\s*)*/,"");if(""===c)return;var d=(new DOMParser).parseFromString(c,"text/xml").documentElement;this._conn.xmlInput(d),this._conn.rawInput(b.data),this._handleStreamStart(d)&&this._connect_cb(d)}else if(0===b.data.indexOf(" tag.")}}this._conn._doDisconnect()},_doDisconnect:function(){a.info("WebSockets _doDisconnect was called"),this._closeSocket()},_streamWrap:function(a){return""+a+""},_closeSocket:function(){if(this.socket)try{this.socket.close()}catch(a){}this.socket=null},_emptyQueue:function(){return!0},_onClose:function(){this._conn.connected&&!this._conn.disconnecting?(a.error("Websocket closed unexpectedly"),this._conn._doDisconnect()):a.info("Websocket closed")},_no_auth_received:function(b){a.error("Server did not send any auth methods"),this._conn._changeConnectStatus(a.Status.CONNFAIL,"Server did not send any auth methods"),b&&(b=b.bind(this._conn))(),this._conn._doDisconnect()},_onDisconnectTimeout:function(){},_abortAllRequests:function(){},_onError:function(b){a.error("Websocket error "+b),this._conn._changeConnectStatus(a.Status.CONNFAIL,"The WebSocket connection could not be established or was disconnected."),this._disconnect()},_onIdle:function(){var b=this._conn._data;if(b.length>0&&!this._conn.paused){for(var c=0;c0&&(t.splice(u-1,2),u-=2)}t=t.join("/")}if((f||m)&&p){for(n=t.split("/"),u=n.length;u>0;u-=1){if(i=n.slice(0,u).join("/"),f)for(l=f.length;l>0;l-=1)if(s=p[f.slice(0,l).join("/")],s&&(s=s[i])){r=s,a=u;break}if(r)break;!h&&m&&m[i]&&(h=m[i],c=u)}!r&&h&&(r=h,a=c),r&&(n.splice(0,a,r),t=n.join("/"))}return t}function o(t,e){return function(){var n=T.call(arguments,0);return"string"!=typeof n[0]&&1===n.length&&n.push(null),f.apply(i,n.concat([t,e]))}}function a(t){return function(e){return r(e,t)}}function h(t){return function(e){g[t]=e}}function c(t){if(s(S,t)){var e=S[t];delete S[t],y[t]=!0,_.apply(i,e)}if(!s(g,t)&&!s(y,t))throw new Error("No "+t);return g[t]}function u(t){var e,n=t?t.indexOf("!"):-1;return n>-1&&(e=t.substring(0,n),t=t.substring(n+1,t.length)),[e,t]}function l(t){return t?u(t):[]}function d(t){return function(){return b&&b.config&&b.config[t]||{}}}var _,f,p,m,g={},S={},b={},y={},v=Object.prototype.hasOwnProperty,T=[].slice,x=/\.js$/;p=function(t,e){var n,i=u(t),s=i[0],o=e[1];return t=i[1],s&&(s=r(s,o),n=c(s)),s?t=n&&n.normalize?n.normalize(t,a(o)):r(t,o):(t=r(t,o),i=u(t),s=i[0],t=i[1],s&&(n=c(s))),{f:s?s+"!"+t:t,n:t,pr:s,p:n}},m={require:function(t){return o(t)},exports:function(t){var e=g[t];return"undefined"!=typeof e?e:g[t]={}},module:function(t){return{id:t,uri:"",exports:g[t],config:d(t)}}},_=function(t,e,n,r){var a,u,d,_,f,b,v,T=[],x=typeof n;if(r=r||t,b=l(r),"undefined"===x||"function"===x){for(e=!e.length&&n.length?["require","exports","module"]:e,f=0;f>>0;if("function"!=typeof t)throw new TypeError(t+" is not a function");for(arguments.length>1&&(n=e),i=0;i>2,o=(3&n)<<4|i>>4,a=(15&i)<<2|s>>6,h=63&s,isNaN(i)?(o=(3&n)<<4,a=h=64):isNaN(s)&&(h=64),c=c+e.charAt(r)+e.charAt(o)+e.charAt(a)+e.charAt(h);while(u>4,i=(15&o)<<4|a>>2,s=(3&a)<<6|h,c+=String.fromCharCode(n),64!==a&&(c+=String.fromCharCode(i)),64!==h&&(c+=String.fromCharCode(s));while(u>5]|=128<<24-i%32,t[(i+64>>9<<4)+15]=i;var o,a,h,c,u,l,d,_,f=new Array(80),p=1732584193,m=-271733879,g=-1732584194,S=271733878,b=-1009589776;for(o=0;o16&&(i=t(i,8*e.length));for(var s=new Array(16),r=new Array(16),a=0;a<16;a++)s[a]=909522486^i[a],r[a]=1549556828^i[a];var h=t(s.concat(o(n)),512+8*n.length);return t(r.concat(h),672)}function s(t,e){var n=(65535&t)+(65535&e),i=(t>>16)+(e>>16)+(n>>16);return i<<16|65535&n}function r(t,e){return t<>>32-e}function o(t){for(var e=[],n=255,i=0;i<8*t.length;i+=8)e[i>>5]|=(t.charCodeAt(i/8)&n)<<24-i%32;return e}function a(t){for(var e="",n=255,i=0;i<32*t.length;i+=8)e+=String.fromCharCode(t[i>>5]>>>24-i%32&n);return e}function h(t){for(var e,n,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s="",r=0;r<4*t.length;r+=3)for(e=(t[r>>2]>>8*(3-r%4)&255)<<16|(t[r+1>>2]>>8*(3-(r+1)%4)&255)<<8|t[r+2>>2]>>8*(3-(r+2)%4)&255,n=0;n<4;n++)s+=8*r+6*n>32*t.length?"=":i.charAt(e>>6*(3-n)&63);return s}return{b64_hmac_sha1:function(t,e){return h(i(t,e))},b64_sha1:function(e){return h(t(o(e),8*e.length))},binb2str:a,core_hmac_sha1:i,str_hmac_sha1:function(t,e){return a(i(t,e))},str_sha1:function(e){return a(t(o(e),8*e.length))}}}),function(t,e){"function"==typeof n&&n.amd?n("strophe-md5",[],function(){return e()}):t.MD5=e()}(this,function(){var t=function(t,e){var n=(65535&t)+(65535&e),i=(t>>16)+(e>>16)+(n>>16);return i<<16|65535&n},e=function(t,e){return t<>>32-e},n=function(t){for(var e=[],n=0;n<8*t.length;n+=8)e[n>>5]|=(255&t.charCodeAt(n/8))<>5]>>>n%32&255);return e},s=function(t){for(var e="0123456789abcdef",n="",i=0;i<4*t.length;i++)n+=e.charAt(t[i>>2]>>i%4*8+4&15)+e.charAt(t[i>>2]>>i%4*8&15);return n},r=function(n,i,s,r,o,a){return t(e(t(t(i,n),t(r,a)),o),s)},o=function(t,e,n,i,s,o,a){return r(e&n|~e&i,t,e,s,o,a)},a=function(t,e,n,i,s,o,a){return r(e&i|n&~i,t,e,s,o,a)},h=function(t,e,n,i,s,o,a){return r(e^n^i,t,e,s,o,a)},c=function(t,e,n,i,s,o,a){return r(n^(e|~i),t,e,s,o,a)},u=function(e,n){e[n>>5]|=128<>>9<<4)+14]=n;for(var i,s,r,u,l=1732584193,d=-271733879,_=-1732584194,f=271733878,p=0;p=0&&n<=127?i+=t.charAt(e):n>2047?(i+=String.fromCharCode(224|n>>12&15),i+=String.fromCharCode(128|n>>6&63),i+=String.fromCharCode(128|n>>0&63)):(i+=String.fromCharCode(192|n>>6&31),i+=String.fromCharCode(128|n>>0&63));return i},addCookies:function(t){var e,n,i,s,r,o,a;for(e in t||{})r="",o="",a="",n=t[e],i="object"==typeof n,s=escape(unescape(i?n.value:n)),i&&(r=n.expires?";expires="+n.expires:"",o=n.domain?";domain="+n.domain:"",a=n.path?";path="+n.path:""),document.cookie=e+"="+s+r+o+a}};return t}),function(t,e){if("function"==typeof n&&n.amd)n("strophe-core",["strophe-sha1","strophe-md5","strophe-utils"],function(){return e.apply(this,arguments)});else{var i=e(t.SHA1,t.MD5,t.stropheUtils);t.Strophe=i.Strophe,t.$build=i.$build,t.$iq=i.$iq,t.$msg=i.$msg,t.$pres=i.$pres,t.SHA1=i.SHA1,t.MD5=i.MD5,t.b64_hmac_sha1=i.SHA1.b64_hmac_sha1,t.b64_sha1=i.SHA1.b64_sha1,t.str_hmac_sha1=i.SHA1.str_hmac_sha1,t.str_sha1=i.SHA1.str_sha1}}(this,function(t,e,n){function i(t,e){return new a.Builder(t,e)}function s(t){return new a.Builder("message",t)}function r(t){return new a.Builder("iq",t)}function o(t){return new a.Builder("presence",t)}var a;return a={VERSION:"1.2.13",NS:{HTTPBIND:"http://jabber.org/protocol/httpbind",BOSH:"urn:xmpp:xbosh",CLIENT:"jabber:client",AUTH:"jabber:iq:auth",ROSTER:"jabber:iq:roster",PROFILE:"jabber:iq:profile",DISCO_INFO:"http://jabber.org/protocol/disco#info",DISCO_ITEMS:"http://jabber.org/protocol/disco#items",MUC:"http://jabber.org/protocol/muc",SASL:"urn:ietf:params:xml:ns:xmpp-sasl",STREAM:"http://etherx.jabber.org/streams",FRAMING:"urn:ietf:params:xml:ns:xmpp-framing",BIND:"urn:ietf:params:xml:ns:xmpp-bind",SESSION:"urn:ietf:params:xml:ns:xmpp-session",VERSION:"jabber:iq:version",STANZAS:"urn:ietf:params:xml:ns:xmpp-stanzas",XHTML_IM:"http://jabber.org/protocol/xhtml-im",XHTML:"http://www.w3.org/1999/xhtml"},XHTML:{tags:["a","blockquote","br","cite","em","img","li","ol","p","span","strong","ul","body"],attributes:{a:["href"],blockquote:["style"],br:[],cite:["style"],em:[],img:["src","alt","style","height","width"],li:["style"],ol:["style"],p:["style"],span:["style"],strong:[],ul:["style"],body:[]},css:["background-color","color","font-family","font-size","font-style","font-weight","margin-left","margin-right","text-align","text-decoration"],validTag:function(t){for(var e=0;e0)for(var n=0;n/g,">"),t=t.replace(/'/g,"'"),t=t.replace(/"/g,""")},xmlunescape:function(t){return t=t.replace(/\&/g,"&"),t=t.replace(/</g,"<"),t=t.replace(/>/g,">"),t=t.replace(/'/g,"'"),t=t.replace(/"/g,'"')},xmlTextNode:function(t){return a.xmlGenerator().createTextNode(t)},xmlHtmlNode:function(t){var e;if(DOMParser){var n=new DOMParser;e=n.parseFromString(t,"text/xml")}else e=new ActiveXObject("Microsoft.XMLDOM"),e.async="false",e.loadXML(t);return e},getText:function(t){if(!t)return null;var e="";0===t.childNodes.length&&t.nodeType===a.ElementType.TEXT&&(e+=t.nodeValue);for(var n=0;n0&&(o=h.join("; "),n.setAttribute(r,o))}else n.setAttribute(r,o);for(e=0;e/g,"\\3e").replace(/@/g,"\\40")},unescapeNode:function(t){return"string"!=typeof t?t:t.replace(/\\20/g," ").replace(/\\22/g,'"').replace(/\\26/g,"&").replace(/\\27/g,"'").replace(/\\2f/g,"/").replace(/\\3a/g,":").replace(/\\3c/g,"<").replace(/\\3e/g,">").replace(/\\40/g,"@").replace(/\\5c/g,"\\")},getNodeFromJid:function(t){return t.indexOf("@")<0?null:t.split("@")[0]},getDomainFromJid:function(t){var e=a.getBareJidFromJid(t);if(e.indexOf("@")<0)return e;var n=e.split("@");return n.splice(0,1),n.join("@")},getResourceFromJid:function(t){var e=t.split("/");return e.length<2?null:(e.splice(0,1),e.join("/"))},getBareJidFromJid:function(t){return t?t.split("/")[0]:null},_handleError:function(t){"undefined"!=typeof t.stack&&a.fatal(t.stack),t.sourceURL?a.fatal("error: "+this.handler+" "+t.sourceURL+":"+t.line+" - "+t.name+": "+t.message):t.fileName?a.fatal("error: "+this.handler+" "+t.fileName+":"+t.lineNumber+" - "+t.name+": "+t.message):a.fatal("error: "+t.message)},log:function(t,e){},debug:function(t){this.log(this.LogLevel.DEBUG,t)},info:function(t){this.log(this.LogLevel.INFO,t)},warn:function(t){this.log(this.LogLevel.WARN,t)},error:function(t){this.log(this.LogLevel.ERROR,t)},fatal:function(t){this.log(this.LogLevel.FATAL,t)},serialize:function(t){var e;if(!t)return null;"function"==typeof t.tree&&(t=t.tree());var n,i,s=t.nodeName;for(t.getAttribute("_realname")&&(s=t.getAttribute("_realname")),e="<"+s,n=0;n0){for(e+=">",n=0;n"}e+=""}else e+="/>";return e},_requestId:0,_connectionPlugins:{},addConnectionPlugin:function(t,e){a._connectionPlugins[t]=e}},a.Builder=function(t,e){"presence"!==t&&"message"!==t&&"iq"!==t||(e&&!e.xmlns?e.xmlns=a.NS.CLIENT:e||(e={xmlns:a.NS.CLIENT})),this.nodeTree=a.xmlElement(t,e),this.node=this.nodeTree},a.Builder.prototype={tree:function(){return this.nodeTree},toString:function(){return a.serialize(this.nodeTree)},up:function(){return this.node=this.node.parentNode,this},root:function(){return this.node=this.nodeTree,this},attrs:function(t){for(var e in t)t.hasOwnProperty(e)&&(void 0===t[e]?this.node.removeAttribute(e):this.node.setAttribute(e,t[e]));return this},c:function(t,e,n){var i=a.xmlElement(t,e,n);return this.node.appendChild(i),"string"!=typeof n&&"number"!=typeof n&&(this.node=i),this},cnode:function(t){var e,n=a.xmlGenerator();try{e=void 0!==n.importNode}catch(t){e=!1}var i=e?n.importNode(t,!0):a.copyElement(t);return this.node.appendChild(i),this.node=i,this},t:function(t){var e=a.xmlTextNode(t);return this.node.appendChild(e),this},h:function(t){var e=document.createElement("body");e.innerHTML=t;for(var n=a.createHtml(e);n.childNodes.length>0;)this.node.appendChild(n.childNodes[0]);return this}},a.Handler=function(t,e,n,i,s,r,o){this.handler=t,this.ns=e,this.name=n,this.type=i,this.id=s,this.options=o||{matchBareFromJid:!1,ignoreNamespaceFragment:!1},this.options.matchBare&&(a.warn('The "matchBare" option is deprecated, use "matchBareFromJid" instead.'),this.options.matchBareFromJid=this.options.matchBare,delete this.options.matchBare),this.options.matchBareFromJid?this.from=r?a.getBareJidFromJid(r):null:this.from=r,this.user=!0},a.Handler.prototype={getNamespace:function(t){var e=t.getAttribute("xmlns");return e&&this.options.ignoreNamespaceFragment&&(e=e.split("#")[0]),e},namespaceMatch:function(t){var e=!1;if(!this.ns)return!0;var n=this;return a.forEachChild(t,null,function(t){n.getNamespace(t)===n.ns&&(e=!0)}),e=e||this.getNamespace(t)===this.ns},isMatch:function(t){var e=t.getAttribute("from");this.options.matchBareFromJid&&(e=a.getBareJidFromJid(e));var n=t.getAttribute("type");return!(!this.namespaceMatch(t)||this.name&&!a.isTagEqual(t,this.name)||this.type&&(Array.isArray(this.type)?this.type.indexOf(n)===-1:n!==this.type)||this.id&&t.getAttribute("id")!==this.id||this.from&&e!==this.from)},run:function(t){var e=null;try{e=this.handler(t)}catch(t){throw a._handleError(t),t}return e},toString:function(){return"{Handler: "+this.handler+"("+this.name+","+this.id+","+this.ns+")}"}},a.TimedHandler=function(t,e){this.period=t,this.handler=e,this.lastCalled=(new Date).getTime(),this.user=!0},a.TimedHandler.prototype={run:function(){return this.lastCalled=(new Date).getTime(),this.handler()},reset:function(){this.lastCalled=(new Date).getTime()},toString:function(){return"{TimedHandler: "+this.handler+"("+this.period+")}"}},a.Connection=function(t,e){this.service=t,this.options=e||{};var i=this.options.protocol||"";0===t.indexOf("ws:")||0===t.indexOf("wss:")||0===i.indexOf("ws")?this._proto=new a.Websocket(this):this._proto=new a.Bosh(this),this.jid="",this.domain=null,this.features=null,this._sasl_data={},this.do_session=!1,this.do_bind=!1,this.timedHandlers=[],this.handlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this.protocolErrorHandlers={HTTP:{},websocket:{}},this._idleTimeout=null,this._disconnectTimeout=null,this.authenticated=!1,this.connected=!1,this.disconnecting=!1,this.do_authentication=!0,this.paused=!1,this.restored=!1,this._data=[],this._uniqueId=0,this._sasl_success_handler=null,this._sasl_failure_handler=null,this._sasl_challenge_handler=null,this.maxRetries=5,this._idleTimeout=setTimeout(function(){this._onIdle()}.bind(this),100),n.addCookies(this.options.cookies),this.registerSASLMechanisms(this.options.mechanisms);for(var s in a._connectionPlugins)if(a._connectionPlugins.hasOwnProperty(s)){var r=a._connectionPlugins[s],o=function(){};o.prototype=r,this[s]=new o,this[s].init(this)}},a.Connection.prototype={reset:function(){this._proto._reset(),this.do_session=!1,this.do_bind=!1,this.timedHandlers=[],this.handlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this.authenticated=!1,this.connected=!1,this.disconnecting=!1,this.restored=!1,this._data=[],this._requests=[],this._uniqueId=0},pause:function(){this.paused=!0},resume:function(){this.paused=!1},getUniqueId:function(t){var e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var e=16*Math.random()|0,n="x"===t?e:3&e|8;return n.toString(16)});return"string"==typeof t||"number"==typeof t?e+":"+t:e+""},addProtocolErrorHandler:function(t,e,n){this.protocolErrorHandlers[t][e]=n},connect:function(t,e,n,i,s,r,o){this.jid=t,this.authzid=a.getBareJidFromJid(this.jid),this.authcid=o||a.getNodeFromJid(this.jid),this.pass=e,this.servtype="xmpp",this.connect_callback=n,this.disconnecting=!1,this.connected=!1,this.authenticated=!1,this.restored=!1,this.domain=a.getDomainFromJid(this.jid),this._changeConnectStatus(a.Status.CONNECTING,null),this._proto._connect(i,s,r)},attach:function(t,e,n,i,s,r,o){if(!(this._proto instanceof a.Bosh))throw{name:"StropheSessionError",message:'The "attach" method can only be used with a BOSH connection.'};this._proto._attach(t,e,n,i,s,r,o)},restore:function(t,e,n,i,s){if(!this._sessionCachingSupported())throw{name:"StropheSessionError",message:'The "restore" method can only be used with a BOSH connection.'};this._proto._restore(t,e,n,i,s)},_sessionCachingSupported:function(){if(this._proto instanceof a.Bosh){if(!JSON)return!1;try{sessionStorage.setItem("_strophe_","_strophe_"),sessionStorage.removeItem("_strophe_")}catch(t){return!1}return!0}return!1},xmlInput:function(t){},xmlOutput:function(t){},rawInput:function(t){},rawOutput:function(t){},nextValidRid:function(t){},send:function(t){if(null!==t){if("function"==typeof t.sort)for(var e=0;e=0&&this.addHandlers.splice(e,1)},registerSASLMechanisms:function(t){this.mechanisms={},t=t||[a.SASLAnonymous,a.SASLExternal,a.SASLMD5,a.SASLOAuthBearer,a.SASLPlain,a.SASLSHA1],t.forEach(this.registerSASLMechanism.bind(this))},registerSASLMechanism:function(t){this.mechanisms[t.prototype.name]=t},disconnect:function(t){if(this._changeConnectStatus(a.Status.DISCONNECTING,t),a.info("Disconnect was called because: "+t),this.connected){var e=!1;this.disconnecting=!0,this.authenticated&&(e=o({xmlns:a.NS.CLIENT,type:"unavailable"})),this._disconnectTimeout=this._addSysTimedHandler(3e3,this._onDisconnectTimeout.bind(this)),this._proto._disconnect(e)}else a.info("Disconnect was called before Strophe connected to the server"),this._proto._abortAllRequests(),this._doDisconnect()},_changeConnectStatus:function(t,e){for(var n in a._connectionPlugins)if(a._connectionPlugins.hasOwnProperty(n)){var i=this[n];if(i.statusChanged)try{i.statusChanged(t,e)}catch(t){a.error(""+n+" plugin caused an exception changing status: "+t)}}if(this.connect_callback)try{this.connect_callback(t,e)}catch(t){a._handleError(t),a.error("User connection callback caused an exception: "+t)}},_doDisconnect:function(t){"number"==typeof this._idleTimeout&&clearTimeout(this._idleTimeout),null!==this._disconnectTimeout&&(this.deleteTimedHandler(this._disconnectTimeout),this._disconnectTimeout=null),a.info("_doDisconnect was called"),this._proto._doDisconnect(),this.authenticated=!1,this.disconnecting=!1,this.restored=!1,this.handlers=[],this.timedHandlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this._changeConnectStatus(a.Status.DISCONNECTED,t),this.connected=!1},_dataRecv:function(t,e){a.info("_dataRecv called");var n=this._proto._reqToData(t);if(null!==n){this.xmlInput!==a.Connection.prototype.xmlInput&&(n.nodeName===this._proto.strip&&n.childNodes.length?this.xmlInput(n.childNodes[0]):this.xmlInput(n)),this.rawInput!==a.Connection.prototype.rawInput&&(e?this.rawInput(e):this.rawInput(a.serialize(n)));for(var i,s;this.removeHandlers.length>0;)s=this.removeHandlers.pop(),i=this.handlers.indexOf(s),i>=0&&this.handlers.splice(i,1);for(;this.addHandlers.length>0;)this.handlers.push(this.addHandlers.pop());if(this.disconnecting&&this._proto._emptyQueue())return void this._doDisconnect();var r,o,h=n.getAttribute("type");if(null!==h&&"terminate"===h){if(this.disconnecting)return;return r=n.getAttribute("condition"),o=n.getElementsByTagName("conflict"),null!==r?("remote-stream-error"===r&&o.length>0&&(r="conflict"),this._changeConnectStatus(a.Status.CONNFAIL,r)):this._changeConnectStatus(a.Status.CONNFAIL,"unknown"),void this._doDisconnect(r)}var c=this;a.forEachChild(n,null,function(t){var e,n;for(n=c.handlers,c.handlers=[],e=0;e0:i.getElementsByTagName("stream:features").length>0||i.getElementsByTagName("features").length>0,!r)return void this._proto._no_auth_received(e);var o,h,c=[],u=i.getElementsByTagName("mechanism");if(u.length>0)for(o=0;ot[i].prototype.priority&&(i=n);i!==e&&(s=t[e],t[e]=t[i],t[i]=s)}return t},_attemptSASLAuth:function(t){t=this.sortMechanismsByPriority(t||[]);var e=0,n=!1;for(e=0;e0&&(e="conflict"),this._changeConnectStatus(a.Status.AUTHFAIL,e),!1}var i,s=t.getElementsByTagName("bind");return s.length>0?(i=s[0].getElementsByTagName("jid"),void(i.length>0&&(this.jid=a.getText(i[0]),this.do_session?(this._addSysHandler(this._sasl_session_cb.bind(this),null,null,null,"_session_auth_2"),this.send(r({type:"set",id:"_session_auth_2"}).c("session",{xmlns:a.NS.SESSION}).tree())):(this.authenticated=!0,this._changeConnectStatus(a.Status.CONNECTED,null))))):(a.info("SASL binding failed."),this._changeConnectStatus(a.Status.AUTHFAIL,null),!1)},_sasl_session_cb:function(t){if("result"===t.getAttribute("type"))this.authenticated=!0,this._changeConnectStatus(a.Status.CONNECTED,null);else if("error"===t.getAttribute("type"))return a.info("Session creation failed."),this._changeConnectStatus(a.Status.AUTHFAIL,null),!1;return!1},_sasl_failure_cb:function(t){return this._sasl_success_handler&&(this.deleteHandler(this._sasl_success_handler),this._sasl_success_handler=null),this._sasl_challenge_handler&&(this.deleteHandler(this._sasl_challenge_handler),this._sasl_challenge_handler=null),this._sasl_mechanism&&this._sasl_mechanism.onFailure(),this._changeConnectStatus(a.Status.AUTHFAIL,null),!1},_auth2_cb:function(t){return"result"===t.getAttribute("type")?(this.authenticated=!0,this._changeConnectStatus(a.Status.CONNECTED,null)):"error"===t.getAttribute("type")&&(this._changeConnectStatus(a.Status.AUTHFAIL,null),this.disconnect("authentication failed")),!1},_addSysTimedHandler:function(t,e){var n=new a.TimedHandler(t,e);return n.user=!1,this.addTimeds.push(n),n},_addSysHandler:function(t,e,n,i,s){var r=new a.Handler(t,e,n,i,s);return r.user=!1,this.addHandlers.push(r),r},_onDisconnectTimeout:function(){return a.info("_onDisconnectTimeout was called"),this._changeConnectStatus(a.Status.CONNTIMEOUT,null),this._proto._onDisconnectTimeout(),this._doDisconnect(),!1},_onIdle:function(){for(var t,e,n,i;this.addTimeds.length>0;)this.timedHandlers.push(this.addTimeds.pop());for(;this.removeTimeds.length>0;)e=this.removeTimeds.pop(),t=this.timedHandlers.indexOf(e),t>=0&&this.timedHandlers.splice(t,1);var s=(new Date).getTime();for(i=[],t=0;t0&&(n="conflict"),this._conn._changeConnectStatus(t.Status.CONNFAIL,n)):this._conn._changeConnectStatus(t.Status.CONNFAIL,"unknown"),this._conn._doDisconnect(n),t.Status.CONNFAIL;this.sid||(this.sid=e.getAttribute("sid"));var r=e.getAttribute("requests");r&&(this.window=parseInt(r,10));var o=e.getAttribute("hold");o&&(this.hold=parseInt(o,10));var a=e.getAttribute("wait");a&&(this.wait=parseInt(a,10));var h=e.getAttribute("inactivity");h&&(this.inactivity=parseInt(h,10))},_disconnect:function(t){this._sendTerminate(t)},_doDisconnect:function(){this.sid=null,this.rid=Math.floor(4294967295*Math.random()),this._conn._sessionCachingSupported()&&window.sessionStorage.removeItem("strophe-bosh-session"),this._conn.nextValidRid(this.rid)},_emptyQueue:function(){return 0===this._requests.length},_callProtocolErrorHandlers:function(t){var e,n=this._getRequestStatus(t);e=this._conn.protocolErrorHandlers.HTTP[n],e&&e.call(this,n)},_hitError:function(e){this.errors++,t.warn("request errored, status: "+e+", number of errors: "+this.errors),this.errors>4&&this._conn._onDisconnectTimeout()},_no_auth_received:function(e){e=e?e.bind(this._conn):this._conn._connect_cb.bind(this._conn);var n=this._buildBody();this._requests.push(new t.Request(n.tree(),this._onRequestStateChange.bind(this,e.bind(this._conn)),n.tree().getAttribute("rid"))),this._throttledRequestHandler()},_onDisconnectTimeout:function(){this._abortAllRequests()},_abortAllRequests:function(){for(var t;this._requests.length>0;)t=this._requests.pop(),t.abort=!0,t.xhr.abort(),t.xhr.onreadystatechange=function(){}},_onIdle:function(){var e=this._conn._data;if(this._conn.authenticated&&0===this._requests.length&&0===e.length&&!this._conn.disconnecting&&(t.info("no requests during idle cycle, sending blank request"),e.push(null)),!this._conn.paused){if(this._requests.length<2&&e.length>0){for(var n=this._buildBody(),i=0;i0){var s=this._requests[0].age();null!==this._requests[0].dead&&this._requests[0].timeDead()>Math.floor(t.SECONDARY_TIMEOUT*this.wait)&&this._throttledRequestHandler(),s>Math.floor(t.TIMEOUT*this.wait)&&(t.warn("Request "+this._requests[0].id+" timed out, over "+Math.floor(t.TIMEOUT*this.wait)+" seconds since last activity"),this._throttledRequestHandler())}}},_getRequestStatus:function(e,n){var i;if(4===e.xhr.readyState)try{i=e.xhr.status}catch(e){t.error("Caught an error while retrieving a request's status, reqStatus: "+i)}return"undefined"==typeof i&&(i="number"==typeof n?n:0),i},_onRequestStateChange:function(e,n){if(t.debug("request id "+n.id+"."+n.sends+" state changed to "+n.xhr.readyState),n.abort)return void(n.abort=!1);if(4===n.xhr.readyState){var i=this._getRequestStatus(n);if(this.disconnecting&&i>=400)return this._hitError(i),void this._callProtocolErrorHandlers(n);if((i>0&&i<500||n.sends>5)&&(this._removeRequest(n),t.debug("request id "+n.id+" should now be removed")),200===i){var s=this._requests[0]===n,r=this._requests[1]===n;(r||s&&this._requests.length>0&&this._requests[0].age()>Math.floor(t.SECONDARY_TIMEOUT*this.wait))&&this._restartRequest(0),this._conn.nextValidRid(Number(n.rid)+1),t.debug("request id "+n.id+"."+n.sends+" got 200"),e(n),this.errors=0}else 0===i||i>=400&&i<600||i>=12e3?(t.error("request id "+n.id+"."+n.sends+" error "+i+" happened"),this._hitError(i),this._callProtocolErrorHandlers(n),i>=400&&i<500&&(this._conn._changeConnectStatus(t.Status.DISCONNECTING,null),this._conn._doDisconnect())):t.error("request id "+n.id+"."+n.sends+" error "+i+" happened");i>0&&i<500&&!(n.sends>5)||this._throttledRequestHandler()}},_processRequest:function(e){var n=this,i=this._requests[e],s=this._getRequestStatus(i,-1);if(i.sends>this._conn.maxRetries)return void this._conn._onDisconnectTimeout();var r=i.age(),o=!isNaN(r)&&r>Math.floor(t.TIMEOUT*this.wait),a=null!==i.dead&&i.timeDead()>Math.floor(t.SECONDARY_TIMEOUT*this.wait),h=4===i.xhr.readyState&&(s<1||s>=500);if((o||a||h)&&(a&&t.error("Request "+this._requests[e].id+" timed out (secondary), restarting"),i.abort=!0,i.xhr.abort(),i.xhr.onreadystatechange=function(){},this._requests[e]=new t.Request(i.xmlData,i.origFunc,i.rid,i.sends),i=this._requests[e]),0===i.xhr.readyState){t.debug("request id "+i.id+"."+i.sends+" posting");try{var c=this._conn.options.contentType||"text/xml; charset=utf-8";i.xhr.open("POST",this._conn.service,!this._conn.options.sync),"undefined"!=typeof i.xhr.setRequestHeader&&i.xhr.setRequestHeader("Content-Type",c),this._conn.options.withCredentials&&(i.xhr.withCredentials=!0)}catch(e){return t.error("XHR open failed."),this._conn.connected||this._conn._changeConnectStatus(t.Status.CONNFAIL,"bad-service"),void this._conn.disconnect()}var u=function(){if(i.date=new Date,n._conn.options.customHeaders){var t=n._conn.options.customHeaders;for(var e in t)t.hasOwnProperty(e)&&i.xhr.setRequestHeader(e,t[e])}i.xhr.send(i.data)};if(i.sends>1){var l=1e3*Math.min(Math.floor(t.TIMEOUT*this.wait),Math.pow(i.sends,3));setTimeout(function(){u()},l)}else u();i.sends++,this._conn.xmlOutput!==t.Connection.prototype.xmlOutput&&(i.xmlData.nodeName===this.strip&&i.xmlData.childNodes.length?this._conn.xmlOutput(i.xmlData.childNodes[0]):this._conn.xmlOutput(i.xmlData)),this._conn.rawOutput!==t.Connection.prototype.rawOutput&&this._conn.rawOutput(i.data)}else t.debug("_processRequest: "+(0===e?"first":"second")+" request has readyState of "+i.xhr.readyState)},_removeRequest:function(e){t.debug("removing request");var n;for(n=this._requests.length-1;n>=0;n--)e===this._requests[n]&&this._requests.splice(n,1);e.xhr.onreadystatechange=function(){},this._throttledRequestHandler()},_restartRequest:function(t){var e=this._requests[t];null===e.dead&&(e.dead=new Date),this._processRequest(t)},_reqToData:function(t){try{return t.getResponse()}catch(t){if("parsererror"!==t)throw t;this._conn.disconnect("strophe-parsererror")}},_sendTerminate:function(e){t.info("_sendTerminate was called");var n=this._buildBody().attrs({type:"terminate"});e&&n.cnode(e.tree());var i=new t.Request(n.tree(),this._onRequestStateChange.bind(this,this._conn._dataRecv.bind(this._conn)),n.tree().getAttribute("rid"));this._requests.push(i),this._throttledRequestHandler()},_send:function(){clearTimeout(this._conn._idleTimeout),this._throttledRequestHandler(),this._conn._idleTimeout=setTimeout(function(){this._onIdle()}.bind(this._conn),100)},_sendRestart:function(){this._throttledRequestHandler(),clearTimeout(this._conn._idleTimeout)},_throttledRequestHandler:function(){this._requests?t.debug("_throttledRequestHandler called with "+this._requests.length+" requests"):t.debug("_throttledRequestHandler called with undefined requests"),this._requests&&0!==this._requests.length&&(this._requests.length>0&&this._processRequest(0),this._requests.length>1&&Math.abs(this._requests[0].rid-this._requests[1].rid): "+i);var s=e.getAttribute("version");return"string"!=typeof s?n="Missing version in ":"1.0"!==s&&(n="Wrong version in : "+s),!n||(this._conn._changeConnectStatus(t.Status.CONNFAIL,n),this._conn._doDisconnect(),!1)},_connect_cb_wrapper:function(e){if(0===e.data.indexOf("\s*)*/,"");if(""===n)return;var i=(new DOMParser).parseFromString(n,"text/xml").documentElement;this._conn.xmlInput(i),this._conn.rawInput(e.data),this._handleStreamStart(i)&&this._connect_cb(i)}else if(0===e.data.indexOf(" tag.")}}this._conn._doDisconnect()},_doDisconnect:function(){t.info("WebSockets _doDisconnect was called"),this._closeSocket()},_streamWrap:function(t){return""+t+""},_closeSocket:function(){if(this.socket)try{this.socket.close()}catch(t){}this.socket=null},_emptyQueue:function(){return!0},_onClose:function(){this._conn.connected&&!this._conn.disconnecting?(t.error("Websocket closed unexpectedly"),this._conn._doDisconnect()):t.info("Websocket closed")},_no_auth_received:function(e){t.error("Server did not send any auth methods"),this._conn._changeConnectStatus(t.Status.CONNFAIL,"Server did not send any auth methods"),e&&(e=e.bind(this._conn))(),this._conn._doDisconnect()},_onDisconnectTimeout:function(){},_abortAllRequests:function(){},_onError:function(e){t.error("Websocket error "+e),this._conn._changeConnectStatus(t.Status.CONNFAIL,"The WebSocket connection could not be established or was disconnected."),this._disconnect()},_onIdle:function(){var e=this._conn._data;if(e.length>0&&!this._conn.paused){for(var n=0;n