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