From 74eed32e825b2b38706dd630849e8ec38505d045 Mon Sep 17 00:00:00 2001 From: JC Brand Date: Sat, 2 Jun 2018 17:18:42 +0200 Subject: [PATCH] Add shims to webpack config and fix bugs in templates --- dev.html | 47 +- dist/converse.js | 81029 ++++++++++++++++++++++++++++++- package-lock.json | 1150 +- package.json | 2 + src/converse-chatview.js | 3 +- src/converse-muc-views.js | 5 +- src/templates/alert_modal.html | 2 +- src/templates/emojis.html | 8 +- src/templates/field.html | 2 +- src/templates/message.html | 2 +- src/templates/occupant.html | 2 +- webpack.config.js | 23 +- 12 files changed, 81872 insertions(+), 403 deletions(-) diff --git a/dev.html b/dev.html index 328d73133..597d7df1d 100644 --- a/dev.html +++ b/dev.html @@ -11,34 +11,35 @@ - - + + + + + diff --git a/dist/converse.js b/dist/converse.js index e194a16b3..7c565e4ae 100644 --- a/dist/converse.js +++ b/dist/converse.js @@ -1,87 +1,56240 @@ -!function(e){var t={};function f(a){if(t[a])return t[a].exports;var n=t[a]={i:a,l:!1,exports:{}};return e[a].call(n.exports,n,n.exports,f),n.l=!0,n.exports}f.m=e,f.c=t,f.d=function(e,t,a){f.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:a})},f.r=function(e){Object.defineProperty(e,"__esModule",{value:!0})},f.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return f.d(t,"a",t),t},f.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},f.p="",f(f.s=292)}([function(e,t,f){(function(e){e.exports=function(){"use strict";var t,a;function n(){return t.apply(null,arguments)}function o(e){return e instanceof Array||"[object Array]"===Object.prototype.toString.call(e)}function r(e){return null!=e&&"[object Object]"===Object.prototype.toString.call(e)}function s(e){return void 0===e}function c(e){return"number"==typeof e||"[object Number]"===Object.prototype.toString.call(e)}function i(e){return e instanceof Date||"[object Date]"===Object.prototype.toString.call(e)}function u(e,t){var f,a=[];for(f=0;f>>0,a=0;a0)for(f=0;f=0;return(o?f?"+":"":"-")+Math.pow(10,Math.max(0,n)).toString().substr(1)+a}var z=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,F=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,B={},q={};function U(e,t,f,a){var n=a;"string"==typeof a&&(n=function(){return this[a]()}),e&&(q[e]=n),t&&(q[t[0]]=function(){return P(n.apply(this,arguments),t[1],t[2])}),f&&(q[f]=function(){return this.localeData().ordinal(n.apply(this,arguments),e)})}function W(e,t){return e.isValid()?(t=J(t,e.localeData()),B[t]=B[t]||function(e){var t,f,a,n=e.match(z);for(t=0,f=n.length;t=0&&F.test(e);)e=e.replace(F,a),F.lastIndex=0,f-=1;return e}var $=/\d/,V=/\d\d/,G=/\d{3}/,Q=/\d{4}/,X=/[+-]?\d{6}/,K=/\d\d?/,Z=/\d\d\d\d?/,ee=/\d\d\d\d\d\d?/,te=/\d{1,3}/,fe=/\d{1,4}/,ae=/[+-]?\d{1,6}/,ne=/\d+/,oe=/[+-]?\d+/,re=/Z|[+-]\d\d:?\d\d/gi,se=/Z|[+-]\d\d(?::?\d\d)?/gi,ce=/[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i,ie={};function ue(e,t,f){ie[e]=j(t)?t:function(e,a){return e&&f?f:t}}function _e(e,t){return _(ie,e)?ie[e](t._strict,t._locale):new RegExp(de(e.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(e,t,f,a,n){return t||f||a||n})))}function de(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}var le={};function he(e,t){var f,a=t;for("string"==typeof e&&(e=[e]),c(t)&&(a=function(e,f){f[t]=M(e)}),f=0;f68?1900:2e3)};var De,Ye=je("FullYear",!0);function je(e,t){return function(f){return null!=f?(Ce(this,e,f),n.updateOffset(this,t),this):Ae(this,e)}}function Ae(e,t){return e.isValid()?e._d["get"+(e._isUTC?"UTC":"")+t]():NaN}function Ce(e,t,f){e.isValid()&&!isNaN(f)&&("FullYear"===t&&Te(e.year())&&1===e.month()&&29===e.date()?e._d["set"+(e._isUTC?"UTC":"")+t](f,e.month(),Ee(f,e.month())):e._d["set"+(e._isUTC?"UTC":"")+t](f))}function Ee(e,t){if(isNaN(e)||isNaN(t))return NaN;var f,a=(t%(f=12)+f)%f;return e+=(t-a)/12,1===a?Te(e)?29:28:31-a%7%2}De=Array.prototype.indexOf?Array.prototype.indexOf:function(e){var t;for(t=0;t=0&&isFinite(t.getUTCFullYear())&&t.setUTCFullYear(e),t}function qe(e,t,f){var a=7+t-f,n=(7+Be(e,0,a).getUTCDay()-t)%7;return-n+a-1}function Ue(e,t,f,a,n){var o,r,s=(7+f-a)%7,c=qe(e,a,n),i=1+7*(t-1)+s+c;return i<=0?r=Se(o=e-1)+i:i>Se(e)?(o=e+1,r=i-Se(e)):(o=e,r=i),{year:o,dayOfYear:r}}function We(e,t,f){var a,n,o=qe(e.year(),t,f),r=Math.floor((e.dayOfYear()-o-1)/7)+1;return r<1?(n=e.year()-1,a=r+Je(n,t,f)):r>Je(e.year(),t,f)?(a=r-Je(e.year(),t,f),n=e.year()+1):(n=e.year(),a=r),{week:a,year:n}}function Je(e,t,f){var a=qe(e,t,f),n=qe(e+1,t,f);return(Se(e)-a+n)/7}U("w",["ww",2],"wo","week"),U("W",["WW",2],"Wo","isoWeek"),H("week","w"),H("isoWeek","W"),I("week",5),I("isoWeek",5),ue("w",K),ue("ww",K,V),ue("W",K),ue("WW",K,V),me(["w","ww","W","WW"],function(e,t,f,a){t[a.substr(0,1)]=M(e)}),U("d",0,"do","day"),U("dd",0,0,function(e){return this.localeData().weekdaysMin(this,e)}),U("ddd",0,0,function(e){return this.localeData().weekdaysShort(this,e)}),U("dddd",0,0,function(e){return this.localeData().weekdays(this,e)}),U("e",0,0,"weekday"),U("E",0,0,"isoWeekday"),H("day","d"),H("weekday","e"),H("isoWeekday","E"),I("day",11),I("weekday",11),I("isoWeekday",11),ue("d",K),ue("e",K),ue("E",K),ue("dd",function(e,t){return t.weekdaysMinRegex(e)}),ue("ddd",function(e,t){return t.weekdaysShortRegex(e)}),ue("dddd",function(e,t){return t.weekdaysRegex(e)}),me(["dd","ddd","dddd"],function(e,t,f,a){var n=f._locale.weekdaysParse(e,a,f._strict);null!=n?t.d=n:h(f).invalidWeekday=e}),me(["d","e","E"],function(e,t,f,a){t[a]=M(e)});var $e="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),Ve="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),Ge="Su_Mo_Tu_We_Th_Fr_Sa".split("_"),Qe=ce,Xe=ce,Ke=ce;function Ze(){function e(e,t){return t.length-e.length}var t,f,a,n,o,r=[],s=[],c=[],i=[];for(t=0;t<7;t++)f=l([2e3,1]).day(t),a=this.weekdaysMin(f,""),n=this.weekdaysShort(f,""),o=this.weekdays(f,""),r.push(a),s.push(n),c.push(o),i.push(a),i.push(n),i.push(o);for(r.sort(e),s.sort(e),c.sort(e),i.sort(e),t=0;t<7;t++)s[t]=de(s[t]),c[t]=de(c[t]),i[t]=de(i[t]);this._weekdaysRegex=new RegExp("^("+i.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+c.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+s.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+r.join("|")+")","i")}function et(){return this.hours()%12||12}function tt(e,t){U(e,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),t)})}function ft(e,t){return t._meridiemParse}U("H",["HH",2],0,"hour"),U("h",["hh",2],0,et),U("k",["kk",2],0,function(){return this.hours()||24}),U("hmm",0,0,function(){return""+et.apply(this)+P(this.minutes(),2)}),U("hmmss",0,0,function(){return""+et.apply(this)+P(this.minutes(),2)+P(this.seconds(),2)}),U("Hmm",0,0,function(){return""+this.hours()+P(this.minutes(),2)}),U("Hmmss",0,0,function(){return""+this.hours()+P(this.minutes(),2)+P(this.seconds(),2)}),tt("a",!0),tt("A",!1),H("hour","h"),I("hour",13),ue("a",ft),ue("A",ft),ue("H",K),ue("h",K),ue("k",K),ue("HH",K,V),ue("hh",K,V),ue("kk",K,V),ue("hmm",Z),ue("hmmss",ee),ue("Hmm",Z),ue("Hmmss",ee),he(["H","HH"],ve),he(["k","kk"],function(e,t,f){var a=M(e);t[ve]=24===a?0:a}),he(["a","A"],function(e,t,f){f._isPm=f._locale.isPM(e),f._meridiem=e}),he(["h","hh"],function(e,t,f){t[ve]=M(e),h(f).bigHour=!0}),he("hmm",function(e,t,f){var a=e.length-2;t[ve]=M(e.substr(0,a)),t[we]=M(e.substr(a)),h(f).bigHour=!0}),he("hmmss",function(e,t,f){var a=e.length-4,n=e.length-2;t[ve]=M(e.substr(0,a)),t[we]=M(e.substr(a,2)),t[ke]=M(e.substr(n)),h(f).bigHour=!0}),he("Hmm",function(e,t,f){var a=e.length-2;t[ve]=M(e.substr(0,a)),t[we]=M(e.substr(a))}),he("Hmmss",function(e,t,f){var a=e.length-4,n=e.length-2;t[ve]=M(e.substr(0,a)),t[we]=M(e.substr(a,2)),t[ke]=M(e.substr(n))});var at,nt=je("Hours",!0),ot={calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},longDateFormat:{LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},invalidDate:"Invalid date",ordinal:"%d",dayOfMonthOrdinalParse:/\d{1,2}/,relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",ss:"%d seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},months:Ne,monthsShort:Oe,week:{dow:0,doy:6},weekdays:$e,weekdaysMin:Ge,weekdaysShort:Ve,meridiemParse:/[ap]\.?m?\.?/i},rt={},st={};function ct(e){return e?e.toLowerCase().replace("_","-"):e}function it(t){var a=null;if(!rt[t]&&void 0!==e&&e&&e.exports)try{a=at._abbr,f(286)("./"+t),ut(a)}catch(e){}return rt[t]}function ut(e,t){var f;return e&&(f=s(t)?dt(e):_t(e,t))&&(at=f),at._abbr}function _t(e,t){if(null!==t){var f=ot;if(t.abbr=e,null!=rt[e])Y("defineLocaleOverride","use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."),f=rt[e]._config;else if(null!=t.parentLocale){if(null==rt[t.parentLocale])return st[t.parentLocale]||(st[t.parentLocale]=[]),st[t.parentLocale].push({name:e,config:t}),null;f=rt[t.parentLocale]._config}return rt[e]=new C(A(f,t)),st[e]&&st[e].forEach(function(e){_t(e.name,e.config)}),ut(e),rt[e]}return delete rt[e],null}function dt(e){var t;if(e&&e._locale&&e._locale._abbr&&(e=e._locale._abbr),!e)return at;if(!o(e)){if(t=it(e))return t;e=[e]}return function(e){for(var t,f,a,n,o=0;o0;){if(a=it(n.slice(0,t).join("-")))return a;if(f&&f.length>=t&&L(n,f,!0)>=t-1)break;t--}o++}return null}(e)}function lt(e){var t,f=e._a;return f&&-2===h(e).overflow&&(t=f[be]<0||f[be]>11?be:f[ye]<1||f[ye]>Ee(f[pe],f[be])?ye:f[ve]<0||f[ve]>24||24===f[ve]&&(0!==f[we]||0!==f[ke]||0!==f[Me])?ve:f[we]<0||f[we]>59?we:f[ke]<0||f[ke]>59?ke:f[Me]<0||f[Me]>999?Me:-1,h(e)._overflowDayOfYear&&(tye)&&(t=ye),h(e)._overflowWeeks&&-1===t&&(t=Le),h(e)._overflowWeekday&&-1===t&&(t=xe),h(e).overflow=t),e}function ht(e,t,f){return null!=e?e:null!=t?t:f}function mt(e){var t,f,a,o,r,s=[];if(!e._d){for(a=function(e){var t=new Date(n.now());return e._useUTC?[t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()]:[t.getFullYear(),t.getMonth(),t.getDate()]}(e),e._w&&null==e._a[ye]&&null==e._a[be]&&function(e){var t,f,a,n,o,r,s,c;if(null!=(t=e._w).GG||null!=t.W||null!=t.E)o=1,r=4,f=ht(t.GG,e._a[pe],We(jt(),1,4).year),a=ht(t.W,1),((n=ht(t.E,1))<1||n>7)&&(c=!0);else{o=e._locale._week.dow,r=e._locale._week.doy;var i=We(jt(),o,r);f=ht(t.gg,e._a[pe],i.year),a=ht(t.w,i.week),null!=t.d?((n=t.d)<0||n>6)&&(c=!0):null!=t.e?(n=t.e+o,(t.e<0||t.e>6)&&(c=!0)):n=o}a<1||a>Je(f,o,r)?h(e)._overflowWeeks=!0:null!=c?h(e)._overflowWeekday=!0:(s=Ue(f,a,n,o,r),e._a[pe]=s.year,e._dayOfYear=s.dayOfYear)}(e),null!=e._dayOfYear&&(r=ht(e._a[pe],a[pe]),(e._dayOfYear>Se(r)||0===e._dayOfYear)&&(h(e)._overflowDayOfYear=!0),f=Be(r,0,e._dayOfYear),e._a[be]=f.getUTCMonth(),e._a[ye]=f.getUTCDate()),t=0;t<3&&null==e._a[t];++t)e._a[t]=s[t]=a[t];for(;t<7;t++)e._a[t]=s[t]=null==e._a[t]?2===t?1:0:e._a[t];24===e._a[ve]&&0===e._a[we]&&0===e._a[ke]&&0===e._a[Me]&&(e._nextDay=!0,e._a[ve]=0),e._d=(e._useUTC?Be:function(e,t,f,a,n,o,r){var s=new Date(e,t,f,a,n,o,r);return e<100&&e>=0&&isFinite(s.getFullYear())&&s.setFullYear(e),s}).apply(null,s),o=e._useUTC?e._d.getUTCDay():e._d.getDay(),null!=e._tzm&&e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),e._nextDay&&(e._a[ve]=24),e._w&&void 0!==e._w.d&&e._w.d!==o&&(h(e).weekdayMismatch=!0)}}var gt=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,pt=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,bt=/Z|[+-]\d\d(?::?\d\d)?/,yt=[["YYYYYY-MM-DD",/[+-]\d{6}-\d\d-\d\d/],["YYYY-MM-DD",/\d{4}-\d\d-\d\d/],["GGGG-[W]WW-E",/\d{4}-W\d\d-\d/],["GGGG-[W]WW",/\d{4}-W\d\d/,!1],["YYYY-DDD",/\d{4}-\d{3}/],["YYYY-MM",/\d{4}-\d\d/,!1],["YYYYYYMMDD",/[+-]\d{10}/],["YYYYMMDD",/\d{8}/],["GGGG[W]WWE",/\d{4}W\d{3}/],["GGGG[W]WW",/\d{4}W\d{2}/,!1],["YYYYDDD",/\d{7}/]],vt=[["HH:mm:ss.SSSS",/\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss,SSSS",/\d\d:\d\d:\d\d,\d+/],["HH:mm:ss",/\d\d:\d\d:\d\d/],["HH:mm",/\d\d:\d\d/],["HHmmss.SSSS",/\d\d\d\d\d\d\.\d+/],["HHmmss,SSSS",/\d\d\d\d\d\d,\d+/],["HHmmss",/\d\d\d\d\d\d/],["HHmm",/\d\d\d\d/],["HH",/\d\d/]],wt=/^\/?Date\((\-?\d+)/i;function kt(e){var t,f,a,n,o,r,s=e._i,c=gt.exec(s)||pt.exec(s);if(c){for(h(e).iso=!0,t=0,f=yt.length;t0&&h(e).unusedInput.push(r),s=s.slice(s.indexOf(f)+f.length),i+=f.length),q[o]?(f?h(e).empty=!1:h(e).unusedTokens.push(o),ge(o,f,e)):e._strict&&!f&&h(e).unusedTokens.push(o);h(e).charsLeftOver=c-i,s.length>0&&h(e).unusedInput.push(s),e._a[ve]<=12&&!0===h(e).bigHour&&e._a[ve]>0&&(h(e).bigHour=void 0),h(e).parsedDateParts=e._a.slice(0),h(e).meridiem=e._meridiem,e._a[ve]=(u=e._locale,_=e._a[ve],null==(d=e._meridiem)?_:null!=u.meridiemHour?u.meridiemHour(_,d):null!=u.isPM?((l=u.isPM(d))&&_<12&&(_+=12),l||12!==_||(_=0),_):_),mt(e),lt(e)}else St(e);else kt(e);var u,_,d,l}function Dt(e){var t=e._i,f=e._f;return e._locale=e._locale||dt(e._l),null===t||void 0===f&&""===t?g({nullInput:!0}):("string"==typeof t&&(e._i=t=e._locale.preparse(t)),w(t)?new v(lt(t)):(i(t)?e._d=t:o(f)?function(e){var t,f,a,n,o;if(0===e._f.length)return h(e).invalidFormat=!0,void(e._d=new Date(NaN));for(n=0;nthis?this:e:g()});function Et(e,t){var f,a;if(1===t.length&&o(t[0])&&(t=t[0]),!t.length)return jt();for(f=t[0],a=1;ao&&(t=o),function(e,t,f,a,n){var o=Ue(e,t,f,a,n),r=Be(o.year,0,o.dayOfYear);return this.year(r.getUTCFullYear()),this.month(r.getUTCMonth()),this.date(r.getUTCDate()),this}.call(this,e,t,f,a,n))}U(0,["gg",2],0,function(){return this.weekYear()%100}),U(0,["GG",2],0,function(){return this.isoWeekYear()%100}),af("gggg","weekYear"),af("ggggg","weekYear"),af("GGGG","isoWeekYear"),af("GGGGG","isoWeekYear"),H("weekYear","gg"),H("isoWeekYear","GG"),I("weekYear",1),I("isoWeekYear",1),ue("G",oe),ue("g",oe),ue("GG",K,V),ue("gg",K,V),ue("GGGG",fe,Q),ue("gggg",fe,Q),ue("GGGGG",ae,X),ue("ggggg",ae,X),me(["gggg","ggggg","GGGG","GGGGG"],function(e,t,f,a){t[a.substr(0,2)]=M(e)}),me(["gg","GG"],function(e,t,f,a){t[a]=n.parseTwoDigitYear(e)}),U("Q",0,"Qo","quarter"),H("quarter","Q"),I("quarter",7),ue("Q",$),he("Q",function(e,t){t[be]=3*(M(e)-1)}),U("D",["DD",2],"Do","date"),H("date","D"),I("date",9),ue("D",K),ue("DD",K,V),ue("Do",function(e,t){return e?t._dayOfMonthOrdinalParse||t._ordinalParse:t._dayOfMonthOrdinalParseLenient}),he(["D","DD"],ye),he("Do",function(e,t){t[ye]=M(e.match(K)[0])});var of=je("Date",!0);U("DDD",["DDDD",3],"DDDo","dayOfYear"),H("dayOfYear","DDD"),I("dayOfYear",4),ue("DDD",te),ue("DDDD",G),he(["DDD","DDDD"],function(e,t,f){f._dayOfYear=M(e)}),U("m",["mm",2],0,"minute"),H("minute","m"),I("minute",14),ue("m",K),ue("mm",K,V),he(["m","mm"],we);var rf=je("Minutes",!1);U("s",["ss",2],0,"second"),H("second","s"),I("second",15),ue("s",K),ue("ss",K,V),he(["s","ss"],ke);var sf,cf=je("Seconds",!1);for(U("S",0,0,function(){return~~(this.millisecond()/100)}),U(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),U(0,["SSS",3],0,"millisecond"),U(0,["SSSS",4],0,function(){return 10*this.millisecond()}),U(0,["SSSSS",5],0,function(){return 100*this.millisecond()}),U(0,["SSSSSS",6],0,function(){return 1e3*this.millisecond()}),U(0,["SSSSSSS",7],0,function(){return 1e4*this.millisecond()}),U(0,["SSSSSSSS",8],0,function(){return 1e5*this.millisecond()}),U(0,["SSSSSSSSS",9],0,function(){return 1e6*this.millisecond()}),H("millisecond","ms"),I("millisecond",16),ue("S",te,$),ue("SS",te,V),ue("SSS",te,G),sf="SSSS";sf.length<=9;sf+="S")ue(sf,ne);function uf(e,t){t[Me]=M(1e3*("0."+e))}for(sf="S";sf.length<=9;sf+="S")he(sf,uf);var _f=je("Milliseconds",!1);U("z",0,0,"zoneAbbr"),U("zz",0,0,"zoneName");var df=v.prototype;function lf(e){return e}df.add=Xt,df.calendar=function(e,t){var f=e||jt(),a=Ft(f,this).startOf("day"),o=n.calendarFormat(this,a)||"sameElse",r=t&&(j(t[o])?t[o].call(this,f):t[o]);return this.format(r||this.localeData().calendar(o,this,jt(f)))},df.clone=function(){return new v(this)},df.diff=function(e,t,f){var a,n,o;if(!this.isValid())return NaN;if(!(a=Ft(e,this)).isValid())return NaN;switch(n=6e4*(a.utcOffset()-this.utcOffset()),t=N(t)){case"year":o=Zt(this,a)/12;break;case"month":o=Zt(this,a);break;case"quarter":o=Zt(this,a)/3;break;case"second":o=(this-a)/1e3;break;case"minute":o=(this-a)/6e4;break;case"hour":o=(this-a)/36e5;break;case"day":o=(this-a-n)/864e5;break;case"week":o=(this-a-n)/6048e5;break;default:o=this-a}return f?o:k(o)},df.endOf=function(e){return void 0===(e=N(e))||"millisecond"===e?this:("date"===e&&(e="day"),this.startOf(e).add(1,"isoWeek"===e?"week":e).subtract(1,"ms"))},df.format=function(e){e||(e=this.isUtc()?n.defaultFormatUtc:n.defaultFormat);var t=W(this,e);return this.localeData().postformat(t)},df.from=function(e,t){return this.isValid()&&(w(e)&&e.isValid()||jt(e).isValid())?Jt({to:this,from:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},df.fromNow=function(e){return this.from(jt(),e)},df.to=function(e,t){return this.isValid()&&(w(e)&&e.isValid()||jt(e).isValid())?Jt({from:this,to:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},df.toNow=function(e){return this.to(jt(),e)},df.get=function(e){return j(this[e=N(e)])?this[e]():this},df.invalidAt=function(){return h(this).overflow},df.isAfter=function(e,t){var f=w(e)?e:jt(e);return!(!this.isValid()||!f.isValid())&&("millisecond"===(t=N(s(t)?"millisecond":t))?this.valueOf()>f.valueOf():f.valueOf()9999?W(e,"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]"):j(Date.prototype.toISOString)?this.toDate().toISOString():W(e,"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]")},df.inspect=function(){if(!this.isValid())return"moment.invalid(/* "+this._i+" */)";var e="moment",t="";this.isLocal()||(e=0===this.utcOffset()?"moment.utc":"moment.parseZone",t="Z");var f="["+e+'("]',a=0<=this.year()&&this.year()<=9999?"YYYY":"YYYYYY",n=t+'[")]';return this.format(f+a+"-MM-DD[T]HH:mm:ss.SSS"+n)},df.toJSON=function(){return this.isValid()?this.toISOString():null},df.toString=function(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")},df.unix=function(){return Math.floor(this.valueOf()/1e3)},df.valueOf=function(){return this._d.valueOf()-6e4*(this._offset||0)},df.creationData=function(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}},df.year=Ye,df.isLeapYear=function(){return Te(this.year())},df.weekYear=function(e){return nf.call(this,e,this.week(),this.weekday(),this.localeData()._week.dow,this.localeData()._week.doy)},df.isoWeekYear=function(e){return nf.call(this,e,this.isoWeek(),this.isoWeekday(),1,4)},df.quarter=df.quarters=function(e){return null==e?Math.ceil((this.month()+1)/3):this.month(3*(e-1)+this.month()%3)},df.month=Ie,df.daysInMonth=function(){return Ee(this.year(),this.month())},df.week=df.weeks=function(e){var t=this.localeData().week(this);return null==e?t:this.add(7*(e-t),"d")},df.isoWeek=df.isoWeeks=function(e){var t=We(this,1,4).week;return null==e?t:this.add(7*(e-t),"d")},df.weeksInYear=function(){var e=this.localeData()._week;return Je(this.year(),e.dow,e.doy)},df.isoWeeksInYear=function(){return Je(this.year(),1,4)},df.date=of,df.day=df.days=function(e){if(!this.isValid())return null!=e?this:NaN;var t=this._isUTC?this._d.getUTCDay():this._d.getDay();return null!=e?(e=function(e,t){return"string"!=typeof e?e:isNaN(e)?"number"==typeof(e=t.weekdaysParse(e))?e:null:parseInt(e,10)}(e,this.localeData()),this.add(e-t,"d")):t},df.weekday=function(e){if(!this.isValid())return null!=e?this:NaN;var t=(this.day()+7-this.localeData()._week.dow)%7;return null==e?t:this.add(e-t,"d")},df.isoWeekday=function(e){if(!this.isValid())return null!=e?this:NaN;if(null!=e){var t=function(e,t){return"string"==typeof e?t.weekdaysParse(e)%7||7:isNaN(e)?null:e}(e,this.localeData());return this.day(this.day()%7?t:t-7)}return this.day()||7},df.dayOfYear=function(e){var t=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==e?t:this.add(e-t,"d")},df.hour=df.hours=nt,df.minute=df.minutes=rf,df.second=df.seconds=cf,df.millisecond=df.milliseconds=_f,df.utcOffset=function(e,t,f){var a,o=this._offset||0;if(!this.isValid())return null!=e?this:NaN;if(null!=e){if("string"==typeof e){if(null===(e=zt(se,e)))return this}else Math.abs(e)<16&&!f&&(e*=60);return!this._isUTC&&t&&(a=Bt(this)),this._offset=e,this._isUTC=!0,null!=a&&this.add(a,"m"),o!==e&&(!t||this._changeInProgress?Qt(this,Jt(e-o,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,n.updateOffset(this,!0),this._changeInProgress=null)),this}return this._isUTC?o:Bt(this)},df.utc=function(e){return this.utcOffset(0,e)},df.local=function(e){return this._isUTC&&(this.utcOffset(0,e),this._isUTC=!1,e&&this.subtract(Bt(this),"m")),this},df.parseZone=function(){if(null!=this._tzm)this.utcOffset(this._tzm,!1,!0);else if("string"==typeof this._i){var e=zt(re,this._i);null!=e?this.utcOffset(e):this.utcOffset(0,!0)}return this},df.hasAlignedHourOffset=function(e){return!!this.isValid()&&(e=e?jt(e).utcOffset():0,(this.utcOffset()-e)%60==0)},df.isDST=function(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()},df.isLocal=function(){return!!this.isValid()&&!this._isUTC},df.isUtcOffset=function(){return!!this.isValid()&&this._isUTC},df.isUtc=qt,df.isUTC=qt,df.zoneAbbr=function(){return this._isUTC?"UTC":""},df.zoneName=function(){return this._isUTC?"Coordinated Universal Time":""},df.dates=S("dates accessor is deprecated. Use date instead.",of),df.months=S("months accessor is deprecated. Use month instead",Ie),df.years=S("years accessor is deprecated. Use year instead",Ye),df.zone=S("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",function(e,t){return null!=e?("string"!=typeof e&&(e=-e),this.utcOffset(e,t),this):-this.utcOffset()}),df.isDSTShifted=S("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",function(){if(!s(this._isDSTShifted))return this._isDSTShifted;var e={};if(b(e,this),(e=Dt(e))._a){var t=e._isUTC?l(e._a):jt(e._a);this._isDSTShifted=this.isValid()&&L(e._a,t.toArray())>0}else this._isDSTShifted=!1;return this._isDSTShifted});var hf=C.prototype;function mf(e,t,f,a){var n=dt(),o=l().set(a,t);return n[f](o,e)}function gf(e,t,f){if(c(e)&&(t=e,e=void 0),e=e||"",null!=t)return mf(e,t,f,"month");var a,n=[];for(a=0;a<12;a++)n[a]=mf(e,a,f,"month");return n}function pf(e,t,f,a){"boolean"==typeof e?(c(t)&&(f=t,t=void 0),t=t||""):(f=t=e,e=!1,c(t)&&(f=t,t=void 0),t=t||"");var n,o=dt(),r=e?o._week.dow:0;if(null!=f)return mf(t,(f+r)%7,a,"day");var s=[];for(n=0;n<7;n++)s[n]=mf(t,(n+r)%7,a,"day");return s}hf.calendar=function(e,t,f){var a=this._calendar[e]||this._calendar.sameElse;return j(a)?a.call(t,f):a},hf.longDateFormat=function(e){var t=this._longDateFormat[e],f=this._longDateFormat[e.toUpperCase()];return t||!f?t:(this._longDateFormat[e]=f.replace(/MMMM|MM|DD|dddd/g,function(e){return e.slice(1)}),this._longDateFormat[e])},hf.invalidDate=function(){return this._invalidDate},hf.ordinal=function(e){return this._ordinal.replace("%d",e)},hf.preparse=lf,hf.postformat=lf,hf.relativeTime=function(e,t,f,a){var n=this._relativeTime[f];return j(n)?n(e,t,f,a):n.replace(/%d/i,e)},hf.pastFuture=function(e,t){var f=this._relativeTime[e>0?"future":"past"];return j(f)?f(t):f.replace(/%s/i,t)},hf.set=function(e){var t,f;for(f in e)j(t=e[f])?this[f]=t:this["_"+f]=t;this._config=e,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)},hf.months=function(e,t){return e?o(this._months)?this._months[e.month()]:this._months[(this._months.isFormat||He).test(t)?"format":"standalone"][e.month()]:o(this._months)?this._months:this._months.standalone},hf.monthsShort=function(e,t){return e?o(this._monthsShort)?this._monthsShort[e.month()]:this._monthsShort[He.test(t)?"format":"standalone"][e.month()]:o(this._monthsShort)?this._monthsShort:this._monthsShort.standalone},hf.monthsParse=function(e,t,f){var a,n,o;if(this._monthsParseExact)return function(e,t,f){var a,n,o,r=e.toLocaleLowerCase();if(!this._monthsParse)for(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[],a=0;a<12;++a)o=l([2e3,a]),this._shortMonthsParse[a]=this.monthsShort(o,"").toLocaleLowerCase(),this._longMonthsParse[a]=this.months(o,"").toLocaleLowerCase();return f?"MMM"===t?-1!==(n=De.call(this._shortMonthsParse,r))?n:null:-1!==(n=De.call(this._longMonthsParse,r))?n:null:"MMM"===t?-1!==(n=De.call(this._shortMonthsParse,r))?n:-1!==(n=De.call(this._longMonthsParse,r))?n:null:-1!==(n=De.call(this._longMonthsParse,r))?n:-1!==(n=De.call(this._shortMonthsParse,r))?n:null}.call(this,e,t,f);for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),a=0;a<12;a++){if(n=l([2e3,a]),f&&!this._longMonthsParse[a]&&(this._longMonthsParse[a]=new RegExp("^"+this.months(n,"").replace(".","")+"$","i"),this._shortMonthsParse[a]=new RegExp("^"+this.monthsShort(n,"").replace(".","")+"$","i")),f||this._monthsParse[a]||(o="^"+this.months(n,"")+"|^"+this.monthsShort(n,""),this._monthsParse[a]=new RegExp(o.replace(".",""),"i")),f&&"MMMM"===t&&this._longMonthsParse[a].test(e))return a;if(f&&"MMM"===t&&this._shortMonthsParse[a].test(e))return a;if(!f&&this._monthsParse[a].test(e))return a}},hf.monthsRegex=function(e){return this._monthsParseExact?(_(this,"_monthsRegex")||Fe.call(this),e?this._monthsStrictRegex:this._monthsRegex):(_(this,"_monthsRegex")||(this._monthsRegex=ze),this._monthsStrictRegex&&e?this._monthsStrictRegex:this._monthsRegex)},hf.monthsShortRegex=function(e){return this._monthsParseExact?(_(this,"_monthsRegex")||Fe.call(this),e?this._monthsShortStrictRegex:this._monthsShortRegex):(_(this,"_monthsShortRegex")||(this._monthsShortRegex=Pe),this._monthsShortStrictRegex&&e?this._monthsShortStrictRegex:this._monthsShortRegex)},hf.week=function(e){return We(e,this._week.dow,this._week.doy).week},hf.firstDayOfYear=function(){return this._week.doy},hf.firstDayOfWeek=function(){return this._week.dow},hf.weekdays=function(e,t){return e?o(this._weekdays)?this._weekdays[e.day()]:this._weekdays[this._weekdays.isFormat.test(t)?"format":"standalone"][e.day()]:o(this._weekdays)?this._weekdays:this._weekdays.standalone},hf.weekdaysMin=function(e){return e?this._weekdaysMin[e.day()]:this._weekdaysMin},hf.weekdaysShort=function(e){return e?this._weekdaysShort[e.day()]:this._weekdaysShort},hf.weekdaysParse=function(e,t,f){var a,n,o;if(this._weekdaysParseExact)return function(e,t,f){var a,n,o,r=e.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],a=0;a<7;++a)o=l([2e3,1]).day(a),this._minWeekdaysParse[a]=this.weekdaysMin(o,"").toLocaleLowerCase(),this._shortWeekdaysParse[a]=this.weekdaysShort(o,"").toLocaleLowerCase(),this._weekdaysParse[a]=this.weekdays(o,"").toLocaleLowerCase();return f?"dddd"===t?-1!==(n=De.call(this._weekdaysParse,r))?n:null:"ddd"===t?-1!==(n=De.call(this._shortWeekdaysParse,r))?n:null:-1!==(n=De.call(this._minWeekdaysParse,r))?n:null:"dddd"===t?-1!==(n=De.call(this._weekdaysParse,r))?n:-1!==(n=De.call(this._shortWeekdaysParse,r))?n:-1!==(n=De.call(this._minWeekdaysParse,r))?n:null:"ddd"===t?-1!==(n=De.call(this._shortWeekdaysParse,r))?n:-1!==(n=De.call(this._weekdaysParse,r))?n:-1!==(n=De.call(this._minWeekdaysParse,r))?n:null:-1!==(n=De.call(this._minWeekdaysParse,r))?n:-1!==(n=De.call(this._weekdaysParse,r))?n:-1!==(n=De.call(this._shortWeekdaysParse,r))?n:null}.call(this,e,t,f);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),a=0;a<7;a++){if(n=l([2e3,1]).day(a),f&&!this._fullWeekdaysParse[a]&&(this._fullWeekdaysParse[a]=new RegExp("^"+this.weekdays(n,"").replace(".",".?")+"$","i"),this._shortWeekdaysParse[a]=new RegExp("^"+this.weekdaysShort(n,"").replace(".",".?")+"$","i"),this._minWeekdaysParse[a]=new RegExp("^"+this.weekdaysMin(n,"").replace(".",".?")+"$","i")),this._weekdaysParse[a]||(o="^"+this.weekdays(n,"")+"|^"+this.weekdaysShort(n,"")+"|^"+this.weekdaysMin(n,""),this._weekdaysParse[a]=new RegExp(o.replace(".",""),"i")),f&&"dddd"===t&&this._fullWeekdaysParse[a].test(e))return a;if(f&&"ddd"===t&&this._shortWeekdaysParse[a].test(e))return a;if(f&&"dd"===t&&this._minWeekdaysParse[a].test(e))return a;if(!f&&this._weekdaysParse[a].test(e))return a}},hf.weekdaysRegex=function(e){return this._weekdaysParseExact?(_(this,"_weekdaysRegex")||Ze.call(this),e?this._weekdaysStrictRegex:this._weekdaysRegex):(_(this,"_weekdaysRegex")||(this._weekdaysRegex=Qe),this._weekdaysStrictRegex&&e?this._weekdaysStrictRegex:this._weekdaysRegex)},hf.weekdaysShortRegex=function(e){return this._weekdaysParseExact?(_(this,"_weekdaysRegex")||Ze.call(this),e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(_(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=Xe),this._weekdaysShortStrictRegex&&e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)},hf.weekdaysMinRegex=function(e){return this._weekdaysParseExact?(_(this,"_weekdaysRegex")||Ze.call(this),e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(_(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=Ke),this._weekdaysMinStrictRegex&&e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)},hf.isPM=function(e){return"p"===(e+"").toLowerCase().charAt(0)},hf.meridiem=function(e,t,f){return e>11?f?"pm":"PM":f?"am":"AM"},ut("en",{dayOfMonthOrdinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(e){var t=e%10,f=1===M(e%100/10)?"th":1===t?"st":2===t?"nd":3===t?"rd":"th";return e+f}}),n.lang=S("moment.lang is deprecated. Use moment.locale instead.",ut),n.langData=S("moment.langData is deprecated. Use moment.localeData instead.",dt);var bf=Math.abs;function yf(e,t,f,a){var n=Jt(t,f);return e._milliseconds+=a*n._milliseconds,e._days+=a*n._days,e._months+=a*n._months,e._bubble()}function vf(e){return e<0?Math.floor(e):Math.ceil(e)}function wf(e){return 4800*e/146097}function kf(e){return 146097*e/4800}function Mf(e){return function(){return this.as(e)}}var Lf=Mf("ms"),xf=Mf("s"),Sf=Mf("m"),Tf=Mf("h"),Df=Mf("d"),Yf=Mf("w"),jf=Mf("M"),Af=Mf("y");function Cf(e){return function(){return this.isValid()?this._data[e]:NaN}}var Ef=Cf("milliseconds"),Hf=Cf("seconds"),Nf=Cf("minutes"),Of=Cf("hours"),Rf=Cf("days"),If=Cf("months"),Pf=Cf("years"),zf=Math.round,Ff={ss:44,s:45,m:45,h:22,d:26,M:11},Bf=Math.abs;function qf(e){return(e>0)-(e<0)||+e}function Uf(){if(!this.isValid())return this.localeData().invalidDate();var e,t,f=Bf(this._milliseconds)/1e3,a=Bf(this._days),n=Bf(this._months);e=k(f/60),t=k(e/60),f%=60,e%=60;var o=k(n/12),r=n%=12,s=a,c=t,i=e,u=f?f.toFixed(3).replace(/\.?0+$/,""):"",_=this.asSeconds();if(!_)return"P0D";var d=_<0?"-":"",l=qf(this._months)!==qf(_)?"-":"",h=qf(this._days)!==qf(_)?"-":"",m=qf(this._milliseconds)!==qf(_)?"-":"";return d+"P"+(o?l+o+"Y":"")+(r?l+r+"M":"")+(s?h+s+"D":"")+(c||i||u?"T":"")+(c?m+c+"H":"")+(i?m+i+"M":"")+(u?m+u+"S":"")}var Wf=Nt.prototype;return Wf.isValid=function(){return this._isValid},Wf.abs=function(){var e=this._data;return this._milliseconds=bf(this._milliseconds),this._days=bf(this._days),this._months=bf(this._months),e.milliseconds=bf(e.milliseconds),e.seconds=bf(e.seconds),e.minutes=bf(e.minutes),e.hours=bf(e.hours),e.months=bf(e.months),e.years=bf(e.years),this},Wf.add=function(e,t){return yf(this,e,t,1)},Wf.subtract=function(e,t){return yf(this,e,t,-1)},Wf.as=function(e){if(!this.isValid())return NaN;var t,f,a=this._milliseconds;if("month"===(e=N(e))||"year"===e)return t=this._days+a/864e5,f=this._months+wf(t),"month"===e?f:f/12;switch(t=this._days+Math.round(kf(this._months)),e){case"week":return t/7+a/6048e5;case"day":return t+a/864e5;case"hour":return 24*t+a/36e5;case"minute":return 1440*t+a/6e4;case"second":return 86400*t+a/1e3;case"millisecond":return Math.floor(864e5*t)+a;default:throw new Error("Unknown unit "+e)}},Wf.asMilliseconds=Lf,Wf.asSeconds=xf,Wf.asMinutes=Sf,Wf.asHours=Tf,Wf.asDays=Df,Wf.asWeeks=Yf,Wf.asMonths=jf,Wf.asYears=Af,Wf.valueOf=function(){return this.isValid()?this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*M(this._months/12):NaN},Wf._bubble=function(){var e,t,f,a,n,o=this._milliseconds,r=this._days,s=this._months,c=this._data;return o>=0&&r>=0&&s>=0||o<=0&&r<=0&&s<=0||(o+=864e5*vf(kf(s)+r),r=0,s=0),c.milliseconds=o%1e3,e=k(o/1e3),c.seconds=e%60,t=k(e/60),c.minutes=t%60,f=k(t/60),c.hours=f%24,r+=k(f/24),n=k(wf(r)),s+=n,r-=vf(kf(n)),a=k(s/12),s%=12,c.days=r,c.months=s,c.years=a,this},Wf.clone=function(){return Jt(this)},Wf.get=function(e){return e=N(e),this.isValid()?this[e+"s"]():NaN},Wf.milliseconds=Ef,Wf.seconds=Hf,Wf.minutes=Nf,Wf.hours=Of,Wf.days=Rf,Wf.weeks=function(){return k(this.days()/7)},Wf.months=If,Wf.years=Pf,Wf.humanize=function(e){if(!this.isValid())return this.localeData().invalidDate();var t=this.localeData(),f=function(e,t,f){var a=Jt(e).abs(),n=zf(a.as("s")),o=zf(a.as("m")),r=zf(a.as("h")),s=zf(a.as("d")),c=zf(a.as("M")),i=zf(a.as("y")),u=n<=Ff.ss&&["s",n]||n0,u[4]=f,function(e,t,f,a,n){return n.relativeTime(t||1,!!f,e,a)}.apply(null,u)}(this,!e,t);return e&&(f=t.pastFuture(+this,f)),t.postformat(f)},Wf.toISOString=Uf,Wf.toString=Uf,Wf.toJSON=Uf,Wf.locale=ef,Wf.localeData=ff,Wf.toIsoString=S("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",Uf),Wf.lang=tf,U("X",0,0,"unix"),U("x",0,0,"valueOf"),ue("x",oe),ue("X",/[+-]?\d+(\.\d{1,3})?/),he("X",function(e,t,f){f._d=new Date(1e3*parseFloat(e,10))}),he("x",function(e,t,f){f._d=new Date(M(e))}),n.version="2.19.4",t=jt,n.fn=df,n.min=function(){return Et("isBefore",[].slice.call(arguments,0))},n.max=function(){return Et("isAfter",[].slice.call(arguments,0))},n.now=function(){return Date.now?Date.now():+new Date},n.utc=l,n.unix=function(e){return jt(1e3*e)},n.months=function(e,t){return gf(e,t,"months")},n.isDate=i,n.locale=ut,n.invalid=g,n.duration=Jt,n.isMoment=w,n.weekdays=function(e,t,f){return pf(e,t,f,"weekdays")},n.parseZone=function(){return jt.apply(null,arguments).parseZone()},n.localeData=dt,n.isDuration=Ot,n.monthsShort=function(e,t){return gf(e,t,"monthsShort")},n.weekdaysMin=function(e,t,f){return pf(e,t,f,"weekdaysMin")},n.defineLocale=_t,n.updateLocale=function(e,t){if(null!=t){var f,a,n=ot;null!=(a=it(e))&&(n=a._config),t=A(n,t),(f=new C(t)).parentLocale=rt[e],rt[e]=f,ut(e)}else null!=rt[e]&&(null!=rt[e].parentLocale?rt[e]=rt[e].parentLocale:null!=rt[e]&&delete rt[e]);return rt[e]},n.locales=function(){return T(rt)},n.weekdaysShort=function(e,t,f){return pf(e,t,f,"weekdaysShort")},n.normalizeUnits=N,n.relativeTimeRounding=function(e){return void 0===e?zf:"function"==typeof e&&(zf=e,!0)},n.relativeTimeThreshold=function(e,t){return void 0!==Ff[e]&&(void 0===t?Ff[e]:(Ff[e]=t,"s"===e&&(Ff.ss=t-1),!0))},n.calendarFormat=function(e,t){var f=e.diff(t,"days",!0);return f<-6?"sameElse":f<-1?"lastWeek":f<0?"lastDay":f<1?"sameDay":f<2?"nextDay":f<7?"nextWeek":"sameElse"},n.prototype=df,n}()}).call(this,f(44)(e))},function(e,t,f){var a=f(279),n=f(277),o=/[&<>"']/g,r=RegExp(o.source);e.exports=function(e){return(e=n(e))&&r.test(e)?e.replace(o,a):e}},function(e,t,f){"use strict";var a,n,o;n=[f(9),f(45),f(16),f(158),f(289),f(288),f(7),f(0),f(14),f(285),f(284),f(282),f(281)],void 0===(o="function"==typeof(a=function(e,t,f,a,n,o,r,s,c,i,u){const _=c,d=_.$build,l=_.$iq,h=_.$msg,m=_.$pres,g=c.SHA1.b64_sha1;(c=c.Strophe).addNamespace("CARBONS","urn:xmpp:carbons:2"),c.addNamespace("CHATSTATES","http://jabber.org/protocol/chatstates"),c.addNamespace("CSI","urn:xmpp:csi:0"),c.addNamespace("DELAY","urn:xmpp:delay"),c.addNamespace("FORWARD","urn:xmpp:forward:0"),c.addNamespace("HINTS","urn:xmpp:hints"),c.addNamespace("HTTPUPLOAD","urn:xmpp:http:upload:0"),c.addNamespace("MAM","urn:xmpp:mam:2"),c.addNamespace("NICK","http://jabber.org/protocol/nick"),c.addNamespace("OUTOFBAND","jabber:x:oob"),c.addNamespace("PUBSUB","http://jabber.org/protocol/pubsub"),c.addNamespace("ROSTERX","http://jabber.org/protocol/rosterx"),c.addNamespace("RSM","http://jabber.org/protocol/rsm"),c.addNamespace("SID","urn:xmpp:sid:0"),c.addNamespace("SPOILER","urn:xmpp:spoiler:0"),c.addNamespace("VCARD","vcard-temp"),c.addNamespace("VCARDUPDATE","vcard-temp:x:update"),c.addNamespace("XFORM","jabber:x:data"),f.templateSettings={escape:/\{\{\{([\s\S]+?)\}\}\}/g,evaluate:/\{\[([\s\S]+?)\]\}/g,interpolate:/\{\{([\s\S]+?)\}\}/g,imports:{_:f}};const p={templates:{},promises:{}};f.extend(p,u.Events),p.core_plugins=["converse-bookmarks","converse-chatboxes","converse-chatview","converse-caps","converse-controlbox","converse-core","converse-disco","converse-dragresize","converse-embedded","converse-fullscreen","converse-headline","converse-mam","converse-message-view","converse-minimize","converse-modal","converse-muc","converse-muc-views","converse-notification","converse-otr","converse-ping","converse-profile","converse-register","converse-roomslist","converse-roster","converse-rosterview","converse-singleton","converse-spoilers","converse-vcard"],i.enable(p,"_converse","pluggable"),p.STATUS_WEIGHTS={offline:6,unavailable:5,xa:4,away:3,dnd:2,chat:1,online:1},p.PRETTY_CHAT_STATUS={offline:"Offline",unavailable:"Unavailable",xa:"Extended Away",away:"Away",dnd:"Do not disturb",chat:"Chattty",online:"Online"},p.ANONYMOUS="anonymous",p.CLOSED="closed",p.EXTERNAL="external",p.LOGIN="login",p.LOGOUT="logout",p.OPENED="opened",p.PREBIND="prebind",p.CONNECTION_STATUS={0:"ERROR",1:"CONNECTING",2:"CONNFAIL",3:"AUTHENTICATING",4:"AUTHFAIL",5:"CONNECTED",6:"DISCONNECTED",7:"DISCONNECTING",8:"ATTACHED",9:"REDIRECT",10:"RECONNECTING"},p.SUCCESS="success",p.FAILURE="failure",p.DEFAULT_IMAGE_TYPE="image/png",p.DEFAULT_IMAGE="iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAIAAABt+uBvAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3gwHCy455JBsggAABkJJREFUeNrtnM1PE1sUwHvvTD8otWLHST/Gimi1CEgr6M6FEWuIBo2pujDVsNDEP8GN/4MbN7oxrlipG2OCgZgYlxAbkRYw1KqkIDRCSkM7nXvvW8x7vjyNeQ9m7p1p3z1LQk/v/Dhz7vkEXL161cHl9wI5Ag6IA+KAOCAOiAPigDggLhwQB2S+iNZ+PcYY/SWEEP2HAAAIoSAIoihCCP+ngDDGtVotGAz29/cfOXJEUZSOjg6n06lp2sbGRqlUWlhYyGazS0tLbrdbEASrzgksyeYJId3d3el0uqenRxRFAAAA4KdfIIRgjD9+/Pj8+fOpqSndslofEIQwHA6Pjo4mEon//qmFhYXHjx8vLi4ihBgDEnp7e9l8E0Jo165dQ0NDd+/eDYVC2/qsJElDQ0OEkKWlpa2tLZamxAhQo9EIBoOjo6MXL17csZLe3l5FUT59+lQul5l5JRaAVFWNRqN37tw5ceKEQVWRSOTw4cOFQuHbt2+iKLYCIISQLMu3b99OJpOmKAwEAgcPHszn8+vr6wzsiG6UQQhxuVyXLl0aGBgwUW0sFstkMl6v90fo1KyAMMYDAwPnzp0zXfPg4GAqlWo0Gk0MiBAiy/L58+edTqf5Aa4onj59OhaLYYybFRCEMBaL0fNxBw4cSCQStN0QRUBut3t4eJjq6U+dOiVJElVPRBFQIBDo6+ujCqirqyscDlONGykC2lYyYSR6pBoQQapHZwAoHo/TuARYAOrs7GQASFEUqn6aIiBJkhgA6ujooFpUo6iaTa7koFwnaoWadLNe81tbWwzoaJrWrICWl5cZAFpbW6OabVAEtLi4yABQsVjUNK0pAWWzWQaAcrlcswKanZ1VVZUqHYRQEwOq1Wpv3ryhCmh6erpcLjdrNl+v1ycnJ+l5UELI27dvv3//3qxxEADgy5cvExMT9Mznw4cPtFtAdAPFarU6Pj5eKpVM17yxsfHy5cvV1VXazXu62gVBKBQKT58+rdVqJqrFGL948eLdu3dU8/g/H4FBUaJYLAqC0NPTY9brMD4+PjY25mDSracOCABACJmZmXE6nUePHjWu8NWrV48ePSKEsGlAs7Agfd5nenq6Wq0mk0kjDzY2NvbkyRMIIbP2PLvhBUEQ8vl8NpuNx+M+n29bzhVjvLKycv/+/YmJCcazQuwA6YzW1tYmJyf1SY+2trZ/rRk1Go1SqfT69esHDx4UCgVmNaa/zZ/9ABUhRFXVYDB48uTJeDweiUQkSfL7/T9MA2NcqVTK5fLy8vL8/PzU1FSxWHS5XJaM4wGr9sUwxqqqer3eUCgkSZJuUBBCfTRvc3OzXC6vrKxUKhWn02nhCJ5lM4oQQo/HgxD6+vXr58+fHf8sDOp+HQDg8XgclorFU676dKLlo6yWRdItIBwQB8QBcUCtfosRQjRNQwhhjPUC4w46WXryBSHU1zgEQWBz99EFhDGu1+t+v//48ePxeFxRlD179ng8nh0Efgiher2+vr6ur3HMzMysrq7uTJVdACGEurq6Ll++nEgkPB7Pj9jPoDHqOxyqqubz+WfPnuVyuV9XPeyeagAAAoHArVu3BgcHab8CuVzu4cOHpVKJUnfA5GweY+xyuc6cOXPv3r1IJMLAR8iyPDw8XK/Xi8Wiqqqmm5KZgBBC7e3tN27cuHbtGuPVpf7+/lAoNDs7W61WzfVKpgHSSzw3b95MpVKW3MfRaDQSiczNzVUqFRMZmQOIEOL1eq9fv3727FlL1t50URRFluX5+flqtWpWEGAOIFEUU6nUlStXLKSjy759+xwOx9zcnKZpphzGHMzhcDiTydgk9r1w4YIp7RPTAAmCkMlk2FeLf/tIEKbTab/fbwtAhJBoNGrutpNx6e7uPnTokC1eMU3T0um0DZPMkZER6wERQnw+n/FFSxpy7Nix3bt3WwwIIcRgIWnHkkwmjecfRgGx7DtuV/r6+iwGhDHev3+/bQF1dnYaH6E2CkiWZdsC2rt3r8WAHA5HW1ubbQGZcjajgOwTH/4qNko1Wlg4IA6IA+KAOKBWBUQIsfNojyliKIoRRfH9+/dut9umf3wzpoUNNQ4BAJubmwz+ic+OxefzWWlBhJD29nbug7iT5sIBcUAcEAfEAXFAHBAHxOVn+QMrmWpuPZx12gAAAABJRU5ErkJggg==",p.log=function(e,t,a=""){t!==c.LogLevel.ERROR&&t!==c.LogLevel.FATAL||(a=a||"color: maroon"),e instanceof Error&&(e=e.stack);const n=a?"%c":"",o=f.assign({debug:f.get(console,"log")?console.log.bind(console):f.noop,error:f.get(console,"log")?console.log.bind(console):f.noop,info:f.get(console,"log")?console.log.bind(console):f.noop,warn:f.get(console,"log")?console.log.bind(console):f.noop},console);t===c.LogLevel.ERROR?o.error(`${n} ERROR: ${e}`,a):t===c.LogLevel.WARN?p.debug&&o.warn(`${n} ${s().format()} WARNING: ${e}`,a):t===c.LogLevel.FATAL?o.error(`${n} FATAL: ${e}`,a):p.debug&&(t===c.LogLevel.DEBUG?o.debug(`${n} ${s().format()} DEBUG: ${e}`,a):o.info(`${n} ${s().format()} INFO: ${e}`,a))},c.log=function(e,t){p.log(e+" "+t,e)},c.error=function(e){p.log(e,c.LogLevel.ERROR)},p.__=function(e){return f.isUndefined(o)?e:o.translate.apply(o,arguments)};const b=p.__,y=["initialized","connectionInitialized","pluginsInitialized","statusInitialized"];function v(e){p.promises[e]=r.getResolveablePromise()}return p.emit=function(e){p.trigger.apply(this,arguments);const t=p.promises[e];f.isUndefined(t)||t.resolve()},p.router=new u.Router,p.initialize=function(e,a){e=f.isUndefined(e)?{}:e;const n=r.getResolveablePromise();let s;if(f.each(y,v),f.isUndefined(p.connection)||(u.history.stop(),p.chatboxviews.closeAllChatBoxes(),p.bookmarks&&p.bookmarks.reset(),delete p.controlboxtoggle,delete p.chatboxviews,p.connection.reset(),p.off(),p.stopListening(),p._tearDown()),"onpagehide"in window?s="pagehide":"onbeforeunload"in window?s="beforeunload":"onunload"in window&&(s="unload"),this.TIMEOUTS={PAUSED:1e4,INACTIVE:9e4},this.INACTIVE="inactive",this.ACTIVE="active",this.COMPOSING="composing",this.PAUSED="paused",this.GONE="gone",this.default_settings={allow_contact_requests:!0,allow_non_roster_messaging:!1,animate:!0,authentication:"login",auto_away:0,auto_login:!1,auto_reconnect:!0,auto_subscribe:!1,auto_xa:0,blacklisted_plugins:[],bosh_service_url:void 0,connection_options:{},credentials_url:null,csi_waiting_time:0,debug:!1,default_state:"online",expose_rid_and_sid:!1,filter_by_resource:!1,forward_messages:!1,geouri_regex:/https:\/\/www.openstreetmap.org\/.*#map=[0-9]+\/([\-0-9.]+)\/([\-0-9.]+)\S*/g,geouri_replacement:"https://www.openstreetmap.org/?mlat=$1&mlon=$2#map=18/$1/$2",hide_offline_users:!1,include_offline_state:!1,jid:void 0,keepalive:!0,locales_url:"locale/{{{locale}}}/LC_MESSAGES/converse.json",locales:["af","ar","bg","ca","de","es","eu","en","fr","he","hu","id","it","ja","nb","nl","pl","pt_BR","ru","tr","uk","zh_CN","zh_TW"],message_carbons:!0,nickname:void 0,password:void 0,prebind_url:null,priority:0,registration_domain:"",rid:void 0,root:window.document,show_only_online_users:!1,show_send_button:!1,sid:void 0,storage:"session",strict_plugin_dependencies:!1,synchronize_availability:!0,trusted:!0,view_mode:"overlayed",websocket_url:void 0,whitelisted_plugins:[]},f.assignIn(this,this.default_settings),f.assignIn(this,f.pick(e,f.keys(this.default_settings))),this.authentication===p.ANONYMOUS&&this.auto_login&&!this.jid)throw new Error("Config Error: you need to provide the server's domain via the 'jid' option when using anonymous authentication with auto_login.");function i(){p.initPlugins(),p.initConnection(),p.setUpXMLLogging(),p.logIn(),p.registerGlobalEventHandlers(),u.history.started||u.history.start()}return f.isUndefined(o)?p.locale="en":o.setLocales(e.i18n,p),this.callback=a||f.noop,this.send_initial_presence=!0,this.msg_counter=0,this.user_settings=e,this.generateResource=(()=>`/converse.js-${Math.floor(139749528*Math.random()).toString()}`),this.sendCSI=function(e){p.connection.send(d(e,{xmlns:c.NS.CSI})),p.inactive=e===p.INACTIVE},this.onUserActivity=function(){p.idle_seconds>0&&(p.idle_seconds=0),p.connection.authenticated&&(p.inactive&&p.sendCSI(p.ACTIVE),!0===p.auto_changed_status&&(p.auto_changed_status=!1,p.xmppstatus.set("status",p.default_state)))},this.onEverySecond=function(){if(!p.connection.authenticated)return;const e=p.xmppstatus.get("status");p.idle_seconds++,p.csi_waiting_time>0&&p.idle_seconds>p.csi_waiting_time&&!p.inactive&&p.sendCSI(p.INACTIVE),p.auto_away>0&&p.idle_seconds>p.auto_away&&"away"!==e&&"xa"!==e&&"dnd"!==e?(p.auto_changed_status=!0,p.xmppstatus.set("status","away")):p.auto_xa>0&&p.idle_seconds>p.auto_xa&&"xa"!==e&&"dnd"!==e&&(p.auto_changed_status=!0,p.xmppstatus.set("status","xa"))},this.registerIntervalHandler=function(){p.auto_away<1&&p.auto_xa<1&&p.csi_waiting_time<1||(p.idle_seconds=0,p.auto_changed_status=!1,window.addEventListener("click",p.onUserActivity),window.addEventListener("focus",p.onUserActivity),window.addEventListener("keypress",p.onUserActivity),window.addEventListener("mousemove",p.onUserActivity),window.addEventListener(s,p.onUserActivity),p.everySecondTrigger=window.setInterval(p.onEverySecond,1e3))},this.setConnectionStatus=function(e,t){p.connfeedback.set({connection_status:e,message:t})},this.rejectPresenceSubscription=function(e,t){const f=m({to:e,type:"unsubscribed"});t&&""!==t&&f.c("status").t(t),p.connection.send(f)},this.reconnect=f.debounce(function(){p.log("RECONNECTING"),p.log("The connection has dropped, attempting to reconnect."),p.setConnectionStatus(c.Status.RECONNECTING,b("The connection has dropped, attempting to reconnect.")),p.connection.reconnecting=!0,p._tearDown(),p.logIn(null,!0)},3e3,{leading:!0}),this.disconnect=function(){p.log("DISCONNECTED"),delete p.connection.reconnecting,p.connection.reset(),p._tearDown(),p.emit("disconnected")},this.onDisconnected=function(){const e=p.disconnection_reason;return p.disconnection_cause===c.Status.AUTHFAIL?p.credentials_url&&p.auto_reconnect?(p.emit("will-reconnect"),p.reconnect()):p.disconnect():p.disconnection_cause===p.LOGOUT||!f.isUndefined(e)&&e===f.get(c,"ErrorCondition.NO_AUTH_MECH")||"host-unknown"===e||"remote-connection-failed"===e||!p.auto_reconnect?p.disconnect():(p.emit("will-reconnect"),void p.reconnect())},this.setDisconnectionCause=function(e,t,a){f.isUndefined(e)?(delete p.disconnection_cause,delete p.disconnection_reason):(f.isUndefined(p.disconnection_cause)||a)&&(p.disconnection_cause=e,p.disconnection_reason=t)},this.onConnectStatusChanged=function(e,t){if(p.log(`Status changed to: ${p.CONNECTION_STATUS[e]}`),e===c.Status.CONNECTED||e===c.Status.ATTACHED)p.setConnectionStatus(e),p.send_initial_presence=!0,p.setDisconnectionCause(),p.connection.reconnecting?(p.log(e===c.Status.CONNECTED?"Reconnected":"Reattached"),p.onConnected(!0)):(p.log(e===c.Status.CONNECTED?"Connected":"Attached"),p.connection.restored&&(p.send_initial_presence=!1),p.onConnected());else if(e===c.Status.DISCONNECTED)p.setDisconnectionCause(e,t),p.onDisconnected();else if(e===c.Status.ERROR)p.setConnectionStatus(e,b("An error occurred while connecting to the chat server."));else if(e===c.Status.CONNECTING)p.setConnectionStatus(e);else if(e===c.Status.AUTHENTICATING)p.setConnectionStatus(e);else if(e===c.Status.AUTHFAIL)t||(t=b("Your Jabber ID and/or password is incorrect. Please try again.")),p.setConnectionStatus(e,t),p.setDisconnectionCause(e,t,!0),p.onDisconnected();else if(e===c.Status.CONNFAIL){let a=t;"host-unknown"===t||"remote-connection-failed"==t?a=b("Sorry, we could not connect to the XMPP host with domain: %1$s",`"${c.getDomainFromJid(p.connection.jid)}"`):f.isUndefined(t)||t!==f.get(c,"ErrorCondition.NO_AUTH_MECH")||(a=b("The XMPP server did not offer a supported authentication mechanism")),p.setConnectionStatus(e,a),p.setDisconnectionCause(e,t)}else e===c.Status.DISCONNECTING&&p.setDisconnectionCause(e,t)},this.incrementMsgCounter=function(){this.msg_counter+=1;const e=this.msg_counter;let t=document.title;f.isNil(t)||(t=-1===t.search(/^Messages \(\d+\) /)?`Messages (${e}) ${t}`:t.replace(/^Messages \(\d+\) /,`Messages (${e})`))},this.clearMsgCounter=function(){this.msg_counter=0;let e=document.title;f.isNil(e)||-1!==e.search(/^Messages \(\d+\) /)&&(e=e.replace(/^Messages \(\d+\) /,""))},this.initStatus=(e=>{if(e=!f.isUndefined(p.xmppstatus)&&e)p.onStatusInitialized(e);else{this.xmppstatus=new this.XMPPStatus;const t=g(`converse.xmppstatus-${p.bare_jid}`);this.xmppstatus.id=t,this.xmppstatus.browserStorage=new u.BrowserStorage[p.storage](t),this.xmppstatus.fetch({success:f.partial(p.onStatusInitialized,e),error:f.partial(p.onStatusInitialized,e)})}}),this.initSession=function(){p.session=new u.Model;const e=g("converse.bosh-session");p.session.id=e,p.session.browserStorage=new u.BrowserStorage[p.storage](e),p.session.fetch()},this.clearSession=function(){p.trusted?!f.isUndefined(this.session)&&this.session.browserStorage&&this.session.browserStorage._clear():(window.localStorage.clear(),window.sessionStorage.clear()),p.emit("clearSession")},this.logOut=function(){p.clearSession(),p.setDisconnectionCause(p.LOGOUT,void 0,!0),f.isUndefined(p.connection)?p._tearDown():p.connection.disconnect(),f.each(f.keys(p.promises),v),p.emit("logout")},this.saveWindowState=function(e,t){let f;const a={focus:"visible",focusin:"visible",pageshow:"visible",blur:"hidden",focusout:"hidden",pagehide:"hidden"};"visible"===(f=(e=e||document.createEvent("Events")).type in a?a[e.type]:document[t]?"hidden":"visible")&&p.clearMsgCounter(),p.windowState=f,p.emit("windowStateChanged",{state:f})},this.registerGlobalEventHandlers=function(){let e="hidden";e in document?document.addEventListener("visibilitychange",f.partial(p.saveWindowState,f,e)):(e="mozHidden")in document?document.addEventListener("mozvisibilitychange",f.partial(p.saveWindowState,f,e)):(e="webkitHidden")in document?document.addEventListener("webkitvisibilitychange",f.partial(p.saveWindowState,f,e)):(e="msHidden")in document?document.addEventListener("msvisibilitychange",f.partial(p.saveWindowState,f,e)):"onfocusin"in document?document.onfocusin=document.onfocusout=f.partial(p.saveWindowState,f,e):window.onpageshow=window.onpagehide=window.onfocus=window.onblur=f.partial(p.saveWindowState,f,e),void 0!==document[e]&&f.partial(p.saveWindowState,f,e)({type:document[e]?"blur":"focus"})},this.enableCarbons=function(){if(!this.message_carbons||this.session.get("carbons_enabled"))return;const e=new c.Builder("iq",{from:this.connection.jid,id:"enablecarbons",type:"set"}).c("enable",{xmlns:c.NS.CARBONS});this.connection.addHandler(e=>{e.querySelectorAll("error").length>0?p.log("An error occured while trying to enable message carbons.",c.LogLevel.ERROR):(this.session.save({carbons_enabled:!0}),p.log("Message carbons have been enabled."))},null,"iq",null,"enablecarbons"),this.connection.send(e)},this.sendInitialPresence=function(){p.send_initial_presence&&p.xmppstatus.sendPresence()},this.onStatusInitialized=function(e){p.emit("statusInitialized",e),e?p.emit("reconnected"):(n.resolve(),p.emit("initialized"),p.emit("connected"))},this.setUserJid=function(){p.jid=p.connection.jid,p.bare_jid=c.getBareJidFromJid(p.connection.jid),p.resource=c.getResourceFromJid(p.connection.jid),p.domain=c.getDomainFromJid(p.connection.jid)},this.onConnected=function(e){p.connection.flush(),p.setUserJid(),p.initSession(),p.enableCarbons(),p.initStatus(e)},this.ConnectionFeedback=u.Model.extend({defaults:{connection_status:c.Status.DISCONNECTED,message:""},initialize(){this.on("change",()=>{p.emit("connfeedback",p.connfeedback)})}}),this.connfeedback=new this.ConnectionFeedback,this.XMPPStatus=u.Model.extend({defaults:()=>({jid:p.bare_jid,status:p.default_state}),initialize(){this.vcard=p.vcards.findWhere({jid:this.get("jid")}),f.isNil(this.vcard)&&(this.vcard=p.vcards.create({jid:this.get("jid")})),this.on("change:status",e=>{const t=this.get("status");this.sendPresence(t),p.emit("statusChanged",t)}),this.on("change:status_message",()=>{const e=this.get("status_message");this.sendPresence(this.get("status"),e),p.emit("statusMessageChanged",e)})},constructPresence(e,t){let a;return e=f.isString(e)?e:this.get("status")||p.default_state,t=f.isString(t)?t:this.get("status_message"),a="unavailable"===e||"probe"===e||"error"===e||"unsubscribe"===e||"unsubscribed"===e||"subscribe"===e||"subscribed"===e?m({type:e}):"offline"===e?m({type:"unavailable"}):"online"===e?m():m().c("show").t(e).up(),t&&a.c("status").t(t).up(),a.c("priority").t(f.isNaN(Number(p.priority))?0:p.priority),a},sendPresence(e,t){p.connection.send(this.constructPresence(e,t))}}),this.setUpXMLLogging=function(){c.log=function(e,t){p.log(t,e)},this.debug&&(this.connection.xmlInput=function(e){p.log(e.outerHTML,c.LogLevel.DEBUG,"color: darkgoldenrod")},this.connection.xmlOutput=function(e){p.log(e.outerHTML,c.LogLevel.DEBUG,"color: darkcyan")})},this.fetchLoginCredentials=(()=>new t((e,t)=>{const f=new XMLHttpRequest;f.open("GET",p.credentials_url,!0),f.setRequestHeader("Accept","application/json, text/javascript"),f.onload=function(){if(f.status>=200&&f.status<400){const t=JSON.parse(f.responseText);e({jid:t.jid,password:t.password})}else f.onerror()},f.onerror=function(){delete p.connection,p.emit("noResumeableSession",this),t(f.responseText)},f.send()})),this.startNewBOSHSession=function(){const e=new XMLHttpRequest;e.open("GET",p.prebind_url,!0),e.setRequestHeader("Accept","application/json, text/javascript"),e.onload=function(){if(e.status>=200&&e.status<400){const t=JSON.parse(e.responseText);p.connection.attach(t.jid,t.sid,t.rid,p.onConnectStatusChanged)}else e.onerror()},e.onerror=function(){delete p.connection,p.emit("noResumeableSession",this)},e.send()},this.restoreBOSHSession=function(e){if(!this.jid){const t='restoreBOSHSession: tried to restore a "keepalive" session but we don\'t have the JID for the user!';if(e)throw new Error(t);p.log(t)}try{return this.connection.restore(this.jid,this.onConnectStatusChanged),!0}catch(e){return p.log("Could not restore session for jid: "+this.jid+" Error message: "+e.message,c.LogLevel.WARN),this.clearSession(),!1}},this.attemptPreboundSession=function(e){if(!e){if(this.keepalive&&this.restoreBOSHSession(!0))return;if(this.jid&&this.sid&&this.rid)return this.connection.attach(this.jid,this.sid,this.rid,this.onConnectStatusChanged)}if(this.prebind_url)return this.startNewBOSHSession();throw new Error("attemptPreboundSession: If you use prebind and not keepalive, then you MUST supply JID, RID and SID values or a prebind_url.")},this.attemptNonPreboundSession=function(e,t){if(t||!this.keepalive||!this.restoreBOSHSession())if(e)this.autoLogin(e);else if(this.auto_login)if(this.credentials_url)this.fetchLoginCredentials().then(this.autoLogin.bind(this),this.autoLogin.bind(this));else{if(!this.jid)throw new Error("attemptNonPreboundSession: If you use auto_login, you also need to give either a jid value (and if applicable a password) or you need to pass in a URL from where the username and password can be fetched (via credentials_url).");this.autoLogin()}else t&&this.autoLogin()},this.autoLogin=function(e){if(e&&(this.jid=e.jid),this.authentication===p.ANONYMOUS||this.authentication===p.EXTERNAL){if(!this.jid)throw new Error("Config Error: when using anonymous login you need to provide the server's domain via the 'jid' option. Either when calling converse.initialize, or when calling _converse.api.user.login.");this.connection.reconnecting||this.connection.reset(),this.connection.connect(this.jid.toLowerCase(),null,this.onConnectStatusChanged)}else if(this.authentication===p.LOGIN){const t=f.isNil(e)?p.connection.pass||this.password:e.password;if(!t){if(this.auto_login)throw new Error("initConnection: If you use auto_login and authentication='login' then you also need to provide a password.");return p.setDisconnectionCause(c.Status.AUTHFAIL,void 0,!0),void p.disconnect()}const a=c.getResourceFromJid(this.jid);this.jid=a?c.getBareJidFromJid(this.jid).toLowerCase()+"/"+a:this.jid.toLowerCase()+p.generateResource(),this.connection.reconnecting||this.connection.reset(),this.connection.connect(this.jid,t,this.onConnectStatusChanged)}},this.logIn=function(e,t){this.authentication===p.PREBIND?this.attemptPreboundSession(t):this.attemptNonPreboundSession(e,t)},this.initConnection=function(){if(!this.connection){if(!this.bosh_service_url&&!this.websocket_url)throw new Error("initConnection: you must supply a value for either the bosh_service_url or websocket_url or both.");if(("WebSocket"in window||"MozWebSocket"in window)&&this.websocket_url)this.connection=new c.Connection(this.websocket_url,this.connection_options);else{if(!this.bosh_service_url)throw new Error("initConnection: this browser does not support websockets and bosh_service_url wasn't specified.");this.connection=new c.Connection(this.bosh_service_url,f.assignIn(this.connection_options,{keepalive:this.keepalive}))}}p.emit("connectionInitialized")},this._tearDown=function(){return p.emit("beforeTearDown"),f.isUndefined(p.session)||p.session.destroy(),window.removeEventListener("click",p.onUserActivity),window.removeEventListener("focus",p.onUserActivity),window.removeEventListener("keypress",p.onUserActivity),window.removeEventListener("mousemove",p.onUserActivity),window.removeEventListener(s,p.onUserActivity),window.clearInterval(p.everySecondTrigger),p.emit("afterTearDown"),p},this.initPlugins=function(){p.pluggable.initialized_plugins=[];const e=p.core_plugins.concat(p.whitelisted_plugins);"embedded"===p.view_mode&&f.forEach(["converse-bookmarks","converse-controlbox","converse-headline","converse-register"],e=>{p.blacklisted_plugins.push(e)}),p.pluggable.initializePlugins({updateSettings(){p.log("(DEPRECATION) The `updateSettings` method has been deprecated. Please use `_converse.api.settings.update` instead.",c.LogLevel.WARN),p.api.settings.update.apply(p,arguments)},_converse:p},e,p.blacklisted_plugins),p.emit("pluginsInitialized")},e.connection&&(this.connection=e.connection),f.isUndefined(p.connection)||"jasmine tests"!==p.connection.service?(f.isUndefined(o)?i():o.fetchTranslations(p.locale,p.locales,r.interpolate(p.locales_url,{locale:p.locale})).catch(f.partial(p.log,f,c.LogLevel.FATAL)).then(i).catch(f.partial(p.log,f,c.LogLevel.FATAL)),n):(i(),p)},p.api={connection:{connected:()=>p.connection&&p.connection.connected||!1,disconnect(){p.connection.disconnect()}},emit(){p.emit.apply(p,arguments)},user:{jid:()=>p.connection.jid,login(e){p.logIn(e)},logout(){p.logOut()},status:{get:()=>p.xmppstatus.get("status"),set(e,t){const a={status:e};if(!f.includes(f.keys(p.STATUS_WEIGHTS),e))throw new Error("Invalid availability value. See https://xmpp.org/rfcs/rfc3921.html#rfc.section.2.2.2.1");f.isString(t)&&(a.status_message=t),p.xmppstatus.sendPresence(e),p.xmppstatus.save(a)},message:{get:()=>p.xmppstatus.get("status_message"),set(e){p.xmppstatus.save({status_message:e})}}}},settings:{update(e){r.merge(p.default_settings,e),r.merge(p,e),r.applyUserSettings(p,e,p.user_settings)},get(e){if(f.includes(f.keys(p.default_settings),e))return p[e]},set(e,t){const a={};f.isObject(e)?f.assignIn(p,f.pick(e,f.keys(p.default_settings))):f.isString("string")&&(a[e]=t,f.assignIn(p,f.pick(a,f.keys(p.default_settings))))}},promises:{add(e){e=f.isArray(e)?e:[e],f.each(e,v)}},tokens:{get:e=>!p.expose_rid_and_sid||f.isUndefined(p.connection)?null:"rid"===e.toLowerCase()?p.connection.rid||p.connection._proto.rid:"sid"===e.toLowerCase()?p.connection.sid||p.connection._proto.sid:void 0},listen:{once:p.once.bind(p),on:p.on.bind(p),not:p.off.bind(p),stanza(e,t,a){f.isFunction(t)?(a=t,t={}):t=t||{},p.connection.addHandler(a,t.ns,e,t.type,t.id,t.from,t)}},waitUntil(e){const t=p.promises[e];return f.isUndefined(t)?null:t},send(e){p.connection.send(e)}},window.converse={initialize:(e,t)=>p.initialize(e,t),plugins:{add(e,t){if(t.__name__=e,!f.isUndefined(p.pluggable.plugins[e]))throw new TypeError(`Error: plugin with name "${e}" has already been `+"registered!");p.pluggable.plugins[e]=t}},env:{$build:d,$iq:l,$msg:h,$pres:m,Backbone:u,Promise:t,Strophe:c,_:f,f:a,b64_sha1:g,moment:s,sizzle:e,utils:r}},window.dispatchEvent(new CustomEvent("converse-loaded")),window.converse})?a.apply(t,n):a)||(e.exports=o)},function(e,t,f){"use strict";var a,n,o;n=[f(2),f(12),f(13),f(53),f(52),f(51),f(241),f(240),f(239),f(238),f(237),f(17),f(236),f(235),f(234),f(18),f(233),f(232),f(231),f(11),f(50),f(228)],void 0===(o="function"==typeof(a=function(e,t,f,a,n,o,r,s,c,i,u,_,d,l,h,m,g,p,b){const y=e.env,v=(y.$msg,y.Backbone),w=y.Promise,k=y.Strophe,M=y._,L=(y.b64_sha1,y.f,y.sizzle),x=y.moment,S=e.env.utils,T={ENTER:13,FORWARD_SLASH:47};return e.plugins.add("converse-chatview",{dependencies:["converse-chatboxes","converse-disco","converse-message-view","converse-modal"],overrides:{ChatBoxViews:{onChatBoxAdded(e){const t=this.__super__._converse;let f=this.get(e.get("id"));return f?this.__super__.onChatBoxAdded.apply(this,arguments):(f=new t.ChatBoxView({model:e}),this.add(e.get("id"),f),f)}}},initialize(){const e=this._converse,n=e.__;e.api.settings.update({use_emojione:!1,emojione_image_path:f.imagePathPNG,show_toolbar:!0,time_format:"HH:mm",visible_toolbar_buttons:{call:!1,clear:!0,emoji:!0,spoiler:!0}}),f.imagePathPNG=e.emojione_image_path,f.ascii=!0,e.api.listen.on("windowStateChanged",function(t){e.chatboxviews.each(function(e){e.onWindowStateChanged(t.state)})}),e.EmojiPicker=v.Model.extend({defaults:{current_category:"people",current_skintone:"",scroll_position:0},initialize(){const t=`converse.emoji-${e.bare_jid}`;this.id=t,this.browserStorage=new v.BrowserStorage[e.storage](t)}}),e.EmojiPickerView=v.VDOMView.extend({className:"emoji-picker-container",events:{"click .emoji-category-picker li.emoji-category":"chooseCategory","click .emoji-skintone-picker li.emoji-skintone":"chooseSkinTone"},initialize(){this.model.on("change:current_skintone",this.render,this),this.model.on("change:current_category",this.render,this)},toHTML(){return c(M.extend(this.model.toJSON(),{transform:e.use_emojione?f.shortnameToImage:f.shortnameToUnicode,emojis_by_category:S.getEmojisByCategory(e,f),toned_emojis:S.getTonedEmojis(e),skintones:["tone1","tone2","tone3","tone4","tone5"],shouldBeHidden:this.shouldBeHidden}))},shouldBeHidden(e,t,f){if(M.includes(e,"_tone")){if(!t||!M.includes(e,t))return!0}else if(t&&M.includes(f,e))return!0;return!1},chooseSkinTone(e){e.preventDefault(),e.stopPropagation();const t=("IMG"===e.target.nodeName?e.target.parentElement:e.target).getAttribute("data-skintone").trim();this.model.get("current_skintone")===t?this.model.save({current_skintone:""}):this.model.save({current_skintone:t})},chooseCategory(e){e.preventDefault(),e.stopPropagation();const t=("IMG"===e.target.nodeName?e.target.parentElement:e.target).getAttribute("data-category").trim();this.model.save({current_category:t,scroll_position:0})}}),e.ChatBoxHeading=e.ViewWithAvatar.extend({initialize(){this.model.on("change:status",this.onStatusMessageChanged,this),this.model.vcard.on("change",this.render,this)},render(){return this.el.innerHTML=r(M.extend(this.model.toJSON(),this.model.vcard.toJSON(),{_converse:e,info_close:n("Close this chat box")})),this.renderAvatar(),this},onStatusMessageChanged(t){this.render(),e.emit("contactStatusMessageChanged",{contact:t.attributes,message:t.get("status")})}}),e.UserDetailsModal=e.BootstrapModal.extend({events:{"click button.remove-contact":"removeContact","click button.refresh-contact":"refreshContact"},initialize(){e.BootstrapModal.prototype.initialize.apply(this,arguments),this.model.on("contactAdded",this.registerContactEventHandlers,this),this.registerContactEventHandlers()},toHTML(){return l(M.extend(this.model.toJSON(),this.model.vcard.toJSON(),{allow_contact_removal:e.allow_contact_removal,alt_profile_image:n("The User's Profile Image"),display_name:this.model.getDisplayName(),is_roster_contact:!M.isUndefined(this.model.contact),label_close:n("Close"),label_email:n("Email"),label_fullname:n("Full Name"),label_jid:n("Jabber ID"),label_nickname:n("Nickname"),label_remove:n("Remove as contact"),label_refresh:n("Refresh"),label_role:n("Role"),label_url:n("URL")}))},registerContactEventHandlers(){M.isUndefined(this.model.contact)||(this.model.contact.on("change",this.render,this),this.model.contact.vcard.on("change",this.render,this),this.model.contact.on("destroy",()=>{delete this.model.contact,this.render()}))},refreshContact(t){t&&t.preventDefault&&t.preventDefault();const f=this.el.querySelector(".fa-refresh");S.addClass("fa-spin",f),e.api.vcard.update(this.model.contact.vcard,!0).then(()=>S.removeClass("fa-spin",f)).catch(M.partial(e.log,M,k.LogLevel.FATAL))},removeContact(t){t&&t.preventDefault&&t.preventDefault(),e.allow_contact_removal&&!0===confirm(n("Are you sure you want to remove this contact?"))&&(this.modal.hide(),this.model.contact.removeFromRoster(e=>{this.model.contact.destroy()},t=>{e.log(t,k.LogLevel.ERROR),e.api.alert.show(k.LogLevel.ERROR,n("Error"),[n("Sorry, there was an error while trying to remove %1$s as a contact.",this.model.contact.getDisplayName())])}))}}),e.ChatBoxView=v.NativeView.extend({length:200,className:"chatbox hidden",is_chatroom:!1,events:{"change input.fileupload":"onFileSelection","click .close-chatbox-button":"close","click .show-user-details-modal":"showUserDetailsModal","click .new-msgs-indicator":"viewUnreadMessages","click .send-button":"onFormSubmitted","click .toggle-call":"toggleCall","click .toggle-clear":"clearMessages","click .toggle-compose-spoiler":"toggleComposeSpoilerMessage","click .toggle-smiley ul.emoji-picker li":"insertEmoji","click .toggle-smiley":"toggleEmojiMenu","click .spoiler-toggle":"toggleSpoilerMessage","click .upload-file":"toggleFileUpload","keypress .chat-textarea":"keyPressed","input .chat-textarea":"inputChanged"},initialize(){this.initDebounced(),this.createEmojiPicker(),this.model.messages.on("add",this.onMessageAdded,this),this.model.messages.on("rendered",this.scrollDown,this),this.model.on("show",this.show,this),this.model.on("destroy",this.remove,this),this.model.presence.on("change:show",this.onPresenceChanged,this),this.model.on("showHelpMessages",this.showHelpMessages,this),this.render(),this.fetchMessages(),e.emit("chatBoxOpened",this),e.emit("chatBoxInitialized",this)},initDebounced(){this.scrollDown=M.debounce(this._scrollDown,250),this.markScrolled=M.debounce(this._markScrolled,100),this.show=M.debounce(this._show,250,{leading:!0})},render(){return this.el.setAttribute("id",this.model.get("box_id")),this.el.innerHTML=o(M.extend(this.model.toJSON(),{unread_msgs:n("You have unread messages")})),this.content=this.el.querySelector(".chat-content"),this.renderMessageForm(),this.insertHeading(),this},renderToolbar(t,f){return e.show_toolbar?(t=t||b,f=M.assign(this.model.toJSON(),this.getToolbarOptions(f||{})),this.el.querySelector(".chat-toolbar").innerHTML=t(f),this.addSpoilerButton(f),this.addFileUploadButton(),this.insertEmojiPicker(),this):this},renderMessageForm(){let t;t=this.model.get("composing_spoiler")?n("Hidden message"):n("Personal message"),this.el.querySelector(".message-form-container").innerHTML=s(M.extend(this.model.toJSON(),{hint_value:M.get(this.el.querySelector(".spoiler-hint"),"value"),label_personal_message:t,label_send:n("Send"),label_spoiler_hint:n("Optional hint"),message_value:M.get(this.el.querySelector(".chat-textarea"),"value"),show_send_button:e.show_send_button,show_toolbar:e.show_toolbar,unread_msgs:n("You have unread messages")})),this.renderToolbar()},showUserDetailsModal(t){M.isUndefined(this.user_details_modal)&&(this.user_details_modal=new e.UserDetailsModal({model:this.model})),this.user_details_modal.show(t)},toggleFileUpload(e){this.el.querySelector("input.fileupload").click()},onFileSelection(e){this.model.sendFiles(e.target.files)},addFileUploadButton(t){e.api.disco.supports(k.NS.HTTPUPLOAD,e.domain).then(e=>{e.length&&this.el.querySelector(".chat-toolbar").insertAdjacentHTML("beforeend",h({tooltip_upload_file:n("Choose a file to send")}))}).catch(M.partial(e.log,M,k.LogLevel.FATAL))},addSpoilerButton(t){if(!t.show_spoiler_button||"chatroom"===this.model.get("type"))return;const f=this.model.get("jid"),a=this.model.presence.get("resources");M.isEmpty(a)||w.all(M.map(M.keys(a),t=>e.api.disco.supports(k.NS.SPOILER,`${f}/${t}`))).then(t=>{if(M.filter(t,"length").length){const t=g(this.model.toJSON());e.visible_toolbar_buttons.emoji?this.el.querySelector(".toggle-smiley").insertAdjacentHTML("afterEnd",t):this.el.querySelector(".chat-toolbar").insertAdjacentHTML("afterBegin",t)}}).catch(M.partial(e.log,M,k.LogLevel.FATAL))},insertHeading(){this.heading=new e.ChatBoxHeading({model:this.model}),this.heading.render(),this.heading.chatview=this,M.isUndefined(this.model.contact)||this.model.contact.on("destroy",this.heading.render,this);const t=this.el.querySelector(".flyout");return t.insertBefore(this.heading.el,t.querySelector(".chat-body")),this},getToolbarOptions(t){let f;return f=this.model.get("composing_spoiler")?n("Click to write as a normal (non-spoiler) message"):n("Click to write your message as a spoiler"),M.extend(t||{},{label_clear:n("Clear all messages"),tooltip_insert_smiley:n("Insert emojis"),tooltip_start_call:n("Start a call"),label_toggle_spoiler:f,show_call_button:e.visible_toolbar_buttons.call,show_spoiler_button:e.visible_toolbar_buttons.spoiler,use_emoji:e.visible_toolbar_buttons.emoji})},afterMessagesFetched(){this.insertIntoDOM(),this.scrollDown(),this.content.addEventListener("scroll",this.markScrolled.bind(this)),e.emit("afterMessagesFetched",this)},fetchMessages(){return this.model.messages.fetch({add:!0,success:this.afterMessagesFetched.bind(this),error:this.afterMessagesFetched.bind(this)}),this},insertIntoDOM(){return e.chatboxviews.insertRowColumn(this.el),this},showChatEvent(e,t=""){const f=x().format();return this.content.insertAdjacentHTML("beforeend",_({extra_classes:"chat-event",message:e,isodate:f,data:t})),this.insertDayIndicator(this.content.lastElementChild),this.scrollDown(),f},showErrorMessage(e){this.content.insertAdjacentHTML("beforeend",i({message:e,isodate:x().format()})),this.scrollDown()},addSpinner(e=!1){M.isNull(this.el.querySelector(".spinner"))&&(e?(this.content.insertAdjacentHTML("beforeend",m()),this.scrollDown()):this.content.insertAdjacentHTML("afterbegin",m()))},clearSpinner(){M.each(this.content.querySelectorAll("span.spinner"),e=>e.parentNode.removeChild(e))},insertDayIndicator(e){const t=S.getPreviousElement(e,".message:not(.chat-state-notification)"),f=M.isNull(t)?null:t.getAttribute("data-isodate"),a=e.getAttribute("data-isodate");if(M.isNull(f)||x(a).isAfter(f,"day")){const t=x(a).startOf("day");e.insertAdjacentHTML("beforeBegin",d({isodate:t.format(),datestring:t.format("dddd MMM Do YYYY")}))}},getLastMessageDate(e){const t=S.getFirstChildElement(this.content,".message:not(.chat-state-notification)"),f=t?t.getAttribute("data-isodate"):null;if(!M.isNull(f)&&x(f).isAfter(e))return null;const a=S.getLastChildElement(this.content,".message:not(.chat-state-notification)"),n=a?a.getAttribute("data-isodate"):null;if(M.isNull(n)||x(n).isBefore(e))return n;const o=M.invokeMap(L(".message:not(.chat-state-notification)",this.content),Element.prototype.getAttribute,"data-isodate");M.isObject(e)&&(e=e.format()),o.push(e),o.sort();const r=o.lastIndexOf(e);return 0===r?null:o[r-1]},setScrollPosition(e){if(this.model.get("scrolled")){const t=S.getNextElement(e,".chat-msg");if(t&&(0===this.content.scrollTop||this.model.get("top_visible_message"))){const e=this.model.get("top_visible_message")||t;this.model.set("top_visible_message",e),this.content.scrollTop=e.offsetTop-30}}else this.scrollDown()},showHelpMessages(e,t,f){return M.each(e,e=>{this.content.insertAdjacentHTML("beforeend",u({isodate:x().format(),type:t,message:a.filterXSS(e,{whiteList:{strong:[]}})}))}),!0===f?this.addSpinner():!1===f&&this.clearSpinner(),this.scrollDown()},clearChatStateNotification(e,t){t?M.each(L(`.chat-state-notification[data-csn="${e.get("from")}"][data-isodate="${t}"]`,this.content),S.removeElement):M.each(L(`.chat-state-notification[data-csn="${e.get("from")}"]`,this.content),S.removeElement)},shouldShowOnTextMessage(){return!S.isVisible(this.el)},insertMessage(e){if("error"===e.model.get("type")){const t=this.content.querySelector(`[data-msgid="${e.model.get("msgid")}"]`);if(t)return t.insertAdjacentElement("afterend",e.el)}const t=x(e.model.get("time"))||x,f=this.getLastMessageDate(t);if(M.isNull(f))this.content.insertAdjacentElement("afterbegin",e.el);else{const t=L(`[data-isodate="${f}"]:last`,this.content).pop();if("error"===e.model.get("type")&&S.hasClass("chat-error",t)&&t.textContent===e.model.get("message"))return;t.insertAdjacentElement("afterend",e.el),this.markFollowups(e.el)}},markFollowups(e){const t=e.getAttribute("data-from"),f=e.previousElementSibling,a=x(e.getAttribute("data-isodate")),n=e.nextElementSibling;S.hasClass("chat-action",e)||S.hasClass("chat-action",f)||f.getAttribute("data-from")!==t||!a.isBefore(x(f.getAttribute("data-isodate")).add(10,"minutes"))||S.addClass("chat-msg-followup",e),n&&(!S.hasClass("chat-action","el")&&n.getAttribute("data-from")===t&&x(n.getAttribute("data-isodate")).isBefore(a.add(10,"minutes"))?S.addClass("chat-msg-followup",n):S.removeClass("chat-msg-followup",n))},showMessage(t){const f=new e.MessageView({model:t});this.clearChatStateNotification(t),this.insertMessage(f),this.insertDayIndicator(f.el),this.setScrollPosition(f.el),S.isNewMessage(t)&&("me"===t.get("sender")?this.model.set("scrolled",!1):this.model.get("scrolled",!0)&&this.showNewMessagesIndicator()),this.shouldShowOnTextMessage()?this.show():this.scrollDown()},onMessageAdded(t){this.showMessage(t),e.emit("messageAdded",{message:t,chatbox:this.model})},parseMessageForCommands(e){const t=e.replace(/^\s*/,"").match(/^\/(.*)\s*$/);if(t){if("clear"===t[1])return this.clearMessages(),!0;if("help"===t[1]){const e=[`/clear: ${n("Remove messages")}`,`/me: ${n("Write in the third person")}`,`/help: ${n("Show this menu")}`];return this.showHelpMessages(e),!0}}},onMessageSubmitted(t,f){if(!e.connection.authenticated)return this.showHelpMessages(["Sorry, the connection has been lost, and your message could not be sent"],"error");if(this.parseMessageForCommands(t))return;const a=this.model.getOutgoingMessageAttributes(t,f);this.model.sendMessage(a)},setChatState(t){return M.isUndefined(this.chat_state_timeout)||(window.clearTimeout(this.chat_state_timeout),delete this.chat_state_timeout),t===e.COMPOSING?this.chat_state_timeout=window.setTimeout(this.setChatState.bind(this),e.TIMEOUTS.PAUSED,e.PAUSED):t===e.PAUSED&&(this.chat_state_timeout=window.setTimeout(this.setChatState.bind(this),e.TIMEOUTS.INACTIVE,e.INACTIVE)),this.model.set("chat_state",t),this},onFormSubmitted(t){t.preventDefault();const f=this.el.querySelector(".chat-textarea"),a=f.value;let n;if(this.model.get("composing_spoiler")){const e=this.el.querySelector("form.sendXMPPMessage input.spoiler-hint");n=e.value,e.value=""}f.value="",f.focus();const o=document.createEvent("Event");o.initEvent("input",!0,!0),f.dispatchEvent(o),""!==a&&(this.onMessageSubmitted(a,n),e.emit("messageSend",a)),this.setChatState(e.ACTIVE)},keyPressed(t){t.keyCode===T.ENTER?this.onFormSubmitted(t):t.keyCode!==T.FORWARD_SLASH&&this.model.get("chat_state")!==e.COMPOSING&&this.setChatState(e.COMPOSING)},inputChanged(e){e.target.style.height="auto",e.target.style.height=e.target.scrollHeight+"px"},clearMessages(e){return e&&e.preventDefault&&e.preventDefault(),!0===confirm(n("Are you sure you want to clear the messages from this conversation?"))&&(this.content.innerHTML="",this.model.messages.reset(),this.model.messages.browserStorage._clear()),this},insertIntoTextArea(e){const t=this.el.querySelector(".chat-textarea");let f=t.value;f&&" "!==f[f.length-1]&&(f+=" "),t.value=f+e+" ",t.focus()},createEmojiPicker(){M.isUndefined(e.emojipicker)&&(e.emojipicker=new e.EmojiPicker,e.emojipicker.fetch()),this.emoji_picker_view=new e.EmojiPickerView({model:e.emojipicker})},insertEmoji(e){e.stopPropagation();const t="IMG"===e.target.nodeName?e.target.parentElement:e.target;this.insertIntoTextArea(t.getAttribute("data-emoji"))},toggleEmojiMenu(e){if(M.isUndefined(this.emoji_dropdown)){e.stopPropagation();const f=this.el.querySelector(".toggle-smiley.dropup");this.emoji_dropdown=new t.Dropdown(f,!0),this.emoji_dropdown.toggle()}},toggleCall(t){t.stopPropagation(),e.emit("callButtonClicked",{connection:e.connection,model:this.model})},toggleComposeSpoilerMessage(){this.model.set("composing_spoiler",!this.model.get("composing_spoiler")),this.renderMessageForm(),this.focus()},toggleSpoilerMessage(e){e&&e.preventDefault&&e.preventDefault();const t=e.target,f=t.firstElementChild;S.slideToggleElement(t.parentElement.parentElement.querySelector(".spoiler")),"closed"==t.getAttribute("data-toggle-state")?(t.textContent="Show less",f.classList.remove("fa-eye"),f.classList.add("fa-eye-slash"),t.insertAdjacentElement("afterBegin",f),t.setAttribute("data-toggle-state","open")):(t.textContent="Show more",f.classList.remove("fa-eye-slash"),f.classList.add("fa-eye"),t.insertAdjacentElement("afterBegin",f),t.setAttribute("data-toggle-state","closed"))},onPresenceChanged(e){const t=e.get("show"),f=this.model.getDisplayName();let a;S.isVisible(this.el)&&("offline"===t?a=f+" "+n("has gone offline"):"away"===t?a=f+" "+n("has gone away"):"dnd"===t?a=f+" "+n("is busy"):"online"===t&&(a=f+" "+n("is online")),a&&(this.content.insertAdjacentHTML("beforeend",p({message:a,isodate:x().format()})),this.scrollDown()))},close(t){t&&t.preventDefault&&t.preventDefault(),v.history.getFragment()==="converse/chat?jid="+this.model.get("jid")&&e.router.navigate(""),e.connection.connected&&(this.setChatState(e.INACTIVE),this.model.sendChatState());try{this.model.destroy()}catch(t){e.log(t,k.LogLevel.ERROR)}return this.remove(),e.emit("chatBoxClosed",this),this},renderEmojiPicker(){this.emoji_picker_view.render()},insertEmojiPicker(){var e=this.el.querySelector(".emoji-picker");M.isNull(e)||(e.innerHTML="",e.appendChild(this.emoji_picker_view.el))},focus(){const t=this.el.querySelector(".chat-textarea");return M.isNull(t)||(t.focus(),e.emit("chatBoxFocused",this)),this},hide(){return this.el.classList.add("hidden"),this},afterShown(){S.isPersistableModel(this.model)&&(this.model.clearUnreadMsgCounter(),this.model.save()),this.setChatState(e.ACTIVE),this.renderEmojiPicker(),this.scrollDown(),this.focus()},_show(e){S.isVisible(this.el)?this.focus():S.fadeIn(this.el,M.bind(this.afterShown,this))},showNewMessagesIndicator(){S.showElement(this.el.querySelector(".new-msgs-indicator"))},hideNewMessagesIndicator(){const e=this.el.querySelector(".new-msgs-indicator");M.isNull(e)||e.classList.add("hidden")},_markScrolled:function(e){e&&e.preventDefault&&e.preventDefault();let t=!0;this.content.scrollTop+this.content.clientHeight>=this.content.scrollHeight-62&&(t=!1,this.onScrolledDown()),S.safeSave(this.model,{scrolled:t,top_visible_message:null})},viewUnreadMessages(){this.model.save({scrolled:!1,top_visible_message:null}),this.scrollDown()},_scrollDown(){M.isUndefined(this.content)||S.isVisible(this.content)&&!this.model.get("scrolled")&&(this.content.scrollTop=this.content.scrollHeight)},onScrolledDown(){this.hideNewMessagesIndicator(),"hidden"!==e.windowState&&this.model.clearUnreadMsgCounter(),e.emit("chatBoxScrolledDown",{chatbox:this.model})},onWindowStateChanged(e){this.model.get("num_unread",0)&&!this.model.newMessageWillBeHidden()&&this.model.clearUnreadMsgCounter()}}),e.on("connected",()=>{e.api.disco.own.features.add(k.NS.SPOILER)}),M.extend(e.api,{chatviews:{get:t=>M.isUndefined(t)?(e.log("chats.create: You need to provide at least one JID",k.LogLevel.ERROR),null):M.isString(t)?e.chatboxviews.get(t):M.map(t,f=>e.chatboxviews.get(t))}})}}),e})?a.apply(t,n):a)||(e.exports=o)},function(e,t,f){(function(a){var n,o,r;r="object"==typeof self&&self.self===self&&self||"object"==typeof a&&a.global===a&&a,n=[f(8),f(283),t],void 0===(o=function(e,t,f){r.Backbone=function(e,t,f,a){var n=e.Backbone,o=Array.prototype.slice;t.VERSION="1.3.3",t.$=a,t.noConflict=function(){return e.Backbone=n,this},t.emulateHTTP=!1,t.emulateJSON=!1;var r=function(e,t,a){f.each(t,function(t,n){f[n]&&(e.prototype[n]=function(e,t,a){switch(e){case 1:return function(){return f[t](this[a])};case 2:return function(e){return f[t](this[a],e)};case 3:return function(e,n){return f[t](this[a],s(e,this),n)};case 4:return function(e,n,o){return f[t](this[a],s(e,this),n,o)};default:return function(){var e=o.call(arguments);return e.unshift(this[a]),f[t].apply(f,e)}}}(t,n,a))})},s=function(e,t){return f.isFunction(e)?e:f.isObject(e)&&!t._isModel(e)?c(e):f.isString(e)?function(t){return t.get(e)}:e},c=function(e){var t=f.matches(e);return function(e){return t(e.attributes)}},i=t.Events={},u=/\s+/,_=function(e,t,a,n,o){var r,s=0;if(a&&"object"==typeof a){void 0!==n&&"context"in o&&void 0===o.context&&(o.context=n);for(r=f.keys(a);sthis.length&&(n=this.length),n<0&&(n+=this.length+1);var o,r,s=[],c=[],i=[],u=[],_={},d=t.add,l=t.merge,h=t.remove,m=!1,g=this.comparator&&null==n&&!1!==t.sort,p=f.isString(this.comparator)?this.comparator:null;for(r=0;r7),this._useHashChange=this._wantsHashChange&&this._hasHashChange,this._wantsPushState=!!this.options.pushState,this._hasPushState=!(!this.history||!this.history.pushState),this._usePushState=this._wantsPushState&&this._hasPushState,this.fragment=this.getFragment(),this.root=("/"+this.root+"/").replace(H,"/"),this._wantsHashChange&&this._wantsPushState){if(!this._hasPushState&&!this.atRoot()){var t=this.root.slice(0,-1)||"/";return this.location.replace(t+"#"+this.getPath()),!0}this._hasPushState&&this.atRoot()&&this.navigate(this.getHash(),{replace:!0})}if(!this._hasHashChange&&this._wantsHashChange&&!this._usePushState){this.iframe=document.createElement("iframe"),this.iframe.src="javascript:0",this.iframe.style.display="none",this.iframe.tabIndex=-1;var a=document.body,n=a.insertBefore(this.iframe,a.firstChild).contentWindow;n.document.open(),n.document.close(),n.location.hash="#"+this.fragment}var o=window.addEventListener||function(e,t){return attachEvent("on"+e,t)};if(this._usePushState?o("popstate",this.checkUrl,!1):this._useHashChange&&!this.iframe?o("hashchange",this.checkUrl,!1):this._wantsHashChange&&(this._checkUrlInterval=setInterval(this.checkUrl,this.interval)),!this.options.silent)return this.loadUrl()},stop:function(){var e=window.removeEventListener||function(e,t){return detachEvent("on"+e,t)};this._usePushState?e("popstate",this.checkUrl,!1):this._useHashChange&&!this.iframe&&e("hashchange",this.checkUrl,!1),this.iframe&&(document.body.removeChild(this.iframe),this.iframe=null),this._checkUrlInterval&&clearInterval(this._checkUrlInterval),C.started=!1},route:function(e,t){this.handlers.unshift({route:e,callback:t})},checkUrl:function(e){var t=this.getFragment();if(t===this.fragment&&this.iframe&&(t=this.getHash(this.iframe.contentWindow)),t===this.fragment)return!1;this.iframe&&this.navigate(t),this.loadUrl()},loadUrl:function(e){return!!this.matchRoot()&&(e=this.fragment=this.getFragment(e),f.some(this.handlers,function(t){if(t.route.test(e))return t.callback(e),!0}))},navigate:function(e,t){if(!C.started)return!1;t&&!0!==t||(t={trigger:!!t}),e=this.getFragment(e||"");var f=this.root;""!==e&&"?"!==e.charAt(0)||(f=f.slice(0,-1)||"/");var a=f+e;if(e=this.decodeFragment(e.replace(N,"")),this.fragment!==e){if(this.fragment=e,this._usePushState)this.history[t.replace?"replaceState":"pushState"]({},document.title,a);else{if(!this._wantsHashChange)return this.location.assign(a);if(this._updateHash(this.location,e,t.replace),this.iframe&&e!==this.getHash(this.iframe.contentWindow)){var n=this.iframe.contentWindow;t.replace||(n.document.open(),n.document.close()),this._updateHash(n.location,e,t.replace)}}return t.trigger?this.loadUrl(e):void 0}},_updateHash:function(e,t,f){if(f){var a=e.href.replace(/(javascript:|#).*$/,"");e.replace(a+"#"+t)}else e.hash="#"+t}}),t.history=new C,b.extend=y.extend=T.extend=M.extend=C.extend=function(e,t){var a,n=this;return a=e&&f.has(e,"constructor")?e.constructor:function(){return n.apply(this,arguments)},f.extend(a,n,t),a.prototype=f.create(n.prototype,e),a.prototype.constructor=a,a.__super__=n.prototype,a};var O=function(){throw new Error('A "url" property or function must be specified')},R=function(e,t){var f=t.error;t.error=function(a){f&&f.call(t.context,e,a,t),e.trigger("error",e,a,t)}};return t}(r,f,e,t)}.apply(t,n))||(e.exports=o)}).call(this,f(5))},function(e,t){var f;f=function(){return this}();try{f=f||Function("return this")()||(0,eval)("this")}catch(e){"object"==typeof window&&(f=window)}e.exports=f},function(e,t,f){"use strict";var a,n,o;n=[f(20),f(2),f(13),f(56),f(19),f(254),f(55),f(54)],void 0===(o="function"==typeof(a=function(e,t,f){const a={moderator:1,participant:2,visitor:3,none:2},n=t.env,o=n.Strophe,r=n.Backbone,s=n.Promise,c=n.$iq,i=n.$build,u=n.$msg,_=n.$pres,d=n.b64_sha1,l=n.sizzle,h=n._;n.moment,o.addNamespace("MUC_ADMIN",o.NS.MUC+"#admin"),o.addNamespace("MUC_OWNER",o.NS.MUC+"#owner"),o.addNamespace("MUC_REGISTER","jabber:iq:register"),o.addNamespace("MUC_ROOMCONF",o.NS.MUC+"#roomconfig"),o.addNamespace("MUC_USER",o.NS.MUC+"#user"),t.MUC_NICK_CHANGED_CODE="303",t.CHATROOMS_TYPE="chatroom",t.ROOM_FEATURES=["passwordprotected","unsecured","hidden","publicroom","membersonly","open","persistent","temporary","nonanonymous","semianonymous","moderated","unmoderated","mam_enabled"],t.ROOMSTATUS={CONNECTED:0,CONNECTING:1,NICKNAME_REQUIRED:2,PASSWORD_REQUIRED:3,DISCONNECTED:4,ENTERED:5},t.plugins.add("converse-muc",{dependencies:["converse-chatboxes","converse-disco","converse-controlbox"],overrides:{_tearDown(){const f=this.chatboxes.where({type:t.CHATROOMS_TYPE});h.each(f,function(f){e.safeSave(f,{connection_status:t.ROOMSTATUS.DISCONNECTED})}),this.__super__._tearDown.call(this,arguments)},ChatBoxes:{model(e,f){const a=this.__super__._converse;return e.type==t.CHATROOMS_TYPE?new a.ChatRoom(e,f):this.__super__.model.apply(this,arguments)}}},initialize(){const n=this._converse,m=n.__;if(n.api.settings.update({allow_muc:!0,allow_muc_invitations:!0,auto_join_on_invite:!1,auto_join_rooms:[],muc_domain:void 0,muc_history_max_stanzas:void 0,muc_instant_rooms:!0,muc_nickname_from_jid:!1}),n.api.promises.add(["roomsAutoJoined"]),n.router.route("converse/room?jid=:jid",function(t){if(!e.isValidMUCJID(t))return n.log(`Invalid JID "${t}" provided in URL fragment`,o.LogLevel.WARN);const f=[n.api.waitUntil("roomsAutoJoined")];n.allow_bookmarks&&f.push(n.api.waitUntil("bookmarksInitialized")),s.all(f).then(()=>{n.api.rooms.open(t)})}),n.openChatRoom=function(e,f,a){f.type=t.CHATROOMS_TYPE,f.id=e,f.box_id=d(e);const o=n.chatboxes.getChatBox(e,f,!0);return o.trigger("show",!0),o},n.ChatRoom=n.ChatBox.extend({defaults:()=>h.assign(h.clone(n.ChatBox.prototype.defaults),h.zipObject(t.ROOM_FEATURES,h.map(t.ROOM_FEATURES,h.stubFalse)),{num_unread_general:0,affiliation:null,connection_status:t.ROOMSTATUS.DISCONNECTED,name:"",nick:n.xmppstatus.get("nickname"),description:"",features_fetched:!1,roomconfig:{},type:t.CHATROOMS_TYPE,message_type:"groupchat"}),initialize(){this.constructor.__super__.initialize.apply(this,arguments),this.occupants=new n.ChatRoomOccupants,this.occupants.browserStorage=new r.BrowserStorage.session(d(`converse.occupants-${n.bare_jid}${this.get("jid")}`)),this.occupants.chatroom=this,this.registerHandlers(),this.on("change:chat_state",this.sendChatState,this)},registerHandlers(){const e=this.get("jid");this.removeHandlers(),this.presence_handler=n.connection.addHandler(e=>(h.each(h.values(this.handlers.presence),t=>t(e)),this.onPresence(e),!0),o.NS.MUC,"presence",null,null,e,{ignoreNamespaceFragment:!0,matchBareFromJid:!0}),this.message_handler=n.connection.addHandler(e=>(h.each(h.values(this.handlers.message),t=>t(e)),this.onMessage(e),!0),null,"message","groupchat",null,e,{matchBareFromJid:!0})},removeHandlers(){return this.message_handler&&(n.connection.deleteHandler(this.message_handler),delete this.message_handler),this.presence_handler&&(n.connection.deleteHandler(this.presence_handler),delete this.presence_handler),this},addHandler(e,t,f){h.isNil(this.handlers)&&(this.handlers={}),h.isNil(this.handlers[e])&&(this.handlers[e]={}),this.handlers[e][t]=f},join(e,f){if(!(e=e||this.get("nick")))throw new TypeError("join: You need to provide a valid nickname");if(this.get("connection_status")===t.ROOMSTATUS.ENTERED)return this;const a=_({from:n.connection.jid,to:this.getRoomJIDAndNick(e)}).c("x",{xmlns:o.NS.MUC}).c("history",{maxstanzas:n.muc_history_max_stanzas}).up();return f&&a.cnode(o.xmlElement("password",[],f)),this.save("connection_status",t.ROOMSTATUS.CONNECTING),n.connection.send(a),this},leave(f){this.occupants.browserStorage._clear(),this.occupants.reset(),n.connection.connected&&this.sendUnavailablePresence(f),e.safeSave(this,{connection_status:t.ROOMSTATUS.DISCONNECTED}),this.removeHandlers()},sendUnavailablePresence(e){const t=_({type:"unavailable",from:n.connection.jid,to:this.getRoomJIDAndNick()});null!==e&&t.c("status",e),n.connection.sendPresence(t)},getOutgoingMessageAttributes(t,a){const o=this.get("composing_spoiler");return{nick:this.get("nick"),from:`${this.get("jid")}/${this.get("nick")}`,fullname:this.get("nick"),is_spoiler:o,message:t?e.httpToGeoUri(f.shortnameToUnicode(t),n):void 0,sender:"me",spoiler_hint:o?a:void 0,type:"groupchat"}},getRoomFeatures(){return new s((e,t)=>{n.api.disco.info(this.get("jid"),null,h.flow(this.parseRoomFeatures.bind(this),e),()=>{t(new Error("Could not parse the room features"))},5e3)})},getRoomJIDAndNick(e){e?this.save({nick:e}):e=this.get("nick");const t=this.get("jid"),f=o.getBareJidFromJid(t);return f+(null!==e?`/${e}`:"")},sendChatState(){if(this.get("connection_status")!==t.ROOMSTATUS.ENTERED)return;const e=this.get("chat_state");e!==n.GONE&&n.connection.send(u({to:this.get("jid"),type:"groupchat"}).c(e,{xmlns:o.NS.CHATSTATES}).up().c("no-store",{xmlns:o.NS.HINTS}).up().c("no-permanent-store",{xmlns:o.NS.HINTS}))},directInvite(t,f){if(this.get("membersonly")){const a={};a[t]="member";const n=h.partial(e.computeAffiliationsDelta,!0,!1);this.updateMemberLists([{jid:t,affiliation:"member",reason:f}],["member","owner","admin"],n)}const a={xmlns:"jabber:x:conference",jid:this.get("jid")};null!==f&&(a.reason=f),this.get("password")&&(a.password=this.get("password"));const o=u({from:n.connection.jid,to:t,id:n.connection.getUniqueId()}).c("x",a);n.connection.send(o),n.emit("roomInviteSent",{room:this,recipient:t,reason:f})},parseRoomFeatures(e){const t={features_fetched:!0,name:e.querySelector("identity").getAttribute("name")};h.each(e.querySelectorAll("feature"),function(e){const f=e.getAttribute("var");f.startsWith("muc_")?t[f.replace("muc_","")]=!0:f===o.NS.MAM&&(t.mam_enabled=!0)});const f=e.querySelector('field[var="muc#roominfo_description"] value');h.isNull(f)||(t.description=f.textContent),this.save(t)},requestMemberList(e){return new s((t,f)=>{e=e||"member";const a=c({to:this.get("jid"),type:"get"}).c("query",{xmlns:o.NS.MUC_ADMIN}).c("item",{affiliation:e});n.connection.sendIQ(a,t,f)})},setAffiliation(e,t){t=h.filter(t,t=>h.isUndefined(t.affiliation)||t.affiliation===e);const f=h.map(t,h.bind(this.sendAffiliationIQ,this,e));return s.all(f)},saveConfiguration(t){return new s((f,a)=>{const n=t?l(":input:not([type=button]):not([type=submit])",t):[],o=h.map(n,e.webForm2xForm);this.sendConfiguration(o,f,a)})},autoConfigureChatRoom(){return new s((e,t)=>{this.fetchRoomConfiguration().then(f=>{const a=[],n=f.querySelectorAll("field"),o=this.get("roomconfig");let r=n.length;h.each(n,f=>{const n=f.getAttribute("var").replace("muc#roomconfig_",""),s=f.getAttribute("type");let c;if(n in o){switch(s){case"boolean":c=o[n]?1:0;break;case"list-multi":c=f.innerHTML;break;default:c=o[n]}f.innerHTML=i("value").t(c)}a.push(f),--r||this.sendConfiguration(a,e,t)})})})},fetchRoomConfiguration(){return new s((e,t)=>{n.connection.sendIQ(c({to:this.get("jid"),type:"get"}).c("query",{xmlns:o.NS.MUC_OWNER}),e,t)})},sendConfiguration(e,t,f){const a=c({to:this.get("jid"),type:"set"}).c("query",{xmlns:o.NS.MUC_OWNER}).c("x",{xmlns:o.NS.XFORM,type:"submit"});return h.each(e||[],function(e){a.cnode(e).up()}),t=h.isUndefined(t)?h.noop:h.partial(t,a.nodeTree),f=h.isUndefined(f)?h.noop:h.partial(f,a.nodeTree),n.connection.sendIQ(a,t,f)},saveAffiliationAndRole(e){const t=l(`x[xmlns="${o.NS.MUC_USER}"] item`,e).pop(),f=e.querySelector("status[code='110']");if(f&&!h.isNil(t)){const e=t.getAttribute("affiliation"),f=t.getAttribute("role");e&&this.save({affiliation:e}),f&&this.save({role:f})}},sendAffiliationIQ(e,t){return new s((f,a)=>{const r=c({to:this.get("jid"),type:"set"}).c("query",{xmlns:o.NS.MUC_ADMIN}).c("item",{affiliation:t.affiliation||e,jid:t.jid});h.isUndefined(t.reason)||r.c("reason",t.reason),n.connection.sendIQ(r,f,a)})},setAffiliations(e){const t=h.uniq(h.map(e,"affiliation"));return s.all(h.map(t,h.partial(this.setAffiliation.bind(this),h,e)))},getJidsWithAffiliations(t){return h.isString(t)&&(t=[t]),new s((f,a)=>{const n=h.map(t,h.partial(this.requestMemberList.bind(this)));s.all(n).then(h.flow(e.marshallAffiliationIQs,f),h.flow(e.marshallAffiliationIQs,f))})},updateMemberLists(e,t,f){this.getJidsWithAffiliations(t).then(t=>this.setAffiliations(f(e,t))).then(()=>this.occupants.fetchMembers()).catch(h.partial(n.log,h,o.LogLevel.ERROR))},checkForReservedNick(e,t){return n.connection.sendIQ(c({to:this.get("jid"),from:n.connection.jid,type:"get"}).c("query",{xmlns:o.NS.DISCO_INFO,node:"x-roomuser-item"}),e,t),this},updateOccupantsOnPresence(e){const f=this.parsePresence(e);if("error"===f.type)return!0;const a=this.occupants.findOccupant(f);if("unavailable"===f.type&&a&&!h.includes(f.states,t.MUC_NICK_CHANGED_CODE)&&!a.isMember())return a.set(f),void a.destroy();const n=o.getBareJidFromJid(f.jid),r=h.extend(f,{jid:n||void 0,resource:f.jid?o.getResourceFromJid(f.jid):void 0});a?a.save(r):this.occupants.create(r)},parsePresence(e){const t=e.getAttribute("from"),f=e.getAttribute("type"),a={from:t,nick:o.getResourceFromJid(t),type:f,states:[],show:"unavailable"!==f?"online":"offline"};return h.each(e.childNodes,function(e){switch(e.nodeName){case"status":a.status=e.textContent||null;break;case"show":a.show=e.textContent||"online";break;case"x":e.getAttribute("xmlns")===o.NS.MUC_USER?h.each(e.childNodes,function(e){switch(e.nodeName){case"item":a.affiliation=e.getAttribute("affiliation"),a.role=e.getAttribute("role"),a.jid=e.getAttribute("jid"),a.nick=e.getAttribute("nick")||a.nick;break;case"status":e.getAttribute("code")&&a.states.push(e.getAttribute("code"))}}):e.getAttribute("xmlns")===o.NS.VCARDUPDATE&&(a.image_hash=h.get(e.querySelector("photo"),"textContent"))}}),a},isDuplicate(e,t){const f=e.getAttribute("id"),a=e.getAttribute("from");return!!f&&this.messages.where({msgid:f,from:a}).length},fetchFeaturesIfConfigurationChanged(e){const t=e.querySelector("status[code='104']"),f=e.querySelector("status[code='170']"),a=e.querySelector("status[code='171']"),n=e.querySelector("status[code='172']"),o=e.querySelector("status[code='173']"),r=e.querySelector("status[code='173']");(t||f||a||n||o||r)&&this.getRoomFeatures()},onMessage(t){this.fetchFeaturesIfConfigurationChanged(t);const f=t,a=t.querySelector("forwarded");let r;h.isNull(a)||(t=a.querySelector("message"),r=a.querySelector("delay"));const s=t.getAttribute("from"),c=o.getResourceFromJid(s),i=c&&o.unescapeNode(c)||"",u=h.propertyOf(t.querySelector("subject"))("textContent");this.isDuplicate(t,f)||(u&&e.safeSave(this,{subject:{author:i,text:u}}),""!==i&&(this.incrementUnreadMsgCounter(f),this.createMessage(t,r,f),i!==this.get("nick")&&n.emit("message",{stanza:f,chatbox:this})))},onPresence(e){if("error"===e.getAttribute("type"))return void this.save("connection_status",t.ROOMSTATUS.DISCONNECTED);const f=e.querySelector("status[code='110']");f&&"unavailable"!==e.getAttribute("type")&&this.onOwnPresence(e),this.updateOccupantsOnPresence(e),"none"!==this.get("role")&&this.get("connection_status")===t.ROOMSTATUS.CONNECTING&&this.save("connection_status",t.ROOMSTATUS.CONNECTED)},onOwnPresence(e){this.saveAffiliationAndRole(e);const f=e.querySelector("status[code='201']");if(f)if(this.get("auto_configure"))this.autoConfigureChatRoom().then(this.getRoomFeatures.bind(this));else{if(!n.muc_instant_rooms)return void this.trigger("configurationNeeded");this.saveConfiguration().then(this.getRoomFeatures.bind(this))}else this.get("features_fetched")||("owner"===this.get("affiliation")&&this.get("auto_configure")?this.autoConfigureChatRoom().then(this.getRoomFeatures.bind(this)):this.getRoomFeatures());this.save("connection_status",t.ROOMSTATUS.ENTERED)},isUserMentioned(e){return new RegExp(`\\b${this.get("nick")}\\b`).test(e)},incrementUnreadMsgCounter(t){const f=t.querySelector("body");if(!h.isNull(f)&&e.isNewMessage(t)&&this.newMessageWillBeHidden()){const e={num_unread_general:this.get("num_unread_general")+1};this.isUserMentioned(f.textContent)&&(e.num_unread=this.get("num_unread")+1,n.incrementMsgCounter()),this.save(e)}},clearUnreadMsgCounter(){e.safeSave(this,{num_unread:0,num_unread_general:0})}}),n.ChatRoomOccupant=r.Model.extend({defaults:{show:"offline"},initialize(e){this.set(h.extend({id:n.connection.getUniqueId()},e)),this.on("change:image_hash",this.onAvatarChanged,this)},onAvatarChanged(){const e=n.vcards.findWhere({jid:this.get("from")});if(!e)return;const t=this.get("image_hash");t&&e.get("image_hash")!==t&&n.api.vcard.update(e)},getDisplayName(){return this.get("nick")||this.get("jid")},isMember(){return h.includes(["admin","owner","member"],this.get("affiliation"))}}),n.ChatRoomOccupants=r.Collection.extend({model:n.ChatRoomOccupant,comparator(e,t){const f=e.get("role")||"none",n=t.get("role")||"none";if(a[f]===a[n]){const f=e.getDisplayName().toLowerCase(),a=t.getDisplayName().toLowerCase();return fa?1:0}return a[f]e.get("jid")),h.map(this.where({affiliation:"member"}),e=>e.get("jid")),h.map(this.where({affiliation:"owner"}),e=>e.get("jid"))));this.chatroom.getJidsWithAffiliations(["member","owner","admin"]).then(t=>{h.each(h.difference(e,t),e=>{const t=this.findOccupant({jid:e});"offline"===t.get("show")&&t.destroy()}),h.each(t,e=>{const t=this.findOccupant({jid:e.jid});t?t.save(e):this.create(e)})}).catch(h.partial(n.log,h,o.LogLevel.ERROR))},findOccupant(e){const t=o.getBareJidFromJid(e.jid);return null!==t?this.where({jid:t}).pop():this.where({nick:e.nick}).pop()}}),n.RoomsPanelModel=r.Model.extend({defaults:{muc_domain:""}}),n.onDirectMUCInvitation=function(e){const f=l('x[xmlns="jabber:x:conference"]',e).pop(),a=o.getBareJidFromJid(e.getAttribute("from")),r=f.getAttribute("jid"),s=f.getAttribute("reason");let c,i=n.roster.get(a);if(n.auto_join_on_invite?c=!0:(i=i?i.get("fullname"):o.getNodeFromJid(a),c=s?confirm(m('%1$s has invited you to join a chat room: %2$s, and left the following reason: "%3$s"',i,r,s)):confirm(m("%1$s has invited you to join a chat room: %2$s",i,r))),!0===c){const e=n.openChatRoom(r,{password:f.getAttribute("password")});e.get("connection_status")===t.ROOMSTATUS.DISCONNECTED&&n.chatboxviews.get(r).join()}},n.allow_muc_invitations){const e=function(){n.connection.addHandler(function(e){return n.onDirectMUCInvitation(e),!0},"jabber:x:conference","message")};n.on("connected",e),n.on("reconnected",e)}const g=function(e,f,a){return e=e.toLowerCase(),f.type=t.CHATROOMS_TYPE,f.id=e,f.box_id=d(e),n.chatboxes.getChatBox(e,f,a)},p=function(e,t){return g(e,t,!0)};function b(){n.chatboxes.each(function(e){e.get("type")===t.CHATROOMS_TYPE&&e.save("connection_status",t.ROOMSTATUS.DISCONNECTED)})}n.on("addClientFeatures",()=>{n.allow_muc&&n.api.disco.own.features.add(o.NS.MUC),n.allow_muc_invitations&&n.api.disco.own.features.add("jabber:x:conference")}),n.on("chatBoxesFetched",function(){h.each(n.auto_join_rooms,function(e){n.chatboxes.where({jid:e}).length||(h.isString(e)?n.api.rooms.open(e):h.isObject(e)?n.api.rooms.open(e.jid,e.nick):n.log('Invalid room criteria specified for "auto_join_rooms"',o.LogLevel.ERROR))}),n.emit("roomsAutoJoined")}),n.on("reconnecting",b),n.on("disconnecting",b),h.extend(n.api,{rooms:{close(e){if(h.isUndefined(e))n.chatboxviews.each(function(e){e.is_chatroom&&e.model&&e.close()});else if(h.isString(e)){const t=n.chatboxviews.get(e);t&&t.close()}else h.each(e,function(e){const t=n.chatboxviews.get(e);t&&t.close()})},create(e,t){if(h.isString(t)?t={nick:t}:h.isUndefined(t)&&(t={}),h.isUndefined(t.maximize)&&(t.maximize=!1),!t.nick&&n.muc_nickname_from_jid&&(t.nick=o.getNodeFromJid(n.bare_jid)),h.isUndefined(e))throw new TypeError("rooms.create: You need to provide at least one JID");return h.isString(e)?p(e,t):h.map(e,h.partial(p,h,t))},open(e,t){if(h.isUndefined(e))throw new TypeError("rooms.open: You need to provide at least one JID");return h.isString(e)?n.api.rooms.create(e,t).trigger("show"):h.map(e,e=>n.api.rooms.create(e,t).trigger("show"))},get(e,f,a){if(h.isString(f)?f={nick:f}:h.isUndefined(f)&&(f={}),h.isUndefined(e)){const e=[];return n.chatboxes.each(function(f){f.get("type")===t.CHATROOMS_TYPE&&e.push(f)}),e}return f.nick||(f.nick=o.getNodeFromJid(n.bare_jid)),h.isString(e)?g(e,f):h.map(e,h.partial(g,h,f))}}})}})})?a.apply(t,n):a)||(e.exports=o)},function(e,t,f){"use strict";var a,n,o;n=[f(9),f(45),f(16),f(4),f(14),f(266),f(265),f(264),f(263),f(280)],void 0===(o="function"==typeof(a=function(e,t,f,a,n,o,r,s,c,i){n=n.Strophe;const u=/\b(https?:\/\/|www\.|https?:\/\/www\.)[^\s<>]{2,200}\b\/?/g,_=f.assign({debug:f.get(console,"log")?console.log.bind(console):f.noop,error:f.get(console,"log")?console.log.bind(console):f.noop,info:f.get(console,"log")?console.log.bind(console):f.noop,warn:f.get(console,"log")?console.log.bind(console):f.noop},console);var d={};function l(e,t){e.classList.remove("visible"),f.isFunction(t)&&t()}return d.getNextElement=function(t,a="*"){let n=t.nextElementSibling;for(;!f.isNull(n)&&!e.matchesSelector(n,a);)n=n.nextElementSibling;return n},d.getPreviousElement=function(t,a="*"){let n=t.previousSibling;for(;!f.isNull(n)&&!e.matchesSelector(n,a);)n=n.previousSibling;return n},d.getFirstChildElement=function(t,a="*"){let n=t.firstElementChild;for(;!f.isNull(n)&&!e.matchesSelector(n,a);)n=n.nextSibling;return n},d.getLastChildElement=function(t,a="*"){let n=t.lastElementChild;for(;!f.isNull(n)&&!e.matchesSelector(n,a);)n=n.previousSibling;return n},d.calculateElementHeight=function(e){return f.reduce(e.children,(e,t)=>e+t.offsetHeight,0)},d.addClass=function(e,t){t instanceof Element&&t.classList.add(e)},d.removeClass=function(e,t){return t instanceof Element&&t.classList.remove(e),t},d.removeElement=function(e){f.isNil(e)||f.isNil(e.parentNode)||e.parentNode.removeChild(e)},d.showElement=f.flow(f.partial(d.removeClass,"collapsed"),f.partial(d.removeClass,"hidden")),d.hideElement=function(e){return f.isNil(e)||e.classList.add("hidden"),e},d.ancestor=function(t,a){let n=t;for(;!f.isNil(n)&&!e.matchesSelector(n,a);)n=n.parentElement;return n},d.nextUntil=function(e,t,a=!1){const n=[];let o=e.nextElementSibling;for(;!f.isNil(o)&&!o.matches(t);)n.push(o),o=o.nextElementSibling;return n},d.unescapeHTML=function(e){var t=document.createElement("div");return t.innerHTML=e,t.innerText},d.escapeHTML=function(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""")},d.addHyperlinks=function(e){return o.withinString(e,function(e){var t=new o(e);return t.normalize(),e.startsWith("http://")||e.startsWith("https://")||(e="http://"+e),e=encodeURI(decodeURI(e)).replace(/[!'()]/g,escape).replace(/\*/g,"%2A"),`${d.escapeHTML(t.readable())}`})},d.renderImageURLs=function(a,n){const o=a.__,r=n.textContent.match(u)||[];return t.all(f.map(r,a=>new t((r,s)=>(a=a,new t((e,t)=>{var f=new Image,n=window.setTimeout(function(){t(new Error("Could not determine whether it's an image")),f=null},3e3);f.onerror=f.onabort=function(){clearTimeout(n),t(new Error("Could not determine whether it's an image"))},f.onload=function(){clearTimeout(n),e(f)},f.src=a})).then(function(t){const s=new Image;s.src=t.src,s.addEventListener("load",r),s.addEventListener("error",r),f.each(e(`a[href="${a}"]`,n),e=>{e.outerHTML=c({url:a,label_download:o("Download")})})}).catch(r))));var s},d.renderFileURL=function(e,t){const a=new o(t),n=e.__,r=a.filename();return!f.includes(["https","http"],a.protocol())||r.endsWith("mp3")||r.endsWith("mp4")||r.endsWith("jpg")||r.endsWith("jpeg")||r.endsWith("png")||r.endsWith("gif")||r.endsWith("svg")?t:s({url:t,label_download:n('Download: "%1$s',r)})},d.renderImageURL=function(e,t){const f=e.__;return t.endsWith("jpg")||t.endsWith("jpeg")||t.endsWith("png")||t.endsWith("gif")||t.endsWith("svg")?c({url:t,label_download:f("Download")}):t},d.renderMovieURL=function(e,t){const f=e.__;return t.endsWith("mp4")?i({url:t,label_download:f("Download video file")}):t},d.renderAudioURL=function(e,t){const f=e.__;return t.endsWith("mp3")?r({url:t,label_download:f("Download audio file")}):t},d.slideInAllElements=function(e,a=300){return t.all(f.map(e,f.partial(d.slideIn,f,a)))},d.slideToggleElement=function(e,t){return f.includes(e.classList,"collapsed")||f.includes(e.classList,"hidden")?d.slideOut(e,t):d.slideIn(e,t)},d.hasClass=function(e,t){return f.includes(t.classList,e)},d.slideOut=function(e,a=200){return new t((t,n)=>{if(f.isNil(e)){const e="Undefined or null element passed into slideOut";return _.warn(e),void n(new Error(e))}const o=e.getAttribute("data-slider-marker");o&&(e.removeAttribute("data-slider-marker"),window.cancelAnimationFrame(o));const r=d.calculateElementHeight(e);if(window.converse_disable_effects)return e.style.height=r+"px",function(e){e.removeAttribute("data-slider-marker"),e.classList.remove("collapsed"),e.style.overflow="",e.style.height=""}(e),void t();if(!d.hasClass("collapsed",e)&&!d.hasClass("hidden",e))return void t();const s=a/17;let c=0;e.style.height="0",e.style.overflow="hidden",e.classList.remove("hidden"),e.classList.remove("collapsed"),e.setAttribute("data-slider-marker",window.requestAnimationFrame(function f(){(c+=r/s){if(f.isNil(e)){const e="Undefined or null element passed into slideIn";return _.warn(e),n(new Error(e))}if(f.includes(e.classList,"collapsed"))return t(e);if(window.converse_disable_effects)return e.classList.add("collapsed"),e.style.height="",t(e);const o=e.getAttribute("data-slider-marker");o&&(e.removeAttribute("data-slider-marker"),window.cancelAnimationFrame(o));const r=e.offsetHeight,s=a/17;let c=r;e.style.overflow="hidden",e.setAttribute("data-slider-marker",window.requestAnimationFrame(function f(){(c-=r/s)>0?(e.style.height=c+"px",e.setAttribute("data-slider-marker",window.requestAnimationFrame(f))):(e.removeAttribute("data-slider-marker"),e.classList.add("collapsed"),e.style.height="",t(e))}))})},d.fadeIn=function(e,t){if(f.isNil(e)&&_.warn("Undefined or null element passed into fadeIn"),window.converse_disable_effects)return e.classList.remove("hidden"),l(e,t);f.includes(e.classList,"hidden")?(e.classList.add("visible"),e.classList.remove("hidden"),e.addEventListener("webkitAnimationEnd",f.partial(l,e,t)),e.addEventListener("animationend",f.partial(l,e,t)),e.addEventListener("oanimationend",f.partial(l,e,t))):l(e,t)},d.isValidJID=function(e){return 2===f.compact(e.split("@")).length&&!e.startsWith("@")&&!e.endsWith("@")},d.isValidMUCJID=function(e){return!e.startsWith("@")&&!e.endsWith("@")},d.isSameBareJID=function(e,t){return n.getBareJidFromJid(e).toLowerCase()===n.getBareJidFromJid(t).toLowerCase()},d.getMostRecentMessage=function(e){const t=e.messages.filter("message");return t[t.length-1]},d.isNewMessage=function(t){return t instanceof Element?!e('result[xmlns="'+n.NS.MAM+'"]',t).length&&!e('delay[xmlns="'+n.NS.DELAY+'"]',t).length:!t.get("delayed")},d.isOnlyChatStateNotification=function(e){return e instanceof a.Model&&(e=e.attributes),e.chat_state&&!e.oob_url&&!e.file&&!e.message},d.isOTRMessage=function(e){var t=e.querySelector("body"),a=f.isNull(t)?void 0:t.textContent;return a&&!!a.match(/^\?OTR/)},d.isHeadlineMessage=function(e,t){var a=t.getAttribute("from");if("headline"===t.getAttribute("type"))return!0;const o=e.chatboxes.get(n.getBareJidFromJid(a));return!(o&&"chatroom"===o.get("type")||"error"===t.getAttribute("type")||f.isNil(a)||f.includes(a,"@"))},d.merge=function e(t,a){for(var n in a)f.isObject(t[n])?e(t[n],a[n]):t[n]=a[n]},d.applyUserSettings=function e(t,a,n){for(var o in a)f.isUndefined(n[o])||(f.isObject(a[o])&&!f.isArray(a[o])?e(t[o],a[o],n[o]):t[o]=n[o])},d.stringToNode=function(e){var t=document.createElement("div");return t.innerHTML=e,t.firstChild},d.getOuterWidth=function(e,t=!1){var f=e.offsetWidth;if(!t)return f;var a=window.getComputedStyle(e);return f+=parseInt(a.marginLeft,10)+parseInt(a.marginRight,10)},d.stringToElement=function(e){var t=document.createElement("div");return t.innerHTML=e,t.firstElementChild},d.matchesSelector=function(e,t){return(e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector).call(e,t)},d.queryChildren=function(e,t){return f.filter(e.childNodes,f.partial(d.matchesSelector,f,t))},d.contains=function(e,t){return function(a){if("object"==typeof e){var n=!1;return f.forEach(e,function(e){n=n||f.includes(a.get(e).toLowerCase(),t.toLowerCase())}),n}if("string"==typeof e)return f.includes(a.get(e).toLowerCase(),t.toLowerCase());throw new TypeError("contains: wrong attribute type. Must be string or array.")}},d.isOfType=function(e,t){return t.get("type")==e},d.isInstance=function(e,t){return t instanceof e},d.getAttribute=function(e,t){return t.get(e)},d.contains.not=function(e,t){return function(f){return!d.contains(e,t)(f)}},d.rootContains=function(e,t){return e!==document||e.contains?e.contains?e.contains(t):window.HTMLElement.prototype.contains.call(e,t):document.head.contains(t)||document.body.contains(t)},d.createFragmentFromText=function(e){var t,f=document.createDocumentFragment(),a=document.createElement("body");for(a.innerHTML=e;t=a.firstChild;)f.appendChild(t);return f},d.addEmoji=function(e,t,f){return e.use_emojione?t.toImage(f):t.shortnameToUnicode(f)},d.getEmojisByCategory=function(e,t){if(f.isUndefined(e.emojis_by_category)){const a=f.values(f.mapValues(t.emojioneList,function(e,t,f){return e._shortname=t,e})),n=[":tone1:",":tone2:",":tone3:",":tone4:",":tone5:"],o=[":kiss_ww:",":kiss_mm:",":kiss_woman_man:"],r=[":woman",":man",":women_",":men_","_man_","_woman_","_woman:","_man:"],s=["modifier","regional"],c=f.difference(f.uniq(f.map(a,f.partial(f.get,f,"category"))),s),i={};f.forEach(c,e=>{let t=f.sortBy(f.filter(a,["category",e]),["uc_base"]);if(t=f.filter(t,e=>!f.includes(f.concat(n,o),e._shortname)&&!f.some(r,f.partial(f.includes,e._shortname))),"people"===e){const e=f.findIndex(t,["uc_base","1f600"]);t=f.union(f.slice(t,e),f.slice(t,0,e+1))}else"activity"===e?t=f.union(f.slice(t,26),f.slice(t,0,27)):"objects"===e?t=f.union(f.slice(t,23),f.slice(t,0,24)):"travel"===e?t=f.union(f.slice(t,16),f.slice(t,0,17)):"symbols"===e&&(t=f.union(f.slice(t,59),f.slice(t,0,60)));i[e]=t}),e.emojis_by_category=i}return e.emojis_by_category},d.getTonedEmojis=function(e){return e.toned_emojis=f.uniq(f.map(f.filter(d.getEmojisByCategory(e).people,e=>f.includes(e._shortname,"_tone")),e=>e._shortname.replace(/_tone[1-5]/,""))),e.toned_emojis},d.isPersistableModel=function(e){return e.collection&&e.collection.browserStorage},d.getResolveablePromise=function(){const e={},a=new t((t,f)=>{e.resolve=t,e.reject=f});return f.assign(a,e),a},d.interpolate=function(e,t){return e.replace(/{{{([^{}]*)}}}/g,(e,f)=>{var a=t[f];return"string"==typeof a||"number"==typeof a?a:e})},d.onMultipleEvents=function(e=[],t){let a=[];function n(f){a.push(f),e.length===a.length&&(t(a),a=[])}f.each(e,e=>e.object.on(e.event,n))},d.safeSave=function(e,t){d.isPersistableModel(e)?e.save(t):e.set(t)},d.isVisible=function(e){return!d.hasClass("hidden",e)&&(e.offsetWidth>0||e.offsetHeight>0||e.getClientRects().length>0)},d.triggerEvent=function(e,t,f="Event",a=!0,n=!0){const o=document.createEvent(f);o.initEvent(t,a,n),e.dispatchEvent(o)},d.geoUriToHttp=function(e,t){return e.replace(/geo:([\-0-9.]+),([\-0-9.]+)(?:,([\-0-9.]+))?(?:\?(.*))?/g,t)},d.httpToGeoUri=function(e,t){return e.replace(t.geouri_regex,"geo:$1,$2")},d.getSelectValues=function(e){for(var t,f=[],a=e&&e.options,n=0,o=a.length;n+~]|"+z+")"+z+"*"),V=new RegExp("="+z+"*([^\\]'\"]*?)"+z+"*\\]","g"),G=new RegExp(q),Q=new RegExp("^"+F+"$"),X={ID:new RegExp("^#("+F+")"),CLASS:new RegExp("^\\.("+F+")"),TAG:new RegExp("^("+F+"|[*])"),ATTR:new RegExp("^"+B),PSEUDO:new RegExp("^"+q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+z+"*(even|odd|(([+-]|)(\\d*)n|)"+z+"*(?:([+-]|)"+z+"*(\\d+)|))"+z+"*\\)|)","i"),bool:new RegExp("^(?:"+P+")$","i"),needsContext:new RegExp("^"+z+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+z+"*((?:-\\d)?\\d*)"+z+"*\\)|)(?=[^-]|$)","i")},K=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,ee=/^[^{]+\{\s*\[native \w/,te=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,fe=/[+~]/,ae=new RegExp("\\\\([\\da-f]{1,6}"+z+"?|("+z+")|.)","ig"),ne=function(e,t,f){var a="0x"+t-65536;return a!=a||f?t:a<0?String.fromCharCode(a+65536):String.fromCharCode(a>>10|55296,1023&a|56320)},oe=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,re=function(e,t){return t?"\0"===e?"�":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},se=function(){g()},ce=ke(function(e){return!0===e.disabled&&("form"in e||"label"in e)},{dir:"parentNode",next:"legend"});try{O.apply(E=R.call(x.childNodes),x.childNodes),E[x.childNodes.length].nodeType}catch(e){O={apply:E.length?function(e,t){N.apply(e,R.call(t))}:function(e,t){for(var f=e.length,a=0;e[f++]=t[a++];);e.length=f-1}}}function ie(e,t,f,a){var n,o,s,c,i,_,l,h=t&&t.ownerDocument,m=t?t.nodeType:9;if(f=f||[],"string"!=typeof e||!e||1!==m&&9!==m&&11!==m)return f;if(!a&&((t?t.ownerDocument||t:x)!==p&&g(t),t=t||p,y)){if(11!==m&&(i=te.exec(e)))if(n=i[1]){if(9===m){if(!(s=t.getElementById(n)))return f;if(s.id===n)return f.push(s),f}else if(h&&(s=h.getElementById(n))&&M(t,s)&&s.id===n)return f.push(s),f}else{if(i[2])return O.apply(f,t.getElementsByTagName(e)),f;if((n=i[3])&&r.getElementsByClassName&&t.getElementsByClassName)return O.apply(f,t.getElementsByClassName(n)),f}if(r.qsa&&!j[e+" "]&&(!v||!v.test(e))){if(1!==m)h=t,l=e;else if("object"!==t.nodeName.toLowerCase()){for((c=t.getAttribute("id"))?c=c.replace(oe,re):t.setAttribute("id",c=L),o=(_=u(e)).length;o--;)_[o]="#"+c+" "+we(_[o]);l=_.join(","),h=fe.test(e)&&ye(t.parentNode)||t}if(l)try{return O.apply(f,h.querySelectorAll(l)),f}catch(e){}finally{c===L&&t.removeAttribute("id")}}}return d(e.replace(W,"$1"),t,f,a)}function ue(){var e=[];return function t(f,a){return e.push(f+" ")>s.cacheLength&&delete t[e.shift()],t[f+" "]=a}}function _e(e){return e[L]=!0,e}function de(e){var t=p.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function le(e,t){for(var f=e.split("|"),a=f.length;a--;)s.attrHandle[f[a]]=t}function he(e,t){var f=t&&e,a=f&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(a)return a;if(f)for(;f=f.nextSibling;)if(f===t)return-1;return e?1:-1}function me(e){return function(t){return"input"===t.nodeName.toLowerCase()&&t.type===e}}function ge(e){return function(t){var f=t.nodeName.toLowerCase();return("input"===f||"button"===f)&&t.type===e}}function pe(e){return function(t){return"form"in t?t.parentNode&&!1===t.disabled?"label"in t?"label"in t.parentNode?t.parentNode.disabled===e:t.disabled===e:t.isDisabled===e||t.isDisabled!==!e&&ce(t)===e:t.disabled===e:"label"in t&&t.disabled===e}}function be(e){return _e(function(t){return t=+t,_e(function(f,a){for(var n,o=e([],f.length,t),r=o.length;r--;)f[n=o[r]]&&(f[n]=!(a[n]=f[n]))})})}function ye(e){return e&&void 0!==e.getElementsByTagName&&e}for(o in r=ie.support={},i=ie.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return!!t&&"HTML"!==t.nodeName},g=ie.setDocument=function(e){var t,f,a=e?e.ownerDocument||e:x;return a!==p&&9===a.nodeType&&a.documentElement?(b=(p=a).documentElement,y=!i(p),x!==p&&(f=p.defaultView)&&f.top!==f&&(f.addEventListener?f.addEventListener("unload",se,!1):f.attachEvent&&f.attachEvent("onunload",se)),r.attributes=de(function(e){return e.className="i",!e.getAttribute("className")}),r.getElementsByTagName=de(function(e){return e.appendChild(p.createComment("")),!e.getElementsByTagName("*").length}),r.getElementsByClassName=ee.test(p.getElementsByClassName),r.getById=de(function(e){return b.appendChild(e).id=L,!p.getElementsByName||!p.getElementsByName(L).length}),r.getById?(s.filter.ID=function(e){var t=e.replace(ae,ne);return function(e){return e.getAttribute("id")===t}},s.find.ID=function(e,t){if(void 0!==t.getElementById&&y){var f=t.getElementById(e);return f?[f]:[]}}):(s.filter.ID=function(e){var t=e.replace(ae,ne);return function(e){var f=void 0!==e.getAttributeNode&&e.getAttributeNode("id");return f&&f.value===t}},s.find.ID=function(e,t){if(void 0!==t.getElementById&&y){var f,a,n,o=t.getElementById(e);if(o){if((f=o.getAttributeNode("id"))&&f.value===e)return[o];for(n=t.getElementsByName(e),a=0;o=n[a++];)if((f=o.getAttributeNode("id"))&&f.value===e)return[o]}return[]}}),s.find.TAG=r.getElementsByTagName?function(e,t){return void 0!==t.getElementsByTagName?t.getElementsByTagName(e):r.qsa?t.querySelectorAll(e):void 0}:function(e,t){var f,a=[],n=0,o=t.getElementsByTagName(e);if("*"===e){for(;f=o[n++];)1===f.nodeType&&a.push(f);return a}return o},s.find.CLASS=r.getElementsByClassName&&function(e,t){if(void 0!==t.getElementsByClassName&&y)return t.getElementsByClassName(e)},w=[],v=[],(r.qsa=ee.test(p.querySelectorAll))&&(de(function(e){b.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+z+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+z+"*(?:value|"+P+")"),e.querySelectorAll("[id~="+L+"-]").length||v.push("~="),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+L+"+*").length||v.push(".#.+[+~]")}),de(function(e){e.innerHTML="";var t=p.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+z+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),b.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(r.matchesSelector=ee.test(k=b.matches||b.webkitMatchesSelector||b.mozMatchesSelector||b.oMatchesSelector||b.msMatchesSelector))&&de(function(e){r.disconnectedMatch=k.call(e,"*"),k.call(e,"[s!='']:x"),w.push("!=",q)}),v=v.length&&new RegExp(v.join("|")),w=w.length&&new RegExp(w.join("|")),t=ee.test(b.compareDocumentPosition),M=t||ee.test(b.contains)?function(e,t){var f=9===e.nodeType?e.documentElement:e,a=t&&t.parentNode;return e===a||!(!a||1!==a.nodeType||!(f.contains?f.contains(a):e.compareDocumentPosition&&16&e.compareDocumentPosition(a)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1},A=t?function(e,t){if(e===t)return m=!0,0;var f=!e.compareDocumentPosition-!t.compareDocumentPosition;return f||(1&(f=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!r.sortDetached&&t.compareDocumentPosition(e)===f?e===p||e.ownerDocument===x&&M(x,e)?-1:t===p||t.ownerDocument===x&&M(x,t)?1:h?I(h,e)-I(h,t):0:4&f?-1:1)}:function(e,t){if(e===t)return m=!0,0;var f,a=0,n=e.parentNode,o=t.parentNode,r=[e],s=[t];if(!n||!o)return e===p?-1:t===p?1:n?-1:o?1:h?I(h,e)-I(h,t):0;if(n===o)return he(e,t);for(f=e;f=f.parentNode;)r.unshift(f);for(f=t;f=f.parentNode;)s.unshift(f);for(;r[a]===s[a];)a++;return a?he(r[a],s[a]):r[a]===x?-1:s[a]===x?1:0},p):p},ie.matches=function(e,t){return ie(e,null,null,t)},ie.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&g(e),t=t.replace(V,"='$1']"),r.matchesSelector&&y&&!j[t+" "]&&(!w||!w.test(t))&&(!v||!v.test(t)))try{var f=k.call(e,t);if(f||r.disconnectedMatch||e.document&&11!==e.document.nodeType)return f}catch(e){}return ie(t,p,null,[e]).length>0},ie.contains=function(e,t){return(e.ownerDocument||e)!==p&&g(e),M(e,t)},ie.attr=function(e,t){(e.ownerDocument||e)!==p&&g(e);var f=s.attrHandle[t.toLowerCase()],a=f&&C.call(s.attrHandle,t.toLowerCase())?f(e,t,!y):void 0;return void 0!==a?a:r.attributes||!y?e.getAttribute(t):(a=e.getAttributeNode(t))&&a.specified?a.value:null},ie.escape=function(e){return(e+"").replace(oe,re)},ie.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},ie.uniqueSort=function(e){var t,f=[],a=0,n=0;if(m=!r.detectDuplicates,h=!r.sortStable&&e.slice(0),e.sort(A),m){for(;t=e[n++];)t===e[n]&&(a=f.push(n));for(;a--;)e.splice(f[a],1)}return h=null,e},c=ie.getText=function(e){var t,f="",a=0,n=e.nodeType;if(n){if(1===n||9===n||11===n){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)f+=c(e)}else if(3===n||4===n)return e.nodeValue}else for(;t=e[a++];)f+=c(t);return f},(s=ie.selectors={cacheLength:50,createPseudo:_e,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(ae,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(ae,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||ie.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&ie.error(e[0]),e},PSEUDO:function(e){var t,f=!e[6]&&e[2];return X.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":f&&G.test(f)&&(t=u(f,!0))&&(t=f.indexOf(")",f.length-t)-f.length)&&(e[0]=e[0].slice(0,t),e[2]=f.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(ae,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=D[e+" "];return t||(t=new RegExp("(^|"+z+")"+e+"("+z+"|$)"))&&D(e,function(e){return t.test("string"==typeof e.className&&e.className||void 0!==e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,t,f){return function(a){var n=ie.attr(a,e);return null==n?"!="===t:!t||(n+="","="===t?n===f:"!="===t?n!==f:"^="===t?f&&0===n.indexOf(f):"*="===t?f&&n.indexOf(f)>-1:"$="===t?f&&n.slice(-f.length)===f:"~="===t?(" "+n.replace(U," ")+" ").indexOf(f)>-1:"|="===t&&(n===f||n.slice(0,f.length+1)===f+"-"))}},CHILD:function(e,t,f,a,n){var o="nth"!==e.slice(0,3),r="last"!==e.slice(-4),s="of-type"===t;return 1===a&&0===n?function(e){return!!e.parentNode}:function(t,f,c){var i,u,_,d,l,h,m=o!==r?"nextSibling":"previousSibling",g=t.parentNode,p=s&&t.nodeName.toLowerCase(),b=!c&&!s,y=!1;if(g){if(o){for(;m;){for(d=t;d=d[m];)if(s?d.nodeName.toLowerCase()===p:1===d.nodeType)return!1;h=m="only"===e&&!h&&"nextSibling"}return!0}if(h=[r?g.firstChild:g.lastChild],r&&b){for(y=(l=(i=(u=(_=(d=g)[L]||(d[L]={}))[d.uniqueID]||(_[d.uniqueID]={}))[e]||[])[0]===S&&i[1])&&i[2],d=l&&g.childNodes[l];d=++l&&d&&d[m]||(y=l=0)||h.pop();)if(1===d.nodeType&&++y&&d===t){u[e]=[S,l,y];break}}else if(b&&(y=l=(i=(u=(_=(d=t)[L]||(d[L]={}))[d.uniqueID]||(_[d.uniqueID]={}))[e]||[])[0]===S&&i[1]),!1===y)for(;(d=++l&&d&&d[m]||(y=l=0)||h.pop())&&((s?d.nodeName.toLowerCase()!==p:1!==d.nodeType)||!++y||(b&&((u=(_=d[L]||(d[L]={}))[d.uniqueID]||(_[d.uniqueID]={}))[e]=[S,y]),d!==t)););return(y-=n)===a||y%a==0&&y/a>=0}}},PSEUDO:function(e,t){var f,a=s.pseudos[e]||s.setFilters[e.toLowerCase()]||ie.error("unsupported pseudo: "+e);return a[L]?a(t):a.length>1?(f=[e,e,"",t],s.setFilters.hasOwnProperty(e.toLowerCase())?_e(function(e,f){for(var n,o=a(e,t),r=o.length;r--;)e[n=I(e,o[r])]=!(f[n]=o[r])}):function(e){return a(e,0,f)}):a}},pseudos:{not:_e(function(e){var t=[],f=[],a=_(e.replace(W,"$1"));return a[L]?_e(function(e,t,f,n){for(var o,r=a(e,null,n,[]),s=e.length;s--;)(o=r[s])&&(e[s]=!(t[s]=o))}):function(e,n,o){return t[0]=e,a(t,null,o,f),t[0]=null,!f.pop()}}),has:_e(function(e){return function(t){return ie(e,t).length>0}}),contains:_e(function(e){return e=e.replace(ae,ne),function(t){return(t.textContent||t.innerText||c(t)).indexOf(e)>-1}}),lang:_e(function(e){return Q.test(e||"")||ie.error("unsupported lang: "+e),e=e.replace(ae,ne).toLowerCase(),function(t){var f;do{if(f=y?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return(f=f.toLowerCase())===e||0===f.indexOf(e+"-")}while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(e){var t=n.location&&n.location.hash;return t&&t.slice(1)===e.id},root:function(e){return e===b},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:pe(!1),disabled:pe(!0),checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!s.pseudos.empty(e)},header:function(e){return Z.test(e.nodeName)},input:function(e){return K.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:be(function(){return[0]}),last:be(function(e,t){return[t-1]}),eq:be(function(e,t,f){return[f<0?f+t:f]}),even:be(function(e,t){for(var f=0;f=0;)e.push(a);return e}),gt:be(function(e,t,f){for(var a=f<0?f+t:f;++a1?function(t,f,a){for(var n=e.length;n--;)if(!e[n](t,f,a))return!1;return!0}:e[0]}function Le(e,t,f,a,n){for(var o,r=[],s=0,c=e.length,i=null!=t;s-1&&(o[i]=!(r[i]=_))}}else p=Le(p===r?p.splice(h,p.length):p),n?n(null,r,p,c):O.apply(r,p)})}function Se(e){for(var t,f,a,n=e.length,o=s.relative[e[0].type],r=o||s.relative[" "],c=o?1:0,i=ke(function(e){return e===t},r,!0),u=ke(function(e){return I(t,e)>-1},r,!0),_=[function(e,f,a){var n=!o&&(a||f!==l)||((t=f).nodeType?i(e,f,a):u(e,f,a));return t=null,n}];c1&&Me(_),c>1&&we(e.slice(0,c-1).concat({value:" "===e[c-2].type?"*":""})).replace(W,"$1"),f,c0,a=e.length>0,n=function(n,o,r,c,i){var u,_,d,h=0,m="0",b=n&&[],v=[],w=l,k=n||a&&s.find.TAG("*",i),M=S+=null==w?1:Math.random()||.1,L=k.length;for(i&&(l=o===p||o||i);m!==L&&null!=(u=k[m]);m++){if(a&&u){for(_=0,o||u.ownerDocument===p||(g(u),r=!y);d=e[_++];)if(d(u,o||p,r)){c.push(u);break}i&&(S=M)}f&&((u=!d&&u)&&h--,n&&b.push(u))}if(h+=m,f&&m!==h){for(_=0;d=t[_++];)d(b,v,o,r);if(n){if(h>0)for(;m--;)b[m]||v[m]||(v[m]=H.call(c));v=Le(v)}O.apply(c,v),i&&!n&&v.length>0&&h+t.length>1&&ie.uniqueSort(c)}return i&&(S=M,l=w),b};return f?_e(n):n}(n,a))).selector=e}return o},d=ie.select=function(e,t,f,a){var n,o,r,c,i,d="function"==typeof e&&e,l=!a&&u(e=d.selector||e);if(f=f||[],1===l.length){if((o=l[0]=l[0].slice(0)).length>2&&"ID"===(r=o[0]).type&&9===t.nodeType&&y&&s.relative[o[1].type]){if(!(t=(s.find.ID(r.matches[0].replace(ae,ne),t)||[])[0]))return f;d&&(t=t.parentNode),e=e.slice(o.shift().value.length)}for(n=X.needsContext.test(e)?0:o.length;n--&&(r=o[n],!s.relative[c=r.type]);)if((i=s.find[c])&&(a=i(r.matches[0].replace(ae,ne),fe.test(o[0].type)&&ye(t.parentNode)||t))){if(o.splice(n,1),!(e=a.length&&we(o)))return O.apply(f,a),f;break}}return(d||_(e,l))(a,t,!y,f,!t||fe.test(e)&&ye(t.parentNode)||t),f},r.sortStable=L.split("").sort(A).join("")===L,r.detectDuplicates=!!m,g(),r.sortDetached=de(function(e){return 1&e.compareDocumentPosition(p.createElement("fieldset"))}),de(function(e){return e.innerHTML="","#"===e.firstChild.getAttribute("href")})||le("type|href|height|width",function(e,t,f){if(!f)return e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),r.attributes&&de(function(e){return e.innerHTML="",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||le("value",function(e,t,f){if(!f&&"input"===e.nodeName.toLowerCase())return e.defaultValue}),de(function(e){return null==e.getAttribute("disabled")})||le(P,function(e,t,f){var a;if(!f)return!0===e[t]?t.toLowerCase():(a=e.getAttributeNode(t))&&a.specified?a.value:null});var Te=n.Sizzle;ie.noConflict=function(){return n.Sizzle===ie&&(n.Sizzle=Te),ie},void 0===(a=function(){return ie}.call(t,f,t,e))||(e.exports=a)}(window)},function(e,t,f){"use strict";var a,n,o;n=[f(2),f(12),f(158),f(223),f(222),f(203),f(221),f(3),f(220),f(211)],void 0===(o="function"==typeof(a=function(e,t,f,a,n,o,r){const s=e.env,c=s.Strophe,i=s.Backbone,u=s.Promise,_=s._,d=s.moment,l=e.env.utils,h={Error:"error",Connecting:"info","Connection failure":"error",Authenticating:"info","Authentication failure":"error",Connected:"info",Disconnected:"error",Disconnecting:"warn",Attached:"info",Redirect:"info",Reconnecting:"warn"},m={0:"Error",1:"Connecting",2:"Connection failure",3:"Authenticating",4:"Authentication failure",5:"Connected",6:"Disconnected",7:"Disconnecting",8:"Attached",9:"Redirect",10:"Reconnecting"},g=[0,1,2,3,4,7,10];e.plugins.add("converse-controlbox",{dependencies:["converse-modal","converse-chatboxes","converse-rosterview","converse-chatview"],overrides:{_tearDown(){this.__super__._tearDown.apply(this,arguments),this.rosterview&&(this.rosterview.model.off().reset(),this.rosterview.each(function(e){e.removeAll(),e.remove()}),this.rosterview.removeAll().remove())},ChatBoxes:{chatBoxMayBeShown(e){return this.__super__.chatBoxMayBeShown.apply(this,arguments)&&"controlbox"!==e.get("id")}},ChatBoxViews:{onChatBoxAdded(e){const t=this.__super__._converse;if("controlbox"===e.get("box_id")){let f=this.get(e.get("id"));return f?(f.model=e,f.initialize(),f):(f=new t.ControlBoxView({model:e}),this.add(e.get("id"),f))}return this.__super__.onChatBoxAdded.apply(this,arguments)},closeAllChatBoxes(){const e=this.__super__._converse;return this.each(function(t){("controlbox"!==t.model.get("id")||e.disconnection_cause===e.LOGOUT&&!e.show_controlbox_by_default)&&t.close()}),this},getChatBoxWidth(e){const t=this.__super__._converse,f=this.get("controlbox");return"controlbox"===e.model.get("id")?f&&l.isVisible(f.el)?l.getOuterWidth(f.el,!0):l.getOuterWidth(t.controlboxtoggle.el,!0):this.__super__.getChatBoxWidth.apply(this,arguments)}},ChatBox:{initialize(){"controlbox"===this.get("id")?this.set({time_opened:d(0).valueOf()}):this.__super__.initialize.apply(this,arguments)}},ChatBoxView:{insertIntoDOM(){const e=this.__super__._converse.chatboxviews.get("controlbox");return e?e.el.insertAdjacentElement("afterend",this.el):this.__super__.insertIntoDOM.apply(this,arguments),this}}},initialize(){const e=this._converse,f=e.__;e.api.settings.update({allow_logout:!0,default_domain:void 0,locked_domain:void 0,show_controlbox_by_default:!1,sticky_controlbox:!1}),e.api.promises.add("controlboxInitialized"),f("Contacts"),e.addControlBox=(()=>e.chatboxes.add({id:"controlbox",box_id:"controlbox",type:"controlbox",closed:!e.show_controlbox_by_default})),e.ControlBoxView=e.ChatBoxView.extend({tagName:"div",className:"chatbox",id:"controlbox",events:{"click a.close-chatbox-button":"close"},initialize(){_.isUndefined(e.controlboxtoggle)&&(e.controlboxtoggle=new e.ControlBoxToggle),e.controlboxtoggle.el.insertAdjacentElement("afterend",this.el),this.model.on("change:connected",this.onConnected,this),this.model.on("destroy",this.hide,this),this.model.on("hide",this.hide,this),this.model.on("show",this.show,this),this.model.on("change:closed",this.ensureClosedState,this),this.render(),this.model.get("connected")&&this.insertRoster(),e.emit("controlboxInitialized",this)},render(){return this.model.get("connected")&&_.isUndefined(this.model.get("closed"))&&this.model.set("closed",!e.show_controlbox_by_default),this.el.innerHTML=n(_.extend(this.model.toJSON())),this.model.get("closed")?this.hide():this.show(),e.connection.connected&&e.connection.authenticated&&!e.connection.disconnecting?!this.model.get("connected")||this.controlbox_pane&&l.isVisible(this.controlbox_pane.el)||this.renderControlBoxPane():this.renderLoginPanel(),this},onConnected(){this.model.get("connected")&&(this.render(),this.insertRoster())},insertRoster(){e.api.waitUntil("rosterViewInitialized").then(()=>this.controlbox_pane.el.insertAdjacentElement("beforeEnd",e.rosterview.el)).catch(_.partial(e.log,_,c.LogLevel.FATAL))},createBrandHeadingHTML:()=>a({sticky_controlbox:e.sticky_controlbox}),insertBrandHeading(){const e=this.el.querySelector(".brand-heading-container");if(_.isNull(e)){const e=this.el.querySelector(".controlbox-head");e.insertAdjacentHTML("beforeend",this.createBrandHeadingHTML())}else e.outerHTML=this.createBrandHeadingHTML()},renderLoginPanel(){if(this.el.classList.add("logged-out"),_.isNil(this.loginpanel)){this.loginpanel=new e.LoginPanel({model:new e.LoginPanelModel});const t=this.el.querySelector(".controlbox-panes");t.innerHTML="",t.appendChild(this.loginpanel.render().el),this.insertBrandHeading()}else this.loginpanel.render();return this},renderControlBoxPane(){this.loginpanel&&(this.loginpanel.remove(),delete this.loginpanel),this.el.classList.remove("logged-out"),this.controlbox_pane=new e.ControlBoxPane,this.el.querySelector(".controlbox-panes").insertAdjacentElement("afterBegin",this.controlbox_pane.el)},close(t){if(t&&t.preventDefault&&t.preventDefault(),!e.sticky_controlbox)return e.connection.connected&&!e.connection.disconnecting?this.model.save({closed:!0}):this.model.trigger("hide"),e.emit("controlBoxClosed",this),this},ensureClosedState(){this.model.get("closed")?this.hide():this.show()},hide(t){if(!e.sticky_controlbox)return l.addClass("hidden",this.el),e.emit("chatBoxClosed",this),e.connection.connected||e.controlboxtoggle.render(),e.controlboxtoggle.show(t),this},onControlBoxToggleHidden(){this.model.set("closed",!1),this.el.classList.remove("hidden"),e.emit("controlBoxOpened",this)},show(){return e.controlboxtoggle.hide(this.onControlBoxToggleHidden.bind(this)),this},showHelpMessages(){}}),e.LoginPanelModel=i.Model.extend({defaults:{errors:[]}}),e.LoginPanel=i.VDOMView.extend({tagName:"div",id:"converse-login-panel",className:"controlbox-pane fade-in",events:{"submit form#converse-login":"authenticate","change input":"validate"},initialize(f){this.model.on("change",this.render,this),this.listenTo(e.connfeedback,"change",this.render),this.render(),_.forEach(this.el.querySelectorAll("[data-title]"),f=>{new t.Popover(f,{trigger:"mobile"===e.view_mode?"click":"hover",dismissible:"mobile"===e.view_mode,container:e.chatboxviews.el})})},toHTML(){const t=e.connfeedback.get("connection_status");let a,n;return _.includes(g,t)&&(a=h[n=m[t]]),r(_.extend(this.model.toJSON(),{__:f,_converse:e,ANONYMOUS:e.ANONYMOUS,EXTERNAL:e.EXTERNAL,LOGIN:e.LOGIN,PREBIND:e.PREBIND,auto_login:e.auto_login,authentication:e.authentication,connection_status:t,conn_feedback_class:a,conn_feedback_subject:n,conn_feedback_message:e.connfeedback.get("message"),placeholder_username:(e.locked_domain||e.default_domain)&&f("Username")||f("user@domain")}))},validate(){const t=this.el.querySelector("form"),a=t.querySelector("input[name=jid]");return!a.value||e.locked_domain||e.default_domain||l.isValidJID(a.value)?(a.setCustomValidity(""),!0):(a.setCustomValidity(f("Please enter a valid XMPP address")),!1)},authenticate(t){if(t&&t.preventDefault&&t.preventDefault(),e.authentication===e.ANONYMOUS)return void this.connect(e.jid,null);if(!this.validate())return;const f=new FormData(t.target);e.trusted=f.get("trusted"),e.storage=f.get("trusted")?"local":"session";let a=f.get("jid");e.locked_domain?a=c.escapeNode(a)+"@"+e.locked_domain:e.default_domain&&!_.includes(a,"@")&&(a=a+"@"+e.default_domain),this.connect(a,f.get("password"))},connect(t,f){if(t){const f=c.getResourceFromJid(t);t=f?c.getBareJidFromJid(t).toLowerCase()+"/"+f:t.toLowerCase()+e.generateResource()}_.includes(["converse/login","converse/register"],i.history.getFragment())&&e.router.navigate("",{replace:!0}),e.connection.reset(),e.connection.connect(t,f,e.onConnectStatusChanged)}}),e.ControlBoxPane=i.NativeView.extend({tagName:"div",className:"controlbox-pane",initialize(){e.xmppstatusview=new e.XMPPStatusView({model:e.xmppstatus}),this.el.insertAdjacentElement("afterBegin",e.xmppstatusview.render().el)}}),e.ControlBoxToggle=i.NativeView.extend({tagName:"a",className:"toggle-controlbox hidden",id:"toggle-controlbox",events:{click:"onClick"},attributes:{href:"#"},initialize(){e.chatboxviews.insertRowColumn(this.render().el),e.api.waitUntil("initialized").then(this.render.bind(this)).catch(_.partial(e.log,_,c.LogLevel.FATAL))},render(){return this.el.innerHTML=o({label_toggle:e.connection.connected?f("Chat Contacts"):f("Toggle chat")}),this},hide(e){l.hideElement(this.el),e()},show(e){l.fadeIn(this.el,e)},showControlBox(){let t=e.chatboxes.get("controlbox");t||(t=e.addControlBox()),e.connection.connected?t.save({closed:!1}):t.trigger("show")},onClick(t){if(t.preventDefault(),l.isVisible(e.root.querySelector("#controlbox"))){const t=e.chatboxes.get("controlbox");e.connection.connected?t.save({closed:!0}):t.trigger("hide")}else this.showControlBox()}}),e.on("clearSession",()=>{if(e.trusted){const t=_.get(e,"chatboxes",null);if(!_.isNil(t)){const e=t.get("controlbox");e&&e.collection&&e.collection.browserStorage&&e.save({connected:!1})}}}),u.all([e.api.waitUntil("connectionInitialized"),e.api.waitUntil("chatBoxesInitialized")]).then(e.addControlBox).catch(_.partial(e.log,_,c.LogLevel.FATAL)),e.on("chatBoxesFetched",()=>{const t=e.chatboxes.get("controlbox")||e.addControlBox();t.save({connected:!0})});const s=function(){const t=e.chatboxviews.get("controlbox");t.model.set({connected:!1}),t.renderLoginPanel()};e.on("disconnected",s),e.on("will-reconnect",s)}})})?a.apply(t,n):a)||(e.exports=o)},function(e,t,f){"use strict";var a,n,o;n=[f(2),f(230),f(12),f(55)],void 0===(o="function"==typeof(a=function(e,t,f){const a=e.env,n=a.Strophe,o=a.Backbone,r=a._;e.plugins.add("converse-modal",{initialize(){const e=this._converse;let a;e.BootstrapModal=o.VDOMView.extend({initialize(){this.render().insertIntoDOM(),this.modal=new f.Modal(this.el,{backdrop:"static",keyboard:!0}),this.el.addEventListener("hide.bs.modal",e=>{r.isNil(this.trigger_el)||this.trigger_el.classList.remove("selected")},!1)},insertIntoDOM(){const t=e.chatboxviews.el.querySelector("#converse-modals");t.insertAdjacentElement("beforeEnd",this.el)},show(e){e&&(e.preventDefault(),this.trigger_el=e.target,this.trigger_el.classList.add("selected")),this.modal.show()}}),e.Alert=e.BootstrapModal.extend({initialize(){e.BootstrapModal.prototype.initialize.apply(this,arguments),this.model.on("change",this.render,this)},toHTML(){return t(this.model.toJSON())}}),r.extend(e.api,{alert:{show(t,f,s){if(r.isString(s)&&(s=[s]),t===n.LogLevel.ERROR?t="alert-danger":t===n.LogLevel.INFO?t="alert-info":t===n.LogLevel.WARN&&(t="alert-warning"),r.isUndefined(a)){const n=new o.Model({title:f,messages:s,type:t});a=new e.Alert({model:n})}else a.model.set({title:f,messages:s,type:t});a.show()}}})}})})?a.apply(t,n):a)||(e.exports=o)},function(e,t,f){(function(f){var a,n,o;n=[],void 0===(o="function"==typeof(a=function(){"use strict";var e=void 0!==f?f:this||window,t=document,a=t.documentElement,n=e.BSN={},o=n.supports=[],r="data-toggle",s="active",c="left",i="top",u="onmouseleave"in t?["mouseenter","mouseleave"]:["mouseover","mouseout"],_=/\b(top|bottom|left|right)+/,d=0,l="WebkitTransition"in a.style||"Transition".toLowerCase()in a.style,h="WebkitTransition"in a.style?"Webkit".toLowerCase()+"TransitionEnd":"Transition".toLowerCase()+"end",m=function(e){e.focus?e.focus():e.setActive()},g=function(e,t){e.classList.add(t)},p=function(e,t){e.classList.remove(t)},b=function(e,t){return e.classList.contains(t)},y=function(e,t){return[].slice.call(e.getElementsByClassName(t))},v=function(e,f){var a=f||t;return"object"==typeof e?e:a.querySelector(e)},w=function(e,f){var a=f.charAt(0),n=f.substr(1);if("."===a){for(;e&&e!==t;e=e.parentNode)if(null!==v(f,e.parentNode)&&b(e,n))return e}else if("#"===a)for(;e&&e!==t;e=e.parentNode)if(e.id===n)return e;return!1},k=function(e,t,f){e.addEventListener(t,f,!1)},M=function(e,t,f){e.removeEventListener(t,f,!1)},L=function(e,t,f){k(e,t,function a(n){f(n),M(e,t,a)})},x=function(e,t){l?L(e,h,function(e){t(e)}):t()},S=function(e,t,f){var a=new CustomEvent(e+".bs."+t);a.relatedTarget=f,this.dispatchEvent(a)},T=function(){return{y:e.pageYOffset||a.scrollTop,x:e.pageXOffset||a.scrollLeft}},D=function(e,f,n,o){var r,s,u,d,l,h,m={w:f.offsetWidth,h:f.offsetHeight},g=a.clientWidth||t.body.clientWidth,p=a.clientHeight||t.body.clientHeight,y=e.getBoundingClientRect(),w=o===t.body?T():{x:o.offsetLeft+o.scrollLeft,y:o.offsetTop+o.scrollTop},k={w:y.right-y.left,h:y.bottom-y.top},M=b(f,"popover"),L=v(".arrow",f),x=y.top+k.h/2-m.h/2<0,S=y.left+k.w/2-m.w/2<0,D=y.left+m.w/2+k.w/2>=g,Y=y.top+m.h/2+k.h/2>=p,j=y.top-m.h<0,A=y.left-m.w<0,C=y.top+m.h+k.h>=p,E=y.left+m.w+k.w>=g;n="right"===(n=(n="bottom"===(n=(n=(n===c||"right"===n)&&A&&E?i:n)===i&&j?"bottom":n)&&C?i:n)===c&&A?"right":n)&&E?c:n,-1===f.className.indexOf(n)&&(f.className=f.className.replace(_,n)),l=L.offsetWidth,h=L.offsetHeight,n===c||"right"===n?(s=n===c?y.left+w.x-m.w-(M?l:0):y.left+w.x+k.w,x?(r=y.top+w.y,u=k.h/2-l):Y?(r=y.top+w.y-m.h+k.h,u=m.h-k.h/2-l):(r=y.top+w.y-m.h/2+k.h/2,u=m.h/2-(M?.9*h:h/2))):n!==i&&"bottom"!==n||(r=n===i?y.top+w.y-m.h-(M?h:0):y.top+w.y+k.h,S?(s=0,d=y.left+k.w/2-l):D?(s=g-1.01*m.w,d=m.w-(g-y.left)+k.w/2-l/2):(s=y.left+w.x-m.w/2+k.w/2,d=m.w/2-l/2)),f.style.top=r+"px",f.style.left=s+"px",u&&(L.style.top=u+"px"),d&&(L.style.left=d+"px")};n.version="2.0.22";var Y=function(e){e=v(e);var t=this,f=w(e,".alert"),a=function(a){f=w(a.target,".alert"),(e=v('[data-dismiss="alert"]',f))&&f&&(e===a.target||e.contains(a.target))&&t.close()},n=function(){S.call(f,"closed","alert"),M(e,"click",a),f.parentNode.removeChild(f)};this.close=function(){f&&e&&b(f,"show")&&(S.call(f,"close","alert"),p(f,"show"),f&&(b(f,"fade")?x(f,n):n()))},"Alert"in e||k(e,"click",a),e.Alert=t};o.push(["Alert",Y,'[data-dismiss="alert"]']);var j=function(e){var f=!1,a="checked",n=function(t){var n="LABEL"===t.target.tagName?t.target:"LABEL"===t.target.parentNode.tagName?t.target.parentNode:null;if(n){var o=t.target,r=y(o.parentNode,"btn"),c=n.getElementsByTagName("INPUT")[0];if(c){if("checkbox"===c.type&&(c.checked?(p(n,s),c.getAttribute(a),c.removeAttribute(a),c.checked=!1):(g(n,s),c.getAttribute(a),c.setAttribute(a,a),c.checked=!0),f||(f=!0,S.call(c,"change","button"),S.call(e,"change","button"))),"radio"===c.type&&!f&&!c.checked){g(n,s),c.setAttribute(a,a),c.checked=!0,S.call(c,"change","button"),S.call(e,"change","button"),f=!0;for(var i=0,u=r.length;i=0&&(w++,m.slideTo(w))},this.interval)},this.slideTo=function(e){if(!x){var a,n=this.getActiveIndex();ne||n===D-1&&0===e)&&(Y=m.direction="right"),e<0?e=D-1:e===D&&(e=0),w=e,a=Y===c?"next":"prev",S.call(f,"slide","carousel",T[e]),x=!0,clearInterval(M),R(e),l&&b(f,"slide")?(g(T[e],"carousel-item-"+a),T[e].offsetWidth,g(T[e],"carousel-item-"+Y),g(T[n],"carousel-item-"+Y),L(T[n],h,function(o){var r=o.target!==T[n]?1e3*o.elapsedTime:0;setTimeout(function(){x=!1,g(T[e],s),p(T[n],s),p(T[e],"carousel-item-"+a),p(T[e],"carousel-item-"+Y),p(T[n],"carousel-item-"+Y),S.call(f,"slid","carousel",T[e]),t.hidden||!m.interval||b(f,"paused")||m.cycle()},r+100)})):(g(T[e],s),T[e].offsetWidth,p(T[n],s),setTimeout(function(){x=!1,m.interval&&!b(f,"paused")&&m.cycle(),S.call(f,"slid","carousel",T[e])},100))}},this.getActiveIndex=function(){return T.indexOf(y(f,"carousel-item active")[0])||0},"Carousel"in f||(m.pause&&m.interval&&(k(f,u[0],H),k(f,u[1],N),k(f,"touchstart",H),k(f,"touchend",N)),A&&k(A,"click",O),j&&k(j,"click",O),C&&k(C,"click",function(e){if(e.preventDefault(),!x){var t=e.target;if(!t||b(t,s)||!t.getAttribute("data-slide-to"))return!1;w=parseInt(t.getAttribute("data-slide-to"),10),m.slideTo(w)}}),!0===m.keyboard&&k(e,"keydown",function(e){if(!x){switch(e.which){case 39:w++;break;case 37:w--;break;default:return}m.slideTo(w)}})),m.getActiveIndex()<0&&(T.length&&g(T[0],s),E.length&&R(0)),m.interval&&m.cycle(),f.Carousel=m};o.push(["Carousel",A,'[data-ride="carousel"]']);var C=function(e,t){e=v(e),t=t||{};var f,a,n,o=null,r=null,s=this,c=!1,i=e.getAttribute("data-parent"),u=function(e,t){S.call(e,"hide","collapse"),c=!0,e.style.height=e.scrollHeight+"px",p(e,"collapse"),p(e,"show"),g(e,"collapsing"),e.offsetWidth,e.style.height="0px",x(e,function(){c=!1,e.setAttribute("aria-expanded","false"),t.setAttribute("aria-expanded","false"),p(e,"collapsing"),g(e,"collapse"),e.style.height="",S.call(e,"hidden","collapse")})};this.toggle=function(e){e.preventDefault(),c||(b(r,"show")?s.hide():s.show())},this.hide=function(){u(r,e),g(e,"collapsed")},this.show=function(){if(o){var t=v(".collapse.show",o),f=t&&(v('[data-toggle="collapse"][data-target="#'+t.id+'"]',o)||v('[data-toggle="collapse"][href="#'+t.id+'"]',o)),a=f&&(f.getAttribute("data-target")||f.href);t&&f&&t!==r&&(u(t,f),a.split("#")[1]!==r.id?g(f,"collapsed"):p(f,"collapsed"))}!function(e,t){S.call(e,"show","collapse"),c=!0,g(e,"collapsing"),p(e,"collapse"),e.style.height=e.scrollHeight+"px",x(e,function(){c=!1,e.setAttribute("aria-expanded","true"),t.setAttribute("aria-expanded","true"),p(e,"collapsing"),g(e,"collapse"),g(e,"show"),e.style.height="",S.call(e,"shown","collapse")})}(r,e),p(e,"collapsed")},"Collapse"in e||k(e,"click",s.toggle),f=e.href&&e.getAttribute("href"),a=e.getAttribute("data-target"),n=f||a&&"#"===a.charAt(0)&&a,r=n&&v(n),o=v(t.parent)||i&&w(e,i),e.Collapse=s};o.push(["Collapse",C,'[data-toggle="collapse"]']);var E=function(e,f){e=v(e),this.persist=!0===f||"true"===e.getAttribute("data-persist")||!1;var a=this,n=e.parentNode,o=null,r=v(".dropdown-menu",n),s=function(){for(var e=r.children,t=[],f=0;f1?i-1:0:40===n&&ia.clientHeight,(o=t.createElement("div")).className="modal-scrollbar-measure",t.body.appendChild(o),n=o.offsetWidth-o.clientWidth,t.body.removeChild(o),u=n},Y=function(){s.style.paddingLeft=!c&&i?u+"px":"",s.style.paddingRight=c&&!i?u+"px":""},j=function(){(_=v(".modal-backdrop"))&&null!==_&&"object"==typeof _&&(d=0,t.body.removeChild(_),_=null),S.call(s,"hidden","modal")},A=function(){b(s,"show")?k(t,"keydown",O):M(t,"keydown",O)},C=function(){b(s,"show")?k(e,"resize",h.update):M(e,"resize",h.update)},E=function(){b(s,"show")?k(s,"click",R):M(s,"click",R)},H=function(){m(s),S.call(s,"shown","modal",w)},N=function(){s.style.display="",f&&m(f),y(t,"modal show")[0]||(s.style.paddingLeft="",s.style.paddingRight="",function(){if(t.body.style.paddingRight="",L.length)for(var e=0;e×',l=v(a.container),h=v(_),m=w(f,".modal"),y=w(f,".fixed-top"),L=w(f,".fixed-bottom");this.template=a.template?a.template:null,this.trigger=a.trigger?a.trigger:n||"hover",this.animation=a.animation&&"fade"!==a.animation?a.animation:o||"fade",this.placement=a.placement?a.placement:r||i,this.delay=parseInt(a.delay||c)||200,this.dismissible=!(!a.dismissible&&"true"!==s),this.container=l||h||y||L||m||t.body;var T=this,Y=f.getAttribute("data-title")||null,j=f.getAttribute("data-content")||null;if(j||this.template){var A=null,C=0,E=this.placement,H=function(e){null!==A&&e.target===v(".close",A)&&T.hide()},N=function(a){"click"!=T.trigger&&"focus"!=T.trigger||!T.dismissible&&a(f,"blur",T.hide),T.dismissible&&a(t,"click",H),a(e,"resize",T.hide)},O=function(){N(k),S.call(f,"shown","popover")},R=function(){N(M),T.container.removeChild(A),C=null,A=null,S.call(f,"hidden","popover")};this.toggle=function(){null===A?T.show():T.hide()},this.show=function(){clearTimeout(C),C=setTimeout(function(){null===A&&(E=T.placement,function(){Y=f.getAttribute("data-title"),j=f.getAttribute("data-content"),A=t.createElement("div");var e=t.createElement("div");if(e.setAttribute("class","arrow"),A.appendChild(e),null!==j&&null===T.template){if(A.setAttribute("role","tooltip"),null!==Y){var a=t.createElement("h3");a.setAttribute("class","popover-header"),a.innerHTML=T.dismissible?Y+d:Y,A.appendChild(a)}var n=t.createElement("div");n.setAttribute("class","popover-body"),n.innerHTML=T.dismissible&&null===Y?j+d:j,A.appendChild(n)}else{var o=t.createElement("div");o.innerHTML=T.template,A.innerHTML=o.firstChild.innerHTML}T.container.appendChild(A),A.style.display="block",A.setAttribute("class","popover bs-popover-"+E+" "+T.animation)}(),D(f,A,E,T.container),!b(A,"show")&&g(A,"show"),S.call(f,"show","popover"),T.animation?x(A,O):O())},20)},this.hide=function(){clearTimeout(C),C=setTimeout(function(){A&&null!==A&&b(A,"show")&&(S.call(f,"hide","popover"),p(A,"show"),T.animation?x(A,R):R())},T.delay)},"Popover"in f||("hover"===T.trigger?(k(f,u[0],T.show),T.dismissible||k(f,u[1],T.hide)):"click"!=T.trigger&&"focus"!=T.trigger||k(f,T.trigger,T.toggle)),f.Popover=T}};o.push(["Popover",N,'[data-toggle="popover"]']);var O=function(t,f){t=v(t);var a=v(t.getAttribute("data-target")),n=t.getAttribute("data-offset");if((f=f||{}).target||a){for(var o,r=f.target&&v(f.target)||a,c=r&&r.getElementsByTagName("A"),i=parseInt(n||f.offset)||10,u=[],_=[],d=t.offsetHeight=h&&m>o;if(!d&&v)b(f,s)||(g(f,s),r&&!b(r,s)&&g(r,s),S.call(t,"activate","scrollspy",u[e]));else if(v){if(!v&&!d||d&&v)return}else b(f,s)&&(p(f,s),r&&b(r,s)&&!y(f.parentNode,s).length&&p(r,s))};this.refresh=function(){!function(){o=l?T().y:t.scrollTop;for(var e=0,f=u.length;e1&&(e=t[t.length-1]):e=t[0],e},A=function(){return v(j().getAttribute("href"))};this.show=function(){i=v((a=a||e).getAttribute("href")),n=j(),o=A(),m.isAnimating=!0,p(n,s),g(a,s),L&&(b(e.parentNode,"dropdown-menu")?b(L,s)||g(L,s):b(L,s)&&p(L,s)),S.call(n,"hide","tab",a),b(o,"fade")?(p(o,"show"),x(o,Y)):Y()},"Tab"in e||k(e,"click",function(e){var t=e.target.getAttribute("href");e.preventDefault(),a="tab"===e.target.getAttribute(r)||t&&"#"===t.charAt(0)?e.target:e.target.parentNode,!m.isAnimating&&!b(a,s)&&h.show()}),h.height&&(M=A().parentNode),e.Tab=h}};o.push(["Tab",R,'[data-toggle="tab"]']);var I=function(f,a){f=v(f),a=a||{};var n=f.getAttribute("data-animation"),o=f.getAttribute("data-placement"),r=f.getAttribute("data-delay"),s=f.getAttribute("data-container"),c=v(a.container),_=v(s),d=w(f,".modal"),l=w(f,".fixed-top"),h=w(f,".fixed-bottom");this.animation=a.animation&&"fade"!==a.animation?a.animation:n||"fade",this.placement=a.placement?a.placement:o||i,this.delay=parseInt(a.delay||r)||200,this.container=c||_||l||h||d||t.body;var m=this,y=0,L=this.placement,T=null,Y=f.getAttribute("title")||f.getAttribute("data-title")||f.getAttribute("data-original-title");if(Y&&""!=Y){var j=function(){k(e,"resize",m.hide),S.call(f,"shown","tooltip")},A=function(){M(e,"resize",m.hide),m.container.removeChild(T),T=null,y=null,S.call(f,"hidden","tooltip")};this.show=function(){clearTimeout(y),y=setTimeout(function(){if(null===T){if(L=m.placement,0==function(){if(!(Y=f.getAttribute("title")||f.getAttribute("data-title")||f.getAttribute("data-original-title"))||""==Y)return!1;(T=t.createElement("div")).setAttribute("role","tooltip");var e=t.createElement("div");e.setAttribute("class","arrow"),T.appendChild(e);var a=t.createElement("div");a.setAttribute("class","tooltip-inner"),T.appendChild(a),a.innerHTML=Y,m.container.appendChild(T),T.setAttribute("class","tooltip bs-tooltip-"+L+" "+m.animation)}())return;D(f,T,L,m.container),!b(T,"show")&&g(T,"show"),S.call(f,"show","tooltip"),m.animation?x(T,j):j()}},20)},this.hide=function(){clearTimeout(y),y=setTimeout(function(){T&&b(T,"show")&&(S.call(f,"hide","tooltip"),p(T,"show"),m.animation?x(T,A):A())},m.delay)},this.toggle=function(){T?m.hide():m.show()},"Tooltip"in f||(f.setAttribute("data-original-title",Y),f.removeAttribute("title"),k(f,u[0],m.show),k(f,u[1],m.hide)),f.Tooltip=m}};o.push(["Tooltip",I,'[data-toggle="tooltip"]']);var P=function(e,t){for(var f=0,a=t.length;f:-)":"1f606","':-(":"1f613",">:-(":"1f620",":'-(":"1f622","O:-)":"1f607","0:-3":"1f607","0:-)":"1f607","0;^)":"1f607","O;-)":"1f607","0;-)":"1f607","O:-3":"1f607","-__-":"1f611",":-Þ":"1f61b",":)":"1f606",">;)":"1f606",">=)":"1f606",";-)":"1f609","*-)":"1f609",";-]":"1f609",";^)":"1f609","':(":"1f613","'=(":"1f613",":-*":"1f618",":^*":"1f618",">:P":"1f61c","X-P":"1f61c",">:[":"1f61e",":-(":"1f61e",":-[":"1f61e",">:(":"1f620",":'(":"1f622",";-(":"1f622",">.<":"1f623","#-)":"1f635","%-)":"1f635","X-)":"1f635","\\0/":"1f646","\\O/":"1f646","0:3":"1f607","0:)":"1f607","O:)":"1f607","O=)":"1f607","O:3":"1f607","B-)":"1f60e","8-)":"1f60e","B-D":"1f60e","8-D":"1f60e","-_-":"1f611",">:\\":"1f615",">:/":"1f615",":-/":"1f615",":-.":"1f615",":-P":"1f61b",":Þ":"1f61b",":-b":"1f61b",":-O":"1f62e",O_O:"1f62e",">:O":"1f62e",":-X":"1f636",":-#":"1f636",":-)":"1f642","(y)":"1f44d","<3":"2764",":D":"1f603","=D":"1f603",";)":"1f609","*)":"1f609",";]":"1f609",";D":"1f609",":*":"1f618","=*":"1f618",":(":"1f61e",":[":"1f61e","=(":"1f61e",":@":"1f620",";(":"1f622","D:":"1f628",":$":"1f633","=$":"1f633","#)":"1f635","%)":"1f635","X)":"1f635","B)":"1f60e","8)":"1f60e",":/":"1f615",":\\":"1f615","=/":"1f615","=\\":"1f615",":L":"1f615","=L":"1f615",":P":"1f61b","=P":"1f61b",":b":"1f61b",":O":"1f62e",":X":"1f636",":#":"1f636","=X":"1f636","=#":"1f636",":)":"1f642","=]":"1f642","=)":"1f642",":]":"1f642"},e.asciiRegexp="(\\*\\\\0\\/\\*|\\*\\\\O\\/\\*|\\-___\\-|\\:'\\-\\)|'\\:\\-\\)|'\\:\\-D|\\>\\:\\-\\)|>\\:\\-\\)|'\\:\\-\\(|\\>\\:\\-\\(|>\\:\\-\\(|\\:'\\-\\(|O\\:\\-\\)|0\\:\\-3|0\\:\\-\\)|0;\\^\\)|O;\\-\\)|0;\\-\\)|O\\:\\-3|\\-__\\-|\\:\\-Þ|\\:\\-Þ|\\<\\/3|<\\/3|\\:'\\)|\\:\\-D|'\\:\\)|'\\=\\)|'\\:D|'\\=D|\\>\\:\\)|>\\:\\)|\\>;\\)|>;\\)|\\>\\=\\)|>\\=\\)|;\\-\\)|\\*\\-\\)|;\\-\\]|;\\^\\)|'\\:\\(|'\\=\\(|\\:\\-\\*|\\:\\^\\*|\\>\\:P|>\\:P|X\\-P|\\>\\:\\[|>\\:\\[|\\:\\-\\(|\\:\\-\\[|\\>\\:\\(|>\\:\\(|\\:'\\(|;\\-\\(|\\>\\.\\<|>\\.<|#\\-\\)|%\\-\\)|X\\-\\)|\\\\0\\/|\\\\O\\/|0\\:3|0\\:\\)|O\\:\\)|O\\=\\)|O\\:3|B\\-\\)|8\\-\\)|B\\-D|8\\-D|\\-_\\-|\\>\\:\\\\|>\\:\\\\|\\>\\:\\/|>\\:\\/|\\:\\-\\/|\\:\\-\\.|\\:\\-P|\\:Þ|\\:Þ|\\:\\-b|\\:\\-O|O_O|\\>\\:O|>\\:O|\\:\\-X|\\:\\-#|\\:\\-\\)|\\(y\\)|\\<3|<3|\\:D|\\=D|;\\)|\\*\\)|;\\]|;D|\\:\\*|\\=\\*|\\:\\(|\\:\\[|\\=\\(|\\:@|;\\(|D\\:|\\:\\$|\\=\\$|#\\)|%\\)|X\\)|B\\)|8\\)|\\:\\/|\\:\\\\|\\=\\/|\\=\\\\|\\:L|\\=L|\\:P|\\=P|\\:b|\\:O|\\:X|\\:#|\\=X|\\=#|\\:\\)|\\=\\]|\\=\\)|\\:\\])",e.emojiVersion="3.1",e.emojiSize="32",e.greedyMatch=!1,e.imagePathPNG="https://cdn.jsdelivr.net/emojione/assets/"+e.emojiVersion+"/png/",e.defaultPathPNG=e.imagePathPNG,e.imageTitleTag=!0,e.sprites=!1,e.spriteSize="32",e.unicodeAlt=!0,e.ascii=!1,e.riskyMatchAscii=!1,e.regShortNames=new RegExp("]*>.*?|]*>.*?|<(?:object|embed|svg|img|div|span|p|a)[^>]*>|("+e.shortnames+")","gi"),e.regAscii=new RegExp("]*>.*?|]*>.*?|<(?:object|embed|svg|img|div|span|p|a)[^>]*>|((\\s|^)"+e.asciiRegexp+"(?=\\s|$|[!,.?]))","gi"),e.regAsciiRisky=new RegExp("]*>.*?|]*>.*?|<(?:object|embed|svg|img|div|span|p|a)[^>]*>|(()"+e.asciiRegexp+"())","gi"),e.regUnicode=new RegExp("]*>.*?|]*>.*?|<(?:object|embed|svg|img|div|span|p|a)[^>]*>|(?:🏳)️?‍?(?:🌈)|(?:👁)️?‍?(?:🗨)️?|[#-9]️?⃣|(?:(?:🏴)(?:\udb40[\udc60-\udcff]){1,6})|(?:\ud83c[\udde0-\uddff]){2}|(?:(?:\ud83d[\udc68\udc69]))️?(?:\ud83c[\udffa-\udfff])?‍?(?:[⚕⚖✈]|\ud83c[\udf3e-\udfed]|\ud83d[\udcbb\udcbc\udd27\udd2c\ude80\ude92])|(?:\ud83d[\udc68\udc69]|\ud83e[\uddd0-\udddf])(?:\ud83c[\udffa-\udfff])?‍?[♀♂⚕⚖✈]?️?|(?:(?:❤|\ud83d[\udc66-\udc69\udc8b])[‍️]{0,2}){1,3}(?:❤|\ud83d[\udc66-\udc69\udc8b])|(?:(?:❤|\ud83d[\udc66-\udc69\udc8b])️?){2,4}|(?:\ud83d[\udc68\udc69\udc6e\udc71-\udc87\udd75\ude45-\ude4e]|\ud83e[\udd26\udd37]|\ud83c[\udfc3-\udfcc]|\ud83e[\udd38-\udd3e]|\ud83d[\udea3-\udeb6]|⛹|👯)️?(?:\ud83c[\udffb-\udfff])?‍?[♀♂]?️?|(?:[☝⛹✊-✍]|\ud83c[\udf85-\udfcc]|\ud83d[\udc42-\udcaa\udd74-\udd96\ude45-\ude4f\udea3-\udecc]|\ud83e[\udd18-\udd3e])️?(?:\ud83c[\udffb-\udfff])|(?:[↔-↙↩-↪]️?|[#*]|[〰〽]️?|(?:\ud83c[\udd70-\udd71]|🆎|\ud83c[\udd91-\udd9a])️?|Ⓜ️?|[㊗㊙]️?|(?:\ud83c[\ude01-\ude02]|🈚|🈯|\ud83c[\ude32-\ude3a]|\ud83c[\ude50-\ude51])️?|[‼⁉]️?|[▪-▫▶◀◻-◾]️?|[©®]️?|[™ℹ]️?|🀄️?|[⬅-⬇⬛-⬜⭐⭕]️?|[⌚-⌛⌨⏏⏩-⏳⏸-⏺]️?|🃏|[⤴⤵]️?)|[✀-➿]️?|[\ud800-\udbff][\udc00-\udfff]️?|[☀-⛿]️?|[0-9]️","g"),e.toImage=function(t){return t=e.unicodeToImage(t),t=e.shortnameToImage(t)},e.unifyUnicode=function(t){return t=e.toShort(t),t=e.shortnameToUnicode(t)},e.shortnameToAscii=function(t){var f,a=e.objectFlip(e.asciiList);return t=t.replace(e.regShortNames,function(t){return void 0!==t&&""!==t&&t in e.emojioneList?(f=e.emojioneList[t].uc_output,void 0!==a[f]?a[f]:t):t})},e.shortnameToUnicode=function(t){var f;if(t=t.replace(e.regShortNames,function(t){return void 0!==t&&""!==t&&t in e.emojioneList?(f=e.emojioneList[t].uc_output.toUpperCase(),e.emojioneList[t].uc_base,e.convert(f)):t}),e.ascii){var a=e.riskyMatchAscii?e.regAsciiRisky:e.regAscii;t=t.replace(a,function(t,a,n,o){return void 0!==o&&""!==o&&e.unescapeHTML(o)in e.asciiList?(o=e.unescapeHTML(o),f=e.asciiList[o].toUpperCase(),n+e.convert(f)):t})}return t},e.shortnameToImage=function(t){var f,a,n,o,r,s,c,i,u=e.mapUnicodeToShort();if(t=t.replace(e.regShortNames,function(t){if(void 0===t||""===t||-1===e.shortnames.indexOf(t))return t;if(!e.emojioneList[t])for(var f in e.emojioneList)if(e.emojioneList.hasOwnProperty(f)&&""!==f&&-1!==e.emojioneList[f].shortnames.indexOf(t)){t=f;break}return a=e.emojioneList[t].uc_output,n=e.emojioneList[t].uc_base,r=n.includes("-1f3f")?"diversity":e.emojioneList[t].category,s=e.imageTitleTag?'title="'+t+'"':"",c="32"==e.spriteSize||"64"==e.spriteSize?e.spriteSize:"32",i=e.imagePathPNG!=e.defaultPathPNG?e.imagePathPNG:e.defaultPathPNG+e.emojiSize+"/",o=e.unicodeAlt?e.convert(a.toUpperCase()):t,e.sprites?'"+o+"":''+o+''}),e.ascii){var _=e.riskyMatchAscii?e.regAsciiRisky:e.regAscii;t=t.replace(_,function(t,n,_,d){return void 0!==d&&""!==d&&e.unescapeHTML(d)in e.asciiList?(d=e.unescapeHTML(d),a=e.asciiList[d],f=u[a],r=a.includes("-1f3f")?"diversity":e.emojioneList[f].category,s=e.imageTitleTag?'title="'+e.escapeHTML(d)+'"':"",c="32"==e.spriteSize||"64"==e.spriteSize?e.spriteSize:"32",i=e.imagePathPNG!=e.defaultPathPNG?e.imagePathPNG:e.defaultPathPNG+e.emojiSize+"/",o=e.unicodeAlt?e.convert(a.toUpperCase()):e.escapeHTML(d),e.sprites?_+'"+o+"":_+''+o+''):t})}return t},e.unicodeToImage=function(t){var f,a,n,o,r,s,c,i,u=e.mapUnicodeToShort(),_=e.emojioneList;if(t=t.replace(e.regUnicode,function(t){if(void 0===t||""===t)return t;if(t in e.jsEscapeMap)n=e.jsEscapeMap[t];else{if(!(e.greedyMatch&&t in e.jsEscapeMapGreedy))return t;n=e.jsEscapeMapGreedy[t]}return a=u[n],n=_[a].uc_base,f=_[a].uc_output,r=n.includes("-1f3f")?"diversity":_[a].category,c="32"==e.spriteSize||"64"==e.spriteSize?e.spriteSize:"32",i=e.imagePathPNG!=e.defaultPathPNG?e.imagePathPNG:e.defaultPathPNG+e.emojiSize+"/",o=e.unicodeAlt?e.convert(f.toUpperCase()):a,s=e.imageTitleTag?'title="'+a+'"':"",e.sprites?'"+o+"":''+o+''}),e.ascii){var d=e.riskyMatchAscii?e.regAsciiRisky:e.regAscii;t=t.replace(d,function(t,a,n,_){return void 0!==_&&""!==_&&e.unescapeHTML(_)in e.asciiList?(_=e.unescapeHTML(_),f=e.asciiList[_],shortname=u[f],r=f.includes("-1f3f")?"diversity":e.emojioneList[shortname].category,s=e.imageTitleTag?'title="'+e.escapeHTML(_)+'"':"",c="32"==e.spriteSize||"64"==e.spriteSize?e.spriteSize:"32",i=e.imagePathPNG!=e.defaultPathPNG?e.imagePathPNG:e.defaultPathPNG+e.emojiSize+"/",o=e.unicodeAlt?e.convert(f.toUpperCase()):e.escapeHTML(_),e.sprites?n+'"+o+"":n+''+o+''):t})}return t},e.toShort=function(t){var f=e.unicodeCharRegex();return e.replaceAll(t,f)},e.convert=function(e){if(e.indexOf("-")>-1){for(var t=[],f=e.split("-"),a=0;a=65536&&n<=1114111){var o=Math.floor((n-65536)/1024)+55296,r=(n-65536)%1024+56320;n=String.fromCharCode(o)+String.fromCharCode(r)}else n=String.fromCharCode(n);t.push(n)}return t.join("")}if((f=parseInt(e,16))>=65536&&f<=1114111){o=Math.floor((f-65536)/1024)+55296,r=(f-65536)%1024+56320;return String.fromCharCode(o)+String.fromCharCode(r)}return String.fromCharCode(f)},e.escapeHTML=function(e){var t={"&":"&","<":"<",">":">",'"':""","'":"'"};return e.replace(/[&<>"']/g,function(e){return t[e]})},e.unescapeHTML=function(e){var t={"&":"&","&":"&","&":"&","<":"<","<":"<","<":"<",">":">",">":">",">":">",""":'"',""":'"',""":'"',"'":"'","'":"'","'":"'"};return e.replace(/&(?:amp|#38|#x26|lt|#60|#x3C|gt|#62|#x3E|apos|#39|#x27|quot|#34|#x22);/gi,function(e){return t[e]})},e.shortnameConversionMap=function(){var t,f=[];for(t in e.emojioneList)e.emojioneList.hasOwnProperty(t)&&""!==t&&(f[e.convert(e.emojioneList[t].uc_output)]=t);return f},e.unicodeCharRegex=function(){var f=[];for(t in e.emojioneList)e.emojioneList.hasOwnProperty(t)&&""!==t&&f.push(e.convert(e.emojioneList[t].uc_output));return f.join("|")},e.mapEmojioneList=function(t){for(var f in e.emojioneList){if(e.emojioneList.hasOwnProperty(f))t(e.emojioneList[f].uc_base,f)}},e.mapUnicodeToShort=function(){return e.memMapShortToUnicode||(e.memMapShortToUnicode={},e.mapEmojioneList(function(t,f){e.memMapShortToUnicode[t]=f})),e.memMapShortToUnicode},e.memorizeReplacement=function(){if(!e.unicodeReplacementRegEx||!e.memMapShortToUnicodeCharacters){var t=[];e.memMapShortToUnicodeCharacters={},e.mapEmojioneList(function(f,a){var n=e.convert(f);e.memMapShortToUnicodeCharacters[n]=a,t.push(n)}),e.unicodeReplacementRegEx=t.join("|")}},e.mapUnicodeCharactersToShort=function(){return e.memorizeReplacement(),e.memMapShortToUnicodeCharacters},e.objectFlip=function(e){var t,f={};for(t in e)e.hasOwnProperty(t)&&(f[e[t]]=t);return f},e.escapeRegExp=function(e){return e.replace(/[-[\]{}()*+?.,;:&\\^$#\s]/g,"\\$&")},e.replaceAll=function(t,f){var a=e.escapeRegExp(f),n=new RegExp("]*>.*?|]*>.*?|<(?:object|embed|svg|img|div|span|p|a)[^>]*>|("+a+")","gi");return t.replace(n,function(t,f){return void 0===f||""===f?t:e.shortnameConversionMap()[f]})}}(this.emojione=this.emojione||{}),e.exports=this.emojione},function(e,t,f){var a,n,o;n=[],void 0===(o="function"==typeof(a=function(){ +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { +/******/ configurable: false, +/******/ enumerable: true, +/******/ get: getter +/******/ }); +/******/ } +/******/ }; +/******/ +/******/ // define __esModule on exports +/******/ __webpack_require__.r = function(exports) { +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = "./src/converse.js"); +/******/ }) +/************************************************************************/ +/******/ ({ + +/***/ "./3rdparty/lodash.fp.js": +/*!*******************************!*\ + !*** ./3rdparty/lodash.fp.js ***! + \*******************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +(function webpackUniversalModuleDefinition(root, factory) { + if (true) module.exports = factory();else {} +})(void 0, function () { + return ( + /******/ + function (modules) { + // webpackBootstrap + + /******/ + // The module cache + + /******/ + var installedModules = {}; + /******/ + // The require function + + /******/ + + function __webpack_require__(moduleId) { + /******/ + // Check if module is in cache + + /******/ + if (installedModules[moduleId]) + /******/ + return installedModules[moduleId].exports; + /******/ + // Create a new module (and put it into the cache) + + /******/ + + var module = installedModules[moduleId] = { + /******/ + exports: {}, + + /******/ + id: moduleId, + + /******/ + loaded: false + /******/ + + }; + /******/ + // Execute the module function + + /******/ + + modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + /******/ + // Flag the module as loaded + + /******/ + + module.loaded = true; + /******/ + // Return the exports of the module + + /******/ + + return module.exports; + /******/ + } + /******/ + // expose the modules object (__webpack_modules__) + + /******/ + + + __webpack_require__.m = modules; + /******/ + // expose the module cache + + /******/ + + __webpack_require__.c = installedModules; + /******/ + // __webpack_public_path__ + + /******/ + + __webpack_require__.p = ""; + /******/ + // Load entry module and return exports + + /******/ + + return __webpack_require__(0); + /******/ + }( + /************************************************************************/ + + /******/ + [ + /* 0 */ + + /***/ + function (module, exports, __webpack_require__) { + var baseConvert = __webpack_require__(1); + /** + * Converts `lodash` to an immutable auto-curried iteratee-first data-last + * version with conversion `options` applied. + * + * @param {Function} lodash The lodash function to convert. + * @param {Object} [options] The options object. See `baseConvert` for more details. + * @returns {Function} Returns the converted `lodash`. + */ + + + function browserConvert(lodash, options) { + return baseConvert(lodash, lodash, options); + } + + if (typeof _ == 'function' && typeof _.runInContext == 'function') { + // XXX: Customization in order to be able to run both _ and fp in the + // non-AMD usecase. + fp = browserConvert(_.runInContext()); + } + + module.exports = browserConvert; + /***/ + }, + /* 1 */ + + /***/ + function (module, exports, __webpack_require__) { + var mapping = __webpack_require__(2), + fallbackHolder = __webpack_require__(3); + /** Built-in value reference. */ + + + var push = Array.prototype.push; + /** + * Creates a function, with an arity of `n`, that invokes `func` with the + * arguments it receives. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} n The arity of the new function. + * @returns {Function} Returns the new function. + */ + + function baseArity(func, n) { + return n == 2 ? function (a, b) { + return func.apply(undefined, arguments); + } : function (a) { + return func.apply(undefined, arguments); + }; + } + /** + * Creates a function that invokes `func`, with up to `n` arguments, ignoring + * any additional arguments. + * + * @private + * @param {Function} func The function to cap arguments for. + * @param {number} n The arity cap. + * @returns {Function} Returns the new function. + */ + + + function baseAry(func, n) { + return n == 2 ? function (a, b) { + return func(a, b); + } : function (a) { + return func(a); + }; + } + /** + * Creates a clone of `array`. + * + * @private + * @param {Array} array The array to clone. + * @returns {Array} Returns the cloned array. + */ + + + function cloneArray(array) { + var length = array ? array.length : 0, + result = Array(length); + + while (length--) { + result[length] = array[length]; + } + + return result; + } + /** + * Creates a function that clones a given object using the assignment `func`. + * + * @private + * @param {Function} func The assignment function. + * @returns {Function} Returns the new cloner function. + */ + + + function createCloner(func) { + return function (object) { + return func({}, object); + }; + } + /** + * A specialized version of `_.spread` which flattens the spread array into + * the arguments of the invoked `func`. + * + * @private + * @param {Function} func The function to spread arguments over. + * @param {number} start The start position of the spread. + * @returns {Function} Returns the new function. + */ + + + function flatSpread(func, start) { + return function () { + var length = arguments.length, + lastIndex = length - 1, + args = Array(length); + + while (length--) { + args[length] = arguments[length]; + } + + var array = args[start], + otherArgs = args.slice(0, start); + + if (array) { + push.apply(otherArgs, array); + } + + if (start != lastIndex) { + push.apply(otherArgs, args.slice(start + 1)); + } + + return func.apply(this, otherArgs); + }; + } + /** + * Creates a function that wraps `func` and uses `cloner` to clone the first + * argument it receives. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} cloner The function to clone arguments. + * @returns {Function} Returns the new immutable function. + */ + + + function wrapImmutable(func, cloner) { + return function () { + var length = arguments.length; + + if (!length) { + return; + } + + var args = Array(length); + + while (length--) { + args[length] = arguments[length]; + } + + var result = args[0] = cloner.apply(undefined, args); + func.apply(undefined, args); + return result; + }; + } + /** + * The base implementation of `convert` which accepts a `util` object of methods + * required to perform conversions. + * + * @param {Object} util The util object. + * @param {string} name The name of the function to convert. + * @param {Function} func The function to convert. + * @param {Object} [options] The options object. + * @param {boolean} [options.cap=true] Specify capping iteratee arguments. + * @param {boolean} [options.curry=true] Specify currying. + * @param {boolean} [options.fixed=true] Specify fixed arity. + * @param {boolean} [options.immutable=true] Specify immutable operations. + * @param {boolean} [options.rearg=true] Specify rearranging arguments. + * @returns {Function|Object} Returns the converted function or object. + */ + + + function baseConvert(util, name, func, options) { + var setPlaceholder, + isLib = typeof name == 'function', + isObj = name === Object(name); + + if (isObj) { + options = func; + func = name; + name = undefined; + } + + if (func == null) { + throw new TypeError(); + } + + options || (options = {}); + var config = { + 'cap': 'cap' in options ? options.cap : true, + 'curry': 'curry' in options ? options.curry : true, + 'fixed': 'fixed' in options ? options.fixed : true, + 'immutable': 'immutable' in options ? options.immutable : true, + 'rearg': 'rearg' in options ? options.rearg : true + }; + var forceCurry = 'curry' in options && options.curry, + forceFixed = 'fixed' in options && options.fixed, + forceRearg = 'rearg' in options && options.rearg, + placeholder = isLib ? func : fallbackHolder, + pristine = isLib ? func.runInContext() : undefined; + var helpers = isLib ? func : { + 'ary': util.ary, + 'assign': util.assign, + 'clone': util.clone, + 'curry': util.curry, + 'forEach': util.forEach, + 'isArray': util.isArray, + 'isFunction': util.isFunction, + 'iteratee': util.iteratee, + 'keys': util.keys, + 'rearg': util.rearg, + 'toInteger': util.toInteger, + 'toPath': util.toPath + }; + var ary = helpers.ary, + assign = helpers.assign, + clone = helpers.clone, + curry = helpers.curry, + each = helpers.forEach, + isArray = helpers.isArray, + isFunction = helpers.isFunction, + keys = helpers.keys, + rearg = helpers.rearg, + toInteger = helpers.toInteger, + toPath = helpers.toPath; + var aryMethodKeys = keys(mapping.aryMethod); + var wrappers = { + 'castArray': function castArray(_castArray) { + return function () { + var value = arguments[0]; + return isArray(value) ? _castArray(cloneArray(value)) : _castArray.apply(undefined, arguments); + }; + }, + 'iteratee': function iteratee(_iteratee) { + return function () { + var func = arguments[0], + arity = arguments[1], + result = _iteratee(func, arity), + length = result.length; + + if (config.cap && typeof arity == 'number') { + arity = arity > 2 ? arity - 2 : 1; + return length && length <= arity ? result : baseAry(result, arity); + } + + return result; + }; + }, + 'mixin': function mixin(_mixin) { + return function (source) { + var func = this; + + if (!isFunction(func)) { + return _mixin(func, Object(source)); + } + + var pairs = []; + each(keys(source), function (key) { + if (isFunction(source[key])) { + pairs.push([key, func.prototype[key]]); + } + }); + + _mixin(func, Object(source)); + + each(pairs, function (pair) { + var value = pair[1]; + + if (isFunction(value)) { + func.prototype[pair[0]] = value; + } else { + delete func.prototype[pair[0]]; + } + }); + return func; + }; + }, + 'nthArg': function nthArg(_nthArg) { + return function (n) { + var arity = n < 0 ? 1 : toInteger(n) + 1; + return curry(_nthArg(n), arity); + }; + }, + 'rearg': function rearg(_rearg) { + return function (func, indexes) { + var arity = indexes ? indexes.length : 0; + return curry(_rearg(func, indexes), arity); + }; + }, + 'runInContext': function runInContext(_runInContext) { + return function (context) { + return baseConvert(util, _runInContext(context), options); + }; + } + }; + /*--------------------------------------------------------------------------*/ + + /** + * Casts `func` to a function with an arity capped iteratee if needed. + * + * @private + * @param {string} name The name of the function to inspect. + * @param {Function} func The function to inspect. + * @returns {Function} Returns the cast function. + */ + + function castCap(name, func) { + if (config.cap) { + var indexes = mapping.iterateeRearg[name]; + + if (indexes) { + return iterateeRearg(func, indexes); + } + + var n = !isLib && mapping.iterateeAry[name]; + + if (n) { + return iterateeAry(func, n); + } + } + + return func; + } + /** + * Casts `func` to a curried function if needed. + * + * @private + * @param {string} name The name of the function to inspect. + * @param {Function} func The function to inspect. + * @param {number} n The arity of `func`. + * @returns {Function} Returns the cast function. + */ + + + function castCurry(name, func, n) { + return forceCurry || config.curry && n > 1 ? curry(func, n) : func; + } + /** + * Casts `func` to a fixed arity function if needed. + * + * @private + * @param {string} name The name of the function to inspect. + * @param {Function} func The function to inspect. + * @param {number} n The arity cap. + * @returns {Function} Returns the cast function. + */ + + + function castFixed(name, func, n) { + if (config.fixed && (forceFixed || !mapping.skipFixed[name])) { + var data = mapping.methodSpread[name], + start = data && data.start; + return start === undefined ? ary(func, n) : flatSpread(func, start); + } + + return func; + } + /** + * Casts `func` to an rearged function if needed. + * + * @private + * @param {string} name The name of the function to inspect. + * @param {Function} func The function to inspect. + * @param {number} n The arity of `func`. + * @returns {Function} Returns the cast function. + */ + + + function castRearg(name, func, n) { + return config.rearg && n > 1 && (forceRearg || !mapping.skipRearg[name]) ? rearg(func, mapping.methodRearg[name] || mapping.aryRearg[n]) : func; + } + /** + * Creates a clone of `object` by `path`. + * + * @private + * @param {Object} object The object to clone. + * @param {Array|string} path The path to clone by. + * @returns {Object} Returns the cloned object. + */ + + + function cloneByPath(object, path) { + path = toPath(path); + var index = -1, + length = path.length, + lastIndex = length - 1, + result = clone(Object(object)), + nested = result; + + while (nested != null && ++index < length) { + var key = path[index], + value = nested[key]; + + if (value != null) { + nested[path[index]] = clone(index == lastIndex ? value : Object(value)); + } + + nested = nested[key]; + } + + return result; + } + /** + * Converts `lodash` to an immutable auto-curried iteratee-first data-last + * version with conversion `options` applied. + * + * @param {Object} [options] The options object. See `baseConvert` for more details. + * @returns {Function} Returns the converted `lodash`. + */ + + + function convertLib(options) { + return _.runInContext.convert(options)(undefined); + } + /** + * Create a converter function for `func` of `name`. + * + * @param {string} name The name of the function to convert. + * @param {Function} func The function to convert. + * @returns {Function} Returns the new converter function. + */ + + + function createConverter(name, func) { + var realName = mapping.aliasToReal[name] || name, + methodName = mapping.remap[realName] || realName, + oldOptions = options; + return function (options) { + var newUtil = isLib ? pristine : helpers, + newFunc = isLib ? pristine[methodName] : func, + newOptions = assign(assign({}, oldOptions), options); + return baseConvert(newUtil, realName, newFunc, newOptions); + }; + } + /** + * Creates a function that wraps `func` to invoke its iteratee, with up to `n` + * arguments, ignoring any additional arguments. + * + * @private + * @param {Function} func The function to cap iteratee arguments for. + * @param {number} n The arity cap. + * @returns {Function} Returns the new function. + */ + + + function iterateeAry(func, n) { + return overArg(func, function (func) { + return typeof func == 'function' ? baseAry(func, n) : func; + }); + } + /** + * Creates a function that wraps `func` to invoke its iteratee with arguments + * arranged according to the specified `indexes` where the argument value at + * the first index is provided as the first argument, the argument value at + * the second index is provided as the second argument, and so on. + * + * @private + * @param {Function} func The function to rearrange iteratee arguments for. + * @param {number[]} indexes The arranged argument indexes. + * @returns {Function} Returns the new function. + */ + + + function iterateeRearg(func, indexes) { + return overArg(func, function (func) { + var n = indexes.length; + return baseArity(rearg(baseAry(func, n), indexes), n); + }); + } + /** + * Creates a function that invokes `func` with its first argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + + + function overArg(func, transform) { + return function () { + var length = arguments.length; + + if (!length) { + return func(); + } + + var args = Array(length); + + while (length--) { + args[length] = arguments[length]; + } + + var index = config.rearg ? 0 : length - 1; + args[index] = transform(args[index]); + return func.apply(undefined, args); + }; + } + /** + * Creates a function that wraps `func` and applys the conversions + * rules by `name`. + * + * @private + * @param {string} name The name of the function to wrap. + * @param {Function} func The function to wrap. + * @returns {Function} Returns the converted function. + */ + + + function wrap(name, func) { + var result, + realName = mapping.aliasToReal[name] || name, + wrapped = func, + wrapper = wrappers[realName]; + + if (wrapper) { + wrapped = wrapper(func); + } else if (config.immutable) { + if (mapping.mutate.array[realName]) { + wrapped = wrapImmutable(func, cloneArray); + } else if (mapping.mutate.object[realName]) { + wrapped = wrapImmutable(func, createCloner(func)); + } else if (mapping.mutate.set[realName]) { + wrapped = wrapImmutable(func, cloneByPath); + } + } + + each(aryMethodKeys, function (aryKey) { + each(mapping.aryMethod[aryKey], function (otherName) { + if (realName == otherName) { + var data = mapping.methodSpread[realName], + afterRearg = data && data.afterRearg; + result = afterRearg ? castFixed(realName, castRearg(realName, wrapped, aryKey), aryKey) : castRearg(realName, castFixed(realName, wrapped, aryKey), aryKey); + result = castCap(realName, result); + result = castCurry(realName, result, aryKey); + return false; + } + }); + return !result; + }); + result || (result = wrapped); + + if (result == func) { + result = forceCurry ? curry(result, 1) : function () { + return func.apply(this, arguments); + }; + } + + result.convert = createConverter(realName, func); + + if (mapping.placeholder[realName]) { + setPlaceholder = true; + result.placeholder = func.placeholder = placeholder; + } + + return result; + } + /*--------------------------------------------------------------------------*/ + + + if (!isObj) { + return wrap(name, func); + } + + var _ = func; // Convert methods by ary cap. + + var pairs = []; + each(aryMethodKeys, function (aryKey) { + each(mapping.aryMethod[aryKey], function (key) { + var func = _[mapping.remap[key] || key]; + + if (func) { + pairs.push([key, wrap(key, func)]); + } + }); + }); // Convert remaining methods. + + each(keys(_), function (key) { + var func = _[key]; + + if (typeof func == 'function') { + var length = pairs.length; + + while (length--) { + if (pairs[length][0] == key) { + return; + } + } + + func.convert = createConverter(key, func); + pairs.push([key, func]); + } + }); // Assign to `_` leaving `_.prototype` unchanged to allow chaining. + + each(pairs, function (pair) { + _[pair[0]] = pair[1]; + }); + _.convert = convertLib; + + if (setPlaceholder) { + _.placeholder = placeholder; + } // Assign aliases. + + + each(keys(_), function (key) { + each(mapping.realToAlias[key] || [], function (alias) { + _[alias] = _[key]; + }); + }); + return _; + } + + module.exports = baseConvert; + /***/ + }, + /* 2 */ + + /***/ + function (module, exports) { + /** Used to map aliases to their real names. */ + exports.aliasToReal = { + // Lodash aliases. + 'each': 'forEach', + 'eachRight': 'forEachRight', + 'entries': 'toPairs', + 'entriesIn': 'toPairsIn', + 'extend': 'assignIn', + 'extendAll': 'assignInAll', + 'extendAllWith': 'assignInAllWith', + 'extendWith': 'assignInWith', + 'first': 'head', + // Methods that are curried variants of others. + 'conforms': 'conformsTo', + 'matches': 'isMatch', + 'property': 'get', + // Ramda aliases. + '__': 'placeholder', + 'F': 'stubFalse', + 'T': 'stubTrue', + 'all': 'every', + 'allPass': 'overEvery', + 'always': 'constant', + 'any': 'some', + 'anyPass': 'overSome', + 'apply': 'spread', + 'assoc': 'set', + 'assocPath': 'set', + 'complement': 'negate', + 'compose': 'flowRight', + 'contains': 'includes', + 'dissoc': 'unset', + 'dissocPath': 'unset', + 'dropLast': 'dropRight', + 'dropLastWhile': 'dropRightWhile', + 'equals': 'isEqual', + 'identical': 'eq', + 'indexBy': 'keyBy', + 'init': 'initial', + 'invertObj': 'invert', + 'juxt': 'over', + 'omitAll': 'omit', + 'nAry': 'ary', + 'path': 'get', + 'pathEq': 'matchesProperty', + 'pathOr': 'getOr', + 'paths': 'at', + 'pickAll': 'pick', + 'pipe': 'flow', + 'pluck': 'map', + 'prop': 'get', + 'propEq': 'matchesProperty', + 'propOr': 'getOr', + 'props': 'at', + 'symmetricDifference': 'xor', + 'symmetricDifferenceBy': 'xorBy', + 'symmetricDifferenceWith': 'xorWith', + 'takeLast': 'takeRight', + 'takeLastWhile': 'takeRightWhile', + 'unapply': 'rest', + 'unnest': 'flatten', + 'useWith': 'overArgs', + 'where': 'conformsTo', + 'whereEq': 'isMatch', + 'zipObj': 'zipObject' + }; + /** Used to map ary to method names. */ + + exports.aryMethod = { + '1': ['assignAll', 'assignInAll', 'attempt', 'castArray', 'ceil', 'create', 'curry', 'curryRight', 'defaultsAll', 'defaultsDeepAll', 'floor', 'flow', 'flowRight', 'fromPairs', 'invert', 'iteratee', 'memoize', 'method', 'mergeAll', 'methodOf', 'mixin', 'nthArg', 'over', 'overEvery', 'overSome', 'rest', 'reverse', 'round', 'runInContext', 'spread', 'template', 'trim', 'trimEnd', 'trimStart', 'uniqueId', 'words', 'zipAll'], + '2': ['add', 'after', 'ary', 'assign', 'assignAllWith', 'assignIn', 'assignInAllWith', 'at', 'before', 'bind', 'bindAll', 'bindKey', 'chunk', 'cloneDeepWith', 'cloneWith', 'concat', 'conformsTo', 'countBy', 'curryN', 'curryRightN', 'debounce', 'defaults', 'defaultsDeep', 'defaultTo', 'delay', 'difference', 'divide', 'drop', 'dropRight', 'dropRightWhile', 'dropWhile', 'endsWith', 'eq', 'every', 'filter', 'find', 'findIndex', 'findKey', 'findLast', 'findLastIndex', 'findLastKey', 'flatMap', 'flatMapDeep', 'flattenDepth', 'forEach', 'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight', 'get', 'groupBy', 'gt', 'gte', 'has', 'hasIn', 'includes', 'indexOf', 'intersection', 'invertBy', 'invoke', 'invokeMap', 'isEqual', 'isMatch', 'join', 'keyBy', 'lastIndexOf', 'lt', 'lte', 'map', 'mapKeys', 'mapValues', 'matchesProperty', 'maxBy', 'meanBy', 'merge', 'mergeAllWith', 'minBy', 'multiply', 'nth', 'omit', 'omitBy', 'overArgs', 'pad', 'padEnd', 'padStart', 'parseInt', 'partial', 'partialRight', 'partition', 'pick', 'pickBy', 'propertyOf', 'pull', 'pullAll', 'pullAt', 'random', 'range', 'rangeRight', 'rearg', 'reject', 'remove', 'repeat', 'restFrom', 'result', 'sampleSize', 'some', 'sortBy', 'sortedIndex', 'sortedIndexOf', 'sortedLastIndex', 'sortedLastIndexOf', 'sortedUniqBy', 'split', 'spreadFrom', 'startsWith', 'subtract', 'sumBy', 'take', 'takeRight', 'takeRightWhile', 'takeWhile', 'tap', 'throttle', 'thru', 'times', 'trimChars', 'trimCharsEnd', 'trimCharsStart', 'truncate', 'union', 'uniqBy', 'uniqWith', 'unset', 'unzipWith', 'without', 'wrap', 'xor', 'zip', 'zipObject', 'zipObjectDeep'], + '3': ['assignInWith', 'assignWith', 'clamp', 'differenceBy', 'differenceWith', 'findFrom', 'findIndexFrom', 'findLastFrom', 'findLastIndexFrom', 'getOr', 'includesFrom', 'indexOfFrom', 'inRange', 'intersectionBy', 'intersectionWith', 'invokeArgs', 'invokeArgsMap', 'isEqualWith', 'isMatchWith', 'flatMapDepth', 'lastIndexOfFrom', 'mergeWith', 'orderBy', 'padChars', 'padCharsEnd', 'padCharsStart', 'pullAllBy', 'pullAllWith', 'rangeStep', 'rangeStepRight', 'reduce', 'reduceRight', 'replace', 'set', 'slice', 'sortedIndexBy', 'sortedLastIndexBy', 'transform', 'unionBy', 'unionWith', 'update', 'xorBy', 'xorWith', 'zipWith'], + '4': ['fill', 'setWith', 'updateWith'] + }; + /** Used to map ary to rearg configs. */ + + exports.aryRearg = { + '2': [1, 0], + '3': [2, 0, 1], + '4': [3, 2, 0, 1] + }; + /** Used to map method names to their iteratee ary. */ + + exports.iterateeAry = { + 'dropRightWhile': 1, + 'dropWhile': 1, + 'every': 1, + 'filter': 1, + 'find': 1, + 'findFrom': 1, + 'findIndex': 1, + 'findIndexFrom': 1, + 'findKey': 1, + 'findLast': 1, + 'findLastFrom': 1, + 'findLastIndex': 1, + 'findLastIndexFrom': 1, + 'findLastKey': 1, + 'flatMap': 1, + 'flatMapDeep': 1, + 'flatMapDepth': 1, + 'forEach': 1, + 'forEachRight': 1, + 'forIn': 1, + 'forInRight': 1, + 'forOwn': 1, + 'forOwnRight': 1, + 'map': 1, + 'mapKeys': 1, + 'mapValues': 1, + 'partition': 1, + 'reduce': 2, + 'reduceRight': 2, + 'reject': 1, + 'remove': 1, + 'some': 1, + 'takeRightWhile': 1, + 'takeWhile': 1, + 'times': 1, + 'transform': 2 + }; + /** Used to map method names to iteratee rearg configs. */ + + exports.iterateeRearg = { + 'mapKeys': [1], + 'reduceRight': [1, 0] + }; + /** Used to map method names to rearg configs. */ + + exports.methodRearg = { + 'assignInAllWith': [1, 0], + 'assignInWith': [1, 2, 0], + 'assignAllWith': [1, 0], + 'assignWith': [1, 2, 0], + 'differenceBy': [1, 2, 0], + 'differenceWith': [1, 2, 0], + 'getOr': [2, 1, 0], + 'intersectionBy': [1, 2, 0], + 'intersectionWith': [1, 2, 0], + 'isEqualWith': [1, 2, 0], + 'isMatchWith': [2, 1, 0], + 'mergeAllWith': [1, 0], + 'mergeWith': [1, 2, 0], + 'padChars': [2, 1, 0], + 'padCharsEnd': [2, 1, 0], + 'padCharsStart': [2, 1, 0], + 'pullAllBy': [2, 1, 0], + 'pullAllWith': [2, 1, 0], + 'rangeStep': [1, 2, 0], + 'rangeStepRight': [1, 2, 0], + 'setWith': [3, 1, 2, 0], + 'sortedIndexBy': [2, 1, 0], + 'sortedLastIndexBy': [2, 1, 0], + 'unionBy': [1, 2, 0], + 'unionWith': [1, 2, 0], + 'updateWith': [3, 1, 2, 0], + 'xorBy': [1, 2, 0], + 'xorWith': [1, 2, 0], + 'zipWith': [1, 2, 0] + }; + /** Used to map method names to spread configs. */ + + exports.methodSpread = { + 'assignAll': { + 'start': 0 + }, + 'assignAllWith': { + 'start': 0 + }, + 'assignInAll': { + 'start': 0 + }, + 'assignInAllWith': { + 'start': 0 + }, + 'defaultsAll': { + 'start': 0 + }, + 'defaultsDeepAll': { + 'start': 0 + }, + 'invokeArgs': { + 'start': 2 + }, + 'invokeArgsMap': { + 'start': 2 + }, + 'mergeAll': { + 'start': 0 + }, + 'mergeAllWith': { + 'start': 0 + }, + 'partial': { + 'start': 1 + }, + 'partialRight': { + 'start': 1 + }, + 'without': { + 'start': 1 + }, + 'zipAll': { + 'start': 0 + } + }; + /** Used to identify methods which mutate arrays or objects. */ + + exports.mutate = { + 'array': { + 'fill': true, + 'pull': true, + 'pullAll': true, + 'pullAllBy': true, + 'pullAllWith': true, + 'pullAt': true, + 'remove': true, + 'reverse': true + }, + 'object': { + 'assign': true, + 'assignAll': true, + 'assignAllWith': true, + 'assignIn': true, + 'assignInAll': true, + 'assignInAllWith': true, + 'assignInWith': true, + 'assignWith': true, + 'defaults': true, + 'defaultsAll': true, + 'defaultsDeep': true, + 'defaultsDeepAll': true, + 'merge': true, + 'mergeAll': true, + 'mergeAllWith': true, + 'mergeWith': true + }, + 'set': { + 'set': true, + 'setWith': true, + 'unset': true, + 'update': true, + 'updateWith': true + } + }; + /** Used to track methods with placeholder support */ + + exports.placeholder = { + 'bind': true, + 'bindKey': true, + 'curry': true, + 'curryRight': true, + 'partial': true, + 'partialRight': true + }; + /** Used to map real names to their aliases. */ + + exports.realToAlias = function () { + var hasOwnProperty = Object.prototype.hasOwnProperty, + object = exports.aliasToReal, + result = {}; + + for (var key in object) { + var value = object[key]; + + if (hasOwnProperty.call(result, value)) { + result[value].push(key); + } else { + result[value] = [key]; + } + } + + return result; + }(); + /** Used to map method names to other names. */ + + + exports.remap = { + 'assignAll': 'assign', + 'assignAllWith': 'assignWith', + 'assignInAll': 'assignIn', + 'assignInAllWith': 'assignInWith', + 'curryN': 'curry', + 'curryRightN': 'curryRight', + 'defaultsAll': 'defaults', + 'defaultsDeepAll': 'defaultsDeep', + 'findFrom': 'find', + 'findIndexFrom': 'findIndex', + 'findLastFrom': 'findLast', + 'findLastIndexFrom': 'findLastIndex', + 'getOr': 'get', + 'includesFrom': 'includes', + 'indexOfFrom': 'indexOf', + 'invokeArgs': 'invoke', + 'invokeArgsMap': 'invokeMap', + 'lastIndexOfFrom': 'lastIndexOf', + 'mergeAll': 'merge', + 'mergeAllWith': 'mergeWith', + 'padChars': 'pad', + 'padCharsEnd': 'padEnd', + 'padCharsStart': 'padStart', + 'propertyOf': 'get', + 'rangeStep': 'range', + 'rangeStepRight': 'rangeRight', + 'restFrom': 'rest', + 'spreadFrom': 'spread', + 'trimChars': 'trim', + 'trimCharsEnd': 'trimEnd', + 'trimCharsStart': 'trimStart', + 'zipAll': 'zip' + }; + /** Used to track methods that skip fixing their arity. */ + + exports.skipFixed = { + 'castArray': true, + 'flow': true, + 'flowRight': true, + 'iteratee': true, + 'mixin': true, + 'rearg': true, + 'runInContext': true + }; + /** Used to track methods that skip rearranging arguments. */ + + exports.skipRearg = { + 'add': true, + 'assign': true, + 'assignIn': true, + 'bind': true, + 'bindKey': true, + 'concat': true, + 'difference': true, + 'divide': true, + 'eq': true, + 'gt': true, + 'gte': true, + 'isEqual': true, + 'lt': true, + 'lte': true, + 'matchesProperty': true, + 'merge': true, + 'multiply': true, + 'overArgs': true, + 'partial': true, + 'partialRight': true, + 'propertyOf': true, + 'random': true, + 'range': true, + 'rangeRight': true, + 'subtract': true, + 'zip': true, + 'zipObject': true, + 'zipObjectDeep': true + }; + /***/ + }, + /* 3 */ + + /***/ + function (module, exports) { + /** + * The default argument placeholder value for methods. + * + * @type {Object} + */ + module.exports = {}; + /***/ + } + /******/ + ]) + ); +}); + +; + +/***/ }), + +/***/ "./node_modules/awesomplete-avoid-xss/awesomplete.js": +/*!***********************************************************!*\ + !*** ./node_modules/awesomplete-avoid-xss/awesomplete.js ***! + \***********************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + /** - * @license almond 0.3.3 Copyright jQuery Foundation and other contributors. - * Released under MIT license, http://github.com/requirejs/almond/LICENSE + * Simple, lightweight, usable local autocomplete library for modern browsers + * Because there weren’t enough autocomplete scripts in the world? Because I’m completely insane and have NIH syndrome? Probably both. :P + * @author Lea Verou http://leaverou.github.io/awesomplete + * MIT license */ -var e,t,f,a,n;return function(a){var n,o,r,s,c={},i={},u={},_={},d=Object.prototype.hasOwnProperty,l=[].slice,h=/\.js$/;function m(e,t){return d.call(e,t)}function g(e,t){var f,a,n,o,r,s,c,i,_,d,l,m=t&&t.split("/"),g=u.map,p=g&&g["*"]||{};if(e){for(r=(e=e.split("/")).length-1,u.nodeIdCompat&&h.test(e[r])&&(e[r]=e[r].replace(h,"")),"."===e[0].charAt(0)&&m&&(e=m.slice(0,m.length-1).concat(e)),_=0;_0&&(e.splice(_-1,2),_-=2)}e=e.join("/")}if((m||p)&&g){for(_=(f=e.split("/")).length;_>0;_-=1){if(a=f.slice(0,_).join("/"),m)for(d=m.length;d>0;d-=1)if((n=g[m.slice(0,d).join("/")])&&(n=n[a])){o=n,s=_;break}if(o)break;!c&&p&&p[a]&&(c=p[a],i=_)}!o&&c&&(o=c,s=i),o&&(f.splice(0,s,o),e=f.join("/"))}return e}function p(e,t){return function(){var f=l.call(arguments,0);return"string"!=typeof f[0]&&1===f.length&&f.push(null),o.apply(a,f.concat([e,t]))}}function b(e){return function(t){c[e]=t}}function y(e){if(m(i,e)){var t=i[e];delete i[e],_[e]=!0,n.apply(a,t)}if(!m(c,e)&&!m(_,e))throw new Error("No "+e);return c[e]}function v(e){var t,f=e?e.indexOf("!"):-1;return f>-1&&(t=e.substring(0,f),e=e.substring(f+1,e.length)),[t,e]}function w(e){return e?v(e):[]}r=function(e,t){var f,a,n=v(e),o=n[0],r=t[1];return e=n[1],o&&(f=y(o=g(o,r))),o?e=f&&f.normalize?f.normalize(e,(a=r,function(e){return g(e,a)})):g(e,r):(o=(n=v(e=g(e,r)))[0],e=n[1],o&&(f=y(o))),{f:o?o+"!"+e:e,n:e,pr:o,p:f}},s={require:function(e){return p(e)},exports:function(e){var t=c[e];return void 0!==t?t:c[e]={}},module:function(e){return{id:e,uri:"",exports:c[e],config:function(e){return function(){return u&&u.config&&u.config[e]||{}}}(e)}}},n=function(e,t,f,n){var o,u,d,l,h,g,v,k=[],M=typeof f;if(g=w(n=n||e),"undefined"===M||"function"===M){for(t=!t.length&&f.length?["require","exports","module"]:t,h=0;h>>0;if("function"!=typeof e)throw new TypeError(e+" is not a function");for(arguments.length>1&&(f=t),a=0;a>2,r=(3&f)<<4|(a=e.charCodeAt(u++))>>4,s=(15&a)<<2|(n=e.charCodeAt(u++))>>6,c=63&n,isNaN(a)?(r=(3&f)<<4,s=c=64):isNaN(n)&&(c=64),i=i+t.charAt(o)+t.charAt(r)+t.charAt(s)+t.charAt(c)}while(u>4,a=(15&o)<<4|(r=t.indexOf(e.charAt(i++)))>>2,n=(3&r)<<6|(s=t.indexOf(e.charAt(i++))),c+=String.fromCharCode(f),64!==r&&(c+=String.fromCharCode(a)),64!==s&&(c+=String.fromCharCode(n))}while(i>5]|=128<<24-a%32,e[15+(a+64>>9<<4)]=a;var r,s,c,i,u,_,d,l,h=new Array(80),m=1732584193,g=-271733879,p=-1732584194,b=271733878,y=-1009589776;for(r=0;r16&&(a=e(a,8*t.length));for(var n=new Array(16),o=new Array(16),s=0;s<16;s++)n[s]=909522486^a[s],o[s]=1549556828^a[s];var c=e(n.concat(r(f)),512+8*f.length);return e(o.concat(c),672)}function n(e,t){var f=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(f>>16)<<16|65535&f}function o(e,t){return e<>>32-t}function r(e){for(var t=[],f=0;f<8*e.length;f+=8)t[f>>5]|=(255&e.charCodeAt(f/8))<<24-f%32;return t}function s(e){for(var t="",f=0;f<32*e.length;f+=8)t+=String.fromCharCode(e[f>>5]>>>24-f%32&255);return t}function c(e){for(var t,f,a="",n=0;n<4*e.length;n+=3)for(t=(e[n>>2]>>8*(3-n%4)&255)<<16|(e[n+1>>2]>>8*(3-(n+1)%4)&255)<<8|e[n+2>>2]>>8*(3-(n+2)%4)&255,f=0;f<4;f++)8*n+6*f>32*e.length?a+="=":a+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(t>>6*(3-f)&63);return a}return{b64_hmac_sha1:function(e,t){return c(a(e,t))},b64_sha1:function(t){return c(e(r(t),8*t.length))},binb2str:s,core_hmac_sha1:a,str_hmac_sha1:function(e,t){return s(a(e,t))},str_sha1:function(t){return s(e(r(t),8*t.length))}}}),function(e,t){"function"==typeof f&&f.amd?f("strophe-md5",[],function(){return t()}):e.MD5=t()}(this,function(){var e=function(e,t){var f=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(f>>16)<<16|65535&f},t=function(e){for(var t=[],f=0;f<8*e.length;f+=8)t[f>>5]|=(255&e.charCodeAt(f/8))<>>32-c,a);var s,c},a=function(e,t,a,n,o,r,s){return f(t&a|~t&n,e,t,o,r,s)},n=function(e,t,a,n,o,r,s){return f(t&n|a&~n,e,t,o,r,s)},o=function(e,t,a,n,o,r,s){return f(t^a^n,e,t,o,r,s)},r=function(e,t,a,n,o,r,s){return f(a^(t|~n),e,t,o,r,s)},s=function(t,f){t[f>>5]|=128<>>9<<4)]=f;for(var s,c,i,u,_=1732584193,d=-271733879,l=-1732584194,h=271733878,m=0;m>2]>>f%4*8+4&15)+"0123456789abcdef".charAt(e[f>>2]>>f%4*8&15);return t}(s(t(e),8*e.length))},hash:function(e){return function(e){for(var t="",f=0;f<32*e.length;f+=8)t+=String.fromCharCode(e[f>>5]>>>f%32&255);return t}(s(t(e),8*e.length))}}}),function(e,t){"function"==typeof f&&f.amd?f("strophe-utils",[],function(){return t()}):e.stropheUtils=t()}(this,function(){return{utf16to8:function(e){var t,f,a="",n=e.length;for(t=0;t=0&&f<=127?a+=e.charAt(t):f>2047?(a+=String.fromCharCode(224|f>>12&15),a+=String.fromCharCode(128|f>>6&63),a+=String.fromCharCode(128|f>>0&63)):(a+=String.fromCharCode(192|f>>6&31),a+=String.fromCharCode(128|f>>0&63));return a},addCookies:function(e){var t,f,a,n,o,r,s;for(t in e||{})o="",r="",s="",a="object"==typeof(f=e[t]),n=escape(unescape(a?f.value:f)),a&&(o=f.expires?";expires="+f.expires:"",r=f.domain?";domain="+f.domain:"",s=f.path?";path="+f.path:""),document.cookie=t+"="+n+o+r+s}}}),function(e,t){if("function"==typeof f&&f.amd)f("strophe-core",["strophe-sha1","strophe-md5","strophe-utils"],function(){return t.apply(this,arguments)});else{var a=t(e.SHA1,e.MD5,e.stropheUtils);e.Strophe=a.Strophe,e.$build=a.$build,e.$iq=a.$iq,e.$msg=a.$msg,e.$pres=a.$pres,e.SHA1=a.SHA1,e.MD5=a.MD5,e.b64_hmac_sha1=a.SHA1.b64_hmac_sha1,e.b64_sha1=a.SHA1.b64_sha1,e.str_hmac_sha1=a.SHA1.str_hmac_sha1,e.str_sha1=a.SHA1.str_sha1}}(this,function(e,t,f){var a;function n(e,t){return new a.Builder(e,t)}function o(e){return new a.Builder("iq",e)}function r(e){return new a.Builder("presence",e)}return(a={VERSION:"1.2.14",NS:{HTTPBIND:"http://jabber.org/protocol/httpbind",BOSH:"urn:xmpp:xbosh",CLIENT:"jabber:client",AUTH:"jabber:iq:auth",ROSTER:"jabber:iq:roster",PROFILE:"jabber:iq:profile",DISCO_INFO:"http://jabber.org/protocol/disco#info",DISCO_ITEMS:"http://jabber.org/protocol/disco#items",MUC:"http://jabber.org/protocol/muc",SASL:"urn:ietf:params:xml:ns:xmpp-sasl",STREAM:"http://etherx.jabber.org/streams",FRAMING:"urn:ietf:params:xml:ns:xmpp-framing",BIND:"urn:ietf:params:xml:ns:xmpp-bind",SESSION:"urn:ietf:params:xml:ns:xmpp-session",VERSION:"jabber:iq:version",STANZAS:"urn:ietf:params:xml:ns:xmpp-stanzas",XHTML_IM:"http://jabber.org/protocol/xhtml-im",XHTML:"http://www.w3.org/1999/xhtml"},XHTML:{tags:["a","blockquote","br","cite","em","img","li","ol","p","span","strong","ul","body"],attributes:{a:["href"],blockquote:["style"],br:[],cite:["style"],em:[],img:["src","alt","style","height","width"],li:["style"],ol:["style"],p:["style"],span:["style"],strong:[],ul:["style"],body:[]},css:["background-color","color","font-family","font-size","font-style","font-weight","margin-left","margin-right","text-align","text-decoration"],validTag:function(e){for(var t=0;t0)for(var f=0;f/g,">")).replace(/'/g,"'")).replace(/"/g,""")},xmlunescape:function(e){return e=(e=(e=(e=(e=e.replace(/\&/g,"&")).replace(/</g,"<")).replace(/>/g,">")).replace(/'/g,"'")).replace(/"/g,'"')},xmlTextNode:function(e){return a.xmlGenerator().createTextNode(e)},xmlHtmlNode:function(e){var t;return DOMParser?t=(new DOMParser).parseFromString(e,"text/xml"):((t=new ActiveXObject("Microsoft.XMLDOM")).async="false",t.loadXML(e)),t},getText:function(e){if(!e)return null;var t="";0===e.childNodes.length&&e.nodeType===a.ElementType.TEXT&&(t+=e.nodeValue);for(var f=0;f0&&(s=c.join("; "),f.setAttribute(r,s))}else f.setAttribute(r,s);for(t=0;t/g,"\\3e").replace(/@/g,"\\40")},unescapeNode:function(e){return"string"!=typeof e?e:e.replace(/\\20/g," ").replace(/\\22/g,'"').replace(/\\26/g,"&").replace(/\\27/g,"'").replace(/\\2f/g,"/").replace(/\\3a/g,":").replace(/\\3c/g,"<").replace(/\\3e/g,">").replace(/\\40/g,"@").replace(/\\5c/g,"\\")},getNodeFromJid:function(e){return e.indexOf("@")<0?null:e.split("@")[0]},getDomainFromJid:function(e){var t=a.getBareJidFromJid(e);if(t.indexOf("@")<0)return t;var f=t.split("@");return f.splice(0,1),f.join("@")},getResourceFromJid:function(e){var t=e.split("/");return t.length<2?null:(t.splice(0,1),t.join("/"))},getBareJidFromJid:function(e){return e?e.split("/")[0]:null},_handleError:function(e){void 0!==e.stack&&a.fatal(e.stack),e.sourceURL?a.fatal("error: "+this.handler+" "+e.sourceURL+":"+e.line+" - "+e.name+": "+e.message):e.fileName?a.fatal("error: "+this.handler+" "+e.fileName+":"+e.lineNumber+" - "+e.name+": "+e.message):a.fatal("error: "+e.message)},log:function(e,t){},debug:function(e){this.log(this.LogLevel.DEBUG,e)},info:function(e){this.log(this.LogLevel.INFO,e)},warn:function(e){this.log(this.LogLevel.WARN,e)},error:function(e){this.log(this.LogLevel.ERROR,e)},fatal:function(e){this.log(this.LogLevel.FATAL,e)},serialize:function(e){var t;if(!e)return null;"function"==typeof e.tree&&(e=e.tree());var f,n,o=e.nodeName;for(e.getAttribute("_realname")&&(o=e.getAttribute("_realname")),t="<"+o,f=0;f0){for(t+=">",f=0;f"}t+=""}else t+="/>";return t},_requestId:0,_connectionPlugins:{},addConnectionPlugin:function(e,t){a._connectionPlugins[e]=t}}).Builder=function(e,t){"presence"!==e&&"message"!==e&&"iq"!==e||(t&&!t.xmlns?t.xmlns=a.NS.CLIENT:t||(t={xmlns:a.NS.CLIENT})),this.nodeTree=a.xmlElement(e,t),this.node=this.nodeTree},a.Builder.prototype={tree:function(){return this.nodeTree},toString:function(){return a.serialize(this.nodeTree)},up:function(){return this.node=this.node.parentNode,this},root:function(){return this.node=this.nodeTree,this},attrs:function(e){for(var t in e)e.hasOwnProperty(t)&&(void 0===e[t]?this.node.removeAttribute(t):this.node.setAttribute(t,e[t]));return this},c:function(e,t,f){var n=a.xmlElement(e,t,f);return this.node.appendChild(n),"string"!=typeof f&&"number"!=typeof f&&(this.node=n),this},cnode:function(e){var t,f=a.xmlGenerator();try{t=void 0!==f.importNode}catch(e){t=!1}var n=t?f.importNode(e,!0):a.copyElement(e);return this.node.appendChild(n),this.node=n,this},t:function(e){var t=a.xmlTextNode(e);return this.node.appendChild(t),this},h:function(e){var t=document.createElement("body");t.innerHTML=e;for(var f=a.createHtml(t);f.childNodes.length>0;)this.node.appendChild(f.childNodes[0]);return this}},a.Handler=function(e,t,f,n,o,r,s){this.handler=e,this.ns=t,this.name=f,this.type=n,this.id=o,this.options=s||{matchBareFromJid:!1,ignoreNamespaceFragment:!1},this.options.matchBare&&(a.warn('The "matchBare" option is deprecated, use "matchBareFromJid" instead.'),this.options.matchBareFromJid=this.options.matchBare,delete this.options.matchBare),this.options.matchBareFromJid?this.from=r?a.getBareJidFromJid(r):null:this.from=r,this.user=!0},a.Handler.prototype={getNamespace:function(e){var t=e.getAttribute("xmlns");return t&&this.options.ignoreNamespaceFragment&&(t=t.split("#")[0]),t},namespaceMatch:function(e){var t=!1;if(!this.ns)return!0;var f=this;return a.forEachChild(e,null,function(e){f.getNamespace(e)===f.ns&&(t=!0)}),t=t||this.getNamespace(e)===this.ns},isMatch:function(e){var t=e.getAttribute("from");this.options.matchBareFromJid&&(t=a.getBareJidFromJid(t));var f=e.getAttribute("type");return!(!this.namespaceMatch(e)||this.name&&!a.isTagEqual(e,this.name)||this.type&&(Array.isArray(this.type)?-1===this.type.indexOf(f):f!==this.type)||this.id&&e.getAttribute("id")!==this.id||this.from&&t!==this.from)},run:function(e){var t=null;try{t=this.handler(e)}catch(e){throw a._handleError(e),e}return t},toString:function(){return"{Handler: "+this.handler+"("+this.name+","+this.id+","+this.ns+")}"}},a.TimedHandler=function(e,t){this.period=e,this.handler=t,this.lastCalled=(new Date).getTime(),this.user=!0},a.TimedHandler.prototype={run:function(){return this.lastCalled=(new Date).getTime(),this.handler()},reset:function(){this.lastCalled=(new Date).getTime()},toString:function(){return"{TimedHandler: "+this.handler+"("+this.period+")}"}},a.Connection=function(e,t){this.service=e,this.options=t||{};var n=this.options.protocol||"";for(var o in 0===e.indexOf("ws:")||0===e.indexOf("wss:")||0===n.indexOf("ws")?this._proto=new a.Websocket(this):this._proto=new a.Bosh(this),this.jid="",this.domain=null,this.features=null,this._sasl_data={},this.do_session=!1,this.do_bind=!1,this.timedHandlers=[],this.handlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this.protocolErrorHandlers={HTTP:{},websocket:{}},this._idleTimeout=null,this._disconnectTimeout=null,this.authenticated=!1,this.connected=!1,this.disconnecting=!1,this.do_authentication=!0,this.paused=!1,this.restored=!1,this._data=[],this._uniqueId=0,this._sasl_success_handler=null,this._sasl_failure_handler=null,this._sasl_challenge_handler=null,this.maxRetries=5,this._idleTimeout=setTimeout(function(){this._onIdle()}.bind(this),100),f.addCookies(this.options.cookies),this.registerSASLMechanisms(this.options.mechanisms),a._connectionPlugins)if(a._connectionPlugins.hasOwnProperty(o)){var r=a._connectionPlugins[o],s=function(){};s.prototype=r,this[o]=new s,this[o].init(this)}},a.Connection.prototype={reset:function(){this._proto._reset(),this.do_session=!1,this.do_bind=!1,this.timedHandlers=[],this.handlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this.authenticated=!1,this.connected=!1,this.disconnecting=!1,this.restored=!1,this._data=[],this._requests=[],this._uniqueId=0},pause:function(){this.paused=!0},resume:function(){this.paused=!1},getUniqueId:function(e){var t="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)});return"string"==typeof e||"number"==typeof e?t+":"+e:t+""},addProtocolErrorHandler:function(e,t,f){this.protocolErrorHandlers[e][t]=f},connect:function(e,t,f,n,o,r,s){this.jid=e,this.authzid=a.getBareJidFromJid(this.jid),this.authcid=s||a.getNodeFromJid(this.jid),this.pass=t,this.servtype="xmpp",this.connect_callback=f,this.disconnecting=!1,this.connected=!1,this.authenticated=!1,this.restored=!1,this.domain=a.getDomainFromJid(this.jid),this._changeConnectStatus(a.Status.CONNECTING,null),this._proto._connect(n,o,r)},attach:function(e,t,f,n,o,r,s){if(!(this._proto instanceof a.Bosh))throw{name:"StropheSessionError",message:'The "attach" method can only be used with a BOSH connection.'};this._proto._attach(e,t,f,n,o,r,s)},restore:function(e,t,f,a,n){if(!this._sessionCachingSupported())throw{name:"StropheSessionError",message:'The "restore" method can only be used with a BOSH connection.'};this._proto._restore(e,t,f,a,n)},_sessionCachingSupported:function(){if(this._proto instanceof a.Bosh){if(!JSON)return!1;try{sessionStorage.setItem("_strophe_","_strophe_"),sessionStorage.removeItem("_strophe_")}catch(e){return!1}return!0}return!1},xmlInput:function(e){},xmlOutput:function(e){},rawInput:function(e){},rawOutput:function(e){},nextValidRid:function(e){},send:function(e){if(null!==e){if("function"==typeof e.sort)for(var t=0;t=0&&this.addHandlers.splice(t,1)},registerSASLMechanisms:function(e){this.mechanisms={},(e=e||[a.SASLAnonymous,a.SASLExternal,a.SASLMD5,a.SASLOAuthBearer,a.SASLPlain,a.SASLSHA1]).forEach(this.registerSASLMechanism.bind(this))},registerSASLMechanism:function(e){this.mechanisms[e.prototype.name]=e},disconnect:function(e){if(this._changeConnectStatus(a.Status.DISCONNECTING,e),a.info("Disconnect was called because: "+e),this.connected){var t=!1;this.disconnecting=!0,this.authenticated&&(t=r({xmlns:a.NS.CLIENT,type:"unavailable"})),this._disconnectTimeout=this._addSysTimedHandler(3e3,this._onDisconnectTimeout.bind(this)),this._proto._disconnect(t)}else a.info("Disconnect was called before Strophe connected to the server"),this._proto._abortAllRequests(),this._doDisconnect()},_changeConnectStatus:function(e,t){for(var f in a._connectionPlugins)if(a._connectionPlugins.hasOwnProperty(f)){var n=this[f];if(n.statusChanged)try{n.statusChanged(e,t)}catch(e){a.error(f+" plugin caused an exception changing status: "+e)}}if(this.connect_callback)try{this.connect_callback(e,t)}catch(e){a._handleError(e),a.error("User connection callback caused an exception: "+e)}},_doDisconnect:function(e){"number"==typeof this._idleTimeout&&clearTimeout(this._idleTimeout),null!==this._disconnectTimeout&&(this.deleteTimedHandler(this._disconnectTimeout),this._disconnectTimeout=null),a.info("_doDisconnect was called"),this._proto._doDisconnect(),this.authenticated=!1,this.disconnecting=!1,this.restored=!1,this.handlers=[],this.timedHandlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this._changeConnectStatus(a.Status.DISCONNECTED,e),this.connected=!1},_dataRecv:function(e,t){a.info("_dataRecv called");var f=this._proto._reqToData(e);if(null!==f){var n,o;for(this.xmlInput!==a.Connection.prototype.xmlInput&&(f.nodeName===this._proto.strip&&f.childNodes.length?this.xmlInput(f.childNodes[0]):this.xmlInput(f)),this.rawInput!==a.Connection.prototype.rawInput&&(t?this.rawInput(t):this.rawInput(a.serialize(f)));this.removeHandlers.length>0;)o=this.removeHandlers.pop(),(n=this.handlers.indexOf(o))>=0&&this.handlers.splice(n,1);for(;this.addHandlers.length>0;)this.handlers.push(this.addHandlers.pop());if(this.disconnecting&&this._proto._emptyQueue())this._doDisconnect();else{var r,s,c=f.getAttribute("type");if(null!==c&&"terminate"===c){if(this.disconnecting)return;return r=f.getAttribute("condition"),s=f.getElementsByTagName("conflict"),null!==r?("remote-stream-error"===r&&s.length>0&&(r="conflict"),this._changeConnectStatus(a.Status.CONNFAIL,r)):this._changeConnectStatus(a.Status.CONNFAIL,"unknown"),void this._doDisconnect(r)}var i=this;a.forEachChild(f,null,function(e){var t,f;for(f=i.handlers,i.handlers=[],t=0;t0:n.getElementsByTagName("stream:features").length>0||n.getElementsByTagName("features").length>0){var o,r,s=[],c=n.getElementsByTagName("mechanism");if(c.length>0)for(o=0;oe[a].prototype.priority&&(a=f);a!==t&&(n=e[t],e[t]=e[a],e[a]=n)}return e},_attemptSASLAuth:function(e){e=this.sortMechanismsByPriority(e||[]);var t=0,f=!1;for(t=0;t0&&(t="conflict"),this._changeConnectStatus(a.Status.AUTHFAIL,t),!1;var f,n=e.getElementsByTagName("bind");if(!(n.length>0))return a.info("SASL binding failed."),this._changeConnectStatus(a.Status.AUTHFAIL,null),!1;(f=n[0].getElementsByTagName("jid")).length>0&&(this.jid=a.getText(f[0]),this.do_session?(this._addSysHandler(this._sasl_session_cb.bind(this),null,null,null,"_session_auth_2"),this.send(o({type:"set",id:"_session_auth_2"}).c("session",{xmlns:a.NS.SESSION}).tree())):(this.authenticated=!0,this._changeConnectStatus(a.Status.CONNECTED,null)))},_sasl_session_cb:function(e){if("result"===e.getAttribute("type"))this.authenticated=!0,this._changeConnectStatus(a.Status.CONNECTED,null);else if("error"===e.getAttribute("type"))return a.info("Session creation failed."),this._changeConnectStatus(a.Status.AUTHFAIL,null),!1;return!1},_sasl_failure_cb:function(e){return this._sasl_success_handler&&(this.deleteHandler(this._sasl_success_handler),this._sasl_success_handler=null),this._sasl_challenge_handler&&(this.deleteHandler(this._sasl_challenge_handler),this._sasl_challenge_handler=null),this._sasl_mechanism&&this._sasl_mechanism.onFailure(),this._changeConnectStatus(a.Status.AUTHFAIL,null),!1},_auth2_cb:function(e){return"result"===e.getAttribute("type")?(this.authenticated=!0,this._changeConnectStatus(a.Status.CONNECTED,null)):"error"===e.getAttribute("type")&&(this._changeConnectStatus(a.Status.AUTHFAIL,null),this.disconnect("authentication failed")),!1},_addSysTimedHandler:function(e,t){var f=new a.TimedHandler(e,t);return f.user=!1,this.addTimeds.push(f),f},_addSysHandler:function(e,t,f,n,o){var r=new a.Handler(e,t,f,n,o);return r.user=!1,this.addHandlers.push(r),r},_onDisconnectTimeout:function(){return a.info("_onDisconnectTimeout was called"),this._changeConnectStatus(a.Status.CONNTIMEOUT,null),this._proto._onDisconnectTimeout(),this._doDisconnect(),!1},_onIdle:function(){for(var e,t,f;this.addTimeds.length>0;)this.timedHandlers.push(this.addTimeds.pop());for(;this.removeTimeds.length>0;)t=this.removeTimeds.pop(),(e=this.timedHandlers.indexOf(t))>=0&&this.timedHandlers.splice(e,1);var a=(new Date).getTime();for(f=[],e=0;e0&&(f="conflict"),this._conn._changeConnectStatus(e.Status.CONNFAIL,f)):this._conn._changeConnectStatus(e.Status.CONNFAIL,"unknown"),this._conn._doDisconnect(f),e.Status.CONNFAIL;this.sid||(this.sid=t.getAttribute("sid"));var o=t.getAttribute("requests");o&&(this.window=parseInt(o,10));var r=t.getAttribute("hold");r&&(this.hold=parseInt(r,10));var s=t.getAttribute("wait");s&&(this.wait=parseInt(s,10));var c=t.getAttribute("inactivity");c&&(this.inactivity=parseInt(c,10))},_disconnect:function(e){this._sendTerminate(e)},_doDisconnect:function(){this.sid=null,this.rid=Math.floor(4294967295*Math.random()),this._conn._sessionCachingSupported()&&window.sessionStorage.removeItem("strophe-bosh-session"),this._conn.nextValidRid(this.rid)},_emptyQueue:function(){return 0===this._requests.length},_callProtocolErrorHandlers:function(e){var t,f=this._getRequestStatus(e);(t=this._conn.protocolErrorHandlers.HTTP[f])&&t.call(this,f)},_hitError:function(t){this.errors++,e.warn("request errored, status: "+t+", number of errors: "+this.errors),this.errors>4&&this._conn._onDisconnectTimeout()},_no_auth_received:function(t){t=t?t.bind(this._conn):this._conn._connect_cb.bind(this._conn);var f=this._buildBody();this._requests.push(new e.Request(f.tree(),this._onRequestStateChange.bind(this,t.bind(this._conn)),f.tree().getAttribute("rid"))),this._throttledRequestHandler()},_onDisconnectTimeout:function(){this._abortAllRequests()},_abortAllRequests:function(){for(var e;this._requests.length>0;)(e=this._requests.pop()).abort=!0,e.xhr.abort(),e.xhr.onreadystatechange=function(){}},_onIdle:function(){var t=this._conn._data;if(this._conn.authenticated&&0===this._requests.length&&0===t.length&&!this._conn.disconnecting&&(e.info("no requests during idle cycle, sending blank request"),t.push(null)),!this._conn.paused){if(this._requests.length<2&&t.length>0){for(var f=this._buildBody(),a=0;a0){var n=this._requests[0].age();null!==this._requests[0].dead&&this._requests[0].timeDead()>Math.floor(e.SECONDARY_TIMEOUT*this.wait)&&this._throttledRequestHandler(),n>Math.floor(e.TIMEOUT*this.wait)&&(e.warn("Request "+this._requests[0].id+" timed out, over "+Math.floor(e.TIMEOUT*this.wait)+" seconds since last activity"),this._throttledRequestHandler())}}},_getRequestStatus:function(t,f){var a;if(4===t.xhr.readyState)try{a=t.xhr.status}catch(t){e.error("Caught an error while retrieving a request's status, reqStatus: "+a)}return void 0===a&&(a="number"==typeof f?f:0),a},_onRequestStateChange:function(t,f){if(e.debug("request id "+f.id+"."+f.sends+" state changed to "+f.xhr.readyState),f.abort)f.abort=!1;else if(4===f.xhr.readyState){var a=this._getRequestStatus(f);if(this.disconnecting&&a>=400)return this._hitError(a),void this._callProtocolErrorHandlers(f);var n=a>0&&a<500,o=f.sends>this._conn.maxRetries;if((n||o)&&(this._removeRequest(f),e.debug("request id "+f.id+" should now be removed")),200===a){var r=this._requests[0]===f;(this._requests[1]===f||r&&this._requests.length>0&&this._requests[0].age()>Math.floor(e.SECONDARY_TIMEOUT*this.wait))&&this._restartRequest(0),this._conn.nextValidRid(Number(f.rid)+1),e.debug("request id "+f.id+"."+f.sends+" got 200"),t(f),this.errors=0}else 0===a||a>=400&&a<600||a>=12e3?(e.error("request id "+f.id+"."+f.sends+" error "+a+" happened"),this._hitError(a),this._callProtocolErrorHandlers(f),a>=400&&a<500&&(this._conn._changeConnectStatus(e.Status.DISCONNECTING,null),this._conn._doDisconnect())):e.error("request id "+f.id+"."+f.sends+" error "+a+" happened");n||o?o&&!this._conn.connected&&this._conn._changeConnectStatus(e.Status.CONNFAIL,"giving-up"):this._throttledRequestHandler()}},_processRequest:function(t){var f=this,a=this._requests[t],n=this._getRequestStatus(a,-1);if(a.sends>this._conn.maxRetries)this._conn._onDisconnectTimeout();else{var o=a.age(),r=!isNaN(o)&&o>Math.floor(e.TIMEOUT*this.wait),s=null!==a.dead&&a.timeDead()>Math.floor(e.SECONDARY_TIMEOUT*this.wait),c=4===a.xhr.readyState&&(n<1||n>=500);if((r||s||c)&&(s&&e.error("Request "+this._requests[t].id+" timed out (secondary), restarting"),a.abort=!0,a.xhr.abort(),a.xhr.onreadystatechange=function(){},this._requests[t]=new e.Request(a.xmlData,a.origFunc,a.rid,a.sends),a=this._requests[t]),0===a.xhr.readyState){e.debug("request id "+a.id+"."+a.sends+" posting");try{var i=this._conn.options.contentType||"text/xml; charset=utf-8";a.xhr.open("POST",this._conn.service,!this._conn.options.sync),void 0!==a.xhr.setRequestHeader&&a.xhr.setRequestHeader("Content-Type",i),this._conn.options.withCredentials&&(a.xhr.withCredentials=!0)}catch(t){return e.error("XHR open failed: "+t.toString()),this._conn.connected||this._conn._changeConnectStatus(e.Status.CONNFAIL,"bad-service"),void this._conn.disconnect()}var u=function(){if(a.date=new Date,f._conn.options.customHeaders){var e=f._conn.options.customHeaders;for(var t in e)e.hasOwnProperty(t)&&a.xhr.setRequestHeader(t,e[t])}a.xhr.send(a.data)};if(a.sends>1){var _=1e3*Math.min(Math.floor(e.TIMEOUT*this.wait),Math.pow(a.sends,3));setTimeout(function(){u()},_)}else u();a.sends++,this._conn.xmlOutput!==e.Connection.prototype.xmlOutput&&(a.xmlData.nodeName===this.strip&&a.xmlData.childNodes.length?this._conn.xmlOutput(a.xmlData.childNodes[0]):this._conn.xmlOutput(a.xmlData)),this._conn.rawOutput!==e.Connection.prototype.rawOutput&&this._conn.rawOutput(a.data)}else e.debug("_processRequest: "+(0===t?"first":"second")+" request has readyState of "+a.xhr.readyState)}},_removeRequest:function(t){var f;for(e.debug("removing request"),f=this._requests.length-1;f>=0;f--)t===this._requests[f]&&this._requests.splice(f,1);t.xhr.onreadystatechange=function(){},this._throttledRequestHandler()},_restartRequest:function(e){var t=this._requests[e];null===t.dead&&(t.dead=new Date),this._processRequest(e)},_reqToData:function(e){try{return e.getResponse()}catch(e){if("parsererror"!==e)throw e;this._conn.disconnect("strophe-parsererror")}},_sendTerminate:function(t){e.info("_sendTerminate was called");var f=this._buildBody().attrs({type:"terminate"});t&&f.cnode(t.tree());var a=new e.Request(f.tree(),this._onRequestStateChange.bind(this,this._conn._dataRecv.bind(this._conn)),f.tree().getAttribute("rid"));this._requests.push(a),this._throttledRequestHandler()},_send:function(){clearTimeout(this._conn._idleTimeout),this._throttledRequestHandler(),this._conn._idleTimeout=setTimeout(function(){this._onIdle()}.bind(this._conn),100)},_sendRestart:function(){this._throttledRequestHandler(),clearTimeout(this._conn._idleTimeout)},_throttledRequestHandler:function(){this._requests?e.debug("_throttledRequestHandler called with "+this._requests.length+" requests"):e.debug("_throttledRequestHandler called with undefined requests"),this._requests&&0!==this._requests.length&&(this._requests.length>0&&this._processRequest(0),this._requests.length>1&&Math.abs(this._requests[0].rid-this._requests[1].rid): "+a);var n=t.getAttribute("version");return"string"!=typeof n?f="Missing version in ":"1.0"!==n&&(f="Wrong version in : "+n),!f||(this._conn._changeConnectStatus(e.Status.CONNFAIL,f),this._conn._doDisconnect(),!1)},_connect_cb_wrapper:function(t){if(0===t.data.indexOf("\s*)*/,"");if(""===f)return;var a=(new DOMParser).parseFromString(f,"text/xml").documentElement;this._conn.xmlInput(a),this._conn.rawInput(t.data),this._handleStreamStart(a)&&this._connect_cb(a)}else if(0===t.data.indexOf(" tag.")}}this._conn._doDisconnect()},_doDisconnect:function(){e.info("WebSockets _doDisconnect was called"),this._closeSocket()},_streamWrap:function(e){return""+e+""},_closeSocket:function(){if(this.socket)try{this.socket.close()}catch(e){}this.socket=null},_emptyQueue:function(){return!0},_onClose:function(t){this._conn.connected&&!this._conn.disconnecting?(e.error("Websocket closed unexpectedly"),this._conn._doDisconnect()):t&&1006===t.code&&!this._conn.connected&&this.socket?(e.error("Websocket closed unexcectedly"),this._conn._changeConnectStatus(e.Status.CONNFAIL,"The WebSocket connection could not be established or was disconnected."),this._conn._doDisconnect()):e.info("Websocket closed")},_no_auth_received:function(t){e.error("Server did not send any auth methods"),this._conn._changeConnectStatus(e.Status.CONNFAIL,"Server did not send any auth methods"),t&&(t=t.bind(this._conn))(),this._conn._doDisconnect()},_onDisconnectTimeout:function(){},_abortAllRequests:function(){},_onError:function(t){e.error("Websocket error "+t),this._conn._changeConnectStatus(e.Status.CONNFAIL,"The WebSocket connection could not be established or was disconnected."),this._disconnect()},_onIdle:function(){var t=this._conn._data;if(t.length>0&&!this._conn.paused){for(var f=0;f -1) { + this._list = list.split(/\s*,\s*/); + } + else { // Element or CSS selector + list = $(list); + + if (list && list.children) { + var items = []; + slice.apply(list.children).forEach(function (el) { + if (!el.disabled) { + var text = el.textContent.trim(); + var value = el.value || text; + var label = el.label || text; + if (value !== "") { + items.push({ label: label, value: value }); + } + } + }); + this._list = items; + } + } + + if (document.activeElement === this.input) { + this.evaluate(); + } + }, + + get selected() { + return this.index > -1; + }, + + get opened() { + return this.isOpened; + }, + + close: function (o) { + if (!this.opened) { + return; + } + + this.ul.setAttribute("hidden", ""); + this.isOpened = false; + this.index = -1; + + $.fire(this.input, "awesomplete-close", o || {}); + }, + + open: function () { + this.ul.removeAttribute("hidden"); + this.isOpened = true; + + if (this.autoFirst && this.index === -1) { + this.goto(0); + } + + $.fire(this.input, "awesomplete-open"); + }, + + destroy: function() { + //remove events from the input and its form + $.unbind(this.input, this._events.input); + $.unbind(this.input.form, this._events.form); + + //move the input out of the awesomplete container and remove the container and its children + var parentNode = this.container.parentNode; + + parentNode.insertBefore(this.input, this.container); + parentNode.removeChild(this.container); + + //remove autocomplete and aria-autocomplete attributes + this.input.removeAttribute("autocomplete"); + this.input.removeAttribute("aria-autocomplete"); + + //remove this awesomeplete instance from the global array of instances + var indexOfAwesomplete = _.all.indexOf(this); + + if (indexOfAwesomplete !== -1) { + _.all.splice(indexOfAwesomplete, 1); + } + }, + + next: function () { + var count = this.ul.children.length; + this.goto(this.index < count - 1 ? this.index + 1 : (count ? 0 : -1) ); + }, + + previous: function () { + var count = this.ul.children.length; + var pos = this.index - 1; + + this.goto(this.selected && pos !== -1 ? pos : count - 1); + }, + + // Should not be used, highlights specific item without any checks! + goto: function (i) { + var lis = this.ul.children; + + if (this.selected) { + lis[this.index].setAttribute("aria-selected", "false"); + } + + this.index = i; + + if (i > -1 && lis.length > 0) { + lis[i].setAttribute("aria-selected", "true"); + this.status.textContent = lis[i].textContent; + + // scroll to highlighted element in case parent's height is fixed + this.ul.scrollTop = lis[i].offsetTop - this.ul.clientHeight + lis[i].clientHeight; + + $.fire(this.input, "awesomplete-highlight", { + text: this.suggestions[this.index] + }); + } + }, + + select: function (selected, origin) { + if (selected) { + this.index = $.siblingIndex(selected); + } else { + selected = this.ul.children[this.index]; + } + + if (selected) { + var suggestion = this.suggestions[this.index]; + + var allowed = $.fire(this.input, "awesomplete-select", { + text: suggestion, + origin: origin || selected + }); + + if (allowed) { + this.replace(suggestion); + this.close({ reason: "select" }); + $.fire(this.input, "awesomplete-selectcomplete", { + text: suggestion + }); + } + } + }, + + evaluate: function() { + var me = this; + var value = this.input.value; + + if (value.length >= this.minChars && this._list.length > 0) { + this.index = -1; + // Populate list with options that match + this.ul.innerHTML = ""; + + this.suggestions = this._list + .map(function(item) { + return new Suggestion(me.data(item, value)); + }) + .filter(function(item) { + return me.filter(item, value); + }); + + if (this.sort !== false) { + this.suggestions = this.suggestions.sort(this.sort); + } + + this.suggestions = this.suggestions.slice(0, this.maxItems); + + this.suggestions.forEach(function(text) { + me.ul.appendChild(me.item(text, value)); + }); + + if (this.ul.children.length === 0) { + this.close({ reason: "nomatches" }); + } else { + this.open(); + } + } + else { + this.close({ reason: "nomatches" }); + } + } +}; + +// Static methods/properties + +_.all = []; + +_.FILTER_CONTAINS = function (text, input) { + return RegExp($.regExpEscape(input.trim()), "i").test(text); +}; + +_.FILTER_STARTSWITH = function (text, input) { + return RegExp("^" + $.regExpEscape(input.trim()), "i").test(text); +}; + +_.SORT_BYLENGTH = function (a, b) { + if (a.length !== b.length) { + return a.length - b.length; + } + + return a < b? -1 : 1; +}; + +_.ITEM = function (text, input) { + input = input.trim(); + var element = document.createElement("li"); + element.setAttribute("aria-selected", "false"); + + var regex = new RegExp("("+input+")", "ig"); + var parts = input ? text.split(regex) : [text]; + parts.forEach(function (txt) { + if (input && txt.match(regex)) { + var match = document.createElement("mark"); + match.textContent = txt; + element.appendChild(match); + } else { + element.appendChild(document.createTextNode(txt)); + } + }); + return element; +}; + +_.REPLACE = function (text) { + this.input.value = text.value; +}; + +_.DATA = function (item/*, input*/) { return item; }; + +// Private functions + +function Suggestion(data) { + var o = Array.isArray(data) + ? { label: data[0], value: data[1] } + : typeof data === "object" && "label" in data && "value" in data ? data : { label: data, value: data }; + + this.label = o.label || o.value; + this.value = o.value; +} +Object.defineProperty(Suggestion.prototype = Object.create(String.prototype), "length", { + get: function() { return this.label.length; } +}); +Suggestion.prototype.toString = Suggestion.prototype.valueOf = function () { + return "" + this.label; +}; + +function configure(instance, properties, o) { + for (var i in properties) { + var initial = properties[i], + attrValue = instance.input.getAttribute("data-" + i.toLowerCase()); + + if (typeof initial === "number") { + instance[i] = parseInt(attrValue); + } + else if (initial === false) { // Boolean options must be false by default anyway + instance[i] = attrValue !== null; + } + else if (initial instanceof Function) { + instance[i] = null; + } + else { + instance[i] = attrValue; + } + + if (!instance[i] && instance[i] !== 0) { + instance[i] = (i in o)? o[i] : initial; + } + } +} + +// Helpers + +var slice = Array.prototype.slice; + +function $(expr, con) { + return typeof expr === "string"? (con || document).querySelector(expr) : expr || null; +} + +function $$(expr, con) { + return slice.call((con || document).querySelectorAll(expr)); +} + +$.create = function(tag, o) { + var element = document.createElement(tag); + + for (var i in o) { + var val = o[i]; + + if (i === "inside") { + $(val).appendChild(element); + } + else if (i === "around") { + var ref = $(val); + ref.parentNode.insertBefore(element, ref); + element.appendChild(ref); + } + else if (i in element) { + element[i] = val; + } + else { + element.setAttribute(i, val); + } + } + + return element; +}; + +$.bind = function(element, o) { + if (element) { + for (var event in o) { + var callback = o[event]; + + event.split(/\s+/).forEach(function (event) { + element.addEventListener(event, callback); + }); + } + } +}; + +$.unbind = function(element, o) { + if (element) { + for (var event in o) { + var callback = o[event]; + + event.split(/\s+/).forEach(function(event) { + element.removeEventListener(event, callback); + }); + } + } +}; + +$.fire = function(target, type, properties) { + var evt = document.createEvent("HTMLEvents"); + + evt.initEvent(type, true, true ); + + for (var j in properties) { + evt[j] = properties[j]; + } + + return target.dispatchEvent(evt); +}; + +$.regExpEscape = function (s) { + return s.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&"); +}; + +$.siblingIndex = function (el) { + /* eslint-disable no-cond-assign */ + for (var i = 0; el = el.previousElementSibling; i++); + return i; +}; + +// Initialization + +function init() { + $$("input.awesomplete").forEach(function (input) { + new _(input); + }); +} + +// Are we in a browser? Check for Document constructor +if (typeof Document !== "undefined") { + // DOM already loaded? + if (document.readyState !== "loading") { + init(); + } + else { + // Wait for it + document.addEventListener("DOMContentLoaded", init); + } +} + +_.$ = $; +_.$$ = $$; + +// Make sure to export Awesomplete on self when in a browser +if (typeof self !== "undefined") { + self.Awesomplete = _; +} + +// Expose Awesomplete as a CJS module +if (typeof module === "object" && module.exports) { + module.exports = _; +} + +return _; + +}()); + + +/*** EXPORTS FROM exports-loader ***/ +module.exports = Awesomplete; + +/***/ }), + +/***/ "./node_modules/backbone.browserStorage/backbone.browserStorage.js": +/*!*************************************************************************!*\ + !*** ./node_modules/backbone.browserStorage/backbone.browserStorage.js ***! + \*************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + /** + * Backbone localStorage and sessionStorage Adapter + * Version 0.0.3 + * + * https://github.com/jcbrand/Backbone.browserStorage + */ +(function (root, factory) { + if (true) { + module.exports = factory(__webpack_require__(/*! backbone */ "./node_modules/backbone/backbone.js"), __webpack_require__(/*! underscore */ "./src/underscore-shim.js")); + } else {} +}(this, function(Backbone, _) { +// A simple module to replace `Backbone.sync` with *browser storage*-based +// persistence. Models are given GUIDS, and saved into a JSON object. Simple +// as that. + +// Hold reference to Underscore.js and Backbone.js in the closure in order +// to make things work even if they are removed from the global namespace + +// Generate four random hex digits. +function S4() { + return (((1+Math.random())*0x10000)|0).toString(16).substring(1); +} + +// Generate a pseudo-GUID by concatenating random hexadecimal. +function guid() { + return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4()); +} + +function contains(array, item) { + var i = array.length; + while (i--) if (array[i] === item) return true; + return false; +} + +function extend(obj, props) { + for (var key in props) { obj[key] = props[key]; } + return obj; +} + +function _browserStorage (name, serializer, type) { + var _store; + if (type === 'local' && !window.localStorage ) { + throw "Backbone.browserStorage: Environment does not support localStorage."; + } else if (type === 'session' && !window.sessionStorage ) { + throw "Backbone.browserStorage: Environment does not support sessionStorage."; + } + this.name = name; + this.serializer = serializer || { + serialize: function(item) { + return _.isObject(item) ? JSON.stringify(item) : item; + }, + // fix for "illegal access" error on Android when JSON.parse is passed null + deserialize: function (data) { + return data && JSON.parse(data); + } + }; + + if (type === 'session') { + this.store = window.sessionStorage; + } else if (type === 'local') { + this.store = window.localStorage; + } else { + throw "Backbone.browserStorage: No storage type was specified"; + } + _store = this.store.getItem(this.name); + this.records = (_store && _store.split(",")) || []; +} + +// Our Store is represented by a single JS object in *localStorage* or *sessionStorage*. +// Create it with a meaningful name, like the name you'd give a table. +Backbone.BrowserStorage = { + local: function (name, serializer) { + return _browserStorage.bind(this, name, serializer, 'local')(); + }, + session: function (name, serializer) { + return _browserStorage.bind(this, name, serializer, 'session')(); + } +}; + +// The browser's local and session stores will be extended with this obj. +var _extension = { + + // Save the current state of the **Store** + save: function() { + this.store.setItem(this.name, this.records.join(",")); + }, + + // Add a model, giving it a (hopefully)-unique GUID, if it doesn't already + // have an id of it's own. + create: function(model) { + if (!model.id) { + model.id = guid(); + model.set(model.idAttribute, model.id); + } + this.store.setItem(this._itemName(model.id), this.serializer.serialize(model)); + this.records.push(model.id.toString()); + this.save(); + return this.find(model) !== false; + }, + + // Update a model by replacing its copy in `this.data`. + update: function(model) { + this.store.setItem(this._itemName(model.id), this.serializer.serialize(model)); + var modelId = model.id.toString(); + if (!contains(this.records, modelId)) { + this.records.push(modelId); + this.save(); + } + return this.find(model) !== false; + }, + + // Retrieve a model from `this.data` by id. + find: function(model) { + return this.serializer.deserialize(this.store.getItem(this._itemName(model.id))); + }, + + // Return the array of all models currently in storage. + findAll: function() { + var result = []; + for (var i = 0, id, data; i < this.records.length; i++) { + id = this.records[i]; + data = this.serializer.deserialize(this.store.getItem(this._itemName(id))); + if (data !== null) result.push(data); + } + return result; + }, + + // Delete a model from `this.data`, returning it. + destroy: function(model) { + this.store.removeItem(this._itemName(model.id)); + var modelId = model.id.toString(); + for (var i = 0, id; i < this.records.length; i++) { + if (this.records[i] === modelId) { + this.records.splice(i, 1); + } + } + this.save(); + return model; + }, + + browserStorage: function() { + return { + session: sessionStorage, + local: localStorage + }; + }, + + // Clear browserStorage for specific collection. + _clear: function() { + var local = this.store, itemRe; + + // Escape special regex characters in id. + itemRe = new RegExp("^" + this.name.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&") + "-"); + + // Remove id-tracking item (e.g., "foo"). + local.removeItem(this.name); + + // Match all data items (e.g., "foo-ID") and remove. + for (var k in local) { + if (itemRe.test(k)) { + local.removeItem(k); + } + } + + this.records.length = 0; + }, + + // Size of browserStorage. + _storageSize: function() { + return this.store.length; + }, + + _itemName: function(id) { + return this.name+"-"+id; + } + +}; + +extend(Backbone.BrowserStorage.session.prototype, _extension); +extend(Backbone.BrowserStorage.local.prototype, _extension); + +// localSync delegate to the model or collection's +// *browserStorage* property, which should be an instance of `Store`. +// window.Store.sync and Backbone.localSync is deprecated, use Backbone.BrowserStorage.sync instead +Backbone.BrowserStorage.sync = Backbone.localSync = function(method, model, options) { + var store = model.browserStorage || model.collection.browserStorage; + + var resp, errorMessage; + //If $ is having Deferred - use it. + var syncDfd = Backbone.$ ? + (Backbone.$.Deferred && Backbone.$.Deferred()) : + (Backbone.Deferred && Backbone.Deferred()); + + try { + + switch (method) { + case "read": + resp = model.id !== undefined ? store.find(model) : store.findAll(); + break; + case "create": + resp = store.create(model); + break; + case "update": + resp = store.update(model); + break; + case "delete": + resp = store.destroy(model); + break; + } + + } catch(error) { + if (error.code === 22 && store._storageSize() === 0) + errorMessage = "Private browsing is unsupported"; + else + errorMessage = error.message; + } + + if (resp) { + if (options && options.success) { + if (Backbone.VERSION === "0.9.10") { + options.success(model, resp, options); + } else { + options.success(resp); + } + } + if (syncDfd) { + syncDfd.resolve(resp); + } + + } else { + errorMessage = errorMessage ? errorMessage + : "Record Not Found"; + + if (options && options.error) + if (Backbone.VERSION === "0.9.10") { + options.error(model, errorMessage, options); + } else { + options.error(errorMessage); + } + + if (syncDfd) + syncDfd.reject(errorMessage); + } + + // add compatibility with $.ajax + // always execute callback for success and error + if (options && options.complete) options.complete(resp); + + return syncDfd && syncDfd.promise(); +}; + +Backbone.ajaxSync = Backbone.sync; + +Backbone.getSyncMethod = function(model) { + if(model.browserStorage || (model.collection && model.collection.browserStorage)) { + return Backbone.localSync; + } + return Backbone.ajaxSync; +}; + +// Override 'Backbone.sync' to default to localSync, +// the original 'Backbone.sync' is still available in 'Backbone.ajaxSync' +Backbone.sync = function(method, model, options) { + return Backbone.getSyncMethod(model).apply(this, [method, model, options]); +}; + +return Backbone.BrowserStorage; +})); + + +/***/ }), + +/***/ "./node_modules/backbone.nativeview/backbone.nativeview.js": +/*!*****************************************************************!*\ + !*** ./node_modules/backbone.nativeview/backbone.nativeview.js ***! + \*****************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Backbone.NativeView.js 0.3.3 +// --------------- + +// (c) 2015 Adam Krebs, Jimmy Yuen Ho Wong +// Backbone.NativeView may be freely distributed under the MIT license. +// For all details and documentation: +// https://github.com/akre54/Backbone.NativeView + +(function (factory) { + if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! backbone */ "./node_modules/backbone/backbone.js")], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} +}(function (Backbone) { + // Cached regex to match an opening '<' of an HTML tag, possibly left-padded + // with whitespace. + var paddedLt = /^\s*=9 and modern browsers. + var matchesSelector = ElementProto.matches || + ElementProto.webkitMatchesSelector || + ElementProto.mozMatchesSelector || + ElementProto.msMatchesSelector || + ElementProto.oMatchesSelector || + // Make our own `Element#matches` for IE8 + function(selector) { + // Use querySelectorAll to find all elements matching the selector, + // then check if the given element is included in that list. + // Executing the query on the parentNode reduces the resulting nodeList, + // (document doesn't have a parentNode). + var nodeList = (this.parentNode || document).querySelectorAll(selector) || []; + return ~indexOf(nodeList, this); + }; + + // Cache Backbone.View for later access in constructor + var BBView = Backbone.View; + + // To extend an existing view to use native methods, extend the View prototype + // with the mixin: _.extend(MyView.prototype, Backbone.NativeViewMixin); + Backbone.NativeViewMixin = { + + _domEvents: null, + + constructor: function() { + this._domEvents = []; + return BBView.apply(this, arguments); + }, + + $: function(selector) { + return this.el.querySelectorAll(selector); + }, + + _removeElement: function() { + this.undelegateEvents(); + if (this.el.parentNode) this.el.parentNode.removeChild(this.el); + }, + + // Apply the `element` to the view. `element` can be a CSS selector, + // a string of HTML, or an Element node. + _setElement: function(element) { + if (typeof element == 'string') { + if (paddedLt.test(element)) { + var el = document.createElement('div'); + el.innerHTML = element; + this.el = el.firstChild; + } else { + this.el = document.querySelector(element); + } + } else { + this.el = element; + } + }, + + // Set a hash of attributes to the view's `el`. We use the "prop" version + // if available, falling back to `setAttribute` for the catch-all. + _setAttributes: function(attrs) { + for (var attr in attrs) { + attr in this.el ? this.el[attr] = attrs[attr] : this.el.setAttribute(attr, attrs[attr]); + } + }, + + // Make a event delegation handler for the given `eventName` and `selector` + // and attach it to `this.el`. + // If selector is empty, the listener will be bound to `this.el`. If not, a + // new handler that will recursively traverse up the event target's DOM + // hierarchy looking for a node that matches the selector. If one is found, + // the event's `delegateTarget` property is set to it and the return the + // result of calling bound `listener` with the parameters given to the + // handler. + delegate: function(eventName, selector, listener) { + if (typeof selector === 'function') { + listener = selector; + selector = null; + } + + var root = this.el; + var handler = selector ? function (e) { + var node = e.target || e.srcElement; + for (; node && node != root; node = node.parentNode) { + if (matchesSelector.call(node, selector)) { + e.delegateTarget = node; + listener(e); + } + } + } : listener; + + elementAddEventListener.call(this.el, eventName, handler, false); + this._domEvents.push({eventName: eventName, handler: handler, listener: listener, selector: selector}); + return handler; + }, + + // Remove a single delegated event. Either `eventName` or `selector` must + // be included, `selector` and `listener` are optional. + undelegate: function(eventName, selector, listener) { + if (typeof selector === 'function') { + listener = selector; + selector = null; + } + + if (this.el) { + var handlers = this._domEvents.slice(); + for (var i = 0, len = handlers.length; i < len; i++) { + var item = handlers[i]; + + var match = item.eventName === eventName && + (listener ? item.listener === listener : true) && + (selector ? item.selector === selector : true); + + if (!match) continue; + + elementRemoveEventListener.call(this.el, item.eventName, item.handler, false); + this._domEvents.splice(indexOf(handlers, item), 1); + } + } + return this; + }, + + // Remove all events created with `delegate` from `el` + undelegateEvents: function() { + if (this.el) { + for (var i = 0, len = this._domEvents.length; i < len; i++) { + var item = this._domEvents[i]; + elementRemoveEventListener.call(this.el, item.eventName, item.handler, false); + }; + this._domEvents.length = 0; + } + return this; + } + }; + + Backbone.NativeView = Backbone.View.extend(Backbone.NativeViewMixin); + + return Backbone.NativeView; +})); + + +/***/ }), + +/***/ "./node_modules/backbone.overview/dist/backbone.orderedlistview.js": +/*!*************************************************************************!*\ + !*** ./node_modules/backbone.overview/dist/backbone.orderedlistview.js ***! + \*************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*** IMPORTS FROM imports-loader ***/ +var backbone = (backbone || {}); +backbone.nativeview = __webpack_require__(/*! backbone.nativeview */ "./node_modules/backbone.nativeview/backbone.nativeview.js"); + +/*! + * Backbone.OrderedListView + * + * Copyright (c) 2017, JC Brand + * Licensed under the Mozilla Public License (MPL) + */ +(function (root, factory) { + if (true) { + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! underscore */ "./src/underscore-shim.js"), __webpack_require__(/*! backbone */ "./node_modules/backbone/backbone.js"), __webpack_require__(/*! backbone.overview */ "./node_modules/backbone.overview/dist/backbone.overview.js")], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} +})(this, function (_, Backbone) { + "use strict"; + + Backbone.OrderedListView = Backbone.Overview.extend({ + /* An OrderedListView is a special type of Overview which adds some + * methods and conventions for rendering an ordered list of elements. + */ + // The `listItems` attribute denotes the path (from this View) to the + // list of items. + listItems: 'model', + // The `sortEvent` attribute specifies the event which should cause the + // ordered list to be sorted. + sortEvent: 'change', + // The `listSelector` is the selector used to query for the DOM list + // element which contains the ordered items. + listSelector: '.ordered-items', + // The `itemView` is constructor which should be called to create a + // View for a new item. + ItemView: undefined, + // The `subviewIndex` is the attribute of the list element model which + // acts as the index of the subview in the overview. + // An overview is a "Collection" of views, and they can be retrieved + // via an index. By default this is the 'id' attribute, but it could be + // set to something else. + subviewIndex: 'id', + initialize: function initialize() { + this.sortEventually = _.debounce(this.sortAndPositionAllItems.bind(this), 500); + this.items = _.get(this, this.listItems); + this.items.on('add', this.sortAndPositionAllItems, this); + this.items.on('remove', this.removeView, this); + + if (!_.isNil(this.sortEvent)) { + this.items.on(this.sortEvent, this.sortEventually, this); + } + }, + createItemView: function createItemView(item) { + var item_view = this.get(item.get(this.subviewIndex)); + + if (!item_view) { + item_view = new this.ItemView({ + model: item + }); + this.add(item.get(this.subviewIndex), item_view); + } else { + item_view.model = item; + item_view.initialize(); + } + + item_view.render(); + return item_view; + }, + removeView: function removeView(item) { + this.remove(item.get(this.subviewIndex)); + }, + sortAndPositionAllItems: function sortAndPositionAllItems() { + var _this = this; + + if (!this.items.length) { + return; + } + + this.items.sort(); + var list_el = this.el.querySelector(this.listSelector); + var div = document.createElement('div'); + list_el.parentNode.replaceChild(div, list_el); + this.items.each(function (item) { + var view = _this.get(item.get(_this.subviewIndex)); + + if (_.isUndefined(view)) { + view = _this.createItemView(item); + } + + list_el.insertAdjacentElement('beforeend', view.el); + }); + div.parentNode.replaceChild(list_el, div); + } + }); + return Backbone.OrderedListView; +}); + +//# sourceMappingURL=backbone.orderedlistview.js.map + + +/***/ }), + +/***/ "./node_modules/backbone.overview/dist/backbone.overview.js": +/*!******************************************************************!*\ + !*** ./node_modules/backbone.overview/dist/backbone.overview.js ***! + \******************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*** IMPORTS FROM imports-loader ***/ +var backbone = (backbone || {}); +backbone.nativeview = __webpack_require__(/*! backbone.nativeview */ "./node_modules/backbone.nativeview/backbone.nativeview.js"); + +/*! + * Backbone.Overview + * + * Copyright (c) 2018, JC Brand + * Licensed under the Mozilla Public License (MPL) + */ +(function (root, factory) { + if (true) { + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! underscore */ "./src/underscore-shim.js"), __webpack_require__(/*! backbone */ "./node_modules/backbone/backbone.js")], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} +})(this, function (_, Backbone) { + "use strict"; + + var View = _.isUndefined(Backbone.NativeView) ? Backbone.View : Backbone.NativeView; + + var Overview = Backbone.Overview = function (options) { + /* An Overview is a View that contains and keeps track of sub-views. + * Kind of like what a Collection is to a Model. + */ + var that = this; + this.views = {}; + this.keys = _.partial(_.keys, this.views); + this.getAll = _.partial(_.identity, this.views); + + this.get = function (id) { + return that.views[id]; + }; + + this.xget = function (id) { + /* Exclusive get. Returns all instances except the given id. */ + return _.filter(that.views, function (view, vid) { + return vid !== id; + }); + }; + + this.add = function (id, view) { + that.views[id] = view; + return view; + }; + + this.remove = function (id) { + if (typeof id === "undefined") { + new View().remove.apply(that); + } + + var view = that.views[id]; + + if (view) { + delete that.views[id]; + view.remove(); + return view; + } + }; + + this.removeAll = function () { + _.each(_.keys(that.views), that.remove); + + return that; + }; + + View.apply(this, Array.prototype.slice.apply(arguments)); + }; + + var methods = ['all', 'any', 'chain', 'collect', 'contains', 'detect', 'difference', 'drop', 'each', 'every', 'filter', 'find', 'first', 'foldl', 'foldr', 'forEach', 'head', 'include', 'indexOf', 'initial', 'inject', 'invoke', 'isEmpty', 'last', 'lastIndexOf', 'map', 'max', 'min', 'reduce', 'reduceRight', 'reject', 'rest', 'sample', 'select', 'shuffle', 'size', 'some', 'sortBy', 'tail', 'take', 'toArray', 'without']; // Mix in each Underscore method as a proxy to `Overview#view`. + + _.each(methods, function (method) { + Overview.prototype[method] = function () { + var args = Array.prototype.slice.call(arguments); + args.unshift(this.views); + return _[method].apply(_, args); + }; + }); + + _.extend(Overview.prototype, View.prototype); + + Overview.extend = View.extend; + Backbone.OrderedListView = Backbone.Overview.extend({ + // The `listItems` attribute denotes the path (from this View) to the + // list of items. + listItems: 'model', + // The `sortEvent` attribute specifies the event which should cause the + // ordered list to be sorted. + sortEvent: 'change', + // The `listSelector` is the selector used to query for the DOM list + // element which contains the ordered items. + listSelector: '.ordered-items', + // The `itemView` is constructor which should be called to create a + // View for a new item. + ItemView: undefined, + initialize: function initialize() { + this.sortEventually = _.debounce(this.sortAndPositionAllItems.bind(this), 500); + this.items = _.get(this, this.listItems); + this.items.on('add', this.createItemView, this); + this.items.on('add', this.sortEventually, this); + this.items.on(this.sortEvent, this.sortEventually, this); + }, + createItemView: function createItemView(item) { + var item_view = this.get(item.get('id')); + + if (!item_view) { + item_view = new this.ItemView({ + model: item + }); + this.add(item.get('id'), item_view); + } else { + item_view.model = item; + item_view.initialize(); + } + + item_view.render(); + return item_view; + }, + sortAndPositionAllItems: function sortAndPositionAllItems() { + var _this = this; + + this.items.sort(); + this.items.each(function (item) { + if (_.isUndefined(_this.get(item.get('id')))) { + _this.createItemView(item); + } + + _this.positionItem(item, _this.el.querySelector(_this.listSelector)); + }); + }, + positionItem: function positionItem(item, list_el) { + /* Place the View's DOM element in the correct alphabetical + * position in the list. + * + * IMPORTANT: there's an important implicit assumption being + * made here. And that is that initially this method gets called + * for each item in the right positional order. + * + * In other words, it gets called for the 0th, then the + * 1st, then the 2nd, 3rd and so on. + * + * That's why we call it in the "success" handler after + * fetching the items, so that we know we have ALL of + * them and that they're sorted. + */ + var view = this.get(item.get('id')), + index = this.items.indexOf(item); + + if (index === 0) { + list_el.insertAdjacentElement('afterbegin', view.el); + } else if (index === this.items.length - 1) { + list_el.insertAdjacentElement('beforeend', view.el); + } else { + var neighbour_el = list_el.querySelector('li:nth-child(' + index + ')'); + neighbour_el.insertAdjacentElement('afterend', view.el); + } + + return view; + } + }); + return Backbone.Overview; +}); + +//# sourceMappingURL=backbone.overview.js.map + + +/***/ }), + +/***/ "./node_modules/backbone.vdomview/dist/backbone.vdomview.js": +/*!******************************************************************!*\ + !*** ./node_modules/backbone.vdomview/dist/backbone.vdomview.js ***! + \******************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*** IMPORTS FROM imports-loader ***/ +var backbone = (backbone || {}); +backbone.nativeview = __webpack_require__(/*! backbone.nativeview */ "./node_modules/backbone.nativeview/backbone.nativeview.js"); + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/*! + * Backbone.VDOMView + * + * MIT Licensed. Copyright (c) 2017, JC Brand + */ +(function (root, factory) { + if (true) { + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! snabbdom */ "./node_modules/snabbdom/dist/snabbdom.js"), __webpack_require__(/*! snabbdom-attributes */ "./node_modules/snabbdom/dist/snabbdom-attributes.js"), __webpack_require__(/*! snabbdom-class */ "./node_modules/snabbdom/dist/snabbdom-class.js"), __webpack_require__(/*! snabbdom-dataset */ "./node_modules/snabbdom/dist/snabbdom-dataset.js"), __webpack_require__(/*! snabbdom-props */ "./node_modules/snabbdom/dist/snabbdom-props.js"), __webpack_require__(/*! snabbdom-style */ "./node_modules/snabbdom/dist/snabbdom-style.js"), __webpack_require__(/*! tovnode */ "./node_modules/snabbdom/dist/tovnode.js"), __webpack_require__(/*! underscore */ "./src/underscore-shim.js"), __webpack_require__(/*! backbone */ "./node_modules/backbone/backbone.js")], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} +})(this, function (snabbdom, snabbdom_attributes, snabbdom_class, snabbdom_dataset, snabbdom_props, snabbdom_style, tovnode, _, Backbone) { + "use strict"; + + var domParser = new DOMParser(); + var patch = snabbdom.init([snabbdom_attributes.default, snabbdom_class.default, snabbdom_dataset.default, snabbdom_props.default, snabbdom_style.default]); + var View = _.isUndefined(Backbone.NativeView) ? Backbone.View : Backbone.NativeView; + + function parseHTMLToDOM(html_str) { + /* Parses a string with HTML and returns a DOM element. + * + * Forked from vdom_parser: + * https://github.com/bitinn/vdom-parser + */ + if (typeof html_str !== 'string') { + throw new Error('Invalid parameter type in parseHTMLToDOM'); + } + + if (!('DOMParser' in window)) { + throw new Error('DOMParser is not available, ' + 'so parsing string to DOM node is not possible.'); + } + + if (!html_str) { + return document.createTextNode(''); + } + + domParser = domParser || new DOMParser(); + var doc = domParser.parseFromString(html_str, 'text/html'); // most tags default to body + + if (doc.body.firstChild) { + return doc.getElementsByTagName('body')[0].firstChild; // some tags, like script and style, default to head + } else if (doc.head.firstChild && (doc.head.firstChild.tagName !== 'TITLE' || doc.title)) { + return doc.head.firstChild; // special case for html comment, cdata, doctype + } else if (doc.firstChild && doc.firstChild.tagName !== 'HTML') { + return doc.firstChild; // other element, such as whitespace, or html/body/head tag, fallback to empty text node + } else { + return document.createTextNode(''); + } + } + + Backbone.VDOMView = View.extend({ + updateEventListeners: function updateEventListeners(old_vnode, new_vnode) { + this.setElement(new_vnode.elm); + }, + render: function render() { + if (_.isFunction(this.beforeRender)) { + this.beforeRender(); + } + + var new_vnode = tovnode.toVNode(parseHTMLToDOM(this.toHTML())); + new_vnode.data.hook = _.extend({ + create: this.updateEventListeners.bind(this), + update: this.updateEventListeners.bind(this) + }); + var el = this.vnode ? this.vnode.elm : this.el; + + if (el.outerHTML !== new_vnode.elm.outerHTML) { + this.vnode = patch(this.vnode || this.el, new_vnode); + } + + if (_.isFunction(this.afterRender)) { + this.afterRender(); + } + + return this; + } + }); + return Backbone.VDOMView; +}); + +//# sourceMappingURL=backbone.vdomview.js.map + + +/***/ }), + +/***/ "./node_modules/backbone/backbone.js": +/*!*******************************************!*\ + !*** ./node_modules/backbone/backbone.js ***! + \*******************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(global) {var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Backbone.js 1.3.3 + +// (c) 2010-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors +// Backbone may be freely distributed under the MIT license. +// For all details and documentation: +// http://backbonejs.org + +(function(factory) { + + // Establish the root object, `window` (`self`) in the browser, or `global` on the server. + // We use `self` instead of `window` for `WebWorker` support. + var root = (typeof self == 'object' && self.self === self && self) || + (typeof global == 'object' && global.global === global && global); + + // Set up Backbone appropriately for the environment. Start with AMD. + if (true) { + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! underscore */ "./src/underscore-shim.js"), __webpack_require__(/*! jquery */ "./src/jquery-stub.js"), exports], __WEBPACK_AMD_DEFINE_RESULT__ = (function(_, $, exports) { + // Export global even in AMD case in case this script is loaded with + // others that may still expect a global Backbone. + root.Backbone = factory(root, exports, _, $); + }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + + // Next for Node.js or CommonJS. jQuery may not be needed as a module. + } else { var _, $; } + +})(function(root, Backbone, _, $) { + + // Initial Setup + // ------------- + + // Save the previous value of the `Backbone` variable, so that it can be + // restored later on, if `noConflict` is used. + var previousBackbone = root.Backbone; + + // Create a local reference to a common array method we'll want to use later. + var slice = Array.prototype.slice; + + // Current version of the library. Keep in sync with `package.json`. + Backbone.VERSION = '1.3.3'; + + // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns + // the `$` variable. + Backbone.$ = $; + + // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable + // to its previous owner. Returns a reference to this Backbone object. + Backbone.noConflict = function() { + root.Backbone = previousBackbone; + return this; + }; + + // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option + // will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and + // set a `X-Http-Method-Override` header. + Backbone.emulateHTTP = false; + + // Turn on `emulateJSON` to support legacy servers that can't deal with direct + // `application/json` requests ... this will encode the body as + // `application/x-www-form-urlencoded` instead and will send the model in a + // form param named `model`. + Backbone.emulateJSON = false; + + // Proxy Backbone class methods to Underscore functions, wrapping the model's + // `attributes` object or collection's `models` array behind the scenes. + // + // collection.filter(function(model) { return model.get('age') > 10 }); + // collection.each(this.addView); + // + // `Function#apply` can be slow so we use the method's arg count, if we know it. + var addMethod = function(length, method, attribute) { + switch (length) { + case 1: return function() { + return _[method](this[attribute]); + }; + case 2: return function(value) { + return _[method](this[attribute], value); + }; + case 3: return function(iteratee, context) { + return _[method](this[attribute], cb(iteratee, this), context); + }; + case 4: return function(iteratee, defaultVal, context) { + return _[method](this[attribute], cb(iteratee, this), defaultVal, context); + }; + default: return function() { + var args = slice.call(arguments); + args.unshift(this[attribute]); + return _[method].apply(_, args); + }; + } + }; + var addUnderscoreMethods = function(Class, methods, attribute) { + _.each(methods, function(length, method) { + if (_[method]) Class.prototype[method] = addMethod(length, method, attribute); + }); + }; + + // Support `collection.sortBy('attr')` and `collection.findWhere({id: 1})`. + var cb = function(iteratee, instance) { + if (_.isFunction(iteratee)) return iteratee; + if (_.isObject(iteratee) && !instance._isModel(iteratee)) return modelMatcher(iteratee); + if (_.isString(iteratee)) return function(model) { return model.get(iteratee); }; + return iteratee; + }; + var modelMatcher = function(attrs) { + var matcher = _.matches(attrs); + return function(model) { + return matcher(model.attributes); + }; + }; + + // Backbone.Events + // --------------- + + // A module that can be mixed in to *any object* in order to provide it with + // a custom event channel. You may bind a callback to an event with `on` or + // remove with `off`; `trigger`-ing an event fires all callbacks in + // succession. + // + // var object = {}; + // _.extend(object, Backbone.Events); + // object.on('expand', function(){ alert('expanded'); }); + // object.trigger('expand'); + // + var Events = Backbone.Events = {}; + + // Regular expression used to split event strings. + var eventSplitter = /\s+/; + + // Iterates over the standard `event, callback` (as well as the fancy multiple + // space-separated events `"change blur", callback` and jQuery-style event + // maps `{event: callback}`). + var eventsApi = function(iteratee, events, name, callback, opts) { + var i = 0, names; + if (name && typeof name === 'object') { + // Handle event maps. + if (callback !== void 0 && 'context' in opts && opts.context === void 0) opts.context = callback; + for (names = _.keys(name); i < names.length ; i++) { + events = eventsApi(iteratee, events, names[i], name[names[i]], opts); + } + } else if (name && eventSplitter.test(name)) { + // Handle space-separated event names by delegating them individually. + for (names = name.split(eventSplitter); i < names.length; i++) { + events = iteratee(events, names[i], callback, opts); + } + } else { + // Finally, standard events. + events = iteratee(events, name, callback, opts); + } + return events; + }; + + // Bind an event to a `callback` function. Passing `"all"` will bind + // the callback to all events fired. + Events.on = function(name, callback, context) { + return internalOn(this, name, callback, context); + }; + + // Guard the `listening` argument from the public API. + var internalOn = function(obj, name, callback, context, listening) { + obj._events = eventsApi(onApi, obj._events || {}, name, callback, { + context: context, + ctx: obj, + listening: listening + }); + + if (listening) { + var listeners = obj._listeners || (obj._listeners = {}); + listeners[listening.id] = listening; + } + + return obj; + }; + + // Inversion-of-control versions of `on`. Tell *this* object to listen to + // an event in another object... keeping track of what it's listening to + // for easier unbinding later. + Events.listenTo = function(obj, name, callback) { + if (!obj) return this; + var id = obj._listenId || (obj._listenId = _.uniqueId('l')); + var listeningTo = this._listeningTo || (this._listeningTo = {}); + var listening = listeningTo[id]; + + // This object is not listening to any other events on `obj` yet. + // Setup the necessary references to track the listening callbacks. + if (!listening) { + var thisId = this._listenId || (this._listenId = _.uniqueId('l')); + listening = listeningTo[id] = {obj: obj, objId: id, id: thisId, listeningTo: listeningTo, count: 0}; + } + + // Bind callbacks on obj, and keep track of them on listening. + internalOn(obj, name, callback, this, listening); + return this; + }; + + // The reducing API that adds a callback to the `events` object. + var onApi = function(events, name, callback, options) { + if (callback) { + var handlers = events[name] || (events[name] = []); + var context = options.context, ctx = options.ctx, listening = options.listening; + if (listening) listening.count++; + + handlers.push({callback: callback, context: context, ctx: context || ctx, listening: listening}); + } + return events; + }; + + // Remove one or many callbacks. If `context` is null, removes all + // callbacks with that function. If `callback` is null, removes all + // callbacks for the event. If `name` is null, removes all bound + // callbacks for all events. + Events.off = function(name, callback, context) { + if (!this._events) return this; + this._events = eventsApi(offApi, this._events, name, callback, { + context: context, + listeners: this._listeners + }); + return this; + }; + + // Tell this object to stop listening to either specific events ... or + // to every object it's currently listening to. + Events.stopListening = function(obj, name, callback) { + var listeningTo = this._listeningTo; + if (!listeningTo) return this; + + var ids = obj ? [obj._listenId] : _.keys(listeningTo); + + for (var i = 0; i < ids.length; i++) { + var listening = listeningTo[ids[i]]; + + // If listening doesn't exist, this object is not currently + // listening to obj. Break out early. + if (!listening) break; + + listening.obj.off(name, callback, this); + } + + return this; + }; + + // The reducing API that removes a callback from the `events` object. + var offApi = function(events, name, callback, options) { + if (!events) return; + + var i = 0, listening; + var context = options.context, listeners = options.listeners; + + // Delete all events listeners and "drop" events. + if (!name && !callback && !context) { + var ids = _.keys(listeners); + for (; i < ids.length; i++) { + listening = listeners[ids[i]]; + delete listeners[listening.id]; + delete listening.listeningTo[listening.objId]; + } + return; + } + + var names = name ? [name] : _.keys(events); + for (; i < names.length; i++) { + name = names[i]; + var handlers = events[name]; + + // Bail out if there are no events stored. + if (!handlers) break; + + // Replace events if there are any remaining. Otherwise, clean up. + var remaining = []; + for (var j = 0; j < handlers.length; j++) { + var handler = handlers[j]; + if ( + callback && callback !== handler.callback && + callback !== handler.callback._callback || + context && context !== handler.context + ) { + remaining.push(handler); + } else { + listening = handler.listening; + if (listening && --listening.count === 0) { + delete listeners[listening.id]; + delete listening.listeningTo[listening.objId]; + } + } + } + + // Update tail event if the list has any events. Otherwise, clean up. + if (remaining.length) { + events[name] = remaining; + } else { + delete events[name]; + } + } + return events; + }; + + // Bind an event to only be triggered a single time. After the first time + // the callback is invoked, its listener will be removed. If multiple events + // are passed in using the space-separated syntax, the handler will fire + // once for each event, not once for a combination of all events. + Events.once = function(name, callback, context) { + // Map the event into a `{event: once}` object. + var events = eventsApi(onceMap, {}, name, callback, _.bind(this.off, this)); + if (typeof name === 'string' && context == null) callback = void 0; + return this.on(events, callback, context); + }; + + // Inversion-of-control versions of `once`. + Events.listenToOnce = function(obj, name, callback) { + // Map the event into a `{event: once}` object. + var events = eventsApi(onceMap, {}, name, callback, _.bind(this.stopListening, this, obj)); + return this.listenTo(obj, events); + }; + + // Reduces the event callbacks into a map of `{event: onceWrapper}`. + // `offer` unbinds the `onceWrapper` after it has been called. + var onceMap = function(map, name, callback, offer) { + if (callback) { + var once = map[name] = _.once(function() { + offer(name, once); + callback.apply(this, arguments); + }); + once._callback = callback; + } + return map; + }; + + // Trigger one or many events, firing all bound callbacks. Callbacks are + // passed the same arguments as `trigger` is, apart from the event name + // (unless you're listening on `"all"`, which will cause your callback to + // receive the true name of the event as the first argument). + Events.trigger = function(name) { + if (!this._events) return this; + + var length = Math.max(0, arguments.length - 1); + var args = Array(length); + for (var i = 0; i < length; i++) args[i] = arguments[i + 1]; + + eventsApi(triggerApi, this._events, name, void 0, args); + return this; + }; + + // Handles triggering the appropriate event callbacks. + var triggerApi = function(objEvents, name, callback, args) { + if (objEvents) { + var events = objEvents[name]; + var allEvents = objEvents.all; + if (events && allEvents) allEvents = allEvents.slice(); + if (events) triggerEvents(events, args); + if (allEvents) triggerEvents(allEvents, [name].concat(args)); + } + return objEvents; + }; + + // A difficult-to-believe, but optimized internal dispatch function for + // triggering events. Tries to keep the usual cases speedy (most internal + // Backbone events have 3 arguments). + var triggerEvents = function(events, args) { + var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2]; + switch (args.length) { + case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return; + case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return; + case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return; + case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return; + default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return; + } + }; + + // Aliases for backwards compatibility. + Events.bind = Events.on; + Events.unbind = Events.off; + + // Allow the `Backbone` object to serve as a global event bus, for folks who + // want global "pubsub" in a convenient place. + _.extend(Backbone, Events); + + // Backbone.Model + // -------------- + + // Backbone **Models** are the basic data object in the framework -- + // frequently representing a row in a table in a database on your server. + // A discrete chunk of data and a bunch of useful, related methods for + // performing computations and transformations on that data. + + // Create a new model with the specified attributes. A client id (`cid`) + // is automatically generated and assigned for you. + var Model = Backbone.Model = function(attributes, options) { + var attrs = attributes || {}; + options || (options = {}); + this.cid = _.uniqueId(this.cidPrefix); + this.attributes = {}; + if (options.collection) this.collection = options.collection; + if (options.parse) attrs = this.parse(attrs, options) || {}; + var defaults = _.result(this, 'defaults'); + attrs = _.defaults(_.extend({}, defaults, attrs), defaults); + this.set(attrs, options); + this.changed = {}; + this.initialize.apply(this, arguments); + }; + + // Attach all inheritable methods to the Model prototype. + _.extend(Model.prototype, Events, { + + // A hash of attributes whose current and previous value differ. + changed: null, + + // The value returned during the last failed validation. + validationError: null, + + // The default name for the JSON `id` attribute is `"id"`. MongoDB and + // CouchDB users may want to set this to `"_id"`. + idAttribute: 'id', + + // The prefix is used to create the client id which is used to identify models locally. + // You may want to override this if you're experiencing name clashes with model ids. + cidPrefix: 'c', + + // Initialize is an empty function by default. Override it with your own + // initialization logic. + initialize: function(){}, + + // Return a copy of the model's `attributes` object. + toJSON: function(options) { + return _.clone(this.attributes); + }, + + // Proxy `Backbone.sync` by default -- but override this if you need + // custom syncing semantics for *this* particular model. + sync: function() { + return Backbone.sync.apply(this, arguments); + }, + + // Get the value of an attribute. + get: function(attr) { + return this.attributes[attr]; + }, + + // Get the HTML-escaped value of an attribute. + escape: function(attr) { + return _.escape(this.get(attr)); + }, + + // Returns `true` if the attribute contains a value that is not null + // or undefined. + has: function(attr) { + return this.get(attr) != null; + }, + + // Special-cased proxy to underscore's `_.matches` method. + matches: function(attrs) { + return !!_.iteratee(attrs, this)(this.attributes); + }, + + // Set a hash of model attributes on the object, firing `"change"`. This is + // the core primitive operation of a model, updating the data and notifying + // anyone who needs to know about the change in state. The heart of the beast. + set: function(key, val, options) { + if (key == null) return this; + + // Handle both `"key", value` and `{key: value}` -style arguments. + var attrs; + if (typeof key === 'object') { + attrs = key; + options = val; + } else { + (attrs = {})[key] = val; + } + + options || (options = {}); + + // Run validation. + if (!this._validate(attrs, options)) return false; + + // Extract attributes and options. + var unset = options.unset; + var silent = options.silent; + var changes = []; + var changing = this._changing; + this._changing = true; + + if (!changing) { + this._previousAttributes = _.clone(this.attributes); + this.changed = {}; + } + + var current = this.attributes; + var changed = this.changed; + var prev = this._previousAttributes; + + // For each `set` attribute, update or delete the current value. + for (var attr in attrs) { + val = attrs[attr]; + if (!_.isEqual(current[attr], val)) changes.push(attr); + if (!_.isEqual(prev[attr], val)) { + changed[attr] = val; + } else { + delete changed[attr]; + } + unset ? delete current[attr] : current[attr] = val; + } + + // Update the `id`. + if (this.idAttribute in attrs) this.id = this.get(this.idAttribute); + + // Trigger all relevant attribute changes. + if (!silent) { + if (changes.length) this._pending = options; + for (var i = 0; i < changes.length; i++) { + this.trigger('change:' + changes[i], this, current[changes[i]], options); + } + } + + // You might be wondering why there's a `while` loop here. Changes can + // be recursively nested within `"change"` events. + if (changing) return this; + if (!silent) { + while (this._pending) { + options = this._pending; + this._pending = false; + this.trigger('change', this, options); + } + } + this._pending = false; + this._changing = false; + return this; + }, + + // Remove an attribute from the model, firing `"change"`. `unset` is a noop + // if the attribute doesn't exist. + unset: function(attr, options) { + return this.set(attr, void 0, _.extend({}, options, {unset: true})); + }, + + // Clear all attributes on the model, firing `"change"`. + clear: function(options) { + var attrs = {}; + for (var key in this.attributes) attrs[key] = void 0; + return this.set(attrs, _.extend({}, options, {unset: true})); + }, + + // Determine if the model has changed since the last `"change"` event. + // If you specify an attribute name, determine if that attribute has changed. + hasChanged: function(attr) { + if (attr == null) return !_.isEmpty(this.changed); + return _.has(this.changed, attr); + }, + + // Return an object containing all the attributes that have changed, or + // false if there are no changed attributes. Useful for determining what + // parts of a view need to be updated and/or what attributes need to be + // persisted to the server. Unset attributes will be set to undefined. + // You can also pass an attributes object to diff against the model, + // determining if there *would be* a change. + changedAttributes: function(diff) { + if (!diff) return this.hasChanged() ? _.clone(this.changed) : false; + var old = this._changing ? this._previousAttributes : this.attributes; + var changed = {}; + for (var attr in diff) { + var val = diff[attr]; + if (_.isEqual(old[attr], val)) continue; + changed[attr] = val; + } + return _.size(changed) ? changed : false; + }, + + // Get the previous value of an attribute, recorded at the time the last + // `"change"` event was fired. + previous: function(attr) { + if (attr == null || !this._previousAttributes) return null; + return this._previousAttributes[attr]; + }, + + // Get all of the attributes of the model at the time of the previous + // `"change"` event. + previousAttributes: function() { + return _.clone(this._previousAttributes); + }, + + // Fetch the model from the server, merging the response with the model's + // local attributes. Any changed attributes will trigger a "change" event. + fetch: function(options) { + options = _.extend({parse: true}, options); + var model = this; + var success = options.success; + options.success = function(resp) { + var serverAttrs = options.parse ? model.parse(resp, options) : resp; + if (!model.set(serverAttrs, options)) return false; + if (success) success.call(options.context, model, resp, options); + model.trigger('sync', model, resp, options); + }; + wrapError(this, options); + return this.sync('read', this, options); + }, + + // Set a hash of model attributes, and sync the model to the server. + // If the server returns an attributes hash that differs, the model's + // state will be `set` again. + save: function(key, val, options) { + // Handle both `"key", value` and `{key: value}` -style arguments. + var attrs; + if (key == null || typeof key === 'object') { + attrs = key; + options = val; + } else { + (attrs = {})[key] = val; + } + + options = _.extend({validate: true, parse: true}, options); + var wait = options.wait; + + // If we're not waiting and attributes exist, save acts as + // `set(attr).save(null, opts)` with validation. Otherwise, check if + // the model will be valid when the attributes, if any, are set. + if (attrs && !wait) { + if (!this.set(attrs, options)) return false; + } else if (!this._validate(attrs, options)) { + return false; + } + + // After a successful server-side save, the client is (optionally) + // updated with the server-side state. + var model = this; + var success = options.success; + var attributes = this.attributes; + options.success = function(resp) { + // Ensure attributes are restored during synchronous saves. + model.attributes = attributes; + var serverAttrs = options.parse ? model.parse(resp, options) : resp; + if (wait) serverAttrs = _.extend({}, attrs, serverAttrs); + if (serverAttrs && !model.set(serverAttrs, options)) return false; + if (success) success.call(options.context, model, resp, options); + model.trigger('sync', model, resp, options); + }; + wrapError(this, options); + + // Set temporary attributes if `{wait: true}` to properly find new ids. + if (attrs && wait) this.attributes = _.extend({}, attributes, attrs); + + var method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update'); + if (method === 'patch' && !options.attrs) options.attrs = attrs; + var xhr = this.sync(method, this, options); + + // Restore attributes. + this.attributes = attributes; + + return xhr; + }, + + // Destroy this model on the server if it was already persisted. + // Optimistically removes the model from its collection, if it has one. + // If `wait: true` is passed, waits for the server to respond before removal. + destroy: function(options) { + options = options ? _.clone(options) : {}; + var model = this; + var success = options.success; + var wait = options.wait; + + var destroy = function() { + model.stopListening(); + model.trigger('destroy', model, model.collection, options); + }; + + options.success = function(resp) { + if (wait) destroy(); + if (success) success.call(options.context, model, resp, options); + if (!model.isNew()) model.trigger('sync', model, resp, options); + }; + + var xhr = false; + if (this.isNew()) { + _.defer(options.success); + } else { + wrapError(this, options); + xhr = this.sync('delete', this, options); + } + if (!wait) destroy(); + return xhr; + }, + + // Default URL for the model's representation on the server -- if you're + // using Backbone's restful methods, override this to change the endpoint + // that will be called. + url: function() { + var base = + _.result(this, 'urlRoot') || + _.result(this.collection, 'url') || + urlError(); + if (this.isNew()) return base; + var id = this.get(this.idAttribute); + return base.replace(/[^\/]$/, '$&/') + encodeURIComponent(id); + }, + + // **parse** converts a response into the hash of attributes to be `set` on + // the model. The default implementation is just to pass the response along. + parse: function(resp, options) { + return resp; + }, + + // Create a new model with identical attributes to this one. + clone: function() { + return new this.constructor(this.attributes); + }, + + // A model is new if it has never been saved to the server, and lacks an id. + isNew: function() { + return !this.has(this.idAttribute); + }, + + // Check if the model is currently in a valid state. + isValid: function(options) { + return this._validate({}, _.extend({}, options, {validate: true})); + }, + + // Run validation against the next complete set of model attributes, + // returning `true` if all is well. Otherwise, fire an `"invalid"` event. + _validate: function(attrs, options) { + if (!options.validate || !this.validate) return true; + attrs = _.extend({}, this.attributes, attrs); + var error = this.validationError = this.validate(attrs, options) || null; + if (!error) return true; + this.trigger('invalid', this, error, _.extend(options, {validationError: error})); + return false; + } + + }); + + // Underscore methods that we want to implement on the Model, mapped to the + // number of arguments they take. + var modelMethods = {keys: 1, values: 1, pairs: 1, invert: 1, pick: 0, + omit: 0, chain: 1, isEmpty: 1}; + + // Mix in each Underscore method as a proxy to `Model#attributes`. + addUnderscoreMethods(Model, modelMethods, 'attributes'); + + // Backbone.Collection + // ------------------- + + // If models tend to represent a single row of data, a Backbone Collection is + // more analogous to a table full of data ... or a small slice or page of that + // table, or a collection of rows that belong together for a particular reason + // -- all of the messages in this particular folder, all of the documents + // belonging to this particular author, and so on. Collections maintain + // indexes of their models, both in order, and for lookup by `id`. + + // Create a new **Collection**, perhaps to contain a specific type of `model`. + // If a `comparator` is specified, the Collection will maintain + // its models in sort order, as they're added and removed. + var Collection = Backbone.Collection = function(models, options) { + options || (options = {}); + if (options.model) this.model = options.model; + if (options.comparator !== void 0) this.comparator = options.comparator; + this._reset(); + this.initialize.apply(this, arguments); + if (models) this.reset(models, _.extend({silent: true}, options)); + }; + + // Default options for `Collection#set`. + var setOptions = {add: true, remove: true, merge: true}; + var addOptions = {add: true, remove: false}; + + // Splices `insert` into `array` at index `at`. + var splice = function(array, insert, at) { + at = Math.min(Math.max(at, 0), array.length); + var tail = Array(array.length - at); + var length = insert.length; + var i; + for (i = 0; i < tail.length; i++) tail[i] = array[i + at]; + for (i = 0; i < length; i++) array[i + at] = insert[i]; + for (i = 0; i < tail.length; i++) array[i + length + at] = tail[i]; + }; + + // Define the Collection's inheritable methods. + _.extend(Collection.prototype, Events, { + + // The default model for a collection is just a **Backbone.Model**. + // This should be overridden in most cases. + model: Model, + + // Initialize is an empty function by default. Override it with your own + // initialization logic. + initialize: function(){}, + + // The JSON representation of a Collection is an array of the + // models' attributes. + toJSON: function(options) { + return this.map(function(model) { return model.toJSON(options); }); + }, + + // Proxy `Backbone.sync` by default. + sync: function() { + return Backbone.sync.apply(this, arguments); + }, + + // Add a model, or list of models to the set. `models` may be Backbone + // Models or raw JavaScript objects to be converted to Models, or any + // combination of the two. + add: function(models, options) { + return this.set(models, _.extend({merge: false}, options, addOptions)); + }, + + // Remove a model, or a list of models from the set. + remove: function(models, options) { + options = _.extend({}, options); + var singular = !_.isArray(models); + models = singular ? [models] : models.slice(); + var removed = this._removeModels(models, options); + if (!options.silent && removed.length) { + options.changes = {added: [], merged: [], removed: removed}; + this.trigger('update', this, options); + } + return singular ? removed[0] : removed; + }, + + // Update a collection by `set`-ing a new list of models, adding new ones, + // removing models that are no longer present, and merging models that + // already exist in the collection, as necessary. Similar to **Model#set**, + // the core operation for updating the data contained by the collection. + set: function(models, options) { + if (models == null) return; + + options = _.extend({}, setOptions, options); + if (options.parse && !this._isModel(models)) { + models = this.parse(models, options) || []; + } + + var singular = !_.isArray(models); + models = singular ? [models] : models.slice(); + + var at = options.at; + if (at != null) at = +at; + if (at > this.length) at = this.length; + if (at < 0) at += this.length + 1; + + var set = []; + var toAdd = []; + var toMerge = []; + var toRemove = []; + var modelMap = {}; + + var add = options.add; + var merge = options.merge; + var remove = options.remove; + + var sort = false; + var sortable = this.comparator && at == null && options.sort !== false; + var sortAttr = _.isString(this.comparator) ? this.comparator : null; + + // Turn bare objects into model references, and prevent invalid models + // from being added. + var model, i; + for (i = 0; i < models.length; i++) { + model = models[i]; + + // If a duplicate is found, prevent it from being added and + // optionally merge it into the existing model. + var existing = this.get(model); + if (existing) { + if (merge && model !== existing) { + var attrs = this._isModel(model) ? model.attributes : model; + if (options.parse) attrs = existing.parse(attrs, options); + existing.set(attrs, options); + toMerge.push(existing); + if (sortable && !sort) sort = existing.hasChanged(sortAttr); + } + if (!modelMap[existing.cid]) { + modelMap[existing.cid] = true; + set.push(existing); + } + models[i] = existing; + + // If this is a new, valid model, push it to the `toAdd` list. + } else if (add) { + model = models[i] = this._prepareModel(model, options); + if (model) { + toAdd.push(model); + this._addReference(model, options); + modelMap[model.cid] = true; + set.push(model); + } + } + } + + // Remove stale models. + if (remove) { + for (i = 0; i < this.length; i++) { + model = this.models[i]; + if (!modelMap[model.cid]) toRemove.push(model); + } + if (toRemove.length) this._removeModels(toRemove, options); + } + + // See if sorting is needed, update `length` and splice in new models. + var orderChanged = false; + var replace = !sortable && add && remove; + if (set.length && replace) { + orderChanged = this.length !== set.length || _.some(this.models, function(m, index) { + return m !== set[index]; + }); + this.models.length = 0; + splice(this.models, set, 0); + this.length = this.models.length; + } else if (toAdd.length) { + if (sortable) sort = true; + splice(this.models, toAdd, at == null ? this.length : at); + this.length = this.models.length; + } + + // Silently sort the collection if appropriate. + if (sort) this.sort({silent: true}); + + // Unless silenced, it's time to fire all appropriate add/sort/update events. + if (!options.silent) { + for (i = 0; i < toAdd.length; i++) { + if (at != null) options.index = at + i; + model = toAdd[i]; + model.trigger('add', model, this, options); + } + if (sort || orderChanged) this.trigger('sort', this, options); + if (toAdd.length || toRemove.length || toMerge.length) { + options.changes = { + added: toAdd, + removed: toRemove, + merged: toMerge + }; + this.trigger('update', this, options); + } + } + + // Return the added (or merged) model (or models). + return singular ? models[0] : models; + }, + + // When you have more items than you want to add or remove individually, + // you can reset the entire set with a new list of models, without firing + // any granular `add` or `remove` events. Fires `reset` when finished. + // Useful for bulk operations and optimizations. + reset: function(models, options) { + options = options ? _.clone(options) : {}; + for (var i = 0; i < this.models.length; i++) { + this._removeReference(this.models[i], options); + } + options.previousModels = this.models; + this._reset(); + models = this.add(models, _.extend({silent: true}, options)); + if (!options.silent) this.trigger('reset', this, options); + return models; + }, + + // Add a model to the end of the collection. + push: function(model, options) { + return this.add(model, _.extend({at: this.length}, options)); + }, + + // Remove a model from the end of the collection. + pop: function(options) { + var model = this.at(this.length - 1); + return this.remove(model, options); + }, + + // Add a model to the beginning of the collection. + unshift: function(model, options) { + return this.add(model, _.extend({at: 0}, options)); + }, + + // Remove a model from the beginning of the collection. + shift: function(options) { + var model = this.at(0); + return this.remove(model, options); + }, + + // Slice out a sub-array of models from the collection. + slice: function() { + return slice.apply(this.models, arguments); + }, + + // Get a model from the set by id, cid, model object with id or cid + // properties, or an attributes object that is transformed through modelId. + get: function(obj) { + if (obj == null) return void 0; + return this._byId[obj] || + this._byId[this.modelId(obj.attributes || obj)] || + obj.cid && this._byId[obj.cid]; + }, + + // Returns `true` if the model is in the collection. + has: function(obj) { + return this.get(obj) != null; + }, + + // Get the model at the given index. + at: function(index) { + if (index < 0) index += this.length; + return this.models[index]; + }, + + // Return models with matching attributes. Useful for simple cases of + // `filter`. + where: function(attrs, first) { + return this[first ? 'find' : 'filter'](attrs); + }, + + // Return the first model with matching attributes. Useful for simple cases + // of `find`. + findWhere: function(attrs) { + return this.where(attrs, true); + }, + + // Force the collection to re-sort itself. You don't need to call this under + // normal circumstances, as the set will maintain sort order as each item + // is added. + sort: function(options) { + var comparator = this.comparator; + if (!comparator) throw new Error('Cannot sort a set without a comparator'); + options || (options = {}); + + var length = comparator.length; + if (_.isFunction(comparator)) comparator = _.bind(comparator, this); + + // Run sort based on type of `comparator`. + if (length === 1 || _.isString(comparator)) { + this.models = this.sortBy(comparator); + } else { + this.models.sort(comparator); + } + if (!options.silent) this.trigger('sort', this, options); + return this; + }, + + // Pluck an attribute from each model in the collection. + pluck: function(attr) { + return this.map(attr + ''); + }, + + // Fetch the default set of models for this collection, resetting the + // collection when they arrive. If `reset: true` is passed, the response + // data will be passed through the `reset` method instead of `set`. + fetch: function(options) { + options = _.extend({parse: true}, options); + var success = options.success; + var collection = this; + options.success = function(resp) { + var method = options.reset ? 'reset' : 'set'; + collection[method](resp, options); + if (success) success.call(options.context, collection, resp, options); + collection.trigger('sync', collection, resp, options); + }; + wrapError(this, options); + return this.sync('read', this, options); + }, + + // Create a new instance of a model in this collection. Add the model to the + // collection immediately, unless `wait: true` is passed, in which case we + // wait for the server to agree. + create: function(model, options) { + options = options ? _.clone(options) : {}; + var wait = options.wait; + model = this._prepareModel(model, options); + if (!model) return false; + if (!wait) this.add(model, options); + var collection = this; + var success = options.success; + options.success = function(m, resp, callbackOpts) { + if (wait) collection.add(m, callbackOpts); + if (success) success.call(callbackOpts.context, m, resp, callbackOpts); + }; + model.save(null, options); + return model; + }, + + // **parse** converts a response into a list of models to be added to the + // collection. The default implementation is just to pass it through. + parse: function(resp, options) { + return resp; + }, + + // Create a new collection with an identical list of models as this one. + clone: function() { + return new this.constructor(this.models, { + model: this.model, + comparator: this.comparator + }); + }, + + // Define how to uniquely identify models in the collection. + modelId: function(attrs) { + return attrs[this.model.prototype.idAttribute || 'id']; + }, + + // Private method to reset all internal state. Called when the collection + // is first initialized or reset. + _reset: function() { + this.length = 0; + this.models = []; + this._byId = {}; + }, + + // Prepare a hash of attributes (or other model) to be added to this + // collection. + _prepareModel: function(attrs, options) { + if (this._isModel(attrs)) { + if (!attrs.collection) attrs.collection = this; + return attrs; + } + options = options ? _.clone(options) : {}; + options.collection = this; + var model = new this.model(attrs, options); + if (!model.validationError) return model; + this.trigger('invalid', this, model.validationError, options); + return false; + }, + + // Internal method called by both remove and set. + _removeModels: function(models, options) { + var removed = []; + for (var i = 0; i < models.length; i++) { + var model = this.get(models[i]); + if (!model) continue; + + var index = this.indexOf(model); + this.models.splice(index, 1); + this.length--; + + // Remove references before triggering 'remove' event to prevent an + // infinite loop. #3693 + delete this._byId[model.cid]; + var id = this.modelId(model.attributes); + if (id != null) delete this._byId[id]; + + if (!options.silent) { + options.index = index; + model.trigger('remove', model, this, options); + } + + removed.push(model); + this._removeReference(model, options); + } + return removed; + }, + + // Method for checking whether an object should be considered a model for + // the purposes of adding to the collection. + _isModel: function(model) { + return model instanceof Model; + }, + + // Internal method to create a model's ties to a collection. + _addReference: function(model, options) { + this._byId[model.cid] = model; + var id = this.modelId(model.attributes); + if (id != null) this._byId[id] = model; + model.on('all', this._onModelEvent, this); + }, + + // Internal method to sever a model's ties to a collection. + _removeReference: function(model, options) { + delete this._byId[model.cid]; + var id = this.modelId(model.attributes); + if (id != null) delete this._byId[id]; + if (this === model.collection) delete model.collection; + model.off('all', this._onModelEvent, this); + }, + + // Internal method called every time a model in the set fires an event. + // Sets need to update their indexes when models change ids. All other + // events simply proxy through. "add" and "remove" events that originate + // in other collections are ignored. + _onModelEvent: function(event, model, collection, options) { + if (model) { + if ((event === 'add' || event === 'remove') && collection !== this) return; + if (event === 'destroy') this.remove(model, options); + if (event === 'change') { + var prevId = this.modelId(model.previousAttributes()); + var id = this.modelId(model.attributes); + if (prevId !== id) { + if (prevId != null) delete this._byId[prevId]; + if (id != null) this._byId[id] = model; + } + } + } + this.trigger.apply(this, arguments); + } + + }); + + // Underscore methods that we want to implement on the Collection. + // 90% of the core usefulness of Backbone Collections is actually implemented + // right here: + var collectionMethods = {forEach: 3, each: 3, map: 3, collect: 3, reduce: 0, + foldl: 0, inject: 0, reduceRight: 0, foldr: 0, find: 3, detect: 3, filter: 3, + select: 3, reject: 3, every: 3, all: 3, some: 3, any: 3, include: 3, includes: 3, + contains: 3, invoke: 0, max: 3, min: 3, toArray: 1, size: 1, first: 3, + head: 3, take: 3, initial: 3, rest: 3, tail: 3, drop: 3, last: 3, + without: 0, difference: 0, indexOf: 3, shuffle: 1, lastIndexOf: 3, + isEmpty: 1, chain: 1, sample: 3, partition: 3, groupBy: 3, countBy: 3, + sortBy: 3, indexBy: 3, findIndex: 3, findLastIndex: 3}; + + // Mix in each Underscore method as a proxy to `Collection#models`. + addUnderscoreMethods(Collection, collectionMethods, 'models'); + + // Backbone.View + // ------------- + + // Backbone Views are almost more convention than they are actual code. A View + // is simply a JavaScript object that represents a logical chunk of UI in the + // DOM. This might be a single item, an entire list, a sidebar or panel, or + // even the surrounding frame which wraps your whole app. Defining a chunk of + // UI as a **View** allows you to define your DOM events declaratively, without + // having to worry about render order ... and makes it easy for the view to + // react to specific changes in the state of your models. + + // Creating a Backbone.View creates its initial element outside of the DOM, + // if an existing element is not provided... + var View = Backbone.View = function(options) { + this.cid = _.uniqueId('view'); + _.extend(this, _.pick(options, viewOptions)); + this._ensureElement(); + this.initialize.apply(this, arguments); + }; + + // Cached regex to split keys for `delegate`. + var delegateEventSplitter = /^(\S+)\s*(.*)$/; + + // List of view options to be set as properties. + var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events']; + + // Set up all inheritable **Backbone.View** properties and methods. + _.extend(View.prototype, Events, { + + // The default `tagName` of a View's element is `"div"`. + tagName: 'div', + + // jQuery delegate for element lookup, scoped to DOM elements within the + // current view. This should be preferred to global lookups where possible. + $: function(selector) { + return this.$el.find(selector); + }, + + // Initialize is an empty function by default. Override it with your own + // initialization logic. + initialize: function(){}, + + // **render** is the core function that your view should override, in order + // to populate its element (`this.el`), with the appropriate HTML. The + // convention is for **render** to always return `this`. + render: function() { + return this; + }, + + // Remove this view by taking the element out of the DOM, and removing any + // applicable Backbone.Events listeners. + remove: function() { + this._removeElement(); + this.stopListening(); + return this; + }, + + // Remove this view's element from the document and all event listeners + // attached to it. Exposed for subclasses using an alternative DOM + // manipulation API. + _removeElement: function() { + this.$el.remove(); + }, + + // Change the view's element (`this.el` property) and re-delegate the + // view's events on the new element. + setElement: function(element) { + this.undelegateEvents(); + this._setElement(element); + this.delegateEvents(); + return this; + }, + + // Creates the `this.el` and `this.$el` references for this view using the + // given `el`. `el` can be a CSS selector or an HTML string, a jQuery + // context or an element. Subclasses can override this to utilize an + // alternative DOM manipulation API and are only required to set the + // `this.el` property. + _setElement: function(el) { + this.$el = el instanceof Backbone.$ ? el : Backbone.$(el); + this.el = this.$el[0]; + }, + + // Set callbacks, where `this.events` is a hash of + // + // *{"event selector": "callback"}* + // + // { + // 'mousedown .title': 'edit', + // 'click .button': 'save', + // 'click .open': function(e) { ... } + // } + // + // pairs. Callbacks will be bound to the view, with `this` set properly. + // Uses event delegation for efficiency. + // Omitting the selector binds the event to `this.el`. + delegateEvents: function(events) { + events || (events = _.result(this, 'events')); + if (!events) return this; + this.undelegateEvents(); + for (var key in events) { + var method = events[key]; + if (!_.isFunction(method)) method = this[method]; + if (!method) continue; + var match = key.match(delegateEventSplitter); + this.delegate(match[1], match[2], _.bind(method, this)); + } + return this; + }, + + // Add a single event listener to the view's element (or a child element + // using `selector`). This only works for delegate-able events: not `focus`, + // `blur`, and not `change`, `submit`, and `reset` in Internet Explorer. + delegate: function(eventName, selector, listener) { + this.$el.on(eventName + '.delegateEvents' + this.cid, selector, listener); + return this; + }, + + // Clears all callbacks previously bound to the view by `delegateEvents`. + // You usually don't need to use this, but may wish to if you have multiple + // Backbone views attached to the same DOM element. + undelegateEvents: function() { + if (this.$el) this.$el.off('.delegateEvents' + this.cid); + return this; + }, + + // A finer-grained `undelegateEvents` for removing a single delegated event. + // `selector` and `listener` are both optional. + undelegate: function(eventName, selector, listener) { + this.$el.off(eventName + '.delegateEvents' + this.cid, selector, listener); + return this; + }, + + // Produces a DOM element to be assigned to your view. Exposed for + // subclasses using an alternative DOM manipulation API. + _createElement: function(tagName) { + return document.createElement(tagName); + }, + + // Ensure that the View has a DOM element to render into. + // If `this.el` is a string, pass it through `$()`, take the first + // matching element, and re-assign it to `el`. Otherwise, create + // an element from the `id`, `className` and `tagName` properties. + _ensureElement: function() { + if (!this.el) { + var attrs = _.extend({}, _.result(this, 'attributes')); + if (this.id) attrs.id = _.result(this, 'id'); + if (this.className) attrs['class'] = _.result(this, 'className'); + this.setElement(this._createElement(_.result(this, 'tagName'))); + this._setAttributes(attrs); + } else { + this.setElement(_.result(this, 'el')); + } + }, + + // Set attributes from a hash on this view's element. Exposed for + // subclasses using an alternative DOM manipulation API. + _setAttributes: function(attributes) { + this.$el.attr(attributes); + } + + }); + + // Backbone.sync + // ------------- + + // Override this function to change the manner in which Backbone persists + // models to the server. You will be passed the type of request, and the + // model in question. By default, makes a RESTful Ajax request + // to the model's `url()`. Some possible customizations could be: + // + // * Use `setTimeout` to batch rapid-fire updates into a single request. + // * Send up the models as XML instead of JSON. + // * Persist models via WebSockets instead of Ajax. + // + // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests + // as `POST`, with a `_method` parameter containing the true HTTP method, + // as well as all requests with the body as `application/x-www-form-urlencoded` + // instead of `application/json` with the model in a param named `model`. + // Useful when interfacing with server-side languages like **PHP** that make + // it difficult to read the body of `PUT` requests. + Backbone.sync = function(method, model, options) { + var type = methodMap[method]; + + // Default options, unless specified. + _.defaults(options || (options = {}), { + emulateHTTP: Backbone.emulateHTTP, + emulateJSON: Backbone.emulateJSON + }); + + // Default JSON-request options. + var params = {type: type, dataType: 'json'}; + + // Ensure that we have a URL. + if (!options.url) { + params.url = _.result(model, 'url') || urlError(); + } + + // Ensure that we have the appropriate request data. + if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) { + params.contentType = 'application/json'; + params.data = JSON.stringify(options.attrs || model.toJSON(options)); + } + + // For older servers, emulate JSON by encoding the request into an HTML-form. + if (options.emulateJSON) { + params.contentType = 'application/x-www-form-urlencoded'; + params.data = params.data ? {model: params.data} : {}; + } + + // For older servers, emulate HTTP by mimicking the HTTP method with `_method` + // And an `X-HTTP-Method-Override` header. + if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) { + params.type = 'POST'; + if (options.emulateJSON) params.data._method = type; + var beforeSend = options.beforeSend; + options.beforeSend = function(xhr) { + xhr.setRequestHeader('X-HTTP-Method-Override', type); + if (beforeSend) return beforeSend.apply(this, arguments); + }; + } + + // Don't process data on a non-GET request. + if (params.type !== 'GET' && !options.emulateJSON) { + params.processData = false; + } + + // Pass along `textStatus` and `errorThrown` from jQuery. + var error = options.error; + options.error = function(xhr, textStatus, errorThrown) { + options.textStatus = textStatus; + options.errorThrown = errorThrown; + if (error) error.call(options.context, xhr, textStatus, errorThrown); + }; + + // Make the request, allowing the user to override any Ajax options. + var xhr = options.xhr = Backbone.ajax(_.extend(params, options)); + model.trigger('request', model, xhr, options); + return xhr; + }; + + // Map from CRUD to HTTP for our default `Backbone.sync` implementation. + var methodMap = { + 'create': 'POST', + 'update': 'PUT', + 'patch': 'PATCH', + 'delete': 'DELETE', + 'read': 'GET' + }; + + // Set the default implementation of `Backbone.ajax` to proxy through to `$`. + // Override this if you'd like to use a different library. + Backbone.ajax = function() { + return Backbone.$.ajax.apply(Backbone.$, arguments); + }; + + // Backbone.Router + // --------------- + + // Routers map faux-URLs to actions, and fire events when routes are + // matched. Creating a new one sets its `routes` hash, if not set statically. + var Router = Backbone.Router = function(options) { + options || (options = {}); + if (options.routes) this.routes = options.routes; + this._bindRoutes(); + this.initialize.apply(this, arguments); + }; + + // Cached regular expressions for matching named param parts and splatted + // parts of route strings. + var optionalParam = /\((.*?)\)/g; + var namedParam = /(\(\?)?:\w+/g; + var splatParam = /\*\w+/g; + var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g; + + // Set up all inheritable **Backbone.Router** properties and methods. + _.extend(Router.prototype, Events, { + + // Initialize is an empty function by default. Override it with your own + // initialization logic. + initialize: function(){}, + + // Manually bind a single named route to a callback. For example: + // + // this.route('search/:query/p:num', 'search', function(query, num) { + // ... + // }); + // + route: function(route, name, callback) { + if (!_.isRegExp(route)) route = this._routeToRegExp(route); + if (_.isFunction(name)) { + callback = name; + name = ''; + } + if (!callback) callback = this[name]; + var router = this; + Backbone.history.route(route, function(fragment) { + var args = router._extractParameters(route, fragment); + if (router.execute(callback, args, name) !== false) { + router.trigger.apply(router, ['route:' + name].concat(args)); + router.trigger('route', name, args); + Backbone.history.trigger('route', router, name, args); + } + }); + return this; + }, + + // Execute a route handler with the provided parameters. This is an + // excellent place to do pre-route setup or post-route cleanup. + execute: function(callback, args, name) { + if (callback) callback.apply(this, args); + }, + + // Simple proxy to `Backbone.history` to save a fragment into the history. + navigate: function(fragment, options) { + Backbone.history.navigate(fragment, options); + return this; + }, + + // Bind all defined routes to `Backbone.history`. We have to reverse the + // order of the routes here to support behavior where the most general + // routes can be defined at the bottom of the route map. + _bindRoutes: function() { + if (!this.routes) return; + this.routes = _.result(this, 'routes'); + var route, routes = _.keys(this.routes); + while ((route = routes.pop()) != null) { + this.route(route, this.routes[route]); + } + }, + + // Convert a route string into a regular expression, suitable for matching + // against the current location hash. + _routeToRegExp: function(route) { + route = route.replace(escapeRegExp, '\\$&') + .replace(optionalParam, '(?:$1)?') + .replace(namedParam, function(match, optional) { + return optional ? match : '([^/?]+)'; + }) + .replace(splatParam, '([^?]*?)'); + return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$'); + }, + + // Given a route, and a URL fragment that it matches, return the array of + // extracted decoded parameters. Empty or unmatched parameters will be + // treated as `null` to normalize cross-browser behavior. + _extractParameters: function(route, fragment) { + var params = route.exec(fragment).slice(1); + return _.map(params, function(param, i) { + // Don't decode the search params. + if (i === params.length - 1) return param || null; + return param ? decodeURIComponent(param) : null; + }); + } + + }); + + // Backbone.History + // ---------------- + + // Handles cross-browser history management, based on either + // [pushState](http://diveintohtml5.info/history.html) and real URLs, or + // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange) + // and URL fragments. If the browser supports neither (old IE, natch), + // falls back to polling. + var History = Backbone.History = function() { + this.handlers = []; + this.checkUrl = _.bind(this.checkUrl, this); + + // Ensure that `History` can be used outside of the browser. + if (typeof window !== 'undefined') { + this.location = window.location; + this.history = window.history; + } + }; + + // Cached regex for stripping a leading hash/slash and trailing space. + var routeStripper = /^[#\/]|\s+$/g; + + // Cached regex for stripping leading and trailing slashes. + var rootStripper = /^\/+|\/+$/g; + + // Cached regex for stripping urls of hash. + var pathStripper = /#.*$/; + + // Has the history handling already been started? + History.started = false; + + // Set up all inheritable **Backbone.History** properties and methods. + _.extend(History.prototype, Events, { + + // The default interval to poll for hash changes, if necessary, is + // twenty times a second. + interval: 50, + + // Are we at the app root? + atRoot: function() { + var path = this.location.pathname.replace(/[^\/]$/, '$&/'); + return path === this.root && !this.getSearch(); + }, + + // Does the pathname match the root? + matchRoot: function() { + var path = this.decodeFragment(this.location.pathname); + var rootPath = path.slice(0, this.root.length - 1) + '/'; + return rootPath === this.root; + }, + + // Unicode characters in `location.pathname` are percent encoded so they're + // decoded for comparison. `%25` should not be decoded since it may be part + // of an encoded parameter. + decodeFragment: function(fragment) { + return decodeURI(fragment.replace(/%25/g, '%2525')); + }, + + // In IE6, the hash fragment and search params are incorrect if the + // fragment contains `?`. + getSearch: function() { + var match = this.location.href.replace(/#.*/, '').match(/\?.+/); + return match ? match[0] : ''; + }, + + // Gets the true hash value. Cannot use location.hash directly due to bug + // in Firefox where location.hash will always be decoded. + getHash: function(window) { + var match = (window || this).location.href.match(/#(.*)$/); + return match ? match[1] : ''; + }, + + // Get the pathname and search params, without the root. + getPath: function() { + var path = this.decodeFragment( + this.location.pathname + this.getSearch() + ).slice(this.root.length - 1); + return path.charAt(0) === '/' ? path.slice(1) : path; + }, + + // Get the cross-browser normalized URL fragment from the path or hash. + getFragment: function(fragment) { + if (fragment == null) { + if (this._usePushState || !this._wantsHashChange) { + fragment = this.getPath(); + } else { + fragment = this.getHash(); + } + } + return fragment.replace(routeStripper, ''); + }, + + // Start the hash change handling, returning `true` if the current URL matches + // an existing route, and `false` otherwise. + start: function(options) { + if (History.started) throw new Error('Backbone.history has already been started'); + History.started = true; + + // Figure out the initial configuration. Do we need an iframe? + // Is pushState desired ... is it available? + this.options = _.extend({root: '/'}, this.options, options); + this.root = this.options.root; + this._wantsHashChange = this.options.hashChange !== false; + this._hasHashChange = 'onhashchange' in window && (document.documentMode === void 0 || document.documentMode > 7); + this._useHashChange = this._wantsHashChange && this._hasHashChange; + this._wantsPushState = !!this.options.pushState; + this._hasPushState = !!(this.history && this.history.pushState); + this._usePushState = this._wantsPushState && this._hasPushState; + this.fragment = this.getFragment(); + + // Normalize root to always include a leading and trailing slash. + this.root = ('/' + this.root + '/').replace(rootStripper, '/'); + + // Transition from hashChange to pushState or vice versa if both are + // requested. + if (this._wantsHashChange && this._wantsPushState) { + + // If we've started off with a route from a `pushState`-enabled + // browser, but we're currently in a browser that doesn't support it... + if (!this._hasPushState && !this.atRoot()) { + var rootPath = this.root.slice(0, -1) || '/'; + this.location.replace(rootPath + '#' + this.getPath()); + // Return immediately as browser will do redirect to new url + return true; + + // Or if we've started out with a hash-based route, but we're currently + // in a browser where it could be `pushState`-based instead... + } else if (this._hasPushState && this.atRoot()) { + this.navigate(this.getHash(), {replace: true}); + } + + } + + // Proxy an iframe to handle location events if the browser doesn't + // support the `hashchange` event, HTML5 history, or the user wants + // `hashChange` but not `pushState`. + if (!this._hasHashChange && this._wantsHashChange && !this._usePushState) { + this.iframe = document.createElement('iframe'); + this.iframe.src = 'javascript:0'; + this.iframe.style.display = 'none'; + this.iframe.tabIndex = -1; + var body = document.body; + // Using `appendChild` will throw on IE < 9 if the document is not ready. + var iWindow = body.insertBefore(this.iframe, body.firstChild).contentWindow; + iWindow.document.open(); + iWindow.document.close(); + iWindow.location.hash = '#' + this.fragment; + } + + // Add a cross-platform `addEventListener` shim for older browsers. + var addEventListener = window.addEventListener || function(eventName, listener) { + return attachEvent('on' + eventName, listener); + }; + + // Depending on whether we're using pushState or hashes, and whether + // 'onhashchange' is supported, determine how we check the URL state. + if (this._usePushState) { + addEventListener('popstate', this.checkUrl, false); + } else if (this._useHashChange && !this.iframe) { + addEventListener('hashchange', this.checkUrl, false); + } else if (this._wantsHashChange) { + this._checkUrlInterval = setInterval(this.checkUrl, this.interval); + } + + if (!this.options.silent) return this.loadUrl(); + }, + + // Disable Backbone.history, perhaps temporarily. Not useful in a real app, + // but possibly useful for unit testing Routers. + stop: function() { + // Add a cross-platform `removeEventListener` shim for older browsers. + var removeEventListener = window.removeEventListener || function(eventName, listener) { + return detachEvent('on' + eventName, listener); + }; + + // Remove window listeners. + if (this._usePushState) { + removeEventListener('popstate', this.checkUrl, false); + } else if (this._useHashChange && !this.iframe) { + removeEventListener('hashchange', this.checkUrl, false); + } + + // Clean up the iframe if necessary. + if (this.iframe) { + document.body.removeChild(this.iframe); + this.iframe = null; + } + + // Some environments will throw when clearing an undefined interval. + if (this._checkUrlInterval) clearInterval(this._checkUrlInterval); + History.started = false; + }, + + // Add a route to be tested when the fragment changes. Routes added later + // may override previous routes. + route: function(route, callback) { + this.handlers.unshift({route: route, callback: callback}); + }, + + // Checks the current URL to see if it has changed, and if it has, + // calls `loadUrl`, normalizing across the hidden iframe. + checkUrl: function(e) { + var current = this.getFragment(); + + // If the user pressed the back button, the iframe's hash will have + // changed and we should use that for comparison. + if (current === this.fragment && this.iframe) { + current = this.getHash(this.iframe.contentWindow); + } + + if (current === this.fragment) return false; + if (this.iframe) this.navigate(current); + this.loadUrl(); + }, + + // Attempt to load the current URL fragment. If a route succeeds with a + // match, returns `true`. If no defined routes matches the fragment, + // returns `false`. + loadUrl: function(fragment) { + // If the root doesn't match, no routes can match either. + if (!this.matchRoot()) return false; + fragment = this.fragment = this.getFragment(fragment); + return _.some(this.handlers, function(handler) { + if (handler.route.test(fragment)) { + handler.callback(fragment); + return true; + } + }); + }, + + // Save a fragment into the hash history, or replace the URL state if the + // 'replace' option is passed. You are responsible for properly URL-encoding + // the fragment in advance. + // + // The options object can contain `trigger: true` if you wish to have the + // route callback be fired (not usually desirable), or `replace: true`, if + // you wish to modify the current URL without adding an entry to the history. + navigate: function(fragment, options) { + if (!History.started) return false; + if (!options || options === true) options = {trigger: !!options}; + + // Normalize the fragment. + fragment = this.getFragment(fragment || ''); + + // Don't include a trailing slash on the root. + var rootPath = this.root; + if (fragment === '' || fragment.charAt(0) === '?') { + rootPath = rootPath.slice(0, -1) || '/'; + } + var url = rootPath + fragment; + + // Strip the hash and decode for matching. + fragment = this.decodeFragment(fragment.replace(pathStripper, '')); + + if (this.fragment === fragment) return; + this.fragment = fragment; + + // If pushState is available, we use it to set the fragment as a real URL. + if (this._usePushState) { + this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url); + + // If hash changes haven't been explicitly disabled, update the hash + // fragment to store history. + } else if (this._wantsHashChange) { + this._updateHash(this.location, fragment, options.replace); + if (this.iframe && fragment !== this.getHash(this.iframe.contentWindow)) { + var iWindow = this.iframe.contentWindow; + + // Opening and closing the iframe tricks IE7 and earlier to push a + // history entry on hash-tag change. When replace is true, we don't + // want this. + if (!options.replace) { + iWindow.document.open(); + iWindow.document.close(); + } + + this._updateHash(iWindow.location, fragment, options.replace); + } + + // If you've told us that you explicitly don't want fallback hashchange- + // based history, then `navigate` becomes a page refresh. + } else { + return this.location.assign(url); + } + if (options.trigger) return this.loadUrl(fragment); + }, + + // Update the hash location, either replacing the current entry, or adding + // a new one to the browser history. + _updateHash: function(location, fragment, replace) { + if (replace) { + var href = location.href.replace(/(javascript:|#).*$/, ''); + location.replace(href + '#' + fragment); + } else { + // Some browsers require that `hash` contains a leading #. + location.hash = '#' + fragment; + } + } + + }); + + // Create the default Backbone.history. + Backbone.history = new History; + + // Helpers + // ------- + + // Helper function to correctly set up the prototype chain for subclasses. + // Similar to `goog.inherits`, but uses a hash of prototype properties and + // class properties to be extended. + var extend = function(protoProps, staticProps) { + var parent = this; + var child; + + // The constructor function for the new subclass is either defined by you + // (the "constructor" property in your `extend` definition), or defaulted + // by us to simply call the parent constructor. + if (protoProps && _.has(protoProps, 'constructor')) { + child = protoProps.constructor; + } else { + child = function(){ return parent.apply(this, arguments); }; + } + + // Add static properties to the constructor function, if supplied. + _.extend(child, parent, staticProps); + + // Set the prototype chain to inherit from `parent`, without calling + // `parent`'s constructor function and add the prototype properties. + child.prototype = _.create(parent.prototype, protoProps); + child.prototype.constructor = child; + + // Set a convenience property in case the parent's prototype is needed + // later. + child.__super__ = parent.prototype; + + return child; + }; + + // Set up inheritance for the model, collection, router, view and history. + Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend; + + // Throw an error when a URL is needed, and none is supplied. + var urlError = function() { + throw new Error('A "url" property or function must be specified'); + }; + + // Wrap an optional error callback with a fallback error event. + var wrapError = function(model, options) { + var error = options.error; + options.error = function(resp) { + if (error) error.call(options.context, model, resp, options); + model.trigger('error', model, resp, options); + }; + }; + + return Backbone; +}); + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js"))) + +/***/ }), + +/***/ "./node_modules/bootstrap.native/dist/bootstrap-native-v4.js": +/*!*******************************************************************!*\ + !*** ./node_modules/bootstrap.native/dist/bootstrap-native-v4.js ***! + \*******************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(global) {var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Native Javascript for Bootstrap 4 v2.0.22 | © dnp_theme | MIT-License +(function (root, factory) { + if (true) { + // AMD support: + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else { var bsn; } +}(this, function () { + + /* Native Javascript for Bootstrap 4 | Internal Utility Functions + ----------------------------------------------------------------*/ + "use strict"; + + // globals + var globalObject = typeof global !== 'undefined' ? global : this||window, + DOC = document, HTML = DOC.documentElement, body = 'body', // allow the library to be used in + + // Native Javascript for Bootstrap Global Object + BSN = globalObject.BSN = {}, + supports = BSN.supports = [], + + // function toggle attributes + dataToggle = 'data-toggle', + dataDismiss = 'data-dismiss', + dataSpy = 'data-spy', + dataRide = 'data-ride', + + // components + stringAlert = 'Alert', + stringButton = 'Button', + stringCarousel = 'Carousel', + stringCollapse = 'Collapse', + stringDropdown = 'Dropdown', + stringModal = 'Modal', + stringPopover = 'Popover', + stringScrollSpy = 'ScrollSpy', + stringTab = 'Tab', + stringTooltip = 'Tooltip', + + // options DATA API + databackdrop = 'data-backdrop', + dataKeyboard = 'data-keyboard', + dataTarget = 'data-target', + dataInterval = 'data-interval', + dataHeight = 'data-height', + dataPause = 'data-pause', + dataTitle = 'data-title', + dataOriginalTitle = 'data-original-title', + dataOriginalText = 'data-original-text', + dataDismissible = 'data-dismissible', + dataTrigger = 'data-trigger', + dataAnimation = 'data-animation', + dataContainer = 'data-container', + dataPlacement = 'data-placement', + dataDelay = 'data-delay', + dataOffsetTop = 'data-offset-top', + dataOffsetBottom = 'data-offset-bottom', + + // option keys + backdrop = 'backdrop', keyboard = 'keyboard', delay = 'delay', + content = 'content', target = 'target', + interval = 'interval', pause = 'pause', animation = 'animation', + placement = 'placement', container = 'container', + + // box model + offsetTop = 'offsetTop', offsetBottom = 'offsetBottom', + offsetLeft = 'offsetLeft', + scrollTop = 'scrollTop', scrollLeft = 'scrollLeft', + clientWidth = 'clientWidth', clientHeight = 'clientHeight', + offsetWidth = 'offsetWidth', offsetHeight = 'offsetHeight', + innerWidth = 'innerWidth', innerHeight = 'innerHeight', + scrollHeight = 'scrollHeight', height = 'height', + + // aria + ariaExpanded = 'aria-expanded', + ariaHidden = 'aria-hidden', + + // event names + clickEvent = 'click', + hoverEvent = 'hover', + keydownEvent = 'keydown', + keyupEvent = 'keyup', + resizeEvent = 'resize', + scrollEvent = 'scroll', + // originalEvents + showEvent = 'show', + shownEvent = 'shown', + hideEvent = 'hide', + hiddenEvent = 'hidden', + closeEvent = 'close', + closedEvent = 'closed', + slidEvent = 'slid', + slideEvent = 'slide', + changeEvent = 'change', + + // other + getAttribute = 'getAttribute', + setAttribute = 'setAttribute', + hasAttribute = 'hasAttribute', + createElement = 'createElement', + appendChild = 'appendChild', + innerHTML = 'innerHTML', + getElementsByTagName = 'getElementsByTagName', + preventDefault = 'preventDefault', + getBoundingClientRect = 'getBoundingClientRect', + querySelectorAll = 'querySelectorAll', + getElementsByCLASSNAME = 'getElementsByClassName', + + indexOf = 'indexOf', + parentNode = 'parentNode', + length = 'length', + toLowerCase = 'toLowerCase', + Transition = 'Transition', + Webkit = 'Webkit', + style = 'style', + push = 'push', + tabindex = 'tabindex', + contains = 'contains', + + active = 'active', + showClass = 'show', + collapsing = 'collapsing', + disabled = 'disabled', + loading = 'loading', + left = 'left', + right = 'right', + top = 'top', + bottom = 'bottom', + + // tooltip / popover + mouseHover = ('onmouseleave' in DOC) ? [ 'mouseenter', 'mouseleave'] : [ 'mouseover', 'mouseout' ], + tipPositions = /\b(top|bottom|left|right)+/, + + // modal + modalOverlay = 0, + fixedTop = 'fixed-top', + fixedBottom = 'fixed-bottom', + + // transitionEnd since 2.0.4 + supportTransitions = Webkit+Transition in HTML[style] || Transition[toLowerCase]() in HTML[style], + transitionEndEvent = Webkit+Transition in HTML[style] ? Webkit[toLowerCase]()+Transition+'End' : Transition[toLowerCase]()+'end', + + // set new focus element since 2.0.3 + setFocus = function(element){ + element.focus ? element.focus() : element.setActive(); + }, + + // class manipulation, since 2.0.0 requires polyfill.js + addClass = function(element,classNAME) { + element.classList.add(classNAME); + }, + removeClass = function(element,classNAME) { + element.classList.remove(classNAME); + }, + hasClass = function(element,classNAME){ // since 2.0.0 + return element.classList[contains](classNAME); + }, + + // selection methods + getElementsByClassName = function(element,classNAME) { // returns Array + return [].slice.call(element[getElementsByCLASSNAME]( classNAME )); + }, + queryElement = function (selector, parent) { + var lookUp = parent ? parent : DOC; + return typeof selector === 'object' ? selector : lookUp.querySelector(selector); + }, + getClosest = function (element, selector) { //element is the element and selector is for the closest parent element to find + // source http://gomakethings.com/climbing-up-and-down-the-dom-tree-with-vanilla-javascript/ + var firstChar = selector.charAt(0), selectorSubstring = selector.substr(1); + if ( firstChar === '.' ) {// If selector is a class + for ( ; element && element !== DOC; element = element[parentNode] ) { // Get closest match + if ( queryElement(selector,element[parentNode]) !== null && hasClass(element,selectorSubstring) ) { return element; } + } + } else if ( firstChar === '#' ) { // If selector is an ID + for ( ; element && element !== DOC; element = element[parentNode] ) { // Get closest match + if ( element.id === selectorSubstring ) { return element; } + } + } + return false; + }, + + // event attach jQuery style / trigger since 1.2.0 + on = function (element, event, handler) { + element.addEventListener(event, handler, false); + }, + off = function(element, event, handler) { + element.removeEventListener(event, handler, false); + }, + one = function (element, event, handler) { // one since 2.0.4 + on(element, event, function handlerWrapper(e){ + handler(e); + off(element, event, handlerWrapper); + }); + }, + emulateTransitionEnd = function(element,handler){ // emulateTransitionEnd since 2.0.4 + if (supportTransitions) { one(element, transitionEndEvent, function(e){ handler(e); }); } + else { handler(); } + }, + bootstrapCustomEvent = function (eventName, componentName, related) { + var OriginalCustomEvent = new CustomEvent( eventName + '.bs.' + componentName); + OriginalCustomEvent.relatedTarget = related; + this.dispatchEvent(OriginalCustomEvent); + }, + + // tooltip / popover stuff + getScroll = function() { // also Affix and ScrollSpy uses it + return { + y : globalObject.pageYOffset || HTML[scrollTop], + x : globalObject.pageXOffset || HTML[scrollLeft] + } + }, + styleTip = function(link,element,position,parent) { // both popovers and tooltips (target,tooltip,placement,elementToAppendTo) + var elementDimensions = { w : element[offsetWidth], h: element[offsetHeight] }, + windowWidth = (HTML[clientWidth] || DOC[body][clientWidth]), + windowHeight = (HTML[clientHeight] || DOC[body][clientHeight]), + rect = link[getBoundingClientRect](), + scroll = parent === DOC[body] ? getScroll() : { x: parent[offsetLeft] + parent[scrollLeft], y: parent[offsetTop] + parent[scrollTop] }, + linkDimensions = { w: rect[right] - rect[left], h: rect[bottom] - rect[top] }, + isPopover = hasClass(element,'popover'), + topPosition, leftPosition, + + arrow = queryElement('.arrow',element), + arrowTop, arrowLeft, arrowWidth, arrowHeight, + + halfTopExceed = rect[top] + linkDimensions.h/2 - elementDimensions.h/2 < 0, + halfLeftExceed = rect[left] + linkDimensions.w/2 - elementDimensions.w/2 < 0, + halfRightExceed = rect[left] + elementDimensions.w/2 + linkDimensions.w/2 >= windowWidth, + halfBottomExceed = rect[top] + elementDimensions.h/2 + linkDimensions.h/2 >= windowHeight, + topExceed = rect[top] - elementDimensions.h < 0, + leftExceed = rect[left] - elementDimensions.w < 0, + bottomExceed = rect[top] + elementDimensions.h + linkDimensions.h >= windowHeight, + rightExceed = rect[left] + elementDimensions.w + linkDimensions.w >= windowWidth; + + // recompute position + position = (position === left || position === right) && leftExceed && rightExceed ? top : position; // first, when both left and right limits are exceeded, we fall back to top|bottom + position = position === top && topExceed ? bottom : position; + position = position === bottom && bottomExceed ? top : position; + position = position === left && leftExceed ? right : position; + position = position === right && rightExceed ? left : position; + + // update tooltip/popover class + element.className[indexOf](position) === -1 && (element.className = element.className.replace(tipPositions,position)); + + // we check the computed width & height and update here + arrowWidth = arrow[offsetWidth]; arrowHeight = arrow[offsetHeight]; + + // apply styling to tooltip or popover + if ( position === left || position === right ) { // secondary|side positions + if ( position === left ) { // LEFT + leftPosition = rect[left] + scroll.x - elementDimensions.w - ( isPopover ? arrowWidth : 0 ); + } else { // RIGHT + leftPosition = rect[left] + scroll.x + linkDimensions.w; + } + + // adjust top and arrow + if (halfTopExceed) { + topPosition = rect[top] + scroll.y; + arrowTop = linkDimensions.h/2 - arrowWidth; + } else if (halfBottomExceed) { + topPosition = rect[top] + scroll.y - elementDimensions.h + linkDimensions.h; + arrowTop = elementDimensions.h - linkDimensions.h/2 - arrowWidth; + } else { + topPosition = rect[top] + scroll.y - elementDimensions.h/2 + linkDimensions.h/2; + arrowTop = elementDimensions.h/2 - (isPopover ? arrowHeight*0.9 : arrowHeight/2); + } + } else if ( position === top || position === bottom ) { // primary|vertical positions + if ( position === top) { // TOP + topPosition = rect[top] + scroll.y - elementDimensions.h - ( isPopover ? arrowHeight : 0 ); + } else { // BOTTOM + topPosition = rect[top] + scroll.y + linkDimensions.h; + } + // adjust left | right and also the arrow + if (halfLeftExceed) { + leftPosition = 0; + arrowLeft = rect[left] + linkDimensions.w/2 - arrowWidth; + } else if (halfRightExceed) { + leftPosition = windowWidth - elementDimensions.w*1.01; + arrowLeft = elementDimensions.w - ( windowWidth - rect[left] ) + linkDimensions.w/2 - arrowWidth/2; + } else { + leftPosition = rect[left] + scroll.x - elementDimensions.w/2 + linkDimensions.w/2; + arrowLeft = elementDimensions.w/2 - arrowWidth/2; + } + } + + // apply style to tooltip/popover and its arrow + element[style][top] = topPosition + 'px'; + element[style][left] = leftPosition + 'px'; + + arrowTop && (arrow[style][top] = arrowTop + 'px'); + arrowLeft && (arrow[style][left] = arrowLeft + 'px'); + }; + + BSN.version = '2.0.22'; + + /* Native Javascript for Bootstrap 4 | Alert + -------------------------------------------*/ + + // ALERT DEFINITION + // ================ + var Alert = function( element ) { + + // initialization element + element = queryElement(element); + + // bind, target alert, duration and stuff + var self = this, component = 'alert', + alert = getClosest(element,'.'+component), + triggerHandler = function(){ hasClass(alert,'fade') ? emulateTransitionEnd(alert,transitionEndHandler) : transitionEndHandler(); }, + // handlers + clickHandler = function(e){ + alert = getClosest(e[target],'.'+component); + element = queryElement('['+dataDismiss+'="'+component+'"]',alert); + element && alert && (element === e[target] || element[contains](e[target])) && self.close(); + }, + transitionEndHandler = function(){ + bootstrapCustomEvent.call(alert, closedEvent, component); + off(element, clickEvent, clickHandler); // detach it's listener + alert[parentNode].removeChild(alert); + }; + + // public method + this.close = function() { + if ( alert && element && hasClass(alert,showClass) ) { + bootstrapCustomEvent.call(alert, closeEvent, component); + removeClass(alert,showClass); + alert && triggerHandler(); + } + }; + + // init + if ( !(stringAlert in element ) ) { // prevent adding event handlers twice + on(element, clickEvent, clickHandler); + } + element[stringAlert] = self; + }; + + // ALERT DATA API + // ============== + supports[push]([stringAlert, Alert, '['+dataDismiss+'="alert"]']); + + + /* Native Javascript for Bootstrap 4 | Button + ---------------------------------------------*/ + + // BUTTON DEFINITION + // =================== + var Button = function( element ) { + + // initialization element + element = queryElement(element); + + // constant + var toggled = false, // toggled makes sure to prevent triggering twice the change.bs.button events + + // strings + component = 'button', + checked = 'checked', + reset = 'reset', + LABEL = 'LABEL', + INPUT = 'INPUT', + + // private methods + keyHandler = function(e){ + var key = e.which || e.keyCode; + key === 32 && e[target] === DOC.activeElement && toggle(e); + }, + preventScroll = function(e){ + var key = e.which || e.keyCode; + key === 32 && e[preventDefault](); + }, + toggle = function(e) { + var label = e[target].tagName === LABEL ? e[target] : e[target][parentNode].tagName === LABEL ? e[target][parentNode] : null; // the .btn label + + if ( !label ) return; //react if a label or its immediate child is clicked + + var eventTarget = e[target], // the button itself, the target of the handler function + labels = getElementsByClassName(eventTarget[parentNode],'btn'), // all the button group buttons + input = label[getElementsByTagName](INPUT)[0]; + + if ( !input ) return; //return if no input found + + // manage the dom manipulation + if ( input.type === 'checkbox' ) { //checkboxes + if ( !input[checked] ) { + addClass(label,active); + input[getAttribute](checked); + input[setAttribute](checked,checked); + input[checked] = true; + } else { + removeClass(label,active); + input[getAttribute](checked); + input.removeAttribute(checked); + input[checked] = false; + } + + if (!toggled) { // prevent triggering the event twice + toggled = true; + bootstrapCustomEvent.call(input, changeEvent, component); //trigger the change for the input + bootstrapCustomEvent.call(element, changeEvent, component); //trigger the change for the btn-group + } + } + + if ( input.type === 'radio' && !toggled ) { // radio buttons + if ( !input[checked] ) { // don't trigger if already active + addClass(label,active); + input[setAttribute](checked,checked); + input[checked] = true; + bootstrapCustomEvent.call(input, changeEvent, component); //trigger the change for the input + bootstrapCustomEvent.call(element, changeEvent, component); //trigger the change for the btn-group + + toggled = true; + for (var i = 0, ll = labels[length]; i= 0; // bottom && top + }, + setActivePage = function( pageIndex ) { //indicators + for ( var i = 0, icl = indicators[length]; i < icl; i++ ) { + removeClass(indicators[i],active); + } + if (indicators[pageIndex]) addClass(indicators[pageIndex], active); + }; + + + // public methods + this.cycle = function() { + timer = setInterval(function() { + isElementInScrollRange() && (index++, self.slideTo( index ) ); + }, this[interval]); + }; + this.slideTo = function( next ) { + if (isSliding) return; // when controled via methods, make sure to check again + + var activeItem = this.getActiveIndex(), // the current active + orientation; + + // determine slideDirection first + if ( (activeItem < next ) || (activeItem === 0 && next === total -1 ) ) { + slideDirection = self[direction] = left; // next + } else if ( (activeItem > next) || (activeItem === total - 1 && next === 0 ) ) { + slideDirection = self[direction] = right; // prev + } + + // find the right next index + if ( next < 0 ) { next = total - 1; } + else if ( next === total ){ next = 0; } + + // update index + index = next; + + orientation = slideDirection === left ? 'next' : 'prev'; //determine type + bootstrapCustomEvent.call(element, slideEvent, component, slides[next]); // here we go with the slide + + isSliding = true; + clearInterval(timer); + setActivePage( next ); + + if ( supportTransitions && hasClass(element,'slide') ) { + + addClass(slides[next],carouselItem +'-'+ orientation); + slides[next][offsetWidth]; + addClass(slides[next],carouselItem +'-'+ slideDirection); + addClass(slides[activeItem],carouselItem +'-'+ slideDirection); + + one(slides[activeItem], transitionEndEvent, function(e) { + var timeout = e[target] !== slides[activeItem] ? e.elapsedTime*1000 : 0; + + setTimeout(function(){ + isSliding = false; + + addClass(slides[next],active); + removeClass(slides[activeItem],active); + + removeClass(slides[next],carouselItem +'-'+ orientation); + removeClass(slides[next],carouselItem +'-'+ slideDirection); + removeClass(slides[activeItem],carouselItem +'-'+ slideDirection); + + bootstrapCustomEvent.call(element, slidEvent, component, slides[next]); + + if ( !DOC.hidden && self[interval] && !hasClass(element,paused) ) { + self.cycle(); + } + },timeout+100); + }); + + } else { + addClass(slides[next],active); + slides[next][offsetWidth]; + removeClass(slides[activeItem],active); + setTimeout(function() { + isSliding = false; + if ( self[interval] && !hasClass(element,paused) ) { + self.cycle(); + } + bootstrapCustomEvent.call(element, slidEvent, component, slides[next]); + }, 100 ); + } + }; + this.getActiveIndex = function () { + return slides[indexOf](getElementsByClassName(element,carouselItem+' active')[0]) || 0; + }; + + // init + if ( !(stringCarousel in element ) ) { // prevent adding event handlers twice + + if ( self[pause] && self[interval] ) { + on( element, mouseHover[0], pauseHandler ); + on( element, mouseHover[1], resumeHandler ); + on( element, 'touchstart', pauseHandler ); + on( element, 'touchend', resumeHandler ); + } + + rightArrow && on( rightArrow, clickEvent, controlsHandler ); + leftArrow && on( leftArrow, clickEvent, controlsHandler ); + + indicator && on( indicator, clickEvent, indicatorHandler ); + self[keyboard] === true && on( globalObject, keydownEvent, keyHandler ); + } + if (self.getActiveIndex()<0) { + slides[length] && addClass(slides[0],active); + indicators[length] && setActivePage(0); + } + + if ( self[interval] ){ self.cycle(); } + element[stringCarousel] = self; + }; + + // CAROUSEL DATA API + // ================= + supports[push]( [ stringCarousel, Carousel, '['+dataRide+'="carousel"]' ] ); + + + /* Native Javascript for Bootstrap 4 | Collapse + -----------------------------------------------*/ + + // COLLAPSE DEFINITION + // =================== + var Collapse = function( element, options ) { + + // initialization element + element = queryElement(element); + + // set options + options = options || {}; + + // event targets and constants + var accordion = null, collapse = null, self = this, + isAnimating = false, // when true it will prevent click handlers + accordionData = element[getAttribute]('data-parent'), + + // component strings + component = 'collapse', + collapsed = 'collapsed', + + // private methods + openAction = function(collapseElement,toggle) { + bootstrapCustomEvent.call(collapseElement, showEvent, component); + isAnimating = true; + addClass(collapseElement,collapsing); + removeClass(collapseElement,component); + collapseElement[style][height] = collapseElement[scrollHeight] + 'px'; + + emulateTransitionEnd(collapseElement, function() { + isAnimating = false; + collapseElement[setAttribute](ariaExpanded,'true'); + toggle[setAttribute](ariaExpanded,'true'); + removeClass(collapseElement,collapsing); + addClass(collapseElement, component); + addClass(collapseElement,showClass); + collapseElement[style][height] = ''; + bootstrapCustomEvent.call(collapseElement, shownEvent, component); + }); + }, + closeAction = function(collapseElement,toggle) { + bootstrapCustomEvent.call(collapseElement, hideEvent, component); + isAnimating = true; + collapseElement[style][height] = collapseElement[scrollHeight] + 'px'; // set height first + removeClass(collapseElement,component); + removeClass(collapseElement,showClass); + addClass(collapseElement,collapsing); + collapseElement[offsetWidth]; // force reflow to enable transition + collapseElement[style][height] = '0px'; + + emulateTransitionEnd(collapseElement, function() { + isAnimating = false; + collapseElement[setAttribute](ariaExpanded,'false'); + toggle[setAttribute](ariaExpanded,'false'); + removeClass(collapseElement,collapsing); + addClass(collapseElement,component); + collapseElement[style][height] = ''; + bootstrapCustomEvent.call(collapseElement, hiddenEvent, component); + }); + }, + getTarget = function() { + var href = element.href && element[getAttribute]('href'), + parent = element[getAttribute](dataTarget), + id = href || ( parent && parent.charAt(0) === '#' ) && parent; + return id && queryElement(id); + }; + + // public methods + this.toggle = function(e) { + e[preventDefault](); + if (isAnimating) return; + if (!hasClass(collapse,showClass)) { self.show(); } + else { self.hide(); } + }; + this.hide = function() { + closeAction(collapse,element); + addClass(element,collapsed); + }; + this.show = function() { + if ( accordion ) { + var activeCollapse = queryElement('.'+component+'.'+showClass,accordion), + toggle = activeCollapse && (queryElement('['+dataToggle+'="'+component+'"]['+dataTarget+'="#'+activeCollapse.id+'"]',accordion) + || queryElement('['+dataToggle+'="'+component+'"][href="#'+activeCollapse.id+'"]',accordion) ), + correspondingCollapse = toggle && (toggle[getAttribute](dataTarget) || toggle.href); + if ( activeCollapse && toggle && activeCollapse !== collapse ) { + closeAction(activeCollapse,toggle); + if ( correspondingCollapse.split('#')[1] !== collapse.id ) { addClass(toggle,collapsed); } + else { removeClass(toggle,collapsed); } + } + } + + openAction(collapse,element); + removeClass(element,collapsed); + }; + + // init + if ( !(stringCollapse in element ) ) { // prevent adding event handlers twice + on(element, clickEvent, self.toggle); + } + collapse = getTarget(); + accordion = queryElement(options.parent) || accordionData && getClosest(element, accordionData); + element[stringCollapse] = self; + }; + + // COLLAPSE DATA API + // ================= + supports[push]( [ stringCollapse, Collapse, '['+dataToggle+'="collapse"]' ] ); + + + /* Native Javascript for Bootstrap 4 | Dropdown + ----------------------------------------------*/ + + // DROPDOWN DEFINITION + // =================== + var Dropdown = function( element, option ) { + + // initialization element + element = queryElement(element); + + // set option + this.persist = option === true || element[getAttribute]('data-persist') === 'true' || false; + + // constants, event targets, strings + var self = this, children = 'children', + parent = element[parentNode], + component = 'dropdown', open = 'open', + relatedTarget = null, + menu = queryElement('.dropdown-menu', parent), + menuItems = (function(){ + var set = menu[children], newSet = []; + for ( var i=0; i1?idx-1:0) + : key === 40 ? (idx HTML[clientHeight]; + scrollbarWidth = measureScrollbar(); + }, + adjustDialog = function () { + modal[style][paddingLeft] = !bodyIsOverflowing && modalIsOverflowing ? scrollbarWidth + 'px' : ''; + modal[style][paddingRight] = bodyIsOverflowing && !modalIsOverflowing ? scrollbarWidth + 'px' : ''; + }, + resetAdjustments = function () { + modal[style][paddingLeft] = ''; + modal[style][paddingRight] = ''; + }, + createOverlay = function() { + modalOverlay = 1; + + var newOverlay = DOC[createElement]('div'); + overlay = queryElement('.'+modalBackdropString); + + if ( overlay === null ) { + newOverlay[setAttribute]('class',modalBackdropString+' fade'); + overlay = newOverlay; + DOC[body][appendChild](overlay); + } + }, + removeOverlay = function() { + overlay = queryElement('.'+modalBackdropString); + if ( overlay && overlay !== null && typeof overlay === 'object' ) { + modalOverlay = 0; + DOC[body].removeChild(overlay); overlay = null; + } + bootstrapCustomEvent.call(modal, hiddenEvent, component); + }, + keydownHandlerToggle = function() { + if (hasClass(modal,showClass)) { + on(DOC, keydownEvent, keyHandler); + } else { + off(DOC, keydownEvent, keyHandler); + } + }, + resizeHandlerToggle = function() { + if (hasClass(modal,showClass)) { + on(globalObject, resizeEvent, self.update); + } else { + off(globalObject, resizeEvent, self.update); + } + }, + dismissHandlerToggle = function() { + if (hasClass(modal,showClass)) { + on(modal, clickEvent, dismissHandler); + } else { + off(modal, clickEvent, dismissHandler); + } + }, + // triggers + triggerShow = function() { + setFocus(modal); + bootstrapCustomEvent.call(modal, shownEvent, component, relatedTarget); + }, + triggerHide = function() { + modal[style].display = ''; + element && (setFocus(element)); + + (function(){ + if (!getElementsByClassName(DOC,component+' '+showClass)[0]) { + resetAdjustments(); + resetScrollbar(); + removeClass(DOC[body],component+'-open'); + overlay && hasClass(overlay,'fade') ? (removeClass(overlay,showClass), emulateTransitionEnd(overlay,removeOverlay)) + : removeOverlay(); + + resizeHandlerToggle(); + dismissHandlerToggle(); + keydownHandlerToggle(); + } + }()); + }, + // handlers + clickHandler = function(e) { + var clickTarget = e[target]; + clickTarget = clickTarget[hasAttribute](dataTarget) || clickTarget[hasAttribute]('href') ? clickTarget : clickTarget[parentNode]; + if ( clickTarget === element && !hasClass(modal,showClass) ) { + modal.modalTrigger = element; + relatedTarget = element; + self.show(); + e[preventDefault](); + } + }, + keyHandler = function(e) { + if (self[keyboard] && e.which == 27 && hasClass(modal,showClass)) { + self.hide(); + } + }, + dismissHandler = function(e) { + var clickTarget = e[target]; + if ( hasClass(modal,showClass) && (clickTarget[parentNode][getAttribute](dataDismiss) === component + || clickTarget[getAttribute](dataDismiss) === component + || (clickTarget === modal && self[backdrop] !== staticString) ) ) { + self.hide(); relatedTarget = null; + e[preventDefault](); + } + }; + + // public methods + this.toggle = function() { + if ( hasClass(modal,showClass) ) {this.hide();} else {this.show();} + }; + this.show = function() { + bootstrapCustomEvent.call(modal, showEvent, component, relatedTarget); + + // we elegantly hide any opened modal + var currentOpen = getElementsByClassName(DOC,component+' '+showClass)[0]; + currentOpen && currentOpen !== modal && currentOpen.modalTrigger[stringModal].hide(); + + if ( this[backdrop] ) { + !modalOverlay && createOverlay(); + } + + if ( overlay && modalOverlay && !hasClass(overlay,showClass)) { + overlay[offsetWidth]; // force reflow to enable trasition + addClass(overlay, showClass); + } + + setTimeout( function() { + modal[style].display = 'block'; + + checkScrollbar(); + setScrollbar(); + adjustDialog(); + + addClass(DOC[body],component+'-open'); + addClass(modal,showClass); + modal[setAttribute](ariaHidden, false); + + resizeHandlerToggle(); + dismissHandlerToggle(); + keydownHandlerToggle(); + + hasClass(modal,'fade') ? emulateTransitionEnd(modal, triggerShow) : triggerShow(); + }, supportTransitions ? 150 : 0); + }; + this.hide = function() { + bootstrapCustomEvent.call(modal, hideEvent, component); + overlay = queryElement('.'+modalBackdropString); + + removeClass(modal,showClass); + modal[setAttribute](ariaHidden, true); + + (function(){ + hasClass(modal,'fade') ? emulateTransitionEnd(modal, triggerHide) : triggerHide(); + }()); + }; + this.setContent = function( content ) { + queryElement('.'+component+'-content',modal)[innerHTML] = content; + }; + this.update = function() { + if (hasClass(modal,showClass)) { + checkScrollbar(); + setScrollbar(); + adjustDialog(); + } + }; + + // init + // prevent adding event handlers over and over + // modal is independent of a triggering element + if ( !!element && !(stringModal in element) ) { + on(element, clickEvent, clickHandler); + } + if ( !!self[content] ) { self.setContent( self[content] ); } + !!element && (element[stringModal] = self); + }; + + // DATA API + supports[push]( [ stringModal, Modal, '['+dataToggle+'="modal"]' ] ); + + /* Native Javascript for Bootstrap 4 | Popover + ----------------------------------------------*/ + + // POPOVER DEFINITION + // ================== + var Popover = function( element, options ) { + + // initialization element + element = queryElement(element); + + // set options + options = options || {}; + + // DATA API + var triggerData = element[getAttribute](dataTrigger), // click / hover / focus + animationData = element[getAttribute](dataAnimation), // true / false + placementData = element[getAttribute](dataPlacement), + dismissibleData = element[getAttribute](dataDismissible), + delayData = element[getAttribute](dataDelay), + containerData = element[getAttribute](dataContainer), + + // internal strings + component = 'popover', + template = 'template', + trigger = 'trigger', + classString = 'class', + div = 'div', + fade = 'fade', + content = 'content', + dataContent = 'data-content', + dismissible = 'dismissible', + closeBtn = '', + + // check container + containerElement = queryElement(options[container]), + containerDataElement = queryElement(containerData), + + // maybe the element is inside a modal + modal = getClosest(element,'.modal'), + + // maybe the element is inside a fixed navbar + navbarFixedTop = getClosest(element,'.'+fixedTop), + navbarFixedBottom = getClosest(element,'.'+fixedBottom); + + // set instance options + this[template] = options[template] ? options[template] : null; // JavaScript only + this[trigger] = options[trigger] ? options[trigger] : triggerData || hoverEvent; + this[animation] = options[animation] && options[animation] !== fade ? options[animation] : animationData || fade; + this[placement] = options[placement] ? options[placement] : placementData || top; + this[delay] = parseInt(options[delay] || delayData) || 200; + this[dismissible] = options[dismissible] || dismissibleData === 'true' ? true : false; + this[container] = containerElement ? containerElement + : containerDataElement ? containerDataElement + : navbarFixedTop ? navbarFixedTop + : navbarFixedBottom ? navbarFixedBottom + : modal ? modal : DOC[body]; + + // bind, content + var self = this, + titleString = element[getAttribute](dataTitle) || null, + contentString = element[getAttribute](dataContent) || null; + + if ( !contentString && !this[template] ) return; // invalidate + + // constants, vars + var popover = null, timer = 0, placementSetting = this[placement], + + // handlers + dismissibleHandler = function(e) { + if (popover !== null && e[target] === queryElement('.close',popover)) { + self.hide(); + } + }, + + // private methods + removePopover = function() { + self[container].removeChild(popover); + timer = null; popover = null; + }, + createPopover = function() { + titleString = element[getAttribute](dataTitle); // check content again + contentString = element[getAttribute](dataContent); + + popover = DOC[createElement](div); + + // popover arrow + var popoverArrow = DOC[createElement](div); + popoverArrow[setAttribute](classString,'arrow'); + popover[appendChild](popoverArrow); + + if ( contentString !== null && self[template] === null ) { //create the popover from data attributes + + popover[setAttribute]('role','tooltip'); + + if (titleString !== null) { + var popoverTitle = DOC[createElement]('h3'); + popoverTitle[setAttribute](classString,component+'-header'); + + popoverTitle[innerHTML] = self[dismissible] ? titleString + closeBtn : titleString; + popover[appendChild](popoverTitle); + } + + //set popover content + var popoverContent = DOC[createElement](div); + popoverContent[setAttribute](classString,component+'-body'); + popoverContent[innerHTML] = self[dismissible] && titleString === null ? contentString + closeBtn : contentString; + popover[appendChild](popoverContent); + + } else { // or create the popover from template + var popoverTemplate = DOC[createElement](div); + popoverTemplate[innerHTML] = self[template]; + popover[innerHTML] = popoverTemplate.firstChild[innerHTML]; + } + + //append to the container + self[container][appendChild](popover); + popover[style].display = 'block'; + popover[setAttribute](classString, component+ ' bs-' + component+'-'+placementSetting + ' ' + self[animation]); + }, + showPopover = function () { + !hasClass(popover,showClass) && ( addClass(popover,showClass) ); + }, + updatePopover = function() { + styleTip(element,popover,placementSetting,self[container]); + }, + + // event toggle + dismissHandlerToggle = function(type){ + if (clickEvent == self[trigger] || 'focus' == self[trigger]) { + !self[dismissible] && type( element, 'blur', self.hide ); + } + self[dismissible] && type( DOC, clickEvent, dismissibleHandler ); + type( globalObject, resizeEvent, self.hide ); + }, + + // triggers + showTrigger = function() { + dismissHandlerToggle(on); + bootstrapCustomEvent.call(element, shownEvent, component); + }, + hideTrigger = function() { + dismissHandlerToggle(off); + removePopover(); + bootstrapCustomEvent.call(element, hiddenEvent, component); + }; + + // public methods / handlers + this.toggle = function() { + if (popover === null) { self.show(); } + else { self.hide(); } + }; + this.show = function() { + clearTimeout(timer); + timer = setTimeout( function() { + if (popover === null) { + placementSetting = self[placement]; // we reset placement in all cases + createPopover(); + updatePopover(); + showPopover(); + bootstrapCustomEvent.call(element, showEvent, component); + !!self[animation] ? emulateTransitionEnd(popover, showTrigger) : showTrigger(); + } + }, 20 ); + }; + this.hide = function() { + clearTimeout(timer); + timer = setTimeout( function() { + if (popover && popover !== null && hasClass(popover,showClass)) { + bootstrapCustomEvent.call(element, hideEvent, component); + removeClass(popover,showClass); + !!self[animation] ? emulateTransitionEnd(popover, hideTrigger) : hideTrigger(); + } + }, self[delay] ); + }; + + // init + if ( !(stringPopover in element) ) { // prevent adding event handlers twice + if (self[trigger] === hoverEvent) { + on( element, mouseHover[0], self.show ); + if (!self[dismissible]) { on( element, mouseHover[1], self.hide ); } + } else if (clickEvent == self[trigger] || 'focus' == self[trigger]) { + on( element, self[trigger], self.toggle ); + } + } + element[stringPopover] = self; + }; + + // POPOVER DATA API + // ================ + supports[push]( [ stringPopover, Popover, '['+dataToggle+'="popover"]' ] ); + + + /* Native Javascript for Bootstrap 4 | ScrollSpy + -----------------------------------------------*/ + + // SCROLLSPY DEFINITION + // ==================== + var ScrollSpy = function(element, options) { + + // initialization element, the element we spy on + element = queryElement(element); + + // DATA API + var targetData = queryElement(element[getAttribute](dataTarget)), + offsetData = element[getAttribute]('data-offset'); + + // set options + options = options || {}; + if ( !options[target] && !targetData ) { return; } // invalidate + + // event targets, constants + var self = this, spyTarget = options[target] && queryElement(options[target]) || targetData, + links = spyTarget && spyTarget[getElementsByTagName]('A'), + offset = parseInt(offsetData || options['offset']) || 10, + items = [], targetItems = [], scrollOffset, + scrollTarget = element[offsetHeight] < element[scrollHeight] ? element : globalObject, // determine which is the real scrollTarget + isWindow = scrollTarget === globalObject; + + // populate items and targets + for (var i=0, il=links[length]; i= topEdge && bottomEdge > scrollOffset; + + if ( !isActive && inside ) { + if ( !hasClass(item,active) ) { + addClass(item,active); + if (dropdownLink && !hasClass(dropdownLink,active) ) { + addClass(dropdownLink,active); + } + bootstrapCustomEvent.call(element, 'activate', 'scrollspy', items[index]); + } + } else if ( !inside ) { + if ( hasClass(item,active) ) { + removeClass(item,active); + if (dropdownLink && hasClass(dropdownLink,active) && !getElementsByClassName(item[parentNode],active).length ) { + removeClass(dropdownLink,active); + } + } + } else if ( !inside && !isActive || isActive && inside ) { + return; + } + }, + updateItems = function(){ + scrollOffset = isWindow ? getScroll().y : element[scrollTop]; + for (var index=0, itl=items[length]; index 1 ) { + activeTab = activeTabs[activeTabs[length]-1]; + } + return activeTab; + }, + getActiveContent = function() { + return queryElement(getActiveTab()[getAttribute]('href')); + }, + // handler + clickHandler = function(e) { + var href = e[target][getAttribute]('href'); + e[preventDefault](); + next = e[target][getAttribute](dataToggle) === component || (href && href.charAt(0) === '#') + ? e[target] : e[target][parentNode]; // allow for child elements like icons to use the handler + !tabs[isAnimating] && !hasClass(next,active) && self.show(); + }; + + // public method + this.show = function() { // the tab we clicked is now the next tab + next = next || element; + nextContent = queryElement(next[getAttribute]('href')); //this is the actual object, the next tab content to activate + activeTab = getActiveTab(); + activeContent = getActiveContent(); + + tabs[isAnimating] = true; + removeClass(activeTab,active); + addClass(next,active); + + if ( dropdown ) { + if ( !hasClass(element[parentNode],'dropdown-menu') ) { + if (hasClass(dropdown,active)) removeClass(dropdown,active); + } else { + if (!hasClass(dropdown,active)) addClass(dropdown,active); + } + } + + bootstrapCustomEvent.call(activeTab, hideEvent, component, next); + + if (hasClass(activeContent, 'fade')) { + removeClass(activeContent,showClass); + emulateTransitionEnd(activeContent, triggerHide); + } else { triggerHide(); } + }; + + // init + if ( !(stringTab in element) ) { // prevent adding event handlers twice + on(element, clickEvent, clickHandler); + } + if (self[height]) { tabsContentContainer = getActiveContent()[parentNode]; } + element[stringTab] = self; + }; + + // TAB DATA API + // ============ + supports[push]( [ stringTab, Tab, '['+dataToggle+'="tab"]' ] ); + + + /* Native Javascript for Bootstrap 4 | Tooltip + ---------------------------------------------*/ + + // TOOLTIP DEFINITION + // ================== + var Tooltip = function( element,options ) { + + // initialization element + element = queryElement(element); + + // set options + options = options || {}; + + // DATA API + var animationData = element[getAttribute](dataAnimation), + placementData = element[getAttribute](dataPlacement), + delayData = element[getAttribute](dataDelay), + containerData = element[getAttribute](dataContainer), + + // strings + component = 'tooltip', + classString = 'class', + title = 'title', + fade = 'fade', + div = 'div', + + // check container + containerElement = queryElement(options[container]), + containerDataElement = queryElement(containerData), + + // maybe the element is inside a modal + modal = getClosest(element,'.modal'), + + // maybe the element is inside a fixed navbar + navbarFixedTop = getClosest(element,'.'+fixedTop), + navbarFixedBottom = getClosest(element,'.'+fixedBottom); + + // set instance options + this[animation] = options[animation] && options[animation] !== fade ? options[animation] : animationData || fade; + this[placement] = options[placement] ? options[placement] : placementData || top; + this[delay] = parseInt(options[delay] || delayData) || 200; + this[container] = containerElement ? containerElement + : containerDataElement ? containerDataElement + : navbarFixedTop ? navbarFixedTop + : navbarFixedBottom ? navbarFixedBottom + : modal ? modal : DOC[body]; + + // bind, event targets, title and constants + var self = this, timer = 0, placementSetting = this[placement], tooltip = null, + titleString = element[getAttribute](title) || element[getAttribute](dataTitle) || element[getAttribute](dataOriginalTitle); + + if ( !titleString || titleString == "" ) return; // invalidate + + // private methods + var removeToolTip = function() { + self[container].removeChild(tooltip); + tooltip = null; timer = null; + }, + createToolTip = function() { + titleString = element[getAttribute](title) || element[getAttribute](dataTitle) || element[getAttribute](dataOriginalTitle); // read the title again + if ( !titleString || titleString == "" ) return false; // invalidate + tooltip = DOC[createElement](div); + tooltip[setAttribute]('role',component); + + // tooltip arrow + var tooltipArrow = DOC[createElement](div); + tooltipArrow[setAttribute](classString,'arrow'); + tooltip[appendChild](tooltipArrow); + + var tooltipInner = DOC[createElement](div); + tooltipInner[setAttribute](classString,component+'-inner'); + tooltip[appendChild](tooltipInner); + tooltipInner[innerHTML] = titleString; + + self[container][appendChild](tooltip); + tooltip[setAttribute](classString, component + ' bs-' + component+'-'+placementSetting + ' ' + self[animation]); + }, + updateTooltip = function () { + styleTip(element,tooltip,placementSetting,self[container]); + }, + showTooltip = function () { + !hasClass(tooltip,showClass) && ( addClass(tooltip,showClass) ); + }, + // triggers + showTrigger = function() { + on( globalObject, resizeEvent, self.hide ); + bootstrapCustomEvent.call(element, shownEvent, component); + }, + hideTrigger = function() { + off( globalObject, resizeEvent, self.hide ); + removeToolTip(); + bootstrapCustomEvent.call(element, hiddenEvent, component); + }; + + // public methods + this.show = function() { + clearTimeout(timer); + timer = setTimeout( function() { + if (tooltip === null) { + placementSetting = self[placement]; // we reset placement in all cases + if(createToolTip() == false) return; + updateTooltip(); + showTooltip(); + bootstrapCustomEvent.call(element, showEvent, component); + !!self[animation] ? emulateTransitionEnd(tooltip, showTrigger) : showTrigger(); + } + }, 20 ); + }; + this.hide = function() { + clearTimeout(timer); + timer = setTimeout( function() { + if (tooltip && hasClass(tooltip,showClass)) { + bootstrapCustomEvent.call(element, hideEvent, component); + removeClass(tooltip,showClass); + !!self[animation] ? emulateTransitionEnd(tooltip, hideTrigger) : hideTrigger(); + } + }, self[delay]); + }; + this.toggle = function() { + if (!tooltip) { self.show(); } + else { self.hide(); } + }; + + // init + if ( !(stringTooltip in element) ) { // prevent adding event handlers twice + element[setAttribute](dataOriginalTitle,titleString); + element.removeAttribute(title); + on(element, mouseHover[0], self.show); + on(element, mouseHover[1], self.hide); + } + element[stringTooltip] = self; + }; + + // TOOLTIP DATA API + // ================= + supports[push]( [ stringTooltip, Tooltip, '['+dataToggle+'="tooltip"]' ] ); + + + + /* Native Javascript for Bootstrap 4 | Initialize Data API + --------------------------------------------------------*/ + var initializeDataAPI = function( constructor, collection ){ + for (var i=0, l=collection[length]; i:-)':'1f606', + '\':-(':'1f613', + '>:-(':'1f620', + ':\'-(':'1f622', + 'O:-)':'1f607', + '0:-3':'1f607', + '0:-)':'1f607', + '0;^)':'1f607', + 'O;-)':'1f607', + '0;-)':'1f607', + 'O:-3':'1f607', + '-__-':'1f611', + ':-Þ':'1f61b', + ':)':'1f606', + '>;)':'1f606', + '>=)':'1f606', + ';-)':'1f609', + '*-)':'1f609', + ';-]':'1f609', + ';^)':'1f609', + '\':(':'1f613', + '\'=(':'1f613', + ':-*':'1f618', + ':^*':'1f618', + '>:P':'1f61c', + 'X-P':'1f61c', + '>:[':'1f61e', + ':-(':'1f61e', + ':-[':'1f61e', + '>:(':'1f620', + ':\'(':'1f622', + ';-(':'1f622', + '>.<':'1f623', + '#-)':'1f635', + '%-)':'1f635', + 'X-)':'1f635', + '\\0/':'1f646', + '\\O/':'1f646', + '0:3':'1f607', + '0:)':'1f607', + 'O:)':'1f607', + 'O=)':'1f607', + 'O:3':'1f607', + 'B-)':'1f60e', + '8-)':'1f60e', + 'B-D':'1f60e', + '8-D':'1f60e', + '-_-':'1f611', + '>:\\':'1f615', + '>:/':'1f615', + ':-/':'1f615', + ':-.':'1f615', + ':-P':'1f61b', + ':Þ':'1f61b', + ':-b':'1f61b', + ':-O':'1f62e', + 'O_O':'1f62e', + '>:O':'1f62e', + ':-X':'1f636', + ':-#':'1f636', + ':-)':'1f642', + '(y)':'1f44d', + '<3':'2764', + ':D':'1f603', + '=D':'1f603', + ';)':'1f609', + '*)':'1f609', + ';]':'1f609', + ';D':'1f609', + ':*':'1f618', + '=*':'1f618', + ':(':'1f61e', + ':[':'1f61e', + '=(':'1f61e', + ':@':'1f620', + ';(':'1f622', + 'D:':'1f628', + ':$':'1f633', + '=$':'1f633', + '#)':'1f635', + '%)':'1f635', + 'X)':'1f635', + 'B)':'1f60e', + '8)':'1f60e', + ':/':'1f615', + ':\\':'1f615', + '=/':'1f615', + '=\\':'1f615', + ':L':'1f615', + '=L':'1f615', + ':P':'1f61b', + '=P':'1f61b', + ':b':'1f61b', + ':O':'1f62e', + ':X':'1f636', + ':#':'1f636', + '=X':'1f636', + '=#':'1f636', + ':)':'1f642', + '=]':'1f642', + '=)':'1f642', + ':]':'1f642' + }; + + ns.asciiRegexp = '(\\*\\\\0\\/\\*|\\*\\\\O\\/\\*|\\-___\\-|\\:\'\\-\\)|\'\\:\\-\\)|\'\\:\\-D|\\>\\:\\-\\)|>\\:\\-\\)|\'\\:\\-\\(|\\>\\:\\-\\(|>\\:\\-\\(|\\:\'\\-\\(|O\\:\\-\\)|0\\:\\-3|0\\:\\-\\)|0;\\^\\)|O;\\-\\)|0;\\-\\)|O\\:\\-3|\\-__\\-|\\:\\-Þ|\\:\\-Þ|\\<\\/3|<\\/3|\\:\'\\)|\\:\\-D|\'\\:\\)|\'\\=\\)|\'\\:D|\'\\=D|\\>\\:\\)|>\\:\\)|\\>;\\)|>;\\)|\\>\\=\\)|>\\=\\)|;\\-\\)|\\*\\-\\)|;\\-\\]|;\\^\\)|\'\\:\\(|\'\\=\\(|\\:\\-\\*|\\:\\^\\*|\\>\\:P|>\\:P|X\\-P|\\>\\:\\[|>\\:\\[|\\:\\-\\(|\\:\\-\\[|\\>\\:\\(|>\\:\\(|\\:\'\\(|;\\-\\(|\\>\\.\\<|>\\.<|#\\-\\)|%\\-\\)|X\\-\\)|\\\\0\\/|\\\\O\\/|0\\:3|0\\:\\)|O\\:\\)|O\\=\\)|O\\:3|B\\-\\)|8\\-\\)|B\\-D|8\\-D|\\-_\\-|\\>\\:\\\\|>\\:\\\\|\\>\\:\\/|>\\:\\/|\\:\\-\\/|\\:\\-\\.|\\:\\-P|\\:Þ|\\:Þ|\\:\\-b|\\:\\-O|O_O|\\>\\:O|>\\:O|\\:\\-X|\\:\\-#|\\:\\-\\)|\\(y\\)|\\<3|<3|\\:D|\\=D|;\\)|\\*\\)|;\\]|;D|\\:\\*|\\=\\*|\\:\\(|\\:\\[|\\=\\(|\\:@|;\\(|D\\:|\\:\\$|\\=\\$|#\\)|%\\)|X\\)|B\\)|8\\)|\\:\\/|\\:\\\\|\\=\\/|\\=\\\\|\\:L|\\=L|\\:P|\\=P|\\:b|\\:O|\\:X|\\:#|\\=X|\\=#|\\:\\)|\\=\\]|\\=\\)|\\:\\])'; + + ns.emojiVersion = '3.1'; // you can [optionally] modify this to load alternate emoji versions. see readme for backwards compatibility and version options + ns.emojiSize = '32'; + ns.greedyMatch = false; // set to true for greedy unicode matching + ns.imagePathPNG = 'https://cdn.jsdelivr.net/emojione/assets/' + ns.emojiVersion + '/png/'; + ns.defaultPathPNG = ns.imagePathPNG; + ns.imageTitleTag = true; // set to false to remove title attribute from img tag + ns.sprites = false; // if this is true then sprite markup will be used + ns.spriteSize = '32'; + ns.unicodeAlt = true; // use the unicode char as the alt attribute (makes copy and pasting the resulting text better) + ns.ascii = false; // change to true to convert ascii smileys + ns.riskyMatchAscii = false; // set true to match ascii without leading/trailing space char + + ns.regShortNames = new RegExp("]*>.*?<\/object>|]*>.*?<\/span>|<(?:object|embed|svg|img|div|span|p|a)[^>]*>|("+ns.shortnames+")", "gi"); + ns.regAscii = new RegExp("]*>.*?<\/object>|]*>.*?<\/span>|<(?:object|embed|svg|img|div|span|p|a)[^>]*>|((\\s|^)"+ns.asciiRegexp+"(?=\\s|$|[!,.?]))", "gi"); + ns.regAsciiRisky = new RegExp("]*>.*?<\/object>|]*>.*?<\/span>|<(?:object|embed|svg|img|div|span|p|a)[^>]*>|(()"+ns.asciiRegexp+"())", "gi"); + + ns.regUnicode = new RegExp("]*>.*?<\/object>|]*>.*?<\/span>|<(?:object|embed|svg|img|div|span|p|a)[^>]*>|(?:\uD83C\uDFF3)\uFE0F?\u200D?(?:\uD83C\uDF08)|(?:\uD83D\uDC41)\uFE0F?\u200D?(?:\uD83D\uDDE8)\uFE0F?|[#-9]\uFE0F?\u20E3|(?:(?:\uD83C\uDFF4)(?:\uDB40[\uDC60-\uDCFF]){1,6})|(?:\uD83C[\uDDE0-\uDDFF]){2}|(?:(?:\uD83D[\uDC68\uDC69]))\uFE0F?(?:\uD83C[\uDFFA-\uDFFF])?\u200D?(?:[\u2695\u2696\u2708]|\uD83C[\uDF3E-\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92])|(?:\uD83D[\uDC68\uDC69]|\uD83E[\uDDD0-\uDDDF])(?:\uD83C[\uDFFA-\uDFFF])?\u200D?[\u2640\u2642\u2695\u2696\u2708]?\uFE0F?|(?:(?:\u2764|\uD83D[\uDC66-\uDC69\uDC8B])[\u200D\uFE0F]{0,2}){1,3}(?:\u2764|\uD83D[\uDC66-\uDC69\uDC8B])|(?:(?:\u2764|\uD83D[\uDC66-\uDC69\uDC8B])\uFE0F?){2,4}|(?:\uD83D[\uDC68\uDC69\uDC6E\uDC71-\uDC87\uDD75\uDE45-\uDE4E]|\uD83E[\uDD26\uDD37]|\uD83C[\uDFC3-\uDFCC]|\uD83E[\uDD38-\uDD3E]|\uD83D[\uDEA3-\uDEB6]|\u26f9|\uD83D\uDC6F)\uFE0F?(?:\uD83C[\uDFFB-\uDFFF])?\u200D?[\u2640\u2642]?\uFE0F?|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85-\uDFCC]|\uD83D[\uDC42-\uDCAA\uDD74-\uDD96\uDE45-\uDE4F\uDEA3-\uDECC]|\uD83E[\uDD18-\uDD3E])\uFE0F?(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u2194-\u2199\u21a9-\u21aa]\uFE0F?|[\u0023\u002a]|[\u3030\u303d]\uFE0F?|(?:\ud83c[\udd70-\udd71]|\ud83c\udd8e|\ud83c[\udd91-\udd9a])\uFE0F?|\u24c2\uFE0F?|[\u3297\u3299]\uFE0F?|(?:\ud83c[\ude01-\ude02]|\ud83c\ude1a|\ud83c\ude2f|\ud83c[\ude32-\ude3a]|\ud83c[\ude50-\ude51])\uFE0F?|[\u203c\u2049]\uFE0F?|[\u25aa-\u25ab\u25b6\u25c0\u25fb-\u25fe]\uFE0F?|[\u00a9\u00ae]\uFE0F?|[\u2122\u2139]\uFE0F?|\ud83c\udc04\uFE0F?|[\u2b05-\u2b07\u2b1b-\u2b1c\u2b50\u2b55]\uFE0F?|[\u231a-\u231b\u2328\u23cf\u23e9-\u23f3\u23f8-\u23fa]\uFE0F?|\ud83c\udccf|[\u2934\u2935]\uFE0F?)|[\u2700-\u27bf]\uFE0F?|[\ud800-\udbff][\udc00-\udfff]\uFE0F?|[\u2600-\u26FF]\uFE0F?|[\u0030-\u0039]\uFE0F", "g"); + + ns.toImage = function(str) { + str = ns.unicodeToImage(str); + str = ns.shortnameToImage(str); + return str; + }; + + // Uses toShort to transform all unicode into a standard shortname + // then transforms the shortname into unicode + // This is done for standardization when converting several unicode types + ns.unifyUnicode = function(str) { + str = ns.toShort(str); + str = ns.shortnameToUnicode(str); + return str; + }; + + // Replace shortnames (:wink:) with Ascii equivalents ( ;^) ) + // Useful for systems that dont support unicode nor images + ns.shortnameToAscii = function(str) { + var unicode, + // something to keep in mind here is that array flip will destroy + // half of the ascii text "emojis" because the unicode numbers are duplicated + // this is ok for what it's being used for + unicodeToAscii = ns.objectFlip(ns.asciiList); + + str = str.replace(ns.regShortNames, function(shortname) { + if( (typeof shortname === 'undefined') || (shortname === '') || (!(shortname in ns.emojioneList)) ) { + // if the shortname doesnt exist just return the entire match + return shortname; + } + else { + unicode = ns.emojioneList[shortname].uc_output; + if(typeof unicodeToAscii[unicode] !== 'undefined') { + return unicodeToAscii[unicode]; + } else { + return shortname; + } + } + }); + return str; + }; + + // will output unicode from shortname + // useful for sending emojis back to mobile devices + ns.shortnameToUnicode = function(str) { + // replace regular shortnames first + var unicode,fname; + str = str.replace(ns.regShortNames, function(shortname) { + if( (typeof shortname === 'undefined') || (shortname === '') || (!(shortname in ns.emojioneList)) ) { + // if the shortname doesnt exist just return the entire matchhju + return shortname; + } + unicode = ns.emojioneList[shortname].uc_output.toUpperCase(); + fname = ns.emojioneList[shortname].uc_base; + return ns.convert(unicode); + }); + + // if ascii smileys are turned on, then we'll replace them! + if (ns.ascii) { + + var asciiRX = ns.riskyMatchAscii ? ns.regAsciiRisky : ns.regAscii; + + str = str.replace(asciiRX, function(entire, m1, m2, m3) { + if( (typeof m3 === 'undefined') || (m3 === '') || (!(ns.unescapeHTML(m3) in ns.asciiList)) ) { + // if the ascii doesnt exist just return the entire match + return entire; + } + + m3 = ns.unescapeHTML(m3); + unicode = ns.asciiList[m3].toUpperCase(); + return m2+ns.convert(unicode); + }); + } + + return str; + }; + + ns.shortnameToImage = function(str) { + // replace regular shortnames first + var replaceWith,shortname,unicode,fname,alt,category,title,size,ePath; + var mappedUnicode = ns.mapUnicodeToShort(); + str = str.replace(ns.regShortNames, function(shortname) { + if( (typeof shortname === 'undefined') || (shortname === '') || (ns.shortnames.indexOf(shortname) === -1) ) { + // if the shortname doesnt exist just return the entire match + return shortname; + } + else { + // map shortname to parent + if (!ns.emojioneList[shortname]) { + for ( var emoji in ns.emojioneList ) { + if (!ns.emojioneList.hasOwnProperty(emoji) || (emoji === '')) continue; + if (ns.emojioneList[emoji].shortnames.indexOf(shortname) === -1) continue; + shortname = emoji; + break; + } + } + unicode = ns.emojioneList[shortname].uc_output; + fname = ns.emojioneList[shortname].uc_base; + category = (fname.includes("-1f3f")) ? 'diversity' : ns.emojioneList[shortname].category; + title = ns.imageTitleTag ? 'title="' + shortname + '"' : ''; + size = (ns.spriteSize == '32' || ns.spriteSize == '64') ? ns.spriteSize : '32'; + //if the image path has not changed, we'll assume the default cdn path, otherwise we'll assume the provided path + ePath = (ns.imagePathPNG != ns.defaultPathPNG) ? ns.imagePathPNG : ns.defaultPathPNG + ns.emojiSize + '/'; + + // depending on the settings, we'll either add the native unicode as the alt tag, otherwise the shortname + alt = (ns.unicodeAlt) ? ns.convert(unicode.toUpperCase()) : shortname; + + if(ns.sprites) { + replaceWith = '' + alt + ''; + } + else { + replaceWith = '' + alt + ''; + } + + return replaceWith; + } + }); + + // if ascii smileys are turned on, then we'll replace them! + if (ns.ascii) { + + var asciiRX = ns.riskyMatchAscii ? ns.regAsciiRisky : ns.regAscii; + + str = str.replace(asciiRX, function(entire, m1, m2, m3) { + if( (typeof m3 === 'undefined') || (m3 === '') || (!(ns.unescapeHTML(m3) in ns.asciiList)) ) { + // if the ascii doesnt exist just return the entire match + return entire; + } + + m3 = ns.unescapeHTML(m3); + unicode = ns.asciiList[m3]; + shortname = mappedUnicode[unicode]; + category = (unicode.includes("-1f3f")) ? 'diversity' : ns.emojioneList[shortname].category; + title = ns.imageTitleTag ? 'title="' + ns.escapeHTML(m3) + '"' : ''; + size = (ns.spriteSize == '32' || ns.spriteSize == '64') ? ns.spriteSize : '32'; + //if the image path has not changed, we'll assume the default cdn path, otherwise we'll assume the provided path + ePath = (ns.imagePathPNG != ns.defaultPathPNG) ? ns.imagePathPNG : ns.defaultPathPNG + ns.emojiSize + '/'; + + // depending on the settings, we'll either add the native unicode as the alt tag, otherwise the shortname + alt = (ns.unicodeAlt) ? ns.convert(unicode.toUpperCase()) : ns.escapeHTML(m3); + + if(ns.sprites) { + replaceWith = m2+'' + alt + ''; + } + else { + replaceWith = m2+''+alt+''; + } + + return replaceWith; + }); + } + + return str; + }; + + ns.unicodeToImage = function(str) { + + var replaceWith,unicode,short,fname,alt,category,title,size,ePath; + var mappedUnicode = ns.mapUnicodeToShort(); + var eList = ns.emojioneList; + str = str.replace(ns.regUnicode, function(unicodeChar) { + if( (typeof unicodeChar === 'undefined') || (unicodeChar === '') ) + { + return unicodeChar; + } + else if ( unicodeChar in ns.jsEscapeMap ) + { + fname = ns.jsEscapeMap[unicodeChar]; + } + else if ( ns.greedyMatch && unicodeChar in ns.jsEscapeMapGreedy ) + { + fname = ns.jsEscapeMapGreedy[unicodeChar]; + } + else + { + return unicodeChar; + } + + // then map to shortname and locate the filename + short = mappedUnicode[fname]; + + // then pull the unicode output from emojioneList + fname = eList[short].uc_base; + unicode = eList[short].uc_output; + category = (fname.includes("-1f3f")) ? 'diversity' : eList[short].category; + size = (ns.spriteSize == '32' || ns.spriteSize == '64') ? ns.spriteSize : '32'; + //if the image path has not changed, we'll assume the default cdn path, otherwise we'll assume the provided path + ePath = (ns.imagePathPNG != ns.defaultPathPNG) ? ns.imagePathPNG : ns.defaultPathPNG + ns.emojiSize + '/'; + + // depending on the settings, we'll either add the native unicode as the alt tag, otherwise the shortname + alt = (ns.unicodeAlt) ? ns.convert(unicode.toUpperCase()) : short; + title = ns.imageTitleTag ? 'title="' + short + '"' : ''; + + if(ns.sprites) { + replaceWith = '' + alt + ''; + } + else { + replaceWith = '' + alt + ''; + } + + return replaceWith; + }); + + // if ascii smileys are turned on, then we'll replace them! + if (ns.ascii) { + + var asciiRX = ns.riskyMatchAscii ? ns.regAsciiRisky : ns.regAscii; + + str = str.replace(asciiRX, function(entire, m1, m2, m3) { + if( (typeof m3 === 'undefined') || (m3 === '') || (!(ns.unescapeHTML(m3) in ns.asciiList)) ) { + // if the ascii doesnt exist just return the entire match + return entire; + } + + m3 = ns.unescapeHTML(m3); + unicode = ns.asciiList[m3]; + shortname = mappedUnicode[unicode]; + category = (unicode.includes("-1f3f")) ? 'diversity' : ns.emojioneList[shortname].category; + title = ns.imageTitleTag ? 'title="' + ns.escapeHTML(m3) + '"' : ''; + size = (ns.spriteSize == '32' || ns.spriteSize == '64') ? ns.spriteSize : '32'; + //if the image path has not changed, we'll assume the default cdn path, otherwise we'll assume the provided path + ePath = (ns.imagePathPNG != ns.defaultPathPNG) ? ns.imagePathPNG : ns.defaultPathPNG + ns.emojiSize + '/'; + + // depending on the settings, we'll either add the native unicode as the alt tag, otherwise the shortname + alt = (ns.unicodeAlt) ? ns.convert(unicode.toUpperCase()) : ns.escapeHTML(m3); + + if(ns.sprites) { + replaceWith = m2+'' + alt + ''; + } + else { + replaceWith = m2+''+alt+''; + } + + return replaceWith; + }); + } + + return str; + }; + + // this is really just unicodeToShortname() but I opted for the shorthand name to match toImage() + ns.toShort = function(str) { + var find = ns.unicodeCharRegex(); + return ns.replaceAll(str, find); + }; + + // for converting unicode code points and code pairs to their respective characters + ns.convert = function(unicode) { + if(unicode.indexOf("-") > -1) { + var parts = []; + var s = unicode.split('-'); + for(var i = 0; i < s.length; i++) { + var part = parseInt(s[i], 16); + if (part >= 0x10000 && part <= 0x10FFFF) { + var hi = Math.floor((part - 0x10000) / 0x400) + 0xD800; + var lo = ((part - 0x10000) % 0x400) + 0xDC00; + part = (String.fromCharCode(hi) + String.fromCharCode(lo)); + } + else { + part = String.fromCharCode(part); + } + parts.push(part); + } + return parts.join(''); + } + else { + var s = parseInt(unicode, 16); + if (s >= 0x10000 && s <= 0x10FFFF) { + var hi = Math.floor((s - 0x10000) / 0x400) + 0xD800; + var lo = ((s - 0x10000) % 0x400) + 0xDC00; + return (String.fromCharCode(hi) + String.fromCharCode(lo)); + } + else { + return String.fromCharCode(s); + } + } + }; + + ns.escapeHTML = function (string) { + var escaped = { + '&' : '&', + '<' : '<', + '>' : '>', + '"' : '"', + '\'': ''' + }; + + return string.replace(/[&<>"']/g, function (match) { + return escaped[match]; + }); + }; + ns.unescapeHTML = function (string) { + var unescaped = { + '&' : '&', + '&' : '&', + '&' : '&', + '<' : '<', + '<' : '<', + '<' : '<', + '>' : '>', + '>' : '>', + '>' : '>', + '"' : '"', + '"' : '"', + '"' : '"', + ''' : '\'', + ''' : '\'', + ''' : '\'' + }; + + return string.replace(/&(?:amp|#38|#x26|lt|#60|#x3C|gt|#62|#x3E|apos|#39|#x27|quot|#34|#x22);/ig, function (match) { + return unescaped[match]; + }); + }; + + ns.shortnameConversionMap = function() { + var map = [], emoji; + for (emoji in ns.emojioneList) { + if (!ns.emojioneList.hasOwnProperty(emoji) || (emoji === '')) continue; + map[ns.convert(ns.emojioneList[emoji].uc_output)] = emoji; + } + return map; + }; + + ns.unicodeCharRegex = function() { + var map = []; + for (emoji in ns.emojioneList) { + if (!ns.emojioneList.hasOwnProperty(emoji) || (emoji === '')) continue; + map.push(ns.convert(ns.emojioneList[emoji].uc_output)); + } + return map.join('|'); + }; + + ns.mapEmojioneList = function (addToMapStorage) { + for (var shortname in ns.emojioneList) { + if (!ns.emojioneList.hasOwnProperty(shortname)) { continue; } + var unicode = ns.emojioneList[shortname].uc_base; + addToMapStorage(unicode, shortname); + } + }; + + ns.mapUnicodeToShort = function() { + if (!ns.memMapShortToUnicode) { + ns.memMapShortToUnicode = {}; + ns.mapEmojioneList(function (unicode, shortname) { + ns.memMapShortToUnicode[unicode] = shortname; + }); + } + return ns.memMapShortToUnicode; + }; + + ns.memorizeReplacement = function() { + if (!ns.unicodeReplacementRegEx || !ns.memMapShortToUnicodeCharacters) { + var unicodeList = []; + ns.memMapShortToUnicodeCharacters = {}; + ns.mapEmojioneList(function (unicode, shortname) { + var emojiCharacter = ns.convert(unicode); + ns.memMapShortToUnicodeCharacters[emojiCharacter] = shortname; + unicodeList.push(emojiCharacter); + }); + ns.unicodeReplacementRegEx = unicodeList.join('|'); + } + }; + + ns.mapUnicodeCharactersToShort = function() { + ns.memorizeReplacement(); + return ns.memMapShortToUnicodeCharacters; + }; + + //reverse an object + ns.objectFlip = function (obj) { + var key, tmp_obj = {}; + + for (key in obj) { + if (obj.hasOwnProperty(key)) { + tmp_obj[obj[key]] = key; + } + } + + return tmp_obj; + }; + + ns.escapeRegExp = function(string) { + return string.replace(/[-[\]{}()*+?.,;:&\\^$#\s]/g, "\\$&"); + }; + + ns.replaceAll = function(string, find) { + var escapedFind = ns.escapeRegExp(find); //sorted largest output to smallest output + var search = new RegExp("]*>.*?<\/object>|]*>.*?<\/span>|<(?:object|embed|svg|img|div|span|p|a)[^>]*>|("+escapedFind+")", "gi"); + + // callback prevents replacing anything inside of these common html tags as well as between an tag + + var replace = function(entire, m1) { + return ((typeof m1 === 'undefined') || (m1 === '')) ? entire : ns.shortnameConversionMap()[m1]; + }; + + return string.replace(search,replace); + }; + +}(this.emojione = this.emojione || {})); +if(true) module.exports = this.emojione; + +/***/ }), + +/***/ "./node_modules/es6-promise/dist/es6-promise.auto.js": +/*!***********************************************************!*\ + !*** ./node_modules/es6-promise/dist/es6-promise.auto.js ***! + \***********************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(process, global) {/*! + * @overview es6-promise - a tiny implementation of Promises/A+. + * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) + * @license Licensed under MIT license + * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE + * @version v4.2.4+314e4831 + */ + +(function (global, factory) { + true ? module.exports = factory() : + undefined; +}(this, (function () { 'use strict'; + +function objectOrFunction(x) { + var type = typeof x; + return x !== null && (type === 'object' || type === 'function'); +} + +function isFunction(x) { + return typeof x === 'function'; +} + + + +var _isArray = void 0; +if (Array.isArray) { + _isArray = Array.isArray; +} else { + _isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; +} + +var isArray = _isArray; + +var len = 0; +var vertxNext = void 0; +var customSchedulerFn = void 0; + +var asap = function asap(callback, arg) { + queue[len] = callback; + queue[len + 1] = arg; + len += 2; + if (len === 2) { + // If len is 2, that means that we need to schedule an async flush. + // If additional callbacks are queued before the queue is flushed, they + // will be processed by this flush that we are scheduling. + if (customSchedulerFn) { + customSchedulerFn(flush); + } else { + scheduleFlush(); + } + } +}; + +function setScheduler(scheduleFn) { + customSchedulerFn = scheduleFn; +} + +function setAsap(asapFn) { + asap = asapFn; +} + +var browserWindow = typeof window !== 'undefined' ? window : undefined; +var browserGlobal = browserWindow || {}; +var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; +var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; + +// test for web worker but not in IE10 +var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; + +// node +function useNextTick() { + // node version 0.10.x displays a deprecation warning when nextTick is used recursively + // see https://github.com/cujojs/when/issues/410 for details + return function () { + return process.nextTick(flush); + }; +} + +// vertx +function useVertxTimer() { + if (typeof vertxNext !== 'undefined') { + return function () { + vertxNext(flush); + }; + } + + return useSetTimeout(); +} + +function useMutationObserver() { + var iterations = 0; + var observer = new BrowserMutationObserver(flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); + + return function () { + node.data = iterations = ++iterations % 2; + }; +} + +// web worker +function useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = flush; + return function () { + return channel.port2.postMessage(0); + }; +} + +function useSetTimeout() { + // Store setTimeout reference so es6-promise will be unaffected by + // other code modifying setTimeout (like sinon.useFakeTimers()) + var globalSetTimeout = setTimeout; + return function () { + return globalSetTimeout(flush, 1); + }; +} + +var queue = new Array(1000); +function flush() { + for (var i = 0; i < len; i += 2) { + var callback = queue[i]; + var arg = queue[i + 1]; + + callback(arg); + + queue[i] = undefined; + queue[i + 1] = undefined; + } + + len = 0; +} + +function attemptVertx() { + try { + var vertx = Function('return this')().require('vertx'); + vertxNext = vertx.runOnLoop || vertx.runOnContext; + return useVertxTimer(); + } catch (e) { + return useSetTimeout(); + } +} + +var scheduleFlush = void 0; +// Decide what async method to use to triggering processing of queued callbacks: +if (isNode) { + scheduleFlush = useNextTick(); +} else if (BrowserMutationObserver) { + scheduleFlush = useMutationObserver(); +} else if (isWorker) { + scheduleFlush = useMessageChannel(); +} else if (browserWindow === undefined && "function" === 'function') { + scheduleFlush = attemptVertx(); +} else { + scheduleFlush = useSetTimeout(); +} + +function then(onFulfillment, onRejection) { + var parent = this; + + var child = new this.constructor(noop); + + if (child[PROMISE_ID] === undefined) { + makePromise(child); + } + + var _state = parent._state; + + + if (_state) { + var callback = arguments[_state - 1]; + asap(function () { + return invokeCallback(_state, child, callback, parent._result); + }); + } else { + subscribe(parent, child, onFulfillment, onRejection); + } + + return child; +} + +/** + `Promise.resolve` returns a promise that will become resolved with the + passed `value`. It is shorthand for the following: + + ```javascript + let promise = new Promise(function(resolve, reject){ + resolve(1); + }); + + promise.then(function(value){ + // value === 1 + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + let promise = Promise.resolve(1); + + promise.then(function(value){ + // value === 1 + }); + ``` + + @method resolve + @static + @param {Any} value value that the returned promise will be resolved with + Useful for tooling. + @return {Promise} a promise that will become fulfilled with the given + `value` +*/ +function resolve$1(object) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } + + var promise = new Constructor(noop); + resolve(promise, object); + return promise; +} + +var PROMISE_ID = Math.random().toString(36).substring(2); + +function noop() {} + +var PENDING = void 0; +var FULFILLED = 1; +var REJECTED = 2; + +var TRY_CATCH_ERROR = { error: null }; + +function selfFulfillment() { + return new TypeError("You cannot resolve a promise with itself"); +} + +function cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); +} + +function getThen(promise) { + try { + return promise.then; + } catch (error) { + TRY_CATCH_ERROR.error = error; + return TRY_CATCH_ERROR; + } +} + +function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) { + try { + then$$1.call(value, fulfillmentHandler, rejectionHandler); + } catch (e) { + return e; + } +} + +function handleForeignThenable(promise, thenable, then$$1) { + asap(function (promise) { + var sealed = false; + var error = tryThen(then$$1, thenable, function (value) { + if (sealed) { + return; + } + sealed = true; + if (thenable !== value) { + resolve(promise, value); + } else { + fulfill(promise, value); + } + }, function (reason) { + if (sealed) { + return; + } + sealed = true; + + reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); + + if (!sealed && error) { + sealed = true; + reject(promise, error); + } + }, promise); +} + +function handleOwnThenable(promise, thenable) { + if (thenable._state === FULFILLED) { + fulfill(promise, thenable._result); + } else if (thenable._state === REJECTED) { + reject(promise, thenable._result); + } else { + subscribe(thenable, undefined, function (value) { + return resolve(promise, value); + }, function (reason) { + return reject(promise, reason); + }); + } +} + +function handleMaybeThenable(promise, maybeThenable, then$$1) { + if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) { + handleOwnThenable(promise, maybeThenable); + } else { + if (then$$1 === TRY_CATCH_ERROR) { + reject(promise, TRY_CATCH_ERROR.error); + TRY_CATCH_ERROR.error = null; + } else if (then$$1 === undefined) { + fulfill(promise, maybeThenable); + } else if (isFunction(then$$1)) { + handleForeignThenable(promise, maybeThenable, then$$1); + } else { + fulfill(promise, maybeThenable); + } + } +} + +function resolve(promise, value) { + if (promise === value) { + reject(promise, selfFulfillment()); + } else if (objectOrFunction(value)) { + handleMaybeThenable(promise, value, getThen(value)); + } else { + fulfill(promise, value); + } +} + +function publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } + + publish(promise); +} + +function fulfill(promise, value) { + if (promise._state !== PENDING) { + return; + } + + promise._result = value; + promise._state = FULFILLED; + + if (promise._subscribers.length !== 0) { + asap(publish, promise); + } +} + +function reject(promise, reason) { + if (promise._state !== PENDING) { + return; + } + promise._state = REJECTED; + promise._result = reason; + + asap(publishRejection, promise); +} + +function subscribe(parent, child, onFulfillment, onRejection) { + var _subscribers = parent._subscribers; + var length = _subscribers.length; + + + parent._onerror = null; + + _subscribers[length] = child; + _subscribers[length + FULFILLED] = onFulfillment; + _subscribers[length + REJECTED] = onRejection; + + if (length === 0 && parent._state) { + asap(publish, parent); + } +} + +function publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; + + if (subscribers.length === 0) { + return; + } + + var child = void 0, + callback = void 0, + detail = promise._result; + + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + + if (child) { + invokeCallback(settled, child, callback, detail); + } else { + callback(detail); + } + } + + promise._subscribers.length = 0; +} + +function tryCatch(callback, detail) { + try { + return callback(detail); + } catch (e) { + TRY_CATCH_ERROR.error = e; + return TRY_CATCH_ERROR; + } +} + +function invokeCallback(settled, promise, callback, detail) { + var hasCallback = isFunction(callback), + value = void 0, + error = void 0, + succeeded = void 0, + failed = void 0; + + if (hasCallback) { + value = tryCatch(callback, detail); + + if (value === TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value.error = null; + } else { + succeeded = true; + } + + if (promise === value) { + reject(promise, cannotReturnOwn()); + return; + } + } else { + value = detail; + succeeded = true; + } + + if (promise._state !== PENDING) { + // noop + } else if (hasCallback && succeeded) { + resolve(promise, value); + } else if (failed) { + reject(promise, error); + } else if (settled === FULFILLED) { + fulfill(promise, value); + } else if (settled === REJECTED) { + reject(promise, value); + } +} + +function initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value) { + resolve(promise, value); + }, function rejectPromise(reason) { + reject(promise, reason); + }); + } catch (e) { + reject(promise, e); + } +} + +var id = 0; +function nextId() { + return id++; +} + +function makePromise(promise) { + promise[PROMISE_ID] = id++; + promise._state = undefined; + promise._result = undefined; + promise._subscribers = []; +} + +function validationError() { + return new Error('Array Methods must be provided an Array'); +} + +var Enumerator = function () { + function Enumerator(Constructor, input) { + this._instanceConstructor = Constructor; + this.promise = new Constructor(noop); + + if (!this.promise[PROMISE_ID]) { + makePromise(this.promise); + } + + if (isArray(input)) { + this.length = input.length; + this._remaining = input.length; + + this._result = new Array(this.length); + + if (this.length === 0) { + fulfill(this.promise, this._result); + } else { + this.length = this.length || 0; + this._enumerate(input); + if (this._remaining === 0) { + fulfill(this.promise, this._result); + } + } + } else { + reject(this.promise, validationError()); + } + } + + Enumerator.prototype._enumerate = function _enumerate(input) { + for (var i = 0; this._state === PENDING && i < input.length; i++) { + this._eachEntry(input[i], i); + } + }; + + Enumerator.prototype._eachEntry = function _eachEntry(entry, i) { + var c = this._instanceConstructor; + var resolve$$1 = c.resolve; + + + if (resolve$$1 === resolve$1) { + var _then = getThen(entry); + + if (_then === then && entry._state !== PENDING) { + this._settledAt(entry._state, i, entry._result); + } else if (typeof _then !== 'function') { + this._remaining--; + this._result[i] = entry; + } else if (c === Promise$2) { + var promise = new c(noop); + handleMaybeThenable(promise, entry, _then); + this._willSettleAt(promise, i); + } else { + this._willSettleAt(new c(function (resolve$$1) { + return resolve$$1(entry); + }), i); + } + } else { + this._willSettleAt(resolve$$1(entry), i); + } + }; + + Enumerator.prototype._settledAt = function _settledAt(state, i, value) { + var promise = this.promise; + + + if (promise._state === PENDING) { + this._remaining--; + + if (state === REJECTED) { + reject(promise, value); + } else { + this._result[i] = value; + } + } + + if (this._remaining === 0) { + fulfill(promise, this._result); + } + }; + + Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) { + var enumerator = this; + + subscribe(promise, undefined, function (value) { + return enumerator._settledAt(FULFILLED, i, value); + }, function (reason) { + return enumerator._settledAt(REJECTED, i, reason); + }); + }; + + return Enumerator; +}(); + +/** + `Promise.all` accepts an array of promises, and returns a new promise which + is fulfilled with an array of fulfillment values for the passed promises, or + rejected with the reason of the first passed promise to be rejected. It casts all + elements of the passed iterable to promises as it runs this algorithm. + + Example: + + ```javascript + let promise1 = resolve(1); + let promise2 = resolve(2); + let promise3 = resolve(3); + let promises = [ promise1, promise2, promise3 ]; + + Promise.all(promises).then(function(array){ + // The array here would be [ 1, 2, 3 ]; + }); + ``` + + If any of the `promises` given to `all` are rejected, the first promise + that is rejected will be given as an argument to the returned promises's + rejection handler. For example: + + Example: + + ```javascript + let promise1 = resolve(1); + let promise2 = reject(new Error("2")); + let promise3 = reject(new Error("3")); + let promises = [ promise1, promise2, promise3 ]; + + Promise.all(promises).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(error) { + // error.message === "2" + }); + ``` + + @method all + @static + @param {Array} entries array of promises + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} promise that is fulfilled when all `promises` have been + fulfilled, or rejected if any of them become rejected. + @static +*/ +function all(entries) { + return new Enumerator(this, entries).promise; +} + +/** + `Promise.race` returns a new promise which is settled in the same way as the + first passed promise to settle. + + Example: + + ```javascript + let promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); + + let promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 2'); + }, 100); + }); + + Promise.race([promise1, promise2]).then(function(result){ + // result === 'promise 2' because it was resolved before promise1 + // was resolved. + }); + ``` + + `Promise.race` is deterministic in that only the state of the first + settled promise matters. For example, even if other promises given to the + `promises` array argument are resolved, but the first settled promise has + become rejected before the other promises became fulfilled, the returned + promise will become rejected: + + ```javascript + let promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); + + let promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + reject(new Error('promise 2')); + }, 100); + }); + + Promise.race([promise1, promise2]).then(function(result){ + // Code here never runs + }, function(reason){ + // reason.message === 'promise 2' because promise 2 became rejected before + // promise 1 became fulfilled + }); + ``` + + An example real-world use case is implementing timeouts: + + ```javascript + Promise.race([ajax('foo.json'), timeout(5000)]) + ``` + + @method race + @static + @param {Array} promises array of promises to observe + Useful for tooling. + @return {Promise} a promise which settles in the same way as the first passed + promise to settle. +*/ +function race(entries) { + /*jshint validthis:true */ + var Constructor = this; + + if (!isArray(entries)) { + return new Constructor(function (_, reject) { + return reject(new TypeError('You must pass an array to race.')); + }); + } else { + return new Constructor(function (resolve, reject) { + var length = entries.length; + for (var i = 0; i < length; i++) { + Constructor.resolve(entries[i]).then(resolve, reject); + } + }); + } +} + +/** + `Promise.reject` returns a promise rejected with the passed `reason`. + It is shorthand for the following: + + ```javascript + let promise = new Promise(function(resolve, reject){ + reject(new Error('WHOOPS')); + }); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + let promise = Promise.reject(new Error('WHOOPS')); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + @method reject + @static + @param {Any} reason value that the returned promise will be rejected with. + Useful for tooling. + @return {Promise} a promise rejected with the given `reason`. +*/ +function reject$1(reason) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(noop); + reject(promise, reason); + return promise; +} + +function needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); +} + +function needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); +} + +/** + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise's eventual value or the reason + why the promise cannot be fulfilled. + + Terminology + ----------- + + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. + + A promise can be in one of three states: pending, fulfilled, or rejected. + + Promises that are fulfilled have a fulfillment value and are in the fulfilled + state. Promises that are rejected have a rejection reason and are in the + rejected state. A fulfillment value is never a thenable. + + Promises can also be said to *resolve* a value. If this value is also a + promise, then the original promise's settled state will match the value's + settled state. So a promise that *resolves* a promise that rejects will + itself reject, and a promise that *resolves* a promise that fulfills will + itself fulfill. + + + Basic Usage: + ------------ + + ```js + let promise = new Promise(function(resolve, reject) { + // on success + resolve(value); + + // on failure + reject(reason); + }); + + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Advanced Usage: + --------------- + + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. + + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + let xhr = new XMLHttpRequest(); + + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200) { + resolve(this.response); + } else { + reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); + } + } + }; + }); + } + + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Unlike callbacks, promises are great composable primitives. + + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class Promise + @param {Function} resolver + Useful for tooling. + @constructor +*/ + +var Promise$2 = function () { + function Promise(resolver) { + this[PROMISE_ID] = nextId(); + this._result = this._state = undefined; + this._subscribers = []; + + if (noop !== resolver) { + typeof resolver !== 'function' && needsResolver(); + this instanceof Promise ? initializePromise(this, resolver) : needsNew(); + } + } + + /** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + Chaining + -------- + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` + }); + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + Assimilation + ------------ + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + If the assimliated promise rejects, then the downstream promise will also reject. + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + Simple Example + -------------- + Synchronous Example + ```javascript + let result; + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + Errback Example + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success + } + }); + ``` + Promise Example; + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + Advanced Example + -------------- + Synchronous Example + ```javascript + let author, books; + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + Errback Example + ```js + function foundBooks(books) { + } + function failure(reason) { + } + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + Promise Example; + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + @method then + @param {Function} onFulfilled + @param {Function} onRejected + Useful for tooling. + @return {Promise} + */ + + /** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + ```js + function findAuthor(){ + throw new Error('couldn't find that author'); + } + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + @method catch + @param {Function} onRejection + Useful for tooling. + @return {Promise} + */ + + + Promise.prototype.catch = function _catch(onRejection) { + return this.then(null, onRejection); + }; + + /** + `finally` will be invoked regardless of the promise's fate just as native + try/catch/finally behaves + + Synchronous example: + + ```js + findAuthor() { + if (Math.random() > 0.5) { + throw new Error(); + } + return new Author(); + } + + try { + return findAuthor(); // succeed or fail + } catch(error) { + return findOtherAuther(); + } finally { + // always runs + // doesn't affect the return value + } + ``` + + Asynchronous example: + + ```js + findAuthor().catch(function(reason){ + return findOtherAuther(); + }).finally(function(){ + // author was either found, or not + }); + ``` + + @method finally + @param {Function} callback + @return {Promise} + */ + + + Promise.prototype.finally = function _finally(callback) { + var promise = this; + var constructor = promise.constructor; + + return promise.then(function (value) { + return constructor.resolve(callback()).then(function () { + return value; + }); + }, function (reason) { + return constructor.resolve(callback()).then(function () { + throw reason; + }); + }); + }; + + return Promise; +}(); + +Promise$2.prototype.then = then; +Promise$2.all = all; +Promise$2.race = race; +Promise$2.resolve = resolve$1; +Promise$2.reject = reject$1; +Promise$2._setScheduler = setScheduler; +Promise$2._setAsap = setAsap; +Promise$2._asap = asap; + +/*global self*/ +function polyfill() { + var local = void 0; + + if (typeof global !== 'undefined') { + local = global; + } else if (typeof self !== 'undefined') { + local = self; + } else { + try { + local = Function('return this')(); + } catch (e) { + throw new Error('polyfill failed because global object is unavailable in this environment'); + } + } + + var P = local.Promise; + + if (P) { + var promiseToString = null; + try { + promiseToString = Object.prototype.toString.call(P.resolve()); + } catch (e) { + // silently ignored + } + + if (promiseToString === '[object Promise]' && !P.cast) { + return; + } + } + + local.Promise = Promise$2; +} + +// Strange compat.. +Promise$2.polyfill = polyfill; +Promise$2.Promise = Promise$2; + +Promise$2.polyfill(); + +return Promise$2; + +}))); + + + +//# sourceMappingURL=es6-promise.auto.map + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../process/browser.js */ "./node_modules/process/browser.js"), __webpack_require__(/*! ./../../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js"))) + +/***/ }), + +/***/ "./node_modules/filesize/lib/filesize.js": +/*!***********************************************!*\ + !*** ./node_modules/filesize/lib/filesize.js ***! + \***********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) { + +/** + * filesize + * + * @copyright 2018 Jason Mulligan + * @license BSD-3-Clause + * @version 3.6.1 + */ +(function (global) { + var b = /^(b|B)$/, + symbol = { + iec: { + bits: ["b", "Kib", "Mib", "Gib", "Tib", "Pib", "Eib", "Zib", "Yib"], + bytes: ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"] + }, + jedec: { + bits: ["b", "Kb", "Mb", "Gb", "Tb", "Pb", "Eb", "Zb", "Yb"], + bytes: ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"] + } + }, + fullform = { + iec: ["", "kibi", "mebi", "gibi", "tebi", "pebi", "exbi", "zebi", "yobi"], + jedec: ["", "kilo", "mega", "giga", "tera", "peta", "exa", "zetta", "yotta"] + }; + + /** + * filesize + * + * @method filesize + * @param {Mixed} arg String, Int or Float to transform + * @param {Object} descriptor [Optional] Flags + * @return {String} Readable file size String + */ + function filesize(arg) { + var descriptor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + var result = [], + val = 0, + e = void 0, + base = void 0, + bits = void 0, + ceil = void 0, + full = void 0, + fullforms = void 0, + neg = void 0, + num = void 0, + output = void 0, + round = void 0, + unix = void 0, + separator = void 0, + spacer = void 0, + standard = void 0, + symbols = void 0; + + if (isNaN(arg)) { + throw new Error("Invalid arguments"); + } + + bits = descriptor.bits === true; + unix = descriptor.unix === true; + base = descriptor.base || 2; + round = descriptor.round !== void 0 ? descriptor.round : unix ? 1 : 2; + separator = descriptor.separator !== void 0 ? descriptor.separator || "" : ""; + spacer = descriptor.spacer !== void 0 ? descriptor.spacer : unix ? "" : " "; + symbols = descriptor.symbols || descriptor.suffixes || {}; + standard = base === 2 ? descriptor.standard || "jedec" : "jedec"; + output = descriptor.output || "string"; + full = descriptor.fullform === true; + fullforms = descriptor.fullforms instanceof Array ? descriptor.fullforms : []; + e = descriptor.exponent !== void 0 ? descriptor.exponent : -1; + num = Number(arg); + neg = num < 0; + ceil = base > 2 ? 1000 : 1024; + + // Flipping a negative number to determine the size + if (neg) { + num = -num; + } + + // Determining the exponent + if (e === -1 || isNaN(e)) { + e = Math.floor(Math.log(num) / Math.log(ceil)); + + if (e < 0) { + e = 0; + } + } + + // Exceeding supported length, time to reduce & multiply + if (e > 8) { + e = 8; + } + + // Zero is now a special case because bytes divide by 1 + if (num === 0) { + result[0] = 0; + result[1] = unix ? "" : symbol[standard][bits ? "bits" : "bytes"][e]; + } else { + val = num / (base === 2 ? Math.pow(2, e * 10) : Math.pow(1000, e)); + + if (bits) { + val = val * 8; + + if (val >= ceil && e < 8) { + val = val / ceil; + e++; + } + } + + result[0] = Number(val.toFixed(e > 0 ? round : 0)); + result[1] = base === 10 && e === 1 ? bits ? "kb" : "kB" : symbol[standard][bits ? "bits" : "bytes"][e]; + + if (unix) { + result[1] = standard === "jedec" ? result[1].charAt(0) : e > 0 ? result[1].replace(/B$/, "") : result[1]; + + if (b.test(result[1])) { + result[0] = Math.floor(result[0]); + result[1] = ""; + } + } + } + + // Decorating a 'diff' + if (neg) { + result[0] = -result[0]; + } + + // Applying custom symbol + result[1] = symbols[result[1]] || result[1]; + + // Returning Array, Object, or String (default) + if (output === "array") { + return result; + } + + if (output === "exponent") { + return e; + } + + if (output === "object") { + return { value: result[0], suffix: result[1], symbol: result[1] }; + } + + if (full) { + result[1] = fullforms[e] ? fullforms[e] : fullform[standard][e] + (bits ? "bit" : "byte") + (result[0] === 1 ? "" : "s"); + } + + if (separator.length > 0) { + result[0] = result[0].toString().replace(".", separator); + } + + return result.join(spacer); + } + + // Partial application for functional programming + filesize.partial = function (opt) { + return function (arg) { + return filesize(arg, opt); + }; + }; + + // CommonJS, AMD, script tag + if (true) { + module.exports = filesize; + } else {} +})(typeof window !== "undefined" ? window : global); + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js"))) + +/***/ }), + +/***/ "./node_modules/jed/jed.js": +/*!*********************************!*\ + !*** ./node_modules/jed/jed.js ***! + \*********************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @preserve jed.js https://github.com/SlexAxton/Jed + */ +/* +----------- +A gettext compatible i18n library for modern JavaScript Applications + +by Alex Sexton - AlexSexton [at] gmail - @SlexAxton + +MIT License + +A jQuery Foundation project - requires CLA to contribute - +https://contribute.jquery.org/CLA/ + + + +Jed offers the entire applicable GNU gettext spec'd set of +functions, but also offers some nicer wrappers around them. +The api for gettext was written for a language with no function +overloading, so Jed allows a little more of that. + +Many thanks to Joshua I. Miller - unrtst@cpan.org - who wrote +gettext.js back in 2008. I was able to vet a lot of my ideas +against his. I also made sure Jed passed against his tests +in order to offer easy upgrades -- jsgettext.berlios.de +*/ +(function (root, undef) { + + // Set up some underscore-style functions, if you already have + // underscore, feel free to delete this section, and use it + // directly, however, the amount of functions used doesn't + // warrant having underscore as a full dependency. + // Underscore 1.3.0 was used to port and is licensed + // under the MIT License by Jeremy Ashkenas. + var ArrayProto = Array.prototype, + ObjProto = Object.prototype, + slice = ArrayProto.slice, + hasOwnProp = ObjProto.hasOwnProperty, + nativeForEach = ArrayProto.forEach, + breaker = {}; + + // We're not using the OOP style _ so we don't need the + // extra level of indirection. This still means that you + // sub out for real `_` though. + var _ = { + forEach : function( obj, iterator, context ) { + var i, l, key; + if ( obj === null ) { + return; + } + + if ( nativeForEach && obj.forEach === nativeForEach ) { + obj.forEach( iterator, context ); + } + else if ( obj.length === +obj.length ) { + for ( i = 0, l = obj.length; i < l; i++ ) { + if ( i in obj && iterator.call( context, obj[i], i, obj ) === breaker ) { + return; + } + } + } + else { + for ( key in obj) { + if ( hasOwnProp.call( obj, key ) ) { + if ( iterator.call (context, obj[key], key, obj ) === breaker ) { + return; + } + } + } + } + }, + extend : function( obj ) { + this.forEach( slice.call( arguments, 1 ), function ( source ) { + for ( var prop in source ) { + obj[prop] = source[prop]; + } + }); + return obj; + } + }; + // END Miniature underscore impl + + // Jed is a constructor function + var Jed = function ( options ) { + // Some minimal defaults + this.defaults = { + "locale_data" : { + "messages" : { + "" : { + "domain" : "messages", + "lang" : "en", + "plural_forms" : "nplurals=2; plural=(n != 1);" + } + // There are no default keys, though + } + }, + // The default domain if one is missing + "domain" : "messages", + // enable debug mode to log untranslated strings to the console + "debug" : false + }; + + // Mix in the sent options with the default options + this.options = _.extend( {}, this.defaults, options ); + this.textdomain( this.options.domain ); + + if ( options.domain && ! this.options.locale_data[ this.options.domain ] ) { + throw new Error('Text domain set to non-existent domain: `' + options.domain + '`'); + } + }; + + // The gettext spec sets this character as the default + // delimiter for context lookups. + // e.g.: context\u0004key + // If your translation company uses something different, + // just change this at any time and it will use that instead. + Jed.context_delimiter = String.fromCharCode( 4 ); + + function getPluralFormFunc ( plural_form_string ) { + return Jed.PF.compile( plural_form_string || "nplurals=2; plural=(n != 1);"); + } + + function Chain( key, i18n ){ + this._key = key; + this._i18n = i18n; + } + + // Create a chainable api for adding args prettily + _.extend( Chain.prototype, { + onDomain : function ( domain ) { + this._domain = domain; + return this; + }, + withContext : function ( context ) { + this._context = context; + return this; + }, + ifPlural : function ( num, pkey ) { + this._val = num; + this._pkey = pkey; + return this; + }, + fetch : function ( sArr ) { + if ( {}.toString.call( sArr ) != '[object Array]' ) { + sArr = [].slice.call(arguments, 0); + } + return ( sArr && sArr.length ? Jed.sprintf : function(x){ return x; } )( + this._i18n.dcnpgettext(this._domain, this._context, this._key, this._pkey, this._val), + sArr + ); + } + }); + + // Add functions to the Jed prototype. + // These will be the functions on the object that's returned + // from creating a `new Jed()` + // These seem redundant, but they gzip pretty well. + _.extend( Jed.prototype, { + // The sexier api start point + translate : function ( key ) { + return new Chain( key, this ); + }, + + textdomain : function ( domain ) { + if ( ! domain ) { + return this._textdomain; + } + this._textdomain = domain; + }, + + gettext : function ( key ) { + return this.dcnpgettext.call( this, undef, undef, key ); + }, + + dgettext : function ( domain, key ) { + return this.dcnpgettext.call( this, domain, undef, key ); + }, + + dcgettext : function ( domain , key /*, category */ ) { + // Ignores the category anyways + return this.dcnpgettext.call( this, domain, undef, key ); + }, + + ngettext : function ( skey, pkey, val ) { + return this.dcnpgettext.call( this, undef, undef, skey, pkey, val ); + }, + + dngettext : function ( domain, skey, pkey, val ) { + return this.dcnpgettext.call( this, domain, undef, skey, pkey, val ); + }, + + dcngettext : function ( domain, skey, pkey, val/*, category */) { + return this.dcnpgettext.call( this, domain, undef, skey, pkey, val ); + }, + + pgettext : function ( context, key ) { + return this.dcnpgettext.call( this, undef, context, key ); + }, + + dpgettext : function ( domain, context, key ) { + return this.dcnpgettext.call( this, domain, context, key ); + }, + + dcpgettext : function ( domain, context, key/*, category */) { + return this.dcnpgettext.call( this, domain, context, key ); + }, + + npgettext : function ( context, skey, pkey, val ) { + return this.dcnpgettext.call( this, undef, context, skey, pkey, val ); + }, + + dnpgettext : function ( domain, context, skey, pkey, val ) { + return this.dcnpgettext.call( this, domain, context, skey, pkey, val ); + }, + + // The most fully qualified gettext function. It has every option. + // Since it has every option, we can use it from every other method. + // This is the bread and butter. + // Technically there should be one more argument in this function for 'Category', + // but since we never use it, we might as well not waste the bytes to define it. + dcnpgettext : function ( domain, context, singular_key, plural_key, val ) { + // Set some defaults + + plural_key = plural_key || singular_key; + + // Use the global domain default if one + // isn't explicitly passed in + domain = domain || this._textdomain; + + var fallback; + + // Handle special cases + + // No options found + if ( ! this.options ) { + // There's likely something wrong, but we'll return the correct key for english + // We do this by instantiating a brand new Jed instance with the default set + // for everything that could be broken. + fallback = new Jed(); + return fallback.dcnpgettext.call( fallback, undefined, undefined, singular_key, plural_key, val ); + } + + // No translation data provided + if ( ! this.options.locale_data ) { + throw new Error('No locale data provided.'); + } + + if ( ! this.options.locale_data[ domain ] ) { + throw new Error('Domain `' + domain + '` was not found.'); + } + + if ( ! this.options.locale_data[ domain ][ "" ] ) { + throw new Error('No locale meta information provided.'); + } + + // Make sure we have a truthy key. Otherwise we might start looking + // into the empty string key, which is the options for the locale + // data. + if ( ! singular_key ) { + throw new Error('No translation key found.'); + } + + var key = context ? context + Jed.context_delimiter + singular_key : singular_key, + locale_data = this.options.locale_data, + dict = locale_data[ domain ], + defaultConf = (locale_data.messages || this.defaults.locale_data.messages)[""], + pluralForms = dict[""].plural_forms || dict[""]["Plural-Forms"] || dict[""]["plural-forms"] || defaultConf.plural_forms || defaultConf["Plural-Forms"] || defaultConf["plural-forms"], + val_list, + res; + + var val_idx; + if (val === undefined) { + // No value passed in; assume singular key lookup. + val_idx = 0; + + } else { + // Value has been passed in; use plural-forms calculations. + + // Handle invalid numbers, but try casting strings for good measure + if ( typeof val != 'number' ) { + val = parseInt( val, 10 ); + + if ( isNaN( val ) ) { + throw new Error('The number that was passed in is not a number.'); + } + } + + val_idx = getPluralFormFunc(pluralForms)(val); + } + + // Throw an error if a domain isn't found + if ( ! dict ) { + throw new Error('No domain named `' + domain + '` could be found.'); + } + + val_list = dict[ key ]; + + // If there is no match, then revert back to + // english style singular/plural with the keys passed in. + if ( ! val_list || val_idx > val_list.length ) { + if (this.options.missing_key_callback) { + this.options.missing_key_callback(key, domain); + } + res = [ singular_key, plural_key ]; + + // collect untranslated strings + if (this.options.debug===true) { + console.log(res[ getPluralFormFunc(pluralForms)( val ) ]); + } + return res[ getPluralFormFunc()( val ) ]; + } + + res = val_list[ val_idx ]; + + // This includes empty strings on purpose + if ( ! res ) { + res = [ singular_key, plural_key ]; + return res[ getPluralFormFunc()( val ) ]; + } + return res; + } + }); + + + // We add in sprintf capabilities for post translation value interolation + // This is not internally used, so you can remove it if you have this + // available somewhere else, or want to use a different system. + + // We _slightly_ modify the normal sprintf behavior to more gracefully handle + // undefined values. + + /** + sprintf() for JavaScript 0.7-beta1 + http://www.diveintojavascript.com/projects/javascript-sprintf + + Copyright (c) Alexandru Marasteanu + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of sprintf() for JavaScript nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL Alexandru Marasteanu BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + var sprintf = (function() { + function get_type(variable) { + return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase(); + } + function str_repeat(input, multiplier) { + for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */} + return output.join(''); + } + + var str_format = function() { + if (!str_format.cache.hasOwnProperty(arguments[0])) { + str_format.cache[arguments[0]] = str_format.parse(arguments[0]); + } + return str_format.format.call(null, str_format.cache[arguments[0]], arguments); + }; + + str_format.format = function(parse_tree, argv) { + var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length; + for (i = 0; i < tree_length; i++) { + node_type = get_type(parse_tree[i]); + if (node_type === 'string') { + output.push(parse_tree[i]); + } + else if (node_type === 'array') { + match = parse_tree[i]; // convenience purposes only + if (match[2]) { // keyword argument + arg = argv[cursor]; + for (k = 0; k < match[2].length; k++) { + if (!arg.hasOwnProperty(match[2][k])) { + throw(sprintf('[sprintf] property "%s" does not exist', match[2][k])); + } + arg = arg[match[2][k]]; + } + } + else if (match[1]) { // positional argument (explicit) + arg = argv[match[1]]; + } + else { // positional argument (implicit) + arg = argv[cursor++]; + } + + if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) { + throw(sprintf('[sprintf] expecting number but found %s', get_type(arg))); + } + + // Jed EDIT + if ( typeof arg == 'undefined' || arg === null ) { + arg = ''; + } + // Jed EDIT + + switch (match[8]) { + case 'b': arg = arg.toString(2); break; + case 'c': arg = String.fromCharCode(arg); break; + case 'd': arg = parseInt(arg, 10); break; + case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break; + case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break; + case 'o': arg = arg.toString(8); break; + case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break; + case 'u': arg = Math.abs(arg); break; + case 'x': arg = arg.toString(16); break; + case 'X': arg = arg.toString(16).toUpperCase(); break; + } + arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg); + pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' '; + pad_length = match[6] - String(arg).length; + pad = match[6] ? str_repeat(pad_character, pad_length) : ''; + output.push(match[5] ? arg + pad : pad + arg); + } + } + return output.join(''); + }; + + str_format.cache = {}; + + str_format.parse = function(fmt) { + var _fmt = fmt, match = [], parse_tree = [], arg_names = 0; + while (_fmt) { + if ((match = /^[^\x25]+/.exec(_fmt)) !== null) { + parse_tree.push(match[0]); + } + else if ((match = /^\x25{2}/.exec(_fmt)) !== null) { + parse_tree.push('%'); + } + else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) { + if (match[2]) { + arg_names |= 1; + var field_list = [], replacement_field = match[2], field_match = []; + if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) { + field_list.push(field_match[1]); + while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') { + if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) { + field_list.push(field_match[1]); + } + else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) { + field_list.push(field_match[1]); + } + else { + throw('[sprintf] huh?'); + } + } + } + else { + throw('[sprintf] huh?'); + } + match[2] = field_list; + } + else { + arg_names |= 2; + } + if (arg_names === 3) { + throw('[sprintf] mixing positional and named placeholders is not (yet) supported'); + } + parse_tree.push(match); + } + else { + throw('[sprintf] huh?'); + } + _fmt = _fmt.substring(match[0].length); + } + return parse_tree; + }; + + return str_format; + })(); + + var vsprintf = function(fmt, argv) { + argv.unshift(fmt); + return sprintf.apply(null, argv); + }; + + Jed.parse_plural = function ( plural_forms, n ) { + plural_forms = plural_forms.replace(/n/g, n); + return Jed.parse_expression(plural_forms); + }; + + Jed.sprintf = function ( fmt, args ) { + if ( {}.toString.call( args ) == '[object Array]' ) { + return vsprintf( fmt, [].slice.call(args) ); + } + return sprintf.apply(this, [].slice.call(arguments) ); + }; + + Jed.prototype.sprintf = function () { + return Jed.sprintf.apply(this, arguments); + }; + // END sprintf Implementation + + // Start the Plural forms section + // This is a full plural form expression parser. It is used to avoid + // running 'eval' or 'new Function' directly against the plural + // forms. + // + // This can be important if you get translations done through a 3rd + // party vendor. I encourage you to use this instead, however, I + // also will provide a 'precompiler' that you can use at build time + // to output valid/safe function representations of the plural form + // expressions. This means you can build this code out for the most + // part. + Jed.PF = {}; + + Jed.PF.parse = function ( p ) { + var plural_str = Jed.PF.extractPluralExpr( p ); + return Jed.PF.parser.parse.call(Jed.PF.parser, plural_str); + }; + + Jed.PF.compile = function ( p ) { + // Handle trues and falses as 0 and 1 + function imply( val ) { + return (val === true ? 1 : val ? val : 0); + } + + var ast = Jed.PF.parse( p ); + return function ( n ) { + return imply( Jed.PF.interpreter( ast )( n ) ); + }; + }; + + Jed.PF.interpreter = function ( ast ) { + return function ( n ) { + var res; + switch ( ast.type ) { + case 'GROUP': + return Jed.PF.interpreter( ast.expr )( n ); + case 'TERNARY': + if ( Jed.PF.interpreter( ast.expr )( n ) ) { + return Jed.PF.interpreter( ast.truthy )( n ); + } + return Jed.PF.interpreter( ast.falsey )( n ); + case 'OR': + return Jed.PF.interpreter( ast.left )( n ) || Jed.PF.interpreter( ast.right )( n ); + case 'AND': + return Jed.PF.interpreter( ast.left )( n ) && Jed.PF.interpreter( ast.right )( n ); + case 'LT': + return Jed.PF.interpreter( ast.left )( n ) < Jed.PF.interpreter( ast.right )( n ); + case 'GT': + return Jed.PF.interpreter( ast.left )( n ) > Jed.PF.interpreter( ast.right )( n ); + case 'LTE': + return Jed.PF.interpreter( ast.left )( n ) <= Jed.PF.interpreter( ast.right )( n ); + case 'GTE': + return Jed.PF.interpreter( ast.left )( n ) >= Jed.PF.interpreter( ast.right )( n ); + case 'EQ': + return Jed.PF.interpreter( ast.left )( n ) == Jed.PF.interpreter( ast.right )( n ); + case 'NEQ': + return Jed.PF.interpreter( ast.left )( n ) != Jed.PF.interpreter( ast.right )( n ); + case 'MOD': + return Jed.PF.interpreter( ast.left )( n ) % Jed.PF.interpreter( ast.right )( n ); + case 'VAR': + return n; + case 'NUM': + return ast.val; + default: + throw new Error("Invalid Token found."); + } + }; + }; + + Jed.PF.extractPluralExpr = function ( p ) { + // trim first + p = p.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); + + if (! /;\s*$/.test(p)) { + p = p.concat(';'); + } + + var nplurals_re = /nplurals\=(\d+);/, + plural_re = /plural\=(.*);/, + nplurals_matches = p.match( nplurals_re ), + res = {}, + plural_matches; + + // Find the nplurals number + if ( nplurals_matches.length > 1 ) { + res.nplurals = nplurals_matches[1]; + } + else { + throw new Error('nplurals not found in plural_forms string: ' + p ); + } + + // remove that data to get to the formula + p = p.replace( nplurals_re, "" ); + plural_matches = p.match( plural_re ); + + if (!( plural_matches && plural_matches.length > 1 ) ) { + throw new Error('`plural` expression not found: ' + p); + } + return plural_matches[ 1 ]; + }; + + /* Jison generated parser */ + Jed.PF.parser = (function(){ + +var parser = {trace: function trace() { }, +yy: {}, +symbols_: {"error":2,"expressions":3,"e":4,"EOF":5,"?":6,":":7,"||":8,"&&":9,"<":10,"<=":11,">":12,">=":13,"!=":14,"==":15,"%":16,"(":17,")":18,"n":19,"NUMBER":20,"$accept":0,"$end":1}, +terminals_: {2:"error",5:"EOF",6:"?",7:":",8:"||",9:"&&",10:"<",11:"<=",12:">",13:">=",14:"!=",15:"==",16:"%",17:"(",18:")",19:"n",20:"NUMBER"}, +productions_: [0,[3,2],[4,5],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,1],[4,1]], +performAction: function anonymous(yytext,yyleng,yylineno,yy,yystate,$$,_$) { + +var $0 = $$.length - 1; +switch (yystate) { +case 1: return { type : 'GROUP', expr: $$[$0-1] }; +break; +case 2:this.$ = { type: 'TERNARY', expr: $$[$0-4], truthy : $$[$0-2], falsey: $$[$0] }; +break; +case 3:this.$ = { type: "OR", left: $$[$0-2], right: $$[$0] }; +break; +case 4:this.$ = { type: "AND", left: $$[$0-2], right: $$[$0] }; +break; +case 5:this.$ = { type: 'LT', left: $$[$0-2], right: $$[$0] }; +break; +case 6:this.$ = { type: 'LTE', left: $$[$0-2], right: $$[$0] }; +break; +case 7:this.$ = { type: 'GT', left: $$[$0-2], right: $$[$0] }; +break; +case 8:this.$ = { type: 'GTE', left: $$[$0-2], right: $$[$0] }; +break; +case 9:this.$ = { type: 'NEQ', left: $$[$0-2], right: $$[$0] }; +break; +case 10:this.$ = { type: 'EQ', left: $$[$0-2], right: $$[$0] }; +break; +case 11:this.$ = { type: 'MOD', left: $$[$0-2], right: $$[$0] }; +break; +case 12:this.$ = { type: 'GROUP', expr: $$[$0-1] }; +break; +case 13:this.$ = { type: 'VAR' }; +break; +case 14:this.$ = { type: 'NUM', val: Number(yytext) }; +break; +} +}, +table: [{3:1,4:2,17:[1,3],19:[1,4],20:[1,5]},{1:[3]},{5:[1,6],6:[1,7],8:[1,8],9:[1,9],10:[1,10],11:[1,11],12:[1,12],13:[1,13],14:[1,14],15:[1,15],16:[1,16]},{4:17,17:[1,3],19:[1,4],20:[1,5]},{5:[2,13],6:[2,13],7:[2,13],8:[2,13],9:[2,13],10:[2,13],11:[2,13],12:[2,13],13:[2,13],14:[2,13],15:[2,13],16:[2,13],18:[2,13]},{5:[2,14],6:[2,14],7:[2,14],8:[2,14],9:[2,14],10:[2,14],11:[2,14],12:[2,14],13:[2,14],14:[2,14],15:[2,14],16:[2,14],18:[2,14]},{1:[2,1]},{4:18,17:[1,3],19:[1,4],20:[1,5]},{4:19,17:[1,3],19:[1,4],20:[1,5]},{4:20,17:[1,3],19:[1,4],20:[1,5]},{4:21,17:[1,3],19:[1,4],20:[1,5]},{4:22,17:[1,3],19:[1,4],20:[1,5]},{4:23,17:[1,3],19:[1,4],20:[1,5]},{4:24,17:[1,3],19:[1,4],20:[1,5]},{4:25,17:[1,3],19:[1,4],20:[1,5]},{4:26,17:[1,3],19:[1,4],20:[1,5]},{4:27,17:[1,3],19:[1,4],20:[1,5]},{6:[1,7],8:[1,8],9:[1,9],10:[1,10],11:[1,11],12:[1,12],13:[1,13],14:[1,14],15:[1,15],16:[1,16],18:[1,28]},{6:[1,7],7:[1,29],8:[1,8],9:[1,9],10:[1,10],11:[1,11],12:[1,12],13:[1,13],14:[1,14],15:[1,15],16:[1,16]},{5:[2,3],6:[2,3],7:[2,3],8:[2,3],9:[1,9],10:[1,10],11:[1,11],12:[1,12],13:[1,13],14:[1,14],15:[1,15],16:[1,16],18:[2,3]},{5:[2,4],6:[2,4],7:[2,4],8:[2,4],9:[2,4],10:[1,10],11:[1,11],12:[1,12],13:[1,13],14:[1,14],15:[1,15],16:[1,16],18:[2,4]},{5:[2,5],6:[2,5],7:[2,5],8:[2,5],9:[2,5],10:[2,5],11:[2,5],12:[2,5],13:[2,5],14:[2,5],15:[2,5],16:[1,16],18:[2,5]},{5:[2,6],6:[2,6],7:[2,6],8:[2,6],9:[2,6],10:[2,6],11:[2,6],12:[2,6],13:[2,6],14:[2,6],15:[2,6],16:[1,16],18:[2,6]},{5:[2,7],6:[2,7],7:[2,7],8:[2,7],9:[2,7],10:[2,7],11:[2,7],12:[2,7],13:[2,7],14:[2,7],15:[2,7],16:[1,16],18:[2,7]},{5:[2,8],6:[2,8],7:[2,8],8:[2,8],9:[2,8],10:[2,8],11:[2,8],12:[2,8],13:[2,8],14:[2,8],15:[2,8],16:[1,16],18:[2,8]},{5:[2,9],6:[2,9],7:[2,9],8:[2,9],9:[2,9],10:[2,9],11:[2,9],12:[2,9],13:[2,9],14:[2,9],15:[2,9],16:[1,16],18:[2,9]},{5:[2,10],6:[2,10],7:[2,10],8:[2,10],9:[2,10],10:[2,10],11:[2,10],12:[2,10],13:[2,10],14:[2,10],15:[2,10],16:[1,16],18:[2,10]},{5:[2,11],6:[2,11],7:[2,11],8:[2,11],9:[2,11],10:[2,11],11:[2,11],12:[2,11],13:[2,11],14:[2,11],15:[2,11],16:[2,11],18:[2,11]},{5:[2,12],6:[2,12],7:[2,12],8:[2,12],9:[2,12],10:[2,12],11:[2,12],12:[2,12],13:[2,12],14:[2,12],15:[2,12],16:[2,12],18:[2,12]},{4:30,17:[1,3],19:[1,4],20:[1,5]},{5:[2,2],6:[1,7],7:[2,2],8:[1,8],9:[1,9],10:[1,10],11:[1,11],12:[1,12],13:[1,13],14:[1,14],15:[1,15],16:[1,16],18:[2,2]}], +defaultActions: {6:[2,1]}, +parseError: function parseError(str, hash) { + throw new Error(str); +}, +parse: function parse(input) { + var self = this, + stack = [0], + vstack = [null], // semantic value stack + lstack = [], // location stack + table = this.table, + yytext = '', + yylineno = 0, + yyleng = 0, + recovering = 0, + TERROR = 2, + EOF = 1; + + //this.reductionCount = this.shiftCount = 0; + + this.lexer.setInput(input); + this.lexer.yy = this.yy; + this.yy.lexer = this.lexer; + if (typeof this.lexer.yylloc == 'undefined') + this.lexer.yylloc = {}; + var yyloc = this.lexer.yylloc; + lstack.push(yyloc); + + if (typeof this.yy.parseError === 'function') + this.parseError = this.yy.parseError; + + function popStack (n) { + stack.length = stack.length - 2*n; + vstack.length = vstack.length - n; + lstack.length = lstack.length - n; + } + + function lex() { + var token; + token = self.lexer.lex() || 1; // $end = 1 + // if token isn't its numeric value, convert + if (typeof token !== 'number') { + token = self.symbols_[token] || token; + } + return token; + } + + var symbol, preErrorSymbol, state, action, a, r, yyval={},p,len,newState, expected; + while (true) { + // retreive state number from top of stack + state = stack[stack.length-1]; + + // use default actions if available + if (this.defaultActions[state]) { + action = this.defaultActions[state]; + } else { + if (symbol == null) + symbol = lex(); + // read action for current state and first input + action = table[state] && table[state][symbol]; + } + + // handle parse error + _handle_error: + if (typeof action === 'undefined' || !action.length || !action[0]) { + + if (!recovering) { + // Report error + expected = []; + for (p in table[state]) if (this.terminals_[p] && p > 2) { + expected.push("'"+this.terminals_[p]+"'"); + } + var errStr = ''; + if (this.lexer.showPosition) { + errStr = 'Parse error on line '+(yylineno+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+expected.join(', ') + ", got '" + this.terminals_[symbol]+ "'"; + } else { + errStr = 'Parse error on line '+(yylineno+1)+": Unexpected " + + (symbol == 1 /*EOF*/ ? "end of input" : + ("'"+(this.terminals_[symbol] || symbol)+"'")); + } + this.parseError(errStr, + {text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected}); + } + + // just recovered from another error + if (recovering == 3) { + if (symbol == EOF) { + throw new Error(errStr || 'Parsing halted.'); + } + + // discard current lookahead and grab another + yyleng = this.lexer.yyleng; + yytext = this.lexer.yytext; + yylineno = this.lexer.yylineno; + yyloc = this.lexer.yylloc; + symbol = lex(); + } + + // try to recover from error + while (1) { + // check for error recovery rule in this state + if ((TERROR.toString()) in table[state]) { + break; + } + if (state == 0) { + throw new Error(errStr || 'Parsing halted.'); + } + popStack(1); + state = stack[stack.length-1]; + } + + preErrorSymbol = symbol; // save the lookahead token + symbol = TERROR; // insert generic error symbol as new lookahead + state = stack[stack.length-1]; + action = table[state] && table[state][TERROR]; + recovering = 3; // allow 3 real symbols to be shifted before reporting a new error + } + + // this shouldn't happen, unless resolve defaults are off + if (action[0] instanceof Array && action.length > 1) { + throw new Error('Parse Error: multiple actions possible at state: '+state+', token: '+symbol); + } + + switch (action[0]) { + + case 1: // shift + //this.shiftCount++; + + stack.push(symbol); + vstack.push(this.lexer.yytext); + lstack.push(this.lexer.yylloc); + stack.push(action[1]); // push state + symbol = null; + if (!preErrorSymbol) { // normal execution/no error + yyleng = this.lexer.yyleng; + yytext = this.lexer.yytext; + yylineno = this.lexer.yylineno; + yyloc = this.lexer.yylloc; + if (recovering > 0) + recovering--; + } else { // error just occurred, resume old lookahead f/ before error + symbol = preErrorSymbol; + preErrorSymbol = null; + } + break; + + case 2: // reduce + //this.reductionCount++; + + len = this.productions_[action[1]][1]; + + // perform semantic action + yyval.$ = vstack[vstack.length-len]; // default to $$ = $1 + // default location, uses first token for firsts, last for lasts + yyval._$ = { + first_line: lstack[lstack.length-(len||1)].first_line, + last_line: lstack[lstack.length-1].last_line, + first_column: lstack[lstack.length-(len||1)].first_column, + last_column: lstack[lstack.length-1].last_column + }; + r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack); + + if (typeof r !== 'undefined') { + return r; + } + + // pop off stack + if (len) { + stack = stack.slice(0,-1*len*2); + vstack = vstack.slice(0, -1*len); + lstack = lstack.slice(0, -1*len); + } + + stack.push(this.productions_[action[1]][0]); // push nonterminal (reduce) + vstack.push(yyval.$); + lstack.push(yyval._$); + // goto new state = table[STATE][NONTERMINAL] + newState = table[stack[stack.length-2]][stack[stack.length-1]]; + stack.push(newState); + break; + + case 3: // accept + return true; + } + + } + + return true; +}};/* Jison generated lexer */ +var lexer = (function(){ + +var lexer = ({EOF:1, +parseError:function parseError(str, hash) { + if (this.yy.parseError) { + this.yy.parseError(str, hash); + } else { + throw new Error(str); + } + }, +setInput:function (input) { + this._input = input; + this._more = this._less = this.done = false; + this.yylineno = this.yyleng = 0; + this.yytext = this.matched = this.match = ''; + this.conditionStack = ['INITIAL']; + this.yylloc = {first_line:1,first_column:0,last_line:1,last_column:0}; + return this; + }, +input:function () { + var ch = this._input[0]; + this.yytext+=ch; + this.yyleng++; + this.match+=ch; + this.matched+=ch; + var lines = ch.match(/\n/); + if (lines) this.yylineno++; + this._input = this._input.slice(1); + return ch; + }, +unput:function (ch) { + this._input = ch + this._input; + return this; + }, +more:function () { + this._more = true; + return this; + }, +pastInput:function () { + var past = this.matched.substr(0, this.matched.length - this.match.length); + return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\n/g, ""); + }, +upcomingInput:function () { + var next = this.match; + if (next.length < 20) { + next += this._input.substr(0, 20-next.length); + } + return (next.substr(0,20)+(next.length > 20 ? '...':'')).replace(/\n/g, ""); + }, +showPosition:function () { + var pre = this.pastInput(); + var c = new Array(pre.length + 1).join("-"); + return pre + this.upcomingInput() + "\n" + c+"^"; + }, +next:function () { + if (this.done) { + return this.EOF; + } + if (!this._input) this.done = true; + + var token, + match, + col, + lines; + if (!this._more) { + this.yytext = ''; + this.match = ''; + } + var rules = this._currentRules(); + for (var i=0;i < rules.length; i++) { + match = this._input.match(this.rules[rules[i]]); + if (match) { + lines = match[0].match(/\n.*/g); + if (lines) this.yylineno += lines.length; + this.yylloc = {first_line: this.yylloc.last_line, + last_line: this.yylineno+1, + first_column: this.yylloc.last_column, + last_column: lines ? lines[lines.length-1].length-1 : this.yylloc.last_column + match[0].length} + this.yytext += match[0]; + this.match += match[0]; + this.matches = match; + this.yyleng = this.yytext.length; + this._more = false; + this._input = this._input.slice(match[0].length); + this.matched += match[0]; + token = this.performAction.call(this, this.yy, this, rules[i],this.conditionStack[this.conditionStack.length-1]); + if (token) return token; + else return; + } + } + if (this._input === "") { + return this.EOF; + } else { + this.parseError('Lexical error on line '+(this.yylineno+1)+'. Unrecognized text.\n'+this.showPosition(), + {text: "", token: null, line: this.yylineno}); + } + }, +lex:function lex() { + var r = this.next(); + if (typeof r !== 'undefined') { + return r; + } else { + return this.lex(); + } + }, +begin:function begin(condition) { + this.conditionStack.push(condition); + }, +popState:function popState() { + return this.conditionStack.pop(); + }, +_currentRules:function _currentRules() { + return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules; + }, +topState:function () { + return this.conditionStack[this.conditionStack.length-2]; + }, +pushState:function begin(condition) { + this.begin(condition); + }}); +lexer.performAction = function anonymous(yy,yy_,$avoiding_name_collisions,YY_START) { + +var YYSTATE=YY_START; +switch($avoiding_name_collisions) { +case 0:/* skip whitespace */ +break; +case 1:return 20 +break; +case 2:return 19 +break; +case 3:return 8 +break; +case 4:return 9 +break; +case 5:return 6 +break; +case 6:return 7 +break; +case 7:return 11 +break; +case 8:return 13 +break; +case 9:return 10 +break; +case 10:return 12 +break; +case 11:return 14 +break; +case 12:return 15 +break; +case 13:return 16 +break; +case 14:return 17 +break; +case 15:return 18 +break; +case 16:return 5 +break; +case 17:return 'INVALID' +break; +} +}; +lexer.rules = [/^\s+/,/^[0-9]+(\.[0-9]+)?\b/,/^n\b/,/^\|\|/,/^&&/,/^\?/,/^:/,/^<=/,/^>=/,/^/,/^!=/,/^==/,/^%/,/^\(/,/^\)/,/^$/,/^./]; +lexer.conditions = {"INITIAL":{"rules":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17],"inclusive":true}};return lexer;})() +parser.lexer = lexer; +return parser; +})(); +// End parser + + // Handle node, amd, and global systems + if (true) { + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = Jed; + } + exports.Jed = Jed; + } + else {} + +})(this); + + +/***/ }), + +/***/ "./node_modules/lodash/_Symbol.js": +/*!****************************************!*\ + !*** ./node_modules/lodash/_Symbol.js ***! + \****************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +var root = __webpack_require__(/*! ./_root */ "./node_modules/lodash/_root.js"); + +/** Built-in value references. */ +var Symbol = root.Symbol; + +module.exports = Symbol; + + +/***/ }), + +/***/ "./node_modules/lodash/_arrayMap.js": +/*!******************************************!*\ + !*** ./node_modules/lodash/_arrayMap.js ***! + \******************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +/** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ +function arrayMap(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; +} + +module.exports = arrayMap; + + +/***/ }), + +/***/ "./node_modules/lodash/_baseGetTag.js": +/*!********************************************!*\ + !*** ./node_modules/lodash/_baseGetTag.js ***! + \********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +var Symbol = __webpack_require__(/*! ./_Symbol */ "./node_modules/lodash/_Symbol.js"), + getRawTag = __webpack_require__(/*! ./_getRawTag */ "./node_modules/lodash/_getRawTag.js"), + objectToString = __webpack_require__(/*! ./_objectToString */ "./node_modules/lodash/_objectToString.js"); + +/** `Object#toString` result references. */ +var nullTag = '[object Null]', + undefinedTag = '[object Undefined]'; + +/** Built-in value references. */ +var symToStringTag = Symbol ? Symbol.toStringTag : undefined; + +/** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag && symToStringTag in Object(value)) + ? getRawTag(value) + : objectToString(value); +} + +module.exports = baseGetTag; + + +/***/ }), + +/***/ "./node_modules/lodash/_basePropertyOf.js": +/*!************************************************!*\ + !*** ./node_modules/lodash/_basePropertyOf.js ***! + \************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +/** + * The base implementation of `_.propertyOf` without support for deep paths. + * + * @private + * @param {Object} object The object to query. + * @returns {Function} Returns the new accessor function. + */ +function basePropertyOf(object) { + return function(key) { + return object == null ? undefined : object[key]; + }; +} + +module.exports = basePropertyOf; + + +/***/ }), + +/***/ "./node_modules/lodash/_baseToString.js": +/*!**********************************************!*\ + !*** ./node_modules/lodash/_baseToString.js ***! + \**********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +var Symbol = __webpack_require__(/*! ./_Symbol */ "./node_modules/lodash/_Symbol.js"), + arrayMap = __webpack_require__(/*! ./_arrayMap */ "./node_modules/lodash/_arrayMap.js"), + isArray = __webpack_require__(/*! ./isArray */ "./node_modules/lodash/isArray.js"), + isSymbol = __webpack_require__(/*! ./isSymbol */ "./node_modules/lodash/isSymbol.js"); + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0; + +/** Used to convert symbols to primitives and strings. */ +var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; + +/** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ +function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isArray(value)) { + // Recursively convert values (susceptible to call stack limits). + return arrayMap(value, baseToString) + ''; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; +} + +module.exports = baseToString; + + +/***/ }), + +/***/ "./node_modules/lodash/_escapeHtmlChar.js": +/*!************************************************!*\ + !*** ./node_modules/lodash/_escapeHtmlChar.js ***! + \************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +var basePropertyOf = __webpack_require__(/*! ./_basePropertyOf */ "./node_modules/lodash/_basePropertyOf.js"); + +/** Used to map characters to HTML entities. */ +var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' +}; + +/** + * Used by `_.escape` to convert characters to HTML entities. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ +var escapeHtmlChar = basePropertyOf(htmlEscapes); + +module.exports = escapeHtmlChar; + + +/***/ }), + +/***/ "./node_modules/lodash/_freeGlobal.js": +/*!********************************************!*\ + !*** ./node_modules/lodash/_freeGlobal.js ***! + \********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(global) {/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + +module.exports = freeGlobal; + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js"))) + +/***/ }), + +/***/ "./node_modules/lodash/_getRawTag.js": +/*!*******************************************!*\ + !*** ./node_modules/lodash/_getRawTag.js ***! + \*******************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +var Symbol = __webpack_require__(/*! ./_Symbol */ "./node_modules/lodash/_Symbol.js"); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString = objectProto.toString; + +/** Built-in value references. */ +var symToStringTag = Symbol ? Symbol.toStringTag : undefined; + +/** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ +function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; + + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; +} + +module.exports = getRawTag; + + +/***/ }), + +/***/ "./node_modules/lodash/_objectToString.js": +/*!************************************************!*\ + !*** ./node_modules/lodash/_objectToString.js ***! + \************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString = objectProto.toString; + +/** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ +function objectToString(value) { + return nativeObjectToString.call(value); +} + +module.exports = objectToString; + + +/***/ }), + +/***/ "./node_modules/lodash/_root.js": +/*!**************************************!*\ + !*** ./node_modules/lodash/_root.js ***! + \**************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +var freeGlobal = __webpack_require__(/*! ./_freeGlobal */ "./node_modules/lodash/_freeGlobal.js"); + +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); + +module.exports = root; + + +/***/ }), + +/***/ "./node_modules/lodash/escape.js": +/*!***************************************!*\ + !*** ./node_modules/lodash/escape.js ***! + \***************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +var escapeHtmlChar = __webpack_require__(/*! ./_escapeHtmlChar */ "./node_modules/lodash/_escapeHtmlChar.js"), + toString = __webpack_require__(/*! ./toString */ "./node_modules/lodash/toString.js"); + +/** Used to match HTML entities and HTML characters. */ +var reUnescapedHtml = /[&<>"']/g, + reHasUnescapedHtml = RegExp(reUnescapedHtml.source); + +/** + * Converts the characters "&", "<", ">", '"', and "'" in `string` to their + * corresponding HTML entities. + * + * **Note:** No other characters are escaped. To escape additional + * characters use a third-party library like [_he_](https://mths.be/he). + * + * Though the ">" character is escaped for symmetry, characters like + * ">" and "/" don't need escaping in HTML and have no special meaning + * unless they're part of a tag or unquoted attribute value. See + * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) + * (under "semi-related fun fact") for more details. + * + * When working with HTML you should always + * [quote attribute values](http://wonko.com/post/html-escaping) to reduce + * XSS vectors. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escape('fred, barney, & pebbles'); + * // => 'fred, barney, & pebbles' + */ +function escape(string) { + string = toString(string); + return (string && reHasUnescapedHtml.test(string)) + ? string.replace(reUnescapedHtml, escapeHtmlChar) + : string; +} + +module.exports = escape; + + +/***/ }), + +/***/ "./node_modules/lodash/isArray.js": +/*!****************************************!*\ + !*** ./node_modules/lodash/isArray.js ***! + \****************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +module.exports = isArray; + + +/***/ }), + +/***/ "./node_modules/lodash/isObjectLike.js": +/*!*********************************************!*\ + !*** ./node_modules/lodash/isObjectLike.js ***! + \*********************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return value != null && typeof value == 'object'; +} + +module.exports = isObjectLike; + + +/***/ }), + +/***/ "./node_modules/lodash/isSymbol.js": +/*!*****************************************!*\ + !*** ./node_modules/lodash/isSymbol.js ***! + \*****************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +var baseGetTag = __webpack_require__(/*! ./_baseGetTag */ "./node_modules/lodash/_baseGetTag.js"), + isObjectLike = __webpack_require__(/*! ./isObjectLike */ "./node_modules/lodash/isObjectLike.js"); + +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && baseGetTag(value) == symbolTag); +} + +module.exports = isSymbol; + + +/***/ }), + +/***/ "./node_modules/lodash/lodash.js": +/*!***************************************!*\ + !*** ./node_modules/lodash/lodash.js ***! + \***************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(global, module) {var __WEBPACK_AMD_DEFINE_RESULT__;/** * @license * Lodash * Copyright JS Foundation and other contributors * Released under MIT license * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */(function(){var o,r=200,s="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",c="Expected a function",i="__lodash_hash_undefined__",u=500,_="__lodash_placeholder__",d=1,l=2,h=4,m=1,g=2,p=1,b=2,y=4,v=8,w=16,k=32,M=64,L=128,x=256,S=512,T=30,D="...",Y=800,j=16,A=1,C=2,E=1/0,H=9007199254740991,N=1.7976931348623157e308,O=NaN,R=4294967295,I=R-1,P=R>>>1,z=[["ary",L],["bind",p],["bindKey",b],["curry",v],["curryRight",w],["flip",S],["partial",k],["partialRight",M],["rearg",x]],F="[object Arguments]",B="[object Array]",q="[object AsyncFunction]",U="[object Boolean]",W="[object Date]",J="[object DOMException]",$="[object Error]",V="[object Function]",G="[object GeneratorFunction]",Q="[object Map]",X="[object Number]",K="[object Null]",Z="[object Object]",ee="[object Proxy]",te="[object RegExp]",fe="[object Set]",ae="[object String]",ne="[object Symbol]",oe="[object Undefined]",re="[object WeakMap]",se="[object WeakSet]",ce="[object ArrayBuffer]",ie="[object DataView]",ue="[object Float32Array]",_e="[object Float64Array]",de="[object Int8Array]",le="[object Int16Array]",he="[object Int32Array]",me="[object Uint8Array]",ge="[object Uint8ClampedArray]",pe="[object Uint16Array]",be="[object Uint32Array]",ye=/\b__p \+= '';/g,ve=/\b(__p \+=) '' \+/g,we=/(__e\(.*?\)|\b__t\)) \+\n'';/g,ke=/&(?:amp|lt|gt|quot|#39);/g,Me=/[&<>"']/g,Le=RegExp(ke.source),xe=RegExp(Me.source),Se=/<%-([\s\S]+?)%>/g,Te=/<%([\s\S]+?)%>/g,De=/<%=([\s\S]+?)%>/g,Ye=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,je=/^\w*$/,Ae=/^\./,Ce=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Ee=/[\\^$.*+?()[\]{}|]/g,He=RegExp(Ee.source),Ne=/^\s+|\s+$/g,Oe=/^\s+/,Re=/\s+$/,Ie=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,Pe=/\{\n\/\* \[wrapped with (.+)\] \*/,ze=/,? & /,Fe=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,Be=/\\(\\)?/g,qe=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,Ue=/\w*$/,We=/^[-+]0x[0-9a-f]+$/i,Je=/^0b[01]+$/i,$e=/^\[object .+?Constructor\]$/,Ve=/^0o[0-7]+$/i,Ge=/^(?:0|[1-9]\d*)$/,Qe=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Xe=/($^)/,Ke=/['\n\r\u2028\u2029\\]/g,Ze="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",et="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",tt="[\\ud800-\\udfff]",ft="["+et+"]",at="["+Ze+"]",nt="\\d+",ot="[\\u2700-\\u27bf]",rt="[a-z\\xdf-\\xf6\\xf8-\\xff]",st="[^\\ud800-\\udfff"+et+nt+"\\u2700-\\u27bfa-z\\xdf-\\xf6\\xf8-\\xffA-Z\\xc0-\\xd6\\xd8-\\xde]",ct="\\ud83c[\\udffb-\\udfff]",it="[^\\ud800-\\udfff]",ut="(?:\\ud83c[\\udde6-\\uddff]){2}",_t="[\\ud800-\\udbff][\\udc00-\\udfff]",dt="[A-Z\\xc0-\\xd6\\xd8-\\xde]",lt="(?:"+rt+"|"+st+")",ht="(?:"+dt+"|"+st+")",mt="(?:"+at+"|"+ct+")"+"?",gt="[\\ufe0e\\ufe0f]?"+mt+("(?:\\u200d(?:"+[it,ut,_t].join("|")+")[\\ufe0e\\ufe0f]?"+mt+")*"),pt="(?:"+[ot,ut,_t].join("|")+")"+gt,bt="(?:"+[it+at+"?",at,ut,_t,tt].join("|")+")",yt=RegExp("['’]","g"),vt=RegExp(at,"g"),wt=RegExp(ct+"(?="+ct+")|"+bt+gt,"g"),kt=RegExp([dt+"?"+rt+"+(?:['’](?:d|ll|m|re|s|t|ve))?(?="+[ft,dt,"$"].join("|")+")",ht+"+(?:['’](?:D|LL|M|RE|S|T|VE))?(?="+[ft,dt+lt,"$"].join("|")+")",dt+"?"+lt+"+(?:['’](?:d|ll|m|re|s|t|ve))?",dt+"+(?:['’](?:D|LL|M|RE|S|T|VE))?","\\d*(?:(?:1ST|2ND|3RD|(?![123])\\dTH)\\b)","\\d*(?:(?:1st|2nd|3rd|(?![123])\\dth)\\b)",nt,pt].join("|"),"g"),Mt=RegExp("[\\u200d\\ud800-\\udfff"+Ze+"\\ufe0e\\ufe0f]"),Lt=/[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,xt=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],St=-1,Tt={};Tt[ue]=Tt[_e]=Tt[de]=Tt[le]=Tt[he]=Tt[me]=Tt[ge]=Tt[pe]=Tt[be]=!0,Tt[F]=Tt[B]=Tt[ce]=Tt[U]=Tt[ie]=Tt[W]=Tt[$]=Tt[V]=Tt[Q]=Tt[X]=Tt[Z]=Tt[te]=Tt[fe]=Tt[ae]=Tt[re]=!1;var Dt={};Dt[F]=Dt[B]=Dt[ce]=Dt[ie]=Dt[U]=Dt[W]=Dt[ue]=Dt[_e]=Dt[de]=Dt[le]=Dt[he]=Dt[Q]=Dt[X]=Dt[Z]=Dt[te]=Dt[fe]=Dt[ae]=Dt[ne]=Dt[me]=Dt[ge]=Dt[pe]=Dt[be]=!0,Dt[$]=Dt[V]=Dt[re]=!1;var Yt={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},jt=parseFloat,At=parseInt,Ct="object"==typeof e&&e&&e.Object===Object&&e,Et="object"==typeof self&&self&&self.Object===Object&&self,Ht=Ct||Et||Function("return this")(),Nt="object"==typeof t&&t&&!t.nodeType&&t,Ot=Nt&&"object"==typeof a&&a&&!a.nodeType&&a,Rt=Ot&&Ot.exports===Nt,It=Rt&&Ct.process,Pt=function(){try{return It&&It.binding&&It.binding("util")}catch(e){}}(),zt=Pt&&Pt.isArrayBuffer,Ft=Pt&&Pt.isDate,Bt=Pt&&Pt.isMap,qt=Pt&&Pt.isRegExp,Ut=Pt&&Pt.isSet,Wt=Pt&&Pt.isTypedArray;function Jt(e,t){return e.set(t[0],t[1]),e}function $t(e,t){return e.add(t),e}function Vt(e,t,f){switch(f.length){case 0:return e.call(t);case 1:return e.call(t,f[0]);case 2:return e.call(t,f[0],f[1]);case 3:return e.call(t,f[0],f[1],f[2])}return e.apply(t,f)}function Gt(e,t,f,a){for(var n=-1,o=null==e?0:e.length;++n-1}function tf(e,t,f){for(var a=-1,n=null==e?0:e.length;++a-1;);return f}function Lf(e,t){for(var f=e.length;f--&&_f(t,e[f],0)>-1;);return f}var xf=gf({"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"}),Sf=gf({"&":"&","<":"<",">":">",'"':""","'":"'"});function Tf(e){return"\\"+Yt[e]}function Df(e){return Mt.test(e)}function Yf(e){var t=-1,f=Array(e.size);return e.forEach(function(e,a){f[++t]=[a,e]}),f}function jf(e,t){return function(f){return e(t(f))}}function Af(e,t){for(var f=-1,a=e.length,n=0,o=[];++f",""":'"',"'":"'"});var Rf=function e(t){var f,a=(t=null==t?Ht:Rf.defaults(Ht.Object(),t,Rf.pick(Ht,xt))).Array,n=t.Date,Ze=t.Error,et=t.Function,tt=t.Math,ft=t.Object,at=t.RegExp,nt=t.String,ot=t.TypeError,rt=a.prototype,st=et.prototype,ct=ft.prototype,it=t["__core-js_shared__"],ut=st.toString,_t=ct.hasOwnProperty,dt=0,lt=(f=/[^.]+$/.exec(it&&it.keys&&it.keys.IE_PROTO||""))?"Symbol(src)_1."+f:"",ht=ct.toString,mt=ut.call(ft),gt=Ht._,pt=at("^"+ut.call(_t).replace(Ee,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),bt=Rt?t.Buffer:o,wt=t.Symbol,Mt=t.Uint8Array,Yt=bt?bt.allocUnsafe:o,Ct=jf(ft.getPrototypeOf,ft),Et=ft.create,Nt=ct.propertyIsEnumerable,Ot=rt.splice,It=wt?wt.isConcatSpreadable:o,Pt=wt?wt.iterator:o,sf=wt?wt.toStringTag:o,gf=function(){try{var e=qo(ft,"defineProperty");return e({},"",{}),e}catch(e){}}(),If=t.clearTimeout!==Ht.clearTimeout&&t.clearTimeout,Pf=n&&n.now!==Ht.Date.now&&n.now,zf=t.setTimeout!==Ht.setTimeout&&t.setTimeout,Ff=tt.ceil,Bf=tt.floor,qf=ft.getOwnPropertySymbols,Uf=bt?bt.isBuffer:o,Wf=t.isFinite,Jf=rt.join,$f=jf(ft.keys,ft),Vf=tt.max,Gf=tt.min,Qf=n.now,Xf=t.parseInt,Kf=tt.random,Zf=rt.reverse,ea=qo(t,"DataView"),ta=qo(t,"Map"),fa=qo(t,"Promise"),aa=qo(t,"Set"),na=qo(t,"WeakMap"),oa=qo(ft,"create"),ra=na&&new na,sa={},ca=hr(ea),ia=hr(ta),ua=hr(fa),_a=hr(aa),da=hr(na),la=wt?wt.prototype:o,ha=la?la.valueOf:o,ma=la?la.toString:o;function ga(e){if(As(e)&&!vs(e)&&!(e instanceof va)){if(e instanceof ya)return e;if(_t.call(e,"__wrapped__"))return mr(e)}return new ya(e)}var pa=function(){function e(){}return function(t){if(!js(t))return{};if(Et)return Et(t);e.prototype=t;var f=new e;return e.prototype=o,f}}();function ba(){}function ya(e,t){this.__wrapped__=e,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=o}function va(e){this.__wrapped__=e,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=R,this.__views__=[]}function wa(e){var t=-1,f=null==e?0:e.length;for(this.clear();++t=t?e:t)),e}function Ia(e,t,f,a,n,r){var s,c=t&d,i=t&l,u=t&h;if(f&&(s=n?f(e,a,n,r):f(e)),s!==o)return s;if(!js(e))return e;var _=vs(e);if(_){if(s=function(e){var t=e.length,f=e.constructor(t);return t&&"string"==typeof e[0]&&_t.call(e,"index")&&(f.index=e.index,f.input=e.input),f}(e),!c)return ro(e,s)}else{var m=Jo(e),g=m==V||m==G;if(Ls(e))return eo(e,c);if(m==Z||m==F||g&&!n){if(s=i||g?{}:Vo(e),!c)return i?function(e,t){return so(e,Wo(e),t)}(e,function(e,t){return e&&so(t,cc(t),e)}(s,e)):function(e,t){return so(e,Uo(e),t)}(e,Ha(s,e))}else{if(!Dt[m])return n?e:{};s=function(e,t,f,a){var n,o,r,s=e.constructor;switch(t){case ce:return to(e);case U:case W:return new s(+e);case ie:return function(e,t){var f=t?to(e.buffer):e.buffer;return new e.constructor(f,e.byteOffset,e.byteLength)}(e,a);case ue:case _e:case de:case le:case he:case me:case ge:case pe:case be:return fo(e,a);case Q:return function(e,t,f){return nf(t?f(Yf(e),d):Yf(e),Jt,new e.constructor)}(e,a,f);case X:case ae:return new s(e);case te:return(r=new(o=e).constructor(o.source,Ue.exec(o))).lastIndex=o.lastIndex,r;case fe:return function(e,t,f){return nf(t?f(Cf(e),d):Cf(e),$t,new e.constructor)}(e,a,f);case ne:return n=e,ha?ft(ha.call(n)):{}}}(e,m,Ia,c)}}r||(r=new xa);var p=r.get(e);if(p)return p;r.set(e,s);var b=_?o:(u?i?Oo:No:i?cc:sc)(e);return Qt(b||e,function(a,n){b&&(a=e[n=a]),Aa(s,n,Ia(a,t,f,n,e,r))}),s}function Pa(e,t,f){var a=f.length;if(null==e)return!a;for(e=ft(e);a--;){var n=f[a],r=t[n],s=e[n];if(s===o&&!(n in e)||!r(s))return!1}return!0}function za(e,t,f){if("function"!=typeof e)throw new ot(c);return sr(function(){e.apply(o,f)},t)}function Fa(e,t,f,a){var n=-1,o=ef,s=!0,c=e.length,i=[],u=t.length;if(!c)return i;f&&(t=ff(t,vf(f))),a?(o=tf,s=!1):t.length>=r&&(o=kf,s=!1,t=new La(t));e:for(;++n-1},ka.prototype.set=function(e,t){var f=this.__data__,a=Ca(f,e);return a<0?(++this.size,f.push([e,t])):f[a][1]=t,this},Ma.prototype.clear=function(){this.size=0,this.__data__={hash:new wa,map:new(ta||ka),string:new wa}},Ma.prototype.delete=function(e){var t=Fo(this,e).delete(e);return this.size-=t?1:0,t},Ma.prototype.get=function(e){return Fo(this,e).get(e)},Ma.prototype.has=function(e){return Fo(this,e).has(e)},Ma.prototype.set=function(e,t){var f=Fo(this,e),a=f.size;return f.set(e,t),this.size+=f.size==a?0:1,this},La.prototype.add=La.prototype.push=function(e){return this.__data__.set(e,i),this},La.prototype.has=function(e){return this.__data__.has(e)},xa.prototype.clear=function(){this.__data__=new ka,this.size=0},xa.prototype.delete=function(e){var t=this.__data__,f=t.delete(e);return this.size=t.size,f},xa.prototype.get=function(e){return this.__data__.get(e)},xa.prototype.has=function(e){return this.__data__.has(e)},xa.prototype.set=function(e,t){var f=this.__data__;if(f instanceof ka){var a=f.__data__;if(!ta||a.length0&&f(s)?t>1?$a(s,t-1,f,a,n):af(n,s):a||(n[n.length]=s)}return n}var Va=_o(),Ga=_o(!0);function Qa(e,t){return e&&Va(e,t,sc)}function Xa(e,t){return e&&Ga(e,t,sc)}function Ka(e,t){return Zt(t,function(t){return Ts(e[t])})}function Za(e,t){for(var f=0,a=(t=Qn(t,e)).length;null!=e&&ft}function an(e,t){return null!=e&&_t.call(e,t)}function nn(e,t){return null!=e&&t in ft(e)}function on(e,t,f){for(var n=f?tf:ef,r=e[0].length,s=e.length,c=s,i=a(s),u=1/0,_=[];c--;){var d=e[c];c&&t&&(d=ff(d,vf(t))),u=Gf(d.length,u),i[c]=!f&&(t||r>=120&&d.length>=120)?new La(c&&d):o}d=e[0];var l=-1,h=i[0];e:for(;++l=s)return c;var i=f[a];return c*("desc"==i?-1:1)}}return e.index-t.index}(e,t,f)})}function kn(e,t,f){for(var a=-1,n=t.length,o={};++a-1;)s!==e&&Ot.call(s,c,1),Ot.call(e,c,1);return e}function Ln(e,t){for(var f=e?t.length:0,a=f-1;f--;){var n=t[f];if(f==a||n!==o){var o=n;Qo(n)?Ot.call(e,n,1):Bn(e,n)}}return e}function xn(e,t){return e+Bf(Kf()*(t-e+1))}function Sn(e,t){var f="";if(!e||t<1||t>H)return f;do{t%2&&(f+=e),(t=Bf(t/2))&&(e+=e)}while(t);return f}function Tn(e,t){return cr(nr(e,t,Ec),e+"")}function Dn(e){return Ta(gc(e))}function Yn(e,t){var f=gc(e);return _r(f,Ra(t,0,f.length))}function jn(e,t,f,a){if(!js(e))return e;for(var n=-1,r=(t=Qn(t,e)).length,s=r-1,c=e;null!=c&&++no?0:o+t),(f=f>o?o:f)<0&&(f+=o),o=t>f?0:f-t>>>0,t>>>=0;for(var r=a(o);++n>>1,r=e[o];null!==r&&!Is(r)&&(f?r<=t:r=r){var u=t?null:To(e);if(u)return Cf(u);s=!1,n=kf,i=new La}else i=t?[]:c;e:for(;++a=a?e:Hn(e,t,f)}var Zn=If||function(e){return Ht.clearTimeout(e)};function eo(e,t){if(t)return e.slice();var f=e.length,a=Yt?Yt(f):new e.constructor(f);return e.copy(a),a}function to(e){var t=new e.constructor(e.byteLength);return new Mt(t).set(new Mt(e)),t}function fo(e,t){var f=t?to(e.buffer):e.buffer;return new e.constructor(f,e.byteOffset,e.length)}function ao(e,t){if(e!==t){var f=e!==o,a=null===e,n=e==e,r=Is(e),s=t!==o,c=null===t,i=t==t,u=Is(t);if(!c&&!u&&!r&&e>t||r&&s&&i&&!c&&!u||a&&s&&i||!f&&i||!n)return 1;if(!a&&!r&&!u&&e1?f[n-1]:o,s=n>2?f[2]:o;for(r=e.length>3&&"function"==typeof r?(n--,r):o,s&&Xo(f[0],f[1],s)&&(r=n<3?o:r,n=1),t=ft(t);++a-1?n[r?t[s]:s]:o}}function po(e){return Ho(function(t){var f=t.length,a=f,n=ya.prototype.thru;for(e&&t.reverse();a--;){var r=t[a];if("function"!=typeof r)throw new ot(c);if(n&&!s&&"wrapper"==Io(r))var s=new ya([],!0)}for(a=s?a:f;++a1&&v.reverse(),d&&uc))return!1;var u=r.get(e);if(u&&r.get(t))return u==t;var _=-1,d=!0,l=f&g?new La:o;for(r.set(e,t),r.set(t,e);++_-1&&e%1==0&&e1?"& ":"")+t[a],t=t.join(f>2?", ":" "),e.replace(Ie,"{\n/* [wrapped with "+t+"] */\n")}(a,function(e,t){return Qt(z,function(f){var a="_."+f[0];t&f[1]&&!ef(e,a)&&e.push(a)}),e.sort()}(function(e){var t=e.match(Pe);return t?t[1].split(ze):[]}(a),f)))}function ur(e){var t=0,f=0;return function(){var a=Qf(),n=j-(a-f);if(f=a,n>0){if(++t>=Y)return arguments[0]}else t=0;return e.apply(o,arguments)}}function _r(e,t){var f=-1,a=e.length,n=a-1;for(t=t===o?a:t;++f1?e[t-1]:o;return Nr(e,f="function"==typeof f?(e.pop(),f):o)});function Br(e){var t=ga(e);return t.__chain__=!0,t}function qr(e,t){return t(e)}var Ur=Ho(function(e){var t=e.length,f=t?e[0]:0,a=this.__wrapped__,n=function(t){return Oa(t,e)};return!(t>1||this.__actions__.length)&&a instanceof va&&Qo(f)?((a=a.slice(f,+f+(t?1:0))).__actions__.push({func:qr,args:[n],thisArg:o}),new ya(a,this.__chain__).thru(function(e){return t&&!e.length&&e.push(o),e})):this.thru(n)});var Wr=co(function(e,t,f){_t.call(e,f)?++e[f]:Na(e,f,1)});var Jr=go(yr),$r=go(vr);function Vr(e,t){return(vs(e)?Qt:Ba)(e,zo(t,3))}function Gr(e,t){return(vs(e)?Xt:qa)(e,zo(t,3))}var Qr=co(function(e,t,f){_t.call(e,f)?e[f].push(t):Na(e,f,[t])});var Xr=Tn(function(e,t,f){var n=-1,o="function"==typeof t,r=ks(e)?a(e.length):[];return Ba(e,function(e){r[++n]=o?Vt(t,e,f):rn(e,t,f)}),r}),Kr=co(function(e,t,f){Na(e,f,t)});function Zr(e,t){return(vs(e)?ff:gn)(e,zo(t,3))}var es=co(function(e,t,f){e[f?0:1].push(t)},function(){return[[],[]]});var ts=Tn(function(e,t){if(null==e)return[];var f=t.length;return f>1&&Xo(e,t[0],t[1])?t=[]:f>2&&Xo(t[0],t[1],t[2])&&(t=[t[0]]),wn(e,$a(t,1),[])}),fs=Pf||function(){return Ht.Date.now()};function as(e,t,f){return t=f?o:t,t=e&&null==t?e.length:t,Yo(e,L,o,o,o,o,t)}function ns(e,t){var f;if("function"!=typeof t)throw new ot(c);return e=Us(e),function(){return--e>0&&(f=t.apply(this,arguments)),e<=1&&(t=o),f}}var os=Tn(function(e,t,f){var a=p;if(f.length){var n=Af(f,Po(os));a|=k}return Yo(e,a,t,f,n)}),rs=Tn(function(e,t,f){var a=p|b;if(f.length){var n=Af(f,Po(rs));a|=k}return Yo(t,a,e,f,n)});function ss(e,t,f){var a,n,r,s,i,u,_=0,d=!1,l=!1,h=!0;if("function"!=typeof e)throw new ot(c);function m(t){var f=a,r=n;return a=n=o,_=t,s=e.apply(r,f)}function g(e){var f=e-u;return u===o||f>=t||f<0||l&&e-_>=r}function p(){var e=fs();if(g(e))return b(e);i=sr(p,function(e){var f=t-(e-u);return l?Gf(f,r-(e-_)):f}(e))}function b(e){return i=o,h&&a?m(e):(a=n=o,s)}function y(){var e=fs(),f=g(e);if(a=arguments,n=this,u=e,f){if(i===o)return function(e){return _=e,i=sr(p,t),d?m(e):s}(u);if(l)return i=sr(p,t),m(u)}return i===o&&(i=sr(p,t)),s}return t=Js(t)||0,js(f)&&(d=!!f.leading,r=(l="maxWait"in f)?Vf(Js(f.maxWait)||0,t):r,h="trailing"in f?!!f.trailing:h),y.cancel=function(){i!==o&&Zn(i),_=0,a=u=n=i=o},y.flush=function(){return i===o?s:b(fs())},y}var cs=Tn(function(e,t){return za(e,1,t)}),is=Tn(function(e,t,f){return za(e,Js(t)||0,f)});function us(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new ot(c);var f=function(){var a=arguments,n=t?t.apply(this,a):a[0],o=f.cache;if(o.has(n))return o.get(n);var r=e.apply(this,a);return f.cache=o.set(n,r)||o,r};return f.cache=new(us.Cache||Ma),f}function _s(e){if("function"!=typeof e)throw new ot(c);return function(){var t=arguments;switch(t.length){case 0:return!e.call(this);case 1:return!e.call(this,t[0]);case 2:return!e.call(this,t[0],t[1]);case 3:return!e.call(this,t[0],t[1],t[2])}return!e.apply(this,t)}}us.Cache=Ma;var ds=Xn(function(e,t){var f=(t=1==t.length&&vs(t[0])?ff(t[0],vf(zo())):ff($a(t,1),vf(zo()))).length;return Tn(function(a){for(var n=-1,o=Gf(a.length,f);++n=t}),ys=sn(function(){return arguments}())?sn:function(e){return As(e)&&_t.call(e,"callee")&&!Nt.call(e,"callee")},vs=a.isArray,ws=zt?vf(zt):function(e){return As(e)&&tn(e)==ce};function ks(e){return null!=e&&Ys(e.length)&&!Ts(e)}function Ms(e){return As(e)&&ks(e)}var Ls=Uf||Jc,xs=Ft?vf(Ft):function(e){return As(e)&&tn(e)==W};function Ss(e){if(!As(e))return!1;var t=tn(e);return t==$||t==J||"string"==typeof e.message&&"string"==typeof e.name&&!Hs(e)}function Ts(e){if(!js(e))return!1;var t=tn(e);return t==V||t==G||t==q||t==ee}function Ds(e){return"number"==typeof e&&e==Us(e)}function Ys(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=H}function js(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function As(e){return null!=e&&"object"==typeof e}var Cs=Bt?vf(Bt):function(e){return As(e)&&Jo(e)==Q};function Es(e){return"number"==typeof e||As(e)&&tn(e)==X}function Hs(e){if(!As(e)||tn(e)!=Z)return!1;var t=Ct(e);if(null===t)return!0;var f=_t.call(t,"constructor")&&t.constructor;return"function"==typeof f&&f instanceof f&&ut.call(f)==mt}var Ns=qt?vf(qt):function(e){return As(e)&&tn(e)==te};var Os=Ut?vf(Ut):function(e){return As(e)&&Jo(e)==fe};function Rs(e){return"string"==typeof e||!vs(e)&&As(e)&&tn(e)==ae}function Is(e){return"symbol"==typeof e||As(e)&&tn(e)==ne}var Ps=Wt?vf(Wt):function(e){return As(e)&&Ys(e.length)&&!!Tt[tn(e)]};var zs=Lo(mn),Fs=Lo(function(e,t){return e<=t});function Bs(e){if(!e)return[];if(ks(e))return Rs(e)?Nf(e):ro(e);if(Pt&&e[Pt])return function(e){for(var t,f=[];!(t=e.next()).done;)f.push(t.value);return f}(e[Pt]());var t=Jo(e);return(t==Q?Yf:t==fe?Cf:gc)(e)}function qs(e){return e?(e=Js(e))===E||e===-E?(e<0?-1:1)*N:e==e?e:0:0===e?e:0}function Us(e){var t=qs(e),f=t%1;return t==t?f?t-f:t:0}function Ws(e){return e?Ra(Us(e),0,R):0}function Js(e){if("number"==typeof e)return e;if(Is(e))return O;if(js(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=js(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(Ne,"");var f=Je.test(e);return f||Ve.test(e)?At(e.slice(2),f?2:8):We.test(e)?O:+e}function $s(e){return so(e,cc(e))}function Vs(e){return null==e?"":zn(e)}var Gs=io(function(e,t){if(tr(t)||ks(t))so(t,sc(t),e);else for(var f in t)_t.call(t,f)&&Aa(e,f,t[f])}),Qs=io(function(e,t){so(t,cc(t),e)}),Xs=io(function(e,t,f,a){so(t,cc(t),e,a)}),Ks=io(function(e,t,f,a){so(t,sc(t),e,a)}),Zs=Ho(Oa);var ec=Tn(function(e){return e.push(o,jo),Vt(Xs,o,e)}),tc=Tn(function(e){return e.push(o,Ao),Vt(uc,o,e)});function fc(e,t,f){var a=null==e?o:Za(e,t);return a===o?f:a}function ac(e,t){return null!=e&&$o(e,t,nn)}var nc=yo(function(e,t,f){e[t]=f},jc(Ec)),oc=yo(function(e,t,f){_t.call(e,t)?e[t].push(f):e[t]=[f]},zo),rc=Tn(rn);function sc(e){return ks(e)?Sa(e):ln(e)}function cc(e){return ks(e)?Sa(e,!0):hn(e)}var ic=io(function(e,t,f){yn(e,t,f)}),uc=io(function(e,t,f,a){yn(e,t,f,a)}),_c=Ho(function(e,t){var f={};if(null==e)return f;var a=!1;t=ff(t,function(t){return t=Qn(t,e),a||(a=t.length>1),t}),so(e,Oo(e),f),a&&(f=Ia(f,d|l|h,Co));for(var n=t.length;n--;)Bn(f,t[n]);return f});var dc=Ho(function(e,t){return null==e?{}:function(e,t){return kn(e,t,function(t,f){return ac(e,f)})}(e,t)});function lc(e,t){if(null==e)return{};var f=ff(Oo(e),function(e){return[e]});return t=zo(t),kn(e,f,function(e,f){return t(e,f[0])})}var hc=Do(sc),mc=Do(cc);function gc(e){return null==e?[]:wf(e,sc(e))}var pc=ho(function(e,t,f){return t=t.toLowerCase(),e+(f?bc(t):t)});function bc(e){return Sc(Vs(e).toLowerCase())}function yc(e){return(e=Vs(e))&&e.replace(Qe,xf).replace(vt,"")}var vc=ho(function(e,t,f){return e+(f?"-":"")+t.toLowerCase()}),wc=ho(function(e,t,f){return e+(f?" ":"")+t.toLowerCase()}),kc=lo("toLowerCase");var Mc=ho(function(e,t,f){return e+(f?"_":"")+t.toLowerCase()});var Lc=ho(function(e,t,f){return e+(f?" ":"")+Sc(t)});var xc=ho(function(e,t,f){return e+(f?" ":"")+t.toUpperCase()}),Sc=lo("toUpperCase");function Tc(e,t,f){return e=Vs(e),(t=f?o:t)===o?function(e){return Lt.test(e)}(e)?function(e){return e.match(kt)||[]}(e):function(e){return e.match(Fe)||[]}(e):e.match(t)||[]}var Dc=Tn(function(e,t){try{return Vt(e,o,t)}catch(e){return Ss(e)?e:new Ze(e)}}),Yc=Ho(function(e,t){return Qt(t,function(t){t=lr(t),Na(e,t,os(e[t],e))}),e});function jc(e){return function(){return e}}var Ac=po(),Cc=po(!0);function Ec(e){return e}function Hc(e){return dn("function"==typeof e?e:Ia(e,d))}var Nc=Tn(function(e,t){return function(f){return rn(f,e,t)}}),Oc=Tn(function(e,t){return function(f){return rn(e,f,t)}});function Rc(e,t,f){var a=sc(t),n=Ka(t,a);null!=f||js(t)&&(n.length||!a.length)||(f=t,t=e,e=this,n=Ka(t,sc(t)));var o=!(js(f)&&"chain"in f&&!f.chain),r=Ts(e);return Qt(n,function(f){var a=t[f];e[f]=a,r&&(e.prototype[f]=function(){var t=this.__chain__;if(o||t){var f=e(this.__wrapped__);return(f.__actions__=ro(this.__actions__)).push({func:a,args:arguments,thisArg:e}),f.__chain__=t,f}return a.apply(e,af([this.value()],arguments))})}),e}function Ic(){}var Pc=wo(ff),zc=wo(Kt),Fc=wo(rf);function Bc(e){return Ko(e)?mf(lr(e)):function(e){return function(t){return Za(t,e)}}(e)}var qc=Mo(),Uc=Mo(!0);function Wc(){return[]}function Jc(){return!1}var $c=vo(function(e,t){return e+t},0),Vc=So("ceil"),Gc=vo(function(e,t){return e/t},1),Qc=So("floor");var Xc,Kc=vo(function(e,t){return e*t},1),Zc=So("round"),ei=vo(function(e,t){return e-t},0);return ga.after=function(e,t){if("function"!=typeof t)throw new ot(c);return e=Us(e),function(){if(--e<1)return t.apply(this,arguments)}},ga.ary=as,ga.assign=Gs,ga.assignIn=Qs,ga.assignInWith=Xs,ga.assignWith=Ks,ga.at=Zs,ga.before=ns,ga.bind=os,ga.bindAll=Yc,ga.bindKey=rs,ga.castArray=function(){if(!arguments.length)return[];var e=arguments[0];return vs(e)?e:[e]},ga.chain=Br,ga.chunk=function(e,t,f){t=(f?Xo(e,t,f):t===o)?1:Vf(Us(t),0);var n=null==e?0:e.length;if(!n||t<1)return[];for(var r=0,s=0,c=a(Ff(n/t));rn?0:n+f),(a=a===o||a>n?n:Us(a))<0&&(a+=n),a=f>a?0:Ws(a);f>>0)?(e=Vs(e))&&("string"==typeof t||null!=t&&!Ns(t))&&!(t=zn(t))&&Df(e)?Kn(Nf(e),0,f):e.split(t,f):[]},ga.spread=function(e,t){if("function"!=typeof e)throw new ot(c);return t=null==t?0:Vf(Us(t),0),Tn(function(f){var a=f[t],n=Kn(f,0,t);return a&&af(n,a),Vt(e,this,n)})},ga.tail=function(e){var t=null==e?0:e.length;return t?Hn(e,1,t):[]},ga.take=function(e,t,f){return e&&e.length?Hn(e,0,(t=f||t===o?1:Us(t))<0?0:t):[]},ga.takeRight=function(e,t,f){var a=null==e?0:e.length;return a?Hn(e,(t=a-(t=f||t===o?1:Us(t)))<0?0:t,a):[]},ga.takeRightWhile=function(e,t){return e&&e.length?Un(e,zo(t,3),!1,!0):[]},ga.takeWhile=function(e,t){return e&&e.length?Un(e,zo(t,3)):[]},ga.tap=function(e,t){return t(e),e},ga.throttle=function(e,t,f){var a=!0,n=!0;if("function"!=typeof e)throw new ot(c);return js(f)&&(a="leading"in f?!!f.leading:a,n="trailing"in f?!!f.trailing:n),ss(e,t,{leading:a,maxWait:t,trailing:n})},ga.thru=qr,ga.toArray=Bs,ga.toPairs=hc,ga.toPairsIn=mc,ga.toPath=function(e){return vs(e)?ff(e,lr):Is(e)?[e]:ro(dr(Vs(e)))},ga.toPlainObject=$s,ga.transform=function(e,t,f){var a=vs(e),n=a||Ls(e)||Ps(e);if(t=zo(t,4),null==f){var o=e&&e.constructor;f=n?a?new o:[]:js(e)&&Ts(o)?pa(Ct(e)):{}}return(n?Qt:Qa)(e,function(e,a,n){return t(f,e,a,n)}),f},ga.unary=function(e){return as(e,1)},ga.union=Ar,ga.unionBy=Cr,ga.unionWith=Er,ga.uniq=function(e){return e&&e.length?Fn(e):[]},ga.uniqBy=function(e,t){return e&&e.length?Fn(e,zo(t,2)):[]},ga.uniqWith=function(e,t){return t="function"==typeof t?t:o,e&&e.length?Fn(e,o,t):[]},ga.unset=function(e,t){return null==e||Bn(e,t)},ga.unzip=Hr,ga.unzipWith=Nr,ga.update=function(e,t,f){return null==e?e:qn(e,t,Gn(f))},ga.updateWith=function(e,t,f,a){return a="function"==typeof a?a:o,null==e?e:qn(e,t,Gn(f),a)},ga.values=gc,ga.valuesIn=function(e){return null==e?[]:wf(e,cc(e))},ga.without=Or,ga.words=Tc,ga.wrap=function(e,t){return ls(Gn(t),e)},ga.xor=Rr,ga.xorBy=Ir,ga.xorWith=Pr,ga.zip=zr,ga.zipObject=function(e,t){return $n(e||[],t||[],Aa)},ga.zipObjectDeep=function(e,t){return $n(e||[],t||[],jn)},ga.zipWith=Fr,ga.entries=hc,ga.entriesIn=mc,ga.extend=Qs,ga.extendWith=Xs,Rc(ga,ga),ga.add=$c,ga.attempt=Dc,ga.camelCase=pc,ga.capitalize=bc,ga.ceil=Vc,ga.clamp=function(e,t,f){return f===o&&(f=t,t=o),f!==o&&(f=(f=Js(f))==f?f:0),t!==o&&(t=(t=Js(t))==t?t:0),Ra(Js(e),t,f)},ga.clone=function(e){return Ia(e,h)},ga.cloneDeep=function(e){return Ia(e,d|h)},ga.cloneDeepWith=function(e,t){return Ia(e,d|h,t="function"==typeof t?t:o)},ga.cloneWith=function(e,t){return Ia(e,h,t="function"==typeof t?t:o)},ga.conformsTo=function(e,t){return null==t||Pa(e,t,sc(t))},ga.deburr=yc,ga.defaultTo=function(e,t){return null==e||e!=e?t:e},ga.divide=Gc,ga.endsWith=function(e,t,f){e=Vs(e),t=zn(t);var a=e.length,n=f=f===o?a:Ra(Us(f),0,a);return(f-=t.length)>=0&&e.slice(f,n)==t},ga.eq=gs,ga.escape=function(e){return(e=Vs(e))&&xe.test(e)?e.replace(Me,Sf):e},ga.escapeRegExp=function(e){return(e=Vs(e))&&He.test(e)?e.replace(Ee,"\\$&"):e},ga.every=function(e,t,f){var a=vs(e)?Kt:Ua;return f&&Xo(e,t,f)&&(t=o),a(e,zo(t,3))},ga.find=Jr,ga.findIndex=yr,ga.findKey=function(e,t){return cf(e,zo(t,3),Qa)},ga.findLast=$r,ga.findLastIndex=vr,ga.findLastKey=function(e,t){return cf(e,zo(t,3),Xa)},ga.floor=Qc,ga.forEach=Vr,ga.forEachRight=Gr,ga.forIn=function(e,t){return null==e?e:Va(e,zo(t,3),cc)},ga.forInRight=function(e,t){return null==e?e:Ga(e,zo(t,3),cc)},ga.forOwn=function(e,t){return e&&Qa(e,zo(t,3))},ga.forOwnRight=function(e,t){return e&&Xa(e,zo(t,3))},ga.get=fc,ga.gt=ps,ga.gte=bs,ga.has=function(e,t){return null!=e&&$o(e,t,an)},ga.hasIn=ac,ga.head=kr,ga.identity=Ec,ga.includes=function(e,t,f,a){e=ks(e)?e:gc(e),f=f&&!a?Us(f):0;var n=e.length;return f<0&&(f=Vf(n+f,0)),Rs(e)?f<=n&&e.indexOf(t,f)>-1:!!n&&_f(e,t,f)>-1},ga.indexOf=function(e,t,f){var a=null==e?0:e.length;if(!a)return-1;var n=null==f?0:Us(f);return n<0&&(n=Vf(a+n,0)),_f(e,t,n)},ga.inRange=function(e,t,f){return t=qs(t),f===o?(f=t,t=0):f=qs(f),function(e,t,f){return e>=Gf(t,f)&&e=-H&&e<=H},ga.isSet=Os,ga.isString=Rs,ga.isSymbol=Is,ga.isTypedArray=Ps,ga.isUndefined=function(e){return e===o},ga.isWeakMap=function(e){return As(e)&&Jo(e)==re},ga.isWeakSet=function(e){return As(e)&&tn(e)==se},ga.join=function(e,t){return null==e?"":Jf.call(e,t)},ga.kebabCase=vc,ga.last=Sr,ga.lastIndexOf=function(e,t,f){var a=null==e?0:e.length;if(!a)return-1;var n=a;return f!==o&&(n=(n=Us(f))<0?Vf(a+n,0):Gf(n,a-1)),t==t?function(e,t,f){for(var a=f+1;a--;)if(e[a]===t)return a;return a}(e,t,n):uf(e,lf,n,!0)},ga.lowerCase=wc,ga.lowerFirst=kc,ga.lt=zs,ga.lte=Fs,ga.max=function(e){return e&&e.length?Wa(e,Ec,fn):o},ga.maxBy=function(e,t){return e&&e.length?Wa(e,zo(t,2),fn):o},ga.mean=function(e){return hf(e,Ec)},ga.meanBy=function(e,t){return hf(e,zo(t,2))},ga.min=function(e){return e&&e.length?Wa(e,Ec,mn):o},ga.minBy=function(e,t){return e&&e.length?Wa(e,zo(t,2),mn):o},ga.stubArray=Wc,ga.stubFalse=Jc,ga.stubObject=function(){return{}},ga.stubString=function(){return""},ga.stubTrue=function(){return!0},ga.multiply=Kc,ga.nth=function(e,t){return e&&e.length?vn(e,Us(t)):o},ga.noConflict=function(){return Ht._===this&&(Ht._=gt),this},ga.noop=Ic,ga.now=fs,ga.pad=function(e,t,f){e=Vs(e);var a=(t=Us(t))?Hf(e):0;if(!t||a>=t)return e;var n=(t-a)/2;return ko(Bf(n),f)+e+ko(Ff(n),f)},ga.padEnd=function(e,t,f){e=Vs(e);var a=(t=Us(t))?Hf(e):0;return t&&at){var a=e;e=t,t=a}if(f||e%1||t%1){var n=Kf();return Gf(e+n*(t-e+jt("1e-"+((n+"").length-1))),t)}return xn(e,t)},ga.reduce=function(e,t,f){var a=vs(e)?nf:pf,n=arguments.length<3;return a(e,zo(t,4),f,n,Ba)},ga.reduceRight=function(e,t,f){var a=vs(e)?of:pf,n=arguments.length<3;return a(e,zo(t,4),f,n,qa)},ga.repeat=function(e,t,f){return t=(f?Xo(e,t,f):t===o)?1:Us(t),Sn(Vs(e),t)},ga.replace=function(){var e=arguments,t=Vs(e[0]);return e.length<3?t:t.replace(e[1],e[2])},ga.result=function(e,t,f){var a=-1,n=(t=Qn(t,e)).length;for(n||(n=1,e=o);++aH)return[];var f=R,a=Gf(e,R);t=zo(t),e-=R;for(var n=yf(a,t);++f=r)return e;var c=f-Hf(a);if(c<1)return a;var i=s?Kn(s,0,c).join(""):e.slice(0,c);if(n===o)return i+a;if(s&&(c+=i.length-c),Ns(n)){if(e.slice(c).search(n)){var u,_=i;for(n.global||(n=at(n.source,Vs(Ue.exec(n))+"g")),n.lastIndex=0;u=n.exec(_);)var d=u.index;i=i.slice(0,d===o?c:d)}}else if(e.indexOf(zn(n),c)!=c){var l=i.lastIndexOf(n);l>-1&&(i=i.slice(0,l))}return i+a},ga.unescape=function(e){return(e=Vs(e))&&Le.test(e)?e.replace(ke,Of):e},ga.uniqueId=function(e){var t=++dt;return Vs(e)+t},ga.upperCase=xc,ga.upperFirst=Sc,ga.each=Vr,ga.eachRight=Gr,ga.first=kr,Rc(ga,(Xc={},Qa(ga,function(e,t){_t.call(ga.prototype,t)||(Xc[t]=e)}),Xc),{chain:!1}),ga.VERSION="4.17.4",Qt(["bind","bindKey","curry","curryRight","partial","partialRight"],function(e){ga[e].placeholder=ga}),Qt(["drop","take"],function(e,t){va.prototype[e]=function(f){f=f===o?1:Vf(Us(f),0);var a=this.__filtered__&&!t?new va(this):this.clone();return a.__filtered__?a.__takeCount__=Gf(f,a.__takeCount__):a.__views__.push({size:Gf(f,R),type:e+(a.__dir__<0?"Right":"")}),a},va.prototype[e+"Right"]=function(t){return this.reverse()[e](t).reverse()}}),Qt(["filter","map","takeWhile"],function(e,t){var f=t+1,a=f==A||3==f;va.prototype[e]=function(e){var t=this.clone();return t.__iteratees__.push({iteratee:zo(e,3),type:f}),t.__filtered__=t.__filtered__||a,t}}),Qt(["head","last"],function(e,t){var f="take"+(t?"Right":"");va.prototype[e]=function(){return this[f](1).value()[0]}}),Qt(["initial","tail"],function(e,t){var f="drop"+(t?"":"Right");va.prototype[e]=function(){return this.__filtered__?new va(this):this[f](1)}}),va.prototype.compact=function(){return this.filter(Ec)},va.prototype.find=function(e){return this.filter(e).head()},va.prototype.findLast=function(e){return this.reverse().find(e)},va.prototype.invokeMap=Tn(function(e,t){return"function"==typeof e?new va(this):this.map(function(f){return rn(f,e,t)})}),va.prototype.reject=function(e){return this.filter(_s(zo(e)))},va.prototype.slice=function(e,t){e=Us(e);var f=this;return f.__filtered__&&(e>0||t<0)?new va(f):(e<0?f=f.takeRight(-e):e&&(f=f.drop(e)),t!==o&&(f=(t=Us(t))<0?f.dropRight(-t):f.take(t-e)),f)},va.prototype.takeRightWhile=function(e){return this.reverse().takeWhile(e).reverse()},va.prototype.toArray=function(){return this.take(R)},Qa(va.prototype,function(e,t){var f=/^(?:filter|find|map|reject)|While$/.test(t),a=/^(?:head|last)$/.test(t),n=ga[a?"take"+("last"==t?"Right":""):t],r=a||/^find/.test(t);n&&(ga.prototype[t]=function(){var t=this.__wrapped__,s=a?[1]:arguments,c=t instanceof va,i=s[0],u=c||vs(t),_=function(e){var t=n.apply(ga,af([e],s));return a&&d?t[0]:t};u&&f&&"function"==typeof i&&1!=i.length&&(c=u=!1);var d=this.__chain__,l=!!this.__actions__.length,h=r&&!d,m=c&&!l;if(!r&&u){t=m?t:new va(this);var g=e.apply(t,s);return g.__actions__.push({func:qr,args:[_],thisArg:o}),new ya(g,d)}return h&&m?e.apply(this,s):(g=this.thru(_),h?a?g.value()[0]:g.value():g)})}),Qt(["pop","push","shift","sort","splice","unshift"],function(e){var t=rt[e],f=/^(?:push|sort|unshift)$/.test(e)?"tap":"thru",a=/^(?:pop|shift)$/.test(e);ga.prototype[e]=function(){var e=arguments;if(a&&!this.__chain__){var n=this.value();return t.apply(vs(n)?n:[],e)}return this[f](function(f){return t.apply(vs(f)?f:[],e)})}}),Qa(va.prototype,function(e,t){var f=ga[t];if(f){var a=f.name+"";(sa[a]||(sa[a]=[])).push({name:t,func:f})}}),sa[bo(o,b).name]=[{name:"wrapper",func:o}],va.prototype.clone=function(){var e=new va(this.__wrapped__);return e.__actions__=ro(this.__actions__),e.__dir__=this.__dir__,e.__filtered__=this.__filtered__,e.__iteratees__=ro(this.__iteratees__),e.__takeCount__=this.__takeCount__,e.__views__=ro(this.__views__),e},va.prototype.reverse=function(){if(this.__filtered__){var e=new va(this);e.__dir__=-1,e.__filtered__=!0}else(e=this.clone()).__dir__*=-1;return e},va.prototype.value=function(){var e=this.__wrapped__.value(),t=this.__dir__,f=vs(e),a=t<0,n=f?e.length:0,o=function(e,t,f){for(var a=-1,n=f.length;++a=this.__values__.length;return{done:e,value:e?o:this.__values__[this.__index__++]}},ga.prototype.plant=function(e){for(var t,f=this;f instanceof ba;){var a=mr(f);a.__index__=0,a.__values__=o,t?n.__wrapped__=a:t=a;var n=a;f=f.__wrapped__}return n.__wrapped__=e,t},ga.prototype.reverse=function(){var e=this.__wrapped__;if(e instanceof va){var t=e;return this.__actions__.length&&(t=new va(this)),(t=t.reverse()).__actions__.push({func:qr,args:[jr],thisArg:o}),new ya(t,this.__chain__)}return this.thru(jr)},ga.prototype.toJSON=ga.prototype.valueOf=ga.prototype.value=function(){return Wn(this.__wrapped__,this.__actions__)},ga.prototype.first=ga.prototype.head,Pt&&(ga.prototype[Pt]=function(){return this}),ga}();Ht._=Rf,(n=function(){return Rf}.call(t,f,t,a))===o||(a.exports=n)}).call(this)}).call(this,f(5),f(44)(e))},function(e,t,f){"use strict";var a,n;a=[f(15)],void 0===(n=function(e){return e.noConflict()}.apply(t,a))||(e.exports=n)},function(e,t,f){var a={escape:f(1)};e.exports=function(e){var t="",f=a.escape;return t+='\x3c!-- src/templates/info.html --\x3e\n
"+f(e.message)+"
\n"}},function(e,t,f){f(1);e.exports=function(e){var t="";return t+='\x3c!-- src/templates/spinner.html --\x3e\n\n'}},function(e,t,f){var a,n,o; -/*! - * Backbone.Overview - * - * Copyright (c) 2018, JC Brand - * Licensed under the Mozilla Public License (MPL) - */n=[f(8),f(4)],void 0===(o="function"==typeof(a=function(e,t){"use strict";var f=e.isUndefined(t.NativeView)?t.View:t.NativeView,a=t.Overview=function(t){var a=this;this.views={},this.keys=e.partial(e.keys,this.views),this.getAll=e.partial(e.identity,this.views),this.get=function(e){return a.views[e]},this.xget=function(t){return e.filter(a.views,function(e,f){return f!==t})},this.add=function(e,t){return a.views[e]=t,t},this.remove=function(e){void 0===e&&(new f).remove.apply(a);var t=a.views[e];if(t)return delete a.views[e],t.remove(),t},this.removeAll=function(){return e.each(e.keys(a.views),a.remove),a},f.apply(this,Array.prototype.slice.apply(arguments))};return e.each(["all","any","chain","collect","contains","detect","difference","drop","each","every","filter","find","first","foldl","foldr","forEach","head","include","indexOf","initial","inject","invoke","isEmpty","last","lastIndexOf","map","max","min","reduce","reduceRight","reject","rest","sample","select","shuffle","size","some","sortBy","tail","take","toArray","without"],function(t){a.prototype[t]=function(){var f=Array.prototype.slice.call(arguments);return f.unshift(this.views),e[t].apply(e,f)}}),e.extend(a.prototype,f.prototype),a.extend=f.extend,t.OrderedListView=t.Overview.extend({listItems:"model",sortEvent:"change",listSelector:".ordered-items",ItemView:void 0,initialize:function(){this.sortEventually=e.debounce(this.sortAndPositionAllItems.bind(this),500),this.items=e.get(this,this.listItems),this.items.on("add",this.createItemView,this),this.items.on("add",this.sortEventually,this),this.items.on(this.sortEvent,this.sortEventually,this)},createItemView:function(e){var t=this.get(e.get("id"));return t?(t.model=e,t.initialize()):(t=new this.ItemView({model:e}),this.add(e.get("id"),t)),t.render(),t},sortAndPositionAllItems:function(){var t=this;this.items.sort(),this.items.each(function(f){e.isUndefined(t.get(f.get("id")))&&t.createItemView(f),t.positionItem(f,t.el.querySelector(t.listSelector))})},positionItem:function(e,t){var f=this.get(e.get("id")),a=this.items.indexOf(e);return 0===a?t.insertAdjacentElement("afterbegin",f.el):a===this.items.length-1?t.insertAdjacentElement("beforeend",f.el):t.querySelector("li:nth-child("+a+")").insertAdjacentElement("afterend",f.el),f}}),t.Overview})?a.apply(t,n):a)||(e.exports=o)},function(e,t,f){"use strict";var a,n,o;n=[f(9),f(16),f(7),f(261),f(260),f(259),f(255),f(258),f(58),f(57),f(257),f(256)],void 0===(o="function"==typeof(a=function(e,t,f,a,n,o,r,s,c,i,u,_){var d={"text-private":"password","text-single":"text",fixed:"label",boolean:"checkbox",hidden:"hidden","jid-multi":"textarea","list-single":"dropdown","list-multi":"dropdown"};return f.webForm2xForm=function(e){let n;return n="checkbox"===e.getAttribute("type")?e.checked?1:0:"TEXTAREA"==e.tagName?t.filter(e.value.split("\n"),t.trim):"SELECT"==e.tagName?f.getSelectValues(e):e.value,f.stringToNode(a({name:e.getAttribute("name"),value:n}))},f.xForm2webForm=function(a,l,h){if(a.getAttribute("type")){if("list-single"===a.getAttribute("type")||"list-multi"===a.getAttribute("type")){const e=t.map(f.queryChildren(a,"value"),t.partial(t.get,t,"textContent")),r=t.map(f.queryChildren(a,"option"),function(f){const o=t.get(f.querySelector("value"),"textContent");return n({value:o,label:f.getAttribute("label"),selected:t.includes(e,o),required:!t.isNil(a.querySelector("required"))})});return o({name:a.getAttribute("var"),label:a.getAttribute("label"),options:r.join(""),multiple:"list-multi"===a.getAttribute("type"),required:!t.isNil(a.querySelector("required"))})}return"fixed"===a.getAttribute("type")?'

'+t.get(a.querySelector("value"),"textContent")+"

":"jid-multi"===a.getAttribute("type")?r({name:a.getAttribute("var"),label:a.getAttribute("label")||"",value:t.get(a.querySelector("value"),"textContent"),required:!t.isNil(a.querySelector("required"))}):"boolean"===a.getAttribute("type")?s({name:a.getAttribute("var"),type:d[a.getAttribute("type")],label:a.getAttribute("label")||"",checked:"1"===t.get(a.querySelector("value"),"textContent")?'checked="1"':"",required:!t.isNil(a.querySelector("required"))}):"url"===a.getAttribute("var")?_({label:a.getAttribute("label")||"",value:t.get(a.querySelector("value"),"textContent")}):"username"===a.getAttribute("var")?c({domain:" @"+h,name:a.getAttribute("var"),type:d[a.getAttribute("type")],label:a.getAttribute("label")||"",value:t.get(a.querySelector("value"),"textContent"),required:!t.isNil(a.querySelector("required"))}):i({label:a.getAttribute("label")||"",name:a.getAttribute("var"),placeholder:null,required:!t.isNil(a.querySelector("required")),type:d[a.getAttribute("type")],value:t.get(a.querySelector("value"),"textContent")})}if("ocr"===a.getAttribute("var")){const f=a.querySelector("uri"),n=e('data[cid="'+f.textContent.replace(/^cid:/,"")+'"]',l)[0];return u({label:a.getAttribute("label"),name:a.getAttribute("var"),data:t.get(n,"textContent"),type:f.getAttribute("type"),required:!t.isNil(a.querySelector("required"))})}},f})?a.apply(t,n):a)||(e.exports=o)},function(e,t,f){var a=f(275).Symbol;e.exports=a},function(e,t,f){!function(e){"use strict";e.defineLocale("zh-tw",{months:"一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),weekdays:"星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"),weekdaysShort:"週日_週一_週二_週三_週四_週五_週六".split("_"),weekdaysMin:"日_一_二_三_四_五_六".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"YYYY年MMMD日",LL:"YYYY年MMMD日",LLL:"YYYY年MMMD日 HH:mm",LLLL:"YYYY年MMMD日dddd HH:mm",l:"YYYY年MMMD日",ll:"YYYY年MMMD日",lll:"YYYY年MMMD日 HH:mm",llll:"YYYY年MMMD日dddd HH:mm"},meridiemParse:/凌晨|早上|上午|中午|下午|晚上/,meridiemHour:function(e,t){return 12===e&&(e=0),"凌晨"===t||"早上"===t||"上午"===t?e:"中午"===t?e>=11?e:e+12:"下午"===t||"晚上"===t?e+12:void 0},meridiem:function(e,t,f){var a=100*e+t;return a<600?"凌晨":a<900?"早上":a<1130?"上午":a<1230?"中午":a<1800?"下午":"晚上"},calendar:{sameDay:"[今天]LT",nextDay:"[明天]LT",nextWeek:"[下]ddddLT",lastDay:"[昨天]LT",lastWeek:"[上]ddddLT",sameElse:"L"},dayOfMonthOrdinalParse:/\d{1,2}(日|月|週)/,ordinal:function(e,t){switch(t){case"d":case"D":case"DDD":return e+"日";case"M":return e+"月";case"w":case"W":return e+"週";default:return e}},relativeTime:{future:"%s內",past:"%s前",s:"幾秒",m:"1 分鐘",mm:"%d 分鐘",h:"1 小時",hh:"%d 小時",d:"1 天",dd:"%d 天",M:"1 個月",MM:"%d 個月",y:"1 年",yy:"%d 年"}})}(f(0))},function(e,t,f){!function(e){"use strict";e.defineLocale("zh-cn",{months:"一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),weekdays:"星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"),weekdaysShort:"周日_周一_周二_周三_周四_周五_周六".split("_"),weekdaysMin:"日_一_二_三_四_五_六".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"YYYY年MMMD日",LL:"YYYY年MMMD日",LLL:"YYYY年MMMD日Ah点mm分",LLLL:"YYYY年MMMD日ddddAh点mm分",l:"YYYY年MMMD日",ll:"YYYY年MMMD日",lll:"YYYY年MMMD日 HH:mm",llll:"YYYY年MMMD日dddd HH:mm"},meridiemParse:/凌晨|早上|上午|中午|下午|晚上/,meridiemHour:function(e,t){return 12===e&&(e=0),"凌晨"===t||"早上"===t||"上午"===t?e:"下午"===t||"晚上"===t?e+12:e>=11?e:e+12},meridiem:function(e,t,f){var a=100*e+t;return a<600?"凌晨":a<900?"早上":a<1130?"上午":a<1230?"中午":a<1800?"下午":"晚上"},calendar:{sameDay:"[今天]LT",nextDay:"[明天]LT",nextWeek:"[下]ddddLT",lastDay:"[昨天]LT",lastWeek:"[上]ddddLT",sameElse:"L"},dayOfMonthOrdinalParse:/\d{1,2}(日|月|周)/,ordinal:function(e,t){switch(t){case"d":case"D":case"DDD":return e+"日";case"M":return e+"月";case"w":case"W":return e+"周";default:return e}},relativeTime:{future:"%s内",past:"%s前",s:"几秒",m:"1 分钟",mm:"%d 分钟",h:"1 小时",hh:"%d 小时",d:"1 天",dd:"%d 天",M:"1 个月",MM:"%d 个月",y:"1 年",yy:"%d 年"},week:{dow:1,doy:4}})}(f(0))},function(e,t,f){!function(e){"use strict";function t(e,t,f){var a,n,o={mm:t?"хвилина_хвилини_хвилин":"хвилину_хвилини_хвилин",hh:t?"година_години_годин":"годину_години_годин",dd:"день_дні_днів",MM:"місяць_місяці_місяців",yy:"рік_роки_років"};return"m"===f?t?"хвилина":"хвилину":"h"===f?t?"година":"годину":e+" "+(a=+e,n=o[f].split("_"),a%10==1&&a%100!=11?n[0]:a%10>=2&&a%10<=4&&(a%100<10||a%100>=20)?n[1]:n[2])}function f(e){return function(){return e+"о"+(11===this.hours()?"б":"")+"] LT"}}e.defineLocale("uk",{months:{format:"січня_лютого_березня_квітня_травня_червня_липня_серпня_вересня_жовтня_листопада_грудня".split("_"),standalone:"січень_лютий_березень_квітень_травень_червень_липень_серпень_вересень_жовтень_листопад_грудень".split("_")},monthsShort:"січ_лют_бер_квіт_трав_черв_лип_серп_вер_жовт_лист_груд".split("_"),weekdays:function(e,t){var f={nominative:"неділя_понеділок_вівторок_середа_четвер_п’ятниця_субота".split("_"),accusative:"неділю_понеділок_вівторок_середу_четвер_п’ятницю_суботу".split("_"),genitive:"неділі_понеділка_вівторка_середи_четверга_п’ятниці_суботи".split("_")};if(!e)return f.nominative;var a=/(\[[ВвУу]\]) ?dddd/.test(t)?"accusative":/\[?(?:минулої|наступної)? ?\] ?dddd/.test(t)?"genitive":"nominative";return f[a][e.day()]},weekdaysShort:"нд_пн_вт_ср_чт_пт_сб".split("_"),weekdaysMin:"нд_пн_вт_ср_чт_пт_сб".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY р.",LLL:"D MMMM YYYY р., HH:mm",LLLL:"dddd, D MMMM YYYY р., HH:mm"},calendar:{sameDay:f("[Сьогодні "),nextDay:f("[Завтра "),lastDay:f("[Вчора "),nextWeek:f("[У] dddd ["),lastWeek:function(){switch(this.day()){case 0:case 3:case 5:case 6:return f("[Минулої] dddd [").call(this);case 1:case 2:case 4:return f("[Минулого] dddd [").call(this)}},sameElse:"L"},relativeTime:{future:"за %s",past:"%s тому",s:"декілька секунд",m:t,mm:t,h:"годину",hh:t,d:"день",dd:t,M:"місяць",MM:t,y:"рік",yy:t},meridiemParse:/ночі|ранку|дня|вечора/,isPM:function(e){return/^(дня|вечора)$/.test(e)},meridiem:function(e,t,f){return e<4?"ночі":e<12?"ранку":e<17?"дня":"вечора"},dayOfMonthOrdinalParse:/\d{1,2}-(й|го)/,ordinal:function(e,t){switch(t){case"M":case"d":case"DDD":case"w":case"W":return e+"-й";case"D":return e+"-го";default:return e}},week:{dow:1,doy:7}})}(f(0))},function(e,t,f){!function(e){"use strict";var t={1:"'inci",5:"'inci",8:"'inci",70:"'inci",80:"'inci",2:"'nci",7:"'nci",20:"'nci",50:"'nci",3:"'üncü",4:"'üncü",100:"'üncü",6:"'ncı",9:"'uncu",10:"'uncu",30:"'uncu",60:"'ıncı",90:"'ıncı"};e.defineLocale("tr",{months:"Ocak_Şubat_Mart_Nisan_Mayıs_Haziran_Temmuz_Ağustos_Eylül_Ekim_Kasım_Aralık".split("_"),monthsShort:"Oca_Şub_Mar_Nis_May_Haz_Tem_Ağu_Eyl_Eki_Kas_Ara".split("_"),weekdays:"Pazar_Pazartesi_Salı_Çarşamba_Perşembe_Cuma_Cumartesi".split("_"),weekdaysShort:"Paz_Pts_Sal_Çar_Per_Cum_Cts".split("_"),weekdaysMin:"Pz_Pt_Sa_Ça_Pe_Cu_Ct".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[bugün saat] LT",nextDay:"[yarın saat] LT",nextWeek:"[gelecek] dddd [saat] LT",lastDay:"[dün] LT",lastWeek:"[geçen] dddd [saat] LT",sameElse:"L"},relativeTime:{future:"%s sonra",past:"%s önce",s:"birkaç saniye",m:"bir dakika",mm:"%d dakika",h:"bir saat",hh:"%d saat",d:"bir gün",dd:"%d gün",M:"bir ay",MM:"%d ay",y:"bir yıl",yy:"%d yıl"},dayOfMonthOrdinalParse:/\d{1,2}'(inci|nci|üncü|ncı|uncu|ıncı)/,ordinal:function(e){if(0===e)return e+"'ıncı";var f=e%10,a=e%100-f,n=e>=100?100:null;return e+(t[f]||t[a]||t[n])},week:{dow:1,doy:7}})}(f(0))},function(e,t,f){!function(e){"use strict";function t(e,t,f){var a,n,o={mm:t?"минута_минуты_минут":"минуту_минуты_минут",hh:"час_часа_часов",dd:"день_дня_дней",MM:"месяц_месяца_месяцев",yy:"год_года_лет"};return"m"===f?t?"минута":"минуту":e+" "+(a=+e,n=o[f].split("_"),a%10==1&&a%100!=11?n[0]:a%10>=2&&a%10<=4&&(a%100<10||a%100>=20)?n[1]:n[2])}var f=[/^янв/i,/^фев/i,/^мар/i,/^апр/i,/^ма[йя]/i,/^июн/i,/^июл/i,/^авг/i,/^сен/i,/^окт/i,/^ноя/i,/^дек/i];e.defineLocale("ru",{months:{format:"января_февраля_марта_апреля_мая_июня_июля_августа_сентября_октября_ноября_декабря".split("_"),standalone:"январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь".split("_")},monthsShort:{format:"янв._февр._мар._апр._мая_июня_июля_авг._сент._окт._нояб._дек.".split("_"),standalone:"янв._февр._март_апр._май_июнь_июль_авг._сент._окт._нояб._дек.".split("_")},weekdays:{standalone:"воскресенье_понедельник_вторник_среда_четверг_пятница_суббота".split("_"),format:"воскресенье_понедельник_вторник_среду_четверг_пятницу_субботу".split("_"),isFormat:/\[ ?[Вв] ?(?:прошлую|следующую|эту)? ?\] ?dddd/},weekdaysShort:"вс_пн_вт_ср_чт_пт_сб".split("_"),weekdaysMin:"вс_пн_вт_ср_чт_пт_сб".split("_"),monthsParse:f,longMonthsParse:f,shortMonthsParse:f,monthsRegex:/^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i,monthsShortRegex:/^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i,monthsStrictRegex:/^(январ[яь]|феврал[яь]|марта?|апрел[яь]|ма[яй]|июн[яь]|июл[яь]|августа?|сентябр[яь]|октябр[яь]|ноябр[яь]|декабр[яь])/i,monthsShortStrictRegex:/^(янв\.|февр?\.|мар[т.]|апр\.|ма[яй]|июн[ья.]|июл[ья.]|авг\.|сент?\.|окт\.|нояб?\.|дек\.)/i,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY г.",LLL:"D MMMM YYYY г., HH:mm",LLLL:"dddd, D MMMM YYYY г., HH:mm"},calendar:{sameDay:"[Сегодня в] LT",nextDay:"[Завтра в] LT",lastDay:"[Вчера в] LT",nextWeek:function(e){if(e.week()===this.week())return 2===this.day()?"[Во] dddd [в] LT":"[В] dddd [в] LT";switch(this.day()){case 0:return"[В следующее] dddd [в] LT";case 1:case 2:case 4:return"[В следующий] dddd [в] LT";case 3:case 5:case 6:return"[В следующую] dddd [в] LT"}},lastWeek:function(e){if(e.week()===this.week())return 2===this.day()?"[Во] dddd [в] LT":"[В] dddd [в] LT";switch(this.day()){case 0:return"[В прошлое] dddd [в] LT";case 1:case 2:case 4:return"[В прошлый] dddd [в] LT";case 3:case 5:case 6:return"[В прошлую] dddd [в] LT"}},sameElse:"L"},relativeTime:{future:"через %s",past:"%s назад",s:"несколько секунд",m:t,mm:t,h:"час",hh:t,d:"день",dd:t,M:"месяц",MM:t,y:"год",yy:t},meridiemParse:/ночи|утра|дня|вечера/i,isPM:function(e){return/^(дня|вечера)$/.test(e)},meridiem:function(e,t,f){return e<4?"ночи":e<12?"утра":e<17?"дня":"вечера"},dayOfMonthOrdinalParse:/\d{1,2}-(й|го|я)/,ordinal:function(e,t){switch(t){case"M":case"d":case"DDD":return e+"-й";case"D":return e+"-го";case"w":case"W":return e+"-я";default:return e}},week:{dow:1,doy:4}})}(f(0))},function(e,t,f){!function(e){"use strict";e.defineLocale("pt-br",{months:"janeiro_fevereiro_março_abril_maio_junho_julho_agosto_setembro_outubro_novembro_dezembro".split("_"),monthsShort:"jan_fev_mar_abr_mai_jun_jul_ago_set_out_nov_dez".split("_"),weekdays:"Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado".split("_"),weekdaysShort:"Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"),weekdaysMin:"Do_2ª_3ª_4ª_5ª_6ª_Sá".split("_"),weekdaysParseExact:!0,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D [de] MMMM [de] YYYY",LLL:"D [de] MMMM [de] YYYY [às] HH:mm",LLLL:"dddd, D [de] MMMM [de] YYYY [às] HH:mm"},calendar:{sameDay:"[Hoje às] LT",nextDay:"[Amanhã às] LT",nextWeek:"dddd [às] LT",lastDay:"[Ontem às] LT",lastWeek:function(){return 0===this.day()||6===this.day()?"[Último] dddd [às] LT":"[Última] dddd [às] LT"},sameElse:"L"},relativeTime:{future:"em %s",past:"%s atrás",s:"poucos segundos",ss:"%d segundos",m:"um minuto",mm:"%d minutos",h:"uma hora",hh:"%d horas",d:"um dia",dd:"%d dias",M:"um mês",MM:"%d meses",y:"um ano",yy:"%d anos"},dayOfMonthOrdinalParse:/\d{1,2}º/,ordinal:"%dº"})}(f(0))},function(e,t,f){!function(e){"use strict";var t="styczeń_luty_marzec_kwiecień_maj_czerwiec_lipiec_sierpień_wrzesień_październik_listopad_grudzień".split("_"),f="stycznia_lutego_marca_kwietnia_maja_czerwca_lipca_sierpnia_września_października_listopada_grudnia".split("_");function a(e){return e%10<5&&e%10>1&&~~(e/10)%10!=1}function n(e,t,f){var n=e+" ";switch(f){case"m":return t?"minuta":"minutę";case"mm":return n+(a(e)?"minuty":"minut");case"h":return t?"godzina":"godzinę";case"hh":return n+(a(e)?"godziny":"godzin");case"MM":return n+(a(e)?"miesiące":"miesięcy");case"yy":return n+(a(e)?"lata":"lat")}}e.defineLocale("pl",{months:function(e,a){return e?""===a?"("+f[e.month()]+"|"+t[e.month()]+")":/D MMMM/.test(a)?f[e.month()]:t[e.month()]:t},monthsShort:"sty_lut_mar_kwi_maj_cze_lip_sie_wrz_paź_lis_gru".split("_"),weekdays:"niedziela_poniedziałek_wtorek_środa_czwartek_piątek_sobota".split("_"),weekdaysShort:"ndz_pon_wt_śr_czw_pt_sob".split("_"),weekdaysMin:"Nd_Pn_Wt_Śr_Cz_Pt_So".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[Dziś o] LT",nextDay:"[Jutro o] LT",nextWeek:function(){switch(this.day()){case 0:return"[W niedzielę o] LT";case 2:return"[We wtorek o] LT";case 3:return"[W środę o] LT";case 6:return"[W sobotę o] LT";default:return"[W] dddd [o] LT"}},lastDay:"[Wczoraj o] LT",lastWeek:function(){switch(this.day()){case 0:return"[W zeszłą niedzielę o] LT";case 3:return"[W zeszłą środę o] LT";case 6:return"[W zeszłą sobotę o] LT";default:return"[W zeszły] dddd [o] LT"}},sameElse:"L"},relativeTime:{future:"za %s",past:"%s temu",s:"kilka sekund",m:n,mm:n,h:n,hh:n,d:"1 dzień",dd:"%d dni",M:"miesiąc",MM:n,y:"rok",yy:n},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}})}(f(0))},function(e,t,f){!function(e){"use strict";var t="jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.".split("_"),f="jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec".split("_"),a=[/^jan/i,/^feb/i,/^maart|mrt.?$/i,/^apr/i,/^mei$/i,/^jun[i.]?$/i,/^jul[i.]?$/i,/^aug/i,/^sep/i,/^okt/i,/^nov/i,/^dec/i],n=/^(januari|februari|maart|april|mei|april|ju[nl]i|augustus|september|oktober|november|december|jan\.?|feb\.?|mrt\.?|apr\.?|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i;e.defineLocale("nl",{months:"januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december".split("_"),monthsShort:function(e,a){return e?/-MMM-/.test(a)?f[e.month()]:t[e.month()]:t},monthsRegex:n,monthsShortRegex:n,monthsStrictRegex:/^(januari|februari|maart|mei|ju[nl]i|april|augustus|september|oktober|november|december)/i,monthsShortStrictRegex:/^(jan\.?|feb\.?|mrt\.?|apr\.?|mei|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i,monthsParse:a,longMonthsParse:a,shortMonthsParse:a,weekdays:"zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag".split("_"),weekdaysShort:"zo._ma._di._wo._do._vr._za.".split("_"),weekdaysMin:"zo_ma_di_wo_do_vr_za".split("_"),weekdaysParseExact:!0,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD-MM-YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[vandaag om] LT",nextDay:"[morgen om] LT",nextWeek:"dddd [om] LT",lastDay:"[gisteren om] LT",lastWeek:"[afgelopen] dddd [om] LT",sameElse:"L"},relativeTime:{future:"over %s",past:"%s geleden",s:"een paar seconden",m:"één minuut",mm:"%d minuten",h:"één uur",hh:"%d uur",d:"één dag",dd:"%d dagen",M:"één maand",MM:"%d maanden",y:"één jaar",yy:"%d jaar"},dayOfMonthOrdinalParse:/\d{1,2}(ste|de)/,ordinal:function(e){return e+(1===e||8===e||e>=20?"ste":"de")},week:{dow:1,doy:4}})}(f(0))},function(e,t,f){!function(e){"use strict";e.defineLocale("nb",{months:"januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember".split("_"),monthsShort:"jan._feb._mars_april_mai_juni_juli_aug._sep._okt._nov._des.".split("_"),monthsParseExact:!0,weekdays:"søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag".split("_"),weekdaysShort:"sø._ma._ti._on._to._fr._lø.".split("_"),weekdaysMin:"sø_ma_ti_on_to_fr_lø".split("_"),weekdaysParseExact:!0,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY [kl.] HH:mm",LLLL:"dddd D. MMMM YYYY [kl.] HH:mm"},calendar:{sameDay:"[i dag kl.] LT",nextDay:"[i morgen kl.] LT",nextWeek:"dddd [kl.] LT",lastDay:"[i går kl.] LT",lastWeek:"[forrige] dddd [kl.] LT",sameElse:"L"},relativeTime:{future:"om %s",past:"%s siden",s:"noen sekunder",m:"ett minutt",mm:"%d minutter",h:"en time",hh:"%d timer",d:"en dag",dd:"%d dager",M:"en måned",MM:"%d måneder",y:"ett år",yy:"%d år"},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}})}(f(0))},function(e,t,f){!function(e){"use strict";e.defineLocale("ja",{months:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),weekdays:"日曜日_月曜日_火曜日_水曜日_木曜日_金曜日_土曜日".split("_"),weekdaysShort:"日_月_火_水_木_金_土".split("_"),weekdaysMin:"日_月_火_水_木_金_土".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"YYYY/MM/DD",LL:"YYYY年M月D日",LLL:"YYYY年M月D日 HH:mm",LLLL:"YYYY年M月D日 HH:mm dddd",l:"YYYY/MM/DD",ll:"YYYY年M月D日",lll:"YYYY年M月D日 HH:mm",llll:"YYYY年M月D日 HH:mm dddd"},meridiemParse:/午前|午後/i,isPM:function(e){return"午後"===e},meridiem:function(e,t,f){return e<12?"午前":"午後"},calendar:{sameDay:"[今日] LT",nextDay:"[明日] LT",nextWeek:"[来週]dddd LT",lastDay:"[昨日] LT",lastWeek:"[前週]dddd LT",sameElse:"L"},dayOfMonthOrdinalParse:/\d{1,2}日/,ordinal:function(e,t){switch(t){case"d":case"D":case"DDD":return e+"日";default:return e}},relativeTime:{future:"%s後",past:"%s前",s:"数秒",m:"1分",mm:"%d分",h:"1時間",hh:"%d時間",d:"1日",dd:"%d日",M:"1ヶ月",MM:"%dヶ月",y:"1年",yy:"%d年"}})}(f(0))},function(e,t,f){!function(e){"use strict";e.defineLocale("it",{months:"gennaio_febbraio_marzo_aprile_maggio_giugno_luglio_agosto_settembre_ottobre_novembre_dicembre".split("_"),monthsShort:"gen_feb_mar_apr_mag_giu_lug_ago_set_ott_nov_dic".split("_"),weekdays:"domenica_lunedì_martedì_mercoledì_giovedì_venerdì_sabato".split("_"),weekdaysShort:"dom_lun_mar_mer_gio_ven_sab".split("_"),weekdaysMin:"do_lu_ma_me_gi_ve_sa".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[Oggi alle] LT",nextDay:"[Domani alle] LT",nextWeek:"dddd [alle] LT",lastDay:"[Ieri alle] LT",lastWeek:function(){switch(this.day()){case 0:return"[la scorsa] dddd [alle] LT";default:return"[lo scorso] dddd [alle] LT"}},sameElse:"L"},relativeTime:{future:function(e){return(/^[0-9].+$/.test(e)?"tra":"in")+" "+e},past:"%s fa",s:"alcuni secondi",m:"un minuto",mm:"%d minuti",h:"un'ora",hh:"%d ore",d:"un giorno",dd:"%d giorni",M:"un mese",MM:"%d mesi",y:"un anno",yy:"%d anni"},dayOfMonthOrdinalParse:/\d{1,2}º/,ordinal:"%dº",week:{dow:1,doy:4}})}(f(0))},function(e,t,f){!function(e){"use strict";e.defineLocale("id",{months:"Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_November_Desember".split("_"),monthsShort:"Jan_Feb_Mar_Apr_Mei_Jun_Jul_Ags_Sep_Okt_Nov_Des".split("_"),weekdays:"Minggu_Senin_Selasa_Rabu_Kamis_Jumat_Sabtu".split("_"),weekdaysShort:"Min_Sen_Sel_Rab_Kam_Jum_Sab".split("_"),weekdaysMin:"Mg_Sn_Sl_Rb_Km_Jm_Sb".split("_"),longDateFormat:{LT:"HH.mm",LTS:"HH.mm.ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY [pukul] HH.mm",LLLL:"dddd, D MMMM YYYY [pukul] HH.mm"},meridiemParse:/pagi|siang|sore|malam/,meridiemHour:function(e,t){return 12===e&&(e=0),"pagi"===t?e:"siang"===t?e>=11?e:e+12:"sore"===t||"malam"===t?e+12:void 0},meridiem:function(e,t,f){return e<11?"pagi":e<15?"siang":e<19?"sore":"malam"},calendar:{sameDay:"[Hari ini pukul] LT",nextDay:"[Besok pukul] LT",nextWeek:"dddd [pukul] LT",lastDay:"[Kemarin pukul] LT",lastWeek:"dddd [lalu pukul] LT",sameElse:"L"},relativeTime:{future:"dalam %s",past:"%s yang lalu",s:"beberapa detik",m:"semenit",mm:"%d menit",h:"sejam",hh:"%d jam",d:"sehari",dd:"%d hari",M:"sebulan",MM:"%d bulan",y:"setahun",yy:"%d tahun"},week:{dow:1,doy:7}})}(f(0))},function(e,t,f){!function(e){"use strict";var t="vasárnap hétfőn kedden szerdán csütörtökön pénteken szombaton".split(" ");function f(e,t,f,a){var n=e;switch(f){case"s":return a||t?"néhány másodperc":"néhány másodperce";case"m":return"egy"+(a||t?" perc":" perce");case"mm":return n+(a||t?" perc":" perce");case"h":return"egy"+(a||t?" óra":" órája");case"hh":return n+(a||t?" óra":" órája");case"d":return"egy"+(a||t?" nap":" napja");case"dd":return n+(a||t?" nap":" napja");case"M":return"egy"+(a||t?" hónap":" hónapja");case"MM":return n+(a||t?" hónap":" hónapja");case"y":return"egy"+(a||t?" év":" éve");case"yy":return n+(a||t?" év":" éve")}return""}function a(e){return(e?"":"[múlt] ")+"["+t[this.day()]+"] LT[-kor]"}e.defineLocale("hu",{months:"január_február_március_április_május_június_július_augusztus_szeptember_október_november_december".split("_"),monthsShort:"jan_feb_márc_ápr_máj_jún_júl_aug_szept_okt_nov_dec".split("_"),weekdays:"vasárnap_hétfő_kedd_szerda_csütörtök_péntek_szombat".split("_"),weekdaysShort:"vas_hét_kedd_sze_csüt_pén_szo".split("_"),weekdaysMin:"v_h_k_sze_cs_p_szo".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"YYYY.MM.DD.",LL:"YYYY. MMMM D.",LLL:"YYYY. MMMM D. H:mm",LLLL:"YYYY. MMMM D., dddd H:mm"},meridiemParse:/de|du/i,isPM:function(e){return"u"===e.charAt(1).toLowerCase()},meridiem:function(e,t,f){return e<12?!0===f?"de":"DE":!0===f?"du":"DU"},calendar:{sameDay:"[ma] LT[-kor]",nextDay:"[holnap] LT[-kor]",nextWeek:function(){return a.call(this,!0)},lastDay:"[tegnap] LT[-kor]",lastWeek:function(){return a.call(this,!1)},sameElse:"L"},relativeTime:{future:"%s múlva",past:"%s",s:f,m:f,mm:f,h:f,hh:f,d:f,dd:f,M:f,MM:f,y:f,yy:f},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}})}(f(0))},function(e,t,f){!function(e){"use strict";e.defineLocale("he",{months:"ינואר_פברואר_מרץ_אפריל_מאי_יוני_יולי_אוגוסט_ספטמבר_אוקטובר_נובמבר_דצמבר".split("_"),monthsShort:"ינו׳_פבר׳_מרץ_אפר׳_מאי_יוני_יולי_אוג׳_ספט׳_אוק׳_נוב׳_דצמ׳".split("_"),weekdays:"ראשון_שני_שלישי_רביעי_חמישי_שישי_שבת".split("_"),weekdaysShort:"א׳_ב׳_ג׳_ד׳_ה׳_ו׳_ש׳".split("_"),weekdaysMin:"א_ב_ג_ד_ה_ו_ש".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D [ב]MMMM YYYY",LLL:"D [ב]MMMM YYYY HH:mm",LLLL:"dddd, D [ב]MMMM YYYY HH:mm",l:"D/M/YYYY",ll:"D MMM YYYY",lll:"D MMM YYYY HH:mm",llll:"ddd, D MMM YYYY HH:mm"},calendar:{sameDay:"[היום ב־]LT",nextDay:"[מחר ב־]LT",nextWeek:"dddd [בשעה] LT",lastDay:"[אתמול ב־]LT",lastWeek:"[ביום] dddd [האחרון בשעה] LT",sameElse:"L"},relativeTime:{future:"בעוד %s",past:"לפני %s",s:"מספר שניות",m:"דקה",mm:"%d דקות",h:"שעה",hh:function(e){return 2===e?"שעתיים":e+" שעות"},d:"יום",dd:function(e){return 2===e?"יומיים":e+" ימים"},M:"חודש",MM:function(e){return 2===e?"חודשיים":e+" חודשים"},y:"שנה",yy:function(e){return 2===e?"שנתיים":e%10==0&&10!==e?e+" שנה":e+" שנים"}},meridiemParse:/אחה"צ|לפנה"צ|אחרי הצהריים|לפני הצהריים|לפנות בוקר|בבוקר|בערב/i,isPM:function(e){return/^(אחה"צ|אחרי הצהריים|בערב)$/.test(e)},meridiem:function(e,t,f){return e<5?"לפנות בוקר":e<10?"בבוקר":e<12?f?'לפנה"צ':"לפני הצהריים":e<18?f?'אחה"צ':"אחרי הצהריים":"בערב"}})}(f(0))},function(e,t,f){!function(e){"use strict";e.defineLocale("fr",{months:"janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre".split("_"),monthsShort:"janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.".split("_"),monthsParseExact:!0,weekdays:"dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi".split("_"),weekdaysShort:"dim._lun._mar._mer._jeu._ven._sam.".split("_"),weekdaysMin:"Di_Lu_Ma_Me_Je_Ve_Sa".split("_"),weekdaysParseExact:!0,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[Aujourd’hui à] LT",nextDay:"[Demain à] LT",nextWeek:"dddd [à] LT",lastDay:"[Hier à] LT",lastWeek:"dddd [dernier à] LT",sameElse:"L"},relativeTime:{future:"dans %s",past:"il y a %s",s:"quelques secondes",m:"une minute",mm:"%d minutes",h:"une heure",hh:"%d heures",d:"un jour",dd:"%d jours",M:"un mois",MM:"%d mois",y:"un an",yy:"%d ans"},dayOfMonthOrdinalParse:/\d{1,2}(er|)/,ordinal:function(e,t){switch(t){case"D":return e+(1===e?"er":"");default:case"M":case"Q":case"DDD":case"d":return e+(1===e?"er":"e");case"w":case"W":return e+(1===e?"re":"e")}},week:{dow:1,doy:4}})}(f(0))},function(e,t,f){!function(e){"use strict";e.defineLocale("eu",{months:"urtarrila_otsaila_martxoa_apirila_maiatza_ekaina_uztaila_abuztua_iraila_urria_azaroa_abendua".split("_"),monthsShort:"urt._ots._mar._api._mai._eka._uzt._abu._ira._urr._aza._abe.".split("_"),monthsParseExact:!0,weekdays:"igandea_astelehena_asteartea_asteazkena_osteguna_ostirala_larunbata".split("_"),weekdaysShort:"ig._al._ar._az._og._ol._lr.".split("_"),weekdaysMin:"ig_al_ar_az_og_ol_lr".split("_"),weekdaysParseExact:!0,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"YYYY-MM-DD",LL:"YYYY[ko] MMMM[ren] D[a]",LLL:"YYYY[ko] MMMM[ren] D[a] HH:mm",LLLL:"dddd, YYYY[ko] MMMM[ren] D[a] HH:mm",l:"YYYY-M-D",ll:"YYYY[ko] MMM D[a]",lll:"YYYY[ko] MMM D[a] HH:mm",llll:"ddd, YYYY[ko] MMM D[a] HH:mm"},calendar:{sameDay:"[gaur] LT[etan]",nextDay:"[bihar] LT[etan]",nextWeek:"dddd LT[etan]",lastDay:"[atzo] LT[etan]",lastWeek:"[aurreko] dddd LT[etan]",sameElse:"L"},relativeTime:{future:"%s barru",past:"duela %s",s:"segundo batzuk",m:"minutu bat",mm:"%d minutu",h:"ordu bat",hh:"%d ordu",d:"egun bat",dd:"%d egun",M:"hilabete bat",MM:"%d hilabete",y:"urte bat",yy:"%d urte"},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:7}})}(f(0))},function(e,t,f){!function(e){"use strict";var t="ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.".split("_"),f="ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic".split("_"),a=[/^ene/i,/^feb/i,/^mar/i,/^abr/i,/^may/i,/^jun/i,/^jul/i,/^ago/i,/^sep/i,/^oct/i,/^nov/i,/^dic/i],n=/^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre|ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i;e.defineLocale("es",{months:"enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre".split("_"),monthsShort:function(e,a){return e?/-MMM-/.test(a)?f[e.month()]:t[e.month()]:t},monthsRegex:n,monthsShortRegex:n,monthsStrictRegex:/^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i,monthsShortStrictRegex:/^(ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i,monthsParse:a,longMonthsParse:a,shortMonthsParse:a,weekdays:"domingo_lunes_martes_miércoles_jueves_viernes_sábado".split("_"),weekdaysShort:"dom._lun._mar._mié._jue._vie._sáb.".split("_"),weekdaysMin:"do_lu_ma_mi_ju_vi_sá".split("_"),weekdaysParseExact:!0,longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD/MM/YYYY",LL:"D [de] MMMM [de] YYYY",LLL:"D [de] MMMM [de] YYYY H:mm",LLLL:"dddd, D [de] MMMM [de] YYYY H:mm"},calendar:{sameDay:function(){return"[hoy a la"+(1!==this.hours()?"s":"")+"] LT"},nextDay:function(){return"[mañana a la"+(1!==this.hours()?"s":"")+"] LT"},nextWeek:function(){return"dddd [a la"+(1!==this.hours()?"s":"")+"] LT"},lastDay:function(){return"[ayer a la"+(1!==this.hours()?"s":"")+"] LT"},lastWeek:function(){return"[el] dddd [pasado a la"+(1!==this.hours()?"s":"")+"] LT"},sameElse:"L"},relativeTime:{future:"en %s",past:"hace %s",s:"unos segundos",m:"un minuto",mm:"%d minutos",h:"una hora",hh:"%d horas",d:"un día",dd:"%d días",M:"un mes",MM:"%d meses",y:"un año",yy:"%d años"},dayOfMonthOrdinalParse:/\d{1,2}º/,ordinal:"%dº",week:{dow:1,doy:4}})}(f(0))},function(e,t,f){!function(e){"use strict";function t(e,t,f,a){var n={m:["eine Minute","einer Minute"],h:["eine Stunde","einer Stunde"],d:["ein Tag","einem Tag"],dd:[e+" Tage",e+" Tagen"],M:["ein Monat","einem Monat"],MM:[e+" Monate",e+" Monaten"],y:["ein Jahr","einem Jahr"],yy:[e+" Jahre",e+" Jahren"]};return t?n[f][0]:n[f][1]}e.defineLocale("de",{months:"Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember".split("_"),monthsShort:"Jan._Feb._März_Apr._Mai_Juni_Juli_Aug._Sep._Okt._Nov._Dez.".split("_"),monthsParseExact:!0,weekdays:"Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag".split("_"),weekdaysShort:"So._Mo._Di._Mi._Do._Fr._Sa.".split("_"),weekdaysMin:"So_Mo_Di_Mi_Do_Fr_Sa".split("_"),weekdaysParseExact:!0,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY HH:mm",LLLL:"dddd, D. MMMM YYYY HH:mm"},calendar:{sameDay:"[heute um] LT [Uhr]",sameElse:"L",nextDay:"[morgen um] LT [Uhr]",nextWeek:"dddd [um] LT [Uhr]",lastDay:"[gestern um] LT [Uhr]",lastWeek:"[letzten] dddd [um] LT [Uhr]"},relativeTime:{future:"in %s",past:"vor %s",s:"ein paar Sekunden",m:t,mm:"%d Minuten",h:t,hh:"%d Stunden",d:t,dd:t,M:t,MM:t,y:t,yy:t},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}})}(f(0))},function(e,t,f){!function(e){"use strict";e.defineLocale("ca",{months:{standalone:"gener_febrer_març_abril_maig_juny_juliol_agost_setembre_octubre_novembre_desembre".split("_"),format:"de gener_de febrer_de març_d'abril_de maig_de juny_de juliol_d'agost_de setembre_d'octubre_de novembre_de desembre".split("_"),isFormat:/D[oD]?(\s)+MMMM/},monthsShort:"gen._febr._març_abr._maig_juny_jul._ag._set._oct._nov._des.".split("_"),monthsParseExact:!0,weekdays:"diumenge_dilluns_dimarts_dimecres_dijous_divendres_dissabte".split("_"),weekdaysShort:"dg._dl._dt._dc._dj._dv._ds.".split("_"),weekdaysMin:"dg_dl_dt_dc_dj_dv_ds".split("_"),weekdaysParseExact:!0,longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM [de] YYYY",ll:"D MMM YYYY",LLL:"D MMMM [de] YYYY [a les] H:mm",lll:"D MMM YYYY, H:mm",LLLL:"dddd D MMMM [de] YYYY [a les] H:mm",llll:"ddd D MMM YYYY, H:mm"},calendar:{sameDay:function(){return"[avui a "+(1!==this.hours()?"les":"la")+"] LT"},nextDay:function(){return"[demà a "+(1!==this.hours()?"les":"la")+"] LT"},nextWeek:function(){return"dddd [a "+(1!==this.hours()?"les":"la")+"] LT"},lastDay:function(){return"[ahir a "+(1!==this.hours()?"les":"la")+"] LT"},lastWeek:function(){return"[el] dddd [passat a "+(1!==this.hours()?"les":"la")+"] LT"},sameElse:"L"},relativeTime:{future:"d'aquí %s",past:"fa %s",s:"uns segons",m:"un minut",mm:"%d minuts",h:"una hora",hh:"%d hores",d:"un dia",dd:"%d dies",M:"un mes",MM:"%d mesos",y:"un any",yy:"%d anys"},dayOfMonthOrdinalParse:/\d{1,2}(r|n|t|è|a)/,ordinal:function(e,t){var f=1===e?"r":2===e?"n":3===e?"r":4===e?"t":"è";return"w"!==t&&"W"!==t||(f="a"),e+f},week:{dow:1,doy:4}})}(f(0))},function(e,t,f){!function(e){"use strict";e.defineLocale("bg",{months:"януари_февруари_март_април_май_юни_юли_август_септември_октомври_ноември_декември".split("_"),monthsShort:"янр_фев_мар_апр_май_юни_юли_авг_сеп_окт_ное_дек".split("_"),weekdays:"неделя_понеделник_вторник_сряда_четвъртък_петък_събота".split("_"),weekdaysShort:"нед_пон_вто_сря_чет_пет_съб".split("_"),weekdaysMin:"нд_пн_вт_ср_чт_пт_сб".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"D.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY H:mm",LLLL:"dddd, D MMMM YYYY H:mm"},calendar:{sameDay:"[Днес в] LT",nextDay:"[Утре в] LT",nextWeek:"dddd [в] LT",lastDay:"[Вчера в] LT",lastWeek:function(){switch(this.day()){case 0:case 3:case 6:return"[В изминалата] dddd [в] LT";case 1:case 2:case 4:case 5:return"[В изминалия] dddd [в] LT"}},sameElse:"L"},relativeTime:{future:"след %s",past:"преди %s",s:"няколко секунди",m:"минута",mm:"%d минути",h:"час",hh:"%d часа",d:"ден",dd:"%d дни",M:"месец",MM:"%d месеца",y:"година",yy:"%d години"},dayOfMonthOrdinalParse:/\d{1,2}-(ев|ен|ти|ви|ри|ми)/,ordinal:function(e){var t=e%10,f=e%100;return 0===e?e+"-ев":0===f?e+"-ен":f>10&&f<20?e+"-ти":1===t?e+"-ви":2===t?e+"-ри":7===t||8===t?e+"-ми":e+"-ти"},week:{dow:1,doy:7}})}(f(0))},function(e,t,f){!function(e){"use strict";var t={1:"١",2:"٢",3:"٣",4:"٤",5:"٥",6:"٦",7:"٧",8:"٨",9:"٩",0:"٠"},f={"١":"1","٢":"2","٣":"3","٤":"4","٥":"5","٦":"6","٧":"7","٨":"8","٩":"9","٠":"0"},a=function(e){return 0===e?0:1===e?1:2===e?2:e%100>=3&&e%100<=10?3:e%100>=11?4:5},n={s:["أقل من ثانية","ثانية واحدة",["ثانيتان","ثانيتين"],"%d ثوان","%d ثانية","%d ثانية"],m:["أقل من دقيقة","دقيقة واحدة",["دقيقتان","دقيقتين"],"%d دقائق","%d دقيقة","%d دقيقة"],h:["أقل من ساعة","ساعة واحدة",["ساعتان","ساعتين"],"%d ساعات","%d ساعة","%d ساعة"],d:["أقل من يوم","يوم واحد",["يومان","يومين"],"%d أيام","%d يومًا","%d يوم"],M:["أقل من شهر","شهر واحد",["شهران","شهرين"],"%d أشهر","%d شهرا","%d شهر"],y:["أقل من عام","عام واحد",["عامان","عامين"],"%d أعوام","%d عامًا","%d عام"]},o=function(e){return function(t,f,o,r){var s=a(t),c=n[e][a(t)];return 2===s&&(c=c[f?0:1]),c.replace(/%d/i,t)}},r=["كانون الثاني يناير","شباط فبراير","آذار مارس","نيسان أبريل","أيار مايو","حزيران يونيو","تموز يوليو","آب أغسطس","أيلول سبتمبر","تشرين الأول أكتوبر","تشرين الثاني نوفمبر","كانون الأول ديسمبر"];e.defineLocale("ar",{months:r,monthsShort:r,weekdays:"الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"),weekdaysShort:"أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت".split("_"),weekdaysMin:"ح_ن_ث_ر_خ_ج_س".split("_"),weekdaysParseExact:!0,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"D/‏M/‏YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},meridiemParse:/ص|م/,isPM:function(e){return"م"===e},meridiem:function(e,t,f){return e<12?"ص":"م"},calendar:{sameDay:"[اليوم عند الساعة] LT",nextDay:"[غدًا عند الساعة] LT",nextWeek:"dddd [عند الساعة] LT",lastDay:"[أمس عند الساعة] LT",lastWeek:"dddd [عند الساعة] LT",sameElse:"L"},relativeTime:{future:"بعد %s",past:"منذ %s",s:o("s"),m:o("m"),mm:o("m"),h:o("h"),hh:o("h"),d:o("d"),dd:o("d"),M:o("M"),MM:o("M"),y:o("y"),yy:o("y")},preparse:function(e){return e.replace(/[١٢٣٤٥٦٧٨٩٠]/g,function(e){return f[e]}).replace(/،/g,",")},postformat:function(e){return e.replace(/\d/g,function(e){return t[e]}).replace(/,/g,"،")},week:{dow:6,doy:12}})}(f(0))},function(e,t,f){!function(e){"use strict";e.defineLocale("af",{months:"Januarie_Februarie_Maart_April_Mei_Junie_Julie_Augustus_September_Oktober_November_Desember".split("_"),monthsShort:"Jan_Feb_Mrt_Apr_Mei_Jun_Jul_Aug_Sep_Okt_Nov_Des".split("_"),weekdays:"Sondag_Maandag_Dinsdag_Woensdag_Donderdag_Vrydag_Saterdag".split("_"),weekdaysShort:"Son_Maa_Din_Woe_Don_Vry_Sat".split("_"),weekdaysMin:"So_Ma_Di_Wo_Do_Vr_Sa".split("_"),meridiemParse:/vm|nm/i,isPM:function(e){return/^nm$/i.test(e)},meridiem:function(e,t,f){return e<12?f?"vm":"VM":f?"nm":"NM"},longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[Vandag om] LT",nextDay:"[Môre om] LT",nextWeek:"dddd [om] LT",lastDay:"[Gister om] LT",lastWeek:"[Laas] dddd [om] LT",sameElse:"L"},relativeTime:{future:"oor %s",past:"%s gelede",s:"'n paar sekondes",m:"'n minuut",mm:"%d minute",h:"'n uur",hh:"%d ure",d:"'n dag",dd:"%d dae",M:"'n maand",MM:"%d maande",y:"'n jaar",yy:"%d jaar"},dayOfMonthOrdinalParse:/\d{1,2}(ste|de)/,ordinal:function(e){return e+(1===e||8===e||e>=20?"ste":"de")},week:{dow:1,doy:4}})}(f(0))},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},function(e,t,f){(function(t,f){ -/*! - * @overview es6-promise - a tiny implementation of Promises/A+. - * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) - * @license Licensed under MIT license - * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE - * @version v4.2.4+314e4831 - */var a;a=function(){"use strict";function e(e){return"function"==typeof e}var a=Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)},n=0,o=void 0,r=void 0,s=function(e,t){h[n]=e,h[n+1]=t,2===(n+=2)&&(r?r(m):v())};var c="undefined"!=typeof window?window:void 0,i=c||{},u=i.MutationObserver||i.WebKitMutationObserver,_="undefined"==typeof self&&void 0!==t&&"[object process]"==={}.toString.call(t),d="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel;function l(){var e=setTimeout;return function(){return e(m,1)}}var h=new Array(1e3);function m(){for(var e=0;e{t.api.listen.on("serviceDiscovered",f),t.disco_entities.each(e=>{const t=e.features.findWhere({var:x.NS.MUC});t&&f(t)})}).catch(j.partial(t.log,j,x.LogLevel.ERROR))}(e):P(t.muc_domain,e)))}t.api.promises.add(["roomsPanelRendered"]),t.api.settings.update({auto_list_rooms:!1,hide_muc_server:!1,muc_disable_moderator_commands:!1,visible_toolbar_buttons:{toggle_occupants:!0}}),t.muc={info_messages:{100:M("This room is not anonymous"),102:M("This room now shows unavailable members"),103:M("This room does not show unavailable members"),104:M("The room configuration has changed"),170:M("Room logging is now enabled"),171:M("Room logging is now disabled"),172:M("This room is now no longer anonymous"),173:M("This room is now semi-anonymous"),174:M("This room is now fully-anonymous"),201:M("A new room has been created")},disconnect_messages:{301:M("You have been banned from this room"),307:M("You have been kicked from this room"),321:M("You have been removed from this room because of an affiliation change"),322:M("You have been removed from this room because the room has changed to members-only and you're not a member"),332:M("You have been removed from this room because the MUC (Multi-user chat) service is being shut down")},action_info_messages:{301:S("%1$s has been banned"),303:S("%1$s's nickname has changed"),307:S("%1$s has been kicked out"),321:S("%1$s has been removed because of an affiliation change"),322:S("%1$s has been removed for not being a member")},new_nickname_messages:{210:S("Your nickname has been automatically set to %1$s"),303:S("Your nickname has been changed to %1$s")}},t.ListChatRoomsModal=t.BootstrapModal.extend({events:{"submit form":"showRooms","click a.room-info":"toggleRoomInfo","change input[name=nick]":"setNick","change input[name=server]":"setDomain","click .open-room":"openRoom"},initialize(){t.BootstrapModal.prototype.initialize.apply(this,arguments),this.model.on("change:muc_domain",this.onDomainChange,this)},toHTML(){return m(j.extend(this.model.toJSON(),{heading_list_chatrooms:M("Query for Chatrooms"),label_server_address:M("Server address"),label_query:M("Show rooms"),server_placeholder:M("conference.example.org")}))},afterRender(){this.el.addEventListener("shown.bs.modal",()=>{this.el.querySelector('input[name="server"]').focus()},!1)},openRoom(e){e.preventDefault();const f=e.target.getAttribute("data-room-jid"),a=e.target.getAttribute("data-room-name");this.modal.hide(),t.api.rooms.open(f,{name:a})},toggleRoomInfo(e){e.preventDefault(),I(e)},onDomainChange(e){t.auto_list_rooms&&this.updateRoomsList()},roomStanzaItemToHTMLElement(e){const t=x.unescapeNode(e.getAttribute("name")||e.getAttribute("jid")),f=document.createElement("div");return f.innerHTML=b({name:x.xmlunescape(t),jid:e.getAttribute("jid"),open_title:M("Click to open this room"),info_title:M("Show more information on this room")}),f.firstChild},removeSpinner(){j.each(this.el.querySelectorAll("span.spinner"),e=>e.parentNode.removeChild(e))},informNoRoomsFound(){const e=this.el.querySelector(".available-chatrooms");e.innerHTML=v({feedback_text:M("No rooms found")});const t=this.el.querySelector('input[name="server"]');t.classList.remove("hidden"),this.removeSpinner()},onRoomsFound(e){const t=this.el.querySelector(".available-chatrooms");if(this.rooms=e.querySelectorAll("query item"),this.rooms.length){t.innerHTML=v({feedback_text:M("Rooms found:")});const e=document.createDocumentFragment(),f=j.reject(j.map(this.rooms,this.roomStanzaItemToHTMLElement),j.isNil);j.each(f,t=>e.appendChild(t)),t.appendChild(e),this.removeSpinner()}else this.informNoRoomsFound();return!0},updateRoomsList(){t.connection.sendIQ(C({to:this.model.get("muc_domain"),from:t.connection.jid,type:"get"}).c("query",{xmlns:x.NS.DISCO_ITEMS}),this.onRoomsFound.bind(this),this.informNoRoomsFound.bind(this),5e3)},showRooms(e){e.preventDefault();const t=new FormData(e.target);this.model.save("muc_domain",t.get("server")),this.updateRoomsList()},setDomain(e){this.model.save({muc_domain:e.target.value})},setNick(e){this.model.save({nick:e.target.value})}}),t.AddChatRoomModal=t.BootstrapModal.extend({events:{"submit form.add-chatroom":"openChatRoom"},toHTML(){return f(j.extend(this.model.toJSON(),{heading_new_chatroom:M("Enter a new Chatroom"),label_room_address:M("Room address"),label_nickname:M("Optional nickname"),chatroom_placeholder:M("name@conference.example.org"),label_join:M("Join")}))},afterRender(){this.el.addEventListener("shown.bs.modal",()=>{this.el.querySelector('input[name="chatroom"]').focus()},!1)},parseRoomDataFromEvent(e){const t=new FormData(e),f=t.get("chatroom"),a=x.getDomainFromJid(f);return this.model.save("muc_domain",a),{jid:f,nick:t.get("nickname")}},openChatRoom(e){e.preventDefault();const f=this.parseRoomDataFromEvent(e.target);t.api.rooms.open(f.jid,f),this.modal.hide(),e.target.reset()}}),t.ChatRoomView=t.ChatBoxView.extend({length:300,tagName:"div",className:"chatbox chatroom hidden",is_chatroom:!0,events:{"change input.fileupload":"onFileSelection","click .close-chatbox-button":"close","click .configure-chatroom-button":"getAndRenderConfigurationForm","click .new-msgs-indicator":"viewUnreadMessages","click .occupant-nick":"onOccupantClicked","click .send-button":"onFormSubmitted","click .toggle-call":"toggleCall","click .toggle-occupants":"toggleOccupants","click .toggle-smiley ul.emoji-picker li":"insertEmoji","click .toggle-smiley":"toggleEmojiMenu","click .upload-file":"toggleFileUpload","keypress .chat-textarea":"keyPressed","input .chat-textarea":"inputChanged"},initialize(){if(this.initDebounced(),this.model.messages.on("add",this.onMessageAdded,this),this.model.messages.on("rendered",this.scrollDown,this),this.model.on("change:affiliation",this.renderHeading,this),this.model.on("change:connection_status",this.afterConnected,this),this.model.on("change:description",this.renderHeading,this),this.model.on("change:name",this.renderHeading,this),this.model.on("change:subject",this.setChatRoomSubject,this),this.model.on("configurationNeeded",this.getAndRenderConfigurationForm,this),this.model.on("destroy",this.hide,this),this.model.on("show",this.show,this),this.model.occupants.on("add",this.showJoinNotification,this),this.model.occupants.on("remove",this.showLeaveNotification,this),this.model.occupants.on("change:show",e=>{e.isMember()&&!j.includes(e.get("states"),"303")&&("offline"===e.get("show")?this.showLeaveNotification(e):"online"===e.get("show")&&this.showJoinNotification(e))}),this.createEmojiPicker(),this.createOccupantsView(),this.render().insertIntoDOM(),this.registerHandlers(),this.model.get("connection_status")!==e.ROOMSTATUS.ENTERED){const e=()=>{N.isPersistableModel(this.model)&&(this.populateAndJoin(),t.emit("chatRoomOpened",this))};this.model.getRoomFeatures().then(e,e)}else this.fetchMessages(),t.emit("chatRoomOpened",this)},render(){return this.el.setAttribute("id",this.model.get("box_id")),this.el.innerHTML=n(),this.renderHeading(),this.renderChatArea(),this.model.get("connection_status")!==e.ROOMSTATUS.ENTERED&&this.showSpinner(),this},renderHeading(){this.el.querySelector(".chat-head-chatroom").innerHTML=this.generateHeadingHTML()},renderChatArea(){if(j.isNull(this.el.querySelector(".chat-area"))){const e=this.el.querySelector(".chatroom-body");e.innerHTML=a({label_message:M("Message"),label_send:M("Send"),show_send_button:t.show_send_button,show_toolbar:t.show_toolbar,unread_msgs:M("You have unread messages")}),e.insertAdjacentElement("beforeend",this.occupantsview.el),this.renderToolbar(l),this.content=this.el.querySelector(".chat-content"),this.toggleOccupants(null,!0)}return this},showChatStateNotification(e){if("me"!==e.get("sender"))return t.ChatBoxView.prototype.showChatStateNotification.apply(this,arguments)},createOccupantsView(){return this.model.occupants.chatroomview=this,this.occupantsview=new t.ChatRoomOccupantsView({model:this.model.occupants}),this.occupantsview.model.on("change:role",this.informOfOccupantsRoleChange,this),this},informOfOccupantsRoleChange(e,t){const f=e._previousAttributes.role;"moderator"===f&&this.showChatEvent(M("%1$s is no longer a moderator",e.get("nick"))),"visitor"===f&&this.showChatEvent(M("%1$s has been given a voice again",e.get("nick"))),"visitor"===e.get("role")&&this.showChatEvent(M("%1$s has been muted",e.get("nick"))),"moderator"===e.get("role")&&this.showChatEvent(M("%1$s is now a moderator",e.get("nick")))},generateHeadingHTML(){return c(j.extend(this.model.toJSON(),{Strophe:x,info_close:M("Close and leave this room"),info_configure:M("Configure this room"),description:this.model.get("description")||""}))},afterShown(){N.isPersistableModel(this.model)&&(this.model.clearUnreadMsgCounter(),this.model.save()),this.occupantsview.setOccupantsHeight(),this.scrollDown(),this.renderEmojiPicker()},show(){N.isVisible(this.el)?this.focus():(N.showElement(this.el),this.afterShown())},afterConnected(){this.model.get("connection_status")===e.ROOMSTATUS.ENTERED&&(this.hideSpinner(),this.setChatState(t.ACTIVE),this.scrollDown(),this.focus())},getToolbarOptions(){return j.extend(t.ChatBoxView.prototype.getToolbarOptions.apply(this,arguments),{label_hide_occupants:M("Hide the list of occupants"),show_occupants_toggle:this.is_chatroom&&t.visible_toolbar_buttons.toggle_occupants})},close(e){this.hide(),L.history.getFragment()==="converse/room?jid="+this.model.get("jid")&&t.router.navigate(""),this.model.leave(),t.ChatBoxView.prototype.close.apply(this,arguments)},setOccupantsVisibility(){this.el.querySelector(".toggle-occupants"),this.model.get("hidden_occupants")?(this.el.querySelector(".chat-area").classList.add("full"),N.hideElement(this.el.querySelector(".occupants"))):(this.el.querySelector(".chat-area").classList.remove("full"),this.el.querySelector(".occupants").classList.remove("hidden")),this.occupantsview.setOccupantsHeight()},toggleOccupants(e,t){e&&(e.preventDefault(),e.stopPropagation()),t||this.model.set({hidden_occupants:!this.model.get("hidden_occupants")}),this.setOccupantsVisibility(),this.scrollDown()},onOccupantClicked(e){this.insertIntoTextArea(e.target.textContent)},handleChatStateNotification(e){e.get("fullname")!==this.model.get("nick")&&e.get("chat_state")!==t.GONE&&t.ChatBoxView.prototype.handleChatStateNotification.apply(this,arguments)},modifyRole(e,f,a,n,o,r){const s=A("item",{nick:f,role:a}),c=C({to:e,type:"set"}).c("query",{xmlns:x.NS.MUC_ADMIN}).cnode(s.node);return null!==n&&c.c("reason",n),t.connection.sendIQ(c,o,r)},validateRoleChangeCommand(e,t){return!(t.length<1||t.length>2)||(this.showErrorMessage(M('Error: the "%1$s" command takes two arguments, the user\'s nickname and optionally a reason.',e),!0),!1)},onCommandError(e){t.log(e,x.LogLevel.FATAL),this.showErrorMessage(M("Sorry, an error happened while running the command. Check your browser's developer console for details."),!0)},parseMessageForCommands(e){const f=t.ChatBoxView.prototype;if(f.parseMessageForCommands.apply(this,arguments))return!0;if(t.muc_disable_moderator_commands)return!1;const a=e.replace(/^\s*/,"").match(/^\/(.*?)(?: (.*))?$/)||[!1,"",""],n=a[2]&&a[2].splitOnce(" ")||[],o=a[1].toLowerCase();switch(o){case"admin":if(!this.validateRoleChangeCommand(o,n))break;this.model.setAffiliation("admin",[{jid:n[0],reason:n[1]}]).then(()=>this.model.occupants.fetchMembers(),e=>this.onCommandError(e));break;case"ban":if(!this.validateRoleChangeCommand(o,n))break;this.model.setAffiliation("outcast",[{jid:n[0],reason:n[1]}]).then(()=>this.model.occupants.fetchMembers(),e=>this.onCommandError(e));break;case"deop":if(!this.validateRoleChangeCommand(o,n))break;this.modifyRole(this.model.get("jid"),n[0],"participant",n[1],void 0,this.onCommandError.bind(this));break;case"help":this.showHelpMessages([`/admin: ${M("Change user's affiliation to admin")}`,`/ban: ${M("Ban user from room")}`,`/clear: ${M("Remove messages")}`,`/deop: ${M("Change user role to participant")}`,`/help: ${M("Show this menu")}`,`/kick: ${M("Kick user from room")}`,`/me: ${M("Write in 3rd person")}`,`/member: ${M("Grant membership to a user")}`,`/mute: ${M("Remove user's ability to post messages")}`,`/nick: ${M("Change your nickname")}`,`/op: ${M("Grant moderator role to user")}`,`/owner: ${M("Grant ownership of this room")}`,`/revoke: ${M("Revoke user's membership")}`,`/subject: ${M("Set room subject")}`,`/topic: ${M("Set room subject (alias for /subject)")}`,`/voice: ${M("Allow muted user to post messages")}`]);break;case"kick":if(!this.validateRoleChangeCommand(o,n))break;this.modifyRole(this.model.get("jid"),n[0],"none",n[1],void 0,this.onCommandError.bind(this));break;case"mute":if(!this.validateRoleChangeCommand(o,n))break;this.modifyRole(this.model.get("jid"),n[0],"visitor",n[1],void 0,this.onCommandError.bind(this));break;case"member":if(!this.validateRoleChangeCommand(o,n))break;this.model.setAffiliation("member",[{jid:n[0],reason:n[1]}]).then(()=>this.model.occupants.fetchMembers(),e=>this.onCommandError(e));break;case"nick":t.connection.send(H({from:t.connection.jid,to:this.model.getRoomJIDAndNick(a[2]),id:t.connection.getUniqueId()}).tree());break;case"owner":if(!this.validateRoleChangeCommand(o,n))break;this.model.setAffiliation("owner",[{jid:n[0],reason:n[1]}]).then(()=>this.model.occupants.fetchMembers(),e=>this.onCommandError(e));break;case"op":if(!this.validateRoleChangeCommand(o,n))break;this.modifyRole(this.model.get("jid"),n[0],"moderator",n[1],void 0,this.onCommandError.bind(this));break;case"revoke":if(!this.validateRoleChangeCommand(o,n))break;this.model.setAffiliation("none",[{jid:n[0],reason:n[1]}]).then(()=>this.model.occupants.fetchMembers(),e=>this.onCommandError(e));break;case"topic":case"subject":t.connection.send(E({to:this.model.get("jid"),from:t.connection.jid,type:"groupchat"}).c("subject",{xmlns:"jabber:client"}).t(a[2]).tree());break;case"voice":if(!this.validateRoleChangeCommand(o,n))break;this.modifyRole(this.model.get("jid"),n[0],"participant",n[1],void 0,this.onCommandError.bind(this));break;default:return!1}return!0},registerHandlers(){this.model.addHandler("presence","ChatRoomView.onPresence",this.onPresence.bind(this)),this.model.addHandler("message","ChatRoomView.showStatusMessages",this.showStatusMessages.bind(this))},onPresence(e){"error"===e.getAttribute("type")?this.showErrorMessageFromPresence(e):this.showStatusMessages(e)},populateAndJoin(){this.model.occupants.fetchMembers(),this.join(),this.fetchMessages()},join(e,t){return e||this.model.get("nick")?(this.model.join(e,t),this):(this.checkForReservedNick(),this)},renderConfigurationForm(e){const t=this.el.querySelector(".chatroom-body");j.each(t.querySelectorAll(".chatroom-form-container"),N.removeElement),j.each(t.children,N.hideElement),t.insertAdjacentHTML("beforeend",s());const f=t.querySelector("form.chatroom-form"),a=f.querySelector("fieldset"),n=e.querySelectorAll("field"),o=j.get(e.querySelector("title"),"textContent"),r=j.get(e.querySelector("instructions"),"textContent");N.removeElement(a.querySelector("span.spinner")),a.insertAdjacentHTML("beforeend",`${o}`),r&&r!==o&&a.insertAdjacentHTML("beforeend",`

${r}

`),j.each(n,function(t){a.insertAdjacentHTML("beforeend",N.xForm2webForm(t,e))});const c=document.createElement("fieldset");c.insertAdjacentHTML("beforeend",``),c.insertAdjacentHTML("beforeend",``),f.insertAdjacentElement("beforeend",c),c.querySelector("input[type=button]").addEventListener("click",e=>{e.preventDefault(),this.closeForm()}),f.addEventListener("submit",e=>{e.preventDefault(),this.model.saveConfiguration(e.target).then(this.model.getRoomFeatures.bind(this.model)),this.closeForm()},!1)},closeForm(){N.removeElement(this.el.querySelector(".chatroom-form-container")),this.renderAfterTransition()},getAndRenderConfigurationForm(e){this.showSpinner(),this.model.fetchRoomConfiguration().then(this.renderConfigurationForm.bind(this)).catch(j.partial(t.log,j,x.LogLevel.ERROR))},submitNickname(e){e.preventDefault();const t=e.target.nick,f=t.value;f?(t.classList.remove("error"),this.el.querySelector(".chatroom-form-container").outerHTML=w(),this.join(f)):t.classList.add("error")},checkForReservedNick(){this.showSpinner(),this.model.checkForReservedNick(this.onNickNameFound.bind(this),this.onNickNameNotFound.bind(this))},onNickNameFound(e){const t=e.querySelector('query[node="x-roomuser-item"] identity'),f=t?t.getAttribute("name"):null;f?this.join(f):this.onNickNameNotFound()},onNickNameNotFound(e){const t=this.getDefaultNickName();t?this.join(t):this.renderNicknameForm(e)},getDefaultNickName(){const e=t.xmppstatus.vcard.get("nickname");return e||(t.muc_nickname_from_jid?x.unescapeNode(x.getNodeFromJid(t.bare_jid)):void 0)},onNicknameClash(e){if(t.muc_nickname_from_jid){const t=e.getAttribute("from").split("/")[1];if(t===this.getDefaultNickName())this.join(t+"-2");else{const e=t.lastIndexOf("-"),f=t.substring(e+1,t.length);this.join(t.substring(0,e+1)+String(Number(f)+1))}}else this.renderNicknameForm(M("The nickname you chose is reserved or currently in use, please choose a different one."))},hideChatRoomContents(){const e=this.el.querySelector(".chatroom-body");j.isNull(e)||j.each(e.children,e=>{e.classList.add("hidden")})},renderNicknameForm(t){this.hideChatRoomContents(),j.each(this.el.querySelectorAll("span.centered.spinner"),N.removeElement),j.isString(t)||(t="");const f=this.el.querySelector(".chatroom-body");f.insertAdjacentHTML("beforeend",u({heading:M("Please choose your nickname"),label_nickname:M("Nickname"),label_join:M("Enter room"),validation_message:t})),this.model.save("connection_status",e.ROOMSTATUS.NICKNAME_REQUIRED);const a=this.el.querySelector(".chatroom-form");a.addEventListener("submit",this.submitNickname.bind(this),!1)},submitPassword(e){e.preventDefault();const t=this.el.querySelector(".chatroom-form input[type=password]").value;this.showSpinner(),this.join(this.model.get("nick"),t)},renderPasswordForm(){const t=this.el.querySelector(".chatroom-body");j.each(t.children,N.hideElement),j.each(this.el.querySelectorAll(".spinner"),N.removeElement),t.insertAdjacentHTML("beforeend",_({heading:M("This chatroom requires a password"),label_password:M("Password: "),label_submit:M("Submit")})),this.model.save("connection_status",e.ROOMSTATUS.PASSWORD_REQUIRED),this.el.querySelector(".chatroom-form").addEventListener("submit",this.submitPassword.bind(this),!1)},showDisconnectMessage(e){N.hideElement(this.el.querySelector(".chat-area")),N.hideElement(this.el.querySelector(".occupants")),j.each(this.el.querySelectorAll(".spinner"),N.removeElement),this.el.querySelector(".chatroom-body").insertAdjacentHTML("beforeend",o({disconnect_message:e}))},getMessageFromStatus(e,f,a){const n=e.getAttribute("code");if("110"===n||"100"===n&&!a)return;if(n in t.muc.info_messages)return t.muc.info_messages[n];let o;if(a){if(n in t.muc.new_nickname_messages)return a&&"210"===n?o=x.getResourceFromJid(f.getAttribute("from")):a&&"303"===n&&(o=f.querySelector("x item").getAttribute("nick")),M(t.muc.new_nickname_messages[n],o)}else if(n in t.muc.action_info_messages)return o=x.getResourceFromJid(f.getAttribute("from")),M(t.muc.action_info_messages[n],o)},parseXUserElement(e,f,a){const n=e.querySelectorAll("status"),o=j.partial(this.getMessageFromStatus,j,f,a),r={},s=j.reject(j.map(n,o),j.isUndefined);s.length&&(r.messages=s);const c=j.invokeMap(n,Element.prototype.getAttribute,"code"),i=j.intersection(c,j.keys(t.muc.disconnect_messages)),u=a&&i.length>0;u&&(r.disconnected=!0,r.disconnection_message=t.muc.disconnect_messages[i[0]]);const _=e.querySelector("item");if(!j.isNull(_)){const e=_.querySelector("reason");e&&(r.reason=e?e.textContent:void 0);const t=_.querySelector("actor");t&&(r.actor=t?t.getAttribute("nick"):void 0)}return r},showNotificationsforUser(t){if(t.disconnected)return this.showDisconnectMessage(t.disconnection_message),t.actor&&this.showDisconnectMessage(M("This action was done by %1$s.",t.actor)),t.reason&&this.showDisconnectMessage(M('The reason given is: "%1$s".',t.reason)),void this.model.save("connection_status",e.ROOMSTATUS.DISCONNECTED);j.each(t.messages,e=>{this.content.insertAdjacentHTML("beforeend",h({data:"",isodate:T().format(),extra_classes:"chat-event",message:e}))}),t.reason&&this.showChatEvent(M('The reason given is: "%1$s".',t.reason)),j.get(t.messages,"length")&&this.scrollDown()},showJoinNotification(t){if(this.model.get("connection_status")!==e.ROOMSTATUS.ENTERED)return;const f=t.get("nick"),a=t.get("status"),n=this.content.lastElementChild;if(j.includes(j.get(n,"classList",[]),"chat-info")&&j.get(n,"dataset",{}).leave===`"${f}"`)n.outerHTML=h({data:`data-leavejoin="${f}"`,isodate:T().format(),extra_classes:"chat-event",message:M("%1$s has left and re-entered the room",f)});else{let e;e=j.isNil(a)?M("%1$s has entered the room",f):M('%1$s has entered the room. "%2$s"',f,a);const t={data:`data-join="${f}"`,isodate:T().format(),extra_classes:"chat-event",message:e};if(j.includes(j.get(n,"classList",[]),"chat-info")&&j.get(n,"dataset",{}).joinleave===`"${f}"`)n.outerHTML=h(t);else{const e=N.stringToElement(h(t));this.content.insertAdjacentElement("beforeend",e),this.insertDayIndicator(e)}}this.scrollDown()},showLeaveNotification(e){const t=e.get("nick"),f=e.get("status"),a=this.content.lastElementChild,n=a.getAttribute("data-isodate");if(j.includes(j.get(a,"classList",[]),"chat-info")&&T(n).isSame(new Date,"day")&&j.get(a,"dataset",{}).join===`"${t}"`){let e;e=j.isNil(f)?M("%1$s has entered and left the room",t):M('%1$s has entered and left the room. "%2$s"',t,f),a.outerHTML=h({data:`data-joinleave="${t}"`,isodate:T().format(),extra_classes:"chat-event",message:e})}else{let e;const n={message:e=j.isNil(f)?M("%1$s has left the room",t):M('%1$s has left the room. "%2$s"',t,f),isodate:T().format(),extra_classes:"chat-event",data:`data-leave="${t}"`};if(j.includes(j.get(a,"classList",[]),"chat-info")&&j.get(a,"dataset",{}).leavejoin===`"${t}"`)a.outerHTML=h(n);else{const e=N.stringToElement(h(n));this.content.insertAdjacentElement("beforeend",e),this.insertDayIndicator(e)}}this.scrollDown()},showStatusMessages(e){const t=Y(`x[xmlns="${x.NS.MUC_USER}"]`,e),f=e.querySelectorAll("status[code='110']").length,a=j.partial(this.parseXUserElement.bind(this),j,e,f),n=j.reject(j.map(t,a),j.isEmpty);j.each(n,this.showNotificationsforUser.bind(this))},showErrorMessageFromPresence(e){const t=e.querySelector("error");"auth"===t.getAttribute("type")?j.isNull(t.querySelector("not-authorized"))?j.isNull(t.querySelector("registration-required"))?j.isNull(t.querySelector("forbidden"))||this.showDisconnectMessage(M("You have been banned from this room.")):this.showDisconnectMessage(M("You are not on the member list of this room.")):this.renderPasswordForm():"modify"===t.getAttribute("type")?j.isNull(t.querySelector("jid-malformed"))||this.showDisconnectMessage(M("No nickname was specified.")):"cancel"===t.getAttribute("type")&&(j.isNull(t.querySelector("not-allowed"))?j.isNull(t.querySelector("not-acceptable"))?j.isNull(t.querySelector("conflict"))?j.isNull(t.querySelector("item-not-found"))?j.isNull(t.querySelector("service-unavailable"))||this.showDisconnectMessage(M("This room has reached its maximum number of occupants.")):this.showDisconnectMessage(M("This room does not (yet) exist.")):this.onNicknameClash(e):this.showDisconnectMessage(M("Your nickname doesn't conform to this room's policies.")):this.showDisconnectMessage(M("You are not allowed to create new rooms.")))},renderAfterTransition(){this.model.get("connection_status")==e.ROOMSTATUS.NICKNAME_REQUIRED?this.renderNicknameForm():this.model.get("connection_status")==e.ROOMSTATUS.PASSWORD_REQUIRED?this.renderPasswordForm():(this.el.querySelector(".chat-area").classList.remove("hidden"),this.setOccupantsVisibility(),this.scrollDown())},showSpinner(){N.removeElement(this.el.querySelector(".spinner"));const e=this.el.querySelector(".chatroom-body"),t=Array.prototype.slice.call(e.children,0);e.insertAdjacentHTML("afterbegin",w()),j.each(t,N.hideElement)},hideSpinner(){const e=this.el.querySelector(".spinner");return j.isNull(e)||(N.removeElement(e),this.renderAfterTransition()),this},setChatRoomSubject(){const e=this.model.get("subject");this.content.insertAdjacentHTML("beforeend",h({data:"",isodate:T().format(),extra_classes:"chat-event",message:M("Topic set by %1$s",e.author)})),this.content.insertAdjacentHTML("beforeend",h({data:"",isodate:T().format(),extra_classes:"chat-topic",message:e.text})),this.scrollDown()}}),t.RoomsPanel=L.NativeView.extend({tagName:"div",className:"controlbox-section",id:"chatrooms",events:{"click a.chatbox-btn.fa-users":"showAddRoomModal","click a.chatbox-btn.fa-list-ul":"showListRoomsModal","click a.room-info":"toggleRoomInfo"},render(){return this.el.innerHTML=y({heading_chatrooms:M("Chatrooms"),title_new_room:M("Add a new room"),title_list_rooms:M("Query for rooms")}),this},toggleRoomInfo(e){e.preventDefault(),I(e)},showAddRoomModal(e){j.isUndefined(this.add_room_modal)&&(this.add_room_modal=new t.AddChatRoomModal({model:this.model})),this.add_room_modal.show(e)},showListRoomsModal(e){j.isUndefined(this.list_rooms_modal)&&(this.list_rooms_modal=new t.ListChatRoomsModal({model:this.model})),this.list_rooms_modal.show(e)}}),t.ChatRoomOccupantView=L.VDOMView.extend({tagName:"li",initialize(){this.model.on("change",this.render,this)},toHTML(){const e=this.model.get("show");return g(j.extend({jid:"",show:e,hint_show:t.PRETTY_CHAT_STATUS[e],hint_occupant:M("Click to mention %1$s in your message.",this.model.get("nick")),desc_moderator:M("This user is a moderator."),desc_participant:M("This user can send messages in this room."),desc_visitor:M("This user can NOT send messages in this room."),label_moderator:M("Moderator"),label_visitor:M("Visitor"),label_owner:M("Owner"),label_member:M("Member"),label_admin:M("Admin")},this.model.toJSON()))},destroy(){this.el.parentElement.removeChild(this.el)}}),t.ChatRoomOccupantsView=L.OrderedListView.extend({tagName:"div",className:"occupants col-md-3 col-4",listItems:"model",sortEvent:"change:role",listSelector:".occupant-list",ItemView:t.ChatRoomOccupantView,initialize(){L.OrderedListView.prototype.initialize.apply(this,arguments),this.chatroomview=this.model.chatroomview,this.chatroomview.model.on("change:open",this.renderInviteWidget,this),this.chatroomview.model.on("change:affiliation",this.renderInviteWidget,this),this.chatroomview.model.on("change:hidden",this.onFeatureChanged,this),this.chatroomview.model.on("change:mam_enabled",this.onFeatureChanged,this),this.chatroomview.model.on("change:membersonly",this.onFeatureChanged,this),this.chatroomview.model.on("change:moderated",this.onFeatureChanged,this),this.chatroomview.model.on("change:nonanonymous",this.onFeatureChanged,this),this.chatroomview.model.on("change:open",this.onFeatureChanged,this),this.chatroomview.model.on("change:passwordprotected",this.onFeatureChanged,this),this.chatroomview.model.on("change:persistent",this.onFeatureChanged,this),this.chatroomview.model.on("change:publicroom",this.onFeatureChanged,this),this.chatroomview.model.on("change:semianonymous",this.onFeatureChanged,this),this.chatroomview.model.on("change:temporary",this.onFeatureChanged,this),this.chatroomview.model.on("change:unmoderated",this.onFeatureChanged,this),this.chatroomview.model.on("change:unsecured",this.onFeatureChanged,this),this.render(),this.model.fetch({add:!0,silent:!0,success:this.sortAndPositionAllItems.bind(this)})},render(){return this.el.innerHTML=d(j.extend(this.chatroomview.model.toJSON(),{allow_muc_invitations:t.allow_muc_invitations,label_occupants:M("Occupants")})),t.allow_muc_invitations&&t.api.waitUntil("rosterContactsFetched").then(this.renderInviteWidget.bind(this)),this.renderRoomFeatures()},renderInviteWidget(){const e=this.el.querySelector("form.room-invite");if(this.shouldInviteWidgetBeShown()){if(j.isNull(e)){const e=this.el.querySelector(".occupants-heading");e.insertAdjacentHTML("afterend",i({error_message:null,label_invitation:M("Invite")})),this.initInviteWidget()}}else j.isNull(e)||e.remove();return this},renderRoomFeatures(){const t=j.pick(this.chatroomview.model.attributes,e.ROOM_FEATURES),f=this.el.querySelector(".chatroom-features");return f.innerHTML=r(j.extend(this.chatroomview.model.toJSON(),{has_features:j.reduce(j.values(t),(e,t)=>e||t),label_features:M("Features"),label_hidden:M("Hidden"),label_mam_enabled:M("Message archiving"),label_membersonly:M("Members only"),label_moderated:M("Moderated"),label_nonanonymous:M("Non-anonymous"),label_open:M("Open"),label_passwordprotected:M("Password protected"),label_persistent:M("Persistent"),label_public:M("Public"),label_semianonymous:M("Semi-anonymous"),label_temporary:M("Temporary"),label_unmoderated:M("Unmoderated"),label_unsecured:M("No password"),tt_hidden:M("This room is not publicly searchable"),tt_mam_enabled:M("Messages are archived on the server"),tt_membersonly:M("This room is restricted to members only"),tt_moderated:M("This room is being moderated"),tt_nonanonymous:M("All other room occupants can see your XMPP username"),tt_open:M("Anyone can join this room"),tt_passwordprotected:M("This room requires a password before entry"),tt_persistent:M("This room persists even if it's unoccupied"),tt_public:M("This room is publicly searchable"),tt_semianonymous:M("Only moderators can see your XMPP username"),tt_temporary:M("This room will disappear once the last person leaves"),tt_unmoderated:M("This room is not being moderated"),tt_unsecured:M("This room does not require a password upon entry")})),this.setOccupantsHeight(),this},onFeatureChanged(e){j.isUndefined(this.debouncedRenderRoomFeatures)&&(this.debouncedRenderRoomFeatures=j.debounce(this.renderRoomFeatures,100,{leading:!1}));const t={};j.each(j.keys(e.changed),function(f){j.isNil(O[f])||(t[O[f]]=!e.changed[f])}),this.chatroomview.model.save(t,{silent:!0}),this.debouncedRenderRoomFeatures()},setOccupantsHeight(){const e=this.el.querySelector(".chatroom-features");this.el.querySelector(".occupant-list").style.cssText=`height: calc(100% - ${e.offsetHeight}px - 5em);`},promptForInvite(e){const t=prompt(M('You are about to invite %1$s to the chat room "%2$s". You may optionally include a message, explaining the reason for the invitation.',e.text.label,this.model.get("id")));null!==t&&this.chatroomview.model.directInvite(e.text.value,t);const f=e.target.form,a=f.querySelector(".pure-form-message.error");j.isNull(a)||a.parentNode.removeChild(a),e.target.value=""},inviteFormSubmitted(e){e.preventDefault();const t=e.target.querySelector("input.invited-contact"),f=t.value;if(!f||j.compact(f.split("@")).length<2)return e.target.outerHTML=i({error_message:M("Please enter a valid XMPP username"),label_invitation:M("Invite")}),void this.initInviteWidget();this.promptForInvite({target:t,text:{label:f,value:f}})},shouldInviteWidgetBeShown(){return t.allow_muc_invitations&&(this.chatroomview.model.get("open")||"owner"===this.chatroomview.model.get("affiliation"))},initInviteWidget(){const e=this.el.querySelector("form.room-invite");if(j.isNull(e))return;e.addEventListener("submit",this.inviteFormSubmitted.bind(this),!1);const f=this.el.querySelector("input.invited-contact"),a=t.roster.map(function(e){const t=e.get("fullname")||e.get("jid");return{label:t,value:e.get("jid")}});new k(f,{minChars:1,list:a}),f.addEventListener("awesomplete-selectcomplete",this.promptForInvite.bind(this))}}),t.on("controlboxInitialized",e=>{t.allow_muc&&(z(e),e.model.on("change:connected",j.partial(z,e)))}),t.on("reconnected",function(){t.chatboxviews.each(function(t){t.model.get("type")===e.CHATROOMS_TYPE&&(t.model.save("connection_status",e.ROOMSTATUS.DISCONNECTED),t.model.registerHandlers(),t.populateAndJoin())})})}})})?a.apply(t,n):a)||(e.exports=o)},function(e,t,f){"use strict";var a,n,o;n=[f(2),f(206),f(205)],void 0===(o="function"==typeof(a=function(e,t,f){const a=e.env,n=a.Backbone,o=a.Promise,r=a.Strophe,s=(a.SHA1,a._),c=a.$iq,i=(a.$build,a.b64_sha1),u=a.moment;a.sizzle,e.env.utils,e.plugins.add("converse-vcard",{initialize(){const e=this._converse;function a(e,f,a,n){const o=a.querySelector("vCard");let r={};if(s.isNull(o)||(r={stanza:a,fullname:s.get(o.querySelector("FN"),"textContent"),nickname:s.get(o.querySelector("NICKNAME"),"textContent"),image:s.get(o.querySelector("PHOTO BINVAL"),"textContent"),image_type:s.get(o.querySelector("PHOTO TYPE"),"textContent"),url:s.get(o.querySelector("URL"),"textContent"),role:s.get(o.querySelector("ROLE"),"textContent"),email:s.get(o.querySelector("EMAIL USERID"),"textContent")}),r.image){const e=t.enc.Base64.parse(r.image);r.image_hash=t.SHA1(e).toString()}n&&n(r)}function _(e,t,f,a){a&&a({stanza:f,jid:t})}function d(e,t,f){const a=c(t?{type:e,to:t}:{type:e});return f?a.cnode(f):a.c("vCard",{xmlns:r.NS.VCARD}),a}function l(e,t){return t=r.getBareJidFromJid(t)===e.bare_jid?null:t,new o((f,n)=>{e.connection.sendIQ(d("get",t),s.partial(a,e,t,s,f),s.partial(_,e,t,s,f),5e3)})}e.VCard=n.Model.extend({defaults:{image:e.DEFAULT_IMAGE,image_type:e.DEFAULT_IMAGE_TYPE},set(t,f,a){let o;return"object"==typeof t?(o=t,a=f):(o={})[t]=f,s.has(o,"image")&&!o.image?(o.image=e.DEFAULT_IMAGE,o.image_type=e.DEFAULT_IMAGE_TYPE,n.Model.prototype.set.call(this,o,a)):n.Model.prototype.set.apply(this,arguments)}}),e.VCards=n.Collection.extend({model:e.VCard,initialize(){this.on("add",t=>e.api.vcard.update(t))}}),e.initVCardCollection=function(){e.vcards=new e.VCards,e.vcards.browserStorage=new n.BrowserStorage[e.storage](i("converse.vcards")),e.vcards.fetch()},e.api.listen.on("connectionInitialized",e.initVCardCollection),e.on("addClientFeatures",()=>{e.api.disco.own.features.add(r.NS.VCARD)}),s.extend(e.api,{vcard:{set:function(t){return new o((a,n)=>{const o=r.xmlHtmlNode(f(t)).firstElementChild;e.connection.sendIQ(d("set",t.jid,o),a,n)})},get(t,f){if(s.isString(t))return l(e,t);if(!t.get("vcard_updated")||f){const f=t.get("jid")||t.get("muc_jid");if(!f)throw new Error("No JID to get vcard for!");return l(e,f)}return o.resolve({})},update(e,t){return new o((f,a)=>{this.get(e,t).then(t=>{e.save(s.extend(s.pick(t,["fullname","nickname","email","url","role","image_type","image","image_hash"]),{vcard_updated:u().format()})),f()})})}}})}})})?a.apply(t,n):a)||(e.exports=o)},function(e,t){!function(){var t=function(e,f){var a=this;this.isOpened=!1,this.input=n(e),this.input.setAttribute("autocomplete","off"),this.input.setAttribute("aria-autocomplete","list"),f=f||{},function(e,t,f){for(var a in t){var n=t[a],o=e.input.getAttribute("data-"+a.toLowerCase());"number"==typeof n?e[a]=parseInt(o):!1===n?e[a]=null!==o:n instanceof Function?e[a]=null:e[a]=o,e[a]||0===e[a]||(e[a]=a in f?f[a]:n)}}(this,{minChars:2,maxItems:10,autoFirst:!1,data:t.DATA,filter:t.FILTER_CONTAINS,sort:!1!==f.sort&&t.SORT_BYLENGTH,item:t.ITEM,replace:t.REPLACE},f),this.index=-1,this.container=n.create("div",{className:"awesomplete",around:e}),this.ul=n.create("ul",{hidden:"hidden",inside:this.container}),this.status=n.create("span",{className:"visually-hidden",role:"status","aria-live":"assertive","aria-relevant":"additions",inside:this.container}),this._events={input:{input:this.evaluate.bind(this),blur:this.close.bind(this,{reason:"blur"}),keydown:function(e){var t=e.keyCode;a.opened&&(13===t&&a.selected?(e.preventDefault(),a.select()):27===t?a.close({reason:"esc"}):38!==t&&40!==t||(e.preventDefault(),a[38===t?"previous":"next"]()))}},form:{submit:this.close.bind(this,{reason:"submit"})},ul:{mousedown:function(e){var t=e.target;if(t!==this){for(;t&&!/li/i.test(t.nodeName);)t=t.parentNode;t&&0===e.button&&(e.preventDefault(),a.select(t,e.target))}}}},n.bind(this.input,this._events.input),n.bind(this.input.form,this._events.form),n.bind(this.ul,this._events.ul),this.input.hasAttribute("list")?(this.list="#"+this.input.getAttribute("list"),this.input.removeAttribute("list")):this.list=this.input.getAttribute("data-list")||f.list||[],t.all.push(this)};function f(e){var t=Array.isArray(e)?{label:e[0],value:e[1]}:"object"==typeof e&&"label"in e&&"value"in e?e:{label:e,value:e};this.label=t.label||t.value,this.value=t.value}t.prototype={set list(e){if(Array.isArray(e))this._list=e;else if("string"==typeof e&&e.indexOf(",")>-1)this._list=e.split(/\s*,\s*/);else if((e=n(e))&&e.children){var t=[];a.apply(e.children).forEach(function(e){if(!e.disabled){var f=e.textContent.trim(),a=e.value||f,n=e.label||f;""!==a&&t.push({label:n,value:a})}}),this._list=t}document.activeElement===this.input&&this.evaluate()},get selected(){return this.index>-1},get opened(){return this.isOpened},close:function(e){this.opened&&(this.ul.setAttribute("hidden",""),this.isOpened=!1,this.index=-1,n.fire(this.input,"awesomplete-close",e||{}))},open:function(){this.ul.removeAttribute("hidden"),this.isOpened=!0,this.autoFirst&&-1===this.index&&this.goto(0),n.fire(this.input,"awesomplete-open")},destroy:function(){n.unbind(this.input,this._events.input),n.unbind(this.input.form,this._events.form);var e=this.container.parentNode;e.insertBefore(this.input,this.container),e.removeChild(this.container),this.input.removeAttribute("autocomplete"),this.input.removeAttribute("aria-autocomplete");var f=t.all.indexOf(this);-1!==f&&t.all.splice(f,1)},next:function(){var e=this.ul.children.length;this.goto(this.index-1&&t.length>0&&(t[e].setAttribute("aria-selected","true"),this.status.textContent=t[e].textContent,this.ul.scrollTop=t[e].offsetTop-this.ul.clientHeight+t[e].clientHeight,n.fire(this.input,"awesomplete-highlight",{text:this.suggestions[this.index]}))},select:function(e,t){if(e?this.index=n.siblingIndex(e):e=this.ul.children[this.index],e){var f=this.suggestions[this.index];n.fire(this.input,"awesomplete-select",{text:f,origin:t||e})&&(this.replace(f),this.close({reason:"select"}),n.fire(this.input,"awesomplete-selectcomplete",{text:f}))}},evaluate:function(){var e=this,t=this.input.value;t.length>=this.minChars&&this._list.length>0?(this.index=-1,this.ul.innerHTML="",this.suggestions=this._list.map(function(a){return new f(e.data(a,t))}).filter(function(f){return e.filter(f,t)}),!1!==this.sort&&(this.suggestions=this.suggestions.sort(this.sort)),this.suggestions=this.suggestions.slice(0,this.maxItems),this.suggestions.forEach(function(f){e.ul.appendChild(e.item(f,t))}),0===this.ul.children.length?this.close({reason:"nomatches"}):this.open()):this.close({reason:"nomatches"})}},t.all=[],t.FILTER_CONTAINS=function(e,t){return RegExp(n.regExpEscape(t.trim()),"i").test(e)},t.FILTER_STARTSWITH=function(e,t){return RegExp("^"+n.regExpEscape(t.trim()),"i").test(e)},t.SORT_BYLENGTH=function(e,t){return e.length!==t.length?e.length-t.length:e>> 1; + + /** Used to associate wrap methods with their bit flags. */ + var wrapFlags = [ + ['ary', WRAP_ARY_FLAG], + ['bind', WRAP_BIND_FLAG], + ['bindKey', WRAP_BIND_KEY_FLAG], + ['curry', WRAP_CURRY_FLAG], + ['curryRight', WRAP_CURRY_RIGHT_FLAG], + ['flip', WRAP_FLIP_FLAG], + ['partial', WRAP_PARTIAL_FLAG], + ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], + ['rearg', WRAP_REARG_FLAG] + ]; + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + asyncTag = '[object AsyncFunction]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + domExcTag = '[object DOMException]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag = '[object Map]', + numberTag = '[object Number]', + nullTag = '[object Null]', + objectTag = '[object Object]', + promiseTag = '[object Promise]', + proxyTag = '[object Proxy]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]', + undefinedTag = '[object Undefined]', + weakMapTag = '[object WeakMap]', + weakSetTag = '[object WeakSet]'; + + var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + + /** Used to match empty string literals in compiled template source. */ + var reEmptyStringLeading = /\b__p \+= '';/g, + reEmptyStringMiddle = /\b(__p \+=) '' \+/g, + reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; + + /** Used to match HTML entities and HTML characters. */ + var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, + reUnescapedHtml = /[&<>"']/g, + reHasEscapedHtml = RegExp(reEscapedHtml.source), + reHasUnescapedHtml = RegExp(reUnescapedHtml.source); + + /** Used to match template delimiters. */ + var reEscape = /<%-([\s\S]+?)%>/g, + reEvaluate = /<%([\s\S]+?)%>/g, + reInterpolate = /<%=([\s\S]+?)%>/g; + + /** Used to match property names within property paths. */ + var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/, + reLeadingDot = /^\./, + rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + + /** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, + reHasRegExpChar = RegExp(reRegExpChar.source); + + /** Used to match leading and trailing whitespace. */ + var reTrim = /^\s+|\s+$/g, + reTrimStart = /^\s+/, + reTrimEnd = /\s+$/; + + /** Used to match wrap detail comments. */ + var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, + reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, + reSplitDetails = /,? & /; + + /** Used to match words composed of alphanumeric characters. */ + var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + + /** Used to match backslashes in property paths. */ + var reEscapeChar = /\\(\\)?/g; + + /** + * Used to match + * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). + */ + var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; + + /** Used to match `RegExp` flags from their coerced string values. */ + var reFlags = /\w*$/; + + /** Used to detect bad signed hexadecimal string values. */ + var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + + /** Used to detect binary string values. */ + var reIsBinary = /^0b[01]+$/i; + + /** Used to detect host constructors (Safari). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/; + + /** Used to detect octal string values. */ + var reIsOctal = /^0o[0-7]+$/i; + + /** Used to detect unsigned integer values. */ + var reIsUint = /^(?:0|[1-9]\d*)$/; + + /** Used to match Latin Unicode letters (excluding mathematical operators). */ + var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; + + /** Used to ensure capturing order of template delimiters. */ + var reNoMatch = /($^)/; + + /** Used to match unescaped characters in compiled string literals. */ + var reUnescapedString = /['\n\r\u2028\u2029\\]/g; + + /** Used to compose unicode character classes. */ + var rsAstralRange = '\\ud800-\\udfff', + rsComboMarksRange = '\\u0300-\\u036f', + reComboHalfMarksRange = '\\ufe20-\\ufe2f', + rsComboSymbolsRange = '\\u20d0-\\u20ff', + rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, + rsDingbatRange = '\\u2700-\\u27bf', + rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', + rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', + rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', + rsPunctuationRange = '\\u2000-\\u206f', + rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', + rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', + rsVarRange = '\\ufe0e\\ufe0f', + rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; + + /** Used to compose unicode capture groups. */ + var rsApos = "['\u2019]", + rsAstral = '[' + rsAstralRange + ']', + rsBreak = '[' + rsBreakRange + ']', + rsCombo = '[' + rsComboRange + ']', + rsDigits = '\\d+', + rsDingbat = '[' + rsDingbatRange + ']', + rsLower = '[' + rsLowerRange + ']', + rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', + rsFitz = '\\ud83c[\\udffb-\\udfff]', + rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', + rsNonAstral = '[^' + rsAstralRange + ']', + rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsUpper = '[' + rsUpperRange + ']', + rsZWJ = '\\u200d'; + + /** Used to compose unicode regexes. */ + var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', + rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', + rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', + rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', + reOptMod = rsModifier + '?', + rsOptVar = '[' + rsVarRange + ']?', + rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', + rsOrdLower = '\\d*(?:(?:1st|2nd|3rd|(?![123])\\dth)\\b)', + rsOrdUpper = '\\d*(?:(?:1ST|2ND|3RD|(?![123])\\dTH)\\b)', + rsSeq = rsOptVar + reOptMod + rsOptJoin, + rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, + rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; + + /** Used to match apostrophes. */ + var reApos = RegExp(rsApos, 'g'); + + /** + * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and + * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). + */ + var reComboMark = RegExp(rsCombo, 'g'); + + /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ + var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); + + /** Used to match complex or compound words. */ + var reUnicodeWord = RegExp([ + rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', + rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', + rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, + rsUpper + '+' + rsOptContrUpper, + rsOrdUpper, + rsOrdLower, + rsDigits, + rsEmoji + ].join('|'), 'g'); + + /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ + var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); + + /** Used to detect strings that need a more robust regexp to match words. */ + var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; + + /** Used to assign default `context` object properties. */ + var contextProps = [ + 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', + 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', + 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', + 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', + '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' + ]; + + /** Used to make template sourceURLs easier to identify. */ + var templateCounter = -1; + + /** Used to identify `toStringTag` values of typed arrays. */ + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = + typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag] = typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = + typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = + typedArrayTags[errorTag] = typedArrayTags[funcTag] = + typedArrayTags[mapTag] = typedArrayTags[numberTag] = + typedArrayTags[objectTag] = typedArrayTags[regexpTag] = + typedArrayTags[setTag] = typedArrayTags[stringTag] = + typedArrayTags[weakMapTag] = false; + + /** Used to identify `toStringTag` values supported by `_.clone`. */ + var cloneableTags = {}; + cloneableTags[argsTag] = cloneableTags[arrayTag] = + cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = + cloneableTags[boolTag] = cloneableTags[dateTag] = + cloneableTags[float32Tag] = cloneableTags[float64Tag] = + cloneableTags[int8Tag] = cloneableTags[int16Tag] = + cloneableTags[int32Tag] = cloneableTags[mapTag] = + cloneableTags[numberTag] = cloneableTags[objectTag] = + cloneableTags[regexpTag] = cloneableTags[setTag] = + cloneableTags[stringTag] = cloneableTags[symbolTag] = + cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = + cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; + cloneableTags[errorTag] = cloneableTags[funcTag] = + cloneableTags[weakMapTag] = false; + + /** Used to map Latin Unicode letters to basic Latin letters. */ + var deburredLetters = { + // Latin-1 Supplement block. + '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', + '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', + '\xc7': 'C', '\xe7': 'c', + '\xd0': 'D', '\xf0': 'd', + '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', + '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', + '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', + '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', + '\xd1': 'N', '\xf1': 'n', + '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', + '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', + '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', + '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', + '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', + '\xc6': 'Ae', '\xe6': 'ae', + '\xde': 'Th', '\xfe': 'th', + '\xdf': 'ss', + // Latin Extended-A block. + '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', + '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', + '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', + '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', + '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', + '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', + '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', + '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', + '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', + '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', + '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', + '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', + '\u0134': 'J', '\u0135': 'j', + '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', + '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', + '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', + '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', + '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', + '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', + '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', + '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', + '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', + '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', + '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', + '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', + '\u0163': 't', '\u0165': 't', '\u0167': 't', + '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', + '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', + '\u0174': 'W', '\u0175': 'w', + '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', + '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', + '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', + '\u0132': 'IJ', '\u0133': 'ij', + '\u0152': 'Oe', '\u0153': 'oe', + '\u0149': "'n", '\u017f': 's' + }; + + /** Used to map characters to HTML entities. */ + var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + }; + + /** Used to map HTML entities to characters. */ + var htmlUnescapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + ''': "'" + }; + + /** Used to escape characters for inclusion in compiled string literals. */ + var stringEscapes = { + '\\': '\\', + "'": "'", + '\n': 'n', + '\r': 'r', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + + /** Built-in method references without a dependency on `root`. */ + var freeParseFloat = parseFloat, + freeParseInt = parseInt; + + /** Detect free variable `global` from Node.js. */ + var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + + /** Detect free variable `self`. */ + var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + + /** Used as a reference to the global object. */ + var root = freeGlobal || freeSelf || Function('return this')(); + + /** Detect free variable `exports`. */ + var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; + + /** Detect free variable `process` from Node.js. */ + var freeProcess = moduleExports && freeGlobal.process; + + /** Used to access faster Node.js helpers. */ + var nodeUtil = (function() { + try { + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} + }()); + + /* Node.js helper references. */ + var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, + nodeIsDate = nodeUtil && nodeUtil.isDate, + nodeIsMap = nodeUtil && nodeUtil.isMap, + nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, + nodeIsSet = nodeUtil && nodeUtil.isSet, + nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + + /*--------------------------------------------------------------------------*/ + + /** + * Adds the key-value `pair` to `map`. + * + * @private + * @param {Object} map The map to modify. + * @param {Array} pair The key-value pair to add. + * @returns {Object} Returns `map`. + */ + function addMapEntry(map, pair) { + // Don't return `map.set` because it's not chainable in IE 11. + map.set(pair[0], pair[1]); + return map; + } + + /** + * Adds `value` to `set`. + * + * @private + * @param {Object} set The set to modify. + * @param {*} value The value to add. + * @returns {Object} Returns `set`. + */ + function addSetEntry(set, value) { + // Don't return `set.add` because it's not chainable in IE 11. + set.add(value); + return set; + } + + /** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ + function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); + } + + /** + * A specialized version of `baseAggregator` for arrays. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ + function arrayAggregator(array, setter, iteratee, accumulator) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + var value = array[index]; + setter(accumulator, value, iteratee(value), array); + } + return accumulator; + } + + /** + * A specialized version of `_.forEach` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEach(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; + } + + /** + * A specialized version of `_.forEachRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEachRight(array, iteratee) { + var length = array == null ? 0 : array.length; + + while (length--) { + if (iteratee(array[length], length, array) === false) { + break; + } + } + return array; + } + + /** + * A specialized version of `_.every` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + */ + function arrayEvery(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (!predicate(array[index], index, array)) { + return false; + } + } + return true; + } + + /** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; + } + + /** + * A specialized version of `_.includes` for arrays without support for + * specifying an index to search from. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ + function arrayIncludes(array, value) { + var length = array == null ? 0 : array.length; + return !!length && baseIndexOf(array, value, 0) > -1; + } + + /** + * This function is like `arrayIncludes` except that it accepts a comparator. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @param {Function} comparator The comparator invoked per element. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ + function arrayIncludesWith(array, value, comparator) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (comparator(value, array[index])) { + return true; + } + } + return false; + } + + /** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function arrayMap(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; + } + + /** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ + function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; + } + + /** + * A specialized version of `_.reduce` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the first element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduce(array, iteratee, accumulator, initAccum) { + var index = -1, + length = array == null ? 0 : array.length; + + if (initAccum && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); + } + return accumulator; + } + + /** + * A specialized version of `_.reduceRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the last element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduceRight(array, iteratee, accumulator, initAccum) { + var length = array == null ? 0 : array.length; + if (initAccum && length) { + accumulator = array[--length]; + } + while (length--) { + accumulator = iteratee(accumulator, array[length], length, array); + } + return accumulator; + } + + /** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; + } + + /** + * Gets the size of an ASCII `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + var asciiSize = baseProperty('length'); + + /** + * Converts an ASCII `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function asciiToArray(string) { + return string.split(''); + } + + /** + * Splits an ASCII `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ + function asciiWords(string) { + return string.match(reAsciiWord) || []; + } + + /** + * The base implementation of methods like `_.findKey` and `_.findLastKey`, + * without support for iteratee shorthands, which iterates over `collection` + * using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the found element or its key, else `undefined`. + */ + function baseFindKey(collection, predicate, eachFunc) { + var result; + eachFunc(collection, function(value, key, collection) { + if (predicate(value, key, collection)) { + result = key; + return false; + } + }); + return result; + } + + /** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; + } + + /** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOf(array, value, fromIndex) { + return value === value + ? strictIndexOf(array, value, fromIndex) + : baseFindIndex(array, baseIsNaN, fromIndex); + } + + /** + * This function is like `baseIndexOf` except that it accepts a comparator. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @param {Function} comparator The comparator invoked per element. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOfWith(array, value, fromIndex, comparator) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (comparator(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ + function baseIsNaN(value) { + return value !== value; + } + + /** + * The base implementation of `_.mean` and `_.meanBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the mean. + */ + function baseMean(array, iteratee) { + var length = array == null ? 0 : array.length; + return length ? (baseSum(array, iteratee) / length) : NAN; + } + + /** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.propertyOf` without support for deep paths. + * + * @private + * @param {Object} object The object to query. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyOf(object) { + return function(key) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.reduce` and `_.reduceRight`, without support + * for iteratee shorthands, which iterates over `collection` using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} accumulator The initial value. + * @param {boolean} initAccum Specify using the first or last element of + * `collection` as the initial value. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the accumulated value. + */ + function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { + eachFunc(collection, function(value, index, collection) { + accumulator = initAccum + ? (initAccum = false, value) + : iteratee(accumulator, value, index, collection); + }); + return accumulator; + } + + /** + * The base implementation of `_.sortBy` which uses `comparer` to define the + * sort order of `array` and replaces criteria objects with their corresponding + * values. + * + * @private + * @param {Array} array The array to sort. + * @param {Function} comparer The function to define sort order. + * @returns {Array} Returns `array`. + */ + function baseSortBy(array, comparer) { + var length = array.length; + + array.sort(comparer); + while (length--) { + array[length] = array[length].value; + } + return array; + } + + /** + * The base implementation of `_.sum` and `_.sumBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the sum. + */ + function baseSum(array, iteratee) { + var result, + index = -1, + length = array.length; + + while (++index < length) { + var current = iteratee(array[index]); + if (current !== undefined) { + result = result === undefined ? current : (result + current); + } + } + return result; + } + + /** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ + function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; + } + + /** + * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array + * of key-value pairs for `object` corresponding to the property names of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the key-value pairs. + */ + function baseToPairs(object, props) { + return arrayMap(props, function(key) { + return [key, object[key]]; + }); + } + + /** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + function baseUnary(func) { + return function(value) { + return func(value); + }; + } + + /** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ + function baseValues(object, props) { + return arrayMap(props, function(key) { + return object[key]; + }); + } + + /** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function cacheHas(cache, key) { + return cache.has(key); + } + + /** + * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the first unmatched string symbol. + */ + function charsStartIndex(strSymbols, chrSymbols) { + var index = -1, + length = strSymbols.length; + + while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; + } + + /** + * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the last unmatched string symbol. + */ + function charsEndIndex(strSymbols, chrSymbols) { + var index = strSymbols.length; + + while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; + } + + /** + * Gets the number of `placeholder` occurrences in `array`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} placeholder The placeholder to search for. + * @returns {number} Returns the placeholder count. + */ + function countHolders(array, placeholder) { + var length = array.length, + result = 0; + + while (length--) { + if (array[length] === placeholder) { + ++result; + } + } + return result; + } + + /** + * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A + * letters to basic Latin letters. + * + * @private + * @param {string} letter The matched letter to deburr. + * @returns {string} Returns the deburred letter. + */ + var deburrLetter = basePropertyOf(deburredLetters); + + /** + * Used by `_.escape` to convert characters to HTML entities. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + var escapeHtmlChar = basePropertyOf(htmlEscapes); + + /** + * Used by `_.template` to escape characters for inclusion in compiled string literals. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + function escapeStringChar(chr) { + return '\\' + stringEscapes[chr]; + } + + /** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function getValue(object, key) { + return object == null ? undefined : object[key]; + } + + /** + * Checks if `string` contains Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a symbol is found, else `false`. + */ + function hasUnicode(string) { + return reHasUnicode.test(string); + } + + /** + * Checks if `string` contains a word composed of Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a word is found, else `false`. + */ + function hasUnicodeWord(string) { + return reHasUnicodeWord.test(string); + } + + /** + * Converts `iterator` to an array. + * + * @private + * @param {Object} iterator The iterator to convert. + * @returns {Array} Returns the converted array. + */ + function iteratorToArray(iterator) { + var data, + result = []; + + while (!(data = iterator.next()).done) { + result.push(data.value); + } + return result; + } + + /** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ + function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; + } + + /** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } + + /** + * Replaces all `placeholder` elements in `array` with an internal placeholder + * and returns an array of their indexes. + * + * @private + * @param {Array} array The array to modify. + * @param {*} placeholder The placeholder to replace. + * @returns {Array} Returns the new array of placeholder indexes. + */ + function replaceHolders(array, placeholder) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value === placeholder || value === PLACEHOLDER) { + array[index] = PLACEHOLDER; + result[resIndex++] = index; + } + } + return result; + } + + /** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ + function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; + } + + /** + * Converts `set` to its value-value pairs. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the value-value pairs. + */ + function setToPairs(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = [value, value]; + }); + return result; + } + + /** + * A specialized version of `_.indexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function strictIndexOf(array, value, fromIndex) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * A specialized version of `_.lastIndexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function strictLastIndexOf(array, value, fromIndex) { + var index = fromIndex + 1; + while (index--) { + if (array[index] === value) { + return index; + } + } + return index; + } + + /** + * Gets the number of symbols in `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the string size. + */ + function stringSize(string) { + return hasUnicode(string) + ? unicodeSize(string) + : asciiSize(string); + } + + /** + * Converts `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function stringToArray(string) { + return hasUnicode(string) + ? unicodeToArray(string) + : asciiToArray(string); + } + + /** + * Used by `_.unescape` to convert HTML entities to characters. + * + * @private + * @param {string} chr The matched character to unescape. + * @returns {string} Returns the unescaped character. + */ + var unescapeHtmlChar = basePropertyOf(htmlUnescapes); + + /** + * Gets the size of a Unicode `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + function unicodeSize(string) { + var result = reUnicode.lastIndex = 0; + while (reUnicode.test(string)) { + ++result; + } + return result; + } + + /** + * Converts a Unicode `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function unicodeToArray(string) { + return string.match(reUnicode) || []; + } + + /** + * Splits a Unicode `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ + function unicodeWords(string) { + return string.match(reUnicodeWord) || []; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Create a new pristine `lodash` function using the `context` object. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Util + * @param {Object} [context=root] The context object. + * @returns {Function} Returns a new `lodash` function. + * @example + * + * _.mixin({ 'foo': _.constant('foo') }); + * + * var lodash = _.runInContext(); + * lodash.mixin({ 'bar': lodash.constant('bar') }); + * + * _.isFunction(_.foo); + * // => true + * _.isFunction(_.bar); + * // => false + * + * lodash.isFunction(lodash.foo); + * // => false + * lodash.isFunction(lodash.bar); + * // => true + * + * // Create a suped-up `defer` in Node.js. + * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; + */ + var runInContext = (function runInContext(context) { + context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); + + /** Built-in constructor references. */ + var Array = context.Array, + Date = context.Date, + Error = context.Error, + Function = context.Function, + Math = context.Math, + Object = context.Object, + RegExp = context.RegExp, + String = context.String, + TypeError = context.TypeError; + + /** Used for built-in method references. */ + var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; + + /** Used to detect overreaching core-js shims. */ + var coreJsData = context['__core-js_shared__']; + + /** Used to resolve the decompiled source of functions. */ + var funcToString = funcProto.toString; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** Used to generate unique IDs. */ + var idCounter = 0; + + /** Used to detect methods masquerading as native. */ + var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; + }()); + + /** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + var nativeObjectToString = objectProto.toString; + + /** Used to infer the `Object` constructor. */ + var objectCtorString = funcToString.call(Object); + + /** Used to restore the original `_` reference in `_.noConflict`. */ + var oldDash = root._; + + /** Used to detect if a method is native. */ + var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' + ); + + /** Built-in value references. */ + var Buffer = moduleExports ? context.Buffer : undefined, + Symbol = context.Symbol, + Uint8Array = context.Uint8Array, + allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, + getPrototype = overArg(Object.getPrototypeOf, Object), + objectCreate = Object.create, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice, + spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, + symIterator = Symbol ? Symbol.iterator : undefined, + symToStringTag = Symbol ? Symbol.toStringTag : undefined; + + var defineProperty = (function() { + try { + var func = getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} + }()); + + /** Mocked built-ins. */ + var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, + ctxNow = Date && Date.now !== root.Date.now && Date.now, + ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeCeil = Math.ceil, + nativeFloor = Math.floor, + nativeGetSymbols = Object.getOwnPropertySymbols, + nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, + nativeIsFinite = context.isFinite, + nativeJoin = arrayProto.join, + nativeKeys = overArg(Object.keys, Object), + nativeMax = Math.max, + nativeMin = Math.min, + nativeNow = Date.now, + nativeParseInt = context.parseInt, + nativeRandom = Math.random, + nativeReverse = arrayProto.reverse; + + /* Built-in method references that are verified to be native. */ + var DataView = getNative(context, 'DataView'), + Map = getNative(context, 'Map'), + Promise = getNative(context, 'Promise'), + Set = getNative(context, 'Set'), + WeakMap = getNative(context, 'WeakMap'), + nativeCreate = getNative(Object, 'create'); + + /** Used to store function metadata. */ + var metaMap = WeakMap && new WeakMap; + + /** Used to lookup unminified function names. */ + var realNames = {}; + + /** Used to detect maps, sets, and weakmaps. */ + var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap); + + /** Used to convert symbols to primitives and strings. */ + var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` object which wraps `value` to enable implicit method + * chain sequences. Methods that operate on and return arrays, collections, + * and functions can be chained together. Methods that retrieve a single value + * or may return a primitive value will automatically end the chain sequence + * and return the unwrapped value. Otherwise, the value must be unwrapped + * with `_#value`. + * + * Explicit chain sequences, which must be unwrapped with `_#value`, may be + * enabled using `_.chain`. + * + * The execution of chained methods is lazy, that is, it's deferred until + * `_#value` is implicitly or explicitly called. + * + * Lazy evaluation allows several methods to support shortcut fusion. + * Shortcut fusion is an optimization to merge iteratee calls; this avoids + * the creation of intermediate arrays and can greatly reduce the number of + * iteratee executions. Sections of a chain sequence qualify for shortcut + * fusion if the section is applied to an array and iteratees accept only + * one argument. The heuristic for whether a section qualifies for shortcut + * fusion is subject to change. + * + * Chaining is supported in custom builds as long as the `_#value` method is + * directly or indirectly included in the build. + * + * In addition to lodash methods, wrappers have `Array` and `String` methods. + * + * The wrapper `Array` methods are: + * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` + * + * The wrapper `String` methods are: + * `replace` and `split` + * + * The wrapper methods that support shortcut fusion are: + * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, + * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, + * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` + * + * The chainable wrapper methods are: + * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, + * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, + * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, + * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, + * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, + * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, + * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, + * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, + * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, + * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, + * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, + * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, + * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, + * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, + * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, + * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, + * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, + * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, + * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, + * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, + * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, + * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, + * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, + * `zipObject`, `zipObjectDeep`, and `zipWith` + * + * The wrapper methods that are **not** chainable by default are: + * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, + * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, + * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, + * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, + * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, + * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, + * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, + * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, + * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, + * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, + * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, + * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, + * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, + * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, + * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, + * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, + * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, + * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, + * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, + * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, + * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, + * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, + * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, + * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, + * `upperFirst`, `value`, and `words` + * + * @name _ + * @constructor + * @category Seq + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2, 3]); + * + * // Returns an unwrapped value. + * wrapped.reduce(_.add); + * // => 6 + * + * // Returns a wrapped value. + * var squares = wrapped.map(square); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true + */ + function lodash(value) { + if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { + if (value instanceof LodashWrapper) { + return value; + } + if (hasOwnProperty.call(value, '__wrapped__')) { + return wrapperClone(value); + } + } + return new LodashWrapper(value); + } + + /** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. + */ + var baseCreate = (function() { + function object() {} + return function(proto) { + if (!isObject(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result = new object; + object.prototype = undefined; + return result; + }; + }()); + + /** + * The function whose prototype chain sequence wrappers inherit from. + * + * @private + */ + function baseLodash() { + // No operation performed. + } + + /** + * The base constructor for creating `lodash` wrapper objects. + * + * @private + * @param {*} value The value to wrap. + * @param {boolean} [chainAll] Enable explicit method chain sequences. + */ + function LodashWrapper(value, chainAll) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__chain__ = !!chainAll; + this.__index__ = 0; + this.__values__ = undefined; + } + + /** + * By default, the template delimiters used by lodash are like those in + * embedded Ruby (ERB) as well as ES2015 template strings. Change the + * following template settings to use alternative delimiters. + * + * @static + * @memberOf _ + * @type {Object} + */ + lodash.templateSettings = { + + /** + * Used to detect `data` property values to be HTML-escaped. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'escape': reEscape, + + /** + * Used to detect code to be evaluated. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'evaluate': reEvaluate, + + /** + * Used to detect `data` property values to inject. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'interpolate': reInterpolate, + + /** + * Used to reference the data object in the template text. + * + * @memberOf _.templateSettings + * @type {string} + */ + 'variable': '', + + /** + * Used to import variables into the compiled template. + * + * @memberOf _.templateSettings + * @type {Object} + */ + 'imports': { + + /** + * A reference to the `lodash` function. + * + * @memberOf _.templateSettings.imports + * @type {Function} + */ + '_': lodash + } + }; + + // Ensure wrappers are instances of `baseLodash`. + lodash.prototype = baseLodash.prototype; + lodash.prototype.constructor = lodash; + + LodashWrapper.prototype = baseCreate(baseLodash.prototype); + LodashWrapper.prototype.constructor = LodashWrapper; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. + * + * @private + * @constructor + * @param {*} value The value to wrap. + */ + function LazyWrapper(value) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__dir__ = 1; + this.__filtered__ = false; + this.__iteratees__ = []; + this.__takeCount__ = MAX_ARRAY_LENGTH; + this.__views__ = []; + } + + /** + * Creates a clone of the lazy wrapper object. + * + * @private + * @name clone + * @memberOf LazyWrapper + * @returns {Object} Returns the cloned `LazyWrapper` object. + */ + function lazyClone() { + var result = new LazyWrapper(this.__wrapped__); + result.__actions__ = copyArray(this.__actions__); + result.__dir__ = this.__dir__; + result.__filtered__ = this.__filtered__; + result.__iteratees__ = copyArray(this.__iteratees__); + result.__takeCount__ = this.__takeCount__; + result.__views__ = copyArray(this.__views__); + return result; + } + + /** + * Reverses the direction of lazy iteration. + * + * @private + * @name reverse + * @memberOf LazyWrapper + * @returns {Object} Returns the new reversed `LazyWrapper` object. + */ + function lazyReverse() { + if (this.__filtered__) { + var result = new LazyWrapper(this); + result.__dir__ = -1; + result.__filtered__ = true; + } else { + result = this.clone(); + result.__dir__ *= -1; + } + return result; + } + + /** + * Extracts the unwrapped value from its lazy wrapper. + * + * @private + * @name value + * @memberOf LazyWrapper + * @returns {*} Returns the unwrapped value. + */ + function lazyValue() { + var array = this.__wrapped__.value(), + dir = this.__dir__, + isArr = isArray(array), + isRight = dir < 0, + arrLength = isArr ? array.length : 0, + view = getView(0, arrLength, this.__views__), + start = view.start, + end = view.end, + length = end - start, + index = isRight ? end : (start - 1), + iteratees = this.__iteratees__, + iterLength = iteratees.length, + resIndex = 0, + takeCount = nativeMin(length, this.__takeCount__); + + if (!isArr || (!isRight && arrLength == length && takeCount == length)) { + return baseWrapperValue(array, this.__actions__); + } + var result = []; + + outer: + while (length-- && resIndex < takeCount) { + index += dir; + + var iterIndex = -1, + value = array[index]; + + while (++iterIndex < iterLength) { + var data = iteratees[iterIndex], + iteratee = data.iteratee, + type = data.type, + computed = iteratee(value); + + if (type == LAZY_MAP_FLAG) { + value = computed; + } else if (!computed) { + if (type == LAZY_FILTER_FLAG) { + continue outer; + } else { + break outer; + } + } + } + result[resIndex++] = value; + } + return result; + } + + // Ensure `LazyWrapper` is an instance of `baseLodash`. + LazyWrapper.prototype = baseCreate(baseLodash.prototype); + LazyWrapper.prototype.constructor = LazyWrapper; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; + } + + /** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; + } + + /** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; + } + + /** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); + } + + /** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ + function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; + } + + // Add methods to `Hash`. + Hash.prototype.clear = hashClear; + Hash.prototype['delete'] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ + function listCacheClear() { + this.__data__ = []; + this.size = 0; + } + + /** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; + } + + /** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; + } + + /** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; + } + + /** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ + function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; + } + + // Add methods to `ListCache`. + ListCache.prototype.clear = listCacheClear; + ListCache.prototype['delete'] = listCacheDelete; + ListCache.prototype.get = listCacheGet; + ListCache.prototype.has = listCacheHas; + ListCache.prototype.set = listCacheSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ + function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; + } + + /** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; + } + + /** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function mapCacheGet(key) { + return getMapData(this, key).get(key); + } + + /** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function mapCacheHas(key) { + return getMapData(this, key).has(key); + } + + /** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ + function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; + } + + // Add methods to `MapCache`. + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype['delete'] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; + + /*------------------------------------------------------------------------*/ + + /** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ + function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; + + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } + } + + /** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; + } + + /** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ + function setCacheHas(value) { + return this.__data__.has(value); + } + + // Add methods to `SetCache`. + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; + } + + /** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ + function stackClear() { + this.__data__ = new ListCache; + this.size = 0; + } + + /** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + + this.size = data.size; + return result; + } + + /** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function stackGet(key) { + return this.__data__.get(key); + } + + /** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function stackHas(key) { + return this.__data__.has(key); + } + + /** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ + function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; + } + + // Add methods to `Stack`. + Stack.prototype.clear = stackClear; + Stack.prototype['delete'] = stackDelete; + Stack.prototype.get = stackGet; + Stack.prototype.has = stackHas; + Stack.prototype.set = stackSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ + function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } + } + return result; + } + + /** + * A specialized version of `_.sample` for arrays. + * + * @private + * @param {Array} array The array to sample. + * @returns {*} Returns the random element. + */ + function arraySample(array) { + var length = array.length; + return length ? array[baseRandom(0, length - 1)] : undefined; + } + + /** + * A specialized version of `_.sampleSize` for arrays. + * + * @private + * @param {Array} array The array to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. + */ + function arraySampleSize(array, n) { + return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); + } + + /** + * A specialized version of `_.shuffle` for arrays. + * + * @private + * @param {Array} array The array to shuffle. + * @returns {Array} Returns the new shuffled array. + */ + function arrayShuffle(array) { + return shuffleSelf(copyArray(array)); + } + + /** + * This function is like `assignValue` except that it doesn't assign + * `undefined` values. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignMergeValue(object, key, value) { + if ((value !== undefined && !eq(object[key], value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; + } + + /** + * Aggregates elements of `collection` on `accumulator` with keys transformed + * by `iteratee` and values set by `setter`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ + function baseAggregator(collection, setter, iteratee, accumulator) { + baseEach(collection, function(value, key, collection) { + setter(accumulator, value, iteratee(value), collection); + }); + return accumulator; + } + + /** + * The base implementation of `_.assign` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ + function baseAssign(object, source) { + return object && copyObject(source, keys(source), object); + } + + /** + * The base implementation of `_.assignIn` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ + function baseAssignIn(object, source) { + return object && copyObject(source, keysIn(source), object); + } + + /** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function baseAssignValue(object, key, value) { + if (key == '__proto__' && defineProperty) { + defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; + } + } + + /** + * The base implementation of `_.at` without support for individual paths. + * + * @private + * @param {Object} object The object to iterate over. + * @param {string[]} paths The property paths to pick. + * @returns {Array} Returns the picked elements. + */ + function baseAt(object, paths) { + var index = -1, + length = paths.length, + result = Array(length), + skip = object == null; + + while (++index < length) { + result[index] = skip ? undefined : get(object, paths[index]); + } + return result; + } + + /** + * The base implementation of `_.clamp` which doesn't coerce arguments. + * + * @private + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. + */ + function baseClamp(number, lower, upper) { + if (number === number) { + if (upper !== undefined) { + number = number <= upper ? number : upper; + } + if (lower !== undefined) { + number = number >= lower ? number : lower; + } + } + return number; + } + + /** + * The base implementation of `_.clone` and `_.cloneDeep` which tracks + * traversed objects. + * + * @private + * @param {*} value The value to clone. + * @param {boolean} bitmask The bitmask flags. + * 1 - Deep clone + * 2 - Flatten inherited properties + * 4 - Clone symbols + * @param {Function} [customizer] The function to customize cloning. + * @param {string} [key] The key of `value`. + * @param {Object} [object] The parent object of `value`. + * @param {Object} [stack] Tracks traversed objects and their clone counterparts. + * @returns {*} Returns the cloned value. + */ + function baseClone(value, bitmask, customizer, key, object, stack) { + var result, + isDeep = bitmask & CLONE_DEEP_FLAG, + isFlat = bitmask & CLONE_FLAT_FLAG, + isFull = bitmask & CLONE_SYMBOLS_FLAG; + + if (customizer) { + result = object ? customizer(value, key, object, stack) : customizer(value); + } + if (result !== undefined) { + return result; + } + if (!isObject(value)) { + return value; + } + var isArr = isArray(value); + if (isArr) { + result = initCloneArray(value); + if (!isDeep) { + return copyArray(value, result); + } + } else { + var tag = getTag(value), + isFunc = tag == funcTag || tag == genTag; + + if (isBuffer(value)) { + return cloneBuffer(value, isDeep); + } + if (tag == objectTag || tag == argsTag || (isFunc && !object)) { + result = (isFlat || isFunc) ? {} : initCloneObject(value); + if (!isDeep) { + return isFlat + ? copySymbolsIn(value, baseAssignIn(result, value)) + : copySymbols(value, baseAssign(result, value)); + } + } else { + if (!cloneableTags[tag]) { + return object ? value : {}; + } + result = initCloneByTag(value, tag, baseClone, isDeep); + } + } + // Check for circular references and return its corresponding clone. + stack || (stack = new Stack); + var stacked = stack.get(value); + if (stacked) { + return stacked; + } + stack.set(value, result); + + var keysFunc = isFull + ? (isFlat ? getAllKeysIn : getAllKeys) + : (isFlat ? keysIn : keys); + + var props = isArr ? undefined : keysFunc(value); + arrayEach(props || value, function(subValue, key) { + if (props) { + key = subValue; + subValue = value[key]; + } + // Recursively populate clone (susceptible to call stack limits). + assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); + }); + return result; + } + + /** + * The base implementation of `_.conforms` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property predicates to conform to. + * @returns {Function} Returns the new spec function. + */ + function baseConforms(source) { + var props = keys(source); + return function(object) { + return baseConformsTo(object, source, props); + }; + } + + /** + * The base implementation of `_.conformsTo` which accepts `props` to check. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. + */ + function baseConformsTo(object, source, props) { + var length = props.length; + if (object == null) { + return !length; + } + object = Object(object); + while (length--) { + var key = props[length], + predicate = source[key], + value = object[key]; + + if ((value === undefined && !(key in object)) || !predicate(value)) { + return false; + } + } + return true; + } + + /** + * The base implementation of `_.delay` and `_.defer` which accepts `args` + * to provide to `func`. + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {Array} args The arguments to provide to `func`. + * @returns {number|Object} Returns the timer id or timeout object. + */ + function baseDelay(func, wait, args) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return setTimeout(function() { func.apply(undefined, args); }, wait); + } + + /** + * The base implementation of methods like `_.difference` without support + * for excluding multiple arrays or iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Array} values The values to exclude. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + */ + function baseDifference(array, values, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + isCommon = true, + length = array.length, + result = [], + valuesLength = values.length; + + if (!length) { + return result; + } + if (iteratee) { + values = arrayMap(values, baseUnary(iteratee)); + } + if (comparator) { + includes = arrayIncludesWith; + isCommon = false; + } + else if (values.length >= LARGE_ARRAY_SIZE) { + includes = cacheHas; + isCommon = false; + values = new SetCache(values); + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee == null ? value : iteratee(value); + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var valuesIndex = valuesLength; + while (valuesIndex--) { + if (values[valuesIndex] === computed) { + continue outer; + } + } + result.push(value); + } + else if (!includes(values, computed, comparator)) { + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.forEach` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ + var baseEach = createBaseEach(baseForOwn); + + /** + * The base implementation of `_.forEachRight` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ + var baseEachRight = createBaseEach(baseForOwnRight, true); + + /** + * The base implementation of `_.every` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false` + */ + function baseEvery(collection, predicate) { + var result = true; + baseEach(collection, function(value, index, collection) { + result = !!predicate(value, index, collection); + return result; + }); + return result; + } + + /** + * The base implementation of methods like `_.max` and `_.min` which accepts a + * `comparator` to determine the extremum value. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The iteratee invoked per iteration. + * @param {Function} comparator The comparator used to compare values. + * @returns {*} Returns the extremum value. + */ + function baseExtremum(array, iteratee, comparator) { + var index = -1, + length = array.length; + + while (++index < length) { + var value = array[index], + current = iteratee(value); + + if (current != null && (computed === undefined + ? (current === current && !isSymbol(current)) + : comparator(current, computed) + )) { + var computed = current, + result = value; + } + } + return result; + } + + /** + * The base implementation of `_.fill` without an iteratee call guard. + * + * @private + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + */ + function baseFill(array, value, start, end) { + var length = array.length; + + start = toInteger(start); + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = (end === undefined || end > length) ? length : toInteger(end); + if (end < 0) { + end += length; + } + end = start > end ? 0 : toLength(end); + while (start < end) { + array[start++] = value; + } + return array; + } + + /** + * The base implementation of `_.filter` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function baseFilter(collection, predicate) { + var result = []; + baseEach(collection, function(value, index, collection) { + if (predicate(value, index, collection)) { + result.push(value); + } + }); + return result; + } + + /** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ + function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; + + predicate || (predicate = isFlattenable); + result || (result = []); + + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; + } + + /** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseFor = createBaseFor(); + + /** + * This function is like `baseFor` except that it iterates over properties + * in the opposite order. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseForRight = createBaseFor(true); + + /** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); + } + + /** + * The base implementation of `_.forOwnRight` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwnRight(object, iteratee) { + return object && baseForRight(object, iteratee, keys); + } + + /** + * The base implementation of `_.functions` which creates an array of + * `object` function property names filtered from `props`. + * + * @private + * @param {Object} object The object to inspect. + * @param {Array} props The property names to filter. + * @returns {Array} Returns the function names. + */ + function baseFunctions(object, props) { + return arrayFilter(props, function(key) { + return isFunction(object[key]); + }); + } + + /** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */ + function baseGet(object, path) { + path = castPath(path, object); + + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[toKey(path[index++])]; + } + return (index && index == length) ? object : undefined; + } + + /** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ + function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); + } + + /** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag && symToStringTag in Object(value)) + ? getRawTag(value) + : objectToString(value); + } + + /** + * The base implementation of `_.gt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + */ + function baseGt(value, other) { + return value > other; + } + + /** + * The base implementation of `_.has` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ + function baseHas(object, key) { + return object != null && hasOwnProperty.call(object, key); + } + + /** + * The base implementation of `_.hasIn` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ + function baseHasIn(object, key) { + return object != null && key in Object(object); + } + + /** + * The base implementation of `_.inRange` which doesn't coerce arguments. + * + * @private + * @param {number} number The number to check. + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + */ + function baseInRange(number, start, end) { + return number >= nativeMin(start, end) && number < nativeMax(start, end); + } + + /** + * The base implementation of methods like `_.intersection`, without support + * for iteratee shorthands, that accepts an array of arrays to inspect. + * + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of shared values. + */ + function baseIntersection(arrays, iteratee, comparator) { + var includes = comparator ? arrayIncludesWith : arrayIncludes, + length = arrays[0].length, + othLength = arrays.length, + othIndex = othLength, + caches = Array(othLength), + maxLength = Infinity, + result = []; + + while (othIndex--) { + var array = arrays[othIndex]; + if (othIndex && iteratee) { + array = arrayMap(array, baseUnary(iteratee)); + } + maxLength = nativeMin(array.length, maxLength); + caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) + ? new SetCache(othIndex && array) + : undefined; + } + array = arrays[0]; + + var index = -1, + seen = caches[0]; + + outer: + while (++index < length && result.length < maxLength) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (!(seen + ? cacheHas(seen, computed) + : includes(result, computed, comparator) + )) { + othIndex = othLength; + while (--othIndex) { + var cache = caches[othIndex]; + if (!(cache + ? cacheHas(cache, computed) + : includes(arrays[othIndex], computed, comparator)) + ) { + continue outer; + } + } + if (seen) { + seen.push(computed); + } + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.invert` and `_.invertBy` which inverts + * `object` with values transformed by `iteratee` and set by `setter`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform values. + * @param {Object} accumulator The initial inverted object. + * @returns {Function} Returns `accumulator`. + */ + function baseInverter(object, setter, iteratee, accumulator) { + baseForOwn(object, function(value, key, object) { + setter(accumulator, iteratee(value), key, object); + }); + return accumulator; + } + + /** + * The base implementation of `_.invoke` without support for individual + * method arguments. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {Array} args The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + */ + function baseInvoke(object, path, args) { + path = castPath(path, object); + object = parent(object, path); + var func = object == null ? object : object[toKey(last(path))]; + return func == null ? undefined : apply(func, object, args); + } + + /** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ + function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; + } + + /** + * The base implementation of `_.isArrayBuffer` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + */ + function baseIsArrayBuffer(value) { + return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; + } + + /** + * The base implementation of `_.isDate` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + */ + function baseIsDate(value) { + return isObjectLike(value) && baseGetTag(value) == dateTag; + } + + /** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); + } + + /** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = objIsArr ? arrayTag : getTag(object), + othTag = othIsArr ? arrayTag : getTag(other); + + objTag = objTag == argsTag ? objectTag : objTag; + othTag = othTag == argsTag ? objectTag : othTag; + + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); + } + + /** + * The base implementation of `_.isMap` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + */ + function baseIsMap(value) { + return isObjectLike(value) && getTag(value) == mapTag; + } + + /** + * The base implementation of `_.isMatch` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Array} matchData The property names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + */ + function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; + } + object = Object(object); + while (index--) { + var data = matchData[index]; + if ((noCustomizer && data[2]) + ? data[1] !== object[data[0]] + : !(data[0] in object) + ) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; + + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new Stack; + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result === undefined + ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) + : result + )) { + return false; + } + } + } + return true; + } + + /** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ + function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); + } + + /** + * The base implementation of `_.isRegExp` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + */ + function baseIsRegExp(value) { + return isObjectLike(value) && baseGetTag(value) == regexpTag; + } + + /** + * The base implementation of `_.isSet` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + */ + function baseIsSet(value) { + return isObjectLike(value) && getTag(value) == setTag; + } + + /** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ + function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; + } + + /** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ + function baseIteratee(value) { + // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. + // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. + if (typeof value == 'function') { + return value; + } + if (value == null) { + return identity; + } + if (typeof value == 'object') { + return isArray(value) + ? baseMatchesProperty(value[0], value[1]) + : baseMatches(value); + } + return property(value); + } + + /** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; + } + + /** + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeysIn(object) { + if (!isObject(object)) { + return nativeKeysIn(object); + } + var isProto = isPrototype(object), + result = []; + + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { + result.push(key); + } + } + return result; + } + + /** + * The base implementation of `_.lt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + */ + function baseLt(value, other) { + return value < other; + } + + /** + * The base implementation of `_.map` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function baseMap(collection, iteratee) { + var index = -1, + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); + }); + return result; + } + + /** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatches(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return matchesStrictComparable(matchData[0][0], matchData[0][1]); + } + return function(object) { + return object === source || baseIsMatch(object, source, matchData); + }; + } + + /** + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. + * + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatchesProperty(path, srcValue) { + if (isKey(path) && isStrictComparable(srcValue)) { + return matchesStrictComparable(toKey(path), srcValue); + } + return function(object) { + var objValue = get(object, path); + return (objValue === undefined && objValue === srcValue) + ? hasIn(object, path) + : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); + }; + } + + /** + * The base implementation of `_.merge` without support for multiple sources. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {number} srcIndex The index of `source`. + * @param {Function} [customizer] The function to customize merged values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ + function baseMerge(object, source, srcIndex, customizer, stack) { + if (object === source) { + return; + } + baseFor(source, function(srcValue, key) { + if (isObject(srcValue)) { + stack || (stack = new Stack); + baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); + } + else { + var newValue = customizer + ? customizer(object[key], srcValue, (key + ''), object, source, stack) + : undefined; + + if (newValue === undefined) { + newValue = srcValue; + } + assignMergeValue(object, key, newValue); + } + }, keysIn); + } + + /** + * A specialized version of `baseMerge` for arrays and objects which performs + * deep merges and tracks traversed objects enabling objects with circular + * references to be merged. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {string} key The key of the value to merge. + * @param {number} srcIndex The index of `source`. + * @param {Function} mergeFunc The function to merge values. + * @param {Function} [customizer] The function to customize assigned values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ + function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { + var objValue = object[key], + srcValue = source[key], + stacked = stack.get(srcValue); + + if (stacked) { + assignMergeValue(object, key, stacked); + return; + } + var newValue = customizer + ? customizer(objValue, srcValue, (key + ''), object, source, stack) + : undefined; + + var isCommon = newValue === undefined; + + if (isCommon) { + var isArr = isArray(srcValue), + isBuff = !isArr && isBuffer(srcValue), + isTyped = !isArr && !isBuff && isTypedArray(srcValue); + + newValue = srcValue; + if (isArr || isBuff || isTyped) { + if (isArray(objValue)) { + newValue = objValue; + } + else if (isArrayLikeObject(objValue)) { + newValue = copyArray(objValue); + } + else if (isBuff) { + isCommon = false; + newValue = cloneBuffer(srcValue, true); + } + else if (isTyped) { + isCommon = false; + newValue = cloneTypedArray(srcValue, true); + } + else { + newValue = []; + } + } + else if (isPlainObject(srcValue) || isArguments(srcValue)) { + newValue = objValue; + if (isArguments(objValue)) { + newValue = toPlainObject(objValue); + } + else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) { + newValue = initCloneObject(srcValue); + } + } + else { + isCommon = false; + } + } + if (isCommon) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, newValue); + mergeFunc(newValue, srcValue, srcIndex, customizer, stack); + stack['delete'](srcValue); + } + assignMergeValue(object, key, newValue); + } + + /** + * The base implementation of `_.nth` which doesn't coerce arguments. + * + * @private + * @param {Array} array The array to query. + * @param {number} n The index of the element to return. + * @returns {*} Returns the nth element of `array`. + */ + function baseNth(array, n) { + var length = array.length; + if (!length) { + return; + } + n += n < 0 ? length : 0; + return isIndex(n, length) ? array[n] : undefined; + } + + /** + * The base implementation of `_.orderBy` without param guards. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. + * @param {string[]} orders The sort orders of `iteratees`. + * @returns {Array} Returns the new sorted array. + */ + function baseOrderBy(collection, iteratees, orders) { + var index = -1; + iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(getIteratee())); + + var result = baseMap(collection, function(value, key, collection) { + var criteria = arrayMap(iteratees, function(iteratee) { + return iteratee(value); + }); + return { 'criteria': criteria, 'index': ++index, 'value': value }; + }); + + return baseSortBy(result, function(object, other) { + return compareMultiple(object, other, orders); + }); + } + + /** + * The base implementation of `_.pick` without support for individual + * property identifiers. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @returns {Object} Returns the new object. + */ + function basePick(object, paths) { + return basePickBy(object, paths, function(value, path) { + return hasIn(object, path); + }); + } + + /** + * The base implementation of `_.pickBy` without support for iteratee shorthands. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @param {Function} predicate The function invoked per property. + * @returns {Object} Returns the new object. + */ + function basePickBy(object, paths, predicate) { + var index = -1, + length = paths.length, + result = {}; + + while (++index < length) { + var path = paths[index], + value = baseGet(object, path); + + if (predicate(value, path)) { + baseSet(result, castPath(path, object), value); + } + } + return result; + } + + /** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyDeep(path) { + return function(object) { + return baseGet(object, path); + }; + } + + /** + * The base implementation of `_.pullAllBy` without support for iteratee + * shorthands. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. + */ + function basePullAll(array, values, iteratee, comparator) { + var indexOf = comparator ? baseIndexOfWith : baseIndexOf, + index = -1, + length = values.length, + seen = array; + + if (array === values) { + values = copyArray(values); + } + if (iteratee) { + seen = arrayMap(array, baseUnary(iteratee)); + } + while (++index < length) { + var fromIndex = 0, + value = values[index], + computed = iteratee ? iteratee(value) : value; + + while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { + if (seen !== array) { + splice.call(seen, fromIndex, 1); + } + splice.call(array, fromIndex, 1); + } + } + return array; + } + + /** + * The base implementation of `_.pullAt` without support for individual + * indexes or capturing the removed elements. + * + * @private + * @param {Array} array The array to modify. + * @param {number[]} indexes The indexes of elements to remove. + * @returns {Array} Returns `array`. + */ + function basePullAt(array, indexes) { + var length = array ? indexes.length : 0, + lastIndex = length - 1; + + while (length--) { + var index = indexes[length]; + if (length == lastIndex || index !== previous) { + var previous = index; + if (isIndex(index)) { + splice.call(array, index, 1); + } else { + baseUnset(array, index); + } + } + } + return array; + } + + /** + * The base implementation of `_.random` without support for returning + * floating-point numbers. + * + * @private + * @param {number} lower The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the random number. + */ + function baseRandom(lower, upper) { + return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); + } + + /** + * The base implementation of `_.range` and `_.rangeRight` which doesn't + * coerce arguments. + * + * @private + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @param {number} step The value to increment or decrement by. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the range of numbers. + */ + function baseRange(start, end, step, fromRight) { + var index = -1, + length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), + result = Array(length); + + while (length--) { + result[fromRight ? length : ++index] = start; + start += step; + } + return result; + } + + /** + * The base implementation of `_.repeat` which doesn't coerce arguments. + * + * @private + * @param {string} string The string to repeat. + * @param {number} n The number of times to repeat the string. + * @returns {string} Returns the repeated string. + */ + function baseRepeat(string, n) { + var result = ''; + if (!string || n < 1 || n > MAX_SAFE_INTEGER) { + return result; + } + // Leverage the exponentiation by squaring algorithm for a faster repeat. + // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. + do { + if (n % 2) { + result += string; + } + n = nativeFloor(n / 2); + if (n) { + string += string; + } + } while (n); + + return result; + } + + /** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ + function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ''); + } + + /** + * The base implementation of `_.sample`. + * + * @private + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. + */ + function baseSample(collection) { + return arraySample(values(collection)); + } + + /** + * The base implementation of `_.sampleSize` without param guards. + * + * @private + * @param {Array|Object} collection The collection to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. + */ + function baseSampleSize(collection, n) { + var array = values(collection); + return shuffleSelf(array, baseClamp(n, 0, array.length)); + } + + /** + * The base implementation of `_.set`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ + function baseSet(object, path, value, customizer) { + if (!isObject(object)) { + return object; + } + path = castPath(path, object); + + var index = -1, + length = path.length, + lastIndex = length - 1, + nested = object; + + while (nested != null && ++index < length) { + var key = toKey(path[index]), + newValue = value; + + if (index != lastIndex) { + var objValue = nested[key]; + newValue = customizer ? customizer(objValue, key, nested) : undefined; + if (newValue === undefined) { + newValue = isObject(objValue) + ? objValue + : (isIndex(path[index + 1]) ? [] : {}); + } + } + assignValue(nested, key, newValue); + nested = nested[key]; + } + return object; + } + + /** + * The base implementation of `setData` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ + var baseSetData = !metaMap ? identity : function(func, data) { + metaMap.set(func, data); + return func; + }; + + /** + * The base implementation of `setToString` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var baseSetToString = !defineProperty ? identity : function(func, string) { + return defineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant(string), + 'writable': true + }); + }; + + /** + * The base implementation of `_.shuffle`. + * + * @private + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. + */ + function baseShuffle(collection) { + return shuffleSelf(values(collection)); + } + + /** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; + } + + /** + * The base implementation of `_.some` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function baseSome(collection, predicate) { + var result; + + baseEach(collection, function(value, index, collection) { + result = predicate(value, index, collection); + return !result; + }); + return !!result; + } + + /** + * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which + * performs a binary search of `array` to determine the index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ + function baseSortedIndex(array, value, retHighest) { + var low = 0, + high = array == null ? low : array.length; + + if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { + while (low < high) { + var mid = (low + high) >>> 1, + computed = array[mid]; + + if (computed !== null && !isSymbol(computed) && + (retHighest ? (computed <= value) : (computed < value))) { + low = mid + 1; + } else { + high = mid; + } + } + return high; + } + return baseSortedIndexBy(array, value, identity, retHighest); + } + + /** + * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` + * which invokes `iteratee` for `value` and each element of `array` to compute + * their sort ranking. The iteratee is invoked with one argument; (value). + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} iteratee The iteratee invoked per element. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ + function baseSortedIndexBy(array, value, iteratee, retHighest) { + value = iteratee(value); + + var low = 0, + high = array == null ? 0 : array.length, + valIsNaN = value !== value, + valIsNull = value === null, + valIsSymbol = isSymbol(value), + valIsUndefined = value === undefined; + + while (low < high) { + var mid = nativeFloor((low + high) / 2), + computed = iteratee(array[mid]), + othIsDefined = computed !== undefined, + othIsNull = computed === null, + othIsReflexive = computed === computed, + othIsSymbol = isSymbol(computed); + + if (valIsNaN) { + var setLow = retHighest || othIsReflexive; + } else if (valIsUndefined) { + setLow = othIsReflexive && (retHighest || othIsDefined); + } else if (valIsNull) { + setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); + } else if (valIsSymbol) { + setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); + } else if (othIsNull || othIsSymbol) { + setLow = false; + } else { + setLow = retHighest ? (computed <= value) : (computed < value); + } + if (setLow) { + low = mid + 1; + } else { + high = mid; + } + } + return nativeMin(high, MAX_ARRAY_INDEX); + } + + /** + * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ + function baseSortedUniq(array, iteratee) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + if (!index || !eq(computed, seen)) { + var seen = computed; + result[resIndex++] = value === 0 ? 0 : value; + } + } + return result; + } + + /** + * The base implementation of `_.toNumber` which doesn't ensure correct + * conversions of binary, hexadecimal, or octal string values. + * + * @private + * @param {*} value The value to process. + * @returns {number} Returns the number. + */ + function baseToNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + return +value; + } + + /** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ + function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isArray(value)) { + // Recursively convert values (susceptible to call stack limits). + return arrayMap(value, baseToString) + ''; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + } + + /** + * The base implementation of `_.uniqBy` without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ + function baseUniq(array, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + length = array.length, + isCommon = true, + result = [], + seen = result; + + if (comparator) { + isCommon = false; + includes = arrayIncludesWith; + } + else if (length >= LARGE_ARRAY_SIZE) { + var set = iteratee ? null : createSet(array); + if (set) { + return setToArray(set); + } + isCommon = false; + includes = cacheHas; + seen = new SetCache; + } + else { + seen = iteratee ? [] : result; + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var seenIndex = seen.length; + while (seenIndex--) { + if (seen[seenIndex] === computed) { + continue outer; + } + } + if (iteratee) { + seen.push(computed); + } + result.push(value); + } + else if (!includes(seen, computed, comparator)) { + if (seen !== result) { + seen.push(computed); + } + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.unset`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The property path to unset. + * @returns {boolean} Returns `true` if the property is deleted, else `false`. + */ + function baseUnset(object, path) { + path = castPath(path, object); + object = parent(object, path); + return object == null || delete object[toKey(last(path))]; + } + + /** + * The base implementation of `_.update`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to update. + * @param {Function} updater The function to produce the updated value. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ + function baseUpdate(object, path, updater, customizer) { + return baseSet(object, path, updater(baseGet(object, path)), customizer); + } + + /** + * The base implementation of methods like `_.dropWhile` and `_.takeWhile` + * without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to query. + * @param {Function} predicate The function invoked per iteration. + * @param {boolean} [isDrop] Specify dropping elements instead of taking them. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the slice of `array`. + */ + function baseWhile(array, predicate, isDrop, fromRight) { + var length = array.length, + index = fromRight ? length : -1; + + while ((fromRight ? index-- : ++index < length) && + predicate(array[index], index, array)) {} + + return isDrop + ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) + : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); + } + + /** + * The base implementation of `wrapperValue` which returns the result of + * performing a sequence of actions on the unwrapped `value`, where each + * successive action is supplied the return value of the previous. + * + * @private + * @param {*} value The unwrapped value. + * @param {Array} actions Actions to perform to resolve the unwrapped value. + * @returns {*} Returns the resolved value. + */ + function baseWrapperValue(value, actions) { + var result = value; + if (result instanceof LazyWrapper) { + result = result.value(); + } + return arrayReduce(actions, function(result, action) { + return action.func.apply(action.thisArg, arrayPush([result], action.args)); + }, result); + } + + /** + * The base implementation of methods like `_.xor`, without support for + * iteratee shorthands, that accepts an array of arrays to inspect. + * + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of values. + */ + function baseXor(arrays, iteratee, comparator) { + var length = arrays.length; + if (length < 2) { + return length ? baseUniq(arrays[0]) : []; + } + var index = -1, + result = Array(length); + + while (++index < length) { + var array = arrays[index], + othIndex = -1; + + while (++othIndex < length) { + if (othIndex != index) { + result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); + } + } + } + return baseUniq(baseFlatten(result, 1), iteratee, comparator); + } + + /** + * This base implementation of `_.zipObject` which assigns values using `assignFunc`. + * + * @private + * @param {Array} props The property identifiers. + * @param {Array} values The property values. + * @param {Function} assignFunc The function to assign values. + * @returns {Object} Returns the new object. + */ + function baseZipObject(props, values, assignFunc) { + var index = -1, + length = props.length, + valsLength = values.length, + result = {}; + + while (++index < length) { + var value = index < valsLength ? values[index] : undefined; + assignFunc(result, props[index], value); + } + return result; + } + + /** + * Casts `value` to an empty array if it's not an array like object. + * + * @private + * @param {*} value The value to inspect. + * @returns {Array|Object} Returns the cast array-like object. + */ + function castArrayLikeObject(value) { + return isArrayLikeObject(value) ? value : []; + } + + /** + * Casts `value` to `identity` if it's not a function. + * + * @private + * @param {*} value The value to inspect. + * @returns {Function} Returns cast function. + */ + function castFunction(value) { + return typeof value == 'function' ? value : identity; + } + + /** + * Casts `value` to a path array if it's not one. + * + * @private + * @param {*} value The value to inspect. + * @param {Object} [object] The object to query keys on. + * @returns {Array} Returns the cast property path array. + */ + function castPath(value, object) { + if (isArray(value)) { + return value; + } + return isKey(value, object) ? [value] : stringToPath(toString(value)); + } + + /** + * A `baseRest` alias which can be replaced with `identity` by module + * replacement plugins. + * + * @private + * @type {Function} + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ + var castRest = baseRest; + + /** + * Casts `array` to a slice if it's needed. + * + * @private + * @param {Array} array The array to inspect. + * @param {number} start The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the cast slice. + */ + function castSlice(array, start, end) { + var length = array.length; + end = end === undefined ? length : end; + return (!start && end >= length) ? array : baseSlice(array, start, end); + } + + /** + * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). + * + * @private + * @param {number|Object} id The timer id or timeout object of the timer to clear. + */ + var clearTimeout = ctxClearTimeout || function(id) { + return root.clearTimeout(id); + }; + + /** + * Creates a clone of `buffer`. + * + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. + */ + function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); + } + var length = buffer.length, + result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + + buffer.copy(result); + return result; + } + + /** + * Creates a clone of `arrayBuffer`. + * + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */ + function cloneArrayBuffer(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array(result).set(new Uint8Array(arrayBuffer)); + return result; + } + + /** + * Creates a clone of `dataView`. + * + * @private + * @param {Object} dataView The data view to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned data view. + */ + function cloneDataView(dataView, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; + return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); + } + + /** + * Creates a clone of `map`. + * + * @private + * @param {Object} map The map to clone. + * @param {Function} cloneFunc The function to clone values. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned map. + */ + function cloneMap(map, isDeep, cloneFunc) { + var array = isDeep ? cloneFunc(mapToArray(map), CLONE_DEEP_FLAG) : mapToArray(map); + return arrayReduce(array, addMapEntry, new map.constructor); + } + + /** + * Creates a clone of `regexp`. + * + * @private + * @param {Object} regexp The regexp to clone. + * @returns {Object} Returns the cloned regexp. + */ + function cloneRegExp(regexp) { + var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); + result.lastIndex = regexp.lastIndex; + return result; + } + + /** + * Creates a clone of `set`. + * + * @private + * @param {Object} set The set to clone. + * @param {Function} cloneFunc The function to clone values. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned set. + */ + function cloneSet(set, isDeep, cloneFunc) { + var array = isDeep ? cloneFunc(setToArray(set), CLONE_DEEP_FLAG) : setToArray(set); + return arrayReduce(array, addSetEntry, new set.constructor); + } + + /** + * Creates a clone of the `symbol` object. + * + * @private + * @param {Object} symbol The symbol object to clone. + * @returns {Object} Returns the cloned symbol object. + */ + function cloneSymbol(symbol) { + return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; + } + + /** + * Creates a clone of `typedArray`. + * + * @private + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. + */ + function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); + } + + /** + * Compares values to sort them in ascending order. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {number} Returns the sort order indicator for `value`. + */ + function compareAscending(value, other) { + if (value !== other) { + var valIsDefined = value !== undefined, + valIsNull = value === null, + valIsReflexive = value === value, + valIsSymbol = isSymbol(value); + + var othIsDefined = other !== undefined, + othIsNull = other === null, + othIsReflexive = other === other, + othIsSymbol = isSymbol(other); + + if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || + (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || + (valIsNull && othIsDefined && othIsReflexive) || + (!valIsDefined && othIsReflexive) || + !valIsReflexive) { + return 1; + } + if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || + (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || + (othIsNull && valIsDefined && valIsReflexive) || + (!othIsDefined && valIsReflexive) || + !othIsReflexive) { + return -1; + } + } + return 0; + } + + /** + * Used by `_.orderBy` to compare multiple properties of a value to another + * and stable sort them. + * + * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, + * specify an order of "desc" for descending or "asc" for ascending sort order + * of corresponding values. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {boolean[]|string[]} orders The order to sort by for each property. + * @returns {number} Returns the sort order indicator for `object`. + */ + function compareMultiple(object, other, orders) { + var index = -1, + objCriteria = object.criteria, + othCriteria = other.criteria, + length = objCriteria.length, + ordersLength = orders.length; + + while (++index < length) { + var result = compareAscending(objCriteria[index], othCriteria[index]); + if (result) { + if (index >= ordersLength) { + return result; + } + var order = orders[index]; + return result * (order == 'desc' ? -1 : 1); + } + } + // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications + // that causes it, under certain circumstances, to provide the same value for + // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 + // for more details. + // + // This also ensures a stable sort in V8 and other engines. + // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. + return object.index - other.index; + } + + /** + * Creates an array that is the composition of partially applied arguments, + * placeholders, and provided arguments into a single array of arguments. + * + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to prepend to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. + */ + function composeArgs(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersLength = holders.length, + leftIndex = -1, + leftLength = partials.length, + rangeLength = nativeMax(argsLength - holdersLength, 0), + result = Array(leftLength + rangeLength), + isUncurried = !isCurried; + + while (++leftIndex < leftLength) { + result[leftIndex] = partials[leftIndex]; + } + while (++argsIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[holders[argsIndex]] = args[argsIndex]; + } + } + while (rangeLength--) { + result[leftIndex++] = args[argsIndex++]; + } + return result; + } + + /** + * This function is like `composeArgs` except that the arguments composition + * is tailored for `_.partialRight`. + * + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to append to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. + */ + function composeArgsRight(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersIndex = -1, + holdersLength = holders.length, + rightIndex = -1, + rightLength = partials.length, + rangeLength = nativeMax(argsLength - holdersLength, 0), + result = Array(rangeLength + rightLength), + isUncurried = !isCurried; + + while (++argsIndex < rangeLength) { + result[argsIndex] = args[argsIndex]; + } + var offset = argsIndex; + while (++rightIndex < rightLength) { + result[offset + rightIndex] = partials[rightIndex]; + } + while (++holdersIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[offset + holders[holdersIndex]] = args[argsIndex++]; + } + } + return result; + } + + /** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ + function copyArray(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; + } + + /** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ + function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } + } + return object; + } + + /** + * Copies own symbols of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ + function copySymbols(source, object) { + return copyObject(source, getSymbols(source), object); + } + + /** + * Copies own and inherited symbols of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ + function copySymbolsIn(source, object) { + return copyObject(source, getSymbolsIn(source), object); + } + + /** + * Creates a function like `_.groupBy`. + * + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} [initializer] The accumulator object initializer. + * @returns {Function} Returns the new aggregator function. + */ + function createAggregator(setter, initializer) { + return function(collection, iteratee) { + var func = isArray(collection) ? arrayAggregator : baseAggregator, + accumulator = initializer ? initializer() : {}; + + return func(collection, setter, getIteratee(iteratee, 2), accumulator); + }; + } + + /** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ + function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); + } + + /** + * Creates a `baseEach` or `baseEachRight` function. + * + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseEach(eachFunc, fromRight) { + return function(collection, iteratee) { + if (collection == null) { + return collection; + } + if (!isArrayLike(collection)) { + return eachFunc(collection, iteratee); + } + var length = collection.length, + index = fromRight ? length : -1, + iterable = Object(collection); + + while ((fromRight ? index-- : ++index < length)) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; + } + + /** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; + } + + /** + * Creates a function that wraps `func` to invoke it with the optional `this` + * binding of `thisArg`. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createBind(func, bitmask, thisArg) { + var isBind = bitmask & WRAP_BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return fn.apply(isBind ? thisArg : this, arguments); + } + return wrapper; + } + + /** + * Creates a function like `_.lowerFirst`. + * + * @private + * @param {string} methodName The name of the `String` case method to use. + * @returns {Function} Returns the new case function. + */ + function createCaseFirst(methodName) { + return function(string) { + string = toString(string); + + var strSymbols = hasUnicode(string) + ? stringToArray(string) + : undefined; + + var chr = strSymbols + ? strSymbols[0] + : string.charAt(0); + + var trailing = strSymbols + ? castSlice(strSymbols, 1).join('') + : string.slice(1); + + return chr[methodName]() + trailing; + }; + } + + /** + * Creates a function like `_.camelCase`. + * + * @private + * @param {Function} callback The function to combine each word. + * @returns {Function} Returns the new compounder function. + */ + function createCompounder(callback) { + return function(string) { + return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); + }; + } + + /** + * Creates a function that produces an instance of `Ctor` regardless of + * whether it was invoked as part of a `new` expression or by `call` or `apply`. + * + * @private + * @param {Function} Ctor The constructor to wrap. + * @returns {Function} Returns the new wrapped function. + */ + function createCtor(Ctor) { + return function() { + // Use a `switch` statement to work with class constructors. See + // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist + // for more details. + var args = arguments; + switch (args.length) { + case 0: return new Ctor; + case 1: return new Ctor(args[0]); + case 2: return new Ctor(args[0], args[1]); + case 3: return new Ctor(args[0], args[1], args[2]); + case 4: return new Ctor(args[0], args[1], args[2], args[3]); + case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); + case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); + case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + } + var thisBinding = baseCreate(Ctor.prototype), + result = Ctor.apply(thisBinding, args); + + // Mimic the constructor's `return` behavior. + // See https://es5.github.io/#x13.2.2 for more details. + return isObject(result) ? result : thisBinding; + }; + } + + /** + * Creates a function that wraps `func` to enable currying. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {number} arity The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createCurry(func, bitmask, arity) { + var Ctor = createCtor(func); + + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length, + placeholder = getHolder(wrapper); + + while (index--) { + args[index] = arguments[index]; + } + var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) + ? [] + : replaceHolders(args, placeholder); + + length -= holders.length; + if (length < arity) { + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, undefined, + args, holders, undefined, undefined, arity - length); + } + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return apply(fn, this, args); + } + return wrapper; + } + + /** + * Creates a `_.find` or `_.findLast` function. + * + * @private + * @param {Function} findIndexFunc The function to find the collection index. + * @returns {Function} Returns the new find function. + */ + function createFind(findIndexFunc) { + return function(collection, predicate, fromIndex) { + var iterable = Object(collection); + if (!isArrayLike(collection)) { + var iteratee = getIteratee(predicate, 3); + collection = keys(collection); + predicate = function(key) { return iteratee(iterable[key], key, iterable); }; + } + var index = findIndexFunc(collection, predicate, fromIndex); + return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; + }; + } + + /** + * Creates a `_.flow` or `_.flowRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new flow function. + */ + function createFlow(fromRight) { + return flatRest(function(funcs) { + var length = funcs.length, + index = length, + prereq = LodashWrapper.prototype.thru; + + if (fromRight) { + funcs.reverse(); + } + while (index--) { + var func = funcs[index]; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (prereq && !wrapper && getFuncName(func) == 'wrapper') { + var wrapper = new LodashWrapper([], true); + } + } + index = wrapper ? index : length; + while (++index < length) { + func = funcs[index]; + + var funcName = getFuncName(func), + data = funcName == 'wrapper' ? getData(func) : undefined; + + if (data && isLaziable(data[0]) && + data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && + !data[4].length && data[9] == 1 + ) { + wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); + } else { + wrapper = (func.length == 1 && isLaziable(func)) + ? wrapper[funcName]() + : wrapper.thru(func); + } + } + return function() { + var args = arguments, + value = args[0]; + + if (wrapper && args.length == 1 && isArray(value)) { + return wrapper.plant(value).value(); + } + var index = 0, + result = length ? funcs[index].apply(this, args) : value; + + while (++index < length) { + result = funcs[index].call(this, result); + } + return result; + }; + }); + } + + /** + * Creates a function that wraps `func` to invoke it with optional `this` + * binding of `thisArg`, partial application, and currying. + * + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [partialsRight] The arguments to append to those provided + * to the new function. + * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { + var isAry = bitmask & WRAP_ARY_FLAG, + isBind = bitmask & WRAP_BIND_FLAG, + isBindKey = bitmask & WRAP_BIND_KEY_FLAG, + isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), + isFlip = bitmask & WRAP_FLIP_FLAG, + Ctor = isBindKey ? undefined : createCtor(func); + + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length; + + while (index--) { + args[index] = arguments[index]; + } + if (isCurried) { + var placeholder = getHolder(wrapper), + holdersCount = countHolders(args, placeholder); + } + if (partials) { + args = composeArgs(args, partials, holders, isCurried); + } + if (partialsRight) { + args = composeArgsRight(args, partialsRight, holdersRight, isCurried); + } + length -= holdersCount; + if (isCurried && length < arity) { + var newHolders = replaceHolders(args, placeholder); + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, thisArg, + args, newHolders, argPos, ary, arity - length + ); + } + var thisBinding = isBind ? thisArg : this, + fn = isBindKey ? thisBinding[func] : func; + + length = args.length; + if (argPos) { + args = reorder(args, argPos); + } else if (isFlip && length > 1) { + args.reverse(); + } + if (isAry && ary < length) { + args.length = ary; + } + if (this && this !== root && this instanceof wrapper) { + fn = Ctor || createCtor(fn); + } + return fn.apply(thisBinding, args); + } + return wrapper; + } + + /** + * Creates a function like `_.invertBy`. + * + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} toIteratee The function to resolve iteratees. + * @returns {Function} Returns the new inverter function. + */ + function createInverter(setter, toIteratee) { + return function(object, iteratee) { + return baseInverter(object, setter, toIteratee(iteratee), {}); + }; + } + + /** + * Creates a function that performs a mathematical operation on two values. + * + * @private + * @param {Function} operator The function to perform the operation. + * @param {number} [defaultValue] The value used for `undefined` arguments. + * @returns {Function} Returns the new mathematical operation function. + */ + function createMathOperation(operator, defaultValue) { + return function(value, other) { + var result; + if (value === undefined && other === undefined) { + return defaultValue; + } + if (value !== undefined) { + result = value; + } + if (other !== undefined) { + if (result === undefined) { + return other; + } + if (typeof value == 'string' || typeof other == 'string') { + value = baseToString(value); + other = baseToString(other); + } else { + value = baseToNumber(value); + other = baseToNumber(other); + } + result = operator(value, other); + } + return result; + }; + } + + /** + * Creates a function like `_.over`. + * + * @private + * @param {Function} arrayFunc The function to iterate over iteratees. + * @returns {Function} Returns the new over function. + */ + function createOver(arrayFunc) { + return flatRest(function(iteratees) { + iteratees = arrayMap(iteratees, baseUnary(getIteratee())); + return baseRest(function(args) { + var thisArg = this; + return arrayFunc(iteratees, function(iteratee) { + return apply(iteratee, thisArg, args); + }); + }); + }); + } + + /** + * Creates the padding for `string` based on `length`. The `chars` string + * is truncated if the number of characters exceeds `length`. + * + * @private + * @param {number} length The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padding for `string`. + */ + function createPadding(length, chars) { + chars = chars === undefined ? ' ' : baseToString(chars); + + var charsLength = chars.length; + if (charsLength < 2) { + return charsLength ? baseRepeat(chars, length) : chars; + } + var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); + return hasUnicode(chars) + ? castSlice(stringToArray(result), 0, length).join('') + : result.slice(0, length); + } + + /** + * Creates a function that wraps `func` to invoke it with the `this` binding + * of `thisArg` and `partials` prepended to the arguments it receives. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} partials The arguments to prepend to those provided to + * the new function. + * @returns {Function} Returns the new wrapped function. + */ + function createPartial(func, bitmask, thisArg, partials) { + var isBind = bitmask & WRAP_BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var argsIndex = -1, + argsLength = arguments.length, + leftIndex = -1, + leftLength = partials.length, + args = Array(leftLength + argsLength), + fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + + while (++leftIndex < leftLength) { + args[leftIndex] = partials[leftIndex]; + } + while (argsLength--) { + args[leftIndex++] = arguments[++argsIndex]; + } + return apply(fn, isBind ? thisArg : this, args); + } + return wrapper; + } + + /** + * Creates a `_.range` or `_.rangeRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new range function. + */ + function createRange(fromRight) { + return function(start, end, step) { + if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { + end = step = undefined; + } + // Ensure the sign of `-0` is preserved. + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); + return baseRange(start, end, step, fromRight); + }; + } + + /** + * Creates a function that performs a relational operation on two values. + * + * @private + * @param {Function} operator The function to perform the operation. + * @returns {Function} Returns the new relational operation function. + */ + function createRelationalOperation(operator) { + return function(value, other) { + if (!(typeof value == 'string' && typeof other == 'string')) { + value = toNumber(value); + other = toNumber(other); + } + return operator(value, other); + }; + } + + /** + * Creates a function that wraps `func` to continue currying. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {Function} wrapFunc The function to create the `func` wrapper. + * @param {*} placeholder The placeholder value. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { + var isCurry = bitmask & WRAP_CURRY_FLAG, + newHolders = isCurry ? holders : undefined, + newHoldersRight = isCurry ? undefined : holders, + newPartials = isCurry ? partials : undefined, + newPartialsRight = isCurry ? undefined : partials; + + bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); + bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); + + if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { + bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); + } + var newData = [ + func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, + newHoldersRight, argPos, ary, arity + ]; + + var result = wrapFunc.apply(undefined, newData); + if (isLaziable(func)) { + setData(result, newData); + } + result.placeholder = placeholder; + return setWrapToString(result, func, bitmask); + } + + /** + * Creates a function like `_.round`. + * + * @private + * @param {string} methodName The name of the `Math` method to use when rounding. + * @returns {Function} Returns the new round function. + */ + function createRound(methodName) { + var func = Math[methodName]; + return function(number, precision) { + number = toNumber(number); + precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); + if (precision) { + // Shift with exponential notation to avoid floating-point issues. + // See [MDN](https://mdn.io/round#Examples) for more details. + var pair = (toString(number) + 'e').split('e'), + value = func(pair[0] + 'e' + (+pair[1] + precision)); + + pair = (toString(value) + 'e').split('e'); + return +(pair[0] + 'e' + (+pair[1] - precision)); + } + return func(number); + }; + } + + /** + * Creates a set object of `values`. + * + * @private + * @param {Array} values The values to add to the set. + * @returns {Object} Returns the new set. + */ + var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { + return new Set(values); + }; + + /** + * Creates a `_.toPairs` or `_.toPairsIn` function. + * + * @private + * @param {Function} keysFunc The function to get the keys of a given object. + * @returns {Function} Returns the new pairs function. + */ + function createToPairs(keysFunc) { + return function(object) { + var tag = getTag(object); + if (tag == mapTag) { + return mapToArray(object); + } + if (tag == setTag) { + return setToPairs(object); + } + return baseToPairs(object, keysFunc(object)); + }; + } + + /** + * Creates a function that either curries or invokes `func` with optional + * `this` binding and partially applied arguments. + * + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. + * 1 - `_.bind` + * 2 - `_.bindKey` + * 4 - `_.curry` or `_.curryRight` of a bound function + * 8 - `_.curry` + * 16 - `_.curryRight` + * 32 - `_.partial` + * 64 - `_.partialRight` + * 128 - `_.rearg` + * 256 - `_.ary` + * 512 - `_.flip` + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to be partially applied. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { + var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; + if (!isBindKey && typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + var length = partials ? partials.length : 0; + if (!length) { + bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); + partials = holders = undefined; + } + ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); + arity = arity === undefined ? arity : toInteger(arity); + length -= holders ? holders.length : 0; + + if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { + var partialsRight = partials, + holdersRight = holders; + + partials = holders = undefined; + } + var data = isBindKey ? undefined : getData(func); + + var newData = [ + func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, + argPos, ary, arity + ]; + + if (data) { + mergeData(newData, data); + } + func = newData[0]; + bitmask = newData[1]; + thisArg = newData[2]; + partials = newData[3]; + holders = newData[4]; + arity = newData[9] = newData[9] === undefined + ? (isBindKey ? 0 : func.length) + : nativeMax(newData[9] - length, 0); + + if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { + bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); + } + if (!bitmask || bitmask == WRAP_BIND_FLAG) { + var result = createBind(func, bitmask, thisArg); + } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { + result = createCurry(func, bitmask, arity); + } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { + result = createPartial(func, bitmask, thisArg, partials); + } else { + result = createHybrid.apply(undefined, newData); + } + var setter = data ? baseSetData : setData; + return setWrapToString(setter(result, newData), func, bitmask); + } + + /** + * Used by `_.defaults` to customize its `_.assignIn` use to assign properties + * of source objects to the destination object for all destination properties + * that resolve to `undefined`. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to assign. + * @param {Object} object The parent object of `objValue`. + * @returns {*} Returns the value to assign. + */ + function customDefaultsAssignIn(objValue, srcValue, key, object) { + if (objValue === undefined || + (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { + return srcValue; + } + return objValue; + } + + /** + * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source + * objects into destination objects that are passed thru. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to merge. + * @param {Object} object The parent object of `objValue`. + * @param {Object} source The parent object of `srcValue`. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + * @returns {*} Returns the value to assign. + */ + function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { + if (isObject(objValue) && isObject(srcValue)) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, objValue); + baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); + stack['delete'](srcValue); + } + return objValue; + } + + /** + * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain + * objects. + * + * @private + * @param {*} value The value to inspect. + * @param {string} key The key of the property to inspect. + * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. + */ + function customOmitClone(value) { + return isPlainObject(value) ? undefined : value; + } + + /** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ + function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(array); + if (stacked && stack.get(other)) { + return stacked == other; + } + var index = -1, + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; + + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; + } + + /** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array(object), new Uint8Array(other))) { + return false; + } + return true; + + case boolTag: + case dateTag: + case numberTag: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag: + var convert = mapToArray; + + case setTag: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG; + convert || (convert = setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; + + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; + } + + /** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + objProps = getAllKeys(object), + objLength = objProps.length, + othProps = getAllKeys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked && stack.get(other)) { + return stacked == other; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; + } + + /** + * A specialized version of `baseRest` which flattens the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ + function flatRest(func) { + return setToString(overRest(func, undefined, flatten), func + ''); + } + + /** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); + } + + /** + * Creates an array of own and inherited enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeysIn(object) { + return baseGetAllKeys(object, keysIn, getSymbolsIn); + } + + /** + * Gets metadata for `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {*} Returns the metadata for `func`. + */ + var getData = !metaMap ? noop : function(func) { + return metaMap.get(func); + }; + + /** + * Gets the name of `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {string} Returns the function name. + */ + function getFuncName(func) { + var result = (func.name + ''), + array = realNames[result], + length = hasOwnProperty.call(realNames, result) ? array.length : 0; + + while (length--) { + var data = array[length], + otherFunc = data.func; + if (otherFunc == null || otherFunc == func) { + return data.name; + } + } + return result; + } + + /** + * Gets the argument placeholder value for `func`. + * + * @private + * @param {Function} func The function to inspect. + * @returns {*} Returns the placeholder value. + */ + function getHolder(func) { + var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; + return object.placeholder; + } + + /** + * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, + * this function returns the custom method, otherwise it returns `baseIteratee`. + * If arguments are provided, the chosen function is invoked with them and + * its result is returned. + * + * @private + * @param {*} [value] The value to convert to an iteratee. + * @param {number} [arity] The arity of the created iteratee. + * @returns {Function} Returns the chosen function or its result. + */ + function getIteratee() { + var result = lodash.iteratee || iteratee; + result = result === iteratee ? baseIteratee : result; + return arguments.length ? result(arguments[0], arguments[1]) : result; + } + + /** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ + function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; + } + + /** + * Gets the property names, values, and compare flags of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. + */ + function getMatchData(object) { + var result = keys(object), + length = result.length; + + while (length--) { + var key = result[length], + value = object[key]; + + result[length] = [key, value, isStrictComparable(value)]; + } + return result; + } + + /** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ + function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; + } + + /** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ + function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; + + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; + } + + /** + * Creates an array of the own enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + if (object == null) { + return []; + } + object = Object(object); + return arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable.call(object, symbol); + }); + }; + + /** + * Creates an array of the own and inherited enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { + var result = []; + while (object) { + arrayPush(result, getSymbols(object)); + object = getPrototype(object); + } + return result; + }; + + /** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + var getTag = baseGetTag; + + // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. + if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || + (Map && getTag(new Map) != mapTag) || + (Promise && getTag(Promise.resolve()) != promiseTag) || + (Set && getTag(new Set) != setTag) || + (WeakMap && getTag(new WeakMap) != weakMapTag)) { + getTag = function(value) { + var result = baseGetTag(value), + Ctor = result == objectTag ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag; + case mapCtorString: return mapTag; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag; + case weakMapCtorString: return weakMapTag; + } + } + return result; + }; + } + + /** + * Gets the view, applying any `transforms` to the `start` and `end` positions. + * + * @private + * @param {number} start The start of the view. + * @param {number} end The end of the view. + * @param {Array} transforms The transformations to apply to the view. + * @returns {Object} Returns an object containing the `start` and `end` + * positions of the view. + */ + function getView(start, end, transforms) { + var index = -1, + length = transforms.length; + + while (++index < length) { + var data = transforms[index], + size = data.size; + + switch (data.type) { + case 'drop': start += size; break; + case 'dropRight': end -= size; break; + case 'take': end = nativeMin(end, start + size); break; + case 'takeRight': start = nativeMax(start, end - size); break; + } + } + return { 'start': start, 'end': end }; + } + + /** + * Extracts wrapper details from the `source` body comment. + * + * @private + * @param {string} source The source to inspect. + * @returns {Array} Returns the wrapper details. + */ + function getWrapDetails(source) { + var match = source.match(reWrapDetails); + return match ? match[1].split(reSplitDetails) : []; + } + + /** + * Checks if `path` exists on `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @param {Function} hasFunc The function to check properties. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + */ + function hasPath(object, path, hasFunc) { + path = castPath(path, object); + + var index = -1, + length = path.length, + result = false; + + while (++index < length) { + var key = toKey(path[index]); + if (!(result = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result || ++index != length) { + return result; + } + length = object == null ? 0 : object.length; + return !!length && isLength(length) && isIndex(key, length) && + (isArray(object) || isArguments(object)); + } + + /** + * Initializes an array clone. + * + * @private + * @param {Array} array The array to clone. + * @returns {Array} Returns the initialized clone. + */ + function initCloneArray(array) { + var length = array.length, + result = array.constructor(length); + + // Add properties assigned by `RegExp#exec`. + if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { + result.index = array.index; + result.input = array.input; + } + return result; + } + + /** + * Initializes an object clone. + * + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneObject(object) { + return (typeof object.constructor == 'function' && !isPrototype(object)) + ? baseCreate(getPrototype(object)) + : {}; + } + + /** + * Initializes an object clone based on its `toStringTag`. + * + * **Note:** This function only supports cloning values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to clone. + * @param {string} tag The `toStringTag` of the object to clone. + * @param {Function} cloneFunc The function to clone values. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneByTag(object, tag, cloneFunc, isDeep) { + var Ctor = object.constructor; + switch (tag) { + case arrayBufferTag: + return cloneArrayBuffer(object); + + case boolTag: + case dateTag: + return new Ctor(+object); + + case dataViewTag: + return cloneDataView(object, isDeep); + + case float32Tag: case float64Tag: + case int8Tag: case int16Tag: case int32Tag: + case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: + return cloneTypedArray(object, isDeep); + + case mapTag: + return cloneMap(object, isDeep, cloneFunc); + + case numberTag: + case stringTag: + return new Ctor(object); + + case regexpTag: + return cloneRegExp(object); + + case setTag: + return cloneSet(object, isDeep, cloneFunc); + + case symbolTag: + return cloneSymbol(object); + } + } + + /** + * Inserts wrapper `details` in a comment at the top of the `source` body. + * + * @private + * @param {string} source The source to modify. + * @returns {Array} details The details to insert. + * @returns {string} Returns the modified source. + */ + function insertWrapDetails(source, details) { + var length = details.length; + if (!length) { + return source; + } + var lastIndex = length - 1; + details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; + details = details.join(length > 2 ? ', ' : ' '); + return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); + } + + /** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */ + function isFlattenable(value) { + return isArray(value) || isArguments(value) || + !!(spreadableSymbol && value && value[spreadableSymbol]); + } + + /** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && + (typeof value == 'number' || reIsUint.test(value)) && + (value > -1 && value % 1 == 0 && value < length); + } + + /** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ + function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; + } + + /** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ + function isKey(value, object) { + if (isArray(value)) { + return false; + } + var type = typeof value; + if (type == 'number' || type == 'symbol' || type == 'boolean' || + value == null || isSymbol(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); + } + + /** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ + function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); + } + + /** + * Checks if `func` has a lazy counterpart. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` has a lazy counterpart, + * else `false`. + */ + function isLaziable(func) { + var funcName = getFuncName(func), + other = lodash[funcName]; + + if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { + return false; + } + if (func === other) { + return true; + } + var data = getData(other); + return !!data && func === data[0]; + } + + /** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ + function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); + } + + /** + * Checks if `func` is capable of being masked. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `func` is maskable, else `false`. + */ + var isMaskable = coreJsData ? isFunction : stubFalse; + + /** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ + function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; + } + + /** + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. + */ + function isStrictComparable(value) { + return value === value && !isObject(value); + } + + /** + * A specialized version of `matchesProperty` for source values suitable + * for strict equality comparisons, i.e. `===`. + * + * @private + * @param {string} key The key of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && + (srcValue !== undefined || (key in Object(object))); + }; + } + + /** + * A specialized version of `_.memoize` which clears the memoized function's + * cache when it exceeds `MAX_MEMOIZE_SIZE`. + * + * @private + * @param {Function} func The function to have its output memoized. + * @returns {Function} Returns the new memoized function. + */ + function memoizeCapped(func) { + var result = memoize(func, function(key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + return key; + }); + + var cache = result.cache; + return result; + } + + /** + * Merges the function metadata of `source` into `data`. + * + * Merging metadata reduces the number of wrappers used to invoke a function. + * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` + * may be applied regardless of execution order. Methods like `_.ary` and + * `_.rearg` modify function arguments, making the order in which they are + * executed important, preventing the merging of metadata. However, we make + * an exception for a safe combined case where curried functions have `_.ary` + * and or `_.rearg` applied. + * + * @private + * @param {Array} data The destination metadata. + * @param {Array} source The source metadata. + * @returns {Array} Returns `data`. + */ + function mergeData(data, source) { + var bitmask = data[1], + srcBitmask = source[1], + newBitmask = bitmask | srcBitmask, + isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); + + var isCombo = + ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || + ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || + ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); + + // Exit early if metadata can't be merged. + if (!(isCommon || isCombo)) { + return data; + } + // Use source `thisArg` if available. + if (srcBitmask & WRAP_BIND_FLAG) { + data[2] = source[2]; + // Set when currying a bound function. + newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; + } + // Compose partial arguments. + var value = source[3]; + if (value) { + var partials = data[3]; + data[3] = partials ? composeArgs(partials, value, source[4]) : value; + data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; + } + // Compose partial right arguments. + value = source[5]; + if (value) { + partials = data[5]; + data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; + data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; + } + // Use source `argPos` if available. + value = source[7]; + if (value) { + data[7] = value; + } + // Use source `ary` if it's smaller. + if (srcBitmask & WRAP_ARY_FLAG) { + data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); + } + // Use source `arity` if one is not provided. + if (data[9] == null) { + data[9] = source[9]; + } + // Use source `func` and merge bitmasks. + data[0] = source[0]; + data[1] = newBitmask; + + return data; + } + + /** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; + } + + /** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ + function objectToString(value) { + return nativeObjectToString.call(value); + } + + /** + * A specialized version of `baseRest` which transforms the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ + function overRest(func, start, transform) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return apply(func, this, otherArgs); + }; + } + + /** + * Gets the parent value at `path` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} path The path to get the parent value of. + * @returns {*} Returns the parent value. + */ + function parent(object, path) { + return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); + } + + /** + * Reorder `array` according to the specified indexes where the element at + * the first index is assigned as the first element, the element at + * the second index is assigned as the second element, and so on. + * + * @private + * @param {Array} array The array to reorder. + * @param {Array} indexes The arranged array indexes. + * @returns {Array} Returns `array`. + */ + function reorder(array, indexes) { + var arrLength = array.length, + length = nativeMin(indexes.length, arrLength), + oldArray = copyArray(array); + + while (length--) { + var index = indexes[length]; + array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; + } + return array; + } + + /** + * Sets metadata for `func`. + * + * **Note:** If this function becomes hot, i.e. is invoked a lot in a short + * period of time, it will trip its breaker and transition to an identity + * function to avoid garbage collection pauses in V8. See + * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) + * for more details. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ + var setData = shortOut(baseSetData); + + /** + * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @returns {number|Object} Returns the timer id or timeout object. + */ + var setTimeout = ctxSetTimeout || function(func, wait) { + return root.setTimeout(func, wait); + }; + + /** + * Sets the `toString` method of `func` to return `string`. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var setToString = shortOut(baseSetToString); + + /** + * Sets the `toString` method of `wrapper` to mimic the source of `reference` + * with wrapper details in a comment at the top of the source body. + * + * @private + * @param {Function} wrapper The function to modify. + * @param {Function} reference The reference function. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Function} Returns `wrapper`. + */ + function setWrapToString(wrapper, reference, bitmask) { + var source = (reference + ''); + return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); + } + + /** + * Creates a function that'll short out and invoke `identity` instead + * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` + * milliseconds. + * + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. + */ + function shortOut(func) { + var count = 0, + lastCalled = 0; + + return function() { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); + + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; + } + + /** + * A specialized version of `_.shuffle` which mutates and sets the size of `array`. + * + * @private + * @param {Array} array The array to shuffle. + * @param {number} [size=array.length] The size of `array`. + * @returns {Array} Returns `array`. + */ + function shuffleSelf(array, size) { + var index = -1, + length = array.length, + lastIndex = length - 1; + + size = size === undefined ? length : size; + while (++index < size) { + var rand = baseRandom(index, lastIndex), + value = array[rand]; + + array[rand] = array[index]; + array[index] = value; + } + array.length = size; + return array; + } + + /** + * Converts `string` to a property path array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ + var stringToPath = memoizeCapped(function(string) { + var result = []; + if (reLeadingDot.test(string)) { + result.push(''); + } + string.replace(rePropName, function(match, number, quote, string) { + result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; + }); + + /** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ + function toKey(value) { + if (typeof value == 'string' || isSymbol(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + } + + /** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ + function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; + } + + /** + * Updates wrapper `details` based on `bitmask` flags. + * + * @private + * @returns {Array} details The details to modify. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Array} Returns `details`. + */ + function updateWrapDetails(details, bitmask) { + arrayEach(wrapFlags, function(pair) { + var value = '_.' + pair[0]; + if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { + details.push(value); + } + }); + return details.sort(); + } + + /** + * Creates a clone of `wrapper`. + * + * @private + * @param {Object} wrapper The wrapper to clone. + * @returns {Object} Returns the cloned wrapper. + */ + function wrapperClone(wrapper) { + if (wrapper instanceof LazyWrapper) { + return wrapper.clone(); + } + var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); + result.__actions__ = copyArray(wrapper.__actions__); + result.__index__ = wrapper.__index__; + result.__values__ = wrapper.__values__; + return result; + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates an array of elements split into groups the length of `size`. + * If `array` can't be split evenly, the final chunk will be the remaining + * elements. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to process. + * @param {number} [size=1] The length of each chunk + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the new array of chunks. + * @example + * + * _.chunk(['a', 'b', 'c', 'd'], 2); + * // => [['a', 'b'], ['c', 'd']] + * + * _.chunk(['a', 'b', 'c', 'd'], 3); + * // => [['a', 'b', 'c'], ['d']] + */ + function chunk(array, size, guard) { + if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { + size = 1; + } else { + size = nativeMax(toInteger(size), 0); + } + var length = array == null ? 0 : array.length; + if (!length || size < 1) { + return []; + } + var index = 0, + resIndex = 0, + result = Array(nativeCeil(length / size)); + + while (index < length) { + result[resIndex++] = baseSlice(array, index, (index += size)); + } + return result; + } + + /** + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `""`, `undefined`, and `NaN` are falsey. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to compact. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] + */ + function compact(array) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value) { + result[resIndex++] = value; + } + } + return result; + } + + /** + * Creates a new array concatenating `array` with any additional arrays + * and/or values. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to concatenate. + * @param {...*} [values] The values to concatenate. + * @returns {Array} Returns the new concatenated array. + * @example + * + * var array = [1]; + * var other = _.concat(array, 2, [3], [[4]]); + * + * console.log(other); + * // => [1, 2, 3, [4]] + * + * console.log(array); + * // => [1] + */ + function concat() { + var length = arguments.length; + if (!length) { + return []; + } + var args = Array(length - 1), + array = arguments[0], + index = length; + + while (index--) { + args[index - 1] = arguments[index]; + } + return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); + } + + /** + * Creates an array of `array` values not included in the other given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * **Note:** Unlike `_.pullAll`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.without, _.xor + * @example + * + * _.difference([2, 1], [2, 3]); + * // => [1] + */ + var difference = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) + : []; + }); + + /** + * This method is like `_.difference` except that it accepts `iteratee` which + * is invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * **Note:** Unlike `_.pullAllBy`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2] + * + * // The `_.property` iteratee shorthand. + * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */ + var differenceBy = baseRest(function(array, values) { + var iteratee = last(values); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) + : []; + }); + + /** + * This method is like `_.difference` except that it accepts `comparator` + * which is invoked to compare elements of `array` to `values`. The order and + * references of result values are determined by the first array. The comparator + * is invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.pullAllWith`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * + * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); + * // => [{ 'x': 2, 'y': 1 }] + */ + var differenceWith = baseRest(function(array, values) { + var comparator = last(values); + if (isArrayLikeObject(comparator)) { + comparator = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) + : []; + }); + + /** + * Creates a slice of `array` with `n` elements dropped from the beginning. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.drop([1, 2, 3]); + * // => [2, 3] + * + * _.drop([1, 2, 3], 2); + * // => [3] + * + * _.drop([1, 2, 3], 5); + * // => [] + * + * _.drop([1, 2, 3], 0); + * // => [1, 2, 3] + */ + function drop(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, n < 0 ? 0 : n, length); + } + + /** + * Creates a slice of `array` with `n` elements dropped from the end. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropRight([1, 2, 3]); + * // => [1, 2] + * + * _.dropRight([1, 2, 3], 2); + * // => [1] + * + * _.dropRight([1, 2, 3], 5); + * // => [] + * + * _.dropRight([1, 2, 3], 0); + * // => [1, 2, 3] + */ + function dropRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, 0, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` excluding elements dropped from the end. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.dropRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney'] + * + * // The `_.matches` iteratee shorthand. + * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropRightWhile(users, ['active', false]); + * // => objects for ['barney'] + * + * // The `_.property` iteratee shorthand. + * _.dropRightWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */ + function dropRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true, true) + : []; + } + + /** + * Creates a slice of `array` excluding elements dropped from the beginning. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.dropWhile(users, function(o) { return !o.active; }); + * // => objects for ['pebbles'] + * + * // The `_.matches` iteratee shorthand. + * _.dropWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropWhile(users, ['active', false]); + * // => objects for ['pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.dropWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */ + function dropWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true) + : []; + } + + /** + * Fills elements of `array` with `value` from `start` up to, but not + * including, `end`. + * + * **Note:** This method mutates `array`. + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Array + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.fill(array, 'a'); + * console.log(array); + * // => ['a', 'a', 'a'] + * + * _.fill(Array(3), 2); + * // => [2, 2, 2] + * + * _.fill([4, 6, 8, 10], '*', 1, 3); + * // => [4, '*', '*', 10] + */ + function fill(array, value, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { + start = 0; + end = length; + } + return baseFill(array, value, start, end); + } + + /** + * This method is like `_.find` except that it returns the index of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.findIndex(users, function(o) { return o.user == 'barney'; }); + * // => 0 + * + * // The `_.matches` iteratee shorthand. + * _.findIndex(users, { 'user': 'fred', 'active': false }); + * // => 1 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findIndex(users, ['active', false]); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.findIndex(users, 'active'); + * // => 2 + */ + function findIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseFindIndex(array, getIteratee(predicate, 3), index); + } + + /** + * This method is like `_.findIndex` except that it iterates over elements + * of `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); + * // => 2 + * + * // The `_.matches` iteratee shorthand. + * _.findLastIndex(users, { 'user': 'barney', 'active': true }); + * // => 0 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastIndex(users, ['active', false]); + * // => 2 + * + * // The `_.property` iteratee shorthand. + * _.findLastIndex(users, 'active'); + * // => 0 + */ + function findLastIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length - 1; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = fromIndex < 0 + ? nativeMax(length + index, 0) + : nativeMin(index, length - 1); + } + return baseFindIndex(array, getIteratee(predicate, 3), index, true); + } + + /** + * Flattens `array` a single level deep. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] + */ + function flatten(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, 1) : []; + } + + /** + * Recursively flattens `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flattenDeep([1, [2, [3, [4]], 5]]); + * // => [1, 2, 3, 4, 5] + */ + function flattenDeep(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, INFINITY) : []; + } + + /** + * Recursively flatten `array` up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Array + * @param {Array} array The array to flatten. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * var array = [1, [2, [3, [4]], 5]]; + * + * _.flattenDepth(array, 1); + * // => [1, 2, [3, [4]], 5] + * + * _.flattenDepth(array, 2); + * // => [1, 2, 3, [4], 5] + */ + function flattenDepth(array, depth) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(array, depth); + } + + /** + * The inverse of `_.toPairs`; this method returns an object composed + * from key-value `pairs`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} pairs The key-value pairs. + * @returns {Object} Returns the new object. + * @example + * + * _.fromPairs([['a', 1], ['b', 2]]); + * // => { 'a': 1, 'b': 2 } + */ + function fromPairs(pairs) { + var index = -1, + length = pairs == null ? 0 : pairs.length, + result = {}; + + while (++index < length) { + var pair = pairs[index]; + result[pair[0]] = pair[1]; + } + return result; + } + + /** + * Gets the first element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias first + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the first element of `array`. + * @example + * + * _.head([1, 2, 3]); + * // => 1 + * + * _.head([]); + * // => undefined + */ + function head(array) { + return (array && array.length) ? array[0] : undefined; + } + + /** + * Gets the index at which the first occurrence of `value` is found in `array` + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it's used as the + * offset from the end of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.indexOf([1, 2, 1, 2], 2); + * // => 1 + * + * // Search from the `fromIndex`. + * _.indexOf([1, 2, 1, 2], 2, 2); + * // => 3 + */ + function indexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseIndexOf(array, value, index); + } + + /** + * Gets all but the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.initial([1, 2, 3]); + * // => [1, 2] + */ + function initial(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 0, -1) : []; + } + + /** + * Creates an array of unique values that are included in all given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersection([2, 1], [2, 3]); + * // => [2] + */ + var intersection = baseRest(function(arrays) { + var mapped = arrayMap(arrays, castArrayLikeObject); + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped) + : []; + }); + + /** + * This method is like `_.intersection` except that it accepts `iteratee` + * which is invoked for each element of each `arrays` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [2.1] + * + * // The `_.property` iteratee shorthand. + * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }] + */ + var intersectionBy = baseRest(function(arrays) { + var iteratee = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + if (iteratee === last(mapped)) { + iteratee = undefined; + } else { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, getIteratee(iteratee, 2)) + : []; + }); + + /** + * This method is like `_.intersection` except that it accepts `comparator` + * which is invoked to compare elements of `arrays`. The order and references + * of result values are determined by the first array. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.intersectionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }] + */ + var intersectionWith = baseRest(function(arrays) { + var comparator = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + comparator = typeof comparator == 'function' ? comparator : undefined; + if (comparator) { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, undefined, comparator) + : []; + }); + + /** + * Converts all elements in `array` into a string separated by `separator`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to convert. + * @param {string} [separator=','] The element separator. + * @returns {string} Returns the joined string. + * @example + * + * _.join(['a', 'b', 'c'], '~'); + * // => 'a~b~c' + */ + function join(array, separator) { + return array == null ? '' : nativeJoin.call(array, separator); + } + + /** + * Gets the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + */ + function last(array) { + var length = array == null ? 0 : array.length; + return length ? array[length - 1] : undefined; + } + + /** + * This method is like `_.indexOf` except that it iterates over elements of + * `array` from right to left. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.lastIndexOf([1, 2, 1, 2], 2); + * // => 3 + * + * // Search from the `fromIndex`. + * _.lastIndexOf([1, 2, 1, 2], 2, 2); + * // => 1 + */ + function lastIndexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); + } + return value === value + ? strictLastIndexOf(array, value, index) + : baseFindIndex(array, baseIsNaN, index, true); + } + + /** + * Gets the element at index `n` of `array`. If `n` is negative, the nth + * element from the end is returned. + * + * @static + * @memberOf _ + * @since 4.11.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=0] The index of the element to return. + * @returns {*} Returns the nth element of `array`. + * @example + * + * var array = ['a', 'b', 'c', 'd']; + * + * _.nth(array, 1); + * // => 'b' + * + * _.nth(array, -2); + * // => 'c'; + */ + function nth(array, n) { + return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; + } + + /** + * Removes all given values from `array` using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` + * to remove elements from an array by predicate. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...*} [values] The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * + * _.pull(array, 'a', 'c'); + * console.log(array); + * // => ['b', 'b'] + */ + var pull = baseRest(pullAll); + + /** + * This method is like `_.pull` except that it accepts an array of values to remove. + * + * **Note:** Unlike `_.difference`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * + * _.pullAll(array, ['a', 'c']); + * console.log(array); + * // => ['b', 'b'] + */ + function pullAll(array, values) { + return (array && array.length && values && values.length) + ? basePullAll(array, values) + : array; + } + + /** + * This method is like `_.pullAll` except that it accepts `iteratee` which is + * invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The iteratee is invoked with one argument: (value). + * + * **Note:** Unlike `_.differenceBy`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns `array`. + * @example + * + * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; + * + * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); + * console.log(array); + * // => [{ 'x': 2 }] + */ + function pullAllBy(array, values, iteratee) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, getIteratee(iteratee, 2)) + : array; + } + + /** + * This method is like `_.pullAll` except that it accepts `comparator` which + * is invoked to compare elements of `array` to `values`. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.differenceWith`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. + * @example + * + * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; + * + * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); + * console.log(array); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] + */ + function pullAllWith(array, values, comparator) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, undefined, comparator) + : array; + } + + /** + * Removes elements from `array` corresponding to `indexes` and returns an + * array of removed elements. + * + * **Note:** Unlike `_.at`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...(number|number[])} [indexes] The indexes of elements to remove. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = ['a', 'b', 'c', 'd']; + * var pulled = _.pullAt(array, [1, 3]); + * + * console.log(array); + * // => ['a', 'c'] + * + * console.log(pulled); + * // => ['b', 'd'] + */ + var pullAt = flatRest(function(array, indexes) { + var length = array == null ? 0 : array.length, + result = baseAt(array, indexes); + + basePullAt(array, arrayMap(indexes, function(index) { + return isIndex(index, length) ? +index : index; + }).sort(compareAscending)); + + return result; + }); + + /** + * Removes all elements from `array` that `predicate` returns truthy for + * and returns an array of the removed elements. The predicate is invoked + * with three arguments: (value, index, array). + * + * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` + * to pull elements from an array by value. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = [1, 2, 3, 4]; + * var evens = _.remove(array, function(n) { + * return n % 2 == 0; + * }); + * + * console.log(array); + * // => [1, 3] + * + * console.log(evens); + * // => [2, 4] + */ + function remove(array, predicate) { + var result = []; + if (!(array && array.length)) { + return result; + } + var index = -1, + indexes = [], + length = array.length; + + predicate = getIteratee(predicate, 3); + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result.push(value); + indexes.push(index); + } + } + basePullAt(array, indexes); + return result; + } + + /** + * Reverses `array` so that the first element becomes the last, the second + * element becomes the second to last, and so on. + * + * **Note:** This method mutates `array` and is based on + * [`Array#reverse`](https://mdn.io/Array/reverse). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.reverse(array); + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */ + function reverse(array) { + return array == null ? array : nativeReverse.call(array); + } + + /** + * Creates a slice of `array` from `start` up to, but not including, `end`. + * + * **Note:** This method is used instead of + * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are + * returned. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function slice(array, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { + start = 0; + end = length; + } + else { + start = start == null ? 0 : toInteger(start); + end = end === undefined ? length : toInteger(end); + } + return baseSlice(array, start, end); + } + + /** + * Uses a binary search to determine the lowest index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedIndex([30, 50], 40); + * // => 1 + */ + function sortedIndex(array, value) { + return baseSortedIndex(array, value); + } + + /** + * This method is like `_.sortedIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * + * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); + * // => 0 + */ + function sortedIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); + } + + /** + * This method is like `_.indexOf` except that it performs a binary + * search on a sorted `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.sortedIndexOf([4, 5, 5, 5, 6], 5); + * // => 1 + */ + function sortedIndexOf(array, value) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value); + if (index < length && eq(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * This method is like `_.sortedIndex` except that it returns the highest + * index at which `value` should be inserted into `array` in order to + * maintain its sort order. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedLastIndex([4, 5, 5, 5, 6], 5); + * // => 4 + */ + function sortedLastIndex(array, value) { + return baseSortedIndex(array, value, true); + } + + /** + * This method is like `_.sortedLastIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * + * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 1 + * + * // The `_.property` iteratee shorthand. + * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); + * // => 1 + */ + function sortedLastIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); + } + + /** + * This method is like `_.lastIndexOf` except that it performs a binary + * search on a sorted `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); + * // => 3 + */ + function sortedLastIndexOf(array, value) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value, true) - 1; + if (eq(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * This method is like `_.uniq` except that it's designed and optimized + * for sorted arrays. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.sortedUniq([1, 1, 2]); + * // => [1, 2] + */ + function sortedUniq(array) { + return (array && array.length) + ? baseSortedUniq(array) + : []; + } + + /** + * This method is like `_.uniqBy` except that it's designed and optimized + * for sorted arrays. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); + * // => [1.1, 2.3] + */ + function sortedUniqBy(array, iteratee) { + return (array && array.length) + ? baseSortedUniq(array, getIteratee(iteratee, 2)) + : []; + } + + /** + * Gets all but the first element of `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.tail([1, 2, 3]); + * // => [2, 3] + */ + function tail(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 1, length) : []; + } + + /** + * Creates a slice of `array` with `n` elements taken from the beginning. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.take([1, 2, 3]); + * // => [1] + * + * _.take([1, 2, 3], 2); + * // => [1, 2] + * + * _.take([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.take([1, 2, 3], 0); + * // => [] + */ + function take(array, n, guard) { + if (!(array && array.length)) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, 0, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` with `n` elements taken from the end. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.takeRight([1, 2, 3]); + * // => [3] + * + * _.takeRight([1, 2, 3], 2); + * // => [2, 3] + * + * _.takeRight([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.takeRight([1, 2, 3], 0); + * // => [] + */ + function takeRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, n < 0 ? 0 : n, length); + } + + /** + * Creates a slice of `array` with elements taken from the end. Elements are + * taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.takeRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.matches` iteratee shorthand. + * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeRightWhile(users, ['active', false]); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.takeRightWhile(users, 'active'); + * // => [] + */ + function takeRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), false, true) + : []; + } + + /** + * Creates a slice of `array` with elements taken from the beginning. Elements + * are taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.takeWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matches` iteratee shorthand. + * _.takeWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeWhile(users, ['active', false]); + * // => objects for ['barney', 'fred'] + * + * // The `_.property` iteratee shorthand. + * _.takeWhile(users, 'active'); + * // => [] + */ + function takeWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3)) + : []; + } + + /** + * Creates an array of unique values, in order, from all given arrays using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.union([2], [1, 2]); + * // => [2, 1] + */ + var union = baseRest(function(arrays) { + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); + }); + + /** + * This method is like `_.union` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which uniqueness is computed. Result values are chosen from the first + * array in which the value occurs. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.unionBy([2.1], [1.2, 2.3], Math.floor); + * // => [2.1, 1.2] + * + * // The `_.property` iteratee shorthand. + * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + var unionBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); + }); + + /** + * This method is like `_.union` except that it accepts `comparator` which + * is invoked to compare elements of `arrays`. Result values are chosen from + * the first array in which the value occurs. The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of combined values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.unionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + */ + var unionWith = baseRest(function(arrays) { + var comparator = last(arrays); + comparator = typeof comparator == 'function' ? comparator : undefined; + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); + }); + + /** + * Creates a duplicate-free version of an array, using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons, in which only the first occurrence of each element + * is kept. The order of result values is determined by the order they occur + * in the array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.uniq([2, 1, 2]); + * // => [2, 1] + */ + function uniq(array) { + return (array && array.length) ? baseUniq(array) : []; + } + + /** + * This method is like `_.uniq` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the criterion by which + * uniqueness is computed. The order of result values is determined by the + * order they occur in the array. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.uniqBy([2.1, 1.2, 2.3], Math.floor); + * // => [2.1, 1.2] + * + * // The `_.property` iteratee shorthand. + * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + function uniqBy(array, iteratee) { + return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; + } + + /** + * This method is like `_.uniq` except that it accepts `comparator` which + * is invoked to compare elements of `array`. The order of result values is + * determined by the order they occur in the array.The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.uniqWith(objects, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] + */ + function uniqWith(array, comparator) { + comparator = typeof comparator == 'function' ? comparator : undefined; + return (array && array.length) ? baseUniq(array, undefined, comparator) : []; + } + + /** + * This method is like `_.zip` except that it accepts an array of grouped + * elements and creates an array regrouping the elements to their pre-zip + * configuration. + * + * @static + * @memberOf _ + * @since 1.2.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] + * + * _.unzip(zipped); + * // => [['a', 'b'], [1, 2], [true, false]] + */ + function unzip(array) { + if (!(array && array.length)) { + return []; + } + var length = 0; + array = arrayFilter(array, function(group) { + if (isArrayLikeObject(group)) { + length = nativeMax(group.length, length); + return true; + } + }); + return baseTimes(length, function(index) { + return arrayMap(array, baseProperty(index)); + }); + } + + /** + * This method is like `_.unzip` except that it accepts `iteratee` to specify + * how regrouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @param {Function} [iteratee=_.identity] The function to combine + * regrouped values. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip([1, 2], [10, 20], [100, 200]); + * // => [[1, 10, 100], [2, 20, 200]] + * + * _.unzipWith(zipped, _.add); + * // => [3, 30, 300] + */ + function unzipWith(array, iteratee) { + if (!(array && array.length)) { + return []; + } + var result = unzip(array); + if (iteratee == null) { + return result; + } + return arrayMap(result, function(group) { + return apply(iteratee, undefined, group); + }); + } + + /** + * Creates an array excluding all given values using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.pull`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...*} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.xor + * @example + * + * _.without([2, 1, 2, 3], 1, 2); + * // => [3] + */ + var without = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, values) + : []; + }); + + /** + * Creates an array of unique values that is the + * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) + * of the given arrays. The order of result values is determined by the order + * they occur in the arrays. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.without + * @example + * + * _.xor([2, 1], [2, 3]); + * // => [1, 3] + */ + var xor = baseRest(function(arrays) { + return baseXor(arrayFilter(arrays, isArrayLikeObject)); + }); + + /** + * This method is like `_.xor` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which by which they're compared. The order of result values is determined + * by the order they occur in the arrays. The iteratee is invoked with one + * argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2, 3.4] + * + * // The `_.property` iteratee shorthand. + * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */ + var xorBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); + }); + + /** + * This method is like `_.xor` except that it accepts `comparator` which is + * invoked to compare elements of `arrays`. The order of result values is + * determined by the order they occur in the arrays. The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.xorWith(objects, others, _.isEqual); + * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + */ + var xorWith = baseRest(function(arrays) { + var comparator = last(arrays); + comparator = typeof comparator == 'function' ? comparator : undefined; + return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); + }); + + /** + * Creates an array of grouped elements, the first of which contains the + * first elements of the given arrays, the second of which contains the + * second elements of the given arrays, and so on. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] + */ + var zip = baseRest(unzip); + + /** + * This method is like `_.fromPairs` except that it accepts two arrays, + * one of property identifiers and one of corresponding values. + * + * @static + * @memberOf _ + * @since 0.4.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example + * + * _.zipObject(['a', 'b'], [1, 2]); + * // => { 'a': 1, 'b': 2 } + */ + function zipObject(props, values) { + return baseZipObject(props || [], values || [], assignValue); + } + + /** + * This method is like `_.zipObject` except that it supports property paths. + * + * @static + * @memberOf _ + * @since 4.1.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example + * + * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); + * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } + */ + function zipObjectDeep(props, values) { + return baseZipObject(props || [], values || [], baseSet); + } + + /** + * This method is like `_.zip` except that it accepts `iteratee` to specify + * how grouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @param {Function} [iteratee=_.identity] The function to combine + * grouped values. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { + * return a + b + c; + * }); + * // => [111, 222] + */ + var zipWith = baseRest(function(arrays) { + var length = arrays.length, + iteratee = length > 1 ? arrays[length - 1] : undefined; + + iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; + return unzipWith(arrays, iteratee); + }); + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` wrapper instance that wraps `value` with explicit method + * chain sequences enabled. The result of such sequences must be unwrapped + * with `_#value`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Seq + * @param {*} value The value to wrap. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'pebbles', 'age': 1 } + * ]; + * + * var youngest = _ + * .chain(users) + * .sortBy('age') + * .map(function(o) { + * return o.user + ' is ' + o.age; + * }) + * .head() + * .value(); + * // => 'pebbles is 1' + */ + function chain(value) { + var result = lodash(value); + result.__chain__ = true; + return result; + } + + /** + * This method invokes `interceptor` and returns `value`. The interceptor + * is invoked with one argument; (value). The purpose of this method is to + * "tap into" a method chain sequence in order to modify intermediate results. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns `value`. + * @example + * + * _([1, 2, 3]) + * .tap(function(array) { + * // Mutate input array. + * array.pop(); + * }) + * .reverse() + * .value(); + * // => [2, 1] + */ + function tap(value, interceptor) { + interceptor(value); + return value; + } + + /** + * This method is like `_.tap` except that it returns the result of `interceptor`. + * The purpose of this method is to "pass thru" values replacing intermediate + * results in a method chain sequence. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns the result of `interceptor`. + * @example + * + * _(' abc ') + * .chain() + * .trim() + * .thru(function(value) { + * return [value]; + * }) + * .value(); + * // => ['abc'] + */ + function thru(value, interceptor) { + return interceptor(value); + } + + /** + * This method is the wrapper version of `_.at`. + * + * @name at + * @memberOf _ + * @since 1.0.0 + * @category Seq + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * + * _(object).at(['a[0].b.c', 'a[1]']).value(); + * // => [3, 4] + */ + var wrapperAt = flatRest(function(paths) { + var length = paths.length, + start = length ? paths[0] : 0, + value = this.__wrapped__, + interceptor = function(object) { return baseAt(object, paths); }; + + if (length > 1 || this.__actions__.length || + !(value instanceof LazyWrapper) || !isIndex(start)) { + return this.thru(interceptor); + } + value = value.slice(start, +start + (length ? 1 : 0)); + value.__actions__.push({ + 'func': thru, + 'args': [interceptor], + 'thisArg': undefined + }); + return new LodashWrapper(value, this.__chain__).thru(function(array) { + if (length && !array.length) { + array.push(undefined); + } + return array; + }); + }); + + /** + * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. + * + * @name chain + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; + * + * // A sequence without explicit chaining. + * _(users).head(); + * // => { 'user': 'barney', 'age': 36 } + * + * // A sequence with explicit chaining. + * _(users) + * .chain() + * .head() + * .pick('user') + * .value(); + * // => { 'user': 'barney' } + */ + function wrapperChain() { + return chain(this); + } + + /** + * Executes the chain sequence and returns the wrapped result. + * + * @name commit + * @memberOf _ + * @since 3.2.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2]; + * var wrapped = _(array).push(3); + * + * console.log(array); + * // => [1, 2] + * + * wrapped = wrapped.commit(); + * console.log(array); + * // => [1, 2, 3] + * + * wrapped.last(); + * // => 3 + * + * console.log(array); + * // => [1, 2, 3] + */ + function wrapperCommit() { + return new LodashWrapper(this.value(), this.__chain__); + } + + /** + * Gets the next value on a wrapped object following the + * [iterator protocol](https://mdn.io/iteration_protocols#iterator). + * + * @name next + * @memberOf _ + * @since 4.0.0 + * @category Seq + * @returns {Object} Returns the next iterator value. + * @example + * + * var wrapped = _([1, 2]); + * + * wrapped.next(); + * // => { 'done': false, 'value': 1 } + * + * wrapped.next(); + * // => { 'done': false, 'value': 2 } + * + * wrapped.next(); + * // => { 'done': true, 'value': undefined } + */ + function wrapperNext() { + if (this.__values__ === undefined) { + this.__values__ = toArray(this.value()); + } + var done = this.__index__ >= this.__values__.length, + value = done ? undefined : this.__values__[this.__index__++]; + + return { 'done': done, 'value': value }; + } + + /** + * Enables the wrapper to be iterable. + * + * @name Symbol.iterator + * @memberOf _ + * @since 4.0.0 + * @category Seq + * @returns {Object} Returns the wrapper object. + * @example + * + * var wrapped = _([1, 2]); + * + * wrapped[Symbol.iterator]() === wrapped; + * // => true + * + * Array.from(wrapped); + * // => [1, 2] + */ + function wrapperToIterator() { + return this; + } + + /** + * Creates a clone of the chain sequence planting `value` as the wrapped value. + * + * @name plant + * @memberOf _ + * @since 3.2.0 + * @category Seq + * @param {*} value The value to plant. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2]).map(square); + * var other = wrapped.plant([3, 4]); + * + * other.value(); + * // => [9, 16] + * + * wrapped.value(); + * // => [1, 4] + */ + function wrapperPlant(value) { + var result, + parent = this; + + while (parent instanceof baseLodash) { + var clone = wrapperClone(parent); + clone.__index__ = 0; + clone.__values__ = undefined; + if (result) { + previous.__wrapped__ = clone; + } else { + result = clone; + } + var previous = clone; + parent = parent.__wrapped__; + } + previous.__wrapped__ = value; + return result; + } + + /** + * This method is the wrapper version of `_.reverse`. + * + * **Note:** This method mutates the wrapped array. + * + * @name reverse + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2, 3]; + * + * _(array).reverse().value() + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */ + function wrapperReverse() { + var value = this.__wrapped__; + if (value instanceof LazyWrapper) { + var wrapped = value; + if (this.__actions__.length) { + wrapped = new LazyWrapper(this); + } + wrapped = wrapped.reverse(); + wrapped.__actions__.push({ + 'func': thru, + 'args': [reverse], + 'thisArg': undefined + }); + return new LodashWrapper(wrapped, this.__chain__); + } + return this.thru(reverse); + } + + /** + * Executes the chain sequence to resolve the unwrapped value. + * + * @name value + * @memberOf _ + * @since 0.1.0 + * @alias toJSON, valueOf + * @category Seq + * @returns {*} Returns the resolved unwrapped value. + * @example + * + * _([1, 2, 3]).value(); + * // => [1, 2, 3] + */ + function wrapperValue() { + return baseWrapperValue(this.__wrapped__, this.__actions__); + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the number of times the key was returned by `iteratee`. The + * iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.countBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': 1, '6': 2 } + * + * // The `_.property` iteratee shorthand. + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } + */ + var countBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + ++result[key]; + } else { + baseAssignValue(result, key, 1); + } + }); + + /** + * Checks if `predicate` returns truthy for **all** elements of `collection`. + * Iteration is stopped once `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * **Note:** This method returns `true` for + * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because + * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of + * elements of empty collections. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + * @example + * + * _.every([true, 1, null, 'yes'], Boolean); + * // => false + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.every(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.every(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.every(users, 'active'); + * // => false + */ + function every(collection, predicate, guard) { + var func = isArray(collection) ? arrayEvery : baseEvery; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, getIteratee(predicate, 3)); + } + + /** + * Iterates over elements of `collection`, returning an array of all elements + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * **Note:** Unlike `_.remove`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.reject + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * _.filter(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.filter(users, { 'age': 36, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.filter(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.filter(users, 'active'); + * // => objects for ['barney'] + */ + function filter(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, getIteratee(predicate, 3)); + } + + /** + * Iterates over elements of `collection`, returning the first element + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': true } + * ]; + * + * _.find(users, function(o) { return o.age < 40; }); + * // => object for 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.find(users, { 'age': 1, 'active': true }); + * // => object for 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.find(users, ['active', false]); + * // => object for 'fred' + * + * // The `_.property` iteratee shorthand. + * _.find(users, 'active'); + * // => object for 'barney' + */ + var find = createFind(findIndex); + + /** + * This method is like `_.find` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=collection.length-1] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * _.findLast([1, 2, 3, 4], function(n) { + * return n % 2 == 1; + * }); + * // => 3 + */ + var findLast = createFind(findLastIndex); + + /** + * Creates a flattened array of values by running each element in `collection` + * thru `iteratee` and flattening the mapped results. The iteratee is invoked + * with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [n, n]; + * } + * + * _.flatMap([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ + function flatMap(collection, iteratee) { + return baseFlatten(map(collection, iteratee), 1); + } + + /** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDeep([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ + function flatMapDeep(collection, iteratee) { + return baseFlatten(map(collection, iteratee), INFINITY); + } + + /** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDepth([1, 2], duplicate, 2); + * // => [[1, 1], [2, 2]] + */ + function flatMapDepth(collection, iteratee, depth) { + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(map(collection, iteratee), depth); + } + + /** + * Iterates over elements of `collection` and invokes `iteratee` for each element. + * The iteratee is invoked with three arguments: (value, index|key, collection). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * **Note:** As with other "Collections" methods, objects with a "length" + * property are iterated like arrays. To avoid this behavior use `_.forIn` + * or `_.forOwn` for object iteration. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias each + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEachRight + * @example + * + * _.forEach([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `1` then `2`. + * + * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ + function forEach(collection, iteratee) { + var func = isArray(collection) ? arrayEach : baseEach; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.forEach` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @alias eachRight + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEach + * @example + * + * _.forEachRight([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `2` then `1`. + */ + function forEachRight(collection, iteratee) { + var func = isArray(collection) ? arrayEachRight : baseEachRight; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The order of grouped values + * is determined by the order they occur in `collection`. The corresponding + * value of each key is an array of elements responsible for generating the + * key. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.groupBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': [4.2], '6': [6.1, 6.3] } + * + * // The `_.property` iteratee shorthand. + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } + */ + var groupBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + result[key].push(value); + } else { + baseAssignValue(result, key, [value]); + } + }); + + /** + * Checks if `value` is in `collection`. If `collection` is a string, it's + * checked for a substring of `value`, otherwise + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * is used for equality comparisons. If `fromIndex` is negative, it's used as + * the offset from the end of `collection`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {boolean} Returns `true` if `value` is found, else `false`. + * @example + * + * _.includes([1, 2, 3], 1); + * // => true + * + * _.includes([1, 2, 3], 1, 2); + * // => false + * + * _.includes({ 'a': 1, 'b': 2 }, 1); + * // => true + * + * _.includes('abcd', 'bc'); + * // => true + */ + function includes(collection, value, fromIndex, guard) { + collection = isArrayLike(collection) ? collection : values(collection); + fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; + + var length = collection.length; + if (fromIndex < 0) { + fromIndex = nativeMax(length + fromIndex, 0); + } + return isString(collection) + ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) + : (!!length && baseIndexOf(collection, value, fromIndex) > -1); + } + + /** + * Invokes the method at `path` of each element in `collection`, returning + * an array of the results of each invoked method. Any additional arguments + * are provided to each invoked method. If `path` is a function, it's invoked + * for, and `this` bound to, each element in `collection`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array|Function|string} path The path of the method to invoke or + * the function invoked per iteration. + * @param {...*} [args] The arguments to invoke each method with. + * @returns {Array} Returns the array of results. + * @example + * + * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); + * // => [[1, 5, 7], [1, 2, 3]] + * + * _.invokeMap([123, 456], String.prototype.split, ''); + * // => [['1', '2', '3'], ['4', '5', '6']] + */ + var invokeMap = baseRest(function(collection, path, args) { + var index = -1, + isFunc = typeof path == 'function', + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value) { + result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); + }); + return result; + }); + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the last element responsible for generating the key. The + * iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * var array = [ + * { 'dir': 'left', 'code': 97 }, + * { 'dir': 'right', 'code': 100 } + * ]; + * + * _.keyBy(array, function(o) { + * return String.fromCharCode(o.code); + * }); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + * + * _.keyBy(array, 'dir'); + * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + */ + var keyBy = createAggregator(function(result, value, key) { + baseAssignValue(result, key, value); + }); + + /** + * Creates an array of values by running each element in `collection` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. + * + * The guarded methods are: + * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, + * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, + * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, + * `template`, `trim`, `trimEnd`, `trimStart`, and `words` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + * @example + * + * function square(n) { + * return n * n; + * } + * + * _.map([4, 8], square); + * // => [16, 64] + * + * _.map({ 'a': 4, 'b': 8 }, square); + * // => [16, 64] (iteration order is not guaranteed) + * + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; + * + * // The `_.property` iteratee shorthand. + * _.map(users, 'user'); + * // => ['barney', 'fred'] + */ + function map(collection, iteratee) { + var func = isArray(collection) ? arrayMap : baseMap; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.sortBy` except that it allows specifying the sort + * orders of the iteratees to sort by. If `orders` is unspecified, all values + * are sorted in ascending order. Otherwise, specify an order of "desc" for + * descending or "asc" for ascending sort order of corresponding values. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] + * The iteratees to sort by. + * @param {string[]} [orders] The sort orders of `iteratees`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 34 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'barney', 'age': 36 } + * ]; + * + * // Sort by `user` in ascending order and by `age` in descending order. + * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] + */ + function orderBy(collection, iteratees, orders, guard) { + if (collection == null) { + return []; + } + if (!isArray(iteratees)) { + iteratees = iteratees == null ? [] : [iteratees]; + } + orders = guard ? undefined : orders; + if (!isArray(orders)) { + orders = orders == null ? [] : [orders]; + } + return baseOrderBy(collection, iteratees, orders); + } + + /** + * Creates an array of elements split into two groups, the first of which + * contains elements `predicate` returns truthy for, the second of which + * contains elements `predicate` returns falsey for. The predicate is + * invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the array of grouped elements. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true }, + * { 'user': 'pebbles', 'age': 1, 'active': false } + * ]; + * + * _.partition(users, function(o) { return o.active; }); + * // => objects for [['fred'], ['barney', 'pebbles']] + * + * // The `_.matches` iteratee shorthand. + * _.partition(users, { 'age': 1, 'active': false }); + * // => objects for [['pebbles'], ['barney', 'fred']] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.partition(users, ['active', false]); + * // => objects for [['barney', 'pebbles'], ['fred']] + * + * // The `_.property` iteratee shorthand. + * _.partition(users, 'active'); + * // => objects for [['fred'], ['barney', 'pebbles']] + */ + var partition = createAggregator(function(result, value, key) { + result[key ? 0 : 1].push(value); + }, function() { return [[], []]; }); + + /** + * Reduces `collection` to a value which is the accumulated result of running + * each element in `collection` thru `iteratee`, where each successive + * invocation is supplied the return value of the previous. If `accumulator` + * is not given, the first element of `collection` is used as the initial + * value. The iteratee is invoked with four arguments: + * (accumulator, value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.reduce`, `_.reduceRight`, and `_.transform`. + * + * The guarded methods are: + * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, + * and `sortBy` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduceRight + * @example + * + * _.reduce([1, 2], function(sum, n) { + * return sum + n; + * }, 0); + * // => 3 + * + * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * return result; + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) + */ + function reduce(collection, iteratee, accumulator) { + var func = isArray(collection) ? arrayReduce : baseReduce, + initAccum = arguments.length < 3; + + return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); + } + + /** + * This method is like `_.reduce` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduce + * @example + * + * var array = [[0, 1], [2, 3], [4, 5]]; + * + * _.reduceRight(array, function(flattened, other) { + * return flattened.concat(other); + * }, []); + * // => [4, 5, 2, 3, 0, 1] + */ + function reduceRight(collection, iteratee, accumulator) { + var func = isArray(collection) ? arrayReduceRight : baseReduce, + initAccum = arguments.length < 3; + + return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); + } + + /** + * The opposite of `_.filter`; this method returns the elements of `collection` + * that `predicate` does **not** return truthy for. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.filter + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true } + * ]; + * + * _.reject(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.reject(users, { 'age': 40, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.reject(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.reject(users, 'active'); + * // => objects for ['barney'] + */ + function reject(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, negate(getIteratee(predicate, 3))); + } + + /** + * Gets a random element from `collection`. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. + * @example + * + * _.sample([1, 2, 3, 4]); + * // => 2 + */ + function sample(collection) { + var func = isArray(collection) ? arraySample : baseSample; + return func(collection); + } + + /** + * Gets `n` random elements at unique keys from `collection` up to the + * size of `collection`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to sample. + * @param {number} [n=1] The number of elements to sample. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the random elements. + * @example + * + * _.sampleSize([1, 2, 3], 2); + * // => [3, 1] + * + * _.sampleSize([1, 2, 3], 4); + * // => [2, 3, 1] + */ + function sampleSize(collection, n, guard) { + if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { + n = 1; + } else { + n = toInteger(n); + } + var func = isArray(collection) ? arraySampleSize : baseSampleSize; + return func(collection, n); + } + + /** + * Creates an array of shuffled values, using a version of the + * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. + * @example + * + * _.shuffle([1, 2, 3, 4]); + * // => [4, 1, 3, 2] + */ + function shuffle(collection) { + var func = isArray(collection) ? arrayShuffle : baseShuffle; + return func(collection); + } + + /** + * Gets the size of `collection` by returning its length for array-like + * values or the number of own enumerable string keyed properties for objects. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @returns {number} Returns the collection size. + * @example + * + * _.size([1, 2, 3]); + * // => 3 + * + * _.size({ 'a': 1, 'b': 2 }); + * // => 2 + * + * _.size('pebbles'); + * // => 7 + */ + function size(collection) { + if (collection == null) { + return 0; + } + if (isArrayLike(collection)) { + return isString(collection) ? stringSize(collection) : collection.length; + } + var tag = getTag(collection); + if (tag == mapTag || tag == setTag) { + return collection.size; + } + return baseKeys(collection).length; + } + + /** + * Checks if `predicate` returns truthy for **any** element of `collection`. + * Iteration is stopped once `predicate` returns truthy. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + * @example + * + * _.some([null, 0, 'yes', false], Boolean); + * // => true + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.some(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.some(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.some(users, 'active'); + * // => true + */ + function some(collection, predicate, guard) { + var func = isArray(collection) ? arraySome : baseSome; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, getIteratee(predicate, 3)); + } + + /** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection thru each iteratee. This method + * performs a stable sort, that is, it preserves the original sort order of + * equal elements. The iteratees are invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {...(Function|Function[])} [iteratees=[_.identity]] + * The iteratees to sort by. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'barney', 'age': 34 } + * ]; + * + * _.sortBy(users, [function(o) { return o.user; }]); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] + * + * _.sortBy(users, ['user', 'age']); + * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] + */ + var sortBy = baseRest(function(collection, iteratees) { + if (collection == null) { + return []; + } + var length = iteratees.length; + if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { + iteratees = []; + } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { + iteratees = [iteratees[0]]; + } + return baseOrderBy(collection, baseFlatten(iteratees, 1), []); + }); + + /*------------------------------------------------------------------------*/ + + /** + * Gets the timestamp of the number of milliseconds that have elapsed since + * the Unix epoch (1 January 1970 00:00:00 UTC). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Date + * @returns {number} Returns the timestamp. + * @example + * + * _.defer(function(stamp) { + * console.log(_.now() - stamp); + * }, _.now()); + * // => Logs the number of milliseconds it took for the deferred invocation. + */ + var now = ctxNow || function() { + return root.Date.now(); + }; + + /*------------------------------------------------------------------------*/ + + /** + * The opposite of `_.before`; this method creates a function that invokes + * `func` once it's called `n` or more times. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {number} n The number of calls before `func` is invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var saves = ['profile', 'settings']; + * + * var done = _.after(saves.length, function() { + * console.log('done saving!'); + * }); + * + * _.forEach(saves, function(type) { + * asyncSave({ 'type': type, 'complete': done }); + * }); + * // => Logs 'done saving!' after the two async saves have completed. + */ + function after(n, func) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n < 1) { + return func.apply(this, arguments); + } + }; + } + + /** + * Creates a function that invokes `func`, with up to `n` arguments, + * ignoring any additional arguments. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to cap arguments for. + * @param {number} [n=func.length] The arity cap. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new capped function. + * @example + * + * _.map(['6', '8', '10'], _.ary(parseInt, 1)); + * // => [6, 8, 10] + */ + function ary(func, n, guard) { + n = guard ? undefined : n; + n = (func && n == null) ? func.length : n; + return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); + } + + /** + * Creates a function that invokes `func`, with the `this` binding and arguments + * of the created function, while it's called less than `n` times. Subsequent + * calls to the created function return the result of the last `func` invocation. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {number} n The number of calls at which `func` is no longer invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * jQuery(element).on('click', _.before(5, addContactToList)); + * // => Allows adding up to 4 contacts to the list. + */ + function before(n, func) { + var result; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n > 0) { + result = func.apply(this, arguments); + } + if (n <= 1) { + func = undefined; + } + return result; + }; + } + + /** + * Creates a function that invokes `func` with the `this` binding of `thisArg` + * and `partials` prepended to the arguments it receives. + * + * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for partially applied arguments. + * + * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" + * property of bound functions. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to bind. + * @param {*} thisArg The `this` binding of `func`. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * function greet(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * + * var object = { 'user': 'fred' }; + * + * var bound = _.bind(greet, object, 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * // Bound with placeholders. + * var bound = _.bind(greet, object, _, '!'); + * bound('hi'); + * // => 'hi fred!' + */ + var bind = baseRest(function(func, thisArg, partials) { + var bitmask = WRAP_BIND_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bind)); + bitmask |= WRAP_PARTIAL_FLAG; + } + return createWrap(func, bitmask, thisArg, partials, holders); + }); + + /** + * Creates a function that invokes the method at `object[key]` with `partials` + * prepended to the arguments it receives. + * + * This method differs from `_.bind` by allowing bound functions to reference + * methods that may be redefined or don't yet exist. See + * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) + * for more details. + * + * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Function + * @param {Object} object The object to invoke the method on. + * @param {string} key The key of the method. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var object = { + * 'user': 'fred', + * 'greet': function(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * }; + * + * var bound = _.bindKey(object, 'greet', 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * object.greet = function(greeting, punctuation) { + * return greeting + 'ya ' + this.user + punctuation; + * }; + * + * bound('!'); + * // => 'hiya fred!' + * + * // Bound with placeholders. + * var bound = _.bindKey(object, 'greet', _, '!'); + * bound('hi'); + * // => 'hiya fred!' + */ + var bindKey = baseRest(function(object, key, partials) { + var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bindKey)); + bitmask |= WRAP_PARTIAL_FLAG; + } + return createWrap(key, bitmask, object, partials, holders); + }); + + /** + * Creates a function that accepts arguments of `func` and either invokes + * `func` returning its result, if at least `arity` number of arguments have + * been provided, or returns a function that accepts the remaining `func` + * arguments, and so on. The arity of `func` may be specified if `func.length` + * is not sufficient. + * + * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curry(abc); + * + * curried(1)(2)(3); + * // => [1, 2, 3] + * + * curried(1, 2)(3); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(1)(_, 3)(2); + * // => [1, 2, 3] + */ + function curry(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curry.placeholder; + return result; + } + + /** + * This method is like `_.curry` except that arguments are applied to `func` + * in the manner of `_.partialRight` instead of `_.partial`. + * + * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curryRight(abc); + * + * curried(3)(2)(1); + * // => [1, 2, 3] + * + * curried(2, 3)(1); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(3)(1, _)(2); + * // => [1, 2, 3] + */ + function curryRight(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curryRight.placeholder; + return result; + } + + /** + * Creates a debounced function that delays invoking `func` until after `wait` + * milliseconds have elapsed since the last time the debounced function was + * invoked. The debounced function comes with a `cancel` method to cancel + * delayed `func` invocations and a `flush` method to immediately invoke them. + * Provide `options` to indicate whether `func` should be invoked on the + * leading and/or trailing edge of the `wait` timeout. The `func` is invoked + * with the last arguments provided to the debounced function. Subsequent + * calls to the debounced function return the result of the last `func` + * invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the debounced function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.debounce` and `_.throttle`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to debounce. + * @param {number} [wait=0] The number of milliseconds to delay. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=false] + * Specify invoking on the leading edge of the timeout. + * @param {number} [options.maxWait] + * The maximum time `func` is allowed to be delayed before it's invoked. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * // Avoid costly calculations while the window size is in flux. + * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); + * + * // Invoke `sendMail` when clicked, debouncing subsequent calls. + * jQuery(element).on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * })); + * + * // Ensure `batchLog` is invoked once after 1 second of debounced calls. + * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); + * var source = new EventSource('/stream'); + * jQuery(source).on('message', debounced); + * + * // Cancel the trailing debounced invocation. + * jQuery(window).on('popstate', debounced.cancel); + */ + function debounce(func, wait, options) { + var lastArgs, + lastThis, + maxWait, + result, + timerId, + lastCallTime, + lastInvokeTime = 0, + leading = false, + maxing = false, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + wait = toNumber(wait) || 0; + if (isObject(options)) { + leading = !!options.leading; + maxing = 'maxWait' in options; + maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + + function invokeFunc(time) { + var args = lastArgs, + thisArg = lastThis; + + lastArgs = lastThis = undefined; + lastInvokeTime = time; + result = func.apply(thisArg, args); + return result; + } + + function leadingEdge(time) { + // Reset any `maxWait` timer. + lastInvokeTime = time; + // Start the timer for the trailing edge. + timerId = setTimeout(timerExpired, wait); + // Invoke the leading edge. + return leading ? invokeFunc(time) : result; + } + + function remainingWait(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime, + result = wait - timeSinceLastCall; + + return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result; + } + + function shouldInvoke(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime; + + // Either this is the first call, activity has stopped and we're at the + // trailing edge, the system time has gone backwards and we're treating + // it as the trailing edge, or we've hit the `maxWait` limit. + return (lastCallTime === undefined || (timeSinceLastCall >= wait) || + (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); + } + + function timerExpired() { + var time = now(); + if (shouldInvoke(time)) { + return trailingEdge(time); + } + // Restart the timer. + timerId = setTimeout(timerExpired, remainingWait(time)); + } + + function trailingEdge(time) { + timerId = undefined; + + // Only invoke if we have `lastArgs` which means `func` has been + // debounced at least once. + if (trailing && lastArgs) { + return invokeFunc(time); + } + lastArgs = lastThis = undefined; + return result; + } + + function cancel() { + if (timerId !== undefined) { + clearTimeout(timerId); + } + lastInvokeTime = 0; + lastArgs = lastCallTime = lastThis = timerId = undefined; + } + + function flush() { + return timerId === undefined ? result : trailingEdge(now()); + } + + function debounced() { + var time = now(), + isInvoking = shouldInvoke(time); + + lastArgs = arguments; + lastThis = this; + lastCallTime = time; + + if (isInvoking) { + if (timerId === undefined) { + return leadingEdge(lastCallTime); + } + if (maxing) { + // Handle invocations in a tight loop. + timerId = setTimeout(timerExpired, wait); + return invokeFunc(lastCallTime); + } + } + if (timerId === undefined) { + timerId = setTimeout(timerExpired, wait); + } + return result; + } + debounced.cancel = cancel; + debounced.flush = flush; + return debounced; + } + + /** + * Defers invoking the `func` until the current call stack has cleared. Any + * additional arguments are provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to defer. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.defer(function(text) { + * console.log(text); + * }, 'deferred'); + * // => Logs 'deferred' after one millisecond. + */ + var defer = baseRest(function(func, args) { + return baseDelay(func, 1, args); + }); + + /** + * Invokes `func` after `wait` milliseconds. Any additional arguments are + * provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.delay(function(text) { + * console.log(text); + * }, 1000, 'later'); + * // => Logs 'later' after one second. + */ + var delay = baseRest(function(func, wait, args) { + return baseDelay(func, toNumber(wait) || 0, args); + }); + + /** + * Creates a function that invokes `func` with arguments reversed. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to flip arguments for. + * @returns {Function} Returns the new flipped function. + * @example + * + * var flipped = _.flip(function() { + * return _.toArray(arguments); + * }); + * + * flipped('a', 'b', 'c', 'd'); + * // => ['d', 'c', 'b', 'a'] + */ + function flip(func) { + return createWrap(func, WRAP_FLIP_FLAG); + } + + /** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided, it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is used as the map cache key. The `func` + * is invoked with the `this` binding of the memoized function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the + * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) + * method interface of `clear`, `delete`, `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoized function. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * var other = { 'c': 3, 'd': 4 }; + * + * var values = _.memoize(_.values); + * values(object); + * // => [1, 2] + * + * values(other); + * // => [3, 4] + * + * object.a = 2; + * values(object); + * // => [1, 2] + * + * // Modify the result cache. + * values.cache.set(object, ['a', 'b']); + * values(object); + * // => ['a', 'b'] + * + * // Replace `_.memoize.Cache`. + * _.memoize.Cache = WeakMap; + */ + function memoize(func, resolver) { + if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, + key = resolver ? resolver.apply(this, args) : args[0], + cache = memoized.cache; + + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + memoized.cache = cache.set(key, result) || cache; + return result; + }; + memoized.cache = new (memoize.Cache || MapCache); + return memoized; + } + + // Expose `MapCache`. + memoize.Cache = MapCache; + + /** + * Creates a function that negates the result of the predicate `func`. The + * `func` predicate is invoked with the `this` binding and arguments of the + * created function. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} predicate The predicate to negate. + * @returns {Function} Returns the new negated function. + * @example + * + * function isEven(n) { + * return n % 2 == 0; + * } + * + * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); + * // => [1, 3, 5] + */ + function negate(predicate) { + if (typeof predicate != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return function() { + var args = arguments; + switch (args.length) { + case 0: return !predicate.call(this); + case 1: return !predicate.call(this, args[0]); + case 2: return !predicate.call(this, args[0], args[1]); + case 3: return !predicate.call(this, args[0], args[1], args[2]); + } + return !predicate.apply(this, args); + }; + } + + /** + * Creates a function that is restricted to invoking `func` once. Repeat calls + * to the function return the value of the first invocation. The `func` is + * invoked with the `this` binding and arguments of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // => `createApplication` is invoked once + */ + function once(func) { + return before(2, func); + } + + /** + * Creates a function that invokes `func` with its arguments transformed. + * + * @static + * @since 4.0.0 + * @memberOf _ + * @category Function + * @param {Function} func The function to wrap. + * @param {...(Function|Function[])} [transforms=[_.identity]] + * The argument transforms. + * @returns {Function} Returns the new function. + * @example + * + * function doubled(n) { + * return n * 2; + * } + * + * function square(n) { + * return n * n; + * } + * + * var func = _.overArgs(function(x, y) { + * return [x, y]; + * }, [square, doubled]); + * + * func(9, 3); + * // => [81, 6] + * + * func(10, 5); + * // => [100, 10] + */ + var overArgs = castRest(function(func, transforms) { + transforms = (transforms.length == 1 && isArray(transforms[0])) + ? arrayMap(transforms[0], baseUnary(getIteratee())) + : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); + + var funcsLength = transforms.length; + return baseRest(function(args) { + var index = -1, + length = nativeMin(args.length, funcsLength); + + while (++index < length) { + args[index] = transforms[index].call(this, args[index]); + } + return apply(func, this, args); + }); + }); + + /** + * Creates a function that invokes `func` with `partials` prepended to the + * arguments it receives. This method is like `_.bind` except it does **not** + * alter the `this` binding. + * + * The `_.partial.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method doesn't set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @since 0.2.0 + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * function greet(greeting, name) { + * return greeting + ' ' + name; + * } + * + * var sayHelloTo = _.partial(greet, 'hello'); + * sayHelloTo('fred'); + * // => 'hello fred' + * + * // Partially applied with placeholders. + * var greetFred = _.partial(greet, _, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + */ + var partial = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partial)); + return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); + }); + + /** + * This method is like `_.partial` except that partially applied arguments + * are appended to the arguments it receives. + * + * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method doesn't set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * function greet(greeting, name) { + * return greeting + ' ' + name; + * } + * + * var greetFred = _.partialRight(greet, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + * + * // Partially applied with placeholders. + * var sayHelloTo = _.partialRight(greet, 'hello', _); + * sayHelloTo('fred'); + * // => 'hello fred' + */ + var partialRight = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partialRight)); + return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); + }); + + /** + * Creates a function that invokes `func` with arguments arranged according + * to the specified `indexes` where the argument value at the first index is + * provided as the first argument, the argument value at the second index is + * provided as the second argument, and so on. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to rearrange arguments for. + * @param {...(number|number[])} indexes The arranged argument indexes. + * @returns {Function} Returns the new function. + * @example + * + * var rearged = _.rearg(function(a, b, c) { + * return [a, b, c]; + * }, [2, 0, 1]); + * + * rearged('b', 'c', 'a') + * // => ['a', 'b', 'c'] + */ + var rearg = flatRest(function(func, indexes) { + return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); + }); + + /** + * Creates a function that invokes `func` with the `this` binding of the + * created function and arguments from `start` and beyond provided as + * an array. + * + * **Note:** This method is based on the + * [rest parameter](https://mdn.io/rest_parameters). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.rest(function(what, names) { + * return what + ' ' + _.initial(names).join(', ') + + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); + * }); + * + * say('hello', 'fred', 'barney', 'pebbles'); + * // => 'hello fred, barney, & pebbles' + */ + function rest(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = start === undefined ? start : toInteger(start); + return baseRest(func, start); + } + + /** + * Creates a function that invokes `func` with the `this` binding of the + * create function and an array of arguments much like + * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). + * + * **Note:** This method is based on the + * [spread operator](https://mdn.io/spread_operator). + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Function + * @param {Function} func The function to spread arguments over. + * @param {number} [start=0] The start position of the spread. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.spread(function(who, what) { + * return who + ' says ' + what; + * }); + * + * say(['fred', 'hello']); + * // => 'fred says hello' + * + * var numbers = Promise.all([ + * Promise.resolve(40), + * Promise.resolve(36) + * ]); + * + * numbers.then(_.spread(function(x, y) { + * return x + y; + * })); + * // => a Promise of 76 + */ + function spread(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = start == null ? 0 : nativeMax(toInteger(start), 0); + return baseRest(function(args) { + var array = args[start], + otherArgs = castSlice(args, 0, start); + + if (array) { + arrayPush(otherArgs, array); + } + return apply(func, this, otherArgs); + }); + } + + /** + * Creates a throttled function that only invokes `func` at most once per + * every `wait` milliseconds. The throttled function comes with a `cancel` + * method to cancel delayed `func` invocations and a `flush` method to + * immediately invoke them. Provide `options` to indicate whether `func` + * should be invoked on the leading and/or trailing edge of the `wait` + * timeout. The `func` is invoked with the last arguments provided to the + * throttled function. Subsequent calls to the throttled function return the + * result of the last `func` invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the throttled function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.throttle` and `_.debounce`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to throttle. + * @param {number} [wait=0] The number of milliseconds to throttle invocations to. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=true] + * Specify invoking on the leading edge of the timeout. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new throttled function. + * @example + * + * // Avoid excessively updating the position while scrolling. + * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); + * + * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. + * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); + * jQuery(element).on('click', throttled); + * + * // Cancel the trailing throttled invocation. + * jQuery(window).on('popstate', throttled.cancel); + */ + function throttle(func, wait, options) { + var leading = true, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (isObject(options)) { + leading = 'leading' in options ? !!options.leading : leading; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + return debounce(func, wait, { + 'leading': leading, + 'maxWait': wait, + 'trailing': trailing + }); + } + + /** + * Creates a function that accepts up to one argument, ignoring any + * additional arguments. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + * @example + * + * _.map(['6', '8', '10'], _.unary(parseInt)); + * // => [6, 8, 10] + */ + function unary(func) { + return ary(func, 1); + } + + /** + * Creates a function that provides `value` to `wrapper` as its first + * argument. Any additional arguments provided to the function are appended + * to those provided to the `wrapper`. The wrapper is invoked with the `this` + * binding of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {*} value The value to wrap. + * @param {Function} [wrapper=identity] The wrapper function. + * @returns {Function} Returns the new function. + * @example + * + * var p = _.wrap(_.escape, function(func, text) { + * return '

' + func(text) + '

'; + * }); + * + * p('fred, barney, & pebbles'); + * // => '

fred, barney, & pebbles

' + */ + function wrap(value, wrapper) { + return partial(castFunction(wrapper), value); + } + + /*------------------------------------------------------------------------*/ + + /** + * Casts `value` as an array if it's not one. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Lang + * @param {*} value The value to inspect. + * @returns {Array} Returns the cast array. + * @example + * + * _.castArray(1); + * // => [1] + * + * _.castArray({ 'a': 1 }); + * // => [{ 'a': 1 }] + * + * _.castArray('abc'); + * // => ['abc'] + * + * _.castArray(null); + * // => [null] + * + * _.castArray(undefined); + * // => [undefined] + * + * _.castArray(); + * // => [] + * + * var array = [1, 2, 3]; + * console.log(_.castArray(array) === array); + * // => true + */ + function castArray() { + if (!arguments.length) { + return []; + } + var value = arguments[0]; + return isArray(value) ? value : [value]; + } + + /** + * Creates a shallow clone of `value`. + * + * **Note:** This method is loosely based on the + * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) + * and supports cloning arrays, array buffers, booleans, date objects, maps, + * numbers, `Object` objects, regexes, sets, strings, symbols, and typed + * arrays. The own enumerable properties of `arguments` objects are cloned + * as plain objects. An empty object is returned for uncloneable values such + * as error objects, functions, DOM nodes, and WeakMaps. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to clone. + * @returns {*} Returns the cloned value. + * @see _.cloneDeep + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var shallow = _.clone(objects); + * console.log(shallow[0] === objects[0]); + * // => true + */ + function clone(value) { + return baseClone(value, CLONE_SYMBOLS_FLAG); + } + + /** + * This method is like `_.clone` except that it accepts `customizer` which + * is invoked to produce the cloned value. If `customizer` returns `undefined`, + * cloning is handled by the method instead. The `customizer` is invoked with + * up to four arguments; (value [, index|key, object, stack]). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the cloned value. + * @see _.cloneDeepWith + * @example + * + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(false); + * } + * } + * + * var el = _.cloneWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 0 + */ + function cloneWith(value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); + } + + /** + * This method is like `_.clone` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @returns {*} Returns the deep cloned value. + * @see _.clone + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var deep = _.cloneDeep(objects); + * console.log(deep[0] === objects[0]); + * // => false + */ + function cloneDeep(value) { + return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); + } + + /** + * This method is like `_.cloneWith` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the deep cloned value. + * @see _.cloneWith + * @example + * + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(true); + * } + * } + * + * var el = _.cloneDeepWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 20 + */ + function cloneDeepWith(value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); + } + + /** + * Checks if `object` conforms to `source` by invoking the predicate + * properties of `source` with the corresponding property values of `object`. + * + * **Note:** This method is equivalent to `_.conforms` when `source` is + * partially applied. + * + * @static + * @memberOf _ + * @since 4.14.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * + * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); + * // => true + * + * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); + * // => false + */ + function conformsTo(object, source) { + return source == null || baseConformsTo(object, source, keys(source)); + } + + /** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ + function eq(value, other) { + return value === other || (value !== value && other !== other); + } + + /** + * Checks if `value` is greater than `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + * @see _.lt + * @example + * + * _.gt(3, 1); + * // => true + * + * _.gt(3, 3); + * // => false + * + * _.gt(1, 3); + * // => false + */ + var gt = createRelationalOperation(baseGt); + + /** + * Checks if `value` is greater than or equal to `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than or equal to + * `other`, else `false`. + * @see _.lte + * @example + * + * _.gte(3, 1); + * // => true + * + * _.gte(3, 3); + * // => true + * + * _.gte(1, 3); + * // => false + */ + var gte = createRelationalOperation(function(value, other) { + return value >= other; + }); + + /** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); + }; + + /** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ + var isArray = Array.isArray; + + /** + * Checks if `value` is classified as an `ArrayBuffer` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + * @example + * + * _.isArrayBuffer(new ArrayBuffer(2)); + * // => true + * + * _.isArrayBuffer(new Array(2)); + * // => false + */ + var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; + + /** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); + } + + /** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ + function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); + } + + /** + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false + */ + function isBoolean(value) { + return value === true || value === false || + (isObjectLike(value) && baseGetTag(value) == boolTag); + } + + /** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ + var isBuffer = nativeIsBuffer || stubFalse; + + /** + * Checks if `value` is classified as a `Date` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + * @example + * + * _.isDate(new Date); + * // => true + * + * _.isDate('Mon April 23 2012'); + * // => false + */ + var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; + + /** + * Checks if `value` is likely a DOM element. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. + * @example + * + * _.isElement(document.body); + * // => true + * + * _.isElement(''); + * // => false + */ + function isElement(value) { + return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); + } + + /** + * Checks if `value` is an empty object, collection, map, or set. + * + * Objects are considered empty if they have no own enumerable string keyed + * properties. + * + * Array-like values such as `arguments` objects, arrays, buffers, strings, or + * jQuery-like collections are considered empty if they have a `length` of `0`. + * Similarly, maps and sets are considered empty if they have a `size` of `0`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is empty, else `false`. + * @example + * + * _.isEmpty(null); + * // => true + * + * _.isEmpty(true); + * // => true + * + * _.isEmpty(1); + * // => true + * + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({ 'a': 1 }); + * // => false + */ + function isEmpty(value) { + if (value == null) { + return true; + } + if (isArrayLike(value) && + (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || + isBuffer(value) || isTypedArray(value) || isArguments(value))) { + return !value.length; + } + var tag = getTag(value); + if (tag == mapTag || tag == setTag) { + return !value.size; + } + if (isPrototype(value)) { + return !baseKeys(value).length; + } + for (var key in value) { + if (hasOwnProperty.call(value, key)) { + return false; + } + } + return true; + } + + /** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are compared by strict equality, i.e. `===`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ + function isEqual(value, other) { + return baseIsEqual(value, other); + } + + /** + * This method is like `_.isEqual` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with up to + * six arguments: (objValue, othValue [, index|key, object, other, stack]). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, othValue) { + * if (isGreeting(objValue) && isGreeting(othValue)) { + * return true; + * } + * } + * + * var array = ['hello', 'goodbye']; + * var other = ['hi', 'goodbye']; + * + * _.isEqualWith(array, other, customizer); + * // => true + */ + function isEqualWith(value, other, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + var result = customizer ? customizer(value, other) : undefined; + return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; + } + + /** + * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, + * `SyntaxError`, `TypeError`, or `URIError` object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an error object, else `false`. + * @example + * + * _.isError(new Error); + * // => true + * + * _.isError(Error); + * // => false + */ + function isError(value) { + if (!isObjectLike(value)) { + return false; + } + var tag = baseGetTag(value); + return tag == errorTag || tag == domExcTag || + (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); + } + + /** + * Checks if `value` is a finite primitive number. + * + * **Note:** This method is based on + * [`Number.isFinite`](https://mdn.io/Number/isFinite). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. + * @example + * + * _.isFinite(3); + * // => true + * + * _.isFinite(Number.MIN_VALUE); + * // => true + * + * _.isFinite(Infinity); + * // => false + * + * _.isFinite('3'); + * // => false + */ + function isFinite(value) { + return typeof value == 'number' && nativeIsFinite(value); + } + + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; + } + + /** + * Checks if `value` is an integer. + * + * **Note:** This method is based on + * [`Number.isInteger`](https://mdn.io/Number/isInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an integer, else `false`. + * @example + * + * _.isInteger(3); + * // => true + * + * _.isInteger(Number.MIN_VALUE); + * // => false + * + * _.isInteger(Infinity); + * // => false + * + * _.isInteger('3'); + * // => false + */ + function isInteger(value) { + return typeof value == 'number' && value == toInteger(value); + } + + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); + } + + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike(value) { + return value != null && typeof value == 'object'; + } + + /** + * Checks if `value` is classified as a `Map` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + * @example + * + * _.isMap(new Map); + * // => true + * + * _.isMap(new WeakMap); + * // => false + */ + var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; + + /** + * Performs a partial deep comparison between `object` and `source` to + * determine if `object` contains equivalent property values. + * + * **Note:** This method is equivalent to `_.matches` when `source` is + * partially applied. + * + * Partial comparisons will match empty array and empty object `source` + * values against any array or object value, respectively. See `_.isEqual` + * for a list of supported value comparisons. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * + * _.isMatch(object, { 'b': 2 }); + * // => true + * + * _.isMatch(object, { 'b': 1 }); + * // => false + */ + function isMatch(object, source) { + return object === source || baseIsMatch(object, source, getMatchData(source)); + } + + /** + * This method is like `_.isMatch` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with five + * arguments: (objValue, srcValue, index|key, object, source). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, srcValue) { + * if (isGreeting(objValue) && isGreeting(srcValue)) { + * return true; + * } + * } + * + * var object = { 'greeting': 'hello' }; + * var source = { 'greeting': 'hi' }; + * + * _.isMatchWith(object, source, customizer); + * // => true + */ + function isMatchWith(object, source, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseIsMatch(object, source, getMatchData(source), customizer); + } + + /** + * Checks if `value` is `NaN`. + * + * **Note:** This method is based on + * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as + * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for + * `undefined` and other non-number values. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ + function isNaN(value) { + // An `NaN` primitive is the only value that is not equal to itself. + // Perform the `toStringTag` check first to avoid errors with some + // ActiveX objects in IE. + return isNumber(value) && value != +value; + } + + /** + * Checks if `value` is a pristine native function. + * + * **Note:** This method can't reliably detect native functions in the presence + * of the core-js package because core-js circumvents this kind of detection. + * Despite multiple requests, the core-js maintainer has made it clear: any + * attempt to fix the detection will be obstructed. As a result, we're left + * with little choice but to throw an error. Unfortunately, this also affects + * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), + * which rely on core-js. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + * @example + * + * _.isNative(Array.prototype.push); + * // => true + * + * _.isNative(_); + * // => false + */ + function isNative(value) { + if (isMaskable(value)) { + throw new Error(CORE_ERROR_TEXT); + } + return baseIsNative(value); + } + + /** + * Checks if `value` is `null`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `null`, else `false`. + * @example + * + * _.isNull(null); + * // => true + * + * _.isNull(void 0); + * // => false + */ + function isNull(value) { + return value === null; + } + + /** + * Checks if `value` is `null` or `undefined`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is nullish, else `false`. + * @example + * + * _.isNil(null); + * // => true + * + * _.isNil(void 0); + * // => true + * + * _.isNil(NaN); + * // => false + */ + function isNil(value) { + return value == null; + } + + /** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are + * classified as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a number, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ + function isNumber(value) { + return typeof value == 'number' || + (isObjectLike(value) && baseGetTag(value) == numberTag); + } + + /** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ + function isPlainObject(value) { + if (!isObjectLike(value) || baseGetTag(value) != objectTag) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; + return typeof Ctor == 'function' && Ctor instanceof Ctor && + funcToString.call(Ctor) == objectCtorString; + } + + /** + * Checks if `value` is classified as a `RegExp` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + * @example + * + * _.isRegExp(/abc/); + * // => true + * + * _.isRegExp('/abc/'); + * // => false + */ + var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; + + /** + * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 + * double precision number which isn't the result of a rounded unsafe integer. + * + * **Note:** This method is based on + * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. + * @example + * + * _.isSafeInteger(3); + * // => true + * + * _.isSafeInteger(Number.MIN_VALUE); + * // => false + * + * _.isSafeInteger(Infinity); + * // => false + * + * _.isSafeInteger('3'); + * // => false + */ + function isSafeInteger(value) { + return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is classified as a `Set` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + * @example + * + * _.isSet(new Set); + * // => true + * + * _.isSet(new WeakSet); + * // => false + */ + var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; + + /** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a string, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ + function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); + } + + /** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ + function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && baseGetTag(value) == symbolTag); + } + + /** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ + var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + + /** + * Checks if `value` is `undefined`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. + * @example + * + * _.isUndefined(void 0); + * // => true + * + * _.isUndefined(null); + * // => false + */ + function isUndefined(value) { + return value === undefined; + } + + /** + * Checks if `value` is classified as a `WeakMap` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. + * @example + * + * _.isWeakMap(new WeakMap); + * // => true + * + * _.isWeakMap(new Map); + * // => false + */ + function isWeakMap(value) { + return isObjectLike(value) && getTag(value) == weakMapTag; + } + + /** + * Checks if `value` is classified as a `WeakSet` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. + * @example + * + * _.isWeakSet(new WeakSet); + * // => true + * + * _.isWeakSet(new Set); + * // => false + */ + function isWeakSet(value) { + return isObjectLike(value) && baseGetTag(value) == weakSetTag; + } + + /** + * Checks if `value` is less than `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + * @see _.gt + * @example + * + * _.lt(1, 3); + * // => true + * + * _.lt(3, 3); + * // => false + * + * _.lt(3, 1); + * // => false + */ + var lt = createRelationalOperation(baseLt); + + /** + * Checks if `value` is less than or equal to `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than or equal to + * `other`, else `false`. + * @see _.gte + * @example + * + * _.lte(1, 3); + * // => true + * + * _.lte(3, 3); + * // => true + * + * _.lte(3, 1); + * // => false + */ + var lte = createRelationalOperation(function(value, other) { + return value <= other; + }); + + /** + * Converts `value` to an array. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to convert. + * @returns {Array} Returns the converted array. + * @example + * + * _.toArray({ 'a': 1, 'b': 2 }); + * // => [1, 2] + * + * _.toArray('abc'); + * // => ['a', 'b', 'c'] + * + * _.toArray(1); + * // => [] + * + * _.toArray(null); + * // => [] + */ + function toArray(value) { + if (!value) { + return []; + } + if (isArrayLike(value)) { + return isString(value) ? stringToArray(value) : copyArray(value); + } + if (symIterator && value[symIterator]) { + return iteratorToArray(value[symIterator]()); + } + var tag = getTag(value), + func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); + + return func(value); + } + + /** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ + function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; + } + + /** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ + function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; + + return result === result ? (remainder ? result - remainder : result) : 0; + } + + /** + * Converts `value` to an integer suitable for use as the length of an + * array-like object. + * + * **Note:** This method is based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toLength(3.2); + * // => 3 + * + * _.toLength(Number.MIN_VALUE); + * // => 0 + * + * _.toLength(Infinity); + * // => 4294967295 + * + * _.toLength('3.2'); + * // => 3 + */ + function toLength(value) { + return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; + } + + /** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ + function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); + } + + /** + * Converts `value` to a plain object flattening inherited enumerable string + * keyed properties of `value` to own properties of the plain object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {Object} Returns the converted plain object. + * @example + * + * function Foo() { + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.assign({ 'a': 1 }, new Foo); + * // => { 'a': 1, 'b': 2 } + * + * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); + * // => { 'a': 1, 'b': 2, 'c': 3 } + */ + function toPlainObject(value) { + return copyObject(value, keysIn(value)); + } + + /** + * Converts `value` to a safe integer. A safe integer can be compared and + * represented correctly. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toSafeInteger(3.2); + * // => 3 + * + * _.toSafeInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toSafeInteger(Infinity); + * // => 9007199254740991 + * + * _.toSafeInteger('3.2'); + * // => 3 + */ + function toSafeInteger(value) { + return value + ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) + : (value === 0 ? value : 0); + } + + /** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ + function toString(value) { + return value == null ? '' : baseToString(value); + } + + /*------------------------------------------------------------------------*/ + + /** + * Assigns own enumerable string keyed properties of source objects to the + * destination object. Source objects are applied from left to right. + * Subsequent sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object` and is loosely based on + * [`Object.assign`](https://mdn.io/Object/assign). + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assignIn + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assign({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'c': 3 } + */ + var assign = createAssigner(function(object, source) { + if (isPrototype(source) || isArrayLike(source)) { + copyObject(source, keys(source), object); + return; + } + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + assignValue(object, key, source[key]); + } + } + }); + + /** + * This method is like `_.assign` except that it iterates over own and + * inherited source properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extend + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assign + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assignIn({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } + */ + var assignIn = createAssigner(function(object, source) { + copyObject(source, keysIn(source), object); + }); + + /** + * This method is like `_.assignIn` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extendWith + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignInWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keysIn(source), object, customizer); + }); + + /** + * This method is like `_.assign` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignInWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var assignWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keys(source), object, customizer); + }); + + /** + * Creates an array of values corresponding to `paths` of `object`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Array} Returns the picked values. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * + * _.at(object, ['a[0].b.c', 'a[1]']); + * // => [3, 4] + */ + var at = flatRest(baseAt); + + /** + * Creates an object that inherits from the `prototype` object. If a + * `properties` object is given, its own enumerable string keyed properties + * are assigned to the created object. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Object + * @param {Object} prototype The object to inherit from. + * @param {Object} [properties] The properties to assign to the object. + * @returns {Object} Returns the new object. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * function Circle() { + * Shape.call(this); + * } + * + * Circle.prototype = _.create(Shape.prototype, { + * 'constructor': Circle + * }); + * + * var circle = new Circle; + * circle instanceof Circle; + * // => true + * + * circle instanceof Shape; + * // => true + */ + function create(prototype, properties) { + var result = baseCreate(prototype); + return properties == null ? result : baseAssign(result, properties); + } + + /** + * Assigns own and inherited enumerable string keyed properties of source + * objects to the destination object for all destination properties that + * resolve to `undefined`. Source objects are applied from left to right. + * Once a property is set, additional values of the same property are ignored. + * + * **Note:** This method mutates `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaultsDeep + * @example + * + * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var defaults = baseRest(function(args) { + args.push(undefined, customDefaultsAssignIn); + return apply(assignInWith, undefined, args); + }); + + /** + * This method is like `_.defaults` except that it recursively assigns + * default properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 3.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaults + * @example + * + * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); + * // => { 'a': { 'b': 2, 'c': 3 } } + */ + var defaultsDeep = baseRest(function(args) { + args.push(undefined, customDefaultsMerge); + return apply(mergeWith, undefined, args); + }); + + /** + * This method is like `_.find` except that it returns the key of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findKey(users, function(o) { return o.age < 40; }); + * // => 'barney' (iteration order is not guaranteed) + * + * // The `_.matches` iteratee shorthand. + * _.findKey(users, { 'age': 1, 'active': true }); + * // => 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findKey(users, 'active'); + * // => 'barney' + */ + function findKey(object, predicate) { + return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); + } + + /** + * This method is like `_.findKey` except that it iterates over elements of + * a collection in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findLastKey(users, function(o) { return o.age < 40; }); + * // => returns 'pebbles' assuming `_.findKey` returns 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.findLastKey(users, { 'age': 36, 'active': true }); + * // => 'barney' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findLastKey(users, 'active'); + * // => 'pebbles' + */ + function findLastKey(object, predicate) { + return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); + } + + /** + * Iterates over own and inherited enumerable string keyed properties of an + * object and invokes `iteratee` for each property. The iteratee is invoked + * with three arguments: (value, key, object). Iteratee functions may exit + * iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forInRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forIn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). + */ + function forIn(object, iteratee) { + return object == null + ? object + : baseFor(object, getIteratee(iteratee, 3), keysIn); + } + + /** + * This method is like `_.forIn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forIn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forInRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. + */ + function forInRight(object, iteratee) { + return object == null + ? object + : baseForRight(object, getIteratee(iteratee, 3), keysIn); + } + + /** + * Iterates over own enumerable string keyed properties of an object and + * invokes `iteratee` for each property. The iteratee is invoked with three + * arguments: (value, key, object). Iteratee functions may exit iteration + * early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwnRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ + function forOwn(object, iteratee) { + return object && baseForOwn(object, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.forOwn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwnRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. + */ + function forOwnRight(object, iteratee) { + return object && baseForOwnRight(object, getIteratee(iteratee, 3)); + } + + /** + * Creates an array of function property names from own enumerable properties + * of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functionsIn + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functions(new Foo); + * // => ['a', 'b'] + */ + function functions(object) { + return object == null ? [] : baseFunctions(object, keys(object)); + } + + /** + * Creates an array of function property names from own and inherited + * enumerable properties of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functions + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functionsIn(new Foo); + * // => ['a', 'b', 'c'] + */ + function functionsIn(object) { + return object == null ? [] : baseFunctions(object, keysIn(object)); + } + + /** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ + function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, path); + return result === undefined ? defaultValue : result; + } + + /** + * Checks if `path` is a direct property of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = { 'a': { 'b': 2 } }; + * var other = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.has(object, 'a'); + * // => true + * + * _.has(object, 'a.b'); + * // => true + * + * _.has(object, ['a', 'b']); + * // => true + * + * _.has(other, 'a'); + * // => false + */ + function has(object, path) { + return object != null && hasPath(object, path, baseHas); + } + + /** + * Checks if `path` is a direct or inherited property of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b'); + * // => true + * + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */ + function hasIn(object, path) { + return object != null && hasPath(object, path, baseHasIn); + } + + /** + * Creates an object composed of the inverted keys and values of `object`. + * If `object` contains duplicate values, subsequent values overwrite + * property assignments of previous values. + * + * @static + * @memberOf _ + * @since 0.7.0 + * @category Object + * @param {Object} object The object to invert. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invert(object); + * // => { '1': 'c', '2': 'b' } + */ + var invert = createInverter(function(result, value, key) { + result[value] = key; + }, constant(identity)); + + /** + * This method is like `_.invert` except that the inverted object is generated + * from the results of running each element of `object` thru `iteratee`. The + * corresponding inverted value of each inverted key is an array of keys + * responsible for generating the inverted value. The iteratee is invoked + * with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.1.0 + * @category Object + * @param {Object} object The object to invert. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invertBy(object); + * // => { '1': ['a', 'c'], '2': ['b'] } + * + * _.invertBy(object, function(value) { + * return 'group' + value; + * }); + * // => { 'group1': ['a', 'c'], 'group2': ['b'] } + */ + var invertBy = createInverter(function(result, value, key) { + if (hasOwnProperty.call(result, value)) { + result[value].push(key); + } else { + result[value] = [key]; + } + }, getIteratee); + + /** + * Invokes the method at `path` of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {...*} [args] The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + * @example + * + * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; + * + * _.invoke(object, 'a[0].b.c.slice', 1, 3); + * // => [2, 3] + */ + var invoke = baseRest(baseInvoke); + + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); + } + + /** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ + function keysIn(object) { + return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); + } + + /** + * The opposite of `_.mapValues`; this method creates an object with the + * same values as `object` and keys generated by running each own enumerable + * string keyed property of `object` thru `iteratee`. The iteratee is invoked + * with three arguments: (value, key, object). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapValues + * @example + * + * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { + * return key + value; + * }); + * // => { 'a1': 1, 'b2': 2 } + */ + function mapKeys(object, iteratee) { + var result = {}; + iteratee = getIteratee(iteratee, 3); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, iteratee(value, key, object), value); + }); + return result; + } + + /** + * Creates an object with the same keys as `object` and values generated + * by running each own enumerable string keyed property of `object` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, key, object). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapKeys + * @example + * + * var users = { + * 'fred': { 'user': 'fred', 'age': 40 }, + * 'pebbles': { 'user': 'pebbles', 'age': 1 } + * }; + * + * _.mapValues(users, function(o) { return o.age; }); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + * + * // The `_.property` iteratee shorthand. + * _.mapValues(users, 'age'); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + */ + function mapValues(object, iteratee) { + var result = {}; + iteratee = getIteratee(iteratee, 3); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, key, iteratee(value, key, object)); + }); + return result; + } + + /** + * This method is like `_.assign` except that it recursively merges own and + * inherited enumerable string keyed properties of source objects into the + * destination object. Source properties that resolve to `undefined` are + * skipped if a destination value exists. Array and plain object properties + * are merged recursively. Other objects and value types are overridden by + * assignment. Source objects are applied from left to right. Subsequent + * sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @example + * + * var object = { + * 'a': [{ 'b': 2 }, { 'd': 4 }] + * }; + * + * var other = { + * 'a': [{ 'c': 3 }, { 'e': 5 }] + * }; + * + * _.merge(object, other); + * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } + */ + var merge = createAssigner(function(object, source, srcIndex) { + baseMerge(object, source, srcIndex); + }); + + /** + * This method is like `_.merge` except that it accepts `customizer` which + * is invoked to produce the merged values of the destination and source + * properties. If `customizer` returns `undefined`, merging is handled by the + * method instead. The `customizer` is invoked with six arguments: + * (objValue, srcValue, key, object, source, stack). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} customizer The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * function customizer(objValue, srcValue) { + * if (_.isArray(objValue)) { + * return objValue.concat(srcValue); + * } + * } + * + * var object = { 'a': [1], 'b': [2] }; + * var other = { 'a': [3], 'b': [4] }; + * + * _.mergeWith(object, other, customizer); + * // => { 'a': [1, 3], 'b': [2, 4] } + */ + var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { + baseMerge(object, source, srcIndex, customizer); + }); + + /** + * The opposite of `_.pick`; this method creates an object composed of the + * own and inherited enumerable property paths of `object` that are not omitted. + * + * **Note:** This method is considerably slower than `_.pick`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [paths] The property paths to omit. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omit(object, ['a', 'c']); + * // => { 'b': '2' } + */ + var omit = flatRest(function(object, paths) { + var result = {}; + if (object == null) { + return result; + } + var isDeep = false; + paths = arrayMap(paths, function(path) { + path = castPath(path, object); + isDeep || (isDeep = path.length > 1); + return path; + }); + copyObject(object, getAllKeysIn(object), result); + if (isDeep) { + result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); + } + var length = paths.length; + while (length--) { + baseUnset(result, paths[length]); + } + return result; + }); + + /** + * The opposite of `_.pickBy`; this method creates an object composed of + * the own and inherited enumerable string keyed properties of `object` that + * `predicate` doesn't return truthy for. The predicate is invoked with two + * arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omitBy(object, _.isNumber); + * // => { 'b': '2' } + */ + function omitBy(object, predicate) { + return pickBy(object, negate(getIteratee(predicate))); + } + + /** + * Creates an object composed of the picked `object` properties. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pick(object, ['a', 'c']); + * // => { 'a': 1, 'c': 3 } + */ + var pick = flatRest(function(object, paths) { + return object == null ? {} : basePick(object, paths); + }); + + /** + * Creates an object composed of the `object` properties `predicate` returns + * truthy for. The predicate is invoked with two arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pickBy(object, _.isNumber); + * // => { 'a': 1, 'c': 3 } + */ + function pickBy(object, predicate) { + if (object == null) { + return {}; + } + var props = arrayMap(getAllKeysIn(object), function(prop) { + return [prop]; + }); + predicate = getIteratee(predicate); + return basePickBy(object, props, function(value, path) { + return predicate(value, path[0]); + }); + } + + /** + * This method is like `_.get` except that if the resolved value is a + * function it's invoked with the `this` binding of its parent object and + * its result is returned. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to resolve. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; + * + * _.result(object, 'a[0].b.c1'); + * // => 3 + * + * _.result(object, 'a[0].b.c2'); + * // => 4 + * + * _.result(object, 'a[0].b.c3', 'default'); + * // => 'default' + * + * _.result(object, 'a[0].b.c3', _.constant('default')); + * // => 'default' + */ + function result(object, path, defaultValue) { + path = castPath(path, object); + + var index = -1, + length = path.length; + + // Ensure the loop is entered when path is empty. + if (!length) { + length = 1; + object = undefined; + } + while (++index < length) { + var value = object == null ? undefined : object[toKey(path[index])]; + if (value === undefined) { + index = length; + value = defaultValue; + } + object = isFunction(value) ? value.call(object) : value; + } + return object; + } + + /** + * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, + * it's created. Arrays are created for missing index properties while objects + * are created for all other missing properties. Use `_.setWith` to customize + * `path` creation. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @returns {Object} Returns `object`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.set(object, 'a[0].b.c', 4); + * console.log(object.a[0].b.c); + * // => 4 + * + * _.set(object, ['x', '0', 'y', 'z'], 5); + * console.log(object.x[0].y.z); + * // => 5 + */ + function set(object, path, value) { + return object == null ? object : baseSet(object, path, value); + } + + /** + * This method is like `_.set` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * var object = {}; + * + * _.setWith(object, '[0][1]', 'a', Object); + * // => { '0': { '1': 'a' } } + */ + function setWith(object, path, value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return object == null ? object : baseSet(object, path, value, customizer); + } + + /** + * Creates an array of own enumerable string keyed-value pairs for `object` + * which can be consumed by `_.fromPairs`. If `object` is a map or set, its + * entries are returned. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias entries + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the key-value pairs. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.toPairs(new Foo); + * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) + */ + var toPairs = createToPairs(keys); + + /** + * Creates an array of own and inherited enumerable string keyed-value pairs + * for `object` which can be consumed by `_.fromPairs`. If `object` is a map + * or set, its entries are returned. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias entriesIn + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the key-value pairs. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.toPairsIn(new Foo); + * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) + */ + var toPairsIn = createToPairs(keysIn); + + /** + * An alternative to `_.reduce`; this method transforms `object` to a new + * `accumulator` object which is the result of running each of its own + * enumerable string keyed properties thru `iteratee`, with each invocation + * potentially mutating the `accumulator` object. If `accumulator` is not + * provided, a new object with the same `[[Prototype]]` will be used. The + * iteratee is invoked with four arguments: (accumulator, value, key, object). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The custom accumulator value. + * @returns {*} Returns the accumulated value. + * @example + * + * _.transform([2, 3, 4], function(result, n) { + * result.push(n *= n); + * return n % 2 == 0; + * }, []); + * // => [4, 9] + * + * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } + */ + function transform(object, iteratee, accumulator) { + var isArr = isArray(object), + isArrLike = isArr || isBuffer(object) || isTypedArray(object); + + iteratee = getIteratee(iteratee, 4); + if (accumulator == null) { + var Ctor = object && object.constructor; + if (isArrLike) { + accumulator = isArr ? new Ctor : []; + } + else if (isObject(object)) { + accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; + } + else { + accumulator = {}; + } + } + (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { + return iteratee(accumulator, value, index, object); + }); + return accumulator; + } + + /** + * Removes the property at `path` of `object`. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to unset. + * @returns {boolean} Returns `true` if the property is deleted, else `false`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 7 } }] }; + * _.unset(object, 'a[0].b.c'); + * // => true + * + * console.log(object); + * // => { 'a': [{ 'b': {} }] }; + * + * _.unset(object, ['a', '0', 'b', 'c']); + * // => true + * + * console.log(object); + * // => { 'a': [{ 'b': {} }] }; + */ + function unset(object, path) { + return object == null ? true : baseUnset(object, path); + } + + /** + * This method is like `_.set` except that accepts `updater` to produce the + * value to set. Use `_.updateWith` to customize `path` creation. The `updater` + * is invoked with one argument: (value). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {Function} updater The function to produce the updated value. + * @returns {Object} Returns `object`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.update(object, 'a[0].b.c', function(n) { return n * n; }); + * console.log(object.a[0].b.c); + * // => 9 + * + * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); + * console.log(object.x[0].y.z); + * // => 0 + */ + function update(object, path, updater) { + return object == null ? object : baseUpdate(object, path, castFunction(updater)); + } + + /** + * This method is like `_.update` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {Function} updater The function to produce the updated value. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * var object = {}; + * + * _.updateWith(object, '[0][1]', _.constant('a'), Object); + * // => { '0': { '1': 'a' } } + */ + function updateWith(object, path, updater, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); + } + + /** + * Creates an array of the own enumerable string keyed property values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.values(new Foo); + * // => [1, 2] (iteration order is not guaranteed) + * + * _.values('hi'); + * // => ['h', 'i'] + */ + function values(object) { + return object == null ? [] : baseValues(object, keys(object)); + } + + /** + * Creates an array of the own and inherited enumerable string keyed property + * values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.valuesIn(new Foo); + * // => [1, 2, 3] (iteration order is not guaranteed) + */ + function valuesIn(object) { + return object == null ? [] : baseValues(object, keysIn(object)); + } + + /*------------------------------------------------------------------------*/ + + /** + * Clamps `number` within the inclusive `lower` and `upper` bounds. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Number + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. + * @example + * + * _.clamp(-10, -5, 5); + * // => -5 + * + * _.clamp(10, -5, 5); + * // => 5 + */ + function clamp(number, lower, upper) { + if (upper === undefined) { + upper = lower; + lower = undefined; + } + if (upper !== undefined) { + upper = toNumber(upper); + upper = upper === upper ? upper : 0; + } + if (lower !== undefined) { + lower = toNumber(lower); + lower = lower === lower ? lower : 0; + } + return baseClamp(toNumber(number), lower, upper); + } + + /** + * Checks if `n` is between `start` and up to, but not including, `end`. If + * `end` is not specified, it's set to `start` with `start` then set to `0`. + * If `start` is greater than `end` the params are swapped to support + * negative ranges. + * + * @static + * @memberOf _ + * @since 3.3.0 + * @category Number + * @param {number} number The number to check. + * @param {number} [start=0] The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + * @see _.range, _.rangeRight + * @example + * + * _.inRange(3, 2, 4); + * // => true + * + * _.inRange(4, 8); + * // => true + * + * _.inRange(4, 2); + * // => false + * + * _.inRange(2, 2); + * // => false + * + * _.inRange(1.2, 2); + * // => true + * + * _.inRange(5.2, 4); + * // => false + * + * _.inRange(-3, -2, -6); + * // => true + */ + function inRange(number, start, end) { + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + number = toNumber(number); + return baseInRange(number, start, end); + } + + /** + * Produces a random number between the inclusive `lower` and `upper` bounds. + * If only one argument is provided a number between `0` and the given number + * is returned. If `floating` is `true`, or either `lower` or `upper` are + * floats, a floating-point number is returned instead of an integer. + * + * **Note:** JavaScript follows the IEEE-754 standard for resolving + * floating-point values which can produce unexpected results. + * + * @static + * @memberOf _ + * @since 0.7.0 + * @category Number + * @param {number} [lower=0] The lower bound. + * @param {number} [upper=1] The upper bound. + * @param {boolean} [floating] Specify returning a floating-point number. + * @returns {number} Returns the random number. + * @example + * + * _.random(0, 5); + * // => an integer between 0 and 5 + * + * _.random(5); + * // => also an integer between 0 and 5 + * + * _.random(5, true); + * // => a floating-point number between 0 and 5 + * + * _.random(1.2, 5.2); + * // => a floating-point number between 1.2 and 5.2 + */ + function random(lower, upper, floating) { + if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { + upper = floating = undefined; + } + if (floating === undefined) { + if (typeof upper == 'boolean') { + floating = upper; + upper = undefined; + } + else if (typeof lower == 'boolean') { + floating = lower; + lower = undefined; + } + } + if (lower === undefined && upper === undefined) { + lower = 0; + upper = 1; + } + else { + lower = toFinite(lower); + if (upper === undefined) { + upper = lower; + lower = 0; + } else { + upper = toFinite(upper); + } + } + if (lower > upper) { + var temp = lower; + lower = upper; + upper = temp; + } + if (floating || lower % 1 || upper % 1) { + var rand = nativeRandom(); + return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); + } + return baseRandom(lower, upper); + } + + /*------------------------------------------------------------------------*/ + + /** + * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the camel cased string. + * @example + * + * _.camelCase('Foo Bar'); + * // => 'fooBar' + * + * _.camelCase('--foo-bar--'); + * // => 'fooBar' + * + * _.camelCase('__FOO_BAR__'); + * // => 'fooBar' + */ + var camelCase = createCompounder(function(result, word, index) { + word = word.toLowerCase(); + return result + (index ? capitalize(word) : word); + }); + + /** + * Converts the first character of `string` to upper case and the remaining + * to lower case. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to capitalize. + * @returns {string} Returns the capitalized string. + * @example + * + * _.capitalize('FRED'); + * // => 'Fred' + */ + function capitalize(string) { + return upperFirst(toString(string).toLowerCase()); + } + + /** + * Deburrs `string` by converting + * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) + * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) + * letters to basic Latin letters and removing + * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to deburr. + * @returns {string} Returns the deburred string. + * @example + * + * _.deburr('déjà vu'); + * // => 'deja vu' + */ + function deburr(string) { + string = toString(string); + return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); + } + + /** + * Checks if `string` ends with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=string.length] The position to search up to. + * @returns {boolean} Returns `true` if `string` ends with `target`, + * else `false`. + * @example + * + * _.endsWith('abc', 'c'); + * // => true + * + * _.endsWith('abc', 'b'); + * // => false + * + * _.endsWith('abc', 'b', 2); + * // => true + */ + function endsWith(string, target, position) { + string = toString(string); + target = baseToString(target); + + var length = string.length; + position = position === undefined + ? length + : baseClamp(toInteger(position), 0, length); + + var end = position; + position -= target.length; + return position >= 0 && string.slice(position, end) == target; + } + + /** + * Converts the characters "&", "<", ">", '"', and "'" in `string` to their + * corresponding HTML entities. + * + * **Note:** No other characters are escaped. To escape additional + * characters use a third-party library like [_he_](https://mths.be/he). + * + * Though the ">" character is escaped for symmetry, characters like + * ">" and "/" don't need escaping in HTML and have no special meaning + * unless they're part of a tag or unquoted attribute value. See + * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) + * (under "semi-related fun fact") for more details. + * + * When working with HTML you should always + * [quote attribute values](http://wonko.com/post/html-escaping) to reduce + * XSS vectors. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escape('fred, barney, & pebbles'); + * // => 'fred, barney, & pebbles' + */ + function escape(string) { + string = toString(string); + return (string && reHasUnescapedHtml.test(string)) + ? string.replace(reUnescapedHtml, escapeHtmlChar) + : string; + } + + /** + * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", + * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escapeRegExp('[lodash](https://lodash.com/)'); + * // => '\[lodash\]\(https://lodash\.com/\)' + */ + function escapeRegExp(string) { + string = toString(string); + return (string && reHasRegExpChar.test(string)) + ? string.replace(reRegExpChar, '\\$&') + : string; + } + + /** + * Converts `string` to + * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the kebab cased string. + * @example + * + * _.kebabCase('Foo Bar'); + * // => 'foo-bar' + * + * _.kebabCase('fooBar'); + * // => 'foo-bar' + * + * _.kebabCase('__FOO_BAR__'); + * // => 'foo-bar' + */ + var kebabCase = createCompounder(function(result, word, index) { + return result + (index ? '-' : '') + word.toLowerCase(); + }); + + /** + * Converts `string`, as space separated words, to lower case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the lower cased string. + * @example + * + * _.lowerCase('--Foo-Bar--'); + * // => 'foo bar' + * + * _.lowerCase('fooBar'); + * // => 'foo bar' + * + * _.lowerCase('__FOO_BAR__'); + * // => 'foo bar' + */ + var lowerCase = createCompounder(function(result, word, index) { + return result + (index ? ' ' : '') + word.toLowerCase(); + }); + + /** + * Converts the first character of `string` to lower case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.lowerFirst('Fred'); + * // => 'fred' + * + * _.lowerFirst('FRED'); + * // => 'fRED' + */ + var lowerFirst = createCaseFirst('toLowerCase'); + + /** + * Pads `string` on the left and right sides if it's shorter than `length`. + * Padding characters are truncated if they can't be evenly divided by `length`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.pad('abc', 8); + * // => ' abc ' + * + * _.pad('abc', 8, '_-'); + * // => '_-abc_-_' + * + * _.pad('abc', 3); + * // => 'abc' + */ + function pad(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + if (!length || strLength >= length) { + return string; + } + var mid = (length - strLength) / 2; + return ( + createPadding(nativeFloor(mid), chars) + + string + + createPadding(nativeCeil(mid), chars) + ); + } + + /** + * Pads `string` on the right side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padEnd('abc', 6); + * // => 'abc ' + * + * _.padEnd('abc', 6, '_-'); + * // => 'abc_-_' + * + * _.padEnd('abc', 3); + * // => 'abc' + */ + function padEnd(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + return (length && strLength < length) + ? (string + createPadding(length - strLength, chars)) + : string; + } + + /** + * Pads `string` on the left side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padStart('abc', 6); + * // => ' abc' + * + * _.padStart('abc', 6, '_-'); + * // => '_-_abc' + * + * _.padStart('abc', 3); + * // => 'abc' + */ + function padStart(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + return (length && strLength < length) + ? (createPadding(length - strLength, chars) + string) + : string; + } + + /** + * Converts `string` to an integer of the specified radix. If `radix` is + * `undefined` or `0`, a `radix` of `10` is used unless `value` is a + * hexadecimal, in which case a `radix` of `16` is used. + * + * **Note:** This method aligns with the + * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category String + * @param {string} string The string to convert. + * @param {number} [radix=10] The radix to interpret `value` by. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {number} Returns the converted integer. + * @example + * + * _.parseInt('08'); + * // => 8 + * + * _.map(['6', '08', '10'], _.parseInt); + * // => [6, 8, 10] + */ + function parseInt(string, radix, guard) { + if (guard || radix == null) { + radix = 0; + } else if (radix) { + radix = +radix; + } + return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); + } + + /** + * Repeats the given string `n` times. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to repeat. + * @param {number} [n=1] The number of times to repeat the string. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {string} Returns the repeated string. + * @example + * + * _.repeat('*', 3); + * // => '***' + * + * _.repeat('abc', 2); + * // => 'abcabc' + * + * _.repeat('abc', 0); + * // => '' + */ + function repeat(string, n, guard) { + if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { + n = 1; + } else { + n = toInteger(n); + } + return baseRepeat(toString(string), n); + } + + /** + * Replaces matches for `pattern` in `string` with `replacement`. + * + * **Note:** This method is based on + * [`String#replace`](https://mdn.io/String/replace). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to modify. + * @param {RegExp|string} pattern The pattern to replace. + * @param {Function|string} replacement The match replacement. + * @returns {string} Returns the modified string. + * @example + * + * _.replace('Hi Fred', 'Fred', 'Barney'); + * // => 'Hi Barney' + */ + function replace() { + var args = arguments, + string = toString(args[0]); + + return args.length < 3 ? string : string.replace(args[1], args[2]); + } + + /** + * Converts `string` to + * [snake case](https://en.wikipedia.org/wiki/Snake_case). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the snake cased string. + * @example + * + * _.snakeCase('Foo Bar'); + * // => 'foo_bar' + * + * _.snakeCase('fooBar'); + * // => 'foo_bar' + * + * _.snakeCase('--FOO-BAR--'); + * // => 'foo_bar' + */ + var snakeCase = createCompounder(function(result, word, index) { + return result + (index ? '_' : '') + word.toLowerCase(); + }); + + /** + * Splits `string` by `separator`. + * + * **Note:** This method is based on + * [`String#split`](https://mdn.io/String/split). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to split. + * @param {RegExp|string} separator The separator pattern to split by. + * @param {number} [limit] The length to truncate results to. + * @returns {Array} Returns the string segments. + * @example + * + * _.split('a-b-c', '-', 2); + * // => ['a', 'b'] + */ + function split(string, separator, limit) { + if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { + separator = limit = undefined; + } + limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; + if (!limit) { + return []; + } + string = toString(string); + if (string && ( + typeof separator == 'string' || + (separator != null && !isRegExp(separator)) + )) { + separator = baseToString(separator); + if (!separator && hasUnicode(string)) { + return castSlice(stringToArray(string), 0, limit); + } + } + return string.split(separator, limit); + } + + /** + * Converts `string` to + * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). + * + * @static + * @memberOf _ + * @since 3.1.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the start cased string. + * @example + * + * _.startCase('--foo-bar--'); + * // => 'Foo Bar' + * + * _.startCase('fooBar'); + * // => 'Foo Bar' + * + * _.startCase('__FOO_BAR__'); + * // => 'FOO BAR' + */ + var startCase = createCompounder(function(result, word, index) { + return result + (index ? ' ' : '') + upperFirst(word); + }); + + /** + * Checks if `string` starts with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=0] The position to search from. + * @returns {boolean} Returns `true` if `string` starts with `target`, + * else `false`. + * @example + * + * _.startsWith('abc', 'a'); + * // => true + * + * _.startsWith('abc', 'b'); + * // => false + * + * _.startsWith('abc', 'b', 1); + * // => true + */ + function startsWith(string, target, position) { + string = toString(string); + position = position == null + ? 0 + : baseClamp(toInteger(position), 0, string.length); + + target = baseToString(target); + return string.slice(position, position + target.length) == target; + } + + /** + * Creates a compiled template function that can interpolate data properties + * in "interpolate" delimiters, HTML-escape interpolated data properties in + * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data + * properties may be accessed as free variables in the template. If a setting + * object is given, it takes precedence over `_.templateSettings` values. + * + * **Note:** In the development build `_.template` utilizes + * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) + * for easier debugging. + * + * For more information on precompiling templates see + * [lodash's custom builds documentation](https://lodash.com/custom-builds). + * + * For more information on Chrome extension sandboxes see + * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The template string. + * @param {Object} [options={}] The options object. + * @param {RegExp} [options.escape=_.templateSettings.escape] + * The HTML "escape" delimiter. + * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] + * The "evaluate" delimiter. + * @param {Object} [options.imports=_.templateSettings.imports] + * An object to import into the template as free variables. + * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] + * The "interpolate" delimiter. + * @param {string} [options.sourceURL='lodash.templateSources[n]'] + * The sourceURL of the compiled template. + * @param {string} [options.variable='obj'] + * The data object variable name. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the compiled template function. + * @example + * + * // Use the "interpolate" delimiter to create a compiled template. + * var compiled = _.template('hello <%= user %>!'); + * compiled({ 'user': 'fred' }); + * // => 'hello fred!' + * + * // Use the HTML "escape" delimiter to escape data property values. + * var compiled = _.template('<%- value %>'); + * compiled({ 'value': '