text: (function(e){"object"==typeof exports?module.exports=e():"function"==typeof define?define(e):breeze=e()})(function(){function e(e,t){for(var n in e)U(e,n)&&t(n,e[n])}function t(e,t){for(var n in e)if(U(e,n)){var r=e[n];if(t(n,r))return{key:n,value:r}}return null}function n(e,t){var n=[];for(var r in e)if(U(e,r)){var a=t?t(r,e[r]):e[r];void 0!==a&&n.push(a)}return n}function r(e,t){return function(n){return n[e]===t}}function a(e){return function(t){return t[e]}}function i(e){var t=[];for(var n in e)U(e,n)&&t.push(e[n]);return t}function o(e,t){if(!t)return e;for(var n in t)U(t,n)&&(e[n]=t[n]);return e}function s(e,t){for(var n in t)void 0===e[n]&&(e[n]=t[n]);return e}function u(e,t){return t.defaultInstance=s(new t(e),t.defaultInstance),e}function p(e,t){var n={};for(var r in t)if(r in e){var a=e[r],i=t[r];a!=i&&(Array.isArray(a)&&0===a.length||("function"==typeof i?a=i(a):"object"==typeof a&&a&&a.parentEnum&&(a=a.name),void 0!==a&&(n[r]=a)))}return n}function c(e,t){var n={},r=e.length;return t.forEach(function(t){for(var a=0;r>a;a++){var i=e[a];if(i){var o=i[t];if(void 0!==o){n[t]=o;break}}}}),n}function y(e){return e?Array.isArray(e)?e:[e]:[]}function l(e,t){for(var n=0,r=e.length;r>n;n++)if(t(e[n]))return e[n];return null}function f(e,t){for(var n=0,r=e.length;r>n;n++)if(t(e[n]))return n;return-1}function h(e,t,n){for(var r=O(t)?t:void 0,a=e.length-1,i=!1,o=a;o>=0;o--)if((r?r(e[o]):e[o]===t)&&(e.splice(o,1),i=!0,!n))return i;return i}function d(e,t,n){for(var r=[],a=Math.min(e.length,t.length),i=0;a>i;++i)r.push(n(e[i],t[i]));return r}function m(e,t,n){if(!e||!t)return!1;if(e.length!==t.length)return!1;for(var r=0;e.length>r;r++)if(Array.isArray(e[r])){if(!m(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 v(e,t){var n=e[t];return n||(n=[],e[t]=n),n}function g(e,t){for(var n=e.split(";"),r=0,a=n.length;a>r;r++){var i=_(n[r]);if(i)return i}if(t)throw Error("Unable to initialize "+e+".  "+t||"")}function _(e){var t;try{if(this.window){var n=this.window;if(t=n[e])return t;if(n.require&&(t=n.require(e)),t)return t}require&&(t=require(e))}catch(r){}return t}function S(e,t,n,r){var a=e[t];if(n===a)return r();e[t]=n;try{return r()}finally{void 0===a?delete e[t]:e[t]=a}}function T(e,t,n){var r;try{return r=e(),n()}catch(a){throw"object"==typeof r&&(r.error=a),a}finally{t(r)}}function E(e){return function(){for(var t=z(arguments),n="",r=t.length,a=null;r--;)a=t[r],n+=a===Object(a)?JSON.stringify(a):a,e.memoize||(e.memoize={});return n in e.memoize?e.memoize[n]:e.memoize[n]=e.apply(this,t)}}function P(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=0|16*Math.random(),n="x"==e?t:8|3&t;return n.toString(16)})}function b(e){if("string"!=typeof e)throw 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 Error("Invalid ISO8601 duration '"+e+"'");for(var n=[2,3,4,6,7,8],r=[31104e3,2592e3,86400,3600,60,1],a=0,i=0;6>i;i++){var o=t[n[i]];o=o?+o.replace(/[A-Za-z]+/g,""):0,a+=o*r[i]}return a}function N(e){return null===e?"null":void 0===e?"undefined":Object.prototype.toString.call(e).slice(8,-1).toLowerCase()}function w(e){return"date"===N(e)&&!isNaN(e.getTime())}function O(e){return"function"===N(e)}function C(e){return"string"==typeof e&&/[a-fA-F\d]{8}-(?:[a-fA-F\d]{4}-){3}[a-fA-F\d]{12}/.test(e)}function A(e){return"string"==typeof e&&/^(-|)?P([0-9]+Y|)?([0-9]+M|)?([0-9]+D|)?T?([0-9]+H|)?([0-9]+M|)?([0-9]+S|)?/.test(e)}function x(e){if(null===e||void 0===e)return!0;for(var t in e)if(U(e,t))return!1;return!0}function M(e){return!isNaN(parseFloat(e))&&isFinite(e)}function k(e,t){return e&&t?0===e.indexOf(t,0):!1}function I(e,t){return e&&t?-1!==e.indexOf(t,e.length-t.length):!1}function D(e){var t=arguments,n=RegExp("%([1-"+(arguments.length-1)+"])","g");return e.replace(n,function(e,n){return t[n]})}function V(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(),a=e.dataType;if(a&&a.parse&&(t=Array.isArray(t)&&!e.isScalar?t.map(function(e){return a.parse(e,typeof e)}):a.parse(t,typeof t)),!(t===r||a&&a.isDate&&t&&r&&t.valueOf()===r.valueOf())){var i,o,s,u=this,p=e.name,c=this.entityAspect;c?i=c:(i=this.complexAspect,c=i.getEntityAspect());var y=i.getPropertyPath(p),l=c._inProcess;if(l){if(l.indexOf(e)>=0)return;l.push(e)}else l=[e],c._inProcess=l;var f=c.entity;try{var h=c.entityManager;if(c.entityState.isUnchangedOrModified()&&void 0===i.originalValues[p]&&e.isDataProperty&&!e.isComplexProperty&&(i.originalValues[p]=void 0!==r?r:e.defaultValue),e.isComplexProperty){if(!e.isScalar)throw Error(D("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.",e.name,e.parentType.name));if(!t)throw Error(D("You cannot set the '%1' property to null because it's datatype is the ComplexType: '%2'",e.name,e.dataType.name));if(!r){var d=a.getCtor();r=new d,n(r)}a.dataProperties.forEach(function(e){var n=e.name,a=t.getProperty(n);r.setProperty(n,a)})}else if(e.isDataProperty){if(!e.isScalar)throw Error("Nonscalar data properties are readonly - items may be added or removed but the collection may not be changed.");if(e.isPartOfKey&&!this.complexAspect&&h&&!h.isLoading){var m=this.entityType.keyProperties,v=m.map(function(n){return n===e?t:this.getProperty(n.name)},this),g=new st(this.entityType,v);if(h.findEntityByKey(g))throw Error("An entity with this key is already in the cache: "+(""+g));var _=this.entityAspect.getKey(),S=h._findEntityGroup(this.entityType);S._replaceKey(_,g)}var T=e.relatedNavigationProperty;if(T&&h)null!=t?(o=new st(T.entityType,[t]),s=h.findEntityByKey(o),s?this.setProperty(T.name,s):h._unattachedChildrenMap.addChild(o,T,this)):this.setProperty(T.name,null);else if(e.inverseNavigationProperty&&h&&!h._inKeyFixup){var E=e.inverseNavigationProperty;if(null!=r&&(o=new st(E.parentType,[r]),s=h.findEntityByKey(o)))if(E.isScalar)s.setProperty(E.name,null);else{var P=s.getProperty(E.name);P.splice(P.indexOf(this),1)}null!=t&&(o=new st(E.parentType,[t]),s=h.findEntityByKey(o),s?E.isScalar?s.setProperty(E.name,this):s.getProperty(E.name).push(this):h._unattachedChildrenMap.addChild(o,E,this))}if(n(t),h&&!h.isLoading&&(c.entityState.isUnchanged()&&!e.isUnmapped&&c.setModified(),h.validationOptions.validateOnPropertyChange&&c._validateProperty(t,{entity:f,property:e,propertyName:y,oldValue:r})),e.isPartOfKey&&!this.complexAspect){var b=this.entityType.keyProperties.indexOf(e);this.entityType.navigationProperties.forEach(function(e){var n=e.inverse,r=n?n.foreignKeyNames:e.invForeignKeyNames;if(0!==r.length){var a=u.getProperty(e.name),i=r[b];if(e.isScalar){if(!a)return;a.setProperty(i,t)}else a.forEach(function(e){e.setProperty(i,t)})}}),c.getKey(!0)}}else{if(!e.isScalar)throw Error("Nonscalar navigation properties are readonly - entities can be added or removed but the collection may not be changed.");var N=e.inverse;if(null!=t){var w=t.entityAspect;if(h){if(w.entityState.isDetached())h.isLoading||h.attachEntity(t,ut.Added);else if(w.entityManager!==h)throw Error("An Entity cannot be attached to an entity in another EntityManager. One of the two entities must be detached first.")}else w&&w.entityManager&&(h=w.entityManager,h.isLoading||h.attachEntity(c.entity,ut.Added))}if(N)if(N.isScalar)null!=r&&r.setProperty(N.name,null),null!=t&&t.setProperty(N.name,this);else{if(null!=r){var O=r.getProperty(N.name),C=O.indexOf(this);-1!==C&&O.splice(C,1)}if(null!=t){var A=t.getProperty(N.name);A.push(this)}}else if(e.invForeignKeyNames&&h&&!h._inKeyFixup){var x=e.invForeignKeyNames;if(null!=t){var M=this.entityAspect.getKey().values;x.forEach(function(e,n){t.setProperty(e,M[n])})}else null!=r&&x.forEach(function(e){var t=r.entityType.getProperty(e);t.isPartOfKey||r.setProperty(e,null)})}if(n(t),h&&!h.isLoading&&(c.entityState.isUnchanged()&&!e.isUnmapped&&c.setModified(),h.validationOptions.validateOnPropertyChange&&c._validateProperty(t,{entity:this,property:e,propertyName:y,oldValue:r})),e.relatedDataProperties&&!c.entityState.isDeleted()){var k=e.entityType.keyProperties;k.forEach(function(n,r){var a=e.relatedDataProperties[r];if(t||!a.isPartOfKey){var i=t?t.getProperty(n.name):a.defaultValue;u.setProperty(a.name,i)}})}}var I={entity:f,property:e,propertyName:y,oldValue:r,newValue:t};h?h.isLoading||h.isRejectingChanges||(c.propertyChanged.publish(I),h.entityChanged.publish({entityAction:at.PropertyChange,entity:f,args:I})):c.propertyChanged.publish(I)}finally{l.pop()}}}function F(e){return e.indexOf(":#")>=0}function K(e,t){return e+":#"+t}function R(e,t,n){if(t)if(Array.isArray(t))t.forEach(e.addProperty.bind(e));else{if("object"!=typeof t)throw 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(U(t,r)){var a=t[r];a.name=r;var i=new n(a);e.addProperty(i)}}}function q(e,t){var n;if(n=Array.isArray(t)?t:t.split("."),1===n.length)return e.getProperty(t);for(var r=e,a=0;n.length>a&&(r=r.getProperty(n[a]),null!=r);a++);return r}function L(e){return e&&e.isDate?function(e){return e&&e.getTime()}:e===yt.Time?function(e){return e&&b(e)}:function(e){return e}}var B={version:"1.3.6",metadataVersion:"1.0.5"};B.entityModel=B,B.entityTracking_backingStore="backingStore",B.entityTracking_ko="ko",B.entityTracking_backbone="backbone",B.remoteAccess_odata="odata",B.remoteAccess_webApi="webApi";var U=V(Object.prototype.hasOwnProperty),z=V(Array.prototype.slice);Object.create||(Object.create=function(e){var t=function(){};return t.prototype=e,new t});var G={};G.objectForEach=e,G.extend=o,G.propEq=r,G.pluck=a,G.arrayEquals=m,G.arrayFirst=l,G.arrayIndexOf=f,G.arrayRemoveItem=h,G.arrayZip=d,G.requireLib=g,G.using=S,G.memoize=E,G.getUuid=P,G.durationToSeconds=b,G.isDate=w,G.isGuid=C,G.isDuration=A,G.isFunction=O,G.isEmpty=x,G.isNumeric=M,G.stringStartsWith=k,G.stringEndsWith=I,G.formatString=D,G.parent=B,B.core=G;var $=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 a(e,t){return null==t?!1:e.enumType.contains(t)}function i(e,t){return e.allowNull?void 0!==t:null!=t}function s(e,t){if(null==t)return!0;var n=e.prevContext;return n?n.fn(n,t):!0}function u(e,t){var n=e.prevContext,r=n?" or it "+y(n,t):"";return"is optional"+r}function p(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,a=r?" where each element "+y(r,t):"";return" must be "+n+a}function y(e,t){var n=e.msg;return"function"==typeof n&&(n=n(e,t)),n}function l(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 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 Error(D("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 l(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 l(this,{fn:t,typeName:e,msg:D("must be a '%1'",e)})},v.isInstanceOf=function(e,t){return t=t||e.prototype._$typeName,l(this,{fn:n,type:e,typeName:t,msg:D("must be an instance of '%1'",t)})},v.hasProperty=function(e){return l(this,{fn:r,propertyName:e,msg:D("must have a '%1' property ",e)})},v.isEnumOf=function(e){return l(this,{fn:a,enumType:e,msg:D("must be an instance of the '%1' enumeration",e.name)})},v.isRequired=function(e){return l(this,{fn:i,allowNull:e,msg:"is required"})},v.isOptional=function(){var e={fn:s,prevContext:null,msg:u};return l(this,e)},v.isNonEmptyArray=function(){return this.isArray(!0)},v.isArray=function(e){var t={fn:p,mustNotBeEmpty:e,prevContext:null,msg:c};return l(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 Error(this.getMessage());return void 0!==this.v?this.v:e}},v._addContext=function(e){return l(this,e)},v.getMessage=function(){var e=this,t=this._contexts.map(function(t){return y(t,e.v)}).join(", or it ");return D(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,n){var r=e._$typeName;n=n||r&&this.parent.config._$typeName===r;var a=o({},this.parent.config);if(this.parent.params.forEach(function(r){n||delete a[r.name];try{r.check()}catch(i){d(e,i.message)}!t&&r._applyOne(e)}),!n)for(var i in a)void 0!==a[i]&&d(e,D("Unknown property: '%1'.",i))},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}(),Q=function(e,t){return new $(e,t)},J=function(){var e=function(e){if("object"!=typeof e)throw 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 $(this.config[e],e);return t.parent=this,this.params.push(t),t},e}(),H=function(e){return new J(e)};G.Param=$,G.assertParam=Q,G.assertConfig=H;var X=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.seal=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)||O(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=l(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}();G.Enum=X;var W=function(){function e(e,t,r){var a=e._subscribers;return a?(a.forEach(function(a){try{a.callback(t)}catch(i){i.context="unable to publish on topic: "+e.name,r?r(i):e._defaultErrorCallback?e._defaultErrorCallback(i):n(i)}}),void 0):!0}function t(e){if(r[e])return e;var t=l(Object.keys(r),function(t){return 0===t.indexOf(e)});if(!t)throw Error("Unable to find any registered event that matches: "+e);return t}function n(){}var r={},a=1,i=function(e,t,n){Q(e,"eventName").isNonEmptyString().check(),Q(t,"publisher").isObject().check(),this.name=e,r[e]=!0,this.publisher=t,n&&(this._defaultErrorCallback=n)},o=i.prototype;return o.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},o.publishAsync=function(e,t){this.publish(e,!0,t)},o.subscribe=function(e){this._subscribers||(this._subscribers=[]);var t=a;return this._subscribers.push({unsubKey:t,callback:e}),++a,t},o.unsubscribe=function(e){if(!this._subscribers)return!1;var t=this._subscribers,n=f(t,function(t){return t.unsubKey===e});return-1!==n?(t.splice(n,1),0===t.length&&(this._subscribers=null),!0):!1},o.clear=function(){this._subscribers=null},i.bubbleEvent=function(e,t){e._getEventParent=t},i.enable=function(e,n,r){Q(e,"eventName").isNonEmptyString().check(),Q(n,"obj").isObject().check(),Q(r,"isEnabled").isBoolean().isOptional().or().isFunction().check(),e=t(e),n._$eventMap||(n._$eventMap={}),n._$eventMap[e]=r},i._enableFast=function(e,t,n){t._$eventMap||(t._$eventMap={}),t._$eventMap[e.name]=n},i.isEnabled=function(e,n){if(Q(e,"eventName").isNonEmptyString().check(),Q(n,"obj").isObject().check(),!n._getEventParent)throw Error("This object does not support event enabling/disabling");return i._isEnabled(n,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}();G.Event=W;var Y=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),a.interfaceInitialized.publish({interfaceName:e.name,instance:r,isDefault:!0}),r.checkForRecomposition&&a.interfaceInitialized.subscribe(function(e){r.checkForRecomposition(e)}),r}function r(e){var n=e.toLowerCase(),r=t(a.interfaceRegistry||{},function(e){return e.toLowerCase()===n});if(!r)throw Error("Unknown interface name: "+e);return r.value}var a={};a.functionRegistry={},a.typeRegistry={},a.objectRegistry={},a.interfaceInitialized=new W("interfaceInitialized_config",a);var i=function(e){this.name=e,this.defaultInstance=null,this._implMap={}};return i.prototype.registerCtor=function(e,t){this._implMap[e.toLowerCase()]={ctor:t,defaultInstance:null}},i.prototype.getImpl=function(e){return this._implMap[e.toLowerCase()]},i.prototype.getFirstImpl=function(){var e=t(this._implMap,function(){return!0});return e?e.value:null},a.interfaceRegistry={ajax:new i("ajax"),modelLibrary:new i("modelLibrary"),dataService:new i("dataService")},a.interfaceRegistry.modelLibrary.getDefaultInstance=function(){if(!this.defaultInstance)throw 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},a.setProperties=function(e){H(e).whereParam("remoteAccessImplementation").isOptional().whereParam("trackingImplementation").isOptional().whereParam("ajaxImplementation").isOptional().applyAll(e),e.remoteAccessImplementation&&a.initializeAdapterInstance("dataService",e.remoteAccessImplementation),e.trackingImplementation&&a.initializeAdapterInstance("modelLibrary",e.trackingImplementation),e.ajaxImplementation&&a.initializeAdapterInstance("ajax",e.ajaxImplementation)},a.registerAdapter=function(e,t){Q(e,"interfaceName").isNonEmptyString().check(),Q(t,"adapterCtor").isFunction().check();var n=new t,a=n.name;if(!a)throw Error("Unable to locate a 'name' property on the constructor passed into the 'registerAdapter' call.");var i=r(e);i.registerCtor(a,t)},a.getAdapter=function(e,t){var n=r(e);if(t){var a=n.getImpl(t);return a?a.ctor:null}return n.defaultInstance?n.defaultInstance._$impl.ctor:null},a.initializeAdapterInstances=function(e){return H(e).whereParam("dataService").isOptional().whereParam("modelLibrary").isOptional().whereParam("ajax").isOptional().applyAll(this,!1),n(e,a.initializeAdapterInstance)},a.initializeAdapterInstance=function(t,n,a){a=void 0===a?!0:a,Q(t,"interfaceName").isNonEmptyString().check(),Q(n,"adapterName").isNonEmptyString().check(),Q(a,"isDefault").isBoolean().check();var i=r(t),o=i.getImpl(n);if(!o)throw Error("Unregistered adapter.  Interface: "+t+" AdapterName: "+n);return e(i,o,a)},a.getAdapterInstance=function(t,n){var a,i=r(t);return n&&""!==n?(a=i.getImpl(n),a?a.defaultInstance:null):i.defaultInstance?i.defaultInstance:(a=i.getFirstImpl(),a.defaultInstance?a.defaultInstance:e(i,a,!0))},a.registerFunction=function(e,t){Q(e,"fn").isFunction().check(),Q(t,"fnName").isString().check(),e.prototype._$fnName=t,a.functionRegistry[t]=e},a._storeObject=function(e,t,n){var r=("string"==typeof t?t:t.prototype._$typeName)+"."+n;a.objectRegistry[r]=e},a._fetchObject=function(e,t){if(!t)return void 0;var n=("string"==typeof e?e:e.prototype._$typeName)+"."+t,r=a.objectRegistry[n];if(!r)throw Error("Unable to locate a registered object by the name: "+n);return r},a.registerType=function(e,t){Q(e,"ctor").isFunction().check(),Q(t,"typeName").isString().check(),e.prototype._$typeName=t,a.typeRegistry[t]=e},a.stringifyPad="  ",a}(),Z=Y.interfaceRegistry.modelLibrary;G.config=Y,B.config=Y;var et=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?a(e._pendingArgs,n):(e._pendingArgs=n,r.push(function(){e[t].publish(e._pendingArgs),e._pendingArgs=null})):e[t].publish(n)}function a(e,t){for(var n in t)if("array"!==n&&e.hasOwnProperty(n)){var r=t[n],a=e[n];if(a){if(!Array.isArray(a))throw Error("Cannot combine non array args");Array.prototype.push.apply(a,r)}else e[n]=r}}function i(e,t,n){e.parent=t,e.parentProperty=n}var o={};return o.push=function(){if(this._inProgress)return-1;var e=this._getGoodAdds(z(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=z(arguments);this._beforeChange();var n=Array.prototype.push.apply(this,e);return t(this,e),n},o.unshift=function(){var e=this._getGoodAdds(z(arguments));if(!e.length)return this.length;this._beforeChange();var n=Array.prototype.unshift.apply(this,e);return t(this,z(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(z(arguments,2)),r=z(arguments,0,2).concat(e);this._beforeChange();var a=Array.prototype.splice.apply(this,r);return n(this,a),e.length&&t(this,e),a},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:i}}(),tt=function(){function t(e,t,n){return t?e.replace(/%([^%]+)%/g,function(e,r){var a;return a=n?t.hasOwnProperty(r)?t[r]:"":t[r],a?O(a)?a(t):a:""}):e}function n(e,t,n,r){return y.messageTemplates[e]=D("'%displayName%' must be an integer between the values of %1 and %2",t,n),function(){var a=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 y(e,a,r)}}var r=-32768,a=32767,i=-2147483648,s=2147483647,u=0,p=255,c={displayName:function(e){return e.property?e.property.displayName||e.propertyName||e.property.name:"Value"}},y=function(e,t,n){this._baseContext=n||{},this._baseContext.name=e,n=o(Object.create(c),this._baseContext),n.messageTemplate=n.messageTemplate||y.messageTemplates[e],this.name=e,this.valFn=t,this.context=n},l=y.prototype;return l._$typeName="Validator",l.validate=function(e,t){var n;return n=t?o(Object.create(this.context),t):this.context,this.currentContext=n,this.valFn(e,n)?null:(n.value=e,new nt(this,n,this.getMessage()))},l.getMessage=function(){try{var e=this.currentContext,n=e.message;return n?"function"==typeof n?n(e):n:e.messageTemplate?t(e.messageTemplate,e):"invalid value: "+this.name||"{unnamed validator}"}catch(r){return"Unable to format error message"+(""+r)}},l.toJSON=function(){return this._baseContext},y.fromJSON=function(e){var t="Validator."+e.name,n=Y.functionRegistry[t];if(!n)throw Error("Unable to locate a validator named:"+e.name);return n(e)},y.register=function(e){Y.registerFunction(function(){return e},"Validator."+e.name)},y.registerFactory=function(e,t){Y.registerFunction(e,"Validator."+t)},y.messageTemplates={required:"'%displayName%' is required",date:"'%displayName%' must be a date",string:"'%displayName%' must be a string",bool:"'%displayName%' must be a 'true' or 'false' value",guid:"'%displayName%' must be a GUID",duration:"'%displayName%' must be a ISO8601 duration string, such as 'P3H24M60S'",number:"'%displayName%' must be a number",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 less than %maxLength% characters",stringLength:"'%displayName%' must be a string with between %minLength% and %maxLength% characters"},y.required=function(){var e=function(e,t){return"string"==typeof e?t&&t.allowEmptyStrings?!0:e.length>0:null!=e};return new y("required",e)},y.maxLength=function(e){var t=function(e,t){return null==e?!0:"string"!=typeof e?!1:e.length<=t.maxLength};return new y("maxLength",t,e)},y.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 y("stringLength",t,e)},y.string=function(){var e=function(e){return null==e?!0:"string"==typeof e};return new y("string",e)},y.guid=function(){var e=function(e){return null==e?!0:C(e)};return new y("guid",e)},y.duration=function(){var e=function(e){return null==e?!0:A(e)};return new y("duration",e)},y.number=y.double=y.single=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))};return new y("number",t,e)},y.integer=y.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 y("integer",t,e)},y.int32=function(e){return n("int32",i,s,e)()},y.int16=function(e){return n("int16",r,a,e)()},y.byte=function(e){return n("byte",u,p,e)()},y.bool=function(){var e=function(e){return null==e?!0:e===!0||e===!1};return new y("bool",e)},y.none=function(){var e=function(){return!0};return new y("none",e)},y.date=function(){var e=function(e){if(null==e)return!0;if("string"!=typeof e)return w(e);try{return!isNaN(Date.parse(e))}catch(t){return!1}};return new y("date",e)},e(y,function(e,t){"function"==typeof t&&"fromJSON"!==e&&"register"!==e&&"registerFactory"!==e&&Y.registerFunction(t,"Validator."+e)}),y}(),nt=function(){var e=function(e,t,n){Q(e,"validator").isString().or().isInstanceOf(tt).check(),this.validator=e,t=t||{},this.context=t,this.property=t.property,this.property&&(this.propertyName=t.propertyName||t.property.name),this.errorMessage=n,this.key=nt.getKey(e,this.propertyName)};return e.getKey=function(e,t){return(t||"")+":"+e.name},e}();B.Validator=tt,B.ValidationError=nt;var rt=function(){function e(e,t){return t&&H(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 rt(this);return e(n,t),n},n.setAsDefault=function(){return u(this,t)},t.defaultInstance=new t({validateOnAttach:!0,validateOnSave:!0,validateOnQuery:!1,validateOnPropertyChange:!0}),t}();B.ValidationOptions=rt,B.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 Error("The complexObject is already attached. Either clone it or remove it from its current owner");a(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 a(e,t){var n=e.complexAspect;return n.parent===t.parent?null:(n.parent=t.parent,n.parentProperty=t.parentProperty,n)}function i(e,t,n){return et.initializeParent(e,t,n),e.arrayChanged=new W("arrayChanged_complexArray",e),o(e,et.mixin),o(e,s)}var s={};return s._getGoodAdds=function(t){return e(this,t)},s._beforeChange=function(){et.updateEntityState(this)},s._processAdds=function(e){t(this,e)},s._processRemoves=function(e){n(this,e)},s._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)}),Array.prototype.push.apply(this,this._origValues)}},s._acceptChanges=function(){this._origValues=null},i}();var at=function(){var e={isAttach:function(){return!!this.isAttach},isDetach:function(){return!!this.isDetach},isModification:function(){return!!this.isModification}},t=new X("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.seal(),t}();B.EntityAction=at;var it=function(){function t(e){var n=e.entityAspect||e.complexAspect,r=e.entityType||e.complexType,a=n.originalValues;for(var i in a)e.setProperty(i,a[i]);r.complexProperties.forEach(function(n){var r=e.getProperty(n.name);n.isScalar?t(r):(r._rejectChanges(),r.forEach(function(e){t(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(function(e){n(e)}))})}function r(e){var t=!0,n=e.entityType||e.complexType,a=e.entityAspect||e.complexAspect,i=e.entityAspect||e.complexAspect.getEntityAspect();return n.getProperties().forEach(function(n){var o=e.getProperty(n.name),s=a.getPropertyPath(n.name);if(n.validators.length>0){var u={entity:i.entity,property:n,propertyName:s};t=i._validateProperty(o,u)&&t}n.isComplexProperty&&n.isScalar&&(t=r(o)&&t)}),n.validators.forEach(function(e){t=u(i,e,a.entity)&&t}),t}function a(e,t){var n=t.isDeleted();n?o(e,!0):S(e.entityAspect.entityManager,"isLoading",!0,function(){o(e,!1)})}function o(e,t){e.entityType.navigationProperties.forEach(function(n){var r=n.inverse;if(r){var a=e.getProperty(n.name);if(n.isScalar){if(a){if(r.isScalar)s(a,r,t);else{var i=a.getProperty(r.name);i.length&&h(i,e)}e.setProperty(n.name,null)}}else a.slice(0).forEach(function(e){r.isScalar&&s(e,r,t)}),a.length=0}})}function s(e,t,n){if(n)e.setProperty(t.name,null);else{e.entityAspect.entityManager;var r=t.foreignKeyNames;if(r)var a=r.map(function(t){return e.getProperty(t)});e.setProperty(t.name,null),r&&r.forEach(function(t,n){e.setProperty(t,a[n])})}}function u(e,t,n,r){var a=t.validate(n,r);return a?(e._addValidationError(a),!1):(e._removeValidationError(t,r?r.propertyName:null),!0)}var p=function(e){if(null===e){var t=it._nullInstance;if(t)return t;it._nullInstance=this
  }else{if(void 0===e)throw Error("The EntityAspect ctor requires an entity as its only argument.");if(e.entityAspect)return e.entityAspect}if(!(this instanceof it))return new it(e);if(this.entity=e,this.entityGroup=null,this.entityManager=null,this.entityState=ut.Detached,this.isBeingSaved=!1,this.originalValues={},this._validationErrors={},this.validationErrorsChanged=new W("validationErrorsChanged_entityAspect",this),this.propertyChanged=new W("propertyChanged_entityAspect",this),null!=e){e.entityAspect=this;var n=e.entityType;if(!n){var r=e.prototype._$typeName;throw r?Error("Metadata for this entityType has not yet been resolved: "+r):Error("This entity is not registered as a valid EntityType")}var a=n.getEntityCtor();Z.getDefaultInstance().startTracking(e,a.prototype)}},c=p.prototype;return c._postInitialize=function(){var e=this.entity,t=e.entityType.getEntityCtor(),n=t._$initializationFn;n&&("string"==typeof n&&(n=e[n]),n(e))},W.bubbleEvent(c,function(){return this.entityManager}),c.getKey=function(e){if(e=Q(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 st(t,r)}return this._entityKey},c.acceptChanges=function(){var e=this.entityManager;this.entityState.isDeleted()?e.detachEntity(this.entity):this.setUnchanged(),e.entityChanged.publish({entityAction:at.AcceptChanges,entity:this.entity})},c.rejectChanges=function(){var e=this.entity,n=this.entityManager;S(n,"isRejectingChanges",!0,function(){t(e)}),this.entityState.isAdded()?(n.detachEntity(e),n._notifyStateChange(e,!1)):(this.entityState.isDeleted()&&this.entityManager._linkRelatedEntities(e),this.setUnchanged(),this.propertyChanged.publish({entity:e,propertyName:null}),this.entityManager.entityChanged.publish({entityAction:at.RejectChanges,entity:e}))},c.getPropertyPath=function(e){return e},c.setUnchanged=function(){n(this.entity),delete this.hasTempKey,this.entityState=ut.Unchanged,this.entityManager._notifyStateChange(this.entity,!1)},c.setModified=function(){this.entityState=ut.Modified,this.entityManager._notifyStateChange(this.entity,!0)},c.setDeleted=function(){var e=this.entityManager,t=this.entity;this.entityState.isAdded()?(e.detachEntity(t),e._notifyStateChange(t,!1)):(this.entityState=ut.Deleted,a(t,ut.Deleted),e._notifyStateChange(t,!0))},c.setDetached=function(){var e=this.entityGroup;if(!e)return!1;var t=this.entity;return e.detachEntity(t),a(t,ut.Detached),this.entityManager.entityChanged.publish({entityAction:at.Detach,entity:t}),this._detach(),!0},c.loadNavigationProperty=function(e,t,n){var r=this.entity,a=r.entityType._checkNavProperty(e),i=Pt.fromEntityNavigation(r,a,t,n);return r.entityAspect.entityManager.executeQuery(i,t,n)},c.validateEntity=function(){var e=!0;return this._processValidationOpAndPublish(function(t){e=r(t.entity)}),e},c.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))},c.getValidationErrors=function(e){Q(e,"property").isOptional().isEntityProperty().or().isString().check();var t=i(this._validationErrors);if(e){var n="string"==typeof e?e:e.name;t=t.filter(function(e){return e.property.name===n})}return t},c.addValidationError=function(e){Q(e,"validationError").isInstanceOf(nt).check(),this._processValidationOpAndPublish(function(t){t._addValidationError(e)})},c.removeValidationError=function(e,t){Q(e,"validator").isString().or().isInstanceOf(tt).check(),Q(t,"property").isOptional().isEntityProperty().check(),this._processValidationOpAndPublish(function(n){n._removeValidationError(e,t&&t.name)})},c.clearValidationErrors=function(){this._processValidationOpAndPublish(function(t){e(t._validationErrors,function(e,n){n&&(delete t._validationErrors[e],t._pendingValidationResult.removed.push(n))})})},c.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 st(e.entityType,r)},c.getPropertyValue=function(e){Q(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 dt))throw 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},c._detach=function(){this.entityGroup=null,this.entityManager=null,this.entityState=ut.Detached,this.originalValues={},this._validationErrors={},this.validationErrorsChanged.clear(),this.propertyChanged.clear()},c._validateProperty=function(e,t){var n=!0;return this._processValidationOpAndPublish(function(r){t.property.validators.forEach(function(a){n=n&&u(r,a,e,t)})}),n},c._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)}finally{this._pendingValidationResult=void 0}},c._addValidationError=function(e){this._validationErrors[e.key]=e,this._pendingValidationResult.added.push(e)},c._removeValidationError=function(e,t){var n=nt.getKey(e,t),r=this._validationErrors[n];r&&(delete this._validationErrors[n],this._pendingValidationResult.removed.push(r))},p}(),ot=function(){var e=function(e,t,n){if(!e)throw Error("The  ComplexAspect ctor requires an entity as its only argument.");if(e.complexAspect)return e.complexAspect;if(!(this instanceof ot))return new ot(e,t,n);this.complexObject=e,e.complexAspect=this,this.originalValues={},null!=t&&(this.parent=t,this.parentProperty=n);var r=e.complexType;if(!r){var a=e.prototype._$typeName;throw a?Error("Metadata for this complexType has not yet been resolved: "+a):Error("This entity is not registered as a valid ComplexType")}var i=r.getCtor();Z.getDefaultInstance().startTracking(e,i.prototype)},t=e.prototype;return t.getEntityAspect=function(){var e=this.parent;if(!e)return new it(null);for(var t=e.entityAspect;e&&!t;)e=e.complexAspect&&e.complexAspect.parent,t=e&&e.entityAspect;return t||new it(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)},t._postInitialize=function(){var e=this.complexObject,t=e.complexType.getCtor(),n=t._$initializationFn;n&&("string"==typeof n?e[n](e):t._$initializationFn(e))},e}();B.EntityAspect=it,B.ComplexAspect=ot;var st=function(){function e(e){return e.join(t)}var t=":::",n=function(t,n){Q(t,"entityType").isInstanceOf(dt).check();var r=t.getSelfAndSubtypes();r.length>1&&(this._subtypes=r.filter(function(e){return e.isAbstract===!1})),Array.isArray(n)||(n=z(arguments,1)),this.entityType=t,t.keyProperties.forEach(function(e,t){e.dataType===yt.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 st(n,e.values)},r.equals=function(e){return e instanceof st?this.entityType===e.entityType&&m(this.values,e.values):!1},r.toString=function(){return this.entityType.name+"-"+this._keyInGroup},n.equals=function(e,t){return e instanceof st?e.equals(t):!1},r._isEmpty=function(){return 0===this.values.join("").length},n.createKeyString=e,n}();B.EntityKey=st;var ut=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 X("EntityState",e);return t.Unchanged=t.addSymbol(),t.Added=t.addSymbol(),t.Modified=t.addSymbol(),t.Deleted=t.addSymbol(),t.Detached=t.addSymbol(),t.seal(),t}();B.EntityState=ut,B.makePrimitiveArray=function(){function e(e,n,r){return et.initializeParent(e,n,r),e.arrayChanged=new W("arrayChanged_primitiveArray",e),o(e,et.mixin),o(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}(),B.makeRelationArray=function(){function e(e,t){var n=r(e,t);if(!n.length)return n;var a=e.parentEntity,i=a.entityAspect.entityManager;return i&&!i.isLoading&&n.forEach(function(t){if(t.entityAspect.entityState.isDetached()){e._inProgress=!0;try{i.attachEntity(t,ut.Added)}finally{e._inProgress=!1}}}),n}function t(e,t){var n=e.parentEntity,r=e.navigationProperty,a=e._addsInProcess,i=r.inverse,o=a.length;try{t.forEach(function(e){if(a.push(e),i)e.setProperty(i.name,n);else{var t=n.entityType.keyProperties;r.invForeignKeyNames.forEach(function(r,a){e.setProperty(r,n.getProperty(t[a].name))})}})}finally{a.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,a=e.navigationProperty,i=a.inverse;if(i)n=t.filter(function(t){if(e._addsInProcess.indexOf(t)>=0)return!1;var n=t.getProperty(i.name);return n!==r});else{var o=a.invForeignKeyNames,s=r.entityType.keyProperties;n=t.filter(function(t){return e._addsInProcess.indexOf(t)>=0?!1:o.some(function(e,n){var a=s[n].name,i=r.getProperty(a),o=t.getProperty(e);return i!==o})})}return n}function a(e,t,n){return e.parentEntity=t,e.navigationProperty=n,e.arrayChanged=new W("arrayChanged_entityCollection",e),e._addsInProcess=[],o(e,et.mixin),o(e,i)}var i={};return i.load=function(e,t){var n=this.parentEntity,r=Pt.fromEntityNavigation(this.parentEntity,this.navigationProperty),a=n.entityAspect.entityManager;return a.executeQuery(r,e,t)},i._getEventParent=function(){return this.parentEntity.entityAspect},i._getPendingPubs=function(){var e=this.parentEntity.entityAspect.entityManager;return e&&e._pendingPubs},i._getGoodAdds=function(t){return e(this,t)},i._processAdds=function(e){t(this,e)},i._processRemoves=function(e){n(this,e)},a}();var pt=function(){function e(e,t){return t&&(H(t).whereParam("serviceName").isOptional().whereParam("adapterName").isString().isOptional().whereParam("hasServerMetadata").isBoolean().isOptional().whereParam("jsonResultsAdapter").isInstanceOf(ct).isOptional().whereParam("useJsonp").isBoolean().isOptional().applyAll(e),e.serviceName=e.serviceName&&pt._normalizeServiceName(e.serviceName),e.adapterInstance=e.adapterName&&Y.getAdapterInstance("dataService",e.adapterName)),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 pt(this);return e(n,t)},t.resolve=function(e){e.push({hasServerMetadata:!0,useJsonp:!1});var t=new pt(c(e,["serviceName","adapterName","hasServerMetadata","jsonResultsAdapter","useJsonp"]));if(!t.serviceName)throw Error("Unable to resolve a 'serviceName' for this dataService");return t.adapterInstance=t.adapterInstance||Y.getAdapterInstance("dataService",t.adapterName),t.jsonResultsAdapter=t.jsonResultsAdapter||t.adapterInstance.jsonResultsAdapter,t},t._normalizeServiceName=function(e){return e=e.trim(),"/"!==e.substr(-1)?e+"/":e},n.toJSON=function(){return p(this,{serviceName:null,adapterName:null,hasServerMetadata:null,jsonResultsAdapter:function(e){return e&&e.name},useJsonp:null})},t.fromJSON=function(e){return e.jsonResultsAdapter=Y._fetchObject(ct,e.jsonResultsAdapter),new pt(e)},n.makeUrl=function(e){var t=this.serviceName;return G.stringEndsWith(t,"/")&&(t=t.substr(0,t.length-1)),e="/"+e,G.stringEndsWith(t,e)||(t+=e),t},t}(),ct=function(){function e(e){return e.results}var t=function(t){if(1!==arguments.length)throw Error("The JsonResultsAdapter ctor should be called with a single argument that is a configuration object.");H(t).whereParam("name").isNonEmptyString().whereParam("extractResults").isFunction().isOptional().withDefault(e).whereParam("visitNode").isFunction().applyAll(this),Y._storeObject(this,n._$typeName,this.name)},n=t.prototype;return n._$typeName="JsonResultsAdapter",t}();B.DataService=pt,B.JsonResultsAdapter=ct;var yt=function(){function e(e,t){throw e=D(e,t),Error(e)}function t(e){switch(e){case b.String:return tt.string;case b.Int64:return tt.int64;case b.Int32:return tt.int32;case b.Int16:return tt.int16;case b.Decimal:return tt.number;case b.Double:return tt.number;case b.Single:return tt.number;case b.DateTime:return tt.date;case b.DateTimeOffset:return tt.date;case b.Boolean:return tt.bool;case b.Guid:return tt.guid;case b.Byte:return tt.byte;case b.Binary:return tt.none;case b.Time:return tt.duration;case b.Undefined:return tt.none}}var n={},r={stringPrefix:"K_",nextNumber:-1,nextNumberIncrement:-1},a=function(){return r.stringPrefix+(""+i())},i=function(){var e=r.nextNumber;return r.nextNumber+=r.nextNumberIncrement,e},o=function(){return P()},s=function(){return new Date},u=function(e){return null==e?e:""+e},p=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},c=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)),w(n)?n:e)}return"number"===t?(n=new Date(e),w(n)?n:e):e},l=function(e,t){if("string"===t){var n=e.trim().toLowerCase();return"false"===n||""===n?!1:"true"===n?!0:e}return e},f=function(e){return null==e?null:"'"+e+"'"},h=function(e){return null==e?null:"string"==typeof e?parseInt(e,10):e},d=function(e){return function(t){return null==t?null:("string"==typeof t&&(t=parseFloat(t)),t+e)}},m=function(t){if(null==t)return null;try{return"datetime'"+t.toISOString()+"'"}catch(n){e("'%1' is not a valid dateTime",t)}},v=function(t){if(null==t)return null;try{return"datetimeoffset'"+t.toISOString()+"'"}catch(n){e("'%1' is not a valid dateTime",t)}},g=function(t){return null==t?null:(A(t)||e("'%1' is not a valid ISO 8601 duration",t),"time'"+t+"'")},_=function(t){return null==t?null:(C(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+"'"},E=function(e){return e},b=new X("DataType",n);b.String=b.addSymbol({defaultValue:"",parse:u,fmtOData:f,getNext:a}),b.Int64=b.addSymbol({defaultValue:0,isNumeric:!0,isInteger:!0,quoteJsonOData:!0,parse:p,fmtOData:h,getNext:i}),b.Int32=b.addSymbol({defaultValue:0,isNumeric:!0,isInteger:!0,parse:p,fmtOData:h,getNext:i}),b.Int16=b.addSymbol({defaultValue:0,isNumeric:!0,isInteger:!0,parse:p,fmtOData:h,getNext:i}),b.Byte=b.addSymbol({defaultValue:0,isNumeric:!0,isInteger:!0,parse:p,fmtOData:h}),b.Decimal=b.addSymbol({defaultValue:0,isNumeric:!0,quoteJsonOData:!0,parse:c,fmtOData:d("m"),getNext:i}),b.Double=b.addSymbol({defaultValue:0,isNumeric:!0,parse:c,fmtOData:d("d"),getNext:i}),b.Single=b.addSymbol({defaultValue:0,isNumeric:!0,parse:c,fmtOData:d("f"),getNext:i}),b.DateTime=b.addSymbol({defaultValue:new Date(1900,0,1),isDate:!0,parse:y,fmtOData:m,getNext:s}),b.DateTimeOffset=b.addSymbol({defaultValue:new Date(1900,0,1),isDate:!0,parse:y,fmtOData:v,getNext:s}),b.Time=b.addSymbol({defaultValue:"PT0S",fmtOData:g}),b.Boolean=b.addSymbol({defaultValue:!1,parse:l,fmtOData:S}),b.Guid=b.addSymbol({defaultValue:"00000000-0000-0000-0000-000000000000",fmtOData:_,getNext:o}),b.Binary=b.addSymbol({defaultValue:null,fmtOData:T}),b.Undefined=b.addSymbol({defaultValue:void 0,fmtOData:E}),b.seal(),b.fromEdmDataType=function(e){var t=null,n=e.split(".");if(n.length>1){var r=n[1];t="image"===r?b.Byte:2===n.length?b.fromName(r)||b.Undefined:b.String}return t},b.fromValue=function(e){if(w(e))return b.DateTime;switch(typeof e){case"string":return C(e)?b.Guid:A(e)&&e.length>3?b.Time:b.String;case"boolean":return b.Boolean;case"number":return b.Int32}return b.Undefined};var N=/.\d{3}$/;return b.parseDateAsUTC=function(e){if("string"==typeof e){var t=N.test(e);e=t?e+"Z":e}return e=new Date(Date.parse(e))},b.parseDateFromServer=b.parseDateAsUTC,b.constants=r,b.getSymbols().forEach(function(e){e.validatorCtor=t(e)}),b}();B.DataType=yt;var lt=g("Q","See https://github.com/kriskowal/q "),ft=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){var n=K(t.shortName,t.namespace),a=e._getEntityType(n,!0);if(a)return a;var i={shortName:t.shortName,namespace:t.namespace,isAbstract:t.isAbstract,autoGeneratedKeyType:_t.fromName(t.autoGeneratedKeyType),defaultResourceName:t.defaultResourceName};if(a=t.isComplexType?new mt(i):new dt(i),t.baseTypeName){a.baseTypeName=t.baseTypeName;var o=e._getEntityType(t.baseTypeName);o?r(e,t,a,o):v(e.deferredTypes,baseTypeName).push({json:t,stype:a})}else r(e,t,a,null);return a}function r(e,t,n,a){t.validators&&(n.validators=t.validators.map(tt.fromJSON)),a&&(n.baseEntityType=a,a.dataProperties.forEach(function(e){var t=new vt(e);t.isInherited=!0,n.addProperty(t)}),a.navigationProperties.forEach(function(e){var t=new gt(e);t.isInherited=!0,n.addProperty(t)})),t.dataProperties.forEach(function(e){n.addProperty(vt.fromJSON(e))});var i=!t.isComplexType;i&&t.navigationProperties&&t.navigationProperties.forEach(function(e){n.addProperty(gt.fromJSON(e))}),e.addEntityType(n);var o=e._deferredTypes,s=o[n.name];s&&(s.forEach(function(t){r(e,t.json,t.stype,n)}),delete o[n.name])}function a(e,t,n){if(F(t))return t;var r=e._shortNameMap[t];if(!r&&n)throw Error("Unable to locate 'entityTypeName' of: "+t);return r}var i=0,s=function(e){e=e||{},H(e).whereParam("namingConvention").isOptional().isInstanceOf(Et).withDefault(Et.defaultInstance).whereParam("localQueryComparisonOptions").isOptional().isInstanceOf(Tt).withDefault(Tt.defaultInstance).applyAll(this),this.dataServices=[],this._resourceEntityTypeMap={},this._structuralTypeMap={},this._shortNameMap={},this._ctorRegistry={},this._incompleteTypeMap={},this._incompleteComplexTypeMap={},this._id=i++},u=s.prototype;return u._$typeName="MetadataStore",s.ANONTYPE_PREFIX="_IB_",u.addDataService=function(e,t){Q(e,"dataService").isInstanceOf(pt).check(),Q(t,"shouldOverwrite").isBoolean().isOptional().check();var n=this._getDataServiceIndex(e.serviceName);if(n>=0){if(!t)throw Error("A dataService with this name '"+e.serviceName+"' already exists in this MetadataStore");this.dataServices[n]=e}else this.dataServices.push(e)},u._getDataServiceIndex=function(e){return f(this.dataServices,function(t){return t.serviceName===e})},u.addEntityType=function(e){if(e instanceof dt||e instanceof mt||(e=e.isComplexType?new mt(e):new dt(e)),!e.isComplexType&&0===e.keyProperties.length)throw 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||(this._structuralTypeMap[e.name]=e,this._shortNameMap[e.shortName]=e.name),e.getProperties().forEach(function(t){e._updateNames(t),t.isUnmapped||e._mappedPropertiesCount++}),e._updateCps(),!e.isComplexType){e._updateNps();var t=e.defaultResourceName||e.baseEntityType&&e.baseEntityType.defaultResourceName;t&&!this.getEntityTypeNameForResourceName(t)&&this.setEntityTypeForResourceName(t,e.name),e.defaultResourceName=t,e.getEntityCtor()}e.baseEntityType&&e.baseEntityType.subtypes.push(e)},u.exportMetadata=function(){var e=JSON.stringify({metadataVersion:B.metadataVersion,namingConvention:this.namingConvention.name,localQueryComparisonOptions:this.localQueryComparisonOptions.name,dataServices:this.dataServices,structuralTypes:n(this._structuralTypeMap),resourceEntityTypeMap:this._resourceEntityTypeMap},Y.stringifyPad);return e},u.importMetadata=function(e){this._deferredTypes={};var n="string"==typeof e?JSON.parse(e):e;if(n.schema)return ht.parse(this,n.schema);if(n.metadataVersion&&n.metadataVersion!==B.metadataVersion){var r=D("Cannot import metadata with a different 'metadataVersion' (%1) than the current 'breeze.metadataVersion' (%2) ",n.metadataVersion,B.metadataVersion);throw Error(r)}var a=n.namingConvention,i=n.localQueryComparisonOptions;if(this.isEmpty())this.namingConvention=Y._fetchObject(Et,a)||Et.defaultInstance,this.localQueryComparisonOptions=Y._fetchObject(Tt,i)||Tt.defaultInstance;else{if(a&&this.namingConvention.name!==a)throw Error("Cannot import metadata with a different 'namingConvention' from the current MetadataStore");if(i&&this.localQueryComparisonOptions.name!==i)throw Error("Cannot import metadata with different 'localQueryComparisonOptions' from the current MetadataStore")}var s=this;n.dataServices&&n.dataServices.forEach(function(e){e=pt.fromJSON(e),s.addDataService(e,!0)});var u=this._structuralTypeMap;return n.structuralTypes.forEach(function(e){var n=t(s,e);u[n.name]=n}),o(this._resourceEntityTypeMap,n.resourceEntityTypeMap),o(this._incompleteTypeMap,n.incompleteTypeMap),this},s.importMetadata=function(e){var t=new ft;return t.importMetadata(e),t},u.hasMetadataFor=function(e){return!!this.getDataService(e)},u.getDataService=function(e){return Q(e,"serviceName").isString().check(),e=pt._normalizeServiceName(e),l(this.dataServices,function(t){return t.serviceName===e})},u.fetchMetadata=function(e,t,n){if(Q(e,"dataService").isString().or().isInstanceOf(pt).check(),Q(t,"callback").isFunction().isOptional().check(),Q(n,"errorCallback").isFunction().isOptional().check(),"string"==typeof e&&(e=this.getDataService(e)||new pt({serviceName:e})),e=pt.resolve([e]),this.hasMetadataFor(e.serviceName))throw Error("Metadata for a specific serviceName may only be fetched once per MetadataStore. ServiceName: "+e.serviceName);return e.adapterInstance.fetchMetadata(this,e).then(function(e){return t&&t(e),lt.resolve(e)}).fail(function(e){return n&&n(e),lt.reject(e)})},u.trackUnmappedType=function(e,t){Q(e,"entityCtor").isFunction().check(),Q(t,"interceptor").isFunction().isOptional().check();var n=new dt(this);n._setCtor(e,t)},u.registerEntityTypeCtor=function(e,t,n){Q(e,"structuralTypeName").isString().check(),Q(t,"aCtor").isFunction().isOptional().check(),Q(n,"initializationFn").isOptional().isFunction().or().isString().check();var r=a(this,e,!1),i=r||e;if(this._ctorRegistry[i]={ctor:t,initFn:n},r){var o=this._structuralTypeMap[r];o&&o.getCtor(!0)}},u.toQueryString=function(e){if(!e)throw Error("query cannot be empty");if("string"==typeof e)return e;if(e instanceof Pt)return e._toUri(this);throw Error("unable to recognize query parameter as either a string or an EntityQuery")},u.isEmpty=function(){return x(this._structuralTypeMap)},u.getEntityType=function(e,t){return Q(e,"structuralTypeName").isString().check(),Q(t,"okIfNotFound").isBoolean().isOptional().check(!1),this._getEntityType(e,t)},u._getEntityType=function(e,t){var n=a(this,e,!1),r=this._structuralTypeMap[n];if(!r){if(t)return null;var i=D("Unable to locate a 'Type' by the name: '%1'. Be sure to execute a query or call fetchMetadata first.",e);throw Error(i)}if(r.length){var o=r.join(",");throw Error("There are multiple types with this 'shortName': "+o)}return r},u.getEntityTypes=function(){return e(this._structuralTypeMap)},u.getIncompleteNavigationProperties=function(){return n(this._incompleteTypeMap,function(e,t){return t})},u.getEntityTypeNameForResourceName=function(e){return Q(e,"resourceName").isString().check(),this._resourceEntityTypeMap[e]},u.setEntityTypeForResourceName=function(e,t){Q(e,"resourceName").isString().check(),Q(t,"entityTypeOrName").isInstanceOf(dt).or().isString().check();var n;n=t instanceof dt?t.name:a(this,t,!0),this._resourceEntityTypeMap[e]=n;var r=this._getEntityType(n,!0);r&&!r.defaultResourceName&&(r.defaultResourceName=e)},u._checkEntityType=function(e){if(!e.entityType){var t=e.prototype._$typeName;if(!t)throw Error("This entity has not been registered. See the MetadataStore.registerEntityTypeCtor method");var n=this._getEntityType(t);n&&(e.entityType=n)}},s}(),ht=function(){function e(e,n){e._entityTypeResourceMap={},y(n).forEach(function(n){if(n.cSpaceOSpaceMapping){var a=JSON.parse(n.cSpaceOSpaceMapping),i={};a.forEach(function(e){i[e[0]]=e[1]}),n.cSpaceOSpaceMapping=i}n.entityContainer&&y(n.entityContainer).forEach(function(t){y(t.entitySet).forEach(function(t){var r=d(t.entityType,n).typeName;e.setEntityTypeForResourceName(t.name,r),e._entityTypeResourceMap[r]=t.name})}),n.complexType&&y(n.complexType).forEach(function(t){r(t,n,e)}),n.entityType&&y(n.entityType).forEach(function(r){t(r,n,e)})});var a=e.getIncompleteNavigationProperties();if(a.length>0)throw Error("Bad nav properties");return e}function t(e,t,r){var a=e.name,i=m(a,t),o=new dt({shortName:a,namespace:i,isAbstract:e.abstract&&"true"===e.abstract});if(e.baseType){var s=d(e.baseType,t).typeName;o.baseTypeName=s;var u=r._getEntityType(s,!0);if(u)n(o,e,t,r,u);else{var p=r._deferredTypes[s];p||(p=[],r._deferredTypes[s]=p),p.push({entityType:o,csdlEntityType:e})}}else n(o,e,t,r,null);return o}function n(e,t,r,o,s){var p=[];s&&(e.baseEntityType=s,e.autoGeneratedKeyType=s.autoGeneratedKeyType,p=s.keyProperties.map(a("name")),s.dataProperties.forEach(function(t){var n=new vt(t);n.isInherited=!0,e.addProperty(n)}),s.navigationProperties.forEach(function(t){var n=new gt(t);n.isInherited=!0,e.addProperty(n)}));var c=t.key?y(t.key.propertyRef).map(a("name")):[];c=p.concat(c),y(t.property).forEach(function(t){i(e,t,r,c)}),y(t.navigationProperty).forEach(function(t){u(e,t,r)}),o.addEntityType(e),e.defaultResourceName=o._entityTypeResourceMap[e.name];var l=o._deferredTypes,f=l[e.name];f&&(f.forEach(function(t){n(t.entityType,t.csdlEntityType,r,o,e)}),delete l[e.name])}function r(e,t,n){var r=e.name,a=m(r,t),o=new mt({shortName:r,namespace:a});return y(e.property).forEach(function(e){i(o,e,t)}),n.addEntityType(o),o}function i(e,t,n,r){var a,i=t.type.split(".");return 2===i.length?a=o(e,t,r):p(t,n)?(a=o(e,t,r),a&&(a.enumType=t.type)):a=s(e,t,n),a&&(e.addProperty(a),c(a)),a}function o(e,t,n){var r=yt.fromEdmDataType(t.type);if(null==r)return e.warnings.push("Unable to recognize DataType for property: "+t.name+" DateType: "+t.type),null;var a="true"===t.nullable||null==t.nullable,i=null!=n&&n.indexOf(t.name)>=0;i&&e.autoGeneratedKeyType===_t.None&&f(t)&&(e.autoGeneratedKeyType=_t.Identity);var o=t.maxLength;o=null==o||"Max"===o?null:parseInt(o,10);var s=new vt({nameOnServer:t.name,dataType:r,isNullable:a,isPartOfKey:i,maxLength:o,concurrencyMode:t.concurrencyMode});return r===yt.Undefined&&(s.rawTypeName=t.type),s}function s(e,t,n){var r=d(t.type,n).typeName,a=new vt({nameOnServer:t.name,complexTypeName:r,isNullable:!1});return a}function u(e,t,n){var r=h(t,n),i=l(r.end,function(e){return e.role===t.toRole}),o="*"!==i.multiplicity,s=d(i.type,n).typeName,u=r.referentialConstraint;if(u){var p,c={nameOnServer:t.name,entityTypeName:s,isScalar:o,associationName:r.name},f=u.principal,m=u.dependent;t.fromRole===f.role?(p=y(f.propertyRef),c.invForeignKeyNamesOnServer=p.map(a("name"))):(p=y(m.propertyRef),c.foreignKeyNamesOnServer=p.map(a("name")));var v=new gt(c);return e.addProperty(v),v}}function p(e,t){if(!t.enumType)return!1;var n=y(t.enumType),r=e.type.split("."),a=r[r.length-1];return n.some(function(e){return e.name===a})}function c(e){var t;if(e.isNullable||e.validators.push(tt.required()),!e.isComplexProperty){if(e.dataType===yt.String)if(e.maxLength){var n={maxLength:e.maxLength};t=tt.maxLength(n)}else t=tt.string();else t=e.dataType.validatorCtor();e.validators.push(t)}}function f(e){var t=l(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=l(n,function(e){return"StoreGeneratedPattern"===e.name&&"Identity"===e.value});return!!r}function h(e,t){var n=d(e.relationship,t).shortTypeName,r=t.association;if(!r)return null;Array.isArray(r)||(r=[r]);var a=l(r,function(e){return e.name===n});return a}function d(e,t){if(!e)return null;if(k(e,ft.ANONTYPE_PREFIX))return{shortTypeName:e,namespace:"",typeName:e,isAnon:!0};var n=e.split(",")[0],r=n.split(".");if(r.length>1){var a,i=r[r.length-1];if(t)a=m(i,t);else{var o=r.slice(0,r.length-1);a=o.join(".")}return{shortTypeName:i,namespace:a,typeName:K(i,a)}}return{shortTypeName:e,namespace:"",typeName:e}}function m(e,t){var n,r=t.cSpaceOSpaceMapping;if(r){var a=r[t.namespace+"."+e];n=a&&a.substr(0,a.length-(e.length+1))}return n||t.namespace}var v=E(function(e){return e&&d(e).typeName});return{parse:e,normalizeTypeName:v}}(),dt=function(){function t(){return function(){}}function n(e){return e.filter(function(e){return!e.isInherited})}function i(e,t,n){var r=n+"OnServer",a=t[n];if(a&&a.length){if(t.isUnmapped)return;var i=y(a).map(function(n){var r=e.clientPropertyNameToServer(n,t),a=e.serverPropertyNameToClient(r,t);if(n!==a)throw Error("NamingConvention for this client property name does not roundtrip properly:"+n+"-->"+a);return r});t[r]=Array.isArray(a)?i:i[0]}else{var o=t[r];if(!o||0===o.length)return;var s=y(o).map(function(n){var r=e.serverPropertyNameToClient(n,t),a=e.clientPropertyNameToServer(r,t);if(n!==a)throw Error("NamingConvention for this server property name does not roundtrip properly:"+n+"-->"+a);return r});t[n]=Array.isArray(o)?s:s[0]}}function o(e,t){var n=t._getEntityType(e.complexTypeName,!0);if(!n)return!1;if(!(n instanceof mt))throw Error("Unable to resolve ComplexType with the name: "+e.complexTypeName+" for the property: "+property.name);return e.dataType=n,e.defaultValue=null,!0}function s(e,t){var n=t._getEntityType(e.entityTypeName,!0);if(!n)return!1;e.entityType=n;var r=l(n.navigationProperties,function(t){return t.associationName===e.associationName&&(t.name!==e.name||t.entityTypeName!==e.entityTypeName)});return e.inverse=r,r||e.invForeignKeyNames.forEach(function(t){var r=n.getDataProperty(t),a=e.parentType;r.inverseNavigationProperty=l(a.navigationProperties,function(e){return e.invForeignKeyNames&&e.invForeignKeyNames.indexOf(r.name)>=0}),n.foreignKeyProperties.push(r)}),u(e),!0}function u(e){var t=e.foreignKeyNames;if(0!==t.length){var n=e.parentType,r=t.map(function(e){return n.getDataProperty(e)});Array.prototype.push.apply(n.foreignKeyProperties,r),r.forEach(function(t){t.relatedNavigationProperty=e,e.relatedDataProperties?e.relatedDataProperties.push(t):e.relatedDataProperties=[t]})}}function c(e,t){var n=e.getPropertyNames(),r=Z.getDefaultInstance().getTrackablePropertyNames(t);r.forEach(function(t){if(-1===n.indexOf(t)){var r=new vt({name:t,dataType:yt.Undefined,isNullable:!0,isUnmapped:!0});e.addProperty(r)}})}var f=0,h=function(e){if(arguments.length>1)throw 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_"+ ++f,this.namespace="",this.isAnonymous=!0):H(e).whereParam("shortName").isNonEmptyString().whereParam("namespace").isString().isOptional().withDefault("").whereParam("baseTypeName").isString().isOptional().whereParam("isAbstract").isBoolean().isOptional().withDefault(!1).whereParam("autoGeneratedKeyType").isEnumOf(_t).isOptional().withDefault(_t.None).whereParam("defaultResourceName").isNonEmptyString().isOptional().withDefault(null).whereParam("dataProperties").isOptional().whereParam("navigationProperties").isOptional().applyAll(this),this.name=K(this.shortName,this.namespace),this.dataProperties=[],this.navigationProperties=[],this.complexProperties=[],this.keyProperties=[],this.foreignKeyProperties=[],this.concurrencyProperties=[],this.unmappedProperties=[],this.validators=[],this.warnings=[],this._mappedPropertiesCount=0,this.subtypes=[],R(this,e.dataProperties,vt),R(this,e.navigationProperties,gt)
  },d=h.prototype;return d._$typeName="EntityType",d.setProperties=function(e){H(e).whereParam("autoGeneratedKeyType").isEnumOf(_t).isOptional().whereParam("defaultResourceName").isString().isOptional().applyAll(this),e.defaultResourceName&&(this.defaultResourceName=e.defaultResourceName)},d.isSubtypeOf=function(e){Q(e,"entityType").isInstanceOf(dt).check();var t=this;do{if(t===e)return!0;t=t.baseEntityType}while(t);return!1},d.getSelfAndSubtypes=function(){var e=[this];return this.subtypes.forEach(function(t){var n=t.getSelfAndSubtypes();e.push.apply(e,n)}),e},d.addProperty=function(e){if(Q(e,"dataProperty").isInstanceOf(vt).or().isInstanceOf(gt).check(),this.metadataStore&&!e.isUnmapped)throw Error("The '"+this.name+"' EntityType has already been added to a MetadataStore and therefore no additional properties may be added to it.");if(e.parentType){if(e.parentType!==this)throw Error("This dataProperty has already been added to "+e.parentType.name);return this}return e.parentType=this,e.isDataProperty?this._addDataProperty(e):this._addNavigationProperty(e),this},d.createEntity=function(t){var n=this._createEntityCore();return t&&e(t,function(e,t){n.setProperty(e,t)}),n.entityAspect._postInitialize(),n},d._createEntityCore=function(){var e=this.getEntityCtor(),t=new e;return new it(t),t},d.getCtor=d.getEntityCtor=function(e){if(this._ctor&&!e)return this._ctor;var n=this.metadataStore._ctorRegistry,r=n[this.name]||n[this.shortName]||{},a=r.ctor||this._ctor;if(!a){var i=Z.getDefaultInstance().createCtor;a=i?i(this):t()}return r.initFn&&(a._$initializationFn=r.initFn),a.prototype._$typeName=this.name,this._setCtor(a),a},d._setCtor=function(e,t){var n=new e,r=e.prototype;"EntityType"===this._$typeName?(c(this,n),r.entityType=this):(c(this,n),r.complexType=this),r._$interceptor=t?t:j,Z.getDefaultInstance().initializeEntityPrototype(r),this._ctor=e},d.addValidator=function(e,t){Q(e,"validator").isInstanceOf(tt).check(),Q(t,"property").isOptional().isString().or().isEntityProperty().check(),t?("string"==typeof t&&(t=this.getProperty(t,!0)),t.validators.push(e)):this.validators.push(e)},d.getProperties=function(){return this.dataProperties.concat(this.navigationProperties)},d.getPropertyNames=function(){return this.getProperties().map(a("name"))},d.getDataProperty=function(e,t){var n=t?"nameOnServer":"name";return l(this.dataProperties,r(n,e))},d.getNavigationProperty=function(e,t){var n=t?"nameOnServer":"name";return l(this.navigationProperties,r(n,e))},d.getProperty=function(e,t){t=t||!1;var n=Array.isArray(e)?e:e.trim().split("."),a=n[0],i=l(this.getProperties(),r("name",a));if(1===n.length){if(i)return i;if(t)throw Error("unable to locate property: "+a+" on entityType: "+this.name);return null}if(i){n.shift();var o=i.isNavigationProperty?i.entityType:i.dataType;if(o)return o.getProperty(n,t);throw Error("should not get here - unknown property type for: "+i.name)}if(t)throw Error("unable to locate property: "+a+" on type: "+this.name);return null},d.toString=function(){return this.name},d.toJSON=function(){return p(this,{shortName:null,namespace:null,baseTypeName:null,isAbstract:!1,autoGeneratedKeyType:null,defaultResourceName:null,dataProperties:n,navigationProperties:n,validators:null})},d._clientPropertyPathToServer=function(e){var t=this.metadataStore.namingConvention.clientPropertyNameToServer,n=this,r=e.split(".").map(function(e){var r=n.getProperty(e);return t(e,r)}).join("/");return r},d._updateNames=function(e){var t=this.metadataStore.namingConvention;i(t,e,"name"),e.isNavigationProperty&&(i(t,e,"foreignKeyNames"),i(t,e,"invForeignKeyNames"))},d._checkNavProperty=function(e){if(e.isNavigationProperty){if(e.parentType!==this)throw Error(D("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 Error("The 'navigationProperty' parameter must either be a NavigationProperty or the name of a NavigationProperty")},d._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)},d._addNavigationProperty=function(e){this.navigationProperties.push(e),F(e.entityTypeName)||(e.entityTypeName=K(e.entityTypeName,this.namespace))},d._updateCps=function(){var e=this.metadataStore,t=e._incompleteComplexTypeMap;this.complexProperties.forEach(function(n){n.complexType||o(n,e)||v(t,n.complexTypeName).push(n)}),this.isComplexType&&((t[this.name]||[]).forEach(function(t){o(t,e)}),delete t[this.name])},d._updateNps=function(){var e=this.metadataStore,t=e._incompleteTypeMap;this.navigationProperties.forEach(function(n){n.entityType||s(n,e)||v(t,n.entityTypeName).push(n)}),(t[this.name]||[]).forEach(function(t){s(t,e)}),delete t[this.name]},h}(),mt=function(){var t=function(e){if(arguments.length>1)throw Error("The ComplexType ctor has a single argument that is a configuration object.");H(e).whereParam("shortName").isNonEmptyString().whereParam("namespace").isString().isOptional().withDefault("").whereParam("dataProperties").isOptional().whereParam("isComplexType").isOptional().isBoolean().applyAll(this),this.name=K(this.shortName,this.namespace),this.isComplexType=!0,this.dataProperties=[],this.complexProperties=[],this.validators=[],this.concurrencyProperties=[],this.unmappedProperties=[],this.navigationProperties=[],this.keyProperties=[],R(this,e.dataProperties,vt)},n=t.prototype;return n.createInstance=function(t){var n=this._createInstanceCore();return t&&e(t,function(e,t){n.setProperty(e,t)}),n.complexAspect._postInitialize(),n},n._createInstanceCore=function(e,t){var n=this.getCtor(),r=new n;return new ot(r,e,t),e&&r.complexAspect._postInitialize(),r},n.addProperty=function(e){if(Q(e,"dataProperty").isInstanceOf(vt).check(),this.metadataStore&&!e.isUnmapped)throw Error("The '"+this.name+"' ComplexType has already been added to a MetadataStore and therefore no additional properties may be added to it.");if(e.parentType){if(e.parentType!==this)throw Error("This dataProperty has already been added to "+property.parentType.name);return this}return this._addDataProperty(e),this},n.getProperties=function(){return this.dataProperties},n.addValidator=dt.prototype.addValidator,n.getProperty=dt.prototype.getProperty,n.getPropertyNames=dt.prototype.getPropertyNames,n._addDataProperty=dt.prototype._addDataProperty,n._updateNames=dt.prototype._updateNames,n._updateCps=dt.prototype._updateCps,n.getCtor=dt.prototype.getEntityCtor,n._setCtor=dt.prototype._setCtor,n.toJSON=function(){return p(this,{shortName:null,namespace:null,isComplexType:null,dataProperties:null,validators:null})},n._$typeName="ComplexType",t}(),vt=function(){var e=function(e){H(e).whereParam("name").isString().isOptional().whereParam("nameOnServer").isString().isOptional().whereParam("dataType").isEnumOf(yt).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("concurrencyMode").isString().isOptional().whereParam("maxLength").isNumber().isOptional().whereParam("validators").isInstanceOf(tt).isArray().isOptional().withDefault([]).whereParam("enumType").isOptional().whereParam("rawTypeName").isOptional().applyAll(this);var t=!(!this.name&&!this.nameOnServer);if(!t)throw 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=yt.fromName(this.dataType);if(!n)throw Error("Unable to find a DataType enumeration by the name of: "+this.dataType);this.dataType=n}else this.dataType||(this.dataType=yt.String);if(null==this.defaultValue)if(this.isNullable)this.defaultValue=null;else if(this.isComplexProperty);else if(this.dataType===yt.Binary)this.defaultValue="AAAAAAAAJ3U=";else if(this.defaultValue=this.dataType.defaultValue,null==this.defaultValue)throw Error("A nonnullable DataProperty cannot have a null defaultValue. Name: "+this.name);this.isComplexProperty&&(this.isScalar=null==this.isScalar||this.isScalar===!0)},t=e.prototype;return t._$typeName="DataProperty",t.isDataProperty=!0,t.isNavigationProperty=!1,t.toJSON=function(){return p(this,{name:null,dataType:function(e){return e&&e.parentEnum?e.name:void 0},complexTypeName:null,isNullable:!0,defaultValue:null,isPartOfKey:!1,isUnmapped:!1,concurrencyMode:null,maxLength:null,validators:null,enumType:null,rawTypeName:null,isScalar:!0})},e.fromJSON=function(e){return e.dataType=yt.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(tt.fromJSON)),new vt(e)},e}(),gt=function(){var e=function(e){H(e).whereParam("name").isString().isOptional().whereParam("nameOnServer").isString().isOptional().whereParam("entityTypeName").isString().whereParam("isScalar").isBoolean().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(tt).isArray().isOptional().withDefault([]).applyAll(this);var t=!(!this.name&&!this.nameOnServer);if(!t)throw Error("A Navigation property must be instantiated with either a 'name' or a 'nameOnServer' property")},t=e.prototype;return t._$typeName="NavigationProperty",t.isDataProperty=!1,t.isNavigationProperty=!0,t.toJSON=function(){return p(this,{name:null,entityTypeName:null,isScalar:null,associationName:null,validators:null,foreignKeyNames:null,invForeignKeyNames:null})},e.fromJSON=function(e){return e.validators&&(e.validators=e.validators.map(tt.fromJSON)),new gt(e)},e}(),_t=function(){var e=new X("AutoGeneratedKeyType");return e.None=e.addSymbol(),e.Identity=e.addSymbol(),e.KeyGenerator=e.addSymbol(),e.seal(),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=$.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"})}})(),B.MetadataStore=ft,B.EntityType=dt,B.ComplexType=mt,B.DataProperty=vt,B.NavigationProperty=gt,B.AutoGeneratedKeyType=_t,ft.normalizeTypeName=ht.normalizeTypeName;var St=function(){function e(e,t,n){var r=t.name+".."+t.parentType.name,a=e._tempIdMap[r];return a||n&&(a={entityType:t.parentType,propertyName:t.name,keyMap:{}},e._tempIdMap[r]=a),a}var t=function(){this._tempIdMap={}},n=t.prototype;return n.generateTempKeyValue=function(t,n){var r=t.keyProperties;if(r.length>1)throw Error("Ids can not be autogenerated for entities with multipart keys");var a,i=r[0],o=e(this,i,!0);if(null!=n&&(o.keyMap[""+n]||(a=n)),void 0===a){var s=i.dataType;if(!s.getNext)throw Error("Cannot use a property with a dataType of: "+(""+s)+" for id generation");for(a=s.getNext(this);null!=o.keyMap[""+a];)a=s.getNext(this)}return o.keyMap[""+a]=!0,a},n.getTempKeys=function(){var e=[];for(var t in this._tempIdMap){var n=this._tempIdMap[t],r=n.entityType;for(var a in n.keyMap)e.push(new st(r,[a]))}return e},n.isTempKey=function(t){var n=t.entityType.keyProperties;if(n.length>1)return!1;var r=n[0],a=e(this,r);return a?void 0!==a.keyMap[""+t.values[0]]:!1},Y.registerType(t,"KeyGenerator"),t}();B.KeyGenerator=St;var Tt=function(){var e=function(e){H(e||{}).whereParam("name").isOptional().isString().whereParam("isCaseSensitive").isOptional().isBoolean().whereParam("usesSql92CompliantStringComparison").isBoolean().applyAll(this),this.name||(this.name=P()),Y._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 u(this,e)},e}();B.LocalQueryComparisonOptions=Tt;var Et=function(){var e=function(e){H(e||{}).whereParam("name").isOptional().isString().whereParam("serverPropertyNameToClient").isFunction().whereParam("clientPropertyNameToServer").isFunction().applyAll(this),this.name||(this.name=P()),Y._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 u(this,e)},e}();B.NamingConvention=Et;var Pt=function(){function t(n,r,a,i){var o=a._$typeName||a.parentEnum&&a.parentEnum.name,s=o&&o.substr(0,1).toLowerCase()+o.substr(1);if(i&&s!=i)throw Error("Invalid value for property: "+i);if(s){var u=r[s];if(void 0===u)throw Error("Invalid config property: "+s);null===u?n[s]=a:u(n,a)}else e(a,function(e,a){t(n,r,a,e)})}function n(e){return Q(e,"propertyPaths").isOptional().isString().or().isArray().isString().check(),"string"==typeof e&&(e=e.split(",")),e=e.map(function(e){return e.trim()})}function r(e){var t=e.entityType,n=t.keyProperties.map(function(t){return Ct.create(t.name,wt.Equals,e.getProperty(t.name))}),r=Ct.and(n);return r}function a(e,t,n){var r,a=e._clone();return t?(r=Mt.create(t,n),a.orderByClause?a.orderByClause.addClause(r):a.orderByClause=r,a):(a.orderByClause=null,a)}function i(e,t){var n=e._clone();return t?(n.selectClause=new Dt(t),n):(n.selectClause=null,n)}function s(e,t){var n=e._clone();return t?(n.expandClause=new Vt(t),n):(n.expandClause=null,n)}function u(e,t){var n=e._clone();return n.parameters=t,n}function p(e){var t=e.entityType.keyProperties,n=d(t,e.values,function(e,t){return Ct.create(e.name,wt.Equals,t)}),r=Ct.and(n);return r}function c(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 st(t.entityType,n);return p(r)}var a=t.inverse,i=a?a.foreignKeyNames:t.invForeignKeyNames;if(0===i.length)return null;var o=e.entityAspect.getKey().values,s=d(i,o,function(e,t){return Ct.create(e,wt.Equals,t)});return Ct.and(s)}var y=function(e){Q(e,"resourceName").isOptional().isString().check(),this.resourceName=e,this.entityType=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.entityManager=null},l=y.prototype;return l._$typeName="EntityQuery",l.from=function(e){Q(e,"resourceName").isString().check();var t=this.resourceName;if(t&&t!==e)throw Error("This query already has an resourceName - the resourceName may only be set once per query");var n=this._clone();return n.resourceName=e,n},y.from=function(e){return Q(e,"resourceName").isString().check(),new Pt(e)},l.toType=function(e){Q(e,"entityType").isString().or().isInstanceOf(dt).check();var t=this._clone();return t.resultEntityType=e,t},l.where=function(e){var t=this._clone();if(0===arguments.length)return t.wherePredicate=null,t;var n;return n=Ct.isPredicate(e)?e:Ct.create(z(arguments)),t.entityType&&n.validate(t.entityType),t.wherePredicate=t.wherePredicate?new xt("and",[t.wherePredicate,n]):n,t},l.orderBy=function(e){return a(this,n(e))},l.orderByDesc=function(e){return a(this,n(e),!0)},l.select=function(e){return i(this,n(e))},l.skip=function(e){Q(e,"count").isOptional().isNumber().check();var t=this._clone();return t.skipCount=0===arguments.length?null:e,t},l.top=function(e){return this.take(e)},l.take=function(e){Q(e,"count").isOptional().isNumber().check();var t=this._clone();return t.takeCount=0===arguments.length?null:e,t},l.expand=function(e){return s(this,n(e))},l.withParameters=function(e){return Q(e,"parameters").isObject().check(),u(this,e)},l.inlineCount=function(e){void 0===e&&(e=!0);var t=this._clone();return t.inlineCountEnabled=e,t},l.using=function(e){if(!e)return this;var n=this._clone();return t(n,{entityManager:null,dataService:null,queryOptions:null,fetchStrategy:function(e,t){e.queryOptions=(e.queryOptions||new Kt).using(t)},mergeStrategy:function(e,t){e.queryOptions=(e.queryOptions||new Kt).using(t)},jsonResultsAdapter:function(e,t){e.dataService=(e.dataService||new pt).using({jsonResultsAdapter:t})}},e),n},l.execute=function(e,t){if(!this.entityManager)throw Error("An EntityQuery must have its EntityManager property set before calling 'execute'");return this.entityManager.executeQuery(this,e,t)},l.executeLocally=function(){if(!this.entityManager)throw Error("An EntityQuery must have its EntityManager property set before calling 'executeLocally'");return this.entityManager.executeQueryLocally(this)},y.fromEntities=function(e){Q(e,"entities").isEntity().or().isNonEmptyArray().isEntity().check(),Array.isArray(e)||(e=z(arguments));var t=e[0],n=new Pt(t.entityType.defaultResourceName),a=e.map(function(e){return r(e)}),i=Ct.or(a);n=n.where(i);var o=t.entityAspect.entityManager;return o&&(n=n.using(o)),n},y.fromEntityKey=function(e){Q(e,"entityKey").isInstanceOf(st).check();var t=new Pt(e.entityType.defaultResourceName),n=p(e);return t=t.where(n)},y.fromEntityNavigation=function(e,t){Q(e,"entity").isEntity().check(),Q(t,"navigationProperty").isInstanceOf(gt).check();var n=e.entityType._checkNavProperty(t),r=new Pt(n.entityType.defaultResourceName),a=c(e,n);r=r.where(a);var i=e.entityAspect.entityManager;return i&&(r=r.using(i)),r},l._getFromEntityType=function(e,t){var n=this.entityType;if(n)return n;var r=this.resourceName;if(!r)throw Error("There is no resourceName for this query");if(e.isEmpty()){if(t)throw Error("There is no metadata available for this query");return null}var a=e.getEntityTypeNameForResourceName(r);if(n=a?e._getEntityType(a):this._getToEntityType(e,!0),!n){if(t)throw Error(D("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.entityType=n,n},l._getToEntityType=function(e,t){return this.resultEntityType instanceof dt?this.resultEntityType:this.resultEntityType?(this.resultEntityType=e._getEntityType(this.resultEntityType,!1),this.resultEntityType):t?null:!this.selectClause&&this._getFromEntityType(e,!1)},l._clone=function(){var e=new Pt;return e.resourceName=this.resourceName,e.entityType=this.entityType,e.wherePredicate=this.wherePredicate,e.orderByClause=this.orderByClause,e.selectClause=this.selectClause,e.skipCount=this.skipCount,e.takeCount=this.takeCount,e.expandClause=this.expandClause,e.inlineCountEnabled=this.inlineCountEnabled,e.parameters=o({},this.parameters),e.queryOptions=this.queryOptions,e.entityManager=this.entityManager,e.dataService=this.dataService,e.resultEntityType=this.resultEntityType,e},l._toUri=function(e){function t(){var e=y.wherePredicate;if(e)return y.entityType&&e.validate(y.entityType),e.toOdataFragment(c)}function n(){return y.inlineCountEnabled?y.inlineCountEnabled?"allpages":"none":void 0}function r(){var e=y.orderByClause;if(e)return y.entityType&&e.validate(y.entityType),e.toOdataFragment(c)}function a(){var e=y.selectClause;if(e)return y.entityType&&e.validate(y.entityType),e.toOdataFragment(c)}function i(){var e=y.expandClause;if(e)return e.toOdataFragment(c)}function s(){var e=y.skipCount;if(e)return""+e}function u(){var e=y.takeCount;if(e)return""+e}function p(e){var t=[];for(var n in e){var r=e[n];void 0!==r&&t.push(n+"="+encodeURIComponent(r))}return t.length>0?"?"+t.join("&"):""}var c=this._getFromEntityType(e,!1);c||(c=new dt(e));var y=this,l={};l.$filter=t(),l.$orderby=r(),l.$skip=s(),l.$top=u(),l.$expand=i(),l.$select=a(),l.$inlinecount=n(),l=o(l,this.parameters);var f=p(l);return this.resourceName+f},l._toFilterFunction=function(e){var t=this.wherePredicate;return t?(t.validate(e),t.toFunction(e)):null},l._toOrderByComparer=function(e){var t=this.orderByClause;return t?t.getComparer(e):null},y}(),bt=function(){var e={toupper:{fn:function(e){return e.toUpperCase()},dataType:yt.String},tolower:{fn:function(e){return e.toLowerCase()},dataType:yt.String},substring:{fn:function(e,t,n){return e.substring(t,n)},dataType:yt.String},substringof:{fn:function(e,t){return t.indexOf(e)>=0},dataType:yt.Boolean},length:{fn:function(e){return e.length},dataType:yt.Int32},trim:{fn:function(e){return e.trim()},dataType:yt.String},concat:{fn:function(e,t){return e.concat(t)},dataType:yt.String},replace:{fn:function(e,t,n){return e.replace(t,n)},dataType:yt.String},startswith:{fn:function(e,t){return k(e,t)},dataType:yt.Boolean},endswith:{fn:function(e,t){return I(e,t)},dataType:yt.Boolean},indexof:{fn:function(e,t){return e.indexOf(t)},dataType:yt.Int32},round:{fn:function(e){return Math.round(e)},dataType:yt.Int32},ceiling:{fn:function(e){return Math.ceil(e)},dataType:yt.Int32},floor:{fn:function(e){return Math.floor(e)},dataType:yt.Int32},second:{fn:function(e){return e.second},dataType:yt.Int32},minute:{fn:function(e){return e.minute},dataType:yt.Int32},day:{fn:function(e){return e.day},dataType:yt.Int32},month:{fn:function(e){return e.month},dataType:yt.Int32},year:{fn:function(e){return e.year},dataType:yt.Int32}};return e}(),Nt=function(){function e(e){var t=e.split(".");return 1===t.length?function(t){return t.getProperty(e)}:function(e){return q(e,t)}}var t=/^[a-z_][\w.$]*$/i,n=/('[^']*'|[^,]+)/g,r=/("[^"]*"|[^,]+)/g,a=function(a,i,o){var s=a.split(":");if(o&&(this.isValidated=!0),1===s.length){var u=s[0].trim();this.value=u;var p=u.substr(0,1),c="'"===p||'"'===p;if(c){var y=u.substr(1,u.length-2);this.fn=function(){return y},this.dataType=yt.String}else{var l=t.test(u);if(l){if(o&&null==o.getProperty(u,!1))return this.isValidated=!1,void 0;this.propertyPath=u,this.fn=e(u)}else{if(o)return this.isValidated=!1,void 0;this.fn=function(){return u},this.dataType=yt.fromValue(u)}}}else try{this.fnName=s[0].trim().toLowerCase();var f=bt[this.fnName];this.localFn=f.fn,this.dataType=f.dataType;var h=this;this.fn=function(e){var t=h.fnNodes.map(function(t){var n=t.fn(e);return n}),n=h.localFn.apply(null,t);return n};var d=i[s[1]].trim();"("===d.substr(0,1)&&(d=d.substr(1,d.length-2));var m=a.indexOf("'")>=0?n:r,v=d.match(m);this.fnNodes=v.map(function(e){return new Nt(e,i)})}catch(g){this.isValidated=!1}},i=a.prototype;return a.create=function(e,t,n){if("string"!=typeof e)return null;for(var r,a=/\([^()]*\)/,i=[],o=0;r=a.exec(e);){var s=r[0];i.push(s);var u=":"+o++;e=e.replace(s,u)}var p=new Nt(e,i,t);return!p.dataType&&n&&n.isStringFn&&(p.dataType=yt.String),p.isValidated===!1?null:p},i.toString=function(){if(this.fnName){var e=this.fnNodes.map(function(e){return""+e}),t=this.fnName+"("+e.join(",")+")";return t}return this.value},i.updateWithEntityType=function(e){if(this.propertyPath){if(e.isAnonymous)return;var t=e.getProperty(this.propertyPath);if(!t){var n=D("Unable to resolve propertyPath.  EntityType: '%1'   PropertyPath: '%2'",e.name,this.propertyPath);throw Error(n)}this.dataType=t.dataType}},i.toOdataFragment=function(e){if(this.updateWithEntityType(e),this.fnName){var t=this.fnNodes.map(function(t){return t.toOdataFragment(e)}),n=this.fnName+"("+t.join(",")+")";return n}var r=this.value.substr(0,1);return"'"===r||'"'===r?this.value:this.value==this.propertyPath?e._clientPropertyPathToServer(this.propertyPath):this.value},i.validate=function(e){if(void 0===this.isValidated)if(this.isValidated=!0,this.propertyPath){var t=e.getProperty(this.propertyPath,!0);this.dataType=t.isDataProperty?t.dataType:t.entityType}else this.fnNodes&&this.fnNodes.forEach(function(t){t.validate(e)})},a}(),wt=function(){var e=new X("FilterQueryOp");return e.Equals=e.addSymbol({operator:"eq",aliases:["=="]}),e.NotEquals=e.addSymbol({operator:"ne",aliases:["!="]}),e.GreaterThan=e.addSymbol({operator:"gt",aliases:[">"]}),e.LessThan=e.addSymbol({operator:"lt",aliases:["<"]}),e.GreaterThanOrEqual=e.addSymbol({operator:"ge",aliases:[">="]}),e.LessThanOrEqual=e.addSymbol({operator:"le",aliases:["<="]}),e.Contains=e.addSymbol({operator:"substringof",isFunction:!0,isStringFn:!0}),e.StartsWith=e.addSymbol({operator:"startswith",isFunction:!0,isStringFn:!0}),e.EndsWith=e.addSymbol({operator:"endswith",isFunction:!0,isStringFn:!0}),e.IsTypeOf=e.addSymbol({operator:"isof",isFunction:!0,aliases:["isTypeOf"]}),e.seal(),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}(),Ot=function(){var e=new X("BooleanQueryOp");return e.And=e.addSymbol({operator:"and",aliases:["&&"]}),e.Or=e.addSymbol({operator:"or",aliases:["||"]}),e.Not=e.addSymbol({operator:"not",aliases:["~","!"]}),e.seal(),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}(),Ct=function(){function e(e){if(1===e.length&&Array.isArray(e[0]))return e[0];var t=z(e);return Ct.isPredicate(t[0])?t:[Ct.create(t)]}var t=function(e,t,n,r){return arguments[0].prototype===!0?this:new At(e,t,n,r)},n=t.prototype;return t.isPredicate=function(e){return e instanceof Ct},t.create=function(e,t,n,r){return Array.isArray(e)?(r=4===e.length?e[3]:!1,new At(e[0],e[1],e[2],r)):new At(e,t,n,r)},t.and=function(t){return t=e(arguments),1===t.length?t[0]:new xt("and",t)},t.or=function(t){return t=e(arguments),1===t.length?t[0]:new xt("or",t)},t.not=function(e){return new xt("not",[e])},n.and=function(n){return n=e(arguments),n.unshift(this),t.and(n)},n.or=function(n){return n=e(arguments),n.unshift(this),t.or(n)},n.not=function(){return new xt("not",[this])},t}(),At=function(){function e(e,i,o){var s,u=e.metadataStore.localQueryComparisonOptions,p=L(o);switch(i){case wt.Equals:s=function(e,n){return e&&"string"==typeof e?t(e,n,u):p(e)==p(n)};break;case wt.NotEquals:s=function(e,n){return e&&"string"==typeof e?!t(e,n,u):p(e)!=p(n)};break;case wt.GreaterThan:s=function(e,t){return p(e)>p(t)};break;case wt.GreaterThanOrEqual:s=function(e,t){return p(e)>=p(t)};break;case wt.LessThan:s=function(e,t){return p(e)<p(t)};break;case wt.LessThanOrEqual:s=function(e,t){return p(e)<=p(t)};break;case wt.StartsWith:s=function(e,t){return n(e,t,u)};break;case wt.EndsWith:s=function(e,t){return r(e,t,u)};break;case wt.Contains:s=function(e,t){return a(e,t,u)};break;default:throw Error("Unknown FilterQueryOp: "+i)}return s}function t(e,t,n){return null==t?!1:("string"!=typeof t&&(t=""+t),n.usesSql92CompliantStringComparison&&(e=(e||"").trim(),t=(t||"").trim()),n.isCaseSensitive||(e=(e||"").toLowerCase(),t=(t||"").toLowerCase()),e===t)}function n(e,t,n){return n.isCaseSensitive||(e=(e||"").toLowerCase(),t=(t||"").toLowerCase()),k(e,t)}function r(e,t,n){return n.isCaseSensitive||(e=(e||"").toLowerCase(),t=(t||"").toLowerCase()),I(e,t)}function a(e,t,n){return n.isCaseSensitive||(e=(e||"").toLowerCase(),t=(t||"").toLowerCase()),e.indexOf(t)>=0}var i=function(e,t,n,r){if(Q(e,"propertyOrExpr").isString().isOptional().check(),Q(t,"operator").isEnumOf(wt).or().isString().check(),Q(n,"value").isRequired(!0).check(),Q(r).isOptional().isBoolean().check(),this._filterQueryOp=wt.from(t),!this._filterQueryOp)throw Error("Unknown query operation: "+t);if(e)this._propertyOrExpr=e,this._fnNode1=Nt.create(e,null,this._filterQueryOp);else if(this._filterQueryOp!==wt.IsTypeOf)throw Error("propertyOrExpr cannot be null except when using the 'IsTypeOf' operator");this._value=n,this._valueIsLiteral=r},o=new Ct({prototype:!0});return i.prototype=o,o.toOdataFragment=function(e){if(this._filterQueryOp==wt.IsTypeOf){var t=e.metadataStore.getEntityType(this._value),n=t.namespace+"."+t.shortName;return this._filterQueryOp.operator+"("+yt.String.fmtOData(n)+")"}var r,a=this._fnNode1&&this._fnNode1.toOdataFragment(e);if(void 0!==this.fnNode2||this._valueIsLiteral||(this.fnNode2=Nt.create(this._value,e)),this.fnNode2)r=this.fnNode2.toOdataFragment(e);else{var i=this._fnNode1.dataType||yt.fromValue(this._value);r=i.fmtOData(this._value)}return this._filterQueryOp.isFunction?this._filterQueryOp==wt.Contains?this._filterQueryOp.operator+"("+r+","+a+") eq true":this._filterQueryOp.operator+"("+a+","+r+") eq true":a+" "+this._filterQueryOp.operator+" "+r},o.toFunction=function(t){var n=this._fnNode1.dataType||yt.fromValue(this._value),r=e(t,this._filterQueryOp,n),a=this._fnNode1.fn;if(void 0!==this.fnNode2||this._valueIsLiteral||(this.fnNode2=Nt.create(this._value,t)),this.fnNode2){var i=this.fnNode2.fn;return function(e){return r(a(e),i(e))}}var o=this._value;return function(e){return r(a(e),o)}},o.toString=function(){return D("{%1} %2 {%3}",this._propertyOrExpr,this._filterQueryOp.operator,this._value)},o.validate=function(e){this._fnNode1&&(this._fnNode1.validate(e),this.dataType=this._fnNode1.dataType)},i}(),xt=function(){function e(e,t,n){var r,a;switch(t){case Ot.Not:return r=n[0].toFunction(e),function(e){return!r(e)};case Ot.And:return a=n.map(function(t){return t.toFunction(e)}),function(e){var t=a.reduce(function(t,n){return t&&n(e)},!0);return t};case Ot.Or:return a=n.map(function(t){return t.toFunction(e)}),function(e){var t=a.reduce(function(t,n){return t||n(e)},!1);return t};default:throw Error("Invalid boolean operator:"+t)}}var t=function(e,t){if(!Array.isArray(t))throw Error("predicates parameter must be an array");if(this._booleanQueryOp=Ot.from(e),!this._booleanQueryOp)throw Error("Unknown query operation: "+e);if(this._booleanQueryOp===Ot.Not&&1!==t.length)throw Error("Only a single predicate can be passed in with the 'Not' operator");this._predicates=t},n=new Ct({prototype:!0});return t.prototype=n,n.toOdataFragment=function(e){if(1==this._predicates.length)return this._booleanQueryOp.operator+" "+"("+this._predicates[0].toOdataFragment(e)+")";var t=this._predicates.map(function(t){return"("+t.toOdataFragment(e)+")"}).join(" "+this._booleanQueryOp.operator+" ");return t},n.toFunction=function(t){return e(t,this._booleanQueryOp,this._predicates)},n.toString=function(){if(1==this._predicates.length)return this._booleanQueryOp.operator+" "+"("+this._predicates[0]+")";var e=this._predicates.map(function(e){return"("+(""+e)+")"}).join(" "+this._booleanQueryOp.operator+" ");return e},n.validate=function(e){this._isValidated||(this._predicates.every(function(t){t.validate(e)}),this._isValidated=!0)},t}(),Mt=function(){var e=function(t,n){return t.prototype===!0?this:e.create(t,n)},t=e.prototype;return e.create=function(e,t){if(e.length>1){var n=e.map(function(e){return new kt(e,t)});return new It(n)}return new kt(e[0],t)},e.combine=function(e){return new It(e)},e.isOrderByClause=function(e){return e instanceof Mt},t.addClause=function(e){return new It([this,e])},e}(),kt=function(){var e=function(e,t){if("string"!=typeof e)throw Error("propertyPath is not a string");e=e.trim();var n=e.split(" ");if(n.length>1&&t!==!0&&t!==!1&&(t=k(n[1].toLowerCase(),"desc"),!t)){var r=k(n[1].toLowerCase(),"asc");
  if(!r)throw Error("the second word in the propertyPath must begin with 'desc' or 'asc'")}this.propertyPath=n[0],this.isDesc=t},t=new Mt({prototype:!0});return e.prototype=t,t.validate=function(e){e&&(this.lastProperty=e.getProperty(this.propertyPath,!0))},t.toOdataFragment=function(e){return e._clientPropertyPathToServer(this.propertyPath)+(this.isDesc?" desc":"")},t.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,a=this.isDesc;return function(e,i){var o=q(e,r),s=q(i,r),u=t||o&&yt.fromValue(o)||yt.fromValue(s);if(u===yt.String)n?(o=o||"",s=s||""):(o=(o||"").toLowerCase(),s=(s||"").toLowerCase());else{var p=L(u);o=p(o),s=p(s)}return o===s?0:o>s||void 0===s?a?-1:1:a?1:-1}},e}(),It=function(){var e=function(e){var t=[];e.forEach(function(e){if(e instanceof It)t=t.concat(e.orderByClauses);else{if(!(e instanceof kt))throw Error("Invalid argument to CompositeOrderByClause ctor.");t.push(e)}}),this._orderByClauses=t},t=new Mt({prototype:!0});return e.prototype=t,t.validate=function(e){this._orderByClauses.forEach(function(t){t.validate(e)})},t.toOdataFragment=function(e){var t=this._orderByClauses.map(function(t){return t.toOdataFragment(e)});return t.join(",")},t.getComparer=function(e){var t=this._orderByClauses.map(function(t){return t.getComparer(e)});return function(e,n){for(var r=0;t.length>r;r++){var a=t[r](e,n);if(0!==a)return a}return 0}},e}(),Dt=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){e&&this.propertyPaths.forEach(function(t){e.getProperty(t,!0)})},t.toOdataFragment=function(e){var t=this.propertyPaths.map(function(t){return e._clientPropertyPathToServer(t)}).join(",");return t},t.toFunction=function(){var e=this;return function(t){var n={};return e.propertyPaths.forEach(function(r,a){n[e._pathNames[a]]=q(t,r)}),n}},e}(),Vt=function(){var e=function(e){this.propertyPaths=e},t=e.prototype;return t.toOdataFragment=function(e){var t=this.propertyPaths.map(function(t){return e._clientPropertyPathToServer(t)}).join(",");return t},e}();B.FilterQueryOp=wt,B.Predicate=Ct,B.EntityQuery=Pt,B.FnNode=Nt,B.OrderByClause=Mt;var jt=function(){var e=new X("MergeStrategy");return e.PreserveChanges=e.addSymbol(),e.OverwriteChanges=e.addSymbol(),e.seal(),e}(),Ft=function(){var e=new X("FetchStrategy");return e.FromServer=e.addSymbol(),e.FromLocalCache=e.addSymbol(),e.seal(),e}(),Kt=function(){function e(e,t){return t&&H(t).whereParam("fetchStrategy").isEnumOf(Ft).isOptional().whereParam("mergeStrategy").isEnumOf(jt).isOptional().applyAll(e),e}var t=function(t){e(this,t)},n=t.prototype;return n._$typeName="QueryOptions",t.resolve=function(e){return new Kt(c(e,["fetchStrategy","mergeStrategy"]))},t.defaultInstance=new t({fetchStrategy:Ft.FromServer,mergeStrategy:jt.PreserveChanges}),n.using=function(t){if(!t)return this;var n=new Kt(this);return jt.contains(t)?t={mergeStrategy:t}:Ft.contains(t)&&(t={fetchStrategy:t}),e(n,t)},n.setAsDefault=function(){return u(this,t)},n.toJSON=function(){return p(this,{fetchStrategy:null,mergeStrategy:null})},t.fromJSON=function(e){return new Kt({fetchStrategy:Ft.fromName(e.fetchStrategy),mergeStrategy:jt.fromName(e.mergeStrategy)})},t}();B.QueryOptions=Kt,B.FetchStrategy=Ft,B.MergeStrategy=jt;var Rt=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([ut.Added,ut.Modified,ut.Deleted]),n=function(e,t){this.entityManager=e,this.entityType=t,this._indexMap={},this._entities=[],this._emptyIndexes=[]},r=n.prototype;return r.attachEntity=function(e,t){var n,r=e.entityAspect,a=r.getKey()._keyInGroup;if(n=this._indexMap[a],n>=0){if(this._entities[n]===e)return r.entityState=t,e;throw Error("This key is already attached: "+r.getKey())}return 0===this._emptyIndexes.length?n=this._entities.push(e)-1:(n=this._emptyIndexes.pop(),this._entities[n]=e),this._indexMap[a]=n,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 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 st?e._keyInGroup:st.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._clear=function(){this._entities.forEach(function(e){null!=e&&e.entityAspect._detach()}),this._entities=null,this._indexMap=null,this._emptyIndexes=null},r._fixupKey=function(e,t){var n=this._indexMap[e];if(void 0===n)throw Error("Internal Error in key fixup - unable to locate entity");var r=this._entities[n],a=r.entityType.keyProperties[0].name;r.setProperty(a,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}(),qt=function(){function t(e,t,n){var r=n?Kt.defaultInstance:e.queryOptions,a=n?Lt.defaultInstance:e.saveOptions,i=n?rt.defaultInstance:e.validationOptions,o=H(t).whereParam("serviceName").isOptional().isString().whereParam("dataService").isOptional().isInstanceOf(pt).whereParam("queryOptions").isInstanceOf(Kt).isOptional().withDefault(r).whereParam("saveOptions").isInstanceOf(Lt).isOptional().withDefault(a).whereParam("validationOptions").isInstanceOf(rt).isOptional().withDefault(i).whereParam("keyGeneratorCtor").isFunction().isOptional();n&&(o=o.whereParam("metadataStore").isInstanceOf(ft).isOptional().withDefault(new ft)),o.applyAll(e),s(e.queryOptions,r),s(e.saveOptions,a),s(e.validationOptions,i),t.serviceName&&(e.dataService=new pt({serviceName:e.serviceName})),e.serviceName=e.dataService&&e.dataService.serviceName,e.keyGeneratorCtor=e.keyGeneratorCtor||St,(n||t.keyGeneratorCtor)&&(e.keyGenerator=new e.keyGeneratorCtor)}function n(e,t){if(e.length!==t.length)return!1;for(var n=0,r=e.length;r>n;n++)if(e[n]!==t[n])return!1;return!0}function r(e,t){return Q(t,"entityTypes").isString().isOptional().or().isNonEmptyArray().isString().or().isInstanceOf(dt).or().isNonEmptyArray().isInstanceOf(dt).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 a(e,t,n){var r,a=b(e,t);return a.forEach(function(e){if(e){var t=e.getEntities(n);r?r.push.apply(r,t):r=t}}),r||[]}function o(e,t){if(t[0]instanceof st)return{entityKey:t[0],remainingArgs:z(t,1)};if("string"==typeof t[0]&&t.length>=2){var n=e.metadataStore._getEntityType(t[0],!1);return{entityKey:new st(n,t[1]),remainingArgs:z(t,2)}}throw Error("This method requires as its initial parameters either an EntityKey or an entityType name followed by a value or an array of values.")}function u(e,t){e.forEach(function(e){e.entityAspect.isBeingSaved=t})}function p(t,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=t._entityGroupMap;var a=[],i={};return e(r,function(e,t){i[e]=c(t,a)}),{entityGroupMap:i,tempKeys:a}}function c(e,t){var n={},r=e.entityType,a=r.dataProperties,i=[];return e._entities.forEach(function(e){if(e){var n=y(e,a,t);i.push(n)}}),n.entities=i,n}function y(e,t,n){var r={};t.forEach(function(t){var n=t.name,a=e.getProperty(n);if(null!=a||null!=t.defaultValue)if(a&&a.complexType){var i=t.dataType.dataProperties;r[n]=Array.isArray(a)?0==a.length?[]:a.map(function(e){return y(e,i)}):y(a,i)}else r[n]=a});var a,i;if(e.entityAspect){a=e.entityAspect;var o=a.entityState;i={tempNavPropNames:f(a,n),entityState:o.name},(o.isModified()||o.isDeleted())&&(i.originalValuesMap=a.originalValues),r.entityAspect=i}else a=e.complexAspect,i={},a.originalValues&&!x(a.originalValues)&&(i.originalValuesMap=a.originalValues),r.complexAspect=i;return r}function f(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 m(e,t,n){var r=n.tempKeyMap,a=e.entityType,i=n.mergeStrategy===jt.OverwriteChanges,o=null,s=a.dataProperties;a.keyProperties;var u=e.entityManager.entityChanged;t.entities.forEach(function(t){var n,p=t.entityAspect,c=q(t,a,!0),y=ut.fromName(p.entityState);if(y.isAdded()?(n=r[""+c],o=void 0===n?e.findEntityByKey(c):null):o=e.findEntityByKey(c),o){var l=o.entityAspect.entityState.isUnchanged();i||l?(K(o,t,s,!0),u.publish({entityAction:at.MergeOnImport,entity:o}),l?y.isUnchanged()||e.entityManager._notifyStateChange(o,!0):y.isUnchanged()&&e.entityManager._notifyStateChange(o,!1)):o=null}else o=a._createEntityCore(),K(o,t,s,!0),void 0!==n&&(o.setProperty(a.keyProperties[0].name,n),p.tempNavPropNames&&p.tempNavPropNames.forEach(function(e){var t=a.getNavigationProperty(e),n=t.relatedDataProperties[0].name,i=o.getProperty(n),s=new st(t.entityType,[i]),u=r[""+s];o.setProperty(n,u)})),o.entityAspect._postInitialize(),o=e.attachEntity(o,y),u&&(u.publish({entityAction:at.AttachOnImport,entity:o}),y.isUnchanged()||e.entityManager._notifyStateChange(o,!0));o&&(o.entityAspect.entityState=y,y.isModified()&&(o.entityAspect.originalValuesMap=p.originalValues),e.entityManager._linkRelatedEntities(o))})}function g(e,t,n){return e=e.then(function(e){return t&&t(e),lt.resolve(e)}).fail(function(e){return n&&n(e),lt.reject(e)})}function _(e,t){var n;return n=t?t.filter(function(t){if(t.entityAspect.entityManager!==e)throw Error("Only entities in this entityManager may be saved");return!t.entityAspect.entityState.isDetached()}):e.getChanges()}function E(e,t){e._inKeyFixup=!0,t.forEach(function(t){var n=e._entityGroupMap[t.entityTypeName];if(!n)throw Error("Unable to locate the following fully qualified EntityType name: "+t.entityTypeName);n._fixupKey(t.tempValue,t.realValue)}),e._inKeyFixup=!1}function b(e,t){function n(){return Error("The EntityManager.getChanges() 'entityTypes' parameter must be either an entityType or an array of entityTypes or null")}var r=e._entityGroupMap;if(t){if(t instanceof dt)return[r[t.name]];if(Array.isArray(t))return t.map(function(e){if(e instanceof dt)return r[e.name];throw n()});throw n()}return i(r)}function N(e,t){var n=t.entityAspect.getKey(),r=d(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!==_t.None)e.generateTempKeyValue(t);else if(r.length===n.values.length)throw Error("Cannot attach an object to an EntityManager without first setting its key or setting its entityType 'AutoGeneratedKeyType' property to something other than 'None'")}function O(e,t){function n(){return Error("The EntityManager.getChanges() 'entityStates' parameter must either be null, an entityState or an array of entityStates")}if(!t)return null;if(ut.contains(t))t=[t];else{if(!Array.isArray(t))throw n();t.forEach(function(e){if(!ut.contains(e))throw n()})}return t}function C(e,t,n){var r=ct(e,t.entityType);r.attachEntity(t,n),e._linkRelatedEntities(t)}function A(e,t,n){var r=t.entityType.navigationProperties;r.forEach(function(r){var a=t.getProperty(r.name);if(r.isScalar){if(!a)return;e.attachEntity(a,n)}else a.forEach(function(t){e.attachEntity(t,n)})})}function M(e,t,n,r){try{var a=e.metadataStore;if(a.isEmpty()&&r.hasServerMetadata)throw Error("cannot execute _executeQueryCore until metadataStore is populated.");if(n.fetchStrategy===Ft.FromLocalCache)return lt.fcall(function(){var n=e.executeQueryLocally(t);return{results:n,query:t}});var i=r.makeUrl(a.toQueryString(t)),o={url:i,query:t,entityManager:e,dataService:r,queryOptions:n,refMap:{},deferredFns:[]},s=e.validationOptions.validateOnQuery;return r.adapterInstance.executeQuery(o).then(function(n){var a=T(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,t=null,o=null,n.error&&lt.reject(n.error)},function(){var a=r.jsonResultsAdapter.extractResults(n);Array.isArray(a)||(a=[a]);var i=a.map(function(e){var t=k(e,o,{nodeType:"root"});return s&&t.entityAspect&&t.entityAspect.validateEntity(),t});return o.deferredFns.length>0&&o.deferredFns.forEach(function(e){e()}),{results:i,query:t,entityManager:e,XHR:n.XHR,inlineCount:n.inlineCount}});return lt.resolve(a)}).fail(function(n){return n&&(n.query=t,n.entityManager=e),lt.reject(n)})}catch(u){return u&&(u.query=t),lt.reject(u)}}function k(e,t,n){if(null==t.query&&e.entityAspect)return e.entityAspect.entityState.isDeleted()?t.entityManager.detachEntity(e):e.entityAspect.acceptChanges(),e;n=n||{};var r=t.dataService.jsonResultsAdapter.visitNode(e,t,n)||{};return t.query&&"root"===n.nodeType&&!r.entityType&&(r.entityType=t.query._getToEntityType&&t.query._getToEntityType(t.entityManager.metadataStore)),I(e,t,r)}function I(e,t,n,r){if(n.ignore||null==e)return null;if(n.nodeRefId){var a=D(n.nodeRefId,t);return"function"==typeof a?(t.deferredFns.push(function(){r(a)}),void 0):a}return n.entityType?n.entityType.isComplexType?e:V(e,t,n):(n.nodeId&&(t.refMap[n.nodeId]=e),"object"!=typeof e||w(e)?e:j(e,t))}function D(e,t){var n=t.refMap[e];return void 0===n?function(){return t.refMap[e]}:n}function V(e,t,n){e._$meta=n;var r=t.entityManager,a=n.entityType;"string"==typeof a&&(a=r.metadataStore._getEntityType(a,!1)),e.entityType=a;var i=t.queryOptions.mergeStrategy,o=null==t.query,s=q(e,a,!1),u=r.findEntityByKey(s);if(u){if(o&&u.entityAspect.entityState.isDeleted())return r.detachEntity(u),u;var p=u.entityAspect.entityState;if(i===jt.OverwriteChanges||p.isUnchanged()){F(u,e,t),u.entityAspect.wasLoaded=!0,n.extra&&(u.entityAspect.extraMetadata=n.extra),u.entityAspect.entityState=ut.Unchanged,u.entityAspect.originalValues={},u.entityAspect.propertyChanged.publish({entity:u,propertyName:null});var c=o?at.MergeOnSave:at.MergeOnQuery;r.entityChanged.publish({entityAction:c,entity:u}),p.isUnchanged||r._notifyStateChange(u,!1)}else G(t,u,e),a.navigationProperties.forEach(function(n){n.isScalar?J(e,n,t):et(e,n,t)})}else u=a._createEntityCore(),u.initializeFrom&&u.initializeFrom(e),F(u,e,t),u.entityAspect._postInitialize(),n.extra&&(u.entityAspect.extraMetadata=n.extra),C(r,u,ut.Unchanged),u.entityAspect.wasLoaded=!0,r.entityChanged.publish({entityAction:at.AttachOnQuery,entity:u});return u}function j(t,n){var r=n.entityManager,a=n.dataService.jsonResultsAdapter,i=r.metadataStore.namingConvention.serverPropertyNameToClient,o={};return e(t,function(e,t){var r=a.visitNode(t,n,{nodeType:"anonProp",propertyName:e})||{};if(!r.ignore){var s=i(e);o[s]=Array.isArray(t)?t.map(function(t,i){return r=a.visitNode(t,n,{nodeType:"anonPropItem",propertyName:e})||{},I(t,n,r,function(e){o[s][i]=e()})}):I(t,n,r,function(e){o[s]=e()})}}),o}function F(e,t,n){G(n,e,t);var r=e.entityType;K(e,t,r.dataProperties,!1),r.navigationProperties.forEach(function(r){r.isScalar?$(r,e,t,n):Z(r,e,t,n)})}function K(e,t,n,r){if(n.forEach(function(n){R(e,t,n,r)}),r){var a=e.entityAspect?"entityAspect":"complexAspect",i=t[a].originalValuesMap;i&&(e[a].originalValues=i)}}function R(e,t,n,r){var a=r?L:B,i=a(t,n);if(void 0!==i){var o;if(n.isComplexProperty){o=e.getProperty(n.name);var s=n.dataType.dataProperties;n.isScalar?K(o,i,s,r):(o.length=0,i.forEach(function(t){var a=n.dataType._createInstanceCore(e,n);K(a,t,s,r),o.push(a)}))}else{var u;n.isScalar?(u=U(n,i),e.setProperty(n.name,u)):(o=e.getProperty(n.name),o.length=0,i.forEach(function(e){u=U(n,e),o.push(u)}))}}}function q(e,t,n){var r=n?L:B,a=t.keyProperties.map(function(t){return U(t,r(e,t))});return new st(t,a)}function L(e,t){return e[t.name]}function B(e,t){return e[t.nameOnServer||t.isUnmapped&&t.name]}function U(e,t){return void 0===t?void 0:(e.dataType.isDate&&t?w(t)||(t=yt.parseDateFromServer(t)):e.dataType===yt.Binary&&t&&void 0!==t.$value&&(t=t.$value),t)}function G(e,t,n){var r=n._$meta.nodeId;null!=r&&(e.refMap[r]=t)}function $(e,t,n,r){var a=J(n,e,r);null!=a&&("function"==typeof a?r.deferredFns.push(function(){a=a(),X(a,t,e)}):X(a,t,e))}function J(e,t,n){var r=e[t.nameOnServer];if(!r)return null;var a=k(r,n,{nodeType:"navProp",navigationProperty:t});return a}function X(e,t,n){if(e){var r=n.name,a=t.getProperty(r);if(a!==e){t.setProperty(r,e);var i=n.inverse;if(!i)return;if(i.isScalar)e.setProperty(i.name,t);else{var o=e.getProperty(i.name);o.push(t)}}}}function Z(e,t,n,r){var a=et(n,e,r);if(null!=a){var i=e.inverse;if(i){var o=t.getProperty(e.name);o.wasLoaded=!0,a.forEach(function(e){"function"==typeof e?r.deferredFns.push(function(){e=e(),tt(e,o,t,i)}):tt(e,o,t,i)})}}}function et(e,t,n){var r=e[t.nameOnServer];if(!r)return null;if(!Array.isArray(r))return null;var a=r.map(function(e){return k(e,n,{nodeType:"navPropItem",navigationProperty:t})});return a}function tt(e,t,n,r){if(e){var a=e.getProperty(r.name);a!==n&&(t.push(e),e.setProperty(r.name,n))}}function nt(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){ot(e,t)})})}function ot(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,a=new Date;r.getTime()===a.getTime();)a=new Date;e.setProperty(t.name,a)}else{if(t.dataType!==yt.Guid){if(t.dataType===yt.Binary)return;throw Error("Unable to update the value of concurrency property before saving: "+t.name)}e.setProperty(t.name,P())}}}function ct(e,t){var n=e._entityGroupMap[t.name];return n||(n=new Rt(e,t),e._entityGroupMap[t.name]=n),n}function ht(e,t){var n=t.getSelfAndSubtypes();return n.map(function(t){return ct(e,t)})}function mt(e,t){var n={},r=e.entityType||e.complexType;return r.dataProperties.forEach(function(r){if(r.isUnmapped){if(t)return;var a=e.getProperty(r.name);a=Tt(a,r,!1),void 0!==a&&(n.__unmapped=n.__unmapped||{},n.__unmapped[r.name]=a)}else if(r.isComplexProperty)if(r.isScalar)n[r.nameOnServer]=mt(e.getProperty(r.name),t);else{var i=e.getProperty(r.name);n[r.nameOnServer]=i.map(function(e){return mt(e,t)})}else{var a=e.getProperty(r.name);a=Tt(a,r,t),void 0!==a&&(n[r.nameOnServer]=a)}}),n}function vt(t,n,r){var a=t.entityType||t.complexType,i=t.entityAspect||t.complexAspect,o=n.namingConvention.clientPropertyNameToServer,s={};return e(i.originalValues,function(e,t){var n=a.getProperty(e);t=Tt(t,n,r),void 0!==t&&(s[o(e,n)]=t)}),a.complexProperties.forEach(function(e){var a=t.getProperty(e.name);if(e.isScalar){var i=vt(a,n,r);x(i)||(s[o(e.name,e)]=i)}else{var u=a.map(function(e){return vt(e,n,r)});s[o(e.name,e)]=u}}),s}function gt(t,n,r){var a=t.entityType||t.complexType,i=t.entityAspect||t.complexAspect,o=n.namingConvention.clientPropertyNameToServer,s={};return e(i.originalValues,function(e){var n=a.getProperty(e),i=t.getProperty(e);i=Tt(i,n,r),void 0!==i&&(s[o(e,n)]=i)}),a.complexProperties.forEach(function(e){var r=t.getProperty(e.name);if(e.isScalar){var a=gt(r,n);x(a)||(s[o(e.name,e)]=a)}else{var i=r.map(function(e){return gt(e,n)});s[o(e.name,e)]=i}}),s}function Tt(e,t,n){if(n){if(t.isUnmapped)return;t.dataType===yt.DateTimeOffset?e=e&&new Date(e.getTime()-6e4*e.getTimezoneOffset()):t.dataType.quoteJsonOData&&(e=null!=e?""+e:e)}return e}function Et(){this.map={}}var bt=function(e){if(arguments.length>1)throw Error("The EntityManager ctor has a single optional argument that is either a 'serviceName' or a configuration object.");0===arguments.length?e={serviceName:""}:"string"==typeof e&&(e={serviceName:e}),t(this,e,!0),this.entityChanged=new W("entityChanged_entityManager",this),this.hasChangesChanged=new W("hasChangesChanged_entityManager",this),this.clear()},Nt=bt.prototype;return Nt._$typeName="EntityManager",W.bubbleEvent(Nt,null),Nt.setProperties=function(e){t(this,e,!1)},Nt.createEntity=function(e,t,n){Q(e,"entityType").isString().or().isInstanceOf(dt).check(),"string"==typeof e&&(e=this.metadataStore._getEntityType(e)),n=n||ut.Added;var r;return S(this,"isLoading",!0,function(){r=e.createEntity(t)}),n!==ut.Detached&&this.attachEntity(r,n),r},bt.importEntities=function(e,t){var n=new qt;return n.importEntities(e,t),n},Nt.exportEntities=function(e){var t=p(this,e),n={metadataStore:this.metadataStore.exportMetadata(),dataService:this.dataService,saveOptions:this.saveOptions,queryOptions:this.queryOptions,validationOptions:this.validationOptions,tempKeys:t.tempKeys,entityGroupMap:t.entityGroupMap},r=JSON.stringify(n,null,Y.stringifyPad);return r},Nt.importEntities=function(t,n){n=n||{},H(n).whereParam("mergeStrategy").isEnumOf(jt).isOptional().withDefault(this.queryOptions.mergeStrategy).applyAll(n);var r=this,a="string"==typeof t?JSON.parse(t):t;this.metadataStore.importMetadata(a.metadataStore),this.dataService=a.dataService&&pt.fromJSON(a.dataService)||new pt({serviceName:a.serviceName}),this.saveOptions=new Lt(a.saveOptions),this.queryOptions=Kt.fromJSON(a.queryOptions),this.validationOptions=new rt(a.validationOptions);var i={};return a.tempKeys.forEach(function(e){var t=st.fromJSON(e,r.metadataStore);i[""+t]=r.keyGenerator.generateTempKeyValue(t.entityType,t.values[0])}),n.tempKeyMap=i,T(function(){r._pendingPubs=[]},function(){r._pendingPubs.forEach(function(e){e()}),r._pendingPubs=null},function(){e(a.entityGroupMap,function(e,t){var a=r.metadataStore._getEntityType(e,!0),i=ct(r,a);m(i,t,n)})}),this},Nt.clear=function(){e(this._entityGroupMap,function(e,t){t._clear()}),this._entityGroupMap={},this._unattachedChildrenMap=new Et,this.keyGenerator=new this.keyGeneratorCtor,this.entityChanged.publish({entityAction:at.Clear}),this._hasChanges&&(this._hasChanges=!1,this.hasChangesChanged.publish({entityManager:this,hasChanges:!1}))},Nt.createEmptyCopy=function(){var e=new bt({dataService:this.dataService,metadataStore:this.metadataStore,queryOptions:this.queryOptions,saveOptions:this.saveOptions,validationOptions:this.validationOptions,keyGeneratorCtor:this.keyGeneratorCtor});return e},Nt.addEntity=function(e){return this.attachEntity(e,ut.Added)},Nt.attachEntity=function(e,t){if(Q(e,"entity").isRequired().check(),this.metadataStore._checkEntityType(e),t=Q(t,"entityState").isEnumOf(ut).isOptional().check(ut.Unchanged),e.entityType.metadataStore!==this.metadataStore)throw Error("Cannot attach this entity because the EntityType and MetadataStore associated with this entity does not match this EntityManager's MetadataStore.");var n=e.entityAspect;n||(n=new it(e),n._postInitialize(e));var r=n.entityManager;if(r){if(r===this)return e;throw Error("This entity already belongs to another EntityManager")}var a=this;return S(this,"isLoading",!0,function(){t.isAdded()&&N(a,e),C(a,e,t),A(a,e,t)}),this.validationOptions.validateOnAttach&&e.entityAspect.validateEntity(),t.isUnchanged()||this._notifyStateChange(e,!0),this.entityChanged.publish({entityAction:at.Attach,entity:e}),e},Nt.detachEntity=function(e){Q(e,"entity").isEntity().check();var t=e.entityAspect;if(!t)return!1;if(t.entityManager!==this)throw Error("This entity does not belong to this EntityManager.");return t.setDetached()},Nt.fetchMetadata=function(e,t,n){"function"==typeof e?(n=t,t=e,e=null):(Q(e,"dataService").isInstanceOf(pt).isOptional().check(),Q(t,"callback").isFunction().isOptional().check(),Q(n,"errorCallback").isFunction().isOptional().check());var r=this.metadataStore.fetchMetadata(e||this.dataService);return g(r,t,n)},Nt.executeQuery=function(e,t,n){Q(e,"query").isInstanceOf(Pt).or().isString().check(),Q(t,"callback").isFunction().isOptional().check(),Q(n,"errorCallback").isFunction().isOptional().check();var r,a=Kt.resolve([e.queryOptions,this.queryOptions,Kt.defaultInstance]),i=pt.resolve([e.dataService,this.dataService]);if(!i.hasServerMetadata||this.metadataStore.hasMetadataFor(i.serviceName))r=M(this,e,a,i);else{var o=this;r=this.fetchMetadata(i).then(function(){return M(o,e,a,i)})}return g(r,t,n)},Nt.executeQueryLocally=function(e){Q(e,"query").isInstanceOf(Pt).check();var t=this.metadataStore,n=e._getFromEntityType(t,!0),r=ht(this,n),a=e._toFilterFunction(n);if(a)var i=function(e){return e&&!e.entityAspect.entityState.isDeleted()&&a(e)};else var i=function(e){return e&&!e.entityAspect.entityState.isDeleted()};var o=[];r.forEach(function(e){o.push.apply(o,e._entities.filter(i))});var s=e._toOrderByComparer(n);s&&o.sort(s);var u=e.skipCount;u&&(o=o.slice(u));var p=e.takeCount;p&&(o=o.slice(0,p));var c=e.selectClause;if(c){var y=c.toFunction();o=o.map(function(e){return y(e)})}return o},Nt.saveChanges=function(e,t,r,a){Q(e,"entities").isOptional().isArray().isEntity().check(),Q(t,"saveOptions").isInstanceOf(Lt).isOptional().check(),Q(r,"callback").isFunction().isOptional().check(),Q(a,"errorCallback").isFunction().isOptional().check(),t=t||this.saveOptions||Lt.defaultInstance;var i=null==e,o=_(this,e);if(0===o.length){var s={entities:[],keyMappings:[]};return r&&r(s),lt.resolve(s)}if(!t.allowConcurrentSaves){var p=o.some(function(e){return e.entityAspect.isBeingSaved});if(p){var c=Error("Concurrent saves not allowed - SaveOptions.allowConcurrentSaves is false");return a&&a(c),lt.reject(c)}}if(this.validationOptions.validateOnSave){var y=o.filter(function(e){var t=e.entityAspect,n=t.entityState.isDeleted()||t.validateEntity();return!n});if(y.length>0){var l=Error("Validation error");return l.entitiesWithErrors=y,a&&a(l),lt.reject(l)}}nt(o);var f=pt.resolve([t.dataService,this.dataService]),h={entityManager:this,dataService:f,resourceName:t.resourceName||this.saveOptions.resourceName||"SaveChanges"},d={mergeStrategy:jt.OverwriteChanges},m={entities:o,saveOptions:t},v=this;return f.adapterInstance.saveChanges(h,m).then(function(e){E(v,e.keyMappings);var t={query:null,entityManager:v,queryOptions:d,dataService:f,refMap:{},deferredFns:[]},a=e.entities.map(function(e){return k(e,t,{nodeType:"root"})});return u(o,!1),v._hasChanges=i&&n(o,a)?!1:v._hasChangesCore(),v._hasChanges||v.hasChangesChanged.publish({entityManager:v,hasChanges:!1}),e.entities=a,r&&r(e),lt.resolve(e)},function(e){return u(o,!1),a&&a(e),lt.reject(e)})},Nt._findEntityGroup=function(e){return this._entityGroupMap[e.name]},Nt.getEntityByKey=function(){var e,t=o(this,arguments).entityKey,n=t._subTypes;if(!n)return e=this._findEntityGroup(t.entityType),e&&e.findEntityByKey(t);for(var r=0,a=n.length;a>r;r++){e=this._findEntityGroup(n[r]);var i=e&&e.findEntityByKey(t);if(i)return i}},Nt.fetchEntityByKey=function(){var e,t=o(this,arguments),n=t.entityKey,r=0===t.remainingArgs.length?!1:!!t.remainingArgs[0],a=!1;return r&&(e=this.getEntityByKey(n),a=e&&e.entityAspect.entityState.isDeleted(),a&&(e=null,this.queryOptions.mergeStrategy===jt.OverwriteChanges&&(a=!1))),e||a?lt.resolve({entity:e,entityKey:n,fromCache:!0}):Pt.fromEntityKey(n).using(this).execute().then(function(t){return e=0===t.results.length?null:t.results[0],lt.resolve({entity:e,entityKey:n,fromCache:!1})})},Nt.findEntityByKey=function(e){return this.getEntityByKey(e)},Nt.generateTempKeyValue=function(e){Q(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},Nt.hasChanges=function(e){return this._hasChanges?void 0===e?this._hasChanges:this._hasChangesCore(e):!1},Nt._hasChangesCore=function(e){e=r(this,e);var t=b(this,e);return t.some(function(e){return e.hasChanges()})},Nt.getChanges=function(e){e=r(this,e);var t=[ut.Added,ut.Modified,ut.Deleted];return a(this,e,t)},Nt.rejectChanges=function(){if(!this._hasChanges)return[];var e=[ut.Added,ut.Modified,ut.Deleted],t=a(this,null,e);return this._hasChanges=!1,t.forEach(function(e){e.entityAspect.rejectChanges()}),this.hasChangesChanged.publish({entityManager:this,hasChanges:!1}),t},Nt.getEntities=function(e,t){return e=r(this,e),Q(t,"entityStates").isOptional().isEnumOf(ut).or().isNonEmptyArray().isEnumOf(ut).check(),t&&(t=O(this,t)),a(this,e,t)},Nt._notifyStateChange=function(e,t){this.entityChanged.publish({entityAction:at.EntityStateChange,entity:e}),t?this._hasChanges||(this._hasChanges=!0,this.hasChangesChanged.publish({entityManager:this,hasChanges:!0})):this._hasChanges&&(this._hasChanges=this._hasChangesCore(),this._hasChanges||this.hasChangesChanged.publish({entityManager:this,hasChanges:!1}))},Nt._linkRelatedEntities=function(e){var t=this,n=e.entityAspect;S(t,"isLoading",!0,function(){var r=t._unattachedChildrenMap,a=n.getKey(),i=r.getTuples(a);i&&i.forEach(function(t){var n,i,o=t.children.filter(function(e){return e.entityAspect.entityState!==ut.Detached}),s=t.navigationProperty;if(s.inverse)if(n=s,i=s.inverse,i.isScalar){var u=o[0];e.setProperty(i.name,u),u.setProperty(n.name,e)}else{var p=e.getProperty(i.name);o.forEach(function(t){p.push(t),t.setProperty(n.name,e)})}else if(s.parentType===e.entityType)if(i=s,i.isScalar)e.setProperty(i.name,o[0]);else{var p=e.getProperty(i.name);o.forEach(function(e){p._push(e)})}else n=s,o.forEach(function(t){t.setProperty(n.name,e)});r.removeChildren(a,n)}),e.entityType.navigationProperties.forEach(function(a){if(a.isScalar){var i=e.getProperty(a.name);if(i)return}var o=n.getParentKey(a);if(o){if(o._isEmpty())return;var s=t.findEntityByKey(o);s?e.setProperty(a.name,s):r.addChild(o,a,e)}}),e.entityType.foreignKeyProperties.forEach(function(n){var a=n.inverseNavigationProperty;if(a){var i=e.getProperty(n.name),o=new st(a.parentType,[i]),s=t.findEntityByKey(o);s?a.isScalar?s.setProperty(a.name,e):t.isLoading?s.getProperty(a.name)._push(e):s.getProperty(a.name).push(e):r.addChild(o,a,e)}})})},Nt.helper={unwrapInstance:mt,unwrapOriginalValues:vt,unwrapChangedValues:gt,getEntityKeyFromRawEntity:q},Et.prototype.addChild=function(e,t,n){var r=this.getTuple(e,t);r||(r={navigationProperty:t,children:[]},v(this.map,""+e).push(r)),r.children.push(n)},Et.prototype.removeChildren=function(e,t){var n=this.map[""+e];n&&(h(n,function(e){return e.navigationProperty===t}),n.length||delete this.map[""+e])},Et.prototype.getChildren=function(e,t){var n=this.getTuple(e,t);return n?n.children.filter(function(e){return!e.entityAspect.entityState.isDetached()}):null},Et.prototype.getTuple=function(e,t){var n=this.map[""+e];if(!n)return null;var r=l(n,function(e){return e.navigationProperty===t});return r},Et.prototype.getTuples=function(e){return this.map[""+e]},bt}();B.EntityManager=qt;var Lt=function(){function e(e,t){return t&&H(t).whereParam("resourceName").isOptional().isString().whereParam("dataService").isOptional().isInstanceOf(pt).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 u(this,t)},n.using=function(t){return e(this,t)},t.defaultInstance=new t({allowConcurrentSaves:!1}),t}();B.SaveOptions=Lt,B.AbstractDataServiceAdapter=function(){var e,t=function(){};return t.prototype.checkForRecomposition=function(e){"ajax"===e.interfaceName&&e.isDefault&&this.initialize()},t.prototype.initialize=function(){if(e=B.config.getAdapterInstance("ajax"),!e)throw Error("Unable to initialize ajax for WebApi.");var t=e.ajax;if(!t)throw Error("Breeze was unable to find an 'ajax' adapter")},t.prototype.fetchMetadata=function(t,n){var r=n.serviceName,a=n.makeUrl("Metadata"),i=lt.defer(),o=this;
  return e.ajax({url:a,dataType:"json",success:function(e,o,s){var u;if(t.hasMetadataFor(r))return i.resolve("already fetched");var p="string"==typeof e?JSON.parse(e):e;if(p)try{t.importMetadata(p)}catch(c){u=Error("Metadata import failed for "+a+"; Unable to process returned metadata:"+c.message)}else u=Error("Metadata query failed for: "+a);return u?i.reject(u):(t.hasMetadataFor(r)||t.addDataService(n),s.onreadystatechange=null,s.abort=null,i.resolve(p),void 0)},error:function(e){o._handleXHRError(i,e,"Metadata query failed for: "+a)}}),i.promise},t.prototype.executeQuery=function(t){var n=lt.defer(),r=this,a={url:t.url,dataType:"json",success:function(e,t,a){try{var i;i=e.Results?{results:e.Results,inlineCount:e.InlineCount,XHR:a}:{results:e,XHR:a},n.resolve(i),a.onreadystatechange=null,a.abort=null}catch(o){var s=o instanceof Error?o:r._createError(a);n.reject(s),a.onreadystatechange=null,a.abort=null}},error:function(e){r._handleXHRError(n,e)}};return t.dataService.useJsonp&&(a.dataType="jsonp",a.crossDomain=!0),e.ajax(a),n.promise},t.prototype.saveChanges=function(t,n){var r=lt.defer();n=this._prepareSaveBundle(n,t);var a=JSON.stringify(n),i=t.dataService.makeUrl(t.resourceName),o=this;return e.ajax({url:i,type:"POST",dataType:"json",contentType:"application/json",data:a,success:function(e,n,a){var i=e.Error||e.error;if(i){var s=o._createError(a);s.message=i,r.reject(s)}else{var u=o._prepareSaveResult(t,e);r.resolve(u)}},error:function(e){o._handleXHRError(r,e)}}),r.promise},t.prototype._prepareSaveBundle=function(){throw Error("Need a concrete implementation of _prepareSaveBundle")},t.prototype._prepareSaveResult=function(){throw Error("Need a concrete implementation of _prepareSaveResult")},t.prototype.jsonResultsAdapter=new ct({name:"noop",visitNode:function(){return{}}}),t.prototype._handleXHRError=function(e,t,n){var r=this._createError(t);n&&(r.message=n+"; "+r.message),e.reject(r),t.onreadystatechange=null,t.abort=null},t.prototype._createError=function(e){var t=Error();if(t.XHR=e,t.responseText=e.responseText,t.status=e.status,t.statusText=e.statusText,t.message=e.statusText,t.responseText)try{var n=JSON.parse(e.responseText);t.detail=n;var r=n.InnerException||n;t.message=r.ExceptionMessage||r.Message||e.responseText}catch(a){t.message=t.message+": "+t.responseText}return t},t}(),function(e){B?e(B):"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?e(require("breeze")):"function"==typeof define&&define.amd&&define(["breeze"],e)}(function(e){var t,n=e.core,r=function(){this.name="jQuery",this.defaultSettings={}};r.prototype.initialize=function(){t=n.requireLib("jQuery")},r.prototype.ajax=function(e){if(!t)throw Error("Unable to locate jQuery");if(n.isEmpty(this.defaultSettings))t.ajax(e);else{var r=n.extend({},this.defaultSettings);n.extend(r,e),t.ajax(r)}},e.config.registerAdapter("ajax",r)}),function(e){B?e(B):"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?e(require("breeze")):"function"==typeof define&&define.amd&&!B&&define(["breeze"],e)}(function(e){function t(e,t){var r=[],a=[],i=[],o=e.dataService.serviceName,s=e.entityManager,u=s.helper,p=0;return t.entities.forEach(function(e){var t=e.entityAspect;p+=1;var c={headers:{"Content-ID":p,DataServiceVersion:"2.0"}};if(i[p]=e,t.entityState.isAdded())c.requestUri=e.entityType.defaultResourceName,c.method="POST",c.data=u.unwrapInstance(e,!0),a[p]=t.getKey();else if(t.entityState.isModified())n(c,t,o),c.method="MERGE",c.data=u.unwrapChangedValues(e,s.metadataStore,!0);else{if(!t.entityState.isDeleted())return;n(c,t,o),c.method="DELETE"}r.push(c)}),e.contentKeys=i,e.tempKeys=a,{__batchRequests:[{__changeRequests:r}]}}function n(e,t,n){var r=t.extraMetadata,a=r.uri;k(a,n)&&(a=a.substring(n.length)),e.requestUri=a,r.etag&&(e.headers["If-Match"]=r.etag)}function r(e,t){var n=Error(),r=e.response;if(n.message=r.statusText,n.statusText=r.statusText,n.status=r.statusCode,t&&(n.url=t),n.body=r.body,r.body){var i;try{var o=JSON.parse(r.body);n.body=o;var s="";do i=o.error||o.innererror,i||(s+=a(o)),i=i||o.internalexception,o=i||o;while(i);s.length>0&&(n.message=s)}catch(u){}}return n}function a(e){var t=e.message;return null==t?"":("string"==typeof t?t:t.value)+"; "}var i,o=e.core,s=e.MetadataStore,u=e.JsonResultsAdapter,p=function(){this.name="OData"};p.prototype.initialize=function(){i=o.requireLib("OData","Needed to support remote OData services"),i.jsonHandler.recognizeDates=!0},p.prototype.executeQuery=function(e){var t=lt.defer();return i.read(e.url,function(e){return t.resolve({results:e.results,inlineCount:e.__count})},function(n){return t.reject(r(n,e.url))}),t.promise},p.prototype.fetchMetadata=function(e,t){var n=lt.defer(),a=t.serviceName,o=t.makeUrl("$metadata");return i.read(o,function(r){if(!r||!r.dataServices){var i=Error("Metadata query failed for: "+o);return n.reject(i)}var s=r.dataServices;if(!e.hasMetadataFor(a)){try{e.importMetadata(s)}catch(u){return n.reject(Error("Metadata query failed for "+o+"; Unable to process returned metadata: "+u.message))}e.addDataService(t)}return n.resolve(s)},function(e){var t=r(e,o);return t.message="Metadata query failed for: "+o+"; "+(t.message||""),n.reject(t)},i.metadataHandler),n.promise},p.prototype.saveChanges=function(e,n){var a=lt.defer(),o=e.entityManager.helper,s=e.dataService.makeUrl("$batch"),u=t(e,n),p=e.tempKeys,c=e.contentKeys;return i.request({headers:{DataServiceVersion:"2.0"},requestUri:s,method:"POST",data:u},function(e){var t=[],n=[],i={entities:t,keyMappings:n};return e.__batchResponses.forEach(function(e){e.__changeResponses.forEach(function(e){var i=e.response||e,u=i.statusCode;if(!u||u>=400)return a.reject(r(e,s));var y=e.headers["Content-ID"],l=e.data;if(l){var f=p[y];if(f){var h=f.entityType;if(h.autoGeneratedKeyType!==_t.None){var d=f.values[0],m=o.getEntityKeyFromRawEntity(l,h,!1),v={entityTypeName:h.name,tempValue:d,realValue:m.values[0]};n.push(v)}}t.push(l)}else{var g=c[y];t.push(g)}})}),a.resolve(i)},function(e){return a.reject(r(e,s))},i.batchHandler),a.promise},p.prototype.jsonResultsAdapter=new u({name:"OData_default",visitNode:function(e,t,n){var r={};if(null==e)return r;if(null!=e.__metadata){var a=s.normalizeTypeName(e.__metadata.type),i=a&&t.entityManager.metadataStore.getEntityType(a,!0);i&&i._mappedPropertiesCount===Object.keys(e).length-1&&(r.entityType=i,r.extra=e.__metadata)}var u=n.propertyName;return r.ignore=null!=e.__deferred||"__metadata"===u||"EntityKey"===u&&e.$type&&o.stringStartsWith(e.$type,"System.Data"),r}}),e.config.registerAdapter("dataService",p)}),function(e){B?e(B):"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?e(require("breeze")):"function"==typeof define&&define.amd&&!B&&define(["breeze"],e)}(function(e){e.core;var t=e.MetadataStore,n=e.JsonResultsAdapter,r=e.AbstractDataServiceAdapter,a=function(){this.name="webApi"};a.prototype=new r,a.prototype._prepareSaveBundle=function(e,t){var n=t.entityManager,r=n.metadataStore,a=n.helper;return e.entities=e.entities.map(function(e){var t=a.unwrapInstance(e),n=null;e.entityType.autoGeneratedKeyType!==_t.None&&(n={propertyName:e.entityType.keyProperties[0].nameOnServer,autoGeneratedKeyType:e.entityType.autoGeneratedKeyType.name});var i=a.unwrapOriginalValues(e,r);return t.entityAspect={entityTypeName:e.entityType.name,defaultResourceName:e.entityType.defaultResourceName,entityState:e.entityAspect.entityState.name,originalValuesMap:i,autoGeneratedKey:n},t}),e.saveOptions={tag:e.saveOptions.tag},e},a.prototype._prepareSaveResult=function(e,n){var r=n.KeyMappings.map(function(e){var n=t.normalizeTypeName(e.EntityTypeName);return{entityTypeName:n,tempValue:e.TempValue,realValue:e.RealValue}});return{entities:n.Entities,keyMappings:r,XHR:n.XHR}},a.prototype.jsonResultsAdapter=new n({name:"webApi_default",visitNode:function(e,n,r){if(null==e)return{};var a=t.normalizeTypeName(e.$type),i=a&&n.entityManager.metadataStore._getEntityType(a,!0),o=r.propertyName,s=o&&"$"===o.substr(0,1);return{entityType:i,nodeId:e.$id,nodeRefId:e.$ref,ignore:s}}}),e.config.registerAdapter("dataService",a)}),function(e){B?e(B):"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?e(require("breeze")):"function"==typeof define&&define.amd&&!B&&define(["breeze"],e)}(function(e){var t=e.core;e.ComplexAspect;var n,r,a,i,o=Object.prototype.hasOwnProperty,s=function(){this.name="backbone"};s.prototype.initialize=function(){n=t.requireLib("Backbone"),r=t.requireLib("_;underscore"),a=n.Model.prototype.set,i=n.Model.prototype.get},s.prototype.createCtor=function(t){var r={};t.dataProperties.forEach(function(e){r[e.name]=e.defaultValue});var a=n.Model.extend({defaults:r,initialize:function(){if(t.navigationProperties){var r=this;t.navigationProperties.forEach(function(t){if(!t.isScalar){var a=e.makeRelationArray([],r,t);n.Model.prototype.set.call(r,t.name,a)}})}}});return a},s.prototype.getTrackablePropertyNames=function(e){var t=[];for(var n in e.attributes)t.push(n);return t},s.prototype.initializeEntityPrototype=function(e){e.getProperty=function(e){return this.get(e)},e.setProperty=function(e,t){return this.set(e,t),this},e.set=function(e,t,n){var s=this.entityAspect||this.complexAspect;if(!s)return a.call(this,e,t,n);var u,p,c,y=this,l=this.entityType||this.complexType;if(r.isObject(e)||null==e){if(u=e,n=t,!this._validate(u,n))return!1;for(c in u)if(o.call(u,c)){if(p=l.getProperty(c),null==p)throw Error("Unknown property: "+e);var f=function(e){return function(t){return 0===arguments.length?i.call(y,e):a.call(y,e,t,n)}}(c);this._$interceptor(p,u[c],f)}}else{if(u={},u[e]=t,n||(n={}),!this._validate(u,n))return!1;if(p=l.getProperty(e),null==p)throw Error("Unknown property: "+e);c=e,this._$interceptor(p,t,function(e){return 0===arguments.length?i.call(y,c):a.call(y,c,e,n)})}return this}},s.prototype.startTracking=function(r){if(!(r instanceof n.Model))throw Error("This entity is not an Backbone.Model instance");var o=r.entityType||r.complexType,s=r.attributes;o.dataProperties.forEach(function(t){var n=t.name,i=s[n];t.isComplexProperty?i=t.isScalar?t.dataType._createInstanceCore(r,t):e.makeComplexArray([],r,t):t.isScalar?void 0===i&&(i=t.defaultValue):i=e.makePrimitiveArray([],r,t),a.call(r,n,i)}),o.navigationProperties&&o.navigationProperties.forEach(function(n){var o;if(n.name in s){var u=i.call(r,n.name);if(n.isScalar){if(u&&!u.entityType)throw o=t.formatString("The value of the '%1' property for entityType: '%2' must be either null or another entity",n.name,r.entityType.name),Error(o)}else if(u){if(!u.parentEntity)throw o=t.formatString("The value of the '%1' property for entityType: '%2' must be either null or a Breeze relation array",n.name,r.entityType.name),Error(o)}else u=e.makeRelationArray([],r,n),a.call(r,n.name,u)}else n.isScalar?a.call(r,n.name,null):(u=e.makeRelationArray([],r,n),a.call(r,n.name,u))})},e.config.registerAdapter("modelLibrary",s)}),function(e){B?e(B):"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?e(require("breeze")):"function"==typeof define&&define.amd&&!B&&define(["breeze"],e)}(function(e){function t(e){var t=e.entityType||e.complexType;t.getProperties().forEach(function(t){var n=t.name;e[n]||Object.defineProperty(e,n,r(t))})}function n(e){var t=Object.getPrototypeOf(e);e._backingStore||(e._backingStore={});var n=t.entityType||t.complexType;return n.getProperties().forEach(function(t){var n=t.name;if(e.hasOwnProperty(n)){var r=e[n];delete e[n],e[n]=r}}),e._backingStore}function r(e){var t=e.name,n=function(e){return function(){return 0==arguments.length?e[t]:(e[t]=arguments[0],void 0)}};return{get:function(){var e=this._backingStore;if(e||(this._pendingSets.process(),e=this._backingStore))return e[t]},set:function(r){var a=this._backingStore;if(!a)return this._pendingSets.schedule(this,t,r),void 0;var i=n(a);this._$interceptor?this._$interceptor(e,r,i):i(r)},enumerable:!0,configurable:!0}}var a=e.core,i=function(){this.name="backingStore"};i.prototype.initialize=function(){},i.prototype.getTrackablePropertyNames=function(e){var t=[];for(var n in e)if("entityType"!==n&&"_$typeName"!==n&&"_pendingSets"!==n&&"_backingStore"!==n){var r=e[n];a.isFunction(r)||t.push(n)}return t},i.prototype.initializeEntityPrototype=function(e){e.getProperty=function(e){return this[e]},e.setProperty=function(e,t){if(!this._backingStore.hasOwnProperty(e))throw Error("Unknown property name:"+e);return this[e]=t,this},e.initializeFrom=function(e){var t=this;this.entityType.unmappedProperties.forEach(function(n){var r=n.name;e[r]=t[r]}),this._backingStore||(this._backingStore={})},e._pendingSets=[],e._pendingSets.schedule=function(e,t,n){if(this.push({entity:e,propName:t,value:n}),!this.isPending){this.isPending=!0;var r=this;setTimeout(function(){r.process()})}},e._pendingSets.process=function(){0!==this.length&&(this.forEach(function(e){e.entity._backingStore||(e.entity._backingStore={}),e.entity._backingStore[e.propName]=e.value}),this.length=0,this.isPending=!1)},t(e)},i.prototype.startTracking=function(t,r){r._pendingSets.process();var a=n(t),i=t.entityType||t.complexType;i.getProperties().forEach(function(n){var r=n.name,i=t[r];if(n.isDataProperty)n.isComplexProperty?i=n.isScalar?n.dataType._createInstanceCore(t,n):e.makeComplexArray([],t,n):n.isScalar?void 0===i&&(i=n.defaultValue):i=e.makePrimitiveArray([],t,n),a[r]=i;else{if(!n.isNavigationProperty)throw Error("unknown property: "+r);if(void 0!==i)throw Error("Cannot assign a navigation property in an entity ctor.: "+n.Name);a[r]=n.isScalar?null:e.makeRelationArray([],t,n)}})},e.config.registerAdapter("modelLibrary",i)}),function(e){B?e(B):"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?e(require("breeze")):"function"==typeof define&&define.amd&&!B&&define(["breeze"],e)}(function(e){function t(e){e._koObj._suppressBreeze=!0}function n(e){var t=e.array._koObj;t._suppressBreeze?t._suppressBreeze=!1:t.valueHasMutated()}var r,a=e.core,i=function(){this.name="ko"};i.prototype.initialize=function(){r=a.requireLib("ko","The Knockout library"),r.extenders.intercept=function(e,t){var n,a=t.instance,i=t.property;return n=e.splice?r.computed({read:e}):r.computed({read:e,write:function(t){return a._$interceptor(i,t,e),a}})}},i.prototype.getTrackablePropertyNames=function(e){var t=[];for(var n in e)if("entityType"!==n&&"_$typeName"!==n){var i=e[n];r.isObservable(i)?t.push(n):a.isFunction(i)||t.push(n)}return t},i.prototype.initializeEntityPrototype=function(e){e.getProperty=function(e){return this[e]()},e.setProperty=function(e,t){return this[e](t),this}},i.prototype.startTracking=function(a){var i=a.entityType||a.complexType;i.getProperties().sort(function(e,t){var n=e.isUnmapped?1:0,r=t.isUnmapped?1:0;return n-r}).forEach(function(i){var o,s=i.name,u=a[s];if(r.isObservable(u)){if(i.isNavigationProperty)throw Error("Cannot assign a navigation property in an entity ctor.: "+s);o=u}else if(i.isDataProperty)i.isComplexProperty?u=i.isScalar?i.dataType._createInstanceCore(a,i):e.makeComplexArray([],a,i):i.isScalar?void 0===u&&(u=i.defaultValue):u=e.makePrimitiveArray([],a,i),o=r.observable(u);else{if(!i.isNavigationProperty)throw Error("unknown property: "+s);if(void 0!==u)throw Error("Cannot assign a navigation property in an entity ctor.: "+s);i.isScalar?o=r.observable(null):(u=e.makeRelationArray([],a,i),o=r.observableArray(u),u._koObj=o,o.subscribe(t,null,"beforeChange"),u.arrayChanged.subscribe(n),o.equalityComparer=function(){throw Error("Collection navigation properties may NOT be set.")})}if(i.isNavigationProperty&&!i.isScalar)a[s]=o;else{var p=o.extend({intercept:{instance:a,property:i}});a[s]=p}})},e.config.registerAdapter("modelLibrary",i)}),B.config.initializeAdapterInstances({dataService:"webApi",ajax:"jQuery"});var Bt=_("ko");return Bt?B.config.initializeAdapterInstance("modelLibrary","ko"):B.config.initializeAdapterInstance("modelLibrary","backingStore"),this.window&&(this.window.breeze=B),B});