From 8150e719f679efc3c71abfc9b162fa931bd2037a Mon Sep 17 00:00:00 2001 From: Gus Caplan Date: Thu, 8 Dec 2016 04:01:12 -0600 Subject: [PATCH] 2.0.0 --- README.md | 10 +- package.json | 2 +- src/Client.js | 111 ++ src/index.js | 3 +- webpack/rpc.2.0.0.es6.js | 3011 ++++++++++++++++++++++++++++++++ webpack/rpc.2.0.0.es6.min.js | 1 + webpack/rpc.2.0.0.js | 3201 ++++++++++++++++++++++++++++++++++ webpack/rpc.2.0.0.min.js | 2 + 8 files changed, 6336 insertions(+), 5 deletions(-) create mode 100644 src/Client.js create mode 100644 webpack/rpc.2.0.0.es6.js create mode 100644 webpack/rpc.2.0.0.es6.min.js create mode 100644 webpack/rpc.2.0.0.js create mode 100644 webpack/rpc.2.0.0.min.js diff --git a/README.md b/README.md index 9b4b345..4f1306f 100644 --- a/README.md +++ b/README.md @@ -24,14 +24,18 @@ const client = new RPCClient({ OAUTH2_CLIENT_ID: 'xyzxyzxyz' }); -client.evts.on('READY', () => { +client.on('ready', () => { console.log('Authenticated!'); console.log('User:' `${client.user.username}#${client.user.discriminator}`, client.user.id) console.log('Application:', client.application.name, client.application.id); - client.request('GET_CHANNELS', {}, (err, data) => { - // data.channels is an array of channels :) + client.getChannels().then(res => { + // res is an array of channels :) }); + client.selectVoiceChannel('1234567890').then(channel => { + console.log('the voice channel was set to', channel.id); + }) + // if you are so lucky as to have the rpc.api scope, you can have a little fun client.rest.sendMessage('some channel id', 'hello, how are you?'); }); diff --git a/package.json b/package.json index 78f2baf..39632f5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "discord-rpc", - "version": "1.1.5", + "version": "2.0.0", "description": "A simple RPC client for Discord somewhat stolen from the Discord StreamKit.", "main": "src/index.js", "repository": { diff --git a/src/Client.js b/src/Client.js new file mode 100644 index 0000000..96952dc --- /dev/null +++ b/src/Client.js @@ -0,0 +1,111 @@ +const RPCClient = require('./RPCClient'); +const EventEmitter = require('events').EventEmitter; + +class Client extends EventEmitter { + constructor ({ OAUTH2_CLIENT_ID } = {}) { + super(); + this.rpc = new RPCClient({ OAUTH2_CLIENT_ID }); + this.rpc.evts.on('READY', () => { + this.user = this.rpc.user; + this.application = this.rpc.application; + this.emit('ready'); + }); + this.rpc.evts.on('ERROR', (err) => this.emit('error', err)); + this.rest = this.rpc.rest; + } + + getGuild (id, timeout) { + return new Promise((resolve, reject) => { + this.rpc.request('GET_GUILD', { guild_id: id, timeout }, (err, res) => { + if (err) reject(err); + resolve(res.data); + }); + }); + } + + getGuilds () { + return new Promise((resolve, reject) => { + this.rpc.request('GET_GUILDS', {}, (err, res) => { + if (err) reject(err); + resolve(res.data.guilds); + }); + }); + } + + getChannel (id, timeout) { + return new Promise((resolve, reject) => { + this.rpc.request('GET_CHANNEL', { channel_id: id, timeout }, (err, res) => { + if (err) reject(err); + resolve(res.data); + }); + }); + } + + getChannels () { + return new Promise((resolve, reject) => { + this.rpc.request('GET_CHANNELS', {}, (err, res) => { + if (err) reject(err); + resolve(res.data.channels); + }); + }); + } + + setUserVoiceSettings (args) { + return new Promise((resolve, reject) => { + this.rpc.request('SET_USER_VOICE_SETTINGS', args, (err, res) => { + if (err) reject(err); + resolve(res.data); + }); + }); + } + + selectVoiceChannel (id, timeout, force = false) { + return new Promise((resolve, reject) => { + this.rpc.request('SELECT_VOICE_CHANNEL', { channel_id: id, timeout, force }, (err, res) => { + if (err) reject(err); + resolve(res.data); + }); + }); + } + + selectTextChannel (id, timeout, force = false) { + return new Promise((resolve, reject) => { + this.rpc.request('SELECT_TEXT_CHANNEL', { channel_id: id, timeout, force }, (err, res) => { + if (err) reject(err); + resolve(res.data); + }); + }); + } + + getVoiceSettings () { + return new Promise((resolve, reject) => { + this.rpc.request('GET_VOICE_SETTINGS', {}, (err, res) => { + if (err) reject(err); + resolve(res.data); + }); + }); + } + + setVoiceSettings (args) { + return new Promise((resolve, reject) => { + this.rpc.request('SET_VOICE_SETTINGS', args, (err, res) => { + if (err) reject(err); + resolve(res.data); + }); + }); + } + + subscribe (event, args, callback) { + return this.rpc.subscribe(event, args, callback); + } + + unsubscribe (event, args, callback) { + return this.rpc.unsubscribe(event, args, callback); + } + + connect (token) { + return this.rpc.connect(token); + } +} + +module.exports = Client; diff --git a/src/index.js b/src/index.js index 69b355e..682071b 100644 --- a/src/index.js +++ b/src/index.js @@ -1,6 +1,7 @@ module.exports = { version: require('../package.json').version, - Client: require('./RPCClient'), + Client: require('./Client'), + RPC: require('./RPCClient'), Rest: require('./RESTClient'), Constants: require('./Constants') } diff --git a/webpack/rpc.2.0.0.es6.js b/webpack/rpc.2.0.0.es6.js new file mode 100644 index 0000000..0564f46 --- /dev/null +++ b/webpack/rpc.2.0.0.es6.js @@ -0,0 +1,3011 @@ +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.l = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // identity function for calling harmory imports with the correct context +/******/ __webpack_require__.i = function(value) { return value; }; + +/******/ // define getter function for harmory exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ Object.defineProperty(exports, name, { +/******/ configurable: false, +/******/ enumerable: true, +/******/ get: getter +/******/ }); +/******/ }; + +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; + +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 18); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ function(module, exports) { + +const keyMirror = (arr) => { + let tmp = {}; + for (const value of arr) tmp[value] = value; + return tmp; +} + +module.exports.RPCCommands = keyMirror([ + 'DISPATCH', + + 'AUTHORIZE', + 'AUTHENTICATE', + + 'GET_GUILD', + 'GET_GUILDS', + 'GET_CHANNEL', + 'GET_CHANNELS', + + 'SUBSCRIBE', + 'UNSUBSCRIBE', + + 'SET_USER_VOICE_SETTINGS', + 'SELECT_VOICE_CHANNEL', + 'GET_VOICE_SETTINGS', + 'SET_VOICE_SETTINGS', + + 'SELECT_TEXT_CHANNEL', + + 'INVITE_BROWSER' // just for kicks +]); + +module.exports.RPCEvents = keyMirror([ + 'READY', + 'ERROR', + + 'GUILD_STATUS', + 'GUILD_CREATE', + + 'CHANNEL_CREATE', + + 'VOICE_STATE_CREATE', + 'VOICE_STATE_DELETE', + 'VOICE_STATE_UPDATE', + + 'VOICE_SETTINGS_UPDATE', + 'VOICE_CONNECTION_STATUS', + + 'SPEAKING_START', + 'SPEAKING_STOP', + + 'MESSAGE_CREATE', + 'MESSAGE_UPDATE', + 'MESSAGE_DELETE' +]); + +module.exports.RPCErrors = { + UNKNOWN_ERROR: 1000, + + INVALID_PAYLOAD: 4000, + INVALID_VERSION: 4001, + INVALID_COMMAND: 4002, + INVALID_GUILD: 4003, + INVALID_EVENT: 4004, + INVALID_CHANNEL: 4005, + INVALID_PERMISSIONS: 4006, + INVALID_CLIENTID: 4007, + INVALID_ORIGIN: 4008, + INVALID_TOKEN: 4009, + INVALID_USER: 4010, + + OAUTH2_ERROR: 5000 +}; + +module.exports.RPCCloseCodes = { + INVALID_CLIENTID: 4000, + INVALID_ORIGIN: 4001, + RATELIMITED: 4002, + TOKEN_REVOKED: 4003 +}; + +module.exports.ChannelTypes = { + DM: 1, + GROUP_DM: 3, + GUILD_TEXT: 0, + GUILD_VOICE: 2 +}; + +// stolen from discord.js +const Endpoints = module.exports.Endpoints = { + // general + login: '/auth/login', + logout: '/auth/logout', + gateway: '/gateway', + botGateway: '/gateway/bot', + invite: (id) => `/invite/${id}`, + inviteLink: (id) => `https://discord.gg/${id}`, + CDN: 'https://cdn.discordapp.com', + + // users + user: (userID) => `/users/${userID}`, + userChannels: (userID) => `${Endpoints.user(userID)}/channels`, + userProfile: (userID) => `${Endpoints.user(userID)}/profile`, + avatar: (userID, avatar) => userID === '1' ? avatar : `${Endpoints.user(userID)}/avatars/${avatar}.jpg`, + me: '/users/@me', + meGuild: (guildID) => `${Endpoints.me}/guilds/${guildID}`, + relationships: (userID) => `${Endpoints.user(userID)}/relationships`, + note: (userID) => `${Endpoints.me}/notes/${userID}`, + + // guilds + guilds: '/guilds', + guild: (guildID) => `${Endpoints.guilds}/${guildID}`, + guildIcon: (guildID, hash) => `${Endpoints.guild(guildID)}/icons/${hash}.jpg`, + guildPrune: (guildID) => `${Endpoints.guild(guildID)}/prune`, + guildEmbed: (guildID) => `${Endpoints.guild(guildID)}/embed`, + guildInvites: (guildID) => `${Endpoints.guild(guildID)}/invites`, + guildRoles: (guildID) => `${Endpoints.guild(guildID)}/roles`, + guildRole: (guildID, roleID) => `${Endpoints.guildRoles(guildID)}/${roleID}`, + guildBans: (guildID) => `${Endpoints.guild(guildID)}/bans`, + guildIntegrations: (guildID) => `${Endpoints.guild(guildID)}/integrations`, + guildMembers: (guildID) => `${Endpoints.guild(guildID)}/members`, + guildMember: (guildID, memberID) => `${Endpoints.guildMembers(guildID)}/${memberID}`, + guildMemberRole: (guildID, memberID, roleID) => `${Endpoints.guildMember(guildID, memberID)}/roles/${roleID}`, + stupidInconsistentGuildEndpoint: (guildID) => `${Endpoints.guildMember(guildID, '@me')}/nick`, + guildChannels: (guildID) => `${Endpoints.guild(guildID)}/channels`, + guildEmojis: (guildID) => `${Endpoints.guild(guildID)}/emojis`, + + // channels + channels: '/channels', + channel: (channelID) => `${Endpoints.channels}/${channelID}`, + channelMessages: (channelID) => `${Endpoints.channel(channelID)}/messages`, + channelInvites: (channelID) => `${Endpoints.channel(channelID)}/invites`, + channelTyping: (channelID) => `${Endpoints.channel(channelID)}/typing`, + channelPermissions: (channelID) => `${Endpoints.channel(channelID)}/permissions`, + channelMessage: (channelID, messageID) => `${Endpoints.channelMessages(channelID)}/${messageID}`, + channelWebhooks: (channelID) => `${Endpoints.channel(channelID)}/webhooks`, + + // message reactions + messageReactions: (channelID, messageID) => `${Endpoints.channelMessage(channelID, messageID)}/reactions`, + messageReaction: (channel, msg, emoji, limit) => `${Endpoints.messageReactions(channel, msg)}/${emoji}${limit ? `?limit=${limit}` : ''}`, + selfMessageReaction: (channel, msg, emoji, limit) => `${Endpoints.messageReaction(channel, msg, emoji, limit)}/@me`, + userMessageReaction: (channel, msg, emoji, limit, id) => `${Endpoints.messageReaction(channel, msg, emoji, limit)}/${id}`, + + // webhooks + webhook: (webhookID, token) => `/webhooks/${webhookID}${token ? `/${token}` : ''}`, + + // oauth + myApplication: '/oauth2/applications/@me', + getApp: (id) => `/oauth2/authorize?client_id=${id}` +}; + + +/***/ }, +/* 1 */ +/***/ function(module, exports, __webpack_require__) { + +const superagent = __webpack_require__(4); +const { Endpoints } = __webpack_require__(0); + +module.exports = class RESTClient { + constructor (client) { + this.client = client; + } + + makeRequest (method, path, body = {}, headers = {}) { + return new Promise((resolve, reject) => { + headers.Authorization = `Bearer ${this.client.accessToken}`; + superagent[method.toLowerCase()](`https://${this.client.hostAndPort}${path}`) + .set(headers).send(body).then(res => resolve(res.body), reject); + }); + } + + sendMessage (channelID, content) { + return this.makeRequest('post', Endpoints.channelMessages(channelID), { content }); + } + + editMessage (channelID, messageID, content) { + return this.makeRequest('patch', Endpoints.channelMessage(channelID, messageID), { content }); + } + + deleteMessage (channelID, messageID) { + return this.makeRequest('delete', Endpoints.channelMessage(channelID, messageID)); + } +} + + +/***/ }, +/* 2 */ +/***/ function(module, exports, __webpack_require__) { + +/* + Stolen from Discord's StreamKit Overlay by ```Macdja38 + Modified by Gus Caplan +*/ + +const WebSocket = typeof window !== 'undefined' ? window.WebSocket : __webpack_require__(17); // eslint-disable-line no-undef +const EventEmitter = __webpack_require__(3).EventEmitter; +const { RPCCommands, RPCEvents, RPCErrors } = __webpack_require__(0); +const superagent = __webpack_require__(4); +const deepEqual = __webpack_require__(9); +const uuid = __webpack_require__(15).v4; +const RESTClient = __webpack_require__(1); + +function getEventName (cmd, nonce, evt) { + return `${cmd}:${nonce || evt}`; +} + +class RPCClient { + constructor (options) { + this.evts = new EventEmitter(); + this.activeSubscriptions = []; + this.queue = []; + this.connected = false; + this.ready = false; + this.requestedDisconnect = false; + this.connectionTries = 0; + this.socket = null; + this.config = {}; + this.OAUTH2_CLIENT_ID = options.OAUTH2_CLIENT_ID; + this.API_ENDPOINT = options.API_ENDPOINT || ''; + this.rest = new RESTClient(this); + } + + connect (accessToken = this.accessToken, tries = 0) { + if (this.connected) return; + this.accessToken = accessToken; + const port = 6463 + (tries % 10); + this.hostAndPort = `${uuid()}.discordapp.io:${port}`; + this.socket = new WebSocket(`wss://${this.hostAndPort}/?v=1&client_id=${this.OAUTH2_CLIENT_ID}`); // eslint-disable-line + this.socket.onopen = this._handleOpen.bind(this); + this.socket.onclose = this._handleClose.bind(this); + this.socket.onmessage = this._handleMessage.bind(this); + } + + disconnect (callback) { + if (!this.connected) return; + this.requestedDisconnect = true; + this.socket.close(); + if (callback) callback(); + } + + reconnect () { + if (!this.connected) return; + this.socket.close(); + } + + authenticate () { + if (this.authenticated) return; + if (!this.accessToken) { + this.authorize(); + return; + } + this.request('AUTHENTICATE', { + access_token: this.accessToken + }, (e, r) => { + if (e && e.code === RPCErrors.INVALID_TOKEN) { + this.authorize(); + return; + } + this.authenticated = true; + this.flushQueue(); + this.activeSubscriptions.forEach(s => this.subscribe(s.evt, s.args, s.callback)); + }); + } + + flushQueue () { + const queue = this.queue; + this.queue = []; + queue.forEach(c => c()); + } + + authorize () { + if (this.authenticated) return; + superagent + .get(`${this.API_ENDPOINT}/token`) + .then(r => { + if (!r.ok || !r.body.rpc_token) { + throw new Error('no rpc token'); + } + return this.request('AUTHORIZE', { + client_id: this.OAUTH2_CLIENT_ID, + scopes: ['rpc', 'rpc.api'], + rpc_token: r.body.rpc_token + }); + }) + .then(r => superagent + .post(`${this.API_ENDPOINT}/token`) + .send({ + code: r.code + }) + ) + .then(r => { + if (!r.ok) { + throw new Error('no access token'); + } + this.accessToken = r.body.access_token; + this.authenticate(); + }) + .catch(e => { + setTimeout(this.authorize.bind(this), 3000); + }); + } + + request (cmd, args, evt, callback) { + if (typeof evt === 'function') { + callback = evt; + evt = undefined; + } + return new Promise((resolve, reject) => { + if (!this.connected || !this.ready || (!this.authenticated && ['AUTHORIZE', 'AUTHENTICATE'].indexOf(cmd) === -1)) { + this.queue.push(() => this.request(cmd, args, evt, callback)); + return; + } + const nonce = uuid(); + this.evts.once(getEventName(RPCCommands.DISPATCH, nonce), (err, res) => { + if (callback) callback(err, res); + if (err) { + reject(err); + } else { + resolve(res); + } + }); + this.socket.send(JSON.stringify({ + cmd, + args, + evt, + nonce + })); + }); + } + + subscribe (evt, args, callback) { + this.request(RPCCommands.SUBSCRIBE, args, evt, error => { + if (error) { + if (callback) callback(error); + return; + } + // on reconnect we resub to events, so don't dup listens + if (!this.activeSubscriptions.find(s => { + return callback === s.callback; + })) { + this.activeSubscriptions.push({ + evt, + args, + callback + }); + this.evts.on(getEventName(RPCCommands.DISPATCH, null, evt), d => { if (callback) callback(null, d); }); + } + }); + } + + unsubscribe (evt, args, callback) { + this.request(RPCCommands.UNSUBSCRIBE, args, evt, error => { + if (error) { + if (callback) callback(error); + return; + } + for (const i in this.activeSubscriptions) { + const s = this.activeSubscriptions[i]; + if (evt === s.evt && deepEqual(args, s.args)) this.activeSubscriptions.splice(i, 1); + } + const eventName = getEventName(RPCCommands.DISPATCH, null, evt); + this.evts.listeners(eventName).forEach(cb => { + this.evts.removeListener(eventName, cb); + }); + if (callback) callback(); + }); + } + + _handleOpen () { + this.connected = true; + this.authenticate(); + } + + _handleClose (e) { + this.connected = false; + this.authenticated = false; + this.ready = false; + console.error('WS Closed:', e); + if (this.requestedDisconnect) { + this.requestedDisconnect = false; + return; + } + try { + this.socket.close(); + } catch (e) {} + setTimeout(() => this.connect(null, e.code === 1006 ? ++this.connectionTries : 0), 250); + } + + _handleMessage (message) { + let payload = null; + try { + payload = JSON.parse(message.data); + } catch (e) { + console.error('Payload not JSON:', payload); + return; + } + let { + cmd, + evt, + nonce, + data + } = payload; + + if (cmd === RPCCommands.AUTHENTICATE) { + if (evt === RPCEvents.ERROR) { + this.evts.emit('ERROR', data); + return; + } + this.user = data.user; + this.application = data.application; + this.evts.emit('READY', data); + } + if (cmd === RPCCommands.DISPATCH) { + if (evt === RPCEvents.READY) { + this.config = data.config; + this.ready = true; + this.flushQueue(); + return; + } + if (evt === RPCEvents.ERROR) { + console.error('Dispatched Error', data); + this.socket.close(); + return; + } + this.evts.emit(getEventName(RPCCommands.DISPATCH, null, evt), data); + return; + } + let error = null; + if (evt === RPCEvents.ERROR) { + error = new Error(data.message); + error.code = data.code; + data = null; + } + this.evts.emit(getEventName(RPCCommands.DISPATCH, nonce), error, data); + } +} +module.exports = RPCClient; + + +/***/ }, +/* 3 */ +/***/ function(module, exports) { + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; +} +module.exports = EventEmitter; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function(n) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError('n must be a positive number'); + this._maxListeners = n; + return this; +}; + +EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; + + if (!this._events) + this._events = {}; + + // If there is no 'error' event listener then throw. + if (type === 'error') { + if (!this._events.error || + (isObject(this._events.error) && !this._events.error.length)) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + } + } + + handler = this._events[type]; + + if (isUndefined(handler)) + return false; + + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + args = Array.prototype.slice.call(arguments, 1); + handler.apply(this, args); + } + } else if (isObject(handler)) { + args = Array.prototype.slice.call(arguments, 1); + listeners = handler.slice(); + len = listeners.length; + for (i = 0; i < len; i++) + listeners[i].apply(this, args); + } + + return true; +}; + +EventEmitter.prototype.addListener = function(type, listener) { + var m; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events) + this._events = {}; + + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (this._events.newListener) + this.emit('newListener', type, + isFunction(listener.listener) ? + listener.listener : listener); + + if (!this._events[type]) + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + else + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; + + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; + } + + if (m && m > 0 && this._events[type].length > m) { + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); + } + } + } + + return this; +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + var fired = false; + + function g() { + this.removeListener(type, g); + + if (!fired) { + fired = true; + listener.apply(this, arguments); + } + } + + g.listener = listener; + this.on(type, g); + + return this; +}; + +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events || !this._events[type]) + return this; + + list = this._events[type]; + length = list.length; + position = -1; + + if (list === listener || + (isFunction(list.listener) && list.listener === listener)) { + delete this._events[type]; + if (this._events.removeListener) + this.emit('removeListener', type, listener); + + } else if (isObject(list)) { + for (i = length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list.length = 0; + delete this._events[type]; + } else { + list.splice(position, 1); + } + + if (this._events.removeListener) + this.emit('removeListener', type, listener); + } + + return this; +}; + +EventEmitter.prototype.removeAllListeners = function(type) { + var key, listeners; + + if (!this._events) + return this; + + // not listening for removeListener, no need to emit + if (!this._events.removeListener) { + if (arguments.length === 0) + this._events = {}; + else if (this._events[type]) + delete this._events[type]; + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; + } + + listeners = this._events[type]; + + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); + } + delete this._events[type]; + + return this; +}; + +EventEmitter.prototype.listeners = function(type) { + var ret; + if (!this._events || !this._events[type]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + ret = this._events[type].slice(); + return ret; +}; + +EventEmitter.prototype.listenerCount = function(type) { + if (this._events) { + var evlistener = this._events[type]; + + if (isFunction(evlistener)) + return 1; + else if (evlistener) + return evlistener.length; + } + return 0; +}; + +EventEmitter.listenerCount = function(emitter, type) { + return emitter.listenerCount(type); +}; + +function isFunction(arg) { + return typeof arg === 'function'; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isUndefined(arg) { + return arg === void 0; +} + + +/***/ }, +/* 4 */ +/***/ function(module, exports, __webpack_require__) { + +/** + * Root reference for iframes. + */ + +var root; +if (typeof window !== 'undefined') { // Browser window + root = window; +} else if (typeof self !== 'undefined') { // Web Worker + root = self; +} else { // Other environments + console.warn("Using browser-only version of superagent in non-browser environment"); + root = this; +} + +var Emitter = __webpack_require__(8); +var RequestBase = __webpack_require__(12); +var isObject = __webpack_require__(5); + +/** + * Noop. + */ + +function noop(){}; + +/** + * Expose `request`. + */ + +var request = module.exports = __webpack_require__(13).bind(null, Request); + +/** + * Determine XHR. + */ + +request.getXHR = function () { + if (root.XMLHttpRequest + && (!root.location || 'file:' != root.location.protocol + || !root.ActiveXObject)) { + return new XMLHttpRequest; + } else { + try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {} + try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {} + try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {} + try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {} + } + throw Error("Browser-only verison of superagent could not find XHR"); +}; + +/** + * Removes leading and trailing whitespace, added to support IE. + * + * @param {String} s + * @return {String} + * @api private + */ + +var trim = ''.trim + ? function(s) { return s.trim(); } + : function(s) { return s.replace(/(^\s*|\s*$)/g, ''); }; + +/** + * Serialize the given `obj`. + * + * @param {Object} obj + * @return {String} + * @api private + */ + +function serialize(obj) { + if (!isObject(obj)) return obj; + var pairs = []; + for (var key in obj) { + pushEncodedKeyValuePair(pairs, key, obj[key]); + } + return pairs.join('&'); +} + +/** + * Helps 'serialize' with serializing arrays. + * Mutates the pairs array. + * + * @param {Array} pairs + * @param {String} key + * @param {Mixed} val + */ + +function pushEncodedKeyValuePair(pairs, key, val) { + if (val != null) { + if (Array.isArray(val)) { + val.forEach(function(v) { + pushEncodedKeyValuePair(pairs, key, v); + }); + } else if (isObject(val)) { + for(var subkey in val) { + pushEncodedKeyValuePair(pairs, key + '[' + subkey + ']', val[subkey]); + } + } else { + pairs.push(encodeURIComponent(key) + + '=' + encodeURIComponent(val)); + } + } else if (val === null) { + pairs.push(encodeURIComponent(key)); + } +} + +/** + * Expose serialization method. + */ + + request.serializeObject = serialize; + + /** + * Parse the given x-www-form-urlencoded `str`. + * + * @param {String} str + * @return {Object} + * @api private + */ + +function parseString(str) { + var obj = {}; + var pairs = str.split('&'); + var pair; + var pos; + + for (var i = 0, len = pairs.length; i < len; ++i) { + pair = pairs[i]; + pos = pair.indexOf('='); + if (pos == -1) { + obj[decodeURIComponent(pair)] = ''; + } else { + obj[decodeURIComponent(pair.slice(0, pos))] = + decodeURIComponent(pair.slice(pos + 1)); + } + } + + return obj; +} + +/** + * Expose parser. + */ + +request.parseString = parseString; + +/** + * Default MIME type map. + * + * superagent.types.xml = 'application/xml'; + * + */ + +request.types = { + html: 'text/html', + json: 'application/json', + xml: 'application/xml', + urlencoded: 'application/x-www-form-urlencoded', + 'form': 'application/x-www-form-urlencoded', + 'form-data': 'application/x-www-form-urlencoded' +}; + +/** + * Default serialization map. + * + * superagent.serialize['application/xml'] = function(obj){ + * return 'generated xml here'; + * }; + * + */ + + request.serialize = { + 'application/x-www-form-urlencoded': serialize, + 'application/json': JSON.stringify + }; + + /** + * Default parsers. + * + * superagent.parse['application/xml'] = function(str){ + * return { object parsed from str }; + * }; + * + */ + +request.parse = { + 'application/x-www-form-urlencoded': parseString, + 'application/json': JSON.parse +}; + +/** + * Parse the given header `str` into + * an object containing the mapped fields. + * + * @param {String} str + * @return {Object} + * @api private + */ + +function parseHeader(str) { + var lines = str.split(/\r?\n/); + var fields = {}; + var index; + var line; + var field; + var val; + + lines.pop(); // trailing CRLF + + for (var i = 0, len = lines.length; i < len; ++i) { + line = lines[i]; + index = line.indexOf(':'); + field = line.slice(0, index).toLowerCase(); + val = trim(line.slice(index + 1)); + fields[field] = val; + } + + return fields; +} + +/** + * Check if `mime` is json or has +json structured syntax suffix. + * + * @param {String} mime + * @return {Boolean} + * @api private + */ + +function isJSON(mime) { + return /[\/+]json\b/.test(mime); +} + +/** + * Return the mime type for the given `str`. + * + * @param {String} str + * @return {String} + * @api private + */ + +function type(str){ + return str.split(/ *; */).shift(); +}; + +/** + * Return header field parameters. + * + * @param {String} str + * @return {Object} + * @api private + */ + +function params(str){ + return str.split(/ *; */).reduce(function(obj, str){ + var parts = str.split(/ *= */), + key = parts.shift(), + val = parts.shift(); + + if (key && val) obj[key] = val; + return obj; + }, {}); +}; + +/** + * Initialize a new `Response` with the given `xhr`. + * + * - set flags (.ok, .error, etc) + * - parse header + * + * Examples: + * + * Aliasing `superagent` as `request` is nice: + * + * request = superagent; + * + * We can use the promise-like API, or pass callbacks: + * + * request.get('/').end(function(res){}); + * request.get('/', function(res){}); + * + * Sending data can be chained: + * + * request + * .post('/user') + * .send({ name: 'tj' }) + * .end(function(res){}); + * + * Or passed to `.send()`: + * + * request + * .post('/user') + * .send({ name: 'tj' }, function(res){}); + * + * Or passed to `.post()`: + * + * request + * .post('/user', { name: 'tj' }) + * .end(function(res){}); + * + * Or further reduced to a single call for simple cases: + * + * request + * .post('/user', { name: 'tj' }, function(res){}); + * + * @param {XMLHTTPRequest} xhr + * @param {Object} options + * @api private + */ + +function Response(req, options) { + options = options || {}; + this.req = req; + this.xhr = this.req.xhr; + // responseText is accessible only if responseType is '' or 'text' and on older browsers + this.text = ((this.req.method !='HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text')) || typeof this.xhr.responseType === 'undefined') + ? this.xhr.responseText + : null; + this.statusText = this.req.xhr.statusText; + this._setStatusProperties(this.xhr.status); + this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders()); + // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but + // getResponseHeader still works. so we get content-type even if getting + // other headers fails. + this.header['content-type'] = this.xhr.getResponseHeader('content-type'); + this._setHeaderProperties(this.header); + this.body = this.req.method != 'HEAD' + ? this._parseBody(this.text ? this.text : this.xhr.response) + : null; +} + +/** + * Get case-insensitive `field` value. + * + * @param {String} field + * @return {String} + * @api public + */ + +Response.prototype.get = function(field){ + return this.header[field.toLowerCase()]; +}; + +/** + * Set header related properties: + * + * - `.type` the content type without params + * + * A response of "Content-Type: text/plain; charset=utf-8" + * will provide you with a `.type` of "text/plain". + * + * @param {Object} header + * @api private + */ + +Response.prototype._setHeaderProperties = function(header){ + // content-type + var ct = this.header['content-type'] || ''; + this.type = type(ct); + + // params + var obj = params(ct); + for (var key in obj) this[key] = obj[key]; +}; + +/** + * Parse the given body `str`. + * + * Used for auto-parsing of bodies. Parsers + * are defined on the `superagent.parse` object. + * + * @param {String} str + * @return {Mixed} + * @api private + */ + +Response.prototype._parseBody = function(str){ + var parse = request.parse[this.type]; + if (!parse && isJSON(this.type)) { + parse = request.parse['application/json']; + } + return parse && str && (str.length || str instanceof Object) + ? parse(str) + : null; +}; + +/** + * Set flags such as `.ok` based on `status`. + * + * For example a 2xx response will give you a `.ok` of __true__ + * whereas 5xx will be __false__ and `.error` will be __true__. The + * `.clientError` and `.serverError` are also available to be more + * specific, and `.statusType` is the class of error ranging from 1..5 + * sometimes useful for mapping respond colors etc. + * + * "sugar" properties are also defined for common cases. Currently providing: + * + * - .noContent + * - .badRequest + * - .unauthorized + * - .notAcceptable + * - .notFound + * + * @param {Number} status + * @api private + */ + +Response.prototype._setStatusProperties = function(status){ + // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request + if (status === 1223) { + status = 204; + } + + var type = status / 100 | 0; + + // status / class + this.status = this.statusCode = status; + this.statusType = type; + + // basics + this.info = 1 == type; + this.ok = 2 == type; + this.clientError = 4 == type; + this.serverError = 5 == type; + this.error = (4 == type || 5 == type) + ? this.toError() + : false; + + // sugar + this.accepted = 202 == status; + this.noContent = 204 == status; + this.badRequest = 400 == status; + this.unauthorized = 401 == status; + this.notAcceptable = 406 == status; + this.notFound = 404 == status; + this.forbidden = 403 == status; +}; + +/** + * Return an `Error` representative of this response. + * + * @return {Error} + * @api public + */ + +Response.prototype.toError = function(){ + var req = this.req; + var method = req.method; + var url = req.url; + + var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')'; + var err = new Error(msg); + err.status = this.status; + err.method = method; + err.url = url; + + return err; +}; + +/** + * Expose `Response`. + */ + +request.Response = Response; + +/** + * Initialize a new `Request` with the given `method` and `url`. + * + * @param {String} method + * @param {String} url + * @api public + */ + +function Request(method, url) { + var self = this; + this._query = this._query || []; + this.method = method; + this.url = url; + this.header = {}; // preserves header name case + this._header = {}; // coerces header names to lowercase + this.on('end', function(){ + var err = null; + var res = null; + + try { + res = new Response(self); + } catch(e) { + err = new Error('Parser is unable to parse the response'); + err.parse = true; + err.original = e; + // issue #675: return the raw response if the response parsing fails + if (self.xhr) { + // ie9 doesn't have 'response' property + err.rawResponse = typeof self.xhr.responseType == 'undefined' ? self.xhr.responseText : self.xhr.response; + // issue #876: return the http status code if the response parsing fails + err.statusCode = self.xhr.status ? self.xhr.status : null; + } else { + err.rawResponse = null; + err.statusCode = null; + } + + return self.callback(err); + } + + self.emit('response', res); + + var new_err; + try { + if (res.status < 200 || res.status >= 300) { + new_err = new Error(res.statusText || 'Unsuccessful HTTP response'); + new_err.original = err; + new_err.response = res; + new_err.status = res.status; + } + } catch(e) { + new_err = e; // #985 touching res may cause INVALID_STATE_ERR on old Android + } + + // #1000 don't catch errors from the callback to avoid double calling it + if (new_err) { + self.callback(new_err, res); + } else { + self.callback(null, res); + } + }); +} + +/** + * Mixin `Emitter` and `RequestBase`. + */ + +Emitter(Request.prototype); +RequestBase(Request.prototype); + +/** + * Set Content-Type to `type`, mapping values from `request.types`. + * + * Examples: + * + * superagent.types.xml = 'application/xml'; + * + * request.post('/') + * .type('xml') + * .send(xmlstring) + * .end(callback); + * + * request.post('/') + * .type('application/xml') + * .send(xmlstring) + * .end(callback); + * + * @param {String} type + * @return {Request} for chaining + * @api public + */ + +Request.prototype.type = function(type){ + this.set('Content-Type', request.types[type] || type); + return this; +}; + +/** + * Set responseType to `val`. Presently valid responseTypes are 'blob' and + * 'arraybuffer'. + * + * Examples: + * + * req.get('/') + * .responseType('blob') + * .end(callback); + * + * @param {String} val + * @return {Request} for chaining + * @api public + */ + +Request.prototype.responseType = function(val){ + this._responseType = val; + return this; +}; + +/** + * Set Accept to `type`, mapping values from `request.types`. + * + * Examples: + * + * superagent.types.json = 'application/json'; + * + * request.get('/agent') + * .accept('json') + * .end(callback); + * + * request.get('/agent') + * .accept('application/json') + * .end(callback); + * + * @param {String} accept + * @return {Request} for chaining + * @api public + */ + +Request.prototype.accept = function(type){ + this.set('Accept', request.types[type] || type); + return this; +}; + +/** + * Set Authorization field value with `user` and `pass`. + * + * @param {String} user + * @param {String} pass + * @param {Object} options with 'type' property 'auto' or 'basic' (default 'basic') + * @return {Request} for chaining + * @api public + */ + +Request.prototype.auth = function(user, pass, options){ + if (!options) { + options = { + type: 'basic' + } + } + + switch (options.type) { + case 'basic': + var str = btoa(user + ':' + pass); + this.set('Authorization', 'Basic ' + str); + break; + + case 'auto': + this.username = user; + this.password = pass; + break; + } + return this; +}; + +/** +* Add query-string `val`. +* +* Examples: +* +* request.get('/shoes') +* .query('size=10') +* .query({ color: 'blue' }) +* +* @param {Object|String} val +* @return {Request} for chaining +* @api public +*/ + +Request.prototype.query = function(val){ + if ('string' != typeof val) val = serialize(val); + if (val) this._query.push(val); + return this; +}; + +/** + * Queue the given `file` as an attachment to the specified `field`, + * with optional `options` (or filename). + * + * ``` js + * request.post('/upload') + * .attach('content', new Blob(['hey!'], { type: "text/html"})) + * .end(callback); + * ``` + * + * @param {String} field + * @param {Blob|File} file + * @param {String|Object} options + * @return {Request} for chaining + * @api public + */ + +Request.prototype.attach = function(field, file, options){ + if (this._data) { + throw Error("superagent can't mix .send() and .attach()"); + } + + this._getFormData().append(field, file, options || file.name); + return this; +}; + +Request.prototype._getFormData = function(){ + if (!this._formData) { + this._formData = new root.FormData(); + } + return this._formData; +}; + +/** + * Invoke the callback with `err` and `res` + * and handle arity check. + * + * @param {Error} err + * @param {Response} res + * @api private + */ + +Request.prototype.callback = function(err, res){ + var fn = this._callback; + this.clearTimeout(); + + if (err) { + this.emit('error', err); + } + + fn(err, res); +}; + +/** + * Invoke callback with x-domain error. + * + * @api private + */ + +Request.prototype.crossDomainError = function(){ + var err = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.'); + err.crossDomain = true; + + err.status = this.status; + err.method = this.method; + err.url = this.url; + + this.callback(err); +}; + +// This only warns, because the request is still likely to work +Request.prototype.buffer = Request.prototype.ca = Request.prototype.agent = function(){ + console.warn("This is not supported in browser version of superagent"); + return this; +}; + +// This throws, because it can't send/receive data as expected +Request.prototype.pipe = Request.prototype.write = function(){ + throw Error("Streaming is not supported in browser version of superagent"); +}; + +/** + * Invoke callback with timeout error. + * + * @api private + */ + +Request.prototype._timeoutError = function(){ + var timeout = this._timeout; + var err = new Error('timeout of ' + timeout + 'ms exceeded'); + err.timeout = timeout; + this.callback(err); +}; + +/** + * Compose querystring to append to req.url + * + * @api private + */ + +Request.prototype._appendQueryString = function(){ + var query = this._query.join('&'); + if (query) { + this.url += ~this.url.indexOf('?') + ? '&' + query + : '?' + query; + } +}; + +/** + * Check if `obj` is a host object, + * we don't want to serialize these :) + * + * @param {Object} obj + * @return {Boolean} + * @api private + */ +Request.prototype._isHost = function _isHost(obj) { + // Native objects stringify to [object File], [object Blob], [object FormData], etc. + return obj && 'object' === typeof obj && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== '[object Object]'; +} + +/** + * Initiate request, invoking callback `fn(res)` + * with an instanceof `Response`. + * + * @param {Function} fn + * @return {Request} for chaining + * @api public + */ + +Request.prototype.end = function(fn){ + var self = this; + var xhr = this.xhr = request.getXHR(); + var timeout = this._timeout; + var data = this._formData || this._data; + + // store callback + this._callback = fn || noop; + + // state change + xhr.onreadystatechange = function(){ + if (4 != xhr.readyState) return; + + // In IE9, reads to any property (e.g. status) off of an aborted XHR will + // result in the error "Could not complete the operation due to error c00c023f" + var status; + try { status = xhr.status } catch(e) { status = 0; } + + if (0 == status) { + if (self.timedout) return self._timeoutError(); + if (self._aborted) return; + return self.crossDomainError(); + } + self.emit('end'); + }; + + // progress + var handleProgress = function(direction, e) { + if (e.total > 0) { + e.percent = e.loaded / e.total * 100; + } + e.direction = direction; + self.emit('progress', e); + } + if (this.hasListeners('progress')) { + try { + xhr.onprogress = handleProgress.bind(null, 'download'); + if (xhr.upload) { + xhr.upload.onprogress = handleProgress.bind(null, 'upload'); + } + } catch(e) { + // Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist. + // Reported here: + // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context + } + } + + // timeout + if (timeout && !this._timer) { + this._timer = setTimeout(function(){ + self.timedout = true; + self.abort(); + }, timeout); + } + + // querystring + this._appendQueryString(); + + // initiate request + if (this.username && this.password) { + xhr.open(this.method, this.url, true, this.username, this.password); + } else { + xhr.open(this.method, this.url, true); + } + + // CORS + if (this._withCredentials) xhr.withCredentials = true; + + // body + if ('GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !this._isHost(data)) { + // serialize stuff + var contentType = this._header['content-type']; + var serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : '']; + if (!serialize && isJSON(contentType)) serialize = request.serialize['application/json']; + if (serialize) data = serialize(data); + } + + // set header fields + for (var field in this.header) { + if (null == this.header[field]) continue; + xhr.setRequestHeader(field, this.header[field]); + } + + if (this._responseType) { + xhr.responseType = this._responseType; + } + + // send stuff + this.emit('request', this); + + // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing) + // We need null here if data is undefined + xhr.send(typeof data !== 'undefined' ? data : null); + return this; +}; + + +/** + * Expose `Request`. + */ + +request.Request = Request; + +/** + * GET `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.get = function(url, data, fn){ + var req = request('GET', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.query(data); + if (fn) req.end(fn); + return req; +}; + +/** + * HEAD `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.head = function(url, data, fn){ + var req = request('HEAD', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + +/** + * OPTIONS query to `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.options = function(url, data, fn){ + var req = request('OPTIONS', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + +/** + * DELETE `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +function del(url, fn){ + var req = request('DELETE', url); + if (fn) req.end(fn); + return req; +}; + +request['del'] = del; +request['delete'] = del; + +/** + * PATCH `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} [data] + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.patch = function(url, data, fn){ + var req = request('PATCH', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + +/** + * POST `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} [data] + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.post = function(url, data, fn){ + var req = request('POST', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + +/** + * PUT `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.put = function(url, data, fn){ + var req = request('PUT', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + + +/***/ }, +/* 5 */ +/***/ function(module, exports) { + +/** + * Check if `obj` is an object. + * + * @param {Object} obj + * @return {Boolean} + * @api private + */ + +function isObject(obj) { + return null !== obj && 'object' === typeof obj; +} + +module.exports = isObject; + + +/***/ }, +/* 6 */ +/***/ function(module, exports) { + +module.exports = { + "name": "discord-rpc", + "version": "2.0.0", + "description": "A simple RPC client for Discord somewhat stolen from the Discord StreamKit.", + "main": "src/index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/GusCaplan/discord-rpc.git" + }, + "scripts": { + "web-dist": "node ./node_modules/parallel-webpack/bin/run.js" + }, + "author": "Gus Caplan ", + "license": "MIT", + "bugs": { + "url": "https://github.com/GusCaplan/discord-rpc/issues" + }, + "homepage": "https://github.com/GusCaplan/discord-rpc#readme", + "dependencies": { + "deep-equal": "^1.0.1", + "superagent": "^3.0.0", + "uuid": "^3.0.0", + "ws": "^1.1.1" + }, + "devDependencies": { + "babel-core": "^6.18.2", + "babel-loader": "^6.2.8", + "babel-preset-es2015": "^6.18.0", + "bufferutil": "^1.2.1", + "ignore-loader": "^0.1.2", + "json-loader": "^0.5.4", + "parallel-webpack": "^1.5.0", + "uglify-js": "github:mishoo/UglifyJS2#harmony", + "utf-8-validate": "^1.2.1", + "webpack": "2.1.0-beta.27" + }, + "browser": { + "ws": false + } +}; + +/***/ }, +/* 7 */ +/***/ function(module, exports, __webpack_require__) { + +const RPCClient = __webpack_require__(2); +const EventEmitter = __webpack_require__(3).EventEmitter; + +class Client extends EventEmitter { + constructor ({ OAUTH2_CLIENT_ID } = {}) { + super(); + this.rpc = new RPCClient({ OAUTH2_CLIENT_ID }); + this.rpc.evts.on('READY', () => { + this.user = this.rpc.user; + this.application = this.rpc.application; + this.emit('ready'); + }); + this.rpc.evts.on('ERROR', (err) => this.emit('error', err)); + this.rest = this.rpc.rest; + } + + getGuild (id, timeout) { + return new Promise((resolve, reject) => { + this.rpc.request('GET_GUILD', { guild_id: id, timeout }, (err, res) => { + if (err) reject(err); + resolve(res.data); + }); + }); + } + + getGuilds () { + return new Promise((resolve, reject) => { + this.rpc.request('GET_GUILDS', {}, (err, res) => { + if (err) reject(err); + resolve(res.data.guilds); + }); + }); + } + + getChannel (id, timeout) { + return new Promise((resolve, reject) => { + this.rpc.request('GET_CHANNEL', { channel_id: id, timeout }, (err, res) => { + if (err) reject(err); + resolve(res.data); + }); + }); + } + + getChannels () { + return new Promise((resolve, reject) => { + this.rpc.request('GET_CHANNELS', {}, (err, res) => { + if (err) reject(err); + resolve(res.data.channels); + }); + }); + } + + setUserVoiceSettings (args) { + return new Promise((resolve, reject) => { + this.rpc.request('SET_USER_VOICE_SETTINGS', args, (err, res) => { + if (err) reject(err); + resolve(res.data); + }); + }); + } + + selectVoiceChannel (id, timeout, force = false) { + return new Promise((resolve, reject) => { + this.rpc.request('SELECT_VOICE_CHANNEL', { channel_id: id, timeout, force }, (err, res) => { + if (err) reject(err); + resolve(res.data); + }); + }); + } + + selectTextChannel (id, timeout, force = false) { + return new Promise((resolve, reject) => { + this.rpc.request('SELECT_TEXT_CHANNEL', { channel_id: id, timeout, force }, (err, res) => { + if (err) reject(err); + resolve(res.data); + }); + }); + } + + getVoiceSettings () { + return new Promise((resolve, reject) => { + this.rpc.request('GET_VOICE_SETTINGS', {}, (err, res) => { + if (err) reject(err); + resolve(res.data); + }); + }); + } + + setVoiceSettings (args) { + return new Promise((resolve, reject) => { + this.rpc.request('SET_VOICE_SETTINGS', args, (err, res) => { + if (err) reject(err); + resolve(res.data); + }); + }); + } + + subscribe (event, args, callback) { + return this.rpc.subscribe(event, args, callback); + } + + unsubscribe (event, args, callback) { + return this.rpc.unsubscribe(event, args, callback); + } + + connect (token) { + return this.rpc.connect(token); + } +} + +module.exports = Client; + + +/***/ }, +/* 8 */ +/***/ function(module, exports, __webpack_require__) { + + +/** + * Expose `Emitter`. + */ + +if (true) { + module.exports = Emitter; +} + +/** + * Initialize a new `Emitter`. + * + * @api public + */ + +function Emitter(obj) { + if (obj) return mixin(obj); +}; + +/** + * Mixin the emitter properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ + +function mixin(obj) { + for (var key in Emitter.prototype) { + obj[key] = Emitter.prototype[key]; + } + return obj; +} + +/** + * Listen on the given `event` with `fn`. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.on = +Emitter.prototype.addEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + (this._callbacks['$' + event] = this._callbacks['$' + event] || []) + .push(fn); + return this; +}; + +/** + * Adds an `event` listener that will be invoked a single + * time then automatically removed. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.once = function(event, fn){ + function on() { + this.off(event, on); + fn.apply(this, arguments); + } + + on.fn = fn; + this.on(event, on); + return this; +}; + +/** + * Remove the given callback for `event` or all + * registered callbacks. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.off = +Emitter.prototype.removeListener = +Emitter.prototype.removeAllListeners = +Emitter.prototype.removeEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + + // all + if (0 == arguments.length) { + this._callbacks = {}; + return this; + } + + // specific event + var callbacks = this._callbacks['$' + event]; + if (!callbacks) return this; + + // remove all handlers + if (1 == arguments.length) { + delete this._callbacks['$' + event]; + return this; + } + + // remove specific handler + var cb; + for (var i = 0; i < callbacks.length; i++) { + cb = callbacks[i]; + if (cb === fn || cb.fn === fn) { + callbacks.splice(i, 1); + break; + } + } + return this; +}; + +/** + * Emit `event` with the given args. + * + * @param {String} event + * @param {Mixed} ... + * @return {Emitter} + */ + +Emitter.prototype.emit = function(event){ + this._callbacks = this._callbacks || {}; + var args = [].slice.call(arguments, 1) + , callbacks = this._callbacks['$' + event]; + + if (callbacks) { + callbacks = callbacks.slice(0); + for (var i = 0, len = callbacks.length; i < len; ++i) { + callbacks[i].apply(this, args); + } + } + + return this; +}; + +/** + * Return array of callbacks for `event`. + * + * @param {String} event + * @return {Array} + * @api public + */ + +Emitter.prototype.listeners = function(event){ + this._callbacks = this._callbacks || {}; + return this._callbacks['$' + event] || []; +}; + +/** + * Check if this emitter has `event` handlers. + * + * @param {String} event + * @return {Boolean} + * @api public + */ + +Emitter.prototype.hasListeners = function(event){ + return !! this.listeners(event).length; +}; + + +/***/ }, +/* 9 */ +/***/ function(module, exports, __webpack_require__) { + +var pSlice = Array.prototype.slice; +var objectKeys = __webpack_require__(11); +var isArguments = __webpack_require__(10); + +var deepEqual = module.exports = function (actual, expected, opts) { + if (!opts) opts = {}; + // 7.1. All identical values are equivalent, as determined by ===. + if (actual === expected) { + return true; + + } else if (actual instanceof Date && expected instanceof Date) { + return actual.getTime() === expected.getTime(); + + // 7.3. Other pairs that do not both pass typeof value == 'object', + // equivalence is determined by ==. + } else if (!actual || !expected || typeof actual != 'object' && typeof expected != 'object') { + return opts.strict ? actual === expected : actual == expected; + + // 7.4. For all other Object pairs, including Array objects, equivalence is + // determined by having the same number of owned properties (as verified + // with Object.prototype.hasOwnProperty.call), the same set of keys + // (although not necessarily the same order), equivalent values for every + // corresponding key, and an identical 'prototype' property. Note: this + // accounts for both named and indexed properties on Arrays. + } else { + return objEquiv(actual, expected, opts); + } +} + +function isUndefinedOrNull(value) { + return value === null || value === undefined; +} + +function isBuffer (x) { + if (!x || typeof x !== 'object' || typeof x.length !== 'number') return false; + if (typeof x.copy !== 'function' || typeof x.slice !== 'function') { + return false; + } + if (x.length > 0 && typeof x[0] !== 'number') return false; + return true; +} + +function objEquiv(a, b, opts) { + var i, key; + if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) + return false; + // an identical 'prototype' property. + if (a.prototype !== b.prototype) return false; + //~~~I've managed to break Object.keys through screwy arguments passing. + // Converting to array solves the problem. + if (isArguments(a)) { + if (!isArguments(b)) { + return false; + } + a = pSlice.call(a); + b = pSlice.call(b); + return deepEqual(a, b, opts); + } + if (isBuffer(a)) { + if (!isBuffer(b)) { + return false; + } + if (a.length !== b.length) return false; + for (i = 0; i < a.length; i++) { + if (a[i] !== b[i]) return false; + } + return true; + } + try { + var ka = objectKeys(a), + kb = objectKeys(b); + } catch (e) {//happens when one is a string literal and the other isn't + return false; + } + // having the same number of owned properties (keys incorporates + // hasOwnProperty) + if (ka.length != kb.length) + return false; + //the same set of keys (although not necessarily the same order), + ka.sort(); + kb.sort(); + //~~~cheap key test + for (i = ka.length - 1; i >= 0; i--) { + if (ka[i] != kb[i]) + return false; + } + //equivalent values for every corresponding key, and + //~~~possibly expensive deep test + for (i = ka.length - 1; i >= 0; i--) { + key = ka[i]; + if (!deepEqual(a[key], b[key], opts)) return false; + } + return typeof a === typeof b; +} + + +/***/ }, +/* 10 */ +/***/ function(module, exports) { + +var supportsArgumentsClass = (function(){ + return Object.prototype.toString.call(arguments) +})() == '[object Arguments]'; + +exports = module.exports = supportsArgumentsClass ? supported : unsupported; + +exports.supported = supported; +function supported(object) { + return Object.prototype.toString.call(object) == '[object Arguments]'; +}; + +exports.unsupported = unsupported; +function unsupported(object){ + return object && + typeof object == 'object' && + typeof object.length == 'number' && + Object.prototype.hasOwnProperty.call(object, 'callee') && + !Object.prototype.propertyIsEnumerable.call(object, 'callee') || + false; +}; + + +/***/ }, +/* 11 */ +/***/ function(module, exports) { + +exports = module.exports = typeof Object.keys === 'function' + ? Object.keys : shim; + +exports.shim = shim; +function shim (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +} + + +/***/ }, +/* 12 */ +/***/ function(module, exports, __webpack_require__) { + +/** + * Module of mixed-in functions shared between node and client code + */ +var isObject = __webpack_require__(5); + +/** + * Expose `RequestBase`. + */ + +module.exports = RequestBase; + +/** + * Initialize a new `RequestBase`. + * + * @api public + */ + +function RequestBase(obj) { + if (obj) return mixin(obj); +} + +/** + * Mixin the prototype properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ + +function mixin(obj) { + for (var key in RequestBase.prototype) { + obj[key] = RequestBase.prototype[key]; + } + return obj; +} + +/** + * Clear previous timeout. + * + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.clearTimeout = function _clearTimeout(){ + this._timeout = 0; + clearTimeout(this._timer); + return this; +}; + +/** + * Override default response body parser + * + * This function will be called to convert incoming data into request.body + * + * @param {Function} + * @api public + */ + +RequestBase.prototype.parse = function parse(fn){ + this._parser = fn; + return this; +}; + +/** + * Override default request body serializer + * + * This function will be called to convert data set via .send or .attach into payload to send + * + * @param {Function} + * @api public + */ + +RequestBase.prototype.serialize = function serialize(fn){ + this._serializer = fn; + return this; +}; + +/** + * Set timeout to `ms`. + * + * @param {Number} ms + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.timeout = function timeout(ms){ + this._timeout = ms; + return this; +}; + +/** + * Promise support + * + * @param {Function} resolve + * @param {Function} reject + * @return {Request} + */ + +RequestBase.prototype.then = function then(resolve, reject) { + if (!this._fullfilledPromise) { + var self = this; + this._fullfilledPromise = new Promise(function(innerResolve, innerReject){ + self.end(function(err, res){ + if (err) innerReject(err); else innerResolve(res); + }); + }); + } + return this._fullfilledPromise.then(resolve, reject); +} + +RequestBase.prototype.catch = function(cb) { + return this.then(undefined, cb); +}; + +/** + * Allow for extension + */ + +RequestBase.prototype.use = function use(fn) { + fn(this); + return this; +} + + +/** + * Get request header `field`. + * Case-insensitive. + * + * @param {String} field + * @return {String} + * @api public + */ + +RequestBase.prototype.get = function(field){ + return this._header[field.toLowerCase()]; +}; + +/** + * Get case-insensitive header `field` value. + * This is a deprecated internal API. Use `.get(field)` instead. + * + * (getHeader is no longer used internally by the superagent code base) + * + * @param {String} field + * @return {String} + * @api private + * @deprecated + */ + +RequestBase.prototype.getHeader = RequestBase.prototype.get; + +/** + * Set header `field` to `val`, or multiple fields with one object. + * Case-insensitive. + * + * Examples: + * + * req.get('/') + * .set('Accept', 'application/json') + * .set('X-API-Key', 'foobar') + * .end(callback); + * + * req.get('/') + * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' }) + * .end(callback); + * + * @param {String|Object} field + * @param {String} val + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.set = function(field, val){ + if (isObject(field)) { + for (var key in field) { + this.set(key, field[key]); + } + return this; + } + this._header[field.toLowerCase()] = val; + this.header[field] = val; + return this; +}; + +/** + * Remove header `field`. + * Case-insensitive. + * + * Example: + * + * req.get('/') + * .unset('User-Agent') + * .end(callback); + * + * @param {String} field + */ +RequestBase.prototype.unset = function(field){ + delete this._header[field.toLowerCase()]; + delete this.header[field]; + return this; +}; + +/** + * Write the field `name` and `val`, or multiple fields with one object + * for "multipart/form-data" request bodies. + * + * ``` js + * request.post('/upload') + * .field('foo', 'bar') + * .end(callback); + * + * request.post('/upload') + * .field({ foo: 'bar', baz: 'qux' }) + * .end(callback); + * ``` + * + * @param {String|Object} name + * @param {String|Blob|File|Buffer|fs.ReadStream} val + * @return {Request} for chaining + * @api public + */ +RequestBase.prototype.field = function(name, val) { + + // name should be either a string or an object. + if (null === name || undefined === name) { + throw new Error('.field(name, val) name can not be empty'); + } + + if (isObject(name)) { + for (var key in name) { + this.field(key, name[key]); + } + return this; + } + + // val should be defined now + if (null === val || undefined === val) { + throw new Error('.field(name, val) val can not be empty'); + } + this._getFormData().append(name, val); + return this; +}; + +/** + * Abort the request, and clear potential timeout. + * + * @return {Request} + * @api public + */ +RequestBase.prototype.abort = function(){ + if (this._aborted) { + return this; + } + this._aborted = true; + this.xhr && this.xhr.abort(); // browser + this.req && this.req.abort(); // node + this.clearTimeout(); + this.emit('abort'); + return this; +}; + +/** + * Enable transmission of cookies with x-domain requests. + * + * Note that for this to work the origin must not be + * using "Access-Control-Allow-Origin" with a wildcard, + * and also must set "Access-Control-Allow-Credentials" + * to "true". + * + * @api public + */ + +RequestBase.prototype.withCredentials = function(){ + // This is browser-only functionality. Node side is no-op. + this._withCredentials = true; + return this; +}; + +/** + * Set the max redirects to `n`. Does noting in browser XHR implementation. + * + * @param {Number} n + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.redirects = function(n){ + this._maxRedirects = n; + return this; +}; + +/** + * Convert to a plain javascript object (not JSON string) of scalar properties. + * Note as this method is designed to return a useful non-this value, + * it cannot be chained. + * + * @return {Object} describing method, url, and data of this request + * @api public + */ + +RequestBase.prototype.toJSON = function(){ + return { + method: this.method, + url: this.url, + data: this._data, + headers: this._header + }; +}; + + +/** + * Send `data` as the request body, defaulting the `.type()` to "json" when + * an object is given. + * + * Examples: + * + * // manual json + * request.post('/user') + * .type('json') + * .send('{"name":"tj"}') + * .end(callback) + * + * // auto json + * request.post('/user') + * .send({ name: 'tj' }) + * .end(callback) + * + * // manual x-www-form-urlencoded + * request.post('/user') + * .type('form') + * .send('name=tj') + * .end(callback) + * + * // auto x-www-form-urlencoded + * request.post('/user') + * .type('form') + * .send({ name: 'tj' }) + * .end(callback) + * + * // defaults to x-www-form-urlencoded + * request.post('/user') + * .send('name=tobi') + * .send('species=ferret') + * .end(callback) + * + * @param {String|Object} data + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.send = function(data){ + var isObj = isObject(data); + var type = this._header['content-type']; + + if (isObj && !this._data) { + if (Array.isArray(data)) { + this._data = []; + } else if (!this._isHost(data)) { + this._data = {}; + } + } else if (data && this._data && this._isHost(this._data)) { + throw Error("Can't merge these send calls"); + } + + // merge + if (isObj && isObject(this._data)) { + for (var key in data) { + this._data[key] = data[key]; + } + } else if ('string' == typeof data) { + // default to x-www-form-urlencoded + if (!type) this.type('form'); + type = this._header['content-type']; + if ('application/x-www-form-urlencoded' == type) { + this._data = this._data + ? this._data + '&' + data + : data; + } else { + this._data = (this._data || '') + data; + } + } else { + this._data = data; + } + + if (!isObj || this._isHost(data)) return this; + + // default to json + if (!type) this.type('json'); + return this; +}; + + +/***/ }, +/* 13 */ +/***/ function(module, exports) { + +// The node and browser modules expose versions of this with the +// appropriate constructor function bound as first argument +/** + * Issue a request: + * + * Examples: + * + * request('GET', '/users').end(callback) + * request('/users').end(callback) + * request('/users', callback) + * + * @param {String} method + * @param {String|Function} url or callback + * @return {Request} + * @api public + */ + +function request(RequestConstructor, method, url) { + // callback + if ('function' == typeof url) { + return new RequestConstructor('GET', method).end(url); + } + + // url first + if (2 == arguments.length) { + return new RequestConstructor('GET', method); + } + + return new RequestConstructor(method, url); +} + +module.exports = request; + + +/***/ }, +/* 14 */ +/***/ function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(global) { +var rng; + +var crypto = global.crypto || global.msCrypto; // for IE 11 +if (crypto && crypto.getRandomValues) { + // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto + // Moderately fast, high quality + var _rnds8 = new Uint8Array(16); + rng = function whatwgRNG() { + crypto.getRandomValues(_rnds8); + return _rnds8; + }; +} + +if (!rng) { + // Math.random()-based (RNG) + // + // If all else fails, use Math.random(). It's fast, but is of unspecified + // quality. + var _rnds = new Array(16); + rng = function() { + for (var i = 0, r; i < 16; i++) { + if ((i & 0x03) === 0) r = Math.random() * 0x100000000; + _rnds[i] = r >>> ((i & 0x03) << 3) & 0xff; + } + + return _rnds; + }; +} + +module.exports = rng; + + +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(16))) + +/***/ }, +/* 15 */ +/***/ function(module, exports, __webpack_require__) { + +// Unique ID creation requires a high quality random # generator. We feature +// detect to determine the best RNG source, normalizing to a function that +// returns 128-bits of randomness, since that's what's usually required +var _rng = __webpack_require__(14); + +// Maps for number <-> hex string conversion +var _byteToHex = []; +var _hexToByte = {}; +for (var i = 0; i < 256; ++i) { + _byteToHex[i] = (i + 0x100).toString(16).substr(1); + _hexToByte[_byteToHex[i]] = i; +} + +function buff_to_string(buf, offset) { + var i = offset || 0; + var bth = _byteToHex; + return bth[buf[i++]] + bth[buf[i++]] + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + + bth[buf[i++]] + bth[buf[i++]] + + bth[buf[i++]] + bth[buf[i++]]; +} + +// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html + +// random #'s we need to init node and clockseq +var _seedBytes = _rng(); + +// Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) +var _nodeId = [ + _seedBytes[0] | 0x01, + _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5] +]; + +// Per 4.2.2, randomize (14 bit) clockseq +var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff; + +// Previous uuid creation time +var _lastMSecs = 0, _lastNSecs = 0; + +// See https://github.com/broofa/node-uuid for API details +function v1(options, buf, offset) { + var i = buf && offset || 0; + var b = buf || []; + + options = options || {}; + + var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; + + // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); + + // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; + + // Time since last uuid creation (in msecs) + var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000; + + // Per 4.2.1.2, Bump clockseq on clock regression + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } + + // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } + + // Per 4.2.1.2 Throw error if too many uuids are requested + if (nsecs >= 10000) { + throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; + + // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + msecs += 12219292800000; + + // `time_low` + var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; + + // `time_mid` + var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; + + // `time_high_and_version` + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + b[i++] = tmh >>> 16 & 0xff; + + // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + b[i++] = clockseq >>> 8 | 0x80; + + // `clock_seq_low` + b[i++] = clockseq & 0xff; + + // `node` + var node = options.node || _nodeId; + for (var n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf ? buf : buff_to_string(b); +} + +// **`v4()` - Generate random UUID** + +// See https://github.com/broofa/node-uuid for API details +function v4(options, buf, offset) { + // Deprecated - 'format' argument, as supported in v1.2 + var i = buf && offset || 0; + + if (typeof(options) == 'string') { + buf = options == 'binary' ? new Array(16) : null; + options = null; + } + options = options || {}; + + var rnds = options.random || (options.rng || _rng)(); + + // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + rnds[6] = (rnds[6] & 0x0f) | 0x40; + rnds[8] = (rnds[8] & 0x3f) | 0x80; + + // Copy bytes to buffer, if provided + if (buf) { + for (var ii = 0; ii < 16; ++ii) { + buf[i + ii] = rnds[ii]; + } + } + + return buf || buff_to_string(rnds); +} + +// Export public API +var uuid = v4; +uuid.v1 = v1; +uuid.v4 = v4; + +module.exports = uuid; + + +/***/ }, +/* 16 */ +/***/ function(module, exports) { + +var g; + +// This works in non-strict mode +g = (function() { return this; })(); + +try { + // This works if eval is allowed (see CSP) + g = g || Function("return this")() || (1,eval)("this"); +} catch(e) { + // This works if the window reference is available + if(typeof window === "object") + g = window; +} + +// g can still be undefined, but nothing to do about it... +// We return undefined, instead of nothing here, so it's +// easier to handle this case. if(!global) { ...} + +module.exports = g; + + +/***/ }, +/* 17 */ +/***/ function(module, exports) { + +/* (ignored) */ + +/***/ }, +/* 18 */ +/***/ function(module, exports, __webpack_require__) { + +module.exports = { + version: __webpack_require__(6).version, + Client: __webpack_require__(7), + RPC: __webpack_require__(2), + Rest: __webpack_require__(1), + Constants: __webpack_require__(0) +} + +if (typeof window !== 'undefined') window.DiscordRPC = module.exports; + + +/***/ } +/******/ ]); \ No newline at end of file diff --git a/webpack/rpc.2.0.0.es6.min.js b/webpack/rpc.2.0.0.es6.min.js new file mode 100644 index 0000000..21039d8 --- /dev/null +++ b/webpack/rpc.2.0.0.es6.min.js @@ -0,0 +1 @@ +!function(t){function e(i){if(n[i])return n[i].exports;var r=n[i]={i:i,l:!1,exports:{}};return t[i].call(r.exports,r,r.exports,e),r.l=!0,r.exports}var n={};return e.m=t,e.c=n,e.i=function(t){return t},e.d=function(t,e,n){Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:n})},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=18)}([function(t,e){const n=t=>{let e={};for(const n of t)e[n]=n;return e};t.exports.RPCCommands=n(["DISPATCH","AUTHORIZE","AUTHENTICATE","GET_GUILD","GET_GUILDS","GET_CHANNEL","GET_CHANNELS","SUBSCRIBE","UNSUBSCRIBE","SET_USER_VOICE_SETTINGS","SELECT_VOICE_CHANNEL","GET_VOICE_SETTINGS","SET_VOICE_SETTINGS","SELECT_TEXT_CHANNEL","INVITE_BROWSER"]),t.exports.RPCEvents=n(["READY","ERROR","GUILD_STATUS","GUILD_CREATE","CHANNEL_CREATE","VOICE_STATE_CREATE","VOICE_STATE_DELETE","VOICE_STATE_UPDATE","VOICE_SETTINGS_UPDATE","VOICE_CONNECTION_STATUS","SPEAKING_START","SPEAKING_STOP","MESSAGE_CREATE","MESSAGE_UPDATE","MESSAGE_DELETE"]),t.exports.RPCErrors={UNKNOWN_ERROR:1e3,INVALID_PAYLOAD:4e3,INVALID_VERSION:4001,INVALID_COMMAND:4002,INVALID_GUILD:4003,INVALID_EVENT:4004,INVALID_CHANNEL:4005,INVALID_PERMISSIONS:4006,INVALID_CLIENTID:4007,INVALID_ORIGIN:4008,INVALID_TOKEN:4009,INVALID_USER:4010,OAUTH2_ERROR:5e3},t.exports.RPCCloseCodes={INVALID_CLIENTID:4e3,INVALID_ORIGIN:4001,RATELIMITED:4002,TOKEN_REVOKED:4003},t.exports.ChannelTypes={DM:1,GROUP_DM:3,GUILD_TEXT:0,GUILD_VOICE:2};const i=t.exports.Endpoints={login:"/auth/login",logout:"/auth/logout",gateway:"/gateway",botGateway:"/gateway/bot",invite:t=>`/invite/${t}`,inviteLink:t=>`https://discord.gg/${t}`,CDN:"https://cdn.discordapp.com",user:t=>`/users/${t}`,userChannels:t=>`${i.user(t)}/channels`,userProfile:t=>`${i.user(t)}/profile`,avatar:(t,e)=>"1"===t?e:`${i.user(t)}/avatars/${e}.jpg`,me:"/users/@me",meGuild:t=>`${i.me}/guilds/${t}`,relationships:t=>`${i.user(t)}/relationships`,note:t=>`${i.me}/notes/${t}`,guilds:"/guilds",guild:t=>`${i.guilds}/${t}`,guildIcon:(t,e)=>`${i.guild(t)}/icons/${e}.jpg`,guildPrune:t=>`${i.guild(t)}/prune`,guildEmbed:t=>`${i.guild(t)}/embed`,guildInvites:t=>`${i.guild(t)}/invites`,guildRoles:t=>`${i.guild(t)}/roles`,guildRole:(t,e)=>`${i.guildRoles(t)}/${e}`,guildBans:t=>`${i.guild(t)}/bans`,guildIntegrations:t=>`${i.guild(t)}/integrations`,guildMembers:t=>`${i.guild(t)}/members`,guildMember:(t,e)=>`${i.guildMembers(t)}/${e}`,guildMemberRole:(t,e,n)=>`${i.guildMember(t,e)}/roles/${n}`,stupidInconsistentGuildEndpoint:t=>`${i.guildMember(t,"@me")}/nick`,guildChannels:t=>`${i.guild(t)}/channels`,guildEmojis:t=>`${i.guild(t)}/emojis`,channels:"/channels",channel:t=>`${i.channels}/${t}`,channelMessages:t=>`${i.channel(t)}/messages`,channelInvites:t=>`${i.channel(t)}/invites`,channelTyping:t=>`${i.channel(t)}/typing`,channelPermissions:t=>`${i.channel(t)}/permissions`,channelMessage:(t,e)=>`${i.channelMessages(t)}/${e}`,channelWebhooks:t=>`${i.channel(t)}/webhooks`,messageReactions:(t,e)=>`${i.channelMessage(t,e)}/reactions`,messageReaction:(t,e,n,r)=>`${i.messageReactions(t,e)}/${n}${r?`?limit=${r}`:""}`,selfMessageReaction:(t,e,n,r)=>`${i.messageReaction(t,e,n,r)}/@me`,userMessageReaction:(t,e,n,r,s)=>`${i.messageReaction(t,e,n,r)}/${s}`,webhook:(t,e)=>`/webhooks/${t}${e?`/${e}`:""}`,myApplication:"/oauth2/applications/@me",getApp:t=>`/oauth2/authorize?client_id=${t}`}},function(t,e,n){const i=n(4),{Endpoints}=n(0);t.exports=class t{constructor(t){this.client=t}makeRequest(t,e,n={},r={}){return new Promise((s,o)=>{r.Authorization=`Bearer ${this.client.accessToken}`,i[t.toLowerCase()](`https://${this.client.hostAndPort}${e}`).set(r).send(n).then(t=>s(t.body),o)})}sendMessage(t,e){return this.makeRequest("post",Endpoints.channelMessages(t),{content:e})}editMessage(t,e,n){return this.makeRequest("patch",Endpoints.channelMessage(t,e),{content:n})}deleteMessage(t,e){return this.makeRequest("delete",Endpoints.channelMessage(t,e))}}},function(t,e,n){function i(t,e,n){return`${t}:${e||n}`}const r="undefined"!=typeof window?window.WebSocket:n(17),s=n(3).EventEmitter,{RPCCommands,RPCEvents,RPCErrors}=n(0),o=n(4),u=n(9),c=n(15).v4,a=n(1);class h{constructor(t){this.evts=new s,this.activeSubscriptions=[],this.queue=[],this.connected=!1,this.ready=!1,this.requestedDisconnect=!1,this.connectionTries=0,this.socket=null,this.config={},this.OAUTH2_CLIENT_ID=t.OAUTH2_CLIENT_ID,this.API_ENDPOINT=t.API_ENDPOINT||"",this.rest=new a(this)}connect(t=this.accessToken,e=0){if(!this.connected){this.accessToken=t;const n=6463+e%10;this.hostAndPort=`${c()}.discordapp.io:${n}`,this.socket=new r(`wss://${this.hostAndPort}/?v=1&client_id=${this.OAUTH2_CLIENT_ID}`),this.socket.onopen=this._handleOpen.bind(this),this.socket.onclose=this._handleClose.bind(this),this.socket.onmessage=this._handleMessage.bind(this)}}disconnect(t){this.connected&&(this.requestedDisconnect=!0,this.socket.close(),t&&t())}reconnect(){this.connected&&this.socket.close()}authenticate(){if(!this.authenticated)return this.accessToken?void this.request("AUTHENTICATE",{access_token:this.accessToken},(t,e)=>{return t&&t.code===RPCErrors.INVALID_TOKEN?void this.authorize():(this.authenticated=!0,this.flushQueue(),void this.activeSubscriptions.forEach(t=>this.subscribe(t.evt,t.args,t.callback)))}):void this.authorize()}flushQueue(){const t=this.queue;this.queue=[],t.forEach(t=>t())}authorize(){this.authenticated||o.get(`${this.API_ENDPOINT}/token`).then(t=>{if(!t.ok||!t.body.rpc_token)throw new Error("no rpc token");return this.request("AUTHORIZE",{client_id:this.OAUTH2_CLIENT_ID,scopes:["rpc","rpc.api"],rpc_token:t.body.rpc_token})}).then(t=>o.post(`${this.API_ENDPOINT}/token`).send({code:t.code})).then(t=>{if(!t.ok)throw new Error("no access token");this.accessToken=t.body.access_token,this.authenticate()}).catch(t=>{setTimeout(this.authorize.bind(this),3e3)})}request(t,e,n,r){return"function"==typeof n&&(r=n,n=void 0),new Promise((s,o)=>{if(!this.connected||!this.ready||!this.authenticated&&["AUTHORIZE","AUTHENTICATE"].indexOf(t)===-1)return void this.queue.push(()=>this.request(t,e,n,r));const u=c();this.evts.once(i(RPCCommands.DISPATCH,u),(t,e)=>{r&&r(t,e),t?o(t):s(e)}),this.socket.send(JSON.stringify({cmd:t,args:e,evt:n,nonce:u}))})}subscribe(t,e,n){this.request(RPCCommands.SUBSCRIBE,e,t,r=>{return r?void(n&&n(r)):void(this.activeSubscriptions.find(t=>{return n===t.callback})||(this.activeSubscriptions.push({evt:t,args:e,callback:n}),this.evts.on(i(RPCCommands.DISPATCH,null,t),t=>{n&&n(null,t)})))})}unsubscribe(t,e,n){this.request(RPCCommands.UNSUBSCRIBE,e,t,r=>{if(r)return void(n&&n(r));for(const s in this.activeSubscriptions){const n=this.activeSubscriptions[s];t===n.evt&&u(e,n.args)&&this.activeSubscriptions.splice(s,1)}const o=i(RPCCommands.DISPATCH,null,t);this.evts.listeners(o).forEach(t=>{this.evts.removeListener(o,t)}),n&&n()})}_handleOpen(){this.connected=!0,this.authenticate()}_handleClose(t){if(this.connected=!1,this.authenticated=!1,this.ready=!1,console.error("WS Closed:",t),this.requestedDisconnect)return void(this.requestedDisconnect=!1);try{this.socket.close()}catch(t){}setTimeout(()=>this.connect(null,1006===t.code?++this.connectionTries:0),250)}_handleMessage(t){let e=null;try{e=JSON.parse(t.data)}catch(t){return void console.error("Payload not JSON:",e)}let{cmd,evt,nonce,data}=e;if(cmd===RPCCommands.AUTHENTICATE){if(evt===RPCEvents.ERROR)return void this.evts.emit("ERROR",data);this.user=data.user,this.application=data.application,this.evts.emit("READY",data)}if(cmd===RPCCommands.DISPATCH)return evt===RPCEvents.READY?(this.config=data.config,this.ready=!0,void this.flushQueue()):evt===RPCEvents.ERROR?(console.error("Dispatched Error",data),void this.socket.close()):void this.evts.emit(i(RPCCommands.DISPATCH,null,evt),data);let n=null;evt===RPCEvents.ERROR&&(n=new Error(data.message),n.code=data.code,data=null),this.evts.emit(i(RPCCommands.DISPATCH,nonce),n,data)}}t.exports=h},function(t,e){function n(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(t){return"function"==typeof t}function r(t){return"number"==typeof t}function s(t){return"object"==typeof t&&null!==t}function o(t){return void 0===t}t.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.prototype.setMaxListeners=function(t){if(!r(t)||t<0||isNaN(t))throw TypeError("n must be a positive number");return this._maxListeners=t,this},n.prototype.emit=function(t){var e,n,r,u,c,a;if(this._events||(this._events={}),"error"===t&&(!this._events.error||s(this._events.error)&&!this._events.error.length)){if(e=arguments[1],e instanceof Error)throw e;var h=new Error('Uncaught, unspecified "error" event. ('+e+")");throw h.context=e,h}if(n=this._events[t],o(n))return!1;if(i(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:u=Array.prototype.slice.call(arguments,1),n.apply(this,u)}else if(s(n))for(u=Array.prototype.slice.call(arguments,1),a=n.slice(),r=a.length,c=0;c0&&this._events[t].length>r&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace())),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(t,e){function n(){this.removeListener(t,n),r||(r=!0,e.apply(this,arguments))}if(!i(e))throw TypeError("listener must be a function");var r=!1;return n.listener=e,this.on(t,n),this},n.prototype.removeListener=function(t,e){var n,r,o,u;if(!i(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(n=this._events[t],o=n.length,r=-1,n===e||i(n.listener)&&n.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(s(n)){for(u=o;u-- >0;)if(n[u]===e||n[u].listener&&n[u].listener===e){r=u;break}if(r<0)return this;1===n.length?(n.length=0,delete this._events[t]):n.splice(r,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},n.prototype.removeAllListeners=function(t){var e,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(n=this._events[t],i(n))this.removeListener(t,n);else if(n)for(;n.length;)this.removeListener(t,n[n.length-1]);return delete this._events[t],this},n.prototype.listeners=function(t){var e;return e=this._events&&this._events[t]?i(this._events[t])?[this._events[t]]:this._events[t].slice():[]},n.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(i(e))return 1;if(e)return e.length}return 0},n.listenerCount=function(t,e){return t.listenerCount(e)}},function(t,e,n){function i(){}function r(t){if(!y(t))return t;var e=[];for(var n in t)s(e,n,t[n]);return e.join("&")}function s(t,e,n){if(null!=n)if(Array.isArray(n))n.forEach(function(n){s(t,e,n)});else if(y(n))for(var i in n)s(t,e+"["+i+"]",n[i]);else t.push(encodeURIComponent(e)+"="+encodeURIComponent(n));else null===n&&t.push(encodeURIComponent(e))}function o(t){for(var e,n,i={},r=t.split("&"),s=0,o=r.length;s=300)&&(i=new Error(e.statusText||"Unsuccessful HTTP response"),i.original=t,i.response=e,i.status=e.status)}catch(t){i=t}i?n.callback(i,e):n.callback(null,e)})}function f(t,e){var n=m("DELETE",t);return e&&n.end(e),n}var d;"undefined"!=typeof window?d=window:"undefined"!=typeof self?d=self:(console.warn("Using browser-only version of superagent in non-browser environment"),d=this);var _=n(8),v=n(12),y=n(5),m=t.exports=n(13).bind(null,p);m.getXHR=function(){if(!(!d.XMLHttpRequest||d.location&&"file:"==d.location.protocol&&d.ActiveXObject))return new XMLHttpRequest;try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(t){}try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(t){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(t){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(t){}throw Error("Browser-only verison of superagent could not find XHR")};var E="".trim?function(t){return t.trim()}:function(t){return t.replace(/(^\s*|\s*$)/g,"")};m.serializeObject=r,m.parseString=o,m.types={html:"text/html",json:"application/json",xml:"application/xml",urlencoded:"application/x-www-form-urlencoded",form:"application/x-www-form-urlencoded","form-data":"application/x-www-form-urlencoded"},m.serialize={"application/x-www-form-urlencoded":r,"application/json":JSON.stringify},m.parse={"application/x-www-form-urlencoded":o,"application/json":JSON.parse},l.prototype.get=function(t){return this.header[t.toLowerCase()]},l.prototype._setHeaderProperties=function(t){var e=this.header["content-type"]||"";this.type=a(e);var n=h(e);for(var i in n)this[i]=n[i]},l.prototype._parseBody=function(t){var e=m.parse[this.type];return!e&&c(this.type)&&(e=m.parse["application/json"]),e&&t&&(t.length||t instanceof Object)?e(t):null},l.prototype._setStatusProperties=function(t){1223===t&&(t=204);var e=t/100|0;this.status=this.statusCode=t,this.statusType=e,this.info=1==e,this.ok=2==e,this.clientError=4==e,this.serverError=5==e,this.error=(4==e||5==e)&&this.toError(),this.accepted=202==t,this.noContent=204==t,this.badRequest=400==t,this.unauthorized=401==t,this.notAcceptable=406==t,this.notFound=404==t,this.forbidden=403==t},l.prototype.toError=function(){var t=this.req,e=t.method,n=t.url,i="cannot "+e+" "+n+" ("+this.status+")",r=new Error(i);return r.status=this.status,r.method=e,r.url=n,r},m.Response=l,_(p.prototype),v(p.prototype),p.prototype.type=function(t){return this.set("Content-Type",m.types[t]||t),this},p.prototype.responseType=function(t){return this._responseType=t,this},p.prototype.accept=function(t){return this.set("Accept",m.types[t]||t),this},p.prototype.auth=function(t,e,n){switch(n||(n={type:"basic"}),n.type){case"basic":var i=btoa(t+":"+e);this.set("Authorization","Basic "+i);break;case"auto":this.username=t,this.password=e}return this},p.prototype.query=function(t){return"string"!=typeof t&&(t=r(t)),t&&this._query.push(t),this},p.prototype.attach=function(t,e,n){if(this._data)throw Error("superagent can't mix .send() and .attach()");return this._getFormData().append(t,e,n||e.name),this},p.prototype._getFormData=function(){return this._formData||(this._formData=new d.FormData),this._formData},p.prototype.callback=function(t,e){var n=this._callback;this.clearTimeout(),t&&this.emit("error",t),n(t,e)},p.prototype.crossDomainError=function(){var t=new Error("Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.");t.crossDomain=!0,t.status=this.status,t.method=this.method,t.url=this.url,this.callback(t)},p.prototype.buffer=p.prototype.ca=p.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},p.prototype.pipe=p.prototype.write=function(){throw Error("Streaming is not supported in browser version of superagent")},p.prototype._timeoutError=function(){var t=this._timeout,e=new Error("timeout of "+t+"ms exceeded");e.timeout=t,this.callback(e)},p.prototype._appendQueryString=function(){var t=this._query.join("&");t&&(this.url+=~this.url.indexOf("?")?"&"+t:"?"+t)},p.prototype._isHost=function(t){return t&&"object"==typeof t&&!Array.isArray(t)&&"[object Object]"!==Object.prototype.toString.call(t)},p.prototype.end=function(t){var e=this,n=this.xhr=m.getXHR(),r=this._timeout,s=this._formData||this._data;this._callback=t||i,n.onreadystatechange=function(){if(4==n.readyState){var t;try{t=n.status}catch(e){t=0}if(0==t){if(e.timedout)return e._timeoutError();if(e._aborted)return;return e.crossDomainError()}e.emit("end")}};var o=function(t,n){n.total>0&&(n.percent=n.loaded/n.total*100),n.direction=t,e.emit("progress",n)};if(this.hasListeners("progress"))try{n.onprogress=o.bind(null,"download"),n.upload&&(n.upload.onprogress=o.bind(null,"upload"))}catch(t){}if(r&&!this._timer&&(this._timer=setTimeout(function(){e.timedout=!0,e.abort()},r)),this._appendQueryString(),this.username&&this.password?n.open(this.method,this.url,!0,this.username,this.password):n.open(this.method,this.url,!0),this._withCredentials&&(n.withCredentials=!0),"GET"!=this.method&&"HEAD"!=this.method&&"string"!=typeof s&&!this._isHost(s)){var u=this._header["content-type"],a=this._serializer||m.serialize[u?u.split(";")[0]:""];!a&&c(u)&&(a=m.serialize["application/json"]),a&&(s=a(s))}for(var h in this.header)null!=this.header[h]&&n.setRequestHeader(h,this.header[h]);return this._responseType&&(n.responseType=this._responseType),this.emit("request",this),n.send("undefined"!=typeof s?s:null),this},m.Request=p,m.get=function(t,e,n){var i=m("GET",t);return"function"==typeof e&&(n=e,e=null),e&&i.query(e),n&&i.end(n),i},m.head=function(t,e,n){var i=m("HEAD",t);return"function"==typeof e&&(n=e,e=null),e&&i.send(e),n&&i.end(n),i},m.options=function(t,e,n){var i=m("OPTIONS",t);return"function"==typeof e&&(n=e,e=null),e&&i.send(e),n&&i.end(n),i},m.del=f,m.delete=f,m.patch=function(t,e,n){var i=m("PATCH",t);return"function"==typeof e&&(n=e,e=null),e&&i.send(e),n&&i.end(n),i},m.post=function(t,e,n){var i=m("POST",t);return"function"==typeof e&&(n=e,e=null),e&&i.send(e),n&&i.end(n),i},m.put=function(t,e,n){var i=m("PUT",t);return"function"==typeof e&&(n=e,e=null),e&&i.send(e),n&&i.end(n),i}},function(t,e){function n(t){return null!==t&&"object"==typeof t}t.exports=n},function(t,e){t.exports={name:"discord-rpc",version:"2.0.0",description:"A simple RPC client for Discord somewhat stolen from the Discord StreamKit.",main:"src/index.js",repository:{type:"git",url:"git+https://github.com/GusCaplan/discord-rpc.git"},scripts:{"web-dist":"node ./node_modules/parallel-webpack/bin/run.js"},author:"Gus Caplan ",license:"MIT",bugs:{url:"https://github.com/GusCaplan/discord-rpc/issues"},homepage:"https://github.com/GusCaplan/discord-rpc#readme",dependencies:{"deep-equal":"^1.0.1",superagent:"^3.0.0",uuid:"^3.0.0",ws:"^1.1.1"},devDependencies:{"babel-core":"^6.18.2","babel-loader":"^6.2.8","babel-preset-es2015":"^6.18.0",bufferutil:"^1.2.1","ignore-loader":"^0.1.2","json-loader":"^0.5.4","parallel-webpack":"^1.5.0","uglify-js":"github:mishoo/UglifyJS2#harmony","utf-8-validate":"^1.2.1",webpack:"2.1.0-beta.27"},browser:{ws:!1}}},function(t,e,n){const i=n(2),r=n(3).EventEmitter;class s extends r{constructor({OAUTH2_CLIENT_ID}={}){super(),this.rpc=new i({OAUTH2_CLIENT_ID:OAUTH2_CLIENT_ID}),this.rpc.evts.on("READY",()=>{this.user=this.rpc.user,this.application=this.rpc.application,this.emit("ready")}),this.rpc.evts.on("ERROR",t=>this.emit("error",t)),this.rest=this.rpc.rest}getGuild(t,e){return new Promise((n,i)=>{this.rpc.request("GET_GUILD",{guild_id:t,timeout:e},(t,e)=>{t&&i(t),n(e.data)})})}getGuilds(){return new Promise((t,e)=>{this.rpc.request("GET_GUILDS",{},(n,i)=>{n&&e(n),t(i.data.guilds)})})}getChannel(t,e){return new Promise((n,i)=>{this.rpc.request("GET_CHANNEL",{channel_id:t,timeout:e},(t,e)=>{t&&i(t),n(e.data)})})}getChannels(){return new Promise((t,e)=>{this.rpc.request("GET_CHANNELS",{},(n,i)=>{n&&e(n),t(i.data.channels)})})}setUserVoiceSettings(t){return new Promise((e,n)=>{this.rpc.request("SET_USER_VOICE_SETTINGS",t,(t,i)=>{t&&n(t),e(i.data)})})}selectVoiceChannel(t,e,n=false){return new Promise((i,r)=>{this.rpc.request("SELECT_VOICE_CHANNEL",{channel_id:t,timeout:e,force:n},(t,e)=>{t&&r(t),i(e.data)})})}selectTextChannel(t,e,n=false){return new Promise((i,r)=>{this.rpc.request("SELECT_TEXT_CHANNEL",{channel_id:t,timeout:e,force:n},(t,e)=>{t&&r(t),i(e.data)})})}getVoiceSettings(){return new Promise((t,e)=>{this.rpc.request("GET_VOICE_SETTINGS",{},(n,i)=>{n&&e(n),t(i.data)})})}setVoiceSettings(t){return new Promise((e,n)=>{this.rpc.request("SET_VOICE_SETTINGS",t,(t,i)=>{t&&n(t),e(i.data)})})}subscribe(t,e,n){return this.rpc.subscribe(t,e,n)}unsubscribe(t,e,n){return this.rpc.unsubscribe(t,e,n)}connect(t){return this.rpc.connect(t)}}t.exports=s},function(t,e,n){function i(t){if(t)return r(t)}function r(t){for(var e in i.prototype)t[e]=i.prototype[e];return t}t.exports=i,i.prototype.on=i.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},i.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},i.prototype.off=i.prototype.removeListener=i.prototype.removeAllListeners=i.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n=this._callbacks["$"+t];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var i,r=0;r0&&"number"!=typeof t[0]))}function s(t,e,n){var s,h;if(i(t)||i(e))return!1;if(t.prototype!==e.prototype)return!1;if(c(t))return!!c(e)&&(t=o.call(t),e=o.call(e),a(t,e,n));if(r(t)){if(!r(e))return!1;if(t.length!==e.length)return!1;for(s=0;s=0;s--)if(l[s]!=p[s])return!1;for(s=l.length-1;s>=0;s--)if(h=l[s],!a(t[h],e[h],n))return!1;return typeof t==typeof e}var o=Array.prototype.slice,u=n(11),c=n(10),a=t.exports=function(t,e,n){return n||(n={}),t===e||(t instanceof Date&&e instanceof Date?t.getTime()===e.getTime():!t||!e||"object"!=typeof t&&"object"!=typeof e?n.strict?t===e:t==e:s(t,e,n))}},function(t,e){function n(t){return"[object Arguments]"==Object.prototype.toString.call(t)}function i(t){return t&&"object"==typeof t&&"number"==typeof t.length&&Object.prototype.hasOwnProperty.call(t,"callee")&&!Object.prototype.propertyIsEnumerable.call(t,"callee")||!1}var r="[object Arguments]"==function(){return Object.prototype.toString.call(arguments)}();e=t.exports=r?n:i,e.supported=n,e.unsupported=i},function(t,e){function n(t){var e=[];for(var n in t)e.push(n);return e}e=t.exports="function"==typeof Object.keys?Object.keys:n,e.shim=n},function(t,e,n){function i(t){if(t)return r(t)}function r(t){for(var e in i.prototype)t[e]=i.prototype[e];return t}var s=n(5);t.exports=i,i.prototype.clearTimeout=function(){return this._timeout=0,clearTimeout(this._timer),this},i.prototype.parse=function(t){return this._parser=t,this},i.prototype.serialize=function(t){return this._serializer=t,this},i.prototype.timeout=function(t){return this._timeout=t,this},i.prototype.then=function(t,e){if(!this._fullfilledPromise){var n=this;this._fullfilledPromise=new Promise(function(t,e){n.end(function(n,i){n?e(n):t(i)})})}return this._fullfilledPromise.then(t,e)},i.prototype.catch=function(t){return this.then(void 0,t)},i.prototype.use=function(t){return t(this),this},i.prototype.get=function(t){return this._header[t.toLowerCase()]},i.prototype.getHeader=i.prototype.get,i.prototype.set=function(t,e){if(s(t)){for(var n in t)this.set(n,t[n]);return this}return this._header[t.toLowerCase()]=e,this.header[t]=e,this},i.prototype.unset=function(t){return delete this._header[t.toLowerCase()],delete this.header[t],this},i.prototype.field=function(t,e){if(null===t||void 0===t)throw new Error(".field(name, val) name can not be empty");if(s(t)){for(var n in t)this.field(n,t[n]);return this}if(null===e||void 0===e)throw new Error(".field(name, val) val can not be empty");return this._getFormData().append(t,e),this},i.prototype.abort=function(){return this._aborted?this:(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req&&this.req.abort(),this.clearTimeout(),this.emit("abort"),this)},i.prototype.withCredentials=function(){return this._withCredentials=!0,this},i.prototype.redirects=function(t){return this._maxRedirects=t,this},i.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},i.prototype.send=function(t){var e=s(t),n=this._header["content-type"];if(e&&!this._data)Array.isArray(t)?this._data=[]:this._isHost(t)||(this._data={});else if(t&&this._data&&this._isHost(this._data))throw Error("Can't merge these send calls");if(e&&s(this._data))for(var i in t)this._data[i]=t[i];else"string"==typeof t?(n||this.type("form"),n=this._header["content-type"],"application/x-www-form-urlencoded"==n?this._data=this._data?this._data+"&"+t:t:this._data=(this._data||"")+t):this._data=t;return!e||this._isHost(t)?this:(n||this.type("json"),this)}},function(t,e){function n(t,e,n){return"function"==typeof n?new t("GET",e).end(n):2==arguments.length?new t("GET",e):new t(e,n)}t.exports=n},function(t,e,n){(function(e){var n,i=e.crypto||e.msCrypto;if(i&&i.getRandomValues){var r=new Uint8Array(16);n=function(){return i.getRandomValues(r),r}}if(!n){var s=new Array(16);n=function(){for(var t,e=0;e<16;e++)0===(3&e)&&(t=4294967296*Math.random()),s[e]=t>>>((3&e)<<3)&255;return s}}t.exports=n}).call(e,n(16))},function(t,e,n){function i(t,e){var n=e||0,i=u;return i[t[n++]]+i[t[n++]]+i[t[n++]]+i[t[n++]]+"-"+i[t[n++]]+i[t[n++]]+"-"+i[t[n++]]+i[t[n++]]+"-"+i[t[n++]]+i[t[n++]]+"-"+i[t[n++]]+i[t[n++]]+i[t[n++]]+i[t[n++]]+i[t[n++]]+i[t[n++]]}function r(t,e,n){var r=e&&n||0,s=e||[];t=t||{};var o=void 0!==t.clockseq?t.clockseq:p,u=void 0!==t.msecs?t.msecs:(new Date).getTime(),c=void 0!==t.nsecs?t.nsecs:d+1,a=u-f+(c-d)/1e4;if(a<0&&void 0===t.clockseq&&(o=o+1&16383),(a<0||u>f)&&void 0===t.nsecs&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");f=u,d=c,p=o,u+=122192928e5;var h=(1e4*(268435455&u)+c)%4294967296;s[r++]=h>>>24&255,s[r++]=h>>>16&255,s[r++]=h>>>8&255,s[r++]=255&h;var _=u/4294967296*1e4&268435455;s[r++]=_>>>8&255,s[r++]=255&_,s[r++]=_>>>24&15|16,s[r++]=_>>>16&255,s[r++]=o>>>8|128,s[r++]=255&o;for(var v=t.node||l,y=0;y<6;++y)s[r+y]=v[y];return e?e:i(s)}function s(t,e,n){var r=e&&n||0;"string"==typeof t&&(e="binary"==t?new Array(16):null,t=null),t=t||{};var s=t.random||(t.rng||o)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,e)for(var u=0;u<16;++u)e[r+u]=s[u];return e||i(s)}for(var o=n(14),u=[],c={},a=0;a<256;++a)u[a]=(a+256).toString(16).substr(1),c[u[a]]=a;var h=o(),l=[1|h[0],h[1],h[2],h[3],h[4],h[5]],p=16383&(h[6]<<8|h[7]),f=0,d=0,_=s;_.v1=r,_.v4=s,t.exports=_},function(t,e){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(t){"object"==typeof window&&(n=window)}t.exports=n},function(t,e){},function(t,e,n){t.exports={version:n(6).version,Client:n(7),RPC:n(2),Rest:n(1),Constants:n(0)},"undefined"!=typeof window&&(window.DiscordRPC=t.exports)}]); \ No newline at end of file diff --git a/webpack/rpc.2.0.0.js b/webpack/rpc.2.0.0.js new file mode 100644 index 0000000..47dad72 --- /dev/null +++ b/webpack/rpc.2.0.0.js @@ -0,0 +1,3201 @@ +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.l = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // identity function for calling harmory imports with the correct context +/******/ __webpack_require__.i = function(value) { return value; }; + +/******/ // define getter function for harmory exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ Object.defineProperty(exports, name, { +/******/ configurable: false, +/******/ enumerable: true, +/******/ get: getter +/******/ }); +/******/ }; + +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; + +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 18); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ function(module, exports) { + +"use strict"; +'use strict'; + +var keyMirror = function keyMirror(arr) { + var tmp = {}; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = arr[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var value = _step.value; + tmp[value] = value; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + return tmp; +}; + +module.exports.RPCCommands = keyMirror(['DISPATCH', 'AUTHORIZE', 'AUTHENTICATE', 'GET_GUILD', 'GET_GUILDS', 'GET_CHANNEL', 'GET_CHANNELS', 'SUBSCRIBE', 'UNSUBSCRIBE', 'SET_USER_VOICE_SETTINGS', 'SELECT_VOICE_CHANNEL', 'GET_VOICE_SETTINGS', 'SET_VOICE_SETTINGS', 'SELECT_TEXT_CHANNEL', 'INVITE_BROWSER' // just for kicks +]); + +module.exports.RPCEvents = keyMirror(['READY', 'ERROR', 'GUILD_STATUS', 'GUILD_CREATE', 'CHANNEL_CREATE', 'VOICE_STATE_CREATE', 'VOICE_STATE_DELETE', 'VOICE_STATE_UPDATE', 'VOICE_SETTINGS_UPDATE', 'VOICE_CONNECTION_STATUS', 'SPEAKING_START', 'SPEAKING_STOP', 'MESSAGE_CREATE', 'MESSAGE_UPDATE', 'MESSAGE_DELETE']); + +module.exports.RPCErrors = { + UNKNOWN_ERROR: 1000, + + INVALID_PAYLOAD: 4000, + INVALID_VERSION: 4001, + INVALID_COMMAND: 4002, + INVALID_GUILD: 4003, + INVALID_EVENT: 4004, + INVALID_CHANNEL: 4005, + INVALID_PERMISSIONS: 4006, + INVALID_CLIENTID: 4007, + INVALID_ORIGIN: 4008, + INVALID_TOKEN: 4009, + INVALID_USER: 4010, + + OAUTH2_ERROR: 5000 +}; + +module.exports.RPCCloseCodes = { + INVALID_CLIENTID: 4000, + INVALID_ORIGIN: 4001, + RATELIMITED: 4002, + TOKEN_REVOKED: 4003 +}; + +module.exports.ChannelTypes = { + DM: 1, + GROUP_DM: 3, + GUILD_TEXT: 0, + GUILD_VOICE: 2 +}; + +// stolen from discord.js +var Endpoints = module.exports.Endpoints = { + // general + login: '/auth/login', + logout: '/auth/logout', + gateway: '/gateway', + botGateway: '/gateway/bot', + invite: function invite(id) { + return '/invite/' + id; + }, + inviteLink: function inviteLink(id) { + return 'https://discord.gg/' + id; + }, + CDN: 'https://cdn.discordapp.com', + + // users + user: function user(userID) { + return '/users/' + userID; + }, + userChannels: function userChannels(userID) { + return Endpoints.user(userID) + '/channels'; + }, + userProfile: function userProfile(userID) { + return Endpoints.user(userID) + '/profile'; + }, + avatar: function avatar(userID, _avatar) { + return userID === '1' ? _avatar : Endpoints.user(userID) + '/avatars/' + _avatar + '.jpg'; + }, + me: '/users/@me', + meGuild: function meGuild(guildID) { + return Endpoints.me + '/guilds/' + guildID; + }, + relationships: function relationships(userID) { + return Endpoints.user(userID) + '/relationships'; + }, + note: function note(userID) { + return Endpoints.me + '/notes/' + userID; + }, + + // guilds + guilds: '/guilds', + guild: function guild(guildID) { + return Endpoints.guilds + '/' + guildID; + }, + guildIcon: function guildIcon(guildID, hash) { + return Endpoints.guild(guildID) + '/icons/' + hash + '.jpg'; + }, + guildPrune: function guildPrune(guildID) { + return Endpoints.guild(guildID) + '/prune'; + }, + guildEmbed: function guildEmbed(guildID) { + return Endpoints.guild(guildID) + '/embed'; + }, + guildInvites: function guildInvites(guildID) { + return Endpoints.guild(guildID) + '/invites'; + }, + guildRoles: function guildRoles(guildID) { + return Endpoints.guild(guildID) + '/roles'; + }, + guildRole: function guildRole(guildID, roleID) { + return Endpoints.guildRoles(guildID) + '/' + roleID; + }, + guildBans: function guildBans(guildID) { + return Endpoints.guild(guildID) + '/bans'; + }, + guildIntegrations: function guildIntegrations(guildID) { + return Endpoints.guild(guildID) + '/integrations'; + }, + guildMembers: function guildMembers(guildID) { + return Endpoints.guild(guildID) + '/members'; + }, + guildMember: function guildMember(guildID, memberID) { + return Endpoints.guildMembers(guildID) + '/' + memberID; + }, + guildMemberRole: function guildMemberRole(guildID, memberID, roleID) { + return Endpoints.guildMember(guildID, memberID) + '/roles/' + roleID; + }, + stupidInconsistentGuildEndpoint: function stupidInconsistentGuildEndpoint(guildID) { + return Endpoints.guildMember(guildID, '@me') + '/nick'; + }, + guildChannels: function guildChannels(guildID) { + return Endpoints.guild(guildID) + '/channels'; + }, + guildEmojis: function guildEmojis(guildID) { + return Endpoints.guild(guildID) + '/emojis'; + }, + + // channels + channels: '/channels', + channel: function channel(channelID) { + return Endpoints.channels + '/' + channelID; + }, + channelMessages: function channelMessages(channelID) { + return Endpoints.channel(channelID) + '/messages'; + }, + channelInvites: function channelInvites(channelID) { + return Endpoints.channel(channelID) + '/invites'; + }, + channelTyping: function channelTyping(channelID) { + return Endpoints.channel(channelID) + '/typing'; + }, + channelPermissions: function channelPermissions(channelID) { + return Endpoints.channel(channelID) + '/permissions'; + }, + channelMessage: function channelMessage(channelID, messageID) { + return Endpoints.channelMessages(channelID) + '/' + messageID; + }, + channelWebhooks: function channelWebhooks(channelID) { + return Endpoints.channel(channelID) + '/webhooks'; + }, + + // message reactions + messageReactions: function messageReactions(channelID, messageID) { + return Endpoints.channelMessage(channelID, messageID) + '/reactions'; + }, + messageReaction: function messageReaction(channel, msg, emoji, limit) { + return Endpoints.messageReactions(channel, msg) + '/' + emoji + (limit ? '?limit=' + limit : ''); + }, + selfMessageReaction: function selfMessageReaction(channel, msg, emoji, limit) { + return Endpoints.messageReaction(channel, msg, emoji, limit) + '/@me'; + }, + userMessageReaction: function userMessageReaction(channel, msg, emoji, limit, id) { + return Endpoints.messageReaction(channel, msg, emoji, limit) + '/' + id; + }, + + // webhooks + webhook: function webhook(webhookID, token) { + return '/webhooks/' + webhookID + (token ? '/' + token : ''); + }, + + // oauth + myApplication: '/oauth2/applications/@me', + getApp: function getApp(id) { + return '/oauth2/authorize?client_id=' + id; + } +}; + +/***/ }, +/* 1 */ +/***/ function(module, exports, __webpack_require__) { + +"use strict"; +'use strict'; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var superagent = __webpack_require__(4); + +var _require = __webpack_require__(0), + Endpoints = _require.Endpoints; + +module.exports = function () { + function RESTClient(client) { + _classCallCheck(this, RESTClient); + + this.client = client; + } + + _createClass(RESTClient, [{ + key: 'makeRequest', + value: function makeRequest(method, path) { + var _this = this; + + var body = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var headers = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + + return new Promise(function (resolve, reject) { + headers.Authorization = 'Bearer ' + _this.client.accessToken; + superagent[method.toLowerCase()]('https://' + _this.client.hostAndPort + path).set(headers).send(body).then(function (res) { + return resolve(res.body); + }, reject); + }); + } + }, { + key: 'sendMessage', + value: function sendMessage(channelID, content) { + return this.makeRequest('post', Endpoints.channelMessages(channelID), { content: content }); + } + }, { + key: 'editMessage', + value: function editMessage(channelID, messageID, content) { + return this.makeRequest('patch', Endpoints.channelMessage(channelID, messageID), { content: content }); + } + }, { + key: 'deleteMessage', + value: function deleteMessage(channelID, messageID) { + return this.makeRequest('delete', Endpoints.channelMessage(channelID, messageID)); + } + }]); + + return RESTClient; +}(); + +/***/ }, +/* 2 */ +/***/ function(module, exports, __webpack_require__) { + +"use strict"; +'use strict'; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/* + Stolen from Discord's StreamKit Overlay by ```Macdja38 + Modified by Gus Caplan +*/ + +var WebSocket = typeof window !== 'undefined' ? window.WebSocket : __webpack_require__(17); // eslint-disable-line no-undef +var EventEmitter = __webpack_require__(3).EventEmitter; + +var _require = __webpack_require__(0), + RPCCommands = _require.RPCCommands, + RPCEvents = _require.RPCEvents, + RPCErrors = _require.RPCErrors; + +var superagent = __webpack_require__(4); +var deepEqual = __webpack_require__(9); +var uuid = __webpack_require__(15).v4; +var RESTClient = __webpack_require__(1); + +function getEventName(cmd, nonce, evt) { + return cmd + ':' + (nonce || evt); +} + +var RPCClient = function () { + function RPCClient(options) { + _classCallCheck(this, RPCClient); + + this.evts = new EventEmitter(); + this.activeSubscriptions = []; + this.queue = []; + this.connected = false; + this.ready = false; + this.requestedDisconnect = false; + this.connectionTries = 0; + this.socket = null; + this.config = {}; + this.OAUTH2_CLIENT_ID = options.OAUTH2_CLIENT_ID; + this.API_ENDPOINT = options.API_ENDPOINT || ''; + this.rest = new RESTClient(this); + } + + _createClass(RPCClient, [{ + key: 'connect', + value: function connect() { + var accessToken = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.accessToken; + var tries = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + + if (this.connected) return; + this.accessToken = accessToken; + var port = 6463 + tries % 10; + this.hostAndPort = uuid() + '.discordapp.io:' + port; + this.socket = new WebSocket('wss://' + this.hostAndPort + '/?v=1&client_id=' + this.OAUTH2_CLIENT_ID); // eslint-disable-line + this.socket.onopen = this._handleOpen.bind(this); + this.socket.onclose = this._handleClose.bind(this); + this.socket.onmessage = this._handleMessage.bind(this); + } + }, { + key: 'disconnect', + value: function disconnect(callback) { + if (!this.connected) return; + this.requestedDisconnect = true; + this.socket.close(); + if (callback) callback(); + } + }, { + key: 'reconnect', + value: function reconnect() { + if (!this.connected) return; + this.socket.close(); + } + }, { + key: 'authenticate', + value: function authenticate() { + var _this = this; + + if (this.authenticated) return; + if (!this.accessToken) { + this.authorize(); + return; + } + this.request('AUTHENTICATE', { + access_token: this.accessToken + }, function (e, r) { + if (e && e.code === RPCErrors.INVALID_TOKEN) { + _this.authorize(); + return; + } + _this.authenticated = true; + _this.flushQueue(); + _this.activeSubscriptions.forEach(function (s) { + return _this.subscribe(s.evt, s.args, s.callback); + }); + }); + } + }, { + key: 'flushQueue', + value: function flushQueue() { + var queue = this.queue; + this.queue = []; + queue.forEach(function (c) { + return c(); + }); + } + }, { + key: 'authorize', + value: function authorize() { + var _this2 = this; + + if (this.authenticated) return; + superagent.get(this.API_ENDPOINT + '/token').then(function (r) { + if (!r.ok || !r.body.rpc_token) { + throw new Error('no rpc token'); + } + return _this2.request('AUTHORIZE', { + client_id: _this2.OAUTH2_CLIENT_ID, + scopes: ['rpc', 'rpc.api'], + rpc_token: r.body.rpc_token + }); + }).then(function (r) { + return superagent.post(_this2.API_ENDPOINT + '/token').send({ + code: r.code + }); + }).then(function (r) { + if (!r.ok) { + throw new Error('no access token'); + } + _this2.accessToken = r.body.access_token; + _this2.authenticate(); + }).catch(function (e) { + setTimeout(_this2.authorize.bind(_this2), 3000); + }); + } + }, { + key: 'request', + value: function request(cmd, args, evt, callback) { + var _this3 = this; + + if (typeof evt === 'function') { + callback = evt; + evt = undefined; + } + return new Promise(function (resolve, reject) { + if (!_this3.connected || !_this3.ready || !_this3.authenticated && ['AUTHORIZE', 'AUTHENTICATE'].indexOf(cmd) === -1) { + _this3.queue.push(function () { + return _this3.request(cmd, args, evt, callback); + }); + return; + } + var nonce = uuid(); + _this3.evts.once(getEventName(RPCCommands.DISPATCH, nonce), function (err, res) { + if (callback) callback(err, res); + if (err) { + reject(err); + } else { + resolve(res); + } + }); + _this3.socket.send(JSON.stringify({ + cmd: cmd, + args: args, + evt: evt, + nonce: nonce + })); + }); + } + }, { + key: 'subscribe', + value: function subscribe(evt, args, callback) { + var _this4 = this; + + this.request(RPCCommands.SUBSCRIBE, args, evt, function (error) { + if (error) { + if (callback) callback(error); + return; + } + // on reconnect we resub to events, so don't dup listens + if (!_this4.activeSubscriptions.find(function (s) { + return callback === s.callback; + })) { + _this4.activeSubscriptions.push({ + evt: evt, + args: args, + callback: callback + }); + _this4.evts.on(getEventName(RPCCommands.DISPATCH, null, evt), function (d) { + if (callback) callback(null, d); + }); + } + }); + } + }, { + key: 'unsubscribe', + value: function unsubscribe(evt, args, callback) { + var _this5 = this; + + this.request(RPCCommands.UNSUBSCRIBE, args, evt, function (error) { + if (error) { + if (callback) callback(error); + return; + } + for (var i in _this5.activeSubscriptions) { + var s = _this5.activeSubscriptions[i]; + if (evt === s.evt && deepEqual(args, s.args)) _this5.activeSubscriptions.splice(i, 1); + } + var eventName = getEventName(RPCCommands.DISPATCH, null, evt); + _this5.evts.listeners(eventName).forEach(function (cb) { + _this5.evts.removeListener(eventName, cb); + }); + if (callback) callback(); + }); + } + }, { + key: '_handleOpen', + value: function _handleOpen() { + this.connected = true; + this.authenticate(); + } + }, { + key: '_handleClose', + value: function _handleClose(e) { + var _this6 = this; + + this.connected = false; + this.authenticated = false; + this.ready = false; + console.error('WS Closed:', e); + if (this.requestedDisconnect) { + this.requestedDisconnect = false; + return; + } + try { + this.socket.close(); + } catch (e) {} + setTimeout(function () { + return _this6.connect(null, e.code === 1006 ? ++_this6.connectionTries : 0); + }, 250); + } + }, { + key: '_handleMessage', + value: function _handleMessage(message) { + var payload = null; + try { + payload = JSON.parse(message.data); + } catch (e) { + console.error('Payload not JSON:', payload); + return; + } + var _payload = payload, + cmd = _payload.cmd, + evt = _payload.evt, + nonce = _payload.nonce, + data = _payload.data; + + + if (cmd === RPCCommands.AUTHENTICATE) { + if (evt === RPCEvents.ERROR) { + this.evts.emit('ERROR', data); + return; + } + this.user = data.user; + this.application = data.application; + this.evts.emit('READY', data); + } + if (cmd === RPCCommands.DISPATCH) { + if (evt === RPCEvents.READY) { + this.config = data.config; + this.ready = true; + this.flushQueue(); + return; + } + if (evt === RPCEvents.ERROR) { + console.error('Dispatched Error', data); + this.socket.close(); + return; + } + this.evts.emit(getEventName(RPCCommands.DISPATCH, null, evt), data); + return; + } + var error = null; + if (evt === RPCEvents.ERROR) { + error = new Error(data.message); + error.code = data.code; + data = null; + } + this.evts.emit(getEventName(RPCCommands.DISPATCH, nonce), error, data); + } + }]); + + return RPCClient; +}(); + +module.exports = RPCClient; + +/***/ }, +/* 3 */ +/***/ function(module, exports) { + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; +} +module.exports = EventEmitter; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function(n) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError('n must be a positive number'); + this._maxListeners = n; + return this; +}; + +EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; + + if (!this._events) + this._events = {}; + + // If there is no 'error' event listener then throw. + if (type === 'error') { + if (!this._events.error || + (isObject(this._events.error) && !this._events.error.length)) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + } + } + + handler = this._events[type]; + + if (isUndefined(handler)) + return false; + + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + args = Array.prototype.slice.call(arguments, 1); + handler.apply(this, args); + } + } else if (isObject(handler)) { + args = Array.prototype.slice.call(arguments, 1); + listeners = handler.slice(); + len = listeners.length; + for (i = 0; i < len; i++) + listeners[i].apply(this, args); + } + + return true; +}; + +EventEmitter.prototype.addListener = function(type, listener) { + var m; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events) + this._events = {}; + + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (this._events.newListener) + this.emit('newListener', type, + isFunction(listener.listener) ? + listener.listener : listener); + + if (!this._events[type]) + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + else + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; + + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; + } + + if (m && m > 0 && this._events[type].length > m) { + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); + } + } + } + + return this; +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + var fired = false; + + function g() { + this.removeListener(type, g); + + if (!fired) { + fired = true; + listener.apply(this, arguments); + } + } + + g.listener = listener; + this.on(type, g); + + return this; +}; + +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events || !this._events[type]) + return this; + + list = this._events[type]; + length = list.length; + position = -1; + + if (list === listener || + (isFunction(list.listener) && list.listener === listener)) { + delete this._events[type]; + if (this._events.removeListener) + this.emit('removeListener', type, listener); + + } else if (isObject(list)) { + for (i = length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list.length = 0; + delete this._events[type]; + } else { + list.splice(position, 1); + } + + if (this._events.removeListener) + this.emit('removeListener', type, listener); + } + + return this; +}; + +EventEmitter.prototype.removeAllListeners = function(type) { + var key, listeners; + + if (!this._events) + return this; + + // not listening for removeListener, no need to emit + if (!this._events.removeListener) { + if (arguments.length === 0) + this._events = {}; + else if (this._events[type]) + delete this._events[type]; + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; + } + + listeners = this._events[type]; + + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); + } + delete this._events[type]; + + return this; +}; + +EventEmitter.prototype.listeners = function(type) { + var ret; + if (!this._events || !this._events[type]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + ret = this._events[type].slice(); + return ret; +}; + +EventEmitter.prototype.listenerCount = function(type) { + if (this._events) { + var evlistener = this._events[type]; + + if (isFunction(evlistener)) + return 1; + else if (evlistener) + return evlistener.length; + } + return 0; +}; + +EventEmitter.listenerCount = function(emitter, type) { + return emitter.listenerCount(type); +}; + +function isFunction(arg) { + return typeof arg === 'function'; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isUndefined(arg) { + return arg === void 0; +} + + +/***/ }, +/* 4 */ +/***/ function(module, exports, __webpack_require__) { + +/** + * Root reference for iframes. + */ + +var root; +if (typeof window !== 'undefined') { // Browser window + root = window; +} else if (typeof self !== 'undefined') { // Web Worker + root = self; +} else { // Other environments + console.warn("Using browser-only version of superagent in non-browser environment"); + root = this; +} + +var Emitter = __webpack_require__(8); +var RequestBase = __webpack_require__(12); +var isObject = __webpack_require__(5); + +/** + * Noop. + */ + +function noop(){}; + +/** + * Expose `request`. + */ + +var request = module.exports = __webpack_require__(13).bind(null, Request); + +/** + * Determine XHR. + */ + +request.getXHR = function () { + if (root.XMLHttpRequest + && (!root.location || 'file:' != root.location.protocol + || !root.ActiveXObject)) { + return new XMLHttpRequest; + } else { + try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {} + try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {} + try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {} + try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {} + } + throw Error("Browser-only verison of superagent could not find XHR"); +}; + +/** + * Removes leading and trailing whitespace, added to support IE. + * + * @param {String} s + * @return {String} + * @api private + */ + +var trim = ''.trim + ? function(s) { return s.trim(); } + : function(s) { return s.replace(/(^\s*|\s*$)/g, ''); }; + +/** + * Serialize the given `obj`. + * + * @param {Object} obj + * @return {String} + * @api private + */ + +function serialize(obj) { + if (!isObject(obj)) return obj; + var pairs = []; + for (var key in obj) { + pushEncodedKeyValuePair(pairs, key, obj[key]); + } + return pairs.join('&'); +} + +/** + * Helps 'serialize' with serializing arrays. + * Mutates the pairs array. + * + * @param {Array} pairs + * @param {String} key + * @param {Mixed} val + */ + +function pushEncodedKeyValuePair(pairs, key, val) { + if (val != null) { + if (Array.isArray(val)) { + val.forEach(function(v) { + pushEncodedKeyValuePair(pairs, key, v); + }); + } else if (isObject(val)) { + for(var subkey in val) { + pushEncodedKeyValuePair(pairs, key + '[' + subkey + ']', val[subkey]); + } + } else { + pairs.push(encodeURIComponent(key) + + '=' + encodeURIComponent(val)); + } + } else if (val === null) { + pairs.push(encodeURIComponent(key)); + } +} + +/** + * Expose serialization method. + */ + + request.serializeObject = serialize; + + /** + * Parse the given x-www-form-urlencoded `str`. + * + * @param {String} str + * @return {Object} + * @api private + */ + +function parseString(str) { + var obj = {}; + var pairs = str.split('&'); + var pair; + var pos; + + for (var i = 0, len = pairs.length; i < len; ++i) { + pair = pairs[i]; + pos = pair.indexOf('='); + if (pos == -1) { + obj[decodeURIComponent(pair)] = ''; + } else { + obj[decodeURIComponent(pair.slice(0, pos))] = + decodeURIComponent(pair.slice(pos + 1)); + } + } + + return obj; +} + +/** + * Expose parser. + */ + +request.parseString = parseString; + +/** + * Default MIME type map. + * + * superagent.types.xml = 'application/xml'; + * + */ + +request.types = { + html: 'text/html', + json: 'application/json', + xml: 'application/xml', + urlencoded: 'application/x-www-form-urlencoded', + 'form': 'application/x-www-form-urlencoded', + 'form-data': 'application/x-www-form-urlencoded' +}; + +/** + * Default serialization map. + * + * superagent.serialize['application/xml'] = function(obj){ + * return 'generated xml here'; + * }; + * + */ + + request.serialize = { + 'application/x-www-form-urlencoded': serialize, + 'application/json': JSON.stringify + }; + + /** + * Default parsers. + * + * superagent.parse['application/xml'] = function(str){ + * return { object parsed from str }; + * }; + * + */ + +request.parse = { + 'application/x-www-form-urlencoded': parseString, + 'application/json': JSON.parse +}; + +/** + * Parse the given header `str` into + * an object containing the mapped fields. + * + * @param {String} str + * @return {Object} + * @api private + */ + +function parseHeader(str) { + var lines = str.split(/\r?\n/); + var fields = {}; + var index; + var line; + var field; + var val; + + lines.pop(); // trailing CRLF + + for (var i = 0, len = lines.length; i < len; ++i) { + line = lines[i]; + index = line.indexOf(':'); + field = line.slice(0, index).toLowerCase(); + val = trim(line.slice(index + 1)); + fields[field] = val; + } + + return fields; +} + +/** + * Check if `mime` is json or has +json structured syntax suffix. + * + * @param {String} mime + * @return {Boolean} + * @api private + */ + +function isJSON(mime) { + return /[\/+]json\b/.test(mime); +} + +/** + * Return the mime type for the given `str`. + * + * @param {String} str + * @return {String} + * @api private + */ + +function type(str){ + return str.split(/ *; */).shift(); +}; + +/** + * Return header field parameters. + * + * @param {String} str + * @return {Object} + * @api private + */ + +function params(str){ + return str.split(/ *; */).reduce(function(obj, str){ + var parts = str.split(/ *= */), + key = parts.shift(), + val = parts.shift(); + + if (key && val) obj[key] = val; + return obj; + }, {}); +}; + +/** + * Initialize a new `Response` with the given `xhr`. + * + * - set flags (.ok, .error, etc) + * - parse header + * + * Examples: + * + * Aliasing `superagent` as `request` is nice: + * + * request = superagent; + * + * We can use the promise-like API, or pass callbacks: + * + * request.get('/').end(function(res){}); + * request.get('/', function(res){}); + * + * Sending data can be chained: + * + * request + * .post('/user') + * .send({ name: 'tj' }) + * .end(function(res){}); + * + * Or passed to `.send()`: + * + * request + * .post('/user') + * .send({ name: 'tj' }, function(res){}); + * + * Or passed to `.post()`: + * + * request + * .post('/user', { name: 'tj' }) + * .end(function(res){}); + * + * Or further reduced to a single call for simple cases: + * + * request + * .post('/user', { name: 'tj' }, function(res){}); + * + * @param {XMLHTTPRequest} xhr + * @param {Object} options + * @api private + */ + +function Response(req, options) { + options = options || {}; + this.req = req; + this.xhr = this.req.xhr; + // responseText is accessible only if responseType is '' or 'text' and on older browsers + this.text = ((this.req.method !='HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text')) || typeof this.xhr.responseType === 'undefined') + ? this.xhr.responseText + : null; + this.statusText = this.req.xhr.statusText; + this._setStatusProperties(this.xhr.status); + this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders()); + // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but + // getResponseHeader still works. so we get content-type even if getting + // other headers fails. + this.header['content-type'] = this.xhr.getResponseHeader('content-type'); + this._setHeaderProperties(this.header); + this.body = this.req.method != 'HEAD' + ? this._parseBody(this.text ? this.text : this.xhr.response) + : null; +} + +/** + * Get case-insensitive `field` value. + * + * @param {String} field + * @return {String} + * @api public + */ + +Response.prototype.get = function(field){ + return this.header[field.toLowerCase()]; +}; + +/** + * Set header related properties: + * + * - `.type` the content type without params + * + * A response of "Content-Type: text/plain; charset=utf-8" + * will provide you with a `.type` of "text/plain". + * + * @param {Object} header + * @api private + */ + +Response.prototype._setHeaderProperties = function(header){ + // content-type + var ct = this.header['content-type'] || ''; + this.type = type(ct); + + // params + var obj = params(ct); + for (var key in obj) this[key] = obj[key]; +}; + +/** + * Parse the given body `str`. + * + * Used for auto-parsing of bodies. Parsers + * are defined on the `superagent.parse` object. + * + * @param {String} str + * @return {Mixed} + * @api private + */ + +Response.prototype._parseBody = function(str){ + var parse = request.parse[this.type]; + if (!parse && isJSON(this.type)) { + parse = request.parse['application/json']; + } + return parse && str && (str.length || str instanceof Object) + ? parse(str) + : null; +}; + +/** + * Set flags such as `.ok` based on `status`. + * + * For example a 2xx response will give you a `.ok` of __true__ + * whereas 5xx will be __false__ and `.error` will be __true__. The + * `.clientError` and `.serverError` are also available to be more + * specific, and `.statusType` is the class of error ranging from 1..5 + * sometimes useful for mapping respond colors etc. + * + * "sugar" properties are also defined for common cases. Currently providing: + * + * - .noContent + * - .badRequest + * - .unauthorized + * - .notAcceptable + * - .notFound + * + * @param {Number} status + * @api private + */ + +Response.prototype._setStatusProperties = function(status){ + // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request + if (status === 1223) { + status = 204; + } + + var type = status / 100 | 0; + + // status / class + this.status = this.statusCode = status; + this.statusType = type; + + // basics + this.info = 1 == type; + this.ok = 2 == type; + this.clientError = 4 == type; + this.serverError = 5 == type; + this.error = (4 == type || 5 == type) + ? this.toError() + : false; + + // sugar + this.accepted = 202 == status; + this.noContent = 204 == status; + this.badRequest = 400 == status; + this.unauthorized = 401 == status; + this.notAcceptable = 406 == status; + this.notFound = 404 == status; + this.forbidden = 403 == status; +}; + +/** + * Return an `Error` representative of this response. + * + * @return {Error} + * @api public + */ + +Response.prototype.toError = function(){ + var req = this.req; + var method = req.method; + var url = req.url; + + var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')'; + var err = new Error(msg); + err.status = this.status; + err.method = method; + err.url = url; + + return err; +}; + +/** + * Expose `Response`. + */ + +request.Response = Response; + +/** + * Initialize a new `Request` with the given `method` and `url`. + * + * @param {String} method + * @param {String} url + * @api public + */ + +function Request(method, url) { + var self = this; + this._query = this._query || []; + this.method = method; + this.url = url; + this.header = {}; // preserves header name case + this._header = {}; // coerces header names to lowercase + this.on('end', function(){ + var err = null; + var res = null; + + try { + res = new Response(self); + } catch(e) { + err = new Error('Parser is unable to parse the response'); + err.parse = true; + err.original = e; + // issue #675: return the raw response if the response parsing fails + if (self.xhr) { + // ie9 doesn't have 'response' property + err.rawResponse = typeof self.xhr.responseType == 'undefined' ? self.xhr.responseText : self.xhr.response; + // issue #876: return the http status code if the response parsing fails + err.statusCode = self.xhr.status ? self.xhr.status : null; + } else { + err.rawResponse = null; + err.statusCode = null; + } + + return self.callback(err); + } + + self.emit('response', res); + + var new_err; + try { + if (res.status < 200 || res.status >= 300) { + new_err = new Error(res.statusText || 'Unsuccessful HTTP response'); + new_err.original = err; + new_err.response = res; + new_err.status = res.status; + } + } catch(e) { + new_err = e; // #985 touching res may cause INVALID_STATE_ERR on old Android + } + + // #1000 don't catch errors from the callback to avoid double calling it + if (new_err) { + self.callback(new_err, res); + } else { + self.callback(null, res); + } + }); +} + +/** + * Mixin `Emitter` and `RequestBase`. + */ + +Emitter(Request.prototype); +RequestBase(Request.prototype); + +/** + * Set Content-Type to `type`, mapping values from `request.types`. + * + * Examples: + * + * superagent.types.xml = 'application/xml'; + * + * request.post('/') + * .type('xml') + * .send(xmlstring) + * .end(callback); + * + * request.post('/') + * .type('application/xml') + * .send(xmlstring) + * .end(callback); + * + * @param {String} type + * @return {Request} for chaining + * @api public + */ + +Request.prototype.type = function(type){ + this.set('Content-Type', request.types[type] || type); + return this; +}; + +/** + * Set responseType to `val`. Presently valid responseTypes are 'blob' and + * 'arraybuffer'. + * + * Examples: + * + * req.get('/') + * .responseType('blob') + * .end(callback); + * + * @param {String} val + * @return {Request} for chaining + * @api public + */ + +Request.prototype.responseType = function(val){ + this._responseType = val; + return this; +}; + +/** + * Set Accept to `type`, mapping values from `request.types`. + * + * Examples: + * + * superagent.types.json = 'application/json'; + * + * request.get('/agent') + * .accept('json') + * .end(callback); + * + * request.get('/agent') + * .accept('application/json') + * .end(callback); + * + * @param {String} accept + * @return {Request} for chaining + * @api public + */ + +Request.prototype.accept = function(type){ + this.set('Accept', request.types[type] || type); + return this; +}; + +/** + * Set Authorization field value with `user` and `pass`. + * + * @param {String} user + * @param {String} pass + * @param {Object} options with 'type' property 'auto' or 'basic' (default 'basic') + * @return {Request} for chaining + * @api public + */ + +Request.prototype.auth = function(user, pass, options){ + if (!options) { + options = { + type: 'basic' + } + } + + switch (options.type) { + case 'basic': + var str = btoa(user + ':' + pass); + this.set('Authorization', 'Basic ' + str); + break; + + case 'auto': + this.username = user; + this.password = pass; + break; + } + return this; +}; + +/** +* Add query-string `val`. +* +* Examples: +* +* request.get('/shoes') +* .query('size=10') +* .query({ color: 'blue' }) +* +* @param {Object|String} val +* @return {Request} for chaining +* @api public +*/ + +Request.prototype.query = function(val){ + if ('string' != typeof val) val = serialize(val); + if (val) this._query.push(val); + return this; +}; + +/** + * Queue the given `file` as an attachment to the specified `field`, + * with optional `options` (or filename). + * + * ``` js + * request.post('/upload') + * .attach('content', new Blob(['hey!'], { type: "text/html"})) + * .end(callback); + * ``` + * + * @param {String} field + * @param {Blob|File} file + * @param {String|Object} options + * @return {Request} for chaining + * @api public + */ + +Request.prototype.attach = function(field, file, options){ + if (this._data) { + throw Error("superagent can't mix .send() and .attach()"); + } + + this._getFormData().append(field, file, options || file.name); + return this; +}; + +Request.prototype._getFormData = function(){ + if (!this._formData) { + this._formData = new root.FormData(); + } + return this._formData; +}; + +/** + * Invoke the callback with `err` and `res` + * and handle arity check. + * + * @param {Error} err + * @param {Response} res + * @api private + */ + +Request.prototype.callback = function(err, res){ + var fn = this._callback; + this.clearTimeout(); + + if (err) { + this.emit('error', err); + } + + fn(err, res); +}; + +/** + * Invoke callback with x-domain error. + * + * @api private + */ + +Request.prototype.crossDomainError = function(){ + var err = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.'); + err.crossDomain = true; + + err.status = this.status; + err.method = this.method; + err.url = this.url; + + this.callback(err); +}; + +// This only warns, because the request is still likely to work +Request.prototype.buffer = Request.prototype.ca = Request.prototype.agent = function(){ + console.warn("This is not supported in browser version of superagent"); + return this; +}; + +// This throws, because it can't send/receive data as expected +Request.prototype.pipe = Request.prototype.write = function(){ + throw Error("Streaming is not supported in browser version of superagent"); +}; + +/** + * Invoke callback with timeout error. + * + * @api private + */ + +Request.prototype._timeoutError = function(){ + var timeout = this._timeout; + var err = new Error('timeout of ' + timeout + 'ms exceeded'); + err.timeout = timeout; + this.callback(err); +}; + +/** + * Compose querystring to append to req.url + * + * @api private + */ + +Request.prototype._appendQueryString = function(){ + var query = this._query.join('&'); + if (query) { + this.url += ~this.url.indexOf('?') + ? '&' + query + : '?' + query; + } +}; + +/** + * Check if `obj` is a host object, + * we don't want to serialize these :) + * + * @param {Object} obj + * @return {Boolean} + * @api private + */ +Request.prototype._isHost = function _isHost(obj) { + // Native objects stringify to [object File], [object Blob], [object FormData], etc. + return obj && 'object' === typeof obj && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== '[object Object]'; +} + +/** + * Initiate request, invoking callback `fn(res)` + * with an instanceof `Response`. + * + * @param {Function} fn + * @return {Request} for chaining + * @api public + */ + +Request.prototype.end = function(fn){ + var self = this; + var xhr = this.xhr = request.getXHR(); + var timeout = this._timeout; + var data = this._formData || this._data; + + // store callback + this._callback = fn || noop; + + // state change + xhr.onreadystatechange = function(){ + if (4 != xhr.readyState) return; + + // In IE9, reads to any property (e.g. status) off of an aborted XHR will + // result in the error "Could not complete the operation due to error c00c023f" + var status; + try { status = xhr.status } catch(e) { status = 0; } + + if (0 == status) { + if (self.timedout) return self._timeoutError(); + if (self._aborted) return; + return self.crossDomainError(); + } + self.emit('end'); + }; + + // progress + var handleProgress = function(direction, e) { + if (e.total > 0) { + e.percent = e.loaded / e.total * 100; + } + e.direction = direction; + self.emit('progress', e); + } + if (this.hasListeners('progress')) { + try { + xhr.onprogress = handleProgress.bind(null, 'download'); + if (xhr.upload) { + xhr.upload.onprogress = handleProgress.bind(null, 'upload'); + } + } catch(e) { + // Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist. + // Reported here: + // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context + } + } + + // timeout + if (timeout && !this._timer) { + this._timer = setTimeout(function(){ + self.timedout = true; + self.abort(); + }, timeout); + } + + // querystring + this._appendQueryString(); + + // initiate request + if (this.username && this.password) { + xhr.open(this.method, this.url, true, this.username, this.password); + } else { + xhr.open(this.method, this.url, true); + } + + // CORS + if (this._withCredentials) xhr.withCredentials = true; + + // body + if ('GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !this._isHost(data)) { + // serialize stuff + var contentType = this._header['content-type']; + var serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : '']; + if (!serialize && isJSON(contentType)) serialize = request.serialize['application/json']; + if (serialize) data = serialize(data); + } + + // set header fields + for (var field in this.header) { + if (null == this.header[field]) continue; + xhr.setRequestHeader(field, this.header[field]); + } + + if (this._responseType) { + xhr.responseType = this._responseType; + } + + // send stuff + this.emit('request', this); + + // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing) + // We need null here if data is undefined + xhr.send(typeof data !== 'undefined' ? data : null); + return this; +}; + + +/** + * Expose `Request`. + */ + +request.Request = Request; + +/** + * GET `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.get = function(url, data, fn){ + var req = request('GET', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.query(data); + if (fn) req.end(fn); + return req; +}; + +/** + * HEAD `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.head = function(url, data, fn){ + var req = request('HEAD', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + +/** + * OPTIONS query to `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.options = function(url, data, fn){ + var req = request('OPTIONS', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + +/** + * DELETE `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +function del(url, fn){ + var req = request('DELETE', url); + if (fn) req.end(fn); + return req; +}; + +request['del'] = del; +request['delete'] = del; + +/** + * PATCH `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} [data] + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.patch = function(url, data, fn){ + var req = request('PATCH', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + +/** + * POST `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} [data] + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.post = function(url, data, fn){ + var req = request('POST', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + +/** + * PUT `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.put = function(url, data, fn){ + var req = request('PUT', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + + +/***/ }, +/* 5 */ +/***/ function(module, exports) { + +/** + * Check if `obj` is an object. + * + * @param {Object} obj + * @return {Boolean} + * @api private + */ + +function isObject(obj) { + return null !== obj && 'object' === typeof obj; +} + +module.exports = isObject; + + +/***/ }, +/* 6 */ +/***/ function(module, exports, __webpack_require__) { + +"use strict"; +'use strict'; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var RPCClient = __webpack_require__(2); +var EventEmitter = __webpack_require__(3).EventEmitter; + +var Client = function (_EventEmitter) { + _inherits(Client, _EventEmitter); + + function Client() { + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + OAUTH2_CLIENT_ID = _ref.OAUTH2_CLIENT_ID; + + _classCallCheck(this, Client); + + var _this = _possibleConstructorReturn(this, (Client.__proto__ || Object.getPrototypeOf(Client)).call(this)); + + _this.rpc = new RPCClient({ OAUTH2_CLIENT_ID: OAUTH2_CLIENT_ID }); + _this.rpc.evts.on('READY', function () { + _this.user = _this.rpc.user; + _this.application = _this.rpc.application; + _this.emit('ready'); + }); + _this.rpc.evts.on('ERROR', function (err) { + return _this.emit('error', err); + }); + _this.rest = _this.rpc.rest; + return _this; + } + + _createClass(Client, [{ + key: 'getGuild', + value: function getGuild(id, timeout) { + var _this2 = this; + + return new Promise(function (resolve, reject) { + _this2.rpc.request('GET_GUILD', { guild_id: id, timeout: timeout }, function (err, res) { + if (err) reject(err); + resolve(res.data); + }); + }); + } + }, { + key: 'getGuilds', + value: function getGuilds() { + var _this3 = this; + + return new Promise(function (resolve, reject) { + _this3.rpc.request('GET_GUILDS', {}, function (err, res) { + if (err) reject(err); + resolve(res.data.guilds); + }); + }); + } + }, { + key: 'getChannel', + value: function getChannel(id, timeout) { + var _this4 = this; + + return new Promise(function (resolve, reject) { + _this4.rpc.request('GET_CHANNEL', { channel_id: id, timeout: timeout }, function (err, res) { + if (err) reject(err); + resolve(res.data); + }); + }); + } + }, { + key: 'getChannels', + value: function getChannels() { + var _this5 = this; + + return new Promise(function (resolve, reject) { + _this5.rpc.request('GET_CHANNELS', {}, function (err, res) { + if (err) reject(err); + resolve(res.data.channels); + }); + }); + } + }, { + key: 'setUserVoiceSettings', + value: function setUserVoiceSettings(args) { + var _this6 = this; + + return new Promise(function (resolve, reject) { + _this6.rpc.request('SET_USER_VOICE_SETTINGS', args, function (err, res) { + if (err) reject(err); + resolve(res.data); + }); + }); + } + }, { + key: 'selectVoiceChannel', + value: function selectVoiceChannel(id, timeout) { + var _this7 = this; + + var force = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + + return new Promise(function (resolve, reject) { + _this7.rpc.request('SELECT_VOICE_CHANNEL', { channel_id: id, timeout: timeout, force: force }, function (err, res) { + if (err) reject(err); + resolve(res.data); + }); + }); + } + }, { + key: 'selectTextChannel', + value: function selectTextChannel(id, timeout) { + var _this8 = this; + + var force = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + + return new Promise(function (resolve, reject) { + _this8.rpc.request('SELECT_TEXT_CHANNEL', { channel_id: id, timeout: timeout, force: force }, function (err, res) { + if (err) reject(err); + resolve(res.data); + }); + }); + } + }, { + key: 'getVoiceSettings', + value: function getVoiceSettings() { + var _this9 = this; + + return new Promise(function (resolve, reject) { + _this9.rpc.request('GET_VOICE_SETTINGS', {}, function (err, res) { + if (err) reject(err); + resolve(res.data); + }); + }); + } + }, { + key: 'setVoiceSettings', + value: function setVoiceSettings(args) { + var _this10 = this; + + return new Promise(function (resolve, reject) { + _this10.rpc.request('SET_VOICE_SETTINGS', args, function (err, res) { + if (err) reject(err); + resolve(res.data); + }); + }); + } + }, { + key: 'subscribe', + value: function subscribe(event, args, callback) { + return this.rpc.subscribe(event, args, callback); + } + }, { + key: 'unsubscribe', + value: function unsubscribe(event, args, callback) { + return this.rpc.unsubscribe(event, args, callback); + } + }, { + key: 'connect', + value: function connect(token) { + return this.rpc.connect(token); + } + }]); + + return Client; +}(EventEmitter); + +module.exports = Client; + +/***/ }, +/* 7 */ +/***/ function(module, exports) { + +module.exports = { + "name": "discord-rpc", + "version": "2.0.0", + "description": "A simple RPC client for Discord somewhat stolen from the Discord StreamKit.", + "main": "src/index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/GusCaplan/discord-rpc.git" + }, + "scripts": { + "web-dist": "node ./node_modules/parallel-webpack/bin/run.js" + }, + "author": "Gus Caplan ", + "license": "MIT", + "bugs": { + "url": "https://github.com/GusCaplan/discord-rpc/issues" + }, + "homepage": "https://github.com/GusCaplan/discord-rpc#readme", + "dependencies": { + "deep-equal": "^1.0.1", + "superagent": "^3.0.0", + "uuid": "^3.0.0", + "ws": "^1.1.1" + }, + "devDependencies": { + "babel-core": "^6.18.2", + "babel-loader": "^6.2.8", + "babel-preset-es2015": "^6.18.0", + "bufferutil": "^1.2.1", + "ignore-loader": "^0.1.2", + "json-loader": "^0.5.4", + "parallel-webpack": "^1.5.0", + "uglify-js": "github:mishoo/UglifyJS2#harmony", + "utf-8-validate": "^1.2.1", + "webpack": "2.1.0-beta.27" + }, + "browser": { + "ws": false + } +}; + +/***/ }, +/* 8 */ +/***/ function(module, exports, __webpack_require__) { + + +/** + * Expose `Emitter`. + */ + +if (true) { + module.exports = Emitter; +} + +/** + * Initialize a new `Emitter`. + * + * @api public + */ + +function Emitter(obj) { + if (obj) return mixin(obj); +}; + +/** + * Mixin the emitter properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ + +function mixin(obj) { + for (var key in Emitter.prototype) { + obj[key] = Emitter.prototype[key]; + } + return obj; +} + +/** + * Listen on the given `event` with `fn`. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.on = +Emitter.prototype.addEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + (this._callbacks['$' + event] = this._callbacks['$' + event] || []) + .push(fn); + return this; +}; + +/** + * Adds an `event` listener that will be invoked a single + * time then automatically removed. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.once = function(event, fn){ + function on() { + this.off(event, on); + fn.apply(this, arguments); + } + + on.fn = fn; + this.on(event, on); + return this; +}; + +/** + * Remove the given callback for `event` or all + * registered callbacks. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.off = +Emitter.prototype.removeListener = +Emitter.prototype.removeAllListeners = +Emitter.prototype.removeEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + + // all + if (0 == arguments.length) { + this._callbacks = {}; + return this; + } + + // specific event + var callbacks = this._callbacks['$' + event]; + if (!callbacks) return this; + + // remove all handlers + if (1 == arguments.length) { + delete this._callbacks['$' + event]; + return this; + } + + // remove specific handler + var cb; + for (var i = 0; i < callbacks.length; i++) { + cb = callbacks[i]; + if (cb === fn || cb.fn === fn) { + callbacks.splice(i, 1); + break; + } + } + return this; +}; + +/** + * Emit `event` with the given args. + * + * @param {String} event + * @param {Mixed} ... + * @return {Emitter} + */ + +Emitter.prototype.emit = function(event){ + this._callbacks = this._callbacks || {}; + var args = [].slice.call(arguments, 1) + , callbacks = this._callbacks['$' + event]; + + if (callbacks) { + callbacks = callbacks.slice(0); + for (var i = 0, len = callbacks.length; i < len; ++i) { + callbacks[i].apply(this, args); + } + } + + return this; +}; + +/** + * Return array of callbacks for `event`. + * + * @param {String} event + * @return {Array} + * @api public + */ + +Emitter.prototype.listeners = function(event){ + this._callbacks = this._callbacks || {}; + return this._callbacks['$' + event] || []; +}; + +/** + * Check if this emitter has `event` handlers. + * + * @param {String} event + * @return {Boolean} + * @api public + */ + +Emitter.prototype.hasListeners = function(event){ + return !! this.listeners(event).length; +}; + + +/***/ }, +/* 9 */ +/***/ function(module, exports, __webpack_require__) { + +var pSlice = Array.prototype.slice; +var objectKeys = __webpack_require__(11); +var isArguments = __webpack_require__(10); + +var deepEqual = module.exports = function (actual, expected, opts) { + if (!opts) opts = {}; + // 7.1. All identical values are equivalent, as determined by ===. + if (actual === expected) { + return true; + + } else if (actual instanceof Date && expected instanceof Date) { + return actual.getTime() === expected.getTime(); + + // 7.3. Other pairs that do not both pass typeof value == 'object', + // equivalence is determined by ==. + } else if (!actual || !expected || typeof actual != 'object' && typeof expected != 'object') { + return opts.strict ? actual === expected : actual == expected; + + // 7.4. For all other Object pairs, including Array objects, equivalence is + // determined by having the same number of owned properties (as verified + // with Object.prototype.hasOwnProperty.call), the same set of keys + // (although not necessarily the same order), equivalent values for every + // corresponding key, and an identical 'prototype' property. Note: this + // accounts for both named and indexed properties on Arrays. + } else { + return objEquiv(actual, expected, opts); + } +} + +function isUndefinedOrNull(value) { + return value === null || value === undefined; +} + +function isBuffer (x) { + if (!x || typeof x !== 'object' || typeof x.length !== 'number') return false; + if (typeof x.copy !== 'function' || typeof x.slice !== 'function') { + return false; + } + if (x.length > 0 && typeof x[0] !== 'number') return false; + return true; +} + +function objEquiv(a, b, opts) { + var i, key; + if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) + return false; + // an identical 'prototype' property. + if (a.prototype !== b.prototype) return false; + //~~~I've managed to break Object.keys through screwy arguments passing. + // Converting to array solves the problem. + if (isArguments(a)) { + if (!isArguments(b)) { + return false; + } + a = pSlice.call(a); + b = pSlice.call(b); + return deepEqual(a, b, opts); + } + if (isBuffer(a)) { + if (!isBuffer(b)) { + return false; + } + if (a.length !== b.length) return false; + for (i = 0; i < a.length; i++) { + if (a[i] !== b[i]) return false; + } + return true; + } + try { + var ka = objectKeys(a), + kb = objectKeys(b); + } catch (e) {//happens when one is a string literal and the other isn't + return false; + } + // having the same number of owned properties (keys incorporates + // hasOwnProperty) + if (ka.length != kb.length) + return false; + //the same set of keys (although not necessarily the same order), + ka.sort(); + kb.sort(); + //~~~cheap key test + for (i = ka.length - 1; i >= 0; i--) { + if (ka[i] != kb[i]) + return false; + } + //equivalent values for every corresponding key, and + //~~~possibly expensive deep test + for (i = ka.length - 1; i >= 0; i--) { + key = ka[i]; + if (!deepEqual(a[key], b[key], opts)) return false; + } + return typeof a === typeof b; +} + + +/***/ }, +/* 10 */ +/***/ function(module, exports) { + +var supportsArgumentsClass = (function(){ + return Object.prototype.toString.call(arguments) +})() == '[object Arguments]'; + +exports = module.exports = supportsArgumentsClass ? supported : unsupported; + +exports.supported = supported; +function supported(object) { + return Object.prototype.toString.call(object) == '[object Arguments]'; +}; + +exports.unsupported = unsupported; +function unsupported(object){ + return object && + typeof object == 'object' && + typeof object.length == 'number' && + Object.prototype.hasOwnProperty.call(object, 'callee') && + !Object.prototype.propertyIsEnumerable.call(object, 'callee') || + false; +}; + + +/***/ }, +/* 11 */ +/***/ function(module, exports) { + +exports = module.exports = typeof Object.keys === 'function' + ? Object.keys : shim; + +exports.shim = shim; +function shim (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +} + + +/***/ }, +/* 12 */ +/***/ function(module, exports, __webpack_require__) { + +/** + * Module of mixed-in functions shared between node and client code + */ +var isObject = __webpack_require__(5); + +/** + * Expose `RequestBase`. + */ + +module.exports = RequestBase; + +/** + * Initialize a new `RequestBase`. + * + * @api public + */ + +function RequestBase(obj) { + if (obj) return mixin(obj); +} + +/** + * Mixin the prototype properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ + +function mixin(obj) { + for (var key in RequestBase.prototype) { + obj[key] = RequestBase.prototype[key]; + } + return obj; +} + +/** + * Clear previous timeout. + * + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.clearTimeout = function _clearTimeout(){ + this._timeout = 0; + clearTimeout(this._timer); + return this; +}; + +/** + * Override default response body parser + * + * This function will be called to convert incoming data into request.body + * + * @param {Function} + * @api public + */ + +RequestBase.prototype.parse = function parse(fn){ + this._parser = fn; + return this; +}; + +/** + * Override default request body serializer + * + * This function will be called to convert data set via .send or .attach into payload to send + * + * @param {Function} + * @api public + */ + +RequestBase.prototype.serialize = function serialize(fn){ + this._serializer = fn; + return this; +}; + +/** + * Set timeout to `ms`. + * + * @param {Number} ms + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.timeout = function timeout(ms){ + this._timeout = ms; + return this; +}; + +/** + * Promise support + * + * @param {Function} resolve + * @param {Function} reject + * @return {Request} + */ + +RequestBase.prototype.then = function then(resolve, reject) { + if (!this._fullfilledPromise) { + var self = this; + this._fullfilledPromise = new Promise(function(innerResolve, innerReject){ + self.end(function(err, res){ + if (err) innerReject(err); else innerResolve(res); + }); + }); + } + return this._fullfilledPromise.then(resolve, reject); +} + +RequestBase.prototype.catch = function(cb) { + return this.then(undefined, cb); +}; + +/** + * Allow for extension + */ + +RequestBase.prototype.use = function use(fn) { + fn(this); + return this; +} + + +/** + * Get request header `field`. + * Case-insensitive. + * + * @param {String} field + * @return {String} + * @api public + */ + +RequestBase.prototype.get = function(field){ + return this._header[field.toLowerCase()]; +}; + +/** + * Get case-insensitive header `field` value. + * This is a deprecated internal API. Use `.get(field)` instead. + * + * (getHeader is no longer used internally by the superagent code base) + * + * @param {String} field + * @return {String} + * @api private + * @deprecated + */ + +RequestBase.prototype.getHeader = RequestBase.prototype.get; + +/** + * Set header `field` to `val`, or multiple fields with one object. + * Case-insensitive. + * + * Examples: + * + * req.get('/') + * .set('Accept', 'application/json') + * .set('X-API-Key', 'foobar') + * .end(callback); + * + * req.get('/') + * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' }) + * .end(callback); + * + * @param {String|Object} field + * @param {String} val + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.set = function(field, val){ + if (isObject(field)) { + for (var key in field) { + this.set(key, field[key]); + } + return this; + } + this._header[field.toLowerCase()] = val; + this.header[field] = val; + return this; +}; + +/** + * Remove header `field`. + * Case-insensitive. + * + * Example: + * + * req.get('/') + * .unset('User-Agent') + * .end(callback); + * + * @param {String} field + */ +RequestBase.prototype.unset = function(field){ + delete this._header[field.toLowerCase()]; + delete this.header[field]; + return this; +}; + +/** + * Write the field `name` and `val`, or multiple fields with one object + * for "multipart/form-data" request bodies. + * + * ``` js + * request.post('/upload') + * .field('foo', 'bar') + * .end(callback); + * + * request.post('/upload') + * .field({ foo: 'bar', baz: 'qux' }) + * .end(callback); + * ``` + * + * @param {String|Object} name + * @param {String|Blob|File|Buffer|fs.ReadStream} val + * @return {Request} for chaining + * @api public + */ +RequestBase.prototype.field = function(name, val) { + + // name should be either a string or an object. + if (null === name || undefined === name) { + throw new Error('.field(name, val) name can not be empty'); + } + + if (isObject(name)) { + for (var key in name) { + this.field(key, name[key]); + } + return this; + } + + // val should be defined now + if (null === val || undefined === val) { + throw new Error('.field(name, val) val can not be empty'); + } + this._getFormData().append(name, val); + return this; +}; + +/** + * Abort the request, and clear potential timeout. + * + * @return {Request} + * @api public + */ +RequestBase.prototype.abort = function(){ + if (this._aborted) { + return this; + } + this._aborted = true; + this.xhr && this.xhr.abort(); // browser + this.req && this.req.abort(); // node + this.clearTimeout(); + this.emit('abort'); + return this; +}; + +/** + * Enable transmission of cookies with x-domain requests. + * + * Note that for this to work the origin must not be + * using "Access-Control-Allow-Origin" with a wildcard, + * and also must set "Access-Control-Allow-Credentials" + * to "true". + * + * @api public + */ + +RequestBase.prototype.withCredentials = function(){ + // This is browser-only functionality. Node side is no-op. + this._withCredentials = true; + return this; +}; + +/** + * Set the max redirects to `n`. Does noting in browser XHR implementation. + * + * @param {Number} n + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.redirects = function(n){ + this._maxRedirects = n; + return this; +}; + +/** + * Convert to a plain javascript object (not JSON string) of scalar properties. + * Note as this method is designed to return a useful non-this value, + * it cannot be chained. + * + * @return {Object} describing method, url, and data of this request + * @api public + */ + +RequestBase.prototype.toJSON = function(){ + return { + method: this.method, + url: this.url, + data: this._data, + headers: this._header + }; +}; + + +/** + * Send `data` as the request body, defaulting the `.type()` to "json" when + * an object is given. + * + * Examples: + * + * // manual json + * request.post('/user') + * .type('json') + * .send('{"name":"tj"}') + * .end(callback) + * + * // auto json + * request.post('/user') + * .send({ name: 'tj' }) + * .end(callback) + * + * // manual x-www-form-urlencoded + * request.post('/user') + * .type('form') + * .send('name=tj') + * .end(callback) + * + * // auto x-www-form-urlencoded + * request.post('/user') + * .type('form') + * .send({ name: 'tj' }) + * .end(callback) + * + * // defaults to x-www-form-urlencoded + * request.post('/user') + * .send('name=tobi') + * .send('species=ferret') + * .end(callback) + * + * @param {String|Object} data + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.send = function(data){ + var isObj = isObject(data); + var type = this._header['content-type']; + + if (isObj && !this._data) { + if (Array.isArray(data)) { + this._data = []; + } else if (!this._isHost(data)) { + this._data = {}; + } + } else if (data && this._data && this._isHost(this._data)) { + throw Error("Can't merge these send calls"); + } + + // merge + if (isObj && isObject(this._data)) { + for (var key in data) { + this._data[key] = data[key]; + } + } else if ('string' == typeof data) { + // default to x-www-form-urlencoded + if (!type) this.type('form'); + type = this._header['content-type']; + if ('application/x-www-form-urlencoded' == type) { + this._data = this._data + ? this._data + '&' + data + : data; + } else { + this._data = (this._data || '') + data; + } + } else { + this._data = data; + } + + if (!isObj || this._isHost(data)) return this; + + // default to json + if (!type) this.type('json'); + return this; +}; + + +/***/ }, +/* 13 */ +/***/ function(module, exports) { + +// The node and browser modules expose versions of this with the +// appropriate constructor function bound as first argument +/** + * Issue a request: + * + * Examples: + * + * request('GET', '/users').end(callback) + * request('/users').end(callback) + * request('/users', callback) + * + * @param {String} method + * @param {String|Function} url or callback + * @return {Request} + * @api public + */ + +function request(RequestConstructor, method, url) { + // callback + if ('function' == typeof url) { + return new RequestConstructor('GET', method).end(url); + } + + // url first + if (2 == arguments.length) { + return new RequestConstructor('GET', method); + } + + return new RequestConstructor(method, url); +} + +module.exports = request; + + +/***/ }, +/* 14 */ +/***/ function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(global) { +var rng; + +var crypto = global.crypto || global.msCrypto; // for IE 11 +if (crypto && crypto.getRandomValues) { + // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto + // Moderately fast, high quality + var _rnds8 = new Uint8Array(16); + rng = function whatwgRNG() { + crypto.getRandomValues(_rnds8); + return _rnds8; + }; +} + +if (!rng) { + // Math.random()-based (RNG) + // + // If all else fails, use Math.random(). It's fast, but is of unspecified + // quality. + var _rnds = new Array(16); + rng = function() { + for (var i = 0, r; i < 16; i++) { + if ((i & 0x03) === 0) r = Math.random() * 0x100000000; + _rnds[i] = r >>> ((i & 0x03) << 3) & 0xff; + } + + return _rnds; + }; +} + +module.exports = rng; + + +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(16))) + +/***/ }, +/* 15 */ +/***/ function(module, exports, __webpack_require__) { + +// Unique ID creation requires a high quality random # generator. We feature +// detect to determine the best RNG source, normalizing to a function that +// returns 128-bits of randomness, since that's what's usually required +var _rng = __webpack_require__(14); + +// Maps for number <-> hex string conversion +var _byteToHex = []; +var _hexToByte = {}; +for (var i = 0; i < 256; ++i) { + _byteToHex[i] = (i + 0x100).toString(16).substr(1); + _hexToByte[_byteToHex[i]] = i; +} + +function buff_to_string(buf, offset) { + var i = offset || 0; + var bth = _byteToHex; + return bth[buf[i++]] + bth[buf[i++]] + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + + bth[buf[i++]] + bth[buf[i++]] + + bth[buf[i++]] + bth[buf[i++]]; +} + +// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html + +// random #'s we need to init node and clockseq +var _seedBytes = _rng(); + +// Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) +var _nodeId = [ + _seedBytes[0] | 0x01, + _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5] +]; + +// Per 4.2.2, randomize (14 bit) clockseq +var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff; + +// Previous uuid creation time +var _lastMSecs = 0, _lastNSecs = 0; + +// See https://github.com/broofa/node-uuid for API details +function v1(options, buf, offset) { + var i = buf && offset || 0; + var b = buf || []; + + options = options || {}; + + var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; + + // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); + + // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; + + // Time since last uuid creation (in msecs) + var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000; + + // Per 4.2.1.2, Bump clockseq on clock regression + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } + + // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } + + // Per 4.2.1.2 Throw error if too many uuids are requested + if (nsecs >= 10000) { + throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; + + // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + msecs += 12219292800000; + + // `time_low` + var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; + + // `time_mid` + var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; + + // `time_high_and_version` + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + b[i++] = tmh >>> 16 & 0xff; + + // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + b[i++] = clockseq >>> 8 | 0x80; + + // `clock_seq_low` + b[i++] = clockseq & 0xff; + + // `node` + var node = options.node || _nodeId; + for (var n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf ? buf : buff_to_string(b); +} + +// **`v4()` - Generate random UUID** + +// See https://github.com/broofa/node-uuid for API details +function v4(options, buf, offset) { + // Deprecated - 'format' argument, as supported in v1.2 + var i = buf && offset || 0; + + if (typeof(options) == 'string') { + buf = options == 'binary' ? new Array(16) : null; + options = null; + } + options = options || {}; + + var rnds = options.random || (options.rng || _rng)(); + + // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + rnds[6] = (rnds[6] & 0x0f) | 0x40; + rnds[8] = (rnds[8] & 0x3f) | 0x80; + + // Copy bytes to buffer, if provided + if (buf) { + for (var ii = 0; ii < 16; ++ii) { + buf[i + ii] = rnds[ii]; + } + } + + return buf || buff_to_string(rnds); +} + +// Export public API +var uuid = v4; +uuid.v1 = v1; +uuid.v4 = v4; + +module.exports = uuid; + + +/***/ }, +/* 16 */ +/***/ function(module, exports) { + +var g; + +// This works in non-strict mode +g = (function() { return this; })(); + +try { + // This works if eval is allowed (see CSP) + g = g || Function("return this")() || (1,eval)("this"); +} catch(e) { + // This works if the window reference is available + if(typeof window === "object") + g = window; +} + +// g can still be undefined, but nothing to do about it... +// We return undefined, instead of nothing here, so it's +// easier to handle this case. if(!global) { ...} + +module.exports = g; + + +/***/ }, +/* 17 */ +/***/ function(module, exports) { + +/* (ignored) */ + +/***/ }, +/* 18 */ +/***/ function(module, exports, __webpack_require__) { + +"use strict"; +'use strict'; + +module.exports = { + version: __webpack_require__(7).version, + Client: __webpack_require__(6), + RPC: __webpack_require__(2), + Rest: __webpack_require__(1), + Constants: __webpack_require__(0) +}; + +if (typeof window !== 'undefined') window.DiscordRPC = module.exports; + +/***/ } +/******/ ]); \ No newline at end of file diff --git a/webpack/rpc.2.0.0.min.js b/webpack/rpc.2.0.0.min.js new file mode 100644 index 0000000..e1b7494 --- /dev/null +++ b/webpack/rpc.2.0.0.min.js @@ -0,0 +1,2 @@ +!function(t){function e(r){if(n[r])return n[r].exports;var i=n[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,e),i.l=!0,i.exports}var n={};return e.m=t,e.c=n,e.i=function(t){return t},e.d=function(t,e,n){Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:n})},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=18)}([function(t,e){"use strict";var n=function(t){var e={},n=!0,r=!1,i=void 0;try{for(var s,o=t[Symbol.iterator]();!(n=(s=o.next()).done);n=!0){var u=s.value;e[u]=u}}catch(t){r=!0,i=t}finally{try{!n&&o.return&&o.return()}finally{if(r)throw i}}return e};t.exports.RPCCommands=n(["DISPATCH","AUTHORIZE","AUTHENTICATE","GET_GUILD","GET_GUILDS","GET_CHANNEL","GET_CHANNELS","SUBSCRIBE","UNSUBSCRIBE","SET_USER_VOICE_SETTINGS","SELECT_VOICE_CHANNEL","GET_VOICE_SETTINGS","SET_VOICE_SETTINGS","SELECT_TEXT_CHANNEL","INVITE_BROWSER"]),t.exports.RPCEvents=n(["READY","ERROR","GUILD_STATUS","GUILD_CREATE","CHANNEL_CREATE","VOICE_STATE_CREATE","VOICE_STATE_DELETE","VOICE_STATE_UPDATE","VOICE_SETTINGS_UPDATE","VOICE_CONNECTION_STATUS","SPEAKING_START","SPEAKING_STOP","MESSAGE_CREATE","MESSAGE_UPDATE","MESSAGE_DELETE"]),t.exports.RPCErrors={UNKNOWN_ERROR:1e3,INVALID_PAYLOAD:4e3,INVALID_VERSION:4001,INVALID_COMMAND:4002,INVALID_GUILD:4003,INVALID_EVENT:4004,INVALID_CHANNEL:4005,INVALID_PERMISSIONS:4006,INVALID_CLIENTID:4007,INVALID_ORIGIN:4008,INVALID_TOKEN:4009,INVALID_USER:4010,OAUTH2_ERROR:5e3},t.exports.RPCCloseCodes={INVALID_CLIENTID:4e3,INVALID_ORIGIN:4001,RATELIMITED:4002,TOKEN_REVOKED:4003},t.exports.ChannelTypes={DM:1,GROUP_DM:3,GUILD_TEXT:0,GUILD_VOICE:2};var r=t.exports.Endpoints={login:"/auth/login",logout:"/auth/logout",gateway:"/gateway",botGateway:"/gateway/bot",invite:function(t){return"/invite/"+t},inviteLink:function(t){return"https://discord.gg/"+t},CDN:"https://cdn.discordapp.com",user:function(t){return"/users/"+t},userChannels:function(t){return r.user(t)+"/channels"},userProfile:function(t){return r.user(t)+"/profile"},avatar:function(t,e){return"1"===t?e:r.user(t)+"/avatars/"+e+".jpg"},me:"/users/@me",meGuild:function(t){return r.me+"/guilds/"+t},relationships:function(t){return r.user(t)+"/relationships"},note:function(t){return r.me+"/notes/"+t},guilds:"/guilds",guild:function(t){return r.guilds+"/"+t},guildIcon:function(t,e){return r.guild(t)+"/icons/"+e+".jpg"},guildPrune:function(t){return r.guild(t)+"/prune"},guildEmbed:function(t){return r.guild(t)+"/embed"},guildInvites:function(t){return r.guild(t)+"/invites"},guildRoles:function(t){return r.guild(t)+"/roles"},guildRole:function(t,e){return r.guildRoles(t)+"/"+e},guildBans:function(t){return r.guild(t)+"/bans"},guildIntegrations:function(t){return r.guild(t)+"/integrations"},guildMembers:function(t){return r.guild(t)+"/members"},guildMember:function(t,e){return r.guildMembers(t)+"/"+e},guildMemberRole:function(t,e,n){return r.guildMember(t,e)+"/roles/"+n},stupidInconsistentGuildEndpoint:function(t){return r.guildMember(t,"@me")+"/nick"},guildChannels:function(t){return r.guild(t)+"/channels"},guildEmojis:function(t){return r.guild(t)+"/emojis"},channels:"/channels",channel:function(t){return r.channels+"/"+t},channelMessages:function(t){return r.channel(t)+"/messages"},channelInvites:function(t){return r.channel(t)+"/invites"},channelTyping:function(t){return r.channel(t)+"/typing"},channelPermissions:function(t){return r.channel(t)+"/permissions"},channelMessage:function(t,e){return r.channelMessages(t)+"/"+e},channelWebhooks:function(t){return r.channel(t)+"/webhooks"},messageReactions:function(t,e){return r.channelMessage(t,e)+"/reactions"},messageReaction:function(t,e,n,i){return r.messageReactions(t,e)+"/"+n+(i?"?limit="+i:"")},selfMessageReaction:function(t,e,n,i){return r.messageReaction(t,e,n,i)+"/@me"},userMessageReaction:function(t,e,n,i,s){return r.messageReaction(t,e,n,i)+"/"+s},webhook:function(t,e){return"/webhooks/"+t+(e?"/"+e:"")},myApplication:"/oauth2/applications/@me",getApp:function(t){return"/oauth2/authorize?client_id="+t}}},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var i=function(){function t(t,e){for(var n=0;n2&&void 0!==arguments[2]?arguments[2]:{},i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return new Promise(function(o,u){i.Authorization="Bearer "+n.client.accessToken,s[t.toLowerCase()]("https://"+n.client.hostAndPort+e).set(i).send(r).then(function(t){return o(t.body)},u)})}},{key:"sendMessage",value:function(t,e){return this.makeRequest("post",u.channelMessages(t),{content:e})}},{key:"editMessage",value:function(t,e,n){return this.makeRequest("patch",u.channelMessage(t,e),{content:n})}},{key:"deleteMessage",value:function(t,e){return this.makeRequest("delete",u.channelMessage(t,e))}}]),t}()},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e,n){return t+":"+(e||n)}var s=function(){function t(t,e){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:this.accessToken,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(!this.connected){this.accessToken=t;var n=6463+e%10;this.hostAndPort=d()+".discordapp.io:"+n,this.socket=new o("wss://"+this.hostAndPort+"/?v=1&client_id="+this.OAUTH2_CLIENT_ID),this.socket.onopen=this._handleOpen.bind(this),this.socket.onclose=this._handleClose.bind(this),this.socket.onmessage=this._handleMessage.bind(this)}}},{key:"disconnect",value:function(t){this.connected&&(this.requestedDisconnect=!0,this.socket.close(),t&&t())}},{key:"reconnect",value:function(){this.connected&&this.socket.close()}},{key:"authenticate",value:function(){var t=this;if(!this.authenticated)return this.accessToken?void this.request("AUTHENTICATE",{access_token:this.accessToken},function(e,n){return e&&e.code===l.INVALID_TOKEN?void t.authorize():(t.authenticated=!0,t.flushQueue(),void t.activeSubscriptions.forEach(function(e){return t.subscribe(e.evt,e.args,e.callback)}))}):void this.authorize()}},{key:"flushQueue",value:function(){var t=this.queue;this.queue=[],t.forEach(function(t){return t()})}},{key:"authorize",value:function(){var t=this;this.authenticated||p.get(this.API_ENDPOINT+"/token").then(function(e){if(!e.ok||!e.body.rpc_token)throw new Error("no rpc token");return t.request("AUTHORIZE",{client_id:t.OAUTH2_CLIENT_ID,scopes:["rpc","rpc.api"],rpc_token:e.body.rpc_token})}).then(function(e){return p.post(t.API_ENDPOINT+"/token").send({code:e.code})}).then(function(e){if(!e.ok)throw new Error("no access token");t.accessToken=e.body.access_token,t.authenticate()}).catch(function(e){setTimeout(t.authorize.bind(t),3e3)})}},{key:"request",value:function(t,e,n,r){var s=this;return"function"==typeof n&&(r=n,n=void 0),new Promise(function(o,u){if(!s.connected||!s.ready||!s.authenticated&&["AUTHORIZE","AUTHENTICATE"].indexOf(t)===-1)return void s.queue.push(function(){return s.request(t,e,n,r)});var a=d();s.evts.once(i(c.DISPATCH,a),function(t,e){r&&r(t,e),t?u(t):o(e)}),s.socket.send(JSON.stringify({cmd:t,args:e,evt:n,nonce:a}))})}},{key:"subscribe",value:function(t,e,n){var r=this;this.request(c.SUBSCRIBE,e,t,function(s){return s?void(n&&n(s)):void(r.activeSubscriptions.find(function(t){return n===t.callback})||(r.activeSubscriptions.push({evt:t,args:e,callback:n}),r.evts.on(i(c.DISPATCH,null,t),function(t){n&&n(null,t)})))})}},{key:"unsubscribe",value:function(t,e,n){var r=this;this.request(c.UNSUBSCRIBE,e,t,function(s){if(s)return void(n&&n(s));for(var o in r.activeSubscriptions){var u=r.activeSubscriptions[o];t===u.evt&&f(e,u.args)&&r.activeSubscriptions.splice(o,1)}var a=i(c.DISPATCH,null,t);r.evts.listeners(a).forEach(function(t){r.evts.removeListener(a,t)}),n&&n()})}},{key:"_handleOpen",value:function(){this.connected=!0,this.authenticate()}},{key:"_handleClose",value:function(t){var e=this;if(this.connected=!1,this.authenticated=!1,this.ready=!1,console.error("WS Closed:",t),this.requestedDisconnect)return void(this.requestedDisconnect=!1);try{this.socket.close()}catch(t){}setTimeout(function(){return e.connect(null,1006===t.code?++e.connectionTries:0)},250)}},{key:"_handleMessage",value:function(t){var e=null;try{e=JSON.parse(t.data)}catch(t){return void console.error("Payload not JSON:",e)}var n=e,r=n.cmd,s=n.evt,o=n.nonce,u=n.data;if(r===c.AUTHENTICATE){if(s===h.ERROR)return void this.evts.emit("ERROR",u);this.user=u.user,this.application=u.application,this.evts.emit("READY",u)}if(r===c.DISPATCH)return s===h.READY?(this.config=u.config,this.ready=!0,void this.flushQueue()):s===h.ERROR?(console.error("Dispatched Error",u),void this.socket.close()):void this.evts.emit(i(c.DISPATCH,null,s),u);var a=null;s===h.ERROR&&(a=new Error(u.message),a.code=u.code,u=null),this.evts.emit(i(c.DISPATCH,o),a,u)}}]),t}();t.exports=y},function(t,e){function n(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function r(t){return"function"==typeof t}function i(t){return"number"==typeof t}function s(t){return"object"==typeof t&&null!==t}function o(t){return void 0===t}t.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.prototype.setMaxListeners=function(t){if(!i(t)||t<0||isNaN(t))throw TypeError("n must be a positive number");return this._maxListeners=t,this},n.prototype.emit=function(t){var e,n,i,u,a,c;if(this._events||(this._events={}),"error"===t&&(!this._events.error||s(this._events.error)&&!this._events.error.length)){if(e=arguments[1],e instanceof Error)throw e;var h=new Error('Uncaught, unspecified "error" event. ('+e+")");throw h.context=e,h}if(n=this._events[t],o(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:u=Array.prototype.slice.call(arguments,1),n.apply(this,u)}else if(s(n))for(u=Array.prototype.slice.call(arguments,1),c=n.slice(),i=c.length,a=0;a0&&this._events[t].length>i&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace())),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(t,e){function n(){this.removeListener(t,n),i||(i=!0,e.apply(this,arguments))}if(!r(e))throw TypeError("listener must be a function");var i=!1;return n.listener=e,this.on(t,n),this},n.prototype.removeListener=function(t,e){var n,i,o,u;if(!r(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(n=this._events[t],o=n.length,i=-1,n===e||r(n.listener)&&n.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(s(n)){for(u=o;u-- >0;)if(n[u]===e||n[u].listener&&n[u].listener===e){i=u;break}if(i<0)return this;1===n.length?(n.length=0,delete this._events[t]):n.splice(i,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},n.prototype.removeAllListeners=function(t){var e,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(n=this._events[t],r(n))this.removeListener(t,n);else if(n)for(;n.length;)this.removeListener(t,n[n.length-1]);return delete this._events[t],this},n.prototype.listeners=function(t){var e;return e=this._events&&this._events[t]?r(this._events[t])?[this._events[t]]:this._events[t].slice():[]},n.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(r(e))return 1;if(e)return e.length}return 0},n.listenerCount=function(t,e){return t.listenerCount(e)}},function(t,e,n){function r(){}function i(t){if(!_(t))return t;var e=[];for(var n in t)s(e,n,t[n]);return e.join("&")}function s(t,e,n){if(null!=n)if(Array.isArray(n))n.forEach(function(n){s(t,e,n)});else if(_(n))for(var r in n)s(t,e+"["+r+"]",n[r]);else t.push(encodeURIComponent(e)+"="+encodeURIComponent(n));else null===n&&t.push(encodeURIComponent(e))}function o(t){for(var e,n,r={},i=t.split("&"),s=0,o=i.length;s=300)&&(r=new Error(e.statusText||"Unsuccessful HTTP response"),r.original=t,r.response=e,r.status=e.status)}catch(t){r=t}r?n.callback(r,e):n.callback(null,e)})}function f(t,e){var n=m("DELETE",t);return e&&n.end(e),n}var d;"undefined"!=typeof window?d=window:"undefined"!=typeof self?d=self:(console.warn("Using browser-only version of superagent in non-browser environment"),d=this);var v=n(8),y=n(12),_=n(5),m=t.exports=n(13).bind(null,p);m.getXHR=function(){if(!(!d.XMLHttpRequest||d.location&&"file:"==d.location.protocol&&d.ActiveXObject))return new XMLHttpRequest;try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(t){}try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(t){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(t){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(t){}throw Error("Browser-only verison of superagent could not find XHR")};var E="".trim?function(t){return t.trim()}:function(t){return t.replace(/(^\s*|\s*$)/g,"")};m.serializeObject=i,m.parseString=o,m.types={html:"text/html",json:"application/json",xml:"application/xml",urlencoded:"application/x-www-form-urlencoded",form:"application/x-www-form-urlencoded","form-data":"application/x-www-form-urlencoded"},m.serialize={"application/x-www-form-urlencoded":i,"application/json":JSON.stringify},m.parse={"application/x-www-form-urlencoded":o,"application/json":JSON.parse},l.prototype.get=function(t){return this.header[t.toLowerCase()]},l.prototype._setHeaderProperties=function(t){var e=this.header["content-type"]||"";this.type=c(e);var n=h(e);for(var r in n)this[r]=n[r]},l.prototype._parseBody=function(t){var e=m.parse[this.type];return!e&&a(this.type)&&(e=m.parse["application/json"]),e&&t&&(t.length||t instanceof Object)?e(t):null},l.prototype._setStatusProperties=function(t){1223===t&&(t=204);var e=t/100|0;this.status=this.statusCode=t,this.statusType=e,this.info=1==e,this.ok=2==e,this.clientError=4==e,this.serverError=5==e,this.error=(4==e||5==e)&&this.toError(),this.accepted=202==t,this.noContent=204==t,this.badRequest=400==t,this.unauthorized=401==t,this.notAcceptable=406==t,this.notFound=404==t,this.forbidden=403==t},l.prototype.toError=function(){var t=this.req,e=t.method,n=t.url,r="cannot "+e+" "+n+" ("+this.status+")",i=new Error(r);return i.status=this.status,i.method=e,i.url=n,i},m.Response=l,v(p.prototype),y(p.prototype),p.prototype.type=function(t){return this.set("Content-Type",m.types[t]||t),this},p.prototype.responseType=function(t){return this._responseType=t,this},p.prototype.accept=function(t){return this.set("Accept",m.types[t]||t),this},p.prototype.auth=function(t,e,n){switch(n||(n={type:"basic"}),n.type){case"basic":var r=btoa(t+":"+e);this.set("Authorization","Basic "+r);break;case"auto":this.username=t,this.password=e}return this},p.prototype.query=function(t){return"string"!=typeof t&&(t=i(t)),t&&this._query.push(t),this},p.prototype.attach=function(t,e,n){if(this._data)throw Error("superagent can't mix .send() and .attach()");return this._getFormData().append(t,e,n||e.name),this},p.prototype._getFormData=function(){return this._formData||(this._formData=new d.FormData),this._formData},p.prototype.callback=function(t,e){var n=this._callback;this.clearTimeout(),t&&this.emit("error",t),n(t,e)},p.prototype.crossDomainError=function(){var t=new Error("Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.");t.crossDomain=!0,t.status=this.status,t.method=this.method,t.url=this.url,this.callback(t)},p.prototype.buffer=p.prototype.ca=p.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},p.prototype.pipe=p.prototype.write=function(){throw Error("Streaming is not supported in browser version of superagent")},p.prototype._timeoutError=function(){var t=this._timeout,e=new Error("timeout of "+t+"ms exceeded");e.timeout=t,this.callback(e)},p.prototype._appendQueryString=function(){var t=this._query.join("&");t&&(this.url+=~this.url.indexOf("?")?"&"+t:"?"+t)},p.prototype._isHost=function(t){return t&&"object"==typeof t&&!Array.isArray(t)&&"[object Object]"!==Object.prototype.toString.call(t)},p.prototype.end=function(t){var e=this,n=this.xhr=m.getXHR(),i=this._timeout,s=this._formData||this._data;this._callback=t||r,n.onreadystatechange=function(){if(4==n.readyState){var t;try{t=n.status}catch(e){t=0}if(0==t){if(e.timedout)return e._timeoutError();if(e._aborted)return;return e.crossDomainError()}e.emit("end")}};var o=function(t,n){n.total>0&&(n.percent=n.loaded/n.total*100),n.direction=t,e.emit("progress",n)};if(this.hasListeners("progress"))try{n.onprogress=o.bind(null,"download"),n.upload&&(n.upload.onprogress=o.bind(null,"upload"))}catch(t){}if(i&&!this._timer&&(this._timer=setTimeout(function(){e.timedout=!0,e.abort()},i)),this._appendQueryString(),this.username&&this.password?n.open(this.method,this.url,!0,this.username,this.password):n.open(this.method,this.url,!0),this._withCredentials&&(n.withCredentials=!0),"GET"!=this.method&&"HEAD"!=this.method&&"string"!=typeof s&&!this._isHost(s)){var u=this._header["content-type"],c=this._serializer||m.serialize[u?u.split(";")[0]:""];!c&&a(u)&&(c=m.serialize["application/json"]),c&&(s=c(s))}for(var h in this.header)null!=this.header[h]&&n.setRequestHeader(h,this.header[h]);return this._responseType&&(n.responseType=this._responseType),this.emit("request",this),n.send("undefined"!=typeof s?s:null),this},m.Request=p,m.get=function(t,e,n){var r=m("GET",t);return"function"==typeof e&&(n=e,e=null),e&&r.query(e),n&&r.end(n),r},m.head=function(t,e,n){var r=m("HEAD",t);return"function"==typeof e&&(n=e,e=null),e&&r.send(e),n&&r.end(n),r},m.options=function(t,e,n){var r=m("OPTIONS",t);return"function"==typeof e&&(n=e,e=null),e&&r.send(e),n&&r.end(n),r},m.del=f,m.delete=f,m.patch=function(t,e,n){var r=m("PATCH",t);return"function"==typeof e&&(n=e,e=null),e&&r.send(e),n&&r.end(n),r},m.post=function(t,e,n){var r=m("POST",t);return"function"==typeof e&&(n=e,e=null),e&&r.send(e),n&&r.end(n),r},m.put=function(t,e,n){var r=m("PUT",t);return"function"==typeof e&&(n=e,e=null),e&&r.send(e),n&&r.end(n),r}},function(t,e){function n(t){return null!==t&&"object"==typeof t}t.exports=n},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}var o=function(){function t(t,e){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{},n=t.OAUTH2_CLIENT_ID;r(this,e);var s=i(this,(e.__proto__||Object.getPrototypeOf(e)).call(this));return s.rpc=new u({OAUTH2_CLIENT_ID:n}),s.rpc.evts.on("READY",function(){s.user=s.rpc.user,s.application=s.rpc.application,s.emit("ready")}),s.rpc.evts.on("ERROR",function(t){return s.emit("error",t)}),s.rest=s.rpc.rest,s}return s(e,t),o(e,[{key:"getGuild",value:function(t,e){var n=this;return new Promise(function(r,i){n.rpc.request("GET_GUILD",{guild_id:t,timeout:e},function(t,e){t&&i(t),r(e.data)})})}},{key:"getGuilds",value:function(){var t=this;return new Promise(function(e,n){t.rpc.request("GET_GUILDS",{},function(t,r){t&&n(t),e(r.data.guilds)})})}},{key:"getChannel",value:function(t,e){var n=this;return new Promise(function(r,i){n.rpc.request("GET_CHANNEL",{channel_id:t,timeout:e},function(t,e){t&&i(t),r(e.data)})})}},{key:"getChannels",value:function(){var t=this;return new Promise(function(e,n){t.rpc.request("GET_CHANNELS",{},function(t,r){t&&n(t),e(r.data.channels)})})}},{key:"setUserVoiceSettings",value:function(t){var e=this;return new Promise(function(n,r){e.rpc.request("SET_USER_VOICE_SETTINGS",t,function(t,e){t&&r(t),n(e.data)})})}},{key:"selectVoiceChannel",value:function(t,e){var n=this,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return new Promise(function(i,s){n.rpc.request("SELECT_VOICE_CHANNEL",{channel_id:t,timeout:e,force:r},function(t,e){t&&s(t),i(e.data)})})}},{key:"selectTextChannel",value:function(t,e){var n=this,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return new Promise(function(i,s){n.rpc.request("SELECT_TEXT_CHANNEL",{channel_id:t,timeout:e,force:r},function(t,e){t&&s(t),i(e.data)})})}},{key:"getVoiceSettings",value:function(){var t=this;return new Promise(function(e,n){t.rpc.request("GET_VOICE_SETTINGS",{},function(t,r){t&&n(t),e(r.data)})})}},{key:"setVoiceSettings",value:function(t){var e=this;return new Promise(function(n,r){e.rpc.request("SET_VOICE_SETTINGS",t,function(t,e){t&&r(t),n(e.data)})})}},{key:"subscribe",value:function(t,e,n){return this.rpc.subscribe(t,e,n)}},{key:"unsubscribe",value:function(t,e,n){return this.rpc.unsubscribe(t,e,n)}},{key:"connect",value:function(t){return this.rpc.connect(t)}}]),e}(a);t.exports=c},function(t,e){t.exports={name:"discord-rpc",version:"2.0.0",description:"A simple RPC client for Discord somewhat stolen from the Discord StreamKit.",main:"src/index.js",repository:{type:"git",url:"git+https://github.com/GusCaplan/discord-rpc.git"},scripts:{"web-dist":"node ./node_modules/parallel-webpack/bin/run.js"},author:"Gus Caplan ",license:"MIT",bugs:{url:"https://github.com/GusCaplan/discord-rpc/issues"},homepage:"https://github.com/GusCaplan/discord-rpc#readme",dependencies:{"deep-equal":"^1.0.1",superagent:"^3.0.0",uuid:"^3.0.0",ws:"^1.1.1"},devDependencies:{"babel-core":"^6.18.2","babel-loader":"^6.2.8","babel-preset-es2015":"^6.18.0",bufferutil:"^1.2.1","ignore-loader":"^0.1.2","json-loader":"^0.5.4","parallel-webpack":"^1.5.0","uglify-js":"github:mishoo/UglifyJS2#harmony","utf-8-validate":"^1.2.1",webpack:"2.1.0-beta.27"},browser:{ws:!1}}},function(t,e,n){function r(t){if(t)return i(t)}function i(t){for(var e in r.prototype)t[e]=r.prototype[e];return t}t.exports=r,r.prototype.on=r.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},r.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},r.prototype.off=r.prototype.removeListener=r.prototype.removeAllListeners=r.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n=this._callbacks["$"+t];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var r,i=0;i0&&"number"!=typeof t[0]))}function s(t,e,n){var s,h;if(r(t)||r(e))return!1;if(t.prototype!==e.prototype)return!1;if(a(t))return!!a(e)&&(t=o.call(t),e=o.call(e),c(t,e,n));if(i(t)){if(!i(e))return!1;if(t.length!==e.length)return!1;for(s=0;s=0;s--)if(l[s]!=p[s])return!1;for(s=l.length-1;s>=0;s--)if(h=l[s],!c(t[h],e[h],n))return!1;return typeof t==typeof e}var o=Array.prototype.slice,u=n(11),a=n(10),c=t.exports=function(t,e,n){return n||(n={}),t===e||(t instanceof Date&&e instanceof Date?t.getTime()===e.getTime():!t||!e||"object"!=typeof t&&"object"!=typeof e?n.strict?t===e:t==e:s(t,e,n))}},function(t,e){function n(t){return"[object Arguments]"==Object.prototype.toString.call(t)}function r(t){return t&&"object"==typeof t&&"number"==typeof t.length&&Object.prototype.hasOwnProperty.call(t,"callee")&&!Object.prototype.propertyIsEnumerable.call(t,"callee")||!1}var i="[object Arguments]"==function(){return Object.prototype.toString.call(arguments)}();e=t.exports=i?n:r,e.supported=n,e.unsupported=r},function(t,e){function n(t){var e=[];for(var n in t)e.push(n);return e}e=t.exports="function"==typeof Object.keys?Object.keys:n,e.shim=n},function(t,e,n){function r(t){if(t)return i(t)}function i(t){for(var e in r.prototype)t[e]=r.prototype[e];return t}var s=n(5);t.exports=r,r.prototype.clearTimeout=function(){return this._timeout=0,clearTimeout(this._timer),this},r.prototype.parse=function(t){return this._parser=t,this},r.prototype.serialize=function(t){return this._serializer=t,this},r.prototype.timeout=function(t){return this._timeout=t,this},r.prototype.then=function(t,e){if(!this._fullfilledPromise){var n=this;this._fullfilledPromise=new Promise(function(t,e){n.end(function(n,r){n?e(n):t(r)})})}return this._fullfilledPromise.then(t,e)},r.prototype.catch=function(t){return this.then(void 0,t)},r.prototype.use=function(t){return t(this),this},r.prototype.get=function(t){return this._header[t.toLowerCase()]},r.prototype.getHeader=r.prototype.get,r.prototype.set=function(t,e){if(s(t)){for(var n in t)this.set(n,t[n]);return this}return this._header[t.toLowerCase()]=e,this.header[t]=e,this},r.prototype.unset=function(t){return delete this._header[t.toLowerCase()],delete this.header[t],this},r.prototype.field=function(t,e){if(null===t||void 0===t)throw new Error(".field(name, val) name can not be empty");if(s(t)){for(var n in t)this.field(n,t[n]);return this}if(null===e||void 0===e)throw new Error(".field(name, val) val can not be empty");return this._getFormData().append(t,e),this},r.prototype.abort=function(){return this._aborted?this:(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req&&this.req.abort(),this.clearTimeout(),this.emit("abort"),this)},r.prototype.withCredentials=function(){return this._withCredentials=!0,this},r.prototype.redirects=function(t){return this._maxRedirects=t,this},r.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},r.prototype.send=function(t){var e=s(t),n=this._header["content-type"];if(e&&!this._data)Array.isArray(t)?this._data=[]:this._isHost(t)||(this._data={});else if(t&&this._data&&this._isHost(this._data))throw Error("Can't merge these send calls");if(e&&s(this._data))for(var r in t)this._data[r]=t[r];else"string"==typeof t?(n||this.type("form"),n=this._header["content-type"],"application/x-www-form-urlencoded"==n?this._data=this._data?this._data+"&"+t:t:this._data=(this._data||"")+t):this._data=t;return!e||this._isHost(t)?this:(n||this.type("json"),this)}},function(t,e){function n(t,e,n){return"function"==typeof n?new t("GET",e).end(n):2==arguments.length?new t("GET",e):new t(e,n)}t.exports=n},function(t,e,n){(function(e){var n,r=e.crypto||e.msCrypto;if(r&&r.getRandomValues){var i=new Uint8Array(16);n=function(){return r.getRandomValues(i),i}}if(!n){var s=new Array(16);n=function(){for(var t,e=0;e<16;e++)0===(3&e)&&(t=4294967296*Math.random()),s[e]=t>>>((3&e)<<3)&255;return s}}t.exports=n}).call(e,n(16))},function(t,e,n){function r(t,e){var n=e||0,r=u;return r[t[n++]]+r[t[n++]]+r[t[n++]]+r[t[n++]]+"-"+r[t[n++]]+r[t[n++]]+"-"+r[t[n++]]+r[t[n++]]+"-"+r[t[n++]]+r[t[n++]]+"-"+r[t[n++]]+r[t[n++]]+r[t[n++]]+r[t[n++]]+r[t[n++]]+r[t[n++]]}function i(t,e,n){var i=e&&n||0,s=e||[];t=t||{};var o=void 0!==t.clockseq?t.clockseq:p,u=void 0!==t.msecs?t.msecs:(new Date).getTime(),a=void 0!==t.nsecs?t.nsecs:d+1,c=u-f+(a-d)/1e4;if(c<0&&void 0===t.clockseq&&(o=o+1&16383),(c<0||u>f)&&void 0===t.nsecs&&(a=0), +a>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");f=u,d=a,p=o,u+=122192928e5;var h=(1e4*(268435455&u)+a)%4294967296;s[i++]=h>>>24&255,s[i++]=h>>>16&255,s[i++]=h>>>8&255,s[i++]=255&h;var v=u/4294967296*1e4&268435455;s[i++]=v>>>8&255,s[i++]=255&v,s[i++]=v>>>24&15|16,s[i++]=v>>>16&255,s[i++]=o>>>8|128,s[i++]=255&o;for(var y=t.node||l,_=0;_<6;++_)s[i+_]=y[_];return e?e:r(s)}function s(t,e,n){var i=e&&n||0;"string"==typeof t&&(e="binary"==t?new Array(16):null,t=null),t=t||{};var s=t.random||(t.rng||o)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,e)for(var u=0;u<16;++u)e[i+u]=s[u];return e||r(s)}for(var o=n(14),u=[],a={},c=0;c<256;++c)u[c]=(c+256).toString(16).substr(1),a[u[c]]=c;var h=o(),l=[1|h[0],h[1],h[2],h[3],h[4],h[5]],p=16383&(h[6]<<8|h[7]),f=0,d=0,v=s;v.v1=i,v.v4=s,t.exports=v},function(t,e){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(t){"object"==typeof window&&(n=window)}t.exports=n},function(t,e){},function(t,e,n){"use strict";t.exports={version:n(7).version,Client:n(6),RPC:n(2),Rest:n(1),Constants:n(0)},"undefined"!=typeof window&&(window.DiscordRPC=t.exports)}]); \ No newline at end of file