UNPKG

twitch-js

Version:

Javascript library for the Twitch Messaging Interface.

3 lines (2 loc) 46.7 kB
import t from"eventemitter3";import e from"p-event";import n from"lodash/uniq";import r from"pino";import i from"ws";import o from"p-queue";import{parse as s}from"tekko/dist/parse";import a from"camelcase-keys";import u from"lodash/isEmpty";import c from"lodash/toLower";import E from"invariant";import _ from"lodash/conformsTo";import l from"lodash/defaults";import h from"lodash/isString";import O from"lodash/isFinite";import S from"lodash/isBoolean";import d from"lodash/isNil";import T from"lodash/random";import p from"lodash/gt";import f from"lodash/toNumber";import m from"lodash/toUpper";import N from"lodash/camelCase";import I from"lodash/replace";import A from"lodash/isFunction";import{CustomError as v}from"ts-custom-error";import C from"cross-fetch";import{stringify as R}from"qs";import y from"lodash/isUndefined";var D=function(t,e){return D=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},D(t,e)};function g(t,e){function n(){this.constructor=t}D(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}var U,L,M,b,w,P,F,G,H,B=function(){return B=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var i in e=arguments[n])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t},B.apply(this,arguments)};function W(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(t,r[i])&&(n[r[i]]=t[r[i]])}return n}function Y(t,e,n,r){return new(n||(n=Promise))((function(i,o){function s(t){try{u(r.next(t))}catch(t){o(t)}}function a(t){try{u(r.throw(t))}catch(t){o(t)}}function u(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(s,a)}u((r=r.apply(t,e||[])).next())}))}function k(t,e){var n,r,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,r=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]<i[3])){s.label=o[1];break}if(6===o[0]&&s.label<i[1]){s.label=i[1],i=o;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(o);break}i[2]&&s.ops.pop(),s.trys.pop();continue}o=e.call(t,s)}catch(t){o=[6,t],r=0}finally{n=i=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,a])}}}function V(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,i,o=n.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(r=o.next()).done;)s.push(r.value)}catch(t){i={error:t}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s}function j(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(V(arguments[e]));return t}!function(t){t.tags="twitch.tv/tags",t.commands="twitch.tv/commands",t.membership="twitch.tv/membership"}(U||(U={})),function(t){t.JOIN="JOIN",t.MODE="MODE",t.PART="PART",t.NAMES="353",t.NAMES_END="366"}(L||(L={})),function(t){t.CLEAR_CHAT="CLEARCHAT",t.GLOBALUSERSTATE="GLOBALUSERSTATE",t.PRIVATE_MESSAGE="PRIVMSG",t.ROOM_STATE="ROOMSTATE",t.USER_NOTICE="USERNOTICE",t.USER_STATE="USERSTATE"}(M||(M={})),function(t){t.WELCOME="001",t.PING="PING",t.PONG="PONG",t.WHISPER="WHISPER"}(b||(b={})),function(t){t.CLEAR_CHAT="CLEARCHAT",t.CLEAR_MESSAGE="CLEARMSG",t.HOST_TARGET="HOSTTARGET",t.NOTICE="NOTICE",t.RECONNECT="RECONNECT",t.ROOM_STATE="ROOMSTATE",t.USER_NOTICE="USERNOTICE",t.USER_STATE="USERSTATE"}(w||(w={})),function(t){t.WELCOME="001",t.PING="PING",t.PONG="PONG",t.RECONNECT="RECONNECT",t.WHISPER="PRIVMSG #jtv",t.JOIN="JOIN",t.MODE="MODE",t.PART="PART",t.NAMES="353",t.NAMES_END="366",t.CLEAR_CHAT="CLEARCHAT",t.CLEAR_MESSAGE="CLEARMSG",t.GLOBALUSERSTATE="GLOBALUSERSTATE",t.HOST_TARGET="HOSTTARGET",t.NOTICE="NOTICE",t.PRIVATE_MESSAGE="PRIVMSG",t.ROOM_STATE="ROOMSTATE",t.USER_NOTICE="USERNOTICE",t.USER_STATE="USERSTATE"}(P||(P={})),function(t){t.RAW="RAW",t.ALL="*",t.CONNECTED="CONNECTED",t.DISCONNECTED="DISCONNECTED",t.RECONNECT="RECONNECT",t.AUTHENTICATED="AUTHENTICATED",t.AUTHENTICATION_FAILED="AUTHENTICATION_FAILED",t.GLOBALUSERSTATE="GLOBALUSERSTATE",t.ERROR_ENCOUNTERED="ERROR_ENCOUNTERED",t.PARSE_ERROR_ENCOUNTERED="PARSE_ERROR_ENCOUNTERED",t.ANON_GIFT_PAID_UPGRADE="ANON_GIFT_PAID_UPGRADE",t.GIFT_PAID_UPGRADE="GIFT_PAID_UPGRADE",t.RAID="RAID",t.RESUBSCRIPTION="RESUBSCRIPTION",t.RITUAL="RITUAL",t.SUBSCRIPTION="SUBSCRIPTION",t.SUBSCRIPTION_GIFT="SUBSCRIPTION_GIFT",t.SUBSCRIPTION_GIFT_COMMUNITY="SUBSCRIPTION_GIFT_COMMUNITY",t.ROOM_MODS="ROOM_MODS",t.MOD_GAINED="MOD_GAINED",t.MOD_LOST="MOD_LOST",t.USER_BANNED="USER_BANNED",t.CHEER="CHEER",t.HOST_ON="HOST_ON",t.HOST_OFF="HOST_OFF",t.HOSTED="HOSTED",t.HOSTED_WITHOUT_VIEWERS="HOSTED/WITHOUT_VIEWERS",t.HOSTED_WITH_VIEWERS="HOSTED/WITH_VIEWERS",t.HOSTED_AUTO="HOSTED/AUTO"}(F||(F={})),function(t){t.BAN="ban",t.BLOCK="block",t.CLEAR="clear",t.COLOR="color",t.COMMERCIAL="commercial",t.DELETE="delete",t.EMOTE_ONLY="emoteonly",t.EMOTE_ONLY_OFF="emoteonlyoff",t.FOLLOWERS_ONLY="followers",t.FOLLOWERS_ONLY_OFF="followersoff",t.HELP="help",t.HOST="host",t.MARKER="marker",t.ME="me",t.MOD="mod",t.MODS="mods",t.R9K="r9kbeta",t.R9K_OFF="r9kbetaoff",t.RAID="raid",t.SLOW="slow",t.SLOW_OFF="slowoff",t.SUBSCRIBERS="subscribers",t.SUBSCRIBERS_OFF="subscribersoff",t.TIMEOUT="timeout",t.UNBAN="unban",t.UNBLOCK="unblock",t.UNHOST="unhost",t.UNMOD="unmod",t.UNRAID="unraid",t.UNVIP="unvip",t.VIP="vip",t.VIPS="vips",t.WHISPER="w"}(G||(G={})),function(t){t.ALREADY_BANNED="already_banned",t.ALREADY_EMOTE_ONLY_OFF="already_emote_only_off",t.ALREADY_EMOTE_ONLY_ON="already_emote_only_on",t.ALREADY_R9K_OFF="already_r9k_off",t.ALREADY_R9K_ON="already_r9k_on",t.ALREADY_SUBS_OFF="already_subs_off",t.ALREADY_SUBS_ON="already_subs_on",t.BAD_HOST_HOSTING="bad_host_hosting",t.BAD_MOD_MOD="bad_mod_mod",t.BAN_SUCCESS="ban_success",t.BAD_UNBAN_NO_BAN="bad_unban_no_ban",t.COLOR_CHANGED="color_changed",t.CMDS_AVAILABLE="cmds_available",t.COMMERCIAL_SUCCESS="commercial_success",t.EMOTE_ONLY_OFF="emote_only_off",t.EMOTE_ONLY_ON="emote_only_on",t.FOLLOWERS_OFF="followers_off",t.FOLLOWERS_ON="followers_on",t.FOLLOWERS_ONZERO="followers_onzero",t.HOST_OFF="host_off",t.HOST_ON="host_on",t.HOSTS_REMAINING="hosts_remaining",t.MSG_CHANNEL_SUSPENDED="msg_channel_suspended",t.MOD_SUCCESS="mod_success",t.NOT_HOSTING="not_hosting",t.R9K_OFF="r9k_off",t.R9K_ON="r9k_on",t.ROOM_MODS="room_mods",t.SLOW_OFF="slow_off",t.SLOW_ON="slow_on",t.SUBS_OFF="subs_off",t.SUBS_ON="subs_on",t.TIMEOUT_SUCCESS="timeout_success",t.UNBAN_SUCCESS="unban_success",t.UNMOD_SUCCESS="unmod_success",t.UNRAID_SUCCESS="unraid_success",t.UNRECOGNIZED_CMD="unrecognized_cmd"}(H||(H={}));var J,K,x=Object.entries(H).reduce((function(t,e){var n,r=V(e,2),i=r[0],o=r[1];return B(B({},t),((n={})[i]=o.toUpperCase(),n))}),{}),q=Object.keys(H).reduce((function(t,e){var n;return B(B({},t),((n={})[e]=e,n[P.NOTICE+"/"+e.toUpperCase()]=e,n))}),{});!function(t){t.CHEER="CHEER",t.HOSTED_WITHOUT_VIEWERS="HOSTED_WITHOUT_VIEWERS",t.HOSTED_WITH_VIEWERS="HOSTED_WITH_VIEWERS",t.HOSTED_AUTO="HOSTED_AUTO"}(J||(J={})),function(t){t.ANON_GIFT_PAID_UPGRADE="anongiftpaidupgrade",t.GIFT_PAID_UPGRADE="giftpaidupgrade",t.RAID="raid",t.RESUBSCRIPTION="resub",t.RITUAL="ritual",t.SUBSCRIPTION="sub",t.SUBSCRIPTION_GIFT="subgift",t.SUBSCRIPTION_GIFT_COMMUNITY="submysterygift"}(K||(K={}));var Z,Q,z=Object.keys(K).reduce((function(t,e){var n;return B(B({},t),((n={})[e]=e,n[P.USER_NOTICE+"/"+e]=e,n))}),{}),X=B(B(B(B(B(B(B(B({},L),M),b),w),F),q),J),z);!function(t){t[t.admin=0]="admin",t[t.broadcaster=1]="broadcaster",t[t.globalMod=2]="globalMod",t[t.moderator=3]="moderator",t[t.partner=4]="partner",t[t.premium=5]="premium",t[t.staff=6]="staff",t[t.subGifter=7]="subGifter",t[t.turbo=8]="turbo",t[t.vip=9]="vip"}(Z||(Z={})),function(t){t[t.bits=0]="bits",t[t.bitsLeader=1]="bitsLeader",t[t.subscriber=2]="subscriber"}(Q||(Q={}));var $,tt=function(t){void 0===t&&(t={});var e=t.name,n=W(t,["name"]),i=["TwitchJS"].concat(e||[]).join("/"),o=r(B({name:i,prettyPrint:!0,level:"info"},n));return o.profile=function(t){var e=Date.now();return t&&o.info(t),{done:function(t,n){var r=t+" ("+(Date.now()-e)+"ms)";n?o.error(r,n):o.info(r)}}},o},et=function(t){var e=new Date(parseInt(t,10));return"Invalid Date"!==e.toString()?e:new Date},nt=function(t,e){return void 0===e&&(e=""),t.split(/\r?\n/g).reduce((function(t,n){if(!n.length)return t;var r=s(n),i=r.command,o=r.tags,E=void 0===o?{}:o,_=r.prefix,l=void 0===_?{name:void 0,user:void 0,host:void 0}:_,h=l.name,O=l.user,S=l.host,d=V(r.params,2),T=d[0],p=d[1],f=String(E["tmi-sent-ts"])||Date.now().toString(),m=u(E)?{}:a(E),N=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return t.reduce((function(t,e){return"string"!=typeof e?t:"tmi.twitch.tv"===e?"tmi.twitch.tv":c(e).split(".")[0]}),void 0)}(S,h,O,m.login,m.username,m.displayName);return j(t,[{_raw:n,timestamp:et(f),command:i,event:i,channel:"*"!==T?T:"",username:N,isSelf:"string"==typeof N&&c(e)===N,tags:m,message:p}])}),[])},rt=function(t){return null==t?"TWITCHJS":t.startsWith("oauth:")?t:"oauth:"+t};!function(t){t.RAW="RAW",t.ALL="*",t.CONNECTED="CONNECTED",t.DISCONNECTED="DISCONNECTED",t.RECONNECT="RECONNECT",t.AUTHENTICATED="AUTHENTICATED",t.AUTHENTICATION_FAILED="AUTHENTICATION_FAILED",t.ERROR_ENCOUNTERED="ERROR_ENCOUNTERED"}($||($={}));var it,ot,st,at,ut,ct=B(B({},P),$),Et=function(t){function e(e){var n=t.call(this)||this;n._clientPriority=100,n._options=function(t){var e,n={username:function(t){return d(t)||h(t)},token:function(t){return d(t)||h(t)},server:h,port:O,ssl:S,isKnown:S,isVerified:S},r=l(B(B({},t),{username:(e=t.username,u(e)||"justinfan"===e?"justinfan"+T(8e4,81e3):e),token:t.token?rt(t.token):void 0}),{server:"irc-ws.chat.twitch.tv",port:443,ssl:!0,isKnown:!1,isVerified:!1});return E(_(r,n),"[twitch-js/Chat/Client] options: Expected valid options"),r}(e);var r=n._options,s=r.ssl,a=r.server,c=r.port,p=r.log;n._log=tt(B({name:"Chat/Client"},p));var f=s?"wss":"ws";return n._ws=new i(f+"://"+a+":"+c),n._ws.onopen=n._handleOpen.bind(n),n._ws.onmessage=n._handleMessage.bind(n),n._ws.onerror=n._handleError.bind(n),n._ws.onclose=n._handleClose.bind(n),n._queueAuthenticate=n._options.isVerified?new o({intervalCap:200,interval:1e4}):new o({intervalCap:20,interval:1e4}),n._queueJoin=n._options.isVerified?new o({intervalCap:2e3,interval:1e4}):new o({intervalCap:20,interval:1e4}),n._queue=new o({intervalCap:20,interval:3e4}),n._moderatorQueue=new o({intervalCap:100,interval:3e4}),n}return g(e,t),e.prototype.isReady=function(){return 1===this._ws.readyState},e.prototype.send=function(t,e){return Y(this,void 0,void 0,(function(){var n,r,i,o=this;return k(this,(function(s){switch(s.label){case 0:return s.trys.push([0,2,,3]),n=B({priority:0,isModerator:!1},e),r=n.priority,i=n.isModerator,[4,(t.startsWith("JOIN")?this._queueJoin:t.startsWith("PASS")?this._queueAuthenticate:i&&this._moderatorQueue?this._moderatorQueue:this._queue).add((function(){return o._ws.send(t)}),{priority:r})];case 1:return s.sent(),this._log.trace("< "+t),[3,3];case 2:return s.sent(),this._log.error("< "+t),[3,3];case 3:return[2]}}))}))},e.prototype.disconnect=function(){var t,e;this._queueAuthenticate.pause(),this._queueJoin.pause(),this._queue.pause(),null===(t=this._moderatorQueue)||void 0===t||t.pause(),clearTimeout(this._queueAuthenticate._timeoutId),clearTimeout(this._queueJoin._timeoutId),clearTimeout(this._queue._timeoutId),clearTimeout(null===(e=this._moderatorQueue)||void 0===e?void 0:e._timeoutId),this._handleHeartbeatReset(),this._ws.close()},e.prototype._handleOpen=function(){var t=this._clientPriority;this.send("CAP REQ :"+Object.values(U).join(" "),{priority:t});var e=this._options,n=e.token,r=e.username;n&&r&&this.send("PASS "+n,{priority:t}),this.send("NICK "+r,{priority:t}),this._handleHeartbeat()},e.prototype._handleMessage=function(t){var e=this,n=t.data.toString();this._log.trace("> "+n.trim());var r=this._options,i=r.token,o=r.username,s=this._clientPriority;this._handleHeartbeat();var a=[];try{a=nt(n,this._options.username)}catch(t){this._log.error("\nAn error occurred while attempting to parse a message from Twitch. Please use the following stack trace and raw message to resolve the bug in the TwitchJS source code, and then issue a pull request at https://github.com/twitch-js/twitch-js/compare\n\nStack trace:\n"+t+"\n\nRaw message:\n"+n),this.emit(ct.ERROR_ENCOUNTERED,t)}a.forEach((function(t){var n=t.command||"";e._log.debug(B(B({},t),{_raw:void 0}),"> %s",n),!function(t){return void 0!==t&&t.command===P.NOTICE&&""===t.channel&&"Login authentication failed"===t.message}(t)?t.command===P.PING?e.send("PONG :tmi.twitch.tv",{priority:s}):i||t.command!==P.WELCOME?t.command===P.GLOBALUSERSTATE?(e._multiEmit([ct.ALL,ct.GLOBALUSERSTATE],B(B({},t),{event:ct.GLOBALUSERSTATE})),i&&o&&e._multiEmit([ct.ALL,ct.CONNECTED],B(B({},t),{event:ct.CONNECTED}))):t.command===P.RECONNECT?e._multiEmit([ct.ALL,ct.RECONNECT],B(B({},t),{event:ct.RECONNECT})):e.emit(ct.ALL,t):e._multiEmit([ct.ALL,ct.CONNECTED],B(B({},t),{event:ct.CONNECTED})):(e._multiEmit([ct.ALL,ct.AUTHENTICATION_FAILED],B(B({},t),{event:ct.AUTHENTICATION_FAILED})),e.disconnect())})),this.emit(ct.RAW,n)},e.prototype._handleError=function(t){this._log.error(t)},e.prototype._handleClose=function(t){this.emit(ct.DISCONNECTED)},e.prototype._handleHeartbeat=function(){var t=this;this._handleHeartbeatReset();var e=this._clientPriority;this._heartbeatTimeoutId=setTimeout((function(){t.send(P.PING,{priority:e})}),15e4),this._reconnectTimeoutId=setTimeout((function(){t.emit(ct.RECONNECT)}),151e3)},e.prototype._handleHeartbeatReset=function(){this._heartbeatTimeoutId&&clearTimeout(this._heartbeatTimeoutId),this._reconnectTimeoutId&&clearTimeout(this._reconnectTimeoutId)},e.prototype._multiEmit=function(t,e){var n=this;Array.isArray(t)?t.forEach((function(t){return n.emit(t,e)})):this.emit(t,e)},e}(t),_t=new RegExp("^msgParam(\\w+)"),lt=/:.+@jtv\.tmi\.twitch\.tv PRIVMSG #?(\w+) :(\w+) is now (?:(auto) )?hosting[A-z ]+(\d+)?/,ht=Symbol("connect"),Ot=Symbol("connected"),St=Symbol("disconnect"),dt=Symbol("disconnected"),Tt=Symbol("reconnect"),pt=function(t){return"string"==typeof t?I(t,/\\[sn]/g," "):void 0},ft=function(t){var e=parseInt(t,10);return O(e)?e:void 0},mt=function(t){return"1"===t},Nt=function(t){return V(t.split(": "),2)[1].split(", ")},It=function(t){return Object.entries(t).reduce((function(t,e){var n,r,i,o,s,a,u=V(e,2),c=u[0],E=u[1];switch(c){case"followersOnly":return B(B({},t),((n={})[c]=0===(a=parseInt(E,10))||a>0&&a,n));case"broadcasterLang":return B(B({},t),((r={})[c]=pt(E),r));case"slow":return B(B({},t),((i={})[c]=ft(E),i));case"emoteOnly":case"r9k":case"subsOnly":return B(B({},t),((o={})[c]=mt(E),o));default:return B(B({},t),((s={})[c]=E,s))}}),{})},At=function(t){return B(B({},t),{badges:(i=t.badges,"string"==typeof i?i.split(",").reduce((function(t,e){var n,r,i,o=V(e.split("/"),2),s=o[0],a=o[1];if(void 0===a)return t;var u=N(s);return B(B({},t),u in Z?((n={})[u]=mt(a),n):u in Q?((r={})[u]=parseInt(a,10),r):((i={})[u]=a,i))}),{}):{}),bits:ft(t.bits),color:t.color,displayName:t.displayName,emotes:(r=t.emotes,"string"!=typeof r?[]:r.split("/").reduce((function(t,e){var n=V(e.split(":"),2),r=n[0],i=n[1];return r?j(t,i.split(",").map((function(t){var e=V(t.split("-"),2),n=e[0],i=e[1];return{id:r,start:parseInt(n,10),end:parseInt(i,10)}}))):t}),[])),emoteSets:(n=t.emoteSets,"string"==typeof n?n.split(","):[]),userType:(e=t.userType,"string"==typeof e?e:void 0),username:t.displayName?c(t.displayName):t.username,isModerator:"1"===t.mod});var e,n,r,i},vt=function(t){return B(B({},t),At(t))},Ct=At,Rt=function(t){var e,n=t.tags,r=W(t,["tags"]),i=void 0!==(e=t)&&e.command===P.NOTICE&&""===e.channel&&"Login authentication failed"===e.message?B(B({},n),{msgId:c(X.AUTHENTICATION_FAILED)}):n,o=m(i.msgId);return i.msgId===H.ROOM_MODS?B(B({},r),{command:P.NOTICE,event:q.ROOM_MODS,tags:i,mods:Nt(r.message)}):B(B({},r),{command:P.NOTICE,event:o,tags:i})},yt=function(t){var e=t.tags,n=W(t,["tags"]);return B(B({},n),{command:P.USER_STATE,event:P.USER_STATE,tags:At(e)})},Dt=function(t){var e=P.USER_NOTICE,n=B(B({},Ct(t.tags)),{systemMsg:pt(t.tags.systemMsg)}),r=pt(t.tags.systemMsg)||"",i=function(t){return Object.entries(t).reduce((function(t,e){var n,r,i=V(e,2),o=i[0],s=i[1],a=V(_t.exec(o)||[],2)[1];switch(a){case"Months":case"MassGiftCount":case"PromoGiftTotal":case"SenderCount":case"ViewerCount":return B(B({},t),((n={})[N(a)]=ft(s),n));case void 0:return t;default:return B(B({},t),((r={})[N(a)]=pt(s),r))}}),{})}(n);switch(n.msgId){case K.ANON_GIFT_PAID_UPGRADE:return B(B({},t),{command:e,event:F.ANON_GIFT_PAID_UPGRADE,parameters:i,tags:n,systemMessage:r});case K.GIFT_PAID_UPGRADE:return B(B({},t),{command:e,event:F.GIFT_PAID_UPGRADE,parameters:i,tags:n,systemMessage:r});case K.RAID:return B(B({},t),{command:e,event:F.RAID,parameters:i,tags:n,systemMessage:r});case K.RESUBSCRIPTION:return B(B({},t),{command:e,event:F.RESUBSCRIPTION,parameters:i,tags:n,systemMessage:r});case K.RITUAL:return B(B({},t),{command:e,event:F.RITUAL,parameters:i,tags:n,systemMessage:r});case K.SUBSCRIPTION_GIFT_COMMUNITY:return B(B({},t),{command:e,event:F.SUBSCRIPTION_GIFT_COMMUNITY,parameters:i,tags:n,systemMessage:r});case K.SUBSCRIPTION_GIFT:return B(B({},t),{command:e,event:F.SUBSCRIPTION_GIFT,parameters:i,tags:n,systemMessage:r});case K.SUBSCRIPTION:return B(B({},t),{command:e,event:F.SUBSCRIPTION,parameters:i,tags:n,systemMessage:r});default:return B(B({},t),{command:e,event:m(n.msgId),tags:n,parameters:i,systemMessage:r})}},gt=function(t){return"string"!=typeof t||0===t.length?"":(t=t.toLowerCase()).startsWith("#")?t:"#"+t},Ut=function(t){return null==t?"TWITCHJS":t.startsWith("oauth:")?t:"oauth:"+t},Lt=function(t){var e,n={username:function(t){return d(t)||h(t)},token:function(t){return d(t)||h(t)},isKnown:S,isVerified:S,connectionTimeout:O,joinTimeout:O,onAuthenticationFailure:A},r=l(B(B({},t),{username:t.username?(e=t.username,u(e)||"justinfan"===e?"justinfan"+T(8e4,81e3):e):void 0,token:t.token?Ut(t.token):void 0}),{isKnown:!1,isVerified:!1,connectionTimeout:5e3,joinTimeout:1e3,onAuthenticationFailure:function(){return Promise.reject()}});return E(_(r,n),"[twitch-js/Chat] options: Expected valid options"),r},Mt=function(t){if(!(t=gt(t)))throw new Error("Channel required");return t},bt=function(t){function e(e){var n=t.call(this,e)||this;return n.timestamp=new Date,Object.defineProperty(n,"name",{value:"TwitchJSError"}),n}return g(e,t),e}(v),wt=function(t){function e(e,n){var r=t.call(this,e)||this;return r.body=n,Object.defineProperty(r,"name",{value:"TwitchJSAuthenticationError"}),r}return g(e,t),e}(bt),Pt=function(t){function e(e,n){var r=t.call(this,e)||this;return r.body=n,Object.defineProperty(r,"name",{value:"TwitchJSChatError"}),r}return g(e,t),e}(bt);(function(t){function e(e,n){var r=t.call(this,e)||this;return r.body=n,Object.defineProperty(r,"name",{value:"TwitchJSChatParseError"}),r}g(e,t)})(bt),function(t){function e(e,n){var r=t.call(this,e)||this;return r.body=n,Object.defineProperty(r,"name",{value:"TwitchJSChatJoinError"}),r}g(e,t)}(bt),function(t){function e(e,n){var r=t.call(this,e)||this;return r.body=n,Object.defineProperty(r,"name",{value:"TwitchJSChatTimeoutError"}),r}g(e,t)}(bt);!function(t){t[t.WAITING=0]="WAITING",t[t.CONNECTING=1]="CONNECTING",t[t.RECONNECTING=2]="RECONNECTING",t[t.CONNECTED=3]="CONNECTED",t[t.DISCONNECTING=4]="DISCONNECTING",t[t.DISCONNECTED=5]="DISCONNECTED"}(it||(it={})),function(t){t.ALREADY_BANNED="NOTICE/ALREADY_BANNED",t.ALREADY_EMOTE_ONLY_OFF="NOTICE/ALREADY_EMOTE_ONLY_OFF",t.ALREADY_EMOTE_ONLY_ON="NOTICE/ALREADY_EMOTE_ONLY_ON",t.ALREADY_R9K_OFF="NOTICE/ALREADY_R9K_OFF",t.ALREADY_R9K_ON="NOTICE/ALREADY_R9K_ON",t.ALREADY_SUBS_OFF="NOTICE/ALREADY_SUBS_OFF",t.ALREADY_SUBS_ON="NOTICE/ALREADY_SUBS_ON",t.BAD_HOST_HOSTING="NOTICE/BAD_HOST_HOSTING",t.BAD_MOD_MOD="NOTICE/BAD_MOD_MOD",t.BAN_SUCCESS="NOTICE/BAN_SUCCESS",t.BAD_UNBAN_NO_BAN="NOTICE/BAD_UNBAN_NO_BAN",t.COLOR_CHANGED="NOTICE/COLOR_CHANGED",t.CMDS_AVAILABLE="NOTICE/CMDS_AVAILABLE",t.COMMERCIAL_SUCCESS="NOTICE/COMMERCIAL_SUCCESS",t.EMOTE_ONLY_OFF="NOTICE/EMOTE_ONLY_OFF",t.EMOTE_ONLY_ON="NOTICE/EMOTE_ONLY_ON",t.FOLLOWERS_OFF="NOTICE/FOLLOWERS_OFF",t.FOLLOWERS_ON="NOTICE/FOLLOWERS_ON",t.FOLLOWERS_ONZERO="NOTICE/FOLLOWERS_ONZERO",t.HOST_OFF="NOTICE/HOST_OFF",t.HOST_ON="NOTICE/HOST_ON",t.HOSTS_REMAINING="NOTICE/HOSTS_REMAINING",t.MSG_CHANNEL_SUSPENDED="NOTICE/MSG_CHANNEL_SUSPENDED",t.MOD_SUCCESS="NOTICE/MOD_SUCCESS",t.NOT_HOSTING="NOTICE/NOT_HOSTING",t.R9K_OFF="NOTICE/R9K_OFF",t.R9K_ON="NOTICE/R9K_ON",t.ROOM_MODS="NOTICE/ROOM_MODS",t.SLOW_OFF="NOTICE/SLOW_OFF",t.SLOW_ON="NOTICE/SLOW_ON",t.SUBS_OFF="NOTICE/SUBS_OFF",t.SUBS_ON="NOTICE/SUBS_ON",t.TIMEOUT_SUCCESS="NOTICE/TIMEOUT_SUCCESS",t.UNBAN_SUCCESS="NOTICE/UNBAN_SUCCESS",t.UNMOD_SUCCESS="NOTICE/UNMOD_SUCCESS",t.UNRAID_SUCCESS="NOTICE/UNRAID_SUCCESS",t.UNRECOGNIZED_CMD="NOTICE/UNRECOGNIZED_CMD"}(ot||(ot={})),function(t){t.CHEER="PRIVMSG/CHEER",t.HOSTED_WITHOUT_VIEWERS="PRIVMSG/HOSTED_WITHOUT_VIEWERS",t.HOSTED_WITH_VIEWERS="PRIVMSG/HOSTED_WITH_VIEWERS",t.HOSTED_AUTO="PRIVMSG/HOSTED_AUTO"}(st||(st={})),function(t){t.ANON_GIFT_PAID_UPGRADE="USERNOTICE/ANON_GIFT_PAID_UPGRADE",t.GIFT_PAID_UPGRADE="USERNOTICE/GIFT_PAID_UPGRADE",t.RAID="USERNOTICE/RAID",t.RESUBSCRIPTION="USERNOTICE/RESUBSCRIPTION",t.RITUAL="USERNOTICE/RITUAL",t.SUBSCRIPTION="USERNOTICE/SUBSCRIPTION",t.SUBSCRIPTION_GIFT="USERNOTICE/SUBSCRIPTION_GIFT",t.SUBSCRIPTION_GIFT_COMMUNITY="USERNOTICE/SUBSCRIPTION_GIFT_COMMUNITY"}(at||(at={}));var Ft,Gt=function(r){function i(e){var n=r.call(this)||this;return n._internalEmitter=new t,n._readyState=it.WAITING,n._connectionAttempts=0,n._channelState={},n._isAuthenticated=!1,n._handleConnect=function(){var t=n._log.profile("connecting ...");n._readyState=it.CONNECTING,n._connectionAttempts+=1,n._client&&n._client.removeAllListeners(),n._client=new Et(n._options),n._client.once(ct.DISCONNECTED,(function(){return n._internalEmitter.emit(St)})),n._client.once(ct.RECONNECT,(function(){return n._internalEmitter.emit(Tt)})),n._client.once(ct.AUTHENTICATION_FAILED,n._handleClientAuthenticationFailure),n._client.once(ct.CONNECTED,(function(e){if(n._readyState=it.CONNECTED,n._options.token&&n._options.username){var r=(o=(i=e).tags,s=W(i,["tags"]),B(B({},s),{command:P.GLOBALUSERSTATE,event:P.GLOBALUSERSTATE,tags:vt(o)}));n._globalUserState=r.tags,n._isAuthenticated=!0}var i,o,s;n._handleJoinsAfterConnect(),n._internalEmitter.emit(Ot),t.done("connected")})),n._client.on(ct.ALL,n._handleClientMessage,n)},n._handleDisconnect=function(){var t,e;n._log.info("disconnecting ..."),n._readyState=it.DISCONNECTING,n._isAuthenticated=!1,n._clearChannelState(),null===(t=n._client)||void 0===t||t.once(ct.DISCONNECTED,(function(){n._internalEmitter.emit(dt),n._readyState=it.DISCONNECTED,n._log.info("disconnected")})),null===(e=n._client)||void 0===e||e.disconnect()},n._handleReconnect=function(){var t,e,r;n._log.info("reconnecting ..."),n._readyState=it.RECONNECTING,null===(t=n._client)||void 0===t||t.removeAllListeners(),null===(e=n._client)||void 0===e||e.once(ct.DISCONNECTED,(function(){n._internalEmitter.emit(ht)})),null===(r=n._client)||void 0===r||r.disconnect()},n._handleClientAuthenticationFailure=function(t){return Y(n,void 0,void 0,(function(){var e,n,r,i,o,s;return k(this,(function(a){switch(a.label){case 0:return a.trys.push([0,2,,3]),this._log.info("retrying ..."),[4,null===(s=(o=this._options).onAuthenticationFailure)||void 0===s?void 0:s.call(o)];case 1:return(e=a.sent())&&(this._log.info("re-authenticating ..."),this._options=B(B({},this._options),{token:e})),this._internalEmitter.emit(ht),[3,3];case 2:return n=a.sent(),r=n||t,i=new wt((null==t?void 0:t.message)||"Login authentication failed",t),this._internalEmitter.emit(X.ERROR_ENCOUNTERED,i),this._log.error(r,"authentication failed"),[3,3];case 3:return[2]}}))}))},n._options=Lt(e),n._log=tt(B({name:"Chat"},n._options.log)),n._internalEmitter.on(ht,n._handleConnect),n._internalEmitter.on(St,n._handleDisconnect),n._internalEmitter.on(Tt,n._handleReconnect),n}return g(i,r),i.prototype.connect=function(){return this._connectionInProgress||(this._connectionInProgress=e(this._internalEmitter,Ot,{rejectionEvents:[X.ERROR_ENCOUNTERED],timeout:this._options.connectionTimeout}),this._internalEmitter.emit(ht)),this._connectionInProgress},i.prototype.updateOptions=function(t){var e=this._options,n=e.token,r=e.username;this._options=Lt(B(B({},t),{token:n,username:r}))},i.prototype.send=function(t,e){if(!this._client)throw new Pt("Not connected");return this._client.send(t,e)},i.prototype.disconnect=function(){return this._connectionInProgress&&(this._connectionInProgress.cancel(),this._connectionInProgress=void 0),this._disconnectionInProgress=e(this._internalEmitter,dt,{timeout:this._options.connectionTimeout}).catch(),this._internalEmitter.emit(St),this._disconnectionInProgress},i.prototype.reconnect=function(t){return this._reconnectionInProgress||(t&&(this._options=Lt(B(B({},this._options),t))),this._reconnectionInProgress=e(this._internalEmitter,Ot,{timeout:this._options.connectionTimeout}),this._internalEmitter.emit(Tt)),this._reconnectionInProgress},i.prototype.join=function(t){return Y(this,void 0,void 0,(function(){var n,r,i,o,s;return k(this,(function(a){switch(a.label){case 0:return t=Mt(t),n=this._log.profile("joining "+t),[4,Promise.all([e(this,P.ROOM_STATE+"/"+t),this._isAuthenticated?e(this,P.USER_STATE+"/"+t):void 0,this.send(P.JOIN+" "+t)])];case 1:return r=V.apply(void 0,[a.sent(),2]),i=r[0],o=r[1],s={roomState:i.tags,userState:o?o.tags:void 0},this._setChannelState(i.channel,s),n.done("Joined "+t),[2,s]}}))}))},i.prototype.part=function(t){return t=Mt(t),this._log.info("parting "+t),this._removeChannelState(t),this.send(P.PART+" "+t)},i.prototype.say=function(t,n,r){var i,o;return void 0===r&&(r={}),Y(this,void 0,void 0,(function(){var s,a,u;return k(this,(function(c){switch(c.label){case 0:if(!this._isAuthenticated)throw new Pt("To send messages, please connect with a token and username");return t=Mt(t),s=n.startsWith("/"),a="1"===(null===(o=null===(i=this._channelState[t])||void 0===i?void 0:i.userState)||void 0===o?void 0:o.mod),s?this._log.info("CMD/"+t+" :"+n):this._log.info("PRIVMSG/"+t+" :"+n),u=s?Promise.resolve():e(this,P.USER_STATE+"/"+t),[4,Promise.all([u,this.send(P.PRIVATE_MESSAGE+" "+t+" :"+n,B({isModerator:a},r))])];case 1:return c.sent(),[2]}}))}))},i.prototype.broadcast=function(t){return Y(this,void 0,void 0,(function(){var e=this;return k(this,(function(n){if(!this._isAuthenticated)throw new Pt("To broadcast, please connect with a token and username");return[2,this._getChannels().map((function(n){return e.say(n,t)}))]}))}))},i.prototype.ban=function(t,n){return Y(this,void 0,void 0,(function(){var r,i;return k(this,(function(o){switch(o.label){case 0:return t=Mt(t),r="/"+G.BAN+" "+n,[4,Promise.all([e(this,[ot.BAN_SUCCESS+"/"+t,ot.ALREADY_BANNED+"/"+t]),this.say(t,r)])];case 1:return i=V.apply(void 0,[o.sent(),1]),[2,i[0]]}}))}))},i.prototype.block=function(t,e){return Y(this,void 0,void 0,(function(){var n;return k(this,(function(r){return t=Mt(t),n="/"+G.BLOCK+" "+e,[2,this.say(t,n)]}))}))},i.prototype.delete=function(t,e){return Y(this,void 0,void 0,(function(){var n;return k(this,(function(r){return t=Mt(t),n="/"+G.DELETE+" "+e,[2,this.say(t,n)]}))}))},i.prototype.clear=function(t){return Y(this,void 0,void 0,(function(){var n,r;return k(this,(function(i){switch(i.label){case 0:return t=Mt(t),n="/"+G.CLEAR,[4,Promise.all([e(this,[P.CLEAR_CHAT+"/"+t]),this.say(t,n)])];case 1:return r=V.apply(void 0,[i.sent(),1]),[2,r[0]]}}))}))},i.prototype.color=function(t,n){return Y(this,void 0,void 0,(function(){var r,i;return k(this,(function(o){switch(o.label){case 0:return t=Mt(t),r="/"+G.COLOR+" "+n,[4,Promise.all([e(this,[ot.COLOR_CHANGED+"/"+t]),this.say(t,r)])];case 1:return i=V.apply(void 0,[o.sent(),1]),[2,i[0]]}}))}))},i.prototype.commercial=function(t,n){return Y(this,void 0,void 0,(function(){var r,i;return k(this,(function(o){switch(o.label){case 0:return t=Mt(t),r="/"+G.COMMERCIAL+" "+n,[4,Promise.all([e(this,[ot.COMMERCIAL_SUCCESS+"/"+t]),this.say(t,r)])];case 1:return i=V.apply(void 0,[o.sent(),1]),[2,i[0]]}}))}))},i.prototype.emoteOnly=function(t){return Y(this,void 0,void 0,(function(){var n,r;return k(this,(function(i){switch(i.label){case 0:return t=Mt(t),n="/"+G.EMOTE_ONLY,[4,Promise.all([e(this,[ot.EMOTE_ONLY_ON+"/"+t,ot.ALREADY_EMOTE_ONLY_ON+"/"+t]),this.say(t,n)])];case 1:return r=V.apply(void 0,[i.sent(),1]),[2,r[0]]}}))}))},i.prototype.emoteOnlyOff=function(t){return Y(this,void 0,void 0,(function(){var n,r;return k(this,(function(i){switch(i.label){case 0:return t=Mt(t),n="/"+G.EMOTE_ONLY_OFF,[4,Promise.all([e(this,[ot.EMOTE_ONLY_OFF+"/"+t,ot.ALREADY_EMOTE_ONLY_OFF+"/"+t]),this.say(t,n)])];case 1:return r=V.apply(void 0,[i.sent(),1]),[2,r[0]]}}))}))},i.prototype.followersOnly=function(t,n){return Y(this,void 0,void 0,(function(){var r,i;return k(this,(function(o){switch(o.label){case 0:return t=Mt(t),r="/"+G.FOLLOWERS_ONLY+" "+n,[4,Promise.all([e(this,[ot.FOLLOWERS_ONZERO+"/"+t,ot.FOLLOWERS_ON+"/"+t]),this.say(t,r)])];case 1:return i=V.apply(void 0,[o.sent(),1]),[2,i[0]]}}))}))},i.prototype.followersOnlyOff=function(t){return Y(this,void 0,void 0,(function(){var n,r;return k(this,(function(i){switch(i.label){case 0:return t=Mt(t),n="/"+G.FOLLOWERS_ONLY_OFF,[4,Promise.all([e(this,[ot.FOLLOWERS_OFF+"/"+t]),this.say(t,n)])];case 1:return r=V.apply(void 0,[i.sent(),1]),[2,r[0]]}}))}))},i.prototype.help=function(t){return Y(this,void 0,void 0,(function(){var n,r;return k(this,(function(i){switch(i.label){case 0:return t=Mt(t),n="/"+G.HELP,[4,Promise.all([e(this,[ot.CMDS_AVAILABLE+"/"+t]),this.say(t,n)])];case 1:return r=V.apply(void 0,[i.sent(),1]),[2,r[0]]}}))}))},i.prototype.host=function(t,n){return Y(this,void 0,void 0,(function(){var r,i;return k(this,(function(o){switch(o.label){case 0:return t=Mt(t),r="/"+G.HOST+" "+n,[4,Promise.all([e(this,[ot.HOST_ON+"/"+t]),this.say(t,r)])];case 1:return i=V.apply(void 0,[o.sent(),1]),[2,i[0]]}}))}))},i.prototype.marker=function(t,e){return Y(this,void 0,void 0,(function(){var n;return k(this,(function(r){return t=Mt(t),n="/"+G.MARKER+" "+e.slice(0,140),[2,this.say(t,n)]}))}))},i.prototype.me=function(t,e){return Y(this,void 0,void 0,(function(){var n;return k(this,(function(r){return t=Mt(t),n="/"+G.ME+" "+e,[2,this.say(t,n)]}))}))},i.prototype.mod=function(t,n){return Y(this,void 0,void 0,(function(){var r,i;return k(this,(function(o){switch(o.label){case 0:return t=Mt(t),r="/"+G.MOD+" "+n,[4,Promise.all([e(this,[ot.MOD_SUCCESS+"/"+t]),this.say(t,r)])];case 1:return i=V.apply(void 0,[o.sent(),1]),[2,i[0]]}}))}))},i.prototype.mods=function(t){return Y(this,void 0,void 0,(function(){var n,r;return k(this,(function(i){switch(i.label){case 0:return t=Mt(t),n="/"+G.MODS,[4,Promise.all([e(this,[ot.ROOM_MODS+"/"+t]),this.say(t,n)])];case 1:return r=V.apply(void 0,[i.sent(),1]),[2,r[0]]}}))}))},i.prototype.r9K=function(t){return Y(this,void 0,void 0,(function(){var n,r;return k(this,(function(i){switch(i.label){case 0:return t=Mt(t),n="/"+G.R9K,[4,Promise.all([e(this,[ot.R9K_ON+"/"+t,ot.ALREADY_R9K_ON+"/"+t]),this.say(t,n)])];case 1:return r=V.apply(void 0,[i.sent(),1]),[2,r[0]]}}))}))},i.prototype.r9KOff=function(t){return Y(this,void 0,void 0,(function(){var n,r;return k(this,(function(i){switch(i.label){case 0:return t=Mt(t),n="/"+G.R9K_OFF,[4,Promise.all([e(this,[ot.R9K_OFF+"/"+t,ot.ALREADY_R9K_OFF+"/"+t]),this.say(t,n)])];case 1:return r=V.apply(void 0,[i.sent(),1]),[2,r[0]]}}))}))},i.prototype.raid=function(t,e){return Y(this,void 0,void 0,(function(){var n;return k(this,(function(r){return t=Mt(t),n="/"+G.RAID+" "+e,[2,this.say(t,n)]}))}))},i.prototype.slow=function(t,n){return Y(this,void 0,void 0,(function(){var r,i;return k(this,(function(o){switch(o.label){case 0:return t=Mt(t),r="/"+G.SLOW+" "+n,[4,Promise.all([e(this,[ot.SLOW_ON+"/"+t]),this.say(t,r)])];case 1:return i=V.apply(void 0,[o.sent(),1]),[2,i[0]]}}))}))},i.prototype.slowOff=function(t){return Y(this,void 0,void 0,(function(){var n,r;return k(this,(function(i){switch(i.label){case 0:return t=Mt(t),n="/"+G.SLOW_OFF,[4,Promise.all([e(this,[ot.SLOW_OFF+"/"+t]),this.say(t,n)])];case 1:return r=V.apply(void 0,[i.sent(),1]),[2,r[0]]}}))}))},i.prototype.subscribers=function(t){return Y(this,void 0,void 0,(function(){var n,r;return k(this,(function(i){switch(i.label){case 0:return t=Mt(t),n="/"+G.SUBSCRIBERS,[4,Promise.all([e(this,[ot.SUBS_ON+"/"+t,ot.ALREADY_SUBS_ON+"/"+t]),this.say(t,n)])];case 1:return r=V.apply(void 0,[i.sent(),1]),[2,r[0]]}}))}))},i.prototype.subscribersOff=function(t){return Y(this,void 0,void 0,(function(){var n,r;return k(this,(function(i){switch(i.label){case 0:return t=Mt(t),n="/"+G.SUBSCRIBERS_OFF,[4,Promise.all([e(this,[ot.SUBS_OFF+"/"+t,ot.ALREADY_SUBS_OFF+"/"+t]),this.say(t,n)])];case 1:return r=V.apply(void 0,[i.sent(),1]),[2,r[0]]}}))}))},i.prototype.timeout=function(t,n,r){return Y(this,void 0,void 0,(function(){var i,o,s;return k(this,(function(a){switch(a.label){case 0:return t=Mt(t),i=r?" "+r:"",o="/"+G.TIMEOUT+" "+n+i,[4,Promise.all([e(this,[ot.TIMEOUT_SUCCESS+"/"+t]),this.say(t,o)])];case 1:return s=V.apply(void 0,[a.sent(),1]),[2,s[0]]}}))}))},i.prototype.unban=function(t,n){return Y(this,void 0,void 0,(function(){var r,i;return k(this,(function(o){switch(o.label){case 0:return t=Mt(t),r="/"+G.UNBAN+" "+n,[4,Promise.all([e(this,[ot.UNBAN_SUCCESS+"/"+t]),this.say(t,r)])];case 1:return i=V.apply(void 0,[o.sent(),1]),[2,i[0]]}}))}))},i.prototype.unblock=function(t,e){return Y(this,void 0,void 0,(function(){var n;return k(this,(function(r){return t=Mt(t),n="/"+G.UNBLOCK+" "+e,[2,this.say(t,n)]}))}))},i.prototype.unhost=function(t){return Y(this,void 0,void 0,(function(){var n,r;return k(this,(function(i){switch(i.label){case 0:return t=Mt(t),n="/"+G.UNHOST,[4,Promise.all([e(this,[ot.HOST_OFF+"/"+t]),this.say(t,n)])];case 1:return r=V.apply(void 0,[i.sent(),1]),[2,r[0]]}}))}))},i.prototype.unmod=function(t,n){return Y(this,void 0,void 0,(function(){var r,i;return k(this,(function(o){switch(o.label){case 0:return t=Mt(t),r="/"+G.UNMOD+" "+n,[4,Promise.all([e(this,[ot.UNMOD_SUCCESS+"/"+t]),this.say(t,r)])];case 1:return i=V.apply(void 0,[o.sent(),1]),[2,i[0]]}}))}))},i.prototype.unraid=function(t){return Y(this,void 0,void 0,(function(){var n,r;return k(this,(function(i){switch(i.label){case 0:return t=Mt(t),n="/"+G.UNRAID,[4,Promise.all([e(this,[ot.UNRAID_SUCCESS+"/"+t]),this.say(t,n)])];case 1:return r=V.apply(void 0,[i.sent(),1]),[2,r[0]]}}))}))},i.prototype.unvip=function(t,e){t=Mt(t);var n="/"+G.UNVIP+" "+e;return this.say(t,n)},i.prototype.vip=function(t,e){t=Mt(t);var n="/"+G.VIP+" "+e;return this.say(t,n)},i.prototype.vips=function(t){t=Mt(t);var e="/"+G.VIPS;return this.say(t,e)},i.prototype.whisper=function(t,e){return Y(this,void 0,void 0,(function(){var n;return k(this,(function(r){if(!this._isAuthenticated)throw new Pt("To whisper, please connect with a token and username");return n="/"+G.WHISPER+" "+t+" "+e,[2,this.send(n)]}))}))},i.prototype._handleClientMessage=function(t){try{var e=V(this._parseMessageForEmitter(t),2),n=e[0],r=e[1];this._emit(n,r)}catch(e){this._log.error("\nAn error occurred while attempting to parse a message into a event. Please use the following stack trace and raw message to resolve the bug in the TwitchJS source code, and then issue a pull request at https://github.com/twitch-js/twitch-js/compare\n\nStack trace:\n"+e+"\n\nBase message:\n"+JSON.stringify(t)),this._internalEmitter.emit(ct.ERROR_ENCOUNTERED,e)}},i.prototype._handleJoinsAfterConnect=function(){return Y(this,void 0,void 0,(function(){var t,e,n=this;return k(this,(function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),t=this._getChannels(),[4,Promise.all(t.map((function(t){return n.join(t)})))];case 1:return r.sent(),[3,3];case 2:return e=r.sent(),this._log.error(e,"unable to rejoin channels"),[3,3];case 3:return[2]}}))}))},i.prototype._getChannels=function(){return Object.keys(this._channelState)},i.prototype._getChannelState=function(t){return this._channelState[t]},i.prototype._setChannelState=function(t,e){this._channelState[t]=e},i.prototype._removeChannelState=function(t){this._channelState=Object.entries(this._channelState).reduce((function(e,n){var r,i=V(n,2),o=i[0],s=i[1];return o===t?e:B(B({},e),((r={})[o]=s,r))}),{})},i.prototype._clearChannelState=function(){this._channelState={}},i.prototype._parseMessageForEmitter=function(t){var e=gt(t.channel),n=t.event||t.command;switch(t.command){case X.JOIN:var r=function(t){var e=V(/:(.+)!(.+)@(.+).tmi.twitch.tv JOIN (#.+)/g.exec(t._raw)||[],5),n=e[1],r=e[4];return B(B({},t),{channel:r,command:P.JOIN,event:P.JOIN,username:n})}(t);return[i=n+"/"+e,r];case X.PART:r=function(t){var e=V(/:(.+)!(.+)@(.+).tmi.twitch.tv PART (#.+)/g.exec(t._raw)||[],5),n=e[1],r=e[4];return B(B({},t),{channel:r,command:P.PART,event:P.PART,username:n})}(t);return[i=n+"/"+e,r];case X.NAMES:r=function(t){var e=V(/:(.+).tmi.twitch.tv 353 (.+) = (#.+) :(.+)/g.exec(t._raw)||[],5),n=e[3],r=e[4].split(" ");return B(B({},t),{channel:n,command:P.NAMES,event:P.NAMES,usernames:r})}(t);return[i=n+"/"+e,r];case X.NAMES_END:r=function(t){var e=V(/:(.+).tmi.twitch.tv 366 (.+) (#.+) :(.+)/g.exec(t._raw)||[],4),n=e[1],r=e[3];return B(B({},t),{channel:r,command:P.NAMES_END,event:P.NAMES_END,username:n})}(t);return[i=n+"/"+e,r];case X.CLEAR_CHAT:r=function(t){var e=t.tags,n=t.message,r=W(t,["tags","message"]);return B(B({},r),void 0!==n?{tags:B(B({},e),{banReason:pt(e.banReason),banDuration:ft(e.banDuration)}),command:P.CLEAR_CHAT,event:F.USER_BANNED,username:n}:{command:P.CLEAR_CHAT,event:P.CLEAR_CHAT})}(t);return[i=n+"/"+r.event+"/"+e,r];case X.CLEAR_MESSAGE:r=function(t){var e=t.tags;return B(B({},t),{tags:{login:e.login,targetMsgId:e.targetMsgId},command:P.CLEAR_MESSAGE,event:P.CLEAR_MESSAGE,targetMessageId:e.targetMsgId})}(t);return[i=n+"/"+e,r];case X.HOST_TARGET:r=function(t){var e=V(/:tmi.twitch.tv HOSTTARGET (#[^\s]+) :([^\s]+)?\s?(\d+)?/g.exec(t._raw)||[],4),n=e[1],r=e[2],i=e[3],o="-"===r;return B(B({},t),{channel:n,username:r,command:P.HOST_TARGET,event:o?F.HOST_OFF:F.HOST_ON,numberOfViewers:O(f(i))?parseInt(i,10):void 0})}(t);return[i=n+"/"+e,r];case X.MODE:r=function(t){var e=V(/:[^\s]+ MODE (#[^\s]+) (-|\+)o ([^\s]+)/g.exec(t._raw)||[],4),n=e[1],r=e[2],i=e[3],o="+"===r,s=B(B({},t),{command:P.MODE,channel:n,username:i});return B(B({},s),o?{event:F.MOD_GAINED,message:"+o",isModerator:!0}:{event:F.MOD_LOST,message:"-o",isModerator:!1})}(t);var i=n+"/"+e,o=this._getChannelState(e);return this._isAuthenticated&&void 0!==(null==o?void 0:o.userState)&&r.username===this._options.username&&this._setChannelState(e,B(B({},o),{userState:B(B({},o.userState),{mod:r.isModerator?"1":"0",isModerator:r.isModerator})})),[i,r];case X.USER_STATE:r=yt(t),i=n+"/"+e;return(o=this._getChannelState(e))&&this._setChannelState(e,B(B({},o),{userState:r.tags})),[i,r];case X.ROOM_STATE:r=function(t){var e=t.tags,n=W(t,["tags"]);return B(B({},n),{command:P.ROOM_STATE,event:P.ROOM_STATE,tags:It(e)})}(t),i=n+"/"+e;return this._setChannelState(e,B(B({},this._getChannelState(e)),{roomState:r})),[i,r];case X.NOTICE:return[i=n+"/"+(r=Rt(t)).event+"/"+e,r];case X.USER_NOTICE:return[i=n+"/"+(r=Dt(t)).event+"/"+e,r];case X.PRIVATE_MESSAGE:r=function(t){var e=t._raw,n=t.tags;if(p(n.bits,0))return B(B({},yt(t)),{command:P.PRIVATE_MESSAGE,event:F.CHEER,bits:parseInt(n.bits,10)});var r=V(lt.exec(e)||[],5),i=r[0],o=r[1],s=r[2],a=r[3],u=r[4];return i?B(B({},t),a?{command:P.PRIVATE_MESSAGE,event:F.HOSTED_AUTO,channel:"#"+o,tags:{displayName:s},numberOfViewers:ft(u)}:u?{command:P.PRIVATE_MESSAGE,event:F.HOSTED_WITH_VIEWERS,channel:"#"+o,tags:{displayName:s},numberOfViewers:ft(u)}:{command:P.PRIVATE_MESSAGE,event:F.HOSTED_WITHOUT_VIEWERS,channel:"#"+o,tags:{displayName:s}}):B(B({},yt(t)),{command:P.PRIVATE_MESSAGE,event:P.PRIVATE_MESSAGE})}(t);return[i=n+"/"+r.event+"/"+e,r];default:return[i=e?n+"/"+e:n,t]}},i.prototype._emit=function(t,e){var i=this;try{if(t)this._log.info(e,t),n(t.split("/")).filter((function(t){return"#"!==t})).reduce((function(t,n){var o=j(t,[n]),s=o.join("/");return o.length>1&&r.prototype.emit.call(i,n,e),r.prototype.emit.call(i,s,e),o}),[]);r.prototype.emit.call(this,X.ALL,e)}catch(t){this._log.error("\nWhile attempting to handle the "+e.command+" event, an error occurred in your implementation. To avoid seeing this message, please resolve the error:\n\n"+t.stack+"\n\nParsed messages:\n"+JSON.stringify(e)),this._internalEmitter.emit(ct.ERROR_ENCOUNTERED,t)}},i.Commands=P,i.Events=X,i.CompoundEvents=((ut={})[X.NOTICE]=ot,ut[X.PRIVATE_MESSAGE]=st,ut[X.USER_NOTICE]=at,ut),i}(t),Ht=function(t){function e(e,n){var r=t.call(this,e)||this;return r.body=n,Object.defineProperty(r,"name",{value:"TwitchJSFetchError"}),r}return g(e,t),e}(bt),Bt=function(t,e,n){return Y(void 0,void 0,void 0,(function(){var r,i,o,s,u,c,E,_,l,h;return k(this,(function(O){switch(O.label){case 0:return i=(r=e||{}).search,o=r.body,s=W(r,["search","body"]),u=i?R(i,B(B({},n),{addQueryPrefix:!0,arrayFormat:"repeat"})):"",c=Wt(o),E=B(B(B({},s),c),{headers:B(B({},null==e?void 0:e.headers),c.headers)}),[4,C(""+t+u,E)];case 1:return[4,(_=O.sent()).json().catch((function(){return{}}))];case 2:if(l=O.sent(),"error"in(h=a(l,{deep:!0})))throw new Ht(h.message,h);if(!_.ok)throw new Ht(_.statusText,{error:!0,status:_.status,message:_.statusText});return[2,h]}}))}))},Wt=function(t){try{return t?"[object FormData]"===toString.call(t)?{body:t}:{body:JSON.stringify(t),headers:{"Content-Type":"application/json"}}:{}}catch(e){return{body:t}}},Yt=function(t){var e={token:h,clientId:h,onAuthenticationFailure:function(t){return A(t)||y(t)}};return t=l(t,{clientId:void 0,onAuthenticationFailure:void 0}),E(_(t,e),"Expected valid options"),t};!function(t){t[t.NOT_READY=0]="NOT_READY",t[t.READY=1]="READY",t[t.INITIALIZED=2]="INITIALIZED"}(Ft||(Ft={}));var kt=function(){function t(t){this._readyState=Ft.READY,this._options=Yt(t),this._log=tt(B({name:"Api"},this._options.log))}return Object.defineProperty(t.prototype,"readyState",{get:function(){return this._readyState},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"status",{get:function(){return this._status},enumerable:!1,configurable:!0}),t.prototype.updateOptions=function(t){this._options=Yt(B(B({},this._options),t))},t.prototype.initialize=function(t){return Y(this,void 0,void 0,(function(){var e;return k(this,(function(n){switch(n.label){case 0:return t&&(this._options=Yt(B(B({},this._options),t))),t||2!==this.readyState?[4,Bt("https://id.twitch.tv/oauth2/validate",{headers:{Authorization:"Bearer "+this._options.token}})]:[2,Promise.resolve()];case 1:return e=n.sent(),this._readyState=Ft.INITIALIZED,this._status=e,[2]}}))}))},t.prototype.hasScope=function(t){var e=this;return new Promise((function(n,r){var i,o;return(null===(o=null===(i=e.status)||void 0===i?void 0:i.scopes)||void 0===o?void 0:o.includes(t))?n(!0):r(!1)}))},t.prototype.get=function(t,e){return void 0===t&&(t=""),this._handleFetch(t,e)},t.prototype.post=function(t,e){return this._handleFetch(t,B(B({},e),{method:"post"}))},t.prototype.put=function(t,e){return this._handleFetch(t,B(B({},e),{method:"put"}))},t.prototype._getAuthenticationHeaders=function(){var t=this._options,e=t.clientId;return{Authorization:"Bearer "+t.token,"Client-Id":e}},t.prototype._handleFetch=function(t,e){return void 0===t&&(t=""),void 0===e&&(e={}),Y(this,void 0,void 0,(function(){var n,r,i,o,s,a,u,c=this;return k(this,(function(E){switch(E.label){case 0:"https://api.twitch.tv/helix",n="https://api.twitch.tv/helix/"+t,r=(m(e.method)||"GET")+" "+n,i=this._log.profile(),o=function(){return Y(c,void 0,void 0,(function(){var t,r,i;return k(this,(function(o){switch(o.label){case 0:t=this._getAuthenticationHeaders(),r=B(B({},e),{headers:B(B({},e.headers),t)}),o.label=1;case 1:return o.trys.push([1,3,,4]),[4,Bt(n,r)];case 2:return[2,o.sent()];case 3:if((i=o.sent())instanceof Ht&&401===i.body.status)throw new wt(i.message,i.body);throw i;case 4:return[2]}}))}))},E.label=1;case 1:return E.trys.push([1,3,7,8]),[4,o()];case 2:return[2,E.sent()];case 3:return a=E.sent(),"function"==typeof this._options.onAuthenticationFailure&&a instanceof wt?[4,this._handleAuthenticationFailure(a)]:[3,6];case 4:return(u=E.sent())?(this._log.info(r+" ... retrying with new token"),this.updateOptions({token:u}),[4,o()]):[3,6];case 5:return[2,E.sent()];case 6:throw s=a;case 7:return i.done(r,s),[7];case 8:return[2]}}))}))},t.prototype._handleAuthenticationFailure=function(t){var e,n;return Y(this,void 0,void 0,(function(){var r;return k(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,null===(n=(e=this._options).onAuthenticationFailure)||void 0===n?void 0:n.call(e)];case 1:return[2,i.sent()];case 2:throw r=i.sent(),this._log.error(r,"onAuthenticationFailure error occurred"),t;case 3:return[2]}}))}))},t}(),Vt=function(){function t(t){var e=t.token,n=t.username,r=t.clientId,i=t.log,o=t.onAuthenticationFailure,s=t.chat,a=t.api;this.chat=new Gt(B(B({log:i},s),{token:e,username:n,onAuthenticationFailure:o})),this.api=new kt(B(B({log:i},a),{token:e,clientId:r,onAuthenticationFailure:o}))}return t.prototype.updateOptions=function(t){var e=t.chat,n=t.api;e&&this.chat.updateOptions(e),n&&this.api.updateOptions(n)},t.Chat=Gt,t.Api=kt,t}();export default Vt;export{kt as Api,w as BaseCommands,Z as BooleanBadges,U as Capabilities,Gt as Chat,G as ChatCommands,F as ChatEvents,P as Commands,X as Events,H as KnownNoticeMessageIds,x as KnownNoticeMessageIdsUpperCase,K as KnownUserNoticeMessageIds,L as MembershipCommands,q as NoticeEvents,Q as NumberBadges,b as OtherCommands,J as PrivateMessageEvents,M as TagCommands,z as UserNoticeEvents}; //# sourceMappingURL=index.js.map