!function e(t,n,r){function o(s,a){if(!n[s]){if(!t[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(i)return i(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var d=n[s]={exports:{}};t[s][0].call(d.exports,function(e){var n=t[s][1][e];return o(n?n:e)},d,d.exports,e,t,n,r)}return n[s].exports}for(var i="function"==typeof require&&require,s=0;s1&&(n.status=x.QUEUED)),o||(o=a(e,n)),o.done(function(e){if(t){var o=e.event_id,s=O.findElement(t.timeline,function(e){return e.getId()===o},!0);s?(n.encryptedType&&(s.event.content=n.event.content,s.event.type=n.event.type),O.removeElement(t.timeline,function(e){return e.getId()===n.getId()},!0)):(n.event.event_id=e.event_id,n.status=null)}S(r,i,e)},function(e){n.status=x.NOT_SENT,E(r,i,e)}),i.promise}function a(e,t){var n,r={$roomId:t.getRoomId(),$eventType:t.getWireType(),$stateKey:t.getStateKey(),$txnId:t._txnId?t._txnId:(new Date).getTime()};if(t.isState()){var o="/rooms/$roomId/state/$eventType";t.getStateKey()&&t.getStateKey().length>0&&(o="/rooms/$roomId/state/$eventType/$stateKey"),n=O.encodeUri(o,r)}else n=O.encodeUri("/rooms/$roomId/send/$eventType/$txnId",r);return e._http.authedRequest(void 0,"PUT",n,void 0,t.getWireContent())}function u(e,t,n,r,o,i){O.isFunction(o)&&(i=o,o=void 0);var s=O.encodeUri("/rooms/$roomId/state/m.room.member/$userId",{$roomId:t,$userId:n});return e._http.authedRequest(i,"PUT",s,void 0,{membership:r,reason:o})}function c(e,t,n,r,o,i){O.isFunction(o)&&(i=o,o=void 0);var s=O.encodeUri("/rooms/$room_id/$membership",{$room_id:t,$membership:r});return e._http.authedRequest(i,"POST",s,void 0,{user_id:n,reason:o})}function d(e,t,n){var r={limit:t};n&&(r.archived=!0),e._http.authedRequest(void 0,"GET","/initialSync",r).done(function(t){var n,r;if(!(e.store instanceof C)){O.forEach(O.map(t.presence,w(e)),function(t){var n=g(e,t.getContent().user_id);n.setPresenceEvent(t),e.store.storeUser(n)});var o={};for(t.receipts=t.receipts||[],O.forEach(t.receipts.map(w(e)),function(e){o[e.getRoomId()]||(o[e.getRoomId()]=[]),o[e.getRoomId()].push(e)}),n=0;no.lifetime)return;if(i&&"ended"===i.state)return;if(i&&console.log("WARN: Already have a MatrixCall with id %s but got an invite. Clobbering.",o.call_id),i=M.createNewMatrixCall(e,n.getRoomId()),!i)return void console.log("Incoming call ID "+o.call_id+" but this client doesn't support WebRTC");if(i.callId=o.call_id,i._initWithInvite(n),e.callList[i.callId]=i,t[i.callId])for(r=0;ri.callId?(console.log("Glare detected: answering incoming call "+i.callId+" and canceling outgoing call "+s.callId),s._replacedBy(i),i.answer()):(console.log("Glare detected: rejecting incoming call "+i.callId+" and keeping outgoing call "+s.callId),i.hangup()):e.emit("Call.incoming",i)}else if("m.call.answer"===n.getType()){if(!i)return;n.getSender()===e.credentials.userId?"ringing"===i.state&&i._onAnsweredElsewhere(o):i._receivedAnswer(o)}else if("m.call.candidates"===n.getType()){if(n.getSender()===e.credentials.userId)return;if(i)for(r=0;ri,u=l.sessionStore.getEndToEndAccount(),c=new q.Account;try{if(c.unpickle(l.accountKey,u),c.mark_keys_as_published(),s){var d=o-i;e&&(d=Math.min(d,e)),c.generate_one_time_keys(d)}u=c.pickle(l.accountKey),l.sessionStore.storeEndToEndAccount(u)}finally{c.free()}s&&n?l.uploadKeys(e,t):t.resolve()}),t.promise},n.prototype.downloadKeys=function(e,t){if(!P||null===this.sessionStore)return R.reject(new Error("End-to-end encryption disabled"));for(var n={},r={},o=!1,i=0;i0){var l={};for(o=0;on;n++)e+=t.charAt(Math.floor(Math.random()*t.length));return e},t.exports.MatrixClient=n,t.exports.CRYPTO_ENABLED=P},{"./content-repo":3,"./http-api":4,"./models/event":6,"./models/room":10,"./models/user":11,"./pushprocessor":12,"./store/stub":16,"./utils":18,"./webrtc/call":19,events:21,olm:void 0,q:23}],3:[function(e,t){var n=e("./utils");t.exports={getHttpUriForMxc:function(e,t,r,o,i){if("string"!=typeof t||!t)return t;if(0!==t.indexOf("mxc://"))return t;var s=t.slice(6),a="/_matrix/media/v1/download/",u={};r&&(u.width=r),o&&(u.height=o),i&&(u.method=i),n.keys(u).length>0&&(a="/_matrix/media/v1/thumbnail/");var c=s.indexOf("#"),d="";return c>=0&&(d=s.substr(c),s=s.substr(0,c)),e+a+s+(0===n.keys(u).length?"":"?"+n.encodeParams(u))+d},getIdenticonUri:function(e,t,r,o){if(!t)return null;r||(r=96),o||(o=96);var i={width:r,height:o},s=n.encodeUri("/_matrix/media/v1/identicon/$ident",{$ident:t});return e+s+(0===n.keys(i).length?"":"?"+n.encodeParams(i))}}},{"./utils":18}],4:[function(e,t){(function(n){"use strict";var r=e("q"),o=e("./utils");t.exports.PREFIX_V1="/_matrix/client/api/v1",t.exports.PREFIX_V2_ALPHA="/_matrix/client/v2_alpha",t.exports.PREFIX_IDENTITY_V1="/_matrix/identity/api/v1",t.exports.MatrixHttpApi=function(e){o.checkObjectHasKeys(e,["baseUrl","request","prefix"]),e.onlyData=e.onlyData||!1,this.opts=e},t.exports.MatrixHttpApi.prototype={getContentUri:function(){var e={access_token:this.opts.accessToken};return{base:this.opts.baseUrl,path:"/_matrix/media/v1/upload",params:e}},uploadContent:function(e,t){if(void 0!==t&&!o.isFunction(t))throw Error("Expected callback to be a function but got "+typeof t);var s=r.defer(),a=this.opts.baseUrl+"/_matrix/media/v1/upload";if(n.XMLHttpRequest){var u=new n.XMLHttpRequest,c=i(s,t,this.opts.onlyData),d=function(){u.abort(),c(new Error("Timeout"))};u.timeout_timer=setTimeout(d,3e4),u.onreadystatechange=function(){switch(u.readyState){case n.XMLHttpRequest.DONE:if(clearTimeout(u.timeout_timer),!u.responseText)return void c(new Error("No response body."));var e=JSON.parse(u.responseText);if(void 0===e.content_uri)return void c(new Error("Bad response"));c(void 0,u,e.content_uri)}},u.upload.addEventListener("progress",function(e){clearTimeout(u.timeout_timer),u.timeout_timer=setTimeout(d,3e4),s.notify(e)}),a+="?access_token="+encodeURIComponent(this.opts.accessToken),a+="&filename="+encodeURIComponent(e.name),u.open("POST",a),e.type?u.setRequestHeader("Content-Type",e.type):u.setRequestHeader("Content-Type","application/octet-stream"),u.send(e)}else{var l={filename:e.name,access_token:this.opts.accessToken};e.stream.pipe(this.opts.request({uri:a,qs:l,method:"POST"},i(s,t,this.opts.onlyData)))}return s.promise},idServerRequest:function(e,t,n,s,a){var u=this.opts.idBaseUrl+a+n;if(void 0!==e&&!o.isFunction(e))throw Error("Expected callback to be a function but got "+typeof e);var c={uri:u,method:t,withCredentials:!1,json:!1,_matrix_opts:this.opts};"GET"==t?c.qs=s:c.form=s;var d=r.defer();return this.opts.request(c,i(d,e,this.opts.onlyData)),d.promise},authedRequest:function(e,t,n,r,o){return r||(r={}),r.access_token=this.opts.accessToken,this.request(e,t,n,r,o)},request:function(e,t,n,r,o){return this.requestWithPrefix(e,t,n,r,o,this.opts.prefix)},authedRequestWithPrefix:function(e,t,n,r,o,i){var s=this.opts.baseUrl+i+n;return r||(r={}),r.access_token=this.opts.accessToken,this._request(e,t,s,r,o)},requestWithPrefix:function(e,t,n,r,o,i){var s=this.opts.baseUrl+i+n;return r||(r={}),this._request(e,t,s,r,o)},_request:function(e,t,n,s,a){if(void 0!==e&&!o.isFunction(e))throw Error("Expected callback to be a function but got "+typeof e);if(s||(s={}),this.opts.extraParams)for(var u in this.opts.extraParams)this.opts.extraParams.hasOwnProperty(u)&&(s[u]=this.opts.extraParams[u]);var c=r.defer();try{this.opts.request({uri:n,method:t,withCredentials:!1,qs:s,body:a,json:!0,_matrix_opts:this.opts},i(c,e,this.opts.onlyData))}catch(d){c.reject(d),e&&e(d)}return c.promise}};var i=function(e,n,r){return n=n||function(){},function(o,i,s){if(!o&&i.statusCode>=400&&(o=new t.exports.MatrixError(s),o.httpStatus=i.statusCode),o)e.reject(o),n(o);else{var a={code:i.statusCode,headers:i.headers,data:s};e.resolve(r?s:a),n(null,r?s:a); }}};t.exports.MatrixError=function(e){this.errcode=e.errcode,this.name=e.errcode||"Unknown error code",this.message=e.error||"Unknown message",this.data=e},t.exports.MatrixError.prototype=Object.create(Error.prototype),t.exports.MatrixError.prototype.constructor=t.exports.MatrixError}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./utils":18,q:23}],5:[function(e,t){"use strict";t.exports.MatrixEvent=e("./models/event").MatrixEvent,t.exports.EventStatus=e("./models/event").EventStatus,t.exports.MatrixInMemoryStore=e("./store/memory").MatrixInMemoryStore,t.exports.WebStorageStore=e("./store/webstorage"),t.exports.MatrixHttpApi=e("./http-api").MatrixHttpApi,t.exports.MatrixError=e("./http-api").MatrixError,t.exports.MatrixClient=e("./client").MatrixClient,t.exports.Room=e("./models/room"),t.exports.RoomMember=e("./models/room-member"),t.exports.RoomState=e("./models/room-state"),t.exports.User=e("./models/user"),t.exports.MatrixScheduler=e("./scheduler"),t.exports.WebStorageSessionStore=e("./store/session/webstorage"),t.exports.CRYPTO_ENABLED=e("./client").CRYPTO_ENABLED,t.exports.ContentRepo=e("./content-repo"),t.exports.createNewMatrixCall=e("./webrtc/call").createNewMatrixCall;var n;t.exports.request=function(e){n=e},t.exports.createClient=function(e){return"string"==typeof e&&(e={baseUrl:e}),e.request=e.request||n,e.store=e.store||new t.exports.MatrixInMemoryStore,e.scheduler=e.scheduler||new t.exports.MatrixScheduler,new t.exports.MatrixClient(e)}},{"./client":2,"./content-repo":3,"./http-api":4,"./models/event":6,"./models/room":10,"./models/room-member":7,"./models/room-state":8,"./models/user":11,"./scheduler":13,"./store/memory":14,"./store/session/webstorage":15,"./store/webstorage":17,"./webrtc/call":19}],6:[function(e,t){"use strict";t.exports.EventStatus={NOT_SENT:"not_sent",SENDING:"sending",QUEUED:"queued"},t.exports.MatrixEvent=function(e,t){this.event=e||{},this.sender=null,this.target=null,this.status=null,this.forwardLooking=!0,this.encrypted=Boolean(t)},t.exports.MatrixEvent.prototype={getId:function(){return this.event.event_id},getSender:function(){return this.event.user_id},getType:function(){return this.event.type},getWireType:function(){return this.encryptedType||this.event.type},getRoomId:function(){return this.event.room_id},getTs:function(){return this.event.origin_server_ts},getContent:function(){return this.event.content||{}},getWireContent:function(){return this.encryptedContent||this.event.content||{}},getPrevContent:function(){return this.event.prev_content||{}},getDirectionalContent:function(){return this.forwardLooking?this.getContent():this.getPrevContent()},getAge:function(){return this.event.age},getStateKey:function(){return this.event.state_key},isState:function(){return void 0!==this.event.state_key},isEncrypted:function(){return this.encrypted}}},{}],7:[function(e,t){"use strict";function n(e,t){this.roomId=e,this.userId=t,this.typing=!1,this.name=t,this.powerLevel=0,this.powerLevelNorm=0,this.user=null,this.membership=null,this.events={member:null},this._updateModifiedTime()}function r(e,t,n){var r=t.getDirectionalContent().displayname,o=e.userId;if(!r)return o;if(!n)return r;var i=n.getUserIdsWithDisplayName(r),s=i.filter(function(e){return e!==o});return s.length>0?r+" ("+o+")":r}var o=e("events").EventEmitter,i=e("../content-repo"),s=e("../utils");s.inherits(n,o),n.prototype.setMembershipEvent=function(e,t){if("m.room.member"===e.getType()){this.events.member=e;var n=this.membership;this.membership=e.getDirectionalContent().membership;var o=this.name;this.name=r(this,e,t),n!==this.membership&&(this._updateModifiedTime(),this.emit("RoomMember.membership",e,this)),o!==this.name&&(this._updateModifiedTime(),this.emit("RoomMember.name",e,this))}},n.prototype.setPowerLevelEvent=function(e){if("m.room.power_levels"===e.getType()){var t=e.getContent().users_default||0;s.forEach(s.values(e.getContent().users),function(e){t=Math.max(t,e)});var n=this.powerLevel,r=this.powerLevelNorm;this.powerLevel=e.getContent().users[this.userId]||e.getContent().users_default||0,this.powerLevelNorm=0,t>0&&(this.powerLevelNorm=100*this.powerLevel/t),(n!==this.powerLevel||r!==this.powerLevelNorm)&&(this._updateModifiedTime(),this.emit("RoomMember.powerLevel",e,this))}},n.prototype.setTypingEvent=function(e){if("m.typing"===e.getType()){var t=this.typing;this.typing=!1;var n=e.getContent().user_ids;s.isArray(n)&&(-1!==n.indexOf(this.userId)&&(this.typing=!0),t!==this.typing&&(this._updateModifiedTime(),this.emit("RoomMember.typing",e,this)))}},n.prototype._updateModifiedTime=function(){this._modified=Date.now()},n.prototype.getLastModifiedTime=function(){return this._modified},n.prototype.getAvatarUrl=function(e,t,n,r,o){if(void 0===o&&(o=!0),!this.events.member&&!o)return null;var s=this.events.member?this.events.member.getContent().avatar_url:null;return s?i.getHttpUriForMxc(e,s,t,n,r):o?i.getIdenticonUri(e,this.userId,t,n):null},t.exports=n},{"../content-repo":3,"../utils":18,events:21}],8:[function(e,t){"use strict";function n(e){this.roomId=e,this.members={},this.events={},this.paginationToken=null,this._sentinels={},this._updateModifiedTime(),this._displayNameToUserIds={},this._userIdsToDisplayNames={}}function r(e,t,n){var r=e._userIdsToDisplayNames[t];if(delete e._userIdsToDisplayNames[t],r){for(var o=e._displayNameToUserIds[r]||[],i=0;i0},n.prototype.addEventsToTimeline=function(e,t){function n(e){return function(t){return t.getId()===e.event.redacts}}for(var o=t?this.oldState:this.currentState,i=0;i=0)){if(r(e[i],o,t),e[i].isState()&&(o.setStateEvents([e[i]]),e[i].sender||r(e[i],o,t)),"m.room.redaction"===e[i].getType()){var s=c.removeElement(this.timeline,n(e[i]));!s&&t&&this._redactions.push(e[i].event.redacts)}t?this.timeline.unshift(e[i]):this.timeline.push(e[i]),this.emit("Room.timeline",e[i],this,Boolean(t))}},n.prototype.addEvents=function(e,t){if(t&&-1===["replace","ignore"].indexOf(t))throw new Error("duplicateStrategy MUST be either 'replace' or 'ignore'");for(var n=0;n0&&this._updateModifiedTime();for(var r=0;r]*)([0-9]*)$/);if(!i)return!1;var s=i[1],a=parseInt(i[2]);if(isNaN(a))return!1;switch(s){case"":case"==":return o==a;case"<":return a>o;case">":return o>a;case"<=":return a>=o;case">=":return o>=a;default:return!1}},a=function(n,r){if(!r.content||!r.content.body||"string"!=typeof r.content.body)return!1;var o=e.getRoom(r.room_id);if(!(o&&o.currentState&&o.currentState.members&&o.currentState.getMember(e.credentials.userId)))return!1;var i=o.currentState.getMember(e.credentials.userId).name,s=new RegExp("\\b"+t(i)+"\\b","i");return r.content.body.search(s)>-1},u=function(){return!1},c=function(e,t){var n=l(e.key,t);if(!n||"string"!=typeof n)return!1;var r;r="content.body"==e.key?"\\b"+d(e.pattern)+"\\b":"^"+d(e.pattern)+"$";var o=new RegExp(r,"i");return!!n.match(o)},d=function(e){var n=t(e);return n=n.replace(/\\\*/,".*"),n=n.replace(/\?/,"."),n=n.replace(/\\\[(!|)(.*)\\]/,function(e,t,n){var r=t&&"^"||"",o=n.replace(/\\\-/,"-");return"["+r+o+"]"})},l=function(e,t){for(var n=e.split("."),r=t;n.length>0;){var o=n.shift();if(!r[o])return null;r=r[o]}return r},p=function(t,r){if(!r)return null;if(t.user_id==e.credentials.userId)return null;for(var o=Object.keys(r.device),i=0;i0}),function(t){e._activeQueues.push(t),a("Spinning up queue: '%s'",t),o(e,t)})}function o(e,t){var n=i(e,t);if(!n){var r=e._activeQueues.indexOf(t);return r>=0&&e._activeQueues.splice(r,1),void a("Stopping queue '%s' as it is now empty",t)}a("Queue '%s' has %s pending events",t,e._queues[t].length),e._procFn(n.event).done(function(r){s(e,t),a("Queue '%s' sent event %s",t,n.event.getId()),n.defer.resolve(r),o(e,t)},function(r){n.attempts+=1;var i=e.retryAlgorithm(n.event,n.attempts,r);a("retry(%s) err=%s event_id=%s waitTime=%s",n.attempts,r,n.event.getId(),i),-1===i?(a("Queue '%s' giving up on event %s",t,n.event.getId()),s(e,t),n.defer.reject(r),o(e,t)):setTimeout(function(){o(e,t)},i)})}function i(e,t){var n=e._queues[t];return u.isArray(n)?n[0]:null}function s(e,t){var n=e._queues[t];return u.isArray(n)?n.shift():null}function a(){d&&console.log.apply(console,arguments)}var u=e("./utils"),c=e("q"),d=!1;n.prototype.getQueueForEvent=function(e){var t=this.queueAlgorithm(e);return t&&this._queues[t]?u.map(this._queues[t],function(e){return e.event}):null},n.prototype.removeEventFromQueue=function(e){var t=this.queueAlgorithm(e);if(!t||!this._queues[t])return!1;var n=!1;return u.removeElement(this._queues[t],function(t){return t.event.getId()===e.getId()?(n=!0,!0):void 0}),n},n.prototype.setProcessFunction=function(e){this._procFn=e,r(this)},n.prototype.queueEvent=function(e){var t=this.queueAlgorithm(e);if(!t)return null;this._queues[t]||(this._queues[t]=[]);var n=c.defer();return this._queues[t].push({event:e,defer:n,attempts:0}),a("Queue algorithm dumped event %s into queue '%s'",e.getId(),t),r(this),n.promise},n.RETRY_BACKOFF_RATELIMIT=function(e,t,n){if(400===n.httpStatus||403===n.httpStatus||401===n.httpStatus)return-1;if("M_LIMIT_EXCEEDED"===n.name){var r=n.data.retry_after_ms;if(r)return r}return t>4?-1:1e3*Math.pow(2,t)},n.QUEUE_MESSAGES=function(e){return"m.room.message"===e.getType()?"message":null},t.exports=n},{"./utils":18,q:23}],14:[function(e,t){"use strict";var n=e("../utils");t.exports.MatrixInMemoryStore=function(){this.rooms={},this.users={},this.syncToken=null},t.exports.MatrixInMemoryStore.prototype={getSyncToken:function(){return this.syncToken},setSyncToken:function(e){this.syncToken=e},storeRoom:function(e){this.rooms[e.roomId]=e},getRoom:function(e){return this.rooms[e]||null},getRooms:function(){return n.values(this.rooms)},getRoomSummaries:function(){return n.map(n.values(this.rooms),function(e){return e.summary})},storeUser:function(e){this.users[e.userId]=e},getUser:function(e){return this.users[e]||null},scrollback:function(){return[]},storeEvents:function(){}}},{"../utils":18}],15:[function(e,t){"use strict";function n(e){if(this.store=e,!c.isFunction(e.getItem)||!c.isFunction(e.setItem)||!c.isFunction(e.removeItem))throw new Error("Supplied webStore does not meet the WebStorage API interface")}function r(e){return l+"devices/"+e}function o(e){return l+"sessions/"+e}function i(e){return l+"rooms/"+e}function s(e,t){try{return JSON.parse(e.getItem(t))}catch(n){u("Failed to get key %s: %s",t,n),u(n.stack)}return null}function a(e,t,n){e.setItem(t,JSON.stringify(n))}function u(){d&&console.log.apply(console,arguments)}var c=e("../../utils"),d=!1,l="session.e2e.";n.prototype={storeEndToEndAccount:function(e){this.store.setItem(p,e)},getEndToEndAccount:function(){return this.store.getItem(p)},storeEndToEndDevicesForUser:function(e,t){a(this.store,r(e),t)},getEndToEndDevicesForUser:function(e){return s(this.store,r(e))},storeEndToEndSession:function(e,t,n){var r=this.getEndToEndSessions(e)||{};r[t]=n,a(this.store,o(e),r)},getEndToEndSessions:function(e){return s(this.store,o(e))},storeEndToEndRoom:function(e,t){a(this.store,i(e),t)},getEndToEndRoom:function(e){return s(this.store,i(e))}};var p=l+"account";t.exports=n},{"../../utils":18}],16:[function(e,t){"use strict";function n(){this.fromToken=null}n.prototype={getSyncToken:function(){return this.fromToken},setSyncToken:function(e){this.fromToken=e},storeRoom:function(){},getRoom:function(){return null},getRooms:function(){return[]},getRoomSummaries:function(){return[]},storeUser:function(){},getUser:function(){return null},scrollback:function(){return[]},storeEvents:function(){}},t.exports=n},{}],17:[function(e,t){"use strict";function n(e,t){if(this.store=e,this.batchSize=t,!(f.isFunction(e.getItem)&&f.isFunction(e.setItem)&&f.isFunction(e.removeItem)&&f.isFunction(e.key)))throw new Error("Supplied webStore does not meet the WebStorage API interface");if(!parseInt(e.length)&&0!==e.length)throw new Error("Supplied webStore does not meet the WebStorage API interface (length)");this._roomIds=[],this._syncedWithStore=!1,this._tokens=[]}function r(e){this.state={events:{}},this.timeline={},this.roomId=e}function o(e,t,n,r){var o=new h(t,r.length),i=c(e,u(t,"state")),d=[];f.forEach(f.keys(i.events),function(e){f.forEach(f.keys(i.events[e]),function(t){d.push(i.events[e][t])})});var l=f.map(f.deepCopy(d),function(e){return new v(e)}),p=f.map(d,function(e){return new v(e)});o.oldState.setStateEvents(l),o.currentState.setStateEvents(p);for(var m,y,g,_=[],E=a(s(e,t)),S=E;_.length=0;m--)if(_.unshift(new v(g[m])),_.length===n){S=E;break}E--}return o.addEventsToTimeline(_.reverse(),!0),o.oldState.paginationToken=i.pagination_token,r.push({earliestIndex:S}),o}function i(e,t){d(e,u(t.roomId,"state"),t.state),f.forEach(f.keys(t.timeline),function(n){d(e,u(t.roomId,"timeline",n),t.timeline[n])})}function s(e,t){for(var n=[],r=0;rn||t&&n>r)&&(n=r);return n}function u(e,t,n){return"room_"+e+"_"+t+(void 0===n?"":"_"+n)}function c(e,t){try{return JSON.parse(e.getItem(t))}catch(n){l("Failed to get key %s: %s",t,n),l(n.stack)}return null}function d(e,t,n){e.setItem(t,JSON.stringify(n))}function l(){p&&console.log.apply(console,arguments)}var p=!1,f=e("../utils"),h=e("../models/room"),m=e("../models/user"),v=e("../models/event").MatrixEvent;n.prototype.getSyncToken=function(){return this.store.getItem("sync_token")},n.prototype.setSyncToken=function(e){this.store.setItem("sync_token",e)},n.prototype.storeRoom=function(e){var t=r.fromRoom(e,this.batchSize);i(this.store,t),-1===this._roomIds.indexOf(e.roomId)&&this._roomIds.push(e.roomId)},n.prototype.getRoom=function(e){if(!c(this.store,u(e,"state")))return l("getRoom: No room with id %s found.",e),null;var t=s(this.store,e);return-1!==t.indexOf("live")&&(l("getRoom: Live events found. Syncing timeline for %s",e),this._syncTimeline(e,t)),o(this.store,e,this.batchSize,this._tokens)},n.prototype.getRooms=function(){var e,t=[];if(!this._syncedWithStore){for(this._roomIds=[],e=0;e=this._tokens.length)return[];var n,r=this._tokens[e.storageToken]||{},o=r.earliestIndex,i=e.timeline[0]?e.timeline[0].getId():null;l("scrollback in %s (timeline=%s msgs) i=%s, timeline[0].id=%s - req %s events",e.roomId,e.timeline.length,o,i,t);var s=c(this.store,u(e.roomId,"timeline",o));if(!s)return l("No batch with index %s found.",o),[];var a=[],d=!1;for(n=s.length-1;n>=0;n--){var p=new v(s[n]);if(p.getId()!==i){if(d&&(l("Add event at position %s in batch %s",n,o),a.push(s[n]),a.length===t))break}else d=!0,l("Found timeline[0] event at position %s in batch %s",n,o)}if(a.length===t)return l("Batch has enough events to satisfy request."),a;if(!d)return l("Failed to find event ID %s in batch %s",i,o),[];for(;a.length=0&&(l("Add event at position %s in batch %s",n,o),a.push(s[n]),a.length!==t);n--);}return l("Out of %s requested events, returning %s. New index=%s",t,a.length,o),e.addEventsToTimeline(f.map(a,function(e){return new v(e)}),!0),this._tokens[e.storageToken]={earliestIndex:o},a},n.prototype.storeEvents=function(e,t,n,o){if(o){var i,p,h,m=a(s(this.store,e.roomId),!0);for(i=0;i0;)i.push(n.shift());d(this.store,o,i);for(var l=[];n.length>0;)l.push(n.shift()),(l.length===this.batchSize||0===n.length)&&(r++,o=u(e,"timeline",r),d(this.store,o,l),l=[]);d(this.store,u(e,"timeline","live"),[])},r.fromRoom=function(e,t){var n,o=new r(e.roomId);if(o.state.pagination_token=e.oldState.paginationToken,f.forEach(f.keys(e.currentState.events),function(t){f.forEach(f.keys(e.currentState.events[t]),function(n){o.state.events[t]||(o.state.events[t]={}),o.state.events[t][n]=e.currentState.events[t][n].event})}),t>0)for(n=0;n*t>>0;if("function"!=typeof e)throw new TypeError;for(var r=[],o=arguments.length>=2?arguments[1]:void 0,i=0;n>i;i++)if(i in t){var s=t[i];e.call(o,s,i,t)&&r.push(s)}return r}),Array.prototype.map||(Array.prototype.map=function(e,t){var n,r,o;if(null===this||void 0===this)throw new TypeError(" this is null or not defined");var i=Object(this),s=i.length>>>0;if("function"!=typeof e)throw new TypeError(e+" is not a function");for(arguments.length>1&&(n=t),r=new Array(s),o=0;s>o;){var a,u;o in i&&(a=i[o],u=e.call(n,a,o,i),r[o]=u),o++}return r})},t.exports.inherits=function(e,t){"function"!=typeof Object.create&&(Object.create=function(){function e(){}var t=Object.prototype.hasOwnProperty;return function(n){if("object"!=typeof n)throw new TypeError("Object prototype may only be an Object or null");e.prototype=n;var r=new e;if(e.prototype=null,arguments.length>1){var o=Object(arguments[1]);for(var i in o)t.call(o,i)&&(r[i]=o[i])}return r}}()),e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}},{}],19:[function(e,t){(function(n){"use strict";function r(e){this.roomId=e.roomId,this.client=e.client,this.webRtc=e.webRtc,this.URL=e.URL,this.turnServers=e.turnServers||[],0===this.turnServers.length&&this.turnServers.push({urls:[r.FALLBACK_STUN_SERVER]}),o.forEach(this.turnServers,function(e){o.checkObjectHasKeys(e,["urls"])}),this.callId="c"+(new Date).getTime(),this.state="fledgling",this.didConnect=!1,this.candidateSendQueue=[],this.candidateSendTries=0,this.screenSharingStream=null}var o=e("../utils"),i=e("events").EventEmitter,s=!0;r.CALL_TIMEOUT_MS=6e4,r.FALLBACK_STUN_SERVER="stun:stun.l.google.com:19302",r.ERR_LOCAL_OFFER_FAILED="local_offer_failed",r.ERR_NO_USER_MEDIA="no_user_media",o.inherits(r,i),r.prototype.placeVoiceCall=function(){g("placeVoiceCall"),v(this),E(this,b("voice")),this.type="voice"},r.prototype.placeVideoCall=function(e,t){g("placeVideoCall"),v(this),this.localVideoElement=t,this.remoteVideoElement=e,E(this,b("video")),this.type="video",h(this)},r.prototype.placeScreenSharingCall=function(e,t){g("placeScreenSharingCall"),v(this);var n=w(this);if(n){this.localVideoElement=t,this.remoteVideoElement=e;var o=this;this.webRtc.getUserMedia(n,function(e){o.screenSharingStream=e,g("Got screen stream, requesting audio stream...");var t=b("voice");E(o,t)},function(e){o.emit("error",y(r.ERR_NO_USER_MEDIA,"Failed to get screen-sharing stream: "+e))}),this.type="video",h(this)}},r.prototype.getLocalVideoElement=function(){return this.localVideoElement},r.prototype.getRemoteVideoElement=function(){return this.remoteVideoElement},r.prototype.getRemoteAudioElement=function(){return this.remoteAudioElement},r.prototype.setLocalVideoElement=function(e){if(this.localVideoElement=e,e&&this.localAVStream&&"video"===this.type){e.autoplay=!0,e.src=this.URL.createObjectURL(this.localAVStream),e.muted=!0;var t=this;setTimeout(function(){var e=t.getLocalVideoElement();e.play&&e.play()},0)}},r.prototype.setRemoteVideoElement=function(e){this.remoteVideoElement=e,h(this)},r.prototype.setRemoteAudioElement=function(e){ this.remoteAudioElement=e,m(this)},r.prototype._initWithInvite=function(e){this.msg=e.getContent(),this.peerConn=S(this);var t=this;this.peerConn&&this.peerConn.setRemoteDescription(new this.webRtc.RtcSessionDescription(this.msg.offer),T(t,t._onSetRemoteDescriptionSuccess),T(t,t._onSetRemoteDescriptionError)),c(this,"ringing"),this.direction="inbound",this.type=this.msg.offer&&this.msg.offer.sdp&&this.msg.offer.sdp.indexOf("m=video")>-1?"video":"voice",e.getAge()&&setTimeout(function(){"ringing"==t.state&&(g("Call invite has expired. Hanging up."),t.hangupParty="remote",c(t,"ended"),f(t),"closed"!=t.peerConn.signalingState&&t.peerConn.close(),t.emit("hangup",t))},this.msg.lifetime-e.getAge())},r.prototype._initWithHangup=function(e){this.msg=e.getContent(),c(this,"ended")},r.prototype.answer=function(){g("Answering call %s of type %s",this.callId,this.type);var e=this;this.localAVStream||this.waitForLocalAVStream?this.localAVStream?this._gotUserMediaForAnswer(this.localAVStream):this.waitForLocalAVStream&&c(this,"wait_local_media"):(this.webRtc.getUserMedia(b(this.type),T(e,e._gotUserMediaForAnswer),T(e,e._getUserMediaFailed)),c(this,"wait_local_media"))},r.prototype._replacedBy=function(e){g(this.callId+" being replaced by "+e.callId),"wait_local_media"==this.state?(g("Telling new call to wait for local media"),e.waitForLocalAVStream=!0):"create_offer"==this.state?(g("Handing local stream to new call"),e._gotUserMediaForAnswer(this.localAVStream),delete this.localAVStream):"invite_sent"==this.state&&(g("Handing local stream to new call"),e._gotUserMediaForAnswer(this.localAVStream),delete this.localAVStream),e.localVideoElement=this.localVideoElement,e.remoteVideoElement=this.remoteVideoElement,e.remoteAudioElement=this.remoteAudioElement,this.successor=e,this.emit("replaced",e),this.hangup(!0)},r.prototype.hangup=function(e,t){g("Ending call "+this.callId),p(this,"local",e,!t);var n={version:0,call_id:this.callId,reason:e};d(this,"m.call.hangup",n)},r.prototype.setLocalVideoMuted=function(e){this.localAVStream&&a(this.localAVStream.getVideoTracks(),!e)},r.prototype.isLocalVideoMuted=function(){return this.localAVStream?!u(this.localAVStream.getVideoTracks()):!1},r.prototype.setMicrophoneMuted=function(e){this.localAVStream&&a(this.localAVStream.getAudioTracks(),!e)},r.prototype.isMicrophoneMuted=function(){return this.localAVStream?!u(this.localAVStream.getAudioTracks()):!1},r.prototype._gotUserMediaForInvite=function(e){if(this.successor)return void this.successor._gotUserMediaForAnswer(e);if("ended"!=this.state){g("_gotUserMediaForInvite -> "+this.type);var t=this,n=this.getLocalVideoElement();n&&"video"==this.type&&(n.autoplay=!0,this.screenSharingStream?(g("Setting screen sharing stream to the local video element"),n.src=this.URL.createObjectURL(this.screenSharingStream)):n.src=this.URL.createObjectURL(e),n.muted=!0,setTimeout(function(){var e=t.getLocalVideoElement();e.play&&e.play()},0)),this.localAVStream=e,a(e.getAudioTracks(),!0),this.peerConn=S(this),this.peerConn.addStream(e),this.screenSharingStream&&(console.log("Adding screen-sharing stream to peer connection"),this.peerConn.addStream(this.screenSharingStream),this.localAVStream=this.screenSharingStream),this.peerConn.createOffer(T(t,t._gotLocalOffer),T(t,t._getLocalOfferFailed)),c(t,"create_offer")}},r.prototype._gotUserMediaForAnswer=function(e){var t=this;if("ended"!=t.state){var n=t.getLocalVideoElement();n&&"video"==t.type&&(n.autoplay=!0,n.src=t.URL.createObjectURL(e),n.muted=!0,setTimeout(function(){var e=t.getLocalVideoElement();e.play&&e.play()},0)),t.localAVStream=e,a(e.getAudioTracks(),!0),t.peerConn.addStream(e);var r={mandatory:{OfferToReceiveAudio:!0,OfferToReceiveVideo:"video"==t.type}};t.peerConn.createAnswer(function(e){g("Created answer: "+e),t.peerConn.setLocalDescription(e,function(){var e={version:0,call_id:t.callId,answer:{sdp:t.peerConn.localDescription.sdp,type:t.peerConn.localDescription.type}};d(t,"m.call.answer",e),c(t,"connecting")},function(){g("Error setting local description!")},r)},function(e){g("Failed to create answer: "+e)}),c(t,"create_answer")}},r.prototype._gotLocalIceCandidate=function(e){if(e.candidate){g("Got local ICE "+e.candidate.sdpMid+" candidate: "+e.candidate.candidate);var t={candidate:e.candidate.candidate,sdpMid:e.candidate.sdpMid,sdpMLineIndex:e.candidate.sdpMLineIndex};l(this,t)}},r.prototype._gotRemoteIceCandidate=function(e){"ended"!=this.state&&(g("Got remote ICE "+e.sdpMid+" candidate: "+e.candidate),this.peerConn.addIceCandidate(new this.webRtc.RtcIceCandidate(e),function(){},function(){}))},r.prototype._receivedAnswer=function(e){if("ended"!=this.state){var t=this;this.peerConn.setRemoteDescription(new this.webRtc.RtcSessionDescription(e.answer),T(t,t._onSetRemoteDescriptionSuccess),T(t,t._onSetRemoteDescriptionError)),c(t,"connecting")}},r.prototype._gotLocalOffer=function(e){var t=this;return g("Created offer: "+e),"ended"==t.state?void g("Ignoring newly created offer on call ID "+t.callId+" because the call has ended"):void t.peerConn.setLocalDescription(e,function(){var e={version:0,call_id:t.callId,offer:{sdp:t.peerConn.localDescription.sdp,type:t.peerConn.localDescription.type},lifetime:r.CALL_TIMEOUT_MS};d(t,"m.call.invite",e),setTimeout(function(){"invite_sent"==t.state&&t.hangup("invite_timeout")},r.CALL_TIMEOUT_MS),c(t,"invite_sent")},function(){g("Error setting local description!")})},r.prototype._getLocalOfferFailed=function(){this.emit("error",y(r.ERR_LOCAL_OFFER_FAILED,"Failed to start audio for call!"))},r.prototype._getUserMediaFailed=function(){this.emit("error",y(r.ERR_NO_USER_MEDIA,"Couldn't start capturing media! Is your microphone set up and does this app have permission?")),this.hangup("user_media_failed")},r.prototype._onIceConnectionStateChanged=function(){"ended"!=this.state&&(g("Ice connection state changed to: "+this.peerConn.iceConnectionState),"completed"==this.peerConn.iceConnectionState||"connected"==this.peerConn.iceConnectionState?(c(this,"connected"),this.didConnect=!0):"failed"==this.peerConn.iceConnectionState&&this.hangup("ice_failed"))},r.prototype._onSignallingStateChanged=function(){g("call "+this.callId+": Signalling state changed to: "+this.peerConn.signalingState)},r.prototype._onSetRemoteDescriptionSuccess=function(){g("Set remote description")},r.prototype._onSetRemoteDescriptionError=function(e){g("Failed to set remote description"+e)},r.prototype._onAddStream=function(e){g("Stream id "+e.stream.id+" added");var t=e.stream;t.getVideoTracks().length>0?(this.type="video",this.remoteAVStream=t):(this.type="voice",this.remoteAStream=t);var n=this;k(t,function(e){g("Track id "+e.id+" added"),e.onstarted=T(n,n._onRemoteStreamTrackStarted)}),e.stream.onended=T(n,n._onRemoteStreamEnded),e.stream.onstarted=T(n,n._onRemoteStreamStarted),"video"===this.type?h(this):m(this)},r.prototype._onRemoteStreamStarted=function(){c(this,"connected")},r.prototype._onRemoteStreamEnded=function(){g("Remote stream ended"),this.hangupParty="remote",c(this,"ended"),f(this),"closed"!=this.peerConn.signalingState&&this.peerConn.close(),this.emit("hangup",this)},r.prototype._onRemoteStreamTrackStarted=function(){c(this,"connected")},r.prototype._onHangupReceived=function(e){g("Hangup received"),p(this,"remote",e.reason,!0)},r.prototype._onAnsweredElsewhere=function(){g("Answered elsewhere"),p(this,"remote","answered_elsewhere",!0)};var a=function(e,t){for(var n=0;n5)return g("Failed to send candidates on attempt %s. Giving up for now.",e.candidateSendTries),void(e.candidateSendTries=0);var r=500*Math.pow(2,e.candidateSendTries);++e.candidateSendTries,g("Failed to send candidates. Retrying in "+r+"ms"),setTimeout(function(){_(e)},r)})}},E=function(e,t){e.client.callList[e.callId]=e,e.webRtc.getUserMedia(t,T(e,e._gotUserMediaForInvite),T(e,e._getUserMediaFailed)),c(e,"wait_local_media"),e.direction="outbound",e.config=t},S=function(e){var t=e.turnServers;if("mozilla"===e.webRtc.vendor){t=[];for(var n=0;n-1)return!0;return!1};var a=o.navigator.getUserMedia||o.navigator.webkitGetUserMedia||o.navigator.mozGetUserMedia;if(a&&(s.getUserMedia=function(){return a.apply(o.navigator,arguments)}),s.RtcPeerConnection=o.RTCPeerConnection||o.webkitRTCPeerConnection||o.mozRTCPeerConnection,s.RtcSessionDescription=o.RTCSessionDescription||o.webkitRTCSessionDescription||o.mozRTCSessionDescription,s.RtcIceCandidate=o.RTCIceCandidate||o.webkitRTCIceCandidate||o.mozRTCIceCandidate,s.vendor=null,o.mozRTCPeerConnection?s.vendor="mozilla":o.webkitRTCPeerConnection?s.vendor="webkit":o.RTCPeerConnection&&(s.vendor="generic"),!(s.RtcIceCandidate&&s.RtcSessionDescription&&s.RtcPeerConnection&&s.getUserMedia))return null;var u={webRtc:s,client:e,URL:o.URL,roomId:t,turnServers:e.getTurnServers()};return new r(u)}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../utils":18,events:21}],20:[function(e,t,n){!function(e,r){"function"==typeof define&&define.amd?define([],r):"object"==typeof n?t.exports=r():e.returnExports=r()}(this,function(){function e(o,i){if("function"!=typeof i)throw new Error("Bad callback given: "+i);if(!o)throw new Error("No options given");var a=o.onResponse;if(o="string"==typeof o?{uri:o}:JSON.parse(JSON.stringify(o)),o.onResponse=a,o.verbose&&(e.log=r()),o.url&&(o.uri=o.url,delete o.url),!o.uri&&""!==o.uri)throw new Error("options.uri is a required argument");if("string"!=typeof o.uri)throw new Error("options.uri must be a string");for(var u=["proxy","_redirectsFollowed","maxRedirects","followRedirect"],c=0;c>18&63,i=u>>12&63,s=u>>6&63,a=63&u,f[l++]=c.charAt(o)+c.charAt(i)+c.charAt(s)+c.charAt(a);while(d299)&&n.error){e=new Error("CouchDB error: "+(n.error.reason||n.error.error));for(var o in n)e[o]=n[o];return r(e,t,n)}return r(e,t,n)}"string"==typeof t&&(t={uri:t}),t.json=!0,t.body&&(t.json=t.body),delete t.body,r=r||n;var i=e(t,o);return i},e})},{}],21:[function(e,t){function n(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function r(e){return"function"==typeof e}function o(e){return"number"==typeof e}function i(e){return"object"==typeof e&&null!==e}function s(e){return void 0===e}t.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.prototype.setMaxListeners=function(e){if(!o(e)||0>e||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},n.prototype.emit=function(e){var t,n,o,a,u,c;if(this._events||(this._events={}),"error"===e&&(!this._events.error||i(this._events.error)&&!this._events.error.length)){if(t=arguments[1],t instanceof Error)throw t;throw TypeError('Uncaught, unspecified "error" event.')}if(n=this._events[e],s(n))return!1;if(r(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:for(o=arguments.length,a=new Array(o-1),u=1;o>u;u++)a[u-1]=arguments[u];n.apply(this,a)}else if(i(n)){for(o=arguments.length,a=new Array(o-1),u=1;o>u;u++)a[u-1]=arguments[u];for(c=n.slice(),o=c.length,u=0;o>u;u++)c[u].apply(this,a)}return!0},n.prototype.addListener=function(e,t){var o;if(!r(t))throw TypeError("listener must be a function");if(this._events||(this._events={}),this._events.newListener&&this.emit("newListener",e,r(t.listener)?t.listener:t),this._events[e]?i(this._events[e])?this._events[e].push(t):this._events[e]=[this._events[e],t]:this._events[e]=t,i(this._events[e])&&!this._events[e].warned){var o;o=s(this._maxListeners)?n.defaultMaxListeners:this._maxListeners,o&&o>0&&this._events[e].length>o&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace())}return this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(e,t){function n(){this.removeListener(e,n),o||(o=!0,t.apply(this,arguments))}if(!r(t))throw TypeError("listener must be a function");var o=!1;return n.listener=t,this.on(e,n),this},n.prototype.removeListener=function(e,t){var n,o,s,a;if(!r(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(n=this._events[e],s=n.length,o=-1,n===t||r(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(i(n)){for(a=s;a-->0;)if(n[a]===t||n[a].listener&&n[a].listener===t){o=a;break}if(0>o)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(o,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},n.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(n=this._events[e],r(n))this.removeListener(e,n);else for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},n.prototype.listeners=function(e){var t;return t=this._events&&this._events[e]?r(this._events[e])?[this._events[e]]:this._events[e].slice():[]},n.listenerCount=function(e,t){var n;return n=e._events&&e._events[t]?r(e._events[t])?1:e._events[t].length:0}},{}],22:[function(e,t){function n(){c=!1,s.length?u=s.concat(u):d=-1,u.length&&r()}function r(){if(!c){var e=setTimeout(n);c=!0;for(var t=u.length;t;){for(s=u,u=[];++d1)for(var n=1;n=B&&ce>=r}function c(){if($)try{throw new Error}catch(e){var t=e.stack.split("\n"),n=t[0].indexOf("@")>0?t[1]:t[2],r=a(n);if(!r)return;return H=r[0],r[1]}}function d(e,t,n){return function(){return"undefined"!=typeof console&&"function"==typeof console.warn&&console.warn(t+" is deprecated, use "+n+" instead.",new Error("").stack),e.apply(e,arguments)}}function l(e){return e instanceof m?e:_(e)?x(e):k(e)}function p(){function e(e){t=e,i.source=e,z(n,function(t,n){l.nextTick(function(){e.promiseDispatch.apply(e,n)})},void 0),n=void 0,r=void 0}var t,n=[],r=[],o=ee(p.prototype),i=ee(m.prototype);if(i.promiseDispatch=function(e,o,i){var s=X(arguments);n?(n.push(s),"when"===o&&i[1]&&r.push(i[1])):l.nextTick(function(){t.promiseDispatch.apply(t,s)})},i.valueOf=function(){if(n)return i;var e=y(t);return g(e)&&(t=e),e},i.inspect=function(){return t?t.inspect():{state:"pending"}},l.longStackSupport&&$)try{throw new Error}catch(s){i.stack=s.stack.substring(s.stack.indexOf("\n")+1)}return o.promise=i,o.resolve=function(n){t||e(l(n))},o.fulfill=function(n){t||e(k(n))},o.reject=function(n){t||e(I(n))},o.notify=function(e){t||z(r,function(t,n){l.nextTick(function(){n(e)})},void 0)},o}function f(e){if("function"!=typeof e)throw new TypeError("resolver must be a function.");var t=p();try{e(t.resolve,t.reject,t.notify)}catch(n){t.reject(n)}return t.promise}function h(e){return f(function(t,n){for(var r=0,o=e.length;o>r;r++)l(e[r]).then(t,n)})}function m(e,t,n){void 0===t&&(t=function(e){return I(new Error("Promise does not support operation: "+e))}),void 0===n&&(n=function(){return{state:"unknown"}});var r=ee(m.prototype);if(r.promiseDispatch=function(n,o,i){var s;try{s=e[o]?e[o].apply(r,i):t.call(r,o,i)}catch(a){s=I(a)}n&&n(s)},r.inspect=n,n){var o=n();"rejected"===o.state&&(r.exception=o.reason),r.valueOf=function(){var e=n();return"pending"===e.state||"rejected"===e.state?r:e.value}}return r}function v(e,t,n,r){return l(e).then(t,n,r)}function y(e){if(g(e)){var t=e.inspect();if("fulfilled"===t.state)return t.value}return e}function g(e){return e instanceof m}function _(e){return n(e)&&"function"==typeof e.then}function E(e){return g(e)&&"pending"===e.inspect().state}function S(e){return!g(e)||"fulfilled"===e.inspect().state}function w(e){return g(e)&&"rejected"===e.inspect().state}function b(){ie.length=0,se.length=0,ue||(ue=!0)}function T(t,n){ue&&("object"==typeof e&&"function"==typeof e.emit&&l.nextTick.runAfter(function(){-1!==Y(se,t)&&(e.emit("unhandledRejection",n,t),ae.push(t))}),se.push(t),ie.push(n&&"undefined"!=typeof n.stack?n.stack:"(no stack) "+n))}function R(t){if(ue){var n=Y(se,t);-1!==n&&("object"==typeof e&&"function"==typeof e.emit&&l.nextTick.runAfter(function(){var r=Y(ae,t);-1!==r&&(e.emit("rejectionHandled",ie[n],t),ae.splice(r,1))}),se.splice(n,1),ie.splice(n,1))}}function I(e){var t=m({when:function(t){return t&&R(this),t?t(e):this}},function(){return this},function(){return{state:"rejected",reason:e}});return T(t,e),t}function k(e){return m({when:function(){return e},get:function(t){return e[t]},set:function(t,n){e[t]=n},"delete":function(t){delete e[t]},post:function(t,n){return null===t||void 0===t?e.apply(void 0,n):e[t].apply(e,n)},apply:function(t,n){return e.apply(t,n)},keys:function(){return ne(e)}},void 0,function(){return{state:"fulfilled",value:e}})}function x(e){var t=p();return l.nextTick(function(){try{e.then(t.resolve,t.reject,t.notify)}catch(n){t.reject(n)}}),t.promise}function C(e){return m({isDef:function(){}},function(t,n){return P(e,t,n)},function(){return l(e).inspect()})}function A(e,t,n){return l(e).spread(t,n)}function U(e){return function(){function t(e,t){var s;if("undefined"==typeof StopIteration){try{s=n[e](t)}catch(a){return I(a)}return s.done?l(s.value):v(s.value,o,i)}try{s=n[e](t)}catch(a){return r(a)?l(a.value):I(a)}return v(s,o,i)}var n=e.apply(this,arguments),o=t.bind(t,"next"),i=t.bind(t,"throw");return o()}}function M(e){l.done(l.async(e)())}function O(e){throw new W(e)}function L(e){return function(){return A([this,q(arguments)],function(t,n){return e.apply(t,n)})}}function P(e,t,n){return l(e).dispatch(t,n)}function q(e){return v(e,function(e){var t=0,n=p();return z(e,function(r,o,i){var s;g(o)&&"fulfilled"===(s=o.inspect()).state?e[i]=s.value:(++t,v(o,function(r){e[i]=r,0===--t&&n.resolve(e)},n.reject,function(e){n.notify({index:i,value:e})}))},void 0),0===t&&n.resolve(e),n.promise})}function j(e){if(0===e.length)return l.resolve();var t=l.defer(),n=0;return z(e,function(r,o,i){function s(e){t.resolve(e)}function a(){n--,0===n&&t.reject(new Error("Can't get fulfillment value from any promise, all promises were rejected."))}function u(e){t.notify({index:i,value:e})}var c=e[i];n++,v(c,s,a,u)},void 0),t.promise}function N(e){return v(e,function(e){return e=Z(e,l),v(q(Z(e,function(e){return v(e,G,G)})),function(){return e})})}function F(e){return l(e).allSettled()}function D(e,t){return l(e).then(void 0,void 0,t)}function V(e,t){return l(e).nodeify(t)}var $=!1;try{throw new Error}catch(K){$=!!K.stack}var H,W,B=c(),G=function(){},Q=function(){function t(){for(var e,t;r.next;)r=r.next,e=r.task,r.task=void 0,t=r.domain,t&&(r.domain=void 0,t.enter()),n(e,t);for(;u.length;)e=u.pop(),n(e);i=!1}function n(e,n){try{e()}catch(r){if(a)throw n&&n.exit(),setTimeout(t,0),n&&n.enter(),r;setTimeout(function(){throw r},0)}n&&n.exit()}var r={task:void 0,next:null},o=r,i=!1,s=void 0,a=!1,u=[];if(Q=function(t){o=o.next={task:t,domain:a&&e.domain,next:null},i||(i=!0,s())},"object"==typeof e&&"[object process]"===e.toString()&&e.nextTick)a=!0,s=function(){e.nextTick(t)};else if("function"==typeof setImmediate)s="undefined"!=typeof window?setImmediate.bind(window,t):function(){setImmediate(t)};else if("undefined"!=typeof MessageChannel){var c=new MessageChannel;c.port1.onmessage=function(){s=d,c.port1.onmessage=t,t()};var d=function(){c.port2.postMessage(0)};s=function(){setTimeout(t,0),d()}}else s=function(){setTimeout(t,0)};return Q.runAfter=function(e){u.push(e),i||(i=!0,s())},Q}(),J=Function.call,X=t(Array.prototype.slice),z=t(Array.prototype.reduce||function(e,t){var n=0,r=this.length;if(1===arguments.length)for(;;){if(n in this){t=this[n++];break}if(++n>=r)throw new TypeError}for(;r>n;n++)n in this&&(t=e(t,this[n],n));return t}),Y=t(Array.prototype.indexOf||function(e){for(var t=0;t2?X(arguments,1):n)}},l.Promise=f,l.promise=f,f.race=h,f.all=q,f.reject=I,f.resolve=l,l.passByCopy=function(e){return e},m.prototype.passByCopy=function(){return this},l.join=function(e,t){return l(e).join(t)},m.prototype.join=function(e){return l([this,e]).spread(function(e,t){if(e===t)return e;throw new Error("Can't join: not the same: "+e+" "+t)})},l.race=h,m.prototype.race=function(){return this.then(l.race)},l.makePromise=m,m.prototype.toString=function(){return"[object Promise]"},m.prototype.then=function(e,t,n){function r(t){try{return"function"==typeof e?e(t):t}catch(n){return I(n)}}function i(e){if("function"==typeof t){o(e,a);try{return t(e)}catch(n){return I(n)}}return I(e)}function s(e){return"function"==typeof n?n(e):e}var a=this,u=p(),c=!1;return l.nextTick(function(){a.promiseDispatch(function(e){c||(c=!0,u.resolve(r(e)))},"when",[function(e){c||(c=!0,u.resolve(i(e)))}])}),a.promiseDispatch(void 0,"when",[void 0,function(e){var t,n=!1;try{t=s(e)}catch(r){if(n=!0,!l.onerror)throw r;l.onerror(r)}n||u.notify(t)}]),u.promise},l.tap=function(e,t){return l(e).tap(t)},m.prototype.tap=function(e){return e=l(e),this.then(function(t){return e.fcall(t).thenResolve(t)})},l.when=v,m.prototype.thenResolve=function(e){return this.then(function(){return e})},l.thenResolve=function(e,t){return l(e).thenResolve(t)},m.prototype.thenReject=function(e){return this.then(function(){throw e})},l.thenReject=function(e,t){return l(e).thenReject(t)},l.nearer=y,l.isPromise=g,l.isPromiseAlike=_,l.isPending=E,m.prototype.isPending=function(){return"pending"===this.inspect().state},l.isFulfilled=S,m.prototype.isFulfilled=function(){return"fulfilled"===this.inspect().state},l.isRejected=w,m.prototype.isRejected=function(){return"rejected"===this.inspect().state};var ie=[],se=[],ae=[],ue=!0;l.resetUnhandledRejections=b,l.getUnhandledReasons=function(){return ie.slice()},l.stopUnhandledRejectionTracking=function(){b(),ue=!1},b(),l.reject=I,l.fulfill=k,l.master=C,l.spread=A,m.prototype.spread=function(e,t){return this.all().then(function(t){return e.apply(void 0,t)},t)},l.async=U,l.spawn=M,l["return"]=O,l.promised=L,l.dispatch=P,m.prototype.dispatch=function(e,t){var n=this,r=p();return l.nextTick(function(){n.promiseDispatch(r.resolve,e,t)}),r.promise},l.get=function(e,t){return l(e).dispatch("get",[t])},m.prototype.get=function(e){return this.dispatch("get",[e])},l.set=function(e,t,n){return l(e).dispatch("set",[t,n])},m.prototype.set=function(e,t){return this.dispatch("set",[e,t])},l.del=l["delete"]=function(e,t){return l(e).dispatch("delete",[t])},m.prototype.del=m.prototype["delete"]=function(e){return this.dispatch("delete",[e])},l.mapply=l.post=function(e,t,n){return l(e).dispatch("post",[t,n])},m.prototype.mapply=m.prototype.post=function(e,t){return this.dispatch("post",[e,t])},l.send=l.mcall=l.invoke=function(e,t){return l(e).dispatch("post",[t,X(arguments,2)])},m.prototype.send=m.prototype.mcall=m.prototype.invoke=function(e){return this.dispatch("post",[e,X(arguments,1)])},l.fapply=function(e,t){return l(e).dispatch("apply",[void 0,t])},m.prototype.fapply=function(e){return this.dispatch("apply",[void 0,e])},l["try"]=l.fcall=function(e){return l(e).dispatch("apply",[void 0,X(arguments,1)])},m.prototype.fcall=function(){return this.dispatch("apply",[void 0,X(arguments)])},l.fbind=function(e){var t=l(e),n=X(arguments,1);return function(){return t.dispatch("apply",[this,n.concat(X(arguments))])}},m.prototype.fbind=function(){var e=this,t=X(arguments);return function(){return e.dispatch("apply",[this,t.concat(X(arguments))])}},l.keys=function(e){return l(e).dispatch("keys",[])},m.prototype.keys=function(){return this.dispatch("keys",[])},l.all=q,m.prototype.all=function(){return q(this)},l.any=j,m.prototype.any=function(){return j(this)},l.allResolved=d(N,"allResolved","allSettled"),m.prototype.allResolved=function(){return N(this)},l.allSettled=F,m.prototype.allSettled=function(){return this.then(function(e){return q(Z(e,function(e){function t(){return e.inspect()}return e=l(e),e.then(t,t)}))})},l.fail=l["catch"]=function(e,t){return l(e).then(void 0,t)},m.prototype.fail=m.prototype["catch"]=function(e){return this.then(void 0,e)},l.progress=D,m.prototype.progress=function(e){return this.then(void 0,void 0,e)},l.fin=l["finally"]=function(e,t){return l(e)["finally"](t)},m.prototype.fin=m.prototype["finally"]=function(e){return e=l(e),this.then(function(t){return e.fcall().then(function(){return t})},function(t){return e.fcall().then(function(){throw t})})},l.done=function(e,t,n,r){return l(e).done(t,n,r)},m.prototype.done=function(t,n,r){var i=function(e){l.nextTick(function(){if(o(e,s),!l.onerror)throw e;l.onerror(e)})},s=t||n||r?this.then(t,n,r):this;"object"==typeof e&&e&&e.domain&&(i=e.domain.bind(i)),s.then(void 0,i)},l.timeout=function(e,t,n){return l(e).timeout(t,n)},m.prototype.timeout=function(e,t){var n=p(),r=setTimeout(function(){t&&"string"!=typeof t||(t=new Error(t||"Timed out after "+e+" ms"),t.code="ETIMEDOUT"),n.reject(t)},e);return this.then(function(e){clearTimeout(r),n.resolve(e)},function(e){clearTimeout(r),n.reject(e)},n.notify),n.promise},l.delay=function(e,t){return void 0===t&&(t=e,e=void 0),l(e).delay(t)},m.prototype.delay=function(e){return this.then(function(t){var n=p();return setTimeout(function(){n.resolve(t)},e),n.promise})},l.nfapply=function(e,t){return l(e).nfapply(t)},m.prototype.nfapply=function(e){var t=p(),n=X(e);return n.push(t.makeNodeResolver()),this.fapply(n).fail(t.reject),t.promise},l.nfcall=function(e){var t=X(arguments,1);return l(e).nfapply(t)},m.prototype.nfcall=function(){var e=X(arguments),t=p();return e.push(t.makeNodeResolver()),this.fapply(e).fail(t.reject),t.promise},l.nfbind=l.denodeify=function(e){var t=X(arguments,1);return function(){var n=t.concat(X(arguments)),r=p();return n.push(r.makeNodeResolver()),l(e).fapply(n).fail(r.reject),r.promise}},m.prototype.nfbind=m.prototype.denodeify=function(){var e=X(arguments);return e.unshift(this),l.denodeify.apply(void 0,e)},l.nbind=function(e,t){var n=X(arguments,2);return function(){function r(){return e.apply(t,arguments)}var o=n.concat(X(arguments)),i=p();return o.push(i.makeNodeResolver()),l(r).fapply(o).fail(i.reject),i.promise}},m.prototype.nbind=function(){var e=X(arguments,0);return e.unshift(this),l.nbind.apply(void 0,e)},l.nmapply=l.npost=function(e,t,n){return l(e).npost(t,n)},m.prototype.nmapply=m.prototype.npost=function(e,t){var n=X(t||[]),r=p();return n.push(r.makeNodeResolver()),this.dispatch("post",[e,n]).fail(r.reject),r.promise},l.nsend=l.nmcall=l.ninvoke=function(e,t){var n=X(arguments,2),r=p();return n.push(r.makeNodeResolver()),l(e).dispatch("post",[t,n]).fail(r.reject),r.promise},m.prototype.nsend=m.prototype.nmcall=m.prototype.ninvoke=function(e){var t=X(arguments,1),n=p();return t.push(n.makeNodeResolver()),this.dispatch("post",[e,t]).fail(n.reject),n.promise},l.nodeify=V,m.prototype.nodeify=function(e){return e?void this.then(function(t){l.nextTick(function(){e(null,t)})},function(t){l.nextTick(function(){e(t)})}):this},l.noConflict=function(){throw new Error("Q.noConflict only works when Q is used as a global")};var ce=c();return l})}).call(this,e("_process"))},{_process:22}]},{},[1]);