*@
\ No newline at end of file
diff --git a/LLV/Views/Home/Parametro.cshtml b/LLV/Views/Home/Parametro.cshtml
new file mode 100644
index 0000000..8fcff0a
--- /dev/null
+++ b/LLV/Views/Home/Parametro.cshtml
@@ -0,0 +1,10 @@
+@*@{
+ ViewBag.BreadCrumbPagina = "Parâmetros do Sistema";
+ ViewBag.TituloPagina = "Configuração de Parâmetros do Sistema";
+}*@
+@**@
+
+
+
+
+
\ No newline at end of file
diff --git a/LLV/Views/OrdemServico/Index.cshtml b/LLV/Views/OrdemServico/Index.cshtml
new file mode 100644
index 0000000..d8dabb8
--- /dev/null
+++ b/LLV/Views/OrdemServico/Index.cshtml
@@ -0,0 +1,20 @@
+
+
\ No newline at end of file
diff --git a/LLV/scripts/App/View/NavigationUser.html b/LLV/scripts/App/View/NavigationUser.html
new file mode 100644
index 0000000..b26acb5
--- /dev/null
+++ b/LLV/scripts/App/View/NavigationUser.html
@@ -0,0 +1,12 @@
+
\ No newline at end of file
diff --git a/LLV/scripts/App/View/edit-button.html b/LLV/scripts/App/View/edit-button.html
new file mode 100644
index 0000000..307209e
--- /dev/null
+++ b/LLV/scripts/App/View/edit-button.html
@@ -0,0 +1,5 @@
+
+
+
\ No newline at end of file
diff --git a/LLV/scripts/ai.0.15.0-build58334.js b/LLV/scripts/ai.0.15.0-build58334.js
new file mode 100644
index 0000000..65120f7
--- /dev/null
+++ b/LLV/scripts/ai.0.15.0-build58334.js
@@ -0,0 +1,2646 @@
+var Microsoft;
+(function (Microsoft) {
+ var ApplicationInsights;
+ (function (ApplicationInsights) {
+ (function (LoggingSeverity) {
+ LoggingSeverity[LoggingSeverity["CRITICAL"] = 0] = "CRITICAL";
+ LoggingSeverity[LoggingSeverity["WARNING"] = 1] = "WARNING";
+ })(ApplicationInsights.LoggingSeverity || (ApplicationInsights.LoggingSeverity = {}));
+ var LoggingSeverity = ApplicationInsights.LoggingSeverity;
+ var _InternalLogging = (function () {
+ function _InternalLogging() {
+ }
+ _InternalLogging.throwInternalNonUserActionable = function (severity, message) {
+ if (this.enableDebugExceptions()) {
+ throw message;
+ }
+ else {
+ this.warnToConsole(message);
+ this.logInternalMessage(severity, this.AiNonUserActionablePrefix + message);
+ }
+ };
+ _InternalLogging.throwInternalUserActionable = function (severity, message) {
+ if (this.enableDebugExceptions()) {
+ throw message;
+ }
+ else {
+ this.warnToConsole(message);
+ this.logInternalMessage(severity, this.AiUserActionablePrefix + message);
+ }
+ };
+ _InternalLogging.warnToConsole = function (message) {
+ if (typeof console !== "undefined" && !!console) {
+ if (typeof console.warn === "function") {
+ console.warn(message);
+ }
+ else if (typeof console.log === "function") {
+ console.log(message);
+ }
+ }
+ };
+ _InternalLogging.resetInternalMessageCount = function () {
+ this._messageCount = 0;
+ };
+ _InternalLogging.setMaxInternalMessageLimit = function (limit) {
+ if (!limit) {
+ throw new Error('limit cannot be undefined.');
+ }
+ this.MAX_INTERNAL_MESSAGE_LIMIT = limit;
+ };
+ _InternalLogging.logInternalMessage = function (severity, message) {
+ if (this._areInternalMessagesThrottled()) {
+ return;
+ }
+ if (this.verboseLogging() || severity === 0 /* CRITICAL */) {
+ this.queue.push(message);
+ this._messageCount++;
+ }
+ if (this._messageCount == this.MAX_INTERNAL_MESSAGE_LIMIT) {
+ var throttleLimitMessage = this.AiNonUserActionablePrefix + "Internal events throttle limit per PageView reached for this app.";
+ this.queue.push(throttleLimitMessage);
+ this.warnToConsole(throttleLimitMessage);
+ }
+ };
+ _InternalLogging._areInternalMessagesThrottled = function () {
+ return this._messageCount >= this.MAX_INTERNAL_MESSAGE_LIMIT;
+ };
+ _InternalLogging.AiUserActionablePrefix = "AI: ";
+ _InternalLogging.AiNonUserActionablePrefix = "AI (Internal): ";
+ _InternalLogging.enableDebugExceptions = function () { return false; };
+ _InternalLogging.verboseLogging = function () { return false; };
+ _InternalLogging.queue = [];
+ _InternalLogging.MAX_INTERNAL_MESSAGE_LIMIT = 25;
+ _InternalLogging._messageCount = 0;
+ return _InternalLogging;
+ })();
+ ApplicationInsights._InternalLogging = _InternalLogging;
+ })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
+})(Microsoft || (Microsoft = {}));
+var Microsoft;
+(function (Microsoft) {
+ var ApplicationInsights;
+ (function (ApplicationInsights) {
+ var Util = (function () {
+ function Util() {
+ }
+ Util._getStorageObject = function () {
+ try {
+ if (window.localStorage) {
+ return window.localStorage;
+ }
+ else {
+ return null;
+ }
+ }
+ catch (e) {
+ ApplicationInsights._InternalLogging.warnToConsole('Failed to get client localStorage: ' + e.message);
+ return null;
+ }
+ };
+ Util.canUseLocalStorage = function () {
+ return !!Util._getStorageObject();
+ };
+ Util.getStorage = function (name) {
+ var storage = Util._getStorageObject();
+ if (storage !== null) {
+ try {
+ return storage.getItem(name);
+ }
+ catch (e) {
+ ApplicationInsights._InternalLogging.throwInternalNonUserActionable(1 /* WARNING */, "Browser failed read of local storage." + Util.dump(e));
+ }
+ }
+ return null;
+ };
+ Util.setStorage = function (name, data) {
+ var storage = Util._getStorageObject();
+ if (storage !== null) {
+ try {
+ storage.setItem(name, data);
+ return true;
+ }
+ catch (e) {
+ ApplicationInsights._InternalLogging.throwInternalNonUserActionable(1 /* WARNING */, "Browser failed write to local storage." + Util.dump(e));
+ }
+ }
+ return false;
+ };
+ Util.removeStorage = function (name) {
+ var storage = Util._getStorageObject();
+ if (storage !== null) {
+ try {
+ storage.removeItem(name);
+ return true;
+ }
+ catch (e) {
+ ApplicationInsights._InternalLogging.throwInternalNonUserActionable(1 /* WARNING */, "Browser failed removal of local storage item." + Util.dump(e));
+ }
+ }
+ return false;
+ };
+ Util._getSessionStorageObject = function () {
+ try {
+ if (window.sessionStorage) {
+ return window.sessionStorage;
+ }
+ else {
+ return null;
+ }
+ }
+ catch (e) {
+ ApplicationInsights._InternalLogging.warnToConsole('Failed to get client session storage: ' + e.message);
+ return null;
+ }
+ };
+ Util.canUseSessionStorage = function () {
+ return !!Util._getSessionStorageObject();
+ };
+ Util.getSessionStorage = function (name) {
+ var storage = Util._getSessionStorageObject();
+ if (storage !== null) {
+ try {
+ return storage.getItem(name);
+ }
+ catch (e) {
+ ApplicationInsights._InternalLogging.throwInternalNonUserActionable(0 /* CRITICAL */, "Browser failed read of session storage." + Util.dump(e));
+ }
+ }
+ return null;
+ };
+ Util.setSessionStorage = function (name, data) {
+ var storage = Util._getSessionStorageObject();
+ if (storage !== null) {
+ try {
+ storage.setItem(name, data);
+ return true;
+ }
+ catch (e) {
+ ApplicationInsights._InternalLogging.throwInternalNonUserActionable(0 /* CRITICAL */, "Browser failed write to session storage." + Util.dump(e));
+ }
+ }
+ return false;
+ };
+ Util.removeSessionStorage = function (name) {
+ var storage = Util._getSessionStorageObject();
+ if (storage !== null) {
+ try {
+ storage.removeItem(name);
+ return true;
+ }
+ catch (e) {
+ ApplicationInsights._InternalLogging.throwInternalNonUserActionable(0 /* CRITICAL */, "Browser failed removal of session storage item." + Util.dump(e));
+ }
+ }
+ return false;
+ };
+ Util.setCookie = function (name, value) {
+ Util.document.cookie = name + "=" + value + ";path=/";
+ };
+ Util.stringToBoolOrDefault = function (str) {
+ if (!str) {
+ return false;
+ }
+ return str.toString().toLowerCase() === "true";
+ };
+ Util.getCookie = function (name) {
+ var value = "";
+ if (name && name.length) {
+ var cookieName = name + "=";
+ var cookies = Util.document.cookie.split(";");
+ for (var i = 0; i < cookies.length; i++) {
+ var cookie = cookies[i];
+ cookie = Util.trim(cookie);
+ if (cookie && cookie.indexOf(cookieName) === 0) {
+ value = cookie.substring(cookieName.length, cookies[i].length);
+ break;
+ }
+ }
+ }
+ return value;
+ };
+ Util.deleteCookie = function (name) {
+ Util.document.cookie = name + "=;path=/;expires=Thu, 01 Jan 1970 00:00:01 GMT;";
+ };
+ Util.trim = function (str) {
+ if (typeof str !== "string")
+ return str;
+ return str.replace(/^\s+|\s+$/g, "");
+ };
+ Util.newGuid = function () {
+ var hexValues = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"];
+ var oct = "", tmp;
+ for (var a = 0; a < 4; a++) {
+ tmp = (4294967296 * Math.random()) | 0;
+ oct += hexValues[tmp & 0xF] + hexValues[tmp >> 4 & 0xF] + hexValues[tmp >> 8 & 0xF] + hexValues[tmp >> 12 & 0xF] + hexValues[tmp >> 16 & 0xF] + hexValues[tmp >> 20 & 0xF] + hexValues[tmp >> 24 & 0xF] + hexValues[tmp >> 28 & 0xF];
+ }
+ var clockSequenceHi = hexValues[8 + (Math.random() * 4) | 0];
+ return oct.substr(0, 8) + "-" + oct.substr(9, 4) + "-4" + oct.substr(13, 3) + "-" + clockSequenceHi + oct.substr(16, 3) + "-" + oct.substr(19, 12);
+ };
+ Util.isArray = function (obj) {
+ return Object.prototype.toString.call(obj) === "[object Array]";
+ };
+ Util.isError = function (obj) {
+ return Object.prototype.toString.call(obj) === "[object Error]";
+ };
+ Util.isDate = function (obj) {
+ return Object.prototype.toString.call(obj) === "[object Date]";
+ };
+ Util.toISOStringForIE8 = function (date) {
+ if (Util.isDate(date)) {
+ if (Date.prototype.toISOString) {
+ return date.toISOString();
+ }
+ else {
+ function pad(number) {
+ var r = String(number);
+ if (r.length === 1) {
+ r = "0" + r;
+ }
+ return r;
+ }
+ return date.getUTCFullYear() + "-" + pad(date.getUTCMonth() + 1) + "-" + pad(date.getUTCDate()) + "T" + pad(date.getUTCHours()) + ":" + pad(date.getUTCMinutes()) + ":" + pad(date.getUTCSeconds()) + "." + String((date.getUTCMilliseconds() / 1000).toFixed(3)).slice(2, 5) + "Z";
+ }
+ }
+ };
+ Util.msToTimeSpan = function (totalms) {
+ if (isNaN(totalms) || totalms < 0) {
+ totalms = 0;
+ }
+ var ms = "" + totalms % 1000;
+ var sec = "" + Math.floor(totalms / 1000) % 60;
+ var min = "" + Math.floor(totalms / (1000 * 60)) % 60;
+ var hour = "" + Math.floor(totalms / (1000 * 60 * 60)) % 24;
+ ms = ms.length === 1 ? "00" + ms : ms.length === 2 ? "0" + ms : ms;
+ sec = sec.length < 2 ? "0" + sec : sec;
+ min = min.length < 2 ? "0" + min : min;
+ hour = hour.length < 2 ? "0" + hour : hour;
+ return hour + ":" + min + ":" + sec + "." + ms;
+ };
+ Util.isCrossOriginError = function (message, url, lineNumber, columnNumber, error) {
+ return (message == "Script error." || message == "Script error") && url == "" && lineNumber == 0 && columnNumber == 0 && error == null;
+ };
+ Util.dump = function (object) {
+ var objectTypeDump = Object.prototype.toString.call(object);
+ var propertyValueDump = JSON.stringify(object);
+ if (objectTypeDump === "[object Error]") {
+ propertyValueDump = "{ stack: '" + object.stack + "', message: '" + object.message + "', name: '" + object.name + "'";
+ }
+ return objectTypeDump + propertyValueDump;
+ };
+ Util.addEventHandler = function (eventName, callback) {
+ if (!window || typeof eventName !== 'string' || typeof callback !== 'function') {
+ return false;
+ }
+ var verbEventName = 'on' + eventName;
+ if (window.addEventListener) {
+ window.addEventListener(eventName, callback, false);
+ }
+ else if (window.attachEvent) {
+ window.attachEvent(verbEventName, callback);
+ }
+ else {
+ return false;
+ }
+ return true;
+ };
+ Util.document = typeof document !== "undefined" ? document : {};
+ Util.NotSpecified = "not_specified";
+ return Util;
+ })();
+ ApplicationInsights.Util = Util;
+ })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
+})(Microsoft || (Microsoft = {}));
+var Microsoft;
+(function (Microsoft) {
+ var ApplicationInsights;
+ (function (ApplicationInsights) {
+ "use strict";
+ var Serializer = (function () {
+ function Serializer() {
+ }
+ Serializer.serialize = function (input) {
+ var output = Serializer._serializeObject(input, "root");
+ return JSON.stringify(output);
+ };
+ Serializer._serializeObject = function (source, name) {
+ var circularReferenceCheck = "__aiCircularRefCheck";
+ var output = {};
+ if (!source) {
+ ApplicationInsights._InternalLogging.throwInternalUserActionable(0 /* CRITICAL */, "cannot serialize " + name + " because it is null or undefined");
+ return output;
+ }
+ if (source[circularReferenceCheck]) {
+ ApplicationInsights._InternalLogging.throwInternalUserActionable(1 /* WARNING */, "Circular reference detected while serializing: '" + name);
+ return output;
+ }
+ if (!source.aiDataContract) {
+ if (name === "measurements") {
+ output = Serializer._serializeStringMap(source, "number", name);
+ }
+ else if (name === "properties") {
+ output = Serializer._serializeStringMap(source, "string", name);
+ }
+ else if (name === "tags") {
+ output = Serializer._serializeStringMap(source, "string", name);
+ }
+ else if (ApplicationInsights.Util.isArray(source)) {
+ output = Serializer._serializeArray(source, name);
+ }
+ else {
+ ApplicationInsights._InternalLogging.throwInternalUserActionable(1 /* WARNING */, "Attempting to serialize an object which does not implement ISerializable: " + name);
+ try {
+ JSON.stringify(source);
+ output = source;
+ }
+ catch (e) {
+ ApplicationInsights._InternalLogging.throwInternalUserActionable(0 /* CRITICAL */, e && typeof e.toString === 'function' ? e.toString() : "Error serializing object");
+ }
+ }
+ return output;
+ }
+ source[circularReferenceCheck] = true;
+ for (var field in source.aiDataContract) {
+ var isRequired = source.aiDataContract[field];
+ var isArray = typeof isRequired !== "boolean";
+ var isPresent = source[field] !== undefined;
+ var isObject = typeof source[field] === "object" && source[field] !== null;
+ if (isRequired && !isPresent && !isArray) {
+ ApplicationInsights._InternalLogging.throwInternalNonUserActionable(0 /* CRITICAL */, "Missing required field specification: The field '" + field + "' on '" + name + "' is required but not present on source");
+ continue;
+ }
+ var value;
+ if (isObject) {
+ if (isArray) {
+ value = Serializer._serializeArray(source[field], field);
+ }
+ else {
+ value = Serializer._serializeObject(source[field], field);
+ }
+ }
+ else {
+ value = source[field];
+ }
+ if (value !== undefined) {
+ output[field] = value;
+ }
+ }
+ delete source[circularReferenceCheck];
+ return output;
+ };
+ Serializer._serializeArray = function (sources, name) {
+ var output = undefined;
+ if (!!sources) {
+ if (!ApplicationInsights.Util.isArray(sources)) {
+ ApplicationInsights._InternalLogging.throwInternalUserActionable(0 /* CRITICAL */, "This field was specified as an array in the contract but the item is not an array.\r\n" + name);
+ }
+ else {
+ output = [];
+ for (var i = 0; i < sources.length; i++) {
+ var source = sources[i];
+ var item = Serializer._serializeObject(source, name + "[" + i + "]");
+ output.push(item);
+ }
+ }
+ }
+ return output;
+ };
+ Serializer._serializeStringMap = function (map, expectedType, name) {
+ var output = undefined;
+ if (map) {
+ output = {};
+ for (var field in map) {
+ var value = map[field];
+ if (expectedType === "string") {
+ if (value === undefined) {
+ output[field] = "undefined";
+ }
+ else if (value === null) {
+ output[field] = "null";
+ }
+ else if (!value.toString) {
+ output[field] = "invalid field: toString() is not defined.";
+ }
+ else {
+ output[field] = value.toString();
+ }
+ }
+ else if (expectedType === "number") {
+ if (value === undefined) {
+ output[field] = "undefined";
+ }
+ else if (value === null) {
+ output[field] = "null";
+ }
+ else {
+ var num = parseFloat(value);
+ if (isNaN(num)) {
+ output[field] = "NaN";
+ }
+ else {
+ output[field] = num;
+ }
+ }
+ }
+ else {
+ output[field] = "invalid field: " + name + " is of unknown type.";
+ ApplicationInsights._InternalLogging.throwInternalUserActionable(0 /* CRITICAL */, output[field]);
+ }
+ }
+ }
+ return output;
+ };
+ return Serializer;
+ })();
+ ApplicationInsights.Serializer = Serializer;
+ })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
+})(Microsoft || (Microsoft = {}));
+var Microsoft;
+(function (Microsoft) {
+ var Telemetry;
+ (function (Telemetry) {
+ "use strict";
+ var Base = (function () {
+ function Base() {
+ }
+ return Base;
+ })();
+ Telemetry.Base = Base;
+ })(Telemetry = Microsoft.Telemetry || (Microsoft.Telemetry = {}));
+})(Microsoft || (Microsoft = {}));
+var Microsoft;
+(function (Microsoft) {
+ var Telemetry;
+ (function (Telemetry) {
+ "use strict";
+ var Envelope = (function () {
+ function Envelope() {
+ this.ver = 1;
+ this.sampleRate = 100.0;
+ this.tags = {};
+ }
+ return Envelope;
+ })();
+ Telemetry.Envelope = Envelope;
+ })(Telemetry = Microsoft.Telemetry || (Microsoft.Telemetry = {}));
+})(Microsoft || (Microsoft = {}));
+var __extends = this.__extends || function (d, b) {
+ for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
+ function __() { this.constructor = d; }
+ __.prototype = b.prototype;
+ d.prototype = new __();
+};
+var Microsoft;
+(function (Microsoft) {
+ var ApplicationInsights;
+ (function (ApplicationInsights) {
+ var Telemetry;
+ (function (Telemetry) {
+ var Common;
+ (function (Common) {
+ "use strict";
+ var Envelope = (function (_super) {
+ __extends(Envelope, _super);
+ function Envelope(data, name) {
+ _super.call(this);
+ this.name = name;
+ this.data = data;
+ this.time = ApplicationInsights.Util.toISOStringForIE8(new Date());
+ this.aiDataContract = {
+ time: true,
+ iKey: true,
+ name: true,
+ tags: true,
+ data: true
+ };
+ }
+ return Envelope;
+ })(Microsoft.Telemetry.Envelope);
+ Common.Envelope = Envelope;
+ })(Common = Telemetry.Common || (Telemetry.Common = {}));
+ })(Telemetry = ApplicationInsights.Telemetry || (ApplicationInsights.Telemetry = {}));
+ })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
+})(Microsoft || (Microsoft = {}));
+var Microsoft;
+(function (Microsoft) {
+ var ApplicationInsights;
+ (function (ApplicationInsights) {
+ var Telemetry;
+ (function (Telemetry) {
+ var Common;
+ (function (Common) {
+ "use strict";
+ var Base = (function (_super) {
+ __extends(Base, _super);
+ function Base() {
+ _super.apply(this, arguments);
+ this.aiDataContract = {};
+ }
+ return Base;
+ })(Microsoft.Telemetry.Base);
+ Common.Base = Base;
+ })(Common = Telemetry.Common || (Telemetry.Common = {}));
+ })(Telemetry = ApplicationInsights.Telemetry || (ApplicationInsights.Telemetry = {}));
+ })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
+})(Microsoft || (Microsoft = {}));
+var AI;
+(function (AI) {
+ "use strict";
+ var ContextTagKeys = (function () {
+ function ContextTagKeys() {
+ this.applicationVersion = "ai.application.ver";
+ this.applicationBuild = "ai.application.build";
+ this.applicationTypeId = "ai.application.typeId";
+ this.deviceId = "ai.device.id";
+ this.deviceIp = "ai.device.ip";
+ this.deviceLanguage = "ai.device.language";
+ this.deviceLocale = "ai.device.locale";
+ this.deviceModel = "ai.device.model";
+ this.deviceNetwork = "ai.device.network";
+ this.deviceNetworkName = "ai.device.networkName";
+ this.deviceOEMName = "ai.device.oemName";
+ this.deviceOS = "ai.device.os";
+ this.deviceOSVersion = "ai.device.osVersion";
+ this.deviceRoleInstance = "ai.device.roleInstance";
+ this.deviceRoleName = "ai.device.roleName";
+ this.deviceScreenResolution = "ai.device.screenResolution";
+ this.deviceType = "ai.device.type";
+ this.deviceMachineName = "ai.device.machineName";
+ this.deviceVMName = "ai.device.vmName";
+ this.locationIp = "ai.location.ip";
+ this.operationId = "ai.operation.id";
+ this.operationName = "ai.operation.name";
+ this.operationParentId = "ai.operation.parentId";
+ this.operationRootId = "ai.operation.rootId";
+ this.operationSyntheticSource = "ai.operation.syntheticSource";
+ this.operationIsSynthetic = "ai.operation.isSynthetic";
+ this.sessionId = "ai.session.id";
+ this.sessionIsFirst = "ai.session.isFirst";
+ this.sessionIsNew = "ai.session.isNew";
+ this.userAccountAcquisitionDate = "ai.user.accountAcquisitionDate";
+ this.userAccountId = "ai.user.accountId";
+ this.userAgent = "ai.user.userAgent";
+ this.userId = "ai.user.id";
+ this.userStoreRegion = "ai.user.storeRegion";
+ this.userAuthUserId = "ai.user.authUserId";
+ this.userAnonymousUserAcquisitionDate = "ai.user.anonUserAcquisitionDate";
+ this.userAuthenticatedUserAcquisitionDate = "ai.user.authUserAcquisitionDate";
+ this.sampleRate = "ai.sample.sampleRate";
+ this.internalSdkVersion = "ai.internal.sdkVersion";
+ this.internalAgentVersion = "ai.internal.agentVersion";
+ this.internalDataCollectorReceivedTime = "ai.internal.dataCollectorReceivedTime";
+ this.internalProfileId = "ai.internal.profileId";
+ this.internalProfileClassId = "ai.internal.profileClassId";
+ this.internalAccountId = "ai.internal.accountId";
+ this.internalApplicationName = "ai.internal.applicationName";
+ this.internalInstrumentationKey = "ai.internal.instrumentationKey";
+ this.internalTelemetryItemId = "ai.internal.telemetryItemId";
+ this.internalApplicationType = "ai.internal.applicationType";
+ this.internalRequestSource = "ai.internal.requestSource";
+ this.internalFlowType = "ai.internal.flowType";
+ this.internalIsAudit = "ai.internal.isAudit";
+ this.internalTrackingSourceId = "ai.internal.trackingSourceId";
+ this.internalTrackingType = "ai.internal.trackingType";
+ }
+ return ContextTagKeys;
+ })();
+ AI.ContextTagKeys = ContextTagKeys;
+})(AI || (AI = {}));
+var Microsoft;
+(function (Microsoft) {
+ var ApplicationInsights;
+ (function (ApplicationInsights) {
+ var Context;
+ (function (Context) {
+ "use strict";
+ var Application = (function () {
+ function Application() {
+ }
+ return Application;
+ })();
+ Context.Application = Application;
+ })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {}));
+ })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
+})(Microsoft || (Microsoft = {}));
+var Microsoft;
+(function (Microsoft) {
+ var ApplicationInsights;
+ (function (ApplicationInsights) {
+ var Context;
+ (function (Context) {
+ "use strict";
+ var Device = (function () {
+ function Device() {
+ this.id = "browser";
+ if (typeof screen !== "undefined" && screen.width && screen.height) {
+ this.resolution = screen.width + "X" + screen.height;
+ }
+ this.locale = (typeof screen !== "undefined" && navigator.browserLanguage) ? navigator.browserLanguage : "unknown";
+ }
+ return Device;
+ })();
+ Context.Device = Device;
+ })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {}));
+ })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
+})(Microsoft || (Microsoft = {}));
+var Microsoft;
+(function (Microsoft) {
+ var ApplicationInsights;
+ (function (ApplicationInsights) {
+ var Context;
+ (function (Context) {
+ "use strict";
+ var Internal = (function () {
+ function Internal() {
+ this.sdkVersion = "JavaScript:" + ApplicationInsights.Version;
+ }
+ return Internal;
+ })();
+ Context.Internal = Internal;
+ })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {}));
+ })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
+})(Microsoft || (Microsoft = {}));
+var Microsoft;
+(function (Microsoft) {
+ var ApplicationInsights;
+ (function (ApplicationInsights) {
+ var Context;
+ (function (Context) {
+ "use strict";
+ var Location = (function () {
+ function Location() {
+ }
+ return Location;
+ })();
+ Context.Location = Location;
+ })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {}));
+ })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
+})(Microsoft || (Microsoft = {}));
+var Microsoft;
+(function (Microsoft) {
+ var ApplicationInsights;
+ (function (ApplicationInsights) {
+ var Context;
+ (function (Context) {
+ "use strict";
+ var Operation = (function () {
+ function Operation() {
+ this.id = ApplicationInsights.Util.newGuid();
+ }
+ return Operation;
+ })();
+ Context.Operation = Operation;
+ })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {}));
+ })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
+})(Microsoft || (Microsoft = {}));
+var Microsoft;
+(function (Microsoft) {
+ var ApplicationInsights;
+ (function (ApplicationInsights) {
+ var SamplingScoreGenerator = (function () {
+ function SamplingScoreGenerator() {
+ }
+ SamplingScoreGenerator.getScore = function (envelope) {
+ var tagKeys = new AI.ContextTagKeys();
+ var score = 0;
+ if (envelope.tags[tagKeys.userId]) {
+ score = SamplingScoreGenerator.getSamplingHashCode(envelope.tags[tagKeys.userId]) / SamplingScoreGenerator.INT_MAX_VALUE;
+ }
+ else if (envelope.tags[tagKeys.operationId]) {
+ score = SamplingScoreGenerator.getSamplingHashCode(envelope.tags[tagKeys.operationId]) / SamplingScoreGenerator.INT_MAX_VALUE;
+ }
+ else {
+ score = Math.random();
+ }
+ return score * 100;
+ };
+ SamplingScoreGenerator.getSamplingHashCode = function (input) {
+ if (input == "") {
+ return 0;
+ }
+ var hash = 5381;
+ for (var i = 0; i < input.length; ++i) {
+ hash = ((hash << 5) + hash) + input.charCodeAt(i);
+ hash = hash & hash;
+ }
+ return Math.abs(hash);
+ };
+ SamplingScoreGenerator.INT_MAX_VALUE = 2147483647;
+ return SamplingScoreGenerator;
+ })();
+ ApplicationInsights.SamplingScoreGenerator = SamplingScoreGenerator;
+ })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
+})(Microsoft || (Microsoft = {}));
+var Microsoft;
+(function (Microsoft) {
+ var ApplicationInsights;
+ (function (ApplicationInsights) {
+ var Context;
+ (function (Context) {
+ "use strict";
+ var Sample = (function () {
+ function Sample(sampleRate) {
+ this.INT_MAX_VALUE = 2147483647;
+ if (sampleRate > 100 || sampleRate < 0) {
+ ApplicationInsights._InternalLogging.throwInternalUserActionable(1 /* WARNING */, "Sampling rate is out of range (0..100): '" + sampleRate + "'. Sampling will be disabled, you may be sending too much data which may affect your AI service level.");
+ this.sampleRate = 100;
+ }
+ this.sampleRate = sampleRate;
+ }
+ Sample.prototype.isSampledIn = function (envelope) {
+ if (this.sampleRate == 100)
+ return true;
+ var score = ApplicationInsights.SamplingScoreGenerator.getScore(envelope);
+ return score < this.sampleRate;
+ };
+ return Sample;
+ })();
+ Context.Sample = Sample;
+ })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {}));
+ })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
+})(Microsoft || (Microsoft = {}));
+var AI;
+(function (AI) {
+ "use strict";
+ (function (SessionState) {
+ SessionState[SessionState["Start"] = 0] = "Start";
+ SessionState[SessionState["End"] = 1] = "End";
+ })(AI.SessionState || (AI.SessionState = {}));
+ var SessionState = AI.SessionState;
+})(AI || (AI = {}));
+var Microsoft;
+(function (Microsoft) {
+ var ApplicationInsights;
+ (function (ApplicationInsights) {
+ var Context;
+ (function (Context) {
+ "use strict";
+ var Session = (function () {
+ function Session() {
+ }
+ return Session;
+ })();
+ Context.Session = Session;
+ var _SessionManager = (function () {
+ function _SessionManager(config, sessionHandler) {
+ if (!config) {
+ config = {};
+ }
+ if (!(typeof config.sessionExpirationMs === "function")) {
+ config.sessionExpirationMs = function () { return _SessionManager.acquisitionSpan; };
+ }
+ if (!(typeof config.sessionRenewalMs === "function")) {
+ config.sessionRenewalMs = function () { return _SessionManager.renewalSpan; };
+ }
+ this.config = config;
+ this._sessionHandler = sessionHandler;
+ this.automaticSession = new Session();
+ }
+ _SessionManager.prototype.update = function () {
+ if (!this.automaticSession.id) {
+ this.initializeAutomaticSession();
+ }
+ var now = +new Date;
+ var acquisitionExpired = now - this.automaticSession.acquisitionDate > this.config.sessionExpirationMs();
+ var renewalExpired = now - this.automaticSession.renewalDate > this.config.sessionRenewalMs();
+ if (acquisitionExpired || renewalExpired) {
+ if (typeof this._sessionHandler === "function") {
+ this._sessionHandler(1 /* End */, this.automaticSession.renewalDate);
+ }
+ this.automaticSession.isFirst = undefined;
+ this.renew();
+ }
+ else {
+ this.automaticSession.renewalDate = +new Date;
+ this.setCookie(this.automaticSession.id, this.automaticSession.acquisitionDate, this.automaticSession.renewalDate);
+ }
+ };
+ _SessionManager.prototype.backup = function () {
+ this.setStorage(this.automaticSession.id, this.automaticSession.acquisitionDate, this.automaticSession.renewalDate);
+ };
+ _SessionManager.prototype.initializeAutomaticSession = function () {
+ var cookie = ApplicationInsights.Util.getCookie('ai_session');
+ if (cookie && typeof cookie.split === "function") {
+ this.initializeAutomaticSessionWithData(cookie);
+ }
+ else {
+ var storage = ApplicationInsights.Util.getStorage('ai_session');
+ if (storage) {
+ this.initializeAutomaticSessionWithData(storage);
+ }
+ }
+ if (!this.automaticSession.id) {
+ this.automaticSession.isFirst = true;
+ this.renew();
+ }
+ };
+ _SessionManager.prototype.initializeAutomaticSessionWithData = function (sessionData) {
+ var params = sessionData.split("|");
+ if (params.length > 0) {
+ this.automaticSession.id = params[0];
+ }
+ try {
+ if (params.length > 1) {
+ var acq = +params[1];
+ this.automaticSession.acquisitionDate = +new Date(acq);
+ this.automaticSession.acquisitionDate = this.automaticSession.acquisitionDate > 0 ? this.automaticSession.acquisitionDate : 0;
+ }
+ if (params.length > 2) {
+ var renewal = +params[2];
+ this.automaticSession.renewalDate = +new Date(renewal);
+ this.automaticSession.renewalDate = this.automaticSession.renewalDate > 0 ? this.automaticSession.renewalDate : 0;
+ }
+ }
+ catch (e) {
+ ApplicationInsights._InternalLogging.throwInternalNonUserActionable(0 /* CRITICAL */, "Error parsing ai_session cookie, session will be reset: " + ApplicationInsights.Util.dump(e));
+ }
+ if (this.automaticSession.renewalDate == 0) {
+ ApplicationInsights._InternalLogging.throwInternalNonUserActionable(1 /* WARNING */, "AI session renewal date is 0, session will be reset.");
+ }
+ };
+ _SessionManager.prototype.renew = function () {
+ var now = +new Date;
+ this.automaticSession.id = ApplicationInsights.Util.newGuid();
+ this.automaticSession.acquisitionDate = now;
+ this.automaticSession.renewalDate = now;
+ this.setCookie(this.automaticSession.id, this.automaticSession.acquisitionDate, this.automaticSession.renewalDate);
+ if (typeof this._sessionHandler === "function") {
+ this._sessionHandler(0 /* Start */, now);
+ }
+ if (!ApplicationInsights.Util.canUseLocalStorage()) {
+ ApplicationInsights._InternalLogging.throwInternalNonUserActionable(1 /* WARNING */, "Browser does not support local storage. Session durations will be inaccurate.");
+ }
+ };
+ _SessionManager.prototype.setCookie = function (guid, acq, renewal) {
+ var acquisitionExpiry = acq + this.config.sessionExpirationMs();
+ var renewalExpiry = renewal + this.config.sessionRenewalMs();
+ var cookieExpiry = new Date();
+ var cookie = [guid, acq, renewal];
+ if (acquisitionExpiry < renewalExpiry) {
+ cookieExpiry.setTime(acquisitionExpiry);
+ }
+ else {
+ cookieExpiry.setTime(renewalExpiry);
+ }
+ ApplicationInsights.Util.setCookie('ai_session', cookie.join('|') + ';expires=' + cookieExpiry.toUTCString());
+ };
+ _SessionManager.prototype.setStorage = function (guid, acq, renewal) {
+ ApplicationInsights.Util.setStorage('ai_session', [guid, acq, renewal].join('|'));
+ };
+ _SessionManager.acquisitionSpan = 86400000;
+ _SessionManager.renewalSpan = 1800000;
+ return _SessionManager;
+ })();
+ Context._SessionManager = _SessionManager;
+ })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {}));
+ })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
+})(Microsoft || (Microsoft = {}));
+var Microsoft;
+(function (Microsoft) {
+ var ApplicationInsights;
+ (function (ApplicationInsights) {
+ var Context;
+ (function (Context) {
+ "use strict";
+ var User = (function () {
+ function User(accountId) {
+ var cookie = ApplicationInsights.Util.getCookie(User.userCookieName);
+ if (cookie) {
+ var params = cookie.split(User.cookieSeparator);
+ if (params.length > 0) {
+ this.id = params[0];
+ }
+ }
+ if (!this.id) {
+ this.id = ApplicationInsights.Util.newGuid();
+ var date = new Date();
+ var acqStr = ApplicationInsights.Util.toISOStringForIE8(date);
+ this.accountAcquisitionDate = acqStr;
+ date.setTime(date.getTime() + 31536000000);
+ var newCookie = [this.id, acqStr];
+ ApplicationInsights.Util.setCookie(User.userCookieName, newCookie.join(User.cookieSeparator) + ';expires=' + date.toUTCString());
+ ApplicationInsights.Util.removeStorage('ai_session');
+ }
+ this.accountId = accountId;
+ var authCookie = ApplicationInsights.Util.getCookie(User.authUserCookieName);
+ if (authCookie) {
+ authCookie = decodeURI(authCookie);
+ var authCookieString = authCookie.split(User.cookieSeparator);
+ if (authCookieString[0]) {
+ this.authenticatedId = authCookieString[0];
+ }
+ if (authCookieString.length > 1 && authCookieString[1]) {
+ this.accountId = authCookieString[1];
+ }
+ }
+ }
+ User.prototype.setAuthenticatedUserContext = function (authenticatedUserId, accountId) {
+ var isInvalidInput = !this.validateUserInput(authenticatedUserId) || (accountId && !this.validateUserInput(accountId));
+ if (isInvalidInput) {
+ ApplicationInsights._InternalLogging.throwInternalUserActionable(1 /* WARNING */, "Setting auth user context failed. " + "User auth/account id should be of type string, and not contain commas, semi-colons, equal signs, spaces, or vertical-bars.");
+ return;
+ }
+ this.authenticatedId = authenticatedUserId;
+ var authCookie = this.authenticatedId;
+ if (accountId) {
+ this.accountId = accountId;
+ authCookie = [this.authenticatedId, this.accountId].join(User.cookieSeparator);
+ }
+ ApplicationInsights.Util.setCookie(User.authUserCookieName, encodeURI(authCookie));
+ };
+ User.prototype.clearAuthenticatedUserContext = function () {
+ this.authenticatedId = null;
+ this.accountId = null;
+ ApplicationInsights.Util.deleteCookie(User.authUserCookieName);
+ };
+ User.prototype.validateUserInput = function (id) {
+ if (typeof id !== 'string' || !id || id.match(/,|;|=| |\|/)) {
+ return false;
+ }
+ return true;
+ };
+ User.cookieSeparator = '|';
+ User.userCookieName = 'ai_user';
+ User.authUserCookieName = 'ai_authUser';
+ return User;
+ })();
+ Context.User = User;
+ })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {}));
+ })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
+})(Microsoft || (Microsoft = {}));
+var Microsoft;
+(function (Microsoft) {
+ var ApplicationInsights;
+ (function (ApplicationInsights) {
+ "use strict";
+ var Sender = (function () {
+ function Sender(config) {
+ this._buffer = [];
+ this._lastSend = 0;
+ this._config = config;
+ this._sender = null;
+ if (typeof XMLHttpRequest != "undefined") {
+ var testXhr = new XMLHttpRequest();
+ if ("withCredentials" in testXhr) {
+ this._sender = this._xhrSender;
+ }
+ else if (typeof XDomainRequest !== "undefined") {
+ this._sender = this._xdrSender;
+ }
+ }
+ }
+ Sender.prototype.send = function (envelope) {
+ var _this = this;
+ try {
+ if (this._config.disableTelemetry()) {
+ return;
+ }
+ if (!envelope) {
+ ApplicationInsights._InternalLogging.throwInternalNonUserActionable(0 /* CRITICAL */, "Cannot send empty telemetry");
+ return;
+ }
+ if (!this._sender) {
+ ApplicationInsights._InternalLogging.throwInternalNonUserActionable(0 /* CRITICAL */, "Sender was not initialized");
+ return;
+ }
+ var payload = ApplicationInsights.Serializer.serialize(envelope);
+ if (this._getSizeInBytes(this._buffer) + payload.length > this._config.maxBatchSizeInBytes()) {
+ this.triggerSend();
+ }
+ this._buffer.push(payload);
+ if (!this._timeoutHandle) {
+ this._timeoutHandle = setTimeout(function () {
+ _this._timeoutHandle = null;
+ _this.triggerSend();
+ }, this._config.maxBatchInterval());
+ }
+ }
+ catch (e) {
+ ApplicationInsights._InternalLogging.throwInternalNonUserActionable(0 /* CRITICAL */, "Failed adding telemetry to the sender's buffer, some telemetry will be lost: " + ApplicationInsights.Util.dump(e));
+ }
+ };
+ Sender.prototype._getSizeInBytes = function (list) {
+ var size = 0;
+ if (list && list.length) {
+ for (var i = 0; i < list.length; i++) {
+ var item = list[i];
+ if (item && item.length) {
+ size += item.length;
+ }
+ }
+ }
+ return size;
+ };
+ Sender.prototype.triggerSend = function (async) {
+ var isAsync = true;
+ if (typeof async === 'boolean') {
+ isAsync = async;
+ }
+ try {
+ if (!this._config.disableTelemetry()) {
+ if (this._buffer.length) {
+ var batch = this._config.emitLineDelimitedJson() ? this._buffer.join("\n") : "[" + this._buffer.join(",") + "]";
+ this._sender(batch, isAsync);
+ }
+ this._lastSend = +new Date;
+ }
+ this._buffer.length = 0;
+ clearTimeout(this._timeoutHandle);
+ this._timeoutHandle = null;
+ }
+ catch (e) {
+ ApplicationInsights._InternalLogging.throwInternalNonUserActionable(0 /* CRITICAL */, "Telemetry transmission failed, some telemetry will be lost: " + ApplicationInsights.Util.dump(e));
+ }
+ };
+ Sender.prototype._xhrSender = function (payload, isAsync) {
+ var xhr = new XMLHttpRequest();
+ xhr.open("POST", this._config.endpointUrl(), isAsync);
+ xhr.setRequestHeader("Content-type", "application/json");
+ xhr.onreadystatechange = function () { return Sender._xhrReadyStateChange(xhr, payload); };
+ xhr.onerror = function (event) { return Sender._onError(payload, xhr.responseText || xhr.response || "", event); };
+ xhr.send(payload);
+ };
+ Sender.prototype._xdrSender = function (payload, isAsync) {
+ var xdr = new XDomainRequest();
+ xdr.onload = function () { return Sender._xdrOnLoad(xdr, payload); };
+ xdr.onerror = function (event) { return Sender._onError(payload, xdr.responseText || "", event); };
+ xdr.open('POST', this._config.endpointUrl());
+ xdr.send(payload);
+ };
+ Sender._xhrReadyStateChange = function (xhr, payload) {
+ if (xhr.readyState === 4) {
+ if ((xhr.status < 200 || xhr.status >= 300) && xhr.status !== 0) {
+ Sender._onError(payload, xhr.responseText || xhr.response || "");
+ }
+ else {
+ Sender._onSuccess(payload);
+ }
+ }
+ };
+ Sender._xdrOnLoad = function (xdr, payload) {
+ if (xdr && (xdr.responseText + "" === "200" || xdr.responseText === "")) {
+ Sender._onSuccess(payload);
+ }
+ else {
+ Sender._onError(payload, xdr && xdr.responseText || "");
+ }
+ };
+ Sender._onError = function (payload, message, event) {
+ ApplicationInsights._InternalLogging.throwInternalNonUserActionable(1 /* WARNING */, "Failed to send telemetry:\n" + message);
+ };
+ Sender._onSuccess = function (payload) {
+ };
+ return Sender;
+ })();
+ ApplicationInsights.Sender = Sender;
+ })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
+})(Microsoft || (Microsoft = {}));
+var Microsoft;
+(function (Microsoft) {
+ var Telemetry;
+ (function (Telemetry) {
+ "use strict";
+ var Domain = (function () {
+ function Domain() {
+ }
+ return Domain;
+ })();
+ Telemetry.Domain = Domain;
+ })(Telemetry = Microsoft.Telemetry || (Microsoft.Telemetry = {}));
+})(Microsoft || (Microsoft = {}));
+var AI;
+(function (AI) {
+ "use strict";
+ (function (SeverityLevel) {
+ SeverityLevel[SeverityLevel["Verbose"] = 0] = "Verbose";
+ SeverityLevel[SeverityLevel["Information"] = 1] = "Information";
+ SeverityLevel[SeverityLevel["Warning"] = 2] = "Warning";
+ SeverityLevel[SeverityLevel["Error"] = 3] = "Error";
+ SeverityLevel[SeverityLevel["Critical"] = 4] = "Critical";
+ })(AI.SeverityLevel || (AI.SeverityLevel = {}));
+ var SeverityLevel = AI.SeverityLevel;
+})(AI || (AI = {}));
+var AI;
+(function (AI) {
+ "use strict";
+ var MessageData = (function (_super) {
+ __extends(MessageData, _super);
+ function MessageData() {
+ this.ver = 2;
+ this.properties = {};
+ _super.call(this);
+ }
+ return MessageData;
+ })(Microsoft.Telemetry.Domain);
+ AI.MessageData = MessageData;
+})(AI || (AI = {}));
+var Microsoft;
+(function (Microsoft) {
+ var ApplicationInsights;
+ (function (ApplicationInsights) {
+ var Telemetry;
+ (function (Telemetry) {
+ var Common;
+ (function (Common) {
+ "use strict";
+ var DataSanitizer = (function () {
+ function DataSanitizer() {
+ }
+ DataSanitizer.sanitizeKeyAndAddUniqueness = function (key, map) {
+ var origLength = key.length;
+ var field = DataSanitizer.sanitizeKey(key);
+ if (field.length !== origLength) {
+ var i = 0;
+ var uniqueField = field;
+ while (map[uniqueField] !== undefined) {
+ i++;
+ uniqueField = field.substring(0, DataSanitizer.MAX_NAME_LENGTH - 3) + DataSanitizer.padNumber(i);
+ }
+ field = uniqueField;
+ }
+ return field;
+ };
+ DataSanitizer.sanitizeKey = function (name) {
+ if (name) {
+ name = ApplicationInsights.Util.trim(name.toString());
+ if (name.search(/[^0-9a-zA-Z-._()\/ ]/g) >= 0) {
+ name = name.replace(/[^0-9a-zA-Z-._()\/ ]/g, "_");
+ ApplicationInsights._InternalLogging.throwInternalUserActionable(1 /* WARNING */, "name contains illegal characters. Illgeal character have been replaced with '_'. new name: " + name);
+ }
+ if (name.length > DataSanitizer.MAX_NAME_LENGTH) {
+ name = name.substring(0, DataSanitizer.MAX_NAME_LENGTH);
+ ApplicationInsights._InternalLogging.throwInternalUserActionable(1 /* WARNING */, "name is too long. It has been truncated to " + DataSanitizer.MAX_NAME_LENGTH + " characters. name: " + name);
+ }
+ }
+ return name;
+ };
+ DataSanitizer.sanitizeString = function (value) {
+ if (value) {
+ value = ApplicationInsights.Util.trim(value);
+ if (value.toString().length > DataSanitizer.MAX_STRING_LENGTH) {
+ value = value.substring(0, DataSanitizer.MAX_STRING_LENGTH);
+ ApplicationInsights._InternalLogging.throwInternalUserActionable(1 /* WARNING */, "string value is too long. It has been truncated to " + DataSanitizer.MAX_STRING_LENGTH + " characters. value: " + value);
+ }
+ }
+ return value;
+ };
+ DataSanitizer.sanitizeUrl = function (url) {
+ if (url) {
+ if (url.length > DataSanitizer.MAX_URL_LENGTH) {
+ url = url.substring(0, DataSanitizer.MAX_URL_LENGTH);
+ ApplicationInsights._InternalLogging.throwInternalUserActionable(1 /* WARNING */, "url is too long, it has been trucated to " + DataSanitizer.MAX_URL_LENGTH + " characters. url: " + url);
+ }
+ }
+ return url;
+ };
+ DataSanitizer.sanitizeMessage = function (message) {
+ if (message) {
+ if (message.length > DataSanitizer.MAX_MESSAGE_LENGTH) {
+ message = message.substring(0, DataSanitizer.MAX_MESSAGE_LENGTH);
+ ApplicationInsights._InternalLogging.throwInternalUserActionable(1 /* WARNING */, "message is too long, it has been trucated to " + DataSanitizer.MAX_MESSAGE_LENGTH + " characters. message: " + message);
+ }
+ }
+ return message;
+ };
+ DataSanitizer.sanitizeException = function (exception) {
+ if (exception) {
+ if (exception.length > DataSanitizer.MAX_EXCEPTION_LENGTH) {
+ exception = exception.substring(0, DataSanitizer.MAX_EXCEPTION_LENGTH);
+ ApplicationInsights._InternalLogging.throwInternalUserActionable(1 /* WARNING */, "exception is too long, iit has been trucated to " + DataSanitizer.MAX_EXCEPTION_LENGTH + " characters. exception: " + exception);
+ }
+ }
+ return exception;
+ };
+ DataSanitizer.sanitizeProperties = function (properties) {
+ if (properties) {
+ var tempProps = {};
+ for (var prop in properties) {
+ var value = DataSanitizer.sanitizeString(properties[prop]);
+ prop = DataSanitizer.sanitizeKeyAndAddUniqueness(prop, tempProps);
+ tempProps[prop] = value;
+ }
+ properties = tempProps;
+ }
+ return properties;
+ };
+ DataSanitizer.sanitizeMeasurements = function (measurements) {
+ if (measurements) {
+ var tempMeasurements = {};
+ for (var measure in measurements) {
+ var value = measurements[measure];
+ measure = DataSanitizer.sanitizeKeyAndAddUniqueness(measure, tempMeasurements);
+ tempMeasurements[measure] = value;
+ }
+ measurements = tempMeasurements;
+ }
+ return measurements;
+ };
+ DataSanitizer.padNumber = function (num) {
+ var s = "00" + num;
+ return s.substr(s.length - 3);
+ };
+ DataSanitizer.MAX_NAME_LENGTH = 150;
+ DataSanitizer.MAX_STRING_LENGTH = 1024;
+ DataSanitizer.MAX_URL_LENGTH = 2048;
+ DataSanitizer.MAX_MESSAGE_LENGTH = 32768;
+ DataSanitizer.MAX_EXCEPTION_LENGTH = 32768;
+ return DataSanitizer;
+ })();
+ Common.DataSanitizer = DataSanitizer;
+ })(Common = Telemetry.Common || (Telemetry.Common = {}));
+ })(Telemetry = ApplicationInsights.Telemetry || (ApplicationInsights.Telemetry = {}));
+ })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
+})(Microsoft || (Microsoft = {}));
+var Microsoft;
+(function (Microsoft) {
+ var ApplicationInsights;
+ (function (ApplicationInsights) {
+ var Telemetry;
+ (function (Telemetry) {
+ "use strict";
+ var Trace = (function (_super) {
+ __extends(Trace, _super);
+ function Trace(message, properties) {
+ _super.call(this);
+ this.aiDataContract = {
+ ver: true,
+ message: true,
+ severityLevel: false,
+ measurements: false,
+ properties: false
+ };
+ message = message || ApplicationInsights.Util.NotSpecified;
+ this.message = Telemetry.Common.DataSanitizer.sanitizeMessage(message);
+ this.properties = Telemetry.Common.DataSanitizer.sanitizeProperties(properties);
+ }
+ Trace.envelopeType = "Microsoft.ApplicationInsights.Message";
+ Trace.dataType = "MessageData";
+ return Trace;
+ })(AI.MessageData);
+ Telemetry.Trace = Trace;
+ })(Telemetry = ApplicationInsights.Telemetry || (ApplicationInsights.Telemetry = {}));
+ })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
+})(Microsoft || (Microsoft = {}));
+var AI;
+(function (AI) {
+ "use strict";
+ var EventData = (function (_super) {
+ __extends(EventData, _super);
+ function EventData() {
+ this.ver = 2;
+ this.properties = {};
+ this.measurements = {};
+ _super.call(this);
+ }
+ return EventData;
+ })(Microsoft.Telemetry.Domain);
+ AI.EventData = EventData;
+})(AI || (AI = {}));
+var Microsoft;
+(function (Microsoft) {
+ var ApplicationInsights;
+ (function (ApplicationInsights) {
+ var Telemetry;
+ (function (Telemetry) {
+ "use strict";
+ var Event = (function (_super) {
+ __extends(Event, _super);
+ function Event(name, properties, measurements) {
+ _super.call(this);
+ this.aiDataContract = {
+ ver: true,
+ name: true,
+ properties: false,
+ measurements: false
+ };
+ this.name = ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeString(name);
+ this.properties = ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeProperties(properties);
+ this.measurements = ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeMeasurements(measurements);
+ }
+ Event.envelopeType = "Microsoft.ApplicationInsights.Event";
+ Event.dataType = "EventData";
+ return Event;
+ })(AI.EventData);
+ Telemetry.Event = Event;
+ })(Telemetry = ApplicationInsights.Telemetry || (ApplicationInsights.Telemetry = {}));
+ })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
+})(Microsoft || (Microsoft = {}));
+var AI;
+(function (AI) {
+ "use strict";
+ var ExceptionDetails = (function () {
+ function ExceptionDetails() {
+ this.hasFullStack = true;
+ this.parsedStack = [];
+ }
+ return ExceptionDetails;
+ })();
+ AI.ExceptionDetails = ExceptionDetails;
+})(AI || (AI = {}));
+var AI;
+(function (AI) {
+ "use strict";
+ var ExceptionData = (function (_super) {
+ __extends(ExceptionData, _super);
+ function ExceptionData() {
+ this.ver = 2;
+ this.exceptions = [];
+ this.properties = {};
+ this.measurements = {};
+ _super.call(this);
+ }
+ return ExceptionData;
+ })(Microsoft.Telemetry.Domain);
+ AI.ExceptionData = ExceptionData;
+})(AI || (AI = {}));
+var AI;
+(function (AI) {
+ "use strict";
+ var StackFrame = (function () {
+ function StackFrame() {
+ }
+ return StackFrame;
+ })();
+ AI.StackFrame = StackFrame;
+})(AI || (AI = {}));
+var Microsoft;
+(function (Microsoft) {
+ var ApplicationInsights;
+ (function (ApplicationInsights) {
+ var Telemetry;
+ (function (Telemetry) {
+ "use strict";
+ var Exception = (function (_super) {
+ __extends(Exception, _super);
+ function Exception(exception, handledAt, properties, measurements) {
+ _super.call(this);
+ this.aiDataContract = {
+ ver: true,
+ handledAt: true,
+ exceptions: true,
+ severityLevel: false,
+ properties: false,
+ measurements: false
+ };
+ this.properties = ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeProperties(properties);
+ this.measurements = ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeMeasurements(measurements);
+ this.handledAt = handledAt || "unhandled";
+ this.exceptions = [new _ExceptionDetails(exception)];
+ }
+ Exception.CreateSimpleException = function (message, typeName, assembly, fileName, details, line, handledAt) {
+ var exceptionTelemetry;
+ try {
+ throw new Error();
+ }
+ catch (e) {
+ exceptionTelemetry = new Telemetry.Exception(e);
+ }
+ var stack = exceptionTelemetry.exceptions[0].parsedStack[0];
+ stack.assembly = assembly;
+ stack.fileName = fileName;
+ stack.level = 0;
+ stack.line = line;
+ stack.method = "unknown";
+ var exception = exceptionTelemetry.exceptions[0];
+ exception.hasFullStack = true;
+ exception.message = message;
+ exception.parsedStack = null;
+ exception.stack = details;
+ exception.typeName = typeName;
+ exceptionTelemetry.handledAt = handledAt || "unhandled";
+ return exceptionTelemetry;
+ };
+ Exception.envelopeType = "Microsoft.ApplicationInsights.Exception";
+ Exception.dataType = "ExceptionData";
+ return Exception;
+ })(AI.ExceptionData);
+ Telemetry.Exception = Exception;
+ var _ExceptionDetails = (function (_super) {
+ __extends(_ExceptionDetails, _super);
+ function _ExceptionDetails(exception) {
+ _super.call(this);
+ this.aiDataContract = {
+ id: false,
+ outerId: false,
+ typeName: true,
+ message: true,
+ hasFullStack: false,
+ stack: false,
+ parsedStack: []
+ };
+ this.typeName = Telemetry.Common.DataSanitizer.sanitizeString(exception.name || ApplicationInsights.Util.NotSpecified);
+ this.message = Telemetry.Common.DataSanitizer.sanitizeMessage(exception.message || ApplicationInsights.Util.NotSpecified);
+ var stack = exception["stack"];
+ this.parsedStack = this.parseStack(stack);
+ this.stack = Telemetry.Common.DataSanitizer.sanitizeException(stack);
+ this.hasFullStack = ApplicationInsights.Util.isArray(this.parsedStack) && this.parsedStack.length > 0;
+ }
+ _ExceptionDetails.prototype.parseStack = function (stack) {
+ var parsedStack = undefined;
+ if (typeof stack === "string") {
+ var frames = stack.split('\n');
+ parsedStack = [];
+ var level = 0;
+ var totalSizeInBytes = 0;
+ for (var i = 0; i <= frames.length; i++) {
+ var frame = frames[i];
+ if (_StackFrame.regex.test(frame)) {
+ var parsedFrame = new _StackFrame(frames[i], level++);
+ totalSizeInBytes += parsedFrame.sizeInBytes;
+ parsedStack.push(parsedFrame);
+ }
+ }
+ var exceptionParsedStackThreshold = 32 * 1024;
+ if (totalSizeInBytes > exceptionParsedStackThreshold) {
+ var left = 0;
+ var right = parsedStack.length - 1;
+ var size = 0;
+ var acceptedLeft = left;
+ var acceptedRight = right;
+ while (left < right) {
+ var lSize = parsedStack[left].sizeInBytes;
+ var rSize = parsedStack[right].sizeInBytes;
+ size += lSize + rSize;
+ if (size > exceptionParsedStackThreshold) {
+ var howMany = acceptedRight - acceptedLeft + 1;
+ parsedStack.splice(acceptedLeft, howMany);
+ break;
+ }
+ acceptedLeft = left;
+ acceptedRight = right;
+ left++;
+ right--;
+ }
+ }
+ }
+ return parsedStack;
+ };
+ return _ExceptionDetails;
+ })(AI.ExceptionDetails);
+ var _StackFrame = (function (_super) {
+ __extends(_StackFrame, _super);
+ function _StackFrame(frame, level) {
+ _super.call(this);
+ this.sizeInBytes = 0;
+ this.aiDataContract = {
+ level: true,
+ method: true,
+ assembly: false,
+ fileName: false,
+ line: false
+ };
+ this.level = level;
+ this.method = "unavailable";
+ this.assembly = ApplicationInsights.Util.trim(frame);
+ var matches = frame.match(_StackFrame.regex);
+ if (matches && matches.length >= 5) {
+ this.method = ApplicationInsights.Util.trim(matches[2]);
+ this.fileName = ApplicationInsights.Util.trim(matches[4]);
+ this.line = parseInt(matches[5]) || 0;
+ }
+ this.sizeInBytes += this.method.length;
+ this.sizeInBytes += this.fileName.length;
+ this.sizeInBytes += this.assembly.length;
+ this.sizeInBytes += _StackFrame.baseSize;
+ this.sizeInBytes += this.level.toString().length;
+ this.sizeInBytes += this.line.toString().length;
+ }
+ _StackFrame.regex = /^([\s]+at)?(.*?)(\@|\s\(|\s)([^\(\@\n]+):([0-9]+):([0-9]+)(\)?)$/;
+ _StackFrame.baseSize = 58;
+ return _StackFrame;
+ })(AI.StackFrame);
+ })(Telemetry = ApplicationInsights.Telemetry || (ApplicationInsights.Telemetry = {}));
+ })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
+})(Microsoft || (Microsoft = {}));
+var AI;
+(function (AI) {
+ "use strict";
+ var MetricData = (function (_super) {
+ __extends(MetricData, _super);
+ function MetricData() {
+ this.ver = 2;
+ this.metrics = [];
+ this.properties = {};
+ _super.call(this);
+ }
+ return MetricData;
+ })(Microsoft.Telemetry.Domain);
+ AI.MetricData = MetricData;
+})(AI || (AI = {}));
+var AI;
+(function (AI) {
+ "use strict";
+ (function (DataPointType) {
+ DataPointType[DataPointType["Measurement"] = 0] = "Measurement";
+ DataPointType[DataPointType["Aggregation"] = 1] = "Aggregation";
+ })(AI.DataPointType || (AI.DataPointType = {}));
+ var DataPointType = AI.DataPointType;
+})(AI || (AI = {}));
+var AI;
+(function (AI) {
+ "use strict";
+ var DataPoint = (function () {
+ function DataPoint() {
+ this.kind = 0 /* Measurement */;
+ }
+ return DataPoint;
+ })();
+ AI.DataPoint = DataPoint;
+})(AI || (AI = {}));
+var Microsoft;
+(function (Microsoft) {
+ var ApplicationInsights;
+ (function (ApplicationInsights) {
+ var Telemetry;
+ (function (Telemetry) {
+ var Common;
+ (function (Common) {
+ "use strict";
+ var DataPoint = (function (_super) {
+ __extends(DataPoint, _super);
+ function DataPoint() {
+ _super.apply(this, arguments);
+ this.aiDataContract = {
+ name: true,
+ kind: false,
+ value: true,
+ count: false,
+ min: false,
+ max: false,
+ stdDev: false
+ };
+ }
+ return DataPoint;
+ })(AI.DataPoint);
+ Common.DataPoint = DataPoint;
+ })(Common = Telemetry.Common || (Telemetry.Common = {}));
+ })(Telemetry = ApplicationInsights.Telemetry || (ApplicationInsights.Telemetry = {}));
+ })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
+})(Microsoft || (Microsoft = {}));
+var Microsoft;
+(function (Microsoft) {
+ var ApplicationInsights;
+ (function (ApplicationInsights) {
+ var Telemetry;
+ (function (Telemetry) {
+ "use strict";
+ var Metric = (function (_super) {
+ __extends(Metric, _super);
+ function Metric(name, value, count, min, max, properties) {
+ _super.call(this);
+ this.aiDataContract = {
+ ver: true,
+ metrics: true,
+ properties: false
+ };
+ var dataPoint = new Microsoft.ApplicationInsights.Telemetry.Common.DataPoint();
+ dataPoint.count = count > 0 ? count : undefined;
+ dataPoint.max = isNaN(max) || max === null ? undefined : max;
+ dataPoint.min = isNaN(min) || min === null ? undefined : min;
+ dataPoint.name = Telemetry.Common.DataSanitizer.sanitizeString(name);
+ dataPoint.value = value;
+ this.metrics = [dataPoint];
+ this.properties = ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeProperties(properties);
+ }
+ Metric.envelopeType = "Microsoft.ApplicationInsights.Metric";
+ Metric.dataType = "MetricData";
+ return Metric;
+ })(AI.MetricData);
+ Telemetry.Metric = Metric;
+ })(Telemetry = ApplicationInsights.Telemetry || (ApplicationInsights.Telemetry = {}));
+ })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
+})(Microsoft || (Microsoft = {}));
+var AI;
+(function (AI) {
+ "use strict";
+ var PageViewData = (function (_super) {
+ __extends(PageViewData, _super);
+ function PageViewData() {
+ this.ver = 2;
+ this.properties = {};
+ this.measurements = {};
+ _super.call(this);
+ }
+ return PageViewData;
+ })(AI.EventData);
+ AI.PageViewData = PageViewData;
+})(AI || (AI = {}));
+var Microsoft;
+(function (Microsoft) {
+ var ApplicationInsights;
+ (function (ApplicationInsights) {
+ var Telemetry;
+ (function (Telemetry) {
+ "use strict";
+ var PageView = (function (_super) {
+ __extends(PageView, _super);
+ function PageView(name, url, durationMs, properties, measurements) {
+ _super.call(this);
+ this.aiDataContract = {
+ ver: true,
+ name: false,
+ url: false,
+ duration: false,
+ properties: false,
+ measurements: false
+ };
+ this.url = Telemetry.Common.DataSanitizer.sanitizeUrl(url);
+ this.name = Telemetry.Common.DataSanitizer.sanitizeString(name || ApplicationInsights.Util.NotSpecified);
+ if (!isNaN(durationMs)) {
+ this.duration = ApplicationInsights.Util.msToTimeSpan(durationMs);
+ }
+ this.properties = ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeProperties(properties);
+ this.measurements = ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeMeasurements(measurements);
+ }
+ PageView.envelopeType = "Microsoft.ApplicationInsights.Pageview";
+ PageView.dataType = "PageviewData";
+ return PageView;
+ })(AI.PageViewData);
+ Telemetry.PageView = PageView;
+ })(Telemetry = ApplicationInsights.Telemetry || (ApplicationInsights.Telemetry = {}));
+ })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
+})(Microsoft || (Microsoft = {}));
+var AI;
+(function (AI) {
+ "use strict";
+ var PageViewPerfData = (function (_super) {
+ __extends(PageViewPerfData, _super);
+ function PageViewPerfData() {
+ this.ver = 2;
+ this.properties = {};
+ this.measurements = {};
+ _super.call(this);
+ }
+ return PageViewPerfData;
+ })(AI.PageViewData);
+ AI.PageViewPerfData = PageViewPerfData;
+})(AI || (AI = {}));
+var Microsoft;
+(function (Microsoft) {
+ var ApplicationInsights;
+ (function (ApplicationInsights) {
+ var Telemetry;
+ (function (Telemetry) {
+ "use strict";
+ var PageViewPerformance = (function (_super) {
+ __extends(PageViewPerformance, _super);
+ function PageViewPerformance(name, url, durationMs, properties, measurements) {
+ _super.call(this);
+ this.aiDataContract = {
+ ver: true,
+ name: false,
+ url: false,
+ duration: false,
+ perfTotal: false,
+ networkConnect: false,
+ sentRequest: false,
+ receivedResponse: false,
+ domProcessing: false,
+ properties: false,
+ measurements: false
+ };
+ this.isValid = false;
+ var timing = PageViewPerformance.getPerformanceTiming();
+ if (timing) {
+ var total = PageViewPerformance.getDuration(timing.navigationStart, timing.loadEventEnd);
+ var network = PageViewPerformance.getDuration(timing.navigationStart, timing.connectEnd);
+ var request = PageViewPerformance.getDuration(timing.requestStart, timing.responseStart);
+ var response = PageViewPerformance.getDuration(timing.responseStart, timing.responseEnd);
+ var dom = PageViewPerformance.getDuration(timing.responseEnd, timing.loadEventEnd);
+ if (total == 0) {
+ ApplicationInsights._InternalLogging.throwInternalNonUserActionable(1 /* WARNING */, "error calculating page view performance: total='" + total + "', network='" + network + "', request='" + request + "', response='" + response + "', dom='" + dom + "'");
+ }
+ else if (total < Math.floor(network) + Math.floor(request) + Math.floor(response) + Math.floor(dom)) {
+ ApplicationInsights._InternalLogging.throwInternalNonUserActionable(1 /* WARNING */, "client performance math error:" + total + " < " + network + " + " + request + " + " + response + " + " + dom);
+ }
+ else {
+ durationMs = total;
+ this.perfTotal = ApplicationInsights.Util.msToTimeSpan(total);
+ this.networkConnect = ApplicationInsights.Util.msToTimeSpan(network);
+ this.sentRequest = ApplicationInsights.Util.msToTimeSpan(request);
+ this.receivedResponse = ApplicationInsights.Util.msToTimeSpan(response);
+ this.domProcessing = ApplicationInsights.Util.msToTimeSpan(dom);
+ this.isValid = true;
+ }
+ }
+ this.url = Telemetry.Common.DataSanitizer.sanitizeUrl(url);
+ this.name = Telemetry.Common.DataSanitizer.sanitizeString(name || ApplicationInsights.Util.NotSpecified);
+ if (!isNaN(durationMs)) {
+ this.duration = ApplicationInsights.Util.msToTimeSpan(durationMs);
+ }
+ this.properties = ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeProperties(properties);
+ this.measurements = ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeMeasurements(measurements);
+ }
+ PageViewPerformance.getPerformanceTiming = function () {
+ if (typeof window != "undefined" && window.performance && window.performance.timing) {
+ return window.performance.timing;
+ }
+ return null;
+ };
+ PageViewPerformance.isPerformanceTimingSupported = function () {
+ return typeof window != "undefined" && window.performance && window.performance.timing;
+ };
+ PageViewPerformance.isPerformanceTimingDataReady = function () {
+ var timing = window.performance.timing;
+ return timing.domainLookupStart > 0 && timing.navigationStart > 0 && timing.responseStart > 0 && timing.requestStart > 0 && timing.loadEventEnd > 0 && timing.responseEnd > 0 && timing.connectEnd > 0 && timing.domLoading > 0;
+ };
+ PageViewPerformance.getDuration = function (start, end) {
+ var duration = 0;
+ if (!(isNaN(start) || isNaN(end))) {
+ duration = Math.max(end - start, 0);
+ }
+ return duration;
+ };
+ PageViewPerformance.envelopeType = "Microsoft.ApplicationInsights.PageviewPerformance";
+ PageViewPerformance.dataType = "PageviewPerformanceData";
+ return PageViewPerformance;
+ })(AI.PageViewPerfData);
+ Telemetry.PageViewPerformance = PageViewPerformance;
+ })(Telemetry = ApplicationInsights.Telemetry || (ApplicationInsights.Telemetry = {}));
+ })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
+})(Microsoft || (Microsoft = {}));
+var AI;
+(function (AI) {
+ "use strict";
+ var SessionStateData = (function (_super) {
+ __extends(SessionStateData, _super);
+ function SessionStateData() {
+ this.ver = 2;
+ this.state = 0 /* Start */;
+ _super.call(this);
+ }
+ return SessionStateData;
+ })(Microsoft.Telemetry.Domain);
+ AI.SessionStateData = SessionStateData;
+})(AI || (AI = {}));
+var Microsoft;
+(function (Microsoft) {
+ var ApplicationInsights;
+ (function (ApplicationInsights) {
+ var Telemetry;
+ (function (Telemetry) {
+ "use strict";
+ var SessionTelemetry = (function (_super) {
+ __extends(SessionTelemetry, _super);
+ function SessionTelemetry(state) {
+ _super.call(this);
+ this.aiDataContract = {
+ ver: true,
+ state: true
+ };
+ this.state = state;
+ }
+ SessionTelemetry.envelopeType = "Microsoft.ApplicationInsights.SessionState";
+ SessionTelemetry.dataType = "SessionStateData";
+ return SessionTelemetry;
+ })(AI.SessionStateData);
+ Telemetry.SessionTelemetry = SessionTelemetry;
+ })(Telemetry = ApplicationInsights.Telemetry || (ApplicationInsights.Telemetry = {}));
+ })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
+})(Microsoft || (Microsoft = {}));
+var Microsoft;
+(function (Microsoft) {
+ var ApplicationInsights;
+ (function (ApplicationInsights) {
+ "use strict";
+ var TelemetryContext = (function () {
+ function TelemetryContext(config) {
+ var _this = this;
+ this._config = config;
+ this._sender = new ApplicationInsights.Sender(config);
+ if (typeof window !== 'undefined') {
+ this._sessionManager = new ApplicationInsights.Context._SessionManager(config, function (sessionState, timestamp) { return TelemetryContext._sessionHandler(_this, sessionState, timestamp); });
+ this.application = new ApplicationInsights.Context.Application();
+ this.device = new ApplicationInsights.Context.Device();
+ this.internal = new ApplicationInsights.Context.Internal();
+ this.location = new ApplicationInsights.Context.Location();
+ this.user = new ApplicationInsights.Context.User(config.accountId());
+ this.operation = new ApplicationInsights.Context.Operation();
+ this.session = new ApplicationInsights.Context.Session();
+ this.sample = new ApplicationInsights.Context.Sample(config.sampleRate());
+ }
+ }
+ TelemetryContext.prototype.addTelemetryInitializer = function (telemetryInitializer) {
+ this.telemetryInitializers = this.telemetryInitializers || [];
+ this.telemetryInitializers.push(telemetryInitializer);
+ };
+ TelemetryContext.prototype.track = function (envelope) {
+ if (!envelope) {
+ ApplicationInsights._InternalLogging.throwInternalUserActionable(0 /* CRITICAL */, "cannot call .track() with a null or undefined argument");
+ }
+ else {
+ if (envelope.name === ApplicationInsights.Telemetry.PageView.envelopeType) {
+ ApplicationInsights._InternalLogging.resetInternalMessageCount();
+ }
+ if (this.session) {
+ if (typeof this.session.id !== "string") {
+ this._sessionManager.update();
+ }
+ }
+ this._track(envelope);
+ }
+ return envelope;
+ };
+ TelemetryContext.prototype._track = function (envelope) {
+ if (this.session) {
+ if (typeof this.session.id === "string") {
+ this._applySessionContext(envelope, this.session);
+ }
+ else {
+ this._applySessionContext(envelope, this._sessionManager.automaticSession);
+ }
+ }
+ this._applyApplicationContext(envelope, this.application);
+ this._applyDeviceContext(envelope, this.device);
+ this._applyInternalContext(envelope, this.internal);
+ this._applyLocationContext(envelope, this.location);
+ this._applySampleContext(envelope, this.sample);
+ this._applyUserContext(envelope, this.user);
+ this._applyOperationContext(envelope, this.operation);
+ envelope.iKey = this._config.instrumentationKey();
+ var telemetryInitializersFailed = false;
+ try {
+ this.telemetryInitializers = this.telemetryInitializers || [];
+ var telemetryInitializersCount = this.telemetryInitializers.length;
+ for (var i = 0; i < telemetryInitializersCount; ++i) {
+ var telemetryInitializer = this.telemetryInitializers[i];
+ if (telemetryInitializer) {
+ telemetryInitializer.apply(null, [envelope]);
+ }
+ }
+ }
+ catch (e) {
+ telemetryInitializersFailed = true;
+ ApplicationInsights._InternalLogging.throwInternalUserActionable(0 /* CRITICAL */, "One of telemetry initializers failed, telemetry item will not be sent: " + ApplicationInsights.Util.dump(e));
+ }
+ if (!telemetryInitializersFailed) {
+ if (envelope.name === ApplicationInsights.Telemetry.SessionTelemetry.envelopeType || envelope.name === ApplicationInsights.Telemetry.Metric.envelopeType || this.sample.isSampledIn(envelope)) {
+ this._sender.send(envelope);
+ }
+ else {
+ ApplicationInsights._InternalLogging.logInternalMessage(1 /* WARNING */, "Telemetry is sampled and not sent to the AI service. SampleRate is " + this.sample.sampleRate);
+ }
+ }
+ return envelope;
+ };
+ TelemetryContext._sessionHandler = function (tc, sessionState, timestamp) {
+ var sessionStateTelemetry = new ApplicationInsights.Telemetry.SessionTelemetry(sessionState);
+ var sessionStateData = new ApplicationInsights.Telemetry.Common.Data(ApplicationInsights.Telemetry.SessionTelemetry.dataType, sessionStateTelemetry);
+ var sessionStateEnvelope = new ApplicationInsights.Telemetry.Common.Envelope(sessionStateData, ApplicationInsights.Telemetry.SessionTelemetry.envelopeType);
+ sessionStateEnvelope.time = ApplicationInsights.Util.toISOStringForIE8(new Date(timestamp));
+ tc._track(sessionStateEnvelope);
+ };
+ TelemetryContext.prototype._applyApplicationContext = function (envelope, appContext) {
+ if (appContext) {
+ var tagKeys = new AI.ContextTagKeys();
+ if (typeof appContext.ver === "string") {
+ envelope.tags[tagKeys.applicationVersion] = appContext.ver;
+ }
+ if (typeof appContext.build === "string") {
+ envelope.tags[tagKeys.applicationBuild] = appContext.build;
+ }
+ }
+ };
+ TelemetryContext.prototype._applyDeviceContext = function (envelope, deviceContext) {
+ var tagKeys = new AI.ContextTagKeys();
+ if (deviceContext) {
+ if (typeof deviceContext.id === "string") {
+ envelope.tags[tagKeys.deviceId] = deviceContext.id;
+ }
+ if (typeof deviceContext.ip === "string") {
+ envelope.tags[tagKeys.deviceIp] = deviceContext.ip;
+ }
+ if (typeof deviceContext.language === "string") {
+ envelope.tags[tagKeys.deviceLanguage] = deviceContext.language;
+ }
+ if (typeof deviceContext.locale === "string") {
+ envelope.tags[tagKeys.deviceLocale] = deviceContext.locale;
+ }
+ if (typeof deviceContext.model === "string") {
+ envelope.tags[tagKeys.deviceModel] = deviceContext.model;
+ }
+ if (typeof deviceContext.network !== "undefined") {
+ envelope.tags[tagKeys.deviceNetwork] = deviceContext.network;
+ }
+ if (typeof deviceContext.oemName === "string") {
+ envelope.tags[tagKeys.deviceOEMName] = deviceContext.oemName;
+ }
+ if (typeof deviceContext.os === "string") {
+ envelope.tags[tagKeys.deviceOS] = deviceContext.os;
+ }
+ if (typeof deviceContext.osversion === "string") {
+ envelope.tags[tagKeys.deviceOSVersion] = deviceContext.osversion;
+ }
+ if (typeof deviceContext.resolution === "string") {
+ envelope.tags[tagKeys.deviceScreenResolution] = deviceContext.resolution;
+ }
+ if (typeof deviceContext.type === "string") {
+ envelope.tags[tagKeys.deviceType] = deviceContext.type;
+ }
+ }
+ };
+ TelemetryContext.prototype._applyInternalContext = function (envelope, internalContext) {
+ if (internalContext) {
+ var tagKeys = new AI.ContextTagKeys();
+ if (typeof internalContext.agentVersion === "string") {
+ envelope.tags[tagKeys.internalAgentVersion] = internalContext.agentVersion;
+ }
+ if (typeof internalContext.sdkVersion === "string") {
+ envelope.tags[tagKeys.internalSdkVersion] = internalContext.sdkVersion;
+ }
+ }
+ };
+ TelemetryContext.prototype._applyLocationContext = function (envelope, locationContext) {
+ if (locationContext) {
+ var tagKeys = new AI.ContextTagKeys();
+ if (typeof locationContext.ip === "string") {
+ envelope.tags[tagKeys.locationIp] = locationContext.ip;
+ }
+ }
+ };
+ TelemetryContext.prototype._applyOperationContext = function (envelope, operationContext) {
+ if (operationContext) {
+ var tagKeys = new AI.ContextTagKeys();
+ if (typeof operationContext.id === "string") {
+ envelope.tags[tagKeys.operationId] = operationContext.id;
+ }
+ if (typeof operationContext.name === "string") {
+ envelope.tags[tagKeys.operationName] = operationContext.name;
+ }
+ if (typeof operationContext.parentId === "string") {
+ envelope.tags[tagKeys.operationParentId] = operationContext.parentId;
+ }
+ if (typeof operationContext.rootId === "string") {
+ envelope.tags[tagKeys.operationRootId] = operationContext.rootId;
+ }
+ if (typeof operationContext.syntheticSource === "string") {
+ envelope.tags[tagKeys.operationSyntheticSource] = operationContext.syntheticSource;
+ }
+ }
+ };
+ TelemetryContext.prototype._applySampleContext = function (envelope, sampleContext) {
+ if (sampleContext) {
+ var tagKeys = new AI.ContextTagKeys();
+ envelope.tags[tagKeys.sampleRate] = sampleContext.sampleRate;
+ }
+ };
+ TelemetryContext.prototype._applySessionContext = function (envelope, sessionContext) {
+ if (sessionContext) {
+ var tagKeys = new AI.ContextTagKeys();
+ if (typeof sessionContext.id === "string") {
+ envelope.tags[tagKeys.sessionId] = sessionContext.id;
+ }
+ if (typeof sessionContext.isFirst !== "undefined") {
+ envelope.tags[tagKeys.sessionIsFirst] = sessionContext.isFirst;
+ }
+ }
+ };
+ TelemetryContext.prototype._applyUserContext = function (envelope, userContext) {
+ if (userContext) {
+ var tagKeys = new AI.ContextTagKeys();
+ if (typeof userContext.accountAcquisitionDate === "string") {
+ envelope.tags[tagKeys.userAccountAcquisitionDate] = userContext.accountAcquisitionDate;
+ }
+ if (typeof userContext.accountId === "string") {
+ envelope.tags[tagKeys.userAccountId] = userContext.accountId;
+ }
+ if (typeof userContext.agent === "string") {
+ envelope.tags[tagKeys.userAgent] = userContext.agent;
+ }
+ if (typeof userContext.id === "string") {
+ envelope.tags[tagKeys.userId] = userContext.id;
+ }
+ if (typeof userContext.authenticatedId === "string") {
+ envelope.tags[tagKeys.userAuthUserId] = userContext.authenticatedId;
+ }
+ if (typeof userContext.storeRegion === "string") {
+ envelope.tags[tagKeys.userStoreRegion] = userContext.storeRegion;
+ }
+ }
+ };
+ return TelemetryContext;
+ })();
+ ApplicationInsights.TelemetryContext = TelemetryContext;
+ })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
+})(Microsoft || (Microsoft = {}));
+var Microsoft;
+(function (Microsoft) {
+ var Telemetry;
+ (function (Telemetry) {
+ "use strict";
+ var Data = (function (_super) {
+ __extends(Data, _super);
+ function Data() {
+ _super.call(this);
+ }
+ return Data;
+ })(Microsoft.Telemetry.Base);
+ Telemetry.Data = Data;
+ })(Telemetry = Microsoft.Telemetry || (Microsoft.Telemetry = {}));
+})(Microsoft || (Microsoft = {}));
+var Microsoft;
+(function (Microsoft) {
+ var ApplicationInsights;
+ (function (ApplicationInsights) {
+ var Telemetry;
+ (function (Telemetry) {
+ var Common;
+ (function (Common) {
+ "use strict";
+ var Data = (function (_super) {
+ __extends(Data, _super);
+ function Data(type, data) {
+ _super.call(this);
+ this.aiDataContract = {
+ baseType: true,
+ baseData: true
+ };
+ this.baseType = type;
+ this.baseData = data;
+ }
+ return Data;
+ })(Microsoft.Telemetry.Data);
+ Common.Data = Data;
+ })(Common = Telemetry.Common || (Telemetry.Common = {}));
+ })(Telemetry = ApplicationInsights.Telemetry || (ApplicationInsights.Telemetry = {}));
+ })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
+})(Microsoft || (Microsoft = {}));
+var Microsoft;
+(function (Microsoft) {
+ var ApplicationInsights;
+ (function (ApplicationInsights) {
+ var Telemetry;
+ (function (Telemetry) {
+ "use strict";
+ var PageVisitTimeManager = (function () {
+ function PageVisitTimeManager(pageVisitTimeTrackingHandler) {
+ this.prevPageVisitDataKeyName = "prevPageVisitData";
+ this.pageVisitTimeTrackingHandler = pageVisitTimeTrackingHandler;
+ }
+ PageVisitTimeManager.prototype.trackPreviousPageVisit = function (currentPageName, currentPageUrl) {
+ try {
+ var prevPageVisitTimeData = this.restartPageVisitTimer(currentPageName, currentPageUrl);
+ if (prevPageVisitTimeData) {
+ this.pageVisitTimeTrackingHandler(prevPageVisitTimeData.pageName, prevPageVisitTimeData.pageUrl, prevPageVisitTimeData.pageVisitTime);
+ }
+ }
+ catch (e) {
+ ApplicationInsights._InternalLogging.warnToConsole("Auto track page visit time failed, metric will not be collected: " + ApplicationInsights.Util.dump(e));
+ }
+ };
+ PageVisitTimeManager.prototype.restartPageVisitTimer = function (pageName, pageUrl) {
+ try {
+ var prevPageVisitData = this.stopPageVisitTimer();
+ this.startPageVisitTimer(pageName, pageUrl);
+ return prevPageVisitData;
+ }
+ catch (e) {
+ ApplicationInsights._InternalLogging.warnToConsole("Call to restart failed: " + ApplicationInsights.Util.dump(e));
+ return null;
+ }
+ };
+ PageVisitTimeManager.prototype.startPageVisitTimer = function (pageName, pageUrl) {
+ try {
+ if (ApplicationInsights.Util.canUseSessionStorage()) {
+ if (ApplicationInsights.Util.getSessionStorage(this.prevPageVisitDataKeyName) != null) {
+ throw new Error("Cannot call startPageVisit consecutively without first calling stopPageVisit");
+ }
+ var currPageVisitData = new PageVisitData(pageName, pageUrl);
+ var currPageVisitDataStr = JSON.stringify(currPageVisitData);
+ ApplicationInsights.Util.setSessionStorage(this.prevPageVisitDataKeyName, currPageVisitDataStr);
+ }
+ }
+ catch (e) {
+ ApplicationInsights._InternalLogging.warnToConsole("Call to start failed: " + ApplicationInsights.Util.dump(e));
+ }
+ };
+ PageVisitTimeManager.prototype.stopPageVisitTimer = function () {
+ try {
+ if (ApplicationInsights.Util.canUseSessionStorage()) {
+ var pageVisitEndTime = Date.now();
+ var pageVisitDataJsonStr = ApplicationInsights.Util.getSessionStorage(this.prevPageVisitDataKeyName);
+ if (pageVisitDataJsonStr) {
+ var prevPageVisitData = JSON.parse(pageVisitDataJsonStr);
+ prevPageVisitData.pageVisitTime = pageVisitEndTime - prevPageVisitData.pageVisitStartTime;
+ ApplicationInsights.Util.removeSessionStorage(this.prevPageVisitDataKeyName);
+ return prevPageVisitData;
+ }
+ else {
+ return null;
+ }
+ }
+ return null;
+ }
+ catch (e) {
+ ApplicationInsights._InternalLogging.warnToConsole("Stop page visit timer failed: " + ApplicationInsights.Util.dump(e));
+ return null;
+ }
+ };
+ return PageVisitTimeManager;
+ })();
+ Telemetry.PageVisitTimeManager = PageVisitTimeManager;
+ var PageVisitData = (function () {
+ function PageVisitData(pageName, pageUrl) {
+ this.pageVisitStartTime = Date.now();
+ this.pageName = pageName;
+ this.pageUrl = pageUrl;
+ }
+ return PageVisitData;
+ })();
+ Telemetry.PageVisitData = PageVisitData;
+ })(Telemetry = ApplicationInsights.Telemetry || (ApplicationInsights.Telemetry = {}));
+ })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
+})(Microsoft || (Microsoft = {}));
+var Microsoft;
+(function (Microsoft) {
+ var ApplicationInsights;
+ (function (ApplicationInsights) {
+ "use strict";
+ ApplicationInsights.Version = "0.18.0";
+ var AppInsights = (function () {
+ function AppInsights(config) {
+ var _this = this;
+ this.config = config || {};
+ var defaults = AppInsights.defaultConfig;
+ if (defaults !== undefined) {
+ for (var field in defaults) {
+ if (this.config[field] === undefined) {
+ this.config[field] = defaults[field];
+ }
+ }
+ }
+ ApplicationInsights._InternalLogging.verboseLogging = function () { return _this.config.verboseLogging; };
+ ApplicationInsights._InternalLogging.enableDebugExceptions = function () { return _this.config.enableDebug; };
+ var configGetters = {
+ instrumentationKey: function () { return _this.config.instrumentationKey; },
+ accountId: function () { return _this.config.accountId; },
+ appUserId: function () { return _this.config.appUserId; },
+ sessionRenewalMs: function () { return _this.config.sessionRenewalMs; },
+ sessionExpirationMs: function () { return _this.config.sessionExpirationMs; },
+ endpointUrl: function () { return _this.config.endpointUrl; },
+ emitLineDelimitedJson: function () { return _this.config.emitLineDelimitedJson; },
+ maxBatchSizeInBytes: function () { return _this.config.maxBatchSizeInBytes; },
+ maxBatchInterval: function () { return _this.config.maxBatchInterval; },
+ disableTelemetry: function () { return _this.config.disableTelemetry; },
+ sampleRate: function () { return _this.config.samplingPercentage; }
+ };
+ this.context = new ApplicationInsights.TelemetryContext(configGetters);
+ this._eventTracking = new Timing("trackEvent");
+ this._eventTracking.action = function (name, url, duration, properties, measurements) {
+ var event = new ApplicationInsights.Telemetry.Event(name, properties, measurements);
+ var data = new ApplicationInsights.Telemetry.Common.Data(ApplicationInsights.Telemetry.Event.dataType, event);
+ var envelope = new ApplicationInsights.Telemetry.Common.Envelope(data, ApplicationInsights.Telemetry.Event.envelopeType);
+ _this.context.track(envelope);
+ };
+ this._pageTracking = new Timing("trackPageView");
+ this._pageTracking.action = function (name, url, duration, properties, measurements) {
+ _this.sendPageViewInternal(name, url, duration, properties, measurements);
+ };
+ this._pageVisitTimeManager = new ApplicationInsights.Telemetry.PageVisitTimeManager(function (pageName, pageUrl, pageVisitTime) { return _this.trackPageVisitTime(pageName, pageUrl, pageVisitTime); });
+ }
+ AppInsights.prototype.sendPageViewInternal = function (name, url, duration, properties, measurements) {
+ var pageView = new ApplicationInsights.Telemetry.PageView(name, url, duration, properties, measurements);
+ var data = new ApplicationInsights.Telemetry.Common.Data(ApplicationInsights.Telemetry.PageView.dataType, pageView);
+ var envelope = new ApplicationInsights.Telemetry.Common.Envelope(data, ApplicationInsights.Telemetry.PageView.envelopeType);
+ this.context.track(envelope);
+ };
+ AppInsights.prototype.startTrackPage = function (name) {
+ try {
+ if (typeof name !== "string") {
+ name = window.document && window.document.title || "";
+ }
+ this._pageTracking.start(name);
+ }
+ catch (e) {
+ ApplicationInsights._InternalLogging.throwInternalNonUserActionable(0 /* CRITICAL */, "startTrackPage failed, page view may not be collected: " + ApplicationInsights.Util.dump(e));
+ }
+ };
+ AppInsights.prototype.stopTrackPage = function (name, url, properties, measurements) {
+ try {
+ if (typeof name !== "string") {
+ name = window.document && window.document.title || "";
+ }
+ if (typeof url !== "string") {
+ url = window.location && window.location.href || "";
+ }
+ this._pageTracking.stop(name, url, properties, measurements);
+ if (this.config.autoTrackPageVisitTime) {
+ this._pageVisitTimeManager.trackPreviousPageVisit(name, url);
+ }
+ }
+ catch (e) {
+ ApplicationInsights._InternalLogging.throwInternalNonUserActionable(0 /* CRITICAL */, "stopTrackPage failed, page view will not be collected: " + ApplicationInsights.Util.dump(e));
+ }
+ };
+ AppInsights.prototype.trackPageView = function (name, url, properties, measurements) {
+ try {
+ if (typeof name !== "string") {
+ name = window.document && window.document.title || "";
+ }
+ if (typeof url !== "string") {
+ url = window.location && window.location.href || "";
+ }
+ this.trackPageViewInternal(name, url, properties, measurements);
+ if (this.config.autoTrackPageVisitTime) {
+ this._pageVisitTimeManager.trackPreviousPageVisit(name, url);
+ }
+ }
+ catch (e) {
+ ApplicationInsights._InternalLogging.throwInternalNonUserActionable(0 /* CRITICAL */, "trackPageView failed, page view will not be collected: " + ApplicationInsights.Util.dump(e));
+ }
+ };
+ AppInsights.prototype.trackPageViewInternal = function (name, url, properties, measurements) {
+ var _this = this;
+ var durationMs = 0;
+ if (ApplicationInsights.Telemetry.PageViewPerformance.isPerformanceTimingSupported()) {
+ var startTime = window.performance.timing.navigationStart;
+ durationMs = ApplicationInsights.Telemetry.PageViewPerformance.getDuration(startTime, +new Date);
+ var handle = setInterval(function () {
+ try {
+ durationMs = ApplicationInsights.Telemetry.PageViewPerformance.getDuration(startTime, +new Date);
+ var timingDataReady = ApplicationInsights.Telemetry.PageViewPerformance.isPerformanceTimingDataReady();
+ var timeoutReached = durationMs > 60000;
+ if (timeoutReached || timingDataReady) {
+ clearInterval(handle);
+ durationMs = ApplicationInsights.Telemetry.PageViewPerformance.getDuration(startTime, +new Date);
+ var pageViewPerformance = new ApplicationInsights.Telemetry.PageViewPerformance(name, url, durationMs, properties, measurements);
+ _this.sendPageViewInternal(name, url, pageViewPerformance.isValid && !isNaN(pageViewPerformance.duration) ? +pageViewPerformance.duration : durationMs, properties, measurements);
+ if (pageViewPerformance.isValid) {
+ var pageViewPerformanceData = new ApplicationInsights.Telemetry.Common.Data(ApplicationInsights.Telemetry.PageViewPerformance.dataType, pageViewPerformance);
+ var pageViewPerformanceEnvelope = new ApplicationInsights.Telemetry.Common.Envelope(pageViewPerformanceData, ApplicationInsights.Telemetry.PageViewPerformance.envelopeType);
+ _this.context.track(pageViewPerformanceEnvelope);
+ }
+ _this.context._sender.triggerSend();
+ }
+ }
+ catch (e) {
+ ApplicationInsights._InternalLogging.throwInternalNonUserActionable(0 /* CRITICAL */, "trackPageView failed on page load calculation: " + ApplicationInsights.Util.dump(e));
+ }
+ }, 100);
+ }
+ };
+ AppInsights.prototype.startTrackEvent = function (name) {
+ try {
+ this._eventTracking.start(name);
+ }
+ catch (e) {
+ ApplicationInsights._InternalLogging.throwInternalNonUserActionable(0 /* CRITICAL */, "startTrackEvent failed, event will not be collected: " + ApplicationInsights.Util.dump(e));
+ }
+ };
+ AppInsights.prototype.stopTrackEvent = function (name, properties, measurements) {
+ try {
+ this._eventTracking.stop(name, undefined, properties, measurements);
+ }
+ catch (e) {
+ ApplicationInsights._InternalLogging.throwInternalNonUserActionable(0 /* CRITICAL */, "stopTrackEvent failed, event will not be collected: " + ApplicationInsights.Util.dump(e));
+ }
+ };
+ AppInsights.prototype.trackEvent = function (name, properties, measurements) {
+ try {
+ var eventTelemetry = new ApplicationInsights.Telemetry.Event(name, properties, measurements);
+ var data = new ApplicationInsights.Telemetry.Common.Data(ApplicationInsights.Telemetry.Event.dataType, eventTelemetry);
+ var envelope = new ApplicationInsights.Telemetry.Common.Envelope(data, ApplicationInsights.Telemetry.Event.envelopeType);
+ this.context.track(envelope);
+ }
+ catch (e) {
+ ApplicationInsights._InternalLogging.throwInternalNonUserActionable(0 /* CRITICAL */, "trackEvent failed, event will not be collected: " + ApplicationInsights.Util.dump(e));
+ }
+ };
+ AppInsights.prototype.trackException = function (exception, handledAt, properties, measurements) {
+ try {
+ if (!ApplicationInsights.Util.isError(exception)) {
+ try {
+ throw new Error(exception);
+ }
+ catch (error) {
+ exception = error;
+ }
+ }
+ var exceptionTelemetry = new ApplicationInsights.Telemetry.Exception(exception, handledAt, properties, measurements);
+ var data = new ApplicationInsights.Telemetry.Common.Data(ApplicationInsights.Telemetry.Exception.dataType, exceptionTelemetry);
+ var envelope = new ApplicationInsights.Telemetry.Common.Envelope(data, ApplicationInsights.Telemetry.Exception.envelopeType);
+ this.context.track(envelope);
+ }
+ catch (e) {
+ ApplicationInsights._InternalLogging.throwInternalNonUserActionable(0 /* CRITICAL */, "trackException failed, exception will not be collected: " + ApplicationInsights.Util.dump(e));
+ }
+ };
+ AppInsights.prototype.trackMetric = function (name, average, sampleCount, min, max, properties) {
+ try {
+ var telemetry = new ApplicationInsights.Telemetry.Metric(name, average, sampleCount, min, max, properties);
+ var data = new ApplicationInsights.Telemetry.Common.Data(ApplicationInsights.Telemetry.Metric.dataType, telemetry);
+ var envelope = new ApplicationInsights.Telemetry.Common.Envelope(data, ApplicationInsights.Telemetry.Metric.envelopeType);
+ this.context.track(envelope);
+ }
+ catch (e) {
+ ApplicationInsights._InternalLogging.throwInternalNonUserActionable(0 /* CRITICAL */, "trackMetric failed, metric will not be collected: " + ApplicationInsights.Util.dump(e));
+ }
+ };
+ AppInsights.prototype.trackTrace = function (message, properties) {
+ try {
+ var telemetry = new ApplicationInsights.Telemetry.Trace(message, properties);
+ var data = new ApplicationInsights.Telemetry.Common.Data(ApplicationInsights.Telemetry.Trace.dataType, telemetry);
+ var envelope = new ApplicationInsights.Telemetry.Common.Envelope(data, ApplicationInsights.Telemetry.Trace.envelopeType);
+ this.context.track(envelope);
+ }
+ catch (e) {
+ ApplicationInsights._InternalLogging.throwInternalNonUserActionable(1 /* WARNING */, "trackTrace failed, trace will not be collected: " + ApplicationInsights.Util.dump(e));
+ }
+ };
+ AppInsights.prototype.trackPageVisitTime = function (pageName, pageUrl, pageVisitTime) {
+ var properties = { PageName: pageName, PageUrl: pageUrl };
+ this.trackMetric("PageVisitTime", pageVisitTime, 1, pageVisitTime, pageVisitTime, properties);
+ };
+ AppInsights.prototype.flush = function () {
+ try {
+ this.context._sender.triggerSend();
+ }
+ catch (e) {
+ ApplicationInsights._InternalLogging.throwInternalNonUserActionable(0 /* CRITICAL */, "flush failed, telemetry will not be collected: " + ApplicationInsights.Util.dump(e));
+ }
+ };
+ AppInsights.prototype.setAuthenticatedUserContext = function (authenticatedUserId, accountId) {
+ try {
+ this.context.user.setAuthenticatedUserContext(authenticatedUserId, accountId);
+ }
+ catch (e) {
+ ApplicationInsights._InternalLogging.throwInternalUserActionable(1 /* WARNING */, "Setting auth user context failed. " + ApplicationInsights.Util.dump(e));
+ }
+ };
+ AppInsights.prototype.clearAuthenticatedUserContext = function () {
+ try {
+ this.context.user.clearAuthenticatedUserContext();
+ }
+ catch (e) {
+ ApplicationInsights._InternalLogging.throwInternalUserActionable(1 /* WARNING */, "Clearing auth user context failed. " + ApplicationInsights.Util.dump(e));
+ }
+ };
+ AppInsights.prototype.SendCORSException = function (properties) {
+ var exceptionData = Microsoft.ApplicationInsights.Telemetry.Exception.CreateSimpleException("Script error.", "Error", "unknown", "unknown", "The browser’s same-origin policy prevents us from getting the details of this exception.The exception occurred in a script loaded from an origin different than the web page.For cross- domain error reporting you can use crossorigin attribute together with appropriate CORS HTTP headers.For more information please see http://www.w3.org/TR/cors/.", 0, null);
+ exceptionData.properties = properties;
+ var data = new ApplicationInsights.Telemetry.Common.Data(ApplicationInsights.Telemetry.Exception.dataType, exceptionData);
+ var envelope = new ApplicationInsights.Telemetry.Common.Envelope(data, ApplicationInsights.Telemetry.Exception.envelopeType);
+ this.context.track(envelope);
+ };
+ AppInsights.prototype._onerror = function (message, url, lineNumber, columnNumber, error) {
+ try {
+ var properties = { url: url ? url : document.URL };
+ if (ApplicationInsights.Util.isCrossOriginError(message, url, lineNumber, columnNumber, error)) {
+ this.SendCORSException(properties);
+ }
+ else {
+ if (!ApplicationInsights.Util.isError(error)) {
+ var stack = "window.onerror@" + properties.url + ":" + lineNumber + ":" + (columnNumber || 0);
+ error = new Error(message);
+ error["stack"] = stack;
+ }
+ this.trackException(error, null, properties);
+ }
+ }
+ catch (exception) {
+ var errorString = error ? (error.name + ", " + error.message) : "null";
+ var exceptionDump = ApplicationInsights.Util.dump(exception);
+ ApplicationInsights._InternalLogging.throwInternalNonUserActionable(0 /* CRITICAL */, "_onerror threw " + exceptionDump + " while logging error, error will not be collected: " + errorString);
+ }
+ };
+ return AppInsights;
+ })();
+ ApplicationInsights.AppInsights = AppInsights;
+ var Timing = (function () {
+ function Timing(name) {
+ this._name = name;
+ this._events = {};
+ }
+ Timing.prototype.start = function (name) {
+ if (typeof this._events[name] !== "undefined") {
+ ApplicationInsights._InternalLogging.throwInternalUserActionable(1 /* WARNING */, "start" + this._name + " was called more than once for this event without calling stop" + this._name + ". key is '" + name + "'");
+ }
+ this._events[name] = +new Date;
+ };
+ Timing.prototype.stop = function (name, url, properties, measurements) {
+ var start = this._events[name];
+ if (isNaN(start)) {
+ ApplicationInsights._InternalLogging.throwInternalUserActionable(1 /* WARNING */, "stop" + this._name + " was called without a corresponding start" + this._name + " . Event name is '" + name + "'");
+ }
+ else {
+ var end = +new Date;
+ var duration = ApplicationInsights.Telemetry.PageViewPerformance.getDuration(start, end);
+ this.action(name, url, duration, properties, measurements);
+ }
+ delete this._events[name];
+ this._events[name] = undefined;
+ };
+ return Timing;
+ })();
+ })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
+})(Microsoft || (Microsoft = {}));
+var AI;
+(function (AI) {
+ "use strict";
+ var AjaxCallData = (function (_super) {
+ __extends(AjaxCallData, _super);
+ function AjaxCallData() {
+ this.ver = 2;
+ this.properties = {};
+ this.measurements = {};
+ _super.call(this);
+ }
+ return AjaxCallData;
+ })(AI.PageViewData);
+ AI.AjaxCallData = AjaxCallData;
+})(AI || (AI = {}));
+var AI;
+(function (AI) {
+ "use strict";
+ (function (DependencyKind) {
+ DependencyKind[DependencyKind["SQL"] = 0] = "SQL";
+ DependencyKind[DependencyKind["Http"] = 1] = "Http";
+ DependencyKind[DependencyKind["Other"] = 2] = "Other";
+ })(AI.DependencyKind || (AI.DependencyKind = {}));
+ var DependencyKind = AI.DependencyKind;
+})(AI || (AI = {}));
+var AI;
+(function (AI) {
+ "use strict";
+ (function (DependencySourceType) {
+ DependencySourceType[DependencySourceType["Undefined"] = 0] = "Undefined";
+ DependencySourceType[DependencySourceType["Aic"] = 1] = "Aic";
+ DependencySourceType[DependencySourceType["Apmc"] = 2] = "Apmc";
+ })(AI.DependencySourceType || (AI.DependencySourceType = {}));
+ var DependencySourceType = AI.DependencySourceType;
+})(AI || (AI = {}));
+var AI;
+(function (AI) {
+ "use strict";
+ var RemoteDependencyData = (function (_super) {
+ __extends(RemoteDependencyData, _super);
+ function RemoteDependencyData() {
+ this.ver = 2;
+ this.kind = 0 /* Measurement */;
+ this.dependencyKind = 2 /* Other */;
+ this.success = true;
+ this.dependencySource = 0 /* Undefined */;
+ this.properties = {};
+ _super.call(this);
+ }
+ return RemoteDependencyData;
+ })(Microsoft.Telemetry.Domain);
+ AI.RemoteDependencyData = RemoteDependencyData;
+})(AI || (AI = {}));
+var AI;
+(function (AI) {
+ "use strict";
+ var RequestData = (function (_super) {
+ __extends(RequestData, _super);
+ function RequestData() {
+ this.ver = 2;
+ this.properties = {};
+ this.measurements = {};
+ _super.call(this);
+ }
+ return RequestData;
+ })(Microsoft.Telemetry.Domain);
+ AI.RequestData = RequestData;
+})(AI || (AI = {}));
+var Microsoft;
+(function (Microsoft) {
+ var ApplicationInsights;
+ (function (ApplicationInsights) {
+ "use strict";
+ var Initialization = (function () {
+ function Initialization(snippet) {
+ snippet.queue = snippet.queue || [];
+ var config = snippet.config || {};
+ if (config && !config.instrumentationKey) {
+ config = snippet;
+ if (config["iKey"]) {
+ Microsoft.ApplicationInsights.Version = "0.10.0.0";
+ config.instrumentationKey = config["iKey"];
+ }
+ else if (config["applicationInsightsId"]) {
+ Microsoft.ApplicationInsights.Version = "0.7.2.0";
+ config.instrumentationKey = config["applicationInsightsId"];
+ }
+ else {
+ throw new Error("Cannot load Application Insights SDK, no instrumentationKey was provided.");
+ }
+ }
+ config = Initialization.getDefaultConfig(config);
+ this.snippet = snippet;
+ this.config = config;
+ }
+ Initialization.prototype.loadAppInsights = function () {
+ var appInsights = new Microsoft.ApplicationInsights.AppInsights(this.config);
+ if (this.config["iKey"]) {
+ var originalTrackPageView = appInsights.trackPageView;
+ appInsights.trackPageView = function (pagePath, properties, measurements) {
+ originalTrackPageView.apply(appInsights, [null, pagePath, properties, measurements]);
+ };
+ }
+ var legacyPageView = "logPageView";
+ if (typeof this.snippet[legacyPageView] === "function") {
+ appInsights[legacyPageView] = function (pagePath, properties, measurements) {
+ appInsights.trackPageView(null, pagePath, properties, measurements);
+ };
+ }
+ var legacyEvent = "logEvent";
+ if (typeof this.snippet[legacyEvent] === "function") {
+ appInsights[legacyEvent] = function (name, properties, measurements) {
+ appInsights.trackEvent(name, properties, measurements);
+ };
+ }
+ return appInsights;
+ };
+ Initialization.prototype.emptyQueue = function () {
+ try {
+ if (Microsoft.ApplicationInsights.Util.isArray(this.snippet.queue)) {
+ var length = this.snippet.queue.length;
+ for (var i = 0; i < length; i++) {
+ var call = this.snippet.queue[i];
+ call();
+ }
+ this.snippet.queue = undefined;
+ delete this.snippet.queue;
+ }
+ }
+ catch (exception) {
+ var message = "Failed to send queued telemetry";
+ if (exception && typeof exception.toString === "function") {
+ message += ": " + exception.toString();
+ }
+ Microsoft.ApplicationInsights._InternalLogging.throwInternalNonUserActionable(1 /* WARNING */, message);
+ }
+ };
+ Initialization.prototype.pollInteralLogs = function (appInsightsInstance) {
+ return setInterval(function () {
+ var queue = Microsoft.ApplicationInsights._InternalLogging.queue;
+ var length = queue.length;
+ for (var i = 0; i < length; i++) {
+ appInsightsInstance.trackTrace(queue[i]);
+ }
+ queue.length = 0;
+ }, this.config.diagnosticLogInterval);
+ };
+ Initialization.prototype.addHousekeepingBeforeUnload = function (appInsightsInstance) {
+ if ('onbeforeunload' in window) {
+ var performHousekeeping = function () {
+ appInsightsInstance.context._sender.triggerSend();
+ appInsightsInstance.context._sessionManager.backup();
+ };
+ if (!Microsoft.ApplicationInsights.Util.addEventHandler('beforeunload', performHousekeeping)) {
+ Microsoft.ApplicationInsights._InternalLogging.throwInternalNonUserActionable(0 /* CRITICAL */, 'Could not add handler for beforeunload');
+ }
+ }
+ };
+ Initialization.getDefaultConfig = function (config) {
+ if (!config) {
+ config = {};
+ }
+ config.endpointUrl = config.endpointUrl || "//dc.services.visualstudio.com/v2/track";
+ config.accountId = config.accountId;
+ config.appUserId = config.appUserId;
+ config.sessionRenewalMs = 30 * 60 * 1000;
+ config.sessionExpirationMs = 24 * 60 * 60 * 1000;
+ config.maxBatchSizeInBytes = config.maxBatchSizeInBytes > 0 ? config.maxBatchSizeInBytes : 1000000;
+ config.maxBatchInterval = !isNaN(config.maxBatchInterval) ? config.maxBatchInterval : 15000;
+ config.enableDebug = ApplicationInsights.Util.stringToBoolOrDefault(config.enableDebug);
+ config.autoCollectErrors = (config.autoCollectErrors !== undefined && config.autoCollectErrors !== null) ? ApplicationInsights.Util.stringToBoolOrDefault(config.autoCollectErrors) : true;
+ config.disableTelemetry = ApplicationInsights.Util.stringToBoolOrDefault(config.disableTelemetry);
+ config.verboseLogging = ApplicationInsights.Util.stringToBoolOrDefault(config.verboseLogging);
+ config.emitLineDelimitedJson = ApplicationInsights.Util.stringToBoolOrDefault(config.emitLineDelimitedJson);
+ config.diagnosticLogInterval = config.diagnosticLogInterval || 10000;
+ config.autoTrackPageVisitTime = ApplicationInsights.Util.stringToBoolOrDefault(config.autoTrackPageVisitTime);
+ if (isNaN(config.samplingPercentage) || config.samplingPercentage <= 0 || config.samplingPercentage >= 100) {
+ config.samplingPercentage = 100;
+ }
+ return config;
+ };
+ return Initialization;
+ })();
+ ApplicationInsights.Initialization = Initialization;
+ })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
+})(Microsoft || (Microsoft = {}));
+function initializeAppInsights() {
+ try {
+ if (typeof window !== "undefined" && typeof JSON !== "undefined") {
+ var aiName = "appInsights";
+ if (window[aiName] === undefined) {
+ Microsoft.ApplicationInsights.AppInsights.defaultConfig = Microsoft.ApplicationInsights.Initialization.getDefaultConfig();
+ }
+ else {
+ var snippet = window[aiName] || {};
+ var init = new Microsoft.ApplicationInsights.Initialization(snippet);
+ var appInsightsLocal = init.loadAppInsights();
+ for (var field in appInsightsLocal) {
+ snippet[field] = appInsightsLocal[field];
+ }
+ init.emptyQueue();
+ init.pollInteralLogs(appInsightsLocal);
+ init.addHousekeepingBeforeUnload(appInsightsLocal);
+ }
+ }
+ }
+ catch (e) {
+ Microsoft.ApplicationInsights._InternalLogging.warnToConsole('Failed to initialize AppInsights JS SDK: ' + e.message);
+ }
+}
+initializeAppInsights();
diff --git a/LLV/scripts/ai.0.15.0-build58334.min.js b/LLV/scripts/ai.0.15.0-build58334.min.js
new file mode 100644
index 0000000..db2a9be
--- /dev/null
+++ b/LLV/scripts/ai.0.15.0-build58334.min.js
@@ -0,0 +1 @@
+function initializeAppInsights(){var i,r;try{if(typeof window!="undefined"&&typeof JSON!="undefined")if(i="appInsights",window[i]===undefined)Microsoft.ApplicationInsights.AppInsights.defaultConfig=Microsoft.ApplicationInsights.Initialization.getDefaultConfig();else{var u=window[i]||{},n=new Microsoft.ApplicationInsights.Initialization(u),t=n.loadAppInsights();for(r in t)u[r]=t[r];n.emptyQueue();n.pollInteralLogs(t);n.addHousekeepingBeforeUnload(t)}}catch(f){Microsoft.ApplicationInsights._InternalLogging.warnToConsole("Failed to initialize AppInsights JS SDK: "+f.message)}}var __extends,AI,Microsoft;(function(n){var t;(function(n){(function(n){n[n.CRITICAL=0]="CRITICAL";n[n.WARNING=1]="WARNING"})(n.LoggingSeverity||(n.LoggingSeverity={}));var i=n.LoggingSeverity,t=function(){function n(){}return n.throwInternalNonUserActionable=function(n,t){if(this.enableDebugExceptions())throw t;else this.warnToConsole(t),this.logInternalMessage(n,this.AiNonUserActionablePrefix+t)},n.throwInternalUserActionable=function(n,t){if(this.enableDebugExceptions())throw t;else this.warnToConsole(t),this.logInternalMessage(n,this.AiUserActionablePrefix+t)},n.warnToConsole=function(n){typeof console=="undefined"||!console||(typeof console.warn=="function"?console.warn(n):typeof console.log=="function"&&console.log(n))},n.resetInternalMessageCount=function(){this._messageCount=0},n.setMaxInternalMessageLimit=function(n){if(!n)throw new Error("limit cannot be undefined.");this.MAX_INTERNAL_MESSAGE_LIMIT=n},n.logInternalMessage=function(n,t){if(!this._areInternalMessagesThrottled()&&((this.verboseLogging()||n===0)&&(this.queue.push(t),this._messageCount++),this._messageCount==this.MAX_INTERNAL_MESSAGE_LIMIT)){var i=this.AiNonUserActionablePrefix+"Internal events throttle limit per PageView reached for this app.";this.queue.push(i);this.warnToConsole(i)}},n._areInternalMessagesThrottled=function(){return this._messageCount>=this.MAX_INTERNAL_MESSAGE_LIMIT},n.AiUserActionablePrefix="AI: ",n.AiNonUserActionablePrefix="AI (Internal): ",n.enableDebugExceptions=function(){return!1},n.verboseLogging=function(){return!1},n.queue=[],n.MAX_INTERNAL_MESSAGE_LIMIT=25,n._messageCount=0,n}();n._InternalLogging=t})(t=n.ApplicationInsights||(n.ApplicationInsights={}))})(Microsoft||(Microsoft={})),function(n){var t;(function(n){var t=function(){function t(){}return t._getStorageObject=function(){try{return window.localStorage?window.localStorage:null}catch(t){return n._InternalLogging.warnToConsole("Failed to get client localStorage: "+t.message),null}},t.canUseLocalStorage=function(){return!!t._getStorageObject()},t.getStorage=function(i){var r=t._getStorageObject();if(r!==null)try{return r.getItem(i)}catch(u){n._InternalLogging.throwInternalNonUserActionable(1,"Browser failed read of local storage."+t.dump(u))}return null},t.setStorage=function(i,r){var u=t._getStorageObject();if(u!==null)try{return u.setItem(i,r),!0}catch(f){n._InternalLogging.throwInternalNonUserActionable(1,"Browser failed write to local storage."+t.dump(f))}return!1},t.removeStorage=function(i){var r=t._getStorageObject();if(r!==null)try{return r.removeItem(i),!0}catch(u){n._InternalLogging.throwInternalNonUserActionable(1,"Browser failed removal of local storage item."+t.dump(u))}return!1},t._getSessionStorageObject=function(){try{return window.sessionStorage?window.sessionStorage:null}catch(t){return n._InternalLogging.warnToConsole("Failed to get client session storage: "+t.message),null}},t.canUseSessionStorage=function(){return!!t._getSessionStorageObject()},t.getSessionStorage=function(i){var r=t._getSessionStorageObject();if(r!==null)try{return r.getItem(i)}catch(u){n._InternalLogging.throwInternalNonUserActionable(0,"Browser failed read of session storage."+t.dump(u))}return null},t.setSessionStorage=function(i,r){var u=t._getSessionStorageObject();if(u!==null)try{return u.setItem(i,r),!0}catch(f){n._InternalLogging.throwInternalNonUserActionable(0,"Browser failed write to session storage."+t.dump(f))}return!1},t.removeSessionStorage=function(i){var r=t._getSessionStorageObject();if(r!==null)try{return r.removeItem(i),!0}catch(u){n._InternalLogging.throwInternalNonUserActionable(0,"Browser failed removal of session storage item."+t.dump(u))}return!1},t.setCookie=function(n,i){t.document.cookie=n+"="+i+";path=/"},t.stringToBoolOrDefault=function(n){return n?n.toString().toLowerCase()==="true":!1},t.getCookie=function(n){var e="",f,u,r,i;if(n&&n.length)for(f=n+"=",u=t.document.cookie.split(";"),r=0;r>4&15]+n[t>>8&15]+n[t>>12&15]+n[t>>16&15]+n[t>>20&15]+n[t>>24&15]+n[t>>28&15];return u=n[8+Math.random()*4|0],i.substr(0,8)+"-"+i.substr(9,4)+"-4"+i.substr(13,3)+"-"+u+i.substr(16,3)+"-"+i.substr(19,12)},t.isArray=function(n){return Object.prototype.toString.call(n)==="[object Array]"},t.isError=function(n){return Object.prototype.toString.call(n)==="[object Error]"},t.isDate=function(n){return Object.prototype.toString.call(n)==="[object Date]"},t.toISOStringForIE8=function(n){if(t.isDate(n)){function i(n){var t=String(n);return t.length===1&&(t="0"+t),t}return Date.prototype.toISOString?n.toISOString():n.getUTCFullYear()+"-"+i(n.getUTCMonth()+1)+"-"+i(n.getUTCDate())+"T"+i(n.getUTCHours())+":"+i(n.getUTCMinutes())+":"+i(n.getUTCSeconds())+"."+String((n.getUTCMilliseconds()/1e3).toFixed(3)).slice(2,5)+"Z"}},t.msToTimeSpan=function(n){(isNaN(n)||n<0)&&(n=0);var t=""+n%1e3,i=""+Math.floor(n/1e3)%60,r=""+Math.floor(n/6e4)%60,u=""+Math.floor(n/36e5)%24;return t=t.length===1?"00"+t:t.length===2?"0"+t:t,i=i.length<2?"0"+i:i,r=r.length<2?"0"+r:r,u=u.length<2?"0"+u:u,u+":"+r+":"+i+"."+t},t.isCrossOriginError=function(n,t,i,r,u){return(n=="Script error."||n=="Script error")&&t==""&&i==0&&r==0&&u==null},t.dump=function(n){var t=Object.prototype.toString.call(n),i=JSON.stringify(n);return t==="[object Error]"&&(i="{ stack: '"+n.stack+"', message: '"+n.message+"', name: '"+n.name+"'"),t+i},t.addEventHandler=function(n,t){if(!window||typeof n!="string"||typeof t!="function")return!1;var i="on"+n;if(window.addEventListener)window.addEventListener(n,t,!1);else if(window.attachEvent)window.attachEvent(i,t);else return!1;return!0},t.document=typeof document!="undefined"?document:{},t.NotSpecified="not_specified",t}();n.Util=t})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){var t;(function(n){"use strict";var t=function(){function t(){}return t.serialize=function(n){var i=t._serializeObject(n,"root");return JSON.stringify(i)},t._serializeObject=function(i,r){var e="__aiCircularRefCheck",f={},u,s;if(!i)return n._InternalLogging.throwInternalUserActionable(0,"cannot serialize "+r+" because it is null or undefined"),f;if(i[e])return n._InternalLogging.throwInternalUserActionable(1,"Circular reference detected while serializing: '"+r),f;if(!i.aiDataContract){if(r==="measurements")f=t._serializeStringMap(i,"number",r);else if(r==="properties")f=t._serializeStringMap(i,"string",r);else if(r==="tags")f=t._serializeStringMap(i,"string",r);else if(n.Util.isArray(i))f=t._serializeArray(i,r);else{n._InternalLogging.throwInternalUserActionable(1,"Attempting to serialize an object which does not implement ISerializable: "+r);try{JSON.stringify(i);f=i}catch(o){n._InternalLogging.throwInternalUserActionable(0,o&&typeof o.toString=="function"?o.toString():"Error serializing object")}}return f}i[e]=!0;for(u in i.aiDataContract){var h=i.aiDataContract[u],c=typeof h!="boolean",l=i[u]!==undefined,a=typeof i[u]=="object"&&i[u]!==null;if(h&&!l&&!c){n._InternalLogging.throwInternalNonUserActionable(0,"Missing required field specification: The field '"+u+"' on '"+r+"' is required but not present on source");continue}s=a?c?t._serializeArray(i[u],u):t._serializeObject(i[u],u):i[u];s!==undefined&&(f[u]=s)}return delete i[e],f},t._serializeArray=function(i,r){var f=undefined,u,e,o;if(!!i)if(n.Util.isArray(i))for(f=[],u=0;u100||t<0)&&(n._InternalLogging.throwInternalUserActionable(1,"Sampling rate is out of range (0..100): '"+t+"'. Sampling will be disabled, you may be sending too much data which may affect your AI service level."),this.sampleRate=100);this.sampleRate=t}return t.prototype.isSampledIn=function(t){if(this.sampleRate==100)return!0;var i=n.SamplingScoreGenerator.getScore(t);return ithis.config.sessionExpirationMs(),i=n-this.automaticSession.renewalDate>this.config.sessionRenewalMs();t||i?(typeof this._sessionHandler=="function"&&this._sessionHandler(1,this.automaticSession.renewalDate),this.automaticSession.isFirst=undefined,this.renew()):(this.automaticSession.renewalDate=+new Date,this.setCookie(this.automaticSession.id,this.automaticSession.acquisitionDate,this.automaticSession.renewalDate))},t.prototype.backup=function(){this.setStorage(this.automaticSession.id,this.automaticSession.acquisitionDate,this.automaticSession.renewalDate)},t.prototype.initializeAutomaticSession=function(){var t=n.Util.getCookie("ai_session"),i;t&&typeof t.split=="function"?this.initializeAutomaticSessionWithData(t):(i=n.Util.getStorage("ai_session"),i&&this.initializeAutomaticSessionWithData(i));this.automaticSession.id||(this.automaticSession.isFirst=!0,this.renew())},t.prototype.initializeAutomaticSessionWithData=function(t){var i=t.split("|"),r,u;i.length>0&&(this.automaticSession.id=i[0]);try{i.length>1&&(r=+i[1],this.automaticSession.acquisitionDate=+new Date(r),this.automaticSession.acquisitionDate=this.automaticSession.acquisitionDate>0?this.automaticSession.acquisitionDate:0);i.length>2&&(u=+i[2],this.automaticSession.renewalDate=+new Date(u),this.automaticSession.renewalDate=this.automaticSession.renewalDate>0?this.automaticSession.renewalDate:0)}catch(f){n._InternalLogging.throwInternalNonUserActionable(0,"Error parsing ai_session cookie, session will be reset: "+n.Util.dump(f))}this.automaticSession.renewalDate==0&&n._InternalLogging.throwInternalNonUserActionable(1,"AI session renewal date is 0, session will be reset.")},t.prototype.renew=function(){var t=+new Date;this.automaticSession.id=n.Util.newGuid();this.automaticSession.acquisitionDate=t;this.automaticSession.renewalDate=t;this.setCookie(this.automaticSession.id,this.automaticSession.acquisitionDate,this.automaticSession.renewalDate);typeof this._sessionHandler=="function"&&this._sessionHandler(0,t);n.Util.canUseLocalStorage()||n._InternalLogging.throwInternalNonUserActionable(1,"Browser does not support local storage. Session durations will be inaccurate.")},t.prototype.setCookie=function(t,i,r){var f=i+this.config.sessionExpirationMs(),e=r+this.config.sessionRenewalMs(),u=new Date,o=[t,i,r];f0&&(this.id=e[0]));this.id||(this.id=n.Util.newGuid(),u=new Date,o=n.Util.toISOStringForIE8(u),this.accountAcquisitionDate=o,u.setTime(u.getTime()+31536e6),h=[this.id,o],n.Util.setCookie(t.userCookieName,h.join(t.cookieSeparator)+";expires="+u.toUTCString()),n.Util.removeStorage("ai_session"));this.accountId=i;f=n.Util.getCookie(t.authUserCookieName);f&&(f=decodeURI(f),r=f.split(t.cookieSeparator),r[0]&&(this.authenticatedId=r[0]),r.length>1&&r[1]&&(this.accountId=r[1]))}return t.prototype.setAuthenticatedUserContext=function(i,r){var f=!this.validateUserInput(i)||r&&!this.validateUserInput(r),u;if(f){n._InternalLogging.throwInternalUserActionable(1,"Setting auth user context failed. User auth/account id should be of type string, and not contain commas, semi-colons, equal signs, spaces, or vertical-bars.");return}this.authenticatedId=i;u=this.authenticatedId;r&&(this.accountId=r,u=[this.authenticatedId,this.accountId].join(t.cookieSeparator));n.Util.setCookie(t.authUserCookieName,encodeURI(u))},t.prototype.clearAuthenticatedUserContext=function(){this.authenticatedId=null;this.accountId=null;n.Util.deleteCookie(t.authUserCookieName)},t.prototype.validateUserInput=function(n){return typeof n!="string"||!n||n.match(/,|;|=| |\|/)?!1:!0},t.cookieSeparator="|",t.userCookieName="ai_user",t.authUserCookieName="ai_authUser",t}();t.User=i})(t=n.Context||(n.Context={}))})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){var t;(function(n){"use strict";var t=function(){function t(n){if(this._buffer=[],this._lastSend=0,this._config=n,this._sender=null,typeof XMLHttpRequest!="undefined"){var t=new XMLHttpRequest;"withCredentials"in t?this._sender=this._xhrSender:typeof XDomainRequest!="undefined"&&(this._sender=this._xdrSender)}}return t.prototype.send=function(t){var r=this,i;try{if(this._config.disableTelemetry())return;if(!t){n._InternalLogging.throwInternalNonUserActionable(0,"Cannot send empty telemetry");return}if(!this._sender){n._InternalLogging.throwInternalNonUserActionable(0,"Sender was not initialized");return}i=n.Serializer.serialize(t);this._getSizeInBytes(this._buffer)+i.length>this._config.maxBatchSizeInBytes()&&this.triggerSend();this._buffer.push(i);this._timeoutHandle||(this._timeoutHandle=setTimeout(function(){r._timeoutHandle=null;r.triggerSend()},this._config.maxBatchInterval()))}catch(u){n._InternalLogging.throwInternalNonUserActionable(0,"Failed adding telemetry to the sender's buffer, some telemetry will be lost: "+n.Util.dump(u))}},t.prototype._getSizeInBytes=function(n){var r=0,t,i;if(n&&n.length)for(t=0;t=300)&&n.status!==0?t._onError(i,n.responseText||n.response||""):t._onSuccess(i))},t._xdrOnLoad=function(n,i){n&&(n.responseText+""=="200"||n.responseText==="")?t._onSuccess(i):t._onError(i,n&&n.responseText||"")},t._onError=function(t,i){n._InternalLogging.throwInternalNonUserActionable(1,"Failed to send telemetry:\n"+i)},t._onSuccess=function(){},t}();n.Sender=t})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){var t;(function(n){"use strict";var t=function(){function n(){}return n}();n.Domain=t})(t=n.Telemetry||(n.Telemetry={}))}(Microsoft||(Microsoft={})),function(n){"use strict";(function(n){n[n.Verbose=0]="Verbose";n[n.Information=1]="Information";n[n.Warning=2]="Warning";n[n.Error=3]="Error";n[n.Critical=4]="Critical"})(n.SeverityLevel||(n.SeverityLevel={}));var t=n.SeverityLevel}(AI||(AI={})),function(n){"use strict";var t=function(n){function t(){this.ver=2;this.properties={};n.call(this)}return __extends(t,n),t}(Microsoft.Telemetry.Domain);n.MessageData=t}(AI||(AI={})),function(n){var t;(function(n){var t;(function(t){var i;(function(t){"use strict";var i=function(){function t(){}return t.sanitizeKeyAndAddUniqueness=function(n,i){var e=n.length,r=t.sanitizeKey(n),f,u;if(r.length!==e){for(f=0,u=r;i[u]!==undefined;)f++,u=r.substring(0,t.MAX_NAME_LENGTH-3)+t.padNumber(f);r=u}return r},t.sanitizeKey=function(i){return i&&(i=n.Util.trim(i.toString()),i.search(/[^0-9a-zA-Z-._()\/ ]/g)>=0&&(i=i.replace(/[^0-9a-zA-Z-._()\/ ]/g,"_"),n._InternalLogging.throwInternalUserActionable(1,"name contains illegal characters. Illgeal character have been replaced with '_'. new name: "+i)),i.length>t.MAX_NAME_LENGTH&&(i=i.substring(0,t.MAX_NAME_LENGTH),n._InternalLogging.throwInternalUserActionable(1,"name is too long. It has been truncated to "+t.MAX_NAME_LENGTH+" characters. name: "+i))),i},t.sanitizeString=function(i){return i&&(i=n.Util.trim(i),i.toString().length>t.MAX_STRING_LENGTH&&(i=i.substring(0,t.MAX_STRING_LENGTH),n._InternalLogging.throwInternalUserActionable(1,"string value is too long. It has been truncated to "+t.MAX_STRING_LENGTH+" characters. value: "+i))),i},t.sanitizeUrl=function(i){return i&&i.length>t.MAX_URL_LENGTH&&(i=i.substring(0,t.MAX_URL_LENGTH),n._InternalLogging.throwInternalUserActionable(1,"url is too long, it has been trucated to "+t.MAX_URL_LENGTH+" characters. url: "+i)),i},t.sanitizeMessage=function(i){return i&&i.length>t.MAX_MESSAGE_LENGTH&&(i=i.substring(0,t.MAX_MESSAGE_LENGTH),n._InternalLogging.throwInternalUserActionable(1,"message is too long, it has been trucated to "+t.MAX_MESSAGE_LENGTH+" characters. message: "+i)),i},t.sanitizeException=function(i){return i&&i.length>t.MAX_EXCEPTION_LENGTH&&(i=i.substring(0,t.MAX_EXCEPTION_LENGTH),n._InternalLogging.throwInternalUserActionable(1,"exception is too long, iit has been trucated to "+t.MAX_EXCEPTION_LENGTH+" characters. exception: "+i)),i},t.sanitizeProperties=function(n){var r,i,u;if(n){r={};for(i in n)u=t.sanitizeString(n[i]),i=t.sanitizeKeyAndAddUniqueness(i,r),r[i]=u;n=r}return n},t.sanitizeMeasurements=function(n){var r,i,u;if(n){r={};for(i in n)u=n[i],i=t.sanitizeKeyAndAddUniqueness(i,r),r[i]=u;n=r}return n},t.padNumber=function(n){var t="00"+n;return t.substr(t.length-3)},t.MAX_NAME_LENGTH=150,t.MAX_STRING_LENGTH=1024,t.MAX_URL_LENGTH=2048,t.MAX_MESSAGE_LENGTH=32768,t.MAX_EXCEPTION_LENGTH=32768,t}();t.DataSanitizer=i})(i=t.Common||(t.Common={}))})(t=n.Telemetry||(n.Telemetry={}))})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){var t;(function(n){var t;(function(t){"use strict";var i=function(i){function r(r,u){i.call(this);this.aiDataContract={ver:!0,message:!0,severityLevel:!1,measurements:!1,properties:!1};r=r||n.Util.NotSpecified;this.message=t.Common.DataSanitizer.sanitizeMessage(r);this.properties=t.Common.DataSanitizer.sanitizeProperties(u)}return __extends(r,i),r.envelopeType="Microsoft.ApplicationInsights.Message",r.dataType="MessageData",r}(AI.MessageData);t.Trace=i})(t=n.Telemetry||(n.Telemetry={}))})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){"use strict";var t=function(n){function t(){this.ver=2;this.properties={};this.measurements={};n.call(this)}return __extends(t,n),t}(Microsoft.Telemetry.Domain);n.EventData=t}(AI||(AI={})),function(n){var t;(function(n){var t;(function(t){"use strict";var i=function(t){function i(i,r,u){t.call(this);this.aiDataContract={ver:!0,name:!0,properties:!1,measurements:!1};this.name=n.Telemetry.Common.DataSanitizer.sanitizeString(i);this.properties=n.Telemetry.Common.DataSanitizer.sanitizeProperties(r);this.measurements=n.Telemetry.Common.DataSanitizer.sanitizeMeasurements(u)}return __extends(i,t),i.envelopeType="Microsoft.ApplicationInsights.Event",i.dataType="EventData",i}(AI.EventData);t.Event=i})(t=n.Telemetry||(n.Telemetry={}))})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){"use strict";var t=function(){function n(){this.hasFullStack=!0;this.parsedStack=[]}return n}();n.ExceptionDetails=t}(AI||(AI={})),function(n){"use strict";var t=function(n){function t(){this.ver=2;this.exceptions=[];this.properties={};this.measurements={};n.call(this)}return __extends(t,n),t}(Microsoft.Telemetry.Domain);n.ExceptionData=t}(AI||(AI={})),function(n){"use strict";var t=function(){function n(){}return n}();n.StackFrame=t}(AI||(AI={})),function(n){var t;(function(n){var t;(function(t){"use strict";var u=function(i){function u(t,u,f,e){i.call(this);this.aiDataContract={ver:!0,handledAt:!0,exceptions:!0,severityLevel:!1,properties:!1,measurements:!1};this.properties=n.Telemetry.Common.DataSanitizer.sanitizeProperties(f);this.measurements=n.Telemetry.Common.DataSanitizer.sanitizeMeasurements(e);this.handledAt=u||"unhandled";this.exceptions=[new r(t)]}return __extends(u,i),u.CreateSimpleException=function(n,i,r,u,f,e,o){var c,s,h;try{throw new Error;}catch(l){c=new t.Exception(l)}return s=c.exceptions[0].parsedStack[0],s.assembly=r,s.fileName=u,s.level=0,s.line=e,s.method="unknown",h=c.exceptions[0],h.hasFullStack=!0,h.message=n,h.parsedStack=null,h.stack=f,h.typeName=i,c.handledAt=o||"unhandled",c},u.envelopeType="Microsoft.ApplicationInsights.Exception",u.dataType="ExceptionData",u}(AI.ExceptionData),r,i;t.Exception=u;r=function(r){function u(i){r.call(this);this.aiDataContract={id:!1,outerId:!1,typeName:!0,message:!0,hasFullStack:!1,stack:!1,parsedStack:[]};this.typeName=t.Common.DataSanitizer.sanitizeString(i.name||n.Util.NotSpecified);this.message=t.Common.DataSanitizer.sanitizeMessage(i.message||n.Util.NotSpecified);var u=i.stack;this.parsedStack=this.parseStack(u);this.stack=t.Common.DataSanitizer.sanitizeException(u);this.hasFullStack=n.Util.isArray(this.parsedStack)&&this.parsedStack.length>0}return __extends(u,r),u.prototype.parseStack=function(n){var t=undefined,e,l,o,r,a,s,h,p,w,b;if(typeof n=="string"){for(e=n.split("\n"),t=[],l=0,o=0,r=0;r<=e.length;r++)a=e[r],i.regex.test(a)&&(s=new i(e[r],l++),o+=s.sizeInBytes,t.push(s));if(h=32768,o>h)for(var u=0,f=t.length-1,v=0,c=u,y=f;uh){b=y-c+1;t.splice(c,b);break}c=u;y=f;u++;f--}}return t},u}(AI.ExceptionDetails);i=function(t){function i(r,u){t.call(this);this.sizeInBytes=0;this.aiDataContract={level:!0,method:!0,assembly:!1,fileName:!1,line:!1};this.level=u;this.method="unavailable";this.assembly=n.Util.trim(r);var f=r.match(i.regex);f&&f.length>=5&&(this.method=n.Util.trim(f[2]),this.fileName=n.Util.trim(f[4]),this.line=parseInt(f[5])||0);this.sizeInBytes+=this.method.length;this.sizeInBytes+=this.fileName.length;this.sizeInBytes+=this.assembly.length;this.sizeInBytes+=i.baseSize;this.sizeInBytes+=this.level.toString().length;this.sizeInBytes+=this.line.toString().length}return __extends(i,t),i.regex=/^([\s]+at)?(.*?)(\@|\s\(|\s)([^\(\@\n]+):([0-9]+):([0-9]+)(\)?)$/,i.baseSize=58,i}(AI.StackFrame)})(t=n.Telemetry||(n.Telemetry={}))})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){"use strict";var t=function(n){function t(){this.ver=2;this.metrics=[];this.properties={};n.call(this)}return __extends(t,n),t}(Microsoft.Telemetry.Domain);n.MetricData=t}(AI||(AI={})),function(n){"use strict";(function(n){n[n.Measurement=0]="Measurement";n[n.Aggregation=1]="Aggregation"})(n.DataPointType||(n.DataPointType={}));var t=n.DataPointType}(AI||(AI={})),function(n){"use strict";var t=function(){function n(){this.kind=0}return n}();n.DataPoint=t}(AI||(AI={})),function(n){var t;(function(n){var t;(function(n){var t;(function(n){"use strict";var t=function(n){function t(){n.apply(this,arguments);this.aiDataContract={name:!0,kind:!1,value:!0,count:!1,min:!1,max:!1,stdDev:!1}}return __extends(t,n),t}(AI.DataPoint);n.DataPoint=t})(t=n.Common||(n.Common={}))})(t=n.Telemetry||(n.Telemetry={}))})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){var t;(function(t){var i;(function(i){"use strict";var r=function(r){function u(u,f,e,o,s,h){r.call(this);this.aiDataContract={ver:!0,metrics:!0,properties:!1};var c=new n.ApplicationInsights.Telemetry.Common.DataPoint;c.count=e>0?e:undefined;c.max=isNaN(s)||s===null?undefined:s;c.min=isNaN(o)||o===null?undefined:o;c.name=i.Common.DataSanitizer.sanitizeString(u);c.value=f;this.metrics=[c];this.properties=t.Telemetry.Common.DataSanitizer.sanitizeProperties(h)}return __extends(u,r),u.envelopeType="Microsoft.ApplicationInsights.Metric",u.dataType="MetricData",u}(AI.MetricData);i.Metric=r})(i=t.Telemetry||(t.Telemetry={}))})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){"use strict";var t=function(n){function t(){this.ver=2;this.properties={};this.measurements={};n.call(this)}return __extends(t,n),t}(n.EventData);n.PageViewData=t}(AI||(AI={})),function(n){var t;(function(n){var t;(function(t){"use strict";var i=function(i){function r(r,u,f,e,o){i.call(this);this.aiDataContract={ver:!0,name:!1,url:!1,duration:!1,properties:!1,measurements:!1};this.url=t.Common.DataSanitizer.sanitizeUrl(u);this.name=t.Common.DataSanitizer.sanitizeString(r||n.Util.NotSpecified);isNaN(f)||(this.duration=n.Util.msToTimeSpan(f));this.properties=n.Telemetry.Common.DataSanitizer.sanitizeProperties(e);this.measurements=n.Telemetry.Common.DataSanitizer.sanitizeMeasurements(o)}return __extends(r,i),r.envelopeType="Microsoft.ApplicationInsights.Pageview",r.dataType="PageviewData",r}(AI.PageViewData);t.PageView=i})(t=n.Telemetry||(n.Telemetry={}))})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){"use strict";var t=function(n){function t(){this.ver=2;this.properties={};this.measurements={};n.call(this)}return __extends(t,n),t}(n.PageViewData);n.PageViewPerfData=t}(AI||(AI={})),function(n){var t;(function(n){var t;(function(t){"use strict";var i=function(i){function r(u,f,e,o,s){var h;if(i.call(this),this.aiDataContract={ver:!0,name:!1,url:!1,duration:!1,perfTotal:!1,networkConnect:!1,sentRequest:!1,receivedResponse:!1,domProcessing:!1,properties:!1,measurements:!1},this.isValid=!1,h=r.getPerformanceTiming(),h){var c=r.getDuration(h.navigationStart,h.loadEventEnd),l=r.getDuration(h.navigationStart,h.connectEnd),a=r.getDuration(h.requestStart,h.responseStart),v=r.getDuration(h.responseStart,h.responseEnd),y=r.getDuration(h.responseEnd,h.loadEventEnd);c==0?n._InternalLogging.throwInternalNonUserActionable(1,"error calculating page view performance: total='"+c+"', network='"+l+"', request='"+a+"', response='"+v+"', dom='"+y+"'"):c0&&n.navigationStart>0&&n.responseStart>0&&n.requestStart>0&&n.loadEventEnd>0&&n.responseEnd>0&&n.connectEnd>0&&n.domLoading>0},r.getDuration=function(n,t){var i=0;return isNaN(n)||isNaN(t)||(i=Math.max(t-n,0)),i},r.envelopeType="Microsoft.ApplicationInsights.PageviewPerformance",r.dataType="PageviewPerformanceData",r}(AI.PageViewPerfData);t.PageViewPerformance=i})(t=n.Telemetry||(n.Telemetry={}))})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){"use strict";var t=function(n){function t(){this.ver=2;this.state=0;n.call(this)}return __extends(t,n),t}(Microsoft.Telemetry.Domain);n.SessionStateData=t}(AI||(AI={})),function(n){var t;(function(n){var t;(function(n){"use strict";var t=function(n){function t(t){n.call(this);this.aiDataContract={ver:!0,state:!0};this.state=t}return __extends(t,n),t.envelopeType="Microsoft.ApplicationInsights.SessionState",t.dataType="SessionStateData",t}(AI.SessionStateData);n.SessionTelemetry=t})(t=n.Telemetry||(n.Telemetry={}))})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){var t;(function(n){"use strict";var t=function(){function t(i){var r=this;this._config=i;this._sender=new n.Sender(i);typeof window!="undefined"&&(this._sessionManager=new n.Context._SessionManager(i,function(n,i){return t._sessionHandler(r,n,i)}),this.application=new n.Context.Application,this.device=new n.Context.Device,this.internal=new n.Context.Internal,this.location=new n.Context.Location,this.user=new n.Context.User(i.accountId()),this.operation=new n.Context.Operation,this.session=new n.Context.Session,this.sample=new n.Context.Sample(i.sampleRate()))}return t.prototype.addTelemetryInitializer=function(n){this.telemetryInitializers=this.telemetryInitializers||[];this.telemetryInitializers.push(n)},t.prototype.track=function(t){return t?(t.name===n.Telemetry.PageView.envelopeType&&n._InternalLogging.resetInternalMessageCount(),this.session&&typeof this.session.id!="string"&&this._sessionManager.update(),this._track(t)):n._InternalLogging.throwInternalUserActionable(0,"cannot call .track() with a null or undefined argument"),t},t.prototype._track=function(t){var r,f,i,u;this.session&&(typeof this.session.id=="string"?this._applySessionContext(t,this.session):this._applySessionContext(t,this._sessionManager.automaticSession));this._applyApplicationContext(t,this.application);this._applyDeviceContext(t,this.device);this._applyInternalContext(t,this.internal);this._applyLocationContext(t,this.location);this._applySampleContext(t,this.sample);this._applyUserContext(t,this.user);this._applyOperationContext(t,this.operation);t.iKey=this._config.instrumentationKey();r=!1;try{for(this.telemetryInitializers=this.telemetryInitializers||[],f=this.telemetryInitializers.length,i=0;i6e4;(l||c)&&(clearInterval(s),f=t.Telemetry.PageViewPerformance.getDuration(e,+new Date),h=new t.Telemetry.PageViewPerformance(n,i,f,r,u),o.sendPageViewInternal(n,i,h.isValid&&!isNaN(h.duration)?+h.duration:f,r,u),h.isValid&&(a=new t.Telemetry.Common.Data(t.Telemetry.PageViewPerformance.dataType,h),v=new t.Telemetry.Common.Envelope(a,t.Telemetry.PageViewPerformance.envelopeType),o.context.track(v)),o.context._sender.triggerSend())}catch(y){t._InternalLogging.throwInternalNonUserActionable(0,"trackPageView failed on page load calculation: "+t.Util.dump(y))}},100))},r.prototype.startTrackEvent=function(n){try{this._eventTracking.start(n)}catch(i){t._InternalLogging.throwInternalNonUserActionable(0,"startTrackEvent failed, event will not be collected: "+t.Util.dump(i))}},r.prototype.stopTrackEvent=function(n,i,r){try{this._eventTracking.stop(n,undefined,i,r)}catch(u){t._InternalLogging.throwInternalNonUserActionable(0,"stopTrackEvent failed, event will not be collected: "+t.Util.dump(u))}},r.prototype.trackEvent=function(n,i,r){try{var u=new t.Telemetry.Event(n,i,r),f=new t.Telemetry.Common.Data(t.Telemetry.Event.dataType,u),e=new t.Telemetry.Common.Envelope(f,t.Telemetry.Event.envelopeType);this.context.track(e)}catch(o){t._InternalLogging.throwInternalNonUserActionable(0,"trackEvent failed, event will not be collected: "+t.Util.dump(o))}},r.prototype.trackException=function(n,i,r,u){try{if(!t.Util.isError(n))try{throw new Error(n);}catch(f){n=f}var e=new t.Telemetry.Exception(n,i,r,u),o=new t.Telemetry.Common.Data(t.Telemetry.Exception.dataType,e),s=new t.Telemetry.Common.Envelope(o,t.Telemetry.Exception.envelopeType);this.context.track(s)}catch(h){t._InternalLogging.throwInternalNonUserActionable(0,"trackException failed, exception will not be collected: "+t.Util.dump(h))}},r.prototype.trackMetric=function(n,i,r,u,f,e){try{var o=new t.Telemetry.Metric(n,i,r,u,f,e),s=new t.Telemetry.Common.Data(t.Telemetry.Metric.dataType,o),h=new t.Telemetry.Common.Envelope(s,t.Telemetry.Metric.envelopeType);this.context.track(h)}catch(c){t._InternalLogging.throwInternalNonUserActionable(0,"trackMetric failed, metric will not be collected: "+t.Util.dump(c))}},r.prototype.trackTrace=function(n,i){try{var r=new t.Telemetry.Trace(n,i),u=new t.Telemetry.Common.Data(t.Telemetry.Trace.dataType,r),f=new t.Telemetry.Common.Envelope(u,t.Telemetry.Trace.envelopeType);this.context.track(f)}catch(e){t._InternalLogging.throwInternalNonUserActionable(1,"trackTrace failed, trace will not be collected: "+t.Util.dump(e))}},r.prototype.trackPageVisitTime=function(n,t,i){var r={PageName:n,PageUrl:t};this.trackMetric("PageVisitTime",i,1,i,i,r)},r.prototype.flush=function(){try{this.context._sender.triggerSend()}catch(n){t._InternalLogging.throwInternalNonUserActionable(0,"flush failed, telemetry will not be collected: "+t.Util.dump(n))}},r.prototype.setAuthenticatedUserContext=function(n,i){try{this.context.user.setAuthenticatedUserContext(n,i)}catch(r){t._InternalLogging.throwInternalUserActionable(1,"Setting auth user context failed. "+t.Util.dump(r))}},r.prototype.clearAuthenticatedUserContext=function(){try{this.context.user.clearAuthenticatedUserContext()}catch(n){t._InternalLogging.throwInternalUserActionable(1,"Clearing auth user context failed. "+t.Util.dump(n))}},r.prototype.SendCORSException=function(i){var r=n.ApplicationInsights.Telemetry.Exception.CreateSimpleException("Script error.","Error","unknown","unknown","The browser’s same-origin policy prevents us from getting the details of this exception.The exception occurred in a script loaded from an origin different than the web page.For cross- domain error reporting you can use crossorigin attribute together with appropriate CORS HTTP headers.For more information please see http://www.w3.org/TR/cors/.",0,null),u,f;r.properties=i;u=new t.Telemetry.Common.Data(t.Telemetry.Exception.dataType,r);f=new t.Telemetry.Common.Envelope(u,t.Telemetry.Exception.envelopeType);this.context.track(f)},r.prototype._onerror=function(n,i,r,u,f){var e,o,s,h;try{e={url:i?i:document.URL};t.Util.isCrossOriginError(n,i,r,u,f)?this.SendCORSException(e):(t.Util.isError(f)||(o="window.onerror@"+e.url+":"+r+":"+(u||0),f=new Error(n),f.stack=o),this.trackException(f,null,e))}catch(c){s=f?f.name+", "+f.message:"null";h=t.Util.dump(c);t._InternalLogging.throwInternalNonUserActionable(0,"_onerror threw "+h+" while logging error, error will not be collected: "+s)}},r}();t.AppInsights=r;i=function(){function n(n){this._name=n;this._events={}}return n.prototype.start=function(n){typeof this._events[n]!="undefined"&&t._InternalLogging.throwInternalUserActionable(1,"start"+this._name+" was called more than once for this event without calling stop"+this._name+". key is '"+n+"'");this._events[n]=+new Date},n.prototype.stop=function(n,i,r,u){var f=this._events[n],e,o;isNaN(f)?t._InternalLogging.throwInternalUserActionable(1,"stop"+this._name+" was called without a corresponding start"+this._name+" . Event name is '"+n+"'"):(e=+new Date,o=t.Telemetry.PageViewPerformance.getDuration(f,e),this.action(n,i,o,r,u));delete this._events[n];this._events[n]=undefined},n}()})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){"use strict";var t=function(n){function t(){this.ver=2;this.properties={};this.measurements={};n.call(this)}return __extends(t,n),t}(n.PageViewData);n.AjaxCallData=t}(AI||(AI={})),function(n){"use strict";(function(n){n[n.SQL=0]="SQL";n[n.Http=1]="Http";n[n.Other=2]="Other"})(n.DependencyKind||(n.DependencyKind={}));var t=n.DependencyKind}(AI||(AI={})),function(n){"use strict";(function(n){n[n.Undefined=0]="Undefined";n[n.Aic=1]="Aic";n[n.Apmc=2]="Apmc"})(n.DependencySourceType||(n.DependencySourceType={}));var t=n.DependencySourceType}(AI||(AI={})),function(n){"use strict";var t=function(n){function t(){this.ver=2;this.kind=0;this.dependencyKind=2;this.success=!0;this.dependencySource=0;this.properties={};n.call(this)}return __extends(t,n),t}(Microsoft.Telemetry.Domain);n.RemoteDependencyData=t}(AI||(AI={})),function(n){"use strict";var t=function(n){function t(){this.ver=2;this.properties={};this.measurements={};n.call(this)}return __extends(t,n),t}(Microsoft.Telemetry.Domain);n.RequestData=t}(AI||(AI={})),function(n){var t;(function(t){"use strict";var i=function(){function i(t){t.queue=t.queue||[];var r=t.config||{};if(r&&!r.instrumentationKey)if(r=t,r.iKey)n.ApplicationInsights.Version="0.10.0.0",r.instrumentationKey=r.iKey;else if(r.applicationInsightsId)n.ApplicationInsights.Version="0.7.2.0",r.instrumentationKey=r.applicationInsightsId;else throw new Error("Cannot load Application Insights SDK, no instrumentationKey was provided.");r=i.getDefaultConfig(r);this.snippet=t;this.config=r}return i.prototype.loadAppInsights=function(){var t=new n.ApplicationInsights.AppInsights(this.config),u,i,r;return this.config.iKey&&(u=t.trackPageView,t.trackPageView=function(n,i,r){u.apply(t,[null,n,i,r])}),i="logPageView",typeof this.snippet[i]=="function"&&(t[i]=function(n,i,r){t.trackPageView(null,n,i,r)}),r="logEvent",typeof this.snippet[r]=="function"&&(t[r]=function(n,i,r){t.trackEvent(n,i,r)}),t},i.prototype.emptyQueue=function(){var u,t,f,r;try{if(n.ApplicationInsights.Util.isArray(this.snippet.queue)){for(u=this.snippet.queue.length,t=0;t0?n.maxBatchSizeInBytes:1e6,n.maxBatchInterval=isNaN(n.maxBatchInterval)?15e3:n.maxBatchInterval,n.enableDebug=t.Util.stringToBoolOrDefault(n.enableDebug),n.autoCollectErrors=n.autoCollectErrors!==undefined&&n.autoCollectErrors!==null?t.Util.stringToBoolOrDefault(n.autoCollectErrors):!0,n.disableTelemetry=t.Util.stringToBoolOrDefault(n.disableTelemetry),n.verboseLogging=t.Util.stringToBoolOrDefault(n.verboseLogging),n.emitLineDelimitedJson=t.Util.stringToBoolOrDefault(n.emitLineDelimitedJson),n.diagnosticLogInterval=n.diagnosticLogInterval||1e4,n.autoTrackPageVisitTime=t.Util.stringToBoolOrDefault(n.autoTrackPageVisitTime),(isNaN(n.samplingPercentage)||n.samplingPercentage<=0||n.samplingPercentage>=100)&&(n.samplingPercentage=100),n},i}();t.Initialization=i})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={}));initializeAppInsights()
\ No newline at end of file
diff --git a/LLV/scripts/angular-animate.js b/LLV/scripts/angular-animate.js
new file mode 100644
index 0000000..2778fc5
--- /dev/null
+++ b/LLV/scripts/angular-animate.js
@@ -0,0 +1,4121 @@
+/**
+ * @license AngularJS v1.5.0
+ * (c) 2010-2016 Google, Inc. http://angularjs.org
+ * License: MIT
+ */
+(function(window, angular, undefined) {'use strict';
+
+/* jshint ignore:start */
+var noop = angular.noop;
+var copy = angular.copy;
+var extend = angular.extend;
+var jqLite = angular.element;
+var forEach = angular.forEach;
+var isArray = angular.isArray;
+var isString = angular.isString;
+var isObject = angular.isObject;
+var isUndefined = angular.isUndefined;
+var isDefined = angular.isDefined;
+var isFunction = angular.isFunction;
+var isElement = angular.isElement;
+
+var ELEMENT_NODE = 1;
+var COMMENT_NODE = 8;
+
+var ADD_CLASS_SUFFIX = '-add';
+var REMOVE_CLASS_SUFFIX = '-remove';
+var EVENT_CLASS_PREFIX = 'ng-';
+var ACTIVE_CLASS_SUFFIX = '-active';
+var PREPARE_CLASS_SUFFIX = '-prepare';
+
+var NG_ANIMATE_CLASSNAME = 'ng-animate';
+var NG_ANIMATE_CHILDREN_DATA = '$$ngAnimateChildren';
+
+// Detect proper transitionend/animationend event names.
+var CSS_PREFIX = '', TRANSITION_PROP, TRANSITIONEND_EVENT, ANIMATION_PROP, ANIMATIONEND_EVENT;
+
+// If unprefixed events are not supported but webkit-prefixed are, use the latter.
+// Otherwise, just use W3C names, browsers not supporting them at all will just ignore them.
+// Note: Chrome implements `window.onwebkitanimationend` and doesn't implement `window.onanimationend`
+// but at the same time dispatches the `animationend` event and not `webkitAnimationEnd`.
+// Register both events in case `window.onanimationend` is not supported because of that,
+// do the same for `transitionend` as Safari is likely to exhibit similar behavior.
+// Also, the only modern browser that uses vendor prefixes for transitions/keyframes is webkit
+// therefore there is no reason to test anymore for other vendor prefixes:
+// http://caniuse.com/#search=transition
+if (isUndefined(window.ontransitionend) && isDefined(window.onwebkittransitionend)) {
+ CSS_PREFIX = '-webkit-';
+ TRANSITION_PROP = 'WebkitTransition';
+ TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend';
+} else {
+ TRANSITION_PROP = 'transition';
+ TRANSITIONEND_EVENT = 'transitionend';
+}
+
+if (isUndefined(window.onanimationend) && isDefined(window.onwebkitanimationend)) {
+ CSS_PREFIX = '-webkit-';
+ ANIMATION_PROP = 'WebkitAnimation';
+ ANIMATIONEND_EVENT = 'webkitAnimationEnd animationend';
+} else {
+ ANIMATION_PROP = 'animation';
+ ANIMATIONEND_EVENT = 'animationend';
+}
+
+var DURATION_KEY = 'Duration';
+var PROPERTY_KEY = 'Property';
+var DELAY_KEY = 'Delay';
+var TIMING_KEY = 'TimingFunction';
+var ANIMATION_ITERATION_COUNT_KEY = 'IterationCount';
+var ANIMATION_PLAYSTATE_KEY = 'PlayState';
+var SAFE_FAST_FORWARD_DURATION_VALUE = 9999;
+
+var ANIMATION_DELAY_PROP = ANIMATION_PROP + DELAY_KEY;
+var ANIMATION_DURATION_PROP = ANIMATION_PROP + DURATION_KEY;
+var TRANSITION_DELAY_PROP = TRANSITION_PROP + DELAY_KEY;
+var TRANSITION_DURATION_PROP = TRANSITION_PROP + DURATION_KEY;
+
+var isPromiseLike = function(p) {
+ return p && p.then ? true : false;
+};
+
+var ngMinErr = angular.$$minErr('ng');
+function assertArg(arg, name, reason) {
+ if (!arg) {
+ throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
+ }
+ return arg;
+}
+
+function mergeClasses(a,b) {
+ if (!a && !b) return '';
+ if (!a) return b;
+ if (!b) return a;
+ if (isArray(a)) a = a.join(' ');
+ if (isArray(b)) b = b.join(' ');
+ return a + ' ' + b;
+}
+
+function packageStyles(options) {
+ var styles = {};
+ if (options && (options.to || options.from)) {
+ styles.to = options.to;
+ styles.from = options.from;
+ }
+ return styles;
+}
+
+function pendClasses(classes, fix, isPrefix) {
+ var className = '';
+ classes = isArray(classes)
+ ? classes
+ : classes && isString(classes) && classes.length
+ ? classes.split(/\s+/)
+ : [];
+ forEach(classes, function(klass, i) {
+ if (klass && klass.length > 0) {
+ className += (i > 0) ? ' ' : '';
+ className += isPrefix ? fix + klass
+ : klass + fix;
+ }
+ });
+ return className;
+}
+
+function removeFromArray(arr, val) {
+ var index = arr.indexOf(val);
+ if (val >= 0) {
+ arr.splice(index, 1);
+ }
+}
+
+function stripCommentsFromElement(element) {
+ if (element instanceof jqLite) {
+ switch (element.length) {
+ case 0:
+ return [];
+ break;
+
+ case 1:
+ // there is no point of stripping anything if the element
+ // is the only element within the jqLite wrapper.
+ // (it's important that we retain the element instance.)
+ if (element[0].nodeType === ELEMENT_NODE) {
+ return element;
+ }
+ break;
+
+ default:
+ return jqLite(extractElementNode(element));
+ break;
+ }
+ }
+
+ if (element.nodeType === ELEMENT_NODE) {
+ return jqLite(element);
+ }
+}
+
+function extractElementNode(element) {
+ if (!element[0]) return element;
+ for (var i = 0; i < element.length; i++) {
+ var elm = element[i];
+ if (elm.nodeType == ELEMENT_NODE) {
+ return elm;
+ }
+ }
+}
+
+function $$addClass($$jqLite, element, className) {
+ forEach(element, function(elm) {
+ $$jqLite.addClass(elm, className);
+ });
+}
+
+function $$removeClass($$jqLite, element, className) {
+ forEach(element, function(elm) {
+ $$jqLite.removeClass(elm, className);
+ });
+}
+
+function applyAnimationClassesFactory($$jqLite) {
+ return function(element, options) {
+ if (options.addClass) {
+ $$addClass($$jqLite, element, options.addClass);
+ options.addClass = null;
+ }
+ if (options.removeClass) {
+ $$removeClass($$jqLite, element, options.removeClass);
+ options.removeClass = null;
+ }
+ }
+}
+
+function prepareAnimationOptions(options) {
+ options = options || {};
+ if (!options.$$prepared) {
+ var domOperation = options.domOperation || noop;
+ options.domOperation = function() {
+ options.$$domOperationFired = true;
+ domOperation();
+ domOperation = noop;
+ };
+ options.$$prepared = true;
+ }
+ return options;
+}
+
+function applyAnimationStyles(element, options) {
+ applyAnimationFromStyles(element, options);
+ applyAnimationToStyles(element, options);
+}
+
+function applyAnimationFromStyles(element, options) {
+ if (options.from) {
+ element.css(options.from);
+ options.from = null;
+ }
+}
+
+function applyAnimationToStyles(element, options) {
+ if (options.to) {
+ element.css(options.to);
+ options.to = null;
+ }
+}
+
+function mergeAnimationDetails(element, oldAnimation, newAnimation) {
+ var target = oldAnimation.options || {};
+ var newOptions = newAnimation.options || {};
+
+ var toAdd = (target.addClass || '') + ' ' + (newOptions.addClass || '');
+ var toRemove = (target.removeClass || '') + ' ' + (newOptions.removeClass || '');
+ var classes = resolveElementClasses(element.attr('class'), toAdd, toRemove);
+
+ if (newOptions.preparationClasses) {
+ target.preparationClasses = concatWithSpace(newOptions.preparationClasses, target.preparationClasses);
+ delete newOptions.preparationClasses;
+ }
+
+ // noop is basically when there is no callback; otherwise something has been set
+ var realDomOperation = target.domOperation !== noop ? target.domOperation : null;
+
+ extend(target, newOptions);
+
+ // TODO(matsko or sreeramu): proper fix is to maintain all animation callback in array and call at last,but now only leave has the callback so no issue with this.
+ if (realDomOperation) {
+ target.domOperation = realDomOperation;
+ }
+
+ if (classes.addClass) {
+ target.addClass = classes.addClass;
+ } else {
+ target.addClass = null;
+ }
+
+ if (classes.removeClass) {
+ target.removeClass = classes.removeClass;
+ } else {
+ target.removeClass = null;
+ }
+
+ oldAnimation.addClass = target.addClass;
+ oldAnimation.removeClass = target.removeClass;
+
+ return target;
+}
+
+function resolveElementClasses(existing, toAdd, toRemove) {
+ var ADD_CLASS = 1;
+ var REMOVE_CLASS = -1;
+
+ var flags = {};
+ existing = splitClassesToLookup(existing);
+
+ toAdd = splitClassesToLookup(toAdd);
+ forEach(toAdd, function(value, key) {
+ flags[key] = ADD_CLASS;
+ });
+
+ toRemove = splitClassesToLookup(toRemove);
+ forEach(toRemove, function(value, key) {
+ flags[key] = flags[key] === ADD_CLASS ? null : REMOVE_CLASS;
+ });
+
+ var classes = {
+ addClass: '',
+ removeClass: ''
+ };
+
+ forEach(flags, function(val, klass) {
+ var prop, allow;
+ if (val === ADD_CLASS) {
+ prop = 'addClass';
+ allow = !existing[klass];
+ } else if (val === REMOVE_CLASS) {
+ prop = 'removeClass';
+ allow = existing[klass];
+ }
+ if (allow) {
+ if (classes[prop].length) {
+ classes[prop] += ' ';
+ }
+ classes[prop] += klass;
+ }
+ });
+
+ function splitClassesToLookup(classes) {
+ if (isString(classes)) {
+ classes = classes.split(' ');
+ }
+
+ var obj = {};
+ forEach(classes, function(klass) {
+ // sometimes the split leaves empty string values
+ // incase extra spaces were applied to the options
+ if (klass.length) {
+ obj[klass] = true;
+ }
+ });
+ return obj;
+ }
+
+ return classes;
+}
+
+function getDomNode(element) {
+ return (element instanceof angular.element) ? element[0] : element;
+}
+
+function applyGeneratedPreparationClasses(element, event, options) {
+ var classes = '';
+ if (event) {
+ classes = pendClasses(event, EVENT_CLASS_PREFIX, true);
+ }
+ if (options.addClass) {
+ classes = concatWithSpace(classes, pendClasses(options.addClass, ADD_CLASS_SUFFIX));
+ }
+ if (options.removeClass) {
+ classes = concatWithSpace(classes, pendClasses(options.removeClass, REMOVE_CLASS_SUFFIX));
+ }
+ if (classes.length) {
+ options.preparationClasses = classes;
+ element.addClass(classes);
+ }
+}
+
+function clearGeneratedClasses(element, options) {
+ if (options.preparationClasses) {
+ element.removeClass(options.preparationClasses);
+ options.preparationClasses = null;
+ }
+ if (options.activeClasses) {
+ element.removeClass(options.activeClasses);
+ options.activeClasses = null;
+ }
+}
+
+function blockTransitions(node, duration) {
+ // we use a negative delay value since it performs blocking
+ // yet it doesn't kill any existing transitions running on the
+ // same element which makes this safe for class-based animations
+ var value = duration ? '-' + duration + 's' : '';
+ applyInlineStyle(node, [TRANSITION_DELAY_PROP, value]);
+ return [TRANSITION_DELAY_PROP, value];
+}
+
+function blockKeyframeAnimations(node, applyBlock) {
+ var value = applyBlock ? 'paused' : '';
+ var key = ANIMATION_PROP + ANIMATION_PLAYSTATE_KEY;
+ applyInlineStyle(node, [key, value]);
+ return [key, value];
+}
+
+function applyInlineStyle(node, styleTuple) {
+ var prop = styleTuple[0];
+ var value = styleTuple[1];
+ node.style[prop] = value;
+}
+
+function concatWithSpace(a,b) {
+ if (!a) return b;
+ if (!b) return a;
+ return a + ' ' + b;
+}
+
+var $$rAFSchedulerFactory = ['$$rAF', function($$rAF) {
+ var queue, cancelFn;
+
+ function scheduler(tasks) {
+ // we make a copy since RAFScheduler mutates the state
+ // of the passed in array variable and this would be difficult
+ // to track down on the outside code
+ queue = queue.concat(tasks);
+ nextTick();
+ }
+
+ queue = scheduler.queue = [];
+
+ /* waitUntilQuiet does two things:
+ * 1. It will run the FINAL `fn` value only when an uncanceled RAF has passed through
+ * 2. It will delay the next wave of tasks from running until the quiet `fn` has run.
+ *
+ * The motivation here is that animation code can request more time from the scheduler
+ * before the next wave runs. This allows for certain DOM properties such as classes to
+ * be resolved in time for the next animation to run.
+ */
+ scheduler.waitUntilQuiet = function(fn) {
+ if (cancelFn) cancelFn();
+
+ cancelFn = $$rAF(function() {
+ cancelFn = null;
+ fn();
+ nextTick();
+ });
+ };
+
+ return scheduler;
+
+ function nextTick() {
+ if (!queue.length) return;
+
+ var items = queue.shift();
+ for (var i = 0; i < items.length; i++) {
+ items[i]();
+ }
+
+ if (!cancelFn) {
+ $$rAF(function() {
+ if (!cancelFn) nextTick();
+ });
+ }
+ }
+}];
+
+/**
+ * @ngdoc directive
+ * @name ngAnimateChildren
+ * @restrict AE
+ * @element ANY
+ *
+ * @description
+ *
+ * ngAnimateChildren allows you to specify that children of this element should animate even if any
+ * of the children's parents are currently animating. By default, when an element has an active `enter`, `leave`, or `move`
+ * (structural) animation, child elements that also have an active structural animation are not animated.
+ *
+ * Note that even if `ngAnimteChildren` is set, no child animations will run when the parent element is removed from the DOM (`leave` animation).
+ *
+ *
+ * @param {string} ngAnimateChildren If the value is empty, `true` or `on`,
+ * then child animations are allowed. If the value is `false`, child animations are not allowed.
+ *
+ * @example
+ *
+
+
+
+
+
+
+
+ List of items:
+
Item {{item}}
+
+
+
+
+
+
+ .container.ng-enter,
+ .container.ng-leave {
+ transition: all ease 1.5s;
+ }
+
+ .container.ng-enter,
+ .container.ng-leave-active {
+ opacity: 0;
+ }
+
+ .container.ng-leave,
+ .container.ng-enter-active {
+ opacity: 1;
+ }
+
+ .item {
+ background: firebrick;
+ color: #FFF;
+ margin-bottom: 10px;
+ }
+
+ .item.ng-enter,
+ .item.ng-leave {
+ transition: transform 1.5s ease;
+ }
+
+ .item.ng-enter {
+ transform: translateX(50px);
+ }
+
+ .item.ng-enter-active {
+ transform: translateX(0);
+ }
+
+
+ angular.module('ngAnimateChildren', ['ngAnimate'])
+ .controller('mainController', function() {
+ this.animateChildren = false;
+ this.enterElement = false;
+ });
+
+
+ */
+var $$AnimateChildrenDirective = ['$interpolate', function($interpolate) {
+ return {
+ link: function(scope, element, attrs) {
+ var val = attrs.ngAnimateChildren;
+ if (angular.isString(val) && val.length === 0) { //empty attribute
+ element.data(NG_ANIMATE_CHILDREN_DATA, true);
+ } else {
+ // Interpolate and set the value, so that it is available to
+ // animations that run right after compilation
+ setData($interpolate(val)(scope));
+ attrs.$observe('ngAnimateChildren', setData);
+ }
+
+ function setData(value) {
+ value = value === 'on' || value === 'true';
+ element.data(NG_ANIMATE_CHILDREN_DATA, value);
+ }
+ }
+ };
+}];
+
+var ANIMATE_TIMER_KEY = '$$animateCss';
+
+/**
+ * @ngdoc service
+ * @name $animateCss
+ * @kind object
+ *
+ * @description
+ * The `$animateCss` service is a useful utility to trigger customized CSS-based transitions/keyframes
+ * from a JavaScript-based animation or directly from a directive. The purpose of `$animateCss` is NOT
+ * to side-step how `$animate` and ngAnimate work, but the goal is to allow pre-existing animations or
+ * directives to create more complex animations that can be purely driven using CSS code.
+ *
+ * Note that only browsers that support CSS transitions and/or keyframe animations are capable of
+ * rendering animations triggered via `$animateCss` (bad news for IE9 and lower).
+ *
+ * ## Usage
+ * Once again, `$animateCss` is designed to be used inside of a registered JavaScript animation that
+ * is powered by ngAnimate. It is possible to use `$animateCss` directly inside of a directive, however,
+ * any automatic control over cancelling animations and/or preventing animations from being run on
+ * child elements will not be handled by Angular. For this to work as expected, please use `$animate` to
+ * trigger the animation and then setup a JavaScript animation that injects `$animateCss` to trigger
+ * the CSS animation.
+ *
+ * The example below shows how we can create a folding animation on an element using `ng-if`:
+ *
+ * ```html
+ *
+ *
+ * This element will go BOOM
+ *
+ *
+ * ```
+ *
+ * Now we create the **JavaScript animation** that will trigger the CSS transition:
+ *
+ * ```js
+ * ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) {
+ * return {
+ * enter: function(element, doneFn) {
+ * var height = element[0].offsetHeight;
+ * return $animateCss(element, {
+ * from: { height:'0px' },
+ * to: { height:height + 'px' },
+ * duration: 1 // one second
+ * });
+ * }
+ * }
+ * }]);
+ * ```
+ *
+ * ## More Advanced Uses
+ *
+ * `$animateCss` is the underlying code that ngAnimate uses to power **CSS-based animations** behind the scenes. Therefore CSS hooks
+ * like `.ng-EVENT`, `.ng-EVENT-active`, `.ng-EVENT-stagger` are all features that can be triggered using `$animateCss` via JavaScript code.
+ *
+ * This also means that just about any combination of adding classes, removing classes, setting styles, dynamically setting a keyframe animation,
+ * applying a hardcoded duration or delay value, changing the animation easing or applying a stagger animation are all options that work with
+ * `$animateCss`. The service itself is smart enough to figure out the combination of options and examine the element styling properties in order
+ * to provide a working animation that will run in CSS.
+ *
+ * The example below showcases a more advanced version of the `.fold-animation` from the example above:
+ *
+ * ```js
+ * ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) {
+ * return {
+ * enter: function(element, doneFn) {
+ * var height = element[0].offsetHeight;
+ * return $animateCss(element, {
+ * addClass: 'red large-text pulse-twice',
+ * easing: 'ease-out',
+ * from: { height:'0px' },
+ * to: { height:height + 'px' },
+ * duration: 1 // one second
+ * });
+ * }
+ * }
+ * }]);
+ * ```
+ *
+ * Since we're adding/removing CSS classes then the CSS transition will also pick those up:
+ *
+ * ```css
+ * /* since a hardcoded duration value of 1 was provided in the JavaScript animation code,
+ * the CSS classes below will be transitioned despite them being defined as regular CSS classes */
+ * .red { background:red; }
+ * .large-text { font-size:20px; }
+ *
+ * /* we can also use a keyframe animation and $animateCss will make it work alongside the transition */
+ * .pulse-twice {
+ * animation: 0.5s pulse linear 2;
+ * -webkit-animation: 0.5s pulse linear 2;
+ * }
+ *
+ * @keyframes pulse {
+ * from { transform: scale(0.5); }
+ * to { transform: scale(1.5); }
+ * }
+ *
+ * @-webkit-keyframes pulse {
+ * from { -webkit-transform: scale(0.5); }
+ * to { -webkit-transform: scale(1.5); }
+ * }
+ * ```
+ *
+ * Given this complex combination of CSS classes, styles and options, `$animateCss` will figure everything out and make the animation happen.
+ *
+ * ## How the Options are handled
+ *
+ * `$animateCss` is very versatile and intelligent when it comes to figuring out what configurations to apply to the element to ensure the animation
+ * works with the options provided. Say for example we were adding a class that contained a keyframe value and we wanted to also animate some inline
+ * styles using the `from` and `to` properties.
+ *
+ * ```js
+ * var animator = $animateCss(element, {
+ * from: { background:'red' },
+ * to: { background:'blue' }
+ * });
+ * animator.start();
+ * ```
+ *
+ * ```css
+ * .rotating-animation {
+ * animation:0.5s rotate linear;
+ * -webkit-animation:0.5s rotate linear;
+ * }
+ *
+ * @keyframes rotate {
+ * from { transform: rotate(0deg); }
+ * to { transform: rotate(360deg); }
+ * }
+ *
+ * @-webkit-keyframes rotate {
+ * from { -webkit-transform: rotate(0deg); }
+ * to { -webkit-transform: rotate(360deg); }
+ * }
+ * ```
+ *
+ * The missing pieces here are that we do not have a transition set (within the CSS code nor within the `$animateCss` options) and the duration of the animation is
+ * going to be detected from what the keyframe styles on the CSS class are. In this event, `$animateCss` will automatically create an inline transition
+ * style matching the duration detected from the keyframe style (which is present in the CSS class that is being added) and then prepare both the transition
+ * and keyframe animations to run in parallel on the element. Then when the animation is underway the provided `from` and `to` CSS styles will be applied
+ * and spread across the transition and keyframe animation.
+ *
+ * ## What is returned
+ *
+ * `$animateCss` works in two stages: a preparation phase and an animation phase. Therefore when `$animateCss` is first called it will NOT actually
+ * start the animation. All that is going on here is that the element is being prepared for the animation (which means that the generated CSS classes are
+ * added and removed on the element). Once `$animateCss` is called it will return an object with the following properties:
+ *
+ * ```js
+ * var animator = $animateCss(element, { ... });
+ * ```
+ *
+ * Now what do the contents of our `animator` variable look like:
+ *
+ * ```js
+ * {
+ * // starts the animation
+ * start: Function,
+ *
+ * // ends (aborts) the animation
+ * end: Function
+ * }
+ * ```
+ *
+ * To actually start the animation we need to run `animation.start()` which will then return a promise that we can hook into to detect when the animation ends.
+ * If we choose not to run the animation then we MUST run `animation.end()` to perform a cleanup on the element (since some CSS classes and styles may have been
+ * applied to the element during the preparation phase). Note that all other properties such as duration, delay, transitions and keyframes are just properties
+ * and that changing them will not reconfigure the parameters of the animation.
+ *
+ * ### runner.done() vs runner.then()
+ * It is documented that `animation.start()` will return a promise object and this is true, however, there is also an additional method available on the
+ * runner called `.done(callbackFn)`. The done method works the same as `.finally(callbackFn)`, however, it does **not trigger a digest to occur**.
+ * Therefore, for performance reasons, it's always best to use `runner.done(callback)` instead of `runner.then()`, `runner.catch()` or `runner.finally()`
+ * unless you really need a digest to kick off afterwards.
+ *
+ * Keep in mind that, to make this easier, ngAnimate has tweaked the JS animations API to recognize when a runner instance is returned from $animateCss
+ * (so there is no need to call `runner.done(doneFn)` inside of your JavaScript animation code).
+ * Check the {@link ngAnimate.$animateCss#usage animation code above} to see how this works.
+ *
+ * @param {DOMElement} element the element that will be animated
+ * @param {object} options the animation-related options that will be applied during the animation
+ *
+ * * `event` - The DOM event (e.g. enter, leave, move). When used, a generated CSS class of `ng-EVENT` and `ng-EVENT-active` will be applied
+ * to the element during the animation. Multiple events can be provided when spaces are used as a separator. (Note that this will not perform any DOM operation.)
+ * * `structural` - Indicates that the `ng-` prefix will be added to the event class. Setting to `false` or omitting will turn `ng-EVENT` and
+ * `ng-EVENT-active` in `EVENT` and `EVENT-active`. Unused if `event` is omitted.
+ * * `easing` - The CSS easing value that will be applied to the transition or keyframe animation (or both).
+ * * `transitionStyle` - The raw CSS transition style that will be used (e.g. `1s linear all`).
+ * * `keyframeStyle` - The raw CSS keyframe animation style that will be used (e.g. `1s my_animation linear`).
+ * * `from` - The starting CSS styles (a key/value object) that will be applied at the start of the animation.
+ * * `to` - The ending CSS styles (a key/value object) that will be applied across the animation via a CSS transition.
+ * * `addClass` - A space separated list of CSS classes that will be added to the element and spread across the animation.
+ * * `removeClass` - A space separated list of CSS classes that will be removed from the element and spread across the animation.
+ * * `duration` - A number value representing the total duration of the transition and/or keyframe (note that a value of 1 is 1000ms). If a value of `0`
+ * is provided then the animation will be skipped entirely.
+ * * `delay` - A number value representing the total delay of the transition and/or keyframe (note that a value of 1 is 1000ms). If a value of `true` is
+ * used then whatever delay value is detected from the CSS classes will be mirrored on the elements styles (e.g. by setting delay true then the style value
+ * of the element will be `transition-delay: DETECTED_VALUE`). Using `true` is useful when you want the CSS classes and inline styles to all share the same
+ * CSS delay value.
+ * * `stagger` - A numeric time value representing the delay between successively animated elements
+ * ({@link ngAnimate#css-staggering-animations Click here to learn how CSS-based staggering works in ngAnimate.})
+ * * `staggerIndex` - The numeric index representing the stagger item (e.g. a value of 5 is equal to the sixth item in the stagger; therefore when a
+ * `stagger` option value of `0.1` is used then there will be a stagger delay of `600ms`)
+ * * `applyClassesEarly` - Whether or not the classes being added or removed will be used when detecting the animation. This is set by `$animate` when enter/leave/move animations are fired to ensure that the CSS classes are resolved in time. (Note that this will prevent any transitions from occurring on the classes being added and removed.)
+ * * `cleanupStyles` - Whether or not the provided `from` and `to` styles will be removed once
+ * the animation is closed. This is useful for when the styles are used purely for the sake of
+ * the animation and do not have a lasting visual effect on the element (e.g. a collapse and open animation).
+ * By default this value is set to `false`.
+ *
+ * @return {object} an object with start and end methods and details about the animation.
+ *
+ * * `start` - The method to start the animation. This will return a `Promise` when called.
+ * * `end` - This method will cancel the animation and remove all applied CSS classes and styles.
+ */
+var ONE_SECOND = 1000;
+var BASE_TEN = 10;
+
+var ELAPSED_TIME_MAX_DECIMAL_PLACES = 3;
+var CLOSING_TIME_BUFFER = 1.5;
+
+var DETECT_CSS_PROPERTIES = {
+ transitionDuration: TRANSITION_DURATION_PROP,
+ transitionDelay: TRANSITION_DELAY_PROP,
+ transitionProperty: TRANSITION_PROP + PROPERTY_KEY,
+ animationDuration: ANIMATION_DURATION_PROP,
+ animationDelay: ANIMATION_DELAY_PROP,
+ animationIterationCount: ANIMATION_PROP + ANIMATION_ITERATION_COUNT_KEY
+};
+
+var DETECT_STAGGER_CSS_PROPERTIES = {
+ transitionDuration: TRANSITION_DURATION_PROP,
+ transitionDelay: TRANSITION_DELAY_PROP,
+ animationDuration: ANIMATION_DURATION_PROP,
+ animationDelay: ANIMATION_DELAY_PROP
+};
+
+function getCssKeyframeDurationStyle(duration) {
+ return [ANIMATION_DURATION_PROP, duration + 's'];
+}
+
+function getCssDelayStyle(delay, isKeyframeAnimation) {
+ var prop = isKeyframeAnimation ? ANIMATION_DELAY_PROP : TRANSITION_DELAY_PROP;
+ return [prop, delay + 's'];
+}
+
+function computeCssStyles($window, element, properties) {
+ var styles = Object.create(null);
+ var detectedStyles = $window.getComputedStyle(element) || {};
+ forEach(properties, function(formalStyleName, actualStyleName) {
+ var val = detectedStyles[formalStyleName];
+ if (val) {
+ var c = val.charAt(0);
+
+ // only numerical-based values have a negative sign or digit as the first value
+ if (c === '-' || c === '+' || c >= 0) {
+ val = parseMaxTime(val);
+ }
+
+ // by setting this to null in the event that the delay is not set or is set directly as 0
+ // then we can still allow for negative values to be used later on and not mistake this
+ // value for being greater than any other negative value.
+ if (val === 0) {
+ val = null;
+ }
+ styles[actualStyleName] = val;
+ }
+ });
+
+ return styles;
+}
+
+function parseMaxTime(str) {
+ var maxValue = 0;
+ var values = str.split(/\s*,\s*/);
+ forEach(values, function(value) {
+ // it's always safe to consider only second values and omit `ms` values since
+ // getComputedStyle will always handle the conversion for us
+ if (value.charAt(value.length - 1) == 's') {
+ value = value.substring(0, value.length - 1);
+ }
+ value = parseFloat(value) || 0;
+ maxValue = maxValue ? Math.max(value, maxValue) : value;
+ });
+ return maxValue;
+}
+
+function truthyTimingValue(val) {
+ return val === 0 || val != null;
+}
+
+function getCssTransitionDurationStyle(duration, applyOnlyDuration) {
+ var style = TRANSITION_PROP;
+ var value = duration + 's';
+ if (applyOnlyDuration) {
+ style += DURATION_KEY;
+ } else {
+ value += ' linear all';
+ }
+ return [style, value];
+}
+
+function createLocalCacheLookup() {
+ var cache = Object.create(null);
+ return {
+ flush: function() {
+ cache = Object.create(null);
+ },
+
+ count: function(key) {
+ var entry = cache[key];
+ return entry ? entry.total : 0;
+ },
+
+ get: function(key) {
+ var entry = cache[key];
+ return entry && entry.value;
+ },
+
+ put: function(key, value) {
+ if (!cache[key]) {
+ cache[key] = { total: 1, value: value };
+ } else {
+ cache[key].total++;
+ }
+ }
+ };
+}
+
+// we do not reassign an already present style value since
+// if we detect the style property value again we may be
+// detecting styles that were added via the `from` styles.
+// We make use of `isDefined` here since an empty string
+// or null value (which is what getPropertyValue will return
+// for a non-existing style) will still be marked as a valid
+// value for the style (a falsy value implies that the style
+// is to be removed at the end of the animation). If we had a simple
+// "OR" statement then it would not be enough to catch that.
+function registerRestorableStyles(backup, node, properties) {
+ forEach(properties, function(prop) {
+ backup[prop] = isDefined(backup[prop])
+ ? backup[prop]
+ : node.style.getPropertyValue(prop);
+ });
+}
+
+var $AnimateCssProvider = ['$animateProvider', function($animateProvider) {
+ var gcsLookup = createLocalCacheLookup();
+ var gcsStaggerLookup = createLocalCacheLookup();
+
+ this.$get = ['$window', '$$jqLite', '$$AnimateRunner', '$timeout',
+ '$$forceReflow', '$sniffer', '$$rAFScheduler', '$$animateQueue',
+ function($window, $$jqLite, $$AnimateRunner, $timeout,
+ $$forceReflow, $sniffer, $$rAFScheduler, $$animateQueue) {
+
+ var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
+
+ var parentCounter = 0;
+ function gcsHashFn(node, extraClasses) {
+ var KEY = "$$ngAnimateParentKey";
+ var parentNode = node.parentNode;
+ var parentID = parentNode[KEY] || (parentNode[KEY] = ++parentCounter);
+ return parentID + '-' + node.getAttribute('class') + '-' + extraClasses;
+ }
+
+ function computeCachedCssStyles(node, className, cacheKey, properties) {
+ var timings = gcsLookup.get(cacheKey);
+
+ if (!timings) {
+ timings = computeCssStyles($window, node, properties);
+ if (timings.animationIterationCount === 'infinite') {
+ timings.animationIterationCount = 1;
+ }
+ }
+
+ // we keep putting this in multiple times even though the value and the cacheKey are the same
+ // because we're keeping an internal tally of how many duplicate animations are detected.
+ gcsLookup.put(cacheKey, timings);
+ return timings;
+ }
+
+ function computeCachedCssStaggerStyles(node, className, cacheKey, properties) {
+ var stagger;
+
+ // if we have one or more existing matches of matching elements
+ // containing the same parent + CSS styles (which is how cacheKey works)
+ // then staggering is possible
+ if (gcsLookup.count(cacheKey) > 0) {
+ stagger = gcsStaggerLookup.get(cacheKey);
+
+ if (!stagger) {
+ var staggerClassName = pendClasses(className, '-stagger');
+
+ $$jqLite.addClass(node, staggerClassName);
+
+ stagger = computeCssStyles($window, node, properties);
+
+ // force the conversion of a null value to zero incase not set
+ stagger.animationDuration = Math.max(stagger.animationDuration, 0);
+ stagger.transitionDuration = Math.max(stagger.transitionDuration, 0);
+
+ $$jqLite.removeClass(node, staggerClassName);
+
+ gcsStaggerLookup.put(cacheKey, stagger);
+ }
+ }
+
+ return stagger || {};
+ }
+
+ var cancelLastRAFRequest;
+ var rafWaitQueue = [];
+ function waitUntilQuiet(callback) {
+ rafWaitQueue.push(callback);
+ $$rAFScheduler.waitUntilQuiet(function() {
+ gcsLookup.flush();
+ gcsStaggerLookup.flush();
+
+ // DO NOT REMOVE THIS LINE OR REFACTOR OUT THE `pageWidth` variable.
+ // PLEASE EXAMINE THE `$$forceReflow` service to understand why.
+ var pageWidth = $$forceReflow();
+
+ // we use a for loop to ensure that if the queue is changed
+ // during this looping then it will consider new requests
+ for (var i = 0; i < rafWaitQueue.length; i++) {
+ rafWaitQueue[i](pageWidth);
+ }
+ rafWaitQueue.length = 0;
+ });
+ }
+
+ function computeTimings(node, className, cacheKey) {
+ var timings = computeCachedCssStyles(node, className, cacheKey, DETECT_CSS_PROPERTIES);
+ var aD = timings.animationDelay;
+ var tD = timings.transitionDelay;
+ timings.maxDelay = aD && tD
+ ? Math.max(aD, tD)
+ : (aD || tD);
+ timings.maxDuration = Math.max(
+ timings.animationDuration * timings.animationIterationCount,
+ timings.transitionDuration);
+
+ return timings;
+ }
+
+ return function init(element, initialOptions) {
+ // all of the animation functions should create
+ // a copy of the options data, however, if a
+ // parent service has already created a copy then
+ // we should stick to using that
+ var options = initialOptions || {};
+ if (!options.$$prepared) {
+ options = prepareAnimationOptions(copy(options));
+ }
+
+ var restoreStyles = {};
+ var node = getDomNode(element);
+ if (!node
+ || !node.parentNode
+ || !$$animateQueue.enabled()) {
+ return closeAndReturnNoopAnimator();
+ }
+
+ var temporaryStyles = [];
+ var classes = element.attr('class');
+ var styles = packageStyles(options);
+ var animationClosed;
+ var animationPaused;
+ var animationCompleted;
+ var runner;
+ var runnerHost;
+ var maxDelay;
+ var maxDelayTime;
+ var maxDuration;
+ var maxDurationTime;
+ var startTime;
+ var events = [];
+
+ if (options.duration === 0 || (!$sniffer.animations && !$sniffer.transitions)) {
+ return closeAndReturnNoopAnimator();
+ }
+
+ var method = options.event && isArray(options.event)
+ ? options.event.join(' ')
+ : options.event;
+
+ var isStructural = method && options.structural;
+ var structuralClassName = '';
+ var addRemoveClassName = '';
+
+ if (isStructural) {
+ structuralClassName = pendClasses(method, EVENT_CLASS_PREFIX, true);
+ } else if (method) {
+ structuralClassName = method;
+ }
+
+ if (options.addClass) {
+ addRemoveClassName += pendClasses(options.addClass, ADD_CLASS_SUFFIX);
+ }
+
+ if (options.removeClass) {
+ if (addRemoveClassName.length) {
+ addRemoveClassName += ' ';
+ }
+ addRemoveClassName += pendClasses(options.removeClass, REMOVE_CLASS_SUFFIX);
+ }
+
+ // there may be a situation where a structural animation is combined together
+ // with CSS classes that need to resolve before the animation is computed.
+ // However this means that there is no explicit CSS code to block the animation
+ // from happening (by setting 0s none in the class name). If this is the case
+ // we need to apply the classes before the first rAF so we know to continue if
+ // there actually is a detected transition or keyframe animation
+ if (options.applyClassesEarly && addRemoveClassName.length) {
+ applyAnimationClasses(element, options);
+ }
+
+ var preparationClasses = [structuralClassName, addRemoveClassName].join(' ').trim();
+ var fullClassName = classes + ' ' + preparationClasses;
+ var activeClasses = pendClasses(preparationClasses, ACTIVE_CLASS_SUFFIX);
+ var hasToStyles = styles.to && Object.keys(styles.to).length > 0;
+ var containsKeyframeAnimation = (options.keyframeStyle || '').length > 0;
+
+ // there is no way we can trigger an animation if no styles and
+ // no classes are being applied which would then trigger a transition,
+ // unless there a is raw keyframe value that is applied to the element.
+ if (!containsKeyframeAnimation
+ && !hasToStyles
+ && !preparationClasses) {
+ return closeAndReturnNoopAnimator();
+ }
+
+ var cacheKey, stagger;
+ if (options.stagger > 0) {
+ var staggerVal = parseFloat(options.stagger);
+ stagger = {
+ transitionDelay: staggerVal,
+ animationDelay: staggerVal,
+ transitionDuration: 0,
+ animationDuration: 0
+ };
+ } else {
+ cacheKey = gcsHashFn(node, fullClassName);
+ stagger = computeCachedCssStaggerStyles(node, preparationClasses, cacheKey, DETECT_STAGGER_CSS_PROPERTIES);
+ }
+
+ if (!options.$$skipPreparationClasses) {
+ $$jqLite.addClass(element, preparationClasses);
+ }
+
+ var applyOnlyDuration;
+
+ if (options.transitionStyle) {
+ var transitionStyle = [TRANSITION_PROP, options.transitionStyle];
+ applyInlineStyle(node, transitionStyle);
+ temporaryStyles.push(transitionStyle);
+ }
+
+ if (options.duration >= 0) {
+ applyOnlyDuration = node.style[TRANSITION_PROP].length > 0;
+ var durationStyle = getCssTransitionDurationStyle(options.duration, applyOnlyDuration);
+
+ // we set the duration so that it will be picked up by getComputedStyle later
+ applyInlineStyle(node, durationStyle);
+ temporaryStyles.push(durationStyle);
+ }
+
+ if (options.keyframeStyle) {
+ var keyframeStyle = [ANIMATION_PROP, options.keyframeStyle];
+ applyInlineStyle(node, keyframeStyle);
+ temporaryStyles.push(keyframeStyle);
+ }
+
+ var itemIndex = stagger
+ ? options.staggerIndex >= 0
+ ? options.staggerIndex
+ : gcsLookup.count(cacheKey)
+ : 0;
+
+ var isFirst = itemIndex === 0;
+
+ // this is a pre-emptive way of forcing the setup classes to be added and applied INSTANTLY
+ // without causing any combination of transitions to kick in. By adding a negative delay value
+ // it forces the setup class' transition to end immediately. We later then remove the negative
+ // transition delay to allow for the transition to naturally do it's thing. The beauty here is
+ // that if there is no transition defined then nothing will happen and this will also allow
+ // other transitions to be stacked on top of each other without any chopping them out.
+ if (isFirst && !options.skipBlocking) {
+ blockTransitions(node, SAFE_FAST_FORWARD_DURATION_VALUE);
+ }
+
+ var timings = computeTimings(node, fullClassName, cacheKey);
+ var relativeDelay = timings.maxDelay;
+ maxDelay = Math.max(relativeDelay, 0);
+ maxDuration = timings.maxDuration;
+
+ var flags = {};
+ flags.hasTransitions = timings.transitionDuration > 0;
+ flags.hasAnimations = timings.animationDuration > 0;
+ flags.hasTransitionAll = flags.hasTransitions && timings.transitionProperty == 'all';
+ flags.applyTransitionDuration = hasToStyles && (
+ (flags.hasTransitions && !flags.hasTransitionAll)
+ || (flags.hasAnimations && !flags.hasTransitions));
+ flags.applyAnimationDuration = options.duration && flags.hasAnimations;
+ flags.applyTransitionDelay = truthyTimingValue(options.delay) && (flags.applyTransitionDuration || flags.hasTransitions);
+ flags.applyAnimationDelay = truthyTimingValue(options.delay) && flags.hasAnimations;
+ flags.recalculateTimingStyles = addRemoveClassName.length > 0;
+
+ if (flags.applyTransitionDuration || flags.applyAnimationDuration) {
+ maxDuration = options.duration ? parseFloat(options.duration) : maxDuration;
+
+ if (flags.applyTransitionDuration) {
+ flags.hasTransitions = true;
+ timings.transitionDuration = maxDuration;
+ applyOnlyDuration = node.style[TRANSITION_PROP + PROPERTY_KEY].length > 0;
+ temporaryStyles.push(getCssTransitionDurationStyle(maxDuration, applyOnlyDuration));
+ }
+
+ if (flags.applyAnimationDuration) {
+ flags.hasAnimations = true;
+ timings.animationDuration = maxDuration;
+ temporaryStyles.push(getCssKeyframeDurationStyle(maxDuration));
+ }
+ }
+
+ if (maxDuration === 0 && !flags.recalculateTimingStyles) {
+ return closeAndReturnNoopAnimator();
+ }
+
+ if (options.delay != null) {
+ var delayStyle;
+ if (typeof options.delay !== "boolean") {
+ delayStyle = parseFloat(options.delay);
+ // number in options.delay means we have to recalculate the delay for the closing timeout
+ maxDelay = Math.max(delayStyle, 0);
+ }
+
+ if (flags.applyTransitionDelay) {
+ temporaryStyles.push(getCssDelayStyle(delayStyle));
+ }
+
+ if (flags.applyAnimationDelay) {
+ temporaryStyles.push(getCssDelayStyle(delayStyle, true));
+ }
+ }
+
+ // we need to recalculate the delay value since we used a pre-emptive negative
+ // delay value and the delay value is required for the final event checking. This
+ // property will ensure that this will happen after the RAF phase has passed.
+ if (options.duration == null && timings.transitionDuration > 0) {
+ flags.recalculateTimingStyles = flags.recalculateTimingStyles || isFirst;
+ }
+
+ maxDelayTime = maxDelay * ONE_SECOND;
+ maxDurationTime = maxDuration * ONE_SECOND;
+ if (!options.skipBlocking) {
+ flags.blockTransition = timings.transitionDuration > 0;
+ flags.blockKeyframeAnimation = timings.animationDuration > 0 &&
+ stagger.animationDelay > 0 &&
+ stagger.animationDuration === 0;
+ }
+
+ if (options.from) {
+ if (options.cleanupStyles) {
+ registerRestorableStyles(restoreStyles, node, Object.keys(options.from));
+ }
+ applyAnimationFromStyles(element, options);
+ }
+
+ if (flags.blockTransition || flags.blockKeyframeAnimation) {
+ applyBlocking(maxDuration);
+ } else if (!options.skipBlocking) {
+ blockTransitions(node, false);
+ }
+
+ // TODO(matsko): for 1.5 change this code to have an animator object for better debugging
+ return {
+ $$willAnimate: true,
+ end: endFn,
+ start: function() {
+ if (animationClosed) return;
+
+ runnerHost = {
+ end: endFn,
+ cancel: cancelFn,
+ resume: null, //this will be set during the start() phase
+ pause: null
+ };
+
+ runner = new $$AnimateRunner(runnerHost);
+
+ waitUntilQuiet(start);
+
+ // we don't have access to pause/resume the animation
+ // since it hasn't run yet. AnimateRunner will therefore
+ // set noop functions for resume and pause and they will
+ // later be overridden once the animation is triggered
+ return runner;
+ }
+ };
+
+ function endFn() {
+ close();
+ }
+
+ function cancelFn() {
+ close(true);
+ }
+
+ function close(rejected) { // jshint ignore:line
+ // if the promise has been called already then we shouldn't close
+ // the animation again
+ if (animationClosed || (animationCompleted && animationPaused)) return;
+ animationClosed = true;
+ animationPaused = false;
+
+ if (!options.$$skipPreparationClasses) {
+ $$jqLite.removeClass(element, preparationClasses);
+ }
+ $$jqLite.removeClass(element, activeClasses);
+
+ blockKeyframeAnimations(node, false);
+ blockTransitions(node, false);
+
+ forEach(temporaryStyles, function(entry) {
+ // There is only one way to remove inline style properties entirely from elements.
+ // By using `removeProperty` this works, but we need to convert camel-cased CSS
+ // styles down to hyphenated values.
+ node.style[entry[0]] = '';
+ });
+
+ applyAnimationClasses(element, options);
+ applyAnimationStyles(element, options);
+
+ if (Object.keys(restoreStyles).length) {
+ forEach(restoreStyles, function(value, prop) {
+ value ? node.style.setProperty(prop, value)
+ : node.style.removeProperty(prop);
+ });
+ }
+
+ // the reason why we have this option is to allow a synchronous closing callback
+ // that is fired as SOON as the animation ends (when the CSS is removed) or if
+ // the animation never takes off at all. A good example is a leave animation since
+ // the element must be removed just after the animation is over or else the element
+ // will appear on screen for one animation frame causing an overbearing flicker.
+ if (options.onDone) {
+ options.onDone();
+ }
+
+ if (events && events.length) {
+ // Remove the transitionend / animationend listener(s)
+ element.off(events.join(' '), onAnimationProgress);
+ }
+
+ //Cancel the fallback closing timeout and remove the timer data
+ var animationTimerData = element.data(ANIMATE_TIMER_KEY);
+ if (animationTimerData) {
+ $timeout.cancel(animationTimerData[0].timer);
+ element.removeData(ANIMATE_TIMER_KEY);
+ }
+
+ // if the preparation function fails then the promise is not setup
+ if (runner) {
+ runner.complete(!rejected);
+ }
+ }
+
+ function applyBlocking(duration) {
+ if (flags.blockTransition) {
+ blockTransitions(node, duration);
+ }
+
+ if (flags.blockKeyframeAnimation) {
+ blockKeyframeAnimations(node, !!duration);
+ }
+ }
+
+ function closeAndReturnNoopAnimator() {
+ runner = new $$AnimateRunner({
+ end: endFn,
+ cancel: cancelFn
+ });
+
+ // should flush the cache animation
+ waitUntilQuiet(noop);
+ close();
+
+ return {
+ $$willAnimate: false,
+ start: function() {
+ return runner;
+ },
+ end: endFn
+ };
+ }
+
+ function onAnimationProgress(event) {
+ event.stopPropagation();
+ var ev = event.originalEvent || event;
+
+ // we now always use `Date.now()` due to the recent changes with
+ // event.timeStamp in Firefox, Webkit and Chrome (see #13494 for more info)
+ var timeStamp = ev.$manualTimeStamp || Date.now();
+
+ /* Firefox (or possibly just Gecko) likes to not round values up
+ * when a ms measurement is used for the animation */
+ var elapsedTime = parseFloat(ev.elapsedTime.toFixed(ELAPSED_TIME_MAX_DECIMAL_PLACES));
+
+ /* $manualTimeStamp is a mocked timeStamp value which is set
+ * within browserTrigger(). This is only here so that tests can
+ * mock animations properly. Real events fallback to event.timeStamp,
+ * or, if they don't, then a timeStamp is automatically created for them.
+ * We're checking to see if the timeStamp surpasses the expected delay,
+ * but we're using elapsedTime instead of the timeStamp on the 2nd
+ * pre-condition since animationPauseds sometimes close off early */
+ if (Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) {
+ // we set this flag to ensure that if the transition is paused then, when resumed,
+ // the animation will automatically close itself since transitions cannot be paused.
+ animationCompleted = true;
+ close();
+ }
+ }
+
+ function start() {
+ if (animationClosed) return;
+ if (!node.parentNode) {
+ close();
+ return;
+ }
+
+ // even though we only pause keyframe animations here the pause flag
+ // will still happen when transitions are used. Only the transition will
+ // not be paused since that is not possible. If the animation ends when
+ // paused then it will not complete until unpaused or cancelled.
+ var playPause = function(playAnimation) {
+ if (!animationCompleted) {
+ animationPaused = !playAnimation;
+ if (timings.animationDuration) {
+ var value = blockKeyframeAnimations(node, animationPaused);
+ animationPaused
+ ? temporaryStyles.push(value)
+ : removeFromArray(temporaryStyles, value);
+ }
+ } else if (animationPaused && playAnimation) {
+ animationPaused = false;
+ close();
+ }
+ };
+
+ // checking the stagger duration prevents an accidentally cascade of the CSS delay style
+ // being inherited from the parent. If the transition duration is zero then we can safely
+ // rely that the delay value is an intentional stagger delay style.
+ var maxStagger = itemIndex > 0
+ && ((timings.transitionDuration && stagger.transitionDuration === 0) ||
+ (timings.animationDuration && stagger.animationDuration === 0))
+ && Math.max(stagger.animationDelay, stagger.transitionDelay);
+ if (maxStagger) {
+ $timeout(triggerAnimationStart,
+ Math.floor(maxStagger * itemIndex * ONE_SECOND),
+ false);
+ } else {
+ triggerAnimationStart();
+ }
+
+ // this will decorate the existing promise runner with pause/resume methods
+ runnerHost.resume = function() {
+ playPause(true);
+ };
+
+ runnerHost.pause = function() {
+ playPause(false);
+ };
+
+ function triggerAnimationStart() {
+ // just incase a stagger animation kicks in when the animation
+ // itself was cancelled entirely
+ if (animationClosed) return;
+
+ applyBlocking(false);
+
+ forEach(temporaryStyles, function(entry) {
+ var key = entry[0];
+ var value = entry[1];
+ node.style[key] = value;
+ });
+
+ applyAnimationClasses(element, options);
+ $$jqLite.addClass(element, activeClasses);
+
+ if (flags.recalculateTimingStyles) {
+ fullClassName = node.className + ' ' + preparationClasses;
+ cacheKey = gcsHashFn(node, fullClassName);
+
+ timings = computeTimings(node, fullClassName, cacheKey);
+ relativeDelay = timings.maxDelay;
+ maxDelay = Math.max(relativeDelay, 0);
+ maxDuration = timings.maxDuration;
+
+ if (maxDuration === 0) {
+ close();
+ return;
+ }
+
+ flags.hasTransitions = timings.transitionDuration > 0;
+ flags.hasAnimations = timings.animationDuration > 0;
+ }
+
+ if (flags.applyAnimationDelay) {
+ relativeDelay = typeof options.delay !== "boolean" && truthyTimingValue(options.delay)
+ ? parseFloat(options.delay)
+ : relativeDelay;
+
+ maxDelay = Math.max(relativeDelay, 0);
+ timings.animationDelay = relativeDelay;
+ delayStyle = getCssDelayStyle(relativeDelay, true);
+ temporaryStyles.push(delayStyle);
+ node.style[delayStyle[0]] = delayStyle[1];
+ }
+
+ maxDelayTime = maxDelay * ONE_SECOND;
+ maxDurationTime = maxDuration * ONE_SECOND;
+
+ if (options.easing) {
+ var easeProp, easeVal = options.easing;
+ if (flags.hasTransitions) {
+ easeProp = TRANSITION_PROP + TIMING_KEY;
+ temporaryStyles.push([easeProp, easeVal]);
+ node.style[easeProp] = easeVal;
+ }
+ if (flags.hasAnimations) {
+ easeProp = ANIMATION_PROP + TIMING_KEY;
+ temporaryStyles.push([easeProp, easeVal]);
+ node.style[easeProp] = easeVal;
+ }
+ }
+
+ if (timings.transitionDuration) {
+ events.push(TRANSITIONEND_EVENT);
+ }
+
+ if (timings.animationDuration) {
+ events.push(ANIMATIONEND_EVENT);
+ }
+
+ startTime = Date.now();
+ var timerTime = maxDelayTime + CLOSING_TIME_BUFFER * maxDurationTime;
+ var endTime = startTime + timerTime;
+
+ var animationsData = element.data(ANIMATE_TIMER_KEY) || [];
+ var setupFallbackTimer = true;
+ if (animationsData.length) {
+ var currentTimerData = animationsData[0];
+ setupFallbackTimer = endTime > currentTimerData.expectedEndTime;
+ if (setupFallbackTimer) {
+ $timeout.cancel(currentTimerData.timer);
+ } else {
+ animationsData.push(close);
+ }
+ }
+
+ if (setupFallbackTimer) {
+ var timer = $timeout(onAnimationExpired, timerTime, false);
+ animationsData[0] = {
+ timer: timer,
+ expectedEndTime: endTime
+ };
+ animationsData.push(close);
+ element.data(ANIMATE_TIMER_KEY, animationsData);
+ }
+
+ if (events.length) {
+ element.on(events.join(' '), onAnimationProgress);
+ }
+
+ if (options.to) {
+ if (options.cleanupStyles) {
+ registerRestorableStyles(restoreStyles, node, Object.keys(options.to));
+ }
+ applyAnimationToStyles(element, options);
+ }
+ }
+
+ function onAnimationExpired() {
+ var animationsData = element.data(ANIMATE_TIMER_KEY);
+
+ // this will be false in the event that the element was
+ // removed from the DOM (via a leave animation or something
+ // similar)
+ if (animationsData) {
+ for (var i = 1; i < animationsData.length; i++) {
+ animationsData[i]();
+ }
+ element.removeData(ANIMATE_TIMER_KEY);
+ }
+ }
+ }
+ };
+ }];
+}];
+
+var $$AnimateCssDriverProvider = ['$$animationProvider', function($$animationProvider) {
+ $$animationProvider.drivers.push('$$animateCssDriver');
+
+ var NG_ANIMATE_SHIM_CLASS_NAME = 'ng-animate-shim';
+ var NG_ANIMATE_ANCHOR_CLASS_NAME = 'ng-anchor';
+
+ var NG_OUT_ANCHOR_CLASS_NAME = 'ng-anchor-out';
+ var NG_IN_ANCHOR_CLASS_NAME = 'ng-anchor-in';
+
+ function isDocumentFragment(node) {
+ return node.parentNode && node.parentNode.nodeType === 11;
+ }
+
+ this.$get = ['$animateCss', '$rootScope', '$$AnimateRunner', '$rootElement', '$sniffer', '$$jqLite', '$document',
+ function($animateCss, $rootScope, $$AnimateRunner, $rootElement, $sniffer, $$jqLite, $document) {
+
+ // only browsers that support these properties can render animations
+ if (!$sniffer.animations && !$sniffer.transitions) return noop;
+
+ var bodyNode = $document[0].body;
+ var rootNode = getDomNode($rootElement);
+
+ var rootBodyElement = jqLite(
+ // this is to avoid using something that exists outside of the body
+ // we also special case the doc fragment case because our unit test code
+ // appends the $rootElement to the body after the app has been bootstrapped
+ isDocumentFragment(rootNode) || bodyNode.contains(rootNode) ? rootNode : bodyNode
+ );
+
+ var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
+
+ return function initDriverFn(animationDetails) {
+ return animationDetails.from && animationDetails.to
+ ? prepareFromToAnchorAnimation(animationDetails.from,
+ animationDetails.to,
+ animationDetails.classes,
+ animationDetails.anchors)
+ : prepareRegularAnimation(animationDetails);
+ };
+
+ function filterCssClasses(classes) {
+ //remove all the `ng-` stuff
+ return classes.replace(/\bng-\S+\b/g, '');
+ }
+
+ function getUniqueValues(a, b) {
+ if (isString(a)) a = a.split(' ');
+ if (isString(b)) b = b.split(' ');
+ return a.filter(function(val) {
+ return b.indexOf(val) === -1;
+ }).join(' ');
+ }
+
+ function prepareAnchoredAnimation(classes, outAnchor, inAnchor) {
+ var clone = jqLite(getDomNode(outAnchor).cloneNode(true));
+ var startingClasses = filterCssClasses(getClassVal(clone));
+
+ outAnchor.addClass(NG_ANIMATE_SHIM_CLASS_NAME);
+ inAnchor.addClass(NG_ANIMATE_SHIM_CLASS_NAME);
+
+ clone.addClass(NG_ANIMATE_ANCHOR_CLASS_NAME);
+
+ rootBodyElement.append(clone);
+
+ var animatorIn, animatorOut = prepareOutAnimation();
+
+ // the user may not end up using the `out` animation and
+ // only making use of the `in` animation or vice-versa.
+ // In either case we should allow this and not assume the
+ // animation is over unless both animations are not used.
+ if (!animatorOut) {
+ animatorIn = prepareInAnimation();
+ if (!animatorIn) {
+ return end();
+ }
+ }
+
+ var startingAnimator = animatorOut || animatorIn;
+
+ return {
+ start: function() {
+ var runner;
+
+ var currentAnimation = startingAnimator.start();
+ currentAnimation.done(function() {
+ currentAnimation = null;
+ if (!animatorIn) {
+ animatorIn = prepareInAnimation();
+ if (animatorIn) {
+ currentAnimation = animatorIn.start();
+ currentAnimation.done(function() {
+ currentAnimation = null;
+ end();
+ runner.complete();
+ });
+ return currentAnimation;
+ }
+ }
+ // in the event that there is no `in` animation
+ end();
+ runner.complete();
+ });
+
+ runner = new $$AnimateRunner({
+ end: endFn,
+ cancel: endFn
+ });
+
+ return runner;
+
+ function endFn() {
+ if (currentAnimation) {
+ currentAnimation.end();
+ }
+ }
+ }
+ };
+
+ function calculateAnchorStyles(anchor) {
+ var styles = {};
+
+ var coords = getDomNode(anchor).getBoundingClientRect();
+
+ // we iterate directly since safari messes up and doesn't return
+ // all the keys for the coords object when iterated
+ forEach(['width','height','top','left'], function(key) {
+ var value = coords[key];
+ switch (key) {
+ case 'top':
+ value += bodyNode.scrollTop;
+ break;
+ case 'left':
+ value += bodyNode.scrollLeft;
+ break;
+ }
+ styles[key] = Math.floor(value) + 'px';
+ });
+ return styles;
+ }
+
+ function prepareOutAnimation() {
+ var animator = $animateCss(clone, {
+ addClass: NG_OUT_ANCHOR_CLASS_NAME,
+ delay: true,
+ from: calculateAnchorStyles(outAnchor)
+ });
+
+ // read the comment within `prepareRegularAnimation` to understand
+ // why this check is necessary
+ return animator.$$willAnimate ? animator : null;
+ }
+
+ function getClassVal(element) {
+ return element.attr('class') || '';
+ }
+
+ function prepareInAnimation() {
+ var endingClasses = filterCssClasses(getClassVal(inAnchor));
+ var toAdd = getUniqueValues(endingClasses, startingClasses);
+ var toRemove = getUniqueValues(startingClasses, endingClasses);
+
+ var animator = $animateCss(clone, {
+ to: calculateAnchorStyles(inAnchor),
+ addClass: NG_IN_ANCHOR_CLASS_NAME + ' ' + toAdd,
+ removeClass: NG_OUT_ANCHOR_CLASS_NAME + ' ' + toRemove,
+ delay: true
+ });
+
+ // read the comment within `prepareRegularAnimation` to understand
+ // why this check is necessary
+ return animator.$$willAnimate ? animator : null;
+ }
+
+ function end() {
+ clone.remove();
+ outAnchor.removeClass(NG_ANIMATE_SHIM_CLASS_NAME);
+ inAnchor.removeClass(NG_ANIMATE_SHIM_CLASS_NAME);
+ }
+ }
+
+ function prepareFromToAnchorAnimation(from, to, classes, anchors) {
+ var fromAnimation = prepareRegularAnimation(from, noop);
+ var toAnimation = prepareRegularAnimation(to, noop);
+
+ var anchorAnimations = [];
+ forEach(anchors, function(anchor) {
+ var outElement = anchor['out'];
+ var inElement = anchor['in'];
+ var animator = prepareAnchoredAnimation(classes, outElement, inElement);
+ if (animator) {
+ anchorAnimations.push(animator);
+ }
+ });
+
+ // no point in doing anything when there are no elements to animate
+ if (!fromAnimation && !toAnimation && anchorAnimations.length === 0) return;
+
+ return {
+ start: function() {
+ var animationRunners = [];
+
+ if (fromAnimation) {
+ animationRunners.push(fromAnimation.start());
+ }
+
+ if (toAnimation) {
+ animationRunners.push(toAnimation.start());
+ }
+
+ forEach(anchorAnimations, function(animation) {
+ animationRunners.push(animation.start());
+ });
+
+ var runner = new $$AnimateRunner({
+ end: endFn,
+ cancel: endFn // CSS-driven animations cannot be cancelled, only ended
+ });
+
+ $$AnimateRunner.all(animationRunners, function(status) {
+ runner.complete(status);
+ });
+
+ return runner;
+
+ function endFn() {
+ forEach(animationRunners, function(runner) {
+ runner.end();
+ });
+ }
+ }
+ };
+ }
+
+ function prepareRegularAnimation(animationDetails) {
+ var element = animationDetails.element;
+ var options = animationDetails.options || {};
+
+ if (animationDetails.structural) {
+ options.event = animationDetails.event;
+ options.structural = true;
+ options.applyClassesEarly = true;
+
+ // we special case the leave animation since we want to ensure that
+ // the element is removed as soon as the animation is over. Otherwise
+ // a flicker might appear or the element may not be removed at all
+ if (animationDetails.event === 'leave') {
+ options.onDone = options.domOperation;
+ }
+ }
+
+ // We assign the preparationClasses as the actual animation event since
+ // the internals of $animateCss will just suffix the event token values
+ // with `-active` to trigger the animation.
+ if (options.preparationClasses) {
+ options.event = concatWithSpace(options.event, options.preparationClasses);
+ }
+
+ var animator = $animateCss(element, options);
+
+ // the driver lookup code inside of $$animation attempts to spawn a
+ // driver one by one until a driver returns a.$$willAnimate animator object.
+ // $animateCss will always return an object, however, it will pass in
+ // a flag as a hint as to whether an animation was detected or not
+ return animator.$$willAnimate ? animator : null;
+ }
+ }];
+}];
+
+// TODO(matsko): use caching here to speed things up for detection
+// TODO(matsko): add documentation
+// by the time...
+
+var $$AnimateJsProvider = ['$animateProvider', function($animateProvider) {
+ this.$get = ['$injector', '$$AnimateRunner', '$$jqLite',
+ function($injector, $$AnimateRunner, $$jqLite) {
+
+ var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
+ // $animateJs(element, 'enter');
+ return function(element, event, classes, options) {
+ var animationClosed = false;
+
+ // the `classes` argument is optional and if it is not used
+ // then the classes will be resolved from the element's className
+ // property as well as options.addClass/options.removeClass.
+ if (arguments.length === 3 && isObject(classes)) {
+ options = classes;
+ classes = null;
+ }
+
+ options = prepareAnimationOptions(options);
+ if (!classes) {
+ classes = element.attr('class') || '';
+ if (options.addClass) {
+ classes += ' ' + options.addClass;
+ }
+ if (options.removeClass) {
+ classes += ' ' + options.removeClass;
+ }
+ }
+
+ var classesToAdd = options.addClass;
+ var classesToRemove = options.removeClass;
+
+ // the lookupAnimations function returns a series of animation objects that are
+ // matched up with one or more of the CSS classes. These animation objects are
+ // defined via the module.animation factory function. If nothing is detected then
+ // we don't return anything which then makes $animation query the next driver.
+ var animations = lookupAnimations(classes);
+ var before, after;
+ if (animations.length) {
+ var afterFn, beforeFn;
+ if (event == 'leave') {
+ beforeFn = 'leave';
+ afterFn = 'afterLeave'; // TODO(matsko): get rid of this
+ } else {
+ beforeFn = 'before' + event.charAt(0).toUpperCase() + event.substr(1);
+ afterFn = event;
+ }
+
+ if (event !== 'enter' && event !== 'move') {
+ before = packageAnimations(element, event, options, animations, beforeFn);
+ }
+ after = packageAnimations(element, event, options, animations, afterFn);
+ }
+
+ // no matching animations
+ if (!before && !after) return;
+
+ function applyOptions() {
+ options.domOperation();
+ applyAnimationClasses(element, options);
+ }
+
+ function close() {
+ animationClosed = true;
+ applyOptions();
+ applyAnimationStyles(element, options);
+ }
+
+ var runner;
+
+ return {
+ $$willAnimate: true,
+ end: function() {
+ if (runner) {
+ runner.end();
+ } else {
+ close();
+ runner = new $$AnimateRunner();
+ runner.complete(true);
+ }
+ return runner;
+ },
+ start: function() {
+ if (runner) {
+ return runner;
+ }
+
+ runner = new $$AnimateRunner();
+ var closeActiveAnimations;
+ var chain = [];
+
+ if (before) {
+ chain.push(function(fn) {
+ closeActiveAnimations = before(fn);
+ });
+ }
+
+ if (chain.length) {
+ chain.push(function(fn) {
+ applyOptions();
+ fn(true);
+ });
+ } else {
+ applyOptions();
+ }
+
+ if (after) {
+ chain.push(function(fn) {
+ closeActiveAnimations = after(fn);
+ });
+ }
+
+ runner.setHost({
+ end: function() {
+ endAnimations();
+ },
+ cancel: function() {
+ endAnimations(true);
+ }
+ });
+
+ $$AnimateRunner.chain(chain, onComplete);
+ return runner;
+
+ function onComplete(success) {
+ close(success);
+ runner.complete(success);
+ }
+
+ function endAnimations(cancelled) {
+ if (!animationClosed) {
+ (closeActiveAnimations || noop)(cancelled);
+ onComplete(cancelled);
+ }
+ }
+ }
+ };
+
+ function executeAnimationFn(fn, element, event, options, onDone) {
+ var args;
+ switch (event) {
+ case 'animate':
+ args = [element, options.from, options.to, onDone];
+ break;
+
+ case 'setClass':
+ args = [element, classesToAdd, classesToRemove, onDone];
+ break;
+
+ case 'addClass':
+ args = [element, classesToAdd, onDone];
+ break;
+
+ case 'removeClass':
+ args = [element, classesToRemove, onDone];
+ break;
+
+ default:
+ args = [element, onDone];
+ break;
+ }
+
+ args.push(options);
+
+ var value = fn.apply(fn, args);
+ if (value) {
+ if (isFunction(value.start)) {
+ value = value.start();
+ }
+
+ if (value instanceof $$AnimateRunner) {
+ value.done(onDone);
+ } else if (isFunction(value)) {
+ // optional onEnd / onCancel callback
+ return value;
+ }
+ }
+
+ return noop;
+ }
+
+ function groupEventedAnimations(element, event, options, animations, fnName) {
+ var operations = [];
+ forEach(animations, function(ani) {
+ var animation = ani[fnName];
+ if (!animation) return;
+
+ // note that all of these animations will run in parallel
+ operations.push(function() {
+ var runner;
+ var endProgressCb;
+
+ var resolved = false;
+ var onAnimationComplete = function(rejected) {
+ if (!resolved) {
+ resolved = true;
+ (endProgressCb || noop)(rejected);
+ runner.complete(!rejected);
+ }
+ };
+
+ runner = new $$AnimateRunner({
+ end: function() {
+ onAnimationComplete();
+ },
+ cancel: function() {
+ onAnimationComplete(true);
+ }
+ });
+
+ endProgressCb = executeAnimationFn(animation, element, event, options, function(result) {
+ var cancelled = result === false;
+ onAnimationComplete(cancelled);
+ });
+
+ return runner;
+ });
+ });
+
+ return operations;
+ }
+
+ function packageAnimations(element, event, options, animations, fnName) {
+ var operations = groupEventedAnimations(element, event, options, animations, fnName);
+ if (operations.length === 0) {
+ var a,b;
+ if (fnName === 'beforeSetClass') {
+ a = groupEventedAnimations(element, 'removeClass', options, animations, 'beforeRemoveClass');
+ b = groupEventedAnimations(element, 'addClass', options, animations, 'beforeAddClass');
+ } else if (fnName === 'setClass') {
+ a = groupEventedAnimations(element, 'removeClass', options, animations, 'removeClass');
+ b = groupEventedAnimations(element, 'addClass', options, animations, 'addClass');
+ }
+
+ if (a) {
+ operations = operations.concat(a);
+ }
+ if (b) {
+ operations = operations.concat(b);
+ }
+ }
+
+ if (operations.length === 0) return;
+
+ // TODO(matsko): add documentation
+ return function startAnimation(callback) {
+ var runners = [];
+ if (operations.length) {
+ forEach(operations, function(animateFn) {
+ runners.push(animateFn());
+ });
+ }
+
+ runners.length ? $$AnimateRunner.all(runners, callback) : callback();
+
+ return function endFn(reject) {
+ forEach(runners, function(runner) {
+ reject ? runner.cancel() : runner.end();
+ });
+ };
+ };
+ }
+ };
+
+ function lookupAnimations(classes) {
+ classes = isArray(classes) ? classes : classes.split(' ');
+ var matches = [], flagMap = {};
+ for (var i=0; i < classes.length; i++) {
+ var klass = classes[i],
+ animationFactory = $animateProvider.$$registeredAnimations[klass];
+ if (animationFactory && !flagMap[klass]) {
+ matches.push($injector.get(animationFactory));
+ flagMap[klass] = true;
+ }
+ }
+ return matches;
+ }
+ }];
+}];
+
+var $$AnimateJsDriverProvider = ['$$animationProvider', function($$animationProvider) {
+ $$animationProvider.drivers.push('$$animateJsDriver');
+ this.$get = ['$$animateJs', '$$AnimateRunner', function($$animateJs, $$AnimateRunner) {
+ return function initDriverFn(animationDetails) {
+ if (animationDetails.from && animationDetails.to) {
+ var fromAnimation = prepareAnimation(animationDetails.from);
+ var toAnimation = prepareAnimation(animationDetails.to);
+ if (!fromAnimation && !toAnimation) return;
+
+ return {
+ start: function() {
+ var animationRunners = [];
+
+ if (fromAnimation) {
+ animationRunners.push(fromAnimation.start());
+ }
+
+ if (toAnimation) {
+ animationRunners.push(toAnimation.start());
+ }
+
+ $$AnimateRunner.all(animationRunners, done);
+
+ var runner = new $$AnimateRunner({
+ end: endFnFactory(),
+ cancel: endFnFactory()
+ });
+
+ return runner;
+
+ function endFnFactory() {
+ return function() {
+ forEach(animationRunners, function(runner) {
+ // at this point we cannot cancel animations for groups just yet. 1.5+
+ runner.end();
+ });
+ };
+ }
+
+ function done(status) {
+ runner.complete(status);
+ }
+ }
+ };
+ } else {
+ return prepareAnimation(animationDetails);
+ }
+ };
+
+ function prepareAnimation(animationDetails) {
+ // TODO(matsko): make sure to check for grouped animations and delegate down to normal animations
+ var element = animationDetails.element;
+ var event = animationDetails.event;
+ var options = animationDetails.options;
+ var classes = animationDetails.classes;
+ return $$animateJs(element, event, classes, options);
+ }
+ }];
+}];
+
+var NG_ANIMATE_ATTR_NAME = 'data-ng-animate';
+var NG_ANIMATE_PIN_DATA = '$ngAnimatePin';
+var $$AnimateQueueProvider = ['$animateProvider', function($animateProvider) {
+ var PRE_DIGEST_STATE = 1;
+ var RUNNING_STATE = 2;
+ var ONE_SPACE = ' ';
+
+ var rules = this.rules = {
+ skip: [],
+ cancel: [],
+ join: []
+ };
+
+ function makeTruthyCssClassMap(classString) {
+ if (!classString) {
+ return null;
+ }
+
+ var keys = classString.split(ONE_SPACE);
+ var map = Object.create(null);
+
+ forEach(keys, function(key) {
+ map[key] = true;
+ });
+ return map;
+ }
+
+ function hasMatchingClasses(newClassString, currentClassString) {
+ if (newClassString && currentClassString) {
+ var currentClassMap = makeTruthyCssClassMap(currentClassString);
+ return newClassString.split(ONE_SPACE).some(function(className) {
+ return currentClassMap[className];
+ });
+ }
+ }
+
+ function isAllowed(ruleType, element, currentAnimation, previousAnimation) {
+ return rules[ruleType].some(function(fn) {
+ return fn(element, currentAnimation, previousAnimation);
+ });
+ }
+
+ function hasAnimationClasses(animation, and) {
+ var a = (animation.addClass || '').length > 0;
+ var b = (animation.removeClass || '').length > 0;
+ return and ? a && b : a || b;
+ }
+
+ rules.join.push(function(element, newAnimation, currentAnimation) {
+ // if the new animation is class-based then we can just tack that on
+ return !newAnimation.structural && hasAnimationClasses(newAnimation);
+ });
+
+ rules.skip.push(function(element, newAnimation, currentAnimation) {
+ // there is no need to animate anything if no classes are being added and
+ // there is no structural animation that will be triggered
+ return !newAnimation.structural && !hasAnimationClasses(newAnimation);
+ });
+
+ rules.skip.push(function(element, newAnimation, currentAnimation) {
+ // why should we trigger a new structural animation if the element will
+ // be removed from the DOM anyway?
+ return currentAnimation.event == 'leave' && newAnimation.structural;
+ });
+
+ rules.skip.push(function(element, newAnimation, currentAnimation) {
+ // if there is an ongoing current animation then don't even bother running the class-based animation
+ return currentAnimation.structural && currentAnimation.state === RUNNING_STATE && !newAnimation.structural;
+ });
+
+ rules.cancel.push(function(element, newAnimation, currentAnimation) {
+ // there can never be two structural animations running at the same time
+ return currentAnimation.structural && newAnimation.structural;
+ });
+
+ rules.cancel.push(function(element, newAnimation, currentAnimation) {
+ // if the previous animation is already running, but the new animation will
+ // be triggered, but the new animation is structural
+ return currentAnimation.state === RUNNING_STATE && newAnimation.structural;
+ });
+
+ rules.cancel.push(function(element, newAnimation, currentAnimation) {
+ var nA = newAnimation.addClass;
+ var nR = newAnimation.removeClass;
+ var cA = currentAnimation.addClass;
+ var cR = currentAnimation.removeClass;
+
+ // early detection to save the global CPU shortage :)
+ if ((isUndefined(nA) && isUndefined(nR)) || (isUndefined(cA) && isUndefined(cR))) {
+ return false;
+ }
+
+ return hasMatchingClasses(nA, cR) || hasMatchingClasses(nR, cA);
+ });
+
+ this.$get = ['$$rAF', '$rootScope', '$rootElement', '$document', '$$HashMap',
+ '$$animation', '$$AnimateRunner', '$templateRequest', '$$jqLite', '$$forceReflow',
+ function($$rAF, $rootScope, $rootElement, $document, $$HashMap,
+ $$animation, $$AnimateRunner, $templateRequest, $$jqLite, $$forceReflow) {
+
+ var activeAnimationsLookup = new $$HashMap();
+ var disabledElementsLookup = new $$HashMap();
+ var animationsEnabled = null;
+
+ function postDigestTaskFactory() {
+ var postDigestCalled = false;
+ return function(fn) {
+ // we only issue a call to postDigest before
+ // it has first passed. This prevents any callbacks
+ // from not firing once the animation has completed
+ // since it will be out of the digest cycle.
+ if (postDigestCalled) {
+ fn();
+ } else {
+ $rootScope.$$postDigest(function() {
+ postDigestCalled = true;
+ fn();
+ });
+ }
+ };
+ }
+
+ // Wait until all directive and route-related templates are downloaded and
+ // compiled. The $templateRequest.totalPendingRequests variable keeps track of
+ // all of the remote templates being currently downloaded. If there are no
+ // templates currently downloading then the watcher will still fire anyway.
+ var deregisterWatch = $rootScope.$watch(
+ function() { return $templateRequest.totalPendingRequests === 0; },
+ function(isEmpty) {
+ if (!isEmpty) return;
+ deregisterWatch();
+
+ // Now that all templates have been downloaded, $animate will wait until
+ // the post digest queue is empty before enabling animations. By having two
+ // calls to $postDigest calls we can ensure that the flag is enabled at the
+ // very end of the post digest queue. Since all of the animations in $animate
+ // use $postDigest, it's important that the code below executes at the end.
+ // This basically means that the page is fully downloaded and compiled before
+ // any animations are triggered.
+ $rootScope.$$postDigest(function() {
+ $rootScope.$$postDigest(function() {
+ // we check for null directly in the event that the application already called
+ // .enabled() with whatever arguments that it provided it with
+ if (animationsEnabled === null) {
+ animationsEnabled = true;
+ }
+ });
+ });
+ }
+ );
+
+ var callbackRegistry = {};
+
+ // remember that the classNameFilter is set during the provider/config
+ // stage therefore we can optimize here and setup a helper function
+ var classNameFilter = $animateProvider.classNameFilter();
+ var isAnimatableClassName = !classNameFilter
+ ? function() { return true; }
+ : function(className) {
+ return classNameFilter.test(className);
+ };
+
+ var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
+
+ function normalizeAnimationDetails(element, animation) {
+ return mergeAnimationDetails(element, animation, {});
+ }
+
+ // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
+ var contains = Node.prototype.contains || function(arg) {
+ // jshint bitwise: false
+ return this === arg || !!(this.compareDocumentPosition(arg) & 16);
+ // jshint bitwise: true
+ };
+
+ function findCallbacks(parent, element, event) {
+ var targetNode = getDomNode(element);
+ var targetParentNode = getDomNode(parent);
+
+ var matches = [];
+ var entries = callbackRegistry[event];
+ if (entries) {
+ forEach(entries, function(entry) {
+ if (contains.call(entry.node, targetNode)) {
+ matches.push(entry.callback);
+ } else if (event === 'leave' && contains.call(entry.node, targetParentNode)) {
+ matches.push(entry.callback);
+ }
+ });
+ }
+
+ return matches;
+ }
+
+ return {
+ on: function(event, container, callback) {
+ var node = extractElementNode(container);
+ callbackRegistry[event] = callbackRegistry[event] || [];
+ callbackRegistry[event].push({
+ node: node,
+ callback: callback
+ });
+ },
+
+ off: function(event, container, callback) {
+ var entries = callbackRegistry[event];
+ if (!entries) return;
+
+ callbackRegistry[event] = arguments.length === 1
+ ? null
+ : filterFromRegistry(entries, container, callback);
+
+ function filterFromRegistry(list, matchContainer, matchCallback) {
+ var containerNode = extractElementNode(matchContainer);
+ return list.filter(function(entry) {
+ var isMatch = entry.node === containerNode &&
+ (!matchCallback || entry.callback === matchCallback);
+ return !isMatch;
+ });
+ }
+ },
+
+ pin: function(element, parentElement) {
+ assertArg(isElement(element), 'element', 'not an element');
+ assertArg(isElement(parentElement), 'parentElement', 'not an element');
+ element.data(NG_ANIMATE_PIN_DATA, parentElement);
+ },
+
+ push: function(element, event, options, domOperation) {
+ options = options || {};
+ options.domOperation = domOperation;
+ return queueAnimation(element, event, options);
+ },
+
+ // this method has four signatures:
+ // () - global getter
+ // (bool) - global setter
+ // (element) - element getter
+ // (element, bool) - element setter
+ enabled: function(element, bool) {
+ var argCount = arguments.length;
+
+ if (argCount === 0) {
+ // () - Global getter
+ bool = !!animationsEnabled;
+ } else {
+ var hasElement = isElement(element);
+
+ if (!hasElement) {
+ // (bool) - Global setter
+ bool = animationsEnabled = !!element;
+ } else {
+ var node = getDomNode(element);
+ var recordExists = disabledElementsLookup.get(node);
+
+ if (argCount === 1) {
+ // (element) - Element getter
+ bool = !recordExists;
+ } else {
+ // (element, bool) - Element setter
+ disabledElementsLookup.put(node, !bool);
+ }
+ }
+ }
+
+ return bool;
+ }
+ };
+
+ function queueAnimation(element, event, initialOptions) {
+ // we always make a copy of the options since
+ // there should never be any side effects on
+ // the input data when running `$animateCss`.
+ var options = copy(initialOptions);
+
+ var node, parent;
+ element = stripCommentsFromElement(element);
+ if (element) {
+ node = getDomNode(element);
+ parent = element.parent();
+ }
+
+ options = prepareAnimationOptions(options);
+
+ // we create a fake runner with a working promise.
+ // These methods will become available after the digest has passed
+ var runner = new $$AnimateRunner();
+
+ // this is used to trigger callbacks in postDigest mode
+ var runInNextPostDigestOrNow = postDigestTaskFactory();
+
+ if (isArray(options.addClass)) {
+ options.addClass = options.addClass.join(' ');
+ }
+
+ if (options.addClass && !isString(options.addClass)) {
+ options.addClass = null;
+ }
+
+ if (isArray(options.removeClass)) {
+ options.removeClass = options.removeClass.join(' ');
+ }
+
+ if (options.removeClass && !isString(options.removeClass)) {
+ options.removeClass = null;
+ }
+
+ if (options.from && !isObject(options.from)) {
+ options.from = null;
+ }
+
+ if (options.to && !isObject(options.to)) {
+ options.to = null;
+ }
+
+ // there are situations where a directive issues an animation for
+ // a jqLite wrapper that contains only comment nodes... If this
+ // happens then there is no way we can perform an animation
+ if (!node) {
+ close();
+ return runner;
+ }
+
+ var className = [node.className, options.addClass, options.removeClass].join(' ');
+ if (!isAnimatableClassName(className)) {
+ close();
+ return runner;
+ }
+
+ var isStructural = ['enter', 'move', 'leave'].indexOf(event) >= 0;
+
+ // this is a hard disable of all animations for the application or on
+ // the element itself, therefore there is no need to continue further
+ // past this point if not enabled
+ // Animations are also disabled if the document is currently hidden (page is not visible
+ // to the user), because browsers slow down or do not flush calls to requestAnimationFrame
+ var skipAnimations = !animationsEnabled || $document[0].hidden || disabledElementsLookup.get(node);
+ var existingAnimation = (!skipAnimations && activeAnimationsLookup.get(node)) || {};
+ var hasExistingAnimation = !!existingAnimation.state;
+
+ // there is no point in traversing the same collection of parent ancestors if a followup
+ // animation will be run on the same element that already did all that checking work
+ if (!skipAnimations && (!hasExistingAnimation || existingAnimation.state != PRE_DIGEST_STATE)) {
+ skipAnimations = !areAnimationsAllowed(element, parent, event);
+ }
+
+ if (skipAnimations) {
+ close();
+ return runner;
+ }
+
+ if (isStructural) {
+ closeChildAnimations(element);
+ }
+
+ var newAnimation = {
+ structural: isStructural,
+ element: element,
+ event: event,
+ addClass: options.addClass,
+ removeClass: options.removeClass,
+ close: close,
+ options: options,
+ runner: runner
+ };
+
+ if (hasExistingAnimation) {
+ var skipAnimationFlag = isAllowed('skip', element, newAnimation, existingAnimation);
+ if (skipAnimationFlag) {
+ if (existingAnimation.state === RUNNING_STATE) {
+ close();
+ return runner;
+ } else {
+ mergeAnimationDetails(element, existingAnimation, newAnimation);
+ return existingAnimation.runner;
+ }
+ }
+ var cancelAnimationFlag = isAllowed('cancel', element, newAnimation, existingAnimation);
+ if (cancelAnimationFlag) {
+ if (existingAnimation.state === RUNNING_STATE) {
+ // this will end the animation right away and it is safe
+ // to do so since the animation is already running and the
+ // runner callback code will run in async
+ existingAnimation.runner.end();
+ } else if (existingAnimation.structural) {
+ // this means that the animation is queued into a digest, but
+ // hasn't started yet. Therefore it is safe to run the close
+ // method which will call the runner methods in async.
+ existingAnimation.close();
+ } else {
+ // this will merge the new animation options into existing animation options
+ mergeAnimationDetails(element, existingAnimation, newAnimation);
+
+ return existingAnimation.runner;
+ }
+ } else {
+ // a joined animation means that this animation will take over the existing one
+ // so an example would involve a leave animation taking over an enter. Then when
+ // the postDigest kicks in the enter will be ignored.
+ var joinAnimationFlag = isAllowed('join', element, newAnimation, existingAnimation);
+ if (joinAnimationFlag) {
+ if (existingAnimation.state === RUNNING_STATE) {
+ normalizeAnimationDetails(element, newAnimation);
+ } else {
+ applyGeneratedPreparationClasses(element, isStructural ? event : null, options);
+
+ event = newAnimation.event = existingAnimation.event;
+ options = mergeAnimationDetails(element, existingAnimation, newAnimation);
+
+ //we return the same runner since only the option values of this animation will
+ //be fed into the `existingAnimation`.
+ return existingAnimation.runner;
+ }
+ }
+ }
+ } else {
+ // normalization in this case means that it removes redundant CSS classes that
+ // already exist (addClass) or do not exist (removeClass) on the element
+ normalizeAnimationDetails(element, newAnimation);
+ }
+
+ // when the options are merged and cleaned up we may end up not having to do
+ // an animation at all, therefore we should check this before issuing a post
+ // digest callback. Structural animations will always run no matter what.
+ var isValidAnimation = newAnimation.structural;
+ if (!isValidAnimation) {
+ // animate (from/to) can be quickly checked first, otherwise we check if any classes are present
+ isValidAnimation = (newAnimation.event === 'animate' && Object.keys(newAnimation.options.to || {}).length > 0)
+ || hasAnimationClasses(newAnimation);
+ }
+
+ if (!isValidAnimation) {
+ close();
+ clearElementAnimationState(element);
+ return runner;
+ }
+
+ // the counter keeps track of cancelled animations
+ var counter = (existingAnimation.counter || 0) + 1;
+ newAnimation.counter = counter;
+
+ markElementAnimationState(element, PRE_DIGEST_STATE, newAnimation);
+
+ $rootScope.$$postDigest(function() {
+ var animationDetails = activeAnimationsLookup.get(node);
+ var animationCancelled = !animationDetails;
+ animationDetails = animationDetails || {};
+
+ // if addClass/removeClass is called before something like enter then the
+ // registered parent element may not be present. The code below will ensure
+ // that a final value for parent element is obtained
+ var parentElement = element.parent() || [];
+
+ // animate/structural/class-based animations all have requirements. Otherwise there
+ // is no point in performing an animation. The parent node must also be set.
+ var isValidAnimation = parentElement.length > 0
+ && (animationDetails.event === 'animate'
+ || animationDetails.structural
+ || hasAnimationClasses(animationDetails));
+
+ // this means that the previous animation was cancelled
+ // even if the follow-up animation is the same event
+ if (animationCancelled || animationDetails.counter !== counter || !isValidAnimation) {
+ // if another animation did not take over then we need
+ // to make sure that the domOperation and options are
+ // handled accordingly
+ if (animationCancelled) {
+ applyAnimationClasses(element, options);
+ applyAnimationStyles(element, options);
+ }
+
+ // if the event changed from something like enter to leave then we do
+ // it, otherwise if it's the same then the end result will be the same too
+ if (animationCancelled || (isStructural && animationDetails.event !== event)) {
+ options.domOperation();
+ runner.end();
+ }
+
+ // in the event that the element animation was not cancelled or a follow-up animation
+ // isn't allowed to animate from here then we need to clear the state of the element
+ // so that any future animations won't read the expired animation data.
+ if (!isValidAnimation) {
+ clearElementAnimationState(element);
+ }
+
+ return;
+ }
+
+ // this combined multiple class to addClass / removeClass into a setClass event
+ // so long as a structural event did not take over the animation
+ event = !animationDetails.structural && hasAnimationClasses(animationDetails, true)
+ ? 'setClass'
+ : animationDetails.event;
+
+ markElementAnimationState(element, RUNNING_STATE);
+ var realRunner = $$animation(element, event, animationDetails.options);
+
+ realRunner.done(function(status) {
+ close(!status);
+ var animationDetails = activeAnimationsLookup.get(node);
+ if (animationDetails && animationDetails.counter === counter) {
+ clearElementAnimationState(getDomNode(element));
+ }
+ notifyProgress(runner, event, 'close', {});
+ });
+
+ // this will update the runner's flow-control events based on
+ // the `realRunner` object.
+ runner.setHost(realRunner);
+ notifyProgress(runner, event, 'start', {});
+ });
+
+ return runner;
+
+ function notifyProgress(runner, event, phase, data) {
+ runInNextPostDigestOrNow(function() {
+ var callbacks = findCallbacks(parent, element, event);
+ if (callbacks.length) {
+ // do not optimize this call here to RAF because
+ // we don't know how heavy the callback code here will
+ // be and if this code is buffered then this can
+ // lead to a performance regression.
+ $$rAF(function() {
+ forEach(callbacks, function(callback) {
+ callback(element, phase, data);
+ });
+ });
+ }
+ });
+ runner.progress(event, phase, data);
+ }
+
+ function close(reject) { // jshint ignore:line
+ clearGeneratedClasses(element, options);
+ applyAnimationClasses(element, options);
+ applyAnimationStyles(element, options);
+ options.domOperation();
+ runner.complete(!reject);
+ }
+ }
+
+ function closeChildAnimations(element) {
+ var node = getDomNode(element);
+ var children = node.querySelectorAll('[' + NG_ANIMATE_ATTR_NAME + ']');
+ forEach(children, function(child) {
+ var state = parseInt(child.getAttribute(NG_ANIMATE_ATTR_NAME));
+ var animationDetails = activeAnimationsLookup.get(child);
+ if (animationDetails) {
+ switch (state) {
+ case RUNNING_STATE:
+ animationDetails.runner.end();
+ /* falls through */
+ case PRE_DIGEST_STATE:
+ activeAnimationsLookup.remove(child);
+ break;
+ }
+ }
+ });
+ }
+
+ function clearElementAnimationState(element) {
+ var node = getDomNode(element);
+ node.removeAttribute(NG_ANIMATE_ATTR_NAME);
+ activeAnimationsLookup.remove(node);
+ }
+
+ function isMatchingElement(nodeOrElmA, nodeOrElmB) {
+ return getDomNode(nodeOrElmA) === getDomNode(nodeOrElmB);
+ }
+
+ /**
+ * This fn returns false if any of the following is true:
+ * a) animations on any parent element are disabled, and animations on the element aren't explicitly allowed
+ * b) a parent element has an ongoing structural animation, and animateChildren is false
+ * c) the element is not a child of the body
+ * d) the element is not a child of the $rootElement
+ */
+ function areAnimationsAllowed(element, parentElement, event) {
+ var bodyElement = jqLite($document[0].body);
+ var bodyElementDetected = isMatchingElement(element, bodyElement) || element[0].nodeName === 'HTML';
+ var rootElementDetected = isMatchingElement(element, $rootElement);
+ var parentAnimationDetected = false;
+ var animateChildren;
+ var elementDisabled = disabledElementsLookup.get(getDomNode(element));
+
+ var parentHost = element.data(NG_ANIMATE_PIN_DATA);
+ if (parentHost) {
+ parentElement = parentHost;
+ }
+
+ while (parentElement && parentElement.length) {
+ if (!rootElementDetected) {
+ // angular doesn't want to attempt to animate elements outside of the application
+ // therefore we need to ensure that the rootElement is an ancestor of the current element
+ rootElementDetected = isMatchingElement(parentElement, $rootElement);
+ }
+
+ var parentNode = parentElement[0];
+ if (parentNode.nodeType !== ELEMENT_NODE) {
+ // no point in inspecting the #document element
+ break;
+ }
+
+ var details = activeAnimationsLookup.get(parentNode) || {};
+ // either an enter, leave or move animation will commence
+ // therefore we can't allow any animations to take place
+ // but if a parent animation is class-based then that's ok
+ if (!parentAnimationDetected) {
+ var parentElementDisabled = disabledElementsLookup.get(parentNode);
+
+ if (parentElementDisabled === true && elementDisabled !== false) {
+ // disable animations if the user hasn't explicitly enabled animations on the
+ // current element
+ elementDisabled = true;
+ // element is disabled via parent element, no need to check anything else
+ break;
+ } else if (parentElementDisabled === false) {
+ elementDisabled = false;
+ }
+ parentAnimationDetected = details.structural;
+ }
+
+ if (isUndefined(animateChildren) || animateChildren === true) {
+ var value = parentElement.data(NG_ANIMATE_CHILDREN_DATA);
+ if (isDefined(value)) {
+ animateChildren = value;
+ }
+ }
+
+ // there is no need to continue traversing at this point
+ if (parentAnimationDetected && animateChildren === false) break;
+
+ if (!bodyElementDetected) {
+ // we also need to ensure that the element is or will be a part of the body element
+ // otherwise it is pointless to even issue an animation to be rendered
+ bodyElementDetected = isMatchingElement(parentElement, bodyElement);
+ }
+
+ if (bodyElementDetected && rootElementDetected) {
+ // If both body and root have been found, any other checks are pointless,
+ // as no animation data should live outside the application
+ break;
+ }
+
+ if (!rootElementDetected) {
+ // If no rootElement is detected, check if the parentElement is pinned to another element
+ parentHost = parentElement.data(NG_ANIMATE_PIN_DATA);
+ if (parentHost) {
+ // The pin target element becomes the next parent element
+ parentElement = parentHost;
+ continue;
+ }
+ }
+
+ parentElement = parentElement.parent();
+ }
+
+ var allowAnimation = (!parentAnimationDetected || animateChildren) && elementDisabled !== true;
+ return allowAnimation && rootElementDetected && bodyElementDetected;
+ }
+
+ function markElementAnimationState(element, state, details) {
+ details = details || {};
+ details.state = state;
+
+ var node = getDomNode(element);
+ node.setAttribute(NG_ANIMATE_ATTR_NAME, state);
+
+ var oldValue = activeAnimationsLookup.get(node);
+ var newValue = oldValue
+ ? extend(oldValue, details)
+ : details;
+ activeAnimationsLookup.put(node, newValue);
+ }
+ }];
+}];
+
+var $$AnimationProvider = ['$animateProvider', function($animateProvider) {
+ var NG_ANIMATE_REF_ATTR = 'ng-animate-ref';
+
+ var drivers = this.drivers = [];
+
+ var RUNNER_STORAGE_KEY = '$$animationRunner';
+
+ function setRunner(element, runner) {
+ element.data(RUNNER_STORAGE_KEY, runner);
+ }
+
+ function removeRunner(element) {
+ element.removeData(RUNNER_STORAGE_KEY);
+ }
+
+ function getRunner(element) {
+ return element.data(RUNNER_STORAGE_KEY);
+ }
+
+ this.$get = ['$$jqLite', '$rootScope', '$injector', '$$AnimateRunner', '$$HashMap', '$$rAFScheduler',
+ function($$jqLite, $rootScope, $injector, $$AnimateRunner, $$HashMap, $$rAFScheduler) {
+
+ var animationQueue = [];
+ var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
+
+ function sortAnimations(animations) {
+ var tree = { children: [] };
+ var i, lookup = new $$HashMap();
+
+ // this is done first beforehand so that the hashmap
+ // is filled with a list of the elements that will be animated
+ for (i = 0; i < animations.length; i++) {
+ var animation = animations[i];
+ lookup.put(animation.domNode, animations[i] = {
+ domNode: animation.domNode,
+ fn: animation.fn,
+ children: []
+ });
+ }
+
+ for (i = 0; i < animations.length; i++) {
+ processNode(animations[i]);
+ }
+
+ return flatten(tree);
+
+ function processNode(entry) {
+ if (entry.processed) return entry;
+ entry.processed = true;
+
+ var elementNode = entry.domNode;
+ var parentNode = elementNode.parentNode;
+ lookup.put(elementNode, entry);
+
+ var parentEntry;
+ while (parentNode) {
+ parentEntry = lookup.get(parentNode);
+ if (parentEntry) {
+ if (!parentEntry.processed) {
+ parentEntry = processNode(parentEntry);
+ }
+ break;
+ }
+ parentNode = parentNode.parentNode;
+ }
+
+ (parentEntry || tree).children.push(entry);
+ return entry;
+ }
+
+ function flatten(tree) {
+ var result = [];
+ var queue = [];
+ var i;
+
+ for (i = 0; i < tree.children.length; i++) {
+ queue.push(tree.children[i]);
+ }
+
+ var remainingLevelEntries = queue.length;
+ var nextLevelEntries = 0;
+ var row = [];
+
+ for (i = 0; i < queue.length; i++) {
+ var entry = queue[i];
+ if (remainingLevelEntries <= 0) {
+ remainingLevelEntries = nextLevelEntries;
+ nextLevelEntries = 0;
+ result.push(row);
+ row = [];
+ }
+ row.push(entry.fn);
+ entry.children.forEach(function(childEntry) {
+ nextLevelEntries++;
+ queue.push(childEntry);
+ });
+ remainingLevelEntries--;
+ }
+
+ if (row.length) {
+ result.push(row);
+ }
+
+ return result;
+ }
+ }
+
+ // TODO(matsko): document the signature in a better way
+ return function(element, event, options) {
+ options = prepareAnimationOptions(options);
+ var isStructural = ['enter', 'move', 'leave'].indexOf(event) >= 0;
+
+ // there is no animation at the current moment, however
+ // these runner methods will get later updated with the
+ // methods leading into the driver's end/cancel methods
+ // for now they just stop the animation from starting
+ var runner = new $$AnimateRunner({
+ end: function() { close(); },
+ cancel: function() { close(true); }
+ });
+
+ if (!drivers.length) {
+ close();
+ return runner;
+ }
+
+ setRunner(element, runner);
+
+ var classes = mergeClasses(element.attr('class'), mergeClasses(options.addClass, options.removeClass));
+ var tempClasses = options.tempClasses;
+ if (tempClasses) {
+ classes += ' ' + tempClasses;
+ options.tempClasses = null;
+ }
+
+ var prepareClassName;
+ if (isStructural) {
+ prepareClassName = 'ng-' + event + PREPARE_CLASS_SUFFIX;
+ $$jqLite.addClass(element, prepareClassName);
+ }
+
+ animationQueue.push({
+ // this data is used by the postDigest code and passed into
+ // the driver step function
+ element: element,
+ classes: classes,
+ event: event,
+ structural: isStructural,
+ options: options,
+ beforeStart: beforeStart,
+ close: close
+ });
+
+ element.on('$destroy', handleDestroyedElement);
+
+ // we only want there to be one function called within the post digest
+ // block. This way we can group animations for all the animations that
+ // were apart of the same postDigest flush call.
+ if (animationQueue.length > 1) return runner;
+
+ $rootScope.$$postDigest(function() {
+ var animations = [];
+ forEach(animationQueue, function(entry) {
+ // the element was destroyed early on which removed the runner
+ // form its storage. This means we can't animate this element
+ // at all and it already has been closed due to destruction.
+ if (getRunner(entry.element)) {
+ animations.push(entry);
+ } else {
+ entry.close();
+ }
+ });
+
+ // now any future animations will be in another postDigest
+ animationQueue.length = 0;
+
+ var groupedAnimations = groupAnimations(animations);
+ var toBeSortedAnimations = [];
+
+ forEach(groupedAnimations, function(animationEntry) {
+ toBeSortedAnimations.push({
+ domNode: getDomNode(animationEntry.from ? animationEntry.from.element : animationEntry.element),
+ fn: function triggerAnimationStart() {
+ // it's important that we apply the `ng-animate` CSS class and the
+ // temporary classes before we do any driver invoking since these
+ // CSS classes may be required for proper CSS detection.
+ animationEntry.beforeStart();
+
+ var startAnimationFn, closeFn = animationEntry.close;
+
+ // in the event that the element was removed before the digest runs or
+ // during the RAF sequencing then we should not trigger the animation.
+ var targetElement = animationEntry.anchors
+ ? (animationEntry.from.element || animationEntry.to.element)
+ : animationEntry.element;
+
+ if (getRunner(targetElement)) {
+ var operation = invokeFirstDriver(animationEntry);
+ if (operation) {
+ startAnimationFn = operation.start;
+ }
+ }
+
+ if (!startAnimationFn) {
+ closeFn();
+ } else {
+ var animationRunner = startAnimationFn();
+ animationRunner.done(function(status) {
+ closeFn(!status);
+ });
+ updateAnimationRunners(animationEntry, animationRunner);
+ }
+ }
+ });
+ });
+
+ // we need to sort each of the animations in order of parent to child
+ // relationships. This ensures that the child classes are applied at the
+ // right time.
+ $$rAFScheduler(sortAnimations(toBeSortedAnimations));
+ });
+
+ return runner;
+
+ // TODO(matsko): change to reference nodes
+ function getAnchorNodes(node) {
+ var SELECTOR = '[' + NG_ANIMATE_REF_ATTR + ']';
+ var items = node.hasAttribute(NG_ANIMATE_REF_ATTR)
+ ? [node]
+ : node.querySelectorAll(SELECTOR);
+ var anchors = [];
+ forEach(items, function(node) {
+ var attr = node.getAttribute(NG_ANIMATE_REF_ATTR);
+ if (attr && attr.length) {
+ anchors.push(node);
+ }
+ });
+ return anchors;
+ }
+
+ function groupAnimations(animations) {
+ var preparedAnimations = [];
+ var refLookup = {};
+ forEach(animations, function(animation, index) {
+ var element = animation.element;
+ var node = getDomNode(element);
+ var event = animation.event;
+ var enterOrMove = ['enter', 'move'].indexOf(event) >= 0;
+ var anchorNodes = animation.structural ? getAnchorNodes(node) : [];
+
+ if (anchorNodes.length) {
+ var direction = enterOrMove ? 'to' : 'from';
+
+ forEach(anchorNodes, function(anchor) {
+ var key = anchor.getAttribute(NG_ANIMATE_REF_ATTR);
+ refLookup[key] = refLookup[key] || {};
+ refLookup[key][direction] = {
+ animationID: index,
+ element: jqLite(anchor)
+ };
+ });
+ } else {
+ preparedAnimations.push(animation);
+ }
+ });
+
+ var usedIndicesLookup = {};
+ var anchorGroups = {};
+ forEach(refLookup, function(operations, key) {
+ var from = operations.from;
+ var to = operations.to;
+
+ if (!from || !to) {
+ // only one of these is set therefore we can't have an
+ // anchor animation since all three pieces are required
+ var index = from ? from.animationID : to.animationID;
+ var indexKey = index.toString();
+ if (!usedIndicesLookup[indexKey]) {
+ usedIndicesLookup[indexKey] = true;
+ preparedAnimations.push(animations[index]);
+ }
+ return;
+ }
+
+ var fromAnimation = animations[from.animationID];
+ var toAnimation = animations[to.animationID];
+ var lookupKey = from.animationID.toString();
+ if (!anchorGroups[lookupKey]) {
+ var group = anchorGroups[lookupKey] = {
+ structural: true,
+ beforeStart: function() {
+ fromAnimation.beforeStart();
+ toAnimation.beforeStart();
+ },
+ close: function() {
+ fromAnimation.close();
+ toAnimation.close();
+ },
+ classes: cssClassesIntersection(fromAnimation.classes, toAnimation.classes),
+ from: fromAnimation,
+ to: toAnimation,
+ anchors: [] // TODO(matsko): change to reference nodes
+ };
+
+ // the anchor animations require that the from and to elements both have at least
+ // one shared CSS class which effectively marries the two elements together to use
+ // the same animation driver and to properly sequence the anchor animation.
+ if (group.classes.length) {
+ preparedAnimations.push(group);
+ } else {
+ preparedAnimations.push(fromAnimation);
+ preparedAnimations.push(toAnimation);
+ }
+ }
+
+ anchorGroups[lookupKey].anchors.push({
+ 'out': from.element, 'in': to.element
+ });
+ });
+
+ return preparedAnimations;
+ }
+
+ function cssClassesIntersection(a,b) {
+ a = a.split(' ');
+ b = b.split(' ');
+ var matches = [];
+
+ for (var i = 0; i < a.length; i++) {
+ var aa = a[i];
+ if (aa.substring(0,3) === 'ng-') continue;
+
+ for (var j = 0; j < b.length; j++) {
+ if (aa === b[j]) {
+ matches.push(aa);
+ break;
+ }
+ }
+ }
+
+ return matches.join(' ');
+ }
+
+ function invokeFirstDriver(animationDetails) {
+ // we loop in reverse order since the more general drivers (like CSS and JS)
+ // may attempt more elements, but custom drivers are more particular
+ for (var i = drivers.length - 1; i >= 0; i--) {
+ var driverName = drivers[i];
+ if (!$injector.has(driverName)) continue; // TODO(matsko): remove this check
+
+ var factory = $injector.get(driverName);
+ var driver = factory(animationDetails);
+ if (driver) {
+ return driver;
+ }
+ }
+ }
+
+ function beforeStart() {
+ element.addClass(NG_ANIMATE_CLASSNAME);
+ if (tempClasses) {
+ $$jqLite.addClass(element, tempClasses);
+ }
+ if (prepareClassName) {
+ $$jqLite.removeClass(element, prepareClassName);
+ prepareClassName = null;
+ }
+ }
+
+ function updateAnimationRunners(animation, newRunner) {
+ if (animation.from && animation.to) {
+ update(animation.from.element);
+ update(animation.to.element);
+ } else {
+ update(animation.element);
+ }
+
+ function update(element) {
+ getRunner(element).setHost(newRunner);
+ }
+ }
+
+ function handleDestroyedElement() {
+ var runner = getRunner(element);
+ if (runner && (event !== 'leave' || !options.$$domOperationFired)) {
+ runner.end();
+ }
+ }
+
+ function close(rejected) { // jshint ignore:line
+ element.off('$destroy', handleDestroyedElement);
+ removeRunner(element);
+
+ applyAnimationClasses(element, options);
+ applyAnimationStyles(element, options);
+ options.domOperation();
+
+ if (tempClasses) {
+ $$jqLite.removeClass(element, tempClasses);
+ }
+
+ element.removeClass(NG_ANIMATE_CLASSNAME);
+ runner.complete(!rejected);
+ }
+ };
+ }];
+}];
+
+/**
+ * @ngdoc directive
+ * @name ngAnimateSwap
+ * @restrict A
+ * @scope
+ *
+ * @description
+ *
+ * ngAnimateSwap is a animation-oriented directive that allows for the container to
+ * be removed and entered in whenever the associated expression changes. A
+ * common usecase for this directive is a rotating banner component which
+ * contains one image being present at a time. When the active image changes
+ * then the old image will perform a `leave` animation and the new element
+ * will be inserted via an `enter` animation.
+ *
+ * @example
+ *
+ *
+ *
+ *
+ * {{ number }}
+ *
+ *
+ *
+ *
+ * angular.module('ngAnimateSwapExample', ['ngAnimate'])
+ * .controller('AppCtrl', ['$scope', '$interval', function($scope, $interval) {
+ * $scope.number = 0;
+ * $interval(function() {
+ * $scope.number++;
+ * }, 1000);
+ *
+ * var colors = ['red','blue','green','yellow','orange'];
+ * $scope.colorClass = function(number) {
+ * return colors[number % colors.length];
+ * };
+ * }]);
+ *
+ *
+ * .container {
+ * height:250px;
+ * width:250px;
+ * position:relative;
+ * overflow:hidden;
+ * border:2px solid black;
+ * }
+ * .container .cell {
+ * font-size:150px;
+ * text-align:center;
+ * line-height:250px;
+ * position:absolute;
+ * top:0;
+ * left:0;
+ * right:0;
+ * border-bottom:2px solid black;
+ * }
+ * .swap-animation.ng-enter, .swap-animation.ng-leave {
+ * transition:0.5s linear all;
+ * }
+ * .swap-animation.ng-enter {
+ * top:-250px;
+ * }
+ * .swap-animation.ng-enter-active {
+ * top:0px;
+ * }
+ * .swap-animation.ng-leave {
+ * top:0px;
+ * }
+ * .swap-animation.ng-leave-active {
+ * top:250px;
+ * }
+ * .red { background:red; }
+ * .green { background:green; }
+ * .blue { background:blue; }
+ * .yellow { background:yellow; }
+ * .orange { background:orange; }
+ *
+ *
+ */
+var ngAnimateSwapDirective = ['$animate', '$rootScope', function($animate, $rootScope) {
+ return {
+ restrict: 'A',
+ transclude: 'element',
+ terminal: true,
+ priority: 600, // we use 600 here to ensure that the directive is caught before others
+ link: function(scope, $element, attrs, ctrl, $transclude) {
+ var previousElement, previousScope;
+ scope.$watchCollection(attrs.ngAnimateSwap || attrs['for'], function(value) {
+ if (previousElement) {
+ $animate.leave(previousElement);
+ }
+ if (previousScope) {
+ previousScope.$destroy();
+ previousScope = null;
+ }
+ if (value || value === 0) {
+ previousScope = scope.$new();
+ $transclude(previousScope, function(element) {
+ previousElement = element;
+ $animate.enter(element, null, $element);
+ });
+ }
+ });
+ }
+ };
+}];
+
+/* global angularAnimateModule: true,
+
+ ngAnimateSwapDirective,
+ $$AnimateAsyncRunFactory,
+ $$rAFSchedulerFactory,
+ $$AnimateChildrenDirective,
+ $$AnimateQueueProvider,
+ $$AnimationProvider,
+ $AnimateCssProvider,
+ $$AnimateCssDriverProvider,
+ $$AnimateJsProvider,
+ $$AnimateJsDriverProvider,
+*/
+
+/**
+ * @ngdoc module
+ * @name ngAnimate
+ * @description
+ *
+ * The `ngAnimate` module provides support for CSS-based animations (keyframes and transitions) as well as JavaScript-based animations via
+ * callback hooks. Animations are not enabled by default, however, by including `ngAnimate` the animation hooks are enabled for an Angular app.
+ *
+ *
+ *
+ * # Usage
+ * Simply put, there are two ways to make use of animations when ngAnimate is used: by using **CSS** and **JavaScript**. The former works purely based
+ * using CSS (by using matching CSS selectors/styles) and the latter triggers animations that are registered via `module.animation()`. For
+ * both CSS and JS animations the sole requirement is to have a matching `CSS class` that exists both in the registered animation and within
+ * the HTML element that the animation will be triggered on.
+ *
+ * ## Directive Support
+ * The following directives are "animation aware":
+ *
+ * | Directive | Supported Animations |
+ * |----------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------|
+ * | {@link ng.directive:ngRepeat#animations ngRepeat} | enter, leave and move |
+ * | {@link ngRoute.directive:ngView#animations ngView} | enter and leave |
+ * | {@link ng.directive:ngInclude#animations ngInclude} | enter and leave |
+ * | {@link ng.directive:ngSwitch#animations ngSwitch} | enter and leave |
+ * | {@link ng.directive:ngIf#animations ngIf} | enter and leave |
+ * | {@link ng.directive:ngClass#animations ngClass} | add and remove (the CSS class(es) present) |
+ * | {@link ng.directive:ngShow#animations ngShow} & {@link ng.directive:ngHide#animations ngHide} | add and remove (the ng-hide class value) |
+ * | {@link ng.directive:form#animation-hooks form} & {@link ng.directive:ngModel#animation-hooks ngModel} | add and remove (dirty, pristine, valid, invalid & all other validations) |
+ * | {@link module:ngMessages#animations ngMessages} | add and remove (ng-active & ng-inactive) |
+ * | {@link module:ngMessages#animations ngMessage} | enter and leave |
+ *
+ * (More information can be found by visiting each the documentation associated with each directive.)
+ *
+ * ## CSS-based Animations
+ *
+ * CSS-based animations with ngAnimate are unique since they require no JavaScript code at all. By using a CSS class that we reference between our HTML
+ * and CSS code we can create an animation that will be picked up by Angular when an the underlying directive performs an operation.
+ *
+ * The example below shows how an `enter` animation can be made possible on an element using `ng-if`:
+ *
+ * ```html
+ *
+ * Fade me in out
+ *
+ *
+ *
+ * ```
+ *
+ * Notice the CSS class **fade**? We can now create the CSS transition code that references this class:
+ *
+ * ```css
+ * /* The starting CSS styles for the enter animation */
+ * .fade.ng-enter {
+ * transition:0.5s linear all;
+ * opacity:0;
+ * }
+ *
+ * /* The finishing CSS styles for the enter animation */
+ * .fade.ng-enter.ng-enter-active {
+ * opacity:1;
+ * }
+ * ```
+ *
+ * The key thing to remember here is that, depending on the animation event (which each of the directives above trigger depending on what's going on) two
+ * generated CSS classes will be applied to the element; in the example above we have `.ng-enter` and `.ng-enter-active`. For CSS transitions, the transition
+ * code **must** be defined within the starting CSS class (in this case `.ng-enter`). The destination class is what the transition will animate towards.
+ *
+ * If for example we wanted to create animations for `leave` and `move` (ngRepeat triggers move) then we can do so using the same CSS naming conventions:
+ *
+ * ```css
+ * /* now the element will fade out before it is removed from the DOM */
+ * .fade.ng-leave {
+ * transition:0.5s linear all;
+ * opacity:1;
+ * }
+ * .fade.ng-leave.ng-leave-active {
+ * opacity:0;
+ * }
+ * ```
+ *
+ * We can also make use of **CSS Keyframes** by referencing the keyframe animation within the starting CSS class:
+ *
+ * ```css
+ * /* there is no need to define anything inside of the destination
+ * CSS class since the keyframe will take charge of the animation */
+ * .fade.ng-leave {
+ * animation: my_fade_animation 0.5s linear;
+ * -webkit-animation: my_fade_animation 0.5s linear;
+ * }
+ *
+ * @keyframes my_fade_animation {
+ * from { opacity:1; }
+ * to { opacity:0; }
+ * }
+ *
+ * @-webkit-keyframes my_fade_animation {
+ * from { opacity:1; }
+ * to { opacity:0; }
+ * }
+ * ```
+ *
+ * Feel free also mix transitions and keyframes together as well as any other CSS classes on the same element.
+ *
+ * ### CSS Class-based Animations
+ *
+ * Class-based animations (animations that are triggered via `ngClass`, `ngShow`, `ngHide` and some other directives) have a slightly different
+ * naming convention. Class-based animations are basic enough that a standard transition or keyframe can be referenced on the class being added
+ * and removed.
+ *
+ * For example if we wanted to do a CSS animation for `ngHide` then we place an animation on the `.ng-hide` CSS class:
+ *
+ * ```html
+ *
+ * Show and hide me
+ *
+ *
+ *
+ *
+ * ```
+ *
+ * All that is going on here with ngShow/ngHide behind the scenes is the `.ng-hide` class is added/removed (when the hidden state is valid). Since
+ * ngShow and ngHide are animation aware then we can match up a transition and ngAnimate handles the rest.
+ *
+ * In addition the addition and removal of the CSS class, ngAnimate also provides two helper methods that we can use to further decorate the animation
+ * with CSS styles.
+ *
+ * ```html
+ *
+ * Highlight this box
+ *
+ *
+ *
+ *
+ * ```
+ *
+ * We can also make use of CSS keyframes by placing them within the CSS classes.
+ *
+ *
+ * ### CSS Staggering Animations
+ * A Staggering animation is a collection of animations that are issued with a slight delay in between each successive operation resulting in a
+ * curtain-like effect. The ngAnimate module (versions >=1.2) supports staggering animations and the stagger effect can be
+ * performed by creating a **ng-EVENT-stagger** CSS class and attaching that class to the base CSS class used for
+ * the animation. The style property expected within the stagger class can either be a **transition-delay** or an
+ * **animation-delay** property (or both if your animation contains both transitions and keyframe animations).
+ *
+ * ```css
+ * .my-animation.ng-enter {
+ * /* standard transition code */
+ * transition: 1s linear all;
+ * opacity:0;
+ * }
+ * .my-animation.ng-enter-stagger {
+ * /* this will have a 100ms delay between each successive leave animation */
+ * transition-delay: 0.1s;
+ *
+ * /* As of 1.4.4, this must always be set: it signals ngAnimate
+ * to not accidentally inherit a delay property from another CSS class */
+ * transition-duration: 0s;
+ * }
+ * .my-animation.ng-enter.ng-enter-active {
+ * /* standard transition styles */
+ * opacity:1;
+ * }
+ * ```
+ *
+ * Staggering animations work by default in ngRepeat (so long as the CSS class is defined). Outside of ngRepeat, to use staggering animations
+ * on your own, they can be triggered by firing multiple calls to the same event on $animate. However, the restrictions surrounding this
+ * are that each of the elements must have the same CSS className value as well as the same parent element. A stagger operation
+ * will also be reset if one or more animation frames have passed since the multiple calls to `$animate` were fired.
+ *
+ * The following code will issue the **ng-leave-stagger** event on the element provided:
+ *
+ * ```js
+ * var kids = parent.children();
+ *
+ * $animate.leave(kids[0]); //stagger index=0
+ * $animate.leave(kids[1]); //stagger index=1
+ * $animate.leave(kids[2]); //stagger index=2
+ * $animate.leave(kids[3]); //stagger index=3
+ * $animate.leave(kids[4]); //stagger index=4
+ *
+ * window.requestAnimationFrame(function() {
+ * //stagger has reset itself
+ * $animate.leave(kids[5]); //stagger index=0
+ * $animate.leave(kids[6]); //stagger index=1
+ *
+ * $scope.$digest();
+ * });
+ * ```
+ *
+ * Stagger animations are currently only supported within CSS-defined animations.
+ *
+ * ### The `ng-animate` CSS class
+ *
+ * When ngAnimate is animating an element it will apply the `ng-animate` CSS class to the element for the duration of the animation.
+ * This is a temporary CSS class and it will be removed once the animation is over (for both JavaScript and CSS-based animations).
+ *
+ * Therefore, animations can be applied to an element using this temporary class directly via CSS.
+ *
+ * ```css
+ * .zipper.ng-animate {
+ * transition:0.5s linear all;
+ * }
+ * .zipper.ng-enter {
+ * opacity:0;
+ * }
+ * .zipper.ng-enter.ng-enter-active {
+ * opacity:1;
+ * }
+ * .zipper.ng-leave {
+ * opacity:1;
+ * }
+ * .zipper.ng-leave.ng-leave-active {
+ * opacity:0;
+ * }
+ * ```
+ *
+ * (Note that the `ng-animate` CSS class is reserved and it cannot be applied on an element directly since ngAnimate will always remove
+ * the CSS class once an animation has completed.)
+ *
+ *
+ * ### The `ng-[event]-prepare` class
+ *
+ * This is a special class that can be used to prevent unwanted flickering / flash of content before
+ * the actual animation starts. The class is added as soon as an animation is initialized, but removed
+ * before the actual animation starts (after waiting for a $digest).
+ * It is also only added for *structural* animations (`enter`, `move`, and `leave`).
+ *
+ * In practice, flickering can appear when nesting elements with structural animations such as `ngIf`
+ * into elements that have class-based animations such as `ngClass`.
+ *
+ * ```html
+ *
+ *
+ *
+ *
+ *
+ * ```
+ *
+ * It is possible that during the `enter` animation, the `.message` div will be briefly visible before it starts animating.
+ * In that case, you can add styles to the CSS that make sure the element stays hidden before the animation starts:
+ *
+ * ```css
+ * .message.ng-enter-prepare {
+ * opacity: 0;
+ * }
+ *
+ * ```
+ *
+ * ## JavaScript-based Animations
+ *
+ * ngAnimate also allows for animations to be consumed by JavaScript code. The approach is similar to CSS-based animations (where there is a shared
+ * CSS class that is referenced in our HTML code) but in addition we need to register the JavaScript animation on the module. By making use of the
+ * `module.animation()` module function we can register the animation.
+ *
+ * Let's see an example of a enter/leave animation using `ngRepeat`:
+ *
+ * ```html
+ *
+ * {{ item }}
+ *
+ * ```
+ *
+ * See the **slide** CSS class? Let's use that class to define an animation that we'll structure in our module code by using `module.animation`:
+ *
+ * ```js
+ * myModule.animation('.slide', [function() {
+ * return {
+ * // make note that other events (like addClass/removeClass)
+ * // have different function input parameters
+ * enter: function(element, doneFn) {
+ * jQuery(element).fadeIn(1000, doneFn);
+ *
+ * // remember to call doneFn so that angular
+ * // knows that the animation has concluded
+ * },
+ *
+ * move: function(element, doneFn) {
+ * jQuery(element).fadeIn(1000, doneFn);
+ * },
+ *
+ * leave: function(element, doneFn) {
+ * jQuery(element).fadeOut(1000, doneFn);
+ * }
+ * }
+ * }]);
+ * ```
+ *
+ * The nice thing about JS-based animations is that we can inject other services and make use of advanced animation libraries such as
+ * greensock.js and velocity.js.
+ *
+ * If our animation code class-based (meaning that something like `ngClass`, `ngHide` and `ngShow` triggers it) then we can still define
+ * our animations inside of the same registered animation, however, the function input arguments are a bit different:
+ *
+ * ```html
+ *
+ * this box is moody
+ *
+ *
+ *
+ *
+ * ```
+ *
+ * ```js
+ * myModule.animation('.colorful', [function() {
+ * return {
+ * addClass: function(element, className, doneFn) {
+ * // do some cool animation and call the doneFn
+ * },
+ * removeClass: function(element, className, doneFn) {
+ * // do some cool animation and call the doneFn
+ * },
+ * setClass: function(element, addedClass, removedClass, doneFn) {
+ * // do some cool animation and call the doneFn
+ * }
+ * }
+ * }]);
+ * ```
+ *
+ * ## CSS + JS Animations Together
+ *
+ * AngularJS 1.4 and higher has taken steps to make the amalgamation of CSS and JS animations more flexible. However, unlike earlier versions of Angular,
+ * defining CSS and JS animations to work off of the same CSS class will not work anymore. Therefore the example below will only result in **JS animations taking
+ * charge of the animation**:
+ *
+ * ```html
+ *
+ * Slide in and out
+ *
+ * ```
+ *
+ * ```js
+ * myModule.animation('.slide', [function() {
+ * return {
+ * enter: function(element, doneFn) {
+ * jQuery(element).slideIn(1000, doneFn);
+ * }
+ * }
+ * }]);
+ * ```
+ *
+ * ```css
+ * .slide.ng-enter {
+ * transition:0.5s linear all;
+ * transform:translateY(-100px);
+ * }
+ * .slide.ng-enter.ng-enter-active {
+ * transform:translateY(0);
+ * }
+ * ```
+ *
+ * Does this mean that CSS and JS animations cannot be used together? Do JS-based animations always have higher priority? We can make up for the
+ * lack of CSS animations by using the `$animateCss` service to trigger our own tweaked-out, CSS-based animations directly from
+ * our own JS-based animation code:
+ *
+ * ```js
+ * myModule.animation('.slide', ['$animateCss', function($animateCss) {
+ * return {
+ * enter: function(element) {
+* // this will trigger `.slide.ng-enter` and `.slide.ng-enter-active`.
+ * return $animateCss(element, {
+ * event: 'enter',
+ * structural: true
+ * });
+ * }
+ * }
+ * }]);
+ * ```
+ *
+ * The nice thing here is that we can save bandwidth by sticking to our CSS-based animation code and we don't need to rely on a 3rd-party animation framework.
+ *
+ * The `$animateCss` service is very powerful since we can feed in all kinds of extra properties that will be evaluated and fed into a CSS transition or
+ * keyframe animation. For example if we wanted to animate the height of an element while adding and removing classes then we can do so by providing that
+ * data into `$animateCss` directly:
+ *
+ * ```js
+ * myModule.animation('.slide', ['$animateCss', function($animateCss) {
+ * return {
+ * enter: function(element) {
+ * return $animateCss(element, {
+ * event: 'enter',
+ * structural: true,
+ * addClass: 'maroon-setting',
+ * from: { height:0 },
+ * to: { height: 200 }
+ * });
+ * }
+ * }
+ * }]);
+ * ```
+ *
+ * Now we can fill in the rest via our transition CSS code:
+ *
+ * ```css
+ * /* the transition tells ngAnimate to make the animation happen */
+ * .slide.ng-enter { transition:0.5s linear all; }
+ *
+ * /* this extra CSS class will be absorbed into the transition
+ * since the $animateCss code is adding the class */
+ * .maroon-setting { background:red; }
+ * ```
+ *
+ * And `$animateCss` will figure out the rest. Just make sure to have the `done()` callback fire the `doneFn` function to signal when the animation is over.
+ *
+ * To learn more about what's possible be sure to visit the {@link ngAnimate.$animateCss $animateCss service}.
+ *
+ * ## Animation Anchoring (via `ng-animate-ref`)
+ *
+ * ngAnimate in AngularJS 1.4 comes packed with the ability to cross-animate elements between
+ * structural areas of an application (like views) by pairing up elements using an attribute
+ * called `ng-animate-ref`.
+ *
+ * Let's say for example we have two views that are managed by `ng-view` and we want to show
+ * that there is a relationship between two components situated in within these views. By using the
+ * `ng-animate-ref` attribute we can identify that the two components are paired together and we
+ * can then attach an animation, which is triggered when the view changes.
+ *
+ * Say for example we have the following template code:
+ *
+ * ```html
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ * ```
+ *
+ * Now, when the view changes (once the link is clicked), ngAnimate will examine the
+ * HTML contents to see if there is a match reference between any components in the view
+ * that is leaving and the view that is entering. It will scan both the view which is being
+ * removed (leave) and inserted (enter) to see if there are any paired DOM elements that
+ * contain a matching ref value.
+ *
+ * The two images match since they share the same ref value. ngAnimate will now create a
+ * transport element (which is a clone of the first image element) and it will then attempt
+ * to animate to the position of the second image element in the next view. For the animation to
+ * work a special CSS class called `ng-anchor` will be added to the transported element.
+ *
+ * We can now attach a transition onto the `.banner.ng-anchor` CSS class and then
+ * ngAnimate will handle the entire transition for us as well as the addition and removal of
+ * any changes of CSS classes between the elements:
+ *
+ * ```css
+ * .banner.ng-anchor {
+ * /* this animation will last for 1 second since there are
+ * two phases to the animation (an `in` and an `out` phase) */
+ * transition:0.5s linear all;
+ * }
+ * ```
+ *
+ * We also **must** include animations for the views that are being entered and removed
+ * (otherwise anchoring wouldn't be possible since the new view would be inserted right away).
+ *
+ * ```css
+ * .view-animation.ng-enter, .view-animation.ng-leave {
+ * transition:0.5s linear all;
+ * position:fixed;
+ * left:0;
+ * top:0;
+ * width:100%;
+ * }
+ * .view-animation.ng-enter {
+ * transform:translateX(100%);
+ * }
+ * .view-animation.ng-leave,
+ * .view-animation.ng-enter.ng-enter-active {
+ * transform:translateX(0%);
+ * }
+ * .view-animation.ng-leave.ng-leave-active {
+ * transform:translateX(-100%);
+ * }
+ * ```
+ *
+ * Now we can jump back to the anchor animation. When the animation happens, there are two stages that occur:
+ * an `out` and an `in` stage. The `out` stage happens first and that is when the element is animated away
+ * from its origin. Once that animation is over then the `in` stage occurs which animates the
+ * element to its destination. The reason why there are two animations is to give enough time
+ * for the enter animation on the new element to be ready.
+ *
+ * The example above sets up a transition for both the in and out phases, but we can also target the out or
+ * in phases directly via `ng-anchor-out` and `ng-anchor-in`.
+ *
+ * ```css
+ * .banner.ng-anchor-out {
+ * transition: 0.5s linear all;
+ *
+ * /* the scale will be applied during the out animation,
+ * but will be animated away when the in animation runs */
+ * transform: scale(1.2);
+ * }
+ *
+ * .banner.ng-anchor-in {
+ * transition: 1s linear all;
+ * }
+ * ```
+ *
+ *
+ *
+ *
+ * ### Anchoring Demo
+ *
+
+
+ Home
+
+
+
+
+ .record {
+ display:block;
+ font-size:20px;
+ }
+ .profile {
+ background:black;
+ color:white;
+ font-size:100px;
+ }
+ .view-container {
+ position:relative;
+ }
+ .view-container > .view.ng-animate {
+ position:absolute;
+ top:0;
+ left:0;
+ width:100%;
+ min-height:500px;
+ }
+ .view.ng-enter, .view.ng-leave,
+ .record.ng-anchor {
+ transition:0.5s linear all;
+ }
+ .view.ng-enter {
+ transform:translateX(100%);
+ }
+ .view.ng-enter.ng-enter-active, .view.ng-leave {
+ transform:translateX(0%);
+ }
+ .view.ng-leave.ng-leave-active {
+ transform:translateX(-100%);
+ }
+ .record.ng-anchor-out {
+ background:red;
+ }
+
+
+ *
+ * ### How is the element transported?
+ *
+ * When an anchor animation occurs, ngAnimate will clone the starting element and position it exactly where the starting
+ * element is located on screen via absolute positioning. The cloned element will be placed inside of the root element
+ * of the application (where ng-app was defined) and all of the CSS classes of the starting element will be applied. The
+ * element will then animate into the `out` and `in` animations and will eventually reach the coordinates and match
+ * the dimensions of the destination element. During the entire animation a CSS class of `.ng-animate-shim` will be applied
+ * to both the starting and destination elements in order to hide them from being visible (the CSS styling for the class
+ * is: `visibility:hidden`). Once the anchor reaches its destination then it will be removed and the destination element
+ * will become visible since the shim class will be removed.
+ *
+ * ### How is the morphing handled?
+ *
+ * CSS Anchoring relies on transitions and keyframes and the internal code is intelligent enough to figure out
+ * what CSS classes differ between the starting element and the destination element. These different CSS classes
+ * will be added/removed on the anchor element and a transition will be applied (the transition that is provided
+ * in the anchor class). Long story short, ngAnimate will figure out what classes to add and remove which will
+ * make the transition of the element as smooth and automatic as possible. Be sure to use simple CSS classes that
+ * do not rely on DOM nesting structure so that the anchor element appears the same as the starting element (since
+ * the cloned element is placed inside of root element which is likely close to the body element).
+ *
+ * Note that if the root element is on the `` element then the cloned node will be placed inside of body.
+ *
+ *
+ * ## Using $animate in your directive code
+ *
+ * So far we've explored how to feed in animations into an Angular application, but how do we trigger animations within our own directives in our application?
+ * By injecting the `$animate` service into our directive code, we can trigger structural and class-based hooks which can then be consumed by animations. Let's
+ * imagine we have a greeting box that shows and hides itself when the data changes
+ *
+ * ```html
+ * Hi there
+ * ```
+ *
+ * ```js
+ * ngModule.directive('greetingBox', ['$animate', function($animate) {
+ * return function(scope, element, attrs) {
+ * attrs.$observe('active', function(value) {
+ * value ? $animate.addClass(element, 'on') : $animate.removeClass(element, 'on');
+ * });
+ * });
+ * }]);
+ * ```
+ *
+ * Now the `on` CSS class is added and removed on the greeting box component. Now if we add a CSS class on top of the greeting box element
+ * in our HTML code then we can trigger a CSS or JS animation to happen.
+ *
+ * ```css
+ * /* normally we would create a CSS class to reference on the element */
+ * greeting-box.on { transition:0.5s linear all; background:green; color:white; }
+ * ```
+ *
+ * The `$animate` service contains a variety of other methods like `enter`, `leave`, `animate` and `setClass`. To learn more about what's
+ * possible be sure to visit the {@link ng.$animate $animate service API page}.
+ *
+ *
+ * ### Preventing Collisions With Third Party Libraries
+ *
+ * Some third-party frameworks place animation duration defaults across many element or className
+ * selectors in order to make their code small and reuseable. This can lead to issues with ngAnimate, which
+ * is expecting actual animations on these elements and has to wait for their completion.
+ *
+ * You can prevent this unwanted behavior by using a prefix on all your animation classes:
+ *
+ * ```css
+ * /* prefixed with animate- */
+ * .animate-fade-add.animate-fade-add-active {
+ * transition:1s linear all;
+ * opacity:0;
+ * }
+ * ```
+ *
+ * You then configure `$animate` to enforce this prefix:
+ *
+ * ```js
+ * $animateProvider.classNameFilter(/animate-/);
+ * ```
+ *
+ * This also may provide your application with a speed boost since only specific elements containing CSS class prefix
+ * will be evaluated for animation when any DOM changes occur in the application.
+ *
+ * ## Callbacks and Promises
+ *
+ * When `$animate` is called it returns a promise that can be used to capture when the animation has ended. Therefore if we were to trigger
+ * an animation (within our directive code) then we can continue performing directive and scope related activities after the animation has
+ * ended by chaining onto the returned promise that animation method returns.
+ *
+ * ```js
+ * // somewhere within the depths of the directive
+ * $animate.enter(element, parent).then(function() {
+ * //the animation has completed
+ * });
+ * ```
+ *
+ * (Note that earlier versions of Angular prior to v1.4 required the promise code to be wrapped using `$scope.$apply(...)`. This is not the case
+ * anymore.)
+ *
+ * In addition to the animation promise, we can also make use of animation-related callbacks within our directives and controller code by registering
+ * an event listener using the `$animate` service. Let's say for example that an animation was triggered on our view
+ * routing controller to hook into that:
+ *
+ * ```js
+ * ngModule.controller('HomePageController', ['$animate', function($animate) {
+ * $animate.on('enter', ngViewElement, function(element) {
+ * // the animation for this route has completed
+ * }]);
+ * }])
+ * ```
+ *
+ * (Note that you will need to trigger a digest within the callback to get angular to notice any scope-related changes.)
+ */
+
+/**
+ * @ngdoc service
+ * @name $animate
+ * @kind object
+ *
+ * @description
+ * The ngAnimate `$animate` service documentation is the same for the core `$animate` service.
+ *
+ * Click here {@link ng.$animate to learn more about animations with `$animate`}.
+ */
+angular.module('ngAnimate', [])
+ .directive('ngAnimateSwap', ngAnimateSwapDirective)
+
+ .directive('ngAnimateChildren', $$AnimateChildrenDirective)
+ .factory('$$rAFScheduler', $$rAFSchedulerFactory)
+
+ .provider('$$animateQueue', $$AnimateQueueProvider)
+ .provider('$$animation', $$AnimationProvider)
+
+ .provider('$animateCss', $AnimateCssProvider)
+ .provider('$$animateCssDriver', $$AnimateCssDriverProvider)
+
+ .provider('$$animateJs', $$AnimateJsProvider)
+ .provider('$$animateJsDriver', $$AnimateJsDriverProvider);
+
+
+})(window, window.angular);
diff --git a/LLV/scripts/angular-animate.min.js b/LLV/scripts/angular-animate.min.js
new file mode 100644
index 0000000..8e8e41d
--- /dev/null
+++ b/LLV/scripts/angular-animate.min.js
@@ -0,0 +1,56 @@
+/*
+ AngularJS v1.5.0
+ (c) 2010-2016 Google, Inc. http://angularjs.org
+ License: MIT
+*/
+(function(D,r,Va){'use strict';function ya(a,b,c){if(!a)throw Ka("areq",b||"?",c||"required");return a}function za(a,b){if(!a&&!b)return"";if(!a)return b;if(!b)return a;ba(a)&&(a=a.join(" "));ba(b)&&(b=b.join(" "));return a+" "+b}function La(a){var b={};a&&(a.to||a.from)&&(b.to=a.to,b.from=a.from);return b}function X(a,b,c){var d="";a=ba(a)?a:a&&R(a)&&a.length?a.split(/\s+/):[];s(a,function(a,g){a&&0=a&&(a=e,e=0,b.push(t),t=[]);t.push(g.fn);g.children.forEach(function(a){e++;
+c.push(a)});a--}t.length&&b.push(t);return b}(c)}var M=[],r=U(a);return function(u,A,v){function z(a){a=a.hasAttribute("ng-animate-ref")?[a]:a.querySelectorAll("[ng-animate-ref]");var b=[];s(a,function(a){var c=a.getAttribute("ng-animate-ref");c&&c.length&&b.push(a)});return b}function K(a){var b=[],c={};s(a,function(a,f){var d=G(a.element),h=0<=["enter","move"].indexOf(a.event),d=a.structural?z(d):[];if(d.length){var e=h?"to":"from";s(d,function(a){var b=a.getAttribute("ng-animate-ref");c[b]=c[b]||
+{};c[b][e]={animationID:f,element:I(a)}})}else b.push(a)});var d={},h={};s(c,function(c,e){var l=c.from,t=c.to;if(l&&t){var g=a[l.animationID],E=a[t.animationID],k=l.animationID.toString();if(!h[k]){var z=h[k]={structural:!0,beforeStart:function(){g.beforeStart();E.beforeStart()},close:function(){g.close();E.close()},classes:J(g.classes,E.classes),from:g,to:E,anchors:[]};z.classes.length?b.push(z):(b.push(g),b.push(E))}h[k].anchors.push({out:l.element,"in":t.element})}else l=l?l.animationID:t.animationID,
+t=l.toString(),d[t]||(d[t]=!0,b.push(a[l]))});return b}function J(a,b){a=a.split(" ");b=b.split(" ");for(var c=[],d=0;d=P&&b>=O&&(wa=!0,q())}function L(){function b(){if(!A){t(!1);s(m,
+function(a){l.style[a[0]]=a[1]});z(a,f);e.addClass(a,ca);if(p.recalculateTimingStyles){ja=l.className+" "+da;ga=r(l,ja);F=v(l,ja,ga);$=F.maxDelay;n=Math.max($,0);O=F.maxDuration;if(0===O){q();return}p.hasTransitions=0B.expectedEndTime)?H.cancel(B.timer):g.push(q)}L&&(k=H(c,k,!1),g[0]={timer:k,expectedEndTime:d},g.push(q),a.data("$$animateCss",g));if(ea.length)a.on(ea.join(" "),E);f.to&&(f.cleanupStyles&&Ga(x,l,Object.keys(f.to)),Ba(a,
+f))}}function c(){var b=a.data("$$animateCss");if(b){for(var d=1;d scopeB;
+ } else {
+ return scopeA.length > scopeB.length;
+ }
+}
+
+function parseStateRef(ref) {
+ var parsed = ref.replace(/\n/g, " ").match(/^([^(]+?)\s*(\((.*)\))?$/);
+ if (!parsed || parsed.length !== 4) { throw new Error("Invalid state ref '" + ref + "'"); }
+ return { state: parsed[1], paramExpr: parsed[3] || null };
+}
+
+function $Breadcrumb() {
+
+ var $$options = {
+ prefixStateName: null,
+ template: 'bootstrap3',
+ templateUrl: null,
+ includeAbstract : false
+ };
+
+ this.setOptions = function(options) {
+ angular.extend($$options, options);
+ };
+
+ this.$get = ['$state', '$stateParams', '$rootScope', function($state, $stateParams, $rootScope) {
+
+ var $lastViewScope = $rootScope;
+
+ // Early catch of $viewContentLoaded event
+ $rootScope.$on('$viewContentLoaded', function (event) {
+ // With nested views, the event occur several times, in "wrong" order
+ if(!event.targetScope.ncyBreadcrumbIgnore &&
+ isAOlderThanB(event.targetScope.$id, $lastViewScope.$id)) {
+ $lastViewScope = event.targetScope;
+ }
+ });
+
+ // Get the parent state
+ var $$parentState = function(state) {
+ // Check if state has explicit parent OR we try guess parent from its name
+ var parent = state.parent || (/^(.+)\.[^.]+$/.exec(state.name) || [])[1];
+ var isObjectParent = typeof parent === "object";
+ // if parent is a object reference, then extract the name
+ return isObjectParent ? parent.name : parent;
+ };
+
+ // Add the state in the chain if not already in and if not abstract
+ var $$addStateInChain = function(chain, stateRef) {
+ var conf,
+ parentParams,
+ ref = parseStateRef(stateRef),
+ force = false,
+ skip = false;
+
+ for(var i=0, l=chain.length; i' +
+ '
'};return{restrict:"AE",replace:!0,scope:{},template:c.getTemplate(e),templateUrl:c.getTemplateUrl(),link:{post:function(e){var f=[],g=function(){l(f),f=[];var d=c.$getLastViewScope();e.steps=c.getStatesChain(),b.forEach(e.steps,function(b){if(b.ncyBreadcrumb&&b.ncyBreadcrumb.label){var c=a(b.ncyBreadcrumb.label);b.ncyBreadcrumbLabel=c(d),k(f,c,d,b)}else b.ncyBreadcrumbLabel=b.name})};d.$on("$viewContentLoaded",function(a){a.targetScope.ncyBreadcrumbIgnore||g()}),g()}}}}function h(a,b,c){return{restrict:"A",scope:{},template:"{{ncyBreadcrumbLabel}}",compile:function(d,e){var f=d.attr(e.$attr.ncyBreadcrumbLast);return f&&d.html(f),{post:function(d){var e=[],f=function(){l(e),e=[];var c=b.$getLastViewScope(),f=b.getLastStep();if(f)if(d.ncyBreadcrumbLink=f.ncyBreadcrumbLink,f.ncyBreadcrumb&&f.ncyBreadcrumb.label){var g=a(f.ncyBreadcrumb.label);d.ncyBreadcrumbLabel=g(c),k(e,g,c,d)}else d.ncyBreadcrumbLabel=f.name};c.$on("$viewContentLoaded",function(a){a.targetScope.ncyBreadcrumbIgnore||f()}),f()}}}}}function i(a,c,d){return{restrict:"A",scope:{},template:"{{ncyBreadcrumbChain}}",compile:function(e,f){var g=e.attr(f.$attr.ncyBreadcrumbText);g&&e.html(g);var h=e.attr(f.$attr.ncyBreadcrumbTextSeparator)||" / ";return{post:function(e){var f=[],g=function(a,c,d){b.forEach(j(c),function(b){var c=d.$watch(b,function(a,b){a!==b&&i()});a.push(c)})},i=function(){l(f),f=[];var d=c.$getLastViewScope(),i=c.getStatesChain(),j=[];b.forEach(i,function(b){if(b.ncyBreadcrumb&&b.ncyBreadcrumb.label){var c=a(b.ncyBreadcrumb.label);j.push(c(d)),g(f,c,d)}else j.push(b.name)}),e.ncyBreadcrumbChain=j.join(h)};d.$on("$viewContentLoaded",function(a){a.targetScope.ncyBreadcrumbIgnore||i()}),i()}}}}}var j=function(a){if(a.expressions)return a.expressions;var c=[];return b.forEach(a.parts,function(a){b.isFunction(a)&&c.push(a.exp)}),c},k=function(a,c,d,e){b.forEach(j(c),function(b){var f=d.$watch(b,function(){e.ncyBreadcrumbLabel=c(d)});a.push(f)})},l=function(a){b.forEach(a,function(a){a()})};g.$inject=["$interpolate","$breadcrumb","$rootScope"],h.$inject=["$interpolate","$breadcrumb","$rootScope"],i.$inject=["$interpolate","$breadcrumb","$rootScope"],b.module("ncy-angular-breadcrumb",["ui.router.state"]).provider("$breadcrumb",f).directive("ncyBreadcrumb",g).directive("ncyBreadcrumbLast",h).directive("ncyBreadcrumbText",i)}(window,window.angular);
\ No newline at end of file
diff --git a/LLV/scripts/angular-mocks.js b/LLV/scripts/angular-mocks.js
new file mode 100644
index 0000000..34d3608
--- /dev/null
+++ b/LLV/scripts/angular-mocks.js
@@ -0,0 +1,2842 @@
+/**
+ * @license AngularJS v1.5.0
+ * (c) 2010-2016 Google, Inc. http://angularjs.org
+ * License: MIT
+ */
+(function(window, angular, undefined) {
+
+'use strict';
+
+/**
+ * @ngdoc object
+ * @name angular.mock
+ * @description
+ *
+ * Namespace from 'angular-mocks.js' which contains testing related code.
+ */
+angular.mock = {};
+
+/**
+ * ! This is a private undocumented service !
+ *
+ * @name $browser
+ *
+ * @description
+ * This service is a mock implementation of {@link ng.$browser}. It provides fake
+ * implementation for commonly used browser apis that are hard to test, e.g. setTimeout, xhr,
+ * cookies, etc...
+ *
+ * The api of this service is the same as that of the real {@link ng.$browser $browser}, except
+ * that there are several helper methods available which can be used in tests.
+ */
+angular.mock.$BrowserProvider = function() {
+ this.$get = function() {
+ return new angular.mock.$Browser();
+ };
+};
+
+angular.mock.$Browser = function() {
+ var self = this;
+
+ this.isMock = true;
+ self.$$url = "http://server/";
+ self.$$lastUrl = self.$$url; // used by url polling fn
+ self.pollFns = [];
+
+ // TODO(vojta): remove this temporary api
+ self.$$completeOutstandingRequest = angular.noop;
+ self.$$incOutstandingRequestCount = angular.noop;
+
+
+ // register url polling fn
+
+ self.onUrlChange = function(listener) {
+ self.pollFns.push(
+ function() {
+ if (self.$$lastUrl !== self.$$url || self.$$state !== self.$$lastState) {
+ self.$$lastUrl = self.$$url;
+ self.$$lastState = self.$$state;
+ listener(self.$$url, self.$$state);
+ }
+ }
+ );
+
+ return listener;
+ };
+
+ self.$$applicationDestroyed = angular.noop;
+ self.$$checkUrlChange = angular.noop;
+
+ self.deferredFns = [];
+ self.deferredNextId = 0;
+
+ self.defer = function(fn, delay) {
+ delay = delay || 0;
+ self.deferredFns.push({time:(self.defer.now + delay), fn:fn, id: self.deferredNextId});
+ self.deferredFns.sort(function(a, b) { return a.time - b.time;});
+ return self.deferredNextId++;
+ };
+
+
+ /**
+ * @name $browser#defer.now
+ *
+ * @description
+ * Current milliseconds mock time.
+ */
+ self.defer.now = 0;
+
+
+ self.defer.cancel = function(deferId) {
+ var fnIndex;
+
+ angular.forEach(self.deferredFns, function(fn, index) {
+ if (fn.id === deferId) fnIndex = index;
+ });
+
+ if (angular.isDefined(fnIndex)) {
+ self.deferredFns.splice(fnIndex, 1);
+ return true;
+ }
+
+ return false;
+ };
+
+
+ /**
+ * @name $browser#defer.flush
+ *
+ * @description
+ * Flushes all pending requests and executes the defer callbacks.
+ *
+ * @param {number=} number of milliseconds to flush. See {@link #defer.now}
+ */
+ self.defer.flush = function(delay) {
+ if (angular.isDefined(delay)) {
+ self.defer.now += delay;
+ } else {
+ if (self.deferredFns.length) {
+ self.defer.now = self.deferredFns[self.deferredFns.length - 1].time;
+ } else {
+ throw new Error('No deferred tasks to be flushed');
+ }
+ }
+
+ while (self.deferredFns.length && self.deferredFns[0].time <= self.defer.now) {
+ self.deferredFns.shift().fn();
+ }
+ };
+
+ self.$$baseHref = '/';
+ self.baseHref = function() {
+ return this.$$baseHref;
+ };
+};
+angular.mock.$Browser.prototype = {
+
+/**
+ * @name $browser#poll
+ *
+ * @description
+ * run all fns in pollFns
+ */
+ poll: function poll() {
+ angular.forEach(this.pollFns, function(pollFn) {
+ pollFn();
+ });
+ },
+
+ url: function(url, replace, state) {
+ if (angular.isUndefined(state)) {
+ state = null;
+ }
+ if (url) {
+ this.$$url = url;
+ // Native pushState serializes & copies the object; simulate it.
+ this.$$state = angular.copy(state);
+ return this;
+ }
+
+ return this.$$url;
+ },
+
+ state: function() {
+ return this.$$state;
+ },
+
+ notifyWhenNoOutstandingRequests: function(fn) {
+ fn();
+ }
+};
+
+
+/**
+ * @ngdoc provider
+ * @name $exceptionHandlerProvider
+ *
+ * @description
+ * Configures the mock implementation of {@link ng.$exceptionHandler} to rethrow or to log errors
+ * passed to the `$exceptionHandler`.
+ */
+
+/**
+ * @ngdoc service
+ * @name $exceptionHandler
+ *
+ * @description
+ * Mock implementation of {@link ng.$exceptionHandler} that rethrows or logs errors passed
+ * to it. See {@link ngMock.$exceptionHandlerProvider $exceptionHandlerProvider} for configuration
+ * information.
+ *
+ *
+ * ```js
+ * describe('$exceptionHandlerProvider', function() {
+ *
+ * it('should capture log messages and exceptions', function() {
+ *
+ * module(function($exceptionHandlerProvider) {
+ * $exceptionHandlerProvider.mode('log');
+ * });
+ *
+ * inject(function($log, $exceptionHandler, $timeout) {
+ * $timeout(function() { $log.log(1); });
+ * $timeout(function() { $log.log(2); throw 'banana peel'; });
+ * $timeout(function() { $log.log(3); });
+ * expect($exceptionHandler.errors).toEqual([]);
+ * expect($log.assertEmpty());
+ * $timeout.flush();
+ * expect($exceptionHandler.errors).toEqual(['banana peel']);
+ * expect($log.log.logs).toEqual([[1], [2], [3]]);
+ * });
+ * });
+ * });
+ * ```
+ */
+
+angular.mock.$ExceptionHandlerProvider = function() {
+ var handler;
+
+ /**
+ * @ngdoc method
+ * @name $exceptionHandlerProvider#mode
+ *
+ * @description
+ * Sets the logging mode.
+ *
+ * @param {string} mode Mode of operation, defaults to `rethrow`.
+ *
+ * - `log`: Sometimes it is desirable to test that an error is thrown, for this case the `log`
+ * mode stores an array of errors in `$exceptionHandler.errors`, to allow later
+ * assertion of them. See {@link ngMock.$log#assertEmpty assertEmpty()} and
+ * {@link ngMock.$log#reset reset()}
+ * - `rethrow`: If any errors are passed to the handler in tests, it typically means that there
+ * is a bug in the application or test, so this mock will make these tests fail.
+ * For any implementations that expect exceptions to be thrown, the `rethrow` mode
+ * will also maintain a log of thrown errors.
+ */
+ this.mode = function(mode) {
+
+ switch (mode) {
+ case 'log':
+ case 'rethrow':
+ var errors = [];
+ handler = function(e) {
+ if (arguments.length == 1) {
+ errors.push(e);
+ } else {
+ errors.push([].slice.call(arguments, 0));
+ }
+ if (mode === "rethrow") {
+ throw e;
+ }
+ };
+ handler.errors = errors;
+ break;
+ default:
+ throw new Error("Unknown mode '" + mode + "', only 'log'/'rethrow' modes are allowed!");
+ }
+ };
+
+ this.$get = function() {
+ return handler;
+ };
+
+ this.mode('rethrow');
+};
+
+
+/**
+ * @ngdoc service
+ * @name $log
+ *
+ * @description
+ * Mock implementation of {@link ng.$log} that gathers all logged messages in arrays
+ * (one array per logging level). These arrays are exposed as `logs` property of each of the
+ * level-specific log function, e.g. for level `error` the array is exposed as `$log.error.logs`.
+ *
+ */
+angular.mock.$LogProvider = function() {
+ var debug = true;
+
+ function concat(array1, array2, index) {
+ return array1.concat(Array.prototype.slice.call(array2, index));
+ }
+
+ this.debugEnabled = function(flag) {
+ if (angular.isDefined(flag)) {
+ debug = flag;
+ return this;
+ } else {
+ return debug;
+ }
+ };
+
+ this.$get = function() {
+ var $log = {
+ log: function() { $log.log.logs.push(concat([], arguments, 0)); },
+ warn: function() { $log.warn.logs.push(concat([], arguments, 0)); },
+ info: function() { $log.info.logs.push(concat([], arguments, 0)); },
+ error: function() { $log.error.logs.push(concat([], arguments, 0)); },
+ debug: function() {
+ if (debug) {
+ $log.debug.logs.push(concat([], arguments, 0));
+ }
+ }
+ };
+
+ /**
+ * @ngdoc method
+ * @name $log#reset
+ *
+ * @description
+ * Reset all of the logging arrays to empty.
+ */
+ $log.reset = function() {
+ /**
+ * @ngdoc property
+ * @name $log#log.logs
+ *
+ * @description
+ * Array of messages logged using {@link ng.$log#log `log()`}.
+ *
+ * @example
+ * ```js
+ * $log.log('Some Log');
+ * var first = $log.log.logs.unshift();
+ * ```
+ */
+ $log.log.logs = [];
+ /**
+ * @ngdoc property
+ * @name $log#info.logs
+ *
+ * @description
+ * Array of messages logged using {@link ng.$log#info `info()`}.
+ *
+ * @example
+ * ```js
+ * $log.info('Some Info');
+ * var first = $log.info.logs.unshift();
+ * ```
+ */
+ $log.info.logs = [];
+ /**
+ * @ngdoc property
+ * @name $log#warn.logs
+ *
+ * @description
+ * Array of messages logged using {@link ng.$log#warn `warn()`}.
+ *
+ * @example
+ * ```js
+ * $log.warn('Some Warning');
+ * var first = $log.warn.logs.unshift();
+ * ```
+ */
+ $log.warn.logs = [];
+ /**
+ * @ngdoc property
+ * @name $log#error.logs
+ *
+ * @description
+ * Array of messages logged using {@link ng.$log#error `error()`}.
+ *
+ * @example
+ * ```js
+ * $log.error('Some Error');
+ * var first = $log.error.logs.unshift();
+ * ```
+ */
+ $log.error.logs = [];
+ /**
+ * @ngdoc property
+ * @name $log#debug.logs
+ *
+ * @description
+ * Array of messages logged using {@link ng.$log#debug `debug()`}.
+ *
+ * @example
+ * ```js
+ * $log.debug('Some Error');
+ * var first = $log.debug.logs.unshift();
+ * ```
+ */
+ $log.debug.logs = [];
+ };
+
+ /**
+ * @ngdoc method
+ * @name $log#assertEmpty
+ *
+ * @description
+ * Assert that all of the logging methods have no logged messages. If any messages are present,
+ * an exception is thrown.
+ */
+ $log.assertEmpty = function() {
+ var errors = [];
+ angular.forEach(['error', 'warn', 'info', 'log', 'debug'], function(logLevel) {
+ angular.forEach($log[logLevel].logs, function(log) {
+ angular.forEach(log, function(logItem) {
+ errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\n' +
+ (logItem.stack || ''));
+ });
+ });
+ });
+ if (errors.length) {
+ errors.unshift("Expected $log to be empty! Either a message was logged unexpectedly, or " +
+ "an expected log message was not checked and removed:");
+ errors.push('');
+ throw new Error(errors.join('\n---------\n'));
+ }
+ };
+
+ $log.reset();
+ return $log;
+ };
+};
+
+
+/**
+ * @ngdoc service
+ * @name $interval
+ *
+ * @description
+ * Mock implementation of the $interval service.
+ *
+ * Use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
+ * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
+ * time.
+ *
+ * @param {function()} fn A function that should be called repeatedly.
+ * @param {number} delay Number of milliseconds between each function call.
+ * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
+ * indefinitely.
+ * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
+ * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
+ * @param {...*=} Pass additional parameters to the executed function.
+ * @returns {promise} A promise which will be notified on each iteration.
+ */
+angular.mock.$IntervalProvider = function() {
+ this.$get = ['$browser', '$rootScope', '$q', '$$q',
+ function($browser, $rootScope, $q, $$q) {
+ var repeatFns = [],
+ nextRepeatId = 0,
+ now = 0;
+
+ var $interval = function(fn, delay, count, invokeApply) {
+ var hasParams = arguments.length > 4,
+ args = hasParams ? Array.prototype.slice.call(arguments, 4) : [],
+ iteration = 0,
+ skipApply = (angular.isDefined(invokeApply) && !invokeApply),
+ deferred = (skipApply ? $$q : $q).defer(),
+ promise = deferred.promise;
+
+ count = (angular.isDefined(count)) ? count : 0;
+ promise.then(null, null, (!hasParams) ? fn : function() {
+ fn.apply(null, args);
+ });
+
+ promise.$$intervalId = nextRepeatId;
+
+ function tick() {
+ deferred.notify(iteration++);
+
+ if (count > 0 && iteration >= count) {
+ var fnIndex;
+ deferred.resolve(iteration);
+
+ angular.forEach(repeatFns, function(fn, index) {
+ if (fn.id === promise.$$intervalId) fnIndex = index;
+ });
+
+ if (angular.isDefined(fnIndex)) {
+ repeatFns.splice(fnIndex, 1);
+ }
+ }
+
+ if (skipApply) {
+ $browser.defer.flush();
+ } else {
+ $rootScope.$apply();
+ }
+ }
+
+ repeatFns.push({
+ nextTime:(now + delay),
+ delay: delay,
+ fn: tick,
+ id: nextRepeatId,
+ deferred: deferred
+ });
+ repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime;});
+
+ nextRepeatId++;
+ return promise;
+ };
+ /**
+ * @ngdoc method
+ * @name $interval#cancel
+ *
+ * @description
+ * Cancels a task associated with the `promise`.
+ *
+ * @param {promise} promise A promise from calling the `$interval` function.
+ * @returns {boolean} Returns `true` if the task was successfully cancelled.
+ */
+ $interval.cancel = function(promise) {
+ if (!promise) return false;
+ var fnIndex;
+
+ angular.forEach(repeatFns, function(fn, index) {
+ if (fn.id === promise.$$intervalId) fnIndex = index;
+ });
+
+ if (angular.isDefined(fnIndex)) {
+ repeatFns[fnIndex].deferred.reject('canceled');
+ repeatFns.splice(fnIndex, 1);
+ return true;
+ }
+
+ return false;
+ };
+
+ /**
+ * @ngdoc method
+ * @name $interval#flush
+ * @description
+ *
+ * Runs interval tasks scheduled to be run in the next `millis` milliseconds.
+ *
+ * @param {number=} millis maximum timeout amount to flush up until.
+ *
+ * @return {number} The amount of time moved forward.
+ */
+ $interval.flush = function(millis) {
+ now += millis;
+ while (repeatFns.length && repeatFns[0].nextTime <= now) {
+ var task = repeatFns[0];
+ task.fn();
+ task.nextTime += task.delay;
+ repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime;});
+ }
+ return millis;
+ };
+
+ return $interval;
+ }];
+};
+
+
+/* jshint -W101 */
+/* The R_ISO8061_STR regex is never going to fit into the 100 char limit!
+ * This directive should go inside the anonymous function but a bug in JSHint means that it would
+ * not be enacted early enough to prevent the warning.
+ */
+var R_ISO8061_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?:\:?(\d\d)(?:\:?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/;
+
+function jsonStringToDate(string) {
+ var match;
+ if (match = string.match(R_ISO8061_STR)) {
+ var date = new Date(0),
+ tzHour = 0,
+ tzMin = 0;
+ if (match[9]) {
+ tzHour = toInt(match[9] + match[10]);
+ tzMin = toInt(match[9] + match[11]);
+ }
+ date.setUTCFullYear(toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
+ date.setUTCHours(toInt(match[4] || 0) - tzHour,
+ toInt(match[5] || 0) - tzMin,
+ toInt(match[6] || 0),
+ toInt(match[7] || 0));
+ return date;
+ }
+ return string;
+}
+
+function toInt(str) {
+ return parseInt(str, 10);
+}
+
+function padNumber(num, digits, trim) {
+ var neg = '';
+ if (num < 0) {
+ neg = '-';
+ num = -num;
+ }
+ num = '' + num;
+ while (num.length < digits) num = '0' + num;
+ if (trim) {
+ num = num.substr(num.length - digits);
+ }
+ return neg + num;
+}
+
+
+/**
+ * @ngdoc type
+ * @name angular.mock.TzDate
+ * @description
+ *
+ * *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`.
+ *
+ * Mock of the Date type which has its timezone specified via constructor arg.
+ *
+ * The main purpose is to create Date-like instances with timezone fixed to the specified timezone
+ * offset, so that we can test code that depends on local timezone settings without dependency on
+ * the time zone settings of the machine where the code is running.
+ *
+ * @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored)
+ * @param {(number|string)} timestamp Timestamp representing the desired time in *UTC*
+ *
+ * @example
+ * !!!! WARNING !!!!!
+ * This is not a complete Date object so only methods that were implemented can be called safely.
+ * To make matters worse, TzDate instances inherit stuff from Date via a prototype.
+ *
+ * We do our best to intercept calls to "unimplemented" methods, but since the list of methods is
+ * incomplete we might be missing some non-standard methods. This can result in errors like:
+ * "Date.prototype.foo called on incompatible Object".
+ *
+ * ```js
+ * var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z');
+ * newYearInBratislava.getTimezoneOffset() => -60;
+ * newYearInBratislava.getFullYear() => 2010;
+ * newYearInBratislava.getMonth() => 0;
+ * newYearInBratislava.getDate() => 1;
+ * newYearInBratislava.getHours() => 0;
+ * newYearInBratislava.getMinutes() => 0;
+ * newYearInBratislava.getSeconds() => 0;
+ * ```
+ *
+ */
+angular.mock.TzDate = function(offset, timestamp) {
+ var self = new Date(0);
+ if (angular.isString(timestamp)) {
+ var tsStr = timestamp;
+
+ self.origDate = jsonStringToDate(timestamp);
+
+ timestamp = self.origDate.getTime();
+ if (isNaN(timestamp)) {
+ throw {
+ name: "Illegal Argument",
+ message: "Arg '" + tsStr + "' passed into TzDate constructor is not a valid date string"
+ };
+ }
+ } else {
+ self.origDate = new Date(timestamp);
+ }
+
+ var localOffset = new Date(timestamp).getTimezoneOffset();
+ self.offsetDiff = localOffset * 60 * 1000 - offset * 1000 * 60 * 60;
+ self.date = new Date(timestamp + self.offsetDiff);
+
+ self.getTime = function() {
+ return self.date.getTime() - self.offsetDiff;
+ };
+
+ self.toLocaleDateString = function() {
+ return self.date.toLocaleDateString();
+ };
+
+ self.getFullYear = function() {
+ return self.date.getFullYear();
+ };
+
+ self.getMonth = function() {
+ return self.date.getMonth();
+ };
+
+ self.getDate = function() {
+ return self.date.getDate();
+ };
+
+ self.getHours = function() {
+ return self.date.getHours();
+ };
+
+ self.getMinutes = function() {
+ return self.date.getMinutes();
+ };
+
+ self.getSeconds = function() {
+ return self.date.getSeconds();
+ };
+
+ self.getMilliseconds = function() {
+ return self.date.getMilliseconds();
+ };
+
+ self.getTimezoneOffset = function() {
+ return offset * 60;
+ };
+
+ self.getUTCFullYear = function() {
+ return self.origDate.getUTCFullYear();
+ };
+
+ self.getUTCMonth = function() {
+ return self.origDate.getUTCMonth();
+ };
+
+ self.getUTCDate = function() {
+ return self.origDate.getUTCDate();
+ };
+
+ self.getUTCHours = function() {
+ return self.origDate.getUTCHours();
+ };
+
+ self.getUTCMinutes = function() {
+ return self.origDate.getUTCMinutes();
+ };
+
+ self.getUTCSeconds = function() {
+ return self.origDate.getUTCSeconds();
+ };
+
+ self.getUTCMilliseconds = function() {
+ return self.origDate.getUTCMilliseconds();
+ };
+
+ self.getDay = function() {
+ return self.date.getDay();
+ };
+
+ // provide this method only on browsers that already have it
+ if (self.toISOString) {
+ self.toISOString = function() {
+ return padNumber(self.origDate.getUTCFullYear(), 4) + '-' +
+ padNumber(self.origDate.getUTCMonth() + 1, 2) + '-' +
+ padNumber(self.origDate.getUTCDate(), 2) + 'T' +
+ padNumber(self.origDate.getUTCHours(), 2) + ':' +
+ padNumber(self.origDate.getUTCMinutes(), 2) + ':' +
+ padNumber(self.origDate.getUTCSeconds(), 2) + '.' +
+ padNumber(self.origDate.getUTCMilliseconds(), 3) + 'Z';
+ };
+ }
+
+ //hide all methods not implemented in this mock that the Date prototype exposes
+ var unimplementedMethods = ['getUTCDay',
+ 'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds',
+ 'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear',
+ 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds',
+ 'setYear', 'toDateString', 'toGMTString', 'toJSON', 'toLocaleFormat', 'toLocaleString',
+ 'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf'];
+
+ angular.forEach(unimplementedMethods, function(methodName) {
+ self[methodName] = function() {
+ throw new Error("Method '" + methodName + "' is not implemented in the TzDate mock");
+ };
+ });
+
+ return self;
+};
+
+//make "tzDateInstance instanceof Date" return true
+angular.mock.TzDate.prototype = Date.prototype;
+/* jshint +W101 */
+
+
+/**
+ * @ngdoc service
+ * @name $animate
+ *
+ * @description
+ * Mock implementation of the {@link ng.$animate `$animate`} service. Exposes two additional methods
+ * for testing animations.
+ */
+angular.mock.animate = angular.module('ngAnimateMock', ['ng'])
+
+ .config(['$provide', function($provide) {
+
+ $provide.factory('$$forceReflow', function() {
+ function reflowFn() {
+ reflowFn.totalReflows++;
+ }
+ reflowFn.totalReflows = 0;
+ return reflowFn;
+ });
+
+ $provide.factory('$$animateAsyncRun', function() {
+ var queue = [];
+ var queueFn = function() {
+ return function(fn) {
+ queue.push(fn);
+ };
+ };
+ queueFn.flush = function() {
+ if (queue.length === 0) return false;
+
+ for (var i = 0; i < queue.length; i++) {
+ queue[i]();
+ }
+ queue = [];
+
+ return true;
+ };
+ return queueFn;
+ });
+
+ $provide.decorator('$$animateJs', ['$delegate', function($delegate) {
+ var runners = [];
+
+ var animateJsConstructor = function() {
+ var animator = $delegate.apply($delegate, arguments);
+ // If no javascript animation is found, animator is undefined
+ if (animator) {
+ runners.push(animator);
+ }
+ return animator;
+ };
+
+ animateJsConstructor.$closeAndFlush = function() {
+ runners.forEach(function(runner) {
+ runner.end();
+ });
+ runners = [];
+ };
+
+ return animateJsConstructor;
+ }]);
+
+ $provide.decorator('$animateCss', ['$delegate', function($delegate) {
+ var runners = [];
+
+ var animateCssConstructor = function(element, options) {
+ var animator = $delegate(element, options);
+ runners.push(animator);
+ return animator;
+ };
+
+ animateCssConstructor.$closeAndFlush = function() {
+ runners.forEach(function(runner) {
+ runner.end();
+ });
+ runners = [];
+ };
+
+ return animateCssConstructor;
+ }]);
+
+ $provide.decorator('$animate', ['$delegate', '$timeout', '$browser', '$$rAF', '$animateCss', '$$animateJs',
+ '$$forceReflow', '$$animateAsyncRun', '$rootScope',
+ function($delegate, $timeout, $browser, $$rAF, $animateCss, $$animateJs,
+ $$forceReflow, $$animateAsyncRun, $rootScope) {
+ var animate = {
+ queue: [],
+ cancel: $delegate.cancel,
+ on: $delegate.on,
+ off: $delegate.off,
+ pin: $delegate.pin,
+ get reflows() {
+ return $$forceReflow.totalReflows;
+ },
+ enabled: $delegate.enabled,
+ /**
+ * @ngdoc method
+ * @name $animate#closeAndFlush
+ * @description
+ *
+ * This method will close all pending animations (both {@link ngAnimate#javascript-based-animations Javascript}
+ * and {@link ngAnimate.$animateCss CSS}) and it will also flush any remaining animation frames and/or callbacks.
+ */
+ closeAndFlush: function() {
+ // we allow the flush command to swallow the errors
+ // because depending on whether CSS or JS animations are
+ // used, there may not be a RAF flush. The primary flush
+ // at the end of this function must throw an exception
+ // because it will track if there were pending animations
+ this.flush(true);
+ $animateCss.$closeAndFlush();
+ $$animateJs.$closeAndFlush();
+ this.flush();
+ },
+ /**
+ * @ngdoc method
+ * @name $animate#flush
+ * @description
+ *
+ * This method is used to flush the pending callbacks and animation frames to either start
+ * an animation or conclude an animation. Note that this will not actually close an
+ * actively running animation (see {@link ngMock.$animate#closeAndFlush `closeAndFlush()`} for that).
+ */
+ flush: function(hideErrors) {
+ $rootScope.$digest();
+
+ var doNextRun, somethingFlushed = false;
+ do {
+ doNextRun = false;
+
+ if ($$rAF.queue.length) {
+ $$rAF.flush();
+ doNextRun = somethingFlushed = true;
+ }
+
+ if ($$animateAsyncRun.flush()) {
+ doNextRun = somethingFlushed = true;
+ }
+ } while (doNextRun);
+
+ if (!somethingFlushed && !hideErrors) {
+ throw new Error('No pending animations ready to be closed or flushed');
+ }
+
+ $rootScope.$digest();
+ }
+ };
+
+ angular.forEach(
+ ['animate','enter','leave','move','addClass','removeClass','setClass'], function(method) {
+ animate[method] = function() {
+ animate.queue.push({
+ event: method,
+ element: arguments[0],
+ options: arguments[arguments.length - 1],
+ args: arguments
+ });
+ return $delegate[method].apply($delegate, arguments);
+ };
+ });
+
+ return animate;
+ }]);
+
+ }]);
+
+
+/**
+ * @ngdoc function
+ * @name angular.mock.dump
+ * @description
+ *
+ * *NOTE*: this is not an injectable instance, just a globally available function.
+ *
+ * Method for serializing common angular objects (scope, elements, etc..) into strings, useful for
+ * debugging.
+ *
+ * This method is also available on window, where it can be used to display objects on debug
+ * console.
+ *
+ * @param {*} object - any object to turn into string.
+ * @return {string} a serialized string of the argument
+ */
+angular.mock.dump = function(object) {
+ return serialize(object);
+
+ function serialize(object) {
+ var out;
+
+ if (angular.isElement(object)) {
+ object = angular.element(object);
+ out = angular.element('');
+ angular.forEach(object, function(element) {
+ out.append(angular.element(element).clone());
+ });
+ out = out.html();
+ } else if (angular.isArray(object)) {
+ out = [];
+ angular.forEach(object, function(o) {
+ out.push(serialize(o));
+ });
+ out = '[ ' + out.join(', ') + ' ]';
+ } else if (angular.isObject(object)) {
+ if (angular.isFunction(object.$eval) && angular.isFunction(object.$apply)) {
+ out = serializeScope(object);
+ } else if (object instanceof Error) {
+ out = object.stack || ('' + object.name + ': ' + object.message);
+ } else {
+ // TODO(i): this prevents methods being logged,
+ // we should have a better way to serialize objects
+ out = angular.toJson(object, true);
+ }
+ } else {
+ out = String(object);
+ }
+
+ return out;
+ }
+
+ function serializeScope(scope, offset) {
+ offset = offset || ' ';
+ var log = [offset + 'Scope(' + scope.$id + '): {'];
+ for (var key in scope) {
+ if (Object.prototype.hasOwnProperty.call(scope, key) && !key.match(/^(\$|this)/)) {
+ log.push(' ' + key + ': ' + angular.toJson(scope[key]));
+ }
+ }
+ var child = scope.$$childHead;
+ while (child) {
+ log.push(serializeScope(child, offset + ' '));
+ child = child.$$nextSibling;
+ }
+ log.push('}');
+ return log.join('\n' + offset);
+ }
+};
+
+/**
+ * @ngdoc service
+ * @name $httpBackend
+ * @description
+ * Fake HTTP backend implementation suitable for unit testing applications that use the
+ * {@link ng.$http $http service}.
+ *
+ * *Note*: For fake HTTP backend implementation suitable for end-to-end testing or backend-less
+ * development please see {@link ngMockE2E.$httpBackend e2e $httpBackend mock}.
+ *
+ * During unit testing, we want our unit tests to run quickly and have no external dependencies so
+ * we don’t want to send [XHR](https://developer.mozilla.org/en/xmlhttprequest) or
+ * [JSONP](http://en.wikipedia.org/wiki/JSONP) requests to a real server. All we really need is
+ * to verify whether a certain request has been sent or not, or alternatively just let the
+ * application make requests, respond with pre-trained responses and assert that the end result is
+ * what we expect it to be.
+ *
+ * This mock implementation can be used to respond with static or dynamic responses via the
+ * `expect` and `when` apis and their shortcuts (`expectGET`, `whenPOST`, etc).
+ *
+ * When an Angular application needs some data from a server, it calls the $http service, which
+ * sends the request to a real server using $httpBackend service. With dependency injection, it is
+ * easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify
+ * the requests and respond with some testing data without sending a request to a real server.
+ *
+ * There are two ways to specify what test data should be returned as http responses by the mock
+ * backend when the code under test makes http requests:
+ *
+ * - `$httpBackend.expect` - specifies a request expectation
+ * - `$httpBackend.when` - specifies a backend definition
+ *
+ *
+ * ## Request Expectations vs Backend Definitions
+ *
+ * Request expectations provide a way to make assertions about requests made by the application and
+ * to define responses for those requests. The test will fail if the expected requests are not made
+ * or they are made in the wrong order.
+ *
+ * Backend definitions allow you to define a fake backend for your application which doesn't assert
+ * if a particular request was made or not, it just returns a trained response if a request is made.
+ * The test will pass whether or not the request gets made during testing.
+ *
+ *
+ *
+ *
Request expectations
Backend definitions
+ *
+ *
Syntax
+ *
.expect(...).respond(...)
+ *
.when(...).respond(...)
+ *
+ *
+ *
Typical usage
+ *
strict unit tests
+ *
loose (black-box) unit testing
+ *
+ *
+ *
Fulfills multiple requests
+ *
NO
+ *
YES
+ *
+ *
+ *
Order of requests matters
+ *
YES
+ *
NO
+ *
+ *
+ *
Request required
+ *
YES
+ *
NO
+ *
+ *
+ *
Response required
+ *
optional (see below)
+ *
YES
+ *
+ *
+ *
+ * In cases where both backend definitions and request expectations are specified during unit
+ * testing, the request expectations are evaluated first.
+ *
+ * If a request expectation has no response specified, the algorithm will search your backend
+ * definitions for an appropriate response.
+ *
+ * If a request didn't match any expectation or if the expectation doesn't have the response
+ * defined, the backend definitions are evaluated in sequential order to see if any of them match
+ * the request. The response from the first matched definition is returned.
+ *
+ *
+ * ## Flushing HTTP requests
+ *
+ * The $httpBackend used in production always responds to requests asynchronously. If we preserved
+ * this behavior in unit testing, we'd have to create async unit tests, which are hard to write,
+ * to follow and to maintain. But neither can the testing mock respond synchronously; that would
+ * change the execution of the code under test. For this reason, the mock $httpBackend has a
+ * `flush()` method, which allows the test to explicitly flush pending requests. This preserves
+ * the async api of the backend, while allowing the test to execute synchronously.
+ *
+ *
+ * ## Unit testing with mock $httpBackend
+ * The following code shows how to setup and use the mock backend when unit testing a controller.
+ * First we create the controller under test:
+ *
+ ```js
+ // The module code
+ angular
+ .module('MyApp', [])
+ .controller('MyController', MyController);
+
+ // The controller code
+ function MyController($scope, $http) {
+ var authToken;
+
+ $http.get('/auth.py').then(function(response) {
+ authToken = response.headers('A-Token');
+ $scope.user = response.data;
+ });
+
+ $scope.saveMessage = function(message) {
+ var headers = { 'Authorization': authToken };
+ $scope.status = 'Saving...';
+
+ $http.post('/add-msg.py', message, { headers: headers } ).then(function(response) {
+ $scope.status = '';
+ }).catch(function() {
+ $scope.status = 'Failed...';
+ });
+ };
+ }
+ ```
+ *
+ * Now we setup the mock backend and create the test specs:
+ *
+ ```js
+ // testing controller
+ describe('MyController', function() {
+ var $httpBackend, $rootScope, createController, authRequestHandler;
+
+ // Set up the module
+ beforeEach(module('MyApp'));
+
+ beforeEach(inject(function($injector) {
+ // Set up the mock http service responses
+ $httpBackend = $injector.get('$httpBackend');
+ // backend definition common for all tests
+ authRequestHandler = $httpBackend.when('GET', '/auth.py')
+ .respond({userId: 'userX'}, {'A-Token': 'xxx'});
+
+ // Get hold of a scope (i.e. the root scope)
+ $rootScope = $injector.get('$rootScope');
+ // The $controller service is used to create instances of controllers
+ var $controller = $injector.get('$controller');
+
+ createController = function() {
+ return $controller('MyController', {'$scope' : $rootScope });
+ };
+ }));
+
+
+ afterEach(function() {
+ $httpBackend.verifyNoOutstandingExpectation();
+ $httpBackend.verifyNoOutstandingRequest();
+ });
+
+
+ it('should fetch authentication token', function() {
+ $httpBackend.expectGET('/auth.py');
+ var controller = createController();
+ $httpBackend.flush();
+ });
+
+
+ it('should fail authentication', function() {
+
+ // Notice how you can change the response even after it was set
+ authRequestHandler.respond(401, '');
+
+ $httpBackend.expectGET('/auth.py');
+ var controller = createController();
+ $httpBackend.flush();
+ expect($rootScope.status).toBe('Failed...');
+ });
+
+
+ it('should send msg to server', function() {
+ var controller = createController();
+ $httpBackend.flush();
+
+ // now you don’t care about the authentication, but
+ // the controller will still send the request and
+ // $httpBackend will respond without you having to
+ // specify the expectation and response for this request
+
+ $httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, '');
+ $rootScope.saveMessage('message content');
+ expect($rootScope.status).toBe('Saving...');
+ $httpBackend.flush();
+ expect($rootScope.status).toBe('');
+ });
+
+
+ it('should send auth header', function() {
+ var controller = createController();
+ $httpBackend.flush();
+
+ $httpBackend.expectPOST('/add-msg.py', undefined, function(headers) {
+ // check if the header was sent, if it wasn't the expectation won't
+ // match the request and the test will fail
+ return headers['Authorization'] == 'xxx';
+ }).respond(201, '');
+
+ $rootScope.saveMessage('whatever');
+ $httpBackend.flush();
+ });
+ });
+ ```
+ *
+ * ## Dynamic responses
+ *
+ * You define a response to a request by chaining a call to `respond()` onto a definition or expectation.
+ * If you provide a **callback** as the first parameter to `respond(callback)` then you can dynamically generate
+ * a response based on the properties of the request.
+ *
+ * The `callback` function should be of the form `function(method, url, data, headers, params)`.
+ *
+ * ### Query parameters
+ *
+ * By default, query parameters on request URLs are parsed into the `params` object. So a request URL
+ * of `/list?q=searchstr&orderby=-name` would set `params` to be `{q: 'searchstr', orderby: '-name'}`.
+ *
+ * ### Regex parameter matching
+ *
+ * If an expectation or definition uses a **regex** to match the URL, you can provide an array of **keys** via a
+ * `params` argument. The index of each **key** in the array will match the index of a **group** in the
+ * **regex**.
+ *
+ * The `params` object in the **callback** will now have properties with these keys, which hold the value of the
+ * corresponding **group** in the **regex**.
+ *
+ * This also applies to the `when` and `expect` shortcut methods.
+ *
+ *
+ * ```js
+ * $httpBackend.expect('GET', /\/user\/(.+)/, undefined, undefined, ['id'])
+ * .respond(function(method, url, data, headers, params) {
+ * // for requested url of '/user/1234' params is {id: '1234'}
+ * });
+ *
+ * $httpBackend.whenPATCH(/\/user\/(.+)\/article\/(.+)/, undefined, undefined, ['user', 'article'])
+ * .respond(function(method, url, data, headers, params) {
+ * // for url of '/user/1234/article/567' params is {user: '1234', article: '567'}
+ * });
+ * ```
+ *
+ * ## Matching route requests
+ *
+ * For extra convenience, `whenRoute` and `expectRoute` shortcuts are available. These methods offer colon
+ * delimited matching of the url path, ignoring the query string. This allows declarations
+ * similar to how application routes are configured with `$routeProvider`. Because these methods convert
+ * the definition url to regex, declaration order is important. Combined with query parameter parsing,
+ * the following is possible:
+ *
+ ```js
+ $httpBackend.whenRoute('GET', '/users/:id')
+ .respond(function(method, url, data, headers, params) {
+ return [200, MockUserList[Number(params.id)]];
+ });
+
+ $httpBackend.whenRoute('GET', '/users')
+ .respond(function(method, url, data, headers, params) {
+ var userList = angular.copy(MockUserList),
+ defaultSort = 'lastName',
+ count, pages, isPrevious, isNext;
+
+ // paged api response '/v1/users?page=2'
+ params.page = Number(params.page) || 1;
+
+ // query for last names '/v1/users?q=Archer'
+ if (params.q) {
+ userList = $filter('filter')({lastName: params.q});
+ }
+
+ pages = Math.ceil(userList.length / pagingLength);
+ isPrevious = params.page > 1;
+ isNext = params.page < pages;
+
+ return [200, {
+ count: userList.length,
+ previous: isPrevious,
+ next: isNext,
+ // sort field -> '/v1/users?sortBy=firstName'
+ results: $filter('orderBy')(userList, params.sortBy || defaultSort)
+ .splice((params.page - 1) * pagingLength, pagingLength)
+ }];
+ });
+ ```
+ */
+angular.mock.$HttpBackendProvider = function() {
+ this.$get = ['$rootScope', '$timeout', createHttpBackendMock];
+};
+
+/**
+ * General factory function for $httpBackend mock.
+ * Returns instance for unit testing (when no arguments specified):
+ * - passing through is disabled
+ * - auto flushing is disabled
+ *
+ * Returns instance for e2e testing (when `$delegate` and `$browser` specified):
+ * - passing through (delegating request to real backend) is enabled
+ * - auto flushing is enabled
+ *
+ * @param {Object=} $delegate Real $httpBackend instance (allow passing through if specified)
+ * @param {Object=} $browser Auto-flushing enabled if specified
+ * @return {Object} Instance of $httpBackend mock
+ */
+function createHttpBackendMock($rootScope, $timeout, $delegate, $browser) {
+ var definitions = [],
+ expectations = [],
+ responses = [],
+ responsesPush = angular.bind(responses, responses.push),
+ copy = angular.copy;
+
+ function createResponse(status, data, headers, statusText) {
+ if (angular.isFunction(status)) return status;
+
+ return function() {
+ return angular.isNumber(status)
+ ? [status, data, headers, statusText]
+ : [200, status, data, headers];
+ };
+ }
+
+ // TODO(vojta): change params to: method, url, data, headers, callback
+ function $httpBackend(method, url, data, callback, headers, timeout, withCredentials) {
+ var xhr = new MockXhr(),
+ expectation = expectations[0],
+ wasExpected = false;
+
+ function prettyPrint(data) {
+ return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp)
+ ? data
+ : angular.toJson(data);
+ }
+
+ function wrapResponse(wrapped) {
+ if (!$browser && timeout) {
+ timeout.then ? timeout.then(handleTimeout) : $timeout(handleTimeout, timeout);
+ }
+
+ return handleResponse;
+
+ function handleResponse() {
+ var response = wrapped.response(method, url, data, headers, wrapped.params(url));
+ xhr.$$respHeaders = response[2];
+ callback(copy(response[0]), copy(response[1]), xhr.getAllResponseHeaders(),
+ copy(response[3] || ''));
+ }
+
+ function handleTimeout() {
+ for (var i = 0, ii = responses.length; i < ii; i++) {
+ if (responses[i] === handleResponse) {
+ responses.splice(i, 1);
+ callback(-1, undefined, '');
+ break;
+ }
+ }
+ }
+ }
+
+ if (expectation && expectation.match(method, url)) {
+ if (!expectation.matchData(data)) {
+ throw new Error('Expected ' + expectation + ' with different data\n' +
+ 'EXPECTED: ' + prettyPrint(expectation.data) + '\nGOT: ' + data);
+ }
+
+ if (!expectation.matchHeaders(headers)) {
+ throw new Error('Expected ' + expectation + ' with different headers\n' +
+ 'EXPECTED: ' + prettyPrint(expectation.headers) + '\nGOT: ' +
+ prettyPrint(headers));
+ }
+
+ expectations.shift();
+
+ if (expectation.response) {
+ responses.push(wrapResponse(expectation));
+ return;
+ }
+ wasExpected = true;
+ }
+
+ var i = -1, definition;
+ while ((definition = definitions[++i])) {
+ if (definition.match(method, url, data, headers || {})) {
+ if (definition.response) {
+ // if $browser specified, we do auto flush all requests
+ ($browser ? $browser.defer : responsesPush)(wrapResponse(definition));
+ } else if (definition.passThrough) {
+ $delegate(method, url, data, callback, headers, timeout, withCredentials);
+ } else throw new Error('No response defined !');
+ return;
+ }
+ }
+ throw wasExpected ?
+ new Error('No response defined !') :
+ new Error('Unexpected request: ' + method + ' ' + url + '\n' +
+ (expectation ? 'Expected ' + expectation : 'No more request expected'));
+ }
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#when
+ * @description
+ * Creates a new backend definition.
+ *
+ * @param {string} method HTTP method.
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives
+ * data string and returns true if the data is as expected.
+ * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
+ * object and returns true if the headers match the current definition.
+ * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled.
+ *
+ * - respond –
+ * `{function([status,] data[, headers, statusText])
+ * | function(function(method, url, data, headers, params)}`
+ * – The respond method takes a set of static data to be returned or a function that can
+ * return an array containing response status (number), response data (string), response
+ * headers (Object), and the text for the status (string). The respond method returns the
+ * `requestHandler` object for possible overrides.
+ */
+ $httpBackend.when = function(method, url, data, headers, keys) {
+ var definition = new MockHttpExpectation(method, url, data, headers, keys),
+ chain = {
+ respond: function(status, data, headers, statusText) {
+ definition.passThrough = undefined;
+ definition.response = createResponse(status, data, headers, statusText);
+ return chain;
+ }
+ };
+
+ if ($browser) {
+ chain.passThrough = function() {
+ definition.response = undefined;
+ definition.passThrough = true;
+ return chain;
+ };
+ }
+
+ definitions.push(definition);
+ return chain;
+ };
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#whenGET
+ * @description
+ * Creates a new backend definition for GET requests. For more info see `when()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#whenHEAD
+ * @description
+ * Creates a new backend definition for HEAD requests. For more info see `when()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#whenDELETE
+ * @description
+ * Creates a new backend definition for DELETE requests. For more info see `when()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#whenPOST
+ * @description
+ * Creates a new backend definition for POST requests. For more info see `when()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives
+ * data string and returns true if the data is as expected.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#whenPUT
+ * @description
+ * Creates a new backend definition for PUT requests. For more info see `when()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives
+ * data string and returns true if the data is as expected.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#whenJSONP
+ * @description
+ * Creates a new backend definition for JSONP requests. For more info see `when()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled.
+ */
+ createShortMethods('when');
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#whenRoute
+ * @description
+ * Creates a new backend definition that compares only with the requested route.
+ *
+ * @param {string} method HTTP method.
+ * @param {string} url HTTP url string that supports colon param matching.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled. See #when for more info.
+ */
+ $httpBackend.whenRoute = function(method, url) {
+ var pathObj = parseRoute(url);
+ return $httpBackend.when(method, pathObj.regexp, undefined, undefined, pathObj.keys);
+ };
+
+ function parseRoute(url) {
+ var ret = {
+ regexp: url
+ },
+ keys = ret.keys = [];
+
+ if (!url || !angular.isString(url)) return ret;
+
+ url = url
+ .replace(/([().])/g, '\\$1')
+ .replace(/(\/)?:(\w+)([\?\*])?/g, function(_, slash, key, option) {
+ var optional = option === '?' ? option : null;
+ var star = option === '*' ? option : null;
+ keys.push({ name: key, optional: !!optional });
+ slash = slash || '';
+ return ''
+ + (optional ? '' : slash)
+ + '(?:'
+ + (optional ? slash : '')
+ + (star && '(.+?)' || '([^/]+)')
+ + (optional || '')
+ + ')'
+ + (optional || '');
+ })
+ .replace(/([\/$\*])/g, '\\$1');
+
+ ret.regexp = new RegExp('^' + url, 'i');
+ return ret;
+ }
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#expect
+ * @description
+ * Creates a new request expectation.
+ *
+ * @param {string} method HTTP method.
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
+ * receives data string and returns true if the data is as expected, or Object if request body
+ * is in JSON format.
+ * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
+ * object and returns true if the headers match the current expectation.
+ * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled.
+ *
+ * - respond –
+ * `{function([status,] data[, headers, statusText])
+ * | function(function(method, url, data, headers, params)}`
+ * – The respond method takes a set of static data to be returned or a function that can
+ * return an array containing response status (number), response data (string), response
+ * headers (Object), and the text for the status (string). The respond method returns the
+ * `requestHandler` object for possible overrides.
+ */
+ $httpBackend.expect = function(method, url, data, headers, keys) {
+ var expectation = new MockHttpExpectation(method, url, data, headers, keys),
+ chain = {
+ respond: function(status, data, headers, statusText) {
+ expectation.response = createResponse(status, data, headers, statusText);
+ return chain;
+ }
+ };
+
+ expectations.push(expectation);
+ return chain;
+ };
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#expectGET
+ * @description
+ * Creates a new request expectation for GET requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {Object=} headers HTTP headers.
+ * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled. See #expect for more info.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#expectHEAD
+ * @description
+ * Creates a new request expectation for HEAD requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {Object=} headers HTTP headers.
+ * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#expectDELETE
+ * @description
+ * Creates a new request expectation for DELETE requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {Object=} headers HTTP headers.
+ * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#expectPOST
+ * @description
+ * Creates a new request expectation for POST requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
+ * receives data string and returns true if the data is as expected, or Object if request body
+ * is in JSON format.
+ * @param {Object=} headers HTTP headers.
+ * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#expectPUT
+ * @description
+ * Creates a new request expectation for PUT requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
+ * receives data string and returns true if the data is as expected, or Object if request body
+ * is in JSON format.
+ * @param {Object=} headers HTTP headers.
+ * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#expectPATCH
+ * @description
+ * Creates a new request expectation for PATCH requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
+ * receives data string and returns true if the data is as expected, or Object if request body
+ * is in JSON format.
+ * @param {Object=} headers HTTP headers.
+ * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#expectJSONP
+ * @description
+ * Creates a new request expectation for JSONP requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives an url
+ * and returns true if the url matches the current definition.
+ * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled.
+ */
+ createShortMethods('expect');
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#expectRoute
+ * @description
+ * Creates a new request expectation that compares only with the requested route.
+ *
+ * @param {string} method HTTP method.
+ * @param {string} url HTTP url string that supports colon param matching.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled. See #expect for more info.
+ */
+ $httpBackend.expectRoute = function(method, url) {
+ var pathObj = parseRoute(url);
+ return $httpBackend.expect(method, pathObj.regexp, undefined, undefined, pathObj.keys);
+ };
+
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#flush
+ * @description
+ * Flushes all pending requests using the trained responses.
+ *
+ * @param {number=} count Number of responses to flush (in the order they arrived). If undefined,
+ * all pending requests will be flushed. If there are no pending requests when the flush method
+ * is called an exception is thrown (as this typically a sign of programming error).
+ */
+ $httpBackend.flush = function(count, digest) {
+ if (digest !== false) $rootScope.$digest();
+ if (!responses.length) throw new Error('No pending request to flush !');
+
+ if (angular.isDefined(count) && count !== null) {
+ while (count--) {
+ if (!responses.length) throw new Error('No more pending request to flush !');
+ responses.shift()();
+ }
+ } else {
+ while (responses.length) {
+ responses.shift()();
+ }
+ }
+ $httpBackend.verifyNoOutstandingExpectation(digest);
+ };
+
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#verifyNoOutstandingExpectation
+ * @description
+ * Verifies that all of the requests defined via the `expect` api were made. If any of the
+ * requests were not made, verifyNoOutstandingExpectation throws an exception.
+ *
+ * Typically, you would call this method following each test case that asserts requests using an
+ * "afterEach" clause.
+ *
+ * ```js
+ * afterEach($httpBackend.verifyNoOutstandingExpectation);
+ * ```
+ */
+ $httpBackend.verifyNoOutstandingExpectation = function(digest) {
+ if (digest !== false) $rootScope.$digest();
+ if (expectations.length) {
+ throw new Error('Unsatisfied requests: ' + expectations.join(', '));
+ }
+ };
+
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#verifyNoOutstandingRequest
+ * @description
+ * Verifies that there are no outstanding requests that need to be flushed.
+ *
+ * Typically, you would call this method following each test case that asserts requests using an
+ * "afterEach" clause.
+ *
+ * ```js
+ * afterEach($httpBackend.verifyNoOutstandingRequest);
+ * ```
+ */
+ $httpBackend.verifyNoOutstandingRequest = function() {
+ if (responses.length) {
+ throw new Error('Unflushed requests: ' + responses.length);
+ }
+ };
+
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#resetExpectations
+ * @description
+ * Resets all request expectations, but preserves all backend definitions. Typically, you would
+ * call resetExpectations during a multiple-phase test when you want to reuse the same instance of
+ * $httpBackend mock.
+ */
+ $httpBackend.resetExpectations = function() {
+ expectations.length = 0;
+ responses.length = 0;
+ };
+
+ return $httpBackend;
+
+
+ function createShortMethods(prefix) {
+ angular.forEach(['GET', 'DELETE', 'JSONP', 'HEAD'], function(method) {
+ $httpBackend[prefix + method] = function(url, headers, keys) {
+ return $httpBackend[prefix](method, url, undefined, headers, keys);
+ };
+ });
+
+ angular.forEach(['PUT', 'POST', 'PATCH'], function(method) {
+ $httpBackend[prefix + method] = function(url, data, headers, keys) {
+ return $httpBackend[prefix](method, url, data, headers, keys);
+ };
+ });
+ }
+}
+
+function MockHttpExpectation(method, url, data, headers, keys) {
+
+ this.data = data;
+ this.headers = headers;
+
+ this.match = function(m, u, d, h) {
+ if (method != m) return false;
+ if (!this.matchUrl(u)) return false;
+ if (angular.isDefined(d) && !this.matchData(d)) return false;
+ if (angular.isDefined(h) && !this.matchHeaders(h)) return false;
+ return true;
+ };
+
+ this.matchUrl = function(u) {
+ if (!url) return true;
+ if (angular.isFunction(url.test)) return url.test(u);
+ if (angular.isFunction(url)) return url(u);
+ return url == u;
+ };
+
+ this.matchHeaders = function(h) {
+ if (angular.isUndefined(headers)) return true;
+ if (angular.isFunction(headers)) return headers(h);
+ return angular.equals(headers, h);
+ };
+
+ this.matchData = function(d) {
+ if (angular.isUndefined(data)) return true;
+ if (data && angular.isFunction(data.test)) return data.test(d);
+ if (data && angular.isFunction(data)) return data(d);
+ if (data && !angular.isString(data)) {
+ return angular.equals(angular.fromJson(angular.toJson(data)), angular.fromJson(d));
+ }
+ return data == d;
+ };
+
+ this.toString = function() {
+ return method + ' ' + url;
+ };
+
+ this.params = function(u) {
+ return angular.extend(parseQuery(), pathParams());
+
+ function pathParams() {
+ var keyObj = {};
+ if (!url || !angular.isFunction(url.test) || !keys || keys.length === 0) return keyObj;
+
+ var m = url.exec(u);
+ if (!m) return keyObj;
+ for (var i = 1, len = m.length; i < len; ++i) {
+ var key = keys[i - 1];
+ var val = m[i];
+ if (key && val) {
+ keyObj[key.name || key] = val;
+ }
+ }
+
+ return keyObj;
+ }
+
+ function parseQuery() {
+ var obj = {}, key_value, key,
+ queryStr = u.indexOf('?') > -1
+ ? u.substring(u.indexOf('?') + 1)
+ : "";
+
+ angular.forEach(queryStr.split('&'), function(keyValue) {
+ if (keyValue) {
+ key_value = keyValue.replace(/\+/g,'%20').split('=');
+ key = tryDecodeURIComponent(key_value[0]);
+ if (angular.isDefined(key)) {
+ var val = angular.isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
+ if (!hasOwnProperty.call(obj, key)) {
+ obj[key] = val;
+ } else if (angular.isArray(obj[key])) {
+ obj[key].push(val);
+ } else {
+ obj[key] = [obj[key],val];
+ }
+ }
+ }
+ });
+ return obj;
+ }
+ function tryDecodeURIComponent(value) {
+ try {
+ return decodeURIComponent(value);
+ } catch (e) {
+ // Ignore any invalid uri component
+ }
+ }
+ };
+}
+
+function createMockXhr() {
+ return new MockXhr();
+}
+
+function MockXhr() {
+
+ // hack for testing $http, $httpBackend
+ MockXhr.$$lastInstance = this;
+
+ this.open = function(method, url, async) {
+ this.$$method = method;
+ this.$$url = url;
+ this.$$async = async;
+ this.$$reqHeaders = {};
+ this.$$respHeaders = {};
+ };
+
+ this.send = function(data) {
+ this.$$data = data;
+ };
+
+ this.setRequestHeader = function(key, value) {
+ this.$$reqHeaders[key] = value;
+ };
+
+ this.getResponseHeader = function(name) {
+ // the lookup must be case insensitive,
+ // that's why we try two quick lookups first and full scan last
+ var header = this.$$respHeaders[name];
+ if (header) return header;
+
+ name = angular.lowercase(name);
+ header = this.$$respHeaders[name];
+ if (header) return header;
+
+ header = undefined;
+ angular.forEach(this.$$respHeaders, function(headerVal, headerName) {
+ if (!header && angular.lowercase(headerName) == name) header = headerVal;
+ });
+ return header;
+ };
+
+ this.getAllResponseHeaders = function() {
+ var lines = [];
+
+ angular.forEach(this.$$respHeaders, function(value, key) {
+ lines.push(key + ': ' + value);
+ });
+ return lines.join('\n');
+ };
+
+ this.abort = angular.noop;
+}
+
+
+/**
+ * @ngdoc service
+ * @name $timeout
+ * @description
+ *
+ * This service is just a simple decorator for {@link ng.$timeout $timeout} service
+ * that adds a "flush" and "verifyNoPendingTasks" methods.
+ */
+
+angular.mock.$TimeoutDecorator = ['$delegate', '$browser', function($delegate, $browser) {
+
+ /**
+ * @ngdoc method
+ * @name $timeout#flush
+ * @description
+ *
+ * Flushes the queue of pending tasks.
+ *
+ * @param {number=} delay maximum timeout amount to flush up until
+ */
+ $delegate.flush = function(delay) {
+ $browser.defer.flush(delay);
+ };
+
+ /**
+ * @ngdoc method
+ * @name $timeout#verifyNoPendingTasks
+ * @description
+ *
+ * Verifies that there are no pending tasks that need to be flushed.
+ */
+ $delegate.verifyNoPendingTasks = function() {
+ if ($browser.deferredFns.length) {
+ throw new Error('Deferred tasks to flush (' + $browser.deferredFns.length + '): ' +
+ formatPendingTasksAsString($browser.deferredFns));
+ }
+ };
+
+ function formatPendingTasksAsString(tasks) {
+ var result = [];
+ angular.forEach(tasks, function(task) {
+ result.push('{id: ' + task.id + ', ' + 'time: ' + task.time + '}');
+ });
+
+ return result.join(', ');
+ }
+
+ return $delegate;
+}];
+
+angular.mock.$RAFDecorator = ['$delegate', function($delegate) {
+ var rafFn = function(fn) {
+ var index = rafFn.queue.length;
+ rafFn.queue.push(fn);
+ return function() {
+ rafFn.queue.splice(index, 1);
+ };
+ };
+
+ rafFn.queue = [];
+ rafFn.supported = $delegate.supported;
+
+ rafFn.flush = function() {
+ if (rafFn.queue.length === 0) {
+ throw new Error('No rAF callbacks present');
+ }
+
+ var length = rafFn.queue.length;
+ for (var i = 0; i < length; i++) {
+ rafFn.queue[i]();
+ }
+
+ rafFn.queue = rafFn.queue.slice(i);
+ };
+
+ return rafFn;
+}];
+
+/**
+ *
+ */
+angular.mock.$RootElementProvider = function() {
+ this.$get = function() {
+ return angular.element('');
+ };
+};
+
+/**
+ * @ngdoc service
+ * @name $controller
+ * @description
+ * A decorator for {@link ng.$controller} with additional `bindings` parameter, useful when testing
+ * controllers of directives that use {@link $compile#-bindtocontroller- `bindToController`}.
+ *
+ *
+ * ## Example
+ *
+ * ```js
+ *
+ * // Directive definition ...
+ *
+ * myMod.directive('myDirective', {
+ * controller: 'MyDirectiveController',
+ * bindToController: {
+ * name: '@'
+ * }
+ * });
+ *
+ *
+ * // Controller definition ...
+ *
+ * myMod.controller('MyDirectiveController', ['$log', function($log) {
+ * $log.info(this.name);
+ * })];
+ *
+ *
+ * // In a test ...
+ *
+ * describe('myDirectiveController', function() {
+ * it('should write the bound name to the log', inject(function($controller, $log) {
+ * var ctrl = $controller('MyDirectiveController', { /* no locals */ }, { name: 'Clark Kent' });
+ * expect(ctrl.name).toEqual('Clark Kent');
+ * expect($log.info.logs).toEqual(['Clark Kent']);
+ * });
+ * });
+ *
+ * ```
+ *
+ * @param {Function|string} constructor If called with a function then it's considered to be the
+ * controller constructor function. Otherwise it's considered to be a string which is used
+ * to retrieve the controller constructor using the following steps:
+ *
+ * * check if a controller with given name is registered via `$controllerProvider`
+ * * check if evaluating the string on the current scope returns a constructor
+ * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
+ * `window` object (not recommended)
+ *
+ * The string can use the `controller as property` syntax, where the controller instance is published
+ * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
+ * to work correctly.
+ *
+ * @param {Object} locals Injection locals for Controller.
+ * @param {Object=} bindings Properties to add to the controller before invoking the constructor. This is used
+ * to simulate the `bindToController` feature and simplify certain kinds of tests.
+ * @return {Object} Instance of given controller.
+ */
+angular.mock.$ControllerDecorator = ['$delegate', function($delegate) {
+ return function(expression, locals, later, ident) {
+ if (later && typeof later === 'object') {
+ var create = $delegate(expression, locals, true, ident);
+ angular.extend(create.instance, later);
+ return create();
+ }
+ return $delegate(expression, locals, later, ident);
+ };
+}];
+
+/**
+ * @ngdoc service
+ * @name $componentController
+ * @description
+ * A service that can be used to create instances of component controllers.
+ *
+ * Be aware that the controller will be instantiated and attached to the scope as specified in
+ * the component definition object. That means that you must always provide a `$scope` object
+ * in the `locals` param.
+ *
+ * @param {string} componentName the name of the component whose controller we want to instantiate
+ * @param {Object} locals Injection locals for Controller.
+ * @param {Object=} bindings Properties to add to the controller before invoking the constructor. This is used
+ * to simulate the `bindToController` feature and simplify certain kinds of tests.
+ * @param {string=} ident Override the property name to use when attaching the controller to the scope.
+ * @return {Object} Instance of requested controller.
+ */
+angular.mock.$ComponentControllerProvider = ['$compileProvider', function($compileProvider) {
+ return {
+ $get: ['$controller','$injector', function($controller,$injector) {
+ return function $componentController(componentName, locals, bindings, ident) {
+ // get all directives associated to the component name
+ var directives = $injector.get(componentName + 'Directive');
+ // look for those directives that are components
+ var candidateDirectives = directives.filter(function(directiveInfo) {
+ // components have controller, controllerAs and restrict:'E'
+ return directiveInfo.controller && directiveInfo.controllerAs && directiveInfo.restrict === 'E';
+ });
+ // check if valid directives found
+ if (candidateDirectives.length === 0) {
+ throw new Error('No component found');
+ }
+ if (candidateDirectives.length > 1) {
+ throw new Error('Too many components found');
+ }
+ // get the info of the component
+ var directiveInfo = candidateDirectives[0];
+ return $controller(directiveInfo.controller, locals, bindings, ident || directiveInfo.controllerAs);
+ };
+ }]
+ };
+}];
+
+
+/**
+ * @ngdoc module
+ * @name ngMock
+ * @packageName angular-mocks
+ * @description
+ *
+ * # ngMock
+ *
+ * The `ngMock` module provides support to inject and mock Angular services into unit tests.
+ * In addition, ngMock also extends various core ng services such that they can be
+ * inspected and controlled in a synchronous manner within test code.
+ *
+ *
+ *
+ *
+ */
+angular.module('ngMock', ['ng']).provider({
+ $browser: angular.mock.$BrowserProvider,
+ $exceptionHandler: angular.mock.$ExceptionHandlerProvider,
+ $log: angular.mock.$LogProvider,
+ $interval: angular.mock.$IntervalProvider,
+ $httpBackend: angular.mock.$HttpBackendProvider,
+ $rootElement: angular.mock.$RootElementProvider,
+ $componentController: angular.mock.$ComponentControllerProvider
+}).config(['$provide', function($provide) {
+ $provide.decorator('$timeout', angular.mock.$TimeoutDecorator);
+ $provide.decorator('$$rAF', angular.mock.$RAFDecorator);
+ $provide.decorator('$rootScope', angular.mock.$RootScopeDecorator);
+ $provide.decorator('$controller', angular.mock.$ControllerDecorator);
+}]);
+
+/**
+ * @ngdoc module
+ * @name ngMockE2E
+ * @module ngMockE2E
+ * @packageName angular-mocks
+ * @description
+ *
+ * The `ngMockE2E` is an angular module which contains mocks suitable for end-to-end testing.
+ * Currently there is only one mock present in this module -
+ * the {@link ngMockE2E.$httpBackend e2e $httpBackend} mock.
+ */
+angular.module('ngMockE2E', ['ng']).config(['$provide', function($provide) {
+ $provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator);
+}]);
+
+/**
+ * @ngdoc service
+ * @name $httpBackend
+ * @module ngMockE2E
+ * @description
+ * Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of
+ * applications that use the {@link ng.$http $http service}.
+ *
+ * *Note*: For fake http backend implementation suitable for unit testing please see
+ * {@link ngMock.$httpBackend unit-testing $httpBackend mock}.
+ *
+ * This implementation can be used to respond with static or dynamic responses via the `when` api
+ * and its shortcuts (`whenGET`, `whenPOST`, etc) and optionally pass through requests to the
+ * real $httpBackend for specific requests (e.g. to interact with certain remote apis or to fetch
+ * templates from a webserver).
+ *
+ * As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application
+ * is being developed with the real backend api replaced with a mock, it is often desirable for
+ * certain category of requests to bypass the mock and issue a real http request (e.g. to fetch
+ * templates or static files from the webserver). To configure the backend with this behavior
+ * use the `passThrough` request handler of `when` instead of `respond`.
+ *
+ * Additionally, we don't want to manually have to flush mocked out requests like we do during unit
+ * testing. For this reason the e2e $httpBackend flushes mocked out requests
+ * automatically, closely simulating the behavior of the XMLHttpRequest object.
+ *
+ * To setup the application to run with this http backend, you have to create a module that depends
+ * on the `ngMockE2E` and your application modules and defines the fake backend:
+ *
+ * ```js
+ * myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']);
+ * myAppDev.run(function($httpBackend) {
+ * phones = [{name: 'phone1'}, {name: 'phone2'}];
+ *
+ * // returns the current list of phones
+ * $httpBackend.whenGET('/phones').respond(phones);
+ *
+ * // adds a new phone to the phones array
+ * $httpBackend.whenPOST('/phones').respond(function(method, url, data) {
+ * var phone = angular.fromJson(data);
+ * phones.push(phone);
+ * return [200, phone, {}];
+ * });
+ * $httpBackend.whenGET(/^\/templates\//).passThrough();
+ * //...
+ * });
+ * ```
+ *
+ * Afterwards, bootstrap your app with this new module.
+ */
+
+/**
+ * @ngdoc method
+ * @name $httpBackend#when
+ * @module ngMockE2E
+ * @description
+ * Creates a new backend definition.
+ *
+ * @param {string} method HTTP method.
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
+ * object and returns true if the headers match the current definition.
+ * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on
+ * {@link ngMock.$httpBackend $httpBackend mock}.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled. You can save this object for later use and invoke
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
+ *
+ * - respond –
+ * `{function([status,] data[, headers, statusText])
+ * | function(function(method, url, data, headers, params)}`
+ * – The respond method takes a set of static data to be returned or a function that can return
+ * an array containing response status (number), response data (string), response headers
+ * (Object), and the text for the status (string).
+ * - passThrough – `{function()}` – Any request matching a backend definition with
+ * `passThrough` handler will be passed through to the real backend (an XHR request will be made
+ * to the server.)
+ * - Both methods return the `requestHandler` object for possible overrides.
+ */
+
+/**
+ * @ngdoc method
+ * @name $httpBackend#whenGET
+ * @module ngMockE2E
+ * @description
+ * Creates a new backend definition for GET requests. For more info see `when()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on
+ * {@link ngMock.$httpBackend $httpBackend mock}.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled. You can save this object for later use and invoke
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
+ */
+
+/**
+ * @ngdoc method
+ * @name $httpBackend#whenHEAD
+ * @module ngMockE2E
+ * @description
+ * Creates a new backend definition for HEAD requests. For more info see `when()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on
+ * {@link ngMock.$httpBackend $httpBackend mock}.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled. You can save this object for later use and invoke
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
+ */
+
+/**
+ * @ngdoc method
+ * @name $httpBackend#whenDELETE
+ * @module ngMockE2E
+ * @description
+ * Creates a new backend definition for DELETE requests. For more info see `when()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on
+ * {@link ngMock.$httpBackend $httpBackend mock}.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled. You can save this object for later use and invoke
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
+ */
+
+/**
+ * @ngdoc method
+ * @name $httpBackend#whenPOST
+ * @module ngMockE2E
+ * @description
+ * Creates a new backend definition for POST requests. For more info see `when()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on
+ * {@link ngMock.$httpBackend $httpBackend mock}.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled. You can save this object for later use and invoke
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
+ */
+
+/**
+ * @ngdoc method
+ * @name $httpBackend#whenPUT
+ * @module ngMockE2E
+ * @description
+ * Creates a new backend definition for PUT requests. For more info see `when()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on
+ * {@link ngMock.$httpBackend $httpBackend mock}.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled. You can save this object for later use and invoke
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
+ */
+
+/**
+ * @ngdoc method
+ * @name $httpBackend#whenPATCH
+ * @module ngMockE2E
+ * @description
+ * Creates a new backend definition for PATCH requests. For more info see `when()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on
+ * {@link ngMock.$httpBackend $httpBackend mock}.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled. You can save this object for later use and invoke
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
+ */
+
+/**
+ * @ngdoc method
+ * @name $httpBackend#whenJSONP
+ * @module ngMockE2E
+ * @description
+ * Creates a new backend definition for JSONP requests. For more info see `when()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on
+ * {@link ngMock.$httpBackend $httpBackend mock}.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled. You can save this object for later use and invoke
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
+ */
+/**
+ * @ngdoc method
+ * @name $httpBackend#whenRoute
+ * @module ngMockE2E
+ * @description
+ * Creates a new backend definition that compares only with the requested route.
+ *
+ * @param {string} method HTTP method.
+ * @param {string} url HTTP url string that supports colon param matching.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled. You can save this object for later use and invoke
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
+ */
+angular.mock.e2e = {};
+angular.mock.e2e.$httpBackendDecorator =
+ ['$rootScope', '$timeout', '$delegate', '$browser', createHttpBackendMock];
+
+
+/**
+ * @ngdoc type
+ * @name $rootScope.Scope
+ * @module ngMock
+ * @description
+ * {@link ng.$rootScope.Scope Scope} type decorated with helper methods useful for testing. These
+ * methods are automatically available on any {@link ng.$rootScope.Scope Scope} instance when
+ * `ngMock` module is loaded.
+ *
+ * In addition to all the regular `Scope` methods, the following helper methods are available:
+ */
+angular.mock.$RootScopeDecorator = ['$delegate', function($delegate) {
+
+ var $rootScopePrototype = Object.getPrototypeOf($delegate);
+
+ $rootScopePrototype.$countChildScopes = countChildScopes;
+ $rootScopePrototype.$countWatchers = countWatchers;
+
+ return $delegate;
+
+ // ------------------------------------------------------------------------------------------ //
+
+ /**
+ * @ngdoc method
+ * @name $rootScope.Scope#$countChildScopes
+ * @module ngMock
+ * @description
+ * Counts all the direct and indirect child scopes of the current scope.
+ *
+ * The current scope is excluded from the count. The count includes all isolate child scopes.
+ *
+ * @returns {number} Total number of child scopes.
+ */
+ function countChildScopes() {
+ // jshint validthis: true
+ var count = 0; // exclude the current scope
+ var pendingChildHeads = [this.$$childHead];
+ var currentScope;
+
+ while (pendingChildHeads.length) {
+ currentScope = pendingChildHeads.shift();
+
+ while (currentScope) {
+ count += 1;
+ pendingChildHeads.push(currentScope.$$childHead);
+ currentScope = currentScope.$$nextSibling;
+ }
+ }
+
+ return count;
+ }
+
+
+ /**
+ * @ngdoc method
+ * @name $rootScope.Scope#$countWatchers
+ * @module ngMock
+ * @description
+ * Counts all the watchers of direct and indirect child scopes of the current scope.
+ *
+ * The watchers of the current scope are included in the count and so are all the watchers of
+ * isolate child scopes.
+ *
+ * @returns {number} Total number of watchers.
+ */
+ function countWatchers() {
+ // jshint validthis: true
+ var count = this.$$watchers ? this.$$watchers.length : 0; // include the current scope
+ var pendingChildHeads = [this.$$childHead];
+ var currentScope;
+
+ while (pendingChildHeads.length) {
+ currentScope = pendingChildHeads.shift();
+
+ while (currentScope) {
+ count += currentScope.$$watchers ? currentScope.$$watchers.length : 0;
+ pendingChildHeads.push(currentScope.$$childHead);
+ currentScope = currentScope.$$nextSibling;
+ }
+ }
+
+ return count;
+ }
+}];
+
+
+if (window.jasmine || window.mocha) {
+
+ var currentSpec = null,
+ annotatedFunctions = [],
+ isSpecRunning = function() {
+ return !!currentSpec;
+ };
+
+ angular.mock.$$annotate = angular.injector.$$annotate;
+ angular.injector.$$annotate = function(fn) {
+ if (typeof fn === 'function' && !fn.$inject) {
+ annotatedFunctions.push(fn);
+ }
+ return angular.mock.$$annotate.apply(this, arguments);
+ };
+
+
+ (window.beforeEach || window.setup)(function() {
+ annotatedFunctions = [];
+ currentSpec = this;
+ });
+
+ (window.afterEach || window.teardown)(function() {
+ var injector = currentSpec.$injector;
+
+ annotatedFunctions.forEach(function(fn) {
+ delete fn.$inject;
+ });
+
+ angular.forEach(currentSpec.$modules, function(module) {
+ if (module && module.$$hashKey) {
+ module.$$hashKey = undefined;
+ }
+ });
+
+ currentSpec.$injector = null;
+ currentSpec.$modules = null;
+ currentSpec.$providerInjector = null;
+ currentSpec = null;
+
+ if (injector) {
+ injector.get('$rootElement').off();
+ injector.get('$rootScope').$destroy();
+ }
+
+ // clean up jquery's fragment cache
+ angular.forEach(angular.element.fragments, function(val, key) {
+ delete angular.element.fragments[key];
+ });
+
+ MockXhr.$$lastInstance = null;
+
+ angular.forEach(angular.callbacks, function(val, key) {
+ delete angular.callbacks[key];
+ });
+ angular.callbacks.counter = 0;
+ });
+
+ /**
+ * @ngdoc function
+ * @name angular.mock.module
+ * @description
+ *
+ * *NOTE*: This function is also published on window for easy access.
+ * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha
+ *
+ * This function registers a module configuration code. It collects the configuration information
+ * which will be used when the injector is created by {@link angular.mock.inject inject}.
+ *
+ * See {@link angular.mock.inject inject} for usage example
+ *
+ * @param {...(string|Function|Object)} fns any number of modules which are represented as string
+ * aliases or as anonymous module initialization functions. The modules are used to
+ * configure the injector. The 'ng' and 'ngMock' modules are automatically loaded. If an
+ * object literal is passed each key-value pair will be registered on the module via
+ * {@link auto.$provide $provide}.value, the key being the string name (or token) to associate
+ * with the value on the injector.
+ */
+ window.module = angular.mock.module = function() {
+ var moduleFns = Array.prototype.slice.call(arguments, 0);
+ return isSpecRunning() ? workFn() : workFn;
+ /////////////////////
+ function workFn() {
+ if (currentSpec.$injector) {
+ throw new Error('Injector already created, can not register a module!');
+ } else {
+ var fn, modules = currentSpec.$modules || (currentSpec.$modules = []);
+ angular.forEach(moduleFns, function(module) {
+ if (angular.isObject(module) && !angular.isArray(module)) {
+ fn = function($provide) {
+ angular.forEach(module, function(value, key) {
+ $provide.value(key, value);
+ });
+ };
+ } else {
+ fn = module;
+ }
+ if (currentSpec.$providerInjector) {
+ currentSpec.$providerInjector.invoke(fn);
+ } else {
+ modules.push(fn);
+ }
+ });
+ }
+ }
+ };
+
+ /**
+ * @ngdoc function
+ * @name angular.mock.inject
+ * @description
+ *
+ * *NOTE*: This function is also published on window for easy access.
+ * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha
+ *
+ * The inject function wraps a function into an injectable function. The inject() creates new
+ * instance of {@link auto.$injector $injector} per test, which is then used for
+ * resolving references.
+ *
+ *
+ * ## Resolving References (Underscore Wrapping)
+ * Often, we would like to inject a reference once, in a `beforeEach()` block and reuse this
+ * in multiple `it()` clauses. To be able to do this we must assign the reference to a variable
+ * that is declared in the scope of the `describe()` block. Since we would, most likely, want
+ * the variable to have the same name of the reference we have a problem, since the parameter
+ * to the `inject()` function would hide the outer variable.
+ *
+ * To help with this, the injected parameters can, optionally, be enclosed with underscores.
+ * These are ignored by the injector when the reference name is resolved.
+ *
+ * For example, the parameter `_myService_` would be resolved as the reference `myService`.
+ * Since it is available in the function body as _myService_, we can then assign it to a variable
+ * defined in an outer scope.
+ *
+ * ```
+ * // Defined out reference variable outside
+ * var myService;
+ *
+ * // Wrap the parameter in underscores
+ * beforeEach( inject( function(_myService_){
+ * myService = _myService_;
+ * }));
+ *
+ * // Use myService in a series of tests.
+ * it('makes use of myService', function() {
+ * myService.doStuff();
+ * });
+ *
+ * ```
+ *
+ * See also {@link angular.mock.module angular.mock.module}
+ *
+ * ## Example
+ * Example of what a typical jasmine tests looks like with the inject method.
+ * ```js
+ *
+ * angular.module('myApplicationModule', [])
+ * .value('mode', 'app')
+ * .value('version', 'v1.0.1');
+ *
+ *
+ * describe('MyApp', function() {
+ *
+ * // You need to load modules that you want to test,
+ * // it loads only the "ng" module by default.
+ * beforeEach(module('myApplicationModule'));
+ *
+ *
+ * // inject() is used to inject arguments of all given functions
+ * it('should provide a version', inject(function(mode, version) {
+ * expect(version).toEqual('v1.0.1');
+ * expect(mode).toEqual('app');
+ * }));
+ *
+ *
+ * // The inject and module method can also be used inside of the it or beforeEach
+ * it('should override a version and test the new version is injected', function() {
+ * // module() takes functions or strings (module aliases)
+ * module(function($provide) {
+ * $provide.value('version', 'overridden'); // override version here
+ * });
+ *
+ * inject(function(version) {
+ * expect(version).toEqual('overridden');
+ * });
+ * });
+ * });
+ *
+ * ```
+ *
+ * @param {...Function} fns any number of functions which will be injected using the injector.
+ */
+
+
+
+ var ErrorAddingDeclarationLocationStack = function(e, errorForStack) {
+ this.message = e.message;
+ this.name = e.name;
+ if (e.line) this.line = e.line;
+ if (e.sourceId) this.sourceId = e.sourceId;
+ if (e.stack && errorForStack)
+ this.stack = e.stack + '\n' + errorForStack.stack;
+ if (e.stackArray) this.stackArray = e.stackArray;
+ };
+ ErrorAddingDeclarationLocationStack.prototype.toString = Error.prototype.toString;
+
+ window.inject = angular.mock.inject = function() {
+ var blockFns = Array.prototype.slice.call(arguments, 0);
+ var errorForStack = new Error('Declaration Location');
+ return isSpecRunning() ? workFn.call(currentSpec) : workFn;
+ /////////////////////
+ function workFn() {
+ var modules = currentSpec.$modules || [];
+ var strictDi = !!currentSpec.$injectorStrict;
+ modules.unshift(function($injector) {
+ currentSpec.$providerInjector = $injector;
+ });
+ modules.unshift('ngMock');
+ modules.unshift('ng');
+ var injector = currentSpec.$injector;
+ if (!injector) {
+ if (strictDi) {
+ // If strictDi is enabled, annotate the providerInjector blocks
+ angular.forEach(modules, function(moduleFn) {
+ if (typeof moduleFn === "function") {
+ angular.injector.$$annotate(moduleFn);
+ }
+ });
+ }
+ injector = currentSpec.$injector = angular.injector(modules, strictDi);
+ currentSpec.$injectorStrict = strictDi;
+ }
+ for (var i = 0, ii = blockFns.length; i < ii; i++) {
+ if (currentSpec.$injectorStrict) {
+ // If the injector is strict / strictDi, and the spec wants to inject using automatic
+ // annotation, then annotate the function here.
+ injector.annotate(blockFns[i]);
+ }
+ try {
+ /* jshint -W040 *//* Jasmine explicitly provides a `this` object when calling functions */
+ injector.invoke(blockFns[i] || angular.noop, this);
+ /* jshint +W040 */
+ } catch (e) {
+ if (e.stack && errorForStack) {
+ throw new ErrorAddingDeclarationLocationStack(e, errorForStack);
+ }
+ throw e;
+ } finally {
+ errorForStack = null;
+ }
+ }
+ }
+ };
+
+
+ angular.mock.inject.strictDi = function(value) {
+ value = arguments.length ? !!value : true;
+ return isSpecRunning() ? workFn() : workFn;
+
+ function workFn() {
+ if (value !== currentSpec.$injectorStrict) {
+ if (currentSpec.$injector) {
+ throw new Error('Injector already created, can not modify strict annotations');
+ } else {
+ currentSpec.$injectorStrict = value;
+ }
+ }
+ }
+ };
+}
+
+
+})(window, window.angular);
diff --git a/LLV/scripts/angular-route.js b/LLV/scripts/angular-route.js
new file mode 100644
index 0000000..45ac238
--- /dev/null
+++ b/LLV/scripts/angular-route.js
@@ -0,0 +1,1016 @@
+/**
+ * @license AngularJS v1.5.0
+ * (c) 2010-2016 Google, Inc. http://angularjs.org
+ * License: MIT
+ */
+(function(window, angular, undefined) {'use strict';
+
+/**
+ * @ngdoc module
+ * @name ngRoute
+ * @description
+ *
+ * # ngRoute
+ *
+ * The `ngRoute` module provides routing and deeplinking services and directives for angular apps.
+ *
+ * ## Example
+ * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`.
+ *
+ *
+ *
+ */
+ /* global -ngRouteModule */
+var ngRouteModule = angular.module('ngRoute', ['ng']).
+ provider('$route', $RouteProvider),
+ $routeMinErr = angular.$$minErr('ngRoute');
+
+/**
+ * @ngdoc provider
+ * @name $routeProvider
+ *
+ * @description
+ *
+ * Used for configuring routes.
+ *
+ * ## Example
+ * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`.
+ *
+ * ## Dependencies
+ * Requires the {@link ngRoute `ngRoute`} module to be installed.
+ */
+function $RouteProvider() {
+ function inherit(parent, extra) {
+ return angular.extend(Object.create(parent), extra);
+ }
+
+ var routes = {};
+
+ /**
+ * @ngdoc method
+ * @name $routeProvider#when
+ *
+ * @param {string} path Route path (matched against `$location.path`). If `$location.path`
+ * contains redundant trailing slash or is missing one, the route will still match and the
+ * `$location.path` will be updated to add or drop the trailing slash to exactly match the
+ * route definition.
+ *
+ * * `path` can contain named groups starting with a colon: e.g. `:name`. All characters up
+ * to the next slash are matched and stored in `$routeParams` under the given `name`
+ * when the route matches.
+ * * `path` can contain named groups starting with a colon and ending with a star:
+ * e.g.`:name*`. All characters are eagerly stored in `$routeParams` under the given `name`
+ * when the route matches.
+ * * `path` can contain optional named groups with a question mark: e.g.`:name?`.
+ *
+ * For example, routes like `/color/:color/largecode/:largecode*\/edit` will match
+ * `/color/brown/largecode/code/with/slashes/edit` and extract:
+ *
+ * * `color: brown`
+ * * `largecode: code/with/slashes`.
+ *
+ *
+ * @param {Object} route Mapping information to be assigned to `$route.current` on route
+ * match.
+ *
+ * Object properties:
+ *
+ * - `controller` – `{(string|function()=}` – Controller fn that should be associated with
+ * newly created scope or the name of a {@link angular.Module#controller registered
+ * controller} if passed as a string.
+ * - `controllerAs` – `{string=}` – An identifier name for a reference to the controller.
+ * If present, the controller will be published to scope under the `controllerAs` name.
+ * - `template` – `{string=|function()=}` – html template as a string or a function that
+ * returns an html template as a string which should be used by {@link
+ * ngRoute.directive:ngView ngView} or {@link ng.directive:ngInclude ngInclude} directives.
+ * This property takes precedence over `templateUrl`.
+ *
+ * If `template` is a function, it will be called with the following parameters:
+ *
+ * - `{Array.