-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbreeze.base.min.js
5 lines (5 loc) · 153 KB
/
breeze.base.min.js
1
2
3
4
5
!function(e,t){var n=function(){return t(e)};"object"==typeof exports&&"object"==typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):breeze=n()}(this,function(e){"use strict";function t(e,t){for(var n in e)it(e,n)&&t(n,e[n])}function n(e,t){var n=[];for(var r in e)if(it(e,r)){var i=t?t(r,e[r]):e[r];void 0!==i&&n.push(i)}return n}function r(e,t){for(var n in e)if(it(e,n)){var r=e[n];if(t(n,r))return{key:n,value:r}}return null}function i(e,t){var n=a(e,t);return null==n?!0:!(!n.writable&&!n.set)}function a(e,t){if(!ot)return null;if(e.hasOwnProperty(t))return Object.getOwnPropertyDescriptor(e,t);var n=Object.getPrototypeOf(e);return null==n?null:a(n,t)}function o(e,t){return function(n){return n[e]===t}}function s(e){return function(t){return t[e]}}function u(e){var t=[];for(var n in e)it(e,n)&&t.push(e[n]);return t}function p(e,t,n){if(!t)return e;if(n)n.forEach(function(n){e[n]=t[n]});else for(var r in t)it(t,r)&&(e[r]=t[r]);return e}function c(e,t){for(var n in t)void 0===e[n]&&(e[n]=t[n]);return e}function l(e,t){return t.defaultInstance=c(new t(e),t.defaultInstance),e}function y(e,t,n){n=n||{};for(var r in t){var i=r.split(","),a=t[r];i.some(function(t){if(!(t in e))return!1;var r=e[t];return"function"==typeof r?!1:r==a?!0:Array.isArray(r)&&0===r.length?!0:("function"==typeof a?r=a(r):"object"==typeof r&&r&&r.parentEnum&&(r=r.name),void 0===r?!0:(n[i[0]]=r,!0))})}return n}function f(e,t){if(e!==Object(e))return e;if(e._$visited)return void 0;if(e.toJSON){var n=e.toJSON();if(n!==Object(n))return n;if(n!==e)return f(n);e=n}e._$visited=!0;var r;if(e instanceof Array)r=e.map(function(e){return f(e,t)});else if("function"==typeof e)r=void 0;else{r={};for(var i in e)if("_$visited"!==i){var a=e[i];t&&(a=t(i,a),void 0===a)||(a=f(a),void 0!==a&&(r[i]=a))}}return delete e._$visited,r}function h(e,t){var n={},r=e.length;return t.forEach(function(t){for(var i=0;r>i;i++){var a=e[i];if(a){var o=a[t];if(void 0!==o){n[t]=o;break}}}}),n}function d(e){return null==e?[]:Array.isArray(e)?e:[e]}function m(e,t,n){if(n=null==n?!0:n,null==e)return e;var r;return Array.isArray(e)?(r=[],e.forEach(function(e,i){var a=t(e,i);(null!=a||n)&&(r[i]=a)})):r=t(e),r}function v(e,t){for(var n=0,r=e.length;r>n;n++)if(t(e[n]))return e[n];return null}function g(e,t){for(var n=0,r=e.length;r>n;n++)if(t(e[n]))return n;return-1}function w(e,t){var n=e.indexOf(t);-1===n&&e.push(t)}function E(e,t,n){for(var r=V(t)?t:void 0,i=e.length-1,a=!1,o=i;o>=0;o--)if((r?r(e[o]):e[o]===t)&&(e.splice(o,1),a=!0,!n))return!0;return a}function S(e,t,n){for(var r=[],i=Math.min(e.length,t.length),a=0;i>a;++a)r.push(n(e[a],t[a]));return r}function T(e,t,n){if(!e||!t)return!1;if(e.length!==t.length)return!1;for(var r=0;r<e.length;r++)if(Array.isArray(e[r])){if(!T(e[r],t[r]))return!1}else if(n){if(!n(e[r],t[r]))return!1}else if(e[r]!==t[r])return!1;return!0}function P(e,t){var n=e[t];return n||(n=[],e[t]=n),n}function N(e,t){for(var n=e.split(";"),r=0,i=n.length;i>r;r++){var a=_(n[r]);if(a)return a}if(t)throw new Error("Unable to initialize "+e+". "+t)}function _(t){var n=e.window;if(n){var r=n[t];if(r)return r;var i=n.require;if(i){if(i.defined)return i.defined(t)?i(t):void 0;try{return i(t)}catch(a){return}}}}function b(e,t,n,r){var i=e[t];if(n===i)return r();e[t]=n;try{return r()}finally{void 0===i?delete e[t]:e[t]=i}}function O(e,t,n){var r;try{return r=e(),n()}catch(i){throw"object"==typeof r&&(r.error=i),i}finally{t(r)}}function A(e){return function(){for(var t=at(arguments),n="",r=t.length,i=null;r--;)i=t[r],n+=i===Object(i)?JSON.stringify(i):i,e.memoize||(e.memoize={});return n in e.memoize?e.memoize[n]:e.memoize[n]=e.apply(this,t)}}function C(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=16*Math.random()|0,n="x"==e?t:3&t|8;return n.toString(16)})}function x(e){if("string"!=typeof e)throw new Error("Invalid ISO8601 duration '"+e+"'");var t=/^P((\d+Y)?(\d+M)?(\d+D)?)?(T(\d+H)?(\d+M)?(\d+S)?)?$/.exec(e);if(!t)throw new Error("Invalid ISO8601 duration '"+e+"'");for(var n=[2,3,4,6,7,8],r=[31104e3,2592e3,86400,3600,60,1],i=0,a=0;6>a;a++){var o=t[n[a]];o=o?+o.replace(/[A-Za-z]+/g,""):0,i+=o*r[a]}return i}function F(){}function M(e){return e}function D(e){return null===e?"null":void 0===e?"undefined":Object.prototype.toString.call(e).slice(8,-1).toLowerCase()}function k(e){return"date"===D(e)&&!isNaN(e.getTime())}function I(e){var t=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/;return"string"==typeof e&&t.test(e)}function V(e){return"function"===D(e)}function R(e){return"string"==typeof e}function K(e){return"object"==typeof e}function j(e){return"string"==typeof e&&/[a-fA-F\d]{8}-(?:[a-fA-F\d]{4}-){3}[a-fA-F\d]{12}/.test(e)}function L(e){return"string"==typeof e&&/^(-|)?P[T]?[\d\.,\-]+[YMDTHS]/.test(e)}function B(e){if(null===e||void 0===e)return!0;for(var t in e)if(it(e,t))return!1;return!0}function q(e){return!isNaN(parseFloat(e))&&isFinite(e)}function z(e,t){return e?""==t||null==t?!0:0===e.indexOf(t,0):!1}function U(e,t){return e?""==t||null==t?!0:-1!==e.indexOf(t,e.length-t.length):!1}function G(e){var t=arguments,n=RegExp("%([1-"+(arguments.length-1)+"])","g");return e.replace(n,function(e,n){return t[n]})}function $(e){var t=Function.call;return function(){return t.apply(e,arguments)}}function J(e,t,n){void 0===t&&(t=null);var r=n(),i=e.dataType;if(i&&i.parse&&(t=Array.isArray(t)&&!e.isScalar?t.map(function(e){return i.parse(e,typeof e)}):i.parse(t,typeof t)),!(t===r||i&&i.isDate&&t&&r&&t.valueOf()===r.valueOf())){var a,o=this.entityAspect;if(o)a=e.name;else{var s=this.complexAspect;if(!s)return void n(t);o=s.getEntityAspect(),a=s.getPropertyPath(e.name)}var u=o._inProcess=o._inProcess||[];if(!(u.indexOf(e)>=0)){u.push(e);try{var p={parent:this,property:e,newValue:t,oldValue:r,propertyName:a,entityAspect:o};e.isComplexProperty?Z(p,n):e.isDataProperty?Q(p,n):H(p,n),Y(p)}finally{u.pop()}}}}function Q(e,t){var n=e.parent,r=e.property,i=e.entityAspect,a=e.oldValue,o=e.newValue,s=i.entityManager,u=n.entityType;if(!r.isScalar)throw new Error("Nonscalar data properties are readonly - items may be added or removed but the collection may not be changed.");if(i.entityState.isUnchangedOrModified()){var p=r.name,c=n.entityAspect||n.complexAspect;void 0===c.originalValues[p]&&(c.originalValues[p]=void 0!==a?a:r.defaultValue)}if(r.isPartOfKey&&s&&!s.isLoading){var l=u.keyProperties,y=l.map(function(e){return e===r?o:n.getProperty(e.name)}),f=new Pt(u,y);if(s.findEntityByKey(f))throw new Error("An entity with this key is already in the cache: "+f.toString());var h=n.entityAspect.getKey(),d=s._findEntityGroup(u);d._replaceKey(h,f)}var m=r.relatedNavigationProperty;if(m&&s)if(null!=o){var v=new Pt(m.entityType,[o]),g=s.findEntityByKey(v);g?n.setProperty(m.name,g):(s._unattachedChildrenMap.addChild(v,m,n),n.setProperty(m.name,null))}else n.setProperty(m.name,null);else if(r.inverseNavigationProperty&&s&&!s._inKeyFixup){var w=r.inverseNavigationProperty;if(null!=a&&(v=new Pt(w.parentType,[a]),g=s.findEntityByKey(v)))if(w.isScalar)g.setProperty(w.name,null);else{var E=g.getProperty(w.name);E.splice(E.indexOf(n),1)}null!=o&&(v=new Pt(w.parentType,[o]),g=s.findEntityByKey(v),g?w.isScalar?g.setProperty(w.name,n):g.getProperty(w.name).push(n):s._unattachedChildrenMap.addChild(v,w,n))}if(t(o),W(e),r.isPartOfKey){var S=u.keyProperties.indexOf(r);u.navigationProperties.forEach(function(e){var t=e.inverse,r=t?t.foreignKeyNames:e.invForeignKeyNames;if(0!==r.length){var i=n.getProperty(e.name),a=r[S];if(e.isScalar){if(!i)return;i.setProperty(a,o)}else i.forEach(function(e){e.setProperty(a,o)})}}),s&&u.inverseForeignKeyProperties.forEach(function(e){null==e.relatedNavigationProperty.inverse&&s._updateFkVal(e,a,o)}),i.getKey(!0)}}function Z(e,t){var n=e.property,r=e.oldValue,i=e.newValue,a=n.dataType;if(!n.isScalar)throw new Error(G("You cannot set the non-scalar complex property: '%1' on the type: '%2'.Instead get the property and use array functions like 'push' or 'splice' to change its contents.",n.name,n.parentType.name));if(!i)throw new Error(G("You cannot set the '%1' property to null because it's datatype is the ComplexType: '%2'",n.name,n.dataType.name));if(!r){var o=a.getCtor();r=new o,t(r)}a.dataProperties.forEach(function(e){var t=e.name,n=i.getProperty(t);r.setProperty(t,n)})}function H(e,t){var n=e.parent,r=e.property,i=e.entityAspect,a=e.oldValue,o=e.newValue;if(!r.isScalar)throw new Error("Nonscalar navigation properties are readonly - entities can be added or removed but the collection may not be changed.");var s=i.entityManager,u=r.inverse;if(null!=o){var p=o.entityAspect;if(s){if(p.entityState.isDetached())s.isLoading||s.attachEntity(o,Nt.Added);else if(p.entityManager!==s)throw new Error("An Entity cannot be attached to an entity in another EntityManager. One of the two entities must be detached first.")}else p&&p.entityManager&&(s=p.entityManager,s.isLoading||s.attachEntity(i.entity,Nt.Added))}if(u)if(u.isScalar)null!=a&&a.setProperty(u.name,null),null!=o&&o.setProperty(u.name,n);else{if(null!=a){var c=a.getProperty(u.name),l=c.indexOf(n);-1!==l&&c.splice(l,1)}if(null!=o){var y=o.getProperty(u.name);y.push(n)}}else if(r.invForeignKeyNames&&s&&!s._inKeyFixup){var f=r.invForeignKeyNames;if(null!=o){var h=n.entityAspect.getKey().values;f.forEach(function(e,t){o.setProperty(e,h[t])})}else null!=a&&f.forEach(function(e){var t=a.entityType.getProperty(e);t.isPartOfKey||a.setProperty(e,null)})}if(t(o),W(e),r.relatedDataProperties){var d=i.entityState;if(null==o&&(d.isDetached()||a.entityAspect.entityState.isDetached()))return;if(d.isDeleted())return;var m=r.entityType.keyProperties;m.forEach(function(e,t){var i=r.relatedDataProperties[t];if(o||!i.isPartOfKey){var a=o?o.getProperty(e.name):i.defaultValue;n.setProperty(i.name,a)}})}}function Y(e){var t=e.entityAspect,n=t.entityManager,r=t.entity,i={entity:r,parent:e.parent,property:e.property,propertyName:e.propertyName,oldValue:e.oldValue,newValue:e.newValue};n?n.isLoading||n.isRejectingChanges||(t.propertyChanged.publish(i),n.entityChanged.publish({entityAction:Et.PropertyChange,entity:r,args:i})):t.propertyChanged.publish(i)}function W(e){var t=e.entityAspect,n=t.entityManager;if(null!=n&&!n.isLoading){var r=e.property;t.entityState.isUnchanged()&&!r.isUnmapped&&t.setModified(),n.validationOptions.validateOnPropertyChange&&t._validateProperty(e.newValue,{entity:t.entity,property:r,propertyName:e.propertyName,oldValue:e.oldValue})}}function X(e){return e.indexOf(":#")>=0}function et(e,t){return e+":#"+t}function tt(e,t,n){if(t)if(Array.isArray(t))t.forEach(e._addPropertyCore.bind(e));else{if("object"!=typeof t)throw new Error("The 'dataProperties' or 'navigationProperties' values must be either an array of data/nav properties or an object where each property defines a data/nav property");for(var r in t)if(it(t,r)){var i=t[r];i.name=r;var a=new n(i);e._addPropertyCore(a)}}}function nt(e,t){var n=Array.isArray(t)?t:t.split(".");if(1===n.length)return e.getProperty(t);var r=e;return n.some(function(e){return r=r.getProperty(e),null==r}),r}var rt={version:"1.5.2",metadataVersion:"1.0.5"},it=$(Object.prototype.hasOwnProperty),at=$(Array.prototype.slice),ot=function(){try{return!!Object.getPrototypeOf&&Object.defineProperty({},"x",{})}catch(e){return!1}}();Object.create||(Object.create=function(e){var t=function(){};return t.prototype=e,new t});var st={};st.__isES5Supported=ot,st.objectForEach=t,st.extend=p,st.propEq=o,st.pluck=s,st.arrayEquals=T,st.arrayFirst=v,st.arrayIndexOf=g,st.arrayRemoveItem=E,st.arrayZip=S,st.requireLib=N,st.using=b,st.memoize=A,st.getUuid=C,st.durationToSeconds=x,st.isDate=k,st.isGuid=j,st.isDuration=L,st.isFunction=V,st.isEmpty=B,st.isNumeric=q,st.stringStartsWith=z,st.stringEndsWith=U,st.formatString=G,st.getPropertyDescriptor=a,st.toJSONSafe=f,st.parent=rt,rt.core=st;var ut=function(){function e(e,t){return null==t?!1:"string"==typeof t&&t.length>0}function t(e,t){return null==t?!1:typeof t===e.typeName?!0:!1}function n(e,t){return null==t?!1:t instanceof e.type}function r(e,t){return null==t?!1:void 0!==t[e.propertyName]}function i(e,t){return null==t?!1:e.enumType.contains(t)}function a(e,t){return e.allowNull?void 0!==t:null!=t}function o(e,t){if(null==t)return!0;var n=e.prevContext;return n?n.fn(n,t):!0}function s(e,t){var n=e.prevContext,r=n?" or it "+l(n,t):"";return"is optional"+r}function u(e,t){if(!Array.isArray(t))return!1;if(e.mustNotBeEmpty&&0===t.length)return!1;var n=e.prevContext;return n?t.every(function(e){return n.fn(n,e)}):!0}function c(e,t){var n=e.mustNotBeEmpty?"a nonEmpty array":"an array",r=e.prevContext,i=r?" where each element "+l(r,t):"";return" must be "+n+i}function l(e,t){var n=e.msg;return"function"==typeof n&&(n=n(e,t)),n}function y(e,t){if(e._context){for(var n=e._context;null!=n.prevContext;)n=n.prevContext;if(null===n.prevContext)return n.prevContext=t,e;if(null!=t.prevContext)throw new Error("Illegal construction - use 'or' to combine checks");t.prevContext=e._context}return f(e,t)}function f(e,t){return e._contexts[e._contexts.length-1]=t,e._context=t,e}function h(e){var t=e._contexts;return null==t[t.length-1]&&t.pop(),0===t.length?void 0:t.some(function(t){return t.fn(t,e.v)})}function d(e,t){throw new Error(G("Error configuring an instance of '%1'. %2",e&&e._$typeName||"object",t))}var m=function(e,t){this.v=e,this.name=t,this._contexts=[null]},v=m.prototype;return v.isObject=function(){return this.isTypeOf("object")},v.isBoolean=function(){return this.isTypeOf("boolean")},v.isString=function(){return this.isTypeOf("string")},v.isNonEmptyString=function(){return y(this,{fn:e,msg:"must be a nonEmpty string"})},v.isNumber=function(){return this.isTypeOf("number")},v.isFunction=function(){return this.isTypeOf("function")},v.isTypeOf=function(e){return y(this,{fn:t,typeName:e,msg:G("must be a '%1'",e)})},v.isInstanceOf=function(e,t){return t=t||e.prototype._$typeName,y(this,{fn:n,type:e,typeName:t,msg:G("must be an instance of '%1'",t)})},v.hasProperty=function(e){return y(this,{fn:r,propertyName:e,msg:G("must have a '%1' property ",e)})},v.isEnumOf=function(e){return y(this,{fn:i,enumType:e,msg:G("must be an instance of the '%1' enumeration",e.name)})},v.isRequired=function(e){return y(this,{fn:a,allowNull:e,msg:"is required"})},v.isOptional=function(){var e={fn:o,prevContext:null,msg:s};return y(this,e)},v.isNonEmptyArray=function(){return this.isArray(!0)},v.isArray=function(e){var t={fn:u,mustNotBeEmpty:e,prevContext:null,msg:c};return y(this,t)},v.or=function(){return this._contexts.push(null),this._context=null,this},v.check=function(e){var t=h(this);if(void 0!==t){if(!t)throw new Error(this.getMessage());return void 0!==this.v?this.v:e}},v._addContext=function(e){return y(this,e)},v.getMessage=function(){var e=this,t=this._contexts.map(function(t){return l(t,e.v)}).join(", or it ");return G(this.MESSAGE_PREFIX,this.name)+" "+t},v.withDefault=function(e){return this.defaultValue=e,this},v.whereParam=function(e){return this.parent.whereParam(e)},v.applyAll=function(e,t){var n=e._$typeName,r=n&&this.parent.config._$typeName===n,i=p({},this.parent.config);if(this.parent.params.forEach(function(n){r||delete i[n.name];try{n.check()}catch(a){d(e,a.message)}!t&&n._applyOne(e)}),!r)for(var a in i)void 0!==i[a]&&d(e,G("Unknown property: '%1'.",a))},v._applyOne=function(e){void 0!==this.v?e[this.name]=this.v:void 0!==this.defaultValue&&(e[this.name]=this.defaultValue)},v.MESSAGE_PREFIX="The '%1' parameter ",m}(),pt=function(e,t){return new ut(e,t)},ct=function(){var e=function(e){if("object"!=typeof e)throw new Error("Configuration parameter should be an object, instead it is a: "+typeof e);this.config=e,this.params=[]},t=e.prototype;return t.whereParam=function(e){var t=new ut(this.config[e],e);return t.parent=this,this.params.push(t),t},e}(),lt=function(e){return new ct(e)};st.Param=ut,st.assertParam=pt,st.assertConfig=lt;var yt=function(){function e(){}var t=function(t,n){this.name=t;var r=new e(n);r.parentEnum=this,this._symbolPrototype=r,n&&Object.keys(n).forEach(function(e){r[e]=n[e]})},n=t.prototype;return t.isSymbol=function(t){return t instanceof e},n.fromName=function(e){return this[e]},n.addSymbol=function(e){var t=Object.create(this._symbolPrototype);return e&&Object.keys(e).forEach(function(n){t[n]=e[n]}),setTimeout(function(){t.getName()},0),t},n.resolveSymbols=function(){this.getSymbols().forEach(function(e){return e.getName()})},n.getSymbols=function(){return this.getNames().map(function(e){return this[e]},this)},n.getNames=function(){var e=[];for(var t in this)this.hasOwnProperty(t)&&("name"===t||"_"===t.substr(0,1)||V(this[t])||e.push(t));return e},n.contains=function(t){return t instanceof e?this[t.getName()]===t:!1},e.prototype.getName=function(){if(!this.name){var e=this;this.name=v(this.parentEnum.getNames(),function(t){return e.parentEnum[t]===e})}return this.name},e.prototype.toString=function(){return this.getName()},e.prototype.toJSON=function(){return{_$typeName:this.parentEnum.name,name:this.name}},t}();st.Enum=yt;var ft=function(){function e(e,n,r){var i=e._subscribers;return i?void i.forEach(function(i){try{i.callback(n)}catch(a){a.context="unable to publish on topic: "+e.name,r?r(a):e._defaultErrorCallback?e._defaultErrorCallback(a):t(a)}}):!0}function t(){}var n={},r=1,i=function(e,t,r){pt(e,"eventName").isNonEmptyString().check(),pt(t,"publisher").isObject().check(),this.name=e,n[e]=!0,this.publisher=t,r&&(this._defaultErrorCallback=r)},a=i.prototype;return a.publish=function(t,n,r){return i._isEnabled(this.name,this.publisher)?(n===!0?setTimeout(e,0,this,t,r):e(this,t,r),!0):!1},a.publishAsync=function(e,t){this.publish(e,!0,t)},a.subscribe=function(e){this._subscribers||(this._subscribers=[]);var t=r;return this._subscribers.push({unsubKey:t,callback:e}),++r,t},a.unsubscribe=function(e){if(!this._subscribers)return!1;var t=this._subscribers,n=g(t,function(t){return t.unsubKey===e});return-1!==n?(t.splice(n,1),0===t.length&&(this._subscribers=null),!0):!1},a.clear=function(){this._subscribers=null},i.bubbleEvent=function(e,t){e._getEventParent=t},i.enable=function(e,t,n){pt(e,"eventName").isNonEmptyString().check(),pt(t,"obj").isObject().check(),pt(n,"isEnabled").isBoolean().isOptional().or().isFunction().check(),t._$eventMap||(t._$eventMap={}),t._$eventMap[e]=n},i.isEnabled=function(e,t){if(pt(e,"eventName").isNonEmptyString().check(),pt(t,"obj").isObject().check(),void 0===t._getEventParent)throw new Error("This object does not support event enabling/disabling");return i._isEnabled(t,e)},i._isEnabled=function(e,t){var n=null,r=t._$eventMap;if(r&&(n=r[e]),null!=n)return"function"==typeof n?n(t):!!n;var a=t._getEventParent&&t._getEventParent();return a?i._isEnabled(e,a):!0},i}();st.Event=ft;var ht=function(){function e(e,t,n){var r=t.defaultInstance;return r||(r=new t.ctor,t.defaultInstance=r,r._$impl=t),r.initialize(),n&&(e.defaultInstance=r),i.interfaceInitialized.publish({interfaceName:e.name,instance:r,isDefault:!0}),r.checkForRecomposition&&i.interfaceInitialized.subscribe(function(e){r.checkForRecomposition(e)}),r}function t(e){var t=e.toLowerCase(),n=r(i.interfaceRegistry||{},function(e){return e.toLowerCase()===t});if(!n)throw new Error("Unknown interface name: "+e);return n.value}var i={};i.functionRegistry={},i.typeRegistry={},i.objectRegistry={},i.interfaceInitialized=new ft("interfaceInitialized",i);var a=function(e){this.name=e,this.defaultInstance=null,this._implMap={}};return a.prototype.registerCtor=function(e,t){this._implMap[e.toLowerCase()]={ctor:t,defaultInstance:null}},a.prototype.getImpl=function(e){return this._implMap[e.toLowerCase()]},a.prototype.getFirstImpl=function(){var e=r(this._implMap,function(){return!0});return e?e.value:null},i.interfaceRegistry={ajax:new a("ajax"),modelLibrary:new a("modelLibrary"),dataService:new a("dataService"),uriBuilder:new a("uriBuilder")},i.interfaceRegistry.modelLibrary.getDefaultInstance=function(){if(!this.defaultInstance)throw new Error("Unable to locate the default implementation of the '"+this.name+"' interface. Possible options are 'ko', 'backingStore' or 'backbone'. See the breeze.config.initializeAdapterInstances method.");return this.defaultInstance},i.setProperties=function(e){lt(e).whereParam("remoteAccessImplementation").isOptional().whereParam("trackingImplementation").isOptional().whereParam("ajaxImplementation").isOptional().applyAll(e),e.remoteAccessImplementation&&i.initializeAdapterInstance("dataService",e.remoteAccessImplementation),e.trackingImplementation&&i.initializeAdapterInstance("modelLibrary",e.trackingImplementation),e.ajaxImplementation&&i.initializeAdapterInstance("ajax",e.ajaxImplementation)},i.registerAdapter=function(e,n){pt(e,"interfaceName").isNonEmptyString().check(),pt(n,"adapterCtor").isFunction().check();var r=new n,i=r.name;if(!i)throw new Error("Unable to locate a 'name' property on the constructor passed into the 'registerAdapter' call.");var a=t(e);a.registerCtor(i,n)},i.getAdapter=function(e,n){var r=t(e);if(n){var i=r.getImpl(n);return i?i.ctor:null}return r.defaultInstance?r.defaultInstance._$impl.ctor:null},i.initializeAdapterInstances=function(e){return lt(e).whereParam("dataService").isOptional().whereParam("modelLibrary").isOptional().whereParam("ajax").isOptional().whereParam("uriBuilder").isOptional().applyAll(this,!1),n(e,i.initializeAdapterInstance)},i.initializeAdapterInstance=function(n,r,i){i=void 0===i?!0:i,pt(n,"interfaceName").isNonEmptyString().check(),pt(r,"adapterName").isNonEmptyString().check(),pt(i,"isDefault").isBoolean().check();var a=t(n),o=a.getImpl(r);if(!o)throw new Error("Unregistered adapter. Interface: "+n+" AdapterName: "+r);return e(a,o,i)},i.getAdapterInstance=function(n,r){var i,a=t(n),o=null==r||""==r;if(o){if(a.defaultInstance)return a.defaultInstance;i=a.getFirstImpl()}else i=a.getImpl(r);return i?i.defaultInstance?i.defaultInstance:e(a,i,o):null},i.registerFunction=function(e,t){pt(e,"fn").isFunction().check(),pt(t,"fnName").isString().check(),e.prototype._$fnName=t,i.functionRegistry[t]=e},i.getRegisteredFunction=function(e){return i.functionRegistry[e]},i._storeObject=function(e,t,n){var r=("string"==typeof t?t:t.prototype._$typeName)+"."+n;i.objectRegistry[r]=e},i._fetchObject=function(e,t){if(!t)return void 0;var n=("string"==typeof e?e:e.prototype._$typeName)+"."+t,r=i.objectRegistry[n];if(!r)throw new Error("Unable to locate a registered object by the name: "+n);return r},i.registerType=function(e,t){pt(e,"ctor").isFunction().check(),pt(t,"typeName").isString().check(),e.prototype._$typeName=t,i.typeRegistry[t]=e},i.stringifyPad="",i}(),dt=ht.interfaceRegistry.modelLibrary;st.config=ht,rt.config=ht;var mt=function(){function e(e){var t=e.getEntityAspect();t.entityState.isUnchanged()&&t.setModified(),t.entityState.isModified()&&!e._origValues&&(e._origValues=e.slice(0))}function t(e,t){e._processAdds(t),r(e,"arrayChanged",{array:e,added:t})}function n(e,t){e._processRemoves(t),r(e,"arrayChanged",{array:e,removed:t})}function r(e,t,n){var r=e._getPendingPubs();r?e._pendingArgs?i(e._pendingArgs,n):(e._pendingArgs=n,r.push(function(){e[t].publish(e._pendingArgs),e._pendingArgs=null})):e[t].publish(n)}function i(e,t){for(var n in t)if("array"!==n&&e.hasOwnProperty(n)){var r=t[n],i=e[n];if(i){if(!Array.isArray(i))throw new Error("Cannot combine non array args");Array.prototype.push.apply(i,r)}else e[n]=r}}function a(e,t,n){e.parent=t,e.parentProperty=n}var o={};return o.push=function(){if(this._inProgress)return-1;var e=this._getGoodAdds(at(arguments));if(!e.length)return this.length;this._beforeChange();var n=Array.prototype.push.apply(this,e);return t(this,e),n},o._push=function(){if(this._inProgress)return-1;var e=at(arguments);this._beforeChange();var n=Array.prototype.push.apply(this,e);return t(this,e),n},o.unshift=function(){var e=this._getGoodAdds(at(arguments));if(!e.length)return this.length;this._beforeChange();var n=Array.prototype.unshift.apply(this,e);return t(this,at(e)),n},o.pop=function(){this._beforeChange();var e=Array.prototype.pop.apply(this);return n(this,[e]),e},o.shift=function(){this._beforeChange();var e=Array.prototype.shift.apply(this);return n(this,[e]),e},o.splice=function(){var e=this._getGoodAdds(at(arguments,2)),r=at(arguments,0,2).concat(e);this._beforeChange();var i=Array.prototype.splice.apply(this,r);return n(this,i),e.length&&t(this,e),i},o.getEntityAspect=function(){return this.parent.entityAspect||this.parent.complexAspect.getEntityAspect()},o._getEventParent=function(){return this.getEntityAspect()},o._getPendingPubs=function(){var e=this.getEntityAspect().entityManager;return e&&e._pendingPubs},o._beforeChange=function(){},{mixin:o,publish:r,updateEntityState:e,initializeParent:a}}(),vt=function(){function e(e,t,n,r,i){for(r=+e[t=e.length-1],i=0;t--;)n=+e[t],r+=++i%2?2*n%10+(n>4):n;return!(r%10)}function n(e,t,n,r){n&&(f.messageTemplates[e]=n);var i="string"==typeof t?new RegExp(t):t,a=function(e){return null==e||""===e?!0:"string"!=typeof e?!1:i.test(e)};return new f(e,a,r)}function r(e,t,n){return t?e.replace(/%([^%]+)%/g,function(e,r){var i;return i=n?t.hasOwnProperty(r)?t[r]:"":t[r],null!=i?V(i)?i(t):i:""}):e}function i(e,t,n,r){var i=r&&r.messageTemplate||f.messageTemplates[e];return i||(f.messageTemplates[e]=G("'%displayName%' must be an integer between the values of %1 and %2",t,n)),function(){var i=function(e,r){return null==e?!0:("string"==typeof e&&r&&r.allowString&&(e=parseInt(e,0)),"number"!=typeof e||isNaN(e)||Math.floor(e)!==e?!1:null!=t&&t>e?!1:null!=n&&e>n?!1:!0)};return new f(e,i,r)}}var a=-32768,o=32767,s=-2147483648,u=2147483647,c=0,l=255,y={displayName:function(e){return e.property?e.property.resolveProperty("displayName")||e.propertyName||e.property.name:"Value"}},f=function(e,t,n){this._baseContext=n||{},this._baseContext.name=e,n=p(Object.create(y),this._baseContext),n.messageTemplate=n.messageTemplate||f.messageTemplates[e],this.name=e,this.valFn=t,this.context=n},h=f.prototype;return h._$typeName="Validator",h.validate=function(e,t){var n;n=t?p(Object.create(this.context),t):this.context,this.currentContext=n;try{return this.valFn(e,n)?null:(n.value=e,new gt(this,n,this.getMessage()))}catch(r){return new gt(this,n,"Exception occured while executing this validator: "+this.name)}},h.getMessage=function(){try{var e=this.currentContext,t=e.message;return t?"function"==typeof t?t(e):t:e.messageTemplate?r(e.messageTemplate,e):"invalid value: "+(this.name||"{unnamed validator}")}catch(n){return"Unable to format error message"+n.toString()}},h.toJSON=function(){return this._baseContext},f.fromJSON=function(e){if(Array.isArray(e))return e.map(function(e){return f.fromJSON(e)});var t="Validator."+e.name,n=ht.getRegisteredFunction(t);if(!n)throw new Error("Unable to locate a validator named:"+e.name);return n(e)},f.register=function(e){ht.registerFunction(function(){return e},"Validator."+e.name)},f.registerFactory=function(e,t){ht.registerFunction(e,"Validator."+t)},f.messageTemplates={bool:"'%displayName%' must be a 'true' or 'false' value",creditCard:"The %displayName% is not a valid credit card number",date:"'%displayName%' must be a date",duration:"'%displayName%' must be a ISO8601 duration string, such as 'P3H24M60S'",emailAddress:"The %displayName% '%value%' is not a valid email address",guid:"'%displayName%' must be a GUID",integer:"'%displayName%' must be an integer",integerRange:"'%displayName%' must be an integer between the values of %minValue% and %maxValue%",maxLength:"'%displayName%' must be a string with %maxLength% characters or less",number:"'%displayName%' must be a number",phone:"The %displayName% '%value%' is not a valid phone number",regularExpression:"The %displayName% '%value%' does not match '%expression%'",required:"'%displayName%' is required",string:"'%displayName%' must be a string",stringLength:"'%displayName%' must be a string with between %minLength% and %maxLength% characters",url:"The %displayName% '%value%' is not a valid url"},f.required=function(e){var t=function(e,t){return"string"==typeof e?t&&t.allowEmptyStrings?!0:e.length>0:null!=e};return new f("required",t,e)},f.maxLength=function(e){var t=function(e,t){return null==e?!0:"string"!=typeof e?!1:e.length<=t.maxLength};return new f("maxLength",t,e)},f.stringLength=function(e){var t=function(e,t){return null==e?!0:"string"!=typeof e?!1:null!=t.minLength&&e.length<t.minLength?!1:null!=t.maxLength&&e.length>t.maxLength?!1:!0};return new f("stringLength",t,e)},f.string=function(){var e=function(e){return null==e?!0:"string"==typeof e};return new f("string",e)},f.guid=function(){var e=function(e){return null==e?!0:j(e)};return new f("guid",e)},f.duration=function(){var e=function(e){return null==e?!0:L(e)};return new f("duration",e)},f.number=f.double=f.single=function(e){var t=function(e,t){return null==e?!0:("string"==typeof e&&t&&t.allowString&&(e=parseFloat(e,10)),"number"==typeof e&&!isNaN(e))};return new f("number",t,e)},f.integer=f.int64=function(e){var t=function(e,t){return null==e?!0:("string"==typeof e&&t&&t.allowString&&(e=parseInt(e,10)),"number"==typeof e&&!isNaN(e)&&Math.floor(e)===e)};return new f("integer",t,e)},f.int32=function(e){return i("int32",s,u,e)()},f.int16=function(e){return i("int16",a,o,e)()},f.byte=function(e){return i("byte",c,l,e)()},f.bool=function(){var e=function(e){return null==e?!0:e===!0||e===!1};return new f("bool",e)},f.none=function(){var e=function(){return!0};return new f("none",e)},f.date=function(){var e=function(e){if(null==e)return!0;if("string"!=typeof e)return k(e);try{return!isNaN(Date.parse(e))}catch(t){return!1}};return new f("date",e)},f.creditCard=function(t){function n(t){return null==t||""===t?!0:"string"!=typeof t?!1:(t=t.replace(/(\-|\s)/g,""),!t||/\D/.test(t)?!1:e(t))}return new f("creditCard",n,t)},f.regularExpression=function(e){function t(e,t){if(null==e||""===e)return!0;if("string"!=typeof e)return!1;try{var n=new RegExp(t.expression)}catch(r){throw new Error("Missing or invalid expression parameter to regExp validator")}return n.test(e)}return new f("regularExpression",t,e)},f.emailAddress=function(e){var t=/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;return n("emailAddress",t,null,e)},f.phone=function(e){var t=/^((\+|(0(\d+)?[-/.\s]?))[1-9]\d{0,2}[-/.\s]?)?((\(\d{1,6}\)|\d{1,6})[-/.\s]?)?(\d+[-/.\s]?)+\d+$/;return n("phone",t,null,e)},f.url=function(e){var t=/^(https?|ftp):\/\/(((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-fA-F]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|([a-zA-Z][\-a-zA-Z0-9]*)|((([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-fA-F]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-fA-F]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-fA-F]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-fA-F]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/;
return n("url",t,null,e)},f.makeRegExpValidator=n,t(f,function(e,t){"function"==typeof t&&"fromJSON"!==e&&"register"!==e&&"registerFactory"!==e&&"makeRegExpValidator"!==e&&ht.registerFunction(t,"Validator."+e)}),f}(),gt=function(){var e=function t(e,n,r,i){pt(e,"validator").isOptional().isInstanceOf(vt).check(),pt(r,"errorMessage").isNonEmptyString().check(),pt(i,"key").isOptional().isNonEmptyString().check(),this.validator=e,n=n||{},this.context=n,this.errorMessage=r,this.property=n.property,this.propertyName=n.propertyName||n.property&&n.property.name,this.key=i?i:t.getKey(e||r,this.propertyName),this.isServerError=!1};return e.getKey=function(e,t){return(e.name||e)+(t?":"+t:"")},e}();rt.Validator=vt,rt.ValidationError=gt;var wt=function(){function e(e,t){return t&<(t).whereParam("validateOnAttach").isBoolean().isOptional().whereParam("validateOnSave").isBoolean().isOptional().whereParam("validateOnQuery").isBoolean().isOptional().whereParam("validateOnPropertyChange").isBoolean().isOptional().applyAll(e),e}var t=function(t){e(this,t)},n=t.prototype;return n._$typeName="ValidationOptions",n.using=function(t){if(!t)return this;var n=new wt(this);return e(n,t),n},n.setAsDefault=function(){return l(this,t)},t.defaultInstance=new t({validateOnAttach:!0,validateOnSave:!0,validateOnQuery:!1,validateOnPropertyChange:!0}),t}();rt.ValidationOptions=wt,rt.makeComplexArray=function(){function e(e,t){return t.filter(function(t){return t.parent!==e.parent})}function t(e,t){t.forEach(function(t){if(null!=t.parent)throw new Error("The complexObject is already attached. Either clone it or remove it from its current owner");i(t,e)})}function n(e,t){t.forEach(function(t){r(t,e)})}function r(e,t){var n=e.complexAspect;return n.parent!==t.parent?null:(n.parent=null,n.parentProperty=null,n)}function i(e,t){var n=e.complexAspect;return n.parent===t.parent?null:(n.parent=t.parent,n.parentProperty=t.parentProperty,n)}function a(e,t,n){return mt.initializeParent(e,t,n),e.arrayChanged=new ft("arrayChanged",e),p(e,mt.mixin),p(e,o)}var o={};return o._getGoodAdds=function(t){return e(this,t)},o._beforeChange=function(){mt.updateEntityState(this)},o._processAdds=function(e){t(this,e)},o._processRemoves=function(e){n(this,e)},o._rejectChanges=function(){if(this._origValues){var e=this;this.forEach(function(t){r(t,e)}),this.length=0,this._origValues.forEach(function(t){e.push(t)})}},o._acceptChanges=function(){this._origValues=null},a}();var Et=function(){var e={isAttach:function(){return!!this.isAttach},isDetach:function(){return!!this.isDetach},isModification:function(){return!!this.isModification}},t=new yt("EntityAction",e);return t.Attach=t.addSymbol({isAttach:!0}),t.AttachOnQuery=t.addSymbol({isAttach:!0}),t.AttachOnImport=t.addSymbol({isAttach:!0}),t.Detach=t.addSymbol({isDetach:!0}),t.MergeOnQuery=t.addSymbol({isModification:!0}),t.MergeOnImport=t.addSymbol({isModification:!0}),t.MergeOnSave=t.addSymbol({isModification:!0}),t.PropertyChange=t.addSymbol({isModification:!0}),t.EntityStateChange=t.addSymbol(),t.AcceptChanges=t.addSymbol(),t.RejectChanges=t.addSymbol({isModification:!0}),t.Clear=t.addSymbol({isDetach:!0}),t.resolveSymbols(),t}();rt.EntityAction=Et;var St=function(){function e(t){var n=t.entityAspect||t.complexAspect,r=t.entityType||t.complexType,i=n.originalValues;for(var a in i)t.setProperty(a,i[a]);r.complexProperties.forEach(function(n){var r=t.getProperty(n.name);n.isScalar?e(r):(r._rejectChanges(),r.forEach(e))})}function n(e){var t=e.entityAspect||e.complexAspect;t.originalValues={};var r=e.entityType||e.complexType;r.complexProperties.forEach(function(t){var r=e.getProperty(t.name);t.isScalar?n(r):(r._acceptChanges(),r.forEach(n))})}function r(e,t){var n=!0,i=e.entityType||e.complexType,a=e.entityAspect||e.complexAspect,s=e.entityAspect||e.complexAspect.getEntityAspect(),u={entity:s.entity};return void 0!==t&&(u.index=t),i.getProperties().forEach(function(t){var i=e.getProperty(t.name),o=t.getAllValidators();o.length>0&&(u.property=t,u.propertyName=a.getPropertyPath(t.name),n=s._validateProperty(i,u)&&n),t.isComplexProperty&&(n=t.isScalar?r(i)&&n:i.reduce(function(e,t,n){return r(t,n)&&e},n))}),i.getAllValidators().forEach(function(t){n=o(s,t,e)&&n}),n}function i(e,t){var n=t.isDeleted();n?a(e):b(e.entityAspect.entityManager,"isLoading",!0,function(){a(e)})}function a(e){e.entityType.navigationProperties.forEach(function(t){var n=t.inverse,r=e.getProperty(t.name);if(t.isScalar){if(r){if(n)if(n.isScalar)r.setProperty(n.name,null);else{var i=r.getProperty(n.name);i.length&&E(i,e)}e.setProperty(t.name,null)}}else n&&r.slice(0).forEach(function(e){n.isScalar&&e.setProperty(n.name,null)}),r.length=0})}function o(e,t,n,r){var i=t.validate(n,r);if(i)return e._addValidationError(i),!1;var a=gt.getKey(t,r?r.propertyName:null);return e._removeValidationError(a),!0}var s=function c(e){if(null===e){var t=c._nullInstance;if(t)return t;c._nullInstance=this}else{if(void 0===e)throw new Error("The EntityAspect ctor requires an entity as its only argument.");if(e.entityAspect)return e.entityAspect}if(!(this instanceof c))return new c(e);if(this.entity=e,this.entityGroup=null,this.entityManager=null,this.entityState=Nt.Detached,this.isBeingSaved=!1,this.originalValues={},this.hasValidationErrors=!1,this._validationErrors={},this.validationErrorsChanged=new ft("validationErrorsChanged",this),this.propertyChanged=new ft("propertyChanged",this),null!=e){e.entityAspect=this;var n=e.entityType||e._$entityType;if(!n){var r=e.prototype._$typeName;throw new Error(r?"Metadata for this entityType has not yet been resolved: "+r:"This entity is not registered as a valid EntityType")}var i=n.getEntityCtor();dt.getDefaultInstance().startTracking(e,i.prototype)}},p=s.prototype;return ft.bubbleEvent(p,function(){return this.entityManager}),p.getKey=function(e){if(e=pt(e,"forceRefresh").isBoolean().isOptional().check(!1),e||!this._entityKey){var t=this.entity.entityType,n=t.keyProperties,r=n.map(function(e){return this.entity.getProperty(e.name)},this);this._entityKey=new Pt(t,r)}return this._entityKey},p.acceptChanges=function(){this._checkOperation("acceptChanges");var e=this.entityManager;this.entityState.isDeleted()?e.detachEntity(this.entity):this.setUnchanged(),e.entityChanged.publish({entityAction:Et.AcceptChanges,entity:this.entity})},p.rejectChanges=function(){this._checkOperation("rejectChanges");var t=this.entity,n=this.entityManager;b(n,"isRejectingChanges",!0,function(){e(t)}),this.entityState.isAdded()?(n.detachEntity(t),n._notifyStateChange(t,!1)):(this.entityState.isDeleted()&&this.entityManager._linkRelatedEntities(t),this.setUnchanged(),this.propertyChanged.publish({entity:t,propertyName:null}),this.entityManager.entityChanged.publish({entityAction:Et.RejectChanges,entity:t}))},p.getPropertyPath=function(e){return e},p.setAdded=function(){return this.setEntityState(Nt.Added)},p.setUnchanged=function(){return this.setEntityState(Nt.Unchanged)},p.setModified=function(){return this.setEntityState(Nt.Modified)},p.setDeleted=function(){return this.setEntityState(Nt.Deleted)},p.setDetached=function(){return this.setEntityState(Nt.Detached)},p.setEntityState=function(e){if(this.entityState===e)return!1;if(this._checkOperation("setEntityState"),this.entityState.isDetached())throw new Error("You cannot set the 'entityState' of an entity when it is detached - except by first attaching it to an EntityManager");var t=this.entity,r=this.entityManager,a=!0;if(e===Nt.Unchanged)n(t),delete this.hasTempKey,a=!1;else if(e===Nt.Added)n(t);else if(e===Nt.Deleted){if(this.entityState.isAdded())return this.setEntityState(Nt.Detached),!0;this.entityState=Nt.Deleted,i(t,Nt.Deleted)}else if(e===Nt.Modified);else if(e===Nt.Detached){var o=this.entityGroup;if(!o)return!1;o.detachEntity(t),this.entityState=e,i(t,Nt.Detached),this._detach(),r.entityChanged.publish({entityAction:Et.Detach,entity:t}),a=!1}return this.entityState=e,r._notifyStateChange(t,a),!0},p.loadNavigationProperty=function(e,t,n){var r=this.entity,i=r.entityType._checkNavProperty(e),a=Lt.fromEntityNavigation(r,i),o=r.entityAspect.entityManager.executeQuery(a),s=this;return o.then(function(e){return s._markAsLoaded(i.name),t&&t(e),At.resolve(e)},function(e){return n&&n(e),At.reject(e)})},p.markNavigationPropertyAsLoaded=function(e){var t=this.entity.entityType._checkNavProperty(e);this._markAsLoaded(t.name)},p.isNavigationPropertyLoaded=function(e){var t=this.entity.entityType._checkNavProperty(e);return t.isScalar&&null!=this.entity.getProperty(t.name)?!0:this._loadedNps&&this._loadedNps.indexOf(t.name)>=0},p._markAsLoaded=function(e){this._loadedNps=this._loadedNps||[],w(this._loadedNps,e)},p.validateEntity=function(){var e=!0;return this._processValidationOpAndPublish(function(t){e=r(t.entity)}),e},p.validateProperty=function(e,t){var n=this.getPropertyValue(e);return n&&n.complexAspect?r(n):(t=t||{},t.entity=this.entity,"string"==typeof e?(t.property=this.entity.entityType.getProperty(e,!0),t.propertyName=e):(t.property=e,t.propertyName=e.name),this._validateProperty(n,t))},p.getValidationErrors=function(e){pt(e,"property").isOptional().isEntityProperty().or().isString().check();var t=u(this._validationErrors);if(e){var n="string"==typeof e?e:e.name;t=t.filter(function(e){return e.property&&(e.property.name===n||-1!=n.indexOf(".")&&e.propertyName==n)})}return t},p.addValidationError=function(e){pt(e,"validationError").isInstanceOf(gt).check(),this._processValidationOpAndPublish(function(t){t._addValidationError(e)})},p.removeValidationError=function(e){pt(e,"validationErrorOrKey").isString().or().isInstanceOf(gt).or().isInstanceOf(vt).check();var t="string"==typeof e?e:e.key;this._processValidationOpAndPublish(function(e){e._removeValidationError(t)})},p.clearValidationErrors=function(){this._processValidationOpAndPublish(function(e){t(e._validationErrors,function(t,n){n&&(delete e._validationErrors[t],e._pendingValidationResult.removed.push(n))}),e.hasValidationErrors=!B(e._validationErrors)})},p.getParentKey=function(e){var t=e.foreignKeyNames;if(0===t.length)return null;var n=this,r=t.map(function(e){return n.entity.getProperty(e)});return new Pt(e.entityType,r)},p.getPropertyValue=function(e){pt(e,"property").isString().or().isEntityProperty().check();var t;if("string"==typeof e){var n=e.trim().split("."),r=n.shift();for(t=this.entity,t=t.getProperty(r);n.length>0;)r=n.shift(),t=t.getProperty(r)}else{if(!(e.parentType instanceof Ft))throw new Error("The validateProperty method does not accept a 'property' parameter whose parentType is a ComplexType; Pass a 'property path' string as the 'property' parameter instead ");t=this.entity.getProperty(e.name)}return t},p._checkOperation=function(e){if(this.isBeingSaved)throw new Error("Cannot perform a '"+e+"' on an entity that is in the process of being saved");return this},p._detach=function(){this.entityGroup=null,this.entityManager=null,this.entityState=Nt.Detached,this.originalValues={},this._validationErrors={},this.hasValidationErrors=!1,this.validationErrorsChanged.clear(),this.propertyChanged.clear()},p._validateProperty=function(e,t){var n=!0;return this._processValidationOpAndPublish(function(r){t.property.getAllValidators().forEach(function(i){n=o(r,i,e,t)&&n})}),n},p._processValidationOpAndPublish=function(e){if(this._pendingValidationResult)e(this);else try{this._pendingValidationResult={entity:this.entity,added:[],removed:[]},e(this),(this._pendingValidationResult.added.length>0||this._pendingValidationResult.removed.length>0)&&(this.validationErrorsChanged.publish(this._pendingValidationResult),this.entityManager&&this.entityManager.validationErrorsChanged.publish(this._pendingValidationResult))}finally{this._pendingValidationResult=void 0}},p._addValidationError=function(e){this._validationErrors[e.key]=e,this.hasValidationErrors=!0,this._pendingValidationResult.added.push(e)},p._removeValidationError=function(e){var t=this._validationErrors[e];t&&(delete this._validationErrors[e],this.hasValidationErrors=!B(this._validationErrors),this._pendingValidationResult.removed.push(t))},s}(),Tt=function(){var e=function n(e,t,r){if(!e)throw new Error("The ComplexAspect ctor requires an entity as its only argument.");if(e.complexAspect)return e.complexAspect;if(!(this instanceof n))return new n(e,t,r);this.complexObject=e,e.complexAspect=this,this.originalValues={},null!=t&&(this.parent=t,this.parentProperty=r);var i=e.complexType;if(!i){var a=e.prototype._$typeName;throw new Error(a?"Metadata for this complexType has not yet been resolved: "+a:"This entity is not registered as a valid ComplexType")}var o=i.getCtor();dt.getDefaultInstance().startTracking(e,o.prototype)},t=e.prototype;return t.getEntityAspect=function(){var e=this.parent;if(!e)return new St(null);for(var t=e.entityAspect;e&&!t;)e=e.complexAspect&&e.complexAspect.parent,t=e&&e.entityAspect;return t||new St(null)},t.getPropertyPath=function(e){var t=this.parent;if(!t)return null;var n=t.complexAspect||t.entityAspect;return n.getPropertyPath(this.parentProperty.name+"."+e)},e}();rt.EntityAspect=St,rt.ComplexAspect=Tt;var Pt=function(){function e(e){return e.join(t)}var t=":::",n=function(t,n){pt(t,"entityType").isInstanceOf(Ft).check();var r=t.getSelfAndSubtypes();r.length>1&&(this._subtypes=r.filter(function(e){return e.isAbstract===!1})),Array.isArray(n)||(n=at(arguments,1)),this.entityType=t,t.keyProperties.forEach(function(e,t){e.dataType===_t.Guid&&(n[t]=n[t]&&n[t].toLowerCase())}),this.values=n,this._keyInGroup=e(n)};n._$typeName="EntityKey";var r=n.prototype;return r.toJSON=function(){return{entityType:this.entityType.name,values:this.values}},n.fromJSON=function(e,t){var n=t._getEntityType(e.entityType,!0);return new Pt(n,e.values)},r.equals=function(e){return e instanceof Pt?this.entityType===e.entityType&&T(this.values,e.values):!1},r.toString=function(e){return(e||this.entityType).name+"-"+this._keyInGroup},n.equals=function(e,t){return e instanceof Pt?e.equals(t):!1},r._isEmpty=function(){return 0===this.values.join("").length},n.createKeyString=e,n}();rt.EntityKey=Pt;var Nt=function(){var e={isUnchanged:function(){return this===t.Unchanged},isAdded:function(){return this===t.Added},isModified:function(){return this===t.Modified},isDeleted:function(){return this===t.Deleted},isDetached:function(){return this===t.Detached},isUnchangedOrModified:function(){return this===t.Unchanged||this===t.Modified},isAddedModifiedOrDeleted:function(){return this===t.Added||this===t.Modified||this===t.Deleted}},t=new yt("EntityState",e);return t.Unchanged=t.addSymbol(),t.Added=t.addSymbol(),t.Modified=t.addSymbol(),t.Deleted=t.addSymbol(),t.Detached=t.addSymbol(),t.resolveSymbols(),t}();rt.EntityState=Nt,rt.makePrimitiveArray=function(){function e(e,n,r){return mt.initializeParent(e,n,r),e.arrayChanged=new ft("arrayChanged",e),p(e,mt.mixin),p(e,t)}var t={};return t._getGoodAdds=function(e){return e},t._beforeChange=function(){var e=this.getEntityAspect();e.entityState.isUnchanged()&&e.setModified(),e.entityState.isModified()&&!this._origValues&&(this._origValues=this.slice(0))},t._processAdds=function(){},t._processRemoves=function(){},t._rejectChanges=function(){this._origValues&&(this.length=0,Array.prototype.push.apply(this,this._origValues))},t._acceptChanges=function(){this._origValues=null},e}(),rt.makeRelationArray=function(){function e(e,t){var n=r(e,t);if(!n.length)return n;var i=e.parentEntity,a=i.entityAspect.entityManager;return a&&!a.isLoading&&n.forEach(function(t){if(t.entityAspect.entityState.isDetached()){e._inProgress=!0;try{a.attachEntity(t,Nt.Added)}finally{e._inProgress=!1}}}),n}function t(e,t){var n=e.parentEntity,r=e.navigationProperty,i=e._addsInProcess,a=r.inverse,o=i.length;try{t.forEach(function(e){if(i.push(e),a)e.setProperty(a.name,n);else{var t=n.entityType.keyProperties;r.invForeignKeyNames.forEach(function(r,i){e.setProperty(r,n.getProperty(t[i].name))})}})}finally{i.splice(o,t.length)}}function n(e,t){var n=e.navigationProperty.inverse;n&&t.forEach(function(e){e.setProperty(n.name,null)})}function r(e,t){var n,r=e.parentEntity,i=e.navigationProperty,a=i.inverse;if(a)n=t.filter(function(t){if(e._addsInProcess.indexOf(t)>=0)return!1;var n=t.getProperty(a.name);return n!==r});else{var o=i.invForeignKeyNames,s=r.entityType.keyProperties;n=t.filter(function(t){return e._addsInProcess.indexOf(t)>=0?!1:o.some(function(e,n){var i=s[n].name,a=r.getProperty(i),o=t.getProperty(e);return a!==o})})}return n}function i(e,t,n){return e.parentEntity=t,e.navigationProperty=n,e.arrayChanged=new ft("arrayChanged",e),e._addsInProcess=[],p(e,mt.mixin),p(e,a)}var a={};return a.load=function(e,t){var n=this.parentEntity,r=Lt.fromEntityNavigation(this.parentEntity,this.navigationProperty),i=n.entityAspect.entityManager;return i.executeQuery(r,e,t)},a._getEventParent=function(){return this.parentEntity.entityAspect},a._getPendingPubs=function(){var e=this.parentEntity.entityAspect.entityManager;return e&&e._pendingPubs},a._getGoodAdds=function(t){return e(this,t)},a._processAdds=function(e){t(this,e)},a._processRemoves=function(e){n(this,e)},i}();var _t=function(){function e(e,t){throw e=G(e,t),new Error(e)}function t(e){switch(e){case N.String:return vt.string;case N.Int64:return vt.int64;case N.Int32:return vt.int32;case N.Int16:return vt.int16;case N.Decimal:return vt.number;case N.Double:return vt.number;case N.Single:return vt.number;case N.DateTime:return vt.date;case N.DateTimeOffset:return vt.date;case N.Boolean:return vt.bool;case N.Guid:return vt.guid;case N.Byte:return vt.byte;case N.Binary:return vt.none;case N.Time:return vt.duration;case N.Undefined:return vt.none}}var n,r={},i=function(){n={stringPrefix:"K_",nextNumber:-1,nextNumberIncrement:-1}};i();var a=function(){return n.stringPrefix+o().toString()},o=function(){var e=n.nextNumber;return n.nextNumber+=n.nextNumberIncrement,e},s=function(){return C()},u=function(){return new Date},p=function(e){return null==e?e:e.toString()},c=function(e,t){if("string"===t){var n=e.trim();if(""===n)return null;var r=parseInt(n,10);return isNaN(r)?e:r}return"number"===t?Math.round(e):e},l=function(e,t){if("string"===t){var n=e.trim();if(""===n)return null;var r=parseFloat(n);return isNaN(r)?e:r}return e},y=function(e,t){var n;if("string"===t){var r=e.trim();return""===r?null:(n=new Date(Date.parse(r)),k(n)?n:e)}return"number"===t?(n=new Date(e),k(n)?n:e):e},f=function(e,t){if("string"===t){var n=e.trim().toLowerCase();return"false"===n||""===n?!1:"true"===n?!0:e}return e},h=function(e){return null==e?null:"'"+e.replace(/'/g,"''")+"'"},d=function(e){return null==e?null:"string"==typeof e?parseInt(e,10):e},m=function(e){return function(t){return null==t?null:("string"==typeof t&&(t=parseFloat(t)),t+e)}},v=function(t){if(null==t)return null;try{return"datetime'"+t.toISOString()+"'"}catch(n){e("'%1' is not a valid dateTime",t)}},g=function(t){if(null==t)return null;try{return"datetimeoffset'"+t.toISOString()+"'"}catch(n){e("'%1' is not a valid dateTime",t)}},w=function(t){return null==t?null:(L(t)||e("'%1' is not a valid ISO 8601 duration",t),"time'"+t+"'")},E=function(t){return null==t?null:(j(t)||e("'%1' is not a valid guid",t),"guid'"+t+"'")},S=function(e){return null==e?null:"string"==typeof e?"true"===e.trim().toLowerCase():!!e},T=function(e){return null==e?e:"binary'"+e+"'"},P=function(e){return e},N=new yt("DataType",r);N.String=N.addSymbol({defaultValue:"",parse:p,fmtOData:h,getNext:a}),N.Int64=N.addSymbol({defaultValue:0,isNumeric:!0,isInteger:!0,quoteJsonOData:!0,parse:c,fmtOData:m("L"),getNext:o}),N.Int32=N.addSymbol({defaultValue:0,isNumeric:!0,isInteger:!0,parse:c,fmtOData:d,getNext:o}),N.Int16=N.addSymbol({defaultValue:0,isNumeric:!0,isInteger:!0,parse:c,fmtOData:d,getNext:o}),N.Byte=N.addSymbol({defaultValue:0,isNumeric:!0,isInteger:!0,parse:c,fmtOData:d}),N.Decimal=N.addSymbol({defaultValue:0,isNumeric:!0,quoteJsonOData:!0,isFloat:!0,parse:l,fmtOData:m("m"),getNext:o}),N.Double=N.addSymbol({defaultValue:0,isNumeric:!0,isFloat:!0,parse:l,fmtOData:m("d"),getNext:o}),N.Single=N.addSymbol({defaultValue:0,isNumeric:!0,isFloat:!0,parse:l,fmtOData:m("f"),getNext:o}),N.DateTime=N.addSymbol({defaultValue:new Date(1900,0,1),isDate:!0,parse:y,fmtOData:v,getNext:u}),N.DateTimeOffset=N.addSymbol({defaultValue:new Date(1900,0,1),isDate:!0,parse:y,fmtOData:g,getNext:u}),N.Time=N.addSymbol({defaultValue:"PT0S",fmtOData:w}),N.Boolean=N.addSymbol({defaultValue:!1,parse:f,fmtOData:S}),N.Guid=N.addSymbol({defaultValue:"00000000-0000-0000-0000-000000000000",fmtOData:E,getNext:s}),N.Binary=N.addSymbol({defaultValue:null,fmtOData:T}),N.Undefined=N.addSymbol({defaultValue:void 0,fmtOData:P}),N.resolveSymbols(),N.getComparableFn=function(e){return e&&e.isDate?function(e){return e&&e.getTime()}:e===N.Time?function(e){return e&&x(e)}:function(e){return e}},N.fromEdmDataType=function(e){var t=null,n=e.split(".");if(n.length>1){var r=n[1];t="image"===r?N.Byte:2===n.length?N.fromName(r)||N.Undefined:N.String}return t},N.fromValue=function(e){if(k(e))return N.DateTime;switch(typeof e){case"string":return j(e)?N.Guid:L(e)&&e.length>3?N.Time:I(e)?N.DateTime:N.String;case"boolean":return N.Boolean;case"number":return N.Double}return N.Undefined};var _=/.\d{3}$/;return N.parseTimeFromServer=function(e){if("string"==typeof e)return e;if(e&&"Edm.Time"===e.__edmType){var t=Math.floor(e.ms/1e3);return"PT"+t+"S"}return e},N.parseDateAsUTC=function(e){if("string"==typeof e){var t=_.test(e);e=t?e+"Z":e}return e=new Date(Date.parse(e))},N.parseDateFromServer=N.parseDateAsUTC,N.parseRawValue=function(e,t){return void 0===e?void 0:(t.isDate&&e?k(e)||(e=N.parseDateFromServer(e)):t===N.Binary?e&&void 0!==e.$value&&(e=e.$value):t===N.Time&&(e=N.parseTimeFromServer(e)),e)},N.constants=n,N._resetConstants=i,N.getSymbols().forEach(function(e){e.validatorCtor=t(e)}),N}();rt.DataType=_t;var bt=function(){function e(e,t){return t&&(lt(t).whereParam("serviceName").isOptional().whereParam("adapterName").isString().isOptional().whereParam("uriBuilderName").isString().isOptional().whereParam("hasServerMetadata").isBoolean().isOptional().whereParam("jsonResultsAdapter").isInstanceOf(Ot).isOptional().whereParam("useJsonp").isBoolean().isOptional().applyAll(e),e.serviceName=e.serviceName&&bt._normalizeServiceName(e.serviceName),e.adapterInstance=e.adapterName&&ht.getAdapterInstance("dataService",e.adapterName),e.uriBuilder=e.uriBuilderName&&ht.getAdapterInstance("uriBuilder",e.uriBuilderName)),e}var t=function(t){e(this,t)},n=t.prototype;return n._$typeName="DataService",n.using=function(t){if(!t)return this;var n=new bt(this);return e(n,t)},t.resolve=function(e){e.push({hasServerMetadata:!0,useJsonp:!1});var t=new bt(h(e,["serviceName","adapterName","uriBuilderName","hasServerMetadata","jsonResultsAdapter","useJsonp"]));if(!t.serviceName)throw new Error("Unable to resolve a 'serviceName' for this dataService");return t.adapterInstance=t.adapterInstance||ht.getAdapterInstance("dataService",t.adapterName),t.jsonResultsAdapter=t.jsonResultsAdapter||t.adapterInstance.jsonResultsAdapter,t.uriBuilder=t.uriBuilder||ht.getAdapterInstance("uriBuilder",t.uriBuilderName),t},t._normalizeServiceName=function(e){return e=e.trim(),"/"!==e.substr(-1)?e+"/":e},n.toJSON=function(){return y(this,{serviceName:null,adapterName:null,uriBuilderName:null,hasServerMetadata:null,jsonResultsAdapter:function(e){return e&&e.name},useJsonp:null})},t.fromJSON=function(e){return e.jsonResultsAdapter=ht._fetchObject(Ot,e.jsonResultsAdapter),new bt(e)},n.qualifyUrl=function(e){var t=this.serviceName;return st.stringEndsWith(t,"/")&&(t=t.substr(0,t.length-1)),e="/"+e,st.stringEndsWith(t,e)||(t+=e),t},t}(),Ot=function(){function e(e){return e.results}var t=function(t){if(1!==arguments.length)throw new Error("The JsonResultsAdapter ctor should be called with a single argument that is a configuration object.");lt(t).whereParam("name").isNonEmptyString().whereParam("extractResults").isFunction().isOptional().withDefault(e).whereParam("visitNode").isFunction().applyAll(this),ht._storeObject(this,n._$typeName,this.name)},n=t.prototype;return n._$typeName="JsonResultsAdapter",t}();rt.DataService=bt,rt.JsonResultsAdapter=Ot;var At=_("Q");At||(At=function(){var e="Q is undefined. Are you missing Q.js? See https://github.com/kriskowal/q";throw new Error(e)},At.defer=At.resolve=At.reject=At),rt.config.setQ=function(e){rt.Q=At=e},rt.Q=At;var Ct=function(){function e(e){var t=[];for(var n in e){var r=e[n];n===r.name&&t.push(e[n])}return t}function t(e,t,n){var i=et(t.shortName,t.namespace),o=e._getEntityType(i,!0);if(o)return n?r(o,t):o;var s={shortName:t.shortName,namespace:t.namespace,isAbstract:t.isAbstract,autoGeneratedKeyType:It.fromName(t.autoGeneratedKeyType),defaultResourceName:t.defaultResourceName,custom:t.custom};if(o=t.isComplexType?new Mt(s):new Ft(s),t.baseTypeName){o.baseTypeName=t.baseTypeName;var u=e._getEntityType(t.baseTypeName,!0);u?a(e,t,o,u):P(e._deferredTypes,t.baseTypeName).push({json:t,stype:o})}else a(e,t,o);return o}function r(e,t){return t.custom&&(e.custom=t.custom),i(e,t.dataProperties),i(e,t.navigationProperties),e}function i(e,t){t&&t.forEach(function(t){var n=t.name;if(!n){if(!t.nameOnServer)throw new Error("Unable to complete 'importMetadata' - cannot locate a 'name' or 'nameOnServer' for one of the imported property nodes");n=e.metadataStore.namingConvention.serverPropertyNameToClient(t.nameOnServer,{})}if(t.custom){var r=e.getProperty(n,!0);r.custom=t.custom}})}function a(e,t,n){t.validators&&(n.validators=t.validators.map(vt.fromJSON)),t.dataProperties.forEach(function(e){n._addPropertyCore(Dt.fromJSON(e))});var r=!t.isComplexType;r&&t.navigationProperties&&t.navigationProperties.forEach(function(e){n._addPropertyCore(kt.fromJSON(e))}),e.addEntityType(n);var i=e._deferredTypes,o=i[n.name];o&&(o.forEach(function(t){a(e,t.json,t.stype)}),delete i[n.name])}function o(e,t,n){if(X(t))return t;var r=e._shortNameMap[t];if(!r&&n)throw new Error("Unable to locate 'entityTypeName' of: "+t);return r}var s=0,u=function(e){e=e||{},lt(e).whereParam("namingConvention").isOptional().isInstanceOf(Kt).withDefault(Kt.defaultInstance).whereParam("localQueryComparisonOptions").isOptional().isInstanceOf(Rt).withDefault(Rt.defaultInstance).whereParam("serializerFn").isOptional().isFunction().applyAll(this),this.dataServices=[],this._resourceEntityTypeMap={},this._structuralTypeMap={},this._shortNameMap={},this._ctorRegistry={},this._incompleteTypeMap={},this._incompleteComplexTypeMap={},this._id=s++,this.metadataFetched=new ft("metadataFetched",this)},c=u.prototype;return c._$typeName="MetadataStore",ft.bubbleEvent(c,null),u.ANONTYPE_PREFIX="_IB_",c.setProperties=function(e){lt(e).whereParam("name").isString().isOptional().whereParam("serializerFn").isFunction().isOptional().applyAll(this)},c.addDataService=function(e,t){pt(e,"dataService").isInstanceOf(bt).check(),pt(t,"shouldOverwrite").isBoolean().isOptional().check();var n=this._getDataServiceIndex(e.serviceName);if(n>=0){if(!t)throw new Error("A dataService with this name '"+e.serviceName+"' already exists in this MetadataStore");this.dataServices[n]=e}else this.dataServices.push(e)},c._getDataServiceIndex=function(e){return g(this.dataServices,function(t){return t.serviceName===e})},c.addEntityType=function(e){if(e instanceof Ft||e instanceof Mt||(e=e.isComplexType?new Mt(e):new Ft(e)),!e.isComplexType){if(e.baseTypeName&&!e.baseEntityType){var t=this._getEntityType(e.baseTypeName,!0);e._updateFromBase(t)}if(0===e.keyProperties.length&&!e.isAbstract)throw new Error("Unable to add "+e.name+" to this MetadataStore. An EntityType must have at least one property designated as a key property - See the 'DataProperty.isPartOfKey' property.")}if(e.metadataStore=this,!e.isAnonymous){if(this._structuralTypeMap[e.name])throw new Error("Type "+e.name+" already exists in this MetadataStore.");this._structuralTypeMap[e.name]=e,this._shortNameMap[e.shortName]=e.name}if(e.getProperties().forEach(function(t){e._updateNames(t),t.isUnmapped||e._mappedPropertiesCount++}),e._updateCps(),!e.isComplexType){e._updateNps();var n=e.defaultResourceName||e.baseEntityType&&e.baseEntityType.defaultResourceName;n&&!this.getEntityTypeNameForResourceName(n)&&this.setEntityTypeForResourceName(n,e.name),e.defaultResourceName=n,e.getEntityCtor()}},c.exportMetadata=function(){var e=JSON.stringify({metadataVersion:rt.metadataVersion,name:this.name,namingConvention:this.namingConvention.name,localQueryComparisonOptions:this.localQueryComparisonOptions.name,dataServices:this.dataServices,structuralTypes:n(this._structuralTypeMap),resourceEntityTypeMap:this._resourceEntityTypeMap},null,ht.stringifyPad);return e},c.importMetadata=function(e,n){pt(n,"allowMerge").isOptional().isBoolean().check(),this._deferredTypes={};var r="string"==typeof e?JSON.parse(e):e;if(r.schema)return xt.parse(this,r.schema,r.altMetadata);if(r.metadataVersion&&r.metadataVersion!==rt.metadataVersion){var i=G("Cannot import metadata with a different 'metadataVersion' (%1) than the current 'breeze.metadataVersion' (%2) ",r.metadataVersion,rt.metadataVersion);throw new Error(i)}var a=r.namingConvention,o=r.localQueryComparisonOptions;if(this.isEmpty())this.namingConvention=ht._fetchObject(Kt,a)||this.namingConvention,this.localQueryComparisonOptions=ht._fetchObject(Rt,o)||this.localQueryComparisonOptions;else{if(a&&this.namingConvention.name!==a)throw new Error("Cannot import metadata with a different 'namingConvention' from the current MetadataStore");if(o&&this.localQueryComparisonOptions.name!==o)throw new Error("Cannot import metadata with different 'localQueryComparisonOptions' from the current MetadataStore")}var s=this;r.dataServices&&r.dataServices.forEach(function(e){e=bt.fromJSON(e),s.addDataService(e,!0)});this._structuralTypeMap;return r.structuralTypes&&r.structuralTypes.forEach(function(e){t(s,e,n)}),p(this._resourceEntityTypeMap,r.resourceEntityTypeMap),p(this._incompleteTypeMap,r.incompleteTypeMap),this},u.importMetadata=function(e){var t=new Ct;return t.importMetadata(e),t},c.hasMetadataFor=function(e){return!!this.getDataService(e)},c.getDataService=function(e){return pt(e,"serviceName").isString().check(),e=bt._normalizeServiceName(e),v(this.dataServices,function(t){return t.serviceName===e})},c.fetchMetadata=function(e,t,n){try{if(pt(e,"dataService").isString().or().isInstanceOf(bt).check(),pt(t,"callback").isFunction().isOptional().check(),pt(n,"errorCallback").isFunction().isOptional().check(),"string"==typeof e&&(e=this.getDataService(e)||new bt({serviceName:e})),e=bt.resolve([e]),this.hasMetadataFor(e.serviceName))throw new Error("Metadata for a specific serviceName may only be fetched once per MetadataStore. ServiceName: "+e.serviceName);var r=this;return e.adapterInstance.fetchMetadata(this,e).then(function(n){return r.metadataFetched.publish({metadataStore:r,dataService:e,rawMetadata:n}),t&&t(n),At.resolve(n)},function(e){return n&&n(e),At.reject(e)})}catch(i){return At.reject(i)}},c.trackUnmappedType=function(e,t){pt(e,"entityCtor").isFunction().check(),pt(t,"interceptor").isFunction().isOptional().check();var n=new Ft(this);n._setCtor(e,t)},c.registerEntityTypeCtor=function(e,t,n,r){pt(e,"structuralTypeName").isString().check(),pt(t,"aCtor").isFunction().isOptional().check(),pt(n,"initFn").isOptional().isFunction().or().isString().check(),pt(r,"noTrackingFn").isOptional().isFunction().check();var i=o(this,e,!1),a=i||e;if(this._ctorRegistry[a]={ctor:t,initFn:n,noTrackingFn:r},i){var s=this._structuralTypeMap[i];s&&s.getCtor(!0)}},c.isEmpty=function(){return B(this._structuralTypeMap)},c.getEntityType=function(e,t){return pt(e,"structuralTypeName").isString().check(),pt(t,"okIfNotFound").isBoolean().isOptional().check(!1),this._getEntityType(e,t)},c._getEntityType=function(e,t){var n=o(this,e,!1),r=this._structuralTypeMap[n];if(!r){if(t)return null;var i=G("Unable to locate a 'Type' by the name: '%1'. Be sure to execute a query or call fetchMetadata first.",e);
throw new Error(i)}if(r.length){var a=r.join(",");throw new Error("There are multiple types with this 'shortName': "+a)}return r},c.getEntityTypes=function(){return e(this._structuralTypeMap)},c.getIncompleteNavigationProperties=function(){return n(this._incompleteTypeMap,function(e,t){return t})},c.getEntityTypeNameForResourceName=function(e){return pt(e,"resourceName").isString().check(),this._resourceEntityTypeMap[e]},c.setEntityTypeForResourceName=function(e,t){pt(e,"resourceName").isString().check(),pt(t,"entityTypeOrName").isInstanceOf(Ft).or().isString().check();var n;n=t instanceof Ft?t.name:o(this,t,!0),this._resourceEntityTypeMap[e]=n;var r=this._getEntityType(n,!0);r&&!r.defaultResourceName&&(r.defaultResourceName=e)},c._checkEntityType=function(e){if(!e.entityType){var t=e.prototype._$typeName;if(!t)throw new Error("This entity has not been registered. See the MetadataStore.registerEntityTypeCtor method");var n=this._getEntityType(t);n&&(e.entityType=n)}},u}(),xt=function(){function e(e,n,i){e._entityTypeResourceMap={},d(n).forEach(function(n){if(n.cSpaceOSpaceMapping){var i=JSON.parse(n.cSpaceOSpaceMapping),a={};i.forEach(function(e){a[e[0]]=e[1]}),n.cSpaceOSpaceMapping=a}n.entityContainer&&d(n.entityContainer).forEach(function(t){d(t.entitySet).forEach(function(t){var r=m(t.entityType,n).typeName;e.setEntityTypeForResourceName(t.name,r),e._entityTypeResourceMap[r]=t.name})}),n.complexType&&d(n.complexType).forEach(function(t){r(t,n,e)}),n.entityType&&d(n.entityType).forEach(function(r){t(r,n,e)})});var a=e.getIncompleteNavigationProperties();if(a.length>0){var o=a.map(function(e){return e.parentType.name+":"+e.name}).join(", ");throw new Error("Incomplete navigation properties: "+o)}return i&&e.importMetadata(i,!0),e}function t(e,t,r){var i=e.name,a=g(i,t),o=new Ft({shortName:i,namespace:a,isAbstract:e.abstract&&"true"===e.abstract});if(e.baseType){var s=m(e.baseType,t).typeName;o.baseTypeName=s;var u=r._getEntityType(s,!0);if(u)n(o,e,t,r);else{var p=r._deferredTypes[s];p||(p=[],r._deferredTypes[s]=p),p.push({entityType:o,csdlEntityType:e})}}else n(o,e,t,r);return o}function n(e,t,r,a){var o=t.key?d(t.key.propertyRef).map(s("name")):[];d(t.property).forEach(function(t){i(e,t,r,o)}),d(t.navigationProperty).forEach(function(t){u(e,t,r)}),a.addEntityType(e),e.defaultResourceName=a._entityTypeResourceMap[e.name];var p=a._deferredTypes,c=p[e.name];c&&(c.forEach(function(e){n(e.entityType,e.csdlEntityType,r,a)}),delete p[e.name])}function r(e,t,n){var r=e.name,a=g(r,t),o=new Mt({shortName:r,namespace:a});return d(e.property).forEach(function(e){i(o,e,t)}),n.addEntityType(o),o}function i(e,t,n,r){var i,s=t.type.split(".");return"Edm"===s[0]&&2===s.length?i=a(e,t,r):p(t,n)?(i=a(e,t,r),i&&(i.enumType=t.type)):i=o(e,t,n),i&&(e._addPropertyCore(i),y(i)),i}function a(e,t,n){var r=_t.fromEdmDataType(t.type);if(null==r)return e.warnings.push("Unable to recognize DataType for property: "+t.name+" DateType: "+t.type),null;var i="true"===t.nullable||null==t.nullable,a=null!=n&&n.indexOf(t.name)>=0;a&&e.autoGeneratedKeyType===It.None&&f(t)&&(e.autoGeneratedKeyType=It.Identity);var o=t.maxLength;o=null==o||"Max"===o?null:parseInt(o,10);var s=new Dt({nameOnServer:t.name,dataType:r,isNullable:i,isPartOfKey:a,maxLength:o,defaultValue:t.defaultValue,concurrencyMode:t.concurrencyMode});return r===_t.Undefined&&(s.rawTypeName=t.type),s}function o(e,t,n){var r=m(t.type,n).typeName,i=new Dt({nameOnServer:t.name,complexTypeName:r,isNullable:!1});return i}function u(e,t,n){var r=h(t,n),i=v(r.end,function(e){return e.role===t.toRole}),a="*"!==i.multiplicity,o=m(i.type,n).typeName,u=r.referentialConstraint;if(u||"*"!=r.end[0].multiplicity||"*"!=r.end[1].multiplicity){var p={nameOnServer:t.name,entityTypeName:o,isScalar:a,associationName:r.name};if(u){var c=u.principal,l=u.dependent,y=d(l.propertyRef),f=y.map(s("name"));t.fromRole===c.role?p.invForeignKeyNamesOnServer=f:p.foreignKeyNamesOnServer=f}var g=new kt(p);return e._addPropertyCore(g),g}}function p(e,t){return t.enumType?c(e,t):t.extensions?l(e,t):!1}function c(e,t){var n=d(t.enumType),r=e.type.split("."),i=r[r.length-1];return n.some(function(e){return e.name===i})}function l(e,t){var n=t.extensions.filter(function(e){return"EnumType"===e.name}),r=e.type.split("."),i=r[r.length-1];return n.some(function(e){return e.attributes.some(function(e){return"Name"===e.name&&e.value===i})})}function y(e){var t;if(e.isNullable||e.validators.push(vt.required()),!e.isComplexProperty){if(e.dataType===_t.String)if(e.maxLength){var n={maxLength:e.maxLength};t=vt.maxLength(n)}else t=vt.string();else t=e.dataType.validatorCtor();e.validators.push(t)}}function f(e){var t=v(Object.keys(e),function(e){return e.indexOf("StoreGeneratedPattern")>=0});if(t)return"Identity"===e[t];var n=e.extensions;if(!n)return!1;var r=v(n,function(e){return"StoreGeneratedPattern"===e.name&&"Identity"===e.value});return!!r}function h(e,t){var n=m(e.relationship,t).shortTypeName,r=t.association;if(!r)return null;Array.isArray(r)||(r=[r]);var i=v(r,function(e){return e.name===n});return i}function m(e,t){if(!e)return null;if(z(e,Ct.ANONTYPE_PREFIX))return{shortTypeName:e,namespace:"",typeName:e,isAnonymous:!0};var n=e.split(",")[0],r=n.split(".");if(r.length>1){var i=r[r.length-1],a=null;if(t&&(a=g(i,t)),!a){var o=r.slice(0,r.length-1);a=o.join(".")}return{shortTypeName:i,namespace:a,typeName:et(i,a)}}return{shortTypeName:e,namespace:"",typeName:e}}function g(e,t){var n,r=t.cSpaceOSpaceMapping;if(r){var i=r[t.namespace+"."+e];if(n=i&&i.substr(0,i.length-(e.length+1)))return n}return t.entityType||"Default"!=t.namespace?t.namespace:null}var w=A(function(e){return e&&m(e).typeName});return{parse:e,normalizeTypeName:w}}(),Ft=function(){function e(e,t){return e.entityAspect||e.complexAspect?e.getProperty(t.name):e[t.name]}function t(e){var t=e.name.replace(/\W/g,"_");return Function("return function "+t+"(){}")()}function n(e){return e.filter(function(e){return null==e.baseProperty})}function r(e,t,n){var r=n+"OnServer",i=t[n];if(i&&i.length){var a=d(i).map(function(n){var r=e.clientPropertyNameToServer(n,t),i=e.serverPropertyNameToClient(r,t);if(n!==i)throw new Error("NamingConvention for this client property name does not roundtrip properly:"+n+"-->"+i);return r});t[r]=Array.isArray(i)?a:a[0]}else{var o=t[r];if(!o||0===o.length)return;var s=d(o).map(function(n){var r=e.serverPropertyNameToClient(n,t),i=e.clientPropertyNameToServer(r,t);if(n!==i)throw new Error("NamingConvention for this server property name does not roundtrip properly:"+n+"-->"+i);return r});t[n]=Array.isArray(o)?s:s[0]}}function a(e,t){var n=t._getEntityType(e.complexTypeName,!0);if(!n)return!1;if(!(n instanceof Mt))throw new Error("Unable to resolve ComplexType with the name: "+e.complexTypeName+" for the property: "+property.name);return e.dataType=n,e.defaultValue=null,!0}function u(e,t){if(e.entityType)return!0;var n=t._getEntityType(e.entityTypeName,!0);if(n)e.entityType=n,e._resolveNp();else{var r=P(t._incompleteTypeMap,e.entityTypeName);w(r,e)}return!!n}function p(e,t){var n=e.getPropertyNames(),r=dt.getDefaultInstance(),a=r.getTrackablePropertyNames(t);a.forEach(function(r){if(-1===n.indexOf(r)){var a=t[r];try{"function"==typeof a&&(a=a())}catch(o){}var s=_t.fromValue(a),u=new Dt({name:r,dataType:s,isNullable:!0,isUnmapped:!0});u.isSettable=i(t,r),e.subtypes?e.getSelfAndSubtypes().forEach(function(e){e._addPropertyCore(new Dt(u))}):e._addPropertyCore(u)}})}var c=0,l=function(e){if(arguments.length>1)throw new Error("The EntityType ctor has a single argument that is either a 'MetadataStore' or a configuration object.");"MetadataStore"===e._$typeName?(this.metadataStore=e,this.shortName="Anon_"+ ++c,this.namespace="",this.isAnonymous=!0):lt(e).whereParam("shortName").isNonEmptyString().whereParam("namespace").isString().isOptional().withDefault("").whereParam("baseTypeName").isString().isOptional().whereParam("isAbstract").isBoolean().isOptional().withDefault(!1).whereParam("autoGeneratedKeyType").isEnumOf(It).isOptional().withDefault(It.None).whereParam("defaultResourceName").isNonEmptyString().isOptional().withDefault(null).whereParam("dataProperties").isOptional().whereParam("navigationProperties").isOptional().whereParam("serializerFn").isOptional().isFunction().whereParam("custom").isOptional().applyAll(this),this.name=et(this.shortName,this.namespace),this.dataProperties=[],this.navigationProperties=[],this.complexProperties=[],this.keyProperties=[],this.foreignKeyProperties=[],this.inverseForeignKeyProperties=[],this.concurrencyProperties=[],this.unmappedProperties=[],this.validators=[],this.warnings=[],this._mappedPropertiesCount=0,this.subtypes=[],tt(this,e.dataProperties,Dt),tt(this,e.navigationProperties,kt)},f=l.prototype,h=_t.parseRawValue;return f._$typeName="EntityType",l.qualifyTypeName=et,f.setProperties=function(e){lt(e).whereParam("autoGeneratedKeyType").isEnumOf(It).isOptional().whereParam("defaultResourceName").isString().isOptional().whereParam("serializerFn").isFunction().isOptional().whereParam("custom").isOptional().applyAll(this),e.defaultResourceName&&(this.defaultResourceName=e.defaultResourceName)},f.isSubtypeOf=function(e){pt(e,"entityType").isInstanceOf(Ft).check();var t=this;do{if(t===e)return!0;t=t.baseEntityType}while(t);return!1},f.getSelfAndSubtypes=function(){var e=[this];return this.subtypes.forEach(function(t){var n=t.getSelfAndSubtypes();e.push.apply(e,n)}),e},f.getAllValidators=function(){for(var e=this.validators.slice(0),t=this.baseEntityType;t;)e.push.apply(e,t.validators),t=t.baseEntityType;return e},f.addProperty=function(e){return pt(e,"property").isInstanceOf(Dt).or().isInstanceOf(kt).check(),this._addPropertyCore(e,!0)},f._updateFromBase=function(e){this.baseEntityType=e,this.autoGeneratedKeyType===It.None&&(this.autoGeneratedKeyType=e.autoGeneratedKeyType),e.dataProperties.forEach(function(e){var t=new Dt(e);t.validators=[],t.baseProperty=e,this._addPropertyCore(t)},this),e.navigationProperties.forEach(function(e){var t=new kt(e);t.validators=[],t.baseProperty=e,this._addPropertyCore(t)},this),e.subtypes.push(this)},f._addPropertyCore=function(e,t){if(this.isFrozen)throw new Error("The '"+this.name+"' EntityType/ComplexType has been frozen. You can only add properties to an EntityType/ComplexType before any instances of that type have been created and attached to an entityManager.");var n=e.parentType;if(n){if(n!==this)throw new Error("This property: "+e.name+" has already been added to "+e.parentType.name);return this}e.parentType=this;var i=this.metadataStore;return e.isDataProperty?this._addDataProperty(e):(this._addNavigationProperty(e),t&&i&&u(e,i)),!i||e.name&&e.nameOnServer||r(i.namingConvention,e,"name"),this},f.createEntity=function(t){if(t&&t._$eref&&!t._$eref.entityAspect.entityManager)return t._$eref;var n=this._createInstanceCore();return t&&(this.keyProperties.every(function(e){return null!=t[e.name]})&&(t._$eref=n),this._updateTargetFromRaw(n,t,e),this.navigationProperties.forEach(function(e){var r,i=t[e.name];if(void 0!=i){var a=e.entityType;if(e.isScalar)r=i.entityAspect?i:a.createEntity(i),n.setProperty(e.name,r);else{var o=n.getProperty(e.name);i.forEach(function(e){r=e.entityAspect?e:a.createEntity(e),o.push(r)})}}})),this._initializeInstance(n),n},f._createInstanceCore=function(){var e=this.getEntityCtor(),t=new e;return new St(t),t},f._initializeInstance=function(e){this.baseEntityType&&this.baseEntityType._initializeInstance(e);var t=this.initFn;t&&("string"==typeof t&&(t=e[t]),t(e)),this.complexProperties&&this.complexProperties.forEach(function(t){var n=e.getProperty(t.name);Array.isArray(n)?n.forEach(function(e){t.dataType._initializeInstance(e)}):t.dataType._initializeInstance(n)}),e.entityAspect&&(e.entityAspect._initialized=!0)},f.getCtor=f.getEntityCtor=function(e){if(this._ctor&&!e)return this._ctor;var n=this.metadataStore._ctorRegistry,r=n[this.name]||n[this.shortName]||{},i=r.ctor||this._ctor,a=i&&i.prototype&&(i.prototype.entityType||i.prototype.complexType);if(a&&a.metadataStore!==this.metadataStore)throw new Error("Cannot register the same constructor for "+this.name+" in different metadata stores. Please define a separate constructor for each metadata store.");if(r.ctor&&e&&(this._extra=void 0),!i){var o=dt.getDefaultInstance().createCtor;i=o?o(this):t(this)}return this.initFn=r.initFn,this.noTrackingFn=r.noTrackingFn,i.prototype._$typeName=this.name,this._setCtor(i),i},f._setCtor=function(e,t){var n=e.prototype;this._extra=this._extra||{};var r=new e;p(this,r),"EntityType"===this._$typeName?n.entityType=this:n.complexType=this,n._$interceptor=t||J,dt.getDefaultInstance().initializeEntityPrototype(n),this._ctor=e},f.addValidator=function(e,t){pt(e,"validator").isInstanceOf(vt).check(),pt(t,"property").isOptional().isString().or().isEntityProperty().check(),t?("string"==typeof t&&(t=this.getProperty(t,!0)),t.validators.push(e)):this.validators.push(e)},f.getProperties=function(){return this.dataProperties.concat(this.navigationProperties)},f.getPropertyNames=function(){return this.getProperties().map(s("name"))},f.getDataProperty=function(e){return v(this.dataProperties,o("name",e))},f.getNavigationProperty=function(e){return v(this.navigationProperties,o("name",e))},f.getProperty=function(e,t){var n=this.getPropertiesOnPath(e,!1,t);return n?n[n.length-1]:null},f.getPropertiesOnPath=function(e,t,n){n=n||!1;var r=Array.isArray(e)?e:e.trim().split("."),i=!0,a=this,s=t?"nameOnServer":"name",u=r.map(function(e){var t=v(a.getProperties(),o(s,e));if(t)a=t.isNavigationProperty?t.entityType:t.dataType;else{if(n)throw new Error("unable to locate property: "+e+" on entityType: "+a.name);i=!1}return t});return i?u:null},f.clientPropertyPathToServer=function(e,t){var n,t=t||".";if(this.isAnonymous){var r=this.metadataStore.namingConvention.clientPropertyNameToServer;n=e.split(".").map(function(e){return r(e)})}else n=this.getPropertiesOnPath(e,!1,!0).map(function(e){return e.nameOnServer});return n.join(t)},f.getEntityKeyFromRawEntity=function(e,t){var n=this.keyProperties.map(function(n){var r=t(e,n);return h(r,n.dataType)});return new Pt(this,n)},f._updateTargetFromRaw=function(e,t,n){this.dataProperties.forEach(function(r){if(r.isSettable){var i=n(t,r);if(void 0!==i){var a,o=r.dataType;if(r.isComplexProperty){if(null===i)return;a=e.getProperty(r.name),r.isScalar?o._updateTargetFromRaw(a,i,n):(a.length=0,Array.isArray(i)&&i.forEach(function(t){var i=o._createInstanceCore(e,r);o._updateTargetFromRaw(i,t,n),o._initializeInstance(i),a.push(i)}))}else{var s;r.isScalar?(s=h(i,o),e.setProperty(r.name,s)):(a=e.getProperty(r.name),a.length=0,Array.isArray(i)&&i.forEach(function(e){s=h(e,o),a.push(s)}))}}}});var r=t.entityAspect||t.complexAspect;if(r){var i=e.entityAspect||e.complexAspect;r.originalValuesMap&&(i.originalValues=r.originalValuesMap),r.extraMetadata&&(i.extraMetadata=r.extraMetadata)}},f.toString=function(){return this.name},f.toJSON=function(){return y(this,{shortName:null,namespace:null,baseTypeName:null,isAbstract:!1,autoGeneratedKeyType:null,defaultResourceName:null,dataProperties:n,navigationProperties:n,validators:null,custom:null})},f._updateNames=function(e){var t=this.metadataStore.namingConvention;r(t,e,"name"),e.isNavigationProperty&&(r(t,e,"foreignKeyNames"),r(t,e,"invForeignKeyNames"))},f._checkNavProperty=function(e){if(e.isNavigationProperty){if(e.parentType!==this)throw new Error(G("The navigationProperty '%1' is not a property of entity type '%2'",e.name,this.name));return e}if("string"==typeof e){var t=this.getProperty(e);if(t&&t.isNavigationProperty)return t}throw new Error("The 'navigationProperty' parameter must either be a NavigationProperty or the name of a NavigationProperty")},f._addDataProperty=function(e){this.dataProperties.push(e),e.isPartOfKey&&this.keyProperties.push(e),e.isComplexProperty&&this.complexProperties.push(e),e.concurrencyMode&&"None"!==e.concurrencyMode&&this.concurrencyProperties.push(e),e.isUnmapped&&this.unmappedProperties.push(e)},f._addNavigationProperty=function(e){this.navigationProperties.push(e),X(e.entityTypeName)||(e.entityTypeName=et(e.entityTypeName,this.namespace))},f._updateCps=function(){var e=this.metadataStore,t=e._incompleteComplexTypeMap;this.complexProperties.forEach(function(n){n.complexType||a(n,e)||P(t,n.complexTypeName).push(n)}),this.isComplexType&&((t[this.name]||[]).forEach(function(t){a(t,e)}),delete t[this.name])},f._updateNps=function(){var e=this.metadataStore;this.navigationProperties.forEach(function(t){u(t,e)});var t=e._incompleteTypeMap;(t[this.name]||[]).forEach(function(t){u(t,e)}),delete t[this.name]},l}(),Mt=function(){var e=function(e){if(arguments.length>1)throw new Error("The ComplexType ctor has a single argument that is a configuration object.");lt(e).whereParam("shortName").isNonEmptyString().whereParam("namespace").isString().isOptional().withDefault("").whereParam("dataProperties").isOptional().whereParam("isComplexType").isOptional().isBoolean().whereParam("custom").isOptional().applyAll(this),this.name=et(this.shortName,this.namespace),this.isComplexType=!0,this.dataProperties=[],this.complexProperties=[],this.validators=[],this.concurrencyProperties=[],this.unmappedProperties=[],this.navigationProperties=[],this.keyProperties=[],tt(this,e.dataProperties,Dt)},t=e.prototype;return t.setProperties=function(e){lt(e).whereParam("custom").isOptional().applyAll(this)},t.getAllValidators=function(){return this.validators},t._createInstanceCore=function(e,t){var n=this.getCtor(),r=new n;return new Tt(r,e,t),r},t.addProperty=function(e){return pt(e,"dataProperty").isInstanceOf(Dt).check(),this._addPropertyCore(e)},t.getProperties=function(){return this.dataProperties},t=p(t,Ft.prototype,["addValidator","getProperty","getPropertiesOnPath","getPropertyNames","_addPropertyCore","_addDataProperty","_updateNames","_updateCps","_initializeInstance","_updateTargetFromRaw","_setCtor"]),t.createInstance=Ft.prototype.createEntity,t.getCtor=Ft.prototype.getEntityCtor,t.toJSON=function(){return y(this,{shortName:null,namespace:null,isComplexType:null,dataProperties:null,validators:null,custom:null})},t._$typeName="ComplexType",e}(),Dt=function(){var e=function(e){lt(e).whereParam("name").isString().isOptional().whereParam("nameOnServer").isString().isOptional().whereParam("dataType").isEnumOf(_t).isOptional().or().isString().or().isInstanceOf(Mt).whereParam("complexTypeName").isOptional().whereParam("isNullable").isBoolean().isOptional().withDefault(!0).whereParam("isScalar").isOptional().withDefault(!0).whereParam("defaultValue").isOptional().whereParam("isPartOfKey").isBoolean().isOptional().whereParam("isUnmapped").isBoolean().isOptional().whereParam("isSettable").isBoolean().isOptional().withDefault(!0).whereParam("concurrencyMode").isString().isOptional().whereParam("maxLength").isNumber().isOptional().whereParam("validators").isInstanceOf(vt).isArray().isOptional().withDefault([]).whereParam("displayName").isOptional().whereParam("enumType").isOptional().whereParam("rawTypeName").isOptional().whereParam("custom").isOptional().applyAll(this);var t=!(!this.name&&!this.nameOnServer);if(!t)throw new Error("A DataProperty must be instantiated with either a 'name' or a 'nameOnServer' property");if(this.complexTypeName)this.isComplexProperty=!0,this.dataType=null;else if("string"==typeof this.dataType){var n=_t.fromName(this.dataType);if(!n)throw new Error("Unable to find a DataType enumeration by the name of: "+this.dataType);this.dataType=n}else this.dataType||(this.dataType=_t.String);if(null==this.defaultValue){if(this.isNullable)this.defaultValue=null;else if(this.isComplexProperty);else if(this.dataType===_t.Binary)this.defaultValue="AAAAAAAAJ3U=";else if(this.defaultValue=this.dataType.defaultValue,null==this.defaultValue)throw new Error("A nonnullable DataProperty cannot have a null defaultValue. Name: "+(this.name||this.nameOnServer))}else this.dataType.isNumeric&&"string"==typeof this.defaultValue&&(this.defaultValue=parseFloat(this.defaultValue));this.isComplexProperty&&(this.isScalar=null==this.isScalar||this.isScalar===!0)},t=e.prototype;return t._$typeName="DataProperty",e.getRawValueFromServer=function(e,t){if(t.isUnmapped)return e[t.nameOnServer||t.name];var n=e[t.nameOnServer];return void 0!==n?n:t.defaultValue},e.getRawValueFromClient=function(e,t){var n=e[t.name];return void 0!==n?n:t.defaultValue},t.isDataProperty=!0,t.isNavigationProperty=!1,t.resolveProperty=function(e){for(var t=this[e],n=this.baseProperty;void 0==t&&null!=n;)t=n[e],n=n.baseProperty;return t},t.formatName=function(){return this.parentType.name+"--"+this.name},t.setProperties=function(e){lt(e).whereParam("displayName").isOptional().whereParam("custom").isOptional().applyAll(this)},t.getAllValidators=function(){for(var e=this.validators.slice(0),t=this.baseProperty;t;)e.push.apply(e,t.validators),t=t.baseProperty;return e},t.toJSON=function(){return y(this,{name:null,dataType:function(e){return e&&e.parentEnum?e.name:void 0},complexTypeName:null,isNullable:!0,defaultValue:null,isPartOfKey:!1,isUnmapped:!1,isSettable:!0,concurrencyMode:null,maxLength:null,validators:null,displayName:null,enumType:null,rawTypeName:null,isScalar:!0,custom:null})},e.fromJSON=function(e){return e.dataType=_t.fromName(e.dataType),e.defaultValue&&e.dataType&&e.dataType.isDate&&(e.defaultValue=new Date(Date.parse(e.defaultValue))),e.validators&&(e.validators=e.validators.map(vt.fromJSON)),new Dt(e)},e}(),kt=function(){function e(e,t){throw new Error("Cannot set the inverse property for: "+e.formatName()+". "+t)}function t(e,t){throw new Error("Cannot create inverse for: "+e.formatName()+". The entityType for this navigation property "+t)}function n(e){var t=e.foreignKeyNames;if(0!==t.length){var n=e.parentType,r=t.map(function(e){return n.getDataProperty(e)}),i=n.foreignKeyProperties;r.forEach(function(t){w(i,t),t.relatedNavigationProperty=e,w(e.entityType.inverseForeignKeyProperties,t),e.relatedDataProperties?w(e.relatedDataProperties,t):e.relatedDataProperties=[t]})}}var r=function(e){lt(e).whereParam("name").isString().isOptional().whereParam("nameOnServer").isString().isOptional().whereParam("entityTypeName").isString().whereParam("isScalar").isBoolean().isOptional().withDefault(!0).whereParam("associationName").isString().isOptional().whereParam("foreignKeyNames").isArray().isString().isOptional().withDefault([]).whereParam("foreignKeyNamesOnServer").isArray().isString().isOptional().withDefault([]).whereParam("invForeignKeyNames").isArray().isString().isOptional().withDefault([]).whereParam("invForeignKeyNamesOnServer").isArray().isString().isOptional().withDefault([]).whereParam("validators").isInstanceOf(vt).isArray().isOptional().withDefault([]).whereParam("displayName").isOptional().whereParam("custom").isOptional().applyAll(this);var t=!(!this.name&&!this.nameOnServer);if(!t)throw new Error("A Navigation property must be instantiated with either a 'name' or a 'nameOnServer' property")},i=r.prototype;return i._$typeName="NavigationProperty",i.isDataProperty=!1,i.isNavigationProperty=!0,p(i,Dt.prototype,["formatName","getAllValidators","resolveProperty"]),i.setProperties=function(e){if(!this.parentType)throw new Error("Cannot call NavigationProperty.setProperties until the parent EntityType of the NavigationProperty has been set.");var t=e.inverse;t&&delete e.inverse,lt(e).whereParam("displayName").isOptional().whereParam("foreignKeyNames").isArray().isString().isOptional().withDefault([]).whereParam("invForeignKeyNames").isArray().isString().isOptional().withDefault([]).whereParam("custom").isOptional().applyAll(this),this.parentType._updateNames(this),this._resolveNp(),t&&this.setInverse(t)},i.setInverse=function(t){var n;if(n="string"==typeof t?this.entityType.getNavigationProperty(t):t,!n)throw e(this,"Unable to find inverse property: "+invNpName);(this.inverse||n.inverse)&&e(this,"It has already been set on one side or the other."),n.entityType!=this.parentType&&e(this,n.formatName+" is not a valid inverse property for this."),this.associationName?n.associationName=this.associationName:(n.associationName||(n.associationName=this.formatName()+"_"+n.formatName()),this.associationName=n.associationName),this._resolveNp(),n._resolveNp()},i.createInverse=function(e){this.entityType||t(this,"has not yet been defined."),this.entityType.isFrozen&&t(this,"is frozen.");var n=this.entityType.metadataStore;null==n&&t(this,"has not yet been added to the metadataStore."),e.entityTypeName=this.parentEntityType.name,e.associationName=this.associationName;var r=new kt(e);return this.parentEntityType.addNavigationProperty(r),r},i.toJSON=function(){return y(this,{name:null,entityTypeName:null,isScalar:null,associationName:null,validators:null,displayName:null,foreignKeyNames:null,invForeignKeyNames:null,custom:null})},r.fromJSON=function(e){return e.validators&&(e.validators=e.validators.map(vt.fromJSON)),new kt(e)},i._resolveNp=function(){var e=this,t=e.entityType,r=v(t.navigationProperties,function(t){return t.associationName===e.associationName&&(t.name!==e.name||t.entityTypeName!==e.entityTypeName)});e.inverse=r,r||e.invForeignKeyNames.forEach(function(n){var r=t.getDataProperty(n);if(!r)throw new Error("EntityType '"+e.entityTypeName+"' has no foreign key matching '"+n+"'");var i=e.parentType;r.inverseNavigationProperty=v(i.navigationProperties,function(e){return e.invForeignKeyNames&&e.invForeignKeyNames.indexOf(r.name)>=0&&e.entityType===r.parentType}),w(t.foreignKeyProperties,r)}),n(e)},r}(),It=function(){var e=new yt("AutoGeneratedKeyType");return e.None=e.addSymbol(),e.Identity=e.addSymbol(),e.KeyGenerator=e.addSymbol(),e.resolveSymbols(),e}();!function(){function e(e,t){return null==t?!1:void 0!==t.entityType}function t(e,t){return null==t?!1:t.isDataProperty||t.isNavigationProperty}var n=ut.prototype;n.isEntity=function(){return this._addContext({fn:e,msg:" must be an entity"})},n.isEntityProperty=function(){return this._addContext({fn:t,msg:" must be either a DataProperty or a NavigationProperty"})}}(),rt.MetadataStore=Ct,rt.EntityType=Ft,rt.ComplexType=Mt,rt.DataProperty=Dt,rt.NavigationProperty=kt,rt.AutoGeneratedKeyType=It,Ct.normalizeTypeName=xt.normalizeTypeName;var Vt=function(){function e(e,t,n){var r=t.name+".."+t.parentType.name,i=e._tempIdMap[r];return i||n&&(i={entityType:t.parentType,propertyName:t.name,keyMap:{}},e._tempIdMap[r]=i),i}var t=function(){this._tempIdMap={}},n=t.prototype;return n.generateTempKeyValue=function(t,n){var r=t.keyProperties;if(r.length>1)throw new Error("Ids can not be autogenerated for entities with multipart keys");var i,a=r[0],o=e(this,a,!0);if(null!=n&&(o.keyMap[n.toString()]||(i=n)),void 0===i){var s=a.dataType;if(!s.getNext)throw new Error("Cannot use a property with a dataType of: "+s.toString()+" for id generation");for(i=s.getNext(this);null!=o.keyMap[i.toString()];)i=s.getNext(this)}return o.keyMap[i.toString()]=!0,i},n.getTempKeys=function(){var e=[];for(var t in this._tempIdMap){var n=this._tempIdMap[t],r=n.entityType;for(var i in n.keyMap)e.push(new Pt(r,[i]))}return e},n.isTempKey=function(t){var n=t.entityType.keyProperties;if(n.length>1)return!1;var r=n[0],i=e(this,r);return i?void 0!==i.keyMap[t.values[0].toString()]:!1},ht.registerType(t,"KeyGenerator"),t}();rt.KeyGenerator=Vt;var Rt=function(){var e=function(e){lt(e||{}).whereParam("name").isOptional().isString().whereParam("isCaseSensitive").isOptional().isBoolean().whereParam("usesSql92CompliantStringComparison").isBoolean().applyAll(this),this.name||(this.name=C()),ht._storeObject(this,t._$typeName,this.name)},t=e.prototype;return t._$typeName="LocalQueryComparisonOptions",e.caseInsensitiveSQL=new e({name:"caseInsensitiveSQL",isCaseSensitive:!1,usesSql92CompliantStringComparison:!0}),e.defaultInstance=new e(e.caseInsensitiveSQL),t.setAsDefault=function(){return l(this,e)},e}();rt.LocalQueryComparisonOptions=Rt;var Kt=function(){var e=function(e){lt(e||{}).whereParam("name").isOptional().isString().whereParam("serverPropertyNameToClient").isFunction().whereParam("clientPropertyNameToServer").isFunction().applyAll(this),this.name||(this.name=C()),ht._storeObject(this,t._$typeName,this.name)},t=e.prototype;return t._$typeName="NamingConvention",e.none=new e({name:"noChange",serverPropertyNameToClient:function(e){return e},clientPropertyNameToServer:function(e){return e}}),e.camelCase=new e({name:"camelCase",serverPropertyNameToClient:function(e){return e.substr(0,1).toLowerCase()+e.substr(1)},clientPropertyNameToServer:function(e){return e.substr(0,1).toUpperCase()+e.substr(1)}}),e.defaultInstance=new e(e.none),t.setAsDefault=function(){return l(this,e)},e}();rt.NamingConvention=Kt;var jt=function(){function e(e,r){var i=r.entityType;if(Array.isArray(e)){if(!r.isRHS)throw new Error("Array expressions are only permitted on the right hand side of a BinaryPredicate");return new y(e,r.dataType)}if(!R(e)){if(null!=e&&K(e)&&!k(e)){if(void 0===e.value)throw new Error("Unable to resolve an expression for: "+e+" on entityType: "+i.name);return e.isProperty?new f(e.value):new y(e.value,e.dataType||r.dataType,!0)}return new y(e,r.dataType)}if(r.isRHS)return null==i||i.isAnonymous?new y(e,r.dataType):n(e,r);for(var a,o=/\([^()]*\)/,s=[],u=0;a=o.exec(e);){var p=a[0];s.push(p);var c=g+u++;e=e.replace(p,c)}var l=t(e,s,r);return l._validate(i,r.usesNameOnServer),l}function t(e,t,i){var a=e.split(g);return 1===a.length?n(a[0],i):r(e,a,t,i)}function n(e,t){e=e.trim();var n=e.substr(0,1),r=("'"===n||'"'===n)&&e.length>1&&e.substr(e.length-1)===n;if(r){var i=e.substr(1,e.length-2);return new y(i,t.dataType||_t.String)}var a=t.entityType;if(null==a||a.isAnonymous)return new f(e);var o=d.test(e);return o&&null!=a.getPropertiesOnPath(e,t.usesNameOnServer,!1)?new f(e):new y(e,t.dataType)}function r(e,n,r,i){try{var a=n[0].trim().toLowerCase(),o=r[n[1]].trim();"("===o.substr(0,1)&&(o=o.substr(1,o.length-2));var s=e.indexOf("'")>=0?m:v,u=o.match(s),c=p({},i);c.dataType=_t.Undefined,c.isFnArg=!0;var l=u.map(function(e){return t(e,r,c)});return new h(a,l)}catch(y){return null}}var i=function(){function e(e,t,n){var r=t.toLowerCase();n.key=r,e[r]=n,n.aliases&&n.aliases.forEach(function(t){e[t.toLowerCase()]=n})}function t(e){var r={},i={};r[e[0]]=i;var a=e[1];return a=a.operator||a,i[a]=3==e.length?e[2]:t(e.splice(2)),n(r)}function n(e){if(e instanceof i)return e;if("object"!=typeof e)throw new Error("Unable to convert to a Predicate: "+e);var t=Object.keys(e),n=t.map(function(t){return r(t,e[t])});return 1===n.length?n[0]:new u("and",n)}function r(e,t){if(u.prototype._resolveOp(e,!0))return new u(e,t);if(o.prototype._resolveOp(e,!0))return new o(e,t);if("object"!=typeof t||null==t||k(t))return new s("eq",e,t);if(it(t,"value"))return new s("eq",e,t);if(Array.isArray(t))throw new Error("Unable to resolve predicate after the phrase: "+e);var n=e,r=Object.keys(t),i=r.map(function(e){if(c.prototype._resolveOp(e,!0))return new c(e,n,t[e]);if(s.prototype._resolveOp(e,!0))return new s(e,n,t[e]);if(it(t[e],"value"))return new s("eq",n,t[e]);var r=G("Unable to resolve predicate after the phrase: '%1' for operator: '%2' and value: '%3'",n,e,t[e]);throw new Error(r)});return 1===i.length?i[0]:new u("and",i)}var p=function(){if(0!==arguments.length){if(1===arguments.length){var e=arguments[0];return Array.isArray(e)?1===e.length?i(e[0]):t(e):e instanceof i?e:"string"==typeof e?new a(e):n(e)}return t(Array.prototype.slice.call(arguments,0))}},l=p.prototype;return p.create=p,p.and=function(){var e=new u("and",at(arguments));return e.op&&e},p.or=function(){var e=new u("or",at(arguments));return e.op&&e},p.not=function(e){return e.not()},p.extendBinaryPredicateFn=function(t,n){var r=w.binaryPredicate;for(var i in t||{}){var a=t[i];a.visitorFn=n,e(s.prototype.aliasMap,i,t[i])}w.isExtended||(w.binaryPredicate=function(e,t,n){var i=this.aliasMap[this.op.key].visitorFn;return i?i(e,t,n):r(e,t,n)},w.isExtended=!0)},l.and=function(){var e=i(at(arguments));
return new u("and",[this,e])},l.or=function(){var e=i(at(arguments));return new u("or",[this,e])},l.not=function(){return new o("not",this)},l.toJSON=function(){return this.toJSONExt({entityType:this._entityType})},l.toJSONExt=function(e){return this.visit(e,E)},l.toFunction=function(e){return this.visit(e,w)},l.toString=function(){return JSON.stringify(this)},l.visit=function(e,t){if(B(e))e={entityType:null};else if(e instanceof Ft)e={entityType:e};else if(!it(e,"entityType"))throw new Error("All visitor methods must be called with a context object containing at least an 'entityType' property");t?e.visitor=t:t=e.visitor;var n=t[this.visitorMethodName];if(null==n)throw new Error("Unable to locate method: "+this.visitorMethodName+" on visitor");var r=e.entityType;(this._validate&&null==r||this._entityType!==r)&&(this._validate(r,e.usesNameOnServer),this._entityType=r);Array.prototype.slice.call(arguments,1);return n.call(this,e)},l._initialize=function(t,n){this.visitorMethodName=t;var r=this.aliasMap={};for(var i in n||{})e(r,i,n[i])},l._resolveOp=function(e,t){e=e.operator||e;var n=this.aliasMap[e.toLowerCase()];if(!n&&!t)throw new Error("Unable to resolve operator: "+e);return n},p}(),a=function(){var e=function(e){this.value=e},t=e.prototype=new i;return t._initialize("passthruPredicate"),t._validate=F,e}(),o=function(){var e=function(e,t){this.op=this._resolveOp(e),this.pred=i(t)},t=e.prototype=new i;return t._initialize("unaryPredicate",{not:{aliases:["!","~"]}}),t._validate=function(e,t){this.pred._validate(e,t)},e}(),s=function(){var t=function(e,t,n){this.op=this._resolveOp(e),this.expr1Source=t,this.expr2Source=n},n=t.prototype=new i;return n._initialize("binaryPredicate",{eq:{aliases:["=="]},ne:{aliases:["!=","~="]},lt:{aliases:["<"]},le:{aliases:["<="]},gt:{aliases:[">"]},ge:{aliases:[">="]},startswith:{isFunction:!0},endswith:{isFunction:!0},contains:{aliases:["substringof"],isFunction:!0},"in":{}}),n._validate=function(t,n){var r={entityType:t,usesNameOnServer:n};if(this.expr1=e(this.expr1Source,r),null==this.expr1)throw new Error("Unable to validate 1st expression: "+this.expr1Source);if(this.expr1 instanceof y)throw new Error("The left hand side of a binary predicate cannot be a literal expression, it must be a valid property or functional predicate expression: "+this.expr1Source);if("in"==this.op.key&&!Array.isArray(this.expr2Source))throw new Error("The 'in' operator requires that its right hand argument be an array");var i=p(r,{isRHS:!0,dataType:this.expr1.dataType});if(this.expr2=e(this.expr2Source,i),null==this.expr2)throw new Error("Unable to validate 2nd expression: "+this.expr2Source);null==this.expr1.dataType&&(this.expr1.dataType=this.expr2.dataType)},t}(),u=function(){var e=function(e,t){return this.op=this._resolveOp(e),1==t.length&&Array.isArray(t[0])&&(t=t[0]),this.preds=t.filter(function(e){return null!=e}).map(function(e){return i(e)}),0==this.preds.length&&(this.op=null),1==this.preds.length?this.preds[0]:void 0},t=e.prototype=new i;return t._initialize("andOrPredicate",{and:{aliases:["&&"]},or:{aliases:["||"]}}),t._validate=function(e,t){this.preds.every(function(n){n._validate(e,t)})},e}(),c=function(){var t=function(e,t,n){this.op=this._resolveOp(e),this.exprSource=t,this.pred=i(n)},n=t.prototype=new i;return n._initialize("anyAllPredicate",{any:{aliases:["some"]},all:{aliases:["every"]}}),n._validate=function(t,n){this.expr=e(this.exprSource,{entityType:t,usesNameOnServer:n}),(null==t||t.isAnonymous)&&(this.expr.dataType=null),this.pred._validate(this.expr.dataType,n)},t}(),l=function(e){this.visitorMethodName=e,this.visit=i.prototype.visit,this._validate=F},y=function(){function e(e){if(null==e)return e;if(_t.contains(e))return e;if(R(e)){var t=_t.fromName(e);if(t)return t;throw new Error("Unable to resolve a dataType named: "+e)}throw new Error("The dataType parameter passed into this literal expression is not a 'DataType'"+e)}var t=function(t,n,r){n=e(n),n=n||_t.fromValue(t),this.value=n&&n.parse?Array.isArray(t)?t.map(function(e){return n.parse(e,typeof e)}):n.parse(t,typeof t):t,this.dataType=n,this.hasExplicitDataType=r},n=t.prototype=new l("litExpr");return n.toString=function(){return" LitExpr - value: "+this.value.toString()+" dataType: "+this.dataType.toString()},t}(),f=function(){var e=function(e){this.propertyPath=e},t=e.prototype=new l("propExpr");return t.toString=function(){return" PropExpr - "+this.propertyPath},t._validate=function(e,t){if(null!=e&&!e.isAnonymous){var n=e.getPropertiesOnPath(this.propertyPath,t,!1);if(!n){var r=G("Unable to resolve propertyPath. EntityType: '%1' PropertyPath: '%2'",e.name,this.propertyPath);throw new Error(r)}var i=n[n.length-1];this.dataType=i.isDataProperty?i.dataType:i.entityType}},e}(),h=function(){var e=function(e,t){this.fnName=e,this.exprs=t;var r=n[e];if(null==r)throw new Error("Unknown function: "+e);this.localFn=r.fn,this.dataType=r.dataType},t=e.prototype=new l("fnExpr");t.toString=function(){var e=this.exprs.map(function(e){e.toString()}).toString();return"FnExpr - "+this.fnName+"("+e+")"},t._validate=function(e,t){this.exprs.forEach(function(n){n._validate(e,t)})};var n=e.funcMap={toupper:{fn:function(e){return e.toUpperCase()},dataType:_t.String},tolower:{fn:function(e){return e.toLowerCase()},dataType:_t.String},substring:{fn:function(e,t,n){return e.substring(t,n)},dataType:_t.String},substringof:{fn:function(e,t){return t.indexOf(e)>=0},dataType:_t.Boolean},length:{fn:function(e){return e.length},dataType:_t.Int32},trim:{fn:function(e){return e.trim()},dataType:_t.String},concat:{fn:function(e,t){return e.concat(t)},dataType:_t.String},replace:{fn:function(e,t,n){return e.replace(t,n)},dataType:_t.String},startswith:{fn:function(e,t){return z(e,t)},dataType:_t.Boolean},endswith:{fn:function(e,t){return U(e,t)},dataType:_t.Boolean},indexof:{fn:function(e,t){return e.indexOf(t)},dataType:_t.Int32},round:{fn:function(e){return Math.round(e)},dataType:_t.Int32},ceiling:{fn:function(e){return Math.ceil(e)},dataType:_t.Int32},floor:{fn:function(e){return Math.floor(e)},dataType:_t.Int32},second:{fn:function(e){return e.getSeconds()},dataType:_t.Int32},minute:{fn:function(e){return e.getMinutes()},dataType:_t.Int32},day:{fn:function(e){return e.getDate()},dataType:_t.Int32},month:{fn:function(e){return e.getMonth()+1},dataType:_t.Int32},year:{fn:function(e){return e.getFullYear()},dataType:_t.Int32}};return e}(),d=/^[a-z_][\w.$]*$/i,m=/('[^']*'|[^,]+)/g,v=/("[^"]*"|[^,]+)/g,g=String.fromCharCode(191),w=function(){function e(e){switch(e.key){case"any":return function(e,t){return e.some(function(e){return t(e)})};case"all":return function(e,t){return e.every(function(e){return t(e)})};default:throw new Error("Unknown operator: "+e.key)}}function t(e,t,o){var s,u=e.op,p=_t.getComparableFn(t);switch(u.key){case"eq":s=function(e,t){return e&&"string"==typeof e?n(e,t,o):p(e)==p(t)};break;case"ne":s=function(e,t){return e&&"string"==typeof e?!n(e,t,o):p(e)!=p(t)};break;case"gt":s=function(e,t){return p(e)>p(t)};break;case"ge":s=function(e,t){return p(e)>=p(t)};break;case"lt":s=function(e,t){return p(e)<p(t)};break;case"le":s=function(e,t){return p(e)<=p(t)};break;case"startswith":s=function(e,t){return r(e,t,o)};break;case"endswith":s=function(e,t){return i(e,t,o)};break;case"contains":s=function(e,t){return a(e,t,o)};break;case"in":s=function(e,t){return e=p(e),t=t.map(function(e){return p(e)}),t.indexOf(e)>=0};break;default:return null}return s}function n(e,t,n){return null==t?!1:("string"!=typeof t&&(t=t.toString()),n.usesSql92CompliantStringComparison&&(e=(e||"").trim(),t=(t||"").trim()),n.isCaseSensitive||(e=(e||"").toLowerCase(),t=(t||"").toLowerCase()),e===t)}function r(e,t,n){return n.isCaseSensitive||(e=(e||"").toLowerCase(),t=(t||"").toLowerCase()),z(e,t)}function i(e,t,n){return n.isCaseSensitive||(e=(e||"").toLowerCase(),t=(t||"").toLowerCase()),U(e,t)}function a(e,t,n){return n.isCaseSensitive||(e=(e||"").toLowerCase(),t=(t||"").toLowerCase()),e.indexOf(t)>=0}var o={passthruPredicate:function(){throw new Error("Cannot execute an PassthruPredicate expression against the local cache: "+this.value)},unaryPredicate:function(e){var t=this.pred.visit(e);switch(this.op.key){case"not":return function(e){return!t(e)};default:throw new Error("Invalid unary operator:"+this.op.key)}},binaryPredicate:function(e){var n=this.expr1.visit(e),r=this.expr2.visit(e),i=this.expr1.dataType||this.expr2.dataType,a=e.entityType.metadataStore.localQueryComparisonOptions,o=t(this,i,a);if(null==o)throw new Error("Invalid binaryPredicate operator:"+this.op.key);return function(e){return o(n(e),r(e))}},andOrPredicate:function(e){var t=this.preds.map(function(t){return t.visit(e)});switch(this.op.key){case"and":return function(e){var n=t.reduce(function(t,n){return t&&n(e)},!0);return n};case"or":return function(e){var n=t.reduce(function(t,n){return t||n(e)},!1);return n};default:throw new Error("Invalid boolean operator:"+op.key)}},anyAllPredicate:function(t){var n=this.expr.visit(t),r=p({},t);r.entityType=this.expr.dataType;var i=this.pred.visit(r),a=e(this.op);return function(e){return a(n(e),i)}},litExpr:function(){var e=this.value;return function(){return e}},propExpr:function(){var e=this.propertyPath,t=e.split(".");return 1===t.length?function(t){return t.getProperty(e)}:function(e){return nt(e,t)}},fnExpr:function(e){var t=this.exprs.map(function(t){return t.visit(e)}),n=this;return function(e){var r=t.map(function(t){var n=t(e);return n}),i=n.localFn.apply(null,r);return i}}};return o}(),E=function(){function e(t,n){var r=Object.keys(n).every(function(r){if(t.hasOwnProperty(r)){if("object"!=typeof n[r])return!1;if(null==e(t[r],n[r]))return!1}else t[r]=n[r];return!0});return r?t:null}var t={passthruPredicate:function(){return this.value},unaryPredicate:function(e){var t=this.pred.visit(e),n={};return n[this.op.key]=t,n},binaryPredicate:function(e){var t=this.expr1.visit(e),n=this.expr2.visit(e),r={};if(this.expr2 instanceof f&&(n={value:n,isProperty:!0}),"eq"===this.op.key)r[t]=n;else{var i={};r[t]=i,i[this.op.key]=n}return r},andOrPredicate:function(t){var n,r=this.preds.map(function(e){return e.visit(t)});return"and"!==this.op.key||2!==r.length||r.some(R)||(n=r.reduce(e)),null==n&&(n={},n[this.op.key]=r),n},anyAllPredicate:function(e){var t=this.expr.visit(e),n=p({},e);n.entityType=this.expr.dataType;var r=this.pred.visit(n),i={},a={};return a[this.op.key]=r,i[t]=a,i},litExpr:function(e){return this.hasExplicitDataType||e.useExplicitDataType?{value:this.value,dataType:this.dataType.name}:this.value},propExpr:function(e){return e.toNameOnServer?e.entityType.clientPropertyPathToServer(this.propertyPath):this.propertyPath},fnExpr:function(e){var t=this.exprs.map(function(t){return t.visit(e)});return this.fnName+"("+t.join(",")+")"}};return t}();return i}();rt.Predicate=jt;var Lt=function(){function e(e,t){return y(t,{"resourceName,from":null,"resultEntityType,toType":null,"wherePredicate,where":function(e){return e?new jt(e):void 0},"orderByClause,orderBy":function(e){return e?new qt(e):void 0},"selectClause,select":function(e){return e?new zt(e):void 0},"expandClause,expand":function(e){return e?new Ut(e):void 0},"skipCount,skip":null,"takeCount,take":null,parameters:function(e){return B(e)?void 0:e},"inlineCountEnabled,inlineCount":!1,"noTrackingEnabled,noTracking":!1,queryOptions:function(e){return e?Jt.fromJSON(e):void 0}},e),e}function n(e,t,n){if(t&&e[t]===n)return e;var r=p(new Lt,e,["resourceName","fromEntityType","wherePredicate","orderByClause","selectClause","skipCount","takeCount","expandClause","inlineCountEnabled","noTrackingEnabled","usesNameOnServer","queryOptions","entityManager","dataService","resultEntityType"]);return r.parameters=p({},e.parameters),t&&(r[t]=n),r}function r(e,n,i,a){var o=i._$typeName||i.parentEnum&&i.parentEnum.name,s=o&&o.substr(0,1).toLowerCase()+o.substr(1);if(a&&s!=a)throw new Error("Invalid value for property: "+a);if(s){var u=n[s];if(void 0===u)throw new Error("Invalid config property: "+s);null===u?e[s]=i:u(e,i)}else t(i,function(t,i){r(e,n,i,t)})}function i(e){return pt(e,"propertyPaths").isOptional().isString().or().isArray().isString().check(),"string"==typeof e&&(e=e.split(",")),e=e.map(function(e){return e.trim()})}function a(e){var t=e.entityType,n=t.keyProperties.map(function(t){return jt.create(t.name,Bt.Equals,e.getProperty(t.name))}),r=jt.and(n);return r}function o(e){var t=e.entityType.keyProperties,n=S(t,e.values,function(e,t){return jt.create(e.name,Bt.Equals,t)}),r=jt.and(n);return r}function s(e,t){if(t.isScalar){if(0===t.foreignKeyNames.length)return null;var n=t.foreignKeyNames.map(function(t){return e.getProperty(t)}),r=new Pt(t.entityType,n);return o(r)}var i=t.inverse,a=i?i.foreignKeyNames:t.invForeignKeyNames;if(0===a.length)return null;var s=e.entityAspect.getKey().values,u=S(a,s,function(e,t){return jt.create(e,Bt.Equals,t)});return jt.and(u)}var u=function(t){return null==t||R(t)?(this.resourceName=t,this.fromEntityType=null,this.wherePredicate=null,this.orderByClause=null,this.selectClause=null,this.skipCount=null,this.takeCount=null,this.expandClause=null,this.parameters={},this.inlineCountEnabled=!1,this.noTrackingEnabled=!1,void(this.entityManager=null)):e(this,t)},c=u.prototype;return c._$typeName="EntityQuery",c.from=function(e){return pt(e,"resourceName").isString().check(),n(this,"resourceName",e)},u.from=function(e){return pt(e,"resourceName").isString().check(),new Lt(e)},c.toType=function(e){return pt(e,"entityType").isString().or().isInstanceOf(Ft).check(),n(this,"resultEntityType",e)},c.where=function(e){return null!=e&&(e=jt.create(at(arguments)),this.fromEntityType&&e._validate(this.fromEntityType),this.wherePredicate&&(e=this.wherePredicate.and(e))),n(this,"wherePredicate",e)},c.orderBy=function(e,t){var r=null==e?null:new qt(i(e),t);return this.orderByClause&&r&&(r=new qt([this.orderByClause,r])),n(this,"orderByClause",r)},c.orderByDesc=function(e){return this.orderBy(e,!0)},c.select=function(e){var t=null==e?null:new zt(i(e));return n(this,"selectClause",t)},c.skip=function(e){return pt(e,"count").isOptional().isNumber().check(),n(this,"skipCount",null==e?null:e)},c.top=function(e){return this.take(e)},c.take=function(e){return pt(e,"count").isOptional().isNumber().check(),n(this,"takeCount",null==e?null:e)},c.expand=function(e){var t=null==e?null:new Ut(i(e));return n(this,"expandClause",t)},c.withParameters=function(e){return pt(e,"parameters").isObject().check(),n(this,"parameters",e)},c.inlineCount=function(e){return pt(e,"enabled").isBoolean().isOptional().check(),e=void 0===e?!0:!!e,n(this,"inlineCountEnabled",e)},c.useNameOnServer=function(e){return pt(e,"usesNameOnServer").isBoolean().isOptional().check(),e=void 0===e?!0:!!e,n(this,"usesNameOnServer",e)},c.noTracking=function(e){return pt(e,"enabled").isBoolean().isOptional().check(),e=void 0===e?!0:!!e,n(this,"noTrackingEnabled",e)},c.using=function(e){if(!e)return this;var t=n(this);return r(t,{entityManager:null,dataService:null,queryOptions:null,fetchStrategy:function(e,t){e.queryOptions=(e.queryOptions||new Jt).using(t)},mergeStrategy:function(e,t){e.queryOptions=(e.queryOptions||new Jt).using(t)},jsonResultsAdapter:function(e,t){e.dataService=(e.dataService||new bt).using({jsonResultsAdapter:t})}},e),t},c.execute=function(e,t){if(!this.entityManager)throw new Error("An EntityQuery must have its EntityManager property set before calling 'execute'");return this.entityManager.executeQuery(this,e,t)},c.executeLocally=function(){if(!this.entityManager)throw new Error("An EntityQuery must have its EntityManager property set before calling 'executeLocally'");return this.entityManager.executeQueryLocally(this)},c.toJSON=function(){return this.toJSONExt()},c.toJSONExt=function(e){e=e||{},e.entityType=e.entityType||this.fromEntityType,e.propertyPathFn=e.toNameOnServer?e.entityType.clientPropertyPathToServer.bind(e.entityType):M;var t=function(t){return t?t.toJSONExt(e):void 0};return y(this,{"from,resourceName":null,"toType,resultEntityType":function(e){return e?R(e)?e:e.name:void 0},"where,wherePredicate":t,"orderBy,orderByClause":t,"select,selectClause":t,"expand,expandClause":t,"skip,skipCount":null,"take,takeCount":null,parameters:function(e){return B(e)?void 0:e},"inlineCount,inlineCountEnabled":!1,"noTracking,noTrackingEnabled":!1,queryOptions:null})},u.fromEntities=function(e){pt(e,"entities").isEntity().or().isNonEmptyArray().isEntity().check(),Array.isArray(e)||(e=at(arguments));var t=e[0],n=new Lt(t.entityType.defaultResourceName),r=e.map(function(e){return a(e)}),i=jt.or(r);n=n.where(i);var o=t.entityAspect.entityManager;return o&&(n=n.using(o)),n},u.fromEntityKey=function(e){pt(e,"entityKey").isInstanceOf(Pt).check();var t=new Lt(e.entityType.defaultResourceName),n=o(e);return t=t.where(n).toType(e.entityType)},u.fromEntityNavigation=function(e,t){pt(e,"entity").isEntity().check();var n=e.entityType._checkNavProperty(t),r=new Lt(n.entityType.defaultResourceName),i=s(e,n);r=r.where(i);var a=e.entityAspect.entityManager;return a?r.using(a):r},c._getFromEntityType=function(e,t){var n=this.fromEntityType;if(n)return n;var r=this.resourceName;if(!r)throw new Error("There is no resourceName for this query");if(e.isEmpty()){if(t)throw new Error("There is no metadata available for this query. Are you querying the local cache before you've fetched metadata?");return null}var i=e.getEntityTypeNameForResourceName(r);if(n=i?e._getEntityType(i):this._getToEntityType(e,!0),!n){if(t)throw new Error(G("Cannot find an entityType for resourceName: '%1'. Consider adding an 'EntityQuery.toType' call to your query or calling the MetadataStore.setEntityTypeForResourceName method to register an entityType for this resourceName.",r));return null}return this.fromEntityType=n,n},c._getToEntityType=function(e,t){return this.resultEntityType instanceof Ft?this.resultEntityType:this.resultEntityType?(this.resultEntityType=e._getEntityType(this.resultEntityType,!1),this.resultEntityType):t?null:!this.selectClause&&this._getFromEntityType(e,!1)},c._toUri=function(e){var t=bt.resolve([e.dataService]);return t.uriBuilder.buildUri(this,e.metadataStore)},u}(),Bt=function(){var e=new yt("FilterQueryOp");return e.Equals=e.addSymbol({operator:"eq"}),e.NotEquals=e.addSymbol({operator:"ne"}),e.GreaterThan=e.addSymbol({operator:"gt"}),e.LessThan=e.addSymbol({operator:"lt"}),e.GreaterThanOrEqual=e.addSymbol({operator:"ge"}),e.LessThanOrEqual=e.addSymbol({operator:"le"}),e.Contains=e.addSymbol({operator:"contains"}),e.StartsWith=e.addSymbol({operator:"startswith"}),e.EndsWith=e.addSymbol({operator:"endswith"}),e.Any=e.addSymbol({operator:"any"}),e.All=e.addSymbol({operator:"all"}),e.IsTypeOf=e.addSymbol({operator:"isof"}),e.resolveSymbols(),e._map=function(){var t={};return e.getSymbols().forEach(function(e){t[e.name.toLowerCase()]=e,t[e.operator.toLowerCase()]=e,e.aliases&&e.aliases.forEach(function(n){t[n.toLowerCase()]=e})}),t}(),e.from=function(t){return e.contains(t)?t:e._map[t.toLowerCase()]},e}(),qt=(function(){var e=new yt("BooleanQueryOp");return e.And=e.addSymbol({operator:"and"}),e.Or=e.addSymbol({operator:"or"}),e.Not=e.addSymbol({operator:"not"}),e.resolveSymbols(),e._map=function(){var t={};return e.getSymbols().forEach(function(e){t[e.name.toLowerCase()]=e,t[e.operator.toLowerCase()]=e,e.aliases&&e.aliases.forEach(function(n){t[n.toLowerCase()]=e})}),t}(),e.from=function(t){return e.contains(t)?t:e._map[t.toLowerCase()]},e}(),function(){var e=function(e,t){if(e.length>1){if(e[0]instanceof qt)return void(this.items=Array.prototype.concat.apply(e[0].items,e.slice(1).map(s("items"))));var r=e.map(function(e){return new n(e,t)})}else var r=[new n(e[0],t)];this.items=r},t=e.prototype;t.validate=function(e){null==e||e.isAnonymous||this.items.forEach(function(t){t.validate(e)})},t.getComparer=function(e){var t=this.items.map(function(t){return t.getComparer(e)});return function(e,n){for(var r=0;r<t.length;r++){var i=t[r](e,n);if(0!==i)return i}return 0}},t.toJSONExt=function(e){return this.items.map(function(t){return e.propertyPathFn(t.propertyPath)+(t.isDesc?" desc":"")})};var n=function(e,t){if("string"!=typeof e)throw new Error("propertyPath is not a string");e=e.trim();var n=e.split(" ");if(n.length>1&&t!==!0&&t!==!1&&(t=z(n[1].toLowerCase(),"desc"),!t)){var r=z(n[1].toLowerCase(),"asc");if(!r)throw new Error("the second word in the propertyPath must begin with 'desc' or 'asc'")}this.propertyPath=n[0],this.isDesc=t},r=n.prototype;return r.validate=function(e){null==e||e.isAnonymous||(this.lastProperty=e.getProperty(this.propertyPath,!0))},r.getComparer=function(e){if(this.lastProperty||this.validate(e),this.lastProperty)var t=this.lastProperty.dataType,n=this.lastProperty.parentType.metadataStore.localQueryComparisonOptions.isCaseSensitive;var r=this.propertyPath,i=this.isDesc;return function(e,a){var o=nt(e,r),s=nt(a,r),u=t||o&&_t.fromValue(o)||_t.fromValue(s);if(u===_t.String)n?(o=o||"",s=s||""):(o=(o||"").toLowerCase(),s=(s||"").toLowerCase());else{var p=_t.getComparableFn(u);o=p(o),s=p(s)}return o===s?0:o>s||void 0===s?i?-1:1:i?1:-1}},e}()),zt=function(){var e=function(e){this.propertyPaths=e,this._pathNames=e.map(function(e){return e.replace(".","_")})},t=e.prototype;return t.validate=function(e){null==e||e.isAnonymous||this.propertyPaths.forEach(function(t){e.getProperty(t,!0)})},t.toFunction=function(){var e=this;return function(t){var n={};return e.propertyPaths.forEach(function(r,i){n[e._pathNames[i]]=nt(t,r)}),n}},t.toJSONExt=function(e){return this.propertyPaths.map(function(t){return e.propertyPathFn(t)})},e}(),Ut=function(){var e=function(e){this.propertyPaths=e},t=e.prototype;return t.toJSONExt=function(e){return this.propertyPaths.map(function(t){return e.propertyPathFn(t)})},e}();rt.FilterQueryOp=Bt,rt.EntityQuery=Lt,rt.OrderByClause=qt;var Gt=function(){var e=new yt("MergeStrategy");return e.PreserveChanges=e.addSymbol(),e.OverwriteChanges=e.addSymbol(),e.SkipMerge=e.addSymbol(),e.Disallowed=e.addSymbol(),e.resolveSymbols(),e}(),$t=function(){var e=new yt("FetchStrategy");return e.FromServer=e.addSymbol(),e.FromLocalCache=e.addSymbol(),e.resolveSymbols(),e}(),Jt=function(){function e(e,t){return t&<(t).whereParam("fetchStrategy").isEnumOf($t).isOptional().whereParam("mergeStrategy").isEnumOf(Gt).isOptional().whereParam("includeDeleted").isBoolean().isOptional().applyAll(e),e}var t=function(t){e(this,t)},n=t.prototype;return n._$typeName="QueryOptions",t.resolve=function(e){return new Jt(h(e,["fetchStrategy","mergeStrategy","includeDeleted"]))},t.defaultInstance=new t({fetchStrategy:$t.FromServer,mergeStrategy:Gt.PreserveChanges,includeDeleted:!1}),n.using=function(t){if(!t)return this;var n=new Jt(this);return Gt.contains(t)?t={mergeStrategy:t}:$t.contains(t)&&(t={fetchStrategy:t}),e(n,t)},n.setAsDefault=function(){return l(this,t)},n.toJSON=function(){return y(this,{fetchStrategy:null,mergeStrategy:null,includeDeleted:!1})},t.fromJSON=function(e){return new Jt({fetchStrategy:$t.fromName(e.fetchStrategy),mergeStrategy:Gt.fromName(e.mergeStrategy),includeDeleted:e.includeDeleted===!0})},t}();rt.QueryOptions=Jt,rt.FetchStrategy=$t,rt.MergeStrategy=Gt;var Qt=function(){function e(e){if(e){if(1===e.length){var t=e[0];return function(e){return e?e.entityAspect.entityState===t:!1}}return function(t){return t?e.some(function(e){return t.entityAspect.entityState===e}):!1}}return function(e){return!!e}}var t=e([Nt.Added,Nt.Modified,Nt.Deleted]),n=function(e,t){this.entityManager=e,this.entityType=t,this.entityType.isFrozen=!0,this._indexMap={},this._entities=[],this._emptyIndexes=[]},r=n.prototype;return r.attachEntity=function(e,t,n){var r=e.entityAspect;r._initialized||this.entityType._initializeInstance(e),delete r._initialized;var i=r.getKey()._keyInGroup,a=this._indexMap[i];if(a>=0){var o=this._entities[a],s=o.entityAspect.entityState,u=s.isUnchanged();if(o===e)r.entityState=t;else{if(n===Gt.Disallowed)throw new Error("A MergeStrategy of 'Disallowed' does not allow you to attach an entity when an entity with the same key is already attached: "+r.getKey());if(n===Gt.OverwriteChanges||n===Gt.PreserveChanges&&u){var p=this.entityManager.helper.unwrapInstance(e);this.entityType._updateTargetFromRaw(o,p,Dt.getRawValueFromServer),o.entityAspect.setEntityState(t)}}return o}return 0===this._emptyIndexes.length?a=this._entities.push(e)-1:(a=this._emptyIndexes.pop(),this._entities[a]=e),this._indexMap[i]=a,r.entityState=t,r.entityGroup=this,r.entityManager=this.entityManager,e},r.detachEntity=function(e){var t=e.entityAspect,n=t.getKey()._keyInGroup,r=this._indexMap[n];if(void 0===r)throw new Error("internal error - entity cannot be found in group");return delete this._indexMap[n],this._emptyIndexes.push(r),this._entities[r]=null,e},r.findEntityByKey=function(e){var t;t=e instanceof Pt?e._keyInGroup:Pt.createKeyString(e);var n=this._indexMap[t];return void 0!==n?this._entities[n]:null},r.hasChanges=function(){return this._entities.some(t)},r.getEntities=function(t){var n=e(t);return this._entities.filter(n)},r._checkOperation=function(e){return this._entities.forEach(function(t){t&&t.entityAspect._checkOperation(e)}),this},r._clear=function(){this._entities.forEach(function(e){null!=e&&e.entityAspect._detach()}),this._entities=null,this._indexMap=null,this._emptyIndexes=null},r._updateFkVal=function(e,t,n){var r=e.name;this._entities.forEach(function(e){null!=e&&e.getProperty(r)==t&&e.setProperty(r,n)})},r._fixupKey=function(e,t){var n=this._indexMap[e];if(void 0===n)throw new Error("Internal Error in key fixup - unable to locate entity");var r=this._entities[n],i=r.entityType.keyProperties[0].name;r.setProperty(i,t),delete r.entityAspect.hasTempKey,delete this._indexMap[e],this._indexMap[t]=n},r._replaceKey=function(e,t){var n=this._indexMap[e._keyInGroup];delete this._indexMap[e._keyInGroup],this._indexMap[t._keyInGroup]=n},n}(),Zt=function(){function e(e,t,n){var r=n?Jt.defaultInstance:e.queryOptions,i=n?Yt.defaultInstance:e.saveOptions,a=n?wt.defaultInstance:e.validationOptions,o=lt(t).whereParam("serviceName").isOptional().isString().whereParam("dataService").isOptional().isInstanceOf(bt).whereParam("queryOptions").isInstanceOf(Jt).isOptional().withDefault(r).whereParam("saveOptions").isInstanceOf(Yt).isOptional().withDefault(i).whereParam("validationOptions").isInstanceOf(wt).isOptional().withDefault(a).whereParam("keyGeneratorCtor").isFunction().isOptional();n&&(o=o.whereParam("metadataStore").isInstanceOf(Ct).isOptional().withDefault(new Ct)),o.applyAll(e),c(e.queryOptions,r),c(e.saveOptions,i),c(e.validationOptions,a),t.serviceName&&(e.dataService=new bt({serviceName:e.serviceName})),e.serviceName=e.dataService&&e.dataService.serviceName,e.keyGeneratorCtor=e.keyGeneratorCtor||Vt,(n||t.keyGeneratorCtor)&&(e.keyGenerator=new e.keyGeneratorCtor)}function r(e){e.forEach(function(e){var n=[],r=e.entityAspect;t(r._validationErrors,function(e,t){t.isServerError&&n.push(e)}),0!==n.length&&r._processValidationOpAndPublish(function(){n.forEach(function(e){r._removeValidationError(e)})})})}function i(e){var n=[];return e.forEach(function(e){t(e.entityAspect._validationErrors,function(t,r){var i=p({entity:e,errorName:r.validator.name},r,["errorMessage","propertyName","isServerError"]);n.push(i)})}),n}function a(e,t){var n=t.entityErrors;if(n){var r=e.entityManager,i=r.metadataStore;t.entityErrors=n.map(function(e){var t=null;if(e.keyValues){var n=i._getEntityType(e.entityTypeName),a=new Pt(n,e.keyValues);t=r.findEntityByKey(a)}if(t){var o=e.propertyName?{propertyName:e.propertyName,property:n.getProperty(e.propertyName)}:{},s=gt.getKey(e.errorName||e.errorMessage,e.propertyName),u=new gt(null,o,e.errorMessage,s);u.isServerError=!0,t.entityAspect.addValidationError(u)}var c=p({entity:t,isServerError:!0},e,["errorName","errorMessage","propertyName"]);return c})}}function o(e,t){var n,r=y(e,t),i=r.entityKey,a=0===r.remainingArgs.length?!1:!!r.remainingArgs[0],o=!1;return a&&(n=e.getEntityByKey(i),o=!!n,o&&!e.queryOptions.includeDeleted&&n.entityAspect.entityState.isDeleted()&&(n=null,o=e.queryOptions.mergeStrategy!==Gt.OverwriteChanges)),o?At.resolve({entity:n,entityKey:i,fromCache:!0}):Lt.fromEntityKey(i).using(e).execute().then(function(e){return n=0===e.results.length?null:e.results[0],At.resolve({entity:n,entityKey:i,fromCache:!1})})}function s(e,t){return pt(t,"entityTypes").isString().isOptional().or().isNonEmptyArray().isString().or().isInstanceOf(Ft).or().isNonEmptyArray().isInstanceOf(Ft).check(),"string"==typeof t?t=e.metadataStore._getEntityType(t,!1):Array.isArray(t)&&"string"==typeof t[0]&&(t=t.map(function(t){return e.metadataStore._getEntityType(t,!1)})),t}function l(e,t,n){var r,i=D(e,t);return i.forEach(function(e){if(e){var t=e.getEntities(n);r?r.push.apply(r,t):r=t}}),r||[]}function y(e,t){try{if(t[0]instanceof Pt)return{entityKey:t[0],remainingArgs:at(t,1)};if(t.length>=2){var n="string"==typeof t[0]?e.metadataStore._getEntityType(t[0],!1):t[0];return{entityKey:new Pt(n,t[1]),remainingArgs:at(t,2)}}}catch(r){}throw new Error("Must supply an EntityKey OR an EntityType name or EntityType followed by a key value or an array of key values.")}function h(e,t){e.forEach(function(e){e.entityAspect.isBeingSaved=t})}function g(e,n){var r;n?(r={},n.forEach(function(e){var t=r[e.entityType.name];t||(t={},t.entityType=e.entityType,t._entities=[],r[e.entityType.name]=t),t._entities.push(e)})):r=e._entityGroupMap;var i=[],a={};return t(r,function(e,t){a[e]=w(t,i)}),{entityGroupMap:a,tempKeys:i}}function w(e,t){var n={},r=e.entityType,i=r.dataProperties,a=H(r),o=[];return e._entities.forEach(function(e){if(e){var n=T(e,i,a,t);o.push(n)}}),n.entities=o,n}function T(e,t,n,r){var i={};t.forEach(function(t){var r=t.name,a=e.getProperty(r);if(null!=a||null!=t.defaultValue){if(a&&t.isComplexProperty){var o=t.dataType.dataProperties;a=m(a,function(e){return T(e,o,n)})}else a=n?n(t,a):a,t.isUnmapped&&(a=f(a));void 0!==a&&(i[r]=a)}});var a,o;if(e.entityAspect){a=e.entityAspect;var s=a.entityState;o={tempNavPropNames:N(a,r),entityState:s.name},a.extraMetadata&&(o.extraMetadata=a.extraMetadata),(s.isModified()||s.isDeleted())&&(o.originalValuesMap=a.originalValues),i.entityAspect=o}else a=e.complexAspect,o={},a.originalValues&&!B(a.originalValues)&&(o.originalValuesMap=a.originalValues),i.complexAspect=o;return i}function N(e,t){var n=e.entity;e.hasTempKey&&t.push(e.getKey().toJSON());var r;return n.entityType.navigationProperties.forEach(function(e){if(e.relatedDataProperties){var t=n.getProperty(e.name);t&&t.entityAspect.hasTempKey&&(r=r||[],r.push(e.name))}}),r}function _(e,t,n){var r=n.tempKeyMap,i=e.entityType,a=n.mergeStrategy,o=null,s=e.entityManager,u=s.entityChanged,p=[],c=Dt.getRawValueFromClient;return t.entities.forEach(function(t){var n=t.entityAspect,l=i.getEntityKeyFromRawEntity(t,c),y=Nt.fromName(n.entityState),f=y.isAdded()&&A(r,l);if(o=f?null:e.findEntityByKey(l))if(a===Gt.SkipMerge);else{if(a===Gt.Disallowed)throw new Error("A MergeStrategy of 'Disallowed' prevents "+l.toString()+" from being merged");var h=o.entityAspect.entityState,d=h.isUnchanged();(a===Gt.OverwriteChanges||d)&&(i._updateTargetFromRaw(o,t,c),o.entityAspect.setEntityState(y),u.publish({entityAction:Et.MergeOnImport,entity:o}))}else o=i._createInstanceCore(),i._updateTargetFromRaw(o,t,c),f&&(o.entityAspect.hasTempKey=!0,o.setProperty(i.keyProperties[0].name,f.values[0]),n.tempNavPropNames&&n.tempNavPropNames.forEach(function(e){var t=i.getNavigationProperty(e),n=t.relatedDataProperties[0].name,a=o.getProperty(n),s=new Pt(t.entityType,[a]),u=A(r,s);o.setProperty(n,u.values[0])})),o=e.attachEntity(o,y),u.publish({entityAction:Et.AttachOnImport,entity:o}),y.isUnchanged()||s._notifyStateChange(o,!0);p.push(o)}),p}function A(e,t){var n=e[t.toString()];if(n)return n;var r=t._subtypes;if(!r)return null;for(var i=0,a=r.length;a>i;i++)if(n=e[t.toString(r[i])])return n;return null}function x(e,t,n){return e=e.then(function(e){return t&&t(e),At.resolve(e)
},function(e){return n&&n(e),At.reject(e)})}function F(e,t){var n;return n=t?t.filter(function(t){if(t.entityAspect.entityManager!==e)throw new Error("Only entities in this entityManager may be saved");return!t.entityAspect.entityState.isDetached()}):e.getChanges()}function M(e,t){e._inKeyFixup=!0,t.forEach(function(t){var n=e._entityGroupMap[t.entityTypeName];if(!n)throw new Error("Unable to locate the following fully qualified EntityType name: "+t.entityTypeName);n._fixupKey(t.tempValue,t.realValue)}),e._inKeyFixup=!1}function D(e,t){var n=e._entityGroupMap;return t?d(t).map(function(e){if(e instanceof Ft)return n[e.name];throw new Error("The EntityManager.getChanges() 'entityTypes' parameter must be either an entityType or an array of entityTypes or null")}):u(n)}function k(e,t){var n=t.entityAspect.getKey(),r=S(t.entityType.keyProperties,n.values,function(e,t){return e.defaultValue===t?e:null}).filter(function(e){return null!==e});if(r.length)if(t.entityType.autoGeneratedKeyType!==It.None)e.generateTempKeyValue(t);else if(r.length===n.values.length)throw new Error("Cannot attach an object of type ("+t.entityType.name+") to an EntityManager without first setting its key or setting its entityType 'AutoGeneratedKeyType' property to something other than 'None'")}function I(e,t){return t?(t=d(t),t.forEach(function(e){if(!Nt.contains(e))throw new Error("The EntityManager.getChanges() 'entityStates' parameter must either be null, an entityState or an array of entityStates")}),t):null}function V(e,t,n,r){var i=t.entityType.navigationProperties;i.forEach(function(i){var a=t.getProperty(i.name);if(i.isScalar){if(!a)return;e.attachEntity(a,n,r)}else a.forEach(function(t){e.attachEntity(t,n,r)})})}function R(e,t,r,i){try{var a,o=e.metadataStore;if(o.isEmpty()&&i.hasServerMetadata)throw new Error("cannot execute _executeQueryCore until metadataStore is populated.");if(r.fetchStrategy===$t.FromLocalCache)try{return a=e.executeQueryLocally(t),At.resolve({results:a,query:t})}catch(s){return At.reject(s)}var u=new Ht({query:t,entityManager:e,dataService:i,mergeOptions:{mergeStrategy:r.mergeStrategy,noTracking:!!t.noTrackingEnabled,includeDeleted:r.includeDeleted}}),p=e.validationOptions.validateOnQuery;return i.adapterInstance.executeQuery(u).then(function(r){var o=O(function(){var t={isLoading:e.isLoading};return e.isLoading=!0,e._pendingPubs=[],t},function(n){e.isLoading=n.isLoading,e._pendingPubs.forEach(function(e){e()}),e._pendingPubs=null,e._hasChangesAction&&e._hasChangesAction(),t=null,u=null,n.error&&At.reject(n.error)},function(){var o=i.jsonResultsAdapter.extractResults(r);o=d(o),a=u.visitAndMerge(o,{nodeType:"root"}),p&&a.forEach(function(e){e.entityAspect&&e.entityAspect.validateEntity()}),u.processDeferred(),K(a,t);var s=n(u.refMap);return{results:a,query:t,entityManager:e,httpResponse:r.httpResponse,inlineCount:r.inlineCount,retrievedEntities:s}});return At.resolve(o)},function(n){return n&&(n.query=t,n.entityManager=e),At.reject(n)})}catch(s){return s&&(s.query=t),At.reject(s)}}function K(e,t){if(!t.noTrackingEnabled){var n=t.expandClause;null!=n&&n.propertyPaths.forEach(function(t){var n=t.split(".");j(e,n)})}}function j(e,t){var n=t[0];e.forEach(function(e){var r=e.entityAspect;if(r&&(r._markAsLoaded(n),1!==t.length)){var i=e.getProperty(n);i&&(i.arrayChanged||(i=[i]),j(i,t.slice(1)))}})}function L(e){var t=e.filter(function(e){return e.entityAspect.isBeingSaved=!0,e.entityAspect.entityState.isModified()&&e.entityType.concurrencyProperties.length>0});0!==t.length&&t.forEach(function(e){e.entityType.concurrencyProperties.forEach(function(t){q(e,t)})})}function q(e,t){if(!e.entityAspect.originalValues[t.name]){var n=e.getProperty(t.name);if(n||(n=t.dataType.defaultValue),t.dataType.isNumeric)e.setProperty(t.name,n+1);else if(t.dataType.isDate){for(var r=new Date,i=new Date;r.getTime()===i.getTime();)i=new Date;e.setProperty(t.name,i)}else{if(t.dataType!==_t.Guid){if(t.dataType===_t.Binary)return;throw new Error("Unable to update the value of concurrency property before saving: "+t.name)}e.setProperty(t.name,C())}}}function z(e,t){var n=e._entityGroupMap[t.name];return n||(n=new Qt(e,t),e._entityGroupMap[t.name]=n),n}function U(e,t){var n=t.getSelfAndSubtypes();return n.map(function(t){return z(e,t)})}function G(e,t){var n={},r=e.entityType||e.complexType,i=H(r),a={};return r.dataProperties.forEach(function(r){if(r.isComplexProperty)n[r.nameOnServer]=m(e.getProperty(r.name),function(e){return G(e,t)});else{var o=e.getProperty(r.name);if(o=t?t(r,o):o,void 0===o)return;o=i?i(r,o):o,void 0!==o&&(r.isUnmapped?a[r.nameOnServer]=f(o):n[r.nameOnServer]=o)}}),B(a)||(n.__unmapped=a),n}function $(e,n,r){var i=e.entityType||e.complexType,a=e.entityAspect||e.complexAspect,o=n.namingConvention.clientPropertyNameToServer,s={};return t(a.originalValues,function(e,t){var n=i.getProperty(e);t=r?r(n,t):t,void 0!==t&&(s[o(e,n)]=t)}),i.complexProperties.forEach(function(t){var i=e.getProperty(t.name);if(t.isScalar){var a=$(i,n,r);B(a)||(s[o(t.name,t)]=a)}else{var u=i.map(function(e){return $(e,n,r)});s[o(t.name,t)]=u}}),s}function J(e,n,r){var i=e.entityType,a=H(i),o=n.namingConvention.clientPropertyNameToServer,s={};return t(e.entityAspect.originalValues,function(t){var n=i.getProperty(t),u=e.getProperty(t);u=r?r(n,u):u,void 0!==u&&(u=a?a(n,u):u,void 0!==u&&(s[o(t,n)]=u))}),i.complexProperties.forEach(function(t){if(Q(e,t)){var n=e.getProperty(t.name);s[o(t.name,t)]=m(n,function(e){return G(e,r)})}}),s}function Q(e,t){var n=e.getProperty(t.name);return t.isScalar?Z(n):n._origValues?!0:n.some(function(e){return Z(e)})}function Z(e){return B(e.complexAspect.originalValues)?e.complexType.complexProperties.some(function(t){return Q(e,t)}):!0}function H(e){return e.serializerFn||e.metadataStore&&e.metadataStore.serializerFn}function Y(){this.map={}}var W=function(t){if(arguments.length>1)throw new Error("The EntityManager ctor has a single optional argument that is either a 'serviceName' or a configuration object.");0===arguments.length?t={serviceName:""}:"string"==typeof t&&(t={serviceName:t}),e(this,t,!0),this.entityChanged=new ft("entityChanged",this),this.validationErrorsChanged=new ft("validationErrorsChanged",this),this.hasChangesChanged=new ft("hasChangesChanged",this),this.clear()},X=W.prototype;return X._$typeName="EntityManager",ft.bubbleEvent(X,null),X.setProperties=function(t){e(this,t,!1)},X.createEntity=function(e,t,n,r){pt(e,"entityType").isString().or().isInstanceOf(Ft).check(),pt(n,"entityState").isEnumOf(Nt).isOptional().check(),pt(r,"mergeStrategy").isEnumOf(Gt).isOptional().check(),"string"==typeof e&&(e=this.metadataStore._getEntityType(e)),n=n||Nt.Added;var i;return b(this,"isLoading",!0,function(){i=e.createEntity(t)}),n!==Nt.Detached&&(i=this.attachEntity(i,n,r)),i},W.importEntities=function(e,t){var n=new Zt;return n.importEntities(e,t),n},X.acceptChanges=function(){this.getChanges().map(function(e){return e.entityAspect._checkOperation("acceptChanges")}).forEach(function(e){e.acceptChanges()})},X.exportEntities=function(e,t){pt(t,"includeMetadata").isBoolean().isOptional().check(),t=null==t?!0:t;var n=g(this,e),r=p({},n,["tempKeys","entityGroupMap"]);t?(r=p(r,this,["dataService","saveOptions","queryOptions","validationOptions"]),r.metadataStore=this.metadataStore.exportMetadata()):(r.metadataVersion=rt.metadataVersion,r.metadataStoreName=this.metadataStore.name);var i=JSON.stringify(r,null,ht.stringifyPad);return i},X.importEntities=function(e,n){n=n||{},lt(n).whereParam("mergeStrategy").isEnumOf(Gt).isOptional().withDefault(this.queryOptions.mergeStrategy).whereParam("metadataVersionFn").isFunction().isOptional().applyAll(n);var r=this,i="string"==typeof e?JSON.parse(e):e;i.metadataStore?(this.metadataStore.importMetadata(i.metadataStore),this.dataService=i.dataService&&bt.fromJSON(i.dataService)||new bt({serviceName:i.serviceName}),this.saveOptions=new Yt(i.saveOptions),this.queryOptions=Jt.fromJSON(i.queryOptions),this.validationOptions=new wt(i.validationOptions)):n.metadataVersionFn&&n.metadataVersionFn({metadataVersion:i.metadataVersion,metadataStoreName:i.metadataStoreName});var a={};i.tempKeys.forEach(function(e){var t=Pt.fromJSON(e,r.metadataStore);a[t.toString()]=new Pt(t.entityType,r.keyGenerator.generateTempKeyValue(t.entityType,t.values[0]))});var o=[];return n.tempKeyMap=a,O(function(){r._pendingPubs=[]},function(){r._pendingPubs.forEach(function(e){e()}),r._pendingPubs=null,r._hasChangesAction&&r._hasChangesAction()},function(){t(i.entityGroupMap,function(e,t){var i=r.metadataStore._getEntityType(e,!0),a=z(r,i),s=_(a,t,n);Array.prototype.push.apply(o,s)}),o.forEach(function(e){r._linkRelatedEntities(e)})}),{entities:o,tempKeyMapping:a}},X.clear=function(){n(this._entityGroupMap,function(e,t){return t._checkOperation()}).forEach(function(e){e._clear()}),this._entityGroupMap={},this._unattachedChildrenMap=new Y,this.keyGenerator=new this.keyGeneratorCtor,this.entityChanged.publish({entityAction:Et.Clear}),this._setHasChanges(!1)},X.createEmptyCopy=function(){var e=new W(p({},this,["dataService","metadataStore","queryOptions","saveOptions","validationOptions","keyGeneratorCtor"]));return e},X.addEntity=function(e){return this.attachEntity(e,Nt.Added)},X.attachEntity=function(e,t,n){if(pt(e,"entity").isRequired().check(),this.metadataStore._checkEntityType(e),t=pt(t,"entityState").isEnumOf(Nt).isOptional().check(Nt.Unchanged),n=pt(n,"mergeStrategy").isEnumOf(Gt).isOptional().check(Gt.Disallowed),e.entityType.metadataStore!==this.metadataStore)throw new Error("Cannot attach this entity because the EntityType ("+e.entityType.name+") and MetadataStore associated with this entity does not match this EntityManager's MetadataStore.");var r=e.entityAspect;if(r){if(r._inProcessEntity)return r._inProcessEntity}else r=new St(e);var i=r.entityManager;if(i){if(i===this)return e;throw new Error("This entity already belongs to another EntityManager")}var a,o=this;return b(this,"isLoading",!0,function(){t.isAdded()&&k(o,e),a=o._attachEntityCore(e,t,n),r._inProcessEntity=a;try{V(o,e,t,n)}finally{r._inProcessEntity=null}}),this.validationOptions.validateOnAttach&&a.entityAspect.validateEntity(),t.isUnchanged()||this._notifyStateChange(a,!0),this.entityChanged.publish({entityAction:Et.Attach,entity:a}),a},X.detachEntity=function(e){pt(e,"entity").isEntity().check();var t=e.entityAspect;if(!t)return!1;if(t.entityManager!==this)throw new Error("This entity does not belong to this EntityManager.");return t.setDetached()},X.fetchMetadata=function(e,t,n){"function"==typeof e?(n=t,t=e,e=null):(pt(e,"dataService").isInstanceOf(bt).isOptional().check(),pt(t,"callback").isFunction().isOptional().check(),pt(n,"errorCallback").isFunction().isOptional().check());var r=this.metadataStore.fetchMetadata(e||this.dataService);return x(r,t,n)},X.executeQuery=function(e,t,n){pt(e,"query").isInstanceOf(Lt).or().isString().check(),pt(t,"callback").isFunction().isOptional().check(),pt(n,"errorCallback").isFunction().isOptional().check();var r,i=Jt.resolve([e.queryOptions,this.queryOptions,Jt.defaultInstance]),a=bt.resolve([e.dataService,this.dataService]);if(!a.hasServerMetadata||this.metadataStore.hasMetadataFor(a.serviceName))r=R(this,e,i,a);else{var o=this;r=this.fetchMetadata(a).then(function(){return R(o,e,i,a)})}return x(r,t,n)},X.executeQueryLocally=function(e){pt(e,"query").isInstanceOf(Lt).check();var t=this.metadataStore,n=e._getFromEntityType(t,!0),r=U(this,n),i=e.wherePredicate&&e.wherePredicate.toFunction({entityType:n}),a=Jt.resolve([e.queryOptions,this.queryOptions,Jt.defaultInstance]),o=a.includeDeleted===!0,s=function(e){return e&&(o||!e.entityAspect.entityState.isDeleted())&&(i?i(e):!0)},u=[];r.forEach(function(e){u.push.apply(u,e._entities.filter(s))});var p=e.orderByClause&&e.orderByClause.getComparer(n);p&&u.sort(p);var c=e.skipCount;c&&(u=u.slice(c));var l=e.takeCount;l&&(u=u.slice(0,l));var y=e.selectClause;if(y){var f=y.toFunction();u=u.map(f)}return u},X.saveChanges=function(e,t,n,o){function s(e){var t=g.entityManager;h(c,!1);e.entities=g.processSavedEntities(e);return t._setHasChanges(null),n&&n(e),At.resolve(e)}function u(e){var t=e.entities;if(0===t.length)return[];var n=e.keyMappings,r=g.entityManager;return M(r,n),b(r,"isLoading",!0,function(){var e=new Ht({query:null,entityManager:r,mergeOptions:{mergeStrategy:Gt.OverwriteChanges},dataService:v});t=e.visitAndMerge(t,{nodeType:"root"})}),t}function p(e){return h(c,!1),a(g,e),o&&o(e),At.reject(e)}pt(e,"entities").isOptional().isArray().isEntity().check(),pt(t,"saveOptions").isInstanceOf(Yt).isOptional().check(),pt(n,"callback").isFunction().isOptional().check(),pt(o,"errorCallback").isFunction().isOptional().check(),t=t||this.saveOptions||Yt.defaultInstance;var c=F(this,e);if(0===c.length){var l={entities:[],keyMappings:[]};return n&&n(l),At.resolve(l)}if(!t.allowConcurrentSaves){var y=c.some(function(e){return e.entityAspect.isBeingSaved});if(y){var f=new Error("Concurrent saves not allowed - SaveOptions.allowConcurrentSaves is false");return o&&o(f),At.reject(f)}}if(r(c),this.validationOptions.validateOnSave){var d=c.filter(function(e){var t=e.entityAspect,n=t.entityState.isDeleted()||t.validateEntity();return!n});if(d.length>0){var m=new Error("Client side validation errors encountered - see the entityErrors collection on this object for more detail");return m.entityErrors=i(d),o&&o(m),At.reject(m)}}var v=bt.resolve([t.dataService,this.dataService]),g={entityManager:this,dataService:v,processSavedEntities:u,resourceName:t.resourceName||this.saveOptions.resourceName||"SaveChanges"},w={entities:c,saveOptions:t};try{return L(c),v.adapterInstance.saveChanges(g,w).then(s).then(null,p)}catch(f){return h(c,!1),o&&o(f),At.reject(f)}},X._findEntityGroup=function(e){return this._entityGroupMap[e.name]},X.getEntityByKey=function(){var e=y(this,arguments).entityKey,t=e._subtypes||[e.entityType],n=null;return t.some(function(t){var r=this._findEntityGroup(t);return n=r&&r.findEntityByKey(e)},this),n},X.fetchEntityByKey=function(){var e=bt.resolve([this.dataService]);if(!e.hasServerMetadata||this.metadataStore.hasMetadataFor(e.serviceName))return o(this,arguments);var t=this,n=arguments;return this.fetchMetadata(e).then(function(){return o(t,n)})},X.findEntityByKey=function(e){return this.getEntityByKey(e)},X.generateTempKeyValue=function(e){pt(e,"entity").isEntity().check();var t=e.entityType,n=this.keyGenerator.generateTempKeyValue(t),r=t.keyProperties[0];return e.setProperty(r.name,n),e.entityAspect.hasTempKey=!0,n},X.hasChanges=function(e){return this._hasChanges?void 0===e?this._hasChanges:this._hasChangesCore(e):!1},X._hasChangesCore=function(e){e=s(this,e);var t=D(this,e);return t.some(function(e){return e.hasChanges()})},X.getChanges=function(e){e=s(this,e);var t=[Nt.Added,Nt.Modified,Nt.Deleted];return l(this,e,t)},X.rejectChanges=function(){if(!this._hasChanges)return[];var e=[Nt.Added,Nt.Modified,Nt.Deleted],t=l(this,null,e),n=t.map(function(e){return e.entityAspect._checkOperation("rejectChanges")});return this._hasChanges=!1,n.forEach(function(e){e.rejectChanges()}),this.hasChangesChanged.publish({entityManager:this,hasChanges:!1}),t},X.getEntities=function(e,t){return e=s(this,e),pt(t,"entityStates").isOptional().isEnumOf(Nt).or().isNonEmptyArray().isEnumOf(Nt).check(),t=t&&I(this,t),l(this,e,t)},X._notifyStateChange=function(e,t){var n={entityAction:Et.EntityStateChange,entity:e};if(t)this._hasChanges||this._setHasChanges(!0);else if(this._hasChanges){if(this.isLoading)return void(this._hasChangesAction=this._hasChangesAction||function(){this._setHasChanges(null),this.entityChanged.publish(n)}.bind(this));this._setHasChanges(null)}this.entityChanged.publish(n)},X._setHasChanges=function(e){null==e&&(e=this._hasChangesCore());var t=this._hasChanges;this._hasChanges=e,e!=t&&this.hasChangesChanged.publish({entityManager:this,hasChanges:e}),this._hasChangesAction=null},X._linkRelatedEntities=function(e){var t=this,n=e.entityAspect;b(t,"isLoading",!0,function(){var r=t._unattachedChildrenMap,i=n.getKey(),a=r.getTuples(i);a&&a.slice(0).forEach(function(t){var n,a,o=t.children.filter(function(e){return e.entityAspect.entityState!==Nt.Detached}),s=t.navigationProperty;if(s.inverse)if(n=s,a=s.inverse,a.isScalar){var u=o[0];e.setProperty(a.name,u),u.setProperty(n.name,e)}else{var p=e.getProperty(a.name);o.forEach(function(t){p.push(t),t.setProperty(n.name,e)})}else if(s.parentType===e.entityType)if(a=s,a.isScalar)e.setProperty(a.name,o[0]);else{var p=e.getProperty(a.name);o.forEach(function(e){p._push(e)})}else n=s,o.forEach(function(t){t.setProperty(n.name,e)});r.removeChildren(i,n)}),e.entityType.navigationProperties.forEach(function(i){if(i.isScalar){var a=e.getProperty(i.name);if(a)return}var o=n.getParentKey(i);if(o){if(o._isEmpty())return;var s=t.findEntityByKey(o);s?e.setProperty(i.name,s):r.addChild(o,i,e)}}),e.entityType.foreignKeyProperties.forEach(function(n){var i=n.inverseNavigationProperty;if(i){var a=e.getProperty(n.name),o=new Pt(i.parentType,[a]),s=t.findEntityByKey(o);s?i.isScalar?s.setProperty(i.name,e):t.isLoading?s.getProperty(i.name)._push(e):s.getProperty(i.name).push(e):r.addChild(o,i,e)}})})},X._attachEntityCore=function(e,t,n){var r=z(this,e.entityType),i=r.attachEntity(e,t,n);return this._linkRelatedEntities(i),i},X._updateFkVal=function(e,t,n){var r=this._entityGroupMap[e.parentType.name];r&&r._updateFkVal(e,t,n)},X.helper={unwrapInstance:G,unwrapOriginalValues:$,unwrapChangedValues:J},Y.prototype.addChild=function(e,t,n){var r=this.getTuple(e,t);r||(r={navigationProperty:t,children:[]},P(this.map,e.toString()).push(r)),r.children.push(n)},Y.prototype.removeChildren=function(e,t){var n=this.getTuples(e);n&&(E(n,function(e){return e.navigationProperty===t}),n.length||delete this.map[e.toString()])},Y.prototype.getChildren=function(e,t){var n=this.getTuple(e,t);return n?n.children.filter(function(e){return!e.entityAspect.entityState.isDetached()}):null},Y.prototype.getTuple=function(e,t){var n=this.getTuples(e);if(!n)return null;var r=v(n,function(e){return e.navigationProperty===t});return r},Y.prototype.getTuples=function(e){for(var t=this.map[e.toString()],n=e.entityType;!t&&n.baseEntityType;){n=n.baseEntityType;var r=e.toString(n);t=this.map[r]}return t},W}();rt.EntityManager=Zt;var Ht=function(){function e(e,t,i,o){if(i.ignore||null==t)return null;if(i.nodeRefId){var u=a(e,i.nodeRefId);return"function"==typeof u&&null!=o?void e.deferredFns.push(function(){o(u)}):u}if(i.entityType){var p=i.entityType;return e.mergeOptions.noTracking?(t=n(e,p,t),p.noTrackingFn&&(t=p.noTrackingFn(t,p)),i.nodeId&&(e.refMap[i.nodeId]=t),t):p.isComplexType?n(e,p,t):s(e,t,i)}return"object"!=typeof t||k(t)||(t=r(e,t)),i.nodeId&&(e.refMap[i.nodeId]=t),t}function n(e,t,r){var a={};return t.dataProperties.forEach(function(t){a[t.name]=t.isComplexProperty?m(r[t.nameOnServer],function(r){return n(e,t.dataType,r)}):E(r[t.nameOnServer],t.dataType)}),t.navigationProperties&&t.navigationProperties.forEach(function(t){var n={nodeType:"navProp",navigationProperty:t};i(r[t.nameOnServer],e,n,a,t.name)}),a}function r(e,n){var r=e.metadataStore.namingConvention.serverPropertyNameToClient,a={};return t(n,function(t,n){var o=r(t),s={nodeType:"anonProp",propertyName:o};i(n,e,s,a,o)}),a}function i(t,n,r,i,a){var o=n.jsonResultsAdapter,s=o.visitNode(t,n,r)||{};t=s.node||t,s.ignore||(Array.isArray(t)?(r.nodeType=r.nodeType+"Item",i[a]=t.map(function(t,u){return s=o.visitNode(t,n,r)||{},t=s.node||t,e(n,t,s,function(e){i[a][u]=e()})})):i[a]=e(n,t,s,function(e){i[a]=e()}))}function a(e,t){var n=e.refMap[t];return void 0===n?function(){return e.refMap[t]}:n}function o(e,t,n){var r=n._$meta.nodeId;null!=r&&(e.refMap[r]=t)}function s(e,t,n){t._$meta=n;var r=e.entityManager,i=n.entityType;"string"==typeof i&&(i=e.metadataStore._getEntityType(i,!1)),t.entityType=i;var a=e.mergeOptions.mergeStrategy,o=null==e.query,s=i.getEntityKeyFromRawEntity(t,e.rawValueFn),p=r.findEntityByKey(s);if(p){if(o&&p.entityAspect.entityState.isDeleted())return r.detachEntity(p),p;var l=p.entityAspect.entityState;if(a===Gt.Disallowed)throw new Error("A MergeStrategy of 'Disallowed' prevents "+s.toString()+" from being merged");if(a===Gt.SkipMerge)u(e,p,t);else if(a===Gt.OverwriteChanges||l.isUnchanged()){c(e,p,t),p.entityAspect.wasLoaded=!0,n.extraMetadata&&(p.entityAspect.extraMetadata=n.extraMetadata),p.entityAspect.entityState=Nt.Unchanged,p.entityAspect.originalValues={},p.entityAspect.propertyChanged.publish({entity:p,propertyName:null});var y=o?Et.MergeOnSave:Et.MergeOnQuery;r.entityChanged.publish({entityAction:y,entity:p}),l.isUnchanged()||r._notifyStateChange(p,!1)}else{if(l==Nt.Deleted&&!e.mergeOptions.includeDeleted)return null;u(e,p,t)}}else p=i._createInstanceCore(),c(e,p,t),n.extraMetadata&&(p.entityAspect.extraMetadata=n.extraMetadata),r._attachEntityCore(p,Nt.Unchanged,a),p.entityAspect.wasLoaded=!0,r.entityChanged.publish({entityAction:Et.AttachOnQuery,entity:p});return p}function u(e,t,n){o(e,t,n),n.entityType.navigationProperties.forEach(function(t){t.isScalar?f(e,n,t):h(e,n,t)})}function c(e,t,n){o(e,t,n);var r=t.entityType;r._updateTargetFromRaw(t,n,e.rawValueFn),r.navigationProperties.forEach(function(r){r.isScalar?l(e,r,t,n):y(e,r,t,n)})}function l(e,t,n,r){var i=f(e,r,t);null!=i&&("function"==typeof i?e.deferredFns.push(function(){i=i(),d(i,n,t)}):d(i,n,t))}function y(e,t,n,r){var i=h(e,r,t);if(null!=i){var a=t.inverse;if(a){var o=n.getProperty(t.name);o.wasLoaded=!0,i.forEach(function(t){"function"==typeof t?e.deferredFns.push(function(){t=t(),v(t,o,n,a)}):v(t,o,n,a)})}}}function f(e,t,n){var r=t[n.nameOnServer];if(!r)return null;var i=e.visitAndMerge(r,{nodeType:"navProp",navigationProperty:n});return i}function h(e,t,n){var r=t[n.nameOnServer];if(!r)return null;if(!Array.isArray(r)&&(r=r.results,!r))return null;var i=e.visitAndMerge(r,{nodeType:"navPropItem",navigationProperty:n});return i}function d(e,t,n){if(e){var r=n.name,i=t.getProperty(r);if(i!==e){t.setProperty(r,e);var a=n.inverse;if(!a)return;if(a.isScalar)e.setProperty(a.name,t);else{var o=e.getProperty(a.name);o.push(t)}}}}function v(e,t,n,r){if(e){var i=e.getProperty(r.name);i!==n&&(t.push(e),e.setProperty(r.name,n))}}var g=function(e){p(this,e,["query","entityManager","dataService","mergeOptions"]),this.refMap={},this.deferredFns=[],this.jsonResultsAdapter=this.dataService.jsonResultsAdapter,this.metadataStore=this.entityManager.metadataStore,this.rawValueFn=Dt.getRawValueFromServer},w=g.prototype,E=_t.parseRawValue;return w._$typeName="MappingContext",w.getUrl=function(){var e=this.query;if(!e)throw new Error("query cannot be empty");var t;if("string"==typeof e)t=e;else{if(!(e instanceof Lt))throw new Error("unable to recognize query parameter as either a string or an EntityQuery");t=this.dataService.uriBuilder.buildUri(e,this.metadataStore)}return this.dataService.qualifyUrl(t)},w.visitAndMerge=function(t,n){var r=this.query,i=this.jsonResultsAdapter;n=n||{};var a=this;return m(t,function(t){if(null==r&&t.entityAspect)return t.entityAspect.entityState.isDeleted()?a.entityManager.detachEntity(t):t.entityAspect.acceptChanges(),t;var o=i.visitNode(t,a,n)||{};return t=o.node||t,r&&"root"===n.nodeType&&!o.entityType&&(o.entityType=r._getToEntityType&&r._getToEntityType(a.metadataStore)),e(a,t,o)},this.mergeOptions.includeDeleted)},w.processDeferred=function(){this.deferredFns.length>0&&this.deferredFns.forEach(function(e){e()})},g}(),Yt=function(){function e(e,t){return t&<(t).whereParam("resourceName").isOptional().isString().whereParam("dataService").isOptional().isInstanceOf(bt).whereParam("allowConcurrentSaves").isBoolean().isOptional().whereParam("tag").isOptional().applyAll(e),e}var t=function(t){e(this,t)},n=t.prototype;return n._$typeName="SaveOptions",n.setAsDefault=function(){return l(this,t)},n.using=function(t){return e(this,t)},t.defaultInstance=new t({allowConcurrentSaves:!1}),t}();return rt.SaveOptions=Yt,rt.AbstractDataServiceAdapter=function(){function e(){this.getRequest=function(e){return e},this.done=function(){}}function t(e,t,r){var i=n(t);return a._catchNoConnectionError(i),r&&(i.message=r+"; "+i.message),e.reject(i)}function n(e){var t=new Error;t.httpResponse=e,t.status=e.status;var n=e.data;if(!n)return t.message=e.error&&e.error.toString(),t;if("string"==typeof n)try{n=JSON.parse(n)}catch(r){return t.message=n,t}var i,a,o=e.saveContext,s=n.Message||n.ExceptionMessage||n.EntityErrors||n.Errors,u=!!s;if(u){var s=n;do i=s.ExceptionMessage||s.Message,s=s.InnerException;while(s);a=n.Errors||n.EntityErrors,a=a&&a.map(function(e){return{errorName:e.ErrorName,entityTypeName:Ct.normalizeTypeName(e.EntityTypeName),keyValues:e.KeyValues,propertyName:e.PropertyName,errorMessage:e.ErrorMessage}})}else i=n.message,a=n.errors||n.entityErrors;if(o&&a){var p=o.entityManager.metadataStore.namingConvention.serverPropertyNameToClient;a.forEach(function(e){e.propertyName=e.propertyName&&p(e.propertyName)}),t.entityErrors=a}return t.message=i||"Server side errors encountered - see the entityErrors collection on this object for more detail",t}var r,i=function(){},a=i.prototype;return a.checkForRecomposition=function(e){"ajax"===e.interfaceName&&e.isDefault&&this.initialize()},a.initialize=function(){if(r=rt.config.getAdapterInstance("ajax"),!r||!r.ajax)throw new Error("Unable to find ajax adapter for dataservice adapter '"+(this.name||"")+"'.")},a.fetchMetadata=function(e,n){var i=n.serviceName,a=n.qualifyUrl("Metadata"),o=At.defer();return r.ajax({type:"GET",url:a,dataType:"json",success:function(r){if(e.hasMetadataFor(i))return o.resolve("already fetched");var s=r.data;try{var u="string"==typeof s?JSON.parse(s):s;e.importMetadata(u)}catch(p){var c="Unable to either parse or import metadata: "+p.message;return t(o,r,"Metadata query failed for: "+a+". "+c)}return e.hasMetadataFor(i)||e.addDataService(n),o.resolve(u)},error:function(e){t(o,e,"Metadata query failed for: "+a)}}),o.promise},a.executeQuery=function(e){var n=At.defer(),i=e.getUrl(),a={type:"GET",url:i,params:e.query.parameters,dataType:"json",success:function(e){var r=e.data;try{var i,a=r&&(r.results||r.Results);i=a?{results:a,inlineCount:r.inlineCount||r.InlineCount,httpResponse:e}:{results:r,httpResponse:e},n.resolve(i)}catch(o){o instanceof Error?n.reject(o):t(n,e)}},error:function(e){t(n,e)}};return e.dataService.useJsonp&&(a.dataType="jsonp",a.crossDomain=!0),r.ajax(a),n.promise},a.saveChanges=function(e,n){var i=e.adapter=this,a=At.defer();n=i._prepareSaveBundle(e,n);var o=JSON.stringify(n),s=e.dataService.qualifyUrl(e.resourceName);return r.ajax({type:"POST",url:s,dataType:"json",contentType:"application/json",data:o,success:function(n){n.saveContext=e;var r=n.data;if(r.Errors||r.errors)t(a,n);else{var o=i._prepareSaveResult(e,r);o.httpResponse=n,a.resolve(o)}},error:function(n){n.saveContext=e,t(a,n)}}),a.promise},a._prepareSaveBundle=function(){throw new Error("Need a concrete implementation of _prepareSaveBundle")},a.changeRequestInterceptor=e,a._createChangeRequestInterceptor=function(t,n){var r=t.adapter,i=V,a=r.changeRequestInterceptor,o=r.name+" DataServiceAdapter's ChangeRequestInterceptor",s=" is missing or not a function.";if(i(a)){var u=new a(t,n);if(!i(u.getRequest))throw new Error(o+".getRequest"+s);if(!i(u.done))throw new Error(o+".done"+s);return u}return new e(t,n)},a._prepareSaveResult=function(){throw new Error("Need a concrete implementation of _prepareSaveResult")},a.jsonResultsAdapter=new Ot({name:"noop",visitNode:function(){return{}}}),a._catchNoConnectionError=function(e){0==e.status&&null==e.message&&(e.message="HTTP response status 0 and no message. Likely did not or could not reach server. Is the server running?")},i}(),rt});