vis.js is a dynamic, browser-based visualization library
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

26999 lines
807 KiB

  1. (function webpackUniversalModuleDefinition(root, factory) {
  2. if(typeof exports === 'object' && typeof module === 'object')
  3. module.exports = factory(require("amqp"));
  4. else if(typeof define === 'function' && define.amd)
  5. define(["amqp"], factory);
  6. else if(typeof exports === 'object')
  7. exports["eve"] = factory(require("amqp"));
  8. else
  9. root["eve"] = factory(root["amqp"]);
  10. })(this, function(__WEBPACK_EXTERNAL_MODULE_23__) {
  11. return /******/ (function(modules) { // webpackBootstrap
  12. /******/ // The module cache
  13. /******/ var installedModules = {};
  14. /******/
  15. /******/ // The require function
  16. /******/ function __webpack_require__(moduleId) {
  17. /******/
  18. /******/ // Check if module is in cache
  19. /******/ if(installedModules[moduleId])
  20. /******/ return installedModules[moduleId].exports;
  21. /******/
  22. /******/ // Create a new module (and put it into the cache)
  23. /******/ var module = installedModules[moduleId] = {
  24. /******/ exports: {},
  25. /******/ id: moduleId,
  26. /******/ loaded: false
  27. /******/ };
  28. /******/
  29. /******/ // Execute the module function
  30. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  31. /******/
  32. /******/ // Flag the module as loaded
  33. /******/ module.loaded = true;
  34. /******/
  35. /******/ // Return the exports of the module
  36. /******/ return module.exports;
  37. /******/ }
  38. /******/
  39. /******/
  40. /******/ // expose the modules object (__webpack_modules__)
  41. /******/ __webpack_require__.m = modules;
  42. /******/
  43. /******/ // expose the module cache
  44. /******/ __webpack_require__.c = installedModules;
  45. /******/
  46. /******/ // __webpack_public_path__
  47. /******/ __webpack_require__.p = "";
  48. /******/
  49. /******/ // Load entry module and return exports
  50. /******/ return __webpack_require__(0);
  51. /******/ })
  52. /************************************************************************/
  53. /******/ ([
  54. /* 0 */
  55. /***/ function(module, exports, __webpack_require__) {
  56. exports.Agent = __webpack_require__(1);
  57. exports.ServiceManager = __webpack_require__(2);
  58. exports.TransportManager = __webpack_require__(3);
  59. exports.module = {
  60. BabbleModule: __webpack_require__(5),
  61. PatternModule: __webpack_require__(6),
  62. RequestModule: __webpack_require__(7),
  63. RPCModule: __webpack_require__(8)
  64. };
  65. exports.transport = {
  66. Transport: __webpack_require__(9),
  67. AMQPTransport: __webpack_require__(11),
  68. DistribusTransport: __webpack_require__(13),
  69. HTTPTransport: __webpack_require__(15),
  70. LocalTransport: __webpack_require__(17),
  71. PubNubTransport: __webpack_require__(19),
  72. WebSocketTransport: __webpack_require__(21),
  73. connection: {
  74. Connection: __webpack_require__(10),
  75. AMQPConnection: __webpack_require__(12),
  76. DistribusConnection: __webpack_require__(14),
  77. HTTPConnection: __webpack_require__(16),
  78. LocalConnection: __webpack_require__(18),
  79. PubNubConnection: __webpack_require__(20),
  80. WebSocketConnection: __webpack_require__(22)
  81. }
  82. };
  83. exports.hypertimer = __webpack_require__(24);
  84. exports.util = __webpack_require__(4);
  85. // register all modules at the Agent
  86. exports.Agent.registerModule(exports.module.BabbleModule);
  87. exports.Agent.registerModule(exports.module.PatternModule);
  88. exports.Agent.registerModule(exports.module.RequestModule);
  89. exports.Agent.registerModule(exports.module.RPCModule);
  90. // register all transports at the TransportManager
  91. exports.TransportManager.registerType(exports.transport.AMQPTransport);
  92. exports.TransportManager.registerType(exports.transport.DistribusTransport);
  93. exports.TransportManager.registerType(exports.transport.HTTPTransport);
  94. exports.TransportManager.registerType(exports.transport.LocalTransport);
  95. exports.TransportManager.registerType(exports.transport.PubNubTransport);
  96. exports.TransportManager.registerType(exports.transport.WebSocketTransport);
  97. // load the default ServiceManager, a singleton, initialized with a LocalTransport
  98. exports.system = new exports.ServiceManager();
  99. exports.system.transports.add(new exports.transport.LocalTransport());
  100. // override Agent.getTransportById in order to support Agent.connect(transportId)
  101. exports.Agent.getTransportById = function (id) {
  102. return exports.system.transports.get(id);
  103. };
  104. /***/ },
  105. /* 1 */
  106. /***/ function(module, exports, __webpack_require__) {
  107. 'use strict';
  108. var Promise = __webpack_require__(27);
  109. var uuid = __webpack_require__(28);
  110. var util = __webpack_require__(4);
  111. /**
  112. * Agent
  113. * @param {string} [id] Id for the agent. If not provided, the agent
  114. * will be given a uuid.
  115. * @constructor
  116. */
  117. function Agent (id) {
  118. this.id = id ? id.toString() : uuid();
  119. // a list with all connected transports
  120. this.connections = [];
  121. this.defaultConnection = null;
  122. this.ready = Promise.resolve([]);
  123. }
  124. // an object with modules which can be used to extend the agent
  125. Agent.modules = {};
  126. /**
  127. * Register a new type of module. This module can then be loaded via
  128. * Agent.extend() and Agent.loadModule().
  129. * @param {Function} constructor A module constructor
  130. */
  131. Agent.registerModule = function (constructor) {
  132. var type = constructor.prototype.type;
  133. if (typeof constructor !== 'function') {
  134. throw new Error('Constructor function expected');
  135. }
  136. if (!type) {
  137. throw new Error('Field "prototype.type" missing in transport constructor');
  138. }
  139. if (type in Agent.modules) {
  140. if (Agent.modules[type] !== constructor) {
  141. throw new Error('Module of type "' + type + '" already exists');
  142. }
  143. }
  144. Agent.modules[type] = constructor;
  145. };
  146. /**
  147. * Get a transport by id.
  148. * This static method can be overloaded for example by the get function of
  149. * a singleton TransportManager.
  150. * @param {string} id
  151. * @return {Transport}
  152. */
  153. Agent.getTransportById = function (id) {
  154. throw new Error('Transport with id "' + id + '" not found');
  155. };
  156. /**
  157. * Extend an agent with modules (mixins).
  158. * The modules new functions are added to the Agent itself.
  159. * See also function `loadModule`.
  160. * @param {string | string[]} module A module name or an Array with module
  161. * names. Available modules:
  162. * 'pattern', 'request', 'babble'
  163. * @param {Object} [options] Additional options for loading the module
  164. * @return {Agent} Returns the agent itself
  165. */
  166. Agent.prototype.extend = function (module, options) {
  167. if (Array.isArray(module)) {
  168. var modules = [].concat(module);
  169. // order the modules such that 'pattern' comes first, this module must be
  170. // loaded before other modules ('request' specifically)
  171. modules.sort(function (a, b) {
  172. if (a == 'pattern') return -1;
  173. if (b == 'pattern') return 1;
  174. return 0;
  175. });
  176. // an array with module names
  177. for (var i = 0; i < modules.length; i++) {
  178. this.extend(modules[i], options)
  179. }
  180. }
  181. else {
  182. // a single module name
  183. var constructor = _getModuleConstructor(module);
  184. var instance = new constructor(this, options);
  185. var mixin = instance.mixin();
  186. // check for conflicts in the modules mixin functions
  187. var me = this;
  188. Object.keys(mixin).forEach(function (name) {
  189. if (me[name] !== undefined && name !== '_receive') {
  190. throw new Error('Conflict: agent already has a property "' + prop + '"');
  191. }
  192. });
  193. // extend the agent with all mixin functions provided by the module
  194. Object.keys(mixin).forEach(function (name) {
  195. me[name] = mixin[name];
  196. });
  197. }
  198. return this;
  199. };
  200. /**
  201. * Load a module onto an agent.
  202. * See also function `extend`.
  203. * @param {string | string[]} module A module name or an Array with module
  204. * names. Available modules:
  205. * 'pattern', 'request', 'babble'
  206. * @param {Object} [options] Additional options for loading the module
  207. * @return {Object} Returns the created module
  208. */
  209. Agent.prototype.loadModule = function (module, options, additionalOptions) {
  210. var _options = options !== undefined ? Object.create(options) : {};
  211. _options.extend = false;
  212. var constructor = _getModuleConstructor(module);
  213. var instance = new constructor(this, options, additionalOptions);
  214. var mixin = instance.mixin();
  215. // only replace the _receive function, do not add other mixin functions
  216. this._receive = mixin._receive;
  217. return instance;
  218. };
  219. /**
  220. * Get a module constructor by it's name.
  221. * Throws an error when the module is not found.
  222. * @param {string} name
  223. * @return {function} Returns the modules constructor function
  224. * @private
  225. */
  226. function _getModuleConstructor(name) {
  227. var constructor = Agent.modules[name];
  228. if (!constructor) {
  229. throw new Error('Unknown module "' + name + '". ' +
  230. 'Choose from: ' + Object.keys(Agent.modules).map(JSON.stringify).join(', '));
  231. }
  232. return constructor;
  233. }
  234. /**
  235. * Send a message to an agent
  236. * @param {string} to
  237. * to is either:
  238. * - A string "agentId", the id of the recipient. Will be send
  239. * via the default transport or when there is no default
  240. * transport via the first connected transport.
  241. * - A string "agentId@transportId" Only usable locally, not
  242. * for sharing an address with remote agents.
  243. * - A string "protocol://networkId/agentId". This is a sharable
  244. * identifier for an agent.
  245. * @param {*} message Message to be send
  246. * @return {Promise} Returns a promise which resolves when the message as
  247. * successfully been sent, or rejected when sending the
  248. * message failed
  249. */
  250. Agent.prototype.send = function(to, message) {
  251. var colon = to.indexOf('://');
  252. if (colon !== -1) {
  253. // to is an url like "protocol://networkId/agentId"
  254. var url = util.parseUrl(to);
  255. if (url.protocol == 'http' || url.protocol == 'ws' || url.protocol == 'https') { // TODO: ugly fixed listing here...
  256. return this._sendByProtocol(url.protocol, to, message);
  257. }
  258. else {
  259. return this._sendByNetworkId(url.domain, url.path, message);
  260. }
  261. }
  262. // TODO: deprecate this notation "agentId@transportId"?
  263. var at = to.indexOf('@');
  264. if (at != -1) {
  265. // to is an id like "agentId@transportId"
  266. var _to = to.substring(0, at);
  267. var _transportId = to.substring(at + 1);
  268. return this._sendByTransportId(_transportId, _to, message);
  269. }
  270. // to is an id like "agentId". Send via the default transport
  271. var conn = this.defaultConnection;
  272. if (conn) {
  273. return conn.send(to, message);
  274. }
  275. else {
  276. return Promise.reject(new Error('No transport found'));
  277. }
  278. };
  279. /**
  280. * Send a transport to an agent given a networkId
  281. * @param {string} networkId A network id
  282. * @param {string} to An agents id
  283. * @param {string} message Message to be send
  284. * @return {Promise} Returns a promise which resolves when the message as
  285. * successfully been sent, or rejected when sending the
  286. * message failed
  287. * @private
  288. */
  289. Agent.prototype._sendByNetworkId = function(networkId, to, message) {
  290. // TODO: change this.connections to a map with networkId as keys, much faster
  291. for (var i = 0; i < this.connections.length; i++) {
  292. var connection = this.connections[i];
  293. if (connection.transport.networkId == networkId) {
  294. return connection.send(to, message);
  295. }
  296. }
  297. return Promise.reject(new Error('No transport found with networkId "' + networkId + '"'));
  298. };
  299. /**
  300. * Send a message by a transport by protocol.
  301. * The message will be send via the first found transport having the specified
  302. * protocol.
  303. * @param {string} protocol A protocol, for example 'http' or 'ws'
  304. * @param {string} to An agents id
  305. * @param {string} message Message to be send
  306. * @return {Promise} Returns a promise which resolves when the message as
  307. * successfully been sent, or rejected when sending the
  308. * message failed
  309. * @private
  310. */
  311. Agent.prototype._sendByProtocol = function(protocol, to, message) {
  312. // the https addresses also make use of the http protocol.
  313. protocol = protocol == 'https' ? 'http' : protocol;
  314. for (var i = 0; i < this.connections.length; i++) {
  315. var connection = this.connections[i];
  316. if (connection.transport.type == protocol) {
  317. return connection.send(to, message);
  318. }
  319. }
  320. return Promise.reject(new Error('No transport found for protocol "' + protocol + '"'));
  321. };
  322. /**
  323. * Send a transport to an agent via a specific transport
  324. * @param {string} transportId The configured id of a transport.
  325. * @param {string} to An agents id
  326. * @param {string} message Message to be send
  327. * @return {Promise} Returns a promise which resolves when the message as
  328. * successfully been sent, or rejected when sending the
  329. * message failed
  330. * @private
  331. */
  332. Agent.prototype._sendByTransportId = function(transportId, to, message) {
  333. for (var i = 0; i < this.connections.length; i++) {
  334. var connection = this.connections[i];
  335. if (connection.transport.id == transportId) {
  336. return connection.send(to, message);
  337. }
  338. }
  339. return Promise.reject(new Error('No transport found with id "' + transportId + '"'));
  340. };
  341. /**
  342. * Receive a message.
  343. * @param {string} from Id of sender
  344. * @param {*} message Received message, a JSON object (often a string)
  345. */
  346. Agent.prototype.receive = function(from, message) {
  347. // ... to be overloaded
  348. };
  349. /**
  350. * The method _receive is overloaded in a cascaded way by modules, and calls
  351. * the public method Agent.receive at the end of the chain.
  352. * @param {string} from Id of sender
  353. * @param {*} message Received message, a JSON object (often a string)
  354. * @returns {*} Returns the return value of Agent.receive
  355. * @private
  356. */
  357. Agent.prototype._receive = function (from, message) {
  358. return this.receive(from, message);
  359. };
  360. /**
  361. * Connect to a transport. The agent will subscribe itself to
  362. * messages sent to his id.
  363. * @param {string | Transport | Transport[] | string[]} transport
  364. * A Transport instance, or the id of a
  365. * transport loaded in eve.system.
  366. * @param {string} [id] An optional alternative id to be used
  367. * for the connection. By default, the agents
  368. * own id is used.
  369. * @return {Connection | Connection[]} Returns a connection or, in case of
  370. * multiple transports, returns an
  371. * array with connections. The connections
  372. * have a promise .ready which resolves
  373. * as soon as the connection is ready for
  374. * use.
  375. */
  376. Agent.prototype.connect = function(transport, id) {
  377. if (Array.isArray(transport)) {
  378. var me = this;
  379. return transport.map(function (_transport) {
  380. return me._connect(_transport, id);
  381. });
  382. }
  383. else if (typeof transport === 'string') {
  384. // get transport by id
  385. return this._connect(Agent.getTransportById(transport), id);
  386. }
  387. else {
  388. // a transport instance
  389. return this._connect(transport, id);
  390. }
  391. };
  392. /**
  393. * Connect to a transport
  394. * @param {Transport} transport A Transport instance
  395. * @param {string} [id] An optional alternative id to be used
  396. * for the connection. By default, the agents
  397. * own id is used.
  398. * @return {Connection} Returns a connection.
  399. * @private
  400. */
  401. Agent.prototype._connect = function (transport, id) {
  402. // create a receive function which is bound to the _receive function.
  403. // the _receive function can be replaced in by modules in a cascaded way,
  404. // and in the end calls this.receive of the agent.
  405. // note: we don't do receive = this._receive.bind(this) as the _receive
  406. // function can be overloaded after a connection is made.
  407. var me = this;
  408. var receive = function (from, message) {
  409. return me._receive(from, message);
  410. };
  411. var connection = transport.connect(id || this.id, receive);
  412. this.connections.push(connection);
  413. // set or replace the defaultConnection
  414. if (!this.defaultConnection) {
  415. this.defaultConnection = connection;
  416. }
  417. else if (transport['default']) {
  418. if (this.defaultConnection['default']) {
  419. throw new Error('Cannot connect to a second default transport');
  420. }
  421. this.defaultConnection = connection;
  422. }
  423. this._updateReady();
  424. return connection;
  425. };
  426. /**
  427. * Disconnect from one or multiple transports
  428. * @param {string | Transport | string[] | Transport[]} [transport]
  429. * A transport or an array with transports.
  430. * parameter transport can be an instance of a Transport, or the
  431. * id of a transport.
  432. * When transport is undefined, the agent will be disconnected
  433. * from all connected transports.
  434. */
  435. Agent.prototype.disconnect = function(transport) {
  436. var i, connection;
  437. if (!transport) {
  438. // disconnect all transports
  439. while (connection = this.connections[0]) {
  440. this._disconnect(connection);
  441. }
  442. }
  443. else if (Array.isArray(transport)) {
  444. // an array with transports
  445. i = 0;
  446. while (i < this.connections.length) {
  447. connection = this.connections[i];
  448. if (transport.indexOf(connection.transport) !== -1) {
  449. this._disconnect(connection);
  450. }
  451. else {
  452. i++;
  453. }
  454. }
  455. }
  456. else if (typeof transport === 'string') {
  457. // transport by id
  458. this.disconnect(Agent.getTransportById(transport));
  459. }
  460. else {
  461. // a single transport
  462. for (i = 0; i < this.connections.length; i++) {
  463. connection = this.connections[i];
  464. if (connection.transport === transport) {
  465. this._disconnect(connection);
  466. break;
  467. }
  468. }
  469. }
  470. };
  471. /**
  472. * Close a connection
  473. * @param {Connection} connection
  474. * @private
  475. */
  476. Agent.prototype._disconnect = function (connection) {
  477. // find the connection
  478. var index = this.connections.indexOf(connection);
  479. if (index !== -1) {
  480. // close the connection
  481. connection.close();
  482. // remove from the list with connections
  483. this.connections.splice(index, 1);
  484. // replace the defaultConnection if needed
  485. if (this.defaultConnection === connection) {
  486. this.defaultConnection = this.connections[this.connections.length - 1] || null;
  487. }
  488. }
  489. this._updateReady();
  490. };
  491. /**
  492. * Update the ready state of the agent
  493. * @private
  494. */
  495. Agent.prototype._updateReady = function () {
  496. // FIXME: we should not replace with a new Promise,
  497. // we have a problem when this.ready is requested before ready,
  498. // and another connection is opened before ready
  499. this.ready = Promise.all(this.connections.map(function (connection) {
  500. return connection.ready;
  501. }));
  502. };
  503. module.exports = Agent;
  504. /***/ },
  505. /* 2 */
  506. /***/ function(module, exports, __webpack_require__) {
  507. 'use strict';
  508. var seed = __webpack_require__(25);
  509. var hypertimer = __webpack_require__(24);
  510. var TransportManager = __webpack_require__(3);
  511. // map with known configuration properties
  512. var KNOWN_PROPERTIES = {
  513. transports: true,
  514. timer: true,
  515. random: true
  516. };
  517. function ServiceManager(config) {
  518. this.transports = new TransportManager();
  519. this.timer = hypertimer();
  520. this.random = Math.random;
  521. this.init(config);
  522. }
  523. /**
  524. * Initialize the service manager with services loaded from a configuration
  525. * object. All current services are unloaded and removed.
  526. * @param {Object} config
  527. */
  528. ServiceManager.prototype.init = function (config) {
  529. this.transports.clear();
  530. if (config) {
  531. if (config.transports) {
  532. this.transports.load(config.transports);
  533. }
  534. if (config.timer) {
  535. this.timer.config(config.timer);
  536. }
  537. if (config.random) {
  538. if (config.random.deterministic) {
  539. var key = config.random.seed || 'random seed';
  540. this.random = seed(key, config.random);
  541. }
  542. else {
  543. this.random = Math.random;
  544. }
  545. }
  546. for (var prop in config) {
  547. if (config.hasOwnProperty(prop) && !KNOWN_PROPERTIES[prop]) {
  548. // TODO: should log this warning via a configured logger
  549. console.log('WARNING: Unknown configuration option "' + prop + '"')
  550. }
  551. }
  552. }
  553. };
  554. /**
  555. * Clear all configured services
  556. */
  557. ServiceManager.prototype.clear = function () {
  558. this.transports.clear();
  559. };
  560. module.exports = ServiceManager;
  561. /***/ },
  562. /* 3 */
  563. /***/ function(module, exports, __webpack_require__) {
  564. 'use strict';
  565. /**
  566. * A manager for loading and finding transports.
  567. * @param {Array} [config] Optional array containing configuration objects
  568. * for transports.
  569. * @constructor
  570. */
  571. function TransportManager(config) {
  572. this.transports = [];
  573. if (config) {
  574. this.load(config);
  575. }
  576. }
  577. // map with all registered types of transports
  578. // each transport must register itself at the TransportManager using registerType.
  579. TransportManager.types = {};
  580. /**
  581. * Register a new type of transport. This transport can then be loaded via
  582. * configuration.
  583. * @param {Transport.prototype} constructor A transport constructor
  584. */
  585. TransportManager.registerType = function (constructor) {
  586. var type = constructor.prototype.type;
  587. if (typeof constructor !== 'function') {
  588. throw new Error('Constructor function expected');
  589. }
  590. if (!type) {
  591. throw new Error('Field "prototype.type" missing in transport constructor');
  592. }
  593. if (type in TransportManager.types) {
  594. if (TransportManager.types[type] !== constructor) {
  595. throw new Error('Transport type "' + type + '" already exists');
  596. }
  597. }
  598. TransportManager.types[type] = constructor;
  599. };
  600. /**
  601. * Add a loaded transport to the manager
  602. * @param {Transport} transport
  603. * @return {Transport} returns the transport itself
  604. */
  605. TransportManager.prototype.add = function (transport) {
  606. this.transports.push(transport);
  607. return transport;
  608. };
  609. /**
  610. * Load one or multiple transports based on JSON configuration.
  611. * New transports will be appended to current transports.
  612. * @param {Object | Array} config
  613. * @return {Transport | Transport[]} Returns the loaded transport(s)
  614. */
  615. TransportManager.prototype.load = function (config) {
  616. if (Array.isArray(config)) {
  617. return config.map(this.load.bind(this));
  618. }
  619. var type = config.type;
  620. if (!type) {
  621. throw new Error('Property "type" missing');
  622. }
  623. var constructor = TransportManager.types[type];
  624. if (!constructor) {
  625. throw new Error('Unknown type of transport "' + type + '". ' +
  626. 'Choose from: ' + Object.keys(TransportManager.types).join(','))
  627. }
  628. var transport = new constructor(config);
  629. this.transports.push(transport);
  630. return transport;
  631. };
  632. /**
  633. * Unload a transport.
  634. * @param {Transport | Transport[] | string | string[]} transport
  635. * A Transport instance or the id of a transport, or an Array
  636. * with transports or transport ids.
  637. */
  638. TransportManager.prototype.unload = function (transport) {
  639. var _transport;
  640. if (typeof transport === 'string') {
  641. _transport = this.get(transport);
  642. }
  643. else if (Array.isArray(transport)) {
  644. for (var i = 0; i < transport.length; i++) {
  645. this.unload(transport[i]);
  646. }
  647. }
  648. else {
  649. _transport = transport;
  650. }
  651. if (_transport) {
  652. _transport.close();
  653. var index = this.transports.indexOf(_transport);
  654. if (index !== -1) {
  655. this.transports.splice(index, 1);
  656. }
  657. }
  658. };
  659. /**
  660. * Get a transport by its id. The transport must have been created with an id
  661. * @param {string} [id] The id of a transport
  662. * @return {Transport} Returns the transport when found. Throws an error
  663. * when not found.
  664. */
  665. TransportManager.prototype.get = function (id) {
  666. for (var i = 0; i < this.transports.length; i++) {
  667. var transport = this.transports[i];
  668. if (transport.id === id) {
  669. return transport;
  670. }
  671. }
  672. throw new Error('Transport with id "' + id + '" not found');
  673. };
  674. /**
  675. * Get all transports.
  676. * @return {Transport[]} Returns an array with all loaded transports.
  677. */
  678. TransportManager.prototype.getAll = function () {
  679. return this.transports.concat([]);
  680. };
  681. /**
  682. * Find transports by type.
  683. * @param {string} [type] Type of the transport. Choose from 'amqp',
  684. * 'distribus', 'local', 'pubnub'.
  685. * @return {Transport[]} When type is defined, the all transports of this
  686. * type are returned. When undefined, all transports
  687. * are returned.
  688. */
  689. TransportManager.prototype.getByType = function (type) {
  690. if (type) {
  691. if (!(type in TransportManager.types)) {
  692. throw new Error('Unknown type of transport "' + type + '". ' +
  693. 'Choose from: ' + Object.keys(TransportManager.types).join(','))
  694. }
  695. return this.transports.filter(function (transport) {
  696. return transport.type === type;
  697. });
  698. }
  699. else {
  700. return [].concat(this.transports);
  701. }
  702. };
  703. /**
  704. * Close all configured transports and remove them from the manager.
  705. */
  706. TransportManager.prototype.clear = function () {
  707. this.transports.forEach(function (transport) {
  708. transport.close();
  709. });
  710. this.transports = [];
  711. };
  712. module.exports = TransportManager;
  713. /***/ },
  714. /* 4 */
  715. /***/ function(module, exports, __webpack_require__) {
  716. 'use strict';
  717. /**
  718. * Test whether the provided value is a Promise.
  719. * A value is marked as a Promise when it is an object containing functions
  720. * `then` and `catch`.
  721. * @param {*} value
  722. * @return {boolean} Returns true when `value` is a Promise
  723. */
  724. exports.isPromise = function (value) {
  725. return value &&
  726. typeof value['then'] === 'function' &&
  727. typeof value['catch'] === 'function'
  728. };
  729. /**
  730. * Splits an url like "protocol://domain/path"
  731. * @param {string} url
  732. * @return {{protocol: string, domain: string, path: string} | null}
  733. * Returns an object with properties protocol, domain, and path
  734. * when there is a match. Returns null if no valid url.
  735. *
  736. */
  737. exports.parseUrl = function (url) {
  738. // match an url like "protocol://domain/path"
  739. var match = /^([A-z]+):\/\/([^\/]+)(\/(.*)$|$)/.exec(url);
  740. if (match) {
  741. return {
  742. protocol: match[1],
  743. domain: match[2],
  744. path: match[4]
  745. }
  746. }
  747. return null;
  748. };
  749. /**
  750. * Normalize a url. Removes trailing slash
  751. * @param {string} url
  752. * @return {string} Returns the normalized url
  753. */
  754. exports.normalizeURL = function (url) {
  755. if (url[url.length - 1] == '/') {
  756. return url.substring(0, url.length - 1);
  757. }
  758. else {
  759. return url;
  760. }
  761. };
  762. /***/ },
  763. /* 5 */
  764. /***/ function(module, exports, __webpack_require__) {
  765. 'use strict';
  766. var babble = __webpack_require__(26);
  767. /**
  768. * Create a Babble module for an agent.
  769. * The agents _receive function is wrapped into a new handler.
  770. * Creates a Babble instance with function `ask`, `tell`, `listen`, `listenOnce`
  771. * @param {Agent} agent
  772. * @param {Object} [options] Optional parameters. Not applicable for BabbleModule
  773. * @constructor
  774. */
  775. function BabbleModule(agent, options) {
  776. // create a new babbler
  777. var babbler = babble.babbler(agent.id);
  778. babbler.connect({
  779. connect: function (params) {},
  780. disconnect: function(token) {},
  781. send: function (to, message) {
  782. agent.send(to, message);
  783. }
  784. });
  785. this.babbler = babbler;
  786. // create a receive function for the agent
  787. var receiveOriginal = agent._receive;
  788. this._receive = function (from, message) {
  789. babbler._receive(message);
  790. // TODO: only propagate to receiveOriginal if the message is not handled by the babbler
  791. return receiveOriginal.call(agent, from, message);
  792. };
  793. }
  794. BabbleModule.prototype.type = 'babble';
  795. /**
  796. * Get a map with mixin functions
  797. * @return {{_receive: function, ask: function, tell: function, listen: function, listenOnce: function}}
  798. * Returns mixin function, which can be used to extend the agent.
  799. */
  800. BabbleModule.prototype.mixin = function () {
  801. var babbler = this.babbler;
  802. return {
  803. _receive: this._receive,
  804. ask: babbler.ask.bind(babbler),
  805. tell: babbler.tell.bind(babbler),
  806. listen: babbler.listen.bind(babbler),
  807. listenOnce: babbler.listenOnce.bind(babbler)
  808. }
  809. };
  810. module.exports = BabbleModule;
  811. /***/ },
  812. /* 6 */
  813. /***/ function(module, exports, __webpack_require__) {
  814. 'use strict';
  815. /**
  816. * Create a pattern listener onto an Agent.
  817. * A new handler is added to the agents _receiver function.
  818. * Creates a Pattern instance with functions `listen` and `unlisten`.
  819. * @param {Agent} agent
  820. * @param {Object} [options] Optional parameters. Can contain properties:
  821. * - stopPropagation: boolean
  822. * When false (default), a message
  823. * will be delivered at all
  824. * matching pattern listeners.
  825. * When true, a message will be
  826. * be delivered at the first
  827. * matching pattern listener only.
  828. */
  829. function PatternModule(agent, options) {
  830. this.agent = agent;
  831. this.stopPropagation = options && options.stopPropagation || false;
  832. this.receiveOriginal = agent._receive;
  833. this.listeners = [];
  834. }
  835. PatternModule.prototype.type = 'pattern';
  836. /**
  837. * Receive a message.
  838. * All pattern listeners will be checked against their patterns, and if there
  839. * is a match, the pattern listeners callback function is invoked.
  840. * @param {string} from Id of sender
  841. * @param {*} message Received message, a JSON object (often a string)
  842. */
  843. PatternModule.prototype.receive = function(from, message) {
  844. var response;
  845. var responses = [];
  846. for (var i = 0, ii = this.listeners.length; i < ii; i++) {
  847. var listener = this.listeners[i];
  848. var pattern = listener.pattern;
  849. var match = (pattern instanceof Function && pattern(message)) ||
  850. (pattern instanceof RegExp && pattern.test(message)) ||
  851. (pattern == message);
  852. if (match) {
  853. response = listener.callback.call(this.agent, from, message);
  854. responses.push(response);
  855. if (this.stopPropagation) {
  856. return responses[0];
  857. }
  858. }
  859. }
  860. response = this.receiveOriginal.call(this.agent, from, message);
  861. responses.push(response);
  862. return responses[0];
  863. };
  864. /**
  865. * Add a pattern listener for incoming messages
  866. * @param {string | RegExp | Function} pattern Message pattern
  867. * @param {Function} callback Callback function invoked when
  868. * a message matching the pattern
  869. * is received.
  870. * Invoked as callback(from, message)
  871. */
  872. PatternModule.prototype.listen = function(pattern, callback) {
  873. this.listeners.push({
  874. pattern: pattern,
  875. callback: callback
  876. });
  877. };
  878. /**
  879. * Remove a pattern listener for incoming messages
  880. * @param {string | RegExp | Function} pattern Message pattern
  881. * @param {Function} callback
  882. */
  883. PatternModule.prototype.unlisten = function(pattern, callback) {
  884. for (var i = 0, ii = this.listeners.length; i < ii; i++) {
  885. var listener = this.listeners[i];
  886. if (listener.pattern === pattern && listener.callback === callback) {
  887. this.listeners.splice(i, 1);
  888. break;
  889. }
  890. }
  891. };
  892. /**
  893. * Get a map with mixin functions
  894. * @return {{_receive: function, listen: function, unlisten: function}}
  895. * Returns mixin function, which can be used to extend the agent.
  896. */
  897. PatternModule.prototype.mixin = function () {
  898. return {
  899. _receive: this.receive.bind(this),
  900. listen: this.listen.bind(this),
  901. unlisten: this.unlisten.bind(this)
  902. }
  903. };
  904. module.exports = PatternModule;
  905. /***/ },
  906. /* 7 */
  907. /***/ function(module, exports, __webpack_require__) {
  908. 'use strict';
  909. var uuid = __webpack_require__(28);
  910. var Promise = __webpack_require__(27);
  911. var util = __webpack_require__(4);
  912. var TIMEOUT = 60000; // ms
  913. /**
  914. * Create a Request module.
  915. * The module attaches a handler to the agents _receive function.
  916. * Creates a Request instance with function `request`.
  917. * @param {Agent} agent
  918. * @param {Object} [options] Optional parameters. Can contain properties:
  919. * - timeout: number A timeout for responses in
  920. * milliseconds. 60000 ms by
  921. * default.
  922. */
  923. function RequestModule(agent, options) {
  924. this.agent = agent;
  925. this.receiveOriginal = agent._receive;
  926. this.timeout = options && options.timeout || TIMEOUT;
  927. this.queue = [];
  928. }
  929. RequestModule.prototype.type = 'request';
  930. /**
  931. * Event handler, handles incoming messages
  932. * @param {String} from Id of the sender
  933. * @param {*} message
  934. * @return {boolean} Returns true when a message is handled, else returns false
  935. */
  936. RequestModule.prototype.receive = function (from, message) {
  937. var agent = this.agent;
  938. if (typeof message === 'object') {
  939. var envelope = message;
  940. // match the request from the id in the response
  941. var request = this.queue[envelope.id];
  942. if (request) {
  943. // remove the request from the queue
  944. clearTimeout(request.timeout);
  945. delete this.queue[envelope.id];
  946. // resolve the requests promise with the response message
  947. if (envelope.error) {
  948. // TODO: turn this into an Error instance again
  949. request.reject(new Error(envelope.error));
  950. }
  951. else {
  952. request.resolve(envelope.message);
  953. }
  954. return true;
  955. }
  956. else if (message.type == 'request') {
  957. try {
  958. var response = this.receiveOriginal.call(agent, from, message.message);
  959. if (util.isPromise(response)) {
  960. // wait until the promise resolves
  961. response
  962. .then(function (result) {
  963. agent.send(from, {type: 'request', id: message.id, message: result});
  964. })
  965. .catch(function (err) {
  966. agent.send(from, {type: 'request', id: message.id, error: err.message || err.toString()});
  967. });
  968. }
  969. else {
  970. // immediately send a result
  971. agent.send(from, {type: 'request', id: message.id, message: response });
  972. }
  973. }
  974. catch (err) {
  975. agent.send(from, {type: 'request', id: message.id, error: err.message || err.toString()});
  976. }
  977. }
  978. }
  979. else {
  980. if (this.receiveOriginal) {
  981. this.receiveOriginal.call(agent, from, message);
  982. }
  983. }
  984. };
  985. /**
  986. * Send a request
  987. * @param {string} to Id of the recipient
  988. * @param {*} message
  989. * @returns {Promise.<*, Error>} Returns a promise resolving with the response message
  990. */
  991. RequestModule.prototype.request = function (to, message) {
  992. var me = this;
  993. return new Promise(function (resolve, reject) {
  994. // put the data in an envelope with id
  995. var id = uuid();
  996. var envelope = {
  997. type: 'request',
  998. id: id,
  999. message: message
  1000. };
  1001. // add the request to the list with requests in progress
  1002. me.queue[id] = {
  1003. resolve: resolve,
  1004. reject: reject,
  1005. timeout: setTimeout(function () {
  1006. delete me.queue[id];
  1007. reject(new Error('Timeout'));
  1008. }, me.timeout)
  1009. };
  1010. me.agent.send(to, envelope)
  1011. .catch(function (err) {
  1012. reject(err);
  1013. });
  1014. });
  1015. };
  1016. /**
  1017. * Get a map with mixin functions
  1018. * @return {{_receive: function, request: function}}
  1019. * Returns mixin function, which can be used to extend the agent.
  1020. */
  1021. RequestModule.prototype.mixin = function () {
  1022. return {
  1023. _receive: this.receive.bind(this),
  1024. request: this.request.bind(this)
  1025. }
  1026. };
  1027. module.exports = RequestModule;
  1028. /***/ },
  1029. /* 8 */
  1030. /***/ function(module, exports, __webpack_require__) {
  1031. 'use strict';
  1032. var uuid = __webpack_require__(28);
  1033. var Promise = __webpack_require__(27);
  1034. var util = __webpack_require__(4);
  1035. /**
  1036. *
  1037. * @param {Agent} agent
  1038. * @param {Object} availableFunctions
  1039. * @constructor
  1040. */
  1041. function RPCModule(agent, availableFunctions, options) {
  1042. this.agent = agent;
  1043. this.receiveOriginal = agent._receive;
  1044. this.queue = {};
  1045. this.promiseTimeout = options && options.timeout || 1500; // 1 second
  1046. // check the available functions
  1047. if (availableFunctions instanceof Array) {
  1048. this.functionsFromArray(availableFunctions);
  1049. }
  1050. else if (availableFunctions instanceof Object) {
  1051. this.availableFunctions = availableFunctions;
  1052. }
  1053. else {
  1054. console.log('cannot use RPC with the supplied functions', availableFunctions);
  1055. }
  1056. }
  1057. RPCModule.prototype.type = 'rpc';
  1058. /**
  1059. *
  1060. * @param availableFunctions
  1061. */
  1062. RPCModule.prototype.functionsFromArray = function (availableFunctions) {
  1063. this.availableFunctions = {};
  1064. for (var i = 0; i < availableFunctions.length; i++) {
  1065. var fn = availableFunctions[i];
  1066. this.availableFunctions[fn] = this.agent[fn];
  1067. }
  1068. };
  1069. /**
  1070. *
  1071. * @param to
  1072. * @param message
  1073. * @returns {Promise}
  1074. */
  1075. RPCModule.prototype.request = function (to, message) {
  1076. var me = this;
  1077. return new Promise(function (resolve, reject) {
  1078. // prepare the envelope
  1079. if (typeof message != 'object' ) {reject(new TypeError('Message must be an object'));}
  1080. if (message.jsonrpc !== '2.0' ) {message.jsonrpc = '2.0';}
  1081. if (message.id === undefined) {message.id = uuid();}
  1082. if (message.method === undefined) {reject(new Error('Property "method" expected'));}
  1083. if (message.params === undefined) {message.params = {};}
  1084. // add the request to the list with requests in progress
  1085. me.queue[message.id] = {
  1086. resolve: resolve,
  1087. reject: reject,
  1088. timeout: setTimeout(function () {
  1089. delete me.queue[message.id];
  1090. reject(new Error('RPC Promise Timeout surpassed. Timeout: ' + me.promiseTimeout / 1000 + 's'));
  1091. }, me.promiseTimeout)
  1092. };
  1093. var sendRequest = me.agent.send(to, message);
  1094. if (util.isPromise(sendRequest) == true) {
  1095. sendRequest.catch(function (err) {reject(err);});
  1096. }
  1097. });
  1098. };
  1099. /**
  1100. *
  1101. * @param from
  1102. * @param message
  1103. * @returns {*}
  1104. */
  1105. RPCModule.prototype.receive = function (from, message) {
  1106. if (typeof message == 'object') {
  1107. if (message.jsonrpc == '2.0') {
  1108. this._receive(from, message);
  1109. }
  1110. else {
  1111. this.receiveOriginal.call(this.agent, from, message);
  1112. }
  1113. }
  1114. else {
  1115. this.receiveOriginal.call(this.agent, from, message);
  1116. }
  1117. };
  1118. /**
  1119. *
  1120. * @param from
  1121. * @param message
  1122. * @returns {*}
  1123. * @private
  1124. */
  1125. RPCModule.prototype._receive = function (from, message) {
  1126. // define structure of return message
  1127. var returnMessage = {jsonrpc:'2.0', id:message.id};
  1128. // check if this is a request
  1129. if (message.method !== undefined) {
  1130. // check is method is available for this agent
  1131. var method = this.availableFunctions[message.method];
  1132. if (method !== undefined) {
  1133. var response = method.call(this.agent, message.params, from) || null;
  1134. // check if response is a promise
  1135. if (util.isPromise(response)) {
  1136. var me = this;
  1137. response
  1138. .then(function (result) {
  1139. returnMessage.result = result;
  1140. me.agent.send(from, returnMessage)
  1141. })
  1142. .catch(function (error) {
  1143. returnMessage.error = error.message || error.toString();
  1144. me.agent.send(from, returnMessage);
  1145. })
  1146. }
  1147. else {
  1148. returnMessage.result = response;
  1149. this.agent.send(from, returnMessage);
  1150. }
  1151. }
  1152. else {
  1153. var error = new Error('Cannot find function: ' + message.method);
  1154. returnMessage.error = error.message || error.toString();
  1155. this.agent.send(from, returnMessage);
  1156. }
  1157. }
  1158. // check if this is a response
  1159. else if (message.result !== undefined || message.error !== undefined) {
  1160. var request = this.queue[message.id];
  1161. if (request !== undefined) {
  1162. // if an error is defined, reject promise
  1163. if (message.error != undefined) { // null or undefined
  1164. if (typeof message == 'object') {
  1165. request.reject(message.error);
  1166. }
  1167. else {
  1168. request.reject(new Error(message.error));
  1169. }
  1170. }
  1171. else {
  1172. request.resolve(message.result);
  1173. }
  1174. }
  1175. }
  1176. else {
  1177. // send error back to sender.
  1178. var error = new Error('No method or result defined. Message:' + JSON.stringify(message));
  1179. returnMessage.error = error.message || error.toString();
  1180. // FIXME: returned error should be an object {code: number, message: string}
  1181. this.agent.send(from, returnMessage);
  1182. }
  1183. };
  1184. /**
  1185. * Get a map with mixin functions
  1186. * @return {{_receive: function, request: function}}
  1187. * Returns mixin function, which can be used to extend the agent.
  1188. */
  1189. RPCModule.prototype.mixin = function () {
  1190. return {
  1191. _receive: this.receive.bind(this),
  1192. request: this.request.bind(this)
  1193. }
  1194. };
  1195. module.exports = RPCModule;
  1196. /***/ },
  1197. /* 9 */
  1198. /***/ function(module, exports, __webpack_require__) {
  1199. 'use strict';
  1200. /**
  1201. * Abstract prototype of a transport
  1202. * @param {Object} [config]
  1203. * @constructor
  1204. */
  1205. function Transport(config) {
  1206. this.id = config && config.id || null;
  1207. this['default'] = config && config['default'] || false;
  1208. }
  1209. Transport.prototype.type = null;
  1210. /**
  1211. * Connect an agent
  1212. * @param {String} id
  1213. * @param {Function} receive Invoked as receive(from, message)
  1214. * @return {Connection} Returns a connection
  1215. */
  1216. Transport.prototype.connect = function(id, receive) {
  1217. throw new Error('Cannot invoke abstract function "connect"');
  1218. };
  1219. /**
  1220. * Close the transport
  1221. */
  1222. Transport.prototype.close = function() {
  1223. throw new Error('Cannot invoke abstract function "close"');
  1224. };
  1225. module.exports = Transport;
  1226. /***/ },
  1227. /* 10 */
  1228. /***/ function(module, exports, __webpack_require__) {
  1229. 'use strict';
  1230. var Promise = __webpack_require__(27);
  1231. /**
  1232. * An abstract Transport connection
  1233. * @param {Transport} transport
  1234. * @param {string} id
  1235. * @param {function} receive
  1236. * @constructor
  1237. * @abstract
  1238. */
  1239. function Connection (transport, id, receive) {
  1240. throw new Error('Cannot create an abstract Connection');
  1241. }
  1242. Connection.prototype.ready = Promise.reject(new Error('Cannot get abstract property ready'));
  1243. /**
  1244. * Send a message to an agent.
  1245. * @param {string} to
  1246. * @param {*} message
  1247. * @return {Promise} returns a promise which resolves when the message has been sent
  1248. */
  1249. Connection.prototype.send = function (to, message) {
  1250. throw new Error('Cannot call abstract function send');
  1251. };
  1252. /**
  1253. * Close the connection, disconnect from the transport.
  1254. */
  1255. Connection.prototype.close = function () {
  1256. throw new Error('Cannot call abstract function "close"');
  1257. };
  1258. module.exports = Connection;
  1259. /***/ },
  1260. /* 11 */
  1261. /***/ function(module, exports, __webpack_require__) {
  1262. 'use strict';
  1263. var Promise = __webpack_require__(27);
  1264. var Transport = __webpack_require__(9);
  1265. var AMQPConnection = __webpack_require__(12);
  1266. /**
  1267. * Use AMQP as transport
  1268. * @param {Object} config Config can contain the following properties:
  1269. * - `id: string`
  1270. * - `url: string`
  1271. * - `host: string`
  1272. * The config must contain either `url` or `host`.
  1273. * For example: {url: 'amqp://localhost'} or
  1274. * {host: 'dev.rabbitmq.com'}
  1275. * @constructor
  1276. */
  1277. function AMQPTransport(config) {
  1278. this.id = config.id || null;
  1279. this.networkId = config.url || config.host || null;
  1280. this['default'] = config['default'] || false;
  1281. this.config = config;
  1282. this.connection = null;
  1283. this.exchange = null;
  1284. this.subscriptions = [];
  1285. }
  1286. AMQPTransport.prototype = new Transport();
  1287. AMQPTransport.prototype.type = 'amqp';
  1288. /**
  1289. * Connect an agent
  1290. * @param {String} id
  1291. * @param {Function} receive Invoked as receive(from, message)
  1292. * @return {AMQPConnection} Returns a connection.
  1293. */
  1294. AMQPTransport.prototype.connect = function(id, receive) {
  1295. return new AMQPConnection(this, id, receive);
  1296. };
  1297. /**
  1298. * Get an AMQP connection. If there is not yet a connection, a connection will
  1299. * be made.
  1300. * @param {Function} callback Invoked as callback(connection)
  1301. * @private
  1302. */
  1303. AMQPTransport.prototype._getConnection = function(callback) {
  1304. var me = this;
  1305. if (this.connection) {
  1306. // connection is available
  1307. callback(this.connection);
  1308. }
  1309. else {
  1310. if (this._onConnected) {
  1311. // connection is being opened but not yet ready
  1312. this._onConnected.push(callback);
  1313. }
  1314. else {
  1315. // no connection, create one
  1316. this._onConnected = [callback];
  1317. var amqp = __webpack_require__(23); // lazy load the amqp library
  1318. var connection = amqp.createConnection(this.config);
  1319. connection.on('ready', function () {
  1320. var exchange = connection.exchange('', {confirm: true}, function () {
  1321. var _onConnected = me._onConnected;
  1322. delete me._onConnected;
  1323. me.connection = connection;
  1324. me.exchange = exchange;
  1325. _onConnected.forEach(function (callback) {
  1326. callback(me.connection);
  1327. });
  1328. });
  1329. });
  1330. }
  1331. }
  1332. };
  1333. /**
  1334. * Open a connection
  1335. * @param {string} id
  1336. * @param {Function} receive Invoked as receive(from, message)
  1337. */
  1338. AMQPTransport.prototype._connect = function(id, receive) {
  1339. var me = this;
  1340. return new Promise(function (resolve, reject) {
  1341. function subscribe(connection) {
  1342. var queue = connection.queue(id, {}, function() {
  1343. queue
  1344. .subscribe(function(message) {
  1345. var body = message.body;
  1346. receive(body.from, body.message);
  1347. })
  1348. .addCallback(function (ok) {
  1349. // register this subscription
  1350. me.subscriptions.push({
  1351. id: id,
  1352. consumerTag: ok.consumerTag
  1353. });
  1354. resolve(me);
  1355. });
  1356. });
  1357. }
  1358. me._getConnection(subscribe);
  1359. });
  1360. };
  1361. /**
  1362. * Close a connection an agent by its id
  1363. * @param {String} id
  1364. */
  1365. AMQPTransport.prototype._close = function(id) {
  1366. var i = 0;
  1367. while (i < this.subscriptions.length) {
  1368. var subscription = this.subscriptions[i];
  1369. if (subscription.id == id) {
  1370. // remove this entry
  1371. this.subscriptions.splice(i, 1);
  1372. }
  1373. else {
  1374. i++;
  1375. }
  1376. }
  1377. if (this.subscriptions.length == 0) {
  1378. // fully disconnect if there are no subscribers left
  1379. this.exchange.destroy();
  1380. this.connection.disconnect();
  1381. this.connection = null;
  1382. this.exchange = null;
  1383. }
  1384. };
  1385. /**
  1386. * Close the transport.
  1387. */
  1388. AMQPTransport.prototype.close = function() {
  1389. this.connection.destroy();
  1390. this.connection = null;
  1391. };
  1392. module.exports = AMQPTransport;
  1393. /***/ },
  1394. /* 12 */
  1395. /***/ function(module, exports, __webpack_require__) {
  1396. 'use strict';
  1397. var Promise = __webpack_require__(27);
  1398. var Connection = __webpack_require__(10);
  1399. /**
  1400. * A local connection.
  1401. * @param {AMQPTransport} transport
  1402. * @param {string | number} id
  1403. * @param {function} receive
  1404. * @constructor
  1405. */
  1406. function AMQPConnection(transport, id, receive) {
  1407. this.transport = transport;
  1408. this.id = id;
  1409. // ready state
  1410. this.ready = this.transport._connect(id, receive);
  1411. }
  1412. /**
  1413. * Send a message to an agent.
  1414. * @param {string} to
  1415. * @param {*} message
  1416. * @return {Promise} returns a promise which resolves when the message has been sent
  1417. */
  1418. AMQPConnection.prototype.send = function (to, message) {
  1419. var me = this;
  1420. return new Promise(function (resolve, reject) {
  1421. var msg = {
  1422. body: {
  1423. from: me.id,
  1424. to: to,
  1425. message: message
  1426. }
  1427. };
  1428. var options = {
  1429. //immediate: true
  1430. };
  1431. me.transport.exchange.publish(to, msg, options, function () {
  1432. // FIXME: callback is not called. See https://github.com/postwait/node-amqp#exchangepublishroutingkey-message-options-callback
  1433. //console.log('sent', arguments)
  1434. });
  1435. resolve();
  1436. });
  1437. };
  1438. /**
  1439. * Close the connection
  1440. */
  1441. AMQPConnection.prototype.close = function () {
  1442. this.transport._close(this.id);
  1443. };
  1444. module.exports = AMQPConnection;
  1445. /***/ },
  1446. /* 13 */
  1447. /***/ function(module, exports, __webpack_require__) {
  1448. 'use strict';
  1449. var distribus = __webpack_require__(29);
  1450. var Transport = __webpack_require__(9);
  1451. var DistribusConnection = __webpack_require__(14);
  1452. /**
  1453. * Use distribus as transport
  1454. * @param {Object} config Config can contain the following properties:
  1455. * - `id: string`. Optional
  1456. * - `host: distribus.Host`. Optional
  1457. * If `host` is not provided,
  1458. * a new local distribus Host is created.
  1459. * @constructor
  1460. */
  1461. function DistribusTransport(config) {
  1462. this.id = config && config.id || null;
  1463. this['default'] = config && config['default'] || false;
  1464. this.host = config && config.host || new distribus.Host(config);
  1465. this.networkId = this.host.networkId; // FIXME: networkId can change when host connects to another host.
  1466. }
  1467. DistribusTransport.prototype = new Transport();
  1468. DistribusTransport.prototype.type = 'distribus';
  1469. /**
  1470. * Connect an agent
  1471. * @param {String} id
  1472. * @param {Function} receive Invoked as receive(from, message)
  1473. * @return {DistribusConnection} Returns a connection.
  1474. */
  1475. DistribusTransport.prototype.connect = function(id, receive) {
  1476. return new DistribusConnection(this, id, receive);
  1477. };
  1478. /**
  1479. * Close the transport.
  1480. */
  1481. DistribusTransport.prototype.close = function() {
  1482. this.host.close();
  1483. this.host = null;
  1484. };
  1485. module.exports = DistribusTransport;
  1486. /***/ },
  1487. /* 14 */
  1488. /***/ function(module, exports, __webpack_require__) {
  1489. 'use strict';
  1490. var Promise = __webpack_require__(27);
  1491. var Connection = __webpack_require__(10);
  1492. /**
  1493. * A local connection.
  1494. * @param {DistribusTransport} transport
  1495. * @param {string | number} id
  1496. * @param {function} receive
  1497. * @constructor
  1498. */
  1499. function DistribusConnection(transport, id, receive) {
  1500. this.transport = transport;
  1501. this.id = id;
  1502. // create a peer
  1503. var peer = this.transport.host.create(id);
  1504. peer.on('message', receive);
  1505. // ready state
  1506. this.ready = Promise.resolve(this);
  1507. }
  1508. /**
  1509. * Send a message to an agent.
  1510. * @param {string} to
  1511. * @param {*} message
  1512. * @return {Promise} returns a promise which resolves when the message has been sent
  1513. */
  1514. DistribusConnection.prototype.send = function (to, message) {
  1515. return this.transport.host.send(this.id, to, message);
  1516. };
  1517. /**
  1518. * Close the connection
  1519. */
  1520. DistribusConnection.prototype.close = function () {
  1521. this.transport.host.remove(this.id);
  1522. };
  1523. module.exports = DistribusConnection;
  1524. /***/ },
  1525. /* 15 */
  1526. /***/ function(module, exports, __webpack_require__) {
  1527. 'use strict';
  1528. var http = __webpack_require__(30);
  1529. var Promise = __webpack_require__(27);
  1530. var Transport = __webpack_require__(9);
  1531. var HTTPConnection = __webpack_require__(16);
  1532. var uuid = __webpack_require__(28);
  1533. /**
  1534. * HTTP Transport layer:
  1535. *
  1536. * Supported Options:
  1537. *
  1538. * {Number} config.port Port to listen on.
  1539. * {String} config.path Path, with or without leading and trailing slash (/)
  1540. * {Boolean} config.localShortcut If the agentId exists locally, use local transport. (local)
  1541. *
  1542. * Address: http://127.0.0.1:PORTNUMBER/PATH
  1543. */
  1544. function HTTPTransport(config) {
  1545. this.id = config && config.id || null;
  1546. this.networkId = null;
  1547. this.agents = {};
  1548. this.outstandingRequests = {}; // these are received messages that are expecting a response
  1549. this.outstandingMessages = {};
  1550. this.url = config && config.url || "http://127.0.0.1:3000/agents/:id";
  1551. this.remoteUrl = config && config.remoteUrl;
  1552. this.localShortcut = (config && config.localShortcut === false) ? false : true;
  1553. this.httpTimeout = config && config.httpTimeout || 2000; // 1 second - timeout to send message
  1554. this.httpResponseTimeout = config && config.httpResponseTimeout || 200; // 0.5 second - timeout to expect reply after delivering request
  1555. this.regexHosts = /[http]{4}s?:\/\/([a-z\-\.A-Z0-9]*):?([0-9]*)(\/[a-z\/:A-Z0-9._\-% \\\(\)\*\+\.\^\$]*)/;
  1556. this.urlHostData = this.regexHosts.exec(this.url);
  1557. this.regexPath = this.getRegEx(this.urlHostData[3]);
  1558. this.port = config && config.port || this.urlHostData[2] || 3000;
  1559. this.path = this.urlHostData[3].replace(':id', '');
  1560. if (typeof window !== 'undefined') {
  1561. this.send = this.webSend;
  1562. }
  1563. }
  1564. HTTPTransport.prototype = new Transport();
  1565. HTTPTransport.prototype.type = 'http';
  1566. HTTPTransport.prototype.getRegEx = function(url) {
  1567. return new RegExp(url.replace(/[\\\(\)\*\+\.\^\$]/g,function(match) {return '\\' + match;}).replace(':id','([:a-zA-Z_0-9\-]*)'));
  1568. };
  1569. /**
  1570. * Connect an agent
  1571. * @param {String} id
  1572. * @param {Function} receive Invoked as receive(from, message)
  1573. * @return {HTTPConnection} Returns a connection.
  1574. */
  1575. HTTPTransport.prototype.connect = function(id, receive) {
  1576. if (this.server === undefined && typeof window === 'undefined') {
  1577. this.initiateServer();
  1578. }
  1579. this.outstandingRequests[id] = {};
  1580. this.outstandingMessages[id] = {};
  1581. return new HTTPConnection(this, id, receive);
  1582. };
  1583. /**
  1584. * Send a message to an agent
  1585. * @param {String} from Id of sender
  1586. * @param {String} to Id of addressed peer
  1587. * @param {String} message
  1588. */
  1589. HTTPTransport.prototype.send = function(from, to, message) {
  1590. var me = this;
  1591. return new Promise(function (resolve,reject) {
  1592. var hostData = me.regexHosts.exec(to);
  1593. var fromRegexpCheck = me.regexPath.exec(from);
  1594. var fromAgentId = fromRegexpCheck[1];
  1595. var outstandingMessageID = uuid();
  1596. // check for local shortcut possibility
  1597. if (me.localShortcut == true) {
  1598. var toRegexpCheck = me.regexPath.exec(to);
  1599. var toAgentId = toRegexpCheck[1];
  1600. var toPath = hostData[3].replace(toAgentId,"");
  1601. // check if the "to" address is on the same URL, port and path as the "from"
  1602. if ((hostData[1] == '127.0.0.1' && hostData[2] == me.urlHostData[2] && toPath == me.path) ||
  1603. (me.urlHostData[1] == hostData[1] && hostData[2] == me.urlHostData[2] && toPath == me.path)) {
  1604. // by definition true but check anyway
  1605. if (me.agents[toAgentId] !== undefined) {
  1606. me.agents[toAgentId](fromAgentId, message);
  1607. resolve();
  1608. return;
  1609. }
  1610. }
  1611. }
  1612. // stringify the message. If the message is an object, it can have an ID so it may be part of a req/rep.
  1613. if (typeof message == 'object') {
  1614. // check if the send is a reply to an outstanding request and if so, deliver
  1615. var outstanding = me.outstandingRequests[fromAgentId];
  1616. if (outstanding[message.id] !== undefined) {
  1617. var callback = outstanding[message.id];
  1618. callback.response.end(JSON.stringify(message));
  1619. clearTimeout(callback.timeout);
  1620. delete outstanding[message.id];
  1621. resolve();
  1622. return;
  1623. }
  1624. // stringify the message.
  1625. message = JSON.stringify(message)
  1626. }
  1627. // all post options
  1628. var options = {
  1629. host: hostData[1],
  1630. port: hostData[2],
  1631. path: hostData[3],
  1632. method: 'POST',
  1633. headers: {
  1634. 'x-eve-senderurl' : from, // used to get senderID
  1635. 'Content-type' : 'text/plain'
  1636. }
  1637. };
  1638. var request = http.request(options, function(res) {
  1639. res.setEncoding('utf8');
  1640. // message was delivered, clear the cannot deliver timeout.
  1641. clearTimeout(me.outstandingMessages[fromAgentId][outstandingMessageID].timeout);
  1642. // listen to incoming data
  1643. res.on('data', function (response) {
  1644. var parsedResponse;
  1645. try {parsedResponse = JSON.parse(response);} catch (err) {parsedResponse = response;}
  1646. if (typeof parsedResponse == 'object') {
  1647. if (parsedResponse.__httpError__ !== undefined) {
  1648. reject(new Error(parsedResponse.__httpError__));
  1649. return;
  1650. }
  1651. }
  1652. me.agents[fromAgentId](to, parsedResponse);
  1653. resolve();
  1654. });
  1655. });
  1656. me.outstandingMessages[fromAgentId][outstandingMessageID] = {
  1657. timeout: setTimeout(function () {
  1658. request.abort();
  1659. reject(new Error("Cannot connect to " + to))
  1660. }, me.httpTimeout),
  1661. reject: reject
  1662. };
  1663. request.on('error', function(e) {
  1664. reject(e);
  1665. });
  1666. // write data to request body
  1667. request.write(message);
  1668. request.end();
  1669. });
  1670. };
  1671. /**
  1672. * Send a request to an url. Only for web.
  1673. * @param {String} from Id of sender
  1674. * @param {String} to Id of addressed peer
  1675. * @param {String} message
  1676. */
  1677. HTTPTransport.prototype.webSend = function(from, to, message) {
  1678. var me = this;
  1679. return new Promise(function (resolve, reject) {
  1680. if (typeof message == 'object') {
  1681. message = JSON.stringify(message);
  1682. }
  1683. var fromRegexpCheck = me.regexPath.exec(from);
  1684. var fromAgentId = fromRegexpCheck[1];
  1685. // create XMLHttpRequest object to send the POST request
  1686. var http = new XMLHttpRequest();
  1687. // insert the callback function. This is called when the message has been delivered and a response has been received
  1688. http.onreadystatechange = function () {
  1689. if (http.readyState == 4 && http.status == 200) {
  1690. var response = "";
  1691. if (http.responseText.length > 0) {
  1692. response = JSON.parse(http.responseText);
  1693. }
  1694. me.agents[fromAgentId](to, response);
  1695. // launch callback function
  1696. resolve();
  1697. }
  1698. else if (http.readyState == 4) {
  1699. reject(new Error("http.status:" + http.status));
  1700. }
  1701. };
  1702. // open an asynchronous POST connection
  1703. http.open("POST", to, true);
  1704. // include header so the receiving code knows its a JSON object
  1705. http.setRequestHeader("Content-Type", "text/plain");
  1706. // send
  1707. http.send(message);
  1708. });
  1709. };
  1710. /**
  1711. * This is the HTTP equivalent of receiveMessage.
  1712. *
  1713. * @param request
  1714. * @param response
  1715. */
  1716. HTTPTransport.prototype.processRequest = function(request, response) {
  1717. var url = request.url;
  1718. // define headers
  1719. var headers = {};
  1720. headers['Access-Control-Allow-Origin'] = '*';
  1721. headers['Access-Control-Allow-Credentials'] = true;
  1722. headers['Content-Type'] = 'text/plain';
  1723. var regexpCheck = this.regexPath.exec(url);
  1724. if (regexpCheck !== null) {
  1725. var agentId = regexpCheck[1];
  1726. var senderId = 'unknown';
  1727. if (request.headers['x-eve-senderurl'] !== undefined) {
  1728. senderId = request.headers['x-eve-senderurl'];
  1729. }
  1730. var body = '';
  1731. request.on('data', function (data) {
  1732. body += data;
  1733. if (body.length > 30e6) { // 30e6 == 30MB
  1734. request.connection.destroy(); // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
  1735. }
  1736. });
  1737. var me = this;
  1738. request.on('end', function () {
  1739. var expectReply = false;
  1740. var message;
  1741. try {message = JSON.parse(body);} catch (err) {message = body;}
  1742. // check if JSON RPC
  1743. expectReply = message.jsonrpc && message.jsonrpc == '2.0' || expectReply;
  1744. // check if type == 'request'
  1745. expectReply = message.type && message.type == 'request' || expectReply;
  1746. response.writeHead(200, headers);
  1747. // construct callback
  1748. var callback = me.agents[agentId];
  1749. if (callback === undefined) {
  1750. var error = new Error('Agent: "' + agentId + '" does not exist.');
  1751. response.end(JSON.stringify({__httpError__:error.message || error.toString()}));
  1752. }
  1753. else {
  1754. if (expectReply == true) {
  1755. me.outstandingRequests[agentId][message.id] = {
  1756. response: response,
  1757. timeout: setTimeout(function () {
  1758. response.end("timeout");
  1759. delete me.outstandingRequests[agentId][message.id];
  1760. }, me.httpResponseTimeout)
  1761. };
  1762. callback(senderId, message);
  1763. }
  1764. else {
  1765. // if we're not expecting a response, we first close the connection, then receive the message
  1766. response.end('');
  1767. if (callback !== undefined) {
  1768. callback(senderId, message);
  1769. }
  1770. }
  1771. }
  1772. });
  1773. }
  1774. };
  1775. /**
  1776. * Configure a HTTP server listener
  1777. */
  1778. HTTPTransport.prototype.initiateServer = function() {
  1779. if (this.server === undefined) {
  1780. var me = this;
  1781. this.server = http.createServer(function (request, response) {
  1782. if (request.method == 'OPTIONS') {
  1783. var headers = {};
  1784. headers['Access-Control-Allow-Origin'] = '*';
  1785. headers['Access-Control-Allow-Methods'] = 'POST, OPTIONS';
  1786. headers['Access-Control-Allow-Credentials'] = true;
  1787. headers['Access-Control-Max-Age'] = '86400'; // 24 hours
  1788. headers['Access-Control-Allow-Headers'] = 'X-Requested-With, Access-Control-Allow-Origin, X-HTTP-Method-Override, Content-Type, Authorization, Accept';
  1789. // respond to the request
  1790. response.writeHead(200, headers);
  1791. response.end();
  1792. }
  1793. else if (request.method == 'POST') {
  1794. me.processRequest(request, response);
  1795. }
  1796. });
  1797. this.server.on('error', function(err) {
  1798. if (err.code == 'EADDRINUSE') {
  1799. throw new Error('ERROR: Could not start HTTP server. Port ' + me.port + ' is occupied.');
  1800. }
  1801. else {
  1802. throw new Error(err);
  1803. }
  1804. });
  1805. // Listen on port (default: 3000), IP defaults to 127.0.0.1
  1806. this.server.listen(this.port, function() {
  1807. // Put a friendly message on the terminal
  1808. console.log('Server listening at ', me.url);
  1809. });
  1810. }
  1811. else {
  1812. this.server.close();
  1813. this.server = undefined;
  1814. this.initiateServer();
  1815. }
  1816. };
  1817. /**
  1818. * Close the HTTP server
  1819. */
  1820. HTTPTransport.prototype.close = function() {
  1821. // close all open connections
  1822. for (var agentId in this.outstandingRequests) {
  1823. if (this.outstandingRequests.hasOwnProperty(agentId)) {
  1824. var agentRequests = this.outstandingRequests[agentId];
  1825. for (var messageId in agentRequests) {
  1826. if (agentRequests.hasOwnProperty(messageId)) {
  1827. var openMessage = agentRequests[messageId];
  1828. var error = new Error('Server shutting down.');
  1829. openMessage.response.end(JSON.stringify({__httpError__:error.message || error.toString()}));
  1830. }
  1831. }
  1832. }
  1833. }
  1834. // close server
  1835. if (this.server) {
  1836. this.server.close();
  1837. }
  1838. this.server = null;
  1839. };
  1840. module.exports = HTTPTransport;
  1841. /***/ },
  1842. /* 16 */
  1843. /***/ function(module, exports, __webpack_require__) {
  1844. 'use strict';
  1845. var Promise = __webpack_require__(27);
  1846. var Connection = __webpack_require__(10);
  1847. /**
  1848. * A HTTP connection.
  1849. * @param {HTTPTransport} transport
  1850. * @param {string | number} id
  1851. * @param {function} receive
  1852. * @constructor
  1853. */
  1854. function HTTPConnection(transport, id, receive) {
  1855. this.transport = transport;
  1856. this.id = id;
  1857. // register the agents receive function
  1858. if (this.id in this.transport.agents) {
  1859. throw new Error('Agent with id ' + id + ' already exists');
  1860. }
  1861. this.transport.agents[this.id] = receive;
  1862. // ready state
  1863. this.ready = Promise.resolve(this);
  1864. }
  1865. /**
  1866. * Send a message to an agent.
  1867. * @param {string} to
  1868. * @param {*} message
  1869. */
  1870. HTTPConnection.prototype.send = function (to, message) {
  1871. var fromURL = this.transport.url.replace(':id', this.id);
  1872. var isURL = to.indexOf('://') !== -1;
  1873. var toURL;
  1874. if (isURL) {
  1875. toURL = to;
  1876. }
  1877. else {
  1878. if (this.transport.remoteUrl !== undefined) {
  1879. toURL = this.transport.remoteUrl.replace(':id', to);
  1880. }
  1881. else {
  1882. console.log('ERROR: no remote URL specified. Cannot send over HTTP.', to);
  1883. }
  1884. }
  1885. return this.transport.send(fromURL, toURL, message);
  1886. };
  1887. /**
  1888. * Close the connection
  1889. */
  1890. HTTPConnection.prototype.close = function () {
  1891. delete this.transport.agents[this.id];
  1892. };
  1893. module.exports = HTTPConnection;
  1894. /***/ },
  1895. /* 17 */
  1896. /***/ function(module, exports, __webpack_require__) {
  1897. 'use strict';
  1898. var Transport = __webpack_require__(9);
  1899. var LocalConnection = __webpack_require__(18);
  1900. /**
  1901. * Create a local transport.
  1902. * @param {Object} config Config can contain the following properties:
  1903. * - `id: string`. Optional
  1904. * @constructor
  1905. */
  1906. function LocalTransport(config) {
  1907. this.id = config && config.id || null;
  1908. this.networkId = this.id || null;
  1909. this['default'] = config && config['default'] || false;
  1910. this.agents = {};
  1911. }
  1912. LocalTransport.prototype = new Transport();
  1913. LocalTransport.prototype.type = 'local';
  1914. /**
  1915. * Connect an agent
  1916. * @param {String} id
  1917. * @param {Function} receive Invoked as receive(from, message)
  1918. * @return {LocalConnection} Returns a promise which resolves when
  1919. * connected.
  1920. */
  1921. LocalTransport.prototype.connect = function(id, receive) {
  1922. return new LocalConnection(this, id, receive);
  1923. };
  1924. /**
  1925. * Close the transport. Removes all agent connections.
  1926. */
  1927. LocalTransport.prototype.close = function() {
  1928. this.agents = {};
  1929. };
  1930. module.exports = LocalTransport;
  1931. /***/ },
  1932. /* 18 */
  1933. /***/ function(module, exports, __webpack_require__) {
  1934. 'use strict';
  1935. var Promise = __webpack_require__(27);
  1936. var Connection = __webpack_require__(10);
  1937. /**
  1938. * A local connection.
  1939. * @param {LocalTransport} transport
  1940. * @param {string | number} id
  1941. * @param {function} receive
  1942. * @constructor
  1943. */
  1944. function LocalConnection(transport, id, receive) {
  1945. this.transport = transport;
  1946. this.id = id;
  1947. // register the agents receive function
  1948. if (this.id in this.transport.agents) {
  1949. throw new Error('Agent with id ' + id + ' already exists');
  1950. }
  1951. this.transport.agents[this.id] = receive;
  1952. // ready state
  1953. this.ready = Promise.resolve(this);
  1954. }
  1955. /**
  1956. * Send a message to an agent.
  1957. * @param {string} to
  1958. * @param {*} message
  1959. * @return {Promise} returns a promise which resolves when the message has been sent
  1960. */
  1961. LocalConnection.prototype.send = function (to, message) {
  1962. var callback = this.transport.agents[to];
  1963. if (!callback) {
  1964. return Promise.reject(new Error('Agent with id ' + to + ' not found'));
  1965. }
  1966. // invoke the agents receiver as callback(from, message)
  1967. callback(this.id, message);
  1968. return Promise.resolve();
  1969. };
  1970. /**
  1971. * Close the connection
  1972. */
  1973. LocalConnection.prototype.close = function () {
  1974. delete this.transport.agents[this.id];
  1975. };
  1976. module.exports = LocalConnection;
  1977. /***/ },
  1978. /* 19 */
  1979. /***/ function(module, exports, __webpack_require__) {
  1980. 'use strict';
  1981. var Transport = __webpack_require__(9);
  1982. var PubNubConnection = __webpack_require__(20);
  1983. /**
  1984. * Use pubnub as transport
  1985. * @param {Object} config Config can contain the following properties:
  1986. * - `id: string`. Optional
  1987. * - `publish_key: string`. Required
  1988. * - `subscribe_key: string`. Required
  1989. * @constructor
  1990. */
  1991. function PubNubTransport(config) {
  1992. this.id = config.id || null;
  1993. this.networkId = config.publish_key || null;
  1994. this['default'] = config['default'] || false;
  1995. this.pubnub = PUBNUB().init(config);
  1996. }
  1997. PubNubTransport.prototype = new Transport();
  1998. PubNubTransport.prototype.type = 'pubnub';
  1999. /**
  2000. * Connect an agent
  2001. * @param {String} id
  2002. * @param {Function} receive Invoked as receive(from, message)
  2003. * @return {PubNubConnection} Returns a connection
  2004. */
  2005. PubNubTransport.prototype.connect = function(id, receive) {
  2006. return new PubNubConnection(this, id, receive)
  2007. };
  2008. /**
  2009. * Close the transport.
  2010. */
  2011. PubNubTransport.prototype.close = function() {
  2012. // FIXME: how to correctly close a pubnub connection?
  2013. this.pubnub = null;
  2014. };
  2015. /**
  2016. * Load the PubNub library
  2017. * @returns {Object} PUBNUB
  2018. */
  2019. function PUBNUB() {
  2020. if (typeof window !== 'undefined') {
  2021. // browser
  2022. if (typeof window['PUBNUB'] === 'undefined') {
  2023. throw new Error('Please load pubnub first in the browser');
  2024. }
  2025. return window['PUBNUB'];
  2026. }
  2027. else {
  2028. // node.js
  2029. return __webpack_require__(32);
  2030. }
  2031. }
  2032. module.exports = PubNubTransport;
  2033. /***/ },
  2034. /* 20 */
  2035. /***/ function(module, exports, __webpack_require__) {
  2036. 'use strict';
  2037. var Promise = __webpack_require__(27);
  2038. var Connection = __webpack_require__(10);
  2039. /**
  2040. * A connection. The connection is ready when the property .ready resolves.
  2041. * @param {PubNubTransport} transport
  2042. * @param {string | number} id
  2043. * @param {function} receive
  2044. * @constructor
  2045. */
  2046. function PubNubConnection(transport, id, receive) {
  2047. this.id = id;
  2048. this.transport = transport;
  2049. // ready state
  2050. var me = this;
  2051. this.ready = new Promise(function (resolve, reject) {
  2052. transport.pubnub.subscribe({
  2053. channel: id,
  2054. message: function (message) {
  2055. receive(message.from, message.message);
  2056. },
  2057. connect: function () {
  2058. resolve(me);
  2059. }
  2060. });
  2061. });
  2062. }
  2063. /**
  2064. * Send a message to an agent.
  2065. * @param {string} to
  2066. * @param {*} message
  2067. * @return {Promise} returns a promise which resolves when the message has been sent
  2068. */
  2069. PubNubConnection.prototype.send = function (to, message) {
  2070. var me = this;
  2071. return new Promise(function (resolve, reject) {
  2072. me.transport.pubnub.publish({
  2073. channel: to,
  2074. message: {
  2075. from: me.id,
  2076. to: to,
  2077. message: message
  2078. },
  2079. callback: resolve,
  2080. error: reject
  2081. });
  2082. });
  2083. };
  2084. /**
  2085. * Close the connection
  2086. */
  2087. PubNubConnection.prototype.close = function () {
  2088. this.transport.pubnub.unsubscribe({
  2089. channel: this.id
  2090. });
  2091. };
  2092. module.exports = PubNubConnection;
  2093. /***/ },
  2094. /* 21 */
  2095. /***/ function(module, exports, __webpack_require__) {
  2096. 'use strict';
  2097. var urlModule = __webpack_require__(31);
  2098. var uuid = __webpack_require__(28);
  2099. var Promise = __webpack_require__(27);
  2100. var WebSocketServer = __webpack_require__(34).Server;
  2101. var util = __webpack_require__(4);
  2102. var Transport = __webpack_require__(9);
  2103. var WebSocketConnection = __webpack_require__(22);
  2104. /**
  2105. * Create a web socket transport.
  2106. * @param {Object} config Config can contain the following properties:
  2107. * - `id: string`. Optional
  2108. * - `default: boolean`. Optional
  2109. * - `url: string`. Optional. If provided,
  2110. * A WebSocket server is started on given
  2111. * url.
  2112. * - `localShortcut: boolean`. Optional. If true
  2113. * (default), messages to local agents are not
  2114. * send via WebSocket but delivered immediately
  2115. * - `reconnectDelay: number` Optional. Delay in
  2116. * milliseconds for reconnecting a broken
  2117. * connection. 10000 ms by default. Connections
  2118. * are only automatically reconnected after
  2119. * there has been an established connection.
  2120. * @constructor
  2121. */
  2122. function WebSocketTransport(config) {
  2123. this.id = config && config.id || null;
  2124. this.networkId = this.id || null;
  2125. this['default'] = config && config['default'] || false;
  2126. this.localShortcut = (config && config.localShortcut === false) ? false : true;
  2127. this.reconnectDelay = config && config.reconnectDelay || 10000;
  2128. this.httpTransport = config && config.httpTransport;
  2129. this.url = config && config.url || null;
  2130. this.server = null;
  2131. if (this.url != null) {
  2132. var urlParts = urlModule.parse(this.url);
  2133. if (urlParts.protocol != 'ws:') throw new Error('Invalid protocol, "ws:" expected');
  2134. if (this.url.indexOf(':id') == -1) throw new Error('":id" placeholder missing in url');
  2135. this.address = urlParts.protocol + '//' + urlParts.host; // the url without path, for example 'ws://localhost:3000'
  2136. this.ready = this._initServer(this.url);
  2137. }
  2138. else {
  2139. this.address = null;
  2140. this.ready = Promise.resolve(this);
  2141. }
  2142. this.agents = {}; // WebSocketConnections of all registered agents. The keys are the urls of the agents
  2143. }
  2144. WebSocketTransport.prototype = new Transport();
  2145. WebSocketTransport.prototype.type = 'ws';
  2146. /**
  2147. * Build an url for given id. Example:
  2148. * var url = getUrl('agent1'); // 'ws://localhost:3000/agents/agent1'
  2149. * @param {String} id
  2150. * @return {String} Returns the url, or returns null when no url placeholder
  2151. * is defined.
  2152. */
  2153. WebSocketTransport.prototype.getUrl = function (id) {
  2154. return this.url ? this.url.replace(':id', id) : null;
  2155. };
  2156. /**
  2157. * Initialize a server on given url
  2158. * @param {String} url For example 'http://localhost:3000'
  2159. * @return {Promise} Returns a promise which resolves when the server is up
  2160. * and running
  2161. * @private
  2162. */
  2163. WebSocketTransport.prototype._initServer = function (url) {
  2164. var urlParts = urlModule.parse(url);
  2165. var port = urlParts.port || 80;
  2166. var me = this;
  2167. return new Promise(function (resolve, reject) {
  2168. if (me.httpTransport !== undefined) {
  2169. console.log("WEBSOCKETS: using available server.");
  2170. me.server = new WebSocketServer({server: me.httpTransport.server}, function () {
  2171. resolve(me);
  2172. });
  2173. }
  2174. else {
  2175. me.server = new WebSocketServer({port: port}, function () {
  2176. resolve(me);
  2177. });
  2178. }
  2179. me.server.on('connection', me._onConnection.bind(me));
  2180. me.server.on('error', function (err) {
  2181. reject(err)
  2182. });
  2183. })
  2184. };
  2185. /**
  2186. * Handle a new connection. The connection is added to the addressed agent.
  2187. * @param {WebSocket} conn
  2188. * @private
  2189. */
  2190. WebSocketTransport.prototype._onConnection = function (conn) {
  2191. var url = conn.upgradeReq.url;
  2192. var urlParts = urlModule.parse(url, true);
  2193. var toPath = urlParts.pathname;
  2194. var to = util.normalizeURL(this.address + toPath);
  2195. // read sender id from query parameters or generate a random uuid
  2196. var queryParams = urlParts.query;
  2197. var from = queryParams.id || uuid();
  2198. // TODO: make a config option to allow/disallow anonymous connections?
  2199. //console.log('onConnection, to=', to, ', from=', from, ', agents:', Object.keys(this.agents)); // TODO: cleanup
  2200. var agent = this.agents[to];
  2201. if (agent) {
  2202. agent._onConnection(from, conn);
  2203. }
  2204. else {
  2205. // reject the connection
  2206. // conn.send('Error: Agent with id "' + to + '" not found'); // TODO: can we send back a message before closing?
  2207. conn.close();
  2208. }
  2209. };
  2210. /**
  2211. * Connect an agent
  2212. * @param {string} id The id or url of the agent. In case of an
  2213. * url, this url should match the url of the
  2214. * WebSocket server.
  2215. * @param {Function} receive Invoked as receive(from, message)
  2216. * @return {WebSocketConnection} Returns a promise which resolves when
  2217. * connected.
  2218. */
  2219. WebSocketTransport.prototype.connect = function(id, receive) {
  2220. var isURL = (id.indexOf('://') !== -1);
  2221. // FIXME: it's confusing right now what the final url will be based on the provided id...
  2222. var url = isURL ? id : (this.getUrl(id) || id);
  2223. if (url) url = util.normalizeURL(url);
  2224. // register the agents receive function
  2225. if (this.agents[url]) {
  2226. throw new Error('Agent with id ' + this.id + ' already exists');
  2227. }
  2228. var conn = new WebSocketConnection(this, url, receive);
  2229. this.agents[conn.url] = conn; // use conn.url, url can be changed when it was null
  2230. return conn;
  2231. };
  2232. /**
  2233. * Close the transport. Removes all agent connections.
  2234. */
  2235. WebSocketTransport.prototype.close = function() {
  2236. // close all connections
  2237. for (var id in this.agents) {
  2238. if (this.agents.hasOwnProperty(id)) {
  2239. this.agents[id].close();
  2240. }
  2241. }
  2242. this.agents = {};
  2243. // close the server
  2244. if (this.server) {
  2245. this.server.close();
  2246. }
  2247. };
  2248. module.exports = WebSocketTransport;
  2249. /***/ },
  2250. /* 22 */
  2251. /***/ function(module, exports, __webpack_require__) {
  2252. 'use strict';
  2253. var uuid = __webpack_require__(28);
  2254. var Promise = __webpack_require__(27);
  2255. var WebSocket = (typeof window !== 'undefined' && typeof window.WebSocket !== 'undefined') ?
  2256. window.WebSocket :
  2257. __webpack_require__(34);
  2258. var util = __webpack_require__(4);
  2259. var Connection = __webpack_require__(10);
  2260. /**
  2261. * A websocket connection.
  2262. * @param {WebSocketTransport} transport
  2263. * @param {string | number | null} url The url of the agent. The url must match
  2264. * the url of the WebSocket server.
  2265. * If url is null, a UUID id is generated as url.
  2266. * @param {function} receive
  2267. * @constructor
  2268. */
  2269. function WebSocketConnection(transport, url, receive) {
  2270. this.transport = transport;
  2271. this.url = url ? util.normalizeURL(url) : uuid();
  2272. this.receive = receive;
  2273. this.sockets = {};
  2274. this.closed = false;
  2275. this.reconnectTimers = {};
  2276. // ready state
  2277. this.ready = Promise.resolve(this);
  2278. }
  2279. /**
  2280. * Send a message to an agent.
  2281. * @param {string} to The WebSocket url of the receiver
  2282. * @param {*} message
  2283. * @return {Promise} Returns a promise which resolves when the message is sent,
  2284. * and rejects when sending the message failed
  2285. */
  2286. WebSocketConnection.prototype.send = function (to, message) {
  2287. //console.log('send', this.url, to, message); // TODO: cleanup
  2288. // deliver locally when possible
  2289. if (this.transport.localShortcut) {
  2290. var agent = this.transport.agents[to];
  2291. if (agent) {
  2292. try {
  2293. agent.receive(this.url, message);
  2294. return Promise.resolve();
  2295. }
  2296. catch (err) {
  2297. return Promise.reject(err);
  2298. }
  2299. }
  2300. }
  2301. // get or create a connection
  2302. var conn = this.sockets[to];
  2303. if (conn) {
  2304. try {
  2305. if (conn.readyState == conn.CONNECTING) {
  2306. // the connection is still opening
  2307. return new Promise(function (resolve, reject) {
  2308. //console.log(conn.onopen)//, conn.onopen.callback)
  2309. conn.onopen.callbacks.push(function () {
  2310. conn.send(JSON.stringify(message));
  2311. resolve();
  2312. })
  2313. });
  2314. }
  2315. else if (conn.readyState == conn.OPEN) {
  2316. conn.send(JSON.stringify(message));
  2317. return Promise.resolve();
  2318. }
  2319. else {
  2320. // remove the connection
  2321. conn = null;
  2322. }
  2323. }
  2324. catch (err) {
  2325. return Promise.reject(err);
  2326. }
  2327. }
  2328. if (!conn) {
  2329. // try to open a connection
  2330. var me = this;
  2331. return new Promise(function (resolve, reject) {
  2332. me._connect(to, function (conn) {
  2333. conn.send(JSON.stringify(message));
  2334. resolve();
  2335. }, function (err) {
  2336. reject(new Error('Failed to connect to agent "' + to + '"'));
  2337. });
  2338. })
  2339. }
  2340. };
  2341. /**
  2342. * Open a websocket connection to an other agent. No messages are sent.
  2343. * @param {string} to Url of the remote agent.
  2344. * @returns {Promise.<WebSocketConnection, Error>}
  2345. * Returns a promise which resolves when the connection is
  2346. * established and rejects in case of an error.
  2347. */
  2348. WebSocketConnection.prototype.connect = function (to) {
  2349. var me = this;
  2350. return new Promise(function (resolve, reject) {
  2351. me._connect(to, function () {
  2352. resolve(me);
  2353. }, reject);
  2354. });
  2355. };
  2356. /**
  2357. * Open a websocket connection
  2358. * @param {String} to Url of the remote agent
  2359. * @param {function} [callback]
  2360. * @param {function} [errback]
  2361. * @param {boolean} [doReconnect=false]
  2362. * @returns {WebSocket}
  2363. * @private
  2364. */
  2365. WebSocketConnection.prototype._connect = function (to, callback, errback, doReconnect) {
  2366. var me = this;
  2367. var conn = new WebSocket(to + '?id=' + this.url);
  2368. // register the new socket
  2369. me.sockets[to] = conn;
  2370. conn.onopen = function () {
  2371. // Change doReconnect to true as soon as we have had an open connection
  2372. doReconnect = true;
  2373. conn.onopen.callbacks.forEach(function (cb) {
  2374. cb(conn);
  2375. });
  2376. conn.onopen.callbacks = [];
  2377. };
  2378. conn.onopen.callbacks = callback ? [callback] : [];
  2379. conn.onmessage = function (event) {
  2380. me.receive(to, JSON.parse(event.data));
  2381. };
  2382. conn.onclose = function () {
  2383. delete me.sockets[to];
  2384. if (doReconnect) {
  2385. me._reconnect(to);
  2386. }
  2387. };
  2388. conn.onerror = function (err) {
  2389. delete me.sockets[to];
  2390. if (errback) {
  2391. errback(err);
  2392. }
  2393. };
  2394. return conn;
  2395. };
  2396. /**
  2397. * Auto reconnect a broken connection
  2398. * @param {String} to Url of the remote agent
  2399. * @private
  2400. */
  2401. WebSocketConnection.prototype._reconnect = function (to) {
  2402. var me = this;
  2403. var doReconnect = true;
  2404. if (me.closed == false && me.reconnectTimers[to] == null) {
  2405. me.reconnectTimers[to] = setTimeout(function () {
  2406. delete me.reconnectTimers[to];
  2407. me._connect(to, null, null, doReconnect);
  2408. }, me.transport.reconnectDelay);
  2409. }
  2410. };
  2411. /**
  2412. * Register a websocket connection
  2413. * @param {String} from Url of the remote agent
  2414. * @param {WebSocket} conn WebSocket connection
  2415. * @returns {WebSocket} Returns the websocket itself
  2416. * @private
  2417. */
  2418. WebSocketConnection.prototype._onConnection = function (from, conn) {
  2419. var me = this;
  2420. conn.onmessage = function (event) {
  2421. me.receive(from, JSON.parse(event.data));
  2422. };
  2423. conn.onclose = function () {
  2424. // remove this connection from the sockets list
  2425. delete me.sockets[from];
  2426. };
  2427. conn.onerror = function (err) {
  2428. // TODO: what to do with errors?
  2429. delete me.sockets[from];
  2430. };
  2431. if (this.sockets[from]) {
  2432. // there is already a connection open with remote agent
  2433. // TODO: what to do with overwriting existing sockets?
  2434. this.sockets[from].close();
  2435. }
  2436. // register new connection
  2437. this.sockets[from] = conn;
  2438. return conn;
  2439. };
  2440. /**
  2441. * Get a list with all open sockets
  2442. * @return {String[]} Returns all open sockets
  2443. */
  2444. WebSocketConnection.prototype.list = function () {
  2445. return Object.keys(this.sockets);
  2446. };
  2447. /**
  2448. * Close the connection. All open sockets will be closed and the agent will
  2449. * be unregistered from the WebSocketTransport.
  2450. */
  2451. WebSocketConnection.prototype.close = function () {
  2452. this.closed = true;
  2453. // close all connections
  2454. for (var id in this.sockets) {
  2455. if (this.sockets.hasOwnProperty(id)) {
  2456. this.sockets[id].close();
  2457. }
  2458. }
  2459. this.sockets = {};
  2460. delete this.transport.agents[this.url];
  2461. };
  2462. module.exports = WebSocketConnection;
  2463. /***/ },
  2464. /* 23 */
  2465. /***/ function(module, exports, __webpack_require__) {
  2466. module.exports = __WEBPACK_EXTERNAL_MODULE_23__;
  2467. /***/ },
  2468. /* 24 */
  2469. /***/ function(module, exports, __webpack_require__) {
  2470. module.exports = __webpack_require__(33);
  2471. /***/ },
  2472. /* 25 */
  2473. /***/ function(module, exports, __webpack_require__) {
  2474. /* WEBPACK VAR INJECTION */(function(global) {'use strict';
  2475. var width = 256;// each RC4 output is 0 <= x < 256
  2476. var chunks = 6;// at least six RC4 outputs for each double
  2477. var digits = 52;// there are 52 significant digits in a double
  2478. var pool = [];// pool: entropy pool starts empty
  2479. var GLOBAL = typeof global === 'undefined' ? window : global;
  2480. //
  2481. // The following constants are related to IEEE 754 limits.
  2482. //
  2483. var startdenom = Math.pow(width, chunks),
  2484. significance = Math.pow(2, digits),
  2485. overflow = significance * 2,
  2486. mask = width - 1;
  2487. var oldRandom = Math.random;
  2488. //
  2489. // seedrandom()
  2490. // This is the seedrandom function described above.
  2491. //
  2492. module.exports = function(seed, options) {
  2493. if (options && options.global === true) {
  2494. options.global = false;
  2495. Math.random = module.exports(seed, options);
  2496. options.global = true;
  2497. return Math.random;
  2498. }
  2499. var use_entropy = (options && options.entropy) || false;
  2500. var key = [];
  2501. // Flatten the seed string or build one from local entropy if needed.
  2502. var shortseed = mixkey(flatten(
  2503. use_entropy ? [seed, tostring(pool)] :
  2504. 0 in arguments ? seed : autoseed(), 3), key);
  2505. // Use the seed to initialize an ARC4 generator.
  2506. var arc4 = new ARC4(key);
  2507. // Mix the randomness into accumulated entropy.
  2508. mixkey(tostring(arc4.S), pool);
  2509. // Override Math.random
  2510. // This function returns a random double in [0, 1) that contains
  2511. // randomness in every bit of the mantissa of the IEEE 754 value.
  2512. return function() { // Closure to return a random double:
  2513. var n = arc4.g(chunks), // Start with a numerator n < 2 ^ 48
  2514. d = startdenom, // and denominator d = 2 ^ 48.
  2515. x = 0; // and no 'extra last byte'.
  2516. while (n < significance) { // Fill up all significant digits by
  2517. n = (n + x) * width; // shifting numerator and
  2518. d *= width; // denominator and generating a
  2519. x = arc4.g(1); // new least-significant-byte.
  2520. }
  2521. while (n >= overflow) { // To avoid rounding up, before adding
  2522. n /= 2; // last byte, shift everything
  2523. d /= 2; // right using integer Math until
  2524. x >>>= 1; // we have exactly the desired bits.
  2525. }
  2526. return (n + x) / d; // Form the number within [0, 1).
  2527. };
  2528. };
  2529. module.exports.resetGlobal = function () {
  2530. Math.random = oldRandom;
  2531. };
  2532. //
  2533. // ARC4
  2534. //
  2535. // An ARC4 implementation. The constructor takes a key in the form of
  2536. // an array of at most (width) integers that should be 0 <= x < (width).
  2537. //
  2538. // The g(count) method returns a pseudorandom integer that concatenates
  2539. // the next (count) outputs from ARC4. Its return value is a number x
  2540. // that is in the range 0 <= x < (width ^ count).
  2541. //
  2542. /** @constructor */
  2543. function ARC4(key) {
  2544. var t, keylen = key.length,
  2545. me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];
  2546. // The empty key [] is treated as [0].
  2547. if (!keylen) { key = [keylen++]; }
  2548. // Set up S using the standard key scheduling algorithm.
  2549. while (i < width) {
  2550. s[i] = i++;
  2551. }
  2552. for (i = 0; i < width; i++) {
  2553. s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))];
  2554. s[j] = t;
  2555. }
  2556. // The "g" method returns the next (count) outputs as one number.
  2557. (me.g = function(count) {
  2558. // Using instance members instead of closure state nearly doubles speed.
  2559. var t, r = 0,
  2560. i = me.i, j = me.j, s = me.S;
  2561. while (count--) {
  2562. t = s[i = mask & (i + 1)];
  2563. r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))];
  2564. }
  2565. me.i = i; me.j = j;
  2566. return r;
  2567. // For robust unpredictability discard an initial batch of values.
  2568. // See http://www.rsa.com/rsalabs/node.asp?id=2009
  2569. })(width);
  2570. }
  2571. //
  2572. // flatten()
  2573. // Converts an object tree to nested arrays of strings.
  2574. //
  2575. function flatten(obj, depth) {
  2576. var result = [], typ = (typeof obj)[0], prop;
  2577. if (depth && typ == 'o') {
  2578. for (prop in obj) {
  2579. try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}
  2580. }
  2581. }
  2582. return (result.length ? result : typ == 's' ? obj : obj + '\0');
  2583. }
  2584. //
  2585. // mixkey()
  2586. // Mixes a string seed into a key that is an array of integers, and
  2587. // returns a shortened string seed that is equivalent to the result key.
  2588. //
  2589. function mixkey(seed, key) {
  2590. var stringseed = seed + '', smear, j = 0;
  2591. while (j < stringseed.length) {
  2592. key[mask & j] =
  2593. mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++));
  2594. }
  2595. return tostring(key);
  2596. }
  2597. //
  2598. // autoseed()
  2599. // Returns an object for autoseeding, using window.crypto if available.
  2600. //
  2601. /** @param {Uint8Array=} seed */
  2602. function autoseed(seed) {
  2603. try {
  2604. GLOBAL.crypto.getRandomValues(seed = new Uint8Array(width));
  2605. return tostring(seed);
  2606. } catch (e) {
  2607. return [+new Date, GLOBAL, GLOBAL.navigator && GLOBAL.navigator.plugins,
  2608. GLOBAL.screen, tostring(pool)];
  2609. }
  2610. }
  2611. //
  2612. // tostring()
  2613. // Converts an array of charcodes to a string
  2614. //
  2615. function tostring(a) {
  2616. return String.fromCharCode.apply(0, a);
  2617. }
  2618. //
  2619. // When seedrandom.js is loaded, we immediately mix a few bits
  2620. // from the built-in RNG into the entropy pool. Because we do
  2621. // not want to intefere with determinstic PRNG state later,
  2622. // seedrandom will not call Math.random on its own again after
  2623. // initialization.
  2624. //
  2625. mixkey(Math.random(), pool);
  2626. /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
  2627. /***/ },
  2628. /* 26 */
  2629. /***/ function(module, exports, __webpack_require__) {
  2630. 'use strict';
  2631. module.exports = __webpack_require__(39);
  2632. /***/ },
  2633. /* 27 */
  2634. /***/ function(module, exports, __webpack_require__) {
  2635. 'use strict';
  2636. module.exports = __webpack_require__(35)
  2637. __webpack_require__(36)
  2638. __webpack_require__(37)
  2639. __webpack_require__(38)
  2640. /***/ },
  2641. /* 28 */
  2642. /***/ function(module, exports, __webpack_require__) {
  2643. exports = module.exports = function() {
  2644. var ret = '', value;
  2645. for (var i = 0; i < 32; i++) {
  2646. value = exports.random() * 16 | 0;
  2647. // Insert the hypens
  2648. if (i > 4 && i < 21 && ! (i % 4)) {
  2649. ret += '-';
  2650. }
  2651. // Add the next random character
  2652. ret += (
  2653. (i === 12) ? 4 : (
  2654. (i === 16) ? (value & 3 | 8) : value
  2655. )
  2656. ).toString(16);
  2657. }
  2658. return ret;
  2659. };
  2660. var uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
  2661. exports.isUUID = function(uuid) {
  2662. return uuidRegex.test(uuid);
  2663. };
  2664. exports.random = function() {
  2665. return Math.random();
  2666. };
  2667. /***/ },
  2668. /* 29 */
  2669. /***/ function(module, exports, __webpack_require__) {
  2670. exports.Host = __webpack_require__(40);
  2671. exports.Promise = __webpack_require__(41);
  2672. /***/ },
  2673. /* 30 */
  2674. /***/ function(module, exports, __webpack_require__) {
  2675. var http = module.exports;
  2676. var EventEmitter = __webpack_require__(44).EventEmitter;
  2677. var Request = __webpack_require__(42);
  2678. var url = __webpack_require__(31)
  2679. http.request = function (params, cb) {
  2680. if (typeof params === 'string') {
  2681. params = url.parse(params)
  2682. }
  2683. if (!params) params = {};
  2684. if (!params.host && !params.port) {
  2685. params.port = parseInt(window.location.port, 10);
  2686. }
  2687. if (!params.host && params.hostname) {
  2688. params.host = params.hostname;
  2689. }
  2690. if (!params.protocol) {
  2691. if (params.scheme) {
  2692. params.protocol = params.scheme + ':';
  2693. } else {
  2694. params.protocol = window.location.protocol;
  2695. }
  2696. }
  2697. if (!params.host) {
  2698. params.host = window.location.hostname || window.location.host;
  2699. }
  2700. if (/:/.test(params.host)) {
  2701. if (!params.port) {
  2702. params.port = params.host.split(':')[1];
  2703. }
  2704. params.host = params.host.split(':')[0];
  2705. }
  2706. if (!params.port) params.port = params.protocol == 'https:' ? 443 : 80;
  2707. var req = new Request(new xhrHttp, params);
  2708. if (cb) req.on('response', cb);
  2709. return req;
  2710. };
  2711. http.get = function (params, cb) {
  2712. params.method = 'GET';
  2713. var req = http.request(params, cb);
  2714. req.end();
  2715. return req;
  2716. };
  2717. http.Agent = function () {};
  2718. http.Agent.defaultMaxSockets = 4;
  2719. var xhrHttp = (function () {
  2720. if (typeof window === 'undefined') {
  2721. throw new Error('no window object present');
  2722. }
  2723. else if (window.XMLHttpRequest) {
  2724. return window.XMLHttpRequest;
  2725. }
  2726. else if (window.ActiveXObject) {
  2727. var axs = [
  2728. 'Msxml2.XMLHTTP.6.0',
  2729. 'Msxml2.XMLHTTP.3.0',
  2730. 'Microsoft.XMLHTTP'
  2731. ];
  2732. for (var i = 0; i < axs.length; i++) {
  2733. try {
  2734. var ax = new(window.ActiveXObject)(axs[i]);
  2735. return function () {
  2736. if (ax) {
  2737. var ax_ = ax;
  2738. ax = null;
  2739. return ax_;
  2740. }
  2741. else {
  2742. return new(window.ActiveXObject)(axs[i]);
  2743. }
  2744. };
  2745. }
  2746. catch (e) {}
  2747. }
  2748. throw new Error('ajax not supported in this browser')
  2749. }
  2750. else {
  2751. throw new Error('ajax not supported in this browser');
  2752. }
  2753. })();
  2754. http.STATUS_CODES = {
  2755. 100 : 'Continue',
  2756. 101 : 'Switching Protocols',
  2757. 102 : 'Processing', // RFC 2518, obsoleted by RFC 4918
  2758. 200 : 'OK',
  2759. 201 : 'Created',
  2760. 202 : 'Accepted',
  2761. 203 : 'Non-Authoritative Information',
  2762. 204 : 'No Content',
  2763. 205 : 'Reset Content',
  2764. 206 : 'Partial Content',
  2765. 207 : 'Multi-Status', // RFC 4918
  2766. 300 : 'Multiple Choices',
  2767. 301 : 'Moved Permanently',
  2768. 302 : 'Moved Temporarily',
  2769. 303 : 'See Other',
  2770. 304 : 'Not Modified',
  2771. 305 : 'Use Proxy',
  2772. 307 : 'Temporary Redirect',
  2773. 400 : 'Bad Request',
  2774. 401 : 'Unauthorized',
  2775. 402 : 'Payment Required',
  2776. 403 : 'Forbidden',
  2777. 404 : 'Not Found',
  2778. 405 : 'Method Not Allowed',
  2779. 406 : 'Not Acceptable',
  2780. 407 : 'Proxy Authentication Required',
  2781. 408 : 'Request Time-out',
  2782. 409 : 'Conflict',
  2783. 410 : 'Gone',
  2784. 411 : 'Length Required',
  2785. 412 : 'Precondition Failed',
  2786. 413 : 'Request Entity Too Large',
  2787. 414 : 'Request-URI Too Large',
  2788. 415 : 'Unsupported Media Type',
  2789. 416 : 'Requested Range Not Satisfiable',
  2790. 417 : 'Expectation Failed',
  2791. 418 : 'I\'m a teapot', // RFC 2324
  2792. 422 : 'Unprocessable Entity', // RFC 4918
  2793. 423 : 'Locked', // RFC 4918
  2794. 424 : 'Failed Dependency', // RFC 4918
  2795. 425 : 'Unordered Collection', // RFC 4918
  2796. 426 : 'Upgrade Required', // RFC 2817
  2797. 428 : 'Precondition Required', // RFC 6585
  2798. 429 : 'Too Many Requests', // RFC 6585
  2799. 431 : 'Request Header Fields Too Large',// RFC 6585
  2800. 500 : 'Internal Server Error',
  2801. 501 : 'Not Implemented',
  2802. 502 : 'Bad Gateway',
  2803. 503 : 'Service Unavailable',
  2804. 504 : 'Gateway Time-out',
  2805. 505 : 'HTTP Version Not Supported',
  2806. 506 : 'Variant Also Negotiates', // RFC 2295
  2807. 507 : 'Insufficient Storage', // RFC 4918
  2808. 509 : 'Bandwidth Limit Exceeded',
  2809. 510 : 'Not Extended', // RFC 2774
  2810. 511 : 'Network Authentication Required' // RFC 6585
  2811. };
  2812. /***/ },
  2813. /* 31 */
  2814. /***/ function(module, exports, __webpack_require__) {
  2815. // Copyright Joyent, Inc. and other Node contributors.
  2816. //
  2817. // Permission is hereby granted, free of charge, to any person obtaining a
  2818. // copy of this software and associated documentation files (the
  2819. // "Software"), to deal in the Software without restriction, including
  2820. // without limitation the rights to use, copy, modify, merge, publish,
  2821. // distribute, sublicense, and/or sell copies of the Software, and to permit
  2822. // persons to whom the Software is furnished to do so, subject to the
  2823. // following conditions:
  2824. //
  2825. // The above copyright notice and this permission notice shall be included
  2826. // in all copies or substantial portions of the Software.
  2827. //
  2828. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  2829. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  2830. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  2831. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  2832. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  2833. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  2834. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  2835. var punycode = __webpack_require__(54);
  2836. exports.parse = urlParse;
  2837. exports.resolve = urlResolve;
  2838. exports.resolveObject = urlResolveObject;
  2839. exports.format = urlFormat;
  2840. exports.Url = Url;
  2841. function Url() {
  2842. this.protocol = null;
  2843. this.slashes = null;
  2844. this.auth = null;
  2845. this.host = null;
  2846. this.port = null;
  2847. this.hostname = null;
  2848. this.hash = null;
  2849. this.search = null;
  2850. this.query = null;
  2851. this.pathname = null;
  2852. this.path = null;
  2853. this.href = null;
  2854. }
  2855. // Reference: RFC 3986, RFC 1808, RFC 2396
  2856. // define these here so at least they only have to be
  2857. // compiled once on the first module load.
  2858. var protocolPattern = /^([a-z0-9.+-]+:)/i,
  2859. portPattern = /:[0-9]*$/,
  2860. // RFC 2396: characters reserved for delimiting URLs.
  2861. // We actually just auto-escape these.
  2862. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
  2863. // RFC 2396: characters not allowed for various reasons.
  2864. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
  2865. // Allowed by RFCs, but cause of XSS attacks. Always escape these.
  2866. autoEscape = ['\''].concat(unwise),
  2867. // Characters that are never ever allowed in a hostname.
  2868. // Note that any invalid chars are also handled, but these
  2869. // are the ones that are *expected* to be seen, so we fast-path
  2870. // them.
  2871. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
  2872. hostEndingChars = ['/', '?', '#'],
  2873. hostnameMaxLen = 255,
  2874. hostnamePartPattern = /^[a-z0-9A-Z_-]{0,63}$/,
  2875. hostnamePartStart = /^([a-z0-9A-Z_-]{0,63})(.*)$/,
  2876. // protocols that can allow "unsafe" and "unwise" chars.
  2877. unsafeProtocol = {
  2878. 'javascript': true,
  2879. 'javascript:': true
  2880. },
  2881. // protocols that never have a hostname.
  2882. hostlessProtocol = {
  2883. 'javascript': true,
  2884. 'javascript:': true
  2885. },
  2886. // protocols that always contain a // bit.
  2887. slashedProtocol = {
  2888. 'http': true,
  2889. 'https': true,
  2890. 'ftp': true,
  2891. 'gopher': true,
  2892. 'file': true,
  2893. 'http:': true,
  2894. 'https:': true,
  2895. 'ftp:': true,
  2896. 'gopher:': true,
  2897. 'file:': true
  2898. },
  2899. querystring = __webpack_require__(45);
  2900. function urlParse(url, parseQueryString, slashesDenoteHost) {
  2901. if (url && isObject(url) && url instanceof Url) return url;
  2902. var u = new Url;
  2903. u.parse(url, parseQueryString, slashesDenoteHost);
  2904. return u;
  2905. }
  2906. Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  2907. if (!isString(url)) {
  2908. throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
  2909. }
  2910. var rest = url;
  2911. // trim before proceeding.
  2912. // This is to support parse stuff like " http://foo.com \n"
  2913. rest = rest.trim();
  2914. var proto = protocolPattern.exec(rest);
  2915. if (proto) {
  2916. proto = proto[0];
  2917. var lowerProto = proto.toLowerCase();
  2918. this.protocol = lowerProto;
  2919. rest = rest.substr(proto.length);
  2920. }
  2921. // figure out if it's got a host
  2922. // user@server is *always* interpreted as a hostname, and url
  2923. // resolution will treat //foo/bar as host=foo,path=bar because that's
  2924. // how the browser resolves relative URLs.
  2925. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
  2926. var slashes = rest.substr(0, 2) === '//';
  2927. if (slashes && !(proto && hostlessProtocol[proto])) {
  2928. rest = rest.substr(2);
  2929. this.slashes = true;
  2930. }
  2931. }
  2932. if (!hostlessProtocol[proto] &&
  2933. (slashes || (proto && !slashedProtocol[proto]))) {
  2934. // there's a hostname.
  2935. // the first instance of /, ?, ;, or # ends the host.
  2936. //
  2937. // If there is an @ in the hostname, then non-host chars *are* allowed
  2938. // to the left of the last @ sign, unless some host-ending character
  2939. // comes *before* the @-sign.
  2940. // URLs are obnoxious.
  2941. //
  2942. // ex:
  2943. // http://a@b@c/ => user:a@b host:c
  2944. // http://a@b?@c => user:a host:c path:/?@c
  2945. // v0.12 TODO(isaacs): This is not quite how Chrome does things.
  2946. // Review our test case against browsers more comprehensively.
  2947. // find the first instance of any hostEndingChars
  2948. var hostEnd = -1;
  2949. for (var i = 0; i < hostEndingChars.length; i++) {
  2950. var hec = rest.indexOf(hostEndingChars[i]);
  2951. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  2952. hostEnd = hec;
  2953. }
  2954. // at this point, either we have an explicit point where the
  2955. // auth portion cannot go past, or the last @ char is the decider.
  2956. var auth, atSign;
  2957. if (hostEnd === -1) {
  2958. // atSign can be anywhere.
  2959. atSign = rest.lastIndexOf('@');
  2960. } else {
  2961. // atSign must be in auth portion.
  2962. // http://a@b/c@d => host:b auth:a path:/c@d
  2963. atSign = rest.lastIndexOf('@', hostEnd);
  2964. }
  2965. // Now we have a portion which is definitely the auth.
  2966. // Pull that off.
  2967. if (atSign !== -1) {
  2968. auth = rest.slice(0, atSign);
  2969. rest = rest.slice(atSign + 1);
  2970. this.auth = decodeURIComponent(auth);
  2971. }
  2972. // the host is the remaining to the left of the first non-host char
  2973. hostEnd = -1;
  2974. for (var i = 0; i < nonHostChars.length; i++) {
  2975. var hec = rest.indexOf(nonHostChars[i]);
  2976. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  2977. hostEnd = hec;
  2978. }
  2979. // if we still have not hit it, then the entire thing is a host.
  2980. if (hostEnd === -1)
  2981. hostEnd = rest.length;
  2982. this.host = rest.slice(0, hostEnd);
  2983. rest = rest.slice(hostEnd);
  2984. // pull out port.
  2985. this.parseHost();
  2986. // we've indicated that there is a hostname,
  2987. // so even if it's empty, it has to be present.
  2988. this.hostname = this.hostname || '';
  2989. // if hostname begins with [ and ends with ]
  2990. // assume that it's an IPv6 address.
  2991. var ipv6Hostname = this.hostname[0] === '[' &&
  2992. this.hostname[this.hostname.length - 1] === ']';
  2993. // validate a little.
  2994. if (!ipv6Hostname) {
  2995. var hostparts = this.hostname.split(/\./);
  2996. for (var i = 0, l = hostparts.length; i < l; i++) {
  2997. var part = hostparts[i];
  2998. if (!part) continue;
  2999. if (!part.match(hostnamePartPattern)) {
  3000. var newpart = '';
  3001. for (var j = 0, k = part.length; j < k; j++) {
  3002. if (part.charCodeAt(j) > 127) {
  3003. // we replace non-ASCII char with a temporary placeholder
  3004. // we need this to make sure size of hostname is not
  3005. // broken by replacing non-ASCII by nothing
  3006. newpart += 'x';
  3007. } else {
  3008. newpart += part[j];
  3009. }
  3010. }
  3011. // we test again with ASCII char only
  3012. if (!newpart.match(hostnamePartPattern)) {
  3013. var validParts = hostparts.slice(0, i);
  3014. var notHost = hostparts.slice(i + 1);
  3015. var bit = part.match(hostnamePartStart);
  3016. if (bit) {
  3017. validParts.push(bit[1]);
  3018. notHost.unshift(bit[2]);
  3019. }
  3020. if (notHost.length) {
  3021. rest = '/' + notHost.join('.') + rest;
  3022. }
  3023. this.hostname = validParts.join('.');
  3024. break;
  3025. }
  3026. }
  3027. }
  3028. }
  3029. if (this.hostname.length > hostnameMaxLen) {
  3030. this.hostname = '';
  3031. } else {
  3032. // hostnames are always lower case.
  3033. this.hostname = this.hostname.toLowerCase();
  3034. }
  3035. if (!ipv6Hostname) {
  3036. // IDNA Support: Returns a puny coded representation of "domain".
  3037. // It only converts the part of the domain name that
  3038. // has non ASCII characters. I.e. it dosent matter if
  3039. // you call it with a domain that already is in ASCII.
  3040. var domainArray = this.hostname.split('.');
  3041. var newOut = [];
  3042. for (var i = 0; i < domainArray.length; ++i) {
  3043. var s = domainArray[i];
  3044. newOut.push(s.match(/[^A-Za-z0-9_-]/) ?
  3045. 'xn--' + punycode.encode(s) : s);
  3046. }
  3047. this.hostname = newOut.join('.');
  3048. }
  3049. var p = this.port ? ':' + this.port : '';
  3050. var h = this.hostname || '';
  3051. this.host = h + p;
  3052. this.href += this.host;
  3053. // strip [ and ] from the hostname
  3054. // the host field still retains them, though
  3055. if (ipv6Hostname) {
  3056. this.hostname = this.hostname.substr(1, this.hostname.length - 2);
  3057. if (rest[0] !== '/') {
  3058. rest = '/' + rest;
  3059. }
  3060. }
  3061. }
  3062. // now rest is set to the post-host stuff.
  3063. // chop off any delim chars.
  3064. if (!unsafeProtocol[lowerProto]) {
  3065. // First, make 100% sure that any "autoEscape" chars get
  3066. // escaped, even if encodeURIComponent doesn't think they
  3067. // need to be.
  3068. for (var i = 0, l = autoEscape.length; i < l; i++) {
  3069. var ae = autoEscape[i];
  3070. var esc = encodeURIComponent(ae);
  3071. if (esc === ae) {
  3072. esc = escape(ae);
  3073. }
  3074. rest = rest.split(ae).join(esc);
  3075. }
  3076. }
  3077. // chop off from the tail first.
  3078. var hash = rest.indexOf('#');
  3079. if (hash !== -1) {
  3080. // got a fragment string.
  3081. this.hash = rest.substr(hash);
  3082. rest = rest.slice(0, hash);
  3083. }
  3084. var qm = rest.indexOf('?');
  3085. if (qm !== -1) {
  3086. this.search = rest.substr(qm);
  3087. this.query = rest.substr(qm + 1);
  3088. if (parseQueryString) {
  3089. this.query = querystring.parse(this.query);
  3090. }
  3091. rest = rest.slice(0, qm);
  3092. } else if (parseQueryString) {
  3093. // no query string, but parseQueryString still requested
  3094. this.search = '';
  3095. this.query = {};
  3096. }
  3097. if (rest) this.pathname = rest;
  3098. if (slashedProtocol[lowerProto] &&
  3099. this.hostname && !this.pathname) {
  3100. this.pathname = '/';
  3101. }
  3102. //to support http.request
  3103. if (this.pathname || this.search) {
  3104. var p = this.pathname || '';
  3105. var s = this.search || '';
  3106. this.path = p + s;
  3107. }
  3108. // finally, reconstruct the href based on what has been validated.
  3109. this.href = this.format();
  3110. return this;
  3111. };
  3112. // format a parsed object into a url string
  3113. function urlFormat(obj) {
  3114. // ensure it's an object, and not a string url.
  3115. // If it's an obj, this is a no-op.
  3116. // this way, you can call url_format() on strings
  3117. // to clean up potentially wonky urls.
  3118. if (isString(obj)) obj = urlParse(obj);
  3119. if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
  3120. return obj.format();
  3121. }
  3122. Url.prototype.format = function() {
  3123. var auth = this.auth || '';
  3124. if (auth) {
  3125. auth = encodeURIComponent(auth);
  3126. auth = auth.replace(/%3A/i, ':');
  3127. auth += '@';
  3128. }
  3129. var protocol = this.protocol || '',
  3130. pathname = this.pathname || '',
  3131. hash = this.hash || '',
  3132. host = false,
  3133. query = '';
  3134. if (this.host) {
  3135. host = auth + this.host;
  3136. } else if (this.hostname) {
  3137. host = auth + (this.hostname.indexOf(':') === -1 ?
  3138. this.hostname :
  3139. '[' + this.hostname + ']');
  3140. if (this.port) {
  3141. host += ':' + this.port;
  3142. }
  3143. }
  3144. if (this.query &&
  3145. isObject(this.query) &&
  3146. Object.keys(this.query).length) {
  3147. query = querystring.stringify(this.query);
  3148. }
  3149. var search = this.search || (query && ('?' + query)) || '';
  3150. if (protocol && protocol.substr(-1) !== ':') protocol += ':';
  3151. // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
  3152. // unless they had them to begin with.
  3153. if (this.slashes ||
  3154. (!protocol || slashedProtocol[protocol]) && host !== false) {
  3155. host = '//' + (host || '');
  3156. if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  3157. } else if (!host) {
  3158. host = '';
  3159. }
  3160. if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  3161. if (search && search.charAt(0) !== '?') search = '?' + search;
  3162. pathname = pathname.replace(/[?#]/g, function(match) {
  3163. return encodeURIComponent(match);
  3164. });
  3165. search = search.replace('#', '%23');
  3166. return protocol + host + pathname + search + hash;
  3167. };
  3168. function urlResolve(source, relative) {
  3169. return urlParse(source, false, true).resolve(relative);
  3170. }
  3171. Url.prototype.resolve = function(relative) {
  3172. return this.resolveObject(urlParse(relative, false, true)).format();
  3173. };
  3174. function urlResolveObject(source, relative) {
  3175. if (!source) return relative;
  3176. return urlParse(source, false, true).resolveObject(relative);
  3177. }
  3178. Url.prototype.resolveObject = function(relative) {
  3179. if (isString(relative)) {
  3180. var rel = new Url();
  3181. rel.parse(relative, false, true);
  3182. relative = rel;
  3183. }
  3184. var result = new Url();
  3185. Object.keys(this).forEach(function(k) {
  3186. result[k] = this[k];
  3187. }, this);
  3188. // hash is always overridden, no matter what.
  3189. // even href="" will remove it.
  3190. result.hash = relative.hash;
  3191. // if the relative url is empty, then there's nothing left to do here.
  3192. if (relative.href === '') {
  3193. result.href = result.format();
  3194. return result;
  3195. }
  3196. // hrefs like //foo/bar always cut to the protocol.
  3197. if (relative.slashes && !relative.protocol) {
  3198. // take everything except the protocol from relative
  3199. Object.keys(relative).forEach(function(k) {
  3200. if (k !== 'protocol')
  3201. result[k] = relative[k];
  3202. });
  3203. //urlParse appends trailing / to urls like http://www.example.com
  3204. if (slashedProtocol[result.protocol] &&
  3205. result.hostname && !result.pathname) {
  3206. result.path = result.pathname = '/';
  3207. }
  3208. result.href = result.format();
  3209. return result;
  3210. }
  3211. if (relative.protocol && relative.protocol !== result.protocol) {
  3212. // if it's a known url protocol, then changing
  3213. // the protocol does weird things
  3214. // first, if it's not file:, then we MUST have a host,
  3215. // and if there was a path
  3216. // to begin with, then we MUST have a path.
  3217. // if it is file:, then the host is dropped,
  3218. // because that's known to be hostless.
  3219. // anything else is assumed to be absolute.
  3220. if (!slashedProtocol[relative.protocol]) {
  3221. Object.keys(relative).forEach(function(k) {
  3222. result[k] = relative[k];
  3223. });
  3224. result.href = result.format();
  3225. return result;
  3226. }
  3227. result.protocol = relative.protocol;
  3228. if (!relative.host && !hostlessProtocol[relative.protocol]) {
  3229. var relPath = (relative.pathname || '').split('/');
  3230. while (relPath.length && !(relative.host = relPath.shift()));
  3231. if (!relative.host) relative.host = '';
  3232. if (!relative.hostname) relative.hostname = '';
  3233. if (relPath[0] !== '') relPath.unshift('');
  3234. if (relPath.length < 2) relPath.unshift('');
  3235. result.pathname = relPath.join('/');
  3236. } else {
  3237. result.pathname = relative.pathname;
  3238. }
  3239. result.search = relative.search;
  3240. result.query = relative.query;
  3241. result.host = relative.host || '';
  3242. result.auth = relative.auth;
  3243. result.hostname = relative.hostname || relative.host;
  3244. result.port = relative.port;
  3245. // to support http.request
  3246. if (result.pathname || result.search) {
  3247. var p = result.pathname || '';
  3248. var s = result.search || '';
  3249. result.path = p + s;
  3250. }
  3251. result.slashes = result.slashes || relative.slashes;
  3252. result.href = result.format();
  3253. return result;
  3254. }
  3255. var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
  3256. isRelAbs = (
  3257. relative.host ||
  3258. relative.pathname && relative.pathname.charAt(0) === '/'
  3259. ),
  3260. mustEndAbs = (isRelAbs || isSourceAbs ||
  3261. (result.host && relative.pathname)),
  3262. removeAllDots = mustEndAbs,
  3263. srcPath = result.pathname && result.pathname.split('/') || [],
  3264. relPath = relative.pathname && relative.pathname.split('/') || [],
  3265. psychotic = result.protocol && !slashedProtocol[result.protocol];
  3266. // if the url is a non-slashed url, then relative
  3267. // links like ../.. should be able
  3268. // to crawl up to the hostname, as well. This is strange.
  3269. // result.protocol has already been set by now.
  3270. // Later on, put the first path part into the host field.
  3271. if (psychotic) {
  3272. result.hostname = '';
  3273. result.port = null;
  3274. if (result.host) {
  3275. if (srcPath[0] === '') srcPath[0] = result.host;
  3276. else srcPath.unshift(result.host);
  3277. }
  3278. result.host = '';
  3279. if (relative.protocol) {
  3280. relative.hostname = null;
  3281. relative.port = null;
  3282. if (relative.host) {
  3283. if (relPath[0] === '') relPath[0] = relative.host;
  3284. else relPath.unshift(relative.host);
  3285. }
  3286. relative.host = null;
  3287. }
  3288. mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  3289. }
  3290. if (isRelAbs) {
  3291. // it's absolute.
  3292. result.host = (relative.host || relative.host === '') ?
  3293. relative.host : result.host;
  3294. result.hostname = (relative.hostname || relative.hostname === '') ?
  3295. relative.hostname : result.hostname;
  3296. result.search = relative.search;
  3297. result.query = relative.query;
  3298. srcPath = relPath;
  3299. // fall through to the dot-handling below.
  3300. } else if (relPath.length) {
  3301. // it's relative
  3302. // throw away the existing file, and take the new path instead.
  3303. if (!srcPath) srcPath = [];
  3304. srcPath.pop();
  3305. srcPath = srcPath.concat(relPath);
  3306. result.search = relative.search;
  3307. result.query = relative.query;
  3308. } else if (!isNullOrUndefined(relative.search)) {
  3309. // just pull out the search.
  3310. // like href='?foo'.
  3311. // Put this after the other two cases because it simplifies the booleans
  3312. if (psychotic) {
  3313. result.hostname = result.host = srcPath.shift();
  3314. //occationaly the auth can get stuck only in host
  3315. //this especialy happens in cases like
  3316. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  3317. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  3318. result.host.split('@') : false;
  3319. if (authInHost) {
  3320. result.auth = authInHost.shift();
  3321. result.host = result.hostname = authInHost.shift();
  3322. }
  3323. }
  3324. result.search = relative.search;
  3325. result.query = relative.query;
  3326. //to support http.request
  3327. if (!isNull(result.pathname) || !isNull(result.search)) {
  3328. result.path = (result.pathname ? result.pathname : '') +
  3329. (result.search ? result.search : '');
  3330. }
  3331. result.href = result.format();
  3332. return result;
  3333. }
  3334. if (!srcPath.length) {
  3335. // no path at all. easy.
  3336. // we've already handled the other stuff above.
  3337. result.pathname = null;
  3338. //to support http.request
  3339. if (result.search) {
  3340. result.path = '/' + result.search;
  3341. } else {
  3342. result.path = null;
  3343. }
  3344. result.href = result.format();
  3345. return result;
  3346. }
  3347. // if a url ENDs in . or .., then it must get a trailing slash.
  3348. // however, if it ends in anything else non-slashy,
  3349. // then it must NOT get a trailing slash.
  3350. var last = srcPath.slice(-1)[0];
  3351. var hasTrailingSlash = (
  3352. (result.host || relative.host) && (last === '.' || last === '..') ||
  3353. last === '');
  3354. // strip single dots, resolve double dots to parent dir
  3355. // if the path tries to go above the root, `up` ends up > 0
  3356. var up = 0;
  3357. for (var i = srcPath.length; i >= 0; i--) {
  3358. last = srcPath[i];
  3359. if (last == '.') {
  3360. srcPath.splice(i, 1);
  3361. } else if (last === '..') {
  3362. srcPath.splice(i, 1);
  3363. up++;
  3364. } else if (up) {
  3365. srcPath.splice(i, 1);
  3366. up--;
  3367. }
  3368. }
  3369. // if the path is allowed to go above the root, restore leading ..s
  3370. if (!mustEndAbs && !removeAllDots) {
  3371. for (; up--; up) {
  3372. srcPath.unshift('..');
  3373. }
  3374. }
  3375. if (mustEndAbs && srcPath[0] !== '' &&
  3376. (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
  3377. srcPath.unshift('');
  3378. }
  3379. if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
  3380. srcPath.push('');
  3381. }
  3382. var isAbsolute = srcPath[0] === '' ||
  3383. (srcPath[0] && srcPath[0].charAt(0) === '/');
  3384. // put the host back
  3385. if (psychotic) {
  3386. result.hostname = result.host = isAbsolute ? '' :
  3387. srcPath.length ? srcPath.shift() : '';
  3388. //occationaly the auth can get stuck only in host
  3389. //this especialy happens in cases like
  3390. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  3391. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  3392. result.host.split('@') : false;
  3393. if (authInHost) {
  3394. result.auth = authInHost.shift();
  3395. result.host = result.hostname = authInHost.shift();
  3396. }
  3397. }
  3398. mustEndAbs = mustEndAbs || (result.host && srcPath.length);
  3399. if (mustEndAbs && !isAbsolute) {
  3400. srcPath.unshift('');
  3401. }
  3402. if (!srcPath.length) {
  3403. result.pathname = null;
  3404. result.path = null;
  3405. } else {
  3406. result.pathname = srcPath.join('/');
  3407. }
  3408. //to support request.http
  3409. if (!isNull(result.pathname) || !isNull(result.search)) {
  3410. result.path = (result.pathname ? result.pathname : '') +
  3411. (result.search ? result.search : '');
  3412. }
  3413. result.auth = relative.auth || result.auth;
  3414. result.slashes = result.slashes || relative.slashes;
  3415. result.href = result.format();
  3416. return result;
  3417. };
  3418. Url.prototype.parseHost = function() {
  3419. var host = this.host;
  3420. var port = portPattern.exec(host);
  3421. if (port) {
  3422. port = port[0];
  3423. if (port !== ':') {
  3424. this.port = port.substr(1);
  3425. }
  3426. host = host.substr(0, host.length - port.length);
  3427. }
  3428. if (host) this.hostname = host;
  3429. };
  3430. function isString(arg) {
  3431. return typeof arg === "string";
  3432. }
  3433. function isObject(arg) {
  3434. return typeof arg === 'object' && arg !== null;
  3435. }
  3436. function isNull(arg) {
  3437. return arg === null;
  3438. }
  3439. function isNullOrUndefined(arg) {
  3440. return arg == null;
  3441. }
  3442. /***/ },
  3443. /* 32 */
  3444. /***/ function(module, exports, __webpack_require__) {
  3445. /* WEBPACK VAR INJECTION */(function(Buffer) {// Version: 3.7.0
  3446. var NOW = 1
  3447. , READY = false
  3448. , READY_BUFFER = []
  3449. , PRESENCE_SUFFIX = '-pnpres'
  3450. , DEF_WINDOWING = 10 // MILLISECONDS.
  3451. , DEF_TIMEOUT = 10000 // MILLISECONDS.
  3452. , DEF_SUB_TIMEOUT = 310 // SECONDS.
  3453. , DEF_KEEPALIVE = 60 // SECONDS (FOR TIMESYNC).
  3454. , SECOND = 1000 // A THOUSAND MILLISECONDS.
  3455. , URLBIT = '/'
  3456. , PARAMSBIT = '&'
  3457. , PRESENCE_HB_THRESHOLD = 5
  3458. , PRESENCE_HB_DEFAULT = 30
  3459. , SDK_VER = '3.7.0'
  3460. , REPL = /{([\w\-]+)}/g;
  3461. /**
  3462. * UTILITIES
  3463. */
  3464. function unique() { return'x'+ ++NOW+''+(+new Date) }
  3465. function rnow() { return+new Date }
  3466. /**
  3467. * NEXTORIGIN
  3468. * ==========
  3469. * var next_origin = nextorigin();
  3470. */
  3471. var nextorigin = (function() {
  3472. var max = 20
  3473. , ori = Math.floor(Math.random() * max);
  3474. return function( origin, failover ) {
  3475. return origin.indexOf('pubsub.') > 0
  3476. && origin.replace(
  3477. 'pubsub', 'ps' + (
  3478. failover ? uuid().split('-')[0] :
  3479. (++ori < max? ori : ori=1)
  3480. ) ) || origin;
  3481. }
  3482. })();
  3483. /**
  3484. * Build Url
  3485. * =======
  3486. *
  3487. */
  3488. function build_url( url_components, url_params ) {
  3489. var url = url_components.join(URLBIT)
  3490. , params = [];
  3491. if (!url_params) return url;
  3492. each( url_params, function( key, value ) {
  3493. var value_str = (typeof value == 'object')?JSON['stringify'](value):value;
  3494. (typeof value != 'undefined' &&
  3495. value != null && encode(value_str).length > 0
  3496. ) && params.push(key + "=" + encode(value_str));
  3497. } );
  3498. url += "?" + params.join(PARAMSBIT);
  3499. return url;
  3500. }
  3501. /**
  3502. * UPDATER
  3503. * =======
  3504. * var timestamp = unique();
  3505. */
  3506. function updater( fun, rate ) {
  3507. var timeout
  3508. , last = 0
  3509. , runnit = function() {
  3510. if (last + rate > rnow()) {
  3511. clearTimeout(timeout);
  3512. timeout = setTimeout( runnit, rate );
  3513. }
  3514. else {
  3515. last = rnow();
  3516. fun();
  3517. }
  3518. };
  3519. return runnit;
  3520. }
  3521. /**
  3522. * GREP
  3523. * ====
  3524. * var list = grep( [1,2,3], function(item) { return item % 2 } )
  3525. */
  3526. function grep( list, fun ) {
  3527. var fin = [];
  3528. each( list || [], function(l) { fun(l) && fin.push(l) } );
  3529. return fin
  3530. }
  3531. /**
  3532. * SUPPLANT
  3533. * ========
  3534. * var text = supplant( 'Hello {name}!', { name : 'John' } )
  3535. */
  3536. function supplant( str, values ) {
  3537. return str.replace( REPL, function( _, match ) {
  3538. return values[match] || _
  3539. } );
  3540. }
  3541. /**
  3542. * timeout
  3543. * =======
  3544. * timeout( function(){}, 100 );
  3545. */
  3546. function timeout( fun, wait ) {
  3547. return setTimeout( fun, wait );
  3548. }
  3549. /**
  3550. * uuid
  3551. * ====
  3552. * var my_uuid = uuid();
  3553. */
  3554. function uuid(callback) {
  3555. var u = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,
  3556. function(c) {
  3557. var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
  3558. return v.toString(16);
  3559. });
  3560. if (callback) callback(u);
  3561. return u;
  3562. }
  3563. function isArray(arg) {
  3564. //return !!arg && (Array.isArray && Array.isArray(arg) || typeof(arg.length) === "number")
  3565. return !!arg && (Array.isArray && Array.isArray(arg))
  3566. }
  3567. /**
  3568. * EACH
  3569. * ====
  3570. * each( [1,2,3], function(item) { } )
  3571. */
  3572. function each( o, f) {
  3573. if ( !o || !f ) return;
  3574. if ( isArray(o) )
  3575. for ( var i = 0, l = o.length; i < l; )
  3576. f.call( o[i], o[i], i++ );
  3577. else
  3578. for ( var i in o )
  3579. o.hasOwnProperty &&
  3580. o.hasOwnProperty(i) &&
  3581. f.call( o[i], i, o[i] );
  3582. }
  3583. /**
  3584. * MAP
  3585. * ===
  3586. * var list = map( [1,2,3], function(item) { return item + 1 } )
  3587. */
  3588. function map( list, fun ) {
  3589. var fin = [];
  3590. each( list || [], function( k, v ) { fin.push(fun( k, v )) } );
  3591. return fin;
  3592. }
  3593. /**
  3594. * ENCODE
  3595. * ======
  3596. * var encoded_data = encode('path');
  3597. */
  3598. function encode(path) { return encodeURIComponent(path) }
  3599. /**
  3600. * Generate Subscription Channel List
  3601. * ==================================
  3602. * generate_channel_list(channels_object);
  3603. */
  3604. function generate_channel_list(channels, nopresence) {
  3605. var list = [];
  3606. each( channels, function( channel, status ) {
  3607. if (nopresence) {
  3608. if(channel.search('-pnpres') < 0) {
  3609. if (status.subscribed) list.push(channel);
  3610. }
  3611. } else {
  3612. if (status.subscribed) list.push(channel);
  3613. }
  3614. });
  3615. return list.sort();
  3616. }
  3617. /**
  3618. * Generate Subscription Channel Groups List
  3619. * ==================================
  3620. * generate_channel_groups_list(channels_groups object);
  3621. */
  3622. function generate_channel_groups_list(channel_groups, nopresence) {
  3623. var list = [];
  3624. each(channel_groups, function( channel_group, status ) {
  3625. if (nopresence) {
  3626. if(channel.search('-pnpres') < 0) {
  3627. if (status.subscribed) list.push(channel_group);
  3628. }
  3629. } else {
  3630. if (status.subscribed) list.push(channel_group);
  3631. }
  3632. });
  3633. return list.sort();
  3634. }
  3635. // PUBNUB READY TO CONNECT
  3636. function ready() { timeout( function() {
  3637. if (READY) return;
  3638. READY = 1;
  3639. each( READY_BUFFER, function(connect) { connect() } );
  3640. }, SECOND ); }
  3641. function PNmessage(args) {
  3642. msg = args || {'apns' : {}},
  3643. msg['getPubnubMessage'] = function() {
  3644. var m = {};
  3645. if (Object.keys(msg['apns']).length) {
  3646. m['pn_apns'] = {
  3647. 'aps' : {
  3648. 'alert' : msg['apns']['alert'] ,
  3649. 'badge' : msg['apns']['badge']
  3650. }
  3651. }
  3652. for (var k in msg['apns']) {
  3653. m['pn_apns'][k] = msg['apns'][k];
  3654. }
  3655. var exclude1 = ['badge','alert'];
  3656. for (var k in exclude1) {
  3657. //console.log(exclude[k]);
  3658. delete m['pn_apns'][exclude1[k]];
  3659. }
  3660. }
  3661. if (msg['gcm']) {
  3662. m['pn_gcm'] = {
  3663. 'data' : msg['gcm']
  3664. }
  3665. }
  3666. for (var k in msg) {
  3667. m[k] = msg[k];
  3668. }
  3669. var exclude = ['apns','gcm','publish', 'channel','callback','error'];
  3670. for (var k in exclude) {
  3671. delete m[exclude[k]];
  3672. }
  3673. return m;
  3674. };
  3675. msg['publish'] = function() {
  3676. var m = msg.getPubnubMessage();
  3677. if (msg['pubnub'] && msg['channel']) {
  3678. msg['pubnub'].publish({
  3679. 'message' : m,
  3680. 'channel' : msg['channel'],
  3681. 'callback' : msg['callback'],
  3682. 'error' : msg['error']
  3683. })
  3684. }
  3685. };
  3686. return msg;
  3687. }
  3688. function PN_API(setup) {
  3689. var SUB_WINDOWING = +setup['windowing'] || DEF_WINDOWING
  3690. , SUB_TIMEOUT = (+setup['timeout'] || DEF_SUB_TIMEOUT) * SECOND
  3691. , KEEPALIVE = (+setup['keepalive'] || DEF_KEEPALIVE) * SECOND
  3692. , NOLEAVE = setup['noleave'] || 0
  3693. , PUBLISH_KEY = setup['publish_key'] || 'demo'
  3694. , SUBSCRIBE_KEY = setup['subscribe_key'] || 'demo'
  3695. , AUTH_KEY = setup['auth_key'] || ''
  3696. , SECRET_KEY = setup['secret_key'] || ''
  3697. , hmac_SHA256 = setup['hmac_SHA256']
  3698. , SSL = setup['ssl'] ? 's' : ''
  3699. , ORIGIN = 'http'+SSL+'://'+(setup['origin']||'pubsub.pubnub.com')
  3700. , STD_ORIGIN = nextorigin(ORIGIN)
  3701. , SUB_ORIGIN = nextorigin(ORIGIN)
  3702. , CONNECT = function(){}
  3703. , PUB_QUEUE = []
  3704. , CLOAK = true
  3705. , TIME_DRIFT = 0
  3706. , SUB_CALLBACK = 0
  3707. , SUB_CHANNEL = 0
  3708. , SUB_RECEIVER = 0
  3709. , SUB_RESTORE = setup['restore'] || 0
  3710. , SUB_BUFF_WAIT = 0
  3711. , TIMETOKEN = 0
  3712. , RESUMED = false
  3713. , CHANNELS = {}
  3714. , CHANNEL_GROUPS = {}
  3715. , STATE = {}
  3716. , PRESENCE_HB_TIMEOUT = null
  3717. , PRESENCE_HB = validate_presence_heartbeat(setup['heartbeat'] || setup['pnexpires'] || 0, setup['error'])
  3718. , PRESENCE_HB_INTERVAL = setup['heartbeat_interval'] || PRESENCE_HB - 3
  3719. , PRESENCE_HB_RUNNING = false
  3720. , NO_WAIT_FOR_PENDING = setup['no_wait_for_pending']
  3721. , COMPATIBLE_35 = setup['compatible_3.5'] || false
  3722. , xdr = setup['xdr']
  3723. , params = setup['params'] || {}
  3724. , error = setup['error'] || function() {}
  3725. , _is_online = setup['_is_online'] || function() { return 1 }
  3726. , jsonp_cb = setup['jsonp_cb'] || function() { return 0 }
  3727. , db = setup['db'] || {'get': function(){}, 'set': function(){}}
  3728. , CIPHER_KEY = setup['cipher_key']
  3729. , UUID = setup['uuid'] || ( db && db['get'](SUBSCRIBE_KEY+'uuid') || '')
  3730. , _poll_timer
  3731. , _poll_timer2;
  3732. var crypto_obj = setup['crypto_obj'] ||
  3733. {
  3734. 'encrypt' : function(a,key){ return a},
  3735. 'decrypt' : function(b,key){return b}
  3736. };
  3737. function _get_url_params(data) {
  3738. if (!data) data = {};
  3739. each( params , function( key, value ) {
  3740. if (!(key in data)) data[key] = value;
  3741. });
  3742. return data;
  3743. }
  3744. function _object_to_key_list(o) {
  3745. var l = []
  3746. each( o , function( key, value ) {
  3747. l.push(key);
  3748. });
  3749. return l;
  3750. }
  3751. function _object_to_key_list_sorted(o) {
  3752. return _object_to_key_list(o).sort();
  3753. }
  3754. function _get_pam_sign_input_from_params(params) {
  3755. var si = "";
  3756. var l = _object_to_key_list_sorted(params);
  3757. for (var i in l) {
  3758. var k = l[i]
  3759. si += k + "=" + encode(params[k]) ;
  3760. if (i != l.length - 1) si += "&"
  3761. }
  3762. return si;
  3763. }
  3764. function validate_presence_heartbeat(heartbeat, cur_heartbeat, error) {
  3765. var err = false;
  3766. if (typeof heartbeat === 'number') {
  3767. if (heartbeat > PRESENCE_HB_THRESHOLD || heartbeat == 0)
  3768. err = false;
  3769. else
  3770. err = true;
  3771. } else if(typeof heartbeat === 'boolean'){
  3772. if (!heartbeat) {
  3773. return 0;
  3774. } else {
  3775. return PRESENCE_HB_DEFAULT;
  3776. }
  3777. } else {
  3778. err = true;
  3779. }
  3780. if (err) {
  3781. error && error("Presence Heartbeat value invalid. Valid range ( x > " + PRESENCE_HB_THRESHOLD + " or x = 0). Current Value : " + (cur_heartbeat || PRESENCE_HB_THRESHOLD));
  3782. return cur_heartbeat || PRESENCE_HB_THRESHOLD;
  3783. } else return heartbeat;
  3784. }
  3785. function encrypt(input, key) {
  3786. return crypto_obj['encrypt'](input, key || CIPHER_KEY) || input;
  3787. }
  3788. function decrypt(input, key) {
  3789. return crypto_obj['decrypt'](input, key || CIPHER_KEY) ||
  3790. crypto_obj['decrypt'](input, CIPHER_KEY) ||
  3791. input;
  3792. }
  3793. function error_common(message, callback) {
  3794. callback && callback({ 'error' : message || "error occurred"});
  3795. error && error(message);
  3796. }
  3797. function _presence_heartbeat() {
  3798. clearTimeout(PRESENCE_HB_TIMEOUT);
  3799. if (!PRESENCE_HB_INTERVAL || PRESENCE_HB_INTERVAL >= 500 || PRESENCE_HB_INTERVAL < 1 || !generate_channel_list(CHANNELS,true).length){
  3800. PRESENCE_HB_RUNNING = false;
  3801. return;
  3802. }
  3803. PRESENCE_HB_RUNNING = true;
  3804. SELF['presence_heartbeat']({
  3805. 'callback' : function(r) {
  3806. PRESENCE_HB_TIMEOUT = timeout( _presence_heartbeat, (PRESENCE_HB_INTERVAL) * SECOND );
  3807. },
  3808. 'error' : function(e) {
  3809. error && error("Presence Heartbeat unable to reach Pubnub servers." + JSON.stringify(e));
  3810. PRESENCE_HB_TIMEOUT = timeout( _presence_heartbeat, (PRESENCE_HB_INTERVAL) * SECOND );
  3811. }
  3812. });
  3813. }
  3814. function start_presence_heartbeat() {
  3815. !PRESENCE_HB_RUNNING && _presence_heartbeat();
  3816. }
  3817. function publish(next) {
  3818. if (NO_WAIT_FOR_PENDING) {
  3819. if (!PUB_QUEUE.length) return;
  3820. } else {
  3821. if (next) PUB_QUEUE.sending = 0;
  3822. if ( PUB_QUEUE.sending || !PUB_QUEUE.length ) return;
  3823. PUB_QUEUE.sending = 1;
  3824. }
  3825. xdr(PUB_QUEUE.shift());
  3826. }
  3827. function each_channel(callback) {
  3828. var count = 0;
  3829. each( generate_channel_list(CHANNELS), function(channel) {
  3830. var chan = CHANNELS[channel];
  3831. if (!chan) return;
  3832. count++;
  3833. (callback||function(){})(chan);
  3834. } );
  3835. return count;
  3836. }
  3837. function _invoke_callback(response, callback, err) {
  3838. if (typeof response == 'object') {
  3839. if (response['error'] && response['message'] && response['payload']) {
  3840. err({'message' : response['message'], 'payload' : response['payload']});
  3841. return;
  3842. }
  3843. if (response['payload']) {
  3844. callback(response['payload']);
  3845. return;
  3846. }
  3847. }
  3848. callback(response);
  3849. }
  3850. function _invoke_error(response,err) {
  3851. if (typeof response == 'object' && response['error'] &&
  3852. response['message'] && response['payload']) {
  3853. err({'message' : response['message'], 'payload' : response['payload']});
  3854. } else err(response);
  3855. }
  3856. function CR(args, callback, url1, data) {
  3857. var callback = args['callback'] || callback
  3858. , err = args['error'] || error
  3859. , jsonp = jsonp_cb();
  3860. var url = [
  3861. STD_ORIGIN, 'v1', 'channel-registration',
  3862. 'sub-key', SUBSCRIBE_KEY
  3863. ];
  3864. url.push.apply(url,url1);
  3865. xdr({
  3866. callback : jsonp,
  3867. data : _get_url_params(data),
  3868. success : function(response) {
  3869. _invoke_callback(response, callback, err);
  3870. },
  3871. fail : function(response) {
  3872. _invoke_error(response, err);
  3873. },
  3874. url : url
  3875. });
  3876. }
  3877. // Announce Leave Event
  3878. var SELF = {
  3879. 'LEAVE' : function( channel, blocking, callback, error ) {
  3880. var data = { 'uuid' : UUID, 'auth' : AUTH_KEY }
  3881. , origin = nextorigin(ORIGIN)
  3882. , callback = callback || function(){}
  3883. , err = error || function(){}
  3884. , jsonp = jsonp_cb();
  3885. // Prevent Leaving a Presence Channel
  3886. if (channel.indexOf(PRESENCE_SUFFIX) > 0) return true;
  3887. if (COMPATIBLE_35) {
  3888. if (!SSL) return false;
  3889. if (jsonp == '0') return false;
  3890. }
  3891. if (NOLEAVE) return false;
  3892. if (jsonp != '0') data['callback'] = jsonp;
  3893. xdr({
  3894. blocking : blocking || SSL,
  3895. timeout : 2000,
  3896. callback : jsonp,
  3897. data : _get_url_params(data),
  3898. success : function(response) {
  3899. _invoke_callback(response, callback, err);
  3900. },
  3901. fail : function(response) {
  3902. _invoke_error(response, err);
  3903. },
  3904. url : [
  3905. origin, 'v2', 'presence', 'sub_key',
  3906. SUBSCRIBE_KEY, 'channel', encode(channel), 'leave'
  3907. ]
  3908. });
  3909. return true;
  3910. },
  3911. 'set_resumed' : function(resumed) {
  3912. RESUMED = resumed;
  3913. },
  3914. 'get_cipher_key' : function() {
  3915. return CIPHER_KEY;
  3916. },
  3917. 'set_cipher_key' : function(key) {
  3918. CIPHER_KEY = key;
  3919. },
  3920. 'raw_encrypt' : function(input, key) {
  3921. return encrypt(input, key);
  3922. },
  3923. 'raw_decrypt' : function(input, key) {
  3924. return decrypt(input, key);
  3925. },
  3926. 'get_heartbeat' : function() {
  3927. return PRESENCE_HB;
  3928. },
  3929. 'set_heartbeat' : function(heartbeat) {
  3930. PRESENCE_HB = validate_presence_heartbeat(heartbeat, PRESENCE_HB_INTERVAL, error);
  3931. PRESENCE_HB_INTERVAL = (PRESENCE_HB - 3 >= 1)?PRESENCE_HB - 3:1;
  3932. CONNECT();
  3933. _presence_heartbeat();
  3934. },
  3935. 'get_heartbeat_interval' : function() {
  3936. return PRESENCE_HB_INTERVAL;
  3937. },
  3938. 'set_heartbeat_interval' : function(heartbeat_interval) {
  3939. PRESENCE_HB_INTERVAL = heartbeat_interval;
  3940. _presence_heartbeat();
  3941. },
  3942. 'get_version' : function() {
  3943. return SDK_VER;
  3944. },
  3945. 'getGcmMessageObject' : function(obj) {
  3946. return {
  3947. 'data' : obj
  3948. }
  3949. },
  3950. 'getApnsMessageObject' : function(obj) {
  3951. var x = {
  3952. 'aps' : { 'badge' : 1, 'alert' : ''}
  3953. }
  3954. for (k in obj) {
  3955. k[x] = obj[k];
  3956. }
  3957. return x;
  3958. },
  3959. 'newPnMessage' : function() {
  3960. var x = {};
  3961. if (gcm) x['pn_gcm'] = gcm;
  3962. if (apns) x['pn_apns'] = apns;
  3963. for ( k in n ) {
  3964. x[k] = n[k];
  3965. }
  3966. return x;
  3967. },
  3968. '_add_param' : function(key,val) {
  3969. params[key] = val;
  3970. },
  3971. 'channel_group' : function(args, callback) {
  3972. var ns_ch = args['channel_group']
  3973. , channels = args['channels'] || args['channel']
  3974. , cloak = args['cloak']
  3975. , namespace
  3976. , channel_group
  3977. , url = []
  3978. , data = {}
  3979. , mode = args['mode'] || 'add';
  3980. if (ns_ch) {
  3981. var ns_ch_a = ns_ch.split(':');
  3982. if (ns_ch_a.length > 1) {
  3983. namespace = (ns_ch_a[0] === '*')?null:ns_ch_a[0];
  3984. channel_group = ns_ch_a[1];
  3985. } else {
  3986. channel_group = ns_ch_a[0];
  3987. }
  3988. }
  3989. namespace && url.push('namespace') && url.push(encode(namespace));
  3990. url.push('channel-group');
  3991. if (channel_group && channel_group !== '*') {
  3992. url.push(channel_group);
  3993. }
  3994. if (channels ) {
  3995. if (isArray(channels)) {
  3996. channels = channels.join(',');
  3997. }
  3998. data[mode] = channels;
  3999. data['cloak'] = (CLOAK)?'true':'false';
  4000. } else {
  4001. if (mode === 'remove') url.push('remove');
  4002. }
  4003. if (typeof cloak != 'undefined') data['cloak'] = (cloak)?'true':'false';
  4004. CR(args, callback, url, data);
  4005. },
  4006. 'channel_group_list_groups' : function(args, callback) {
  4007. var namespace;
  4008. namespace = args['namespace'] || args['ns'] || args['channel_group'] || null;
  4009. if (namespace) {
  4010. args["channel_group"] = namespace + ":*";
  4011. }
  4012. SELF['channel_group'](args, callback);
  4013. },
  4014. 'channel_group_list_channels' : function(args, callback) {
  4015. if (!args['channel_group']) return error('Missing Channel Group');
  4016. SELF['channel_group'](args, callback);
  4017. },
  4018. 'channel_group_remove_channel' : function(args, callback) {
  4019. if (!args['channel_group']) return error('Missing Channel Group');
  4020. if (!args['channel'] && !args['channels'] ) return error('Missing Channel');
  4021. args['mode'] = 'remove';
  4022. SELF['channel_group'](args,callback);
  4023. },
  4024. 'channel_group_remove_group' : function(args, callback) {
  4025. if (!args['channel_group']) return error('Missing Channel Group');
  4026. if (args['channel']) return error('Use channel_group_remove_channel if you want to remove a channel from a group.');
  4027. args['mode'] = 'remove';
  4028. SELF['channel_group'](args,callback);
  4029. },
  4030. 'channel_group_add_channel' : function(args, callback) {
  4031. if (!args['channel_group']) return error('Missing Channel Group');
  4032. if (!args['channel'] && !args['channels'] ) return error('Missing Channel');
  4033. SELF['channel_group'](args,callback);
  4034. },
  4035. 'channel_group_cloak' : function(args, callback) {
  4036. if (typeof args['cloak'] == 'undefined') {
  4037. callback(CLOAK);
  4038. return;
  4039. }
  4040. CLOAK = args['cloak'];
  4041. SELF['channel_group'](args,callback);
  4042. },
  4043. 'channel_group_list_namespaces' : function(args, callback) {
  4044. var url = ['namespace'];
  4045. CR(args, callback, url);
  4046. },
  4047. 'channel_group_remove_namespace' : function(args, callback) {
  4048. var url = ['namespace',args['namespace'],'remove'];
  4049. CR(args, callback, url);
  4050. },
  4051. /*
  4052. PUBNUB.history({
  4053. channel : 'my_chat_channel',
  4054. limit : 100,
  4055. callback : function(history) { }
  4056. });
  4057. */
  4058. 'history' : function( args, callback ) {
  4059. var callback = args['callback'] || callback
  4060. , count = args['count'] || args['limit'] || 100
  4061. , reverse = args['reverse'] || "false"
  4062. , err = args['error'] || function(){}
  4063. , auth_key = args['auth_key'] || AUTH_KEY
  4064. , cipher_key = args['cipher_key']
  4065. , channel = args['channel']
  4066. , channel_group = args['channel_group']
  4067. , start = args['start']
  4068. , end = args['end']
  4069. , include_token = args['include_token']
  4070. , params = {}
  4071. , jsonp = jsonp_cb();
  4072. // Make sure we have a Channel
  4073. if (!channel && !channel_group) return error('Missing Channel');
  4074. if (!callback) return error('Missing Callback');
  4075. if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
  4076. params['stringtoken'] = 'true';
  4077. params['count'] = count;
  4078. params['reverse'] = reverse;
  4079. params['auth'] = auth_key;
  4080. if (channel_group) {
  4081. params['channel-group'] = channel_group;
  4082. if (!channel) {
  4083. channel = ',';
  4084. }
  4085. }
  4086. if (jsonp) params['callback'] = jsonp;
  4087. if (start) params['start'] = start;
  4088. if (end) params['end'] = end;
  4089. if (include_token) params['include_token'] = 'true';
  4090. // Send Message
  4091. xdr({
  4092. callback : jsonp,
  4093. data : _get_url_params(params),
  4094. success : function(response) {
  4095. if (typeof response == 'object' && response['error']) {
  4096. err({'message' : response['message'], 'payload' : response['payload']});
  4097. return;
  4098. }
  4099. var messages = response[0];
  4100. var decrypted_messages = [];
  4101. for (var a = 0; a < messages.length; a++) {
  4102. var new_message = decrypt(messages[a],cipher_key);
  4103. try {
  4104. decrypted_messages['push'](JSON['parse'](new_message));
  4105. } catch (e) {
  4106. decrypted_messages['push']((new_message));
  4107. }
  4108. }
  4109. callback([decrypted_messages, response[1], response[2]]);
  4110. },
  4111. fail : function(response) {
  4112. _invoke_error(response, err);
  4113. },
  4114. url : [
  4115. STD_ORIGIN, 'v2', 'history', 'sub-key',
  4116. SUBSCRIBE_KEY, 'channel', encode(channel)
  4117. ]
  4118. });
  4119. },
  4120. /*
  4121. PUBNUB.replay({
  4122. source : 'my_channel',
  4123. destination : 'new_channel'
  4124. });
  4125. */
  4126. 'replay' : function(args, callback) {
  4127. var callback = callback || args['callback'] || function(){}
  4128. , auth_key = args['auth_key'] || AUTH_KEY
  4129. , source = args['source']
  4130. , destination = args['destination']
  4131. , stop = args['stop']
  4132. , start = args['start']
  4133. , end = args['end']
  4134. , reverse = args['reverse']
  4135. , limit = args['limit']
  4136. , jsonp = jsonp_cb()
  4137. , data = {}
  4138. , url;
  4139. // Check User Input
  4140. if (!source) return error('Missing Source Channel');
  4141. if (!destination) return error('Missing Destination Channel');
  4142. if (!PUBLISH_KEY) return error('Missing Publish Key');
  4143. if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
  4144. // Setup URL Params
  4145. if (jsonp != '0') data['callback'] = jsonp;
  4146. if (stop) data['stop'] = 'all';
  4147. if (reverse) data['reverse'] = 'true';
  4148. if (start) data['start'] = start;
  4149. if (end) data['end'] = end;
  4150. if (limit) data['count'] = limit;
  4151. data['auth'] = auth_key;
  4152. // Compose URL Parts
  4153. url = [
  4154. STD_ORIGIN, 'v1', 'replay',
  4155. PUBLISH_KEY, SUBSCRIBE_KEY,
  4156. source, destination
  4157. ];
  4158. // Start (or Stop) Replay!
  4159. xdr({
  4160. callback : jsonp,
  4161. success : function(response) {
  4162. _invoke_callback(response, callback, err);
  4163. },
  4164. fail : function() { callback([ 0, 'Disconnected' ]) },
  4165. url : url,
  4166. data : _get_url_params(data)
  4167. });
  4168. },
  4169. /*
  4170. PUBNUB.auth('AJFLKAJSDKLA');
  4171. */
  4172. 'auth' : function(auth) {
  4173. AUTH_KEY = auth;
  4174. CONNECT();
  4175. },
  4176. /*
  4177. PUBNUB.time(function(time){ });
  4178. */
  4179. 'time' : function(callback) {
  4180. var jsonp = jsonp_cb();
  4181. xdr({
  4182. callback : jsonp,
  4183. data : _get_url_params({ 'uuid' : UUID, 'auth' : AUTH_KEY }),
  4184. timeout : SECOND * 5,
  4185. url : [STD_ORIGIN, 'time', jsonp],
  4186. success : function(response) { callback(response[0]) },
  4187. fail : function() { callback(0) }
  4188. });
  4189. },
  4190. /*
  4191. PUBNUB.publish({
  4192. channel : 'my_chat_channel',
  4193. message : 'hello!'
  4194. });
  4195. */
  4196. 'publish' : function( args, callback ) {
  4197. var msg = args['message'];
  4198. if (!msg) return error('Missing Message');
  4199. var callback = callback || args['callback'] || msg['callback'] || function(){}
  4200. , channel = args['channel'] || msg['channel']
  4201. , auth_key = args['auth_key'] || AUTH_KEY
  4202. , cipher_key = args['cipher_key']
  4203. , err = args['error'] || msg['error'] || function() {}
  4204. , post = args['post'] || false
  4205. , store = ('store_in_history' in args) ? args['store_in_history']: true
  4206. , jsonp = jsonp_cb()
  4207. , add_msg = 'push'
  4208. , url;
  4209. if (args['prepend']) add_msg = 'unshift'
  4210. if (!channel) return error('Missing Channel');
  4211. if (!PUBLISH_KEY) return error('Missing Publish Key');
  4212. if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
  4213. if (msg['getPubnubMessage']) {
  4214. msg = msg['getPubnubMessage']();
  4215. }
  4216. // If trying to send Object
  4217. msg = JSON['stringify'](encrypt(msg, cipher_key));
  4218. // Create URL
  4219. url = [
  4220. STD_ORIGIN, 'publish',
  4221. PUBLISH_KEY, SUBSCRIBE_KEY,
  4222. 0, encode(channel),
  4223. jsonp, encode(msg)
  4224. ];
  4225. params = { 'uuid' : UUID, 'auth' : auth_key }
  4226. if (!store) params['store'] ="0"
  4227. // Queue Message Send
  4228. PUB_QUEUE[add_msg]({
  4229. callback : jsonp,
  4230. timeout : SECOND * 5,
  4231. url : url,
  4232. data : _get_url_params(params),
  4233. fail : function(response){
  4234. _invoke_error(response, err);
  4235. publish(1);
  4236. },
  4237. success : function(response) {
  4238. _invoke_callback(response, callback, err);
  4239. publish(1);
  4240. },
  4241. mode : (post)?'POST':'GET'
  4242. });
  4243. // Send Message
  4244. publish();
  4245. },
  4246. /*
  4247. PUBNUB.unsubscribe({ channel : 'my_chat' });
  4248. */
  4249. 'unsubscribe' : function(args, callback) {
  4250. var channel = args['channel']
  4251. , channel_group = args['channel_group']
  4252. , callback = callback || args['callback'] || function(){}
  4253. , err = args['error'] || function(){};
  4254. TIMETOKEN = 0;
  4255. //SUB_RESTORE = 1; REVISIT !!!!
  4256. if (channel) {
  4257. // Prepare Channel(s)
  4258. channel = map( (
  4259. channel.join ? channel.join(',') : ''+channel
  4260. ).split(','), function(channel) {
  4261. if (!CHANNELS[channel]) return;
  4262. return channel + ',' + channel + PRESENCE_SUFFIX;
  4263. } ).join(',');
  4264. // Iterate over Channels
  4265. each( channel.split(','), function(channel) {
  4266. var CB_CALLED = true;
  4267. if (!channel) return;
  4268. if (READY) {
  4269. CB_CALLED = SELF['LEAVE']( channel, 0 , callback, err);
  4270. }
  4271. if (!CB_CALLED) callback({action : "leave"});
  4272. CHANNELS[channel] = 0;
  4273. if (channel in STATE) delete STATE[channel];
  4274. } );
  4275. }
  4276. if (channel_group) {
  4277. // Prepare channel group(s)
  4278. channel_group = map( (
  4279. channel_group.join ? channel_group.join(',') : ''+channel_group
  4280. ).split(','), function(channel_group) {
  4281. if (!CHANNEL_GROUPS[channel_group]) return;
  4282. return channel_group + ',' + channel_group + PRESENCE_SUFFIX;
  4283. } ).join(',');
  4284. // Iterate over channel groups
  4285. each( channel_group.split(','), function(channel) {
  4286. var CB_CALLED = true;
  4287. if (!channel_group) return;
  4288. if (READY) {
  4289. CB_CALLED = SELF['LEAVE']( channel_group, 0 , callback, err);
  4290. }
  4291. if (!CB_CALLED) callback({action : "leave"});
  4292. CHANNEL_GROUPS[channel_group] = 0;
  4293. if (channel_group in STATE) delete STATE[channel_group];
  4294. } );
  4295. }
  4296. // Reset Connection if Count Less
  4297. CONNECT();
  4298. },
  4299. /*
  4300. PUBNUB.subscribe({
  4301. channel : 'my_chat'
  4302. callback : function(message) { }
  4303. });
  4304. */
  4305. 'subscribe' : function( args, callback ) {
  4306. var channel = args['channel']
  4307. , channel_group = args['channel_group']
  4308. , callback = callback || args['callback']
  4309. , callback = callback || args['message']
  4310. , auth_key = args['auth_key'] || AUTH_KEY
  4311. , connect = args['connect'] || function(){}
  4312. , reconnect = args['reconnect'] || function(){}
  4313. , disconnect = args['disconnect'] || function(){}
  4314. , errcb = args['error'] || function(){}
  4315. , idlecb = args['idle'] || function(){}
  4316. , presence = args['presence'] || 0
  4317. , noheresync = args['noheresync'] || 0
  4318. , backfill = args['backfill'] || 0
  4319. , timetoken = args['timetoken'] || 0
  4320. , sub_timeout = args['timeout'] || SUB_TIMEOUT
  4321. , windowing = args['windowing'] || SUB_WINDOWING
  4322. , state = args['state']
  4323. , heartbeat = args['heartbeat'] || args['pnexpires']
  4324. , restore = args['restore'] || SUB_RESTORE;
  4325. // Restore Enabled?
  4326. SUB_RESTORE = restore;
  4327. // Always Reset the TT
  4328. TIMETOKEN = timetoken;
  4329. // Make sure we have a Channel
  4330. if (!channel && !channel_group) {
  4331. return error('Missing Channel');
  4332. }
  4333. if (!callback) return error('Missing Callback');
  4334. if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
  4335. if (heartbeat || heartbeat === 0) {
  4336. SELF['set_heartbeat'](heartbeat);
  4337. }
  4338. // Setup Channel(s)
  4339. if (channel) {
  4340. each( (channel.join ? channel.join(',') : ''+channel).split(','),
  4341. function(channel) {
  4342. var settings = CHANNELS[channel] || {};
  4343. // Store Channel State
  4344. CHANNELS[SUB_CHANNEL = channel] = {
  4345. name : channel,
  4346. connected : settings.connected,
  4347. disconnected : settings.disconnected,
  4348. subscribed : 1,
  4349. callback : SUB_CALLBACK = callback,
  4350. 'cipher_key' : args['cipher_key'],
  4351. connect : connect,
  4352. disconnect : disconnect,
  4353. reconnect : reconnect
  4354. };
  4355. if (state) {
  4356. if (channel in state) {
  4357. STATE[channel] = state[channel];
  4358. } else {
  4359. STATE[channel] = state;
  4360. }
  4361. }
  4362. // Presence Enabled?
  4363. if (!presence) return;
  4364. // Subscribe Presence Channel
  4365. SELF['subscribe']({
  4366. 'channel' : channel + PRESENCE_SUFFIX,
  4367. 'callback' : presence,
  4368. 'restore' : restore
  4369. });
  4370. // Presence Subscribed?
  4371. if (settings.subscribed) return;
  4372. // See Who's Here Now?
  4373. if (noheresync) return;
  4374. SELF['here_now']({
  4375. 'channel' : channel,
  4376. 'callback' : function(here) {
  4377. each( 'uuids' in here ? here['uuids'] : [],
  4378. function(uid) { presence( {
  4379. 'action' : 'join',
  4380. 'uuid' : uid,
  4381. 'timestamp' : Math.floor(rnow() / 1000),
  4382. 'occupancy' : here['occupancy'] || 1
  4383. }, here, channel ); } );
  4384. }
  4385. });
  4386. } );
  4387. }
  4388. // Setup Channel Groups
  4389. if (channel_group) {
  4390. each( (channel_group.join ? channel_group.join(',') : ''+channel_group).split(','),
  4391. function(channel_group) {
  4392. var settings = CHANNEL_GROUPS[channel_group] || {};
  4393. CHANNEL_GROUPS[channel_group] = {
  4394. name : channel_group,
  4395. connected : settings.connected,
  4396. disconnected : settings.disconnected,
  4397. subscribed : 1,
  4398. callback : SUB_CALLBACK = callback,
  4399. 'cipher_key' : args['cipher_key'],
  4400. connect : connect,
  4401. disconnect : disconnect,
  4402. reconnect : reconnect
  4403. };
  4404. // Presence Enabled?
  4405. if (!presence) return;
  4406. // Subscribe Presence Channel
  4407. SELF['subscribe']({
  4408. 'channel_group' : channel_group + PRESENCE_SUFFIX,
  4409. 'callback' : presence,
  4410. 'restore' : restore
  4411. });
  4412. // Presence Subscribed?
  4413. if (settings.subscribed) return;
  4414. // See Who's Here Now?
  4415. if (noheresync) return;
  4416. SELF['here_now']({
  4417. 'channel_group' : channel_group,
  4418. 'callback' : function(here) {
  4419. each( 'uuids' in here ? here['uuids'] : [],
  4420. function(uid) { presence( {
  4421. 'action' : 'join',
  4422. 'uuid' : uid,
  4423. 'timestamp' : Math.floor(rnow() / 1000),
  4424. 'occupancy' : here['occupancy'] || 1
  4425. }, here, channel_group ); } );
  4426. }
  4427. });
  4428. } );
  4429. }
  4430. // Test Network Connection
  4431. function _test_connection(success) {
  4432. if (success) {
  4433. // Begin Next Socket Connection
  4434. timeout( CONNECT, SECOND );
  4435. }
  4436. else {
  4437. // New Origin on Failed Connection
  4438. STD_ORIGIN = nextorigin( ORIGIN, 1 );
  4439. SUB_ORIGIN = nextorigin( ORIGIN, 1 );
  4440. // Re-test Connection
  4441. timeout( function() {
  4442. SELF['time'](_test_connection);
  4443. }, SECOND );
  4444. }
  4445. // Disconnect & Reconnect
  4446. each_channel(function(channel){
  4447. // Reconnect
  4448. if (success && channel.disconnected) {
  4449. channel.disconnected = 0;
  4450. return channel.reconnect(channel.name);
  4451. }
  4452. // Disconnect
  4453. if (!success && !channel.disconnected) {
  4454. channel.disconnected = 1;
  4455. channel.disconnect(channel.name);
  4456. }
  4457. });
  4458. }
  4459. // Evented Subscribe
  4460. function _connect() {
  4461. var jsonp = jsonp_cb()
  4462. , channels = generate_channel_list(CHANNELS).join(',')
  4463. , channel_groups = generate_channel_groups_list(CHANNEL_GROUPS).join(',');
  4464. // Stop Connection
  4465. if (!channels && !channel_groups) return;
  4466. if (!channels) channels = ',';
  4467. // Connect to PubNub Subscribe Servers
  4468. _reset_offline();
  4469. var data = _get_url_params({ 'uuid' : UUID, 'auth' : auth_key });
  4470. if (channel_groups) {
  4471. data['channel-group'] = channel_groups;
  4472. }
  4473. var st = JSON.stringify(STATE);
  4474. if (st.length > 2) data['state'] = JSON.stringify(STATE);
  4475. if (PRESENCE_HB) data['heartbeat'] = PRESENCE_HB;
  4476. start_presence_heartbeat();
  4477. SUB_RECEIVER = xdr({
  4478. timeout : sub_timeout,
  4479. callback : jsonp,
  4480. fail : function(response) {
  4481. _invoke_error(response, errcb);
  4482. //SUB_RECEIVER = null;
  4483. SELF['time'](_test_connection);
  4484. },
  4485. data : _get_url_params(data),
  4486. url : [
  4487. SUB_ORIGIN, 'subscribe',
  4488. SUBSCRIBE_KEY, encode(channels),
  4489. jsonp, TIMETOKEN
  4490. ],
  4491. success : function(messages) {
  4492. //SUB_RECEIVER = null;
  4493. // Check for Errors
  4494. if (!messages || (
  4495. typeof messages == 'object' &&
  4496. 'error' in messages &&
  4497. messages['error']
  4498. )) {
  4499. errcb(messages['error']);
  4500. return timeout( CONNECT, SECOND );
  4501. }
  4502. // User Idle Callback
  4503. idlecb(messages[1]);
  4504. // Restore Previous Connection Point if Needed
  4505. TIMETOKEN = !TIMETOKEN &&
  4506. SUB_RESTORE &&
  4507. db['get'](SUBSCRIBE_KEY) || messages[1];
  4508. /*
  4509. // Connect
  4510. each_channel_registry(function(registry){
  4511. if (registry.connected) return;
  4512. registry.connected = 1;
  4513. registry.connect(channel.name);
  4514. });
  4515. */
  4516. // Connect
  4517. each_channel(function(channel){
  4518. if (channel.connected) return;
  4519. channel.connected = 1;
  4520. channel.connect(channel.name);
  4521. });
  4522. if (RESUMED && !SUB_RESTORE) {
  4523. TIMETOKEN = 0;
  4524. RESUMED = false;
  4525. // Update Saved Timetoken
  4526. db['set']( SUBSCRIBE_KEY, 0 );
  4527. timeout( _connect, windowing );
  4528. return;
  4529. }
  4530. // Invoke Memory Catchup and Receive Up to 100
  4531. // Previous Messages from the Queue.
  4532. if (backfill) {
  4533. TIMETOKEN = 10000;
  4534. backfill = 0;
  4535. }
  4536. // Update Saved Timetoken
  4537. db['set']( SUBSCRIBE_KEY, messages[1] );
  4538. // Route Channel <---> Callback for Message
  4539. var next_callback = (function() {
  4540. var channels = '';
  4541. if (messages.length > 3) {
  4542. channels = messages[3];
  4543. } else if (messages.length > 2) {
  4544. channels = messages[2];
  4545. } else {
  4546. channels = map(
  4547. generate_channel_list(CHANNELS), function(chan) { return map(
  4548. Array(messages[0].length)
  4549. .join(',').split(','),
  4550. function() { return chan; }
  4551. ) }).join(',')
  4552. }
  4553. var list = channels.split(',');
  4554. return function() {
  4555. var channel = list.shift()||SUB_CHANNEL;
  4556. return [
  4557. (CHANNELS[channel]||{})
  4558. .callback||SUB_CALLBACK,
  4559. channel.split(PRESENCE_SUFFIX)[0]
  4560. ];
  4561. };
  4562. })();
  4563. var latency = detect_latency(+messages[1]);
  4564. each( messages[0], function(msg) {
  4565. var next = next_callback();
  4566. var decrypted_msg = decrypt(msg,
  4567. (CHANNELS[next[1]])?CHANNELS[next[1]]['cipher_key']:null);
  4568. next[0]( decrypted_msg, messages, next[2] || next[1], latency);
  4569. });
  4570. timeout( _connect, windowing );
  4571. }
  4572. });
  4573. }
  4574. CONNECT = function() {
  4575. _reset_offline();
  4576. timeout( _connect, windowing );
  4577. };
  4578. // Reduce Status Flicker
  4579. if (!READY) return READY_BUFFER.push(CONNECT);
  4580. // Connect Now
  4581. CONNECT();
  4582. },
  4583. /*
  4584. PUBNUB.here_now({ channel : 'my_chat', callback : fun });
  4585. */
  4586. 'here_now' : function( args, callback ) {
  4587. var callback = args['callback'] || callback
  4588. , err = args['error'] || function(){}
  4589. , auth_key = args['auth_key'] || AUTH_KEY
  4590. , channel = args['channel']
  4591. , channel_group = args['channel_group']
  4592. , jsonp = jsonp_cb()
  4593. , uuids = ('uuids' in args) ? args['uuids'] : true
  4594. , state = args['state']
  4595. , data = { 'uuid' : UUID, 'auth' : auth_key };
  4596. if (!uuids) data['disable_uuids'] = 1;
  4597. if (state) data['state'] = 1;
  4598. // Make sure we have a Channel
  4599. if (!callback) return error('Missing Callback');
  4600. if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
  4601. var url = [
  4602. STD_ORIGIN, 'v2', 'presence',
  4603. 'sub_key', SUBSCRIBE_KEY
  4604. ];
  4605. channel && url.push('channel') && url.push(encode(channel));
  4606. if (jsonp != '0') { data['callback'] = jsonp; }
  4607. if (channel_group) {
  4608. data['channel-group'] = channel_group;
  4609. !channel && url.push('channel') && url.push(',');
  4610. }
  4611. xdr({
  4612. callback : jsonp,
  4613. data : _get_url_params(data),
  4614. success : function(response) {
  4615. _invoke_callback(response, callback, err);
  4616. },
  4617. fail : function(response) {
  4618. _invoke_error(response, err);
  4619. },
  4620. url : url
  4621. });
  4622. },
  4623. /*
  4624. PUBNUB.current_channels_by_uuid({ channel : 'my_chat', callback : fun });
  4625. */
  4626. 'where_now' : function( args, callback ) {
  4627. var callback = args['callback'] || callback
  4628. , err = args['error'] || function(){}
  4629. , auth_key = args['auth_key'] || AUTH_KEY
  4630. , jsonp = jsonp_cb()
  4631. , uuid = args['uuid'] || UUID
  4632. , data = { 'auth' : auth_key };
  4633. // Make sure we have a Channel
  4634. if (!callback) return error('Missing Callback');
  4635. if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
  4636. if (jsonp != '0') { data['callback'] = jsonp; }
  4637. xdr({
  4638. callback : jsonp,
  4639. data : _get_url_params(data),
  4640. success : function(response) {
  4641. _invoke_callback(response, callback, err);
  4642. },
  4643. fail : function(response) {
  4644. _invoke_error(response, err);
  4645. },
  4646. url : [
  4647. STD_ORIGIN, 'v2', 'presence',
  4648. 'sub_key', SUBSCRIBE_KEY,
  4649. 'uuid', encode(uuid)
  4650. ]
  4651. });
  4652. },
  4653. 'state' : function(args, callback) {
  4654. var callback = args['callback'] || callback || function(r) {}
  4655. , err = args['error'] || function(){}
  4656. , auth_key = args['auth_key'] || AUTH_KEY
  4657. , jsonp = jsonp_cb()
  4658. , state = args['state']
  4659. , uuid = args['uuid'] || UUID
  4660. , channel = args['channel']
  4661. , channel_group = args['channel_group']
  4662. , url
  4663. , data = _get_url_params({ 'auth' : auth_key });
  4664. // Make sure we have a Channel
  4665. if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
  4666. if (!uuid) return error('Missing UUID');
  4667. if (!channel && !channel_group) return error('Missing Channel');
  4668. if (jsonp != '0') { data['callback'] = jsonp; }
  4669. if (typeof channel != 'undefined'
  4670. && CHANNELS[channel] && CHANNELS[channel].subscribed ) {
  4671. if (state) STATE[channel] = state;
  4672. }
  4673. if (typeof channel_group != 'undefined'
  4674. && CHANNEL_GROUPS[channel_group]
  4675. && CHANNEL_GROUPS[channel_group].subscribed
  4676. ) {
  4677. if (state) STATE[channel_group] = state;
  4678. data['channel-group'] = channel_group;
  4679. if (!channel) {
  4680. channel = ',';
  4681. }
  4682. }
  4683. data['state'] = JSON.stringify(state);
  4684. if (state) {
  4685. url = [
  4686. STD_ORIGIN, 'v2', 'presence',
  4687. 'sub-key', SUBSCRIBE_KEY,
  4688. 'channel', channel,
  4689. 'uuid', uuid, 'data'
  4690. ]
  4691. } else {
  4692. url = [
  4693. STD_ORIGIN, 'v2', 'presence',
  4694. 'sub-key', SUBSCRIBE_KEY,
  4695. 'channel', channel,
  4696. 'uuid', encode(uuid)
  4697. ]
  4698. }
  4699. xdr({
  4700. callback : jsonp,
  4701. data : _get_url_params(data),
  4702. success : function(response) {
  4703. _invoke_callback(response, callback, err);
  4704. },
  4705. fail : function(response) {
  4706. _invoke_error(response, err);
  4707. },
  4708. url : url
  4709. });
  4710. },
  4711. /*
  4712. PUBNUB.grant({
  4713. channel : 'my_chat',
  4714. callback : fun,
  4715. error : fun,
  4716. ttl : 24 * 60, // Minutes
  4717. read : true,
  4718. write : true,
  4719. auth_key : '3y8uiajdklytowsj'
  4720. });
  4721. */
  4722. 'grant' : function( args, callback ) {
  4723. var callback = args['callback'] || callback
  4724. , err = args['error'] || function(){}
  4725. , channel = args['channel']
  4726. , channel_group = args['channel_group']
  4727. , jsonp = jsonp_cb()
  4728. , ttl = args['ttl']
  4729. , r = (args['read'] )?"1":"0"
  4730. , w = (args['write'])?"1":"0"
  4731. , m = (args['manage'])?"1":"0"
  4732. , auth_key = args['auth_key'];
  4733. if (!callback) return error('Missing Callback');
  4734. if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
  4735. if (!PUBLISH_KEY) return error('Missing Publish Key');
  4736. if (!SECRET_KEY) return error('Missing Secret Key');
  4737. var timestamp = Math.floor(new Date().getTime() / 1000)
  4738. , sign_input = SUBSCRIBE_KEY + "\n" + PUBLISH_KEY + "\n"
  4739. + "grant" + "\n";
  4740. var data = {
  4741. 'w' : w,
  4742. 'r' : r,
  4743. 'timestamp' : timestamp
  4744. };
  4745. if (args['manage']) {
  4746. data['m'] = m;
  4747. }
  4748. if (typeof channel != 'undefined' && channel != null && channel.length > 0) data['channel'] = channel;
  4749. if (typeof channel_group != 'undefined' && channel_group != null && channel_group.length > 0) {
  4750. data['channel-group'] = channel_group;
  4751. }
  4752. if (jsonp != '0') { data['callback'] = jsonp; }
  4753. if (ttl || ttl === 0) data['ttl'] = ttl;
  4754. if (auth_key) data['auth'] = auth_key;
  4755. data = _get_url_params(data)
  4756. if (!auth_key) delete data['auth'];
  4757. sign_input += _get_pam_sign_input_from_params(data);
  4758. var signature = hmac_SHA256( sign_input, SECRET_KEY );
  4759. signature = signature.replace( /\+/g, "-" );
  4760. signature = signature.replace( /\//g, "_" );
  4761. data['signature'] = signature;
  4762. xdr({
  4763. callback : jsonp,
  4764. data : data,
  4765. success : function(response) {
  4766. _invoke_callback(response, callback, err);
  4767. },
  4768. fail : function(response) {
  4769. _invoke_error(response, err);
  4770. },
  4771. url : [
  4772. STD_ORIGIN, 'v1', 'auth', 'grant' ,
  4773. 'sub-key', SUBSCRIBE_KEY
  4774. ]
  4775. });
  4776. },
  4777. /*
  4778. PUBNUB.audit({
  4779. channel : 'my_chat',
  4780. callback : fun,
  4781. error : fun,
  4782. read : true,
  4783. write : true,
  4784. auth_key : '3y8uiajdklytowsj'
  4785. });
  4786. */
  4787. 'audit' : function( args, callback ) {
  4788. var callback = args['callback'] || callback
  4789. , err = args['error'] || function(){}
  4790. , channel = args['channel']
  4791. , channel_group = args['channel_group']
  4792. , auth_key = args['auth_key']
  4793. , jsonp = jsonp_cb();
  4794. // Make sure we have a Channel
  4795. if (!callback) return error('Missing Callback');
  4796. if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
  4797. if (!PUBLISH_KEY) return error('Missing Publish Key');
  4798. if (!SECRET_KEY) return error('Missing Secret Key');
  4799. var timestamp = Math.floor(new Date().getTime() / 1000)
  4800. , sign_input = SUBSCRIBE_KEY + "\n"
  4801. + PUBLISH_KEY + "\n"
  4802. + "audit" + "\n";
  4803. var data = {'timestamp' : timestamp };
  4804. if (jsonp != '0') { data['callback'] = jsonp; }
  4805. if (typeof channel != 'undefined' && channel != null && channel.length > 0) data['channel'] = channel;
  4806. if (typeof channel_group != 'undefined' && channel_group != null && channel_group.length > 0) {
  4807. data['channel-group'] = channel_group;
  4808. }
  4809. if (auth_key) data['auth'] = auth_key;
  4810. data = _get_url_params(data);
  4811. if (!auth_key) delete data['auth'];
  4812. sign_input += _get_pam_sign_input_from_params(data);
  4813. var signature = hmac_SHA256( sign_input, SECRET_KEY );
  4814. signature = signature.replace( /\+/g, "-" );
  4815. signature = signature.replace( /\//g, "_" );
  4816. data['signature'] = signature;
  4817. xdr({
  4818. callback : jsonp,
  4819. data : data,
  4820. success : function(response) {
  4821. _invoke_callback(response, callback, err);
  4822. },
  4823. fail : function(response) {
  4824. _invoke_error(response, err);
  4825. },
  4826. url : [
  4827. STD_ORIGIN, 'v1', 'auth', 'audit' ,
  4828. 'sub-key', SUBSCRIBE_KEY
  4829. ]
  4830. });
  4831. },
  4832. /*
  4833. PUBNUB.revoke({
  4834. channel : 'my_chat',
  4835. callback : fun,
  4836. error : fun,
  4837. auth_key : '3y8uiajdklytowsj'
  4838. });
  4839. */
  4840. 'revoke' : function( args, callback ) {
  4841. args['read'] = false;
  4842. args['write'] = false;
  4843. SELF['grant']( args, callback );
  4844. },
  4845. 'set_uuid' : function(uuid) {
  4846. UUID = uuid;
  4847. CONNECT();
  4848. },
  4849. 'get_uuid' : function() {
  4850. return UUID;
  4851. },
  4852. 'presence_heartbeat' : function(args) {
  4853. var callback = args['callback'] || function() {}
  4854. var err = args['error'] || function() {}
  4855. var jsonp = jsonp_cb();
  4856. var data = { 'uuid' : UUID, 'auth' : AUTH_KEY };
  4857. var st = JSON['stringify'](STATE);
  4858. if (st.length > 2) data['state'] = JSON['stringify'](STATE);
  4859. if (PRESENCE_HB > 0 && PRESENCE_HB < 320) data['heartbeat'] = PRESENCE_HB;
  4860. if (jsonp != '0') { data['callback'] = jsonp; }
  4861. var channels = encode(generate_channel_list(CHANNELS, true)['join'](','));
  4862. var channel_groups = generate_channel_groups_list(CHANNEL_GROUPS, true)['join'](',');
  4863. if (!channels) channels = ',';
  4864. if (channel_groups) data['channel-group'] = channel_groups;
  4865. xdr({
  4866. callback : jsonp,
  4867. data : _get_url_params(data),
  4868. timeout : SECOND * 5,
  4869. url : [
  4870. STD_ORIGIN, 'v2', 'presence',
  4871. 'sub-key', SUBSCRIBE_KEY,
  4872. 'channel' , channels,
  4873. 'heartbeat'
  4874. ],
  4875. success : function(response) {
  4876. _invoke_callback(response, callback, err);
  4877. },
  4878. fail : function(response) { _invoke_error(response, err); }
  4879. });
  4880. },
  4881. 'stop_timers': function () {
  4882. clearTimeout(_poll_timer);
  4883. clearTimeout(_poll_timer2);
  4884. },
  4885. // Expose PUBNUB Functions
  4886. 'xdr' : xdr,
  4887. 'ready' : ready,
  4888. 'db' : db,
  4889. 'uuid' : uuid,
  4890. 'map' : map,
  4891. 'each' : each,
  4892. 'each-channel' : each_channel,
  4893. 'grep' : grep,
  4894. 'offline' : function(){_reset_offline(1, { "message":"Offline. Please check your network settings." })},
  4895. 'supplant' : supplant,
  4896. 'now' : rnow,
  4897. 'unique' : unique,
  4898. 'updater' : updater
  4899. };
  4900. function _poll_online() {
  4901. _is_online() || _reset_offline( 1, {
  4902. "error" : "Offline. Please check your network settings. "
  4903. });
  4904. _poll_timer && clearTimeout(_poll_timer);
  4905. _poll_timer = timeout( _poll_online, SECOND );
  4906. }
  4907. function _poll_online2() {
  4908. SELF['time'](function(success){
  4909. detect_time_detla( function(){}, success );
  4910. success || _reset_offline( 1, {
  4911. "error" : "Heartbeat failed to connect to Pubnub Servers." +
  4912. "Please check your network settings."
  4913. });
  4914. _poll_timer2 && clearTimeout(_poll_timer2);
  4915. _poll_timer2 = timeout( _poll_online2, KEEPALIVE );
  4916. });
  4917. }
  4918. function _reset_offline(err, msg) {
  4919. SUB_RECEIVER && SUB_RECEIVER(err, msg);
  4920. SUB_RECEIVER = null;
  4921. clearTimeout(_poll_timer);
  4922. clearTimeout(_poll_timer2);
  4923. }
  4924. if (!UUID) UUID = SELF['uuid']();
  4925. db['set']( SUBSCRIBE_KEY + 'uuid', UUID );
  4926. _poll_timer = timeout( _poll_online, SECOND );
  4927. _poll_timer2 = timeout( _poll_online2, KEEPALIVE );
  4928. PRESENCE_HB_TIMEOUT = timeout( start_presence_heartbeat, ( PRESENCE_HB_INTERVAL - 3 ) * SECOND ) ;
  4929. // Detect Age of Message
  4930. function detect_latency(tt) {
  4931. var adjusted_time = rnow() - TIME_DRIFT;
  4932. return adjusted_time - tt / 10000;
  4933. }
  4934. detect_time_detla();
  4935. function detect_time_detla( cb, time ) {
  4936. var stime = rnow();
  4937. time && calculate(time) || SELF['time'](calculate);
  4938. function calculate(time) {
  4939. if (!time) return;
  4940. var ptime = time / 10000
  4941. , latency = (rnow() - stime) / 2;
  4942. TIME_DRIFT = rnow() - (ptime + latency);
  4943. cb && cb(TIME_DRIFT);
  4944. }
  4945. }
  4946. return SELF;
  4947. }
  4948. /* ---------------------------------------------------------------------------
  4949. WAIT! - This file depends on instructions from the PUBNUB Cloud.
  4950. http://www.pubnub.com/account
  4951. --------------------------------------------------------------------------- */
  4952. /* ---------------------------------------------------------------------------
  4953. PubNub Real-time Cloud-Hosted Push API and Push Notification Client Frameworks
  4954. Copyright (c) 2011 TopMambo Inc.
  4955. http://www.pubnub.com/
  4956. http://www.pubnub.com/terms
  4957. --------------------------------------------------------------------------- */
  4958. /* ---------------------------------------------------------------------------
  4959. Permission is hereby granted, free of charge, to any person obtaining a copy
  4960. of this software and associated documentation files (the "Software"), to deal
  4961. in the Software without restriction, including without limitation the rights
  4962. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  4963. copies of the Software, and to permit persons to whom the Software is
  4964. furnished to do so, subject to the following conditions:
  4965. The above copyright notice and this permission notice shall be included in
  4966. all copies or substantial portions of the Software.
  4967. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  4968. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  4969. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  4970. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  4971. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  4972. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  4973. THE SOFTWARE.
  4974. --------------------------------------------------------------------------- */
  4975. /**
  4976. * UTIL LOCALS
  4977. */
  4978. var NOW = 1
  4979. , http = __webpack_require__(30)
  4980. , https = __webpack_require__(46)
  4981. , keepAliveAgent = new (keepAliveIsEmbedded() ? http.Agent : __webpack_require__(55))({
  4982. keepAlive: true,
  4983. keepAliveMsecs: 300000,
  4984. maxSockets: 5
  4985. })
  4986. , XHRTME = 310000
  4987. , DEF_TIMEOUT = 10000
  4988. , SECOND = 1000
  4989. , PNSDK = 'PubNub-JS-' + 'Nodejs' + '/' + '3.7.0'
  4990. , crypto = __webpack_require__(48)
  4991. , proxy = null
  4992. , XORIGN = 1;
  4993. function get_hmac_SHA256(data, key) {
  4994. return crypto.createHmac('sha256',
  4995. new Buffer(key, 'utf8')).update(data).digest('base64');
  4996. }
  4997. /**
  4998. * ERROR
  4999. * ===
  5000. * error('message');
  5001. */
  5002. function error(message) { console['error'](message) }
  5003. /**
  5004. * Request
  5005. * =======
  5006. * xdr({
  5007. * url : ['http://www.blah.com/url'],
  5008. * success : function(response) {},
  5009. * fail : function() {}
  5010. * });
  5011. */
  5012. function xdr( setup ) {
  5013. var request
  5014. , response
  5015. , success = setup.success || function(){}
  5016. , fail = setup.fail || function(){}
  5017. , origin = setup.origin || 'pubsub.pubnub.com'
  5018. , ssl = setup.ssl
  5019. , failed = 0
  5020. , complete = 0
  5021. , loaded = 0
  5022. , mode = setup['mode'] || 'GET'
  5023. , data = setup['data'] || {}
  5024. , xhrtme = setup.timeout || DEF_TIMEOUT
  5025. , body = ''
  5026. , finished = function() {
  5027. if (loaded) return;
  5028. loaded = 1;
  5029. clearTimeout(timer);
  5030. try { response = JSON['parse'](body); }
  5031. catch (r) { return done(1); }
  5032. success(response);
  5033. }
  5034. , done = function(failed, response) {
  5035. if (complete) return;
  5036. complete = 1;
  5037. clearTimeout(timer);
  5038. if (request) {
  5039. request.on('error', function(){});
  5040. request.on('data', function(){});
  5041. request.on('end', function(){});
  5042. request.abort && request.abort();
  5043. request = null;
  5044. }
  5045. failed && fail(response);
  5046. }
  5047. , timer = timeout( function(){done(1);} , xhrtme );
  5048. data['pnsdk'] = PNSDK;
  5049. var options = {};
  5050. var headers = {};
  5051. var payload = '';
  5052. if (mode == 'POST')
  5053. payload = decodeURIComponent(setup.url.pop());
  5054. var url = build_url( setup.url, data );
  5055. if (!ssl) ssl = (url.split('://')[0] == 'https')?true:false;
  5056. url = '/' + url.split('/').slice(3).join('/');
  5057. var origin = setup.url[0].split("//")[1]
  5058. options.hostname = proxy ? proxy.hostname : setup.url[0].split("//")[1];
  5059. options.port = proxy ? proxy.port : ssl ? 443 : 80;
  5060. options.path = proxy ? "http://" + origin + url:url;
  5061. options.headers = proxy ? { 'Host': origin }:null;
  5062. options.method = mode;
  5063. options.keepAlive= !!keepAliveAgent;
  5064. //options.agent = keepAliveAgent;
  5065. options.body = payload;
  5066. __webpack_require__(30).globalAgent.maxSockets = Infinity;
  5067. try {
  5068. request = (ssl ? https : http)['request'](options, function(response) {
  5069. response.setEncoding('utf8');
  5070. response.on( 'error', function(){done(1, body || { "error" : "Network Connection Error"})});
  5071. response.on( 'abort', function(){done(1, body || { "error" : "Network Connection Error"})});
  5072. response.on( 'data', function (chunk) {
  5073. if (chunk) body += chunk;
  5074. } );
  5075. response.on( 'end', function(){
  5076. var statusCode = response.statusCode;
  5077. switch(statusCode) {
  5078. case 401:
  5079. case 402:
  5080. case 403:
  5081. try {
  5082. response = JSON['parse'](body);
  5083. done(1,response);
  5084. }
  5085. catch (r) { return done(1, body); }
  5086. return;
  5087. default:
  5088. break;
  5089. }
  5090. finished();
  5091. });
  5092. });
  5093. request.timeout = xhrtme;
  5094. request.on( 'error', function() {
  5095. done( 1, {"error":"Network Connection Error"} );
  5096. } );
  5097. if (mode == 'POST') request.write(payload);
  5098. request.end();
  5099. } catch(e) {
  5100. done(0);
  5101. return xdr(setup);
  5102. }
  5103. return done;
  5104. }
  5105. /**
  5106. * LOCAL STORAGE
  5107. */
  5108. var db = (function(){
  5109. var store = {};
  5110. return {
  5111. 'get' : function(key) {
  5112. return store[key];
  5113. },
  5114. 'set' : function( key, value ) {
  5115. store[key] = value;
  5116. }
  5117. };
  5118. })();
  5119. function crypto_obj() {
  5120. var iv = "0123456789012345";
  5121. function get_padded_key(key) {
  5122. return crypto.createHash('sha256').update(key).digest("hex").slice(0,32);
  5123. }
  5124. return {
  5125. 'encrypt' : function(input, key) {
  5126. if (!key) return input;
  5127. var plain_text = JSON['stringify'](input);
  5128. var cipher = crypto.createCipheriv('aes-256-cbc', get_padded_key(key), iv);
  5129. var base_64_encrypted = cipher.update(plain_text, 'utf8', 'base64') + cipher.final('base64');
  5130. return base_64_encrypted || input;
  5131. },
  5132. 'decrypt' : function(input, key) {
  5133. if (!key) return input;
  5134. var decipher = crypto.createDecipheriv('aes-256-cbc', get_padded_key(key), iv);
  5135. try {
  5136. var decrypted = decipher.update(input, 'base64', 'utf8') + decipher.final('utf8');
  5137. } catch (e) {
  5138. return null;
  5139. }
  5140. return JSON.parse(decrypted);
  5141. }
  5142. }
  5143. }
  5144. function keepAliveIsEmbedded() {
  5145. return 'EventEmitter' in http.Agent.super_;
  5146. }
  5147. var CREATE_PUBNUB = function(setup) {
  5148. proxy = setup['proxy'];
  5149. setup['xdr'] = xdr;
  5150. setup['db'] = db;
  5151. setup['error'] = setup['error'] || error;
  5152. setup['hmac_SHA256'] = get_hmac_SHA256;
  5153. setup['crypto_obj'] = crypto_obj();
  5154. setup['params'] = {'pnsdk' : PNSDK};
  5155. if (setup['keepAlive'] === false) {
  5156. keepAliveAgent = undefined;
  5157. }
  5158. SELF = function(setup) {
  5159. return CREATE_PUBNUB(setup);
  5160. }
  5161. var PN = PN_API(setup);
  5162. for (var prop in PN) {
  5163. if (PN.hasOwnProperty(prop)) {
  5164. SELF[prop] = PN[prop];
  5165. }
  5166. }
  5167. SELF.init = SELF;
  5168. SELF.secure = SELF;
  5169. SELF.ready();
  5170. return SELF;
  5171. }
  5172. CREATE_PUBNUB.init = CREATE_PUBNUB;
  5173. CREATE_PUBNUB.unique = unique
  5174. CREATE_PUBNUB.secure = CREATE_PUBNUB;
  5175. module.exports = CREATE_PUBNUB
  5176. module.exports.PNmessage = PNmessage;
  5177. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(47).Buffer))
  5178. /***/ },
  5179. /* 33 */
  5180. /***/ function(module, exports, __webpack_require__) {
  5181. var util = __webpack_require__(43);
  5182. // enum for type of timeout
  5183. var TYPE = {
  5184. TIMEOUT: 0,
  5185. INTERVAL: 1,
  5186. TRIGGER: 2
  5187. };
  5188. var DISCRETE = 'discrete';
  5189. /**
  5190. * Create a new hypertimer
  5191. * @param {Object} [options] The following options are available:
  5192. * rate: number | 'discrete'
  5193. * The rate of speed of hyper time with
  5194. * respect to real-time in milliseconds
  5195. * per millisecond. Rate must be a
  5196. * positive number, or 'discrete' to
  5197. * run in discrete time (jumping from
  5198. * event to event). By default, rate is 1.
  5199. * deterministic: boolean
  5200. * If true (default), simultaneous events
  5201. * are executed in a deterministic order.
  5202. */
  5203. function hypertimer(options) {
  5204. // options
  5205. var rate = 1; // number of milliseconds per milliseconds
  5206. var deterministic = true; // run simultaneous events in a deterministic order
  5207. // properties
  5208. var running = false; // true when running
  5209. var realTime = null; // timestamp. the moment in real-time when hyperTime was set
  5210. var hyperTime = null; // timestamp. the start time in hyper-time
  5211. var timeouts = []; // array with all running timeouts
  5212. var current = {}; // the timeouts currently in progress (callback is being executed)
  5213. var timeoutId = null; // currently running timer
  5214. var idSeq = 0; // counter for unique timeout id's
  5215. // exported timer object with public functions and variables
  5216. var timer = {};
  5217. /**
  5218. * Change configuration options of the hypertimer, or retrieve current
  5219. * configuration.
  5220. * @param {Object} [options] The following options are available:
  5221. * rate: number | 'discrete'
  5222. * The rate of speed of hyper time with
  5223. * respect to real-time in milliseconds
  5224. * per millisecond. Rate must be a
  5225. * positive number, or 'discrete' to
  5226. * run in discrete time (jumping from
  5227. * event to event). By default, rate is 1.
  5228. * deterministic: boolean
  5229. * If true (default), simultaneous events
  5230. * are executed in a deterministic order.
  5231. * @return {Object} Returns the applied configuration
  5232. */
  5233. timer.config = function(options) {
  5234. if (options) {
  5235. if ('rate' in options) {
  5236. var newRate = (options.rate === DISCRETE) ? DISCRETE : Number(options.rate);
  5237. if (newRate !== DISCRETE && (isNaN(newRate) || newRate <= 0)) {
  5238. throw new TypeError('rate must be a positive number or the string "discrete"');
  5239. }
  5240. hyperTime = timer.now();
  5241. realTime = util.systemNow();
  5242. rate = newRate;
  5243. }
  5244. if ('deterministic' in options) {
  5245. deterministic = options.deterministic ? true : false;
  5246. }
  5247. }
  5248. // reschedule running timeouts
  5249. _schedule();
  5250. // return a copy of the configuration options
  5251. return {
  5252. rate: rate,
  5253. deterministic: deterministic
  5254. };
  5255. };
  5256. /**
  5257. * Set the time of the timer. To get the current time, use getTime() or now().
  5258. * @param {number | Date} time The time in hyper-time.
  5259. */
  5260. timer.setTime = function (time) {
  5261. if (time instanceof Date) {
  5262. hyperTime = time.valueOf();
  5263. }
  5264. else {
  5265. var newTime = Number(time);
  5266. if (isNaN(newTime)) {
  5267. throw new TypeError('time must be a Date or number');
  5268. }
  5269. hyperTime = newTime;
  5270. }
  5271. // reschedule running timeouts
  5272. _schedule();
  5273. };
  5274. /**
  5275. * Returns the current time of the timer as a number.
  5276. * See also getTime().
  5277. * @return {number} The time
  5278. */
  5279. timer.now = function () {
  5280. if (rate === DISCRETE) {
  5281. return hyperTime;
  5282. }
  5283. else {
  5284. if (running) {
  5285. // TODO: implement performance.now() / process.hrtime(time) for high precision calculation of time interval
  5286. var realInterval = util.systemNow() - realTime;
  5287. var hyperInterval = realInterval * rate;
  5288. return hyperTime + hyperInterval;
  5289. }
  5290. else {
  5291. return hyperTime;
  5292. }
  5293. }
  5294. };
  5295. /**
  5296. * Continue the timer.
  5297. */
  5298. timer['continue'] = function() {
  5299. realTime = util.systemNow();
  5300. running = true;
  5301. // reschedule running timeouts
  5302. _schedule();
  5303. };
  5304. /**
  5305. * Pause the timer. The timer can be continued again with `continue()`
  5306. */
  5307. timer.pause = function() {
  5308. hyperTime = timer.now();
  5309. realTime = null;
  5310. running = false;
  5311. // reschedule running timeouts (pauses them)
  5312. _schedule();
  5313. };
  5314. /**
  5315. * Returns the current time of the timer as Date.
  5316. * See also now().
  5317. * @return {Date} The time
  5318. */
  5319. // rename to getTime
  5320. timer.getTime = function() {
  5321. return new Date(timer.now());
  5322. };
  5323. /**
  5324. * Get the value of the hypertimer. This function returns the result of getTime().
  5325. * @return {Date} current time
  5326. */
  5327. timer.valueOf = timer.getTime;
  5328. /**
  5329. * Return a string representation of the current hyper-time.
  5330. * @returns {string} String representation
  5331. */
  5332. timer.toString = function () {
  5333. return timer.getTime().toString();
  5334. };
  5335. /**
  5336. * Set a timeout, which is triggered when the timeout occurs in hyper-time.
  5337. * See also setTrigger.
  5338. * @param {Function} callback Function executed when delay is exceeded.
  5339. * @param {number} delay The delay in milliseconds. When the delay is
  5340. * smaller or equal to zero, the callback is
  5341. * triggered immediately.
  5342. * @return {number} Returns a timeoutId which can be used to cancel the
  5343. * timeout using clearTimeout().
  5344. */
  5345. timer.setTimeout = function(callback, delay) {
  5346. var id = idSeq++;
  5347. var timestamp = timer.now() + delay;
  5348. if (isNaN(timestamp)) {
  5349. throw new TypeError('delay must be a number');
  5350. }
  5351. // add a new timeout to the queue
  5352. _queueTimeout({
  5353. id: id,
  5354. type: TYPE.TIMEOUT,
  5355. time: timestamp,
  5356. callback: callback
  5357. });
  5358. // reschedule the timeouts
  5359. _schedule();
  5360. return id;
  5361. };
  5362. /**
  5363. * Set a trigger, which is triggered when the timeout occurs in hyper-time.
  5364. * See also getTimeout.
  5365. * @param {Function} callback Function executed when timeout occurs.
  5366. * @param {Date | number} time An absolute moment in time (Date) when the
  5367. * callback will be triggered. When the date is
  5368. * a Date in the past, the callback is triggered
  5369. * immediately.
  5370. * @return {number} Returns a triggerId which can be used to cancel the
  5371. * trigger using clearTrigger().
  5372. */
  5373. timer.setTrigger = function (callback, time) {
  5374. var id = idSeq++;
  5375. var timestamp = Number(time);
  5376. if (isNaN(timestamp)) {
  5377. throw new TypeError('time must be a Date or number');
  5378. }
  5379. // add a new timeout to the queue
  5380. _queueTimeout({
  5381. id: id,
  5382. type: TYPE.TRIGGER,
  5383. time: timestamp,
  5384. callback: callback
  5385. });
  5386. // reschedule the timeouts
  5387. _schedule();
  5388. return id;
  5389. };
  5390. /**
  5391. * Trigger a callback every interval. Optionally, a start date can be provided
  5392. * to specify the first time the callback must be triggered.
  5393. * See also setTimeout and setTrigger.
  5394. * @param {Function} callback Function executed when delay is exceeded.
  5395. * @param {number} interval Interval in milliseconds. When interval
  5396. * is smaller than zero or is infinity, the
  5397. * interval will be set to zero and triggered
  5398. * with a maximum rate.
  5399. * @param {Date | number} [firstTime] An absolute moment in time (Date) when the
  5400. * callback will be triggered the first time.
  5401. * By default, firstTime = now() + interval.
  5402. * @return {number} Returns a intervalId which can be used to cancel the
  5403. * trigger using clearInterval().
  5404. */
  5405. timer.setInterval = function(callback, interval, firstTime) {
  5406. var id = idSeq++;
  5407. var _interval = Number(interval);
  5408. if (isNaN(_interval)) {
  5409. throw new TypeError('interval must be a number');
  5410. }
  5411. if (_interval < 0 || !isFinite(_interval)) {
  5412. _interval = 0;
  5413. }
  5414. var timestamp;
  5415. if (firstTime != undefined) {
  5416. timestamp = Number(firstTime);
  5417. if (isNaN(timestamp)) {
  5418. throw new TypeError('firstTime must be a Date or number');
  5419. }
  5420. }
  5421. else {
  5422. // firstTime is undefined or null
  5423. timestamp = (timer.now() + _interval);
  5424. }
  5425. // add a new timeout to the queue
  5426. _queueTimeout({
  5427. id: id,
  5428. type: TYPE.INTERVAL,
  5429. interval: _interval,
  5430. time: timestamp,
  5431. firstTime: timestamp,
  5432. occurrence: 0,
  5433. callback: callback
  5434. });
  5435. // reschedule the timeouts
  5436. _schedule();
  5437. return id;
  5438. };
  5439. /**
  5440. * Cancel a timeout
  5441. * @param {number} timeoutId The id of a timeout
  5442. */
  5443. timer.clearTimeout = function(timeoutId) {
  5444. // test whether timeout is currently being executed
  5445. if (current[timeoutId]) {
  5446. delete current[timeoutId];
  5447. return;
  5448. }
  5449. // find the timeout in the queue
  5450. for (var i = 0; i < timeouts.length; i++) {
  5451. if (timeouts[i].id === timeoutId) {
  5452. // remove this timeout from the queue
  5453. timeouts.splice(i, 1);
  5454. // reschedule timeouts
  5455. _schedule();
  5456. break;
  5457. }
  5458. }
  5459. };
  5460. /**
  5461. * Cancel a trigger
  5462. * @param {number} triggerId The id of a trigger
  5463. */
  5464. timer.clearTrigger = timer.clearTimeout;
  5465. timer.clearInterval = timer.clearTimeout;
  5466. /**
  5467. * Returns a list with the id's of all timeouts
  5468. * @returns {number[]} Timeout id's
  5469. */
  5470. timer.list = function () {
  5471. return timeouts.map(function (timeout) {
  5472. return timeout.id;
  5473. });
  5474. };
  5475. /**
  5476. * Clear all timeouts
  5477. */
  5478. timer.clear = function () {
  5479. // empty the queue
  5480. current = {};
  5481. timeouts = [];
  5482. // reschedule
  5483. _schedule();
  5484. };
  5485. /**
  5486. * Add a timeout to the queue. After the queue has been changed, the queue
  5487. * must be rescheduled by executing _reschedule()
  5488. * @param {{id: number, type: number, time: number, callback: Function}} timeout
  5489. * @private
  5490. */
  5491. function _queueTimeout(timeout) {
  5492. // insert the new timeout at the right place in the array, sorted by time
  5493. if (timeouts.length > 0) {
  5494. var i = timeouts.length - 1;
  5495. while (i >= 0 && timeouts[i].time > timeout.time) {
  5496. i--;
  5497. }
  5498. // insert the new timeout in the queue. Note that the timeout is
  5499. // inserted *after* existing timeouts with the exact *same* time,
  5500. // so the order in which they are executed is deterministic
  5501. timeouts.splice(i + 1, 0, timeout);
  5502. }
  5503. else {
  5504. // queue is empty, append the new timeout
  5505. timeouts.push(timeout);
  5506. }
  5507. }
  5508. /**
  5509. * Execute a timeout
  5510. * @param {{id: number, type: number, time: number, callback: function}} timeout
  5511. * @param {function} [callback]
  5512. * The callback is executed when the timeout's callback is
  5513. * finished. Called without parameters
  5514. * @private
  5515. */
  5516. function _execTimeout(timeout, callback) {
  5517. // store the timeout in the queue with timeouts in progress
  5518. // it can be cleared when a clearTimeout is executed inside the callback
  5519. current[timeout.id] = timeout;
  5520. function finish() {
  5521. // in case of an interval we have to reschedule on next cycle
  5522. // interval must not be cleared while executing the callback
  5523. if (timeout.type === TYPE.INTERVAL && current[timeout.id]) {
  5524. timeout.occurrence++;
  5525. timeout.time = timeout.firstTime + timeout.occurrence * timeout.interval;
  5526. _queueTimeout(timeout);
  5527. }
  5528. // remove the timeout from the queue with timeouts in progress
  5529. delete current[timeout.id];
  5530. if (typeof callback === 'function') callback();
  5531. }
  5532. // execute the callback
  5533. try {
  5534. if (timeout.callback.length == 0) {
  5535. // synchronous timeout, like `timer.setTimeout(function () {...}, delay)`
  5536. timeout.callback();
  5537. finish();
  5538. } else {
  5539. // asynchronous timeout, like `timer.setTimeout(function (done) {...; done(); }, delay)`
  5540. timeout.callback(finish);
  5541. }
  5542. } catch (err) {
  5543. // silently ignore errors thrown by the callback
  5544. finish();
  5545. }
  5546. }
  5547. /**
  5548. * Remove all timeouts occurring before or on the provided time from the
  5549. * queue and return them.
  5550. * @param {number} time A timestamp
  5551. * @returns {Array} returns an array containing all expired timeouts
  5552. * @private
  5553. */
  5554. function _getExpiredTimeouts(time) {
  5555. var i = 0;
  5556. while (i < timeouts.length && ((timeouts[i].time <= time) || !isFinite(timeouts[i].time))) {
  5557. i++;
  5558. }
  5559. var expired = timeouts.splice(0, i);
  5560. if (deterministic == false) {
  5561. // the array with expired timeouts is in deterministic order
  5562. // shuffle them
  5563. util.shuffle(expired);
  5564. }
  5565. return expired;
  5566. }
  5567. /**
  5568. * Reschedule all queued timeouts
  5569. * @private
  5570. */
  5571. function _schedule() {
  5572. // do not _schedule when there are timeouts in progress
  5573. // this can be the case with async timeouts in discrete time.
  5574. // _schedule will be executed again when all async timeouts are finished.
  5575. if (rate === DISCRETE && Object.keys(current).length > 0) {
  5576. return;
  5577. }
  5578. var next = timeouts[0];
  5579. // cancel timer when running
  5580. if (timeoutId) {
  5581. clearTimeout(timeoutId);
  5582. timeoutId = null;
  5583. }
  5584. if (running && next) {
  5585. // schedule next timeout
  5586. var time = next.time;
  5587. var delay = time - timer.now();
  5588. var realDelay = (rate === DISCRETE) ? 0 : delay / rate;
  5589. function onTimeout() {
  5590. // when running in discrete time, update the hyperTime to the time
  5591. // of the current event
  5592. if (rate === DISCRETE) {
  5593. hyperTime = (time > hyperTime && isFinite(time)) ? time : hyperTime;
  5594. }
  5595. // grab all expired timeouts from the queue
  5596. var expired = _getExpiredTimeouts(time);
  5597. // note: expired.length can never be zero (on every change of the queue, we reschedule)
  5598. // execute all expired timeouts
  5599. if (rate === DISCRETE) {
  5600. // in discrete time, we execute all expired timeouts serially,
  5601. // and wait for their completion in order to guarantee deterministic
  5602. // order of execution
  5603. function next() {
  5604. var timeout = expired.shift();
  5605. if (timeout) {
  5606. _execTimeout(timeout, next);
  5607. }
  5608. else {
  5609. // schedule the next round
  5610. _schedule();
  5611. }
  5612. }
  5613. next();
  5614. }
  5615. else {
  5616. // in continuous time, we fire all timeouts in parallel,
  5617. // and don't await their completion (they can do async operations)
  5618. expired.forEach(_execTimeout);
  5619. // schedule the next round
  5620. _schedule();
  5621. }
  5622. }
  5623. timeoutId = setTimeout(onTimeout, Math.round(realDelay));
  5624. // Note: Math.round(realDelay) is to defeat a bug in node.js v0.10.30,
  5625. // see https://github.com/joyent/node/issues/8065
  5626. }
  5627. }
  5628. Object.defineProperty(timer, 'running', {
  5629. get: function () {
  5630. return running;
  5631. }
  5632. });
  5633. timer.config(options); // apply options
  5634. timer.setTime(util.systemNow()); // set time as current real time
  5635. timer.continue(); // start the timer
  5636. return timer;
  5637. }
  5638. module.exports = hypertimer;
  5639. /***/ },
  5640. /* 34 */
  5641. /***/ function(module, exports, __webpack_require__) {
  5642. /**
  5643. * Module dependencies.
  5644. */
  5645. var global = (function() { return this; })();
  5646. /**
  5647. * WebSocket constructor.
  5648. */
  5649. var WebSocket = global.WebSocket || global.MozWebSocket;
  5650. /**
  5651. * Module exports.
  5652. */
  5653. module.exports = WebSocket ? ws : null;
  5654. /**
  5655. * WebSocket constructor.
  5656. *
  5657. * The third `opts` options object gets ignored in web browsers, since it's
  5658. * non-standard, and throws a TypeError if passed to the constructor.
  5659. * See: https://github.com/einaros/ws/issues/227
  5660. *
  5661. * @param {String} uri
  5662. * @param {Array} protocols (optional)
  5663. * @param {Object) opts (optional)
  5664. * @api public
  5665. */
  5666. function ws(uri, protocols, opts) {
  5667. var instance;
  5668. if (protocols) {
  5669. instance = new WebSocket(uri, protocols);
  5670. } else {
  5671. instance = new WebSocket(uri);
  5672. }
  5673. return instance;
  5674. }
  5675. if (WebSocket) ws.prototype = WebSocket.prototype;
  5676. /***/ },
  5677. /* 35 */
  5678. /***/ function(module, exports, __webpack_require__) {
  5679. 'use strict';
  5680. var asap = __webpack_require__(72)
  5681. module.exports = Promise;
  5682. function Promise(fn) {
  5683. if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new')
  5684. if (typeof fn !== 'function') throw new TypeError('not a function')
  5685. var state = null
  5686. var value = null
  5687. var deferreds = []
  5688. var self = this
  5689. this.then = function(onFulfilled, onRejected) {
  5690. return new self.constructor(function(resolve, reject) {
  5691. handle(new Handler(onFulfilled, onRejected, resolve, reject))
  5692. })
  5693. }
  5694. function handle(deferred) {
  5695. if (state === null) {
  5696. deferreds.push(deferred)
  5697. return
  5698. }
  5699. asap(function() {
  5700. var cb = state ? deferred.onFulfilled : deferred.onRejected
  5701. if (cb === null) {
  5702. (state ? deferred.resolve : deferred.reject)(value)
  5703. return
  5704. }
  5705. var ret
  5706. try {
  5707. ret = cb(value)
  5708. }
  5709. catch (e) {
  5710. deferred.reject(e)
  5711. return
  5712. }
  5713. deferred.resolve(ret)
  5714. })
  5715. }
  5716. function resolve(newValue) {
  5717. try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
  5718. if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.')
  5719. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  5720. var then = newValue.then
  5721. if (typeof then === 'function') {
  5722. doResolve(then.bind(newValue), resolve, reject)
  5723. return
  5724. }
  5725. }
  5726. state = true
  5727. value = newValue
  5728. finale()
  5729. } catch (e) { reject(e) }
  5730. }
  5731. function reject(newValue) {
  5732. state = false
  5733. value = newValue
  5734. finale()
  5735. }
  5736. function finale() {
  5737. for (var i = 0, len = deferreds.length; i < len; i++)
  5738. handle(deferreds[i])
  5739. deferreds = null
  5740. }
  5741. doResolve(fn, resolve, reject)
  5742. }
  5743. function Handler(onFulfilled, onRejected, resolve, reject){
  5744. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null
  5745. this.onRejected = typeof onRejected === 'function' ? onRejected : null
  5746. this.resolve = resolve
  5747. this.reject = reject
  5748. }
  5749. /**
  5750. * Take a potentially misbehaving resolver function and make sure
  5751. * onFulfilled and onRejected are only called once.
  5752. *
  5753. * Makes no guarantees about asynchrony.
  5754. */
  5755. function doResolve(fn, onFulfilled, onRejected) {
  5756. var done = false;
  5757. try {
  5758. fn(function (value) {
  5759. if (done) return
  5760. done = true
  5761. onFulfilled(value)
  5762. }, function (reason) {
  5763. if (done) return
  5764. done = true
  5765. onRejected(reason)
  5766. })
  5767. } catch (ex) {
  5768. if (done) return
  5769. done = true
  5770. onRejected(ex)
  5771. }
  5772. }
  5773. /***/ },
  5774. /* 36 */
  5775. /***/ function(module, exports, __webpack_require__) {
  5776. 'use strict';
  5777. var Promise = __webpack_require__(35)
  5778. var asap = __webpack_require__(72)
  5779. module.exports = Promise
  5780. Promise.prototype.done = function (onFulfilled, onRejected) {
  5781. var self = arguments.length ? this.then.apply(this, arguments) : this
  5782. self.then(null, function (err) {
  5783. asap(function () {
  5784. throw err
  5785. })
  5786. })
  5787. }
  5788. /***/ },
  5789. /* 37 */
  5790. /***/ function(module, exports, __webpack_require__) {
  5791. 'use strict';
  5792. //This file contains the ES6 extensions to the core Promises/A+ API
  5793. var Promise = __webpack_require__(35)
  5794. var asap = __webpack_require__(72)
  5795. module.exports = Promise
  5796. /* Static Functions */
  5797. function ValuePromise(value) {
  5798. this.then = function (onFulfilled) {
  5799. if (typeof onFulfilled !== 'function') return this
  5800. return new Promise(function (resolve, reject) {
  5801. asap(function () {
  5802. try {
  5803. resolve(onFulfilled(value))
  5804. } catch (ex) {
  5805. reject(ex);
  5806. }
  5807. })
  5808. })
  5809. }
  5810. }
  5811. ValuePromise.prototype = Promise.prototype
  5812. var TRUE = new ValuePromise(true)
  5813. var FALSE = new ValuePromise(false)
  5814. var NULL = new ValuePromise(null)
  5815. var UNDEFINED = new ValuePromise(undefined)
  5816. var ZERO = new ValuePromise(0)
  5817. var EMPTYSTRING = new ValuePromise('')
  5818. Promise.resolve = function (value) {
  5819. if (value instanceof Promise) return value
  5820. if (value === null) return NULL
  5821. if (value === undefined) return UNDEFINED
  5822. if (value === true) return TRUE
  5823. if (value === false) return FALSE
  5824. if (value === 0) return ZERO
  5825. if (value === '') return EMPTYSTRING
  5826. if (typeof value === 'object' || typeof value === 'function') {
  5827. try {
  5828. var then = value.then
  5829. if (typeof then === 'function') {
  5830. return new Promise(then.bind(value))
  5831. }
  5832. } catch (ex) {
  5833. return new Promise(function (resolve, reject) {
  5834. reject(ex)
  5835. })
  5836. }
  5837. }
  5838. return new ValuePromise(value)
  5839. }
  5840. Promise.all = function (arr) {
  5841. var args = Array.prototype.slice.call(arr)
  5842. return new Promise(function (resolve, reject) {
  5843. if (args.length === 0) return resolve([])
  5844. var remaining = args.length
  5845. function res(i, val) {
  5846. try {
  5847. if (val && (typeof val === 'object' || typeof val === 'function')) {
  5848. var then = val.then
  5849. if (typeof then === 'function') {
  5850. then.call(val, function (val) { res(i, val) }, reject)
  5851. return
  5852. }
  5853. }
  5854. args[i] = val
  5855. if (--remaining === 0) {
  5856. resolve(args);
  5857. }
  5858. } catch (ex) {
  5859. reject(ex)
  5860. }
  5861. }
  5862. for (var i = 0; i < args.length; i++) {
  5863. res(i, args[i])
  5864. }
  5865. })
  5866. }
  5867. Promise.reject = function (value) {
  5868. return new Promise(function (resolve, reject) {
  5869. reject(value);
  5870. });
  5871. }
  5872. Promise.race = function (values) {
  5873. return new Promise(function (resolve, reject) {
  5874. values.forEach(function(value){
  5875. Promise.resolve(value).then(resolve, reject);
  5876. })
  5877. });
  5878. }
  5879. /* Prototype Methods */
  5880. Promise.prototype['catch'] = function (onRejected) {
  5881. return this.then(null, onRejected);
  5882. }
  5883. /***/ },
  5884. /* 38 */
  5885. /***/ function(module, exports, __webpack_require__) {
  5886. 'use strict';
  5887. //This file contains then/promise specific extensions that are only useful for node.js interop
  5888. var Promise = __webpack_require__(35)
  5889. var asap = __webpack_require__(72)
  5890. module.exports = Promise
  5891. /* Static Functions */
  5892. Promise.denodeify = function (fn, argumentCount) {
  5893. argumentCount = argumentCount || Infinity
  5894. return function () {
  5895. var self = this
  5896. var args = Array.prototype.slice.call(arguments)
  5897. return new Promise(function (resolve, reject) {
  5898. while (args.length && args.length > argumentCount) {
  5899. args.pop()
  5900. }
  5901. args.push(function (err, res) {
  5902. if (err) reject(err)
  5903. else resolve(res)
  5904. })
  5905. fn.apply(self, args)
  5906. })
  5907. }
  5908. }
  5909. Promise.nodeify = function (fn) {
  5910. return function () {
  5911. var args = Array.prototype.slice.call(arguments)
  5912. var callback = typeof args[args.length - 1] === 'function' ? args.pop() : null
  5913. var ctx = this
  5914. try {
  5915. return fn.apply(this, arguments).nodeify(callback, ctx)
  5916. } catch (ex) {
  5917. if (callback === null || typeof callback == 'undefined') {
  5918. return new Promise(function (resolve, reject) { reject(ex) })
  5919. } else {
  5920. asap(function () {
  5921. callback.call(ctx, ex)
  5922. })
  5923. }
  5924. }
  5925. }
  5926. }
  5927. Promise.prototype.nodeify = function (callback, ctx) {
  5928. if (typeof callback != 'function') return this
  5929. this.then(function (value) {
  5930. asap(function () {
  5931. callback.call(ctx, null, value)
  5932. })
  5933. }, function (err) {
  5934. asap(function () {
  5935. callback.call(ctx, err)
  5936. })
  5937. })
  5938. }
  5939. /***/ },
  5940. /* 39 */
  5941. /***/ function(module, exports, __webpack_require__) {
  5942. 'use strict';
  5943. var Babbler = __webpack_require__(49);
  5944. var Tell = __webpack_require__(56);
  5945. var Listen = __webpack_require__(57);
  5946. var Then = __webpack_require__(58);
  5947. var Decision = __webpack_require__(59);
  5948. var IIf = __webpack_require__(60);
  5949. /**
  5950. * Create a new babbler
  5951. * @param {String} id
  5952. * @return {Babbler} babbler
  5953. */
  5954. exports.babbler = function (id) {
  5955. return new Babbler(id);
  5956. };
  5957. /**
  5958. * Create a control flow starting with a tell block
  5959. * @param {* | Function} [message] A static message or callback function
  5960. * returning a message dynamically.
  5961. * When `message` is a function, it will be
  5962. * invoked as callback(message, context),
  5963. * where `message` is the output from the
  5964. * previous block in the chain, and `context` is
  5965. * an object where state can be stored during a
  5966. * conversation.
  5967. * @return {Tell} tell
  5968. */
  5969. exports.tell = function (message) {
  5970. return new Tell(message);
  5971. };
  5972. /**
  5973. * Send a question, listen for a response.
  5974. * Creates two blocks: Tell and Listen.
  5975. * This is equivalent of doing `babble.tell(message).listen(callback)`
  5976. * @param {* | Function} message
  5977. * @param {Function} [callback] Invoked as callback(message, context),
  5978. * where `message` is the just received message,
  5979. * and `context` is an object where state can be
  5980. * stored during a conversation. This is equivalent
  5981. * of doing `listen().then(callback)`
  5982. * @return {Block} block Last block in the created control flow
  5983. */
  5984. exports.ask = function (message, callback) {
  5985. return exports
  5986. .tell(message)
  5987. .listen(callback);
  5988. };
  5989. /**
  5990. * Create a decision block and chain it to the current block.
  5991. *
  5992. * Syntax:
  5993. *
  5994. * decide(choices)
  5995. * decide(decision, choices)
  5996. *
  5997. * Where:
  5998. *
  5999. * {Function | Object} [decision]
  6000. * When a `decision` function is provided, the
  6001. * function is invoked as decision(message, context),
  6002. * where `message` is the output from the previous
  6003. * block in the chain, and `context` is an object
  6004. * where state can be stored during a conversation.
  6005. * The function must return the id for the next
  6006. * block in the control flow, which must be
  6007. * available in the provided `choices`.
  6008. * If `decision` is not provided, the next block
  6009. * will be mapped directly from the message.
  6010. * {Object.<String, Block>} choices
  6011. * A map with the possible next blocks in the flow
  6012. * The next block is selected by the id returned
  6013. * by the decision function.
  6014. *
  6015. * There is one special id for choices: 'default'. This id is called when either
  6016. * the decision function returns an id which does not match any of the available
  6017. * choices.
  6018. *
  6019. * @param {Function | Object} arg1 Can be {function} decision or {Object} choices
  6020. * @param {Object} [arg2] choices
  6021. * @return {Block} decision The created decision block
  6022. */
  6023. exports.decide = function (arg1, arg2) {
  6024. // TODO: test arguments.length > 2
  6025. return new Decision(arg1, arg2);
  6026. };
  6027. /**
  6028. * Listen for a message.
  6029. *
  6030. * Optionally a callback function can be provided, which is equivalent of
  6031. * doing `listen().then(callback)`.
  6032. *
  6033. * @param {Function} [callback] Invoked as callback(message, context),
  6034. * where `message` is the just received message,
  6035. * and `context` is an object where state can be
  6036. * stored during a conversation. This is equivalent
  6037. * of doing `listen().then(callback)`
  6038. * @return {Block} Returns the created Listen block
  6039. */
  6040. exports.listen = function(callback) {
  6041. var block = new Listen();
  6042. if (callback) {
  6043. return block.then(callback);
  6044. }
  6045. return block;
  6046. };
  6047. /**
  6048. * Create a control flow starting with a Then block
  6049. * @param {Function} callback Invoked as callback(message, context),
  6050. * where `message` is the output from the previous
  6051. * block in the chain, and `context` is an object
  6052. * where state can be stored during a conversation.
  6053. * @return {Then} then
  6054. */
  6055. exports.then = function (callback) {
  6056. return new Then(callback);
  6057. };
  6058. /**
  6059. * IIf
  6060. * Create an iif block, which checks a condition and continues either with
  6061. * the trueBlock or the falseBlock. The input message is passed to the next
  6062. * block in the flow.
  6063. *
  6064. * Can be used as follows:
  6065. * - When `condition` evaluates true:
  6066. * - when `trueBlock` is provided, the flow continues with `trueBlock`
  6067. * - else, when there is a block connected to the IIf block, the flow continues
  6068. * with that block.
  6069. * - When `condition` evaluates false:
  6070. * - when `falseBlock` is provided, the flow continues with `falseBlock`
  6071. *
  6072. * Syntax:
  6073. *
  6074. * new IIf(condition, trueBlock)
  6075. * new IIf(condition, trueBlock [, falseBlock])
  6076. * new IIf(condition).then(...)
  6077. *
  6078. * @param {Function | RegExp | *} condition A condition returning true or false
  6079. * In case of a function,
  6080. * the function is invoked as
  6081. * `condition(message, context)` and
  6082. * must return a boolean. In case of
  6083. * a RegExp, condition will be tested
  6084. * to return true. In other cases,
  6085. * non-strict equality is tested on
  6086. * the input.
  6087. * @param {Block} [trueBlock]
  6088. * @param {Block} [falseBlock]
  6089. * @returns {Block}
  6090. */
  6091. exports.iif = function (condition, trueBlock, falseBlock) {
  6092. return new IIf(condition, trueBlock, falseBlock);
  6093. };
  6094. // export the babbler prototype
  6095. exports.Babbler = Babbler;
  6096. // export all flow blocks
  6097. exports.block = {
  6098. Block: __webpack_require__(61),
  6099. Then: __webpack_require__(58),
  6100. Decision: __webpack_require__(59),
  6101. IIf: __webpack_require__(60),
  6102. Listen: __webpack_require__(57),
  6103. Tell: __webpack_require__(56)
  6104. };
  6105. // export messagebus interfaces
  6106. exports.messagebus = __webpack_require__(50);
  6107. /**
  6108. * Babblify an actor. The babblified actor will be extended with functions
  6109. * `ask`, `tell`, and `listen`.
  6110. *
  6111. * Babble expects that messages sent via `actor.send(to, message)` will be
  6112. * delivered by the recipient on a function `actor.receive(from, message)`.
  6113. * Babble replaces the original `receive` with a new one, which is used to
  6114. * listen for all incoming messages. Messages ignored by babble are propagated
  6115. * to the original `receive` function.
  6116. *
  6117. * The actor can be restored in its original state using `unbabblify(actor)`.
  6118. *
  6119. * @param {Object} actor The actor to be babblified. Must be an object
  6120. * containing functions `send(to, message)` and
  6121. * `receive(from, message)`.
  6122. * @param {Object} [params] Optional parameters. Can contain properties:
  6123. * - id: string The id for the babbler
  6124. * - send: string The name of an alternative
  6125. * send function available on
  6126. * the actor.
  6127. * - receive: string The name of an alternative
  6128. * receive function available
  6129. * on the actor.
  6130. * @returns {Object} Returns the babblified actor.
  6131. */
  6132. exports.babblify = function (actor, params) {
  6133. var babblerId;
  6134. if (params && params.id !== undefined) {
  6135. babblerId = params.id;
  6136. }
  6137. else if (actor.id !== undefined) {
  6138. babblerId = actor.id
  6139. }
  6140. else {
  6141. throw new Error('Id missing. Ensure that either actor has a property "id", ' +
  6142. 'or provide an id as a property in second argument params')
  6143. }
  6144. // validate actor
  6145. ['ask', 'tell', 'listen'].forEach(function (prop) {
  6146. if (actor[prop] !== undefined) {
  6147. throw new Error('Conflict: actor already has a property "' + prop + '"');
  6148. }
  6149. });
  6150. var sendName = params && params.send || 'send';
  6151. if (typeof actor[sendName] !== 'function') {
  6152. throw new Error('Missing function. ' +
  6153. 'Function "' + sendName + '(to, message)" expected on actor or on params');
  6154. }
  6155. // create a new babbler
  6156. var babbler = exports.babbler(babblerId);
  6157. // attach receive function to the babbler
  6158. var receiveName = params && params.receive || 'receive';
  6159. var receiveOriginal = actor.hasOwnProperty(receiveName) ? actor[receiveName] : null;
  6160. if (receiveOriginal) {
  6161. actor[receiveName] = function (from, message) {
  6162. babbler._receive(message);
  6163. receiveOriginal.call(actor, from, message);
  6164. };
  6165. }
  6166. else {
  6167. actor[receiveName] = function (from, message) {
  6168. babbler._receive(message);
  6169. };
  6170. }
  6171. // attach send function to the babbler
  6172. babbler.send = function (to, message) {
  6173. // FIXME: there should be no need to send a message on next tick
  6174. setTimeout(function () {
  6175. actor[sendName](to, message)
  6176. }, 0)
  6177. };
  6178. // attach babbler functions and properties to the actor
  6179. actor.__babbler__ = {
  6180. babbler: babbler,
  6181. receive: receiveOriginal,
  6182. receiveName: receiveName
  6183. };
  6184. actor.ask = babbler.ask.bind(babbler);
  6185. actor.tell = babbler.tell.bind(babbler);
  6186. actor.listen = babbler.listen.bind(babbler);
  6187. actor.listenOnce = babbler.listenOnce.bind(babbler);
  6188. return actor;
  6189. };
  6190. /**
  6191. * Unbabblify an actor.
  6192. * @param {Object} actor
  6193. * @return {Object} Returns the unbabblified actor.
  6194. */
  6195. exports.unbabblify = function (actor) {
  6196. var __babbler__ = actor.__babbler__;
  6197. if (__babbler__) {
  6198. delete actor.__babbler__;
  6199. delete actor.ask;
  6200. delete actor.tell;
  6201. delete actor.listen;
  6202. delete actor.listenOnce;
  6203. delete actor[__babbler__.receiveName];
  6204. // restore any original receive method
  6205. if (__babbler__.receive) {
  6206. actor[__babbler__.receiveName] = __babbler__.receive;
  6207. }
  6208. }
  6209. return actor;
  6210. };
  6211. /***/ },
  6212. /* 40 */
  6213. /***/ function(module, exports, __webpack_require__) {
  6214. var WebSocket = __webpack_require__(76);
  6215. var WebSocketServer = __webpack_require__(76).Server;
  6216. var uuid = __webpack_require__(74);
  6217. var Promise = __webpack_require__(41);
  6218. var requestify = __webpack_require__(51);
  6219. var Peer = __webpack_require__(52);
  6220. /**
  6221. * Host
  6222. * @param {Object} [options] Available options: see Host.config
  6223. */
  6224. function Host(options) {
  6225. var me = this;
  6226. // peers and cached peer addresses
  6227. this.peers = {}; // local peers
  6228. this.addresses = {}; // cached addresses of peers located on other hosts
  6229. // pubsub
  6230. this.channels = {}; // keys are the channels, values are arrays with callbacks of subscribers
  6231. // default options
  6232. this.options = {
  6233. reconnectTimeout: 5 * 60 * 1000, // give up reconnecting after 5 minutes
  6234. reconnectDelay: 1000, // try reconnecting after one second
  6235. reconnectDecay: 2
  6236. };
  6237. // server properties
  6238. this.server = null;
  6239. this.address = null;
  6240. this.port = null;
  6241. this.connections = {}; // List with open connections, key is the url and value is the connection
  6242. this.timers = {}; // reconnect timers
  6243. /**
  6244. * Send a message from one peer to another
  6245. * @param {string} from Id of the sending peer
  6246. * @param {string} to Id of the receiving peer
  6247. * @param {*} message JSON message
  6248. * @returns {Promise.<null, Error>} Resolves when sent
  6249. */
  6250. this.send = function (from, to, message) {
  6251. // see if the peer lives on the same host
  6252. var peer = me.peers[to];
  6253. if (peer) {
  6254. peer.emit('message', from, message);
  6255. return Promise.resolve(null);
  6256. }
  6257. // find the remote host where the recipient is located
  6258. return me.find(to)
  6259. .then(function (url) {
  6260. var conn = me.connections[url];
  6261. if (conn) {
  6262. var request = {
  6263. method: 'send',
  6264. params: {
  6265. from: from,
  6266. to: to,
  6267. message: message
  6268. }
  6269. };
  6270. // TODO: there is a maximum callstack issue when queuing a lot of notifications
  6271. return conn.request(request) // the send request returns null
  6272. //return conn.notify(request) // the send request returns null
  6273. .catch(function (err) {
  6274. // FIXME: use a protocol for errors, use error code
  6275. if (err.toString().indexOf('Error: Peer not found') === 0) {
  6276. // this peer was deleted. Remove it from cache
  6277. delete me.addresses[to];
  6278. throw _peerNotFoundError(to);
  6279. }
  6280. })
  6281. }
  6282. else {
  6283. throw _peerUnreachable(to, url);
  6284. }
  6285. });
  6286. };
  6287. this.config(options);
  6288. }
  6289. /**
  6290. * Apply configuration options to the host, and/or retrieve the current
  6291. * configuration.
  6292. * @param {Object} [options] Available options:
  6293. * - networkId An id for the distribus
  6294. * network. A Host can only
  6295. * connect to other hosts with
  6296. * the same id. networkId cannot
  6297. * be changed once set.
  6298. * - reconnectTimeout Timeout in milliseconds for
  6299. * giving up reconnecting.
  6300. * 5 minutes by default
  6301. * - reconnectDelay Initial delay for trying to
  6302. * reconnect. for consecutive
  6303. * reconnect trials, the delay
  6304. * decays with a factor
  6305. * `reconnectDecay`.
  6306. * 1 second by default.
  6307. * - reconnectDecay Decay for the reconnect
  6308. * delay. 2 by default.
  6309. * @return {Object} Returns the current configuration
  6310. */
  6311. Host.prototype.config = function (options) {
  6312. // apply new options
  6313. if (options) {
  6314. _merge(this.options, options);
  6315. // apply networkId
  6316. if (options.networkId) {
  6317. if (this.networkId !== null) {
  6318. this.networkId = options.networkId;
  6319. }
  6320. else {
  6321. throw new Error('Cannot replace networkId once set');
  6322. }
  6323. }
  6324. }
  6325. // return a copy of the options
  6326. return _merge({}, this.options);
  6327. };
  6328. /**
  6329. * Create a new peer.
  6330. * Throws an error when a peer with the same id already exists on this host.
  6331. * Does not check whether this id exists on any remote host (use Host.find(id)
  6332. * to validate this before creating a peer, or even better, use a uuid to
  6333. * prevent id collisions).
  6334. * @param {string} id The id for the new peer
  6335. * @return {Peer} Returns the created peer
  6336. */
  6337. Host.prototype.create = function (id) {
  6338. if (id in this.peers) {
  6339. throw new Error('Id already exists (id: ' + id +')');
  6340. }
  6341. var peer = new Peer(id, this.send);
  6342. this.peers[id] = peer;
  6343. return peer;
  6344. };
  6345. /**
  6346. * Remove a peer from the host
  6347. * @param {Peer | string} peer A peer or the id of a peer
  6348. */
  6349. Host.prototype.remove = function (peer) {
  6350. if (peer instanceof Peer) { // a peer instance
  6351. delete this.peers[peer.id];
  6352. }
  6353. else if (peer) { // a string with the peers id
  6354. delete this.peers[peer];
  6355. }
  6356. };
  6357. /**
  6358. * Get a local peer by its id
  6359. * @param {string} id The id of an existing peer
  6360. * @return {Peer | null} returns the peer, or returns null when not existing.
  6361. */
  6362. Host.prototype.get = function (id) {
  6363. return this.peers[id] || null;
  6364. };
  6365. /**
  6366. * Find the host of a peer by it's id
  6367. * @param {string} id Id of a peer
  6368. * @return {Promise.<string | null, Error>} The url of the peers host.
  6369. * Returns null if the found host has no url.
  6370. * Throws an error if not found.
  6371. */
  6372. Host.prototype.find = function (id) {
  6373. var me = this;
  6374. // check if this is a local peer
  6375. if (id in me.peers) {
  6376. return Promise.resolve(me.url || null);
  6377. }
  6378. // check if this id is already in cache
  6379. var url = me.addresses[id];
  6380. if (url) {
  6381. // yes, we already have the address
  6382. return Promise.resolve(url);
  6383. }
  6384. // search on other hosts
  6385. return new Promise(function (resolve, reject) {
  6386. // TODO: send requests in small batches, not all at once
  6387. // send a find request to a host
  6388. var found = false;
  6389. function _find(url) {
  6390. var conn = me.connections[url];
  6391. return conn.request({method: 'find', params: {id: id}})
  6392. .then(function (url) {
  6393. if (url && !found) {
  6394. // we found the peer
  6395. found = true;
  6396. // put this address in cache
  6397. // TODO: limit the number of cached addresses. When exceeding the limit, store on disk in a temporary db
  6398. me.addresses[id] = url;
  6399. // return the found url
  6400. resolve(url);
  6401. }
  6402. });
  6403. }
  6404. // ask all connected hosts if they host this peer
  6405. var results = Object.keys(me.connections).map(_find);
  6406. // if all requests are finished and the peer is not found, reject with an error
  6407. Promise.all(results)
  6408. .then(function () {
  6409. if (!found || results.length == 0) {
  6410. reject(_peerNotFoundError(id));
  6411. }
  6412. });
  6413. });
  6414. };
  6415. /**
  6416. * Start listening on a socket.
  6417. * @param {string} address
  6418. * @param {number} port
  6419. * @return {Promise.<Host, Error>} Returns itself when connected
  6420. */
  6421. Host.prototype.listen = function (address, port) {
  6422. var me = this;
  6423. return new Promise(function (resolve, reject) {
  6424. if (me.server) {
  6425. reject(new Error('Server already listening'));
  6426. return;
  6427. }
  6428. me.server = new WebSocketServer({port: port}, function () {
  6429. me.address = address;
  6430. me.port = port;
  6431. me.url = 'ws://' + address + ':' + port;
  6432. resolve(me);
  6433. });
  6434. me.server.on('connection', function (conn) {
  6435. conn = requestify(conn);
  6436. conn.onerror = function (err) {
  6437. // TODO: what to do with errors?
  6438. };
  6439. conn.onclose = function () {
  6440. // remove this connection from the connections list
  6441. // (we do not yet forget the cached peers)
  6442. var url = me._findUrl(conn);
  6443. delete me.connections[url];
  6444. me.timers[url] = setTimeout(function () {
  6445. delete me.timers[url];
  6446. // clear cache
  6447. me._forgetPeers(url);
  6448. }, me.options.reconnectTimeout);
  6449. };
  6450. conn.onrequest = function (request) {
  6451. return me._onRequest(conn, request);
  6452. };
  6453. });
  6454. me.server.on('error', function (err) {
  6455. reject(err)
  6456. });
  6457. });
  6458. };
  6459. /**
  6460. * Handle a request
  6461. * @param {WebSocket} conn
  6462. * @param {Object} request
  6463. * @returns {Promise}
  6464. * @private
  6465. */
  6466. Host.prototype._onRequest = function (conn, request) {
  6467. var me = this;
  6468. var url;
  6469. switch (request.method) {
  6470. case 'greeting':
  6471. url = request.params && request.params.url;
  6472. var networkId = request.params.networkId || null;
  6473. if (networkId === null || networkId === me.networkId) {
  6474. if (url && !(url in this.connections)) {
  6475. this.connections[url] = conn;
  6476. return this._broadcastJoin(url)
  6477. .then(function () {
  6478. return Promise.resolve({networkId: me.networkId})
  6479. });
  6480. }
  6481. else {
  6482. return Promise.resolve({networkId: me.networkId});
  6483. }
  6484. }
  6485. else {
  6486. return Promise.reject(new Error('Network id mismatch (' + networkId + ' !== ' + me.networkId + ')'));
  6487. }
  6488. case 'join':
  6489. url = request.params && request.params.url;
  6490. return this.join(url)
  6491. .then(function (host) {
  6492. return Promise.resolve();
  6493. });
  6494. case 'goodbye':
  6495. url = this._findUrl(conn);
  6496. this._forgetPeers(url);
  6497. this._disconnect(url);
  6498. return Promise.resolve('goodbye');
  6499. case 'hosts':
  6500. // connect to all newly retrieved urls
  6501. if (request.params && request.params.urls) {
  6502. this.join(request.params.urls);
  6503. }
  6504. // return a list with the urls of all known hosts
  6505. return Promise.resolve(Object.keys(this.connections));
  6506. case 'find': // find a peer
  6507. var id = request.params && request.params.id;
  6508. return Promise.resolve(this.peers[id] ? this.url : null);
  6509. case 'send':
  6510. var from = request.params && request.params.from;
  6511. var to = request.params && request.params.to;
  6512. var message = request.params && request.params.message;
  6513. // TODO: validate whether all parameters are there
  6514. var peer = this.peers[to];
  6515. if (peer) {
  6516. peer.emit('message', from, message);
  6517. return Promise.resolve(null);
  6518. }
  6519. else {
  6520. return Promise.reject(_peerNotFoundError(to).toString());
  6521. }
  6522. case 'publish':
  6523. var channel = request.params && request.params.channel;
  6524. var message = request.params && request.params.message;
  6525. this._publish(channel, message);
  6526. return Promise.resolve({
  6527. result: null,
  6528. error: null
  6529. });
  6530. case 'ping':
  6531. return Promise.resolve({
  6532. result: request.params,
  6533. error: null
  6534. });
  6535. default:
  6536. return Promise.reject('Unknown method "' + request.method + '"');
  6537. }
  6538. };
  6539. /**
  6540. * Find an url from a connection
  6541. * @param {WebSocket} conn
  6542. * @return {String | null} url
  6543. * @private
  6544. */
  6545. Host.prototype._findUrl = function (conn) {
  6546. // search by instance
  6547. for (var url in this.connections) {
  6548. if (this.connections.hasOwnProperty(url) && this.connections[url] === conn) {
  6549. return url;
  6550. }
  6551. }
  6552. return null;
  6553. };
  6554. /**
  6555. * Remove all cached peers of given
  6556. * @param {string} url Url of a host for which to forget the cached peers
  6557. * @private
  6558. */
  6559. Host.prototype._forgetPeers = function (url) {
  6560. // remove all cached peers
  6561. for (var id in this.addresses) {
  6562. if (this.addresses.hasOwnProperty(id) && this.addresses[id] === url) {
  6563. delete this.addresses[id];
  6564. }
  6565. }
  6566. };
  6567. /**
  6568. * Join an other Host.
  6569. * A host can only join another host when having the same id, or having no id
  6570. * defined. In the latter case, the host will orphan the id of the host it
  6571. * connects to.
  6572. * @param {string} url For example 'ws://localhost:3000'
  6573. * @return {Promise.<Host, Error>} Returns itself when joined
  6574. */
  6575. Host.prototype.join = function (url) {
  6576. var me = this;
  6577. if (url && !(url in me.connections)) {
  6578. return me._connect(url)
  6579. .then(function () {
  6580. // broadcast the join request to all known hosts
  6581. return me._broadcastJoin(url);
  6582. })
  6583. .then(function (urls) {
  6584. // return the host itself as last result in the promise chain
  6585. return me;
  6586. });
  6587. // TODO: handle connection error
  6588. }
  6589. else {
  6590. // already known url. ignore this join
  6591. // FIXME: it is possible that this connection is still being established
  6592. return Promise.resolve(me);
  6593. }
  6594. };
  6595. /**
  6596. * Open a connection to an other host and add the host to the list of connected
  6597. * hosts.
  6598. * @param {String} url
  6599. * @returns {Promise.<WebSocket, Error>} Returns the established connection
  6600. * @private
  6601. */
  6602. Host.prototype._connect = function(url) {
  6603. var me = this;
  6604. return new Promise(function (resolve, reject) {
  6605. // open a web socket
  6606. var conn = new WebSocket(url);
  6607. requestify(conn);
  6608. me.connections[url] = conn;
  6609. conn.onrequest = function (request) {
  6610. return me._onRequest(conn, request);
  6611. };
  6612. conn.onclose = function () {
  6613. if (me.connections[url]) {
  6614. // remove the connection from the list
  6615. delete me.connections[url];
  6616. // schedule reconnection
  6617. me._reconnect(url);
  6618. }
  6619. };
  6620. conn.onopen = function () {
  6621. // send a greeting with the hosts url
  6622. conn.request({method: 'greeting', params: { url: me.url, networkId: me.networkId } })
  6623. .then(function (params) {
  6624. me.networkId = params.networkId;
  6625. resolve(conn);
  6626. })
  6627. .catch(function (err) {
  6628. // greeting rejected
  6629. delete me.connections[url];
  6630. conn.close();
  6631. reject(err);
  6632. });
  6633. };
  6634. conn.onerror = function (err) {
  6635. delete me.connections[url];
  6636. reject(err);
  6637. conn.close();
  6638. };
  6639. });
  6640. };
  6641. /**
  6642. * Reconnect with a host
  6643. * @param {String} url Url of the host to which to reconnect
  6644. * @private
  6645. */
  6646. Host.prototype._reconnect = function (url) {
  6647. var me = this;
  6648. var start = new Date().valueOf();
  6649. function scheduleReconnect(delay, trial) {
  6650. me.timers[url] = setTimeout(function () {
  6651. delete me.timers[url];
  6652. var now = new Date().valueOf();
  6653. if (now - start < me.options.reconnectTimeout) {
  6654. // reconnect
  6655. me._connect(url)
  6656. .catch(function (err) {
  6657. // schedule next reconnect trial
  6658. scheduleReconnect(delay / me.options.reconnectDecay, trial + 1);
  6659. });
  6660. }
  6661. else {
  6662. // give up trying to reconnect
  6663. me._forgetPeers(url);
  6664. }
  6665. }, delay);
  6666. }
  6667. // schedule reconnection after a delay
  6668. scheduleReconnect(me.options.reconnectDelay, 0);
  6669. };
  6670. /**
  6671. * Forward a join message to all known hosts
  6672. * @param {string} url For example 'ws://localhost:3000'
  6673. * @return {Promise.<String[], Error>} returns the joined urls
  6674. */
  6675. Host.prototype._broadcastJoin = function (url) {
  6676. // TODO: implement a more efficient broadcast mechanism
  6677. var me = this;
  6678. var urls = Object.keys(me.connections)
  6679. .filter(function (u) {
  6680. return u !== url
  6681. });
  6682. function join (existingUrl) {
  6683. var conn = me.connections[existingUrl];
  6684. return conn.request({method: 'join', params: {'url': url}})
  6685. .catch(function (err) {
  6686. // TODO: what to do with failed requests? Right now we ignore them
  6687. })
  6688. .then(function () {
  6689. // return the url where the join is broadcasted to
  6690. return existingUrl;
  6691. })
  6692. }
  6693. // send a join request to all known hosts
  6694. return Promise.all(urls.map(join));
  6695. };
  6696. /**
  6697. * Stop listening on currently a socket
  6698. * @return {Promise.<Host, Error>} Returns itself
  6699. */
  6700. Host.prototype.close = function () {
  6701. var me = this;
  6702. // TODO: create a flag while closing? and opening?
  6703. if (this.server) {
  6704. // close the host, and clean up cache
  6705. function closeHost() {
  6706. // close the host itself
  6707. me.addresses = {};
  6708. if (me.server) {
  6709. me.server.close();
  6710. me.server = null;
  6711. me.address = null;
  6712. me.port = null;
  6713. me.url = null;
  6714. }
  6715. return me;
  6716. }
  6717. // close all connections
  6718. var urls = Object.keys(this.connections);
  6719. return Promise.all(urls.map(function (url) {
  6720. return me._disconnect(url);
  6721. })).then(closeHost);
  6722. }
  6723. else {
  6724. // no socket open. resolve immediately
  6725. Promise.resolve(this);
  6726. }
  6727. };
  6728. /**
  6729. * Close the connection with a host. Note: peers are not removed from cache
  6730. * @param {string} url Url of a connected host
  6731. * @return {Promise.<undefined, Error>} Resolves a promise when closed
  6732. * @private
  6733. */
  6734. Host.prototype._disconnect = function (url) {
  6735. var conn = this.connections[url];
  6736. if (conn) {
  6737. delete this.connections[url];
  6738. if (this.timers[url]) {
  6739. clearTimeout(this.timers[url]);
  6740. delete this.timers[url];
  6741. }
  6742. // send a goodbye message
  6743. return conn.request({method: 'goodbye'})
  6744. .catch(function (err) {
  6745. // ignore failing to send goodbye
  6746. })
  6747. // then close the connection
  6748. .then(function () {
  6749. conn.close();
  6750. });
  6751. }
  6752. else {
  6753. Promise.resolve();
  6754. }
  6755. };
  6756. /**
  6757. * Publish a message via a channel. All listeners subscribed to this channel
  6758. * will be triggered, both listeners on this host as well as connected hosts.
  6759. * @param {string} channel The name of the channel
  6760. * @param {*} message A message, can be any type. Must be serializable JSON.
  6761. */
  6762. Host.prototype.publish = function (channel, message) {
  6763. // trigger local subscribers
  6764. this._publish(channel, message);
  6765. // send the message to all connected hosts
  6766. for (var url in this.connections) {
  6767. if (this.connections.hasOwnProperty(url)) {
  6768. var connection = this.connections[url];
  6769. connection.notify({
  6770. method: 'publish',
  6771. params: {
  6772. channel: channel,
  6773. message: message
  6774. }
  6775. });
  6776. }
  6777. }
  6778. // TODO: improve efficiency by having the hosts share the channels for which
  6779. // they have subscribers, so we only have to send a message to a
  6780. // particular host when it has subscribers to the channel.
  6781. };
  6782. /**
  6783. * Publish a channel to all subscribers on this host.
  6784. * @param {string} channel The name of the channel
  6785. * @param {*} message A message, can be any type. Must be serializable JSON.
  6786. * @private
  6787. */
  6788. Host.prototype._publish = function (channel, message) {
  6789. // trigger local subscribers
  6790. var callbacks = this.channels[channel];
  6791. if (callbacks) {
  6792. callbacks.forEach(function (callback) {
  6793. callback(message);
  6794. });
  6795. }
  6796. };
  6797. /**
  6798. * Subscribe to a channel.
  6799. * @param {string} channel The name of the channel
  6800. * @param {function} callback Called as callback(message)
  6801. */
  6802. Host.prototype.subscribe = function (channel, callback) {
  6803. // TODO: implement support for wildcards, like subscribing to "foo.*" or something like that
  6804. var callbacks = this.channels[channel];
  6805. if (!callbacks) {
  6806. callbacks = [];
  6807. this.channels[channel] = callbacks;
  6808. }
  6809. callbacks.push(callback);
  6810. };
  6811. /**
  6812. * Unsubscribe from a channel.
  6813. * @param {string} channel The name of the channel
  6814. * @param {function} callback A callback used before to subscribe
  6815. */
  6816. Host.prototype.unsubscribe = function (channel, callback) {
  6817. var callbacks = this.channels[channel];
  6818. if (callbacks) {
  6819. var index = callbacks.indexOf(callback);
  6820. if (index !== -1) {
  6821. callbacks.splice(index, 1);
  6822. if (callbacks.length === 0) {
  6823. delete this.channels[channel];
  6824. }
  6825. }
  6826. }
  6827. };
  6828. /**
  6829. * Merge object b into object a: copy all properties of b to a
  6830. * @param {Object} a
  6831. * @param {Object} b
  6832. * @return {Object} returns the merged a
  6833. * @private
  6834. */
  6835. function _merge (a, b) {
  6836. for (var prop in b) {
  6837. if (b.hasOwnProperty(prop)) {
  6838. a[prop] = b[prop];
  6839. }
  6840. }
  6841. return a;
  6842. }
  6843. /**
  6844. * Create an Error "Peer not found"
  6845. * @param {string} id The id of the peer
  6846. * @return {Error}
  6847. * @private
  6848. */
  6849. function _peerNotFoundError(id) {
  6850. return new Error('Peer not found (id: ' + id + ')');
  6851. }
  6852. /**
  6853. * Create an Error "Peer unreachable"
  6854. * @param {string} id The id of the peer
  6855. * @param {string} url Url of the peers host
  6856. * @return {Error}
  6857. * @private
  6858. */
  6859. function _peerUnreachable(id, url) {
  6860. return new Error('Peer unreachable (id: ' + id + ', url: ' + url + ')');
  6861. }
  6862. // TODO: implement a function list() which returns the id's of all peers in the system
  6863. module.exports = Host;
  6864. /***/ },
  6865. /* 41 */
  6866. /***/ function(module, exports, __webpack_require__) {
  6867. // Return a promise implementation.
  6868. module.exports = __webpack_require__(77);
  6869. /***/ },
  6870. /* 42 */
  6871. /***/ function(module, exports, __webpack_require__) {
  6872. var Stream = __webpack_require__(64);
  6873. var Response = __webpack_require__(53);
  6874. var Base64 = __webpack_require__(70);
  6875. var inherits = __webpack_require__(71);
  6876. var Request = module.exports = function (xhr, params) {
  6877. var self = this;
  6878. self.writable = true;
  6879. self.xhr = xhr;
  6880. self.body = [];
  6881. self.uri = (params.protocol || 'http:') + '//'
  6882. + params.host
  6883. + (params.port ? ':' + params.port : '')
  6884. + (params.path || '/')
  6885. ;
  6886. if (typeof params.withCredentials === 'undefined') {
  6887. params.withCredentials = true;
  6888. }
  6889. try { xhr.withCredentials = params.withCredentials }
  6890. catch (e) {}
  6891. if (params.responseType) try { xhr.responseType = params.responseType }
  6892. catch (e) {}
  6893. xhr.open(
  6894. params.method || 'GET',
  6895. self.uri,
  6896. true
  6897. );
  6898. xhr.onerror = function(event) {
  6899. self.emit('error', new Error('Network error'));
  6900. };
  6901. self._headers = {};
  6902. if (params.headers) {
  6903. var keys = objectKeys(params.headers);
  6904. for (var i = 0; i < keys.length; i++) {
  6905. var key = keys[i];
  6906. if (!self.isSafeRequestHeader(key)) continue;
  6907. var value = params.headers[key];
  6908. self.setHeader(key, value);
  6909. }
  6910. }
  6911. if (params.auth) {
  6912. //basic auth
  6913. this.setHeader('Authorization', 'Basic ' + Base64.btoa(params.auth));
  6914. }
  6915. var res = new Response;
  6916. res.on('close', function () {
  6917. self.emit('close');
  6918. });
  6919. res.on('ready', function () {
  6920. self.emit('response', res);
  6921. });
  6922. res.on('error', function (err) {
  6923. self.emit('error', err);
  6924. });
  6925. xhr.onreadystatechange = function () {
  6926. // Fix for IE9 bug
  6927. // SCRIPT575: Could not complete the operation due to error c00c023f
  6928. // It happens when a request is aborted, calling the success callback anyway with readyState === 4
  6929. if (xhr.__aborted) return;
  6930. res.handle(xhr);
  6931. };
  6932. };
  6933. inherits(Request, Stream);
  6934. Request.prototype.setHeader = function (key, value) {
  6935. this._headers[key.toLowerCase()] = value
  6936. };
  6937. Request.prototype.getHeader = function (key) {
  6938. return this._headers[key.toLowerCase()]
  6939. };
  6940. Request.prototype.removeHeader = function (key) {
  6941. delete this._headers[key.toLowerCase()]
  6942. };
  6943. Request.prototype.write = function (s) {
  6944. this.body.push(s);
  6945. };
  6946. Request.prototype.destroy = function (s) {
  6947. this.xhr.__aborted = true;
  6948. this.xhr.abort();
  6949. this.emit('close');
  6950. };
  6951. Request.prototype.end = function (s) {
  6952. if (s !== undefined) this.body.push(s);
  6953. var keys = objectKeys(this._headers);
  6954. for (var i = 0; i < keys.length; i++) {
  6955. var key = keys[i];
  6956. var value = this._headers[key];
  6957. if (isArray(value)) {
  6958. for (var j = 0; j < value.length; j++) {
  6959. this.xhr.setRequestHeader(key, value[j]);
  6960. }
  6961. }
  6962. else this.xhr.setRequestHeader(key, value)
  6963. }
  6964. if (this.body.length === 0) {
  6965. this.xhr.send('');
  6966. }
  6967. else if (typeof this.body[0] === 'string') {
  6968. this.xhr.send(this.body.join(''));
  6969. }
  6970. else if (isArray(this.body[0])) {
  6971. var body = [];
  6972. for (var i = 0; i < this.body.length; i++) {
  6973. body.push.apply(body, this.body[i]);
  6974. }
  6975. this.xhr.send(body);
  6976. }
  6977. else if (/Array/.test(Object.prototype.toString.call(this.body[0]))) {
  6978. var len = 0;
  6979. for (var i = 0; i < this.body.length; i++) {
  6980. len += this.body[i].length;
  6981. }
  6982. var body = new(this.body[0].constructor)(len);
  6983. var k = 0;
  6984. for (var i = 0; i < this.body.length; i++) {
  6985. var b = this.body[i];
  6986. for (var j = 0; j < b.length; j++) {
  6987. body[k++] = b[j];
  6988. }
  6989. }
  6990. this.xhr.send(body);
  6991. }
  6992. else if (isXHR2Compatible(this.body[0])) {
  6993. this.xhr.send(this.body[0]);
  6994. }
  6995. else {
  6996. var body = '';
  6997. for (var i = 0; i < this.body.length; i++) {
  6998. body += this.body[i].toString();
  6999. }
  7000. this.xhr.send(body);
  7001. }
  7002. };
  7003. // Taken from http://dxr.mozilla.org/mozilla/mozilla-central/content/base/src/nsXMLHttpRequest.cpp.html
  7004. Request.unsafeHeaders = [
  7005. "accept-charset",
  7006. "accept-encoding",
  7007. "access-control-request-headers",
  7008. "access-control-request-method",
  7009. "connection",
  7010. "content-length",
  7011. "cookie",
  7012. "cookie2",
  7013. "content-transfer-encoding",
  7014. "date",
  7015. "expect",
  7016. "host",
  7017. "keep-alive",
  7018. "origin",
  7019. "referer",
  7020. "te",
  7021. "trailer",
  7022. "transfer-encoding",
  7023. "upgrade",
  7024. "user-agent",
  7025. "via"
  7026. ];
  7027. Request.prototype.isSafeRequestHeader = function (headerName) {
  7028. if (!headerName) return false;
  7029. return indexOf(Request.unsafeHeaders, headerName.toLowerCase()) === -1;
  7030. };
  7031. var objectKeys = Object.keys || function (obj) {
  7032. var keys = [];
  7033. for (var key in obj) keys.push(key);
  7034. return keys;
  7035. };
  7036. var isArray = Array.isArray || function (xs) {
  7037. return Object.prototype.toString.call(xs) === '[object Array]';
  7038. };
  7039. var indexOf = function (xs, x) {
  7040. if (xs.indexOf) return xs.indexOf(x);
  7041. for (var i = 0; i < xs.length; i++) {
  7042. if (xs[i] === x) return i;
  7043. }
  7044. return -1;
  7045. };
  7046. var isXHR2Compatible = function (obj) {
  7047. if (typeof Blob !== 'undefined' && obj instanceof Blob) return true;
  7048. if (typeof ArrayBuffer !== 'undefined' && obj instanceof ArrayBuffer) return true;
  7049. if (typeof FormData !== 'undefined' && obj instanceof FormData) return true;
  7050. };
  7051. /***/ },
  7052. /* 43 */
  7053. /***/ function(module, exports, __webpack_require__) {
  7054. /* istanbul ignore else */
  7055. if (typeof Date.now === 'function') {
  7056. /**
  7057. * Helper function to get the current time
  7058. * @return {number} Current time
  7059. */
  7060. exports.systemNow = function () {
  7061. return Date.now();
  7062. }
  7063. }
  7064. else {
  7065. /**
  7066. * Helper function to get the current time
  7067. * @return {number} Current time
  7068. */
  7069. exports.systemNow = function () {
  7070. return new Date().valueOf();
  7071. }
  7072. }
  7073. /**
  7074. * Shuffle an array
  7075. *
  7076. * + Jonas Raoni Soares Silva
  7077. * @ http://jsfromhell.com/array/shuffle [v1.0]
  7078. *
  7079. * @param {Array} o Array to be shuffled
  7080. * @returns {Array} Returns the shuffled array
  7081. */
  7082. exports.shuffle = function (o){
  7083. for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
  7084. return o;
  7085. };
  7086. /***/ },
  7087. /* 44 */
  7088. /***/ function(module, exports, __webpack_require__) {
  7089. // Copyright Joyent, Inc. and other Node contributors.
  7090. //
  7091. // Permission is hereby granted, free of charge, to any person obtaining a
  7092. // copy of this software and associated documentation files (the
  7093. // "Software"), to deal in the Software without restriction, including
  7094. // without limitation the rights to use, copy, modify, merge, publish,
  7095. // distribute, sublicense, and/or sell copies of the Software, and to permit
  7096. // persons to whom the Software is furnished to do so, subject to the
  7097. // following conditions:
  7098. //
  7099. // The above copyright notice and this permission notice shall be included
  7100. // in all copies or substantial portions of the Software.
  7101. //
  7102. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  7103. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  7104. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  7105. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  7106. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  7107. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  7108. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  7109. function EventEmitter() {
  7110. this._events = this._events || {};
  7111. this._maxListeners = this._maxListeners || undefined;
  7112. }
  7113. module.exports = EventEmitter;
  7114. // Backwards-compat with node 0.10.x
  7115. EventEmitter.EventEmitter = EventEmitter;
  7116. EventEmitter.prototype._events = undefined;
  7117. EventEmitter.prototype._maxListeners = undefined;
  7118. // By default EventEmitters will print a warning if more than 10 listeners are
  7119. // added to it. This is a useful default which helps finding memory leaks.
  7120. EventEmitter.defaultMaxListeners = 10;
  7121. // Obviously not all Emitters should be limited to 10. This function allows
  7122. // that to be increased. Set to zero for unlimited.
  7123. EventEmitter.prototype.setMaxListeners = function(n) {
  7124. if (!isNumber(n) || n < 0 || isNaN(n))
  7125. throw TypeError('n must be a positive number');
  7126. this._maxListeners = n;
  7127. return this;
  7128. };
  7129. EventEmitter.prototype.emit = function(type) {
  7130. var er, handler, len, args, i, listeners;
  7131. if (!this._events)
  7132. this._events = {};
  7133. // If there is no 'error' event listener then throw.
  7134. if (type === 'error') {
  7135. if (!this._events.error ||
  7136. (isObject(this._events.error) && !this._events.error.length)) {
  7137. er = arguments[1];
  7138. if (er instanceof Error) {
  7139. throw er; // Unhandled 'error' event
  7140. }
  7141. throw TypeError('Uncaught, unspecified "error" event.');
  7142. }
  7143. }
  7144. handler = this._events[type];
  7145. if (isUndefined(handler))
  7146. return false;
  7147. if (isFunction(handler)) {
  7148. switch (arguments.length) {
  7149. // fast cases
  7150. case 1:
  7151. handler.call(this);
  7152. break;
  7153. case 2:
  7154. handler.call(this, arguments[1]);
  7155. break;
  7156. case 3:
  7157. handler.call(this, arguments[1], arguments[2]);
  7158. break;
  7159. // slower
  7160. default:
  7161. len = arguments.length;
  7162. args = new Array(len - 1);
  7163. for (i = 1; i < len; i++)
  7164. args[i - 1] = arguments[i];
  7165. handler.apply(this, args);
  7166. }
  7167. } else if (isObject(handler)) {
  7168. len = arguments.length;
  7169. args = new Array(len - 1);
  7170. for (i = 1; i < len; i++)
  7171. args[i - 1] = arguments[i];
  7172. listeners = handler.slice();
  7173. len = listeners.length;
  7174. for (i = 0; i < len; i++)
  7175. listeners[i].apply(this, args);
  7176. }
  7177. return true;
  7178. };
  7179. EventEmitter.prototype.addListener = function(type, listener) {
  7180. var m;
  7181. if (!isFunction(listener))
  7182. throw TypeError('listener must be a function');
  7183. if (!this._events)
  7184. this._events = {};
  7185. // To avoid recursion in the case that type === "newListener"! Before
  7186. // adding it to the listeners, first emit "newListener".
  7187. if (this._events.newListener)
  7188. this.emit('newListener', type,
  7189. isFunction(listener.listener) ?
  7190. listener.listener : listener);
  7191. if (!this._events[type])
  7192. // Optimize the case of one listener. Don't need the extra array object.
  7193. this._events[type] = listener;
  7194. else if (isObject(this._events[type]))
  7195. // If we've already got an array, just append.
  7196. this._events[type].push(listener);
  7197. else
  7198. // Adding the second element, need to change to array.
  7199. this._events[type] = [this._events[type], listener];
  7200. // Check for listener leak
  7201. if (isObject(this._events[type]) && !this._events[type].warned) {
  7202. var m;
  7203. if (!isUndefined(this._maxListeners)) {
  7204. m = this._maxListeners;
  7205. } else {
  7206. m = EventEmitter.defaultMaxListeners;
  7207. }
  7208. if (m && m > 0 && this._events[type].length > m) {
  7209. this._events[type].warned = true;
  7210. console.error('(node) warning: possible EventEmitter memory ' +
  7211. 'leak detected. %d listeners added. ' +
  7212. 'Use emitter.setMaxListeners() to increase limit.',
  7213. this._events[type].length);
  7214. if (typeof console.trace === 'function') {
  7215. // not supported in IE 10
  7216. console.trace();
  7217. }
  7218. }
  7219. }
  7220. return this;
  7221. };
  7222. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  7223. EventEmitter.prototype.once = function(type, listener) {
  7224. if (!isFunction(listener))
  7225. throw TypeError('listener must be a function');
  7226. var fired = false;
  7227. function g() {
  7228. this.removeListener(type, g);
  7229. if (!fired) {
  7230. fired = true;
  7231. listener.apply(this, arguments);
  7232. }
  7233. }
  7234. g.listener = listener;
  7235. this.on(type, g);
  7236. return this;
  7237. };
  7238. // emits a 'removeListener' event iff the listener was removed
  7239. EventEmitter.prototype.removeListener = function(type, listener) {
  7240. var list, position, length, i;
  7241. if (!isFunction(listener))
  7242. throw TypeError('listener must be a function');
  7243. if (!this._events || !this._events[type])
  7244. return this;
  7245. list = this._events[type];
  7246. length = list.length;
  7247. position = -1;
  7248. if (list === listener ||
  7249. (isFunction(list.listener) && list.listener === listener)) {
  7250. delete this._events[type];
  7251. if (this._events.removeListener)
  7252. this.emit('removeListener', type, listener);
  7253. } else if (isObject(list)) {
  7254. for (i = length; i-- > 0;) {
  7255. if (list[i] === listener ||
  7256. (list[i].listener && list[i].listener === listener)) {
  7257. position = i;
  7258. break;
  7259. }
  7260. }
  7261. if (position < 0)
  7262. return this;
  7263. if (list.length === 1) {
  7264. list.length = 0;
  7265. delete this._events[type];
  7266. } else {
  7267. list.splice(position, 1);
  7268. }
  7269. if (this._events.removeListener)
  7270. this.emit('removeListener', type, listener);
  7271. }
  7272. return this;
  7273. };
  7274. EventEmitter.prototype.removeAllListeners = function(type) {
  7275. var key, listeners;
  7276. if (!this._events)
  7277. return this;
  7278. // not listening for removeListener, no need to emit
  7279. if (!this._events.removeListener) {
  7280. if (arguments.length === 0)
  7281. this._events = {};
  7282. else if (this._events[type])
  7283. delete this._events[type];
  7284. return this;
  7285. }
  7286. // emit removeListener for all listeners on all events
  7287. if (arguments.length === 0) {
  7288. for (key in this._events) {
  7289. if (key === 'removeListener') continue;
  7290. this.removeAllListeners(key);
  7291. }
  7292. this.removeAllListeners('removeListener');
  7293. this._events = {};
  7294. return this;
  7295. }
  7296. listeners = this._events[type];
  7297. if (isFunction(listeners)) {
  7298. this.removeListener(type, listeners);
  7299. } else {
  7300. // LIFO order
  7301. while (listeners.length)
  7302. this.removeListener(type, listeners[listeners.length - 1]);
  7303. }
  7304. delete this._events[type];
  7305. return this;
  7306. };
  7307. EventEmitter.prototype.listeners = function(type) {
  7308. var ret;
  7309. if (!this._events || !this._events[type])
  7310. ret = [];
  7311. else if (isFunction(this._events[type]))
  7312. ret = [this._events[type]];
  7313. else
  7314. ret = this._events[type].slice();
  7315. return ret;
  7316. };
  7317. EventEmitter.listenerCount = function(emitter, type) {
  7318. var ret;
  7319. if (!emitter._events || !emitter._events[type])
  7320. ret = 0;
  7321. else if (isFunction(emitter._events[type]))
  7322. ret = 1;
  7323. else
  7324. ret = emitter._events[type].length;
  7325. return ret;
  7326. };
  7327. function isFunction(arg) {
  7328. return typeof arg === 'function';
  7329. }
  7330. function isNumber(arg) {
  7331. return typeof arg === 'number';
  7332. }
  7333. function isObject(arg) {
  7334. return typeof arg === 'object' && arg !== null;
  7335. }
  7336. function isUndefined(arg) {
  7337. return arg === void 0;
  7338. }
  7339. /***/ },
  7340. /* 45 */
  7341. /***/ function(module, exports, __webpack_require__) {
  7342. 'use strict';
  7343. exports.decode = exports.parse = __webpack_require__(62);
  7344. exports.encode = exports.stringify = __webpack_require__(63);
  7345. /***/ },
  7346. /* 46 */
  7347. /***/ function(module, exports, __webpack_require__) {
  7348. var http = __webpack_require__(30);
  7349. var https = module.exports;
  7350. for (var key in http) {
  7351. if (http.hasOwnProperty(key)) https[key] = http[key];
  7352. };
  7353. https.request = function (params, cb) {
  7354. if (!params) params = {};
  7355. params.scheme = 'https';
  7356. return http.request.call(this, params, cb);
  7357. }
  7358. /***/ },
  7359. /* 47 */
  7360. /***/ function(module, exports, __webpack_require__) {
  7361. /* WEBPACK VAR INJECTION */(function(Buffer) {/*!
  7362. * The buffer module from node.js, for the browser.
  7363. *
  7364. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  7365. * @license MIT
  7366. */
  7367. var base64 = __webpack_require__(87)
  7368. var ieee754 = __webpack_require__(80)
  7369. var isArray = __webpack_require__(81)
  7370. exports.Buffer = Buffer
  7371. exports.SlowBuffer = Buffer
  7372. exports.INSPECT_MAX_BYTES = 50
  7373. Buffer.poolSize = 8192 // not used by this implementation
  7374. var kMaxLength = 0x3fffffff
  7375. /**
  7376. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  7377. * === true Use Uint8Array implementation (fastest)
  7378. * === false Use Object implementation (most compatible, even IE6)
  7379. *
  7380. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  7381. * Opera 11.6+, iOS 4.2+.
  7382. *
  7383. * Note:
  7384. *
  7385. * - Implementation must support adding new properties to `Uint8Array` instances.
  7386. * Firefox 4-29 lacked support, fixed in Firefox 30+.
  7387. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  7388. *
  7389. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  7390. *
  7391. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  7392. * incorrect length in some situations.
  7393. *
  7394. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they will
  7395. * get the Object implementation, which is slower but will work correctly.
  7396. */
  7397. Buffer.TYPED_ARRAY_SUPPORT = (function () {
  7398. try {
  7399. var buf = new ArrayBuffer(0)
  7400. var arr = new Uint8Array(buf)
  7401. arr.foo = function () { return 42 }
  7402. return 42 === arr.foo() && // typed array instances can be augmented
  7403. typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
  7404. new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  7405. } catch (e) {
  7406. return false
  7407. }
  7408. })()
  7409. /**
  7410. * Class: Buffer
  7411. * =============
  7412. *
  7413. * The Buffer constructor returns instances of `Uint8Array` that are augmented
  7414. * with function properties for all the node `Buffer` API functions. We use
  7415. * `Uint8Array` so that square bracket notation works as expected -- it returns
  7416. * a single octet.
  7417. *
  7418. * By augmenting the instances, we can avoid modifying the `Uint8Array`
  7419. * prototype.
  7420. */
  7421. function Buffer (subject, encoding, noZero) {
  7422. if (!(this instanceof Buffer))
  7423. return new Buffer(subject, encoding, noZero)
  7424. var type = typeof subject
  7425. // Find the length
  7426. var length
  7427. if (type === 'number')
  7428. length = subject > 0 ? subject >>> 0 : 0
  7429. else if (type === 'string') {
  7430. if (encoding === 'base64')
  7431. subject = base64clean(subject)
  7432. length = Buffer.byteLength(subject, encoding)
  7433. } else if (type === 'object' && subject !== null) { // assume object is array-like
  7434. if (subject.type === 'Buffer' && isArray(subject.data))
  7435. subject = subject.data
  7436. length = +subject.length > 0 ? Math.floor(+subject.length) : 0
  7437. } else
  7438. throw new TypeError('must start with number, buffer, array or string')
  7439. if (this.length > kMaxLength)
  7440. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  7441. 'size: 0x' + kMaxLength.toString(16) + ' bytes')
  7442. var buf
  7443. if (Buffer.TYPED_ARRAY_SUPPORT) {
  7444. // Preferred: Return an augmented `Uint8Array` instance for best performance
  7445. buf = Buffer._augment(new Uint8Array(length))
  7446. } else {
  7447. // Fallback: Return THIS instance of Buffer (created by `new`)
  7448. buf = this
  7449. buf.length = length
  7450. buf._isBuffer = true
  7451. }
  7452. var i
  7453. if (Buffer.TYPED_ARRAY_SUPPORT && typeof subject.byteLength === 'number') {
  7454. // Speed optimization -- use set if we're copying from a typed array
  7455. buf._set(subject)
  7456. } else if (isArrayish(subject)) {
  7457. // Treat array-ish objects as a byte array
  7458. if (Buffer.isBuffer(subject)) {
  7459. for (i = 0; i < length; i++)
  7460. buf[i] = subject.readUInt8(i)
  7461. } else {
  7462. for (i = 0; i < length; i++)
  7463. buf[i] = ((subject[i] % 256) + 256) % 256
  7464. }
  7465. } else if (type === 'string') {
  7466. buf.write(subject, 0, encoding)
  7467. } else if (type === 'number' && !Buffer.TYPED_ARRAY_SUPPORT && !noZero) {
  7468. for (i = 0; i < length; i++) {
  7469. buf[i] = 0
  7470. }
  7471. }
  7472. return buf
  7473. }
  7474. Buffer.isBuffer = function (b) {
  7475. return !!(b != null && b._isBuffer)
  7476. }
  7477. Buffer.compare = function (a, b) {
  7478. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b))
  7479. throw new TypeError('Arguments must be Buffers')
  7480. var x = a.length
  7481. var y = b.length
  7482. for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; i++) {}
  7483. if (i !== len) {
  7484. x = a[i]
  7485. y = b[i]
  7486. }
  7487. if (x < y) return -1
  7488. if (y < x) return 1
  7489. return 0
  7490. }
  7491. Buffer.isEncoding = function (encoding) {
  7492. switch (String(encoding).toLowerCase()) {
  7493. case 'hex':
  7494. case 'utf8':
  7495. case 'utf-8':
  7496. case 'ascii':
  7497. case 'binary':
  7498. case 'base64':
  7499. case 'raw':
  7500. case 'ucs2':
  7501. case 'ucs-2':
  7502. case 'utf16le':
  7503. case 'utf-16le':
  7504. return true
  7505. default:
  7506. return false
  7507. }
  7508. }
  7509. Buffer.concat = function (list, totalLength) {
  7510. if (!isArray(list)) throw new TypeError('Usage: Buffer.concat(list[, length])')
  7511. if (list.length === 0) {
  7512. return new Buffer(0)
  7513. } else if (list.length === 1) {
  7514. return list[0]
  7515. }
  7516. var i
  7517. if (totalLength === undefined) {
  7518. totalLength = 0
  7519. for (i = 0; i < list.length; i++) {
  7520. totalLength += list[i].length
  7521. }
  7522. }
  7523. var buf = new Buffer(totalLength)
  7524. var pos = 0
  7525. for (i = 0; i < list.length; i++) {
  7526. var item = list[i]
  7527. item.copy(buf, pos)
  7528. pos += item.length
  7529. }
  7530. return buf
  7531. }
  7532. Buffer.byteLength = function (str, encoding) {
  7533. var ret
  7534. str = str + ''
  7535. switch (encoding || 'utf8') {
  7536. case 'ascii':
  7537. case 'binary':
  7538. case 'raw':
  7539. ret = str.length
  7540. break
  7541. case 'ucs2':
  7542. case 'ucs-2':
  7543. case 'utf16le':
  7544. case 'utf-16le':
  7545. ret = str.length * 2
  7546. break
  7547. case 'hex':
  7548. ret = str.length >>> 1
  7549. break
  7550. case 'utf8':
  7551. case 'utf-8':
  7552. ret = utf8ToBytes(str).length
  7553. break
  7554. case 'base64':
  7555. ret = base64ToBytes(str).length
  7556. break
  7557. default:
  7558. ret = str.length
  7559. }
  7560. return ret
  7561. }
  7562. // pre-set for values that may exist in the future
  7563. Buffer.prototype.length = undefined
  7564. Buffer.prototype.parent = undefined
  7565. // toString(encoding, start=0, end=buffer.length)
  7566. Buffer.prototype.toString = function (encoding, start, end) {
  7567. var loweredCase = false
  7568. start = start >>> 0
  7569. end = end === undefined || end === Infinity ? this.length : end >>> 0
  7570. if (!encoding) encoding = 'utf8'
  7571. if (start < 0) start = 0
  7572. if (end > this.length) end = this.length
  7573. if (end <= start) return ''
  7574. while (true) {
  7575. switch (encoding) {
  7576. case 'hex':
  7577. return hexSlice(this, start, end)
  7578. case 'utf8':
  7579. case 'utf-8':
  7580. return utf8Slice(this, start, end)
  7581. case 'ascii':
  7582. return asciiSlice(this, start, end)
  7583. case 'binary':
  7584. return binarySlice(this, start, end)
  7585. case 'base64':
  7586. return base64Slice(this, start, end)
  7587. case 'ucs2':
  7588. case 'ucs-2':
  7589. case 'utf16le':
  7590. case 'utf-16le':
  7591. return utf16leSlice(this, start, end)
  7592. default:
  7593. if (loweredCase)
  7594. throw new TypeError('Unknown encoding: ' + encoding)
  7595. encoding = (encoding + '').toLowerCase()
  7596. loweredCase = true
  7597. }
  7598. }
  7599. }
  7600. Buffer.prototype.equals = function (b) {
  7601. if(!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  7602. return Buffer.compare(this, b) === 0
  7603. }
  7604. Buffer.prototype.inspect = function () {
  7605. var str = ''
  7606. var max = exports.INSPECT_MAX_BYTES
  7607. if (this.length > 0) {
  7608. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  7609. if (this.length > max)
  7610. str += ' ... '
  7611. }
  7612. return '<Buffer ' + str + '>'
  7613. }
  7614. Buffer.prototype.compare = function (b) {
  7615. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  7616. return Buffer.compare(this, b)
  7617. }
  7618. // `get` will be removed in Node 0.13+
  7619. Buffer.prototype.get = function (offset) {
  7620. console.log('.get() is deprecated. Access using array indexes instead.')
  7621. return this.readUInt8(offset)
  7622. }
  7623. // `set` will be removed in Node 0.13+
  7624. Buffer.prototype.set = function (v, offset) {
  7625. console.log('.set() is deprecated. Access using array indexes instead.')
  7626. return this.writeUInt8(v, offset)
  7627. }
  7628. function hexWrite (buf, string, offset, length) {
  7629. offset = Number(offset) || 0
  7630. var remaining = buf.length - offset
  7631. if (!length) {
  7632. length = remaining
  7633. } else {
  7634. length = Number(length)
  7635. if (length > remaining) {
  7636. length = remaining
  7637. }
  7638. }
  7639. // must be an even number of digits
  7640. var strLen = string.length
  7641. if (strLen % 2 !== 0) throw new Error('Invalid hex string')
  7642. if (length > strLen / 2) {
  7643. length = strLen / 2
  7644. }
  7645. for (var i = 0; i < length; i++) {
  7646. var byte = parseInt(string.substr(i * 2, 2), 16)
  7647. if (isNaN(byte)) throw new Error('Invalid hex string')
  7648. buf[offset + i] = byte
  7649. }
  7650. return i
  7651. }
  7652. function utf8Write (buf, string, offset, length) {
  7653. var charsWritten = blitBuffer(utf8ToBytes(string), buf, offset, length)
  7654. return charsWritten
  7655. }
  7656. function asciiWrite (buf, string, offset, length) {
  7657. var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length)
  7658. return charsWritten
  7659. }
  7660. function binaryWrite (buf, string, offset, length) {
  7661. return asciiWrite(buf, string, offset, length)
  7662. }
  7663. function base64Write (buf, string, offset, length) {
  7664. var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length)
  7665. return charsWritten
  7666. }
  7667. function utf16leWrite (buf, string, offset, length) {
  7668. var charsWritten = blitBuffer(utf16leToBytes(string), buf, offset, length)
  7669. return charsWritten
  7670. }
  7671. Buffer.prototype.write = function (string, offset, length, encoding) {
  7672. // Support both (string, offset, length, encoding)
  7673. // and the legacy (string, encoding, offset, length)
  7674. if (isFinite(offset)) {
  7675. if (!isFinite(length)) {
  7676. encoding = length
  7677. length = undefined
  7678. }
  7679. } else { // legacy
  7680. var swap = encoding
  7681. encoding = offset
  7682. offset = length
  7683. length = swap
  7684. }
  7685. offset = Number(offset) || 0
  7686. var remaining = this.length - offset
  7687. if (!length) {
  7688. length = remaining
  7689. } else {
  7690. length = Number(length)
  7691. if (length > remaining) {
  7692. length = remaining
  7693. }
  7694. }
  7695. encoding = String(encoding || 'utf8').toLowerCase()
  7696. var ret
  7697. switch (encoding) {
  7698. case 'hex':
  7699. ret = hexWrite(this, string, offset, length)
  7700. break
  7701. case 'utf8':
  7702. case 'utf-8':
  7703. ret = utf8Write(this, string, offset, length)
  7704. break
  7705. case 'ascii':
  7706. ret = asciiWrite(this, string, offset, length)
  7707. break
  7708. case 'binary':
  7709. ret = binaryWrite(this, string, offset, length)
  7710. break
  7711. case 'base64':
  7712. ret = base64Write(this, string, offset, length)
  7713. break
  7714. case 'ucs2':
  7715. case 'ucs-2':
  7716. case 'utf16le':
  7717. case 'utf-16le':
  7718. ret = utf16leWrite(this, string, offset, length)
  7719. break
  7720. default:
  7721. throw new TypeError('Unknown encoding: ' + encoding)
  7722. }
  7723. return ret
  7724. }
  7725. Buffer.prototype.toJSON = function () {
  7726. return {
  7727. type: 'Buffer',
  7728. data: Array.prototype.slice.call(this._arr || this, 0)
  7729. }
  7730. }
  7731. function base64Slice (buf, start, end) {
  7732. if (start === 0 && end === buf.length) {
  7733. return base64.fromByteArray(buf)
  7734. } else {
  7735. return base64.fromByteArray(buf.slice(start, end))
  7736. }
  7737. }
  7738. function utf8Slice (buf, start, end) {
  7739. var res = ''
  7740. var tmp = ''
  7741. end = Math.min(buf.length, end)
  7742. for (var i = start; i < end; i++) {
  7743. if (buf[i] <= 0x7F) {
  7744. res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i])
  7745. tmp = ''
  7746. } else {
  7747. tmp += '%' + buf[i].toString(16)
  7748. }
  7749. }
  7750. return res + decodeUtf8Char(tmp)
  7751. }
  7752. function asciiSlice (buf, start, end) {
  7753. var ret = ''
  7754. end = Math.min(buf.length, end)
  7755. for (var i = start; i < end; i++) {
  7756. ret += String.fromCharCode(buf[i])
  7757. }
  7758. return ret
  7759. }
  7760. function binarySlice (buf, start, end) {
  7761. return asciiSlice(buf, start, end)
  7762. }
  7763. function hexSlice (buf, start, end) {
  7764. var len = buf.length
  7765. if (!start || start < 0) start = 0
  7766. if (!end || end < 0 || end > len) end = len
  7767. var out = ''
  7768. for (var i = start; i < end; i++) {
  7769. out += toHex(buf[i])
  7770. }
  7771. return out
  7772. }
  7773. function utf16leSlice (buf, start, end) {
  7774. var bytes = buf.slice(start, end)
  7775. var res = ''
  7776. for (var i = 0; i < bytes.length; i += 2) {
  7777. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  7778. }
  7779. return res
  7780. }
  7781. Buffer.prototype.slice = function (start, end) {
  7782. var len = this.length
  7783. start = ~~start
  7784. end = end === undefined ? len : ~~end
  7785. if (start < 0) {
  7786. start += len;
  7787. if (start < 0)
  7788. start = 0
  7789. } else if (start > len) {
  7790. start = len
  7791. }
  7792. if (end < 0) {
  7793. end += len
  7794. if (end < 0)
  7795. end = 0
  7796. } else if (end > len) {
  7797. end = len
  7798. }
  7799. if (end < start)
  7800. end = start
  7801. if (Buffer.TYPED_ARRAY_SUPPORT) {
  7802. return Buffer._augment(this.subarray(start, end))
  7803. } else {
  7804. var sliceLen = end - start
  7805. var newBuf = new Buffer(sliceLen, undefined, true)
  7806. for (var i = 0; i < sliceLen; i++) {
  7807. newBuf[i] = this[i + start]
  7808. }
  7809. return newBuf
  7810. }
  7811. }
  7812. /*
  7813. * Need to make sure that buffer isn't trying to write out of bounds.
  7814. */
  7815. function checkOffset (offset, ext, length) {
  7816. if ((offset % 1) !== 0 || offset < 0)
  7817. throw new RangeError('offset is not uint')
  7818. if (offset + ext > length)
  7819. throw new RangeError('Trying to access beyond buffer length')
  7820. }
  7821. Buffer.prototype.readUInt8 = function (offset, noAssert) {
  7822. if (!noAssert)
  7823. checkOffset(offset, 1, this.length)
  7824. return this[offset]
  7825. }
  7826. Buffer.prototype.readUInt16LE = function (offset, noAssert) {
  7827. if (!noAssert)
  7828. checkOffset(offset, 2, this.length)
  7829. return this[offset] | (this[offset + 1] << 8)
  7830. }
  7831. Buffer.prototype.readUInt16BE = function (offset, noAssert) {
  7832. if (!noAssert)
  7833. checkOffset(offset, 2, this.length)
  7834. return (this[offset] << 8) | this[offset + 1]
  7835. }
  7836. Buffer.prototype.readUInt32LE = function (offset, noAssert) {
  7837. if (!noAssert)
  7838. checkOffset(offset, 4, this.length)
  7839. return ((this[offset]) |
  7840. (this[offset + 1] << 8) |
  7841. (this[offset + 2] << 16)) +
  7842. (this[offset + 3] * 0x1000000)
  7843. }
  7844. Buffer.prototype.readUInt32BE = function (offset, noAssert) {
  7845. if (!noAssert)
  7846. checkOffset(offset, 4, this.length)
  7847. return (this[offset] * 0x1000000) +
  7848. ((this[offset + 1] << 16) |
  7849. (this[offset + 2] << 8) |
  7850. this[offset + 3])
  7851. }
  7852. Buffer.prototype.readInt8 = function (offset, noAssert) {
  7853. if (!noAssert)
  7854. checkOffset(offset, 1, this.length)
  7855. if (!(this[offset] & 0x80))
  7856. return (this[offset])
  7857. return ((0xff - this[offset] + 1) * -1)
  7858. }
  7859. Buffer.prototype.readInt16LE = function (offset, noAssert) {
  7860. if (!noAssert)
  7861. checkOffset(offset, 2, this.length)
  7862. var val = this[offset] | (this[offset + 1] << 8)
  7863. return (val & 0x8000) ? val | 0xFFFF0000 : val
  7864. }
  7865. Buffer.prototype.readInt16BE = function (offset, noAssert) {
  7866. if (!noAssert)
  7867. checkOffset(offset, 2, this.length)
  7868. var val = this[offset + 1] | (this[offset] << 8)
  7869. return (val & 0x8000) ? val | 0xFFFF0000 : val
  7870. }
  7871. Buffer.prototype.readInt32LE = function (offset, noAssert) {
  7872. if (!noAssert)
  7873. checkOffset(offset, 4, this.length)
  7874. return (this[offset]) |
  7875. (this[offset + 1] << 8) |
  7876. (this[offset + 2] << 16) |
  7877. (this[offset + 3] << 24)
  7878. }
  7879. Buffer.prototype.readInt32BE = function (offset, noAssert) {
  7880. if (!noAssert)
  7881. checkOffset(offset, 4, this.length)
  7882. return (this[offset] << 24) |
  7883. (this[offset + 1] << 16) |
  7884. (this[offset + 2] << 8) |
  7885. (this[offset + 3])
  7886. }
  7887. Buffer.prototype.readFloatLE = function (offset, noAssert) {
  7888. if (!noAssert)
  7889. checkOffset(offset, 4, this.length)
  7890. return ieee754.read(this, offset, true, 23, 4)
  7891. }
  7892. Buffer.prototype.readFloatBE = function (offset, noAssert) {
  7893. if (!noAssert)
  7894. checkOffset(offset, 4, this.length)
  7895. return ieee754.read(this, offset, false, 23, 4)
  7896. }
  7897. Buffer.prototype.readDoubleLE = function (offset, noAssert) {
  7898. if (!noAssert)
  7899. checkOffset(offset, 8, this.length)
  7900. return ieee754.read(this, offset, true, 52, 8)
  7901. }
  7902. Buffer.prototype.readDoubleBE = function (offset, noAssert) {
  7903. if (!noAssert)
  7904. checkOffset(offset, 8, this.length)
  7905. return ieee754.read(this, offset, false, 52, 8)
  7906. }
  7907. function checkInt (buf, value, offset, ext, max, min) {
  7908. if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
  7909. if (value > max || value < min) throw new TypeError('value is out of bounds')
  7910. if (offset + ext > buf.length) throw new TypeError('index out of range')
  7911. }
  7912. Buffer.prototype.writeUInt8 = function (value, offset, noAssert) {
  7913. value = +value
  7914. offset = offset >>> 0
  7915. if (!noAssert)
  7916. checkInt(this, value, offset, 1, 0xff, 0)
  7917. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  7918. this[offset] = value
  7919. return offset + 1
  7920. }
  7921. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  7922. if (value < 0) value = 0xffff + value + 1
  7923. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
  7924. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  7925. (littleEndian ? i : 1 - i) * 8
  7926. }
  7927. }
  7928. Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) {
  7929. value = +value
  7930. offset = offset >>> 0
  7931. if (!noAssert)
  7932. checkInt(this, value, offset, 2, 0xffff, 0)
  7933. if (Buffer.TYPED_ARRAY_SUPPORT) {
  7934. this[offset] = value
  7935. this[offset + 1] = (value >>> 8)
  7936. } else objectWriteUInt16(this, value, offset, true)
  7937. return offset + 2
  7938. }
  7939. Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) {
  7940. value = +value
  7941. offset = offset >>> 0
  7942. if (!noAssert)
  7943. checkInt(this, value, offset, 2, 0xffff, 0)
  7944. if (Buffer.TYPED_ARRAY_SUPPORT) {
  7945. this[offset] = (value >>> 8)
  7946. this[offset + 1] = value
  7947. } else objectWriteUInt16(this, value, offset, false)
  7948. return offset + 2
  7949. }
  7950. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  7951. if (value < 0) value = 0xffffffff + value + 1
  7952. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
  7953. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  7954. }
  7955. }
  7956. Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) {
  7957. value = +value
  7958. offset = offset >>> 0
  7959. if (!noAssert)
  7960. checkInt(this, value, offset, 4, 0xffffffff, 0)
  7961. if (Buffer.TYPED_ARRAY_SUPPORT) {
  7962. this[offset + 3] = (value >>> 24)
  7963. this[offset + 2] = (value >>> 16)
  7964. this[offset + 1] = (value >>> 8)
  7965. this[offset] = value
  7966. } else objectWriteUInt32(this, value, offset, true)
  7967. return offset + 4
  7968. }
  7969. Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) {
  7970. value = +value
  7971. offset = offset >>> 0
  7972. if (!noAssert)
  7973. checkInt(this, value, offset, 4, 0xffffffff, 0)
  7974. if (Buffer.TYPED_ARRAY_SUPPORT) {
  7975. this[offset] = (value >>> 24)
  7976. this[offset + 1] = (value >>> 16)
  7977. this[offset + 2] = (value >>> 8)
  7978. this[offset + 3] = value
  7979. } else objectWriteUInt32(this, value, offset, false)
  7980. return offset + 4
  7981. }
  7982. Buffer.prototype.writeInt8 = function (value, offset, noAssert) {
  7983. value = +value
  7984. offset = offset >>> 0
  7985. if (!noAssert)
  7986. checkInt(this, value, offset, 1, 0x7f, -0x80)
  7987. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  7988. if (value < 0) value = 0xff + value + 1
  7989. this[offset] = value
  7990. return offset + 1
  7991. }
  7992. Buffer.prototype.writeInt16LE = function (value, offset, noAssert) {
  7993. value = +value
  7994. offset = offset >>> 0
  7995. if (!noAssert)
  7996. checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  7997. if (Buffer.TYPED_ARRAY_SUPPORT) {
  7998. this[offset] = value
  7999. this[offset + 1] = (value >>> 8)
  8000. } else objectWriteUInt16(this, value, offset, true)
  8001. return offset + 2
  8002. }
  8003. Buffer.prototype.writeInt16BE = function (value, offset, noAssert) {
  8004. value = +value
  8005. offset = offset >>> 0
  8006. if (!noAssert)
  8007. checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  8008. if (Buffer.TYPED_ARRAY_SUPPORT) {
  8009. this[offset] = (value >>> 8)
  8010. this[offset + 1] = value
  8011. } else objectWriteUInt16(this, value, offset, false)
  8012. return offset + 2
  8013. }
  8014. Buffer.prototype.writeInt32LE = function (value, offset, noAssert) {
  8015. value = +value
  8016. offset = offset >>> 0
  8017. if (!noAssert)
  8018. checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  8019. if (Buffer.TYPED_ARRAY_SUPPORT) {
  8020. this[offset] = value
  8021. this[offset + 1] = (value >>> 8)
  8022. this[offset + 2] = (value >>> 16)
  8023. this[offset + 3] = (value >>> 24)
  8024. } else objectWriteUInt32(this, value, offset, true)
  8025. return offset + 4
  8026. }
  8027. Buffer.prototype.writeInt32BE = function (value, offset, noAssert) {
  8028. value = +value
  8029. offset = offset >>> 0
  8030. if (!noAssert)
  8031. checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  8032. if (value < 0) value = 0xffffffff + value + 1
  8033. if (Buffer.TYPED_ARRAY_SUPPORT) {
  8034. this[offset] = (value >>> 24)
  8035. this[offset + 1] = (value >>> 16)
  8036. this[offset + 2] = (value >>> 8)
  8037. this[offset + 3] = value
  8038. } else objectWriteUInt32(this, value, offset, false)
  8039. return offset + 4
  8040. }
  8041. function checkIEEE754 (buf, value, offset, ext, max, min) {
  8042. if (value > max || value < min) throw new TypeError('value is out of bounds')
  8043. if (offset + ext > buf.length) throw new TypeError('index out of range')
  8044. }
  8045. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  8046. if (!noAssert)
  8047. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  8048. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  8049. return offset + 4
  8050. }
  8051. Buffer.prototype.writeFloatLE = function (value, offset, noAssert) {
  8052. return writeFloat(this, value, offset, true, noAssert)
  8053. }
  8054. Buffer.prototype.writeFloatBE = function (value, offset, noAssert) {
  8055. return writeFloat(this, value, offset, false, noAssert)
  8056. }
  8057. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  8058. if (!noAssert)
  8059. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  8060. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  8061. return offset + 8
  8062. }
  8063. Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) {
  8064. return writeDouble(this, value, offset, true, noAssert)
  8065. }
  8066. Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) {
  8067. return writeDouble(this, value, offset, false, noAssert)
  8068. }
  8069. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  8070. Buffer.prototype.copy = function (target, target_start, start, end) {
  8071. var source = this
  8072. if (!start) start = 0
  8073. if (!end && end !== 0) end = this.length
  8074. if (!target_start) target_start = 0
  8075. // Copy 0 bytes; we're done
  8076. if (end === start) return
  8077. if (target.length === 0 || source.length === 0) return
  8078. // Fatal error conditions
  8079. if (end < start) throw new TypeError('sourceEnd < sourceStart')
  8080. if (target_start < 0 || target_start >= target.length)
  8081. throw new TypeError('targetStart out of bounds')
  8082. if (start < 0 || start >= source.length) throw new TypeError('sourceStart out of bounds')
  8083. if (end < 0 || end > source.length) throw new TypeError('sourceEnd out of bounds')
  8084. // Are we oob?
  8085. if (end > this.length)
  8086. end = this.length
  8087. if (target.length - target_start < end - start)
  8088. end = target.length - target_start + start
  8089. var len = end - start
  8090. if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  8091. for (var i = 0; i < len; i++) {
  8092. target[i + target_start] = this[i + start]
  8093. }
  8094. } else {
  8095. target._set(this.subarray(start, start + len), target_start)
  8096. }
  8097. }
  8098. // fill(value, start=0, end=buffer.length)
  8099. Buffer.prototype.fill = function (value, start, end) {
  8100. if (!value) value = 0
  8101. if (!start) start = 0
  8102. if (!end) end = this.length
  8103. if (end < start) throw new TypeError('end < start')
  8104. // Fill 0 bytes; we're done
  8105. if (end === start) return
  8106. if (this.length === 0) return
  8107. if (start < 0 || start >= this.length) throw new TypeError('start out of bounds')
  8108. if (end < 0 || end > this.length) throw new TypeError('end out of bounds')
  8109. var i
  8110. if (typeof value === 'number') {
  8111. for (i = start; i < end; i++) {
  8112. this[i] = value
  8113. }
  8114. } else {
  8115. var bytes = utf8ToBytes(value.toString())
  8116. var len = bytes.length
  8117. for (i = start; i < end; i++) {
  8118. this[i] = bytes[i % len]
  8119. }
  8120. }
  8121. return this
  8122. }
  8123. /**
  8124. * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
  8125. * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
  8126. */
  8127. Buffer.prototype.toArrayBuffer = function () {
  8128. if (typeof Uint8Array !== 'undefined') {
  8129. if (Buffer.TYPED_ARRAY_SUPPORT) {
  8130. return (new Buffer(this)).buffer
  8131. } else {
  8132. var buf = new Uint8Array(this.length)
  8133. for (var i = 0, len = buf.length; i < len; i += 1) {
  8134. buf[i] = this[i]
  8135. }
  8136. return buf.buffer
  8137. }
  8138. } else {
  8139. throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
  8140. }
  8141. }
  8142. // HELPER FUNCTIONS
  8143. // ================
  8144. var BP = Buffer.prototype
  8145. /**
  8146. * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
  8147. */
  8148. Buffer._augment = function (arr) {
  8149. arr.constructor = Buffer
  8150. arr._isBuffer = true
  8151. // save reference to original Uint8Array get/set methods before overwriting
  8152. arr._get = arr.get
  8153. arr._set = arr.set
  8154. // deprecated, will be removed in node 0.13+
  8155. arr.get = BP.get
  8156. arr.set = BP.set
  8157. arr.write = BP.write
  8158. arr.toString = BP.toString
  8159. arr.toLocaleString = BP.toString
  8160. arr.toJSON = BP.toJSON
  8161. arr.equals = BP.equals
  8162. arr.compare = BP.compare
  8163. arr.copy = BP.copy
  8164. arr.slice = BP.slice
  8165. arr.readUInt8 = BP.readUInt8
  8166. arr.readUInt16LE = BP.readUInt16LE
  8167. arr.readUInt16BE = BP.readUInt16BE
  8168. arr.readUInt32LE = BP.readUInt32LE
  8169. arr.readUInt32BE = BP.readUInt32BE
  8170. arr.readInt8 = BP.readInt8
  8171. arr.readInt16LE = BP.readInt16LE
  8172. arr.readInt16BE = BP.readInt16BE
  8173. arr.readInt32LE = BP.readInt32LE
  8174. arr.readInt32BE = BP.readInt32BE
  8175. arr.readFloatLE = BP.readFloatLE
  8176. arr.readFloatBE = BP.readFloatBE
  8177. arr.readDoubleLE = BP.readDoubleLE
  8178. arr.readDoubleBE = BP.readDoubleBE
  8179. arr.writeUInt8 = BP.writeUInt8
  8180. arr.writeUInt16LE = BP.writeUInt16LE
  8181. arr.writeUInt16BE = BP.writeUInt16BE
  8182. arr.writeUInt32LE = BP.writeUInt32LE
  8183. arr.writeUInt32BE = BP.writeUInt32BE
  8184. arr.writeInt8 = BP.writeInt8
  8185. arr.writeInt16LE = BP.writeInt16LE
  8186. arr.writeInt16BE = BP.writeInt16BE
  8187. arr.writeInt32LE = BP.writeInt32LE
  8188. arr.writeInt32BE = BP.writeInt32BE
  8189. arr.writeFloatLE = BP.writeFloatLE
  8190. arr.writeFloatBE = BP.writeFloatBE
  8191. arr.writeDoubleLE = BP.writeDoubleLE
  8192. arr.writeDoubleBE = BP.writeDoubleBE
  8193. arr.fill = BP.fill
  8194. arr.inspect = BP.inspect
  8195. arr.toArrayBuffer = BP.toArrayBuffer
  8196. return arr
  8197. }
  8198. var INVALID_BASE64_RE = /[^+\/0-9A-z]/g
  8199. function base64clean (str) {
  8200. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  8201. str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  8202. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  8203. while (str.length % 4 !== 0) {
  8204. str = str + '='
  8205. }
  8206. return str
  8207. }
  8208. function stringtrim (str) {
  8209. if (str.trim) return str.trim()
  8210. return str.replace(/^\s+|\s+$/g, '')
  8211. }
  8212. function isArrayish (subject) {
  8213. return isArray(subject) || Buffer.isBuffer(subject) ||
  8214. subject && typeof subject === 'object' &&
  8215. typeof subject.length === 'number'
  8216. }
  8217. function toHex (n) {
  8218. if (n < 16) return '0' + n.toString(16)
  8219. return n.toString(16)
  8220. }
  8221. function utf8ToBytes (str) {
  8222. var byteArray = []
  8223. for (var i = 0; i < str.length; i++) {
  8224. var b = str.charCodeAt(i)
  8225. if (b <= 0x7F) {
  8226. byteArray.push(b)
  8227. } else {
  8228. var start = i
  8229. if (b >= 0xD800 && b <= 0xDFFF) i++
  8230. var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%')
  8231. for (var j = 0; j < h.length; j++) {
  8232. byteArray.push(parseInt(h[j], 16))
  8233. }
  8234. }
  8235. }
  8236. return byteArray
  8237. }
  8238. function asciiToBytes (str) {
  8239. var byteArray = []
  8240. for (var i = 0; i < str.length; i++) {
  8241. // Node's code seems to be doing this and not & 0x7F..
  8242. byteArray.push(str.charCodeAt(i) & 0xFF)
  8243. }
  8244. return byteArray
  8245. }
  8246. function utf16leToBytes (str) {
  8247. var c, hi, lo
  8248. var byteArray = []
  8249. for (var i = 0; i < str.length; i++) {
  8250. c = str.charCodeAt(i)
  8251. hi = c >> 8
  8252. lo = c % 256
  8253. byteArray.push(lo)
  8254. byteArray.push(hi)
  8255. }
  8256. return byteArray
  8257. }
  8258. function base64ToBytes (str) {
  8259. return base64.toByteArray(str)
  8260. }
  8261. function blitBuffer (src, dst, offset, length) {
  8262. for (var i = 0; i < length; i++) {
  8263. if ((i + offset >= dst.length) || (i >= src.length))
  8264. break
  8265. dst[i + offset] = src[i]
  8266. }
  8267. return i
  8268. }
  8269. function decodeUtf8Char (str) {
  8270. try {
  8271. return decodeURIComponent(str)
  8272. } catch (err) {
  8273. return String.fromCharCode(0xFFFD) // UTF 8 invalid char
  8274. }
  8275. }
  8276. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(47).Buffer))
  8277. /***/ },
  8278. /* 48 */
  8279. /***/ function(module, exports, __webpack_require__) {
  8280. /* WEBPACK VAR INJECTION */(function(Buffer) {var rng = __webpack_require__(65)
  8281. function error () {
  8282. var m = [].slice.call(arguments).join(' ')
  8283. throw new Error([
  8284. m,
  8285. 'we accept pull requests',
  8286. 'http://github.com/dominictarr/crypto-browserify'
  8287. ].join('\n'))
  8288. }
  8289. exports.createHash = __webpack_require__(66)
  8290. exports.createHmac = __webpack_require__(67)
  8291. exports.randomBytes = function(size, callback) {
  8292. if (callback && callback.call) {
  8293. try {
  8294. callback.call(this, undefined, new Buffer(rng(size)))
  8295. } catch (err) { callback(err) }
  8296. } else {
  8297. return new Buffer(rng(size))
  8298. }
  8299. }
  8300. function each(a, f) {
  8301. for(var i in a)
  8302. f(a[i], i)
  8303. }
  8304. exports.getHashes = function () {
  8305. return ['sha1', 'sha256', 'sha512', 'md5', 'rmd160']
  8306. }
  8307. var p = __webpack_require__(68)(exports)
  8308. exports.pbkdf2 = p.pbkdf2
  8309. exports.pbkdf2Sync = p.pbkdf2Sync
  8310. __webpack_require__(84)(exports, module.exports);
  8311. // the least I can do is make error messages for the rest of the node.js/crypto api.
  8312. each(['createCredentials'
  8313. , 'createSign'
  8314. , 'createVerify'
  8315. , 'createDiffieHellman'
  8316. ], function (name) {
  8317. exports[name] = function () {
  8318. error('sorry,', name, 'is not implemented yet')
  8319. }
  8320. })
  8321. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(47).Buffer))
  8322. /***/ },
  8323. /* 49 */
  8324. /***/ function(module, exports, __webpack_require__) {
  8325. 'use strict';
  8326. var uuid = __webpack_require__(85);
  8327. var Promise = __webpack_require__(90).Promise;
  8328. var messagebus = __webpack_require__(50);
  8329. var Conversation = __webpack_require__(69);
  8330. var Block = __webpack_require__(61);
  8331. var Then = __webpack_require__(58);
  8332. var Tell = __webpack_require__(56);
  8333. var Listen = __webpack_require__(57);
  8334. __webpack_require__(60); // append iif function to Block
  8335. /**
  8336. * Babbler
  8337. * @param {String} id
  8338. * @constructor
  8339. */
  8340. function Babbler (id) {
  8341. if (!(this instanceof Babbler)) {
  8342. throw new SyntaxError('Constructor must be called with the new operator');
  8343. }
  8344. if (!id) {
  8345. throw new Error('id required');
  8346. }
  8347. this.id = id;
  8348. this.listeners = []; // Array.<Listen>
  8349. this.conversations = {}; // Array.<Array.<Conversation>> all open conversations
  8350. this.connect(); // automatically connect to the local message bus
  8351. }
  8352. /**
  8353. * Connect to a message bus
  8354. * @param {{connect: function, disconnect: function, send: function}} [bus]
  8355. * A messaging interface. Must have the following functions:
  8356. * - connect(params: {id: string,
  8357. * message: function, callback: function}) : string
  8358. * must return a token to disconnects again.
  8359. * parameter callback is optional.
  8360. * - disconnect(token: string)
  8361. * disconnect from a message bus.
  8362. * - send(id: string, message: *)
  8363. * send a message
  8364. * A number of interfaces is provided under babble.messagebus.
  8365. * Default interface is babble.messagebus['default']
  8366. * @return {Promise.<Babbler>} Returns a Promise which resolves when the
  8367. * babbler is connected.
  8368. */
  8369. Babbler.prototype.connect = function (bus) {
  8370. // disconnect (in case we are already connected)
  8371. this.disconnect();
  8372. if (!bus) {
  8373. bus = messagebus['default']();
  8374. }
  8375. // validate the message bus functions
  8376. if (typeof bus.connect !== 'function') {
  8377. throw new Error('message bus must contain a function ' +
  8378. 'connect(params: {id: string, callback: function}) : string');
  8379. }
  8380. if (typeof bus.disconnect !== 'function') {
  8381. throw new Error('message bus must contain a function ' +
  8382. 'disconnect(token: string)');
  8383. }
  8384. if (typeof bus.send !== 'function') {
  8385. throw new Error('message bus must contain a function ' +
  8386. 'send(params: {id: string, message: *})');
  8387. }
  8388. // we return a promise, but we run the message.connect function immediately
  8389. // (outside of the Promise), so that synchronous connects are done without
  8390. // the need to await the promise to resolve on the next tick.
  8391. var _resolve = null;
  8392. var connected = new Promise(function (resolve, reject) {
  8393. _resolve = resolve;
  8394. });
  8395. var token = bus.connect({
  8396. id: this.id,
  8397. message: this._receive.bind(this),
  8398. callback: _resolve
  8399. });
  8400. // link functions to disconnect and send
  8401. this.disconnect = function () {
  8402. bus.disconnect(token);
  8403. };
  8404. this.send = bus.send;
  8405. // return a promise
  8406. return connected;
  8407. };
  8408. /**
  8409. * Handle an incoming message
  8410. * @param {{id: string, from: string, to: string, message: string}} envelope
  8411. * @private
  8412. */
  8413. Babbler.prototype._receive = function (envelope) {
  8414. // ignore when envelope does not contain an id and message
  8415. if (!envelope || !('id' in envelope) || !('message' in envelope)) {
  8416. return;
  8417. }
  8418. // console.log('_receive', envelope) // TODO: cleanup
  8419. var me = this;
  8420. var id = envelope.id;
  8421. var conversations = this.conversations[id];
  8422. if (conversations && conversations.length) {
  8423. // directly deliver to all open conversations with this id
  8424. conversations.forEach(function (conversation) {
  8425. conversation.deliver(envelope);
  8426. })
  8427. }
  8428. else {
  8429. // start new conversations at each of the listeners
  8430. if (!conversations) {
  8431. conversations = [];
  8432. }
  8433. this.conversations[id] = conversations;
  8434. this.listeners.forEach(function (block) {
  8435. // create a new conversation
  8436. var conversation = new Conversation({
  8437. id: id,
  8438. self: me.id,
  8439. other: envelope.from,
  8440. context: {
  8441. from: envelope.from
  8442. },
  8443. send: me.send
  8444. });
  8445. // append this conversation to the list with conversations
  8446. conversations.push(conversation);
  8447. // deliver the first message to the new conversation
  8448. conversation.deliver(envelope);
  8449. // process the conversation
  8450. return me._process(block, conversation)
  8451. .then(function() {
  8452. // remove the conversation from the list again
  8453. var index = conversations.indexOf(conversation);
  8454. if (index !== -1) {
  8455. conversations.splice(index, 1);
  8456. }
  8457. if (conversations.length === 0) {
  8458. delete me.conversations[id];
  8459. }
  8460. });
  8461. });
  8462. }
  8463. };
  8464. /**
  8465. * Disconnect from the babblebox
  8466. */
  8467. Babbler.prototype.disconnect = function () {
  8468. // by default, do nothing. The disconnect function will be overwritten
  8469. // when the Babbler is connected to a message bus.
  8470. };
  8471. /**
  8472. * Send a message
  8473. * @param {String} to Id of a babbler
  8474. * @param {*} message Any message. Message must be a stringifiable JSON object.
  8475. */
  8476. Babbler.prototype.send = function (to, message) {
  8477. // send is overridden when running connect
  8478. throw new Error('Cannot send: not connected');
  8479. };
  8480. /**
  8481. * Listen for a specific event
  8482. *
  8483. * Providing a condition will only start the flow when condition is met,
  8484. * this is equivalent of doing `listen().iif(condition)`
  8485. *
  8486. * Providing a callback function is equivalent of doing either
  8487. * `listen(message).then(callback)` or `listen().iif(message).then(callback)`.
  8488. *
  8489. * @param {function | RegExp | String | *} [condition]
  8490. * @param {Function} [callback] Invoked as callback(message, context),
  8491. * where `message` is the just received message,
  8492. * and `context` is an object where state can be
  8493. * stored during a conversation. This is equivalent
  8494. * of doing `listen().then(callback)`
  8495. * @return {Block} block Start block of a control flow.
  8496. */
  8497. Babbler.prototype.listen = function (condition, callback) {
  8498. var listen = new Listen();
  8499. this.listeners.push(listen);
  8500. var block = listen;
  8501. if (condition) {
  8502. block = block.iif(condition);
  8503. }
  8504. if (callback) {
  8505. block = block.then(callback);
  8506. }
  8507. return block;
  8508. };
  8509. /**
  8510. * Listen for a specific event, and execute the flow once.
  8511. *
  8512. * Providing a condition will only start the flow when condition is met,
  8513. * this is equivalent of doing `listen().iif(condition)`
  8514. *
  8515. * Providing a callback function is equivalent of doing either
  8516. * `listen(message).then(callback)` or `listen().iif(message).then(callback)`.
  8517. *
  8518. * @param {function | RegExp | String | *} [condition]
  8519. * @param {Function} [callback] Invoked as callback(message, context),
  8520. * where `message` is the just received message,
  8521. * and `context` is an object where state can be
  8522. * stored during a conversation. This is equivalent
  8523. * of doing `listen().then(callback)`
  8524. * @return {Block} block Start block of a control flow.
  8525. */
  8526. Babbler.prototype.listenOnce = function (condition, callback) {
  8527. var listen = new Listen();
  8528. this.listeners.push(listen);
  8529. var me = this;
  8530. var block = listen;
  8531. if (condition) {
  8532. block = block.iif(condition);
  8533. }
  8534. block = block.then(function (message) {
  8535. // remove the flow from the listeners after fired once
  8536. var index = me.listeners.indexOf(listen);
  8537. if (index !== -1) {
  8538. me.listeners.splice(index, 1);
  8539. }
  8540. return message;
  8541. });
  8542. if (callback) {
  8543. block = block.then(callback);
  8544. }
  8545. return block;
  8546. };
  8547. /**
  8548. * Send a message to the other peer
  8549. * Creates a block Tell, and runs the block immediately.
  8550. * @param {String} to Babbler id
  8551. * @param {Function | *} message
  8552. * @return {Block} block Last block in the created control flow
  8553. */
  8554. Babbler.prototype.tell = function (to, message) {
  8555. var me = this;
  8556. var cid = uuid.v4(); // create an id for this conversation
  8557. // create a new conversation
  8558. var conversation = new Conversation({
  8559. id: cid,
  8560. self: this.id,
  8561. other: to,
  8562. context: {
  8563. from: to
  8564. },
  8565. send: me.send
  8566. });
  8567. this.conversations[cid] = [conversation];
  8568. var block = new Tell(message);
  8569. // run the Tell block on the next tick, when the conversation flow is created
  8570. setTimeout(function () {
  8571. me._process(block, conversation)
  8572. .then(function () {
  8573. // cleanup the conversation
  8574. delete me.conversations[cid];
  8575. })
  8576. }, 0);
  8577. return block;
  8578. };
  8579. /**
  8580. * Send a question, listen for a response.
  8581. * Creates two blocks: Tell and Listen, and runs them immediately.
  8582. * This is equivalent of doing `Babbler.tell(to, message).listen(callback)`
  8583. * @param {String} to Babbler id
  8584. * @param {* | Function} message A message or a callback returning a message.
  8585. * @param {Function} [callback] Invoked as callback(message, context),
  8586. * where `message` is the just received message,
  8587. * and `context` is an object where state can be
  8588. * stored during a conversation. This is equivalent
  8589. * of doing `listen().then(callback)`
  8590. * @return {Block} block Last block in the created control flow
  8591. */
  8592. Babbler.prototype.ask = function (to, message, callback) {
  8593. return this
  8594. .tell(to, message)
  8595. .listen(callback);
  8596. };
  8597. /**
  8598. * Process a flow starting with `block`, given a conversation
  8599. * @param {Block} block
  8600. * @param {Conversation} conversation
  8601. * @return {Promise.<Conversation>} Resolves when the conversation is finished
  8602. * @private
  8603. */
  8604. Babbler.prototype._process = function (block, conversation) {
  8605. return new Promise(function (resolve, reject) {
  8606. /**
  8607. * Process a block, given the conversation and a message which is chained
  8608. * from block to block.
  8609. * @param {Block} block
  8610. * @param {*} [message]
  8611. */
  8612. function process(block, message) {
  8613. //console.log('process', conversation.self, conversation.id, block.constructor.name, message) // TODO: cleanup
  8614. block.execute(conversation, message)
  8615. .then(function (next) {
  8616. if (next.block) {
  8617. // recursively evaluate the next block in the conversation flow
  8618. process(next.block, next.result);
  8619. }
  8620. else {
  8621. // we are done, this is the end of the conversation
  8622. resolve(conversation);
  8623. }
  8624. });
  8625. }
  8626. // process the first block
  8627. process(block);
  8628. });
  8629. };
  8630. module.exports = Babbler;
  8631. /***/ },
  8632. /* 50 */
  8633. /***/ function(module, exports, __webpack_require__) {
  8634. 'use strict';
  8635. var Promise = __webpack_require__(90).Promise;
  8636. // built-in messaging interfaces
  8637. /**
  8638. * pubsub-js messaging interface
  8639. * @returns {{connect: function, disconnect: function, send: function}}
  8640. */
  8641. exports['pubsub-js'] = function () {
  8642. var PubSub = __webpack_require__(89);
  8643. return {
  8644. connect: function (params) {
  8645. var token = PubSub.subscribe(params.id, function (id, message) {
  8646. params.message(message);
  8647. });
  8648. if (typeof params.callback === 'function') {
  8649. params.callback();
  8650. }
  8651. return token;
  8652. },
  8653. disconnect: function(token) {
  8654. PubSub.unsubscribe(token);
  8655. },
  8656. send: function (to, message) {
  8657. PubSub.publish(to, message);
  8658. }
  8659. }
  8660. };
  8661. /**
  8662. * // pubnub messaging interface
  8663. * @param {{publish_key: string, subscribe_key: string}} params
  8664. * @returns {{connect: function, disconnect: function, send: function}}
  8665. */
  8666. exports['pubnub'] = function (params) {
  8667. var PUBNUB;
  8668. if (typeof window !== 'undefined') {
  8669. // browser
  8670. if (typeof window['PUBNUB'] === 'undefined') {
  8671. throw new Error('Please load pubnub first in the browser');
  8672. }
  8673. PUBNUB = window['PUBNUB'];
  8674. }
  8675. else {
  8676. // node.js
  8677. PUBNUB = __webpack_require__(86);
  8678. }
  8679. var pubnub = PUBNUB.init(params);
  8680. return {
  8681. connect: function (params) {
  8682. pubnub.subscribe({
  8683. channel: params.id,
  8684. message: params.message,
  8685. connect: params.callback
  8686. });
  8687. return params.id;
  8688. },
  8689. disconnect: function (id) {
  8690. pubnub.unsubscribe(id);
  8691. },
  8692. send: function (to, message) {
  8693. return new Promise(function (resolve, reject) {
  8694. pubnub.publish({
  8695. channel: to,
  8696. message: message,
  8697. callback: resolve
  8698. });
  8699. })
  8700. }
  8701. }
  8702. };
  8703. // default interface
  8704. exports['default'] = exports['pubsub-js'];
  8705. /***/ },
  8706. /* 51 */
  8707. /***/ function(module, exports, __webpack_require__) {
  8708. var uuid = __webpack_require__(74),
  8709. Promise = __webpack_require__(41);
  8710. var TIMEOUT = 60000; // ms
  8711. // TODO: make timeout a configuration setting
  8712. /**
  8713. * Wrap a socket in a request/response handling layer.
  8714. * Requests are wrapped in an envelope with id and data, and responses
  8715. * are packed in an envelope with this same id and response data.
  8716. *
  8717. * The socket is extended with functions:
  8718. * request(data: *) : Promise.<*, Error>
  8719. * onrequest(data: *) : Promise.<*, Error>
  8720. *
  8721. * @param {WebSocket} socket
  8722. * @return {WebSocket} requestified socket
  8723. */
  8724. function requestify (socket) {
  8725. return (function () {
  8726. var queue = {}; // queue with requests in progress
  8727. if ('request' in socket) {
  8728. throw new Error('Socket already has a request property');
  8729. }
  8730. var requestified = socket;
  8731. /**
  8732. * Event handler, handles incoming messages
  8733. * @param {Object} event
  8734. */
  8735. socket.onmessage = function (event) {
  8736. var data = event.data;
  8737. if (data.charAt(0) == '{') {
  8738. var envelope = JSON.parse(data);
  8739. // match the request from the id in the response
  8740. var request = queue[envelope.id];
  8741. if (request) {
  8742. // handle an incoming response
  8743. clearTimeout(request.timeout);
  8744. delete queue[envelope.id];
  8745. // resolve the promise with response data
  8746. if (envelope.error) {
  8747. // TODO: implement a smarter way to serialize and deserialize errors
  8748. request.reject(new Error(envelope.error));
  8749. }
  8750. else {
  8751. request.resolve(envelope.message);
  8752. }
  8753. }
  8754. else {
  8755. if ('id' in envelope) {
  8756. try {
  8757. // handle an incoming request
  8758. requestified.onrequest(envelope.message)
  8759. .then(function (message) {
  8760. var response = {
  8761. id: envelope.id,
  8762. message: message,
  8763. error: null
  8764. };
  8765. socket.send(JSON.stringify(response));
  8766. })
  8767. .catch(function (error) {
  8768. var response = {
  8769. id: envelope.id,
  8770. message: null,
  8771. error: error.message || error.toString()
  8772. };
  8773. socket.send(JSON.stringify(response));
  8774. });
  8775. }
  8776. catch (err) {
  8777. var response = {
  8778. id: envelope.id,
  8779. message: null,
  8780. error: err.message || err.toString()
  8781. };
  8782. socket.send(JSON.stringify(response));
  8783. }
  8784. }
  8785. else {
  8786. // handle incoming notification (we don't do anything with the response)
  8787. requestified.onrequest(envelope.message);
  8788. }
  8789. }
  8790. }
  8791. };
  8792. /**
  8793. * Send a request
  8794. * @param {*} message
  8795. * @returns {Promise.<*, Error>} Returns a promise resolving with the response message
  8796. */
  8797. requestified.request = function (message) {
  8798. return new Promise(function (resolve, reject) {
  8799. // put the data in an envelope with id
  8800. var id = uuid.v1();
  8801. var envelope = {
  8802. id: id,
  8803. message: message
  8804. };
  8805. // add the request to the list with requests in progress
  8806. queue[id] = {
  8807. resolve: resolve,
  8808. reject: reject,
  8809. timeout: setTimeout(function () {
  8810. delete queue[id];
  8811. reject(new Error('Timeout'));
  8812. }, TIMEOUT)
  8813. };
  8814. socket.send(JSON.stringify(envelope));
  8815. });
  8816. };
  8817. /**
  8818. * Send a notification. A notification does not receive a response.
  8819. * @param {*} message
  8820. * @returns {Promise.<null, Error>} Returns a promise resolving with the null
  8821. * when the notification has been sent.
  8822. */
  8823. requestified.notify = function (message) {
  8824. return new Promise(function (resolve, reject) {
  8825. // put the data in an envelope
  8826. var envelope = {
  8827. // we don't add an id, so we send this as notification instead of a request
  8828. message: message
  8829. };
  8830. socket.send(JSON.stringify(envelope), function () {
  8831. resolve(null);
  8832. });
  8833. });
  8834. };
  8835. /**
  8836. * Handle an incoming request.
  8837. * @param {*} message Request message
  8838. * @returns {Promise.<*, Error>} Resolves with a response message
  8839. */
  8840. requestified.onrequest = function (message) {
  8841. // this function must be implemented by the socket
  8842. return Promise.reject('No onrequest handler implemented');
  8843. };
  8844. // TODO: disable send and onmessage on the requestified socket
  8845. return requestified;
  8846. })();
  8847. }
  8848. module.exports = requestify;
  8849. /***/ },
  8850. /* 52 */
  8851. /***/ function(module, exports, __webpack_require__) {
  8852. //var Emitter = require('emitter-component');
  8853. /**
  8854. * Peer
  8855. * A peer can send and receive messages via a connected message bus
  8856. * @param {string} id
  8857. * @param {function(string, string, *)} send A function to send a message to an other peer
  8858. */
  8859. function Peer(id, send) {
  8860. this.id = id;
  8861. this._send = send;
  8862. this.listeners = {};
  8863. }
  8864. /**
  8865. * Send a message to another peer
  8866. * @param {string} to Id of the recipient
  8867. * @param {*} message Message to be send, can be JSON
  8868. * @returns {Promise.<null, Error>} Resolves when sent
  8869. */
  8870. Peer.prototype.send = function (to, message) {
  8871. return this._send(this.id, to, message);
  8872. };
  8873. // Extend the Peer with event emitter functionality
  8874. //Emitter(Peer.prototype);
  8875. // TODO: complete this custom event emitter, it's about 5 times as fast as Emitter because its not slicing arguments
  8876. /**
  8877. * Register an event listener
  8878. * @param {string} event Available events: 'message'
  8879. * @param {Function} callback Callback function, called as callback(from, message)
  8880. */
  8881. Peer.prototype.on = function (event, callback) {
  8882. if (!(event in this.listeners)) this.listeners[event] = [];
  8883. this.listeners[event].push(callback);
  8884. };
  8885. // TODO: implement off
  8886. /**
  8887. * Emit an event
  8888. * @param {string} event For example 'message'
  8889. * @param {string} from Id of the sender, for example 'peer1'
  8890. * @param {*} message A message, can be any type. Must be serializable JSON.
  8891. */
  8892. Peer.prototype.emit = function (event, from, message) {
  8893. var listeners = this.listeners[event];
  8894. if (listeners) {
  8895. for (var i = 0, ii = listeners.length; i < ii; i++) {
  8896. var listener = listeners[i];
  8897. listener(from, message);
  8898. }
  8899. }
  8900. };
  8901. module.exports = Peer;
  8902. /***/ },
  8903. /* 53 */
  8904. /***/ function(module, exports, __webpack_require__) {
  8905. var Stream = __webpack_require__(64);
  8906. var util = __webpack_require__(79);
  8907. var Response = module.exports = function (res) {
  8908. this.offset = 0;
  8909. this.readable = true;
  8910. };
  8911. util.inherits(Response, Stream);
  8912. var capable = {
  8913. streaming : true,
  8914. status2 : true
  8915. };
  8916. function parseHeaders (res) {
  8917. var lines = res.getAllResponseHeaders().split(/\r?\n/);
  8918. var headers = {};
  8919. for (var i = 0; i < lines.length; i++) {
  8920. var line = lines[i];
  8921. if (line === '') continue;
  8922. var m = line.match(/^([^:]+):\s*(.*)/);
  8923. if (m) {
  8924. var key = m[1].toLowerCase(), value = m[2];
  8925. if (headers[key] !== undefined) {
  8926. if (isArray(headers[key])) {
  8927. headers[key].push(value);
  8928. }
  8929. else {
  8930. headers[key] = [ headers[key], value ];
  8931. }
  8932. }
  8933. else {
  8934. headers[key] = value;
  8935. }
  8936. }
  8937. else {
  8938. headers[line] = true;
  8939. }
  8940. }
  8941. return headers;
  8942. }
  8943. Response.prototype.getResponse = function (xhr) {
  8944. var respType = String(xhr.responseType).toLowerCase();
  8945. if (respType === 'blob') return xhr.responseBlob || xhr.response;
  8946. if (respType === 'arraybuffer') return xhr.response;
  8947. return xhr.responseText;
  8948. }
  8949. Response.prototype.getHeader = function (key) {
  8950. return this.headers[key.toLowerCase()];
  8951. };
  8952. Response.prototype.handle = function (res) {
  8953. if (res.readyState === 2 && capable.status2) {
  8954. try {
  8955. this.statusCode = res.status;
  8956. this.headers = parseHeaders(res);
  8957. }
  8958. catch (err) {
  8959. capable.status2 = false;
  8960. }
  8961. if (capable.status2) {
  8962. this.emit('ready');
  8963. }
  8964. }
  8965. else if (capable.streaming && res.readyState === 3) {
  8966. try {
  8967. if (!this.statusCode) {
  8968. this.statusCode = res.status;
  8969. this.headers = parseHeaders(res);
  8970. this.emit('ready');
  8971. }
  8972. }
  8973. catch (err) {}
  8974. try {
  8975. this._emitData(res);
  8976. }
  8977. catch (err) {
  8978. capable.streaming = false;
  8979. }
  8980. }
  8981. else if (res.readyState === 4) {
  8982. if (!this.statusCode) {
  8983. this.statusCode = res.status;
  8984. this.emit('ready');
  8985. }
  8986. this._emitData(res);
  8987. if (res.error) {
  8988. this.emit('error', this.getResponse(res));
  8989. }
  8990. else this.emit('end');
  8991. this.emit('close');
  8992. }
  8993. };
  8994. Response.prototype._emitData = function (res) {
  8995. var respBody = this.getResponse(res);
  8996. if (respBody.toString().match(/ArrayBuffer/)) {
  8997. this.emit('data', new Uint8Array(respBody, this.offset));
  8998. this.offset = respBody.byteLength;
  8999. return;
  9000. }
  9001. if (respBody.length > this.offset) {
  9002. this.emit('data', respBody.slice(this.offset));
  9003. this.offset = respBody.length;
  9004. }
  9005. };
  9006. var isArray = Array.isArray || function (xs) {
  9007. return Object.prototype.toString.call(xs) === '[object Array]';
  9008. };
  9009. /***/ },
  9010. /* 54 */
  9011. /***/ function(module, exports, __webpack_require__) {
  9012. var __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(module, global) {/*! http://mths.be/punycode v1.2.4 by @mathias */
  9013. ;(function(root) {
  9014. /** Detect free variables */
  9015. var freeExports = typeof exports == 'object' && exports;
  9016. var freeModule = typeof module == 'object' && module &&
  9017. module.exports == freeExports && module;
  9018. var freeGlobal = typeof global == 'object' && global;
  9019. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  9020. root = freeGlobal;
  9021. }
  9022. /**
  9023. * The `punycode` object.
  9024. * @name punycode
  9025. * @type Object
  9026. */
  9027. var punycode,
  9028. /** Highest positive signed 32-bit float value */
  9029. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  9030. /** Bootstring parameters */
  9031. base = 36,
  9032. tMin = 1,
  9033. tMax = 26,
  9034. skew = 38,
  9035. damp = 700,
  9036. initialBias = 72,
  9037. initialN = 128, // 0x80
  9038. delimiter = '-', // '\x2D'
  9039. /** Regular expressions */
  9040. regexPunycode = /^xn--/,
  9041. regexNonASCII = /[^ -~]/, // unprintable ASCII chars + non-ASCII chars
  9042. regexSeparators = /\x2E|\u3002|\uFF0E|\uFF61/g, // RFC 3490 separators
  9043. /** Error messages */
  9044. errors = {
  9045. 'overflow': 'Overflow: input needs wider integers to process',
  9046. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  9047. 'invalid-input': 'Invalid input'
  9048. },
  9049. /** Convenience shortcuts */
  9050. baseMinusTMin = base - tMin,
  9051. floor = Math.floor,
  9052. stringFromCharCode = String.fromCharCode,
  9053. /** Temporary variable */
  9054. key;
  9055. /*--------------------------------------------------------------------------*/
  9056. /**
  9057. * A generic error utility function.
  9058. * @private
  9059. * @param {String} type The error type.
  9060. * @returns {Error} Throws a `RangeError` with the applicable error message.
  9061. */
  9062. function error(type) {
  9063. throw RangeError(errors[type]);
  9064. }
  9065. /**
  9066. * A generic `Array#map` utility function.
  9067. * @private
  9068. * @param {Array} array The array to iterate over.
  9069. * @param {Function} callback The function that gets called for every array
  9070. * item.
  9071. * @returns {Array} A new array of values returned by the callback function.
  9072. */
  9073. function map(array, fn) {
  9074. var length = array.length;
  9075. while (length--) {
  9076. array[length] = fn(array[length]);
  9077. }
  9078. return array;
  9079. }
  9080. /**
  9081. * A simple `Array#map`-like wrapper to work with domain name strings.
  9082. * @private
  9083. * @param {String} domain The domain name.
  9084. * @param {Function} callback The function that gets called for every
  9085. * character.
  9086. * @returns {Array} A new string of characters returned by the callback
  9087. * function.
  9088. */
  9089. function mapDomain(string, fn) {
  9090. return map(string.split(regexSeparators), fn).join('.');
  9091. }
  9092. /**
  9093. * Creates an array containing the numeric code points of each Unicode
  9094. * character in the string. While JavaScript uses UCS-2 internally,
  9095. * this function will convert a pair of surrogate halves (each of which
  9096. * UCS-2 exposes as separate characters) into a single code point,
  9097. * matching UTF-16.
  9098. * @see `punycode.ucs2.encode`
  9099. * @see <http://mathiasbynens.be/notes/javascript-encoding>
  9100. * @memberOf punycode.ucs2
  9101. * @name decode
  9102. * @param {String} string The Unicode input string (UCS-2).
  9103. * @returns {Array} The new array of code points.
  9104. */
  9105. function ucs2decode(string) {
  9106. var output = [],
  9107. counter = 0,
  9108. length = string.length,
  9109. value,
  9110. extra;
  9111. while (counter < length) {
  9112. value = string.charCodeAt(counter++);
  9113. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  9114. // high surrogate, and there is a next character
  9115. extra = string.charCodeAt(counter++);
  9116. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  9117. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  9118. } else {
  9119. // unmatched surrogate; only append this code unit, in case the next
  9120. // code unit is the high surrogate of a surrogate pair
  9121. output.push(value);
  9122. counter--;
  9123. }
  9124. } else {
  9125. output.push(value);
  9126. }
  9127. }
  9128. return output;
  9129. }
  9130. /**
  9131. * Creates a string based on an array of numeric code points.
  9132. * @see `punycode.ucs2.decode`
  9133. * @memberOf punycode.ucs2
  9134. * @name encode
  9135. * @param {Array} codePoints The array of numeric code points.
  9136. * @returns {String} The new Unicode string (UCS-2).
  9137. */
  9138. function ucs2encode(array) {
  9139. return map(array, function(value) {
  9140. var output = '';
  9141. if (value > 0xFFFF) {
  9142. value -= 0x10000;
  9143. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  9144. value = 0xDC00 | value & 0x3FF;
  9145. }
  9146. output += stringFromCharCode(value);
  9147. return output;
  9148. }).join('');
  9149. }
  9150. /**
  9151. * Converts a basic code point into a digit/integer.
  9152. * @see `digitToBasic()`
  9153. * @private
  9154. * @param {Number} codePoint The basic numeric code point value.
  9155. * @returns {Number} The numeric value of a basic code point (for use in
  9156. * representing integers) in the range `0` to `base - 1`, or `base` if
  9157. * the code point does not represent a value.
  9158. */
  9159. function basicToDigit(codePoint) {
  9160. if (codePoint - 48 < 10) {
  9161. return codePoint - 22;
  9162. }
  9163. if (codePoint - 65 < 26) {
  9164. return codePoint - 65;
  9165. }
  9166. if (codePoint - 97 < 26) {
  9167. return codePoint - 97;
  9168. }
  9169. return base;
  9170. }
  9171. /**
  9172. * Converts a digit/integer into a basic code point.
  9173. * @see `basicToDigit()`
  9174. * @private
  9175. * @param {Number} digit The numeric value of a basic code point.
  9176. * @returns {Number} The basic code point whose value (when used for
  9177. * representing integers) is `digit`, which needs to be in the range
  9178. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  9179. * used; else, the lowercase form is used. The behavior is undefined
  9180. * if `flag` is non-zero and `digit` has no uppercase form.
  9181. */
  9182. function digitToBasic(digit, flag) {
  9183. // 0..25 map to ASCII a..z or A..Z
  9184. // 26..35 map to ASCII 0..9
  9185. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  9186. }
  9187. /**
  9188. * Bias adaptation function as per section 3.4 of RFC 3492.
  9189. * http://tools.ietf.org/html/rfc3492#section-3.4
  9190. * @private
  9191. */
  9192. function adapt(delta, numPoints, firstTime) {
  9193. var k = 0;
  9194. delta = firstTime ? floor(delta / damp) : delta >> 1;
  9195. delta += floor(delta / numPoints);
  9196. for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  9197. delta = floor(delta / baseMinusTMin);
  9198. }
  9199. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  9200. }
  9201. /**
  9202. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  9203. * symbols.
  9204. * @memberOf punycode
  9205. * @param {String} input The Punycode string of ASCII-only symbols.
  9206. * @returns {String} The resulting string of Unicode symbols.
  9207. */
  9208. function decode(input) {
  9209. // Don't use UCS-2
  9210. var output = [],
  9211. inputLength = input.length,
  9212. out,
  9213. i = 0,
  9214. n = initialN,
  9215. bias = initialBias,
  9216. basic,
  9217. j,
  9218. index,
  9219. oldi,
  9220. w,
  9221. k,
  9222. digit,
  9223. t,
  9224. /** Cached calculation results */
  9225. baseMinusT;
  9226. // Handle the basic code points: let `basic` be the number of input code
  9227. // points before the last delimiter, or `0` if there is none, then copy
  9228. // the first basic code points to the output.
  9229. basic = input.lastIndexOf(delimiter);
  9230. if (basic < 0) {
  9231. basic = 0;
  9232. }
  9233. for (j = 0; j < basic; ++j) {
  9234. // if it's not a basic code point
  9235. if (input.charCodeAt(j) >= 0x80) {
  9236. error('not-basic');
  9237. }
  9238. output.push(input.charCodeAt(j));
  9239. }
  9240. // Main decoding loop: start just after the last delimiter if any basic code
  9241. // points were copied; start at the beginning otherwise.
  9242. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
  9243. // `index` is the index of the next character to be consumed.
  9244. // Decode a generalized variable-length integer into `delta`,
  9245. // which gets added to `i`. The overflow checking is easier
  9246. // if we increase `i` as we go, then subtract off its starting
  9247. // value at the end to obtain `delta`.
  9248. for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
  9249. if (index >= inputLength) {
  9250. error('invalid-input');
  9251. }
  9252. digit = basicToDigit(input.charCodeAt(index++));
  9253. if (digit >= base || digit > floor((maxInt - i) / w)) {
  9254. error('overflow');
  9255. }
  9256. i += digit * w;
  9257. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  9258. if (digit < t) {
  9259. break;
  9260. }
  9261. baseMinusT = base - t;
  9262. if (w > floor(maxInt / baseMinusT)) {
  9263. error('overflow');
  9264. }
  9265. w *= baseMinusT;
  9266. }
  9267. out = output.length + 1;
  9268. bias = adapt(i - oldi, out, oldi == 0);
  9269. // `i` was supposed to wrap around from `out` to `0`,
  9270. // incrementing `n` each time, so we'll fix that now:
  9271. if (floor(i / out) > maxInt - n) {
  9272. error('overflow');
  9273. }
  9274. n += floor(i / out);
  9275. i %= out;
  9276. // Insert `n` at position `i` of the output
  9277. output.splice(i++, 0, n);
  9278. }
  9279. return ucs2encode(output);
  9280. }
  9281. /**
  9282. * Converts a string of Unicode symbols to a Punycode string of ASCII-only
  9283. * symbols.
  9284. * @memberOf punycode
  9285. * @param {String} input The string of Unicode symbols.
  9286. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  9287. */
  9288. function encode(input) {
  9289. var n,
  9290. delta,
  9291. handledCPCount,
  9292. basicLength,
  9293. bias,
  9294. j,
  9295. m,
  9296. q,
  9297. k,
  9298. t,
  9299. currentValue,
  9300. output = [],
  9301. /** `inputLength` will hold the number of code points in `input`. */
  9302. inputLength,
  9303. /** Cached calculation results */
  9304. handledCPCountPlusOne,
  9305. baseMinusT,
  9306. qMinusT;
  9307. // Convert the input in UCS-2 to Unicode
  9308. input = ucs2decode(input);
  9309. // Cache the length
  9310. inputLength = input.length;
  9311. // Initialize the state
  9312. n = initialN;
  9313. delta = 0;
  9314. bias = initialBias;
  9315. // Handle the basic code points
  9316. for (j = 0; j < inputLength; ++j) {
  9317. currentValue = input[j];
  9318. if (currentValue < 0x80) {
  9319. output.push(stringFromCharCode(currentValue));
  9320. }
  9321. }
  9322. handledCPCount = basicLength = output.length;
  9323. // `handledCPCount` is the number of code points that have been handled;
  9324. // `basicLength` is the number of basic code points.
  9325. // Finish the basic string - if it is not empty - with a delimiter
  9326. if (basicLength) {
  9327. output.push(delimiter);
  9328. }
  9329. // Main encoding loop:
  9330. while (handledCPCount < inputLength) {
  9331. // All non-basic code points < n have been handled already. Find the next
  9332. // larger one:
  9333. for (m = maxInt, j = 0; j < inputLength; ++j) {
  9334. currentValue = input[j];
  9335. if (currentValue >= n && currentValue < m) {
  9336. m = currentValue;
  9337. }
  9338. }
  9339. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  9340. // but guard against overflow
  9341. handledCPCountPlusOne = handledCPCount + 1;
  9342. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  9343. error('overflow');
  9344. }
  9345. delta += (m - n) * handledCPCountPlusOne;
  9346. n = m;
  9347. for (j = 0; j < inputLength; ++j) {
  9348. currentValue = input[j];
  9349. if (currentValue < n && ++delta > maxInt) {
  9350. error('overflow');
  9351. }
  9352. if (currentValue == n) {
  9353. // Represent delta as a generalized variable-length integer
  9354. for (q = delta, k = base; /* no condition */; k += base) {
  9355. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  9356. if (q < t) {
  9357. break;
  9358. }
  9359. qMinusT = q - t;
  9360. baseMinusT = base - t;
  9361. output.push(
  9362. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  9363. );
  9364. q = floor(qMinusT / baseMinusT);
  9365. }
  9366. output.push(stringFromCharCode(digitToBasic(q, 0)));
  9367. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  9368. delta = 0;
  9369. ++handledCPCount;
  9370. }
  9371. }
  9372. ++delta;
  9373. ++n;
  9374. }
  9375. return output.join('');
  9376. }
  9377. /**
  9378. * Converts a Punycode string representing a domain name to Unicode. Only the
  9379. * Punycoded parts of the domain name will be converted, i.e. it doesn't
  9380. * matter if you call it on a string that has already been converted to
  9381. * Unicode.
  9382. * @memberOf punycode
  9383. * @param {String} domain The Punycode domain name to convert to Unicode.
  9384. * @returns {String} The Unicode representation of the given Punycode
  9385. * string.
  9386. */
  9387. function toUnicode(domain) {
  9388. return mapDomain(domain, function(string) {
  9389. return regexPunycode.test(string)
  9390. ? decode(string.slice(4).toLowerCase())
  9391. : string;
  9392. });
  9393. }
  9394. /**
  9395. * Converts a Unicode string representing a domain name to Punycode. Only the
  9396. * non-ASCII parts of the domain name will be converted, i.e. it doesn't
  9397. * matter if you call it with a domain that's already in ASCII.
  9398. * @memberOf punycode
  9399. * @param {String} domain The domain name to convert, as a Unicode string.
  9400. * @returns {String} The Punycode representation of the given domain name.
  9401. */
  9402. function toASCII(domain) {
  9403. return mapDomain(domain, function(string) {
  9404. return regexNonASCII.test(string)
  9405. ? 'xn--' + encode(string)
  9406. : string;
  9407. });
  9408. }
  9409. /*--------------------------------------------------------------------------*/
  9410. /** Define the public API */
  9411. punycode = {
  9412. /**
  9413. * A string representing the current Punycode.js version number.
  9414. * @memberOf punycode
  9415. * @type String
  9416. */
  9417. 'version': '1.2.4',
  9418. /**
  9419. * An object of methods to convert from JavaScript's internal character
  9420. * representation (UCS-2) to Unicode code points, and back.
  9421. * @see <http://mathiasbynens.be/notes/javascript-encoding>
  9422. * @memberOf punycode
  9423. * @type Object
  9424. */
  9425. 'ucs2': {
  9426. 'decode': ucs2decode,
  9427. 'encode': ucs2encode
  9428. },
  9429. 'decode': decode,
  9430. 'encode': encode,
  9431. 'toASCII': toASCII,
  9432. 'toUnicode': toUnicode
  9433. };
  9434. /** Expose `punycode` */
  9435. // Some AMD build optimizers, like r.js, check for specific condition patterns
  9436. // like the following:
  9437. if (
  9438. true
  9439. ) {
  9440. !(__WEBPACK_AMD_DEFINE_RESULT__ = function() {
  9441. return punycode;
  9442. }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  9443. } else if (freeExports && !freeExports.nodeType) {
  9444. if (freeModule) { // in Node.js or RingoJS v0.8.0+
  9445. freeModule.exports = punycode;
  9446. } else { // in Narwhal or RingoJS v0.7.0-
  9447. for (key in punycode) {
  9448. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  9449. }
  9450. }
  9451. } else { // in Rhino or a web browser
  9452. root.punycode = punycode;
  9453. }
  9454. }(this));
  9455. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(83)(module), (function() { return this; }())))
  9456. /***/ },
  9457. /* 55 */
  9458. /***/ function(module, exports, __webpack_require__) {
  9459. module.exports = __webpack_require__(75);
  9460. /***/ },
  9461. /* 56 */
  9462. /***/ function(module, exports, __webpack_require__) {
  9463. 'use strict';
  9464. var Promise = __webpack_require__(90).Promise;
  9465. var Block = __webpack_require__(61);
  9466. var isPromise = __webpack_require__(73).isPromise;
  9467. __webpack_require__(58); // extend Block with function then
  9468. __webpack_require__(57); // extend Block with function listen
  9469. /**
  9470. * Tell
  9471. * Send a message to the other peer.
  9472. * @param {* | Function} message A static message or callback function
  9473. * returning a message dynamically.
  9474. * When `message` is a function, it will be
  9475. * invoked as callback(message, context),
  9476. * where `message` is the output from the
  9477. * previous block in the chain, and `context` is
  9478. * an object where state can be stored during a
  9479. * conversation.
  9480. * @constructor
  9481. * @extends {Block}
  9482. */
  9483. function Tell (message) {
  9484. if (!(this instanceof Tell)) {
  9485. throw new SyntaxError('Constructor must be called with the new operator');
  9486. }
  9487. this.message = message;
  9488. }
  9489. Tell.prototype = Object.create(Block.prototype);
  9490. Tell.prototype.constructor = Tell;
  9491. /**
  9492. * Execute the block
  9493. * @param {Conversation} conversation
  9494. * @param {*} [message] A message is ignored by the Tell block
  9495. * @return {Promise.<{result: *, block: Block}, Error>} next
  9496. */
  9497. Tell.prototype.execute = function (conversation, message) {
  9498. // resolve the message
  9499. var me = this;
  9500. var resolve;
  9501. if (typeof this.message === 'function') {
  9502. var result = this.message(message, conversation.context);
  9503. resolve = isPromise(result) ? result : Promise.resolve(result);
  9504. }
  9505. else {
  9506. resolve = Promise.resolve(this.message); // static string or value
  9507. }
  9508. return resolve
  9509. .then(function (result) {
  9510. var res = conversation.send(result);
  9511. var done = isPromise(res) ? res : Promise.resolve(res);
  9512. return done.then(function () {
  9513. return {
  9514. result: result,
  9515. block: me.next
  9516. };
  9517. });
  9518. });
  9519. };
  9520. /**
  9521. * Create a Tell block and chain it to the current block
  9522. * @param {* | Function} [message] A static message or callback function
  9523. * returning a message dynamically.
  9524. * When `message` is a function, it will be
  9525. * invoked as callback(message, context),
  9526. * where `message` is the output from the
  9527. * previous block in the chain, and `context` is
  9528. * an object where state can be stored during a
  9529. * conversation.
  9530. * @return {Block} Returns the appended block
  9531. */
  9532. Block.prototype.tell = function (message) {
  9533. var block = new Tell(message);
  9534. return this.then(block);
  9535. };
  9536. /**
  9537. * Send a question, listen for a response.
  9538. * Creates two blocks: Tell and Listen.
  9539. * This is equivalent of doing `babble.tell(message).listen(callback)`
  9540. * @param {* | Function} message
  9541. * @param {Function} [callback] Invoked as callback(message, context),
  9542. * where `message` is the just received message,
  9543. * and `context` is an object where state can be
  9544. * stored during a conversation. This is equivalent
  9545. * of doing `listen().then(callback)`
  9546. * @return {Block} Returns the appended block
  9547. */
  9548. Block.prototype.ask = function (message, callback) {
  9549. // FIXME: this doesn't work
  9550. return this
  9551. .tell(message)
  9552. .listen(callback);
  9553. };
  9554. module.exports = Tell;
  9555. /***/ },
  9556. /* 57 */
  9557. /***/ function(module, exports, __webpack_require__) {
  9558. 'use strict';
  9559. var Promise = __webpack_require__(90).Promise;
  9560. var Block = __webpack_require__(61);
  9561. var Then = __webpack_require__(58);
  9562. /**
  9563. * Listen
  9564. * Wait until a message comes in from the connected peer, then continue
  9565. * with the next block in the control flow.
  9566. *
  9567. * @constructor
  9568. * @extends {Block}
  9569. */
  9570. function Listen () {
  9571. if (!(this instanceof Listen)) {
  9572. throw new SyntaxError('Constructor must be called with the new operator');
  9573. }
  9574. }
  9575. Listen.prototype = Object.create(Block.prototype);
  9576. Listen.prototype.constructor = Listen;
  9577. /**
  9578. * Execute the block
  9579. * @param {Conversation} conversation
  9580. * @param {*} [message] Message is ignored by Listen blocks
  9581. * @return {Promise.<{result: *, block: Block}, Error>} next
  9582. */
  9583. Listen.prototype.execute = function (conversation, message) {
  9584. var me = this;
  9585. // wait until a message is received
  9586. return conversation.receive()
  9587. .then(function (message) {
  9588. return {
  9589. result: message,
  9590. block: me.next
  9591. }
  9592. });
  9593. };
  9594. /**
  9595. * Create a Listen block and chain it to the current block
  9596. *
  9597. * Optionally a callback function can be provided, which is equivalent of
  9598. * doing `listen().then(callback)`.
  9599. *
  9600. * @param {Function} [callback] Executed as callback(message: *, context: Object)
  9601. * Must return a result
  9602. * @return {Block} Returns the appended block
  9603. */
  9604. Block.prototype.listen = function (callback) {
  9605. var listen = new Listen();
  9606. var block = this.then(listen);
  9607. if (callback) {
  9608. block = block.then(callback);
  9609. }
  9610. return block;
  9611. };
  9612. module.exports = Listen;
  9613. /***/ },
  9614. /* 58 */
  9615. /***/ function(module, exports, __webpack_require__) {
  9616. 'use strict';
  9617. var Promise = __webpack_require__(90).Promise;
  9618. var Block = __webpack_require__(61);
  9619. var isPromise = __webpack_require__(73).isPromise;
  9620. /**
  9621. * Then
  9622. * Execute a callback function or a next block in the chain.
  9623. * @param {Function} callback Invoked as callback(message, context),
  9624. * where `message` is the output from the previous
  9625. * block in the chain, and `context` is an object
  9626. * where state can be stored during a conversation.
  9627. * @constructor
  9628. * @extends {Block}
  9629. */
  9630. function Then (callback) {
  9631. if (!(this instanceof Then)) {
  9632. throw new SyntaxError('Constructor must be called with the new operator');
  9633. }
  9634. if (!(typeof callback === 'function')) {
  9635. throw new TypeError('Parameter callback must be a Function');
  9636. }
  9637. this.callback = callback;
  9638. }
  9639. Then.prototype = Object.create(Block.prototype);
  9640. Then.prototype.constructor = Then;
  9641. /**
  9642. * Execute the block
  9643. * @param {Conversation} conversation
  9644. * @param {*} message
  9645. * @return {Promise.<{result: *, block: Block}, Error>} next
  9646. */
  9647. Then.prototype.execute = function (conversation, message) {
  9648. var me = this;
  9649. var result = this.callback(message, conversation.context);
  9650. var resolve = isPromise(result) ? result : Promise.resolve(result);
  9651. return resolve.then(function (result) {
  9652. return {
  9653. result: result,
  9654. block: me.next
  9655. }
  9656. });
  9657. };
  9658. /**
  9659. * Chain a block to the current block.
  9660. *
  9661. * When a function is provided, a Then block will be generated which
  9662. * executes the function. The function is invoked as callback(message, context),
  9663. * where `message` is the output from the previous block in the chain,
  9664. * and `context` is an object where state can be stored during a conversation.
  9665. *
  9666. * @param {Block | function} next A callback function or Block.
  9667. * @return {Block} Returns the appended block
  9668. */
  9669. Block.prototype.then = function (next) {
  9670. // turn a callback function into a Then block
  9671. if (typeof next === 'function') {
  9672. next = new Then(next);
  9673. }
  9674. if (!(next instanceof Block)) {
  9675. throw new TypeError('Parameter next must be a Block or function');
  9676. }
  9677. // append after the last block
  9678. next.previous = this;
  9679. this.next = next;
  9680. // return the appended block
  9681. return next;
  9682. };
  9683. module.exports = Then;
  9684. /***/ },
  9685. /* 59 */
  9686. /***/ function(module, exports, __webpack_require__) {
  9687. 'use strict';
  9688. var Promise = __webpack_require__(90).Promise;
  9689. var Block = __webpack_require__(61);
  9690. var isPromise =__webpack_require__(73).isPromise;
  9691. __webpack_require__(58); // extend Block with function then
  9692. /**
  9693. * Decision
  9694. * A decision is made by executing the provided callback function, which returns
  9695. * a next control flow block.
  9696. *
  9697. * Syntax:
  9698. *
  9699. * new Decision(choices)
  9700. * new Decision(decision, choices)
  9701. *
  9702. * Where:
  9703. *
  9704. * {Function | Object} [decision]
  9705. * When a `decision` function is provided, the
  9706. * function is invoked as decision(message, context),
  9707. * where `message` is the output from the previous
  9708. * block in the chain, and `context` is an object
  9709. * where state can be stored during a conversation.
  9710. * The function must return the id for the next
  9711. * block in the control flow, which must be
  9712. * available in the provided `choices`.
  9713. * If `decision` is not provided, the next block
  9714. * will be mapped directly from the message.
  9715. * {Object.<String, Block>} choices
  9716. * A map with the possible next blocks in the flow
  9717. * The next block is selected by the id returned
  9718. * by the decision function.
  9719. *
  9720. * There is one special id for choices: 'default'. This id is called when either
  9721. * the decision function returns an id which does not match any of the available
  9722. * choices.
  9723. *
  9724. * @param arg1
  9725. * @param arg2
  9726. * @constructor
  9727. * @extends {Block}
  9728. */
  9729. function Decision (arg1, arg2) {
  9730. var decision, choices;
  9731. if (!(this instanceof Decision)) {
  9732. throw new SyntaxError('Constructor must be called with the new operator');
  9733. }
  9734. if (typeof arg1 === 'function') {
  9735. decision = arg1;
  9736. choices = arg2;
  9737. }
  9738. else {
  9739. decision = null;
  9740. choices = arg1;
  9741. }
  9742. if (decision) {
  9743. if (typeof decision !== 'function') {
  9744. throw new TypeError('Parameter decision must be a function');
  9745. }
  9746. }
  9747. else {
  9748. decision = function (message, context) {
  9749. return message;
  9750. }
  9751. }
  9752. if (choices && (choices instanceof Function)) {
  9753. throw new TypeError('Parameter choices must be an object');
  9754. }
  9755. this.decision = decision;
  9756. this.choices = {};
  9757. // append all choices
  9758. if (choices) {
  9759. var me = this;
  9760. Object.keys(choices).forEach(function (id) {
  9761. me.addChoice(id, choices[id]);
  9762. });
  9763. }
  9764. }
  9765. Decision.prototype = Object.create(Block.prototype);
  9766. Decision.prototype.constructor = Decision;
  9767. /**
  9768. * Execute the block
  9769. * @param {Conversation} conversation
  9770. * @param {*} message
  9771. * @return {Promise.<{result: *, block: Block}, Error>} next
  9772. */
  9773. Decision.prototype.execute = function (conversation, message) {
  9774. var me = this;
  9775. var id = this.decision(message, conversation.context);
  9776. var resolve = isPromise(id) ? id : Promise.resolve(id);
  9777. return resolve.then(function (id) {
  9778. var next = me.choices[id];
  9779. if (!next) {
  9780. // there is no match, fall back on the default choice
  9781. next = me.choices['default'];
  9782. }
  9783. if (!next) {
  9784. throw new Error('Block with id "' + id + '" not found');
  9785. }
  9786. return {
  9787. result: message,
  9788. block: next
  9789. };
  9790. });
  9791. };
  9792. /**
  9793. * Add a choice to the decision block.
  9794. * The choice can be a new chain of blocks. The first block of the chain
  9795. * will be triggered when the this id comes out of the decision function.
  9796. * @param {String | 'default'} id
  9797. * @param {Block} block
  9798. * @return {Decision} self
  9799. */
  9800. Decision.prototype.addChoice = function (id, block) {
  9801. if (typeof id !== 'string') {
  9802. throw new TypeError('String expected as choice id');
  9803. }
  9804. if (!(block instanceof Block)) {
  9805. throw new TypeError('Block expected as choice');
  9806. }
  9807. if (id in this.choices) {
  9808. throw new Error('Choice with id "' + id + '" already exists');
  9809. }
  9810. // find the first block of the chain
  9811. var first = block;
  9812. while (first && first.previous) {
  9813. first = first.previous;
  9814. }
  9815. this.choices[id] = first;
  9816. return this;
  9817. };
  9818. /**
  9819. * Create a decision block and chain it to the current block.
  9820. * Returns the first block in the chain.
  9821. *
  9822. * Syntax:
  9823. *
  9824. * decide(choices)
  9825. * decide(decision, choices)
  9826. *
  9827. * Where:
  9828. *
  9829. * {Function | Object} [decision]
  9830. * When a `decision` function is provided, the
  9831. * function is invoked as decision(message, context),
  9832. * where `message` is the output from the previous
  9833. * block in the chain, and `context` is an object
  9834. * where state can be stored during a conversation.
  9835. * The function must return the id for the next
  9836. * block in the control flow, which must be
  9837. * available in the provided `choices`.
  9838. * If `decision` is not provided, the next block
  9839. * will be mapped directly from the message.
  9840. * {Object.<String, Block>} choices
  9841. * A map with the possible next blocks in the flow
  9842. * The next block is selected by the id returned
  9843. * by the decision function.
  9844. *
  9845. * There is one special id for choices: 'default'. This id is called when either
  9846. * the decision function returns an id which does not match any of the available
  9847. * choices.
  9848. *
  9849. * @param {Function | Object} arg1 Can be {function} decision or {Object} choices
  9850. * @param {Object} [arg2] choices
  9851. * @return {Block} first First block in the chain
  9852. */
  9853. Block.prototype.decide = function (arg1, arg2) {
  9854. var decision = new Decision(arg1, arg2);
  9855. return this.then(decision);
  9856. };
  9857. module.exports = Decision;
  9858. /***/ },
  9859. /* 60 */
  9860. /***/ function(module, exports, __webpack_require__) {
  9861. 'use strict';
  9862. var Promise = __webpack_require__(90).Promise;
  9863. var Block = __webpack_require__(61);
  9864. var isPromise = __webpack_require__(73).isPromise;
  9865. __webpack_require__(58); // extend Block with function then
  9866. /**
  9867. * IIf
  9868. * Create an iif block, which checks a condition and continues either with
  9869. * the trueBlock or the falseBlock. The input message is passed to the next
  9870. * block in the flow.
  9871. *
  9872. * Can be used as follows:
  9873. * - When `condition` evaluates true:
  9874. * - when `trueBlock` is provided, the flow continues with `trueBlock`
  9875. * - else, when there is a block connected to the IIf block, the flow continues
  9876. * with that block.
  9877. * - When `condition` evaluates false:
  9878. * - when `falseBlock` is provided, the flow continues with `falseBlock`
  9879. *
  9880. * Syntax:
  9881. *
  9882. * new IIf(condition, trueBlock)
  9883. * new IIf(condition, trueBlock [, falseBlock])
  9884. * new IIf(condition).then(...)
  9885. *
  9886. * @param {Function | RegExp | *} condition A condition returning true or false
  9887. * In case of a function,
  9888. * the function is invoked as
  9889. * `condition(message, context)` and
  9890. * must return a boolean. In case of
  9891. * a RegExp, condition will be tested
  9892. * to return true. In other cases,
  9893. * non-strict equality is tested on
  9894. * the input.
  9895. * @param {Block} [trueBlock]
  9896. * @param {Block} [falseBlock]
  9897. * @constructor
  9898. * @extends {Block}
  9899. */
  9900. function IIf (condition, trueBlock, falseBlock) {
  9901. if (!(this instanceof IIf)) {
  9902. throw new SyntaxError('Constructor must be called with the new operator');
  9903. }
  9904. if (condition instanceof Function) {
  9905. this.condition = condition;
  9906. }
  9907. else if (condition instanceof RegExp) {
  9908. this.condition = function (message, context) {
  9909. return condition.test(message);
  9910. }
  9911. }
  9912. else {
  9913. this.condition = function (message, context) {
  9914. return message == condition;
  9915. }
  9916. }
  9917. if (trueBlock && !(trueBlock instanceof Block)) {
  9918. throw new TypeError('Parameter trueBlock must be a Block');
  9919. }
  9920. if (falseBlock && !(falseBlock instanceof Block)) {
  9921. throw new TypeError('Parameter falseBlock must be a Block');
  9922. }
  9923. this.trueBlock = trueBlock || null;
  9924. this.falseBlock = falseBlock || null;
  9925. }
  9926. IIf.prototype = Object.create(Block.prototype);
  9927. IIf.prototype.constructor = IIf;
  9928. /**
  9929. * Execute the block
  9930. * @param {Conversation} conversation
  9931. * @param {*} message
  9932. * @return {Promise.<{result: *, block: Block}, Error>} next
  9933. */
  9934. IIf.prototype.execute = function (conversation, message) {
  9935. var me = this;
  9936. var condition = this.condition(message, conversation.context);
  9937. var resolve = isPromise(condition) ? condition : Promise.resolve(condition);
  9938. return resolve.then(function (condition) {
  9939. var next = condition ? (me.trueBlock || me.next) : me.falseBlock;
  9940. return {
  9941. result: message,
  9942. block: next
  9943. };
  9944. });
  9945. };
  9946. /**
  9947. * IIf
  9948. * Create an iif block, which checks a condition and continues either with
  9949. * the trueBlock or the falseBlock. The input message is passed to the next
  9950. * block in the flow.
  9951. *
  9952. * Can be used as follows:
  9953. * - When `condition` evaluates true:
  9954. * - when `trueBlock` is provided, the flow continues with `trueBlock`
  9955. * - else, when there is a block connected to the IIf block, the flow continues
  9956. * with that block.
  9957. * - When `condition` evaluates false:
  9958. * - when `falseBlock` is provided, the flow continues with `falseBlock`
  9959. *
  9960. * Syntax:
  9961. *
  9962. * new IIf(condition, trueBlock)
  9963. * new IIf(condition, trueBlock [, falseBlock])
  9964. * new IIf(condition).then(...)
  9965. *
  9966. * @param {Function | RegExp | *} condition A condition returning true or false
  9967. * In case of a function,
  9968. * the function is invoked as
  9969. * `condition(message, context)` and
  9970. * must return a boolean. In case of
  9971. * a RegExp, condition will be tested
  9972. * to return true. In other cases,
  9973. * non-strict equality is tested on
  9974. * the input.
  9975. * @param {Block} [trueBlock]
  9976. * @param {Block} [falseBlock]
  9977. * @returns {Block} Returns the created IIf block
  9978. */
  9979. Block.prototype.iif = function (condition, trueBlock, falseBlock) {
  9980. var iif = new IIf(condition, trueBlock, falseBlock);
  9981. return this.then(iif);
  9982. };
  9983. module.exports = IIf;
  9984. /***/ },
  9985. /* 61 */
  9986. /***/ function(module, exports, __webpack_require__) {
  9987. 'use strict';
  9988. /**
  9989. * Abstract control flow diagram block
  9990. * @constructor
  9991. */
  9992. function Block() {
  9993. this.next = null;
  9994. this.previous = null;
  9995. }
  9996. /**
  9997. * Execute the block
  9998. * @param {Conversation} conversation
  9999. * @param {*} message
  10000. * @return {Promise.<{result: *, block: Block}, Error>} next
  10001. */
  10002. Block.prototype.execute = function (conversation, message) {
  10003. throw new Error('Cannot run an abstract Block');
  10004. };
  10005. module.exports = Block;
  10006. /***/ },
  10007. /* 62 */
  10008. /***/ function(module, exports, __webpack_require__) {
  10009. // Copyright Joyent, Inc. and other Node contributors.
  10010. //
  10011. // Permission is hereby granted, free of charge, to any person obtaining a
  10012. // copy of this software and associated documentation files (the
  10013. // "Software"), to deal in the Software without restriction, including
  10014. // without limitation the rights to use, copy, modify, merge, publish,
  10015. // distribute, sublicense, and/or sell copies of the Software, and to permit
  10016. // persons to whom the Software is furnished to do so, subject to the
  10017. // following conditions:
  10018. //
  10019. // The above copyright notice and this permission notice shall be included
  10020. // in all copies or substantial portions of the Software.
  10021. //
  10022. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  10023. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  10024. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  10025. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  10026. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  10027. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  10028. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  10029. 'use strict';
  10030. // If obj.hasOwnProperty has been overridden, then calling
  10031. // obj.hasOwnProperty(prop) will break.
  10032. // See: https://github.com/joyent/node/issues/1707
  10033. function hasOwnProperty(obj, prop) {
  10034. return Object.prototype.hasOwnProperty.call(obj, prop);
  10035. }
  10036. module.exports = function(qs, sep, eq, options) {
  10037. sep = sep || '&';
  10038. eq = eq || '=';
  10039. var obj = {};
  10040. if (typeof qs !== 'string' || qs.length === 0) {
  10041. return obj;
  10042. }
  10043. var regexp = /\+/g;
  10044. qs = qs.split(sep);
  10045. var maxKeys = 1000;
  10046. if (options && typeof options.maxKeys === 'number') {
  10047. maxKeys = options.maxKeys;
  10048. }
  10049. var len = qs.length;
  10050. // maxKeys <= 0 means that we should not limit keys count
  10051. if (maxKeys > 0 && len > maxKeys) {
  10052. len = maxKeys;
  10053. }
  10054. for (var i = 0; i < len; ++i) {
  10055. var x = qs[i].replace(regexp, '%20'),
  10056. idx = x.indexOf(eq),
  10057. kstr, vstr, k, v;
  10058. if (idx >= 0) {
  10059. kstr = x.substr(0, idx);
  10060. vstr = x.substr(idx + 1);
  10061. } else {
  10062. kstr = x;
  10063. vstr = '';
  10064. }
  10065. k = decodeURIComponent(kstr);
  10066. v = decodeURIComponent(vstr);
  10067. if (!hasOwnProperty(obj, k)) {
  10068. obj[k] = v;
  10069. } else if (isArray(obj[k])) {
  10070. obj[k].push(v);
  10071. } else {
  10072. obj[k] = [obj[k], v];
  10073. }
  10074. }
  10075. return obj;
  10076. };
  10077. var isArray = Array.isArray || function (xs) {
  10078. return Object.prototype.toString.call(xs) === '[object Array]';
  10079. };
  10080. /***/ },
  10081. /* 63 */
  10082. /***/ function(module, exports, __webpack_require__) {
  10083. // Copyright Joyent, Inc. and other Node contributors.
  10084. //
  10085. // Permission is hereby granted, free of charge, to any person obtaining a
  10086. // copy of this software and associated documentation files (the
  10087. // "Software"), to deal in the Software without restriction, including
  10088. // without limitation the rights to use, copy, modify, merge, publish,
  10089. // distribute, sublicense, and/or sell copies of the Software, and to permit
  10090. // persons to whom the Software is furnished to do so, subject to the
  10091. // following conditions:
  10092. //
  10093. // The above copyright notice and this permission notice shall be included
  10094. // in all copies or substantial portions of the Software.
  10095. //
  10096. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  10097. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  10098. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  10099. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  10100. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  10101. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  10102. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  10103. 'use strict';
  10104. var stringifyPrimitive = function(v) {
  10105. switch (typeof v) {
  10106. case 'string':
  10107. return v;
  10108. case 'boolean':
  10109. return v ? 'true' : 'false';
  10110. case 'number':
  10111. return isFinite(v) ? v : '';
  10112. default:
  10113. return '';
  10114. }
  10115. };
  10116. module.exports = function(obj, sep, eq, name) {
  10117. sep = sep || '&';
  10118. eq = eq || '=';
  10119. if (obj === null) {
  10120. obj = undefined;
  10121. }
  10122. if (typeof obj === 'object') {
  10123. return map(objectKeys(obj), function(k) {
  10124. var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
  10125. if (isArray(obj[k])) {
  10126. return map(obj[k], function(v) {
  10127. return ks + encodeURIComponent(stringifyPrimitive(v));
  10128. }).join(sep);
  10129. } else {
  10130. return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
  10131. }
  10132. }).join(sep);
  10133. }
  10134. if (!name) return '';
  10135. return encodeURIComponent(stringifyPrimitive(name)) + eq +
  10136. encodeURIComponent(stringifyPrimitive(obj));
  10137. };
  10138. var isArray = Array.isArray || function (xs) {
  10139. return Object.prototype.toString.call(xs) === '[object Array]';
  10140. };
  10141. function map (xs, f) {
  10142. if (xs.map) return xs.map(f);
  10143. var res = [];
  10144. for (var i = 0; i < xs.length; i++) {
  10145. res.push(f(xs[i], i));
  10146. }
  10147. return res;
  10148. }
  10149. var objectKeys = Object.keys || function (obj) {
  10150. var res = [];
  10151. for (var key in obj) {
  10152. if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
  10153. }
  10154. return res;
  10155. };
  10156. /***/ },
  10157. /* 64 */
  10158. /***/ function(module, exports, __webpack_require__) {
  10159. // Copyright Joyent, Inc. and other Node contributors.
  10160. //
  10161. // Permission is hereby granted, free of charge, to any person obtaining a
  10162. // copy of this software and associated documentation files (the
  10163. // "Software"), to deal in the Software without restriction, including
  10164. // without limitation the rights to use, copy, modify, merge, publish,
  10165. // distribute, sublicense, and/or sell copies of the Software, and to permit
  10166. // persons to whom the Software is furnished to do so, subject to the
  10167. // following conditions:
  10168. //
  10169. // The above copyright notice and this permission notice shall be included
  10170. // in all copies or substantial portions of the Software.
  10171. //
  10172. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  10173. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  10174. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  10175. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  10176. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  10177. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  10178. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  10179. module.exports = Stream;
  10180. var EE = __webpack_require__(44).EventEmitter;
  10181. var inherits = __webpack_require__(101);
  10182. inherits(Stream, EE);
  10183. Stream.Readable = __webpack_require__(93);
  10184. Stream.Writable = __webpack_require__(94);
  10185. Stream.Duplex = __webpack_require__(95);
  10186. Stream.Transform = __webpack_require__(96);
  10187. Stream.PassThrough = __webpack_require__(97);
  10188. // Backwards-compat with node 0.4.x
  10189. Stream.Stream = Stream;
  10190. // old-style streams. Note that the pipe method (the only relevant
  10191. // part of this class) is overridden in the Readable class.
  10192. function Stream() {
  10193. EE.call(this);
  10194. }
  10195. Stream.prototype.pipe = function(dest, options) {
  10196. var source = this;
  10197. function ondata(chunk) {
  10198. if (dest.writable) {
  10199. if (false === dest.write(chunk) && source.pause) {
  10200. source.pause();
  10201. }
  10202. }
  10203. }
  10204. source.on('data', ondata);
  10205. function ondrain() {
  10206. if (source.readable && source.resume) {
  10207. source.resume();
  10208. }
  10209. }
  10210. dest.on('drain', ondrain);
  10211. // If the 'end' option is not supplied, dest.end() will be called when
  10212. // source gets the 'end' or 'close' events. Only dest.end() once.
  10213. if (!dest._isStdio && (!options || options.end !== false)) {
  10214. source.on('end', onend);
  10215. source.on('close', onclose);
  10216. }
  10217. var didOnEnd = false;
  10218. function onend() {
  10219. if (didOnEnd) return;
  10220. didOnEnd = true;
  10221. dest.end();
  10222. }
  10223. function onclose() {
  10224. if (didOnEnd) return;
  10225. didOnEnd = true;
  10226. if (typeof dest.destroy === 'function') dest.destroy();
  10227. }
  10228. // don't leave dangling pipes when there are errors.
  10229. function onerror(er) {
  10230. cleanup();
  10231. if (EE.listenerCount(this, 'error') === 0) {
  10232. throw er; // Unhandled stream error in pipe.
  10233. }
  10234. }
  10235. source.on('error', onerror);
  10236. dest.on('error', onerror);
  10237. // remove all the event listeners that were added.
  10238. function cleanup() {
  10239. source.removeListener('data', ondata);
  10240. dest.removeListener('drain', ondrain);
  10241. source.removeListener('end', onend);
  10242. source.removeListener('close', onclose);
  10243. source.removeListener('error', onerror);
  10244. dest.removeListener('error', onerror);
  10245. source.removeListener('end', cleanup);
  10246. source.removeListener('close', cleanup);
  10247. dest.removeListener('close', cleanup);
  10248. }
  10249. source.on('end', cleanup);
  10250. source.on('close', cleanup);
  10251. dest.on('close', cleanup);
  10252. dest.emit('pipe', source);
  10253. // Allow for unix-like usage: A.pipe(B).pipe(C)
  10254. return dest;
  10255. };
  10256. /***/ },
  10257. /* 65 */
  10258. /***/ function(module, exports, __webpack_require__) {
  10259. /* WEBPACK VAR INJECTION */(function(global, Buffer) {(function() {
  10260. var g = ('undefined' === typeof window ? global : window) || {}
  10261. _crypto = (
  10262. g.crypto || g.msCrypto || __webpack_require__(78)
  10263. )
  10264. module.exports = function(size) {
  10265. // Modern Browsers
  10266. if(_crypto.getRandomValues) {
  10267. var bytes = new Buffer(size); //in browserify, this is an extended Uint8Array
  10268. /* This will not work in older browsers.
  10269. * See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
  10270. */
  10271. _crypto.getRandomValues(bytes);
  10272. return bytes;
  10273. }
  10274. else if (_crypto.randomBytes) {
  10275. return _crypto.randomBytes(size)
  10276. }
  10277. else
  10278. throw new Error(
  10279. 'secure random number generation not supported by this browser\n'+
  10280. 'use chrome, FireFox or Internet Explorer 11'
  10281. )
  10282. }
  10283. }())
  10284. /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(47).Buffer))
  10285. /***/ },
  10286. /* 66 */
  10287. /***/ function(module, exports, __webpack_require__) {
  10288. /* WEBPACK VAR INJECTION */(function(Buffer) {var createHash = __webpack_require__(92)
  10289. var md5 = toConstructor(__webpack_require__(82))
  10290. var rmd160 = toConstructor(__webpack_require__(102))
  10291. function toConstructor (fn) {
  10292. return function () {
  10293. var buffers = []
  10294. var m= {
  10295. update: function (data, enc) {
  10296. if(!Buffer.isBuffer(data)) data = new Buffer(data, enc)
  10297. buffers.push(data)
  10298. return this
  10299. },
  10300. digest: function (enc) {
  10301. var buf = Buffer.concat(buffers)
  10302. var r = fn(buf)
  10303. buffers = null
  10304. return enc ? r.toString(enc) : r
  10305. }
  10306. }
  10307. return m
  10308. }
  10309. }
  10310. module.exports = function (alg) {
  10311. if('md5' === alg) return new md5()
  10312. if('rmd160' === alg) return new rmd160()
  10313. return createHash(alg)
  10314. }
  10315. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(47).Buffer))
  10316. /***/ },
  10317. /* 67 */
  10318. /***/ function(module, exports, __webpack_require__) {
  10319. /* WEBPACK VAR INJECTION */(function(Buffer) {var createHash = __webpack_require__(66)
  10320. var zeroBuffer = new Buffer(128)
  10321. zeroBuffer.fill(0)
  10322. module.exports = Hmac
  10323. function Hmac (alg, key) {
  10324. if(!(this instanceof Hmac)) return new Hmac(alg, key)
  10325. this._opad = opad
  10326. this._alg = alg
  10327. var blocksize = (alg === 'sha512') ? 128 : 64
  10328. key = this._key = !Buffer.isBuffer(key) ? new Buffer(key) : key
  10329. if(key.length > blocksize) {
  10330. key = createHash(alg).update(key).digest()
  10331. } else if(key.length < blocksize) {
  10332. key = Buffer.concat([key, zeroBuffer], blocksize)
  10333. }
  10334. var ipad = this._ipad = new Buffer(blocksize)
  10335. var opad = this._opad = new Buffer(blocksize)
  10336. for(var i = 0; i < blocksize; i++) {
  10337. ipad[i] = key[i] ^ 0x36
  10338. opad[i] = key[i] ^ 0x5C
  10339. }
  10340. this._hash = createHash(alg).update(ipad)
  10341. }
  10342. Hmac.prototype.update = function (data, enc) {
  10343. this._hash.update(data, enc)
  10344. return this
  10345. }
  10346. Hmac.prototype.digest = function (enc) {
  10347. var h = this._hash.digest()
  10348. return createHash(this._alg).update(this._opad).update(h).digest(enc)
  10349. }
  10350. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(47).Buffer))
  10351. /***/ },
  10352. /* 68 */
  10353. /***/ function(module, exports, __webpack_require__) {
  10354. var pbkdf2Export = __webpack_require__(100)
  10355. module.exports = function (crypto, exports) {
  10356. exports = exports || {}
  10357. var exported = pbkdf2Export(crypto)
  10358. exports.pbkdf2 = exported.pbkdf2
  10359. exports.pbkdf2Sync = exported.pbkdf2Sync
  10360. return exports
  10361. }
  10362. /***/ },
  10363. /* 69 */
  10364. /***/ function(module, exports, __webpack_require__) {
  10365. var uuid = __webpack_require__(85);
  10366. var Promise = __webpack_require__(90).Promise;
  10367. /**
  10368. * A conversation
  10369. * Holds meta data for a conversation between two peers
  10370. * @param {Object} [config] Configuration options:
  10371. * {string} [id] A unique id for the conversation. If not provided, a uuid is generated
  10372. * {string} self Id of the peer on this side of the conversation
  10373. * {string} other Id of the peer on the other side of the conversation
  10374. * {Object} [context] Context passed with all callbacks of the conversation
  10375. * {function(to: string, message: *): Promise} send Function to send a message
  10376. * @constructor
  10377. */
  10378. function Conversation (config) {
  10379. if (!(this instanceof Conversation)) {
  10380. throw new SyntaxError('Constructor must be called with the new operator');
  10381. }
  10382. // public properties
  10383. this.id = config && config.id || uuid.v4();
  10384. this.self = config && config.self || null;
  10385. this.other = config && config.other || null;
  10386. this.context = config && config.context || {};
  10387. // private properties
  10388. this._send = config && config.send || null;
  10389. this._inbox = []; // queue with received but not yet picked messages
  10390. this._receivers = []; // queue with handlers waiting for a new message
  10391. }
  10392. /**
  10393. * Send a message
  10394. * @param {*} message
  10395. * @return {Promise.<null>} Resolves when the message has been sent
  10396. */
  10397. Conversation.prototype.send = function (message) {
  10398. return this._send(this.other, {
  10399. id: this.id,
  10400. from: this.self,
  10401. to: this.other,
  10402. message: message
  10403. });
  10404. };
  10405. /**
  10406. * Deliver a message
  10407. * @param {{id: string, from: string, to: string, message: string}} envelope
  10408. */
  10409. Conversation.prototype.deliver = function (envelope) {
  10410. if (this._receivers.length) {
  10411. var receiver = this._receivers.shift();
  10412. receiver(envelope.message);
  10413. }
  10414. else {
  10415. this._inbox.push(envelope.message);
  10416. }
  10417. };
  10418. /**
  10419. * Receive a message.
  10420. * @returns {Promise.<*>} Resolves with a message as soon as a message
  10421. * is delivered.
  10422. */
  10423. Conversation.prototype.receive = function () {
  10424. var me = this;
  10425. if (this._inbox.length) {
  10426. return Promise.resolve(this._inbox.shift());
  10427. }
  10428. else {
  10429. return new Promise(function (resolve) {
  10430. me._receivers.push(resolve);
  10431. })
  10432. }
  10433. };
  10434. module.exports = Conversation;
  10435. /***/ },
  10436. /* 70 */
  10437. /***/ function(module, exports, __webpack_require__) {
  10438. ;(function () {
  10439. var object = true ? exports : this; // #8: web workers
  10440. var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  10441. function InvalidCharacterError(message) {
  10442. this.message = message;
  10443. }
  10444. InvalidCharacterError.prototype = new Error;
  10445. InvalidCharacterError.prototype.name = 'InvalidCharacterError';
  10446. // encoder
  10447. // [https://gist.github.com/999166] by [https://github.com/nignag]
  10448. object.btoa || (
  10449. object.btoa = function (input) {
  10450. for (
  10451. // initialize result and counter
  10452. var block, charCode, idx = 0, map = chars, output = '';
  10453. // if the next input index does not exist:
  10454. // change the mapping table to "="
  10455. // check if d has no fractional digits
  10456. input.charAt(idx | 0) || (map = '=', idx % 1);
  10457. // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8
  10458. output += map.charAt(63 & block >> 8 - idx % 1 * 8)
  10459. ) {
  10460. charCode = input.charCodeAt(idx += 3/4);
  10461. if (charCode > 0xFF) {
  10462. throw new InvalidCharacterError("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
  10463. }
  10464. block = block << 8 | charCode;
  10465. }
  10466. return output;
  10467. });
  10468. // decoder
  10469. // [https://gist.github.com/1020396] by [https://github.com/atk]
  10470. object.atob || (
  10471. object.atob = function (input) {
  10472. input = input.replace(/=+$/, '');
  10473. if (input.length % 4 == 1) {
  10474. throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded.");
  10475. }
  10476. for (
  10477. // initialize result and counters
  10478. var bc = 0, bs, buffer, idx = 0, output = '';
  10479. // get next character
  10480. buffer = input.charAt(idx++);
  10481. // character found in table? initialize bit storage and add its ascii value;
  10482. ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
  10483. // and if not first of each 4 characters,
  10484. // convert the first 8 bits to one ascii character
  10485. bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
  10486. ) {
  10487. // try to find character in table (0-63, not found => -1)
  10488. buffer = chars.indexOf(buffer);
  10489. }
  10490. return output;
  10491. });
  10492. }());
  10493. /***/ },
  10494. /* 71 */
  10495. /***/ function(module, exports, __webpack_require__) {
  10496. if (typeof Object.create === 'function') {
  10497. // implementation from standard node.js 'util' module
  10498. module.exports = function inherits(ctor, superCtor) {
  10499. ctor.super_ = superCtor
  10500. ctor.prototype = Object.create(superCtor.prototype, {
  10501. constructor: {
  10502. value: ctor,
  10503. enumerable: false,
  10504. writable: true,
  10505. configurable: true
  10506. }
  10507. });
  10508. };
  10509. } else {
  10510. // old school shim for old browsers
  10511. module.exports = function inherits(ctor, superCtor) {
  10512. ctor.super_ = superCtor
  10513. var TempCtor = function () {}
  10514. TempCtor.prototype = superCtor.prototype
  10515. ctor.prototype = new TempCtor()
  10516. ctor.prototype.constructor = ctor
  10517. }
  10518. }
  10519. /***/ },
  10520. /* 72 */
  10521. /***/ function(module, exports, __webpack_require__) {
  10522. /* WEBPACK VAR INJECTION */(function(process) {
  10523. // Use the fastest possible means to execute a task in a future turn
  10524. // of the event loop.
  10525. // linked list of tasks (single, with head node)
  10526. var head = {task: void 0, next: null};
  10527. var tail = head;
  10528. var flushing = false;
  10529. var requestFlush = void 0;
  10530. var isNodeJS = false;
  10531. function flush() {
  10532. /* jshint loopfunc: true */
  10533. while (head.next) {
  10534. head = head.next;
  10535. var task = head.task;
  10536. head.task = void 0;
  10537. var domain = head.domain;
  10538. if (domain) {
  10539. head.domain = void 0;
  10540. domain.enter();
  10541. }
  10542. try {
  10543. task();
  10544. } catch (e) {
  10545. if (isNodeJS) {
  10546. // In node, uncaught exceptions are considered fatal errors.
  10547. // Re-throw them synchronously to interrupt flushing!
  10548. // Ensure continuation if the uncaught exception is suppressed
  10549. // listening "uncaughtException" events (as domains does).
  10550. // Continue in next event to avoid tick recursion.
  10551. if (domain) {
  10552. domain.exit();
  10553. }
  10554. setTimeout(flush, 0);
  10555. if (domain) {
  10556. domain.enter();
  10557. }
  10558. throw e;
  10559. } else {
  10560. // In browsers, uncaught exceptions are not fatal.
  10561. // Re-throw them asynchronously to avoid slow-downs.
  10562. setTimeout(function() {
  10563. throw e;
  10564. }, 0);
  10565. }
  10566. }
  10567. if (domain) {
  10568. domain.exit();
  10569. }
  10570. }
  10571. flushing = false;
  10572. }
  10573. if (typeof process !== "undefined" && process.nextTick) {
  10574. // Node.js before 0.9. Note that some fake-Node environments, like the
  10575. // Mocha test runner, introduce a `process` global without a `nextTick`.
  10576. isNodeJS = true;
  10577. requestFlush = function () {
  10578. process.nextTick(flush);
  10579. };
  10580. } else if (typeof setImmediate === "function") {
  10581. // In IE10, Node.js 0.9+, or https://github.com/NobleJS/setImmediate
  10582. if (typeof window !== "undefined") {
  10583. requestFlush = setImmediate.bind(window, flush);
  10584. } else {
  10585. requestFlush = function () {
  10586. setImmediate(flush);
  10587. };
  10588. }
  10589. } else if (typeof MessageChannel !== "undefined") {
  10590. // modern browsers
  10591. // http://www.nonblocking.io/2011/06/windownexttick.html
  10592. var channel = new MessageChannel();
  10593. channel.port1.onmessage = flush;
  10594. requestFlush = function () {
  10595. channel.port2.postMessage(0);
  10596. };
  10597. } else {
  10598. // old browsers
  10599. requestFlush = function () {
  10600. setTimeout(flush, 0);
  10601. };
  10602. }
  10603. function asap(task) {
  10604. tail = tail.next = {
  10605. task: task,
  10606. domain: isNodeJS && process.domain,
  10607. next: null
  10608. };
  10609. if (!flushing) {
  10610. flushing = true;
  10611. requestFlush();
  10612. }
  10613. };
  10614. module.exports = asap;
  10615. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(99)))
  10616. /***/ },
  10617. /* 73 */
  10618. /***/ function(module, exports, __webpack_require__) {
  10619. /**
  10620. * Test whether the provided value is a Promise.
  10621. * A value is marked as a Promise when it is an object containing functions
  10622. * `then` and `catch`.
  10623. * @param {*} value
  10624. * @return {boolean} Returns true when `value` is a Promise
  10625. */
  10626. exports.isPromise = function (value) {
  10627. return value &&
  10628. typeof value['then'] === 'function' &&
  10629. typeof value['catch'] === 'function'
  10630. };
  10631. /***/ },
  10632. /* 74 */
  10633. /***/ function(module, exports, __webpack_require__) {
  10634. var __WEBPACK_AMD_DEFINE_RESULT__;// uuid.js
  10635. //
  10636. // Copyright (c) 2010-2012 Robert Kieffer
  10637. // MIT License - http://opensource.org/licenses/mit-license.php
  10638. (function() {
  10639. var _global = this;
  10640. // Unique ID creation requires a high quality random # generator. We feature
  10641. // detect to determine the best RNG source, normalizing to a function that
  10642. // returns 128-bits of randomness, since that's what's usually required
  10643. var _rng;
  10644. // Node.js crypto-based RNG - http://nodejs.org/docs/v0.6.2/api/crypto.html
  10645. //
  10646. // Moderately fast, high quality
  10647. if (typeof(_global.require) == 'function') {
  10648. try {
  10649. var _rb = _global.require('crypto').randomBytes;
  10650. _rng = _rb && function() {return _rb(16);};
  10651. } catch(e) {}
  10652. }
  10653. if (!_rng && _global.crypto && crypto.getRandomValues) {
  10654. // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto
  10655. //
  10656. // Moderately fast, high quality
  10657. var _rnds8 = new Uint8Array(16);
  10658. _rng = function whatwgRNG() {
  10659. crypto.getRandomValues(_rnds8);
  10660. return _rnds8;
  10661. };
  10662. }
  10663. if (!_rng) {
  10664. // Math.random()-based (RNG)
  10665. //
  10666. // If all else fails, use Math.random(). It's fast, but is of unspecified
  10667. // quality.
  10668. var _rnds = new Array(16);
  10669. _rng = function() {
  10670. for (var i = 0, r; i < 16; i++) {
  10671. if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
  10672. _rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
  10673. }
  10674. return _rnds;
  10675. };
  10676. }
  10677. // Buffer class to use
  10678. var BufferClass = typeof(_global.Buffer) == 'function' ? _global.Buffer : Array;
  10679. // Maps for number <-> hex string conversion
  10680. var _byteToHex = [];
  10681. var _hexToByte = {};
  10682. for (var i = 0; i < 256; i++) {
  10683. _byteToHex[i] = (i + 0x100).toString(16).substr(1);
  10684. _hexToByte[_byteToHex[i]] = i;
  10685. }
  10686. // **`parse()` - Parse a UUID into it's component bytes**
  10687. function parse(s, buf, offset) {
  10688. var i = (buf && offset) || 0, ii = 0;
  10689. buf = buf || [];
  10690. s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {
  10691. if (ii < 16) { // Don't overflow!
  10692. buf[i + ii++] = _hexToByte[oct];
  10693. }
  10694. });
  10695. // Zero out remaining bytes if string was short
  10696. while (ii < 16) {
  10697. buf[i + ii++] = 0;
  10698. }
  10699. return buf;
  10700. }
  10701. // **`unparse()` - Convert UUID byte array (ala parse()) into a string**
  10702. function unparse(buf, offset) {
  10703. var i = offset || 0, bth = _byteToHex;
  10704. return bth[buf[i++]] + bth[buf[i++]] +
  10705. bth[buf[i++]] + bth[buf[i++]] + '-' +
  10706. bth[buf[i++]] + bth[buf[i++]] + '-' +
  10707. bth[buf[i++]] + bth[buf[i++]] + '-' +
  10708. bth[buf[i++]] + bth[buf[i++]] + '-' +
  10709. bth[buf[i++]] + bth[buf[i++]] +
  10710. bth[buf[i++]] + bth[buf[i++]] +
  10711. bth[buf[i++]] + bth[buf[i++]];
  10712. }
  10713. // **`v1()` - Generate time-based UUID**
  10714. //
  10715. // Inspired by https://github.com/LiosK/UUID.js
  10716. // and http://docs.python.org/library/uuid.html
  10717. // random #'s we need to init node and clockseq
  10718. var _seedBytes = _rng();
  10719. // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
  10720. var _nodeId = [
  10721. _seedBytes[0] | 0x01,
  10722. _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]
  10723. ];
  10724. // Per 4.2.2, randomize (14 bit) clockseq
  10725. var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;
  10726. // Previous uuid creation time
  10727. var _lastMSecs = 0, _lastNSecs = 0;
  10728. // See https://github.com/broofa/node-uuid for API details
  10729. function v1(options, buf, offset) {
  10730. var i = buf && offset || 0;
  10731. var b = buf || [];
  10732. options = options || {};
  10733. var clockseq = options.clockseq != null ? options.clockseq : _clockseq;
  10734. // UUID timestamps are 100 nano-second units since the Gregorian epoch,
  10735. // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
  10736. // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
  10737. // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
  10738. var msecs = options.msecs != null ? options.msecs : new Date().getTime();
  10739. // Per 4.2.1.2, use count of uuid's generated during the current clock
  10740. // cycle to simulate higher resolution clock
  10741. var nsecs = options.nsecs != null ? options.nsecs : _lastNSecs + 1;
  10742. // Time since last uuid creation (in msecs)
  10743. var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
  10744. // Per 4.2.1.2, Bump clockseq on clock regression
  10745. if (dt < 0 && options.clockseq == null) {
  10746. clockseq = clockseq + 1 & 0x3fff;
  10747. }
  10748. // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
  10749. // time interval
  10750. if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) {
  10751. nsecs = 0;
  10752. }
  10753. // Per 4.2.1.2 Throw error if too many uuids are requested
  10754. if (nsecs >= 10000) {
  10755. throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
  10756. }
  10757. _lastMSecs = msecs;
  10758. _lastNSecs = nsecs;
  10759. _clockseq = clockseq;
  10760. // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
  10761. msecs += 12219292800000;
  10762. // `time_low`
  10763. var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
  10764. b[i++] = tl >>> 24 & 0xff;
  10765. b[i++] = tl >>> 16 & 0xff;
  10766. b[i++] = tl >>> 8 & 0xff;
  10767. b[i++] = tl & 0xff;
  10768. // `time_mid`
  10769. var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
  10770. b[i++] = tmh >>> 8 & 0xff;
  10771. b[i++] = tmh & 0xff;
  10772. // `time_high_and_version`
  10773. b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
  10774. b[i++] = tmh >>> 16 & 0xff;
  10775. // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
  10776. b[i++] = clockseq >>> 8 | 0x80;
  10777. // `clock_seq_low`
  10778. b[i++] = clockseq & 0xff;
  10779. // `node`
  10780. var node = options.node || _nodeId;
  10781. for (var n = 0; n < 6; n++) {
  10782. b[i + n] = node[n];
  10783. }
  10784. return buf ? buf : unparse(b);
  10785. }
  10786. // **`v4()` - Generate random UUID**
  10787. // See https://github.com/broofa/node-uuid for API details
  10788. function v4(options, buf, offset) {
  10789. // Deprecated - 'format' argument, as supported in v1.2
  10790. var i = buf && offset || 0;
  10791. if (typeof(options) == 'string') {
  10792. buf = options == 'binary' ? new BufferClass(16) : null;
  10793. options = null;
  10794. }
  10795. options = options || {};
  10796. var rnds = options.random || (options.rng || _rng)();
  10797. // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
  10798. rnds[6] = (rnds[6] & 0x0f) | 0x40;
  10799. rnds[8] = (rnds[8] & 0x3f) | 0x80;
  10800. // Copy bytes to buffer, if provided
  10801. if (buf) {
  10802. for (var ii = 0; ii < 16; ii++) {
  10803. buf[i + ii] = rnds[ii];
  10804. }
  10805. }
  10806. return buf || unparse(rnds);
  10807. }
  10808. // Export public API
  10809. var uuid = v4;
  10810. uuid.v1 = v1;
  10811. uuid.v4 = v4;
  10812. uuid.parse = parse;
  10813. uuid.unparse = unparse;
  10814. uuid.BufferClass = BufferClass;
  10815. if (true) {
  10816. // Publish as AMD module
  10817. !(__WEBPACK_AMD_DEFINE_RESULT__ = function() {return uuid;}.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  10818. } else if (typeof(module) != 'undefined' && module.exports) {
  10819. // Publish as node.js module
  10820. module.exports = uuid;
  10821. } else {
  10822. // Publish as global (in browsers)
  10823. var _previousRoot = _global.uuid;
  10824. // **`noConflict()` - (browser only) to reset global 'uuid' var**
  10825. uuid.noConflict = function() {
  10826. _global.uuid = _previousRoot;
  10827. return uuid;
  10828. };
  10829. _global.uuid = uuid;
  10830. }
  10831. }).call(this);
  10832. /***/ },
  10833. /* 75 */
  10834. /***/ function(module, exports, __webpack_require__) {
  10835. /* WEBPACK VAR INJECTION */(function(process) {/**!
  10836. * agentkeepalive - lib/agent.js
  10837. *
  10838. * refer:
  10839. * * @atimb "Real keep-alive HTTP agent": https://gist.github.com/2963672
  10840. * * https://github.com/joyent/node/blob/master/lib/http.js
  10841. * * https://github.com/joyent/node/blob/master/lib/_http_agent.js
  10842. *
  10843. * Copyright(c) 2012 - 2013 fengmk2 <fengmk2@gmail.com>
  10844. * MIT Licensed
  10845. */
  10846. "use strict";
  10847. /**
  10848. * Module dependencies.
  10849. */
  10850. var http = __webpack_require__(30);
  10851. var https = __webpack_require__(46);
  10852. var util = __webpack_require__(79);
  10853. var debug;
  10854. if (process.env.NODE_DEBUG && /agentkeepalive/.test(process.env.NODE_DEBUG)) {
  10855. debug = function (x) {
  10856. console.error.apply(console, arguments);
  10857. };
  10858. } else {
  10859. debug = function () { };
  10860. }
  10861. var OriginalAgent = http.Agent;
  10862. if (process.version.indexOf('v0.8.') === 0 || process.version.indexOf('v0.10.') === 0) {
  10863. OriginalAgent = __webpack_require__(88).Agent;
  10864. debug('%s use _http_agent', process.version);
  10865. }
  10866. function Agent(options) {
  10867. options = options || {};
  10868. options.keepAlive = options.keepAlive !== false;
  10869. options.keepAliveMsecs = options.keepAliveMsecs || options.maxKeepAliveTime;
  10870. OriginalAgent.call(this, options);
  10871. var self = this;
  10872. // max requests per keepalive socket, default is 0, no limit.
  10873. self.maxKeepAliveRequests = parseInt(options.maxKeepAliveRequests, 10) || 0;
  10874. // max keep alive time, default 60 seconds.
  10875. // if set `keepAliveMsecs = 0`, will disable keepalive feature.
  10876. self.createSocketCount = 0;
  10877. self.timeoutSocketCount = 0;
  10878. self.requestFinishedCount = 0;
  10879. // override the `free` event listener
  10880. self.removeAllListeners('free');
  10881. self.on('free', function (socket, options) {
  10882. self.requestFinishedCount++;
  10883. socket._requestCount++;
  10884. var name = self.getName(options);
  10885. debug('agent.on(free)', name);
  10886. if (!self.isDestroyed(socket) &&
  10887. self.requests[name] && self.requests[name].length) {
  10888. self.requests[name].shift().onSocket(socket);
  10889. if (self.requests[name].length === 0) {
  10890. // don't leak
  10891. delete self.requests[name];
  10892. }
  10893. } else {
  10894. // If there are no pending requests, then put it in
  10895. // the freeSockets pool, but only if we're allowed to do so.
  10896. var req = socket._httpMessage;
  10897. if (req &&
  10898. req.shouldKeepAlive &&
  10899. !self.isDestroyed(socket) &&
  10900. self.options.keepAlive) {
  10901. var freeSockets = self.freeSockets[name];
  10902. var freeLen = freeSockets ? freeSockets.length : 0;
  10903. var count = freeLen;
  10904. if (self.sockets[name])
  10905. count += self.sockets[name].length;
  10906. if (count >= self.maxSockets || freeLen >= self.maxFreeSockets) {
  10907. self.removeSocket(socket, options);
  10908. socket.destroy();
  10909. } else {
  10910. freeSockets = freeSockets || [];
  10911. self.freeSockets[name] = freeSockets;
  10912. socket.setKeepAlive(true, self.keepAliveMsecs);
  10913. socket.unref && socket.unref();
  10914. socket._httpMessage = null;
  10915. self.removeSocket(socket, options);
  10916. freeSockets.push(socket);
  10917. // Avoid duplicitive timeout events by removing timeout listeners set on
  10918. // socket by previous requests. node does not do this normally because it
  10919. // assumes sockets are too short-lived for it to matter. It becomes a
  10920. // problem when sockets are being reused. Steps are being taken to fix
  10921. // this issue upstream in node v0.10.0.
  10922. //
  10923. // See https://github.com/joyent/node/commit/451ff1540ab536237e8d751d241d7fc3391a4087
  10924. if (self.keepAliveMsecs && socket._events && Array.isArray(socket._events.timeout)) {
  10925. socket.removeAllListeners('timeout');
  10926. // Restore the socket's setTimeout() that was remove as collateral
  10927. // damage.
  10928. socket.setTimeout(self.keepAliveMsecs, socket._maxKeepAliveTimeout);
  10929. }
  10930. }
  10931. } else {
  10932. self.removeSocket(socket, options);
  10933. socket.destroy();
  10934. }
  10935. }
  10936. });
  10937. }
  10938. util.inherits(Agent, OriginalAgent);
  10939. module.exports = Agent;
  10940. Agent.prototype.createSocket = function (req, options) {
  10941. var self = this;
  10942. var socket = OriginalAgent.prototype.createSocket.call(this, req, options);
  10943. socket._requestCount = 0;
  10944. if (self.keepAliveMsecs) {
  10945. socket._maxKeepAliveTimeout = function () {
  10946. debug('maxKeepAliveTimeout, socket destroy()');
  10947. socket.destroy();
  10948. self.timeoutSocketCount++;
  10949. };
  10950. socket.setTimeout(self.keepAliveMsecs, socket._maxKeepAliveTimeout);
  10951. // Disable Nagle's algorithm: http://blog.caustik.com/2012/04/08/scaling-node-js-to-100k-concurrent-connections/
  10952. socket.setNoDelay(true);
  10953. }
  10954. this.createSocketCount++;
  10955. return socket;
  10956. };
  10957. Agent.prototype.removeSocket = function (s, options) {
  10958. OriginalAgent.prototype.removeSocket.call(this, s, options);
  10959. var name = this.getName(options);
  10960. debug('removeSocket', name, 'destroyed:', this.isDestroyed(s));
  10961. if (this.isDestroyed(s) && this.freeSockets[name]) {
  10962. var index = this.freeSockets[name].indexOf(s);
  10963. if (index !== -1) {
  10964. this.freeSockets[name].splice(index, 1);
  10965. if (this.freeSockets[name].length === 0) {
  10966. // don't leak
  10967. delete this.freeSockets[name];
  10968. }
  10969. }
  10970. }
  10971. };
  10972. function HttpsAgent(options) {
  10973. Agent.call(this, options);
  10974. this.defaultPort = 443;
  10975. this.protocol = 'https:';
  10976. }
  10977. util.inherits(HttpsAgent, Agent);
  10978. HttpsAgent.prototype.createConnection = https.globalAgent.createConnection;
  10979. HttpsAgent.prototype.getName = function(options) {
  10980. var name = Agent.prototype.getName.call(this, options);
  10981. name += ':';
  10982. if (options.ca)
  10983. name += options.ca;
  10984. name += ':';
  10985. if (options.cert)
  10986. name += options.cert;
  10987. name += ':';
  10988. if (options.ciphers)
  10989. name += options.ciphers;
  10990. name += ':';
  10991. if (options.key)
  10992. name += options.key;
  10993. name += ':';
  10994. if (options.pfx)
  10995. name += options.pfx;
  10996. name += ':';
  10997. if (options.rejectUnauthorized !== undefined)
  10998. name += options.rejectUnauthorized;
  10999. return name;
  11000. };
  11001. Agent.HttpsAgent = HttpsAgent;
  11002. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(99)))
  11003. /***/ },
  11004. /* 76 */
  11005. /***/ function(module, exports, __webpack_require__) {
  11006. /**
  11007. * Module dependencies.
  11008. */
  11009. var global = (function() { return this; })();
  11010. /**
  11011. * WebSocket constructor.
  11012. */
  11013. var WebSocket = global.WebSocket || global.MozWebSocket;
  11014. /**
  11015. * Module exports.
  11016. */
  11017. module.exports = WebSocket ? ws : null;
  11018. /**
  11019. * WebSocket constructor.
  11020. *
  11021. * The third `opts` options object gets ignored in web browsers, since it's
  11022. * non-standard, and throws a TypeError if passed to the constructor.
  11023. * See: https://github.com/einaros/ws/issues/227
  11024. *
  11025. * @param {String} uri
  11026. * @param {Array} protocols (optional)
  11027. * @param {Object) opts (optional)
  11028. * @api public
  11029. */
  11030. function ws(uri, protocols, opts) {
  11031. var instance;
  11032. if (protocols) {
  11033. instance = new WebSocket(uri, protocols);
  11034. } else {
  11035. instance = new WebSocket(uri);
  11036. }
  11037. return instance;
  11038. }
  11039. if (WebSocket) ws.prototype = WebSocket.prototype;
  11040. /***/ },
  11041. /* 77 */
  11042. /***/ function(module, exports, __webpack_require__) {
  11043. /**
  11044. * Copyright (c) 2014 Petka Antonov
  11045. *
  11046. * Permission is hereby granted, free of charge, to any person obtaining a copy
  11047. * of this software and associated documentation files (the "Software"), to deal
  11048. * in the Software without restriction, including without limitation the rights
  11049. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11050. * copies of the Software, and to permit persons to whom the Software is
  11051. * furnished to do so, subject to the following conditions:</p>
  11052. *
  11053. * The above copyright notice and this permission notice shall be included in
  11054. * all copies or substantial portions of the Software.
  11055. *
  11056. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  11057. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  11058. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  11059. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  11060. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  11061. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  11062. * THE SOFTWARE.
  11063. *
  11064. */
  11065. "use strict";
  11066. var Promise = __webpack_require__(91)();
  11067. module.exports = Promise;
  11068. /***/ },
  11069. /* 78 */
  11070. /***/ function(module, exports, __webpack_require__) {
  11071. /* (ignored) */
  11072. /***/ },
  11073. /* 79 */
  11074. /***/ function(module, exports, __webpack_require__) {
  11075. /* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors.
  11076. //
  11077. // Permission is hereby granted, free of charge, to any person obtaining a
  11078. // copy of this software and associated documentation files (the
  11079. // "Software"), to deal in the Software without restriction, including
  11080. // without limitation the rights to use, copy, modify, merge, publish,
  11081. // distribute, sublicense, and/or sell copies of the Software, and to permit
  11082. // persons to whom the Software is furnished to do so, subject to the
  11083. // following conditions:
  11084. //
  11085. // The above copyright notice and this permission notice shall be included
  11086. // in all copies or substantial portions of the Software.
  11087. //
  11088. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  11089. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11090. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  11091. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  11092. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  11093. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  11094. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  11095. var formatRegExp = /%[sdj%]/g;
  11096. exports.format = function(f) {
  11097. if (!isString(f)) {
  11098. var objects = [];
  11099. for (var i = 0; i < arguments.length; i++) {
  11100. objects.push(inspect(arguments[i]));
  11101. }
  11102. return objects.join(' ');
  11103. }
  11104. var i = 1;
  11105. var args = arguments;
  11106. var len = args.length;
  11107. var str = String(f).replace(formatRegExp, function(x) {
  11108. if (x === '%%') return '%';
  11109. if (i >= len) return x;
  11110. switch (x) {
  11111. case '%s': return String(args[i++]);
  11112. case '%d': return Number(args[i++]);
  11113. case '%j':
  11114. try {
  11115. return JSON.stringify(args[i++]);
  11116. } catch (_) {
  11117. return '[Circular]';
  11118. }
  11119. default:
  11120. return x;
  11121. }
  11122. });
  11123. for (var x = args[i]; i < len; x = args[++i]) {
  11124. if (isNull(x) || !isObject(x)) {
  11125. str += ' ' + x;
  11126. } else {
  11127. str += ' ' + inspect(x);
  11128. }
  11129. }
  11130. return str;
  11131. };
  11132. // Mark that a method should not be used.
  11133. // Returns a modified function which warns once by default.
  11134. // If --no-deprecation is set, then it is a no-op.
  11135. exports.deprecate = function(fn, msg) {
  11136. // Allow for deprecating things in the process of starting up.
  11137. if (isUndefined(global.process)) {
  11138. return function() {
  11139. return exports.deprecate(fn, msg).apply(this, arguments);
  11140. };
  11141. }
  11142. if (process.noDeprecation === true) {
  11143. return fn;
  11144. }
  11145. var warned = false;
  11146. function deprecated() {
  11147. if (!warned) {
  11148. if (process.throwDeprecation) {
  11149. throw new Error(msg);
  11150. } else if (process.traceDeprecation) {
  11151. console.trace(msg);
  11152. } else {
  11153. console.error(msg);
  11154. }
  11155. warned = true;
  11156. }
  11157. return fn.apply(this, arguments);
  11158. }
  11159. return deprecated;
  11160. };
  11161. var debugs = {};
  11162. var debugEnviron;
  11163. exports.debuglog = function(set) {
  11164. if (isUndefined(debugEnviron))
  11165. debugEnviron = process.env.NODE_DEBUG || '';
  11166. set = set.toUpperCase();
  11167. if (!debugs[set]) {
  11168. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  11169. var pid = process.pid;
  11170. debugs[set] = function() {
  11171. var msg = exports.format.apply(exports, arguments);
  11172. console.error('%s %d: %s', set, pid, msg);
  11173. };
  11174. } else {
  11175. debugs[set] = function() {};
  11176. }
  11177. }
  11178. return debugs[set];
  11179. };
  11180. /**
  11181. * Echos the value of a value. Trys to print the value out
  11182. * in the best way possible given the different types.
  11183. *
  11184. * @param {Object} obj The object to print out.
  11185. * @param {Object} opts Optional options object that alters the output.
  11186. */
  11187. /* legacy: obj, showHidden, depth, colors*/
  11188. function inspect(obj, opts) {
  11189. // default options
  11190. var ctx = {
  11191. seen: [],
  11192. stylize: stylizeNoColor
  11193. };
  11194. // legacy...
  11195. if (arguments.length >= 3) ctx.depth = arguments[2];
  11196. if (arguments.length >= 4) ctx.colors = arguments[3];
  11197. if (isBoolean(opts)) {
  11198. // legacy...
  11199. ctx.showHidden = opts;
  11200. } else if (opts) {
  11201. // got an "options" object
  11202. exports._extend(ctx, opts);
  11203. }
  11204. // set default options
  11205. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  11206. if (isUndefined(ctx.depth)) ctx.depth = 2;
  11207. if (isUndefined(ctx.colors)) ctx.colors = false;
  11208. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  11209. if (ctx.colors) ctx.stylize = stylizeWithColor;
  11210. return formatValue(ctx, obj, ctx.depth);
  11211. }
  11212. exports.inspect = inspect;
  11213. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  11214. inspect.colors = {
  11215. 'bold' : [1, 22],
  11216. 'italic' : [3, 23],
  11217. 'underline' : [4, 24],
  11218. 'inverse' : [7, 27],
  11219. 'white' : [37, 39],
  11220. 'grey' : [90, 39],
  11221. 'black' : [30, 39],
  11222. 'blue' : [34, 39],
  11223. 'cyan' : [36, 39],
  11224. 'green' : [32, 39],
  11225. 'magenta' : [35, 39],
  11226. 'red' : [31, 39],
  11227. 'yellow' : [33, 39]
  11228. };
  11229. // Don't use 'blue' not visible on cmd.exe
  11230. inspect.styles = {
  11231. 'special': 'cyan',
  11232. 'number': 'yellow',
  11233. 'boolean': 'yellow',
  11234. 'undefined': 'grey',
  11235. 'null': 'bold',
  11236. 'string': 'green',
  11237. 'date': 'magenta',
  11238. // "name": intentionally not styling
  11239. 'regexp': 'red'
  11240. };
  11241. function stylizeWithColor(str, styleType) {
  11242. var style = inspect.styles[styleType];
  11243. if (style) {
  11244. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  11245. '\u001b[' + inspect.colors[style][1] + 'm';
  11246. } else {
  11247. return str;
  11248. }
  11249. }
  11250. function stylizeNoColor(str, styleType) {
  11251. return str;
  11252. }
  11253. function arrayToHash(array) {
  11254. var hash = {};
  11255. array.forEach(function(val, idx) {
  11256. hash[val] = true;
  11257. });
  11258. return hash;
  11259. }
  11260. function formatValue(ctx, value, recurseTimes) {
  11261. // Provide a hook for user-specified inspect functions.
  11262. // Check that value is an object with an inspect function on it
  11263. if (ctx.customInspect &&
  11264. value &&
  11265. isFunction(value.inspect) &&
  11266. // Filter out the util module, it's inspect function is special
  11267. value.inspect !== exports.inspect &&
  11268. // Also filter out any prototype objects using the circular check.
  11269. !(value.constructor && value.constructor.prototype === value)) {
  11270. var ret = value.inspect(recurseTimes, ctx);
  11271. if (!isString(ret)) {
  11272. ret = formatValue(ctx, ret, recurseTimes);
  11273. }
  11274. return ret;
  11275. }
  11276. // Primitive types cannot have properties
  11277. var primitive = formatPrimitive(ctx, value);
  11278. if (primitive) {
  11279. return primitive;
  11280. }
  11281. // Look up the keys of the object.
  11282. var keys = Object.keys(value);
  11283. var visibleKeys = arrayToHash(keys);
  11284. if (ctx.showHidden) {
  11285. keys = Object.getOwnPropertyNames(value);
  11286. }
  11287. // IE doesn't make error fields non-enumerable
  11288. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  11289. if (isError(value)
  11290. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  11291. return formatError(value);
  11292. }
  11293. // Some type of object without properties can be shortcutted.
  11294. if (keys.length === 0) {
  11295. if (isFunction(value)) {
  11296. var name = value.name ? ': ' + value.name : '';
  11297. return ctx.stylize('[Function' + name + ']', 'special');
  11298. }
  11299. if (isRegExp(value)) {
  11300. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  11301. }
  11302. if (isDate(value)) {
  11303. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  11304. }
  11305. if (isError(value)) {
  11306. return formatError(value);
  11307. }
  11308. }
  11309. var base = '', array = false, braces = ['{', '}'];
  11310. // Make Array say that they are Array
  11311. if (isArray(value)) {
  11312. array = true;
  11313. braces = ['[', ']'];
  11314. }
  11315. // Make functions say that they are functions
  11316. if (isFunction(value)) {
  11317. var n = value.name ? ': ' + value.name : '';
  11318. base = ' [Function' + n + ']';
  11319. }
  11320. // Make RegExps say that they are RegExps
  11321. if (isRegExp(value)) {
  11322. base = ' ' + RegExp.prototype.toString.call(value);
  11323. }
  11324. // Make dates with properties first say the date
  11325. if (isDate(value)) {
  11326. base = ' ' + Date.prototype.toUTCString.call(value);
  11327. }
  11328. // Make error with message first say the error
  11329. if (isError(value)) {
  11330. base = ' ' + formatError(value);
  11331. }
  11332. if (keys.length === 0 && (!array || value.length == 0)) {
  11333. return braces[0] + base + braces[1];
  11334. }
  11335. if (recurseTimes < 0) {
  11336. if (isRegExp(value)) {
  11337. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  11338. } else {
  11339. return ctx.stylize('[Object]', 'special');
  11340. }
  11341. }
  11342. ctx.seen.push(value);
  11343. var output;
  11344. if (array) {
  11345. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  11346. } else {
  11347. output = keys.map(function(key) {
  11348. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  11349. });
  11350. }
  11351. ctx.seen.pop();
  11352. return reduceToSingleString(output, base, braces);
  11353. }
  11354. function formatPrimitive(ctx, value) {
  11355. if (isUndefined(value))
  11356. return ctx.stylize('undefined', 'undefined');
  11357. if (isString(value)) {
  11358. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  11359. .replace(/'/g, "\\'")
  11360. .replace(/\\"/g, '"') + '\'';
  11361. return ctx.stylize(simple, 'string');
  11362. }
  11363. if (isNumber(value))
  11364. return ctx.stylize('' + value, 'number');
  11365. if (isBoolean(value))
  11366. return ctx.stylize('' + value, 'boolean');
  11367. // For some reason typeof null is "object", so special case here.
  11368. if (isNull(value))
  11369. return ctx.stylize('null', 'null');
  11370. }
  11371. function formatError(value) {
  11372. return '[' + Error.prototype.toString.call(value) + ']';
  11373. }
  11374. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  11375. var output = [];
  11376. for (var i = 0, l = value.length; i < l; ++i) {
  11377. if (hasOwnProperty(value, String(i))) {
  11378. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  11379. String(i), true));
  11380. } else {
  11381. output.push('');
  11382. }
  11383. }
  11384. keys.forEach(function(key) {
  11385. if (!key.match(/^\d+$/)) {
  11386. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  11387. key, true));
  11388. }
  11389. });
  11390. return output;
  11391. }
  11392. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  11393. var name, str, desc;
  11394. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  11395. if (desc.get) {
  11396. if (desc.set) {
  11397. str = ctx.stylize('[Getter/Setter]', 'special');
  11398. } else {
  11399. str = ctx.stylize('[Getter]', 'special');
  11400. }
  11401. } else {
  11402. if (desc.set) {
  11403. str = ctx.stylize('[Setter]', 'special');
  11404. }
  11405. }
  11406. if (!hasOwnProperty(visibleKeys, key)) {
  11407. name = '[' + key + ']';
  11408. }
  11409. if (!str) {
  11410. if (ctx.seen.indexOf(desc.value) < 0) {
  11411. if (isNull(recurseTimes)) {
  11412. str = formatValue(ctx, desc.value, null);
  11413. } else {
  11414. str = formatValue(ctx, desc.value, recurseTimes - 1);
  11415. }
  11416. if (str.indexOf('\n') > -1) {
  11417. if (array) {
  11418. str = str.split('\n').map(function(line) {
  11419. return ' ' + line;
  11420. }).join('\n').substr(2);
  11421. } else {
  11422. str = '\n' + str.split('\n').map(function(line) {
  11423. return ' ' + line;
  11424. }).join('\n');
  11425. }
  11426. }
  11427. } else {
  11428. str = ctx.stylize('[Circular]', 'special');
  11429. }
  11430. }
  11431. if (isUndefined(name)) {
  11432. if (array && key.match(/^\d+$/)) {
  11433. return str;
  11434. }
  11435. name = JSON.stringify('' + key);
  11436. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  11437. name = name.substr(1, name.length - 2);
  11438. name = ctx.stylize(name, 'name');
  11439. } else {
  11440. name = name.replace(/'/g, "\\'")
  11441. .replace(/\\"/g, '"')
  11442. .replace(/(^"|"$)/g, "'");
  11443. name = ctx.stylize(name, 'string');
  11444. }
  11445. }
  11446. return name + ': ' + str;
  11447. }
  11448. function reduceToSingleString(output, base, braces) {
  11449. var numLinesEst = 0;
  11450. var length = output.reduce(function(prev, cur) {
  11451. numLinesEst++;
  11452. if (cur.indexOf('\n') >= 0) numLinesEst++;
  11453. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  11454. }, 0);
  11455. if (length > 60) {
  11456. return braces[0] +
  11457. (base === '' ? '' : base + '\n ') +
  11458. ' ' +
  11459. output.join(',\n ') +
  11460. ' ' +
  11461. braces[1];
  11462. }
  11463. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  11464. }
  11465. // NOTE: These type checking functions intentionally don't use `instanceof`
  11466. // because it is fragile and can be easily faked with `Object.create()`.
  11467. function isArray(ar) {
  11468. return Array.isArray(ar);
  11469. }
  11470. exports.isArray = isArray;
  11471. function isBoolean(arg) {
  11472. return typeof arg === 'boolean';
  11473. }
  11474. exports.isBoolean = isBoolean;
  11475. function isNull(arg) {
  11476. return arg === null;
  11477. }
  11478. exports.isNull = isNull;
  11479. function isNullOrUndefined(arg) {
  11480. return arg == null;
  11481. }
  11482. exports.isNullOrUndefined = isNullOrUndefined;
  11483. function isNumber(arg) {
  11484. return typeof arg === 'number';
  11485. }
  11486. exports.isNumber = isNumber;
  11487. function isString(arg) {
  11488. return typeof arg === 'string';
  11489. }
  11490. exports.isString = isString;
  11491. function isSymbol(arg) {
  11492. return typeof arg === 'symbol';
  11493. }
  11494. exports.isSymbol = isSymbol;
  11495. function isUndefined(arg) {
  11496. return arg === void 0;
  11497. }
  11498. exports.isUndefined = isUndefined;
  11499. function isRegExp(re) {
  11500. return isObject(re) && objectToString(re) === '[object RegExp]';
  11501. }
  11502. exports.isRegExp = isRegExp;
  11503. function isObject(arg) {
  11504. return typeof arg === 'object' && arg !== null;
  11505. }
  11506. exports.isObject = isObject;
  11507. function isDate(d) {
  11508. return isObject(d) && objectToString(d) === '[object Date]';
  11509. }
  11510. exports.isDate = isDate;
  11511. function isError(e) {
  11512. return isObject(e) &&
  11513. (objectToString(e) === '[object Error]' || e instanceof Error);
  11514. }
  11515. exports.isError = isError;
  11516. function isFunction(arg) {
  11517. return typeof arg === 'function';
  11518. }
  11519. exports.isFunction = isFunction;
  11520. function isPrimitive(arg) {
  11521. return arg === null ||
  11522. typeof arg === 'boolean' ||
  11523. typeof arg === 'number' ||
  11524. typeof arg === 'string' ||
  11525. typeof arg === 'symbol' || // ES6 symbol
  11526. typeof arg === 'undefined';
  11527. }
  11528. exports.isPrimitive = isPrimitive;
  11529. exports.isBuffer = __webpack_require__(106);
  11530. function objectToString(o) {
  11531. return Object.prototype.toString.call(o);
  11532. }
  11533. function pad(n) {
  11534. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  11535. }
  11536. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  11537. 'Oct', 'Nov', 'Dec'];
  11538. // 26 Feb 16:19:34
  11539. function timestamp() {
  11540. var d = new Date();
  11541. var time = [pad(d.getHours()),
  11542. pad(d.getMinutes()),
  11543. pad(d.getSeconds())].join(':');
  11544. return [d.getDate(), months[d.getMonth()], time].join(' ');
  11545. }
  11546. // log is just a thin wrapper to console.log that prepends a timestamp
  11547. exports.log = function() {
  11548. console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
  11549. };
  11550. /**
  11551. * Inherit the prototype methods from one constructor into another.
  11552. *
  11553. * The Function.prototype.inherits from lang.js rewritten as a standalone
  11554. * function (not on Function.prototype). NOTE: If this file is to be loaded
  11555. * during bootstrapping this function needs to be rewritten using some native
  11556. * functions as prototype setup using normal JavaScript does not work as
  11557. * expected during bootstrapping (see mirror.js in r114903).
  11558. *
  11559. * @param {function} ctor Constructor function which needs to inherit the
  11560. * prototype.
  11561. * @param {function} superCtor Constructor function to inherit prototype from.
  11562. */
  11563. exports.inherits = __webpack_require__(146);
  11564. exports._extend = function(origin, add) {
  11565. // Don't do anything if add isn't an object
  11566. if (!add || !isObject(add)) return origin;
  11567. var keys = Object.keys(add);
  11568. var i = keys.length;
  11569. while (i--) {
  11570. origin[keys[i]] = add[keys[i]];
  11571. }
  11572. return origin;
  11573. };
  11574. function hasOwnProperty(obj, prop) {
  11575. return Object.prototype.hasOwnProperty.call(obj, prop);
  11576. }
  11577. /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(99)))
  11578. /***/ },
  11579. /* 80 */
  11580. /***/ function(module, exports, __webpack_require__) {
  11581. exports.read = function(buffer, offset, isLE, mLen, nBytes) {
  11582. var e, m,
  11583. eLen = nBytes * 8 - mLen - 1,
  11584. eMax = (1 << eLen) - 1,
  11585. eBias = eMax >> 1,
  11586. nBits = -7,
  11587. i = isLE ? (nBytes - 1) : 0,
  11588. d = isLE ? -1 : 1,
  11589. s = buffer[offset + i];
  11590. i += d;
  11591. e = s & ((1 << (-nBits)) - 1);
  11592. s >>= (-nBits);
  11593. nBits += eLen;
  11594. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8);
  11595. m = e & ((1 << (-nBits)) - 1);
  11596. e >>= (-nBits);
  11597. nBits += mLen;
  11598. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8);
  11599. if (e === 0) {
  11600. e = 1 - eBias;
  11601. } else if (e === eMax) {
  11602. return m ? NaN : ((s ? -1 : 1) * Infinity);
  11603. } else {
  11604. m = m + Math.pow(2, mLen);
  11605. e = e - eBias;
  11606. }
  11607. return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
  11608. };
  11609. exports.write = function(buffer, value, offset, isLE, mLen, nBytes) {
  11610. var e, m, c,
  11611. eLen = nBytes * 8 - mLen - 1,
  11612. eMax = (1 << eLen) - 1,
  11613. eBias = eMax >> 1,
  11614. rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
  11615. i = isLE ? 0 : (nBytes - 1),
  11616. d = isLE ? 1 : -1,
  11617. s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
  11618. value = Math.abs(value);
  11619. if (isNaN(value) || value === Infinity) {
  11620. m = isNaN(value) ? 1 : 0;
  11621. e = eMax;
  11622. } else {
  11623. e = Math.floor(Math.log(value) / Math.LN2);
  11624. if (value * (c = Math.pow(2, -e)) < 1) {
  11625. e--;
  11626. c *= 2;
  11627. }
  11628. if (e + eBias >= 1) {
  11629. value += rt / c;
  11630. } else {
  11631. value += rt * Math.pow(2, 1 - eBias);
  11632. }
  11633. if (value * c >= 2) {
  11634. e++;
  11635. c /= 2;
  11636. }
  11637. if (e + eBias >= eMax) {
  11638. m = 0;
  11639. e = eMax;
  11640. } else if (e + eBias >= 1) {
  11641. m = (value * c - 1) * Math.pow(2, mLen);
  11642. e = e + eBias;
  11643. } else {
  11644. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
  11645. e = 0;
  11646. }
  11647. }
  11648. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8);
  11649. e = (e << mLen) | m;
  11650. eLen += mLen;
  11651. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8);
  11652. buffer[offset + i - d] |= s * 128;
  11653. };
  11654. /***/ },
  11655. /* 81 */
  11656. /***/ function(module, exports, __webpack_require__) {
  11657. /**
  11658. * isArray
  11659. */
  11660. var isArray = Array.isArray;
  11661. /**
  11662. * toString
  11663. */
  11664. var str = Object.prototype.toString;
  11665. /**
  11666. * Whether or not the given `val`
  11667. * is an array.
  11668. *
  11669. * example:
  11670. *
  11671. * isArray([]);
  11672. * // > true
  11673. * isArray(arguments);
  11674. * // > false
  11675. * isArray('');
  11676. * // > false
  11677. *
  11678. * @param {mixed} val
  11679. * @return {bool}
  11680. */
  11681. module.exports = isArray || function (val) {
  11682. return !! val && '[object Array]' == str.call(val);
  11683. };
  11684. /***/ },
  11685. /* 82 */
  11686. /***/ function(module, exports, __webpack_require__) {
  11687. /*
  11688. * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
  11689. * Digest Algorithm, as defined in RFC 1321.
  11690. * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
  11691. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  11692. * Distributed under the BSD License
  11693. * See http://pajhome.org.uk/crypt/md5 for more info.
  11694. */
  11695. var helpers = __webpack_require__(98);
  11696. /*
  11697. * Calculate the MD5 of an array of little-endian words, and a bit length
  11698. */
  11699. function core_md5(x, len)
  11700. {
  11701. /* append padding */
  11702. x[len >> 5] |= 0x80 << ((len) % 32);
  11703. x[(((len + 64) >>> 9) << 4) + 14] = len;
  11704. var a = 1732584193;
  11705. var b = -271733879;
  11706. var c = -1732584194;
  11707. var d = 271733878;
  11708. for(var i = 0; i < x.length; i += 16)
  11709. {
  11710. var olda = a;
  11711. var oldb = b;
  11712. var oldc = c;
  11713. var oldd = d;
  11714. a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
  11715. d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
  11716. c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
  11717. b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
  11718. a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
  11719. d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
  11720. c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
  11721. b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
  11722. a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
  11723. d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
  11724. c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
  11725. b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
  11726. a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
  11727. d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
  11728. c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
  11729. b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
  11730. a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
  11731. d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
  11732. c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
  11733. b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
  11734. a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
  11735. d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
  11736. c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
  11737. b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
  11738. a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
  11739. d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
  11740. c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
  11741. b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
  11742. a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
  11743. d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
  11744. c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
  11745. b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
  11746. a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
  11747. d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
  11748. c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
  11749. b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
  11750. a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
  11751. d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
  11752. c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
  11753. b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
  11754. a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
  11755. d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
  11756. c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
  11757. b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
  11758. a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
  11759. d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
  11760. c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
  11761. b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
  11762. a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
  11763. d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
  11764. c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
  11765. b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
  11766. a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
  11767. d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
  11768. c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
  11769. b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
  11770. a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
  11771. d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
  11772. c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
  11773. b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
  11774. a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
  11775. d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
  11776. c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
  11777. b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
  11778. a = safe_add(a, olda);
  11779. b = safe_add(b, oldb);
  11780. c = safe_add(c, oldc);
  11781. d = safe_add(d, oldd);
  11782. }
  11783. return Array(a, b, c, d);
  11784. }
  11785. /*
  11786. * These functions implement the four basic operations the algorithm uses.
  11787. */
  11788. function md5_cmn(q, a, b, x, s, t)
  11789. {
  11790. return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
  11791. }
  11792. function md5_ff(a, b, c, d, x, s, t)
  11793. {
  11794. return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
  11795. }
  11796. function md5_gg(a, b, c, d, x, s, t)
  11797. {
  11798. return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
  11799. }
  11800. function md5_hh(a, b, c, d, x, s, t)
  11801. {
  11802. return md5_cmn(b ^ c ^ d, a, b, x, s, t);
  11803. }
  11804. function md5_ii(a, b, c, d, x, s, t)
  11805. {
  11806. return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
  11807. }
  11808. /*
  11809. * Add integers, wrapping at 2^32. This uses 16-bit operations internally
  11810. * to work around bugs in some JS interpreters.
  11811. */
  11812. function safe_add(x, y)
  11813. {
  11814. var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  11815. var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  11816. return (msw << 16) | (lsw & 0xFFFF);
  11817. }
  11818. /*
  11819. * Bitwise rotate a 32-bit number to the left.
  11820. */
  11821. function bit_rol(num, cnt)
  11822. {
  11823. return (num << cnt) | (num >>> (32 - cnt));
  11824. }
  11825. module.exports = function md5(buf) {
  11826. return helpers.hash(buf, core_md5, 16);
  11827. };
  11828. /***/ },
  11829. /* 83 */
  11830. /***/ function(module, exports, __webpack_require__) {
  11831. module.exports = function(module) {
  11832. if(!module.webpackPolyfill) {
  11833. module.deprecate = function() {};
  11834. module.paths = [];
  11835. // module.parent = undefined by default
  11836. module.children = [];
  11837. module.webpackPolyfill = 1;
  11838. }
  11839. return module;
  11840. }
  11841. /***/ },
  11842. /* 84 */
  11843. /***/ function(module, exports, __webpack_require__) {
  11844. module.exports = function (crypto, exports) {
  11845. exports = exports || {};
  11846. var ciphers = __webpack_require__(103)(crypto);
  11847. exports.createCipher = ciphers.createCipher;
  11848. exports.createCipheriv = ciphers.createCipheriv;
  11849. var deciphers = __webpack_require__(104)(crypto);
  11850. exports.createDecipher = deciphers.createDecipher;
  11851. exports.createDecipheriv = deciphers.createDecipheriv;
  11852. var modes = __webpack_require__(105);
  11853. function listCiphers () {
  11854. return Object.keys(modes);
  11855. }
  11856. exports.listCiphers = listCiphers;
  11857. };
  11858. /***/ },
  11859. /* 85 */
  11860. /***/ function(module, exports, __webpack_require__) {
  11861. var __WEBPACK_AMD_DEFINE_RESULT__;// uuid.js
  11862. //
  11863. // Copyright (c) 2010-2012 Robert Kieffer
  11864. // MIT License - http://opensource.org/licenses/mit-license.php
  11865. (function() {
  11866. var _global = this;
  11867. // Unique ID creation requires a high quality random # generator. We feature
  11868. // detect to determine the best RNG source, normalizing to a function that
  11869. // returns 128-bits of randomness, since that's what's usually required
  11870. var _rng;
  11871. // Node.js crypto-based RNG - http://nodejs.org/docs/v0.6.2/api/crypto.html
  11872. //
  11873. // Moderately fast, high quality
  11874. if (typeof(_global.require) == 'function') {
  11875. try {
  11876. var _rb = _global.require('crypto').randomBytes;
  11877. _rng = _rb && function() {return _rb(16);};
  11878. } catch(e) {}
  11879. }
  11880. if (!_rng && _global.crypto && crypto.getRandomValues) {
  11881. // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto
  11882. //
  11883. // Moderately fast, high quality
  11884. var _rnds8 = new Uint8Array(16);
  11885. _rng = function whatwgRNG() {
  11886. crypto.getRandomValues(_rnds8);
  11887. return _rnds8;
  11888. };
  11889. }
  11890. if (!_rng) {
  11891. // Math.random()-based (RNG)
  11892. //
  11893. // If all else fails, use Math.random(). It's fast, but is of unspecified
  11894. // quality.
  11895. var _rnds = new Array(16);
  11896. _rng = function() {
  11897. for (var i = 0, r; i < 16; i++) {
  11898. if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
  11899. _rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
  11900. }
  11901. return _rnds;
  11902. };
  11903. }
  11904. // Buffer class to use
  11905. var BufferClass = typeof(_global.Buffer) == 'function' ? _global.Buffer : Array;
  11906. // Maps for number <-> hex string conversion
  11907. var _byteToHex = [];
  11908. var _hexToByte = {};
  11909. for (var i = 0; i < 256; i++) {
  11910. _byteToHex[i] = (i + 0x100).toString(16).substr(1);
  11911. _hexToByte[_byteToHex[i]] = i;
  11912. }
  11913. // **`parse()` - Parse a UUID into it's component bytes**
  11914. function parse(s, buf, offset) {
  11915. var i = (buf && offset) || 0, ii = 0;
  11916. buf = buf || [];
  11917. s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {
  11918. if (ii < 16) { // Don't overflow!
  11919. buf[i + ii++] = _hexToByte[oct];
  11920. }
  11921. });
  11922. // Zero out remaining bytes if string was short
  11923. while (ii < 16) {
  11924. buf[i + ii++] = 0;
  11925. }
  11926. return buf;
  11927. }
  11928. // **`unparse()` - Convert UUID byte array (ala parse()) into a string**
  11929. function unparse(buf, offset) {
  11930. var i = offset || 0, bth = _byteToHex;
  11931. return bth[buf[i++]] + bth[buf[i++]] +
  11932. bth[buf[i++]] + bth[buf[i++]] + '-' +
  11933. bth[buf[i++]] + bth[buf[i++]] + '-' +
  11934. bth[buf[i++]] + bth[buf[i++]] + '-' +
  11935. bth[buf[i++]] + bth[buf[i++]] + '-' +
  11936. bth[buf[i++]] + bth[buf[i++]] +
  11937. bth[buf[i++]] + bth[buf[i++]] +
  11938. bth[buf[i++]] + bth[buf[i++]];
  11939. }
  11940. // **`v1()` - Generate time-based UUID**
  11941. //
  11942. // Inspired by https://github.com/LiosK/UUID.js
  11943. // and http://docs.python.org/library/uuid.html
  11944. // random #'s we need to init node and clockseq
  11945. var _seedBytes = _rng();
  11946. // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
  11947. var _nodeId = [
  11948. _seedBytes[0] | 0x01,
  11949. _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]
  11950. ];
  11951. // Per 4.2.2, randomize (14 bit) clockseq
  11952. var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;
  11953. // Previous uuid creation time
  11954. var _lastMSecs = 0, _lastNSecs = 0;
  11955. // See https://github.com/broofa/node-uuid for API details
  11956. function v1(options, buf, offset) {
  11957. var i = buf && offset || 0;
  11958. var b = buf || [];
  11959. options = options || {};
  11960. var clockseq = options.clockseq != null ? options.clockseq : _clockseq;
  11961. // UUID timestamps are 100 nano-second units since the Gregorian epoch,
  11962. // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
  11963. // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
  11964. // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
  11965. var msecs = options.msecs != null ? options.msecs : new Date().getTime();
  11966. // Per 4.2.1.2, use count of uuid's generated during the current clock
  11967. // cycle to simulate higher resolution clock
  11968. var nsecs = options.nsecs != null ? options.nsecs : _lastNSecs + 1;
  11969. // Time since last uuid creation (in msecs)
  11970. var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
  11971. // Per 4.2.1.2, Bump clockseq on clock regression
  11972. if (dt < 0 && options.clockseq == null) {
  11973. clockseq = clockseq + 1 & 0x3fff;
  11974. }
  11975. // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
  11976. // time interval
  11977. if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) {
  11978. nsecs = 0;
  11979. }
  11980. // Per 4.2.1.2 Throw error if too many uuids are requested
  11981. if (nsecs >= 10000) {
  11982. throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
  11983. }
  11984. _lastMSecs = msecs;
  11985. _lastNSecs = nsecs;
  11986. _clockseq = clockseq;
  11987. // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
  11988. msecs += 12219292800000;
  11989. // `time_low`
  11990. var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
  11991. b[i++] = tl >>> 24 & 0xff;
  11992. b[i++] = tl >>> 16 & 0xff;
  11993. b[i++] = tl >>> 8 & 0xff;
  11994. b[i++] = tl & 0xff;
  11995. // `time_mid`
  11996. var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
  11997. b[i++] = tmh >>> 8 & 0xff;
  11998. b[i++] = tmh & 0xff;
  11999. // `time_high_and_version`
  12000. b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
  12001. b[i++] = tmh >>> 16 & 0xff;
  12002. // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
  12003. b[i++] = clockseq >>> 8 | 0x80;
  12004. // `clock_seq_low`
  12005. b[i++] = clockseq & 0xff;
  12006. // `node`
  12007. var node = options.node || _nodeId;
  12008. for (var n = 0; n < 6; n++) {
  12009. b[i + n] = node[n];
  12010. }
  12011. return buf ? buf : unparse(b);
  12012. }
  12013. // **`v4()` - Generate random UUID**
  12014. // See https://github.com/broofa/node-uuid for API details
  12015. function v4(options, buf, offset) {
  12016. // Deprecated - 'format' argument, as supported in v1.2
  12017. var i = buf && offset || 0;
  12018. if (typeof(options) == 'string') {
  12019. buf = options == 'binary' ? new BufferClass(16) : null;
  12020. options = null;
  12021. }
  12022. options = options || {};
  12023. var rnds = options.random || (options.rng || _rng)();
  12024. // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
  12025. rnds[6] = (rnds[6] & 0x0f) | 0x40;
  12026. rnds[8] = (rnds[8] & 0x3f) | 0x80;
  12027. // Copy bytes to buffer, if provided
  12028. if (buf) {
  12029. for (var ii = 0; ii < 16; ii++) {
  12030. buf[i + ii] = rnds[ii];
  12031. }
  12032. }
  12033. return buf || unparse(rnds);
  12034. }
  12035. // Export public API
  12036. var uuid = v4;
  12037. uuid.v1 = v1;
  12038. uuid.v4 = v4;
  12039. uuid.parse = parse;
  12040. uuid.unparse = unparse;
  12041. uuid.BufferClass = BufferClass;
  12042. if (true) {
  12043. // Publish as AMD module
  12044. !(__WEBPACK_AMD_DEFINE_RESULT__ = function() {return uuid;}.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  12045. } else if (typeof(module) != 'undefined' && module.exports) {
  12046. // Publish as node.js module
  12047. module.exports = uuid;
  12048. } else {
  12049. // Publish as global (in browsers)
  12050. var _previousRoot = _global.uuid;
  12051. // **`noConflict()` - (browser only) to reset global 'uuid' var**
  12052. uuid.noConflict = function() {
  12053. _global.uuid = _previousRoot;
  12054. return uuid;
  12055. };
  12056. _global.uuid = uuid;
  12057. }
  12058. }).call(this);
  12059. /***/ },
  12060. /* 86 */
  12061. /***/ function(module, exports, __webpack_require__) {
  12062. /* WEBPACK VAR INJECTION */(function(Buffer) {// Version: 3.6.8
  12063. var NOW = 1
  12064. , READY = false
  12065. , READY_BUFFER = []
  12066. , PRESENCE_SUFFIX = '-pnpres'
  12067. , DEF_WINDOWING = 10 // MILLISECONDS.
  12068. , DEF_TIMEOUT = 10000 // MILLISECONDS.
  12069. , DEF_SUB_TIMEOUT = 310 // SECONDS.
  12070. , DEF_KEEPALIVE = 60 // SECONDS (FOR TIMESYNC).
  12071. , SECOND = 1000 // A THOUSAND MILLISECONDS.
  12072. , URLBIT = '/'
  12073. , PARAMSBIT = '&'
  12074. , PRESENCE_HB_THRESHOLD = 5
  12075. , PRESENCE_HB_DEFAULT = 30
  12076. , SDK_VER = '3.6.8'
  12077. , REPL = /{([\w\-]+)}/g;
  12078. /**
  12079. * UTILITIES
  12080. */
  12081. function unique() { return'x'+ ++NOW+''+(+new Date) }
  12082. function rnow() { return+new Date }
  12083. /**
  12084. * NEXTORIGIN
  12085. * ==========
  12086. * var next_origin = nextorigin();
  12087. */
  12088. var nextorigin = (function() {
  12089. var max = 20
  12090. , ori = Math.floor(Math.random() * max);
  12091. return function( origin, failover ) {
  12092. return origin.indexOf('pubsub.') > 0
  12093. && origin.replace(
  12094. 'pubsub', 'ps' + (
  12095. failover ? uuid().split('-')[0] :
  12096. (++ori < max? ori : ori=1)
  12097. ) ) || origin;
  12098. }
  12099. })();
  12100. /**
  12101. * Build Url
  12102. * =======
  12103. *
  12104. */
  12105. function build_url( url_components, url_params ) {
  12106. var url = url_components.join(URLBIT)
  12107. , params = [];
  12108. if (!url_params) return url;
  12109. each( url_params, function( key, value ) {
  12110. var value_str = (typeof value == 'object')?JSON['stringify'](value):value;
  12111. (typeof value != 'undefined' &&
  12112. value != null && encode(value_str).length > 0
  12113. ) && params.push(key + "=" + encode(value_str));
  12114. } );
  12115. url += "?" + params.join(PARAMSBIT);
  12116. return url;
  12117. }
  12118. /**
  12119. * UPDATER
  12120. * =======
  12121. * var timestamp = unique();
  12122. */
  12123. function updater( fun, rate ) {
  12124. var timeout
  12125. , last = 0
  12126. , runnit = function() {
  12127. if (last + rate > rnow()) {
  12128. clearTimeout(timeout);
  12129. timeout = setTimeout( runnit, rate );
  12130. }
  12131. else {
  12132. last = rnow();
  12133. fun();
  12134. }
  12135. };
  12136. return runnit;
  12137. }
  12138. /**
  12139. * GREP
  12140. * ====
  12141. * var list = grep( [1,2,3], function(item) { return item % 2 } )
  12142. */
  12143. function grep( list, fun ) {
  12144. var fin = [];
  12145. each( list || [], function(l) { fun(l) && fin.push(l) } );
  12146. return fin
  12147. }
  12148. /**
  12149. * SUPPLANT
  12150. * ========
  12151. * var text = supplant( 'Hello {name}!', { name : 'John' } )
  12152. */
  12153. function supplant( str, values ) {
  12154. return str.replace( REPL, function( _, match ) {
  12155. return values[match] || _
  12156. } );
  12157. }
  12158. /**
  12159. * timeout
  12160. * =======
  12161. * timeout( function(){}, 100 );
  12162. */
  12163. function timeout( fun, wait ) {
  12164. return setTimeout( fun, wait );
  12165. }
  12166. /**
  12167. * uuid
  12168. * ====
  12169. * var my_uuid = uuid();
  12170. */
  12171. function uuid(callback) {
  12172. var u = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,
  12173. function(c) {
  12174. var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
  12175. return v.toString(16);
  12176. });
  12177. if (callback) callback(u);
  12178. return u;
  12179. }
  12180. function isArray(arg) {
  12181. return !!arg && (Array.isArray && Array.isArray(arg) || typeof(arg.length) === "number")
  12182. }
  12183. /**
  12184. * EACH
  12185. * ====
  12186. * each( [1,2,3], function(item) { } )
  12187. */
  12188. function each( o, f) {
  12189. if ( !o || !f ) return;
  12190. if ( isArray(o) )
  12191. for ( var i = 0, l = o.length; i < l; )
  12192. f.call( o[i], o[i], i++ );
  12193. else
  12194. for ( var i in o )
  12195. o.hasOwnProperty &&
  12196. o.hasOwnProperty(i) &&
  12197. f.call( o[i], i, o[i] );
  12198. }
  12199. /**
  12200. * MAP
  12201. * ===
  12202. * var list = map( [1,2,3], function(item) { return item + 1 } )
  12203. */
  12204. function map( list, fun ) {
  12205. var fin = [];
  12206. each( list || [], function( k, v ) { fin.push(fun( k, v )) } );
  12207. return fin;
  12208. }
  12209. /**
  12210. * ENCODE
  12211. * ======
  12212. * var encoded_data = encode('path');
  12213. */
  12214. function encode(path) { return encodeURIComponent(path) }
  12215. /**
  12216. * Generate Subscription Channel List
  12217. * ==================================
  12218. * generate_channel_list(channels_object);
  12219. */
  12220. function generate_channel_list(channels, nopresence) {
  12221. var list = [];
  12222. each( channels, function( channel, status ) {
  12223. if (nopresence) {
  12224. if(channel.search('-pnpres') < 0) {
  12225. if (status.subscribed) list.push(channel);
  12226. }
  12227. } else {
  12228. if (status.subscribed) list.push(channel);
  12229. }
  12230. });
  12231. return list.sort();
  12232. }
  12233. // PUBNUB READY TO CONNECT
  12234. function ready() { timeout( function() {
  12235. if (READY) return;
  12236. READY = 1;
  12237. each( READY_BUFFER, function(connect) { connect() } );
  12238. }, SECOND ); }
  12239. function PNmessage(args) {
  12240. msg = args || {'apns' : {}},
  12241. msg['getPubnubMessage'] = function() {
  12242. var m = {};
  12243. if (Object.keys(msg['apns']).length) {
  12244. m['pn_apns'] = {
  12245. 'aps' : {
  12246. 'alert' : msg['apns']['alert'] ,
  12247. 'badge' : msg['apns']['badge']
  12248. }
  12249. }
  12250. for (var k in msg['apns']) {
  12251. m['pn_apns'][k] = msg['apns'][k];
  12252. }
  12253. var exclude1 = ['badge','alert'];
  12254. for (var k in exclude1) {
  12255. //console.log(exclude[k]);
  12256. delete m['pn_apns'][exclude1[k]];
  12257. }
  12258. }
  12259. if (msg['gcm']) {
  12260. m['pn_gcm'] = {
  12261. 'data' : msg['gcm']
  12262. }
  12263. }
  12264. for (var k in msg) {
  12265. m[k] = msg[k];
  12266. }
  12267. var exclude = ['apns','gcm','publish', 'channel','callback','error'];
  12268. for (var k in exclude) {
  12269. delete m[exclude[k]];
  12270. }
  12271. return m;
  12272. };
  12273. msg['publish'] = function() {
  12274. var m = msg.getPubnubMessage();
  12275. if (msg['pubnub'] && msg['channel']) {
  12276. msg['pubnub'].publish({
  12277. 'message' : m,
  12278. 'channel' : msg['channel'],
  12279. 'callback' : msg['callback'],
  12280. 'error' : msg['error']
  12281. })
  12282. }
  12283. };
  12284. return msg;
  12285. }
  12286. function PN_API(setup) {
  12287. var SUB_WINDOWING = +setup['windowing'] || DEF_WINDOWING
  12288. , SUB_TIMEOUT = (+setup['timeout'] || DEF_SUB_TIMEOUT) * SECOND
  12289. , KEEPALIVE = (+setup['keepalive'] || DEF_KEEPALIVE) * SECOND
  12290. , NOLEAVE = setup['noleave'] || 0
  12291. , PUBLISH_KEY = setup['publish_key'] || 'demo'
  12292. , SUBSCRIBE_KEY = setup['subscribe_key'] || 'demo'
  12293. , AUTH_KEY = setup['auth_key'] || ''
  12294. , SECRET_KEY = setup['secret_key'] || ''
  12295. , hmac_SHA256 = setup['hmac_SHA256']
  12296. , SSL = setup['ssl'] ? 's' : ''
  12297. , ORIGIN = 'http'+SSL+'://'+(setup['origin']||'pubsub.pubnub.com')
  12298. , STD_ORIGIN = nextorigin(ORIGIN)
  12299. , SUB_ORIGIN = nextorigin(ORIGIN)
  12300. , CONNECT = function(){}
  12301. , PUB_QUEUE = []
  12302. , TIME_DRIFT = 0
  12303. , SUB_CALLBACK = 0
  12304. , SUB_CHANNEL = 0
  12305. , SUB_RECEIVER = 0
  12306. , SUB_RESTORE = setup['restore'] || 0
  12307. , SUB_BUFF_WAIT = 0
  12308. , TIMETOKEN = 0
  12309. , RESUMED = false
  12310. , CHANNELS = {}
  12311. , STATE = {}
  12312. , PRESENCE_HB_TIMEOUT = null
  12313. , PRESENCE_HB = validate_presence_heartbeat(setup['heartbeat'] || setup['pnexpires'] || 0, setup['error'])
  12314. , PRESENCE_HB_INTERVAL = setup['heartbeat_interval'] || PRESENCE_HB - 3
  12315. , PRESENCE_HB_RUNNING = false
  12316. , NO_WAIT_FOR_PENDING = setup['no_wait_for_pending']
  12317. , COMPATIBLE_35 = setup['compatible_3.5'] || false
  12318. , xdr = setup['xdr']
  12319. , params = setup['params'] || {}
  12320. , error = setup['error'] || function() {}
  12321. , _is_online = setup['_is_online'] || function() { return 1 }
  12322. , jsonp_cb = setup['jsonp_cb'] || function() { return 0 }
  12323. , db = setup['db'] || {'get': function(){}, 'set': function(){}}
  12324. , CIPHER_KEY = setup['cipher_key']
  12325. , UUID = setup['uuid'] || ( db && db['get'](SUBSCRIBE_KEY+'uuid') || '');
  12326. var crypto_obj = setup['crypto_obj'] ||
  12327. {
  12328. 'encrypt' : function(a,key){ return a},
  12329. 'decrypt' : function(b,key){return b}
  12330. };
  12331. function _get_url_params(data) {
  12332. if (!data) data = {};
  12333. each( params , function( key, value ) {
  12334. if (!(key in data)) data[key] = value;
  12335. });
  12336. return data;
  12337. }
  12338. function _object_to_key_list(o) {
  12339. var l = []
  12340. each( o , function( key, value ) {
  12341. l.push(key);
  12342. });
  12343. return l;
  12344. }
  12345. function _object_to_key_list_sorted(o) {
  12346. return _object_to_key_list(o).sort();
  12347. }
  12348. function _get_pam_sign_input_from_params(params) {
  12349. var si = "";
  12350. var l = _object_to_key_list_sorted(params);
  12351. for (var i in l) {
  12352. var k = l[i]
  12353. si += k + "=" + encode(params[k]) ;
  12354. if (i != l.length - 1) si += "&"
  12355. }
  12356. return si;
  12357. }
  12358. function validate_presence_heartbeat(heartbeat, cur_heartbeat, error) {
  12359. var err = false;
  12360. if (typeof heartbeat === 'number') {
  12361. if (heartbeat > PRESENCE_HB_THRESHOLD || heartbeat == 0)
  12362. err = false;
  12363. else
  12364. err = true;
  12365. } else if(typeof heartbeat === 'boolean'){
  12366. if (!heartbeat) {
  12367. return 0;
  12368. } else {
  12369. return PRESENCE_HB_DEFAULT;
  12370. }
  12371. } else {
  12372. err = true;
  12373. }
  12374. if (err) {
  12375. error && error("Presence Heartbeat value invalid. Valid range ( x > " + PRESENCE_HB_THRESHOLD + " or x = 0). Current Value : " + (cur_heartbeat || PRESENCE_HB_THRESHOLD));
  12376. return cur_heartbeat || PRESENCE_HB_THRESHOLD;
  12377. } else return heartbeat;
  12378. }
  12379. function encrypt(input, key) {
  12380. return crypto_obj['encrypt'](input, key || CIPHER_KEY) || input;
  12381. }
  12382. function decrypt(input, key) {
  12383. return crypto_obj['decrypt'](input, key || CIPHER_KEY) ||
  12384. crypto_obj['decrypt'](input, CIPHER_KEY) ||
  12385. input;
  12386. }
  12387. function error_common(message, callback) {
  12388. callback && callback({ 'error' : message || "error occurred"});
  12389. error && error(message);
  12390. }
  12391. function _presence_heartbeat() {
  12392. clearTimeout(PRESENCE_HB_TIMEOUT);
  12393. if (!PRESENCE_HB_INTERVAL || PRESENCE_HB_INTERVAL >= 500 || PRESENCE_HB_INTERVAL < 1 || !generate_channel_list(CHANNELS,true).length){
  12394. PRESENCE_HB_RUNNING = false;
  12395. return;
  12396. }
  12397. PRESENCE_HB_RUNNING = true;
  12398. SELF['presence_heartbeat']({
  12399. 'callback' : function(r) {
  12400. PRESENCE_HB_TIMEOUT = timeout( _presence_heartbeat, (PRESENCE_HB_INTERVAL) * SECOND );
  12401. },
  12402. 'error' : function(e) {
  12403. error && error("Presence Heartbeat unable to reach Pubnub servers." + JSON.stringify(e));
  12404. PRESENCE_HB_TIMEOUT = timeout( _presence_heartbeat, (PRESENCE_HB_INTERVAL) * SECOND );
  12405. }
  12406. });
  12407. }
  12408. function start_presence_heartbeat() {
  12409. !PRESENCE_HB_RUNNING && _presence_heartbeat();
  12410. }
  12411. function publish(next) {
  12412. if (NO_WAIT_FOR_PENDING) {
  12413. if (!PUB_QUEUE.length) return;
  12414. } else {
  12415. if (next) PUB_QUEUE.sending = 0;
  12416. if ( PUB_QUEUE.sending || !PUB_QUEUE.length ) return;
  12417. PUB_QUEUE.sending = 1;
  12418. }
  12419. xdr(PUB_QUEUE.shift());
  12420. }
  12421. function each_channel(callback) {
  12422. var count = 0;
  12423. each( generate_channel_list(CHANNELS), function(channel) {
  12424. var chan = CHANNELS[channel];
  12425. if (!chan) return;
  12426. count++;
  12427. (callback||function(){})(chan);
  12428. } );
  12429. return count;
  12430. }
  12431. function _invoke_callback(response, callback, err) {
  12432. if (typeof response == 'object') {
  12433. if (response['error'] && response['message'] && response['payload']) {
  12434. err({'message' : response['message'], 'payload' : response['payload']});
  12435. return;
  12436. }
  12437. if (response['payload']) {
  12438. callback(response['payload']);
  12439. return;
  12440. }
  12441. }
  12442. callback(response);
  12443. }
  12444. function _invoke_error(response,err) {
  12445. if (typeof response == 'object' && response['error'] &&
  12446. response['message'] && response['payload']) {
  12447. err({'message' : response['message'], 'payload' : response['payload']});
  12448. } else err(response);
  12449. }
  12450. // Announce Leave Event
  12451. var SELF = {
  12452. 'LEAVE' : function( channel, blocking, callback, error ) {
  12453. var data = { 'uuid' : UUID, 'auth' : AUTH_KEY }
  12454. , origin = nextorigin(ORIGIN)
  12455. , callback = callback || function(){}
  12456. , err = error || function(){}
  12457. , jsonp = jsonp_cb();
  12458. // Prevent Leaving a Presence Channel
  12459. if (channel.indexOf(PRESENCE_SUFFIX) > 0) return true;
  12460. if (COMPATIBLE_35) {
  12461. if (!SSL) return false;
  12462. if (jsonp == '0') return false;
  12463. }
  12464. if (NOLEAVE) return false;
  12465. if (jsonp != '0') data['callback'] = jsonp;
  12466. xdr({
  12467. blocking : blocking || SSL,
  12468. timeout : 2000,
  12469. callback : jsonp,
  12470. data : _get_url_params(data),
  12471. success : function(response) {
  12472. _invoke_callback(response, callback, err);
  12473. },
  12474. fail : function(response) {
  12475. _invoke_error(response, err);
  12476. },
  12477. url : [
  12478. origin, 'v2', 'presence', 'sub_key',
  12479. SUBSCRIBE_KEY, 'channel', encode(channel), 'leave'
  12480. ]
  12481. });
  12482. return true;
  12483. },
  12484. 'set_resumed' : function(resumed) {
  12485. RESUMED = resumed;
  12486. },
  12487. 'get_cipher_key' : function() {
  12488. return CIPHER_KEY;
  12489. },
  12490. 'set_cipher_key' : function(key) {
  12491. CIPHER_KEY = key;
  12492. },
  12493. 'raw_encrypt' : function(input, key) {
  12494. return encrypt(input, key);
  12495. },
  12496. 'raw_decrypt' : function(input, key) {
  12497. return decrypt(input, key);
  12498. },
  12499. 'get_heartbeat' : function() {
  12500. return PRESENCE_HB;
  12501. },
  12502. 'set_heartbeat' : function(heartbeat) {
  12503. PRESENCE_HB = validate_presence_heartbeat(heartbeat, PRESENCE_HB_INTERVAL, error);
  12504. PRESENCE_HB_INTERVAL = (PRESENCE_HB - 3 >= 1)?PRESENCE_HB - 3:1;
  12505. CONNECT();
  12506. _presence_heartbeat();
  12507. },
  12508. 'get_heartbeat_interval' : function() {
  12509. return PRESENCE_HB_INTERVAL;
  12510. },
  12511. 'set_heartbeat_interval' : function(heartbeat_interval) {
  12512. PRESENCE_HB_INTERVAL = heartbeat_interval;
  12513. _presence_heartbeat();
  12514. },
  12515. 'get_version' : function() {
  12516. return SDK_VER;
  12517. },
  12518. 'getGcmMessageObject' : function(obj) {
  12519. return {
  12520. 'data' : obj
  12521. }
  12522. },
  12523. 'getApnsMessageObject' : function(obj) {
  12524. var x = {
  12525. 'aps' : { 'badge' : 1, 'alert' : ''}
  12526. }
  12527. for (k in obj) {
  12528. k[x] = obj[k];
  12529. }
  12530. return x;
  12531. },
  12532. 'newPnMessage' : function() {
  12533. var x = {};
  12534. if (gcm) x['pn_gcm'] = gcm;
  12535. if (apns) x['pn_apns'] = apns;
  12536. for ( k in n ) {
  12537. x[k] = n[k];
  12538. }
  12539. return x;
  12540. },
  12541. '_add_param' : function(key,val) {
  12542. params[key] = val;
  12543. },
  12544. /*
  12545. PUBNUB.history({
  12546. channel : 'my_chat_channel',
  12547. limit : 100,
  12548. callback : function(history) { }
  12549. });
  12550. */
  12551. 'history' : function( args, callback ) {
  12552. var callback = args['callback'] || callback
  12553. , count = args['count'] || args['limit'] || 100
  12554. , reverse = args['reverse'] || "false"
  12555. , err = args['error'] || function(){}
  12556. , auth_key = args['auth_key'] || AUTH_KEY
  12557. , cipher_key = args['cipher_key']
  12558. , channel = args['channel']
  12559. , start = args['start']
  12560. , end = args['end']
  12561. , include_token = args['include_token']
  12562. , params = {}
  12563. , jsonp = jsonp_cb();
  12564. // Make sure we have a Channel
  12565. if (!channel) return error('Missing Channel');
  12566. if (!callback) return error('Missing Callback');
  12567. if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
  12568. params['stringtoken'] = 'true';
  12569. params['count'] = count;
  12570. params['reverse'] = reverse;
  12571. params['auth'] = auth_key;
  12572. if (jsonp) params['callback'] = jsonp;
  12573. if (start) params['start'] = start;
  12574. if (end) params['end'] = end;
  12575. if (include_token) params['include_token'] = 'true';
  12576. // Send Message
  12577. xdr({
  12578. callback : jsonp,
  12579. data : _get_url_params(params),
  12580. success : function(response) {
  12581. if (typeof response == 'object' && response['error']) {
  12582. err({'message' : response['message'], 'payload' : response['payload']});
  12583. return;
  12584. }
  12585. var messages = response[0];
  12586. var decrypted_messages = [];
  12587. for (var a = 0; a < messages.length; a++) {
  12588. var new_message = decrypt(messages[a],cipher_key);
  12589. try {
  12590. decrypted_messages['push'](JSON['parse'](new_message));
  12591. } catch (e) {
  12592. decrypted_messages['push']((new_message));
  12593. }
  12594. }
  12595. callback([decrypted_messages, response[1], response[2]]);
  12596. },
  12597. fail : function(response) {
  12598. _invoke_error(response, err);
  12599. },
  12600. url : [
  12601. STD_ORIGIN, 'v2', 'history', 'sub-key',
  12602. SUBSCRIBE_KEY, 'channel', encode(channel)
  12603. ]
  12604. });
  12605. },
  12606. /*
  12607. PUBNUB.replay({
  12608. source : 'my_channel',
  12609. destination : 'new_channel'
  12610. });
  12611. */
  12612. 'replay' : function(args, callback) {
  12613. var callback = callback || args['callback'] || function(){}
  12614. , auth_key = args['auth_key'] || AUTH_KEY
  12615. , source = args['source']
  12616. , destination = args['destination']
  12617. , stop = args['stop']
  12618. , start = args['start']
  12619. , end = args['end']
  12620. , reverse = args['reverse']
  12621. , limit = args['limit']
  12622. , jsonp = jsonp_cb()
  12623. , data = {}
  12624. , url;
  12625. // Check User Input
  12626. if (!source) return error('Missing Source Channel');
  12627. if (!destination) return error('Missing Destination Channel');
  12628. if (!PUBLISH_KEY) return error('Missing Publish Key');
  12629. if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
  12630. // Setup URL Params
  12631. if (jsonp != '0') data['callback'] = jsonp;
  12632. if (stop) data['stop'] = 'all';
  12633. if (reverse) data['reverse'] = 'true';
  12634. if (start) data['start'] = start;
  12635. if (end) data['end'] = end;
  12636. if (limit) data['count'] = limit;
  12637. data['auth'] = auth_key;
  12638. // Compose URL Parts
  12639. url = [
  12640. STD_ORIGIN, 'v1', 'replay',
  12641. PUBLISH_KEY, SUBSCRIBE_KEY,
  12642. source, destination
  12643. ];
  12644. // Start (or Stop) Replay!
  12645. xdr({
  12646. callback : jsonp,
  12647. success : function(response) {
  12648. _invoke_callback(response, callback, err);
  12649. },
  12650. fail : function() { callback([ 0, 'Disconnected' ]) },
  12651. url : url,
  12652. data : _get_url_params(data)
  12653. });
  12654. },
  12655. /*
  12656. PUBNUB.auth('AJFLKAJSDKLA');
  12657. */
  12658. 'auth' : function(auth) {
  12659. AUTH_KEY = auth;
  12660. CONNECT();
  12661. },
  12662. /*
  12663. PUBNUB.time(function(time){ });
  12664. */
  12665. 'time' : function(callback) {
  12666. var jsonp = jsonp_cb();
  12667. xdr({
  12668. callback : jsonp,
  12669. data : _get_url_params({ 'uuid' : UUID, 'auth' : AUTH_KEY }),
  12670. timeout : SECOND * 5,
  12671. url : [STD_ORIGIN, 'time', jsonp],
  12672. success : function(response) { callback(response[0]) },
  12673. fail : function() { callback(0) }
  12674. });
  12675. },
  12676. /*
  12677. PUBNUB.publish({
  12678. channel : 'my_chat_channel',
  12679. message : 'hello!'
  12680. });
  12681. */
  12682. 'publish' : function( args, callback ) {
  12683. var msg = args['message'];
  12684. if (!msg) return error('Missing Message');
  12685. var callback = callback || args['callback'] || msg['callback'] || function(){}
  12686. , channel = args['channel'] || msg['channel']
  12687. , auth_key = args['auth_key'] || AUTH_KEY
  12688. , cipher_key = args['cipher_key']
  12689. , err = args['error'] || msg['error'] || function() {}
  12690. , post = args['post'] || false
  12691. , store = ('store_in_history' in args) ? args['store_in_history']: true
  12692. , jsonp = jsonp_cb()
  12693. , add_msg = 'push'
  12694. , url;
  12695. if (args['prepend']) add_msg = 'unshift'
  12696. if (!channel) return error('Missing Channel');
  12697. if (!PUBLISH_KEY) return error('Missing Publish Key');
  12698. if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
  12699. if (msg['getPubnubMessage']) {
  12700. msg = msg['getPubnubMessage']();
  12701. }
  12702. // If trying to send Object
  12703. msg = JSON['stringify'](encrypt(msg, cipher_key));
  12704. // Create URL
  12705. url = [
  12706. STD_ORIGIN, 'publish',
  12707. PUBLISH_KEY, SUBSCRIBE_KEY,
  12708. 0, encode(channel),
  12709. jsonp, encode(msg)
  12710. ];
  12711. params = { 'uuid' : UUID, 'auth' : auth_key }
  12712. if (!store) params['store'] ="0"
  12713. // Queue Message Send
  12714. PUB_QUEUE[add_msg]({
  12715. callback : jsonp,
  12716. timeout : SECOND * 5,
  12717. url : url,
  12718. data : _get_url_params(params),
  12719. fail : function(response){
  12720. _invoke_error(response, err);
  12721. publish(1);
  12722. },
  12723. success : function(response) {
  12724. _invoke_callback(response, callback, err);
  12725. publish(1);
  12726. },
  12727. mode : (post)?'POST':'GET'
  12728. });
  12729. // Send Message
  12730. publish();
  12731. },
  12732. /*
  12733. PUBNUB.unsubscribe({ channel : 'my_chat' });
  12734. */
  12735. 'unsubscribe' : function(args, callback) {
  12736. var channel = args['channel']
  12737. , callback = callback || args['callback'] || function(){}
  12738. , err = args['error'] || function(){};
  12739. TIMETOKEN = 0;
  12740. //SUB_RESTORE = 1; REVISIT !!!!
  12741. // Prepare Channel(s)
  12742. channel = map( (
  12743. channel.join ? channel.join(',') : ''+channel
  12744. ).split(','), function(channel) {
  12745. if (!CHANNELS[channel]) return;
  12746. return channel + ',' + channel + PRESENCE_SUFFIX;
  12747. } ).join(',');
  12748. // Iterate over Channels
  12749. each( channel.split(','), function(channel) {
  12750. var CB_CALLED = true;
  12751. if (!channel) return;
  12752. if (READY) {
  12753. CB_CALLED = SELF['LEAVE']( channel, 0 , callback, err);
  12754. }
  12755. if (!CB_CALLED) callback({action : "leave"});
  12756. CHANNELS[channel] = 0;
  12757. if (channel in STATE) delete STATE[channel];
  12758. } );
  12759. // Reset Connection if Count Less
  12760. CONNECT();
  12761. },
  12762. /*
  12763. PUBNUB.subscribe({
  12764. channel : 'my_chat'
  12765. callback : function(message) { }
  12766. });
  12767. */
  12768. 'subscribe' : function( args, callback ) {
  12769. var channel = args['channel']
  12770. , callback = callback || args['callback']
  12771. , callback = callback || args['message']
  12772. , auth_key = args['auth_key'] || AUTH_KEY
  12773. , connect = args['connect'] || function(){}
  12774. , reconnect = args['reconnect'] || function(){}
  12775. , disconnect = args['disconnect'] || function(){}
  12776. , errcb = args['error'] || function(){}
  12777. , idlecb = args['idle'] || function(){}
  12778. , presence = args['presence'] || 0
  12779. , noheresync = args['noheresync'] || 0
  12780. , backfill = args['backfill'] || 0
  12781. , timetoken = args['timetoken'] || 0
  12782. , sub_timeout = args['timeout'] || SUB_TIMEOUT
  12783. , windowing = args['windowing'] || SUB_WINDOWING
  12784. , state = args['state']
  12785. , heartbeat = args['heartbeat'] || args['pnexpires']
  12786. , restore = args['restore'] || SUB_RESTORE;
  12787. // Restore Enabled?
  12788. SUB_RESTORE = restore;
  12789. // Always Reset the TT
  12790. TIMETOKEN = timetoken;
  12791. // Make sure we have a Channel
  12792. if (!channel) return error('Missing Channel');
  12793. if (!callback) return error('Missing Callback');
  12794. if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
  12795. if (heartbeat || heartbeat === 0) {
  12796. SELF['set_heartbeat'](heartbeat);
  12797. }
  12798. // Setup Channel(s)
  12799. each( (channel.join ? channel.join(',') : ''+channel).split(','),
  12800. function(channel) {
  12801. var settings = CHANNELS[channel] || {};
  12802. // Store Channel State
  12803. CHANNELS[SUB_CHANNEL = channel] = {
  12804. name : channel,
  12805. connected : settings.connected,
  12806. disconnected : settings.disconnected,
  12807. subscribed : 1,
  12808. callback : SUB_CALLBACK = callback,
  12809. 'cipher_key' : args['cipher_key'],
  12810. connect : connect,
  12811. disconnect : disconnect,
  12812. reconnect : reconnect
  12813. };
  12814. if (state) {
  12815. if (channel in state) {
  12816. STATE[channel] = state[channel];
  12817. } else {
  12818. STATE[channel] = state;
  12819. }
  12820. }
  12821. // Presence Enabled?
  12822. if (!presence) return;
  12823. // Subscribe Presence Channel
  12824. SELF['subscribe']({
  12825. 'channel' : channel + PRESENCE_SUFFIX,
  12826. 'callback' : presence,
  12827. 'restore' : restore
  12828. });
  12829. // Presence Subscribed?
  12830. if (settings.subscribed) return;
  12831. // See Who's Here Now?
  12832. if (noheresync) return;
  12833. SELF['here_now']({
  12834. 'channel' : channel,
  12835. 'callback' : function(here) {
  12836. each( 'uuids' in here ? here['uuids'] : [],
  12837. function(uid) { presence( {
  12838. 'action' : 'join',
  12839. 'uuid' : uid,
  12840. 'timestamp' : Math.floor(rnow() / 1000),
  12841. 'occupancy' : here['occupancy'] || 1
  12842. }, here, channel ); } );
  12843. }
  12844. });
  12845. } );
  12846. // Test Network Connection
  12847. function _test_connection(success) {
  12848. if (success) {
  12849. // Begin Next Socket Connection
  12850. timeout( CONNECT, SECOND );
  12851. }
  12852. else {
  12853. // New Origin on Failed Connection
  12854. STD_ORIGIN = nextorigin( ORIGIN, 1 );
  12855. SUB_ORIGIN = nextorigin( ORIGIN, 1 );
  12856. // Re-test Connection
  12857. timeout( function() {
  12858. SELF['time'](_test_connection);
  12859. }, SECOND );
  12860. }
  12861. // Disconnect & Reconnect
  12862. each_channel(function(channel){
  12863. // Reconnect
  12864. if (success && channel.disconnected) {
  12865. channel.disconnected = 0;
  12866. return channel.reconnect(channel.name);
  12867. }
  12868. // Disconnect
  12869. if (!success && !channel.disconnected) {
  12870. channel.disconnected = 1;
  12871. channel.disconnect(channel.name);
  12872. }
  12873. });
  12874. }
  12875. // Evented Subscribe
  12876. function _connect() {
  12877. var jsonp = jsonp_cb()
  12878. , channels = generate_channel_list(CHANNELS).join(',');
  12879. // Stop Connection
  12880. if (!channels) return;
  12881. // Connect to PubNub Subscribe Servers
  12882. _reset_offline();
  12883. var data = _get_url_params({ 'uuid' : UUID, 'auth' : auth_key });
  12884. var st = JSON.stringify(STATE);
  12885. if (st.length > 2) data['state'] = JSON.stringify(STATE);
  12886. if (PRESENCE_HB) data['heartbeat'] = PRESENCE_HB;
  12887. start_presence_heartbeat();
  12888. SUB_RECEIVER = xdr({
  12889. timeout : sub_timeout,
  12890. callback : jsonp,
  12891. fail : function(response) {
  12892. _invoke_error(response, errcb);
  12893. //SUB_RECEIVER = null;
  12894. SELF['time'](_test_connection);
  12895. },
  12896. data : _get_url_params(data),
  12897. url : [
  12898. SUB_ORIGIN, 'subscribe',
  12899. SUBSCRIBE_KEY, encode(channels),
  12900. jsonp, TIMETOKEN
  12901. ],
  12902. success : function(messages) {
  12903. //SUB_RECEIVER = null;
  12904. // Check for Errors
  12905. if (!messages || (
  12906. typeof messages == 'object' &&
  12907. 'error' in messages &&
  12908. messages['error']
  12909. )) {
  12910. errcb(messages['error']);
  12911. return timeout( CONNECT, SECOND );
  12912. }
  12913. // User Idle Callback
  12914. idlecb(messages[1]);
  12915. // Restore Previous Connection Point if Needed
  12916. TIMETOKEN = !TIMETOKEN &&
  12917. SUB_RESTORE &&
  12918. db['get'](SUBSCRIBE_KEY) || messages[1];
  12919. // Connect
  12920. each_channel(function(channel){
  12921. if (channel.connected) return;
  12922. channel.connected = 1;
  12923. channel.connect(channel.name);
  12924. });
  12925. if (RESUMED && !SUB_RESTORE) {
  12926. TIMETOKEN = 0;
  12927. RESUMED = false;
  12928. // Update Saved Timetoken
  12929. db['set']( SUBSCRIBE_KEY, 0 );
  12930. timeout( _connect, windowing );
  12931. return;
  12932. }
  12933. // Invoke Memory Catchup and Receive Up to 100
  12934. // Previous Messages from the Queue.
  12935. if (backfill) {
  12936. TIMETOKEN = 10000;
  12937. backfill = 0;
  12938. }
  12939. // Update Saved Timetoken
  12940. db['set']( SUBSCRIBE_KEY, messages[1] );
  12941. // Route Channel <---> Callback for Message
  12942. var next_callback = (function() {
  12943. var channels = (messages.length>2?messages[2]:map(
  12944. generate_channel_list(CHANNELS), function(chan) { return map(
  12945. Array(messages[0].length)
  12946. .join(',').split(','),
  12947. function() { return chan; }
  12948. ) }).join(','));
  12949. var list = channels.split(',');
  12950. return function() {
  12951. var channel = list.shift()||SUB_CHANNEL;
  12952. return [
  12953. (CHANNELS[channel]||{})
  12954. .callback||SUB_CALLBACK,
  12955. channel.split(PRESENCE_SUFFIX)[0]
  12956. ];
  12957. };
  12958. })();
  12959. var latency = detect_latency(+messages[1]);
  12960. each( messages[0], function(msg) {
  12961. var next = next_callback();
  12962. var decrypted_msg = decrypt(msg,
  12963. (CHANNELS[next[1]])?CHANNELS[next[1]]['cipher_key']:null);
  12964. next[0]( decrypted_msg, messages, next[1], latency);
  12965. });
  12966. timeout( _connect, windowing );
  12967. }
  12968. });
  12969. }
  12970. CONNECT = function() {
  12971. _reset_offline();
  12972. timeout( _connect, windowing );
  12973. };
  12974. // Reduce Status Flicker
  12975. if (!READY) return READY_BUFFER.push(CONNECT);
  12976. // Connect Now
  12977. CONNECT();
  12978. },
  12979. /*
  12980. PUBNUB.here_now({ channel : 'my_chat', callback : fun });
  12981. */
  12982. 'here_now' : function( args, callback ) {
  12983. var callback = args['callback'] || callback
  12984. , err = args['error'] || function(){}
  12985. , auth_key = args['auth_key'] || AUTH_KEY
  12986. , channel = args['channel']
  12987. , jsonp = jsonp_cb()
  12988. , uuids = ('uuids' in args) ? args['uuids'] : true
  12989. , state = args['state']
  12990. , data = { 'uuid' : UUID, 'auth' : auth_key };
  12991. if (!uuids) data['disable_uuids'] = 1;
  12992. if (state) data['state'] = 1;
  12993. // Make sure we have a Channel
  12994. if (!callback) return error('Missing Callback');
  12995. if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
  12996. var url = [
  12997. STD_ORIGIN, 'v2', 'presence',
  12998. 'sub_key', SUBSCRIBE_KEY
  12999. ];
  13000. channel && url.push('channel') && url.push(encode(channel));
  13001. if (jsonp != '0') { data['callback'] = jsonp; }
  13002. xdr({
  13003. callback : jsonp,
  13004. data : _get_url_params(data),
  13005. success : function(response) {
  13006. _invoke_callback(response, callback, err);
  13007. },
  13008. fail : function(response) {
  13009. _invoke_error(response, err);
  13010. },
  13011. url : url
  13012. });
  13013. },
  13014. /*
  13015. PUBNUB.current_channels_by_uuid({ channel : 'my_chat', callback : fun });
  13016. */
  13017. 'where_now' : function( args, callback ) {
  13018. var callback = args['callback'] || callback
  13019. , err = args['error'] || function(){}
  13020. , auth_key = args['auth_key'] || AUTH_KEY
  13021. , jsonp = jsonp_cb()
  13022. , uuid = args['uuid'] || UUID
  13023. , data = { 'auth' : auth_key };
  13024. // Make sure we have a Channel
  13025. if (!callback) return error('Missing Callback');
  13026. if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
  13027. if (jsonp != '0') { data['callback'] = jsonp; }
  13028. xdr({
  13029. callback : jsonp,
  13030. data : _get_url_params(data),
  13031. success : function(response) {
  13032. _invoke_callback(response, callback, err);
  13033. },
  13034. fail : function(response) {
  13035. _invoke_error(response, err);
  13036. },
  13037. url : [
  13038. STD_ORIGIN, 'v2', 'presence',
  13039. 'sub_key', SUBSCRIBE_KEY,
  13040. 'uuid', encode(uuid)
  13041. ]
  13042. });
  13043. },
  13044. 'state' : function(args, callback) {
  13045. var callback = args['callback'] || callback || function(r) {}
  13046. , err = args['error'] || function(){}
  13047. , auth_key = args['auth_key'] || AUTH_KEY
  13048. , jsonp = jsonp_cb()
  13049. , state = args['state']
  13050. , uuid = args['uuid'] || UUID
  13051. , channel = args['channel']
  13052. , url
  13053. , data = _get_url_params({ 'auth' : auth_key });
  13054. // Make sure we have a Channel
  13055. if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
  13056. if (!uuid) return error('Missing UUID');
  13057. if (!channel) return error('Missing Channel');
  13058. if (jsonp != '0') { data['callback'] = jsonp; }
  13059. if (CHANNELS[channel] && CHANNELS[channel].subscribed && state) STATE[channel] = state;
  13060. data['state'] = JSON.stringify(state);
  13061. if (state) {
  13062. url = [
  13063. STD_ORIGIN, 'v2', 'presence',
  13064. 'sub-key', SUBSCRIBE_KEY,
  13065. 'channel', encode(channel),
  13066. 'uuid', uuid, 'data'
  13067. ]
  13068. } else {
  13069. url = [
  13070. STD_ORIGIN, 'v2', 'presence',
  13071. 'sub-key', SUBSCRIBE_KEY,
  13072. 'channel', encode(channel),
  13073. 'uuid', encode(uuid)
  13074. ]
  13075. }
  13076. xdr({
  13077. callback : jsonp,
  13078. data : _get_url_params(data),
  13079. success : function(response) {
  13080. _invoke_callback(response, callback, err);
  13081. },
  13082. fail : function(response) {
  13083. _invoke_error(response, err);
  13084. },
  13085. url : url
  13086. });
  13087. },
  13088. /*
  13089. PUBNUB.grant({
  13090. channel : 'my_chat',
  13091. callback : fun,
  13092. error : fun,
  13093. ttl : 24 * 60, // Minutes
  13094. read : true,
  13095. write : true,
  13096. auth_key : '3y8uiajdklytowsj'
  13097. });
  13098. */
  13099. 'grant' : function( args, callback ) {
  13100. var callback = args['callback'] || callback
  13101. , err = args['error'] || function(){}
  13102. , channel = args['channel']
  13103. , jsonp = jsonp_cb()
  13104. , ttl = args['ttl']
  13105. , r = (args['read'] )?"1":"0"
  13106. , w = (args['write'])?"1":"0"
  13107. , auth_key = args['auth_key'];
  13108. if (!callback) return error('Missing Callback');
  13109. if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
  13110. if (!PUBLISH_KEY) return error('Missing Publish Key');
  13111. if (!SECRET_KEY) return error('Missing Secret Key');
  13112. var timestamp = Math.floor(new Date().getTime() / 1000)
  13113. , sign_input = SUBSCRIBE_KEY + "\n" + PUBLISH_KEY + "\n"
  13114. + "grant" + "\n";
  13115. var data = {
  13116. 'w' : w,
  13117. 'r' : r,
  13118. 'timestamp' : timestamp
  13119. };
  13120. if (channel != 'undefined' && channel != null && channel.length > 0) data['channel'] = channel;
  13121. if (jsonp != '0') { data['callback'] = jsonp; }
  13122. if (ttl || ttl === 0) data['ttl'] = ttl;
  13123. if (auth_key) data['auth'] = auth_key;
  13124. data = _get_url_params(data)
  13125. if (!auth_key) delete data['auth'];
  13126. sign_input += _get_pam_sign_input_from_params(data);
  13127. var signature = hmac_SHA256( sign_input, SECRET_KEY );
  13128. signature = signature.replace( /\+/g, "-" );
  13129. signature = signature.replace( /\//g, "_" );
  13130. data['signature'] = signature;
  13131. xdr({
  13132. callback : jsonp,
  13133. data : data,
  13134. success : function(response) {
  13135. _invoke_callback(response, callback, err);
  13136. },
  13137. fail : function(response) {
  13138. _invoke_error(response, err);
  13139. },
  13140. url : [
  13141. STD_ORIGIN, 'v1', 'auth', 'grant' ,
  13142. 'sub-key', SUBSCRIBE_KEY
  13143. ]
  13144. });
  13145. },
  13146. /*
  13147. PUBNUB.audit({
  13148. channel : 'my_chat',
  13149. callback : fun,
  13150. error : fun,
  13151. read : true,
  13152. write : true,
  13153. auth_key : '3y8uiajdklytowsj'
  13154. });
  13155. */
  13156. 'audit' : function( args, callback ) {
  13157. var callback = args['callback'] || callback
  13158. , err = args['error'] || function(){}
  13159. , channel = args['channel']
  13160. , auth_key = args['auth_key']
  13161. , jsonp = jsonp_cb();
  13162. // Make sure we have a Channel
  13163. if (!callback) return error('Missing Callback');
  13164. if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
  13165. if (!PUBLISH_KEY) return error('Missing Publish Key');
  13166. if (!SECRET_KEY) return error('Missing Secret Key');
  13167. var timestamp = Math.floor(new Date().getTime() / 1000)
  13168. , sign_input = SUBSCRIBE_KEY + "\n"
  13169. + PUBLISH_KEY + "\n"
  13170. + "audit" + "\n";
  13171. var data = {'timestamp' : timestamp };
  13172. if (jsonp != '0') { data['callback'] = jsonp; }
  13173. if (channel != 'undefined' && channel != null && channel.length > 0) data['channel'] = channel;
  13174. if (auth_key) data['auth'] = auth_key;
  13175. data = _get_url_params(data)
  13176. if (!auth_key) delete data['auth'];
  13177. sign_input += _get_pam_sign_input_from_params(data);
  13178. var signature = hmac_SHA256( sign_input, SECRET_KEY );
  13179. signature = signature.replace( /\+/g, "-" );
  13180. signature = signature.replace( /\//g, "_" );
  13181. data['signature'] = signature;
  13182. xdr({
  13183. callback : jsonp,
  13184. data : data,
  13185. success : function(response) {
  13186. _invoke_callback(response, callback, err);
  13187. },
  13188. fail : function(response) {
  13189. _invoke_error(response, err);
  13190. },
  13191. url : [
  13192. STD_ORIGIN, 'v1', 'auth', 'audit' ,
  13193. 'sub-key', SUBSCRIBE_KEY
  13194. ]
  13195. });
  13196. },
  13197. /*
  13198. PUBNUB.revoke({
  13199. channel : 'my_chat',
  13200. callback : fun,
  13201. error : fun,
  13202. auth_key : '3y8uiajdklytowsj'
  13203. });
  13204. */
  13205. 'revoke' : function( args, callback ) {
  13206. args['read'] = false;
  13207. args['write'] = false;
  13208. SELF['grant']( args, callback );
  13209. },
  13210. 'set_uuid' : function(uuid) {
  13211. UUID = uuid;
  13212. CONNECT();
  13213. },
  13214. 'get_uuid' : function() {
  13215. return UUID;
  13216. },
  13217. 'presence_heartbeat' : function(args) {
  13218. var callback = args['callback'] || function() {}
  13219. var err = args['error'] || function() {}
  13220. var jsonp = jsonp_cb();
  13221. var data = { 'uuid' : UUID, 'auth' : AUTH_KEY };
  13222. var st = JSON['stringify'](STATE);
  13223. if (st.length > 2) data['state'] = JSON['stringify'](STATE);
  13224. if (PRESENCE_HB > 0 && PRESENCE_HB < 320) data['heartbeat'] = PRESENCE_HB;
  13225. if (jsonp != '0') { data['callback'] = jsonp; }
  13226. xdr({
  13227. callback : jsonp,
  13228. data : _get_url_params(data),
  13229. timeout : SECOND * 5,
  13230. url : [
  13231. STD_ORIGIN, 'v2', 'presence',
  13232. 'sub-key', SUBSCRIBE_KEY,
  13233. 'channel' , encode(generate_channel_list(CHANNELS, true)['join'](',')),
  13234. 'heartbeat'
  13235. ],
  13236. success : function(response) {
  13237. _invoke_callback(response, callback, err);
  13238. },
  13239. fail : function(response) { _invoke_error(response, err); }
  13240. });
  13241. },
  13242. // Expose PUBNUB Functions
  13243. 'xdr' : xdr,
  13244. 'ready' : ready,
  13245. 'db' : db,
  13246. 'uuid' : uuid,
  13247. 'map' : map,
  13248. 'each' : each,
  13249. 'each-channel' : each_channel,
  13250. 'grep' : grep,
  13251. 'offline' : function(){_reset_offline(1, { "message":"Offline. Please check your network settings." })},
  13252. 'supplant' : supplant,
  13253. 'now' : rnow,
  13254. 'unique' : unique,
  13255. 'updater' : updater
  13256. };
  13257. function _poll_online() {
  13258. _is_online() || _reset_offline( 1, {
  13259. "error" : "Offline. Please check your network settings. "
  13260. });
  13261. timeout( _poll_online, SECOND );
  13262. }
  13263. function _poll_online2() {
  13264. SELF['time'](function(success){
  13265. detect_time_detla( function(){}, success );
  13266. success || _reset_offline( 1, {
  13267. "error" : "Heartbeat failed to connect to Pubnub Servers." +
  13268. "Please check your network settings."
  13269. });
  13270. timeout( _poll_online2, KEEPALIVE );
  13271. });
  13272. }
  13273. function _reset_offline(err, msg) {
  13274. SUB_RECEIVER && SUB_RECEIVER(err, msg);
  13275. SUB_RECEIVER = null;
  13276. }
  13277. if (!UUID) UUID = SELF['uuid']();
  13278. db['set']( SUBSCRIBE_KEY + 'uuid', UUID );
  13279. timeout( _poll_online, SECOND );
  13280. timeout( _poll_online2, KEEPALIVE );
  13281. PRESENCE_HB_TIMEOUT = timeout( start_presence_heartbeat, ( PRESENCE_HB_INTERVAL - 3 ) * SECOND ) ;
  13282. // Detect Age of Message
  13283. function detect_latency(tt) {
  13284. var adjusted_time = rnow() - TIME_DRIFT;
  13285. return adjusted_time - tt / 10000;
  13286. }
  13287. detect_time_detla();
  13288. function detect_time_detla( cb, time ) {
  13289. var stime = rnow();
  13290. time && calculate(time) || SELF['time'](calculate);
  13291. function calculate(time) {
  13292. if (!time) return;
  13293. var ptime = time / 10000
  13294. , latency = (rnow() - stime) / 2;
  13295. TIME_DRIFT = rnow() - (ptime + latency);
  13296. cb && cb(TIME_DRIFT);
  13297. }
  13298. }
  13299. return SELF;
  13300. }
  13301. /* ---------------------------------------------------------------------------
  13302. WAIT! - This file depends on instructions from the PUBNUB Cloud.
  13303. http://www.pubnub.com/account
  13304. --------------------------------------------------------------------------- */
  13305. /* ---------------------------------------------------------------------------
  13306. PubNub Real-time Cloud-Hosted Push API and Push Notification Client Frameworks
  13307. Copyright (c) 2011 TopMambo Inc.
  13308. http://www.pubnub.com/
  13309. http://www.pubnub.com/terms
  13310. --------------------------------------------------------------------------- */
  13311. /* ---------------------------------------------------------------------------
  13312. Permission is hereby granted, free of charge, to any person obtaining a copy
  13313. of this software and associated documentation files (the "Software"), to deal
  13314. in the Software without restriction, including without limitation the rights
  13315. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13316. copies of the Software, and to permit persons to whom the Software is
  13317. furnished to do so, subject to the following conditions:
  13318. The above copyright notice and this permission notice shall be included in
  13319. all copies or substantial portions of the Software.
  13320. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13321. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13322. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  13323. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  13324. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  13325. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  13326. THE SOFTWARE.
  13327. --------------------------------------------------------------------------- */
  13328. /**
  13329. * UTIL LOCALS
  13330. */
  13331. var NOW = 1
  13332. , http = __webpack_require__(30)
  13333. , https = __webpack_require__(46)
  13334. , keepAliveAgent = new (keepAliveIsEmbedded() ? http.Agent : __webpack_require__(156))({
  13335. keepAlive: true,
  13336. keepAliveMsecs: 300000,
  13337. maxSockets: 5
  13338. })
  13339. , XHRTME = 310000
  13340. , DEF_TIMEOUT = 10000
  13341. , SECOND = 1000
  13342. , PNSDK = 'PubNub-JS-' + 'Nodejs' + '/' + '3.6.8'
  13343. , crypto = __webpack_require__(48)
  13344. , proxy = null
  13345. , XORIGN = 1;
  13346. function get_hmac_SHA256(data, key) {
  13347. return crypto.createHmac('sha256',
  13348. new Buffer(key, 'utf8')).update(data).digest('base64');
  13349. }
  13350. /**
  13351. * ERROR
  13352. * ===
  13353. * error('message');
  13354. */
  13355. function error(message) { console['error'](message) }
  13356. /**
  13357. * Request
  13358. * =======
  13359. * xdr({
  13360. * url : ['http://www.blah.com/url'],
  13361. * success : function(response) {},
  13362. * fail : function() {}
  13363. * });
  13364. */
  13365. function xdr( setup ) {
  13366. var request
  13367. , response
  13368. , success = setup.success || function(){}
  13369. , fail = setup.fail || function(){}
  13370. , origin = setup.origin || 'pubsub.pubnub.com'
  13371. , ssl = setup.ssl
  13372. , failed = 0
  13373. , complete = 0
  13374. , loaded = 0
  13375. , mode = setup['mode'] || 'GET'
  13376. , data = setup['data'] || {}
  13377. , xhrtme = setup.timeout || DEF_TIMEOUT
  13378. , body = ''
  13379. , finished = function() {
  13380. if (loaded) return;
  13381. loaded = 1;
  13382. clearTimeout(timer);
  13383. try { response = JSON['parse'](body); }
  13384. catch (r) { return done(1); }
  13385. success(response);
  13386. }
  13387. , done = function(failed, response) {
  13388. if (complete) return;
  13389. complete = 1;
  13390. clearTimeout(timer);
  13391. if (request) {
  13392. request.on('error', function(){});
  13393. request.on('data', function(){});
  13394. request.on('end', function(){});
  13395. request.abort && request.abort();
  13396. request = null;
  13397. }
  13398. failed && fail(response);
  13399. }
  13400. , timer = timeout( function(){done(1);} , xhrtme );
  13401. data['pnsdk'] = PNSDK;
  13402. var options = {};
  13403. var headers = {};
  13404. var payload = '';
  13405. if (mode == 'POST')
  13406. payload = decodeURIComponent(setup.url.pop());
  13407. var url = build_url( setup.url, data );
  13408. if (!ssl) ssl = (url.split('://')[0] == 'https')?true:false;
  13409. url = '/' + url.split('/').slice(3).join('/');
  13410. var origin = setup.url[0].split("//")[1]
  13411. options.hostname = proxy ? proxy.hostname : setup.url[0].split("//")[1];
  13412. options.port = proxy ? proxy.port : ssl ? 443 : 80;
  13413. options.path = proxy ? "http://" + origin + url:url;
  13414. options.headers = proxy ? { 'Host': origin }:null;
  13415. options.method = mode;
  13416. options.keepAlive= !!keepAliveAgent;
  13417. options.agent = keepAliveAgent;
  13418. options.body = payload;
  13419. __webpack_require__(30).globalAgent.maxSockets = Infinity;
  13420. try {
  13421. request = (ssl ? https : http)['request'](options, function(response) {
  13422. response.setEncoding('utf8');
  13423. response.on( 'error', function(){console.log('error');done(1, body || { "error" : "Network Connection Error"})});
  13424. response.on( 'abort', function(){console.log('abort');done(1, body || { "error" : "Network Connection Error"})});
  13425. response.on( 'data', function (chunk) {
  13426. if (chunk) body += chunk;
  13427. } );
  13428. response.on( 'end', function(){
  13429. var statusCode = response.statusCode;
  13430. switch(statusCode) {
  13431. case 401:
  13432. case 402:
  13433. case 403:
  13434. try {
  13435. response = JSON['parse'](body);
  13436. done(1,response);
  13437. }
  13438. catch (r) { return done(1, body); }
  13439. return;
  13440. default:
  13441. break;
  13442. }
  13443. finished();
  13444. });
  13445. });
  13446. request.timeout = xhrtme;
  13447. request.on( 'error', function() {
  13448. done( 1, {"error":"Network Connection Error"} );
  13449. } );
  13450. if (mode == 'POST') request.write(payload);
  13451. request.end();
  13452. } catch(e) {
  13453. done(0);
  13454. return xdr(setup);
  13455. }
  13456. return done;
  13457. }
  13458. /**
  13459. * LOCAL STORAGE
  13460. */
  13461. var db = (function(){
  13462. var store = {};
  13463. return {
  13464. 'get' : function(key) {
  13465. return store[key];
  13466. },
  13467. 'set' : function( key, value ) {
  13468. store[key] = value;
  13469. }
  13470. };
  13471. })();
  13472. function crypto_obj() {
  13473. var iv = "0123456789012345";
  13474. function get_padded_key(key) {
  13475. return crypto.createHash('sha256').update(key).digest("hex").slice(0,32);
  13476. }
  13477. return {
  13478. 'encrypt' : function(input, key) {
  13479. if (!key) return input;
  13480. var plain_text = JSON['stringify'](input);
  13481. var cipher = crypto.createCipheriv('aes-256-cbc', get_padded_key(key), iv);
  13482. var base_64_encrypted = cipher.update(plain_text, 'utf8', 'base64') + cipher.final('base64');
  13483. return base_64_encrypted || input;
  13484. },
  13485. 'decrypt' : function(input, key) {
  13486. if (!key) return input;
  13487. var decipher = crypto.createDecipheriv('aes-256-cbc', get_padded_key(key), iv);
  13488. try {
  13489. var decrypted = decipher.update(input, 'base64', 'utf8') + decipher.final('utf8');
  13490. } catch (e) {
  13491. return null;
  13492. }
  13493. return JSON.parse(decrypted);
  13494. }
  13495. }
  13496. }
  13497. function keepAliveIsEmbedded() {
  13498. return 'EventEmitter' in http.Agent.super_;
  13499. }
  13500. var CREATE_PUBNUB = function(setup) {
  13501. proxy = setup['proxy'];
  13502. setup['xdr'] = xdr;
  13503. setup['db'] = db;
  13504. setup['error'] = setup['error'] || error;
  13505. setup['hmac_SHA256'] = get_hmac_SHA256;
  13506. setup['crypto_obj'] = crypto_obj();
  13507. setup['params'] = {'pnsdk' : PNSDK};
  13508. if (setup['keepAlive'] === false) {
  13509. keepAliveAgent = undefined;
  13510. }
  13511. SELF = function(setup) {
  13512. return CREATE_PUBNUB(setup);
  13513. }
  13514. var PN = PN_API(setup);
  13515. for (var prop in PN) {
  13516. if (PN.hasOwnProperty(prop)) {
  13517. SELF[prop] = PN[prop];
  13518. }
  13519. }
  13520. SELF.init = SELF;
  13521. SELF.secure = SELF;
  13522. SELF.ready();
  13523. return SELF;
  13524. }
  13525. CREATE_PUBNUB.init = CREATE_PUBNUB;
  13526. CREATE_PUBNUB.unique = unique
  13527. CREATE_PUBNUB.secure = CREATE_PUBNUB;
  13528. module.exports = CREATE_PUBNUB
  13529. module.exports.PNmessage = PNmessage;
  13530. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(47).Buffer))
  13531. /***/ },
  13532. /* 87 */
  13533. /***/ function(module, exports, __webpack_require__) {
  13534. var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  13535. ;(function (exports) {
  13536. 'use strict';
  13537. var Arr = (typeof Uint8Array !== 'undefined')
  13538. ? Uint8Array
  13539. : Array
  13540. var PLUS = '+'.charCodeAt(0)
  13541. var SLASH = '/'.charCodeAt(0)
  13542. var NUMBER = '0'.charCodeAt(0)
  13543. var LOWER = 'a'.charCodeAt(0)
  13544. var UPPER = 'A'.charCodeAt(0)
  13545. function decode (elt) {
  13546. var code = elt.charCodeAt(0)
  13547. if (code === PLUS)
  13548. return 62 // '+'
  13549. if (code === SLASH)
  13550. return 63 // '/'
  13551. if (code < NUMBER)
  13552. return -1 //no match
  13553. if (code < NUMBER + 10)
  13554. return code - NUMBER + 26 + 26
  13555. if (code < UPPER + 26)
  13556. return code - UPPER
  13557. if (code < LOWER + 26)
  13558. return code - LOWER + 26
  13559. }
  13560. function b64ToByteArray (b64) {
  13561. var i, j, l, tmp, placeHolders, arr
  13562. if (b64.length % 4 > 0) {
  13563. throw new Error('Invalid string. Length must be a multiple of 4')
  13564. }
  13565. // the number of equal signs (place holders)
  13566. // if there are two placeholders, than the two characters before it
  13567. // represent one byte
  13568. // if there is only one, then the three characters before it represent 2 bytes
  13569. // this is just a cheap hack to not do indexOf twice
  13570. var len = b64.length
  13571. placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
  13572. // base64 is 4/3 + up to two characters of the original data
  13573. arr = new Arr(b64.length * 3 / 4 - placeHolders)
  13574. // if there are placeholders, only get up to the last complete 4 chars
  13575. l = placeHolders > 0 ? b64.length - 4 : b64.length
  13576. var L = 0
  13577. function push (v) {
  13578. arr[L++] = v
  13579. }
  13580. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  13581. tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
  13582. push((tmp & 0xFF0000) >> 16)
  13583. push((tmp & 0xFF00) >> 8)
  13584. push(tmp & 0xFF)
  13585. }
  13586. if (placeHolders === 2) {
  13587. tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
  13588. push(tmp & 0xFF)
  13589. } else if (placeHolders === 1) {
  13590. tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
  13591. push((tmp >> 8) & 0xFF)
  13592. push(tmp & 0xFF)
  13593. }
  13594. return arr
  13595. }
  13596. function uint8ToBase64 (uint8) {
  13597. var i,
  13598. extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
  13599. output = "",
  13600. temp, length
  13601. function encode (num) {
  13602. return lookup.charAt(num)
  13603. }
  13604. function tripletToBase64 (num) {
  13605. return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
  13606. }
  13607. // go through the array every three bytes, we'll deal with trailing stuff later
  13608. for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
  13609. temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
  13610. output += tripletToBase64(temp)
  13611. }
  13612. // pad the end with zeros, but make sure to not forget the extra bytes
  13613. switch (extraBytes) {
  13614. case 1:
  13615. temp = uint8[uint8.length - 1]
  13616. output += encode(temp >> 2)
  13617. output += encode((temp << 4) & 0x3F)
  13618. output += '=='
  13619. break
  13620. case 2:
  13621. temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
  13622. output += encode(temp >> 10)
  13623. output += encode((temp >> 4) & 0x3F)
  13624. output += encode((temp << 2) & 0x3F)
  13625. output += '='
  13626. break
  13627. }
  13628. return output
  13629. }
  13630. exports.toByteArray = b64ToByteArray
  13631. exports.fromByteArray = uint8ToBase64
  13632. }(false ? (this.base64js = {}) : exports))
  13633. /***/ },
  13634. /* 88 */
  13635. /***/ function(module, exports, __webpack_require__) {
  13636. /* WEBPACK VAR INJECTION */(function(process) {// Copyright Joyent, Inc. and other Node contributors.
  13637. //
  13638. // Permission is hereby granted, free of charge, to any person obtaining a
  13639. // copy of this software and associated documentation files (the
  13640. // "Software"), to deal in the Software without restriction, including
  13641. // without limitation the rights to use, copy, modify, merge, publish,
  13642. // distribute, sublicense, and/or sell copies of the Software, and to permit
  13643. // persons to whom the Software is furnished to do so, subject to the
  13644. // following conditions:
  13645. //
  13646. // The above copyright notice and this permission notice shall be included
  13647. // in all copies or substantial portions of the Software.
  13648. //
  13649. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  13650. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  13651. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  13652. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  13653. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  13654. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  13655. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  13656. // copy from https://github.com/joyent/node/blob/master/lib/_http_agent.js
  13657. var net = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"net\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()));
  13658. var url = __webpack_require__(31);
  13659. var util = __webpack_require__(79);
  13660. var EventEmitter = __webpack_require__(44).EventEmitter;
  13661. // var ClientRequest = require('_http_client').ClientRequest;
  13662. // var debug = util.debuglog('http');
  13663. var ClientRequest = __webpack_require__(30).ClientRequest;
  13664. var debug;
  13665. if (process.env.NODE_DEBUG && /agentkeepalive/.test(process.env.NODE_DEBUG)) {
  13666. debug = function (x) {
  13667. console.error.apply(console, arguments);
  13668. };
  13669. } else {
  13670. debug = function () { };
  13671. }
  13672. // New Agent code.
  13673. // The largest departure from the previous implementation is that
  13674. // an Agent instance holds connections for a variable number of host:ports.
  13675. // Surprisingly, this is still API compatible as far as third parties are
  13676. // concerned. The only code that really notices the difference is the
  13677. // request object.
  13678. // Another departure is that all code related to HTTP parsing is in
  13679. // ClientRequest.onSocket(). The Agent is now *strictly*
  13680. // concerned with managing a connection pool.
  13681. function Agent(options) {
  13682. if (!(this instanceof Agent))
  13683. return new Agent(options);
  13684. EventEmitter.call(this);
  13685. var self = this;
  13686. self.defaultPort = 80;
  13687. self.protocol = 'http:';
  13688. self.options = util._extend({}, options);
  13689. // don't confuse net and make it think that we're connecting to a pipe
  13690. self.options.path = null;
  13691. self.requests = {};
  13692. self.sockets = {};
  13693. self.freeSockets = {};
  13694. self.keepAliveMsecs = self.options.keepAliveMsecs || 1000;
  13695. self.keepAlive = self.options.keepAlive || false;
  13696. self.maxSockets = self.options.maxSockets || Agent.defaultMaxSockets;
  13697. self.maxFreeSockets = self.options.maxFreeSockets || 256;
  13698. self.on('free', function(socket, options) {
  13699. var name = self.getName(options);
  13700. debug('agent.on(free)', name);
  13701. if (!self.isDestroyed(socket) &&
  13702. self.requests[name] && self.requests[name].length) {
  13703. self.requests[name].shift().onSocket(socket);
  13704. if (self.requests[name].length === 0) {
  13705. // don't leak
  13706. delete self.requests[name];
  13707. }
  13708. } else {
  13709. // If there are no pending requests, then put it in
  13710. // the freeSockets pool, but only if we're allowed to do so.
  13711. var req = socket._httpMessage;
  13712. if (req &&
  13713. req.shouldKeepAlive &&
  13714. !self.isDestroyed(socket) &&
  13715. self.options.keepAlive) {
  13716. var freeSockets = self.freeSockets[name];
  13717. var freeLen = freeSockets ? freeSockets.length : 0;
  13718. var count = freeLen;
  13719. if (self.sockets[name])
  13720. count += self.sockets[name].length;
  13721. if (count >= self.maxSockets || freeLen >= self.maxFreeSockets) {
  13722. self.removeSocket(socket, options);
  13723. socket.destroy();
  13724. } else {
  13725. freeSockets = freeSockets || [];
  13726. self.freeSockets[name] = freeSockets;
  13727. socket.setKeepAlive(true, self.keepAliveMsecs);
  13728. socket.unref && socket.unref();
  13729. socket._httpMessage = null;
  13730. self.removeSocket(socket, options);
  13731. freeSockets.push(socket);
  13732. }
  13733. } else {
  13734. self.removeSocket(socket, options);
  13735. socket.destroy();
  13736. }
  13737. }
  13738. });
  13739. }
  13740. util.inherits(Agent, EventEmitter);
  13741. exports.Agent = Agent;
  13742. Agent.defaultMaxSockets = Infinity;
  13743. Agent.prototype.createConnection = net.createConnection;
  13744. // Get the key for a given set of request options
  13745. Agent.prototype.getName = function(options) {
  13746. var name = '';
  13747. if (options.host)
  13748. name += options.host;
  13749. else
  13750. name += 'localhost';
  13751. name += ':';
  13752. if (options.port)
  13753. name += options.port;
  13754. name += ':';
  13755. if (options.localAddress)
  13756. name += options.localAddress;
  13757. name += ':';
  13758. return name;
  13759. };
  13760. Agent.prototype.addRequest = function(req, options) {
  13761. // Legacy API: addRequest(req, host, port, path)
  13762. if (typeof options === 'string') {
  13763. options = {
  13764. host: options,
  13765. port: arguments[2],
  13766. path: arguments[3]
  13767. };
  13768. }
  13769. var name = this.getName(options);
  13770. if (!this.sockets[name]) {
  13771. this.sockets[name] = [];
  13772. }
  13773. var freeLen = this.freeSockets[name] ? this.freeSockets[name].length : 0;
  13774. var sockLen = freeLen + this.sockets[name].length;
  13775. if (freeLen) {
  13776. // we have a free socket, so use that.
  13777. var socket = this.freeSockets[name].shift();
  13778. debug('have free socket');
  13779. // don't leak
  13780. if (!this.freeSockets[name].length)
  13781. delete this.freeSockets[name];
  13782. socket.ref && socket.ref();
  13783. req.onSocket(socket);
  13784. this.sockets[name].push(socket);
  13785. } else if (sockLen < this.maxSockets) {
  13786. debug('call onSocket', sockLen, freeLen);
  13787. // If we are under maxSockets create a new one.
  13788. req.onSocket(this.createSocket(req, options));
  13789. } else {
  13790. debug('wait for socket');
  13791. // We are over limit so we'll add it to the queue.
  13792. if (!this.requests[name]) {
  13793. this.requests[name] = [];
  13794. }
  13795. this.requests[name].push(req);
  13796. }
  13797. };
  13798. Agent.prototype.createSocket = function(req, options) {
  13799. var self = this;
  13800. options = util._extend({}, options);
  13801. options = util._extend(options, self.options);
  13802. options.servername = options.host;
  13803. if (req) {
  13804. var hostHeader = req.getHeader('host');
  13805. if (hostHeader) {
  13806. options.servername = hostHeader.replace(/:.*$/, '');
  13807. }
  13808. }
  13809. var name = self.getName(options);
  13810. debug('createConnection', name, options);
  13811. var s = self.createConnection(options);
  13812. if (!self.sockets[name]) {
  13813. self.sockets[name] = [];
  13814. }
  13815. this.sockets[name].push(s);
  13816. debug('sockets', name, this.sockets[name].length);
  13817. function onFree() {
  13818. self.emit('free', s, options);
  13819. }
  13820. s.on('free', onFree);
  13821. function onClose(err) {
  13822. debug('CLIENT socket onClose');
  13823. // This is the only place where sockets get removed from the Agent.
  13824. // If you want to remove a socket from the pool, just close it.
  13825. // All socket errors end in a close event anyway.
  13826. self.removeSocket(s, options);
  13827. }
  13828. s.on('close', onClose);
  13829. function onRemove() {
  13830. // We need this function for cases like HTTP 'upgrade'
  13831. // (defined by WebSockets) where we need to remove a socket from the
  13832. // pool because it'll be locked up indefinitely
  13833. debug('CLIENT socket onRemove');
  13834. self.removeSocket(s, options, 'agentRemove');
  13835. s.removeListener('close', onClose);
  13836. s.removeListener('free', onFree);
  13837. s.removeListener('agentRemove', onRemove);
  13838. }
  13839. s.on('agentRemove', onRemove);
  13840. return s;
  13841. };
  13842. Agent.prototype.removeSocket = function(s, options) {
  13843. var name = this.getName(options);
  13844. debug('removeSocket', name, 'destroyed:', this.isDestroyed(s));
  13845. var sets = [this.sockets];
  13846. if (this.isDestroyed(s)) {
  13847. // If the socket was destroyed, we need to remove it from the free buffers.
  13848. sets.push(this.freeSockets);
  13849. }
  13850. sets.forEach(function(sockets) {
  13851. if (sockets[name]) {
  13852. var index = sockets[name].indexOf(s);
  13853. if (index !== -1) {
  13854. sockets[name].splice(index, 1);
  13855. if (sockets[name].length === 0) {
  13856. // don't leak
  13857. delete sockets[name];
  13858. }
  13859. }
  13860. }
  13861. });
  13862. if (this.requests[name] && this.requests[name].length) {
  13863. debug('removeSocket, have a request, make a socket');
  13864. var req = this.requests[name][0];
  13865. // If we have pending requests and a socket gets closed make a new one
  13866. this.createSocket(req, options).emit('free');
  13867. }
  13868. };
  13869. Agent.prototype.destroy = function() {
  13870. var sets = [this.freeSockets, this.sockets];
  13871. sets.forEach(function(set) {
  13872. Object.keys(set).forEach(function(name) {
  13873. set[name].forEach(function(socket) {
  13874. socket.destroy();
  13875. });
  13876. });
  13877. });
  13878. };
  13879. Agent.prototype.request = function(options, cb) {
  13880. // if (util.isString(options)) {
  13881. // options = url.parse(options);
  13882. // }
  13883. if (typeof options === 'string') {
  13884. options = url.parse(options);
  13885. }
  13886. // don't try to do dns lookups of foo.com:8080, just foo.com
  13887. if (options.hostname) {
  13888. options.host = options.hostname;
  13889. }
  13890. if (options && options.path && / /.test(options.path)) {
  13891. // The actual regex is more like /[^A-Za-z0-9\-._~!$&'()*+,;=/:@]/
  13892. // with an additional rule for ignoring percentage-escaped characters
  13893. // but that's a) hard to capture in a regular expression that performs
  13894. // well, and b) possibly too restrictive for real-world usage. That's
  13895. // why it only scans for spaces because those are guaranteed to create
  13896. // an invalid request.
  13897. throw new TypeError('Request path contains unescaped characters.');
  13898. } else if (options.protocol && options.protocol !== this.protocol) {
  13899. throw new Error('Protocol:' + options.protocol + ' not supported.');
  13900. }
  13901. options = util._extend({
  13902. agent: this,
  13903. keepAlive: this.keepAlive
  13904. }, options);
  13905. // if it's false, then make a new one, just like this one.
  13906. if (options.agent === false)
  13907. options.agent = new this.constructor();
  13908. debug('agent.request', options);
  13909. return new ClientRequest(options, cb);
  13910. };
  13911. Agent.prototype.get = function(options, cb) {
  13912. var req = this.request(options, cb);
  13913. req.end();
  13914. return req;
  13915. };
  13916. Agent.prototype.isDestroyed = function(socket){
  13917. return socket.destroyed || socket._destroyed;
  13918. }
  13919. exports.globalAgent = new Agent();
  13920. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(99)))
  13921. /***/ },
  13922. /* 89 */
  13923. /***/ function(module, exports, __webpack_require__) {
  13924. var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(module) {/*
  13925. Copyright (c) 2010,2011,2012,2013 Morgan Roderick http://roderick.dk
  13926. License: MIT - http://mrgnrdrck.mit-license.org
  13927. https://github.com/mroderick/PubSubJS
  13928. */
  13929. /*jslint white:true, plusplus:true, stupid:true*/
  13930. /*global
  13931. setTimeout,
  13932. module,
  13933. exports,
  13934. define,
  13935. require,
  13936. window
  13937. */
  13938. (function(root, factory){
  13939. 'use strict';
  13940. // CommonJS
  13941. if (typeof exports === 'object' && module){
  13942. module.exports = factory();
  13943. // AMD
  13944. } else if (true){
  13945. !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  13946. // Browser
  13947. } else {
  13948. root.PubSub = factory();
  13949. }
  13950. }( ( typeof window === 'object' && window ) || this, function(){
  13951. 'use strict';
  13952. var PubSub = {},
  13953. messages = {},
  13954. lastUid = -1;
  13955. function hasKeys(obj){
  13956. var key;
  13957. for (key in obj){
  13958. if ( obj.hasOwnProperty(key) ){
  13959. return true;
  13960. }
  13961. }
  13962. return false;
  13963. }
  13964. /**
  13965. * Returns a function that throws the passed exception, for use as argument for setTimeout
  13966. * @param { Object } ex An Error object
  13967. */
  13968. function throwException( ex ){
  13969. return function reThrowException(){
  13970. throw ex;
  13971. };
  13972. }
  13973. function callSubscriberWithDelayedExceptions( subscriber, message, data ){
  13974. try {
  13975. subscriber( message, data );
  13976. } catch( ex ){
  13977. setTimeout( throwException( ex ), 0);
  13978. }
  13979. }
  13980. function callSubscriberWithImmediateExceptions( subscriber, message, data ){
  13981. subscriber( message, data );
  13982. }
  13983. function deliverMessage( originalMessage, matchedMessage, data, immediateExceptions ){
  13984. var subscribers = messages[matchedMessage],
  13985. callSubscriber = immediateExceptions ? callSubscriberWithImmediateExceptions : callSubscriberWithDelayedExceptions,
  13986. s;
  13987. if ( !messages.hasOwnProperty( matchedMessage ) ) {
  13988. return;
  13989. }
  13990. for (s in subscribers){
  13991. if ( subscribers.hasOwnProperty(s)){
  13992. callSubscriber( subscribers[s], originalMessage, data );
  13993. }
  13994. }
  13995. }
  13996. function createDeliveryFunction( message, data, immediateExceptions ){
  13997. return function deliverNamespaced(){
  13998. var topic = String( message ),
  13999. position = topic.lastIndexOf( '.' );
  14000. // deliver the message as it is now
  14001. deliverMessage(message, message, data, immediateExceptions);
  14002. // trim the hierarchy and deliver message to each level
  14003. while( position !== -1 ){
  14004. topic = topic.substr( 0, position );
  14005. position = topic.lastIndexOf('.');
  14006. deliverMessage( message, topic, data );
  14007. }
  14008. };
  14009. }
  14010. function messageHasSubscribers( message ){
  14011. var topic = String( message ),
  14012. found = Boolean(messages.hasOwnProperty( topic ) && hasKeys(messages[topic])),
  14013. position = topic.lastIndexOf( '.' );
  14014. while ( !found && position !== -1 ){
  14015. topic = topic.substr( 0, position );
  14016. position = topic.lastIndexOf( '.' );
  14017. found = Boolean(messages.hasOwnProperty( topic ) && hasKeys(messages[topic]));
  14018. }
  14019. return found;
  14020. }
  14021. function publish( message, data, sync, immediateExceptions ){
  14022. var deliver = createDeliveryFunction( message, data, immediateExceptions ),
  14023. hasSubscribers = messageHasSubscribers( message );
  14024. if ( !hasSubscribers ){
  14025. return false;
  14026. }
  14027. if ( sync === true ){
  14028. deliver();
  14029. } else {
  14030. setTimeout( deliver, 0 );
  14031. }
  14032. return true;
  14033. }
  14034. /**
  14035. * PubSub.publish( message[, data] ) -> Boolean
  14036. * - message (String): The message to publish
  14037. * - data: The data to pass to subscribers
  14038. * Publishes the the message, passing the data to it's subscribers
  14039. **/
  14040. PubSub.publish = function( message, data ){
  14041. return publish( message, data, false, PubSub.immediateExceptions );
  14042. };
  14043. /**
  14044. * PubSub.publishSync( message[, data] ) -> Boolean
  14045. * - message (String): The message to publish
  14046. * - data: The data to pass to subscribers
  14047. * Publishes the the message synchronously, passing the data to it's subscribers
  14048. **/
  14049. PubSub.publishSync = function( message, data ){
  14050. return publish( message, data, true, PubSub.immediateExceptions );
  14051. };
  14052. /**
  14053. * PubSub.subscribe( message, func ) -> String
  14054. * - message (String): The message to subscribe to
  14055. * - func (Function): The function to call when a new message is published
  14056. * Subscribes the passed function to the passed message. Every returned token is unique and should be stored if
  14057. * you need to unsubscribe
  14058. **/
  14059. PubSub.subscribe = function( message, func ){
  14060. if ( typeof func !== 'function'){
  14061. return false;
  14062. }
  14063. // message is not registered yet
  14064. if ( !messages.hasOwnProperty( message ) ){
  14065. messages[message] = {};
  14066. }
  14067. // forcing token as String, to allow for future expansions without breaking usage
  14068. // and allow for easy use as key names for the 'messages' object
  14069. var token = 'uid_' + String(++lastUid);
  14070. messages[message][token] = func;
  14071. // return token for unsubscribing
  14072. return token;
  14073. };
  14074. /**
  14075. * PubSub.unsubscribe( tokenOrFunction ) -> String | Boolean
  14076. * - tokenOrFunction (String|Function): The token of the function to unsubscribe or func passed in on subscribe
  14077. * Unsubscribes a specific subscriber from a specific message using the unique token
  14078. * or if using Function as argument, it will remove all subscriptions with that function
  14079. **/
  14080. PubSub.unsubscribe = function( tokenOrFunction ){
  14081. var isToken = typeof tokenOrFunction === 'string',
  14082. result = false,
  14083. m, message, t, token;
  14084. for ( m in messages ){
  14085. if ( messages.hasOwnProperty( m ) ){
  14086. message = messages[m];
  14087. if ( isToken && message[tokenOrFunction] ){
  14088. delete message[tokenOrFunction];
  14089. result = tokenOrFunction;
  14090. // tokens are unique, so we can just stop here
  14091. break;
  14092. } else if (!isToken) {
  14093. for ( t in message ){
  14094. if (message.hasOwnProperty(t) && message[t] === tokenOrFunction){
  14095. delete message[t];
  14096. result = true;
  14097. }
  14098. }
  14099. }
  14100. }
  14101. }
  14102. return result;
  14103. };
  14104. return PubSub;
  14105. }));
  14106. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(83)(module)))
  14107. /***/ },
  14108. /* 90 */
  14109. /***/ function(module, exports, __webpack_require__) {
  14110. "use strict";
  14111. var Promise = __webpack_require__(139).Promise;
  14112. var polyfill = __webpack_require__(140).polyfill;
  14113. exports.Promise = Promise;
  14114. exports.polyfill = polyfill;
  14115. /***/ },
  14116. /* 91 */
  14117. /***/ function(module, exports, __webpack_require__) {
  14118. /* WEBPACK VAR INJECTION */(function(process) {/**
  14119. * Copyright (c) 2014 Petka Antonov
  14120. *
  14121. * Permission is hereby granted, free of charge, to any person obtaining a copy
  14122. * of this software and associated documentation files (the "Software"), to deal
  14123. * in the Software without restriction, including without limitation the rights
  14124. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  14125. * copies of the Software, and to permit persons to whom the Software is
  14126. * furnished to do so, subject to the following conditions:</p>
  14127. *
  14128. * The above copyright notice and this permission notice shall be included in
  14129. * all copies or substantial portions of the Software.
  14130. *
  14131. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14132. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14133. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14134. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  14135. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  14136. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  14137. * THE SOFTWARE.
  14138. *
  14139. */
  14140. "use strict";
  14141. module.exports = function() {
  14142. var global = __webpack_require__(107);
  14143. var util = __webpack_require__(108);
  14144. var async = __webpack_require__(109);
  14145. var errors = __webpack_require__(110);
  14146. var INTERNAL = function(){};
  14147. var APPLY = {};
  14148. var NEXT_FILTER = {e: null};
  14149. var PromiseArray = __webpack_require__(111)(Promise, INTERNAL);
  14150. var CapturedTrace = __webpack_require__(112)();
  14151. var CatchFilter = __webpack_require__(113)(NEXT_FILTER);
  14152. var PromiseResolver = __webpack_require__(114);
  14153. var isArray = util.isArray;
  14154. var errorObj = util.errorObj;
  14155. var tryCatch1 = util.tryCatch1;
  14156. var tryCatch2 = util.tryCatch2;
  14157. var tryCatchApply = util.tryCatchApply;
  14158. var RangeError = errors.RangeError;
  14159. var TypeError = errors.TypeError;
  14160. var CancellationError = errors.CancellationError;
  14161. var TimeoutError = errors.TimeoutError;
  14162. var RejectionError = errors.RejectionError;
  14163. var originatesFromRejection = errors.originatesFromRejection;
  14164. var markAsOriginatingFromRejection = errors.markAsOriginatingFromRejection;
  14165. var canAttach = errors.canAttach;
  14166. var thrower = util.thrower;
  14167. var apiRejection = __webpack_require__(115)(Promise);
  14168. var makeSelfResolutionError = function Promise$_makeSelfResolutionError() {
  14169. return new TypeError("circular promise resolution chain");
  14170. };
  14171. function isPromise(obj) {
  14172. if (obj === void 0) return false;
  14173. return obj instanceof Promise;
  14174. }
  14175. function isPromiseArrayProxy(receiver, promiseSlotValue) {
  14176. if (receiver instanceof PromiseArray) {
  14177. return promiseSlotValue >= 0;
  14178. }
  14179. return false;
  14180. }
  14181. function Promise(resolver) {
  14182. if (typeof resolver !== "function") {
  14183. throw new TypeError("the promise constructor requires a resolver function");
  14184. }
  14185. if (this.constructor !== Promise) {
  14186. throw new TypeError("the promise constructor cannot be invoked directly");
  14187. }
  14188. this._bitField = 0;
  14189. this._fulfillmentHandler0 = void 0;
  14190. this._rejectionHandler0 = void 0;
  14191. this._promise0 = void 0;
  14192. this._receiver0 = void 0;
  14193. this._settledValue = void 0;
  14194. this._boundTo = void 0;
  14195. if (resolver !== INTERNAL) this._resolveFromResolver(resolver);
  14196. }
  14197. Promise.prototype.bind = function Promise$bind(thisArg) {
  14198. var ret = new Promise(INTERNAL);
  14199. ret._setTrace(this);
  14200. ret._follow(this);
  14201. ret._setBoundTo(thisArg);
  14202. if (this._cancellable()) {
  14203. ret._setCancellable();
  14204. ret._cancellationParent = this;
  14205. }
  14206. return ret;
  14207. };
  14208. Promise.prototype.toString = function Promise$toString() {
  14209. return "[object Promise]";
  14210. };
  14211. Promise.prototype.caught = Promise.prototype["catch"] =
  14212. function Promise$catch(fn) {
  14213. var len = arguments.length;
  14214. if (len > 1) {
  14215. var catchInstances = new Array(len - 1),
  14216. j = 0, i;
  14217. for (i = 0; i < len - 1; ++i) {
  14218. var item = arguments[i];
  14219. if (typeof item === "function") {
  14220. catchInstances[j++] = item;
  14221. }
  14222. else {
  14223. var catchFilterTypeError =
  14224. new TypeError(
  14225. "A catch filter must be an error constructor "
  14226. + "or a filter function");
  14227. this._attachExtraTrace(catchFilterTypeError);
  14228. async.invoke(this._reject, this, catchFilterTypeError);
  14229. return;
  14230. }
  14231. }
  14232. catchInstances.length = j;
  14233. fn = arguments[i];
  14234. this._resetTrace();
  14235. var catchFilter = new CatchFilter(catchInstances, fn, this);
  14236. return this._then(void 0, catchFilter.doFilter, void 0,
  14237. catchFilter, void 0);
  14238. }
  14239. return this._then(void 0, fn, void 0, void 0, void 0);
  14240. };
  14241. Promise.prototype.then =
  14242. function Promise$then(didFulfill, didReject, didProgress) {
  14243. return this._then(didFulfill, didReject, didProgress,
  14244. void 0, void 0);
  14245. };
  14246. Promise.prototype.done =
  14247. function Promise$done(didFulfill, didReject, didProgress) {
  14248. var promise = this._then(didFulfill, didReject, didProgress,
  14249. void 0, void 0);
  14250. promise._setIsFinal();
  14251. };
  14252. Promise.prototype.spread = function Promise$spread(didFulfill, didReject) {
  14253. return this._then(didFulfill, didReject, void 0,
  14254. APPLY, void 0);
  14255. };
  14256. Promise.prototype.isCancellable = function Promise$isCancellable() {
  14257. return !this.isResolved() &&
  14258. this._cancellable();
  14259. };
  14260. Promise.prototype.toJSON = function Promise$toJSON() {
  14261. var ret = {
  14262. isFulfilled: false,
  14263. isRejected: false,
  14264. fulfillmentValue: void 0,
  14265. rejectionReason: void 0
  14266. };
  14267. if (this.isFulfilled()) {
  14268. ret.fulfillmentValue = this._settledValue;
  14269. ret.isFulfilled = true;
  14270. }
  14271. else if (this.isRejected()) {
  14272. ret.rejectionReason = this._settledValue;
  14273. ret.isRejected = true;
  14274. }
  14275. return ret;
  14276. };
  14277. Promise.prototype.all = function Promise$all() {
  14278. return Promise$_all(this, true);
  14279. };
  14280. Promise.is = isPromise;
  14281. function Promise$_all(promises, useBound) {
  14282. return Promise$_CreatePromiseArray(
  14283. promises,
  14284. PromiseArray,
  14285. useBound === true && promises._isBound()
  14286. ? promises._boundTo
  14287. : void 0
  14288. ).promise();
  14289. }
  14290. Promise.all = function Promise$All(promises) {
  14291. return Promise$_all(promises, false);
  14292. };
  14293. Promise.join = function Promise$Join() {
  14294. var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];}
  14295. return Promise$_CreatePromiseArray(args, PromiseArray, void 0).promise();
  14296. };
  14297. Promise.resolve = Promise.fulfilled =
  14298. function Promise$Resolve(value) {
  14299. var ret = new Promise(INTERNAL);
  14300. ret._setTrace(void 0);
  14301. if (ret._tryFollow(value)) {
  14302. return ret;
  14303. }
  14304. ret._cleanValues();
  14305. ret._setFulfilled();
  14306. ret._settledValue = value;
  14307. return ret;
  14308. };
  14309. Promise.reject = Promise.rejected = function Promise$Reject(reason) {
  14310. var ret = new Promise(INTERNAL);
  14311. ret._setTrace(void 0);
  14312. markAsOriginatingFromRejection(reason);
  14313. ret._cleanValues();
  14314. ret._setRejected();
  14315. ret._settledValue = reason;
  14316. if (!canAttach(reason)) {
  14317. var trace = new Error(reason + "");
  14318. ret._setCarriedStackTrace(trace);
  14319. }
  14320. ret._ensurePossibleRejectionHandled();
  14321. return ret;
  14322. };
  14323. Promise.prototype.error = function Promise$_error(fn) {
  14324. return this.caught(originatesFromRejection, fn);
  14325. };
  14326. Promise.prototype._resolveFromSyncValue =
  14327. function Promise$_resolveFromSyncValue(value) {
  14328. if (value === errorObj) {
  14329. this._cleanValues();
  14330. this._setRejected();
  14331. this._settledValue = value.e;
  14332. this._ensurePossibleRejectionHandled();
  14333. }
  14334. else {
  14335. var maybePromise = Promise._cast(value, void 0);
  14336. if (maybePromise instanceof Promise) {
  14337. this._follow(maybePromise);
  14338. }
  14339. else {
  14340. this._cleanValues();
  14341. this._setFulfilled();
  14342. this._settledValue = value;
  14343. }
  14344. }
  14345. };
  14346. Promise.method = function Promise$_Method(fn) {
  14347. if (typeof fn !== "function") {
  14348. throw new TypeError("fn must be a function");
  14349. }
  14350. return function Promise$_method() {
  14351. var value;
  14352. switch(arguments.length) {
  14353. case 0: value = tryCatch1(fn, this, void 0); break;
  14354. case 1: value = tryCatch1(fn, this, arguments[0]); break;
  14355. case 2: value = tryCatch2(fn, this, arguments[0], arguments[1]); break;
  14356. default:
  14357. var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];}
  14358. value = tryCatchApply(fn, args, this); break;
  14359. }
  14360. var ret = new Promise(INTERNAL);
  14361. ret._setTrace(void 0);
  14362. ret._resolveFromSyncValue(value);
  14363. return ret;
  14364. };
  14365. };
  14366. Promise.attempt = Promise["try"] = function Promise$_Try(fn, args, ctx) {
  14367. if (typeof fn !== "function") {
  14368. return apiRejection("fn must be a function");
  14369. }
  14370. var value = isArray(args)
  14371. ? tryCatchApply(fn, args, ctx)
  14372. : tryCatch1(fn, ctx, args);
  14373. var ret = new Promise(INTERNAL);
  14374. ret._setTrace(void 0);
  14375. ret._resolveFromSyncValue(value);
  14376. return ret;
  14377. };
  14378. Promise.defer = Promise.pending = function Promise$Defer() {
  14379. var promise = new Promise(INTERNAL);
  14380. promise._setTrace(void 0);
  14381. return new PromiseResolver(promise);
  14382. };
  14383. Promise.bind = function Promise$Bind(thisArg) {
  14384. var ret = new Promise(INTERNAL);
  14385. ret._setTrace(void 0);
  14386. ret._setFulfilled();
  14387. ret._setBoundTo(thisArg);
  14388. return ret;
  14389. };
  14390. Promise.cast = function Promise$_Cast(obj) {
  14391. var ret = Promise._cast(obj, void 0);
  14392. if (!(ret instanceof Promise)) {
  14393. return Promise.resolve(ret);
  14394. }
  14395. return ret;
  14396. };
  14397. Promise.onPossiblyUnhandledRejection =
  14398. function Promise$OnPossiblyUnhandledRejection(fn) {
  14399. CapturedTrace.possiblyUnhandledRejection = typeof fn === "function"
  14400. ? fn : void 0;
  14401. };
  14402. var unhandledRejectionHandled;
  14403. Promise.onUnhandledRejectionHandled =
  14404. function Promise$onUnhandledRejectionHandled(fn) {
  14405. unhandledRejectionHandled = typeof fn === "function" ? fn : void 0;
  14406. };
  14407. var debugging = false || !!(
  14408. typeof process !== "undefined" &&
  14409. typeof process.execPath === "string" &&
  14410. typeof process.env === "object" &&
  14411. (process.env["BLUEBIRD_DEBUG"] ||
  14412. process.env["NODE_ENV"] === "development")
  14413. );
  14414. Promise.longStackTraces = function Promise$LongStackTraces() {
  14415. if (async.haveItemsQueued() &&
  14416. debugging === false
  14417. ) {
  14418. throw new Error("cannot enable long stack traces after promises have been created");
  14419. }
  14420. debugging = CapturedTrace.isSupported();
  14421. };
  14422. Promise.hasLongStackTraces = function Promise$HasLongStackTraces() {
  14423. return debugging && CapturedTrace.isSupported();
  14424. };
  14425. Promise.prototype._setProxyHandlers =
  14426. function Promise$_setProxyHandlers(receiver, promiseSlotValue) {
  14427. var index = this._length();
  14428. if (index >= 524287 - 5) {
  14429. index = 0;
  14430. this._setLength(0);
  14431. }
  14432. if (index === 0) {
  14433. this._promise0 = promiseSlotValue;
  14434. this._receiver0 = receiver;
  14435. }
  14436. else {
  14437. var i = index - 5;
  14438. this[i + 3] = promiseSlotValue;
  14439. this[i + 4] = receiver;
  14440. this[i + 0] =
  14441. this[i + 1] =
  14442. this[i + 2] = void 0;
  14443. }
  14444. this._setLength(index + 5);
  14445. };
  14446. Promise.prototype._proxyPromiseArray =
  14447. function Promise$_proxyPromiseArray(promiseArray, index) {
  14448. this._setProxyHandlers(promiseArray, index);
  14449. };
  14450. Promise.prototype._proxyPromise = function Promise$_proxyPromise(promise) {
  14451. promise._setProxied();
  14452. this._setProxyHandlers(promise, -1);
  14453. };
  14454. Promise.prototype._then =
  14455. function Promise$_then(
  14456. didFulfill,
  14457. didReject,
  14458. didProgress,
  14459. receiver,
  14460. internalData
  14461. ) {
  14462. var haveInternalData = internalData !== void 0;
  14463. var ret = haveInternalData ? internalData : new Promise(INTERNAL);
  14464. if (debugging && !haveInternalData) {
  14465. var haveSameContext = this._peekContext() === this._traceParent;
  14466. ret._traceParent = haveSameContext ? this._traceParent : this;
  14467. ret._setTrace(this);
  14468. }
  14469. if (!haveInternalData && this._isBound()) {
  14470. ret._setBoundTo(this._boundTo);
  14471. }
  14472. var callbackIndex =
  14473. this._addCallbacks(didFulfill, didReject, didProgress, ret, receiver);
  14474. if (!haveInternalData && this._cancellable()) {
  14475. ret._setCancellable();
  14476. ret._cancellationParent = this;
  14477. }
  14478. if (this.isResolved()) {
  14479. async.invoke(this._queueSettleAt, this, callbackIndex);
  14480. }
  14481. return ret;
  14482. };
  14483. Promise.prototype._length = function Promise$_length() {
  14484. return this._bitField & 524287;
  14485. };
  14486. Promise.prototype._isFollowingOrFulfilledOrRejected =
  14487. function Promise$_isFollowingOrFulfilledOrRejected() {
  14488. return (this._bitField & 939524096) > 0;
  14489. };
  14490. Promise.prototype._isFollowing = function Promise$_isFollowing() {
  14491. return (this._bitField & 536870912) === 536870912;
  14492. };
  14493. Promise.prototype._setLength = function Promise$_setLength(len) {
  14494. this._bitField = (this._bitField & -524288) |
  14495. (len & 524287);
  14496. };
  14497. Promise.prototype._setFulfilled = function Promise$_setFulfilled() {
  14498. this._bitField = this._bitField | 268435456;
  14499. };
  14500. Promise.prototype._setRejected = function Promise$_setRejected() {
  14501. this._bitField = this._bitField | 134217728;
  14502. };
  14503. Promise.prototype._setFollowing = function Promise$_setFollowing() {
  14504. this._bitField = this._bitField | 536870912;
  14505. };
  14506. Promise.prototype._setIsFinal = function Promise$_setIsFinal() {
  14507. this._bitField = this._bitField | 33554432;
  14508. };
  14509. Promise.prototype._isFinal = function Promise$_isFinal() {
  14510. return (this._bitField & 33554432) > 0;
  14511. };
  14512. Promise.prototype._cancellable = function Promise$_cancellable() {
  14513. return (this._bitField & 67108864) > 0;
  14514. };
  14515. Promise.prototype._setCancellable = function Promise$_setCancellable() {
  14516. this._bitField = this._bitField | 67108864;
  14517. };
  14518. Promise.prototype._unsetCancellable = function Promise$_unsetCancellable() {
  14519. this._bitField = this._bitField & (~67108864);
  14520. };
  14521. Promise.prototype._setRejectionIsUnhandled =
  14522. function Promise$_setRejectionIsUnhandled() {
  14523. this._bitField = this._bitField | 2097152;
  14524. };
  14525. Promise.prototype._unsetRejectionIsUnhandled =
  14526. function Promise$_unsetRejectionIsUnhandled() {
  14527. this._bitField = this._bitField & (~2097152);
  14528. if (this._isUnhandledRejectionNotified()) {
  14529. this._unsetUnhandledRejectionIsNotified();
  14530. this._notifyUnhandledRejectionIsHandled();
  14531. }
  14532. };
  14533. Promise.prototype._isRejectionUnhandled =
  14534. function Promise$_isRejectionUnhandled() {
  14535. return (this._bitField & 2097152) > 0;
  14536. };
  14537. Promise.prototype._setUnhandledRejectionIsNotified =
  14538. function Promise$_setUnhandledRejectionIsNotified() {
  14539. this._bitField = this._bitField | 524288;
  14540. };
  14541. Promise.prototype._unsetUnhandledRejectionIsNotified =
  14542. function Promise$_unsetUnhandledRejectionIsNotified() {
  14543. this._bitField = this._bitField & (~524288);
  14544. };
  14545. Promise.prototype._isUnhandledRejectionNotified =
  14546. function Promise$_isUnhandledRejectionNotified() {
  14547. return (this._bitField & 524288) > 0;
  14548. };
  14549. Promise.prototype._setCarriedStackTrace =
  14550. function Promise$_setCarriedStackTrace(capturedTrace) {
  14551. this._bitField = this._bitField | 1048576;
  14552. this._fulfillmentHandler0 = capturedTrace;
  14553. };
  14554. Promise.prototype._unsetCarriedStackTrace =
  14555. function Promise$_unsetCarriedStackTrace() {
  14556. this._bitField = this._bitField & (~1048576);
  14557. this._fulfillmentHandler0 = void 0;
  14558. };
  14559. Promise.prototype._isCarryingStackTrace =
  14560. function Promise$_isCarryingStackTrace() {
  14561. return (this._bitField & 1048576) > 0;
  14562. };
  14563. Promise.prototype._getCarriedStackTrace =
  14564. function Promise$_getCarriedStackTrace() {
  14565. return this._isCarryingStackTrace()
  14566. ? this._fulfillmentHandler0
  14567. : void 0;
  14568. };
  14569. Promise.prototype._receiverAt = function Promise$_receiverAt(index) {
  14570. var ret;
  14571. if (index === 0) {
  14572. ret = this._receiver0;
  14573. }
  14574. else {
  14575. ret = this[index + 4 - 5];
  14576. }
  14577. if (this._isBound() && ret === void 0) {
  14578. return this._boundTo;
  14579. }
  14580. return ret;
  14581. };
  14582. Promise.prototype._promiseAt = function Promise$_promiseAt(index) {
  14583. if (index === 0) return this._promise0;
  14584. return this[index + 3 - 5];
  14585. };
  14586. Promise.prototype._fulfillmentHandlerAt =
  14587. function Promise$_fulfillmentHandlerAt(index) {
  14588. if (index === 0) return this._fulfillmentHandler0;
  14589. return this[index + 0 - 5];
  14590. };
  14591. Promise.prototype._rejectionHandlerAt =
  14592. function Promise$_rejectionHandlerAt(index) {
  14593. if (index === 0) return this._rejectionHandler0;
  14594. return this[index + 1 - 5];
  14595. };
  14596. Promise.prototype._unsetAt = function Promise$_unsetAt(index) {
  14597. if (index === 0) {
  14598. this._rejectionHandler0 =
  14599. this._progressHandler0 =
  14600. this._promise0 =
  14601. this._receiver0 = void 0;
  14602. if (!this._isCarryingStackTrace()) {
  14603. this._fulfillmentHandler0 = void 0;
  14604. }
  14605. }
  14606. else {
  14607. this[index - 5 + 0] =
  14608. this[index - 5 + 1] =
  14609. this[index - 5 + 2] =
  14610. this[index - 5 + 3] =
  14611. this[index - 5 + 4] = void 0;
  14612. }
  14613. };
  14614. Promise.prototype._resolveFromResolver =
  14615. function Promise$_resolveFromResolver(resolver) {
  14616. var promise = this;
  14617. this._setTrace(void 0);
  14618. this._pushContext();
  14619. function Promise$_resolver(val) {
  14620. if (promise._tryFollow(val)) {
  14621. return;
  14622. }
  14623. promise._fulfill(val);
  14624. }
  14625. function Promise$_rejecter(val) {
  14626. var trace = canAttach(val) ? val : new Error(val + "");
  14627. promise._attachExtraTrace(trace);
  14628. markAsOriginatingFromRejection(val);
  14629. promise._reject(val, trace === val ? void 0 : trace);
  14630. }
  14631. var r = tryCatch2(resolver, void 0, Promise$_resolver, Promise$_rejecter);
  14632. this._popContext();
  14633. if (r !== void 0 && r === errorObj) {
  14634. var e = r.e;
  14635. var trace = canAttach(e) ? e : new Error(e + "");
  14636. promise._reject(e, trace);
  14637. }
  14638. };
  14639. Promise.prototype._addCallbacks = function Promise$_addCallbacks(
  14640. fulfill,
  14641. reject,
  14642. progress,
  14643. promise,
  14644. receiver
  14645. ) {
  14646. var index = this._length();
  14647. if (index >= 524287 - 5) {
  14648. index = 0;
  14649. this._setLength(0);
  14650. }
  14651. if (index === 0) {
  14652. this._promise0 = promise;
  14653. if (receiver !== void 0) this._receiver0 = receiver;
  14654. if (typeof fulfill === "function" && !this._isCarryingStackTrace())
  14655. this._fulfillmentHandler0 = fulfill;
  14656. if (typeof reject === "function") this._rejectionHandler0 = reject;
  14657. if (typeof progress === "function") this._progressHandler0 = progress;
  14658. }
  14659. else {
  14660. var i = index - 5;
  14661. this[i + 3] = promise;
  14662. this[i + 4] = receiver;
  14663. this[i + 0] = typeof fulfill === "function"
  14664. ? fulfill : void 0;
  14665. this[i + 1] = typeof reject === "function"
  14666. ? reject : void 0;
  14667. this[i + 2] = typeof progress === "function"
  14668. ? progress : void 0;
  14669. }
  14670. this._setLength(index + 5);
  14671. return index;
  14672. };
  14673. Promise.prototype._setBoundTo = function Promise$_setBoundTo(obj) {
  14674. if (obj !== void 0) {
  14675. this._bitField = this._bitField | 8388608;
  14676. this._boundTo = obj;
  14677. }
  14678. else {
  14679. this._bitField = this._bitField & (~8388608);
  14680. }
  14681. };
  14682. Promise.prototype._isBound = function Promise$_isBound() {
  14683. return (this._bitField & 8388608) === 8388608;
  14684. };
  14685. Promise.prototype._spreadSlowCase =
  14686. function Promise$_spreadSlowCase(targetFn, promise, values, boundTo) {
  14687. var promiseForAll =
  14688. Promise$_CreatePromiseArray
  14689. (values, PromiseArray, boundTo)
  14690. .promise()
  14691. ._then(function() {
  14692. return targetFn.apply(boundTo, arguments);
  14693. }, void 0, void 0, APPLY, void 0);
  14694. promise._follow(promiseForAll);
  14695. };
  14696. Promise.prototype._callSpread =
  14697. function Promise$_callSpread(handler, promise, value, localDebugging) {
  14698. var boundTo = this._isBound() ? this._boundTo : void 0;
  14699. if (isArray(value)) {
  14700. for (var i = 0, len = value.length; i < len; ++i) {
  14701. if (isPromise(Promise._cast(value[i], void 0))) {
  14702. this._spreadSlowCase(handler, promise, value, boundTo);
  14703. return;
  14704. }
  14705. }
  14706. }
  14707. if (localDebugging) promise._pushContext();
  14708. return tryCatchApply(handler, value, boundTo);
  14709. };
  14710. Promise.prototype._callHandler =
  14711. function Promise$_callHandler(
  14712. handler, receiver, promise, value, localDebugging) {
  14713. var x;
  14714. if (receiver === APPLY && !this.isRejected()) {
  14715. x = this._callSpread(handler, promise, value, localDebugging);
  14716. }
  14717. else {
  14718. if (localDebugging) promise._pushContext();
  14719. x = tryCatch1(handler, receiver, value);
  14720. }
  14721. if (localDebugging) promise._popContext();
  14722. return x;
  14723. };
  14724. Promise.prototype._settlePromiseFromHandler =
  14725. function Promise$_settlePromiseFromHandler(
  14726. handler, receiver, value, promise
  14727. ) {
  14728. if (!isPromise(promise)) {
  14729. handler.call(receiver, value, promise);
  14730. return;
  14731. }
  14732. var localDebugging = debugging;
  14733. var x = this._callHandler(handler, receiver,
  14734. promise, value, localDebugging);
  14735. if (promise._isFollowing()) return;
  14736. if (x === errorObj || x === promise || x === NEXT_FILTER) {
  14737. var err = x === promise
  14738. ? makeSelfResolutionError()
  14739. : x.e;
  14740. var trace = canAttach(err) ? err : new Error(err + "");
  14741. if (x !== NEXT_FILTER) promise._attachExtraTrace(trace);
  14742. promise._rejectUnchecked(err, trace);
  14743. }
  14744. else {
  14745. var castValue = Promise._cast(x, promise);
  14746. if (isPromise(castValue)) {
  14747. if (castValue.isRejected() &&
  14748. !castValue._isCarryingStackTrace() &&
  14749. !canAttach(castValue._settledValue)) {
  14750. var trace = new Error(castValue._settledValue + "");
  14751. promise._attachExtraTrace(trace);
  14752. castValue._setCarriedStackTrace(trace);
  14753. }
  14754. promise._follow(castValue);
  14755. if (castValue._cancellable()) {
  14756. promise._cancellationParent = castValue;
  14757. promise._setCancellable();
  14758. }
  14759. }
  14760. else {
  14761. promise._fulfillUnchecked(x);
  14762. }
  14763. }
  14764. };
  14765. Promise.prototype._follow =
  14766. function Promise$_follow(promise) {
  14767. this._setFollowing();
  14768. if (promise.isPending()) {
  14769. if (promise._cancellable() ) {
  14770. this._cancellationParent = promise;
  14771. this._setCancellable();
  14772. }
  14773. promise._proxyPromise(this);
  14774. }
  14775. else if (promise.isFulfilled()) {
  14776. this._fulfillUnchecked(promise._settledValue);
  14777. }
  14778. else {
  14779. this._rejectUnchecked(promise._settledValue,
  14780. promise._getCarriedStackTrace());
  14781. }
  14782. if (promise._isRejectionUnhandled()) promise._unsetRejectionIsUnhandled();
  14783. if (debugging &&
  14784. promise._traceParent == null) {
  14785. promise._traceParent = this;
  14786. }
  14787. };
  14788. Promise.prototype._tryFollow =
  14789. function Promise$_tryFollow(value) {
  14790. if (this._isFollowingOrFulfilledOrRejected() ||
  14791. value === this) {
  14792. return false;
  14793. }
  14794. var maybePromise = Promise._cast(value, void 0);
  14795. if (!isPromise(maybePromise)) {
  14796. return false;
  14797. }
  14798. this._follow(maybePromise);
  14799. return true;
  14800. };
  14801. Promise.prototype._resetTrace = function Promise$_resetTrace() {
  14802. if (debugging) {
  14803. this._trace = new CapturedTrace(this._peekContext() === void 0);
  14804. }
  14805. };
  14806. Promise.prototype._setTrace = function Promise$_setTrace(parent) {
  14807. if (debugging) {
  14808. var context = this._peekContext();
  14809. this._traceParent = context;
  14810. var isTopLevel = context === void 0;
  14811. if (parent !== void 0 &&
  14812. parent._traceParent === context) {
  14813. this._trace = parent._trace;
  14814. }
  14815. else {
  14816. this._trace = new CapturedTrace(isTopLevel);
  14817. }
  14818. }
  14819. return this;
  14820. };
  14821. Promise.prototype._attachExtraTrace =
  14822. function Promise$_attachExtraTrace(error) {
  14823. if (debugging) {
  14824. var promise = this;
  14825. var stack = error.stack;
  14826. stack = typeof stack === "string"
  14827. ? stack.split("\n") : [];
  14828. var headerLineCount = 1;
  14829. while(promise != null &&
  14830. promise._trace != null) {
  14831. stack = CapturedTrace.combine(
  14832. stack,
  14833. promise._trace.stack.split("\n")
  14834. );
  14835. promise = promise._traceParent;
  14836. }
  14837. var max = Error.stackTraceLimit + headerLineCount;
  14838. var len = stack.length;
  14839. if (len > max) {
  14840. stack.length = max;
  14841. }
  14842. if (stack.length <= headerLineCount) {
  14843. error.stack = "(No stack trace)";
  14844. }
  14845. else {
  14846. error.stack = stack.join("\n");
  14847. }
  14848. }
  14849. };
  14850. Promise.prototype._cleanValues = function Promise$_cleanValues() {
  14851. if (this._cancellable()) {
  14852. this._cancellationParent = void 0;
  14853. }
  14854. };
  14855. Promise.prototype._fulfill = function Promise$_fulfill(value) {
  14856. if (this._isFollowingOrFulfilledOrRejected()) return;
  14857. this._fulfillUnchecked(value);
  14858. };
  14859. Promise.prototype._reject =
  14860. function Promise$_reject(reason, carriedStackTrace) {
  14861. if (this._isFollowingOrFulfilledOrRejected()) return;
  14862. this._rejectUnchecked(reason, carriedStackTrace);
  14863. };
  14864. Promise.prototype._settlePromiseAt = function Promise$_settlePromiseAt(index) {
  14865. var handler = this.isFulfilled()
  14866. ? this._fulfillmentHandlerAt(index)
  14867. : this._rejectionHandlerAt(index);
  14868. var value = this._settledValue;
  14869. var receiver = this._receiverAt(index);
  14870. var promise = this._promiseAt(index);
  14871. if (typeof handler === "function") {
  14872. this._settlePromiseFromHandler(handler, receiver, value, promise);
  14873. }
  14874. else {
  14875. var done = false;
  14876. var isFulfilled = this.isFulfilled();
  14877. if (receiver !== void 0) {
  14878. if (receiver instanceof Promise &&
  14879. receiver._isProxied()) {
  14880. receiver._unsetProxied();
  14881. if (isFulfilled) receiver._fulfillUnchecked(value);
  14882. else receiver._rejectUnchecked(value,
  14883. this._getCarriedStackTrace());
  14884. done = true;
  14885. }
  14886. else if (isPromiseArrayProxy(receiver, promise)) {
  14887. if (isFulfilled) receiver._promiseFulfilled(value, promise);
  14888. else receiver._promiseRejected(value, promise);
  14889. done = true;
  14890. }
  14891. }
  14892. if (!done) {
  14893. if (isFulfilled) promise._fulfill(value);
  14894. else promise._reject(value, this._getCarriedStackTrace());
  14895. }
  14896. }
  14897. if (index >= 256) {
  14898. this._queueGC();
  14899. }
  14900. };
  14901. Promise.prototype._isProxied = function Promise$_isProxied() {
  14902. return (this._bitField & 4194304) === 4194304;
  14903. };
  14904. Promise.prototype._setProxied = function Promise$_setProxied() {
  14905. this._bitField = this._bitField | 4194304;
  14906. };
  14907. Promise.prototype._unsetProxied = function Promise$_unsetProxied() {
  14908. this._bitField = this._bitField & (~4194304);
  14909. };
  14910. Promise.prototype._isGcQueued = function Promise$_isGcQueued() {
  14911. return (this._bitField & -1073741824) === -1073741824;
  14912. };
  14913. Promise.prototype._setGcQueued = function Promise$_setGcQueued() {
  14914. this._bitField = this._bitField | -1073741824;
  14915. };
  14916. Promise.prototype._unsetGcQueued = function Promise$_unsetGcQueued() {
  14917. this._bitField = this._bitField & (~-1073741824);
  14918. };
  14919. Promise.prototype._queueGC = function Promise$_queueGC() {
  14920. if (this._isGcQueued()) return;
  14921. this._setGcQueued();
  14922. async.invokeLater(this._gc, this, void 0);
  14923. };
  14924. Promise.prototype._gc = function Promise$gc() {
  14925. var len = this._length();
  14926. this._unsetAt(0);
  14927. for (var i = 0; i < len; i++) {
  14928. delete this[i];
  14929. }
  14930. this._setLength(0);
  14931. this._unsetGcQueued();
  14932. };
  14933. Promise.prototype._queueSettleAt = function Promise$_queueSettleAt(index) {
  14934. if (this._isRejectionUnhandled()) this._unsetRejectionIsUnhandled();
  14935. async.invoke(this._settlePromiseAt, this, index);
  14936. };
  14937. Promise.prototype._fulfillUnchecked =
  14938. function Promise$_fulfillUnchecked(value) {
  14939. if (!this.isPending()) return;
  14940. if (value === this) {
  14941. var err = makeSelfResolutionError();
  14942. this._attachExtraTrace(err);
  14943. return this._rejectUnchecked(err, void 0);
  14944. }
  14945. this._cleanValues();
  14946. this._setFulfilled();
  14947. this._settledValue = value;
  14948. var len = this._length();
  14949. if (len > 0) {
  14950. async.invoke(this._settlePromises, this, len);
  14951. }
  14952. };
  14953. Promise.prototype._rejectUncheckedCheckError =
  14954. function Promise$_rejectUncheckedCheckError(reason) {
  14955. var trace = canAttach(reason) ? reason : new Error(reason + "");
  14956. this._rejectUnchecked(reason, trace === reason ? void 0 : trace);
  14957. };
  14958. Promise.prototype._rejectUnchecked =
  14959. function Promise$_rejectUnchecked(reason, trace) {
  14960. if (!this.isPending()) return;
  14961. if (reason === this) {
  14962. var err = makeSelfResolutionError();
  14963. this._attachExtraTrace(err);
  14964. return this._rejectUnchecked(err);
  14965. }
  14966. this._cleanValues();
  14967. this._setRejected();
  14968. this._settledValue = reason;
  14969. if (this._isFinal()) {
  14970. async.invokeLater(thrower, void 0, trace === void 0 ? reason : trace);
  14971. return;
  14972. }
  14973. var len = this._length();
  14974. if (trace !== void 0) this._setCarriedStackTrace(trace);
  14975. if (len > 0) {
  14976. async.invoke(this._rejectPromises, this, null);
  14977. }
  14978. else {
  14979. this._ensurePossibleRejectionHandled();
  14980. }
  14981. };
  14982. Promise.prototype._rejectPromises = function Promise$_rejectPromises() {
  14983. this._settlePromises();
  14984. this._unsetCarriedStackTrace();
  14985. };
  14986. Promise.prototype._settlePromises = function Promise$_settlePromises() {
  14987. var len = this._length();
  14988. for (var i = 0; i < len; i+= 5) {
  14989. this._settlePromiseAt(i);
  14990. }
  14991. };
  14992. Promise.prototype._ensurePossibleRejectionHandled =
  14993. function Promise$_ensurePossibleRejectionHandled() {
  14994. this._setRejectionIsUnhandled();
  14995. if (CapturedTrace.possiblyUnhandledRejection !== void 0) {
  14996. async.invokeLater(this._notifyUnhandledRejection, this, void 0);
  14997. }
  14998. };
  14999. Promise.prototype._notifyUnhandledRejectionIsHandled =
  15000. function Promise$_notifyUnhandledRejectionIsHandled() {
  15001. if (typeof unhandledRejectionHandled === "function") {
  15002. async.invokeLater(unhandledRejectionHandled, void 0, this);
  15003. }
  15004. };
  15005. Promise.prototype._notifyUnhandledRejection =
  15006. function Promise$_notifyUnhandledRejection() {
  15007. if (this._isRejectionUnhandled()) {
  15008. var reason = this._settledValue;
  15009. var trace = this._getCarriedStackTrace();
  15010. this._setUnhandledRejectionIsNotified();
  15011. if (trace !== void 0) {
  15012. this._unsetCarriedStackTrace();
  15013. reason = trace;
  15014. }
  15015. if (typeof CapturedTrace.possiblyUnhandledRejection === "function") {
  15016. CapturedTrace.possiblyUnhandledRejection(reason, this);
  15017. }
  15018. }
  15019. };
  15020. var contextStack = [];
  15021. Promise.prototype._peekContext = function Promise$_peekContext() {
  15022. var lastIndex = contextStack.length - 1;
  15023. if (lastIndex >= 0) {
  15024. return contextStack[lastIndex];
  15025. }
  15026. return void 0;
  15027. };
  15028. Promise.prototype._pushContext = function Promise$_pushContext() {
  15029. if (!debugging) return;
  15030. contextStack.push(this);
  15031. };
  15032. Promise.prototype._popContext = function Promise$_popContext() {
  15033. if (!debugging) return;
  15034. contextStack.pop();
  15035. };
  15036. function Promise$_CreatePromiseArray(
  15037. promises, PromiseArrayConstructor, boundTo) {
  15038. var list = null;
  15039. if (isArray(promises)) {
  15040. list = promises;
  15041. }
  15042. else {
  15043. list = Promise._cast(promises, void 0);
  15044. if (list !== promises) {
  15045. list._setBoundTo(boundTo);
  15046. }
  15047. else if (!isPromise(list)) {
  15048. list = null;
  15049. }
  15050. }
  15051. if (list !== null) {
  15052. return new PromiseArrayConstructor(list, boundTo);
  15053. }
  15054. return {
  15055. promise: function() {return apiRejection("expecting an array, a promise or a thenable");}
  15056. };
  15057. }
  15058. var old = global.Promise;
  15059. Promise.noConflict = function() {
  15060. if (global.Promise === Promise) {
  15061. global.Promise = old;
  15062. }
  15063. return Promise;
  15064. };
  15065. if (!CapturedTrace.isSupported()) {
  15066. Promise.longStackTraces = function(){};
  15067. debugging = false;
  15068. }
  15069. Promise._makeSelfResolutionError = makeSelfResolutionError;
  15070. __webpack_require__(116)(Promise, NEXT_FILTER);
  15071. __webpack_require__(117)(Promise);
  15072. __webpack_require__(118)(Promise, INTERNAL);
  15073. __webpack_require__(119)(Promise);
  15074. Promise.RangeError = RangeError;
  15075. Promise.CancellationError = CancellationError;
  15076. Promise.TimeoutError = TimeoutError;
  15077. Promise.TypeError = TypeError;
  15078. Promise.RejectionError = RejectionError;
  15079. util.toFastProperties(Promise);
  15080. util.toFastProperties(Promise.prototype);
  15081. __webpack_require__(120)(Promise,INTERNAL);
  15082. __webpack_require__(121)(Promise,Promise$_CreatePromiseArray,PromiseArray);
  15083. __webpack_require__(122)(Promise,INTERNAL);
  15084. __webpack_require__(123)(Promise);
  15085. __webpack_require__(124)(Promise,Promise$_CreatePromiseArray,PromiseArray,apiRejection);
  15086. __webpack_require__(125)(Promise,apiRejection,INTERNAL);
  15087. __webpack_require__(126)(Promise,PromiseArray,INTERNAL,apiRejection);
  15088. __webpack_require__(127)(Promise);
  15089. __webpack_require__(128)(Promise,INTERNAL);
  15090. __webpack_require__(129)(Promise,PromiseArray);
  15091. __webpack_require__(130)(Promise,Promise$_CreatePromiseArray,PromiseArray,apiRejection,INTERNAL);
  15092. __webpack_require__(131)(Promise,Promise$_CreatePromiseArray,PromiseArray);
  15093. __webpack_require__(132)(Promise,Promise$_CreatePromiseArray,PromiseArray,apiRejection);
  15094. __webpack_require__(133)(Promise,isPromiseArrayProxy);
  15095. __webpack_require__(134)(Promise,INTERNAL);
  15096. Promise.prototype = Promise.prototype;
  15097. return Promise;
  15098. };
  15099. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(99)))
  15100. /***/ },
  15101. /* 92 */
  15102. /***/ function(module, exports, __webpack_require__) {
  15103. var exports = module.exports = function (alg) {
  15104. var Alg = exports[alg]
  15105. if(!Alg) throw new Error(alg + ' is not supported (we accept pull requests)')
  15106. return new Alg()
  15107. }
  15108. var Buffer = __webpack_require__(47).Buffer
  15109. var Hash = __webpack_require__(135)(Buffer)
  15110. exports.sha1 = __webpack_require__(136)(Buffer, Hash)
  15111. exports.sha256 = __webpack_require__(137)(Buffer, Hash)
  15112. exports.sha512 = __webpack_require__(138)(Buffer, Hash)
  15113. /***/ },
  15114. /* 93 */
  15115. /***/ function(module, exports, __webpack_require__) {
  15116. exports = module.exports = __webpack_require__(143);
  15117. exports.Stream = __webpack_require__(64);
  15118. exports.Readable = exports;
  15119. exports.Writable = __webpack_require__(141);
  15120. exports.Duplex = __webpack_require__(142);
  15121. exports.Transform = __webpack_require__(144);
  15122. exports.PassThrough = __webpack_require__(145);
  15123. /***/ },
  15124. /* 94 */
  15125. /***/ function(module, exports, __webpack_require__) {
  15126. module.exports = __webpack_require__(141)
  15127. /***/ },
  15128. /* 95 */
  15129. /***/ function(module, exports, __webpack_require__) {
  15130. module.exports = __webpack_require__(142)
  15131. /***/ },
  15132. /* 96 */
  15133. /***/ function(module, exports, __webpack_require__) {
  15134. module.exports = __webpack_require__(144)
  15135. /***/ },
  15136. /* 97 */
  15137. /***/ function(module, exports, __webpack_require__) {
  15138. module.exports = __webpack_require__(145)
  15139. /***/ },
  15140. /* 98 */
  15141. /***/ function(module, exports, __webpack_require__) {
  15142. /* WEBPACK VAR INJECTION */(function(Buffer) {var intSize = 4;
  15143. var zeroBuffer = new Buffer(intSize); zeroBuffer.fill(0);
  15144. var chrsz = 8;
  15145. function toArray(buf, bigEndian) {
  15146. if ((buf.length % intSize) !== 0) {
  15147. var len = buf.length + (intSize - (buf.length % intSize));
  15148. buf = Buffer.concat([buf, zeroBuffer], len);
  15149. }
  15150. var arr = [];
  15151. var fn = bigEndian ? buf.readInt32BE : buf.readInt32LE;
  15152. for (var i = 0; i < buf.length; i += intSize) {
  15153. arr.push(fn.call(buf, i));
  15154. }
  15155. return arr;
  15156. }
  15157. function toBuffer(arr, size, bigEndian) {
  15158. var buf = new Buffer(size);
  15159. var fn = bigEndian ? buf.writeInt32BE : buf.writeInt32LE;
  15160. for (var i = 0; i < arr.length; i++) {
  15161. fn.call(buf, arr[i], i * 4, true);
  15162. }
  15163. return buf;
  15164. }
  15165. function hash(buf, fn, hashSize, bigEndian) {
  15166. if (!Buffer.isBuffer(buf)) buf = new Buffer(buf);
  15167. var arr = fn(toArray(buf, bigEndian), buf.length * chrsz);
  15168. return toBuffer(arr, hashSize, bigEndian);
  15169. }
  15170. module.exports = { hash: hash };
  15171. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(47).Buffer))
  15172. /***/ },
  15173. /* 99 */
  15174. /***/ function(module, exports, __webpack_require__) {
  15175. // shim for using process in browser
  15176. var process = module.exports = {};
  15177. process.nextTick = (function () {
  15178. var canSetImmediate = typeof window !== 'undefined'
  15179. && window.setImmediate;
  15180. var canMutationObserver = typeof window !== 'undefined'
  15181. && window.MutationObserver;
  15182. var canPost = typeof window !== 'undefined'
  15183. && window.postMessage && window.addEventListener
  15184. ;
  15185. if (canSetImmediate) {
  15186. return function (f) { return window.setImmediate(f) };
  15187. }
  15188. var queue = [];
  15189. if (canMutationObserver) {
  15190. var hiddenDiv = document.createElement("div");
  15191. var observer = new MutationObserver(function () {
  15192. var queueList = queue.slice();
  15193. queue.length = 0;
  15194. queueList.forEach(function (fn) {
  15195. fn();
  15196. });
  15197. });
  15198. observer.observe(hiddenDiv, { attributes: true });
  15199. return function nextTick(fn) {
  15200. if (!queue.length) {
  15201. hiddenDiv.setAttribute('yes', 'no');
  15202. }
  15203. queue.push(fn);
  15204. };
  15205. }
  15206. if (canPost) {
  15207. window.addEventListener('message', function (ev) {
  15208. var source = ev.source;
  15209. if ((source === window || source === null) && ev.data === 'process-tick') {
  15210. ev.stopPropagation();
  15211. if (queue.length > 0) {
  15212. var fn = queue.shift();
  15213. fn();
  15214. }
  15215. }
  15216. }, true);
  15217. return function nextTick(fn) {
  15218. queue.push(fn);
  15219. window.postMessage('process-tick', '*');
  15220. };
  15221. }
  15222. return function nextTick(fn) {
  15223. setTimeout(fn, 0);
  15224. };
  15225. })();
  15226. process.title = 'browser';
  15227. process.browser = true;
  15228. process.env = {};
  15229. process.argv = [];
  15230. function noop() {}
  15231. process.on = noop;
  15232. process.addListener = noop;
  15233. process.once = noop;
  15234. process.off = noop;
  15235. process.removeListener = noop;
  15236. process.removeAllListeners = noop;
  15237. process.emit = noop;
  15238. process.binding = function (name) {
  15239. throw new Error('process.binding is not supported');
  15240. };
  15241. // TODO(shtylman)
  15242. process.cwd = function () { return '/' };
  15243. process.chdir = function (dir) {
  15244. throw new Error('process.chdir is not supported');
  15245. };
  15246. /***/ },
  15247. /* 100 */
  15248. /***/ function(module, exports, __webpack_require__) {
  15249. /* WEBPACK VAR INJECTION */(function(Buffer) {module.exports = function(crypto) {
  15250. function pbkdf2(password, salt, iterations, keylen, digest, callback) {
  15251. if ('function' === typeof digest) {
  15252. callback = digest
  15253. digest = undefined
  15254. }
  15255. if ('function' !== typeof callback)
  15256. throw new Error('No callback provided to pbkdf2')
  15257. setTimeout(function() {
  15258. var result
  15259. try {
  15260. result = pbkdf2Sync(password, salt, iterations, keylen, digest)
  15261. } catch (e) {
  15262. return callback(e)
  15263. }
  15264. callback(undefined, result)
  15265. })
  15266. }
  15267. function pbkdf2Sync(password, salt, iterations, keylen, digest) {
  15268. if ('number' !== typeof iterations)
  15269. throw new TypeError('Iterations not a number')
  15270. if (iterations < 0)
  15271. throw new TypeError('Bad iterations')
  15272. if ('number' !== typeof keylen)
  15273. throw new TypeError('Key length not a number')
  15274. if (keylen < 0)
  15275. throw new TypeError('Bad key length')
  15276. digest = digest || 'sha1'
  15277. if (!Buffer.isBuffer(password)) password = new Buffer(password)
  15278. if (!Buffer.isBuffer(salt)) salt = new Buffer(salt)
  15279. var hLen, l = 1, r, T
  15280. var DK = new Buffer(keylen)
  15281. var block1 = new Buffer(salt.length + 4)
  15282. salt.copy(block1, 0, 0, salt.length)
  15283. for (var i = 1; i <= l; i++) {
  15284. block1.writeUInt32BE(i, salt.length)
  15285. var U = crypto.createHmac(digest, password).update(block1).digest()
  15286. if (!hLen) {
  15287. hLen = U.length
  15288. T = new Buffer(hLen)
  15289. l = Math.ceil(keylen / hLen)
  15290. r = keylen - (l - 1) * hLen
  15291. if (keylen > (Math.pow(2, 32) - 1) * hLen)
  15292. throw new TypeError('keylen exceeds maximum length')
  15293. }
  15294. U.copy(T, 0, 0, hLen)
  15295. for (var j = 1; j < iterations; j++) {
  15296. U = crypto.createHmac(digest, password).update(U).digest()
  15297. for (var k = 0; k < hLen; k++) {
  15298. T[k] ^= U[k]
  15299. }
  15300. }
  15301. var destPos = (i - 1) * hLen
  15302. var len = (i == l ? r : hLen)
  15303. T.copy(DK, destPos, 0, len)
  15304. }
  15305. return DK
  15306. }
  15307. return {
  15308. pbkdf2: pbkdf2,
  15309. pbkdf2Sync: pbkdf2Sync
  15310. }
  15311. }
  15312. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(47).Buffer))
  15313. /***/ },
  15314. /* 101 */
  15315. /***/ function(module, exports, __webpack_require__) {
  15316. if (typeof Object.create === 'function') {
  15317. // implementation from standard node.js 'util' module
  15318. module.exports = function inherits(ctor, superCtor) {
  15319. ctor.super_ = superCtor
  15320. ctor.prototype = Object.create(superCtor.prototype, {
  15321. constructor: {
  15322. value: ctor,
  15323. enumerable: false,
  15324. writable: true,
  15325. configurable: true
  15326. }
  15327. });
  15328. };
  15329. } else {
  15330. // old school shim for old browsers
  15331. module.exports = function inherits(ctor, superCtor) {
  15332. ctor.super_ = superCtor
  15333. var TempCtor = function () {}
  15334. TempCtor.prototype = superCtor.prototype
  15335. ctor.prototype = new TempCtor()
  15336. ctor.prototype.constructor = ctor
  15337. }
  15338. }
  15339. /***/ },
  15340. /* 102 */
  15341. /***/ function(module, exports, __webpack_require__) {
  15342. /* WEBPACK VAR INJECTION */(function(Buffer) {
  15343. module.exports = ripemd160
  15344. /*
  15345. CryptoJS v3.1.2
  15346. code.google.com/p/crypto-js
  15347. (c) 2009-2013 by Jeff Mott. All rights reserved.
  15348. code.google.com/p/crypto-js/wiki/License
  15349. */
  15350. /** @preserve
  15351. (c) 2012 by Cédric Mesnil. All rights reserved.
  15352. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
  15353. - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  15354. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  15355. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  15356. */
  15357. // Constants table
  15358. var zl = [
  15359. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
  15360. 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
  15361. 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
  15362. 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
  15363. 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13];
  15364. var zr = [
  15365. 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
  15366. 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
  15367. 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
  15368. 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
  15369. 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11];
  15370. var sl = [
  15371. 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
  15372. 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
  15373. 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
  15374. 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
  15375. 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ];
  15376. var sr = [
  15377. 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
  15378. 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
  15379. 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
  15380. 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
  15381. 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ];
  15382. var hl = [ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E];
  15383. var hr = [ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000];
  15384. var bytesToWords = function (bytes) {
  15385. var words = [];
  15386. for (var i = 0, b = 0; i < bytes.length; i++, b += 8) {
  15387. words[b >>> 5] |= bytes[i] << (24 - b % 32);
  15388. }
  15389. return words;
  15390. };
  15391. var wordsToBytes = function (words) {
  15392. var bytes = [];
  15393. for (var b = 0; b < words.length * 32; b += 8) {
  15394. bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF);
  15395. }
  15396. return bytes;
  15397. };
  15398. var processBlock = function (H, M, offset) {
  15399. // Swap endian
  15400. for (var i = 0; i < 16; i++) {
  15401. var offset_i = offset + i;
  15402. var M_offset_i = M[offset_i];
  15403. // Swap
  15404. M[offset_i] = (
  15405. (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
  15406. (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
  15407. );
  15408. }
  15409. // Working variables
  15410. var al, bl, cl, dl, el;
  15411. var ar, br, cr, dr, er;
  15412. ar = al = H[0];
  15413. br = bl = H[1];
  15414. cr = cl = H[2];
  15415. dr = dl = H[3];
  15416. er = el = H[4];
  15417. // Computation
  15418. var t;
  15419. for (var i = 0; i < 80; i += 1) {
  15420. t = (al + M[offset+zl[i]])|0;
  15421. if (i<16){
  15422. t += f1(bl,cl,dl) + hl[0];
  15423. } else if (i<32) {
  15424. t += f2(bl,cl,dl) + hl[1];
  15425. } else if (i<48) {
  15426. t += f3(bl,cl,dl) + hl[2];
  15427. } else if (i<64) {
  15428. t += f4(bl,cl,dl) + hl[3];
  15429. } else {// if (i<80) {
  15430. t += f5(bl,cl,dl) + hl[4];
  15431. }
  15432. t = t|0;
  15433. t = rotl(t,sl[i]);
  15434. t = (t+el)|0;
  15435. al = el;
  15436. el = dl;
  15437. dl = rotl(cl, 10);
  15438. cl = bl;
  15439. bl = t;
  15440. t = (ar + M[offset+zr[i]])|0;
  15441. if (i<16){
  15442. t += f5(br,cr,dr) + hr[0];
  15443. } else if (i<32) {
  15444. t += f4(br,cr,dr) + hr[1];
  15445. } else if (i<48) {
  15446. t += f3(br,cr,dr) + hr[2];
  15447. } else if (i<64) {
  15448. t += f2(br,cr,dr) + hr[3];
  15449. } else {// if (i<80) {
  15450. t += f1(br,cr,dr) + hr[4];
  15451. }
  15452. t = t|0;
  15453. t = rotl(t,sr[i]) ;
  15454. t = (t+er)|0;
  15455. ar = er;
  15456. er = dr;
  15457. dr = rotl(cr, 10);
  15458. cr = br;
  15459. br = t;
  15460. }
  15461. // Intermediate hash value
  15462. t = (H[1] + cl + dr)|0;
  15463. H[1] = (H[2] + dl + er)|0;
  15464. H[2] = (H[3] + el + ar)|0;
  15465. H[3] = (H[4] + al + br)|0;
  15466. H[4] = (H[0] + bl + cr)|0;
  15467. H[0] = t;
  15468. };
  15469. function f1(x, y, z) {
  15470. return ((x) ^ (y) ^ (z));
  15471. }
  15472. function f2(x, y, z) {
  15473. return (((x)&(y)) | ((~x)&(z)));
  15474. }
  15475. function f3(x, y, z) {
  15476. return (((x) | (~(y))) ^ (z));
  15477. }
  15478. function f4(x, y, z) {
  15479. return (((x) & (z)) | ((y)&(~(z))));
  15480. }
  15481. function f5(x, y, z) {
  15482. return ((x) ^ ((y) |(~(z))));
  15483. }
  15484. function rotl(x,n) {
  15485. return (x<<n) | (x>>>(32-n));
  15486. }
  15487. function ripemd160(message) {
  15488. var H = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0];
  15489. if (typeof message == 'string')
  15490. message = new Buffer(message, 'utf8');
  15491. var m = bytesToWords(message);
  15492. var nBitsLeft = message.length * 8;
  15493. var nBitsTotal = message.length * 8;
  15494. // Add padding
  15495. m[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
  15496. m[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
  15497. (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) |
  15498. (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00)
  15499. );
  15500. for (var i=0 ; i<m.length; i += 16) {
  15501. processBlock(H, m, i);
  15502. }
  15503. // Swap endian
  15504. for (var i = 0; i < 5; i++) {
  15505. // Shortcut
  15506. var H_i = H[i];
  15507. // Swap
  15508. H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
  15509. (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
  15510. }
  15511. var digestbytes = wordsToBytes(H);
  15512. return new Buffer(digestbytes);
  15513. }
  15514. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(47).Buffer))
  15515. /***/ },
  15516. /* 103 */
  15517. /***/ function(module, exports, __webpack_require__) {
  15518. /* WEBPACK VAR INJECTION */(function(Buffer) {var aes = __webpack_require__(147);
  15519. var Transform = __webpack_require__(148);
  15520. var inherits = __webpack_require__(173);
  15521. var modes = __webpack_require__(105);
  15522. var ebtk = __webpack_require__(149);
  15523. var StreamCipher = __webpack_require__(150);
  15524. inherits(Cipher, Transform);
  15525. function Cipher(mode, key, iv) {
  15526. if (!(this instanceof Cipher)) {
  15527. return new Cipher(mode, key, iv);
  15528. }
  15529. Transform.call(this);
  15530. this._cache = new Splitter();
  15531. this._cipher = new aes.AES(key);
  15532. this._prev = new Buffer(iv.length);
  15533. iv.copy(this._prev);
  15534. this._mode = mode;
  15535. }
  15536. Cipher.prototype._transform = function (data, _, next) {
  15537. this._cache.add(data);
  15538. var chunk;
  15539. var thing;
  15540. while ((chunk = this._cache.get())) {
  15541. thing = this._mode.encrypt(this, chunk);
  15542. this.push(thing);
  15543. }
  15544. next();
  15545. };
  15546. Cipher.prototype._flush = function (next) {
  15547. var chunk = this._cache.flush();
  15548. this.push(this._mode.encrypt(this, chunk));
  15549. this._cipher.scrub();
  15550. next();
  15551. };
  15552. function Splitter() {
  15553. if (!(this instanceof Splitter)) {
  15554. return new Splitter();
  15555. }
  15556. this.cache = new Buffer('');
  15557. }
  15558. Splitter.prototype.add = function (data) {
  15559. this.cache = Buffer.concat([this.cache, data]);
  15560. };
  15561. Splitter.prototype.get = function () {
  15562. if (this.cache.length > 15) {
  15563. var out = this.cache.slice(0, 16);
  15564. this.cache = this.cache.slice(16);
  15565. return out;
  15566. }
  15567. return null;
  15568. };
  15569. Splitter.prototype.flush = function () {
  15570. var len = 16 - this.cache.length;
  15571. var padBuff = new Buffer(len);
  15572. var i = -1;
  15573. while (++i < len) {
  15574. padBuff.writeUInt8(len, i);
  15575. }
  15576. var out = Buffer.concat([this.cache, padBuff]);
  15577. return out;
  15578. };
  15579. var modelist = {
  15580. ECB: __webpack_require__(151),
  15581. CBC: __webpack_require__(152),
  15582. CFB: __webpack_require__(153),
  15583. OFB: __webpack_require__(154),
  15584. CTR: __webpack_require__(155)
  15585. };
  15586. module.exports = function (crypto) {
  15587. function createCipheriv(suite, password, iv) {
  15588. var config = modes[suite];
  15589. if (!config) {
  15590. throw new TypeError('invalid suite type');
  15591. }
  15592. if (typeof iv === 'string') {
  15593. iv = new Buffer(iv);
  15594. }
  15595. if (typeof password === 'string') {
  15596. password = new Buffer(password);
  15597. }
  15598. if (password.length !== config.key/8) {
  15599. throw new TypeError('invalid key length ' + password.length);
  15600. }
  15601. if (iv.length !== config.iv) {
  15602. throw new TypeError('invalid iv length ' + iv.length);
  15603. }
  15604. if (config.type === 'stream') {
  15605. return new StreamCipher(modelist[config.mode], password, iv);
  15606. }
  15607. return new Cipher(modelist[config.mode], password, iv);
  15608. }
  15609. function createCipher (suite, password) {
  15610. var config = modes[suite];
  15611. if (!config) {
  15612. throw new TypeError('invalid suite type');
  15613. }
  15614. var keys = ebtk(crypto, password, config.key, config.iv);
  15615. return createCipheriv(suite, keys.key, keys.iv);
  15616. }
  15617. return {
  15618. createCipher: createCipher,
  15619. createCipheriv: createCipheriv
  15620. };
  15621. };
  15622. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(47).Buffer))
  15623. /***/ },
  15624. /* 104 */
  15625. /***/ function(module, exports, __webpack_require__) {
  15626. /* WEBPACK VAR INJECTION */(function(Buffer) {var aes = __webpack_require__(147);
  15627. var Transform = __webpack_require__(148);
  15628. var inherits = __webpack_require__(173);
  15629. var modes = __webpack_require__(105);
  15630. var StreamCipher = __webpack_require__(150);
  15631. var ebtk = __webpack_require__(149);
  15632. inherits(Decipher, Transform);
  15633. function Decipher(mode, key, iv) {
  15634. if (!(this instanceof Decipher)) {
  15635. return new Decipher(mode, key, iv);
  15636. }
  15637. Transform.call(this);
  15638. this._cache = new Splitter();
  15639. this._last = void 0;
  15640. this._cipher = new aes.AES(key);
  15641. this._prev = new Buffer(iv.length);
  15642. iv.copy(this._prev);
  15643. this._mode = mode;
  15644. }
  15645. Decipher.prototype._transform = function (data, _, next) {
  15646. this._cache.add(data);
  15647. var chunk;
  15648. var thing;
  15649. while ((chunk = this._cache.get())) {
  15650. thing = this._mode.decrypt(this, chunk);
  15651. this.push(thing);
  15652. }
  15653. next();
  15654. };
  15655. Decipher.prototype._flush = function (next) {
  15656. var chunk = this._cache.flush();
  15657. if (!chunk) {
  15658. return next;
  15659. }
  15660. this.push(unpad(this._mode.decrypt(this, chunk)));
  15661. next();
  15662. };
  15663. function Splitter() {
  15664. if (!(this instanceof Splitter)) {
  15665. return new Splitter();
  15666. }
  15667. this.cache = new Buffer('');
  15668. }
  15669. Splitter.prototype.add = function (data) {
  15670. this.cache = Buffer.concat([this.cache, data]);
  15671. };
  15672. Splitter.prototype.get = function () {
  15673. if (this.cache.length > 16) {
  15674. var out = this.cache.slice(0, 16);
  15675. this.cache = this.cache.slice(16);
  15676. return out;
  15677. }
  15678. return null;
  15679. };
  15680. Splitter.prototype.flush = function () {
  15681. if (this.cache.length) {
  15682. return this.cache;
  15683. }
  15684. };
  15685. function unpad(last) {
  15686. var padded = last[15];
  15687. if (padded === 16) {
  15688. return;
  15689. }
  15690. return last.slice(0, 16 - padded);
  15691. }
  15692. var modelist = {
  15693. ECB: __webpack_require__(151),
  15694. CBC: __webpack_require__(152),
  15695. CFB: __webpack_require__(153),
  15696. OFB: __webpack_require__(154),
  15697. CTR: __webpack_require__(155)
  15698. };
  15699. module.exports = function (crypto) {
  15700. function createDecipheriv(suite, password, iv) {
  15701. var config = modes[suite];
  15702. if (!config) {
  15703. throw new TypeError('invalid suite type');
  15704. }
  15705. if (typeof iv === 'string') {
  15706. iv = new Buffer(iv);
  15707. }
  15708. if (typeof password === 'string') {
  15709. password = new Buffer(password);
  15710. }
  15711. if (password.length !== config.key/8) {
  15712. throw new TypeError('invalid key length ' + password.length);
  15713. }
  15714. if (iv.length !== config.iv) {
  15715. throw new TypeError('invalid iv length ' + iv.length);
  15716. }
  15717. if (config.type === 'stream') {
  15718. return new StreamCipher(modelist[config.mode], password, iv, true);
  15719. }
  15720. return new Decipher(modelist[config.mode], password, iv);
  15721. }
  15722. function createDecipher (suite, password) {
  15723. var config = modes[suite];
  15724. if (!config) {
  15725. throw new TypeError('invalid suite type');
  15726. }
  15727. var keys = ebtk(crypto, password, config.key, config.iv);
  15728. return createDecipheriv(suite, keys.key, keys.iv);
  15729. }
  15730. return {
  15731. createDecipher: createDecipher,
  15732. createDecipheriv: createDecipheriv
  15733. };
  15734. };
  15735. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(47).Buffer))
  15736. /***/ },
  15737. /* 105 */
  15738. /***/ function(module, exports, __webpack_require__) {
  15739. exports['aes-128-ecb'] = {
  15740. cipher: 'AES',
  15741. key: 128,
  15742. iv: 0,
  15743. mode: 'ECB',
  15744. type: 'block'
  15745. };
  15746. exports['aes-192-ecb'] = {
  15747. cipher: 'AES',
  15748. key: 192,
  15749. iv: 0,
  15750. mode: 'ECB',
  15751. type: 'block'
  15752. };
  15753. exports['aes-256-ecb'] = {
  15754. cipher: 'AES',
  15755. key: 256,
  15756. iv: 0,
  15757. mode: 'ECB',
  15758. type: 'block'
  15759. };
  15760. exports['aes-128-cbc'] = {
  15761. cipher: 'AES',
  15762. key: 128,
  15763. iv: 16,
  15764. mode: 'CBC',
  15765. type: 'block'
  15766. };
  15767. exports['aes-192-cbc'] = {
  15768. cipher: 'AES',
  15769. key: 192,
  15770. iv: 16,
  15771. mode: 'CBC',
  15772. type: 'block'
  15773. };
  15774. exports['aes-256-cbc'] = {
  15775. cipher: 'AES',
  15776. key: 256,
  15777. iv: 16,
  15778. mode: 'CBC',
  15779. type: 'block'
  15780. };
  15781. exports['aes128'] = exports['aes-128-cbc'];
  15782. exports['aes192'] = exports['aes-192-cbc'];
  15783. exports['aes256'] = exports['aes-256-cbc'];
  15784. exports['aes-128-cfb'] = {
  15785. cipher: 'AES',
  15786. key: 128,
  15787. iv: 16,
  15788. mode: 'CFB',
  15789. type: 'stream'
  15790. };
  15791. exports['aes-192-cfb'] = {
  15792. cipher: 'AES',
  15793. key: 192,
  15794. iv: 16,
  15795. mode: 'CFB',
  15796. type: 'stream'
  15797. };
  15798. exports['aes-256-cfb'] = {
  15799. cipher: 'AES',
  15800. key: 256,
  15801. iv: 16,
  15802. mode: 'CFB',
  15803. type: 'stream'
  15804. };
  15805. exports['aes-128-ofb'] = {
  15806. cipher: 'AES',
  15807. key: 128,
  15808. iv: 16,
  15809. mode: 'OFB',
  15810. type: 'stream'
  15811. };
  15812. exports['aes-192-ofb'] = {
  15813. cipher: 'AES',
  15814. key: 192,
  15815. iv: 16,
  15816. mode: 'OFB',
  15817. type: 'stream'
  15818. };
  15819. exports['aes-256-ofb'] = {
  15820. cipher: 'AES',
  15821. key: 256,
  15822. iv: 16,
  15823. mode: 'OFB',
  15824. type: 'stream'
  15825. };
  15826. exports['aes-128-ctr'] = {
  15827. cipher: 'AES',
  15828. key: 128,
  15829. iv: 16,
  15830. mode: 'CTR',
  15831. type: 'stream'
  15832. };
  15833. exports['aes-192-ctr'] = {
  15834. cipher: 'AES',
  15835. key: 192,
  15836. iv: 16,
  15837. mode: 'CTR',
  15838. type: 'stream'
  15839. };
  15840. exports['aes-256-ctr'] = {
  15841. cipher: 'AES',
  15842. key: 256,
  15843. iv: 16,
  15844. mode: 'CTR',
  15845. type: 'stream'
  15846. };
  15847. /***/ },
  15848. /* 106 */
  15849. /***/ function(module, exports, __webpack_require__) {
  15850. module.exports = function isBuffer(arg) {
  15851. return arg && typeof arg === 'object'
  15852. && typeof arg.copy === 'function'
  15853. && typeof arg.fill === 'function'
  15854. && typeof arg.readUInt8 === 'function';
  15855. }
  15856. /***/ },
  15857. /* 107 */
  15858. /***/ function(module, exports, __webpack_require__) {
  15859. /* WEBPACK VAR INJECTION */(function(global) {/**
  15860. * Copyright (c) 2014 Petka Antonov
  15861. *
  15862. * Permission is hereby granted, free of charge, to any person obtaining a copy
  15863. * of this software and associated documentation files (the "Software"), to deal
  15864. * in the Software without restriction, including without limitation the rights
  15865. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15866. * copies of the Software, and to permit persons to whom the Software is
  15867. * furnished to do so, subject to the following conditions:</p>
  15868. *
  15869. * The above copyright notice and this permission notice shall be included in
  15870. * all copies or substantial portions of the Software.
  15871. *
  15872. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15873. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15874. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15875. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15876. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  15877. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  15878. * THE SOFTWARE.
  15879. *
  15880. */
  15881. module.exports = (function() {
  15882. if (this !== void 0) return this;
  15883. try {return global;}
  15884. catch(e) {}
  15885. try {return window;}
  15886. catch(e) {}
  15887. try {return self;}
  15888. catch(e) {}
  15889. })();
  15890. /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
  15891. /***/ },
  15892. /* 108 */
  15893. /***/ function(module, exports, __webpack_require__) {
  15894. /**
  15895. * Copyright (c) 2014 Petka Antonov
  15896. *
  15897. * Permission is hereby granted, free of charge, to any person obtaining a copy
  15898. * of this software and associated documentation files (the "Software"), to deal
  15899. * in the Software without restriction, including without limitation the rights
  15900. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15901. * copies of the Software, and to permit persons to whom the Software is
  15902. * furnished to do so, subject to the following conditions:</p>
  15903. *
  15904. * The above copyright notice and this permission notice shall be included in
  15905. * all copies or substantial portions of the Software.
  15906. *
  15907. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15908. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15909. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15910. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15911. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  15912. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  15913. * THE SOFTWARE.
  15914. *
  15915. */
  15916. "use strict";
  15917. var global = __webpack_require__(107);
  15918. var es5 = __webpack_require__(157);
  15919. var haveGetters = (function(){
  15920. try {
  15921. var o = {};
  15922. es5.defineProperty(o, "f", {
  15923. get: function () {
  15924. return 3;
  15925. }
  15926. });
  15927. return o.f === 3;
  15928. }
  15929. catch (e) {
  15930. return false;
  15931. }
  15932. })();
  15933. var canEvaluate = (function() {
  15934. if (typeof window !== "undefined" && window !== null &&
  15935. typeof window.document !== "undefined" &&
  15936. typeof navigator !== "undefined" && navigator !== null &&
  15937. typeof navigator.appName === "string" &&
  15938. window === global) {
  15939. return false;
  15940. }
  15941. return true;
  15942. })();
  15943. function deprecated(msg) {
  15944. if (typeof console !== "undefined" && console !== null &&
  15945. typeof console.warn === "function") {
  15946. console.warn("Bluebird: " + msg);
  15947. }
  15948. }
  15949. var errorObj = {e: {}};
  15950. function tryCatch1(fn, receiver, arg) {
  15951. try {
  15952. return fn.call(receiver, arg);
  15953. }
  15954. catch (e) {
  15955. errorObj.e = e;
  15956. return errorObj;
  15957. }
  15958. }
  15959. function tryCatch2(fn, receiver, arg, arg2) {
  15960. try {
  15961. return fn.call(receiver, arg, arg2);
  15962. }
  15963. catch (e) {
  15964. errorObj.e = e;
  15965. return errorObj;
  15966. }
  15967. }
  15968. function tryCatchApply(fn, args, receiver) {
  15969. try {
  15970. return fn.apply(receiver, args);
  15971. }
  15972. catch (e) {
  15973. errorObj.e = e;
  15974. return errorObj;
  15975. }
  15976. }
  15977. var inherits = function(Child, Parent) {
  15978. var hasProp = {}.hasOwnProperty;
  15979. function T() {
  15980. this.constructor = Child;
  15981. this.constructor$ = Parent;
  15982. for (var propertyName in Parent.prototype) {
  15983. if (hasProp.call(Parent.prototype, propertyName) &&
  15984. propertyName.charAt(propertyName.length-1) !== "$"
  15985. ) {
  15986. this[propertyName + "$"] = Parent.prototype[propertyName];
  15987. }
  15988. }
  15989. }
  15990. T.prototype = Parent.prototype;
  15991. Child.prototype = new T();
  15992. return Child.prototype;
  15993. };
  15994. function asString(val) {
  15995. return typeof val === "string" ? val : ("" + val);
  15996. }
  15997. function isPrimitive(val) {
  15998. return val == null || val === true || val === false ||
  15999. typeof val === "string" || typeof val === "number";
  16000. }
  16001. function isObject(value) {
  16002. return !isPrimitive(value);
  16003. }
  16004. function maybeWrapAsError(maybeError) {
  16005. if (!isPrimitive(maybeError)) return maybeError;
  16006. return new Error(asString(maybeError));
  16007. }
  16008. function withAppended(target, appendee) {
  16009. var len = target.length;
  16010. var ret = new Array(len + 1);
  16011. var i;
  16012. for (i = 0; i < len; ++i) {
  16013. ret[i] = target[i];
  16014. }
  16015. ret[i] = appendee;
  16016. return ret;
  16017. }
  16018. function notEnumerableProp(obj, name, value) {
  16019. if (isPrimitive(obj)) return obj;
  16020. var descriptor = {
  16021. value: value,
  16022. configurable: true,
  16023. enumerable: false,
  16024. writable: true
  16025. };
  16026. es5.defineProperty(obj, name, descriptor);
  16027. return obj;
  16028. }
  16029. var wrapsPrimitiveReceiver = (function() {
  16030. return this !== "string";
  16031. }).call("string");
  16032. function thrower(r) {
  16033. throw r;
  16034. }
  16035. function toFastProperties(obj) {
  16036. /*jshint -W027*/
  16037. function f() {}
  16038. f.prototype = obj;
  16039. return f;
  16040. eval(obj);
  16041. }
  16042. var ret = {
  16043. thrower: thrower,
  16044. isArray: es5.isArray,
  16045. haveGetters: haveGetters,
  16046. notEnumerableProp: notEnumerableProp,
  16047. isPrimitive: isPrimitive,
  16048. isObject: isObject,
  16049. canEvaluate: canEvaluate,
  16050. deprecated: deprecated,
  16051. errorObj: errorObj,
  16052. tryCatch1: tryCatch1,
  16053. tryCatch2: tryCatch2,
  16054. tryCatchApply: tryCatchApply,
  16055. inherits: inherits,
  16056. withAppended: withAppended,
  16057. asString: asString,
  16058. maybeWrapAsError: maybeWrapAsError,
  16059. wrapsPrimitiveReceiver: wrapsPrimitiveReceiver,
  16060. toFastProperties: toFastProperties
  16061. };
  16062. module.exports = ret;
  16063. /***/ },
  16064. /* 109 */
  16065. /***/ function(module, exports, __webpack_require__) {
  16066. /**
  16067. * Copyright (c) 2014 Petka Antonov
  16068. *
  16069. * Permission is hereby granted, free of charge, to any person obtaining a copy
  16070. * of this software and associated documentation files (the "Software"), to deal
  16071. * in the Software without restriction, including without limitation the rights
  16072. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  16073. * copies of the Software, and to permit persons to whom the Software is
  16074. * furnished to do so, subject to the following conditions:</p>
  16075. *
  16076. * The above copyright notice and this permission notice shall be included in
  16077. * all copies or substantial portions of the Software.
  16078. *
  16079. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16080. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16081. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16082. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16083. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16084. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  16085. * THE SOFTWARE.
  16086. *
  16087. */
  16088. "use strict";
  16089. var schedule = __webpack_require__(158);
  16090. var Queue = __webpack_require__(159);
  16091. var errorObj = __webpack_require__(108).errorObj;
  16092. var tryCatch1 = __webpack_require__(108).tryCatch1;
  16093. var process = __webpack_require__(107).process;
  16094. function Async() {
  16095. this._isTickUsed = false;
  16096. this._length = 0;
  16097. this._lateBuffer = new Queue();
  16098. this._functionBuffer = new Queue(25000 * 3);
  16099. var self = this;
  16100. this.consumeFunctionBuffer = function Async$consumeFunctionBuffer() {
  16101. self._consumeFunctionBuffer();
  16102. };
  16103. }
  16104. Async.prototype.haveItemsQueued = function Async$haveItemsQueued() {
  16105. return this._length > 0;
  16106. };
  16107. Async.prototype.invokeLater = function Async$invokeLater(fn, receiver, arg) {
  16108. if (process !== void 0 &&
  16109. process.domain != null &&
  16110. !fn.domain) {
  16111. fn = process.domain.bind(fn);
  16112. }
  16113. this._lateBuffer.push(fn, receiver, arg);
  16114. this._queueTick();
  16115. };
  16116. Async.prototype.invoke = function Async$invoke(fn, receiver, arg) {
  16117. if (process !== void 0 &&
  16118. process.domain != null &&
  16119. !fn.domain) {
  16120. fn = process.domain.bind(fn);
  16121. }
  16122. var functionBuffer = this._functionBuffer;
  16123. functionBuffer.push(fn, receiver, arg);
  16124. this._length = functionBuffer.length();
  16125. this._queueTick();
  16126. };
  16127. Async.prototype._consumeFunctionBuffer =
  16128. function Async$_consumeFunctionBuffer() {
  16129. var functionBuffer = this._functionBuffer;
  16130. while(functionBuffer.length() > 0) {
  16131. var fn = functionBuffer.shift();
  16132. var receiver = functionBuffer.shift();
  16133. var arg = functionBuffer.shift();
  16134. fn.call(receiver, arg);
  16135. }
  16136. this._reset();
  16137. this._consumeLateBuffer();
  16138. };
  16139. Async.prototype._consumeLateBuffer = function Async$_consumeLateBuffer() {
  16140. var buffer = this._lateBuffer;
  16141. while(buffer.length() > 0) {
  16142. var fn = buffer.shift();
  16143. var receiver = buffer.shift();
  16144. var arg = buffer.shift();
  16145. var res = tryCatch1(fn, receiver, arg);
  16146. if (res === errorObj) {
  16147. this._queueTick();
  16148. if (fn.domain != null) {
  16149. fn.domain.emit("error", res.e);
  16150. }
  16151. else {
  16152. throw res.e;
  16153. }
  16154. }
  16155. }
  16156. };
  16157. Async.prototype._queueTick = function Async$_queue() {
  16158. if (!this._isTickUsed) {
  16159. schedule(this.consumeFunctionBuffer);
  16160. this._isTickUsed = true;
  16161. }
  16162. };
  16163. Async.prototype._reset = function Async$_reset() {
  16164. this._isTickUsed = false;
  16165. this._length = 0;
  16166. };
  16167. module.exports = new Async();
  16168. /***/ },
  16169. /* 110 */
  16170. /***/ function(module, exports, __webpack_require__) {
  16171. /**
  16172. * Copyright (c) 2014 Petka Antonov
  16173. *
  16174. * Permission is hereby granted, free of charge, to any person obtaining a copy
  16175. * of this software and associated documentation files (the "Software"), to deal
  16176. * in the Software without restriction, including without limitation the rights
  16177. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  16178. * copies of the Software, and to permit persons to whom the Software is
  16179. * furnished to do so, subject to the following conditions:</p>
  16180. *
  16181. * The above copyright notice and this permission notice shall be included in
  16182. * all copies or substantial portions of the Software.
  16183. *
  16184. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16185. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16186. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16187. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16188. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16189. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  16190. * THE SOFTWARE.
  16191. *
  16192. */
  16193. "use strict";
  16194. var global = __webpack_require__(107);
  16195. var Objectfreeze = __webpack_require__(157).freeze;
  16196. var util = __webpack_require__(108);
  16197. var inherits = util.inherits;
  16198. var notEnumerableProp = util.notEnumerableProp;
  16199. var Error = global.Error;
  16200. function markAsOriginatingFromRejection(e) {
  16201. try {
  16202. notEnumerableProp(e, "isAsync", true);
  16203. }
  16204. catch(ignore) {}
  16205. }
  16206. function originatesFromRejection(e) {
  16207. if (e == null) return false;
  16208. return ((e instanceof RejectionError) ||
  16209. e["isAsync"] === true);
  16210. }
  16211. function isError(obj) {
  16212. return obj instanceof Error;
  16213. }
  16214. function canAttach(obj) {
  16215. return isError(obj);
  16216. }
  16217. function subError(nameProperty, defaultMessage) {
  16218. function SubError(message) {
  16219. if (!(this instanceof SubError)) return new SubError(message);
  16220. this.message = typeof message === "string" ? message : defaultMessage;
  16221. this.name = nameProperty;
  16222. if (Error.captureStackTrace) {
  16223. Error.captureStackTrace(this, this.constructor);
  16224. }
  16225. }
  16226. inherits(SubError, Error);
  16227. return SubError;
  16228. }
  16229. var TypeError = global.TypeError;
  16230. if (typeof TypeError !== "function") {
  16231. TypeError = subError("TypeError", "type error");
  16232. }
  16233. var RangeError = global.RangeError;
  16234. if (typeof RangeError !== "function") {
  16235. RangeError = subError("RangeError", "range error");
  16236. }
  16237. var CancellationError = subError("CancellationError", "cancellation error");
  16238. var TimeoutError = subError("TimeoutError", "timeout error");
  16239. function RejectionError(message) {
  16240. this.name = "RejectionError";
  16241. this.message = message;
  16242. this.cause = message;
  16243. this.isAsync = true;
  16244. if (message instanceof Error) {
  16245. this.message = message.message;
  16246. this.stack = message.stack;
  16247. }
  16248. else if (Error.captureStackTrace) {
  16249. Error.captureStackTrace(this, this.constructor);
  16250. }
  16251. }
  16252. inherits(RejectionError, Error);
  16253. var key = "__BluebirdErrorTypes__";
  16254. var errorTypes = global[key];
  16255. if (!errorTypes) {
  16256. errorTypes = Objectfreeze({
  16257. CancellationError: CancellationError,
  16258. TimeoutError: TimeoutError,
  16259. RejectionError: RejectionError
  16260. });
  16261. notEnumerableProp(global, key, errorTypes);
  16262. }
  16263. module.exports = {
  16264. Error: Error,
  16265. TypeError: TypeError,
  16266. RangeError: RangeError,
  16267. CancellationError: errorTypes.CancellationError,
  16268. RejectionError: errorTypes.RejectionError,
  16269. TimeoutError: errorTypes.TimeoutError,
  16270. originatesFromRejection: originatesFromRejection,
  16271. markAsOriginatingFromRejection: markAsOriginatingFromRejection,
  16272. canAttach: canAttach
  16273. };
  16274. /***/ },
  16275. /* 111 */
  16276. /***/ function(module, exports, __webpack_require__) {
  16277. /**
  16278. * Copyright (c) 2014 Petka Antonov
  16279. *
  16280. * Permission is hereby granted, free of charge, to any person obtaining a copy
  16281. * of this software and associated documentation files (the "Software"), to deal
  16282. * in the Software without restriction, including without limitation the rights
  16283. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  16284. * copies of the Software, and to permit persons to whom the Software is
  16285. * furnished to do so, subject to the following conditions:</p>
  16286. *
  16287. * The above copyright notice and this permission notice shall be included in
  16288. * all copies or substantial portions of the Software.
  16289. *
  16290. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16291. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16292. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16293. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16294. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16295. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  16296. * THE SOFTWARE.
  16297. *
  16298. */
  16299. "use strict";
  16300. module.exports = function(Promise, INTERNAL) {
  16301. var canAttach = __webpack_require__(110).canAttach;
  16302. var util = __webpack_require__(108);
  16303. var async = __webpack_require__(109);
  16304. var hasOwn = {}.hasOwnProperty;
  16305. var isArray = util.isArray;
  16306. function toResolutionValue(val) {
  16307. switch(val) {
  16308. case -1: return void 0;
  16309. case -2: return [];
  16310. case -3: return {};
  16311. }
  16312. }
  16313. function PromiseArray(values, boundTo) {
  16314. var promise = this._promise = new Promise(INTERNAL);
  16315. var parent = void 0;
  16316. if (values instanceof Promise) {
  16317. parent = values;
  16318. if (values._cancellable()) {
  16319. promise._setCancellable();
  16320. promise._cancellationParent = values;
  16321. }
  16322. if (values._isBound()) {
  16323. promise._setBoundTo(boundTo);
  16324. }
  16325. }
  16326. promise._setTrace(parent);
  16327. this._values = values;
  16328. this._length = 0;
  16329. this._totalResolved = 0;
  16330. this._init(void 0, -2);
  16331. }
  16332. PromiseArray.PropertiesPromiseArray = function() {};
  16333. PromiseArray.prototype.length = function PromiseArray$length() {
  16334. return this._length;
  16335. };
  16336. PromiseArray.prototype.promise = function PromiseArray$promise() {
  16337. return this._promise;
  16338. };
  16339. PromiseArray.prototype._init =
  16340. function PromiseArray$_init(_, resolveValueIfEmpty) {
  16341. var values = this._values;
  16342. if (values instanceof Promise) {
  16343. if (values.isFulfilled()) {
  16344. values = values._settledValue;
  16345. if (!isArray(values)) {
  16346. var err = new Promise.TypeError("expecting an array, a promise or a thenable");
  16347. this.__hardReject__(err);
  16348. return;
  16349. }
  16350. this._values = values;
  16351. }
  16352. else if (values.isPending()) {
  16353. values._then(
  16354. this._init,
  16355. this._reject,
  16356. void 0,
  16357. this,
  16358. resolveValueIfEmpty
  16359. );
  16360. return;
  16361. }
  16362. else {
  16363. values._unsetRejectionIsUnhandled();
  16364. this._reject(values._settledValue);
  16365. return;
  16366. }
  16367. }
  16368. if (values.length === 0) {
  16369. this._resolve(toResolutionValue(resolveValueIfEmpty));
  16370. return;
  16371. }
  16372. var len = values.length;
  16373. var newLen = len;
  16374. var newValues;
  16375. if (this instanceof PromiseArray.PropertiesPromiseArray) {
  16376. newValues = this._values;
  16377. }
  16378. else {
  16379. newValues = new Array(len);
  16380. }
  16381. var isDirectScanNeeded = false;
  16382. for (var i = 0; i < len; ++i) {
  16383. var promise = values[i];
  16384. if (promise === void 0 && !hasOwn.call(values, i)) {
  16385. newLen--;
  16386. continue;
  16387. }
  16388. var maybePromise = Promise._cast(promise, void 0);
  16389. if (maybePromise instanceof Promise) {
  16390. if (maybePromise.isPending()) {
  16391. maybePromise._proxyPromiseArray(this, i);
  16392. }
  16393. else {
  16394. maybePromise._unsetRejectionIsUnhandled();
  16395. isDirectScanNeeded = true;
  16396. }
  16397. }
  16398. else {
  16399. isDirectScanNeeded = true;
  16400. }
  16401. newValues[i] = maybePromise;
  16402. }
  16403. if (newLen === 0) {
  16404. if (resolveValueIfEmpty === -2) {
  16405. this._resolve(newValues);
  16406. }
  16407. else {
  16408. this._resolve(toResolutionValue(resolveValueIfEmpty));
  16409. }
  16410. return;
  16411. }
  16412. this._values = newValues;
  16413. this._length = newLen;
  16414. if (isDirectScanNeeded) {
  16415. var scanMethod = newLen === len
  16416. ? this._scanDirectValues
  16417. : this._scanDirectValuesHoled;
  16418. async.invoke(scanMethod, this, len);
  16419. }
  16420. };
  16421. PromiseArray.prototype._settlePromiseAt =
  16422. function PromiseArray$_settlePromiseAt(index) {
  16423. var value = this._values[index];
  16424. if (!(value instanceof Promise)) {
  16425. this._promiseFulfilled(value, index);
  16426. }
  16427. else if (value.isFulfilled()) {
  16428. this._promiseFulfilled(value._settledValue, index);
  16429. }
  16430. else if (value.isRejected()) {
  16431. this._promiseRejected(value._settledValue, index);
  16432. }
  16433. };
  16434. PromiseArray.prototype._scanDirectValuesHoled =
  16435. function PromiseArray$_scanDirectValuesHoled(len) {
  16436. for (var i = 0; i < len; ++i) {
  16437. if (this._isResolved()) {
  16438. break;
  16439. }
  16440. if (hasOwn.call(this._values, i)) {
  16441. this._settlePromiseAt(i);
  16442. }
  16443. }
  16444. };
  16445. PromiseArray.prototype._scanDirectValues =
  16446. function PromiseArray$_scanDirectValues(len) {
  16447. for (var i = 0; i < len; ++i) {
  16448. if (this._isResolved()) {
  16449. break;
  16450. }
  16451. this._settlePromiseAt(i);
  16452. }
  16453. };
  16454. PromiseArray.prototype._isResolved = function PromiseArray$_isResolved() {
  16455. return this._values === null;
  16456. };
  16457. PromiseArray.prototype._resolve = function PromiseArray$_resolve(value) {
  16458. this._values = null;
  16459. this._promise._fulfill(value);
  16460. };
  16461. PromiseArray.prototype.__hardReject__ =
  16462. PromiseArray.prototype._reject = function PromiseArray$_reject(reason) {
  16463. this._values = null;
  16464. var trace = canAttach(reason) ? reason : new Error(reason + "");
  16465. this._promise._attachExtraTrace(trace);
  16466. this._promise._reject(reason, trace);
  16467. };
  16468. PromiseArray.prototype._promiseProgressed =
  16469. function PromiseArray$_promiseProgressed(progressValue, index) {
  16470. if (this._isResolved()) return;
  16471. this._promise._progress({
  16472. index: index,
  16473. value: progressValue
  16474. });
  16475. };
  16476. PromiseArray.prototype._promiseFulfilled =
  16477. function PromiseArray$_promiseFulfilled(value, index) {
  16478. if (this._isResolved()) return;
  16479. this._values[index] = value;
  16480. var totalResolved = ++this._totalResolved;
  16481. if (totalResolved >= this._length) {
  16482. this._resolve(this._values);
  16483. }
  16484. };
  16485. PromiseArray.prototype._promiseRejected =
  16486. function PromiseArray$_promiseRejected(reason, index) {
  16487. if (this._isResolved()) return;
  16488. this._totalResolved++;
  16489. this._reject(reason);
  16490. };
  16491. return PromiseArray;
  16492. };
  16493. /***/ },
  16494. /* 112 */
  16495. /***/ function(module, exports, __webpack_require__) {
  16496. /**
  16497. * Copyright (c) 2014 Petka Antonov
  16498. *
  16499. * Permission is hereby granted, free of charge, to any person obtaining a copy
  16500. * of this software and associated documentation files (the "Software"), to deal
  16501. * in the Software without restriction, including without limitation the rights
  16502. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  16503. * copies of the Software, and to permit persons to whom the Software is
  16504. * furnished to do so, subject to the following conditions:</p>
  16505. *
  16506. * The above copyright notice and this permission notice shall be included in
  16507. * all copies or substantial portions of the Software.
  16508. *
  16509. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16510. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16511. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16512. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16513. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16514. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  16515. * THE SOFTWARE.
  16516. *
  16517. */
  16518. "use strict";
  16519. module.exports = function() {
  16520. var inherits = __webpack_require__(108).inherits;
  16521. var defineProperty = __webpack_require__(157).defineProperty;
  16522. var rignore = new RegExp(
  16523. "\\b(?:[a-zA-Z0-9.]+\\$_\\w+|" +
  16524. "tryCatch(?:1|2|Apply)|new \\w*PromiseArray|" +
  16525. "\\w*PromiseArray\\.\\w*PromiseArray|" +
  16526. "setTimeout|CatchFilter\\$_\\w+|makeNodePromisified|processImmediate|" +
  16527. "process._tickCallback|nextTick|Async\\$\\w+)\\b"
  16528. );
  16529. var rtraceline = null;
  16530. var formatStack = null;
  16531. function formatNonError(obj) {
  16532. var str;
  16533. if (typeof obj === "function") {
  16534. str = "[function " +
  16535. (obj.name || "anonymous") +
  16536. "]";
  16537. }
  16538. else {
  16539. str = obj.toString();
  16540. var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
  16541. if (ruselessToString.test(str)) {
  16542. try {
  16543. var newStr = JSON.stringify(obj);
  16544. str = newStr;
  16545. }
  16546. catch(e) {
  16547. }
  16548. }
  16549. if (str.length === 0) {
  16550. str = "(empty array)";
  16551. }
  16552. }
  16553. return ("(<" + snip(str) + ">, no stack trace)");
  16554. }
  16555. function snip(str) {
  16556. var maxChars = 41;
  16557. if (str.length < maxChars) {
  16558. return str;
  16559. }
  16560. return str.substr(0, maxChars - 3) + "...";
  16561. }
  16562. function CapturedTrace(ignoreUntil, isTopLevel) {
  16563. this.captureStackTrace(CapturedTrace, isTopLevel);
  16564. }
  16565. inherits(CapturedTrace, Error);
  16566. CapturedTrace.prototype.captureStackTrace =
  16567. function CapturedTrace$captureStackTrace(ignoreUntil, isTopLevel) {
  16568. captureStackTrace(this, ignoreUntil, isTopLevel);
  16569. };
  16570. CapturedTrace.possiblyUnhandledRejection =
  16571. function CapturedTrace$PossiblyUnhandledRejection(reason) {
  16572. if (typeof console === "object") {
  16573. var message;
  16574. if (typeof reason === "object" || typeof reason === "function") {
  16575. var stack = reason.stack;
  16576. message = "Possibly unhandled " + formatStack(stack, reason);
  16577. }
  16578. else {
  16579. message = "Possibly unhandled " + String(reason);
  16580. }
  16581. if (typeof console.error === "function" ||
  16582. typeof console.error === "object") {
  16583. console.error(message);
  16584. }
  16585. else if (typeof console.log === "function" ||
  16586. typeof console.log === "object") {
  16587. console.log(message);
  16588. }
  16589. }
  16590. };
  16591. CapturedTrace.combine = function CapturedTrace$Combine(current, prev) {
  16592. var curLast = current.length - 1;
  16593. for (var i = prev.length - 1; i >= 0; --i) {
  16594. var line = prev[i];
  16595. if (current[curLast] === line) {
  16596. current.pop();
  16597. curLast--;
  16598. }
  16599. else {
  16600. break;
  16601. }
  16602. }
  16603. current.push("From previous event:");
  16604. var lines = current.concat(prev);
  16605. var ret = [];
  16606. for (var i = 0, len = lines.length; i < len; ++i) {
  16607. if ((rignore.test(lines[i]) ||
  16608. (i > 0 && !rtraceline.test(lines[i])) &&
  16609. lines[i] !== "From previous event:")
  16610. ) {
  16611. continue;
  16612. }
  16613. ret.push(lines[i]);
  16614. }
  16615. return ret;
  16616. };
  16617. CapturedTrace.isSupported = function CapturedTrace$IsSupported() {
  16618. return typeof captureStackTrace === "function";
  16619. };
  16620. var captureStackTrace = (function stackDetection() {
  16621. if (typeof Error.stackTraceLimit === "number" &&
  16622. typeof Error.captureStackTrace === "function") {
  16623. rtraceline = /^\s*at\s*/;
  16624. formatStack = function(stack, error) {
  16625. if (typeof stack === "string") return stack;
  16626. if (error.name !== void 0 &&
  16627. error.message !== void 0) {
  16628. return error.name + ". " + error.message;
  16629. }
  16630. return formatNonError(error);
  16631. };
  16632. var captureStackTrace = Error.captureStackTrace;
  16633. return function CapturedTrace$_captureStackTrace(
  16634. receiver, ignoreUntil) {
  16635. captureStackTrace(receiver, ignoreUntil);
  16636. };
  16637. }
  16638. var err = new Error();
  16639. if (typeof err.stack === "string" &&
  16640. typeof "".startsWith === "function" &&
  16641. (err.stack.startsWith("stackDetection@")) &&
  16642. stackDetection.name === "stackDetection") {
  16643. defineProperty(Error, "stackTraceLimit", {
  16644. writable: true,
  16645. enumerable: false,
  16646. configurable: false,
  16647. value: 25
  16648. });
  16649. rtraceline = /@/;
  16650. var rline = /[@\n]/;
  16651. formatStack = function(stack, error) {
  16652. if (typeof stack === "string") {
  16653. return (error.name + ". " + error.message + "\n" + stack);
  16654. }
  16655. if (error.name !== void 0 &&
  16656. error.message !== void 0) {
  16657. return error.name + ". " + error.message;
  16658. }
  16659. return formatNonError(error);
  16660. };
  16661. return function captureStackTrace(o) {
  16662. var stack = new Error().stack;
  16663. var split = stack.split(rline);
  16664. var len = split.length;
  16665. var ret = "";
  16666. for (var i = 0; i < len; i += 2) {
  16667. ret += split[i];
  16668. ret += "@";
  16669. ret += split[i + 1];
  16670. ret += "\n";
  16671. }
  16672. o.stack = ret;
  16673. };
  16674. }
  16675. else {
  16676. formatStack = function(stack, error) {
  16677. if (typeof stack === "string") return stack;
  16678. if ((typeof error === "object" ||
  16679. typeof error === "function") &&
  16680. error.name !== void 0 &&
  16681. error.message !== void 0) {
  16682. return error.name + ". " + error.message;
  16683. }
  16684. return formatNonError(error);
  16685. };
  16686. return null;
  16687. }
  16688. })();
  16689. return CapturedTrace;
  16690. };
  16691. /***/ },
  16692. /* 113 */
  16693. /***/ function(module, exports, __webpack_require__) {
  16694. /**
  16695. * Copyright (c) 2014 Petka Antonov
  16696. *
  16697. * Permission is hereby granted, free of charge, to any person obtaining a copy
  16698. * of this software and associated documentation files (the "Software"), to deal
  16699. * in the Software without restriction, including without limitation the rights
  16700. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  16701. * copies of the Software, and to permit persons to whom the Software is
  16702. * furnished to do so, subject to the following conditions:</p>
  16703. *
  16704. * The above copyright notice and this permission notice shall be included in
  16705. * all copies or substantial portions of the Software.
  16706. *
  16707. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16708. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16709. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16710. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16711. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16712. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  16713. * THE SOFTWARE.
  16714. *
  16715. */
  16716. "use strict";
  16717. module.exports = function(NEXT_FILTER) {
  16718. var util = __webpack_require__(108);
  16719. var errors = __webpack_require__(110);
  16720. var tryCatch1 = util.tryCatch1;
  16721. var errorObj = util.errorObj;
  16722. var keys = __webpack_require__(157).keys;
  16723. var TypeError = errors.TypeError;
  16724. function CatchFilter(instances, callback, promise) {
  16725. this._instances = instances;
  16726. this._callback = callback;
  16727. this._promise = promise;
  16728. }
  16729. function CatchFilter$_safePredicate(predicate, e) {
  16730. var safeObject = {};
  16731. var retfilter = tryCatch1(predicate, safeObject, e);
  16732. if (retfilter === errorObj) return retfilter;
  16733. var safeKeys = keys(safeObject);
  16734. if (safeKeys.length) {
  16735. errorObj.e = new TypeError(
  16736. "Catch filter must inherit from Error "
  16737. + "or be a simple predicate function");
  16738. return errorObj;
  16739. }
  16740. return retfilter;
  16741. }
  16742. CatchFilter.prototype.doFilter = function CatchFilter$_doFilter(e) {
  16743. var cb = this._callback;
  16744. var promise = this._promise;
  16745. var boundTo = promise._isBound() ? promise._boundTo : void 0;
  16746. for (var i = 0, len = this._instances.length; i < len; ++i) {
  16747. var item = this._instances[i];
  16748. var itemIsErrorType = item === Error ||
  16749. (item != null && item.prototype instanceof Error);
  16750. if (itemIsErrorType && e instanceof item) {
  16751. var ret = tryCatch1(cb, boundTo, e);
  16752. if (ret === errorObj) {
  16753. NEXT_FILTER.e = ret.e;
  16754. return NEXT_FILTER;
  16755. }
  16756. return ret;
  16757. } else if (typeof item === "function" && !itemIsErrorType) {
  16758. var shouldHandle = CatchFilter$_safePredicate(item, e);
  16759. if (shouldHandle === errorObj) {
  16760. var trace = errors.canAttach(errorObj.e)
  16761. ? errorObj.e
  16762. : new Error(errorObj.e + "");
  16763. this._promise._attachExtraTrace(trace);
  16764. e = errorObj.e;
  16765. break;
  16766. } else if (shouldHandle) {
  16767. var ret = tryCatch1(cb, boundTo, e);
  16768. if (ret === errorObj) {
  16769. NEXT_FILTER.e = ret.e;
  16770. return NEXT_FILTER;
  16771. }
  16772. return ret;
  16773. }
  16774. }
  16775. }
  16776. NEXT_FILTER.e = e;
  16777. return NEXT_FILTER;
  16778. };
  16779. return CatchFilter;
  16780. };
  16781. /***/ },
  16782. /* 114 */
  16783. /***/ function(module, exports, __webpack_require__) {
  16784. /**
  16785. * Copyright (c) 2014 Petka Antonov
  16786. *
  16787. * Permission is hereby granted, free of charge, to any person obtaining a copy
  16788. * of this software and associated documentation files (the "Software"), to deal
  16789. * in the Software without restriction, including without limitation the rights
  16790. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  16791. * copies of the Software, and to permit persons to whom the Software is
  16792. * furnished to do so, subject to the following conditions:</p>
  16793. *
  16794. * The above copyright notice and this permission notice shall be included in
  16795. * all copies or substantial portions of the Software.
  16796. *
  16797. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16798. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16799. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16800. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16801. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16802. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  16803. * THE SOFTWARE.
  16804. *
  16805. */
  16806. "use strict";
  16807. var util = __webpack_require__(108);
  16808. var maybeWrapAsError = util.maybeWrapAsError;
  16809. var errors = __webpack_require__(110);
  16810. var TimeoutError = errors.TimeoutError;
  16811. var RejectionError = errors.RejectionError;
  16812. var async = __webpack_require__(109);
  16813. var haveGetters = util.haveGetters;
  16814. var es5 = __webpack_require__(157);
  16815. function isUntypedError(obj) {
  16816. return obj instanceof Error &&
  16817. es5.getPrototypeOf(obj) === Error.prototype;
  16818. }
  16819. function wrapAsRejectionError(obj) {
  16820. var ret;
  16821. if (isUntypedError(obj)) {
  16822. ret = new RejectionError(obj);
  16823. }
  16824. else {
  16825. ret = obj;
  16826. }
  16827. errors.markAsOriginatingFromRejection(ret);
  16828. return ret;
  16829. }
  16830. function nodebackForPromise(promise) {
  16831. function PromiseResolver$_callback(err, value) {
  16832. if (promise === null) return;
  16833. if (err) {
  16834. var wrapped = wrapAsRejectionError(maybeWrapAsError(err));
  16835. promise._attachExtraTrace(wrapped);
  16836. promise._reject(wrapped);
  16837. }
  16838. else {
  16839. if (arguments.length > 2) {
  16840. var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}
  16841. promise._fulfill(args);
  16842. }
  16843. else {
  16844. promise._fulfill(value);
  16845. }
  16846. }
  16847. promise = null;
  16848. }
  16849. return PromiseResolver$_callback;
  16850. }
  16851. var PromiseResolver;
  16852. if (!haveGetters) {
  16853. PromiseResolver = function PromiseResolver(promise) {
  16854. this.promise = promise;
  16855. this.asCallback = nodebackForPromise(promise);
  16856. this.callback = this.asCallback;
  16857. };
  16858. }
  16859. else {
  16860. PromiseResolver = function PromiseResolver(promise) {
  16861. this.promise = promise;
  16862. };
  16863. }
  16864. if (haveGetters) {
  16865. var prop = {
  16866. get: function() {
  16867. return nodebackForPromise(this.promise);
  16868. }
  16869. };
  16870. es5.defineProperty(PromiseResolver.prototype, "asCallback", prop);
  16871. es5.defineProperty(PromiseResolver.prototype, "callback", prop);
  16872. }
  16873. PromiseResolver._nodebackForPromise = nodebackForPromise;
  16874. PromiseResolver.prototype.toString = function PromiseResolver$toString() {
  16875. return "[object PromiseResolver]";
  16876. };
  16877. PromiseResolver.prototype.resolve =
  16878. PromiseResolver.prototype.fulfill = function PromiseResolver$resolve(value) {
  16879. var promise = this.promise;
  16880. if ((promise === void 0) || (promise._tryFollow === void 0)) {
  16881. throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.");
  16882. }
  16883. if (promise._tryFollow(value)) {
  16884. return;
  16885. }
  16886. async.invoke(promise._fulfill, promise, value);
  16887. };
  16888. PromiseResolver.prototype.reject = function PromiseResolver$reject(reason) {
  16889. var promise = this.promise;
  16890. if ((promise === void 0) || (promise._attachExtraTrace === void 0)) {
  16891. throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.");
  16892. }
  16893. errors.markAsOriginatingFromRejection(reason);
  16894. var trace = errors.canAttach(reason) ? reason : new Error(reason + "");
  16895. promise._attachExtraTrace(trace);
  16896. async.invoke(promise._reject, promise, reason);
  16897. if (trace !== reason) {
  16898. async.invoke(this._setCarriedStackTrace, this, trace);
  16899. }
  16900. };
  16901. PromiseResolver.prototype.progress =
  16902. function PromiseResolver$progress(value) {
  16903. async.invoke(this.promise._progress, this.promise, value);
  16904. };
  16905. PromiseResolver.prototype.cancel = function PromiseResolver$cancel() {
  16906. async.invoke(this.promise.cancel, this.promise, void 0);
  16907. };
  16908. PromiseResolver.prototype.timeout = function PromiseResolver$timeout() {
  16909. this.reject(new TimeoutError("timeout"));
  16910. };
  16911. PromiseResolver.prototype.isResolved = function PromiseResolver$isResolved() {
  16912. return this.promise.isResolved();
  16913. };
  16914. PromiseResolver.prototype.toJSON = function PromiseResolver$toJSON() {
  16915. return this.promise.toJSON();
  16916. };
  16917. PromiseResolver.prototype._setCarriedStackTrace =
  16918. function PromiseResolver$_setCarriedStackTrace(trace) {
  16919. if (this.promise.isRejected()) {
  16920. this.promise._setCarriedStackTrace(trace);
  16921. }
  16922. };
  16923. module.exports = PromiseResolver;
  16924. /***/ },
  16925. /* 115 */
  16926. /***/ function(module, exports, __webpack_require__) {
  16927. /**
  16928. * Copyright (c) 2014 Petka Antonov
  16929. *
  16930. * Permission is hereby granted, free of charge, to any person obtaining a copy
  16931. * of this software and associated documentation files (the "Software"), to deal
  16932. * in the Software without restriction, including without limitation the rights
  16933. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  16934. * copies of the Software, and to permit persons to whom the Software is
  16935. * furnished to do so, subject to the following conditions:</p>
  16936. *
  16937. * The above copyright notice and this permission notice shall be included in
  16938. * all copies or substantial portions of the Software.
  16939. *
  16940. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16941. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16942. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16943. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16944. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16945. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  16946. * THE SOFTWARE.
  16947. *
  16948. */
  16949. "use strict";
  16950. module.exports = function(Promise) {
  16951. var TypeError = __webpack_require__(110).TypeError;
  16952. function apiRejection(msg) {
  16953. var error = new TypeError(msg);
  16954. var ret = Promise.rejected(error);
  16955. var parent = ret._peekContext();
  16956. if (parent != null) {
  16957. parent._attachExtraTrace(error);
  16958. }
  16959. return ret;
  16960. }
  16961. return apiRejection;
  16962. };
  16963. /***/ },
  16964. /* 116 */
  16965. /***/ function(module, exports, __webpack_require__) {
  16966. /**
  16967. * Copyright (c) 2014 Petka Antonov
  16968. *
  16969. * Permission is hereby granted, free of charge, to any person obtaining a copy
  16970. * of this software and associated documentation files (the "Software"), to deal
  16971. * in the Software without restriction, including without limitation the rights
  16972. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  16973. * copies of the Software, and to permit persons to whom the Software is
  16974. * furnished to do so, subject to the following conditions:</p>
  16975. *
  16976. * The above copyright notice and this permission notice shall be included in
  16977. * all copies or substantial portions of the Software.
  16978. *
  16979. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16980. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16981. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16982. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16983. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16984. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  16985. * THE SOFTWARE.
  16986. *
  16987. */
  16988. "use strict";
  16989. module.exports = function(Promise, NEXT_FILTER) {
  16990. var util = __webpack_require__(108);
  16991. var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver;
  16992. var isPrimitive = util.isPrimitive;
  16993. var thrower = util.thrower;
  16994. function returnThis() {
  16995. return this;
  16996. }
  16997. function throwThis() {
  16998. throw this;
  16999. }
  17000. function return$(r) {
  17001. return function Promise$_returner() {
  17002. return r;
  17003. };
  17004. }
  17005. function throw$(r) {
  17006. return function Promise$_thrower() {
  17007. throw r;
  17008. };
  17009. }
  17010. function promisedFinally(ret, reasonOrValue, isFulfilled) {
  17011. var then;
  17012. if (wrapsPrimitiveReceiver && isPrimitive(reasonOrValue)) {
  17013. then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue);
  17014. }
  17015. else {
  17016. then = isFulfilled ? returnThis : throwThis;
  17017. }
  17018. return ret._then(then, thrower, void 0, reasonOrValue, void 0);
  17019. }
  17020. function finallyHandler(reasonOrValue) {
  17021. var promise = this.promise;
  17022. var handler = this.handler;
  17023. var ret = promise._isBound()
  17024. ? handler.call(promise._boundTo)
  17025. : handler();
  17026. if (ret !== void 0) {
  17027. var maybePromise = Promise._cast(ret, void 0);
  17028. if (maybePromise instanceof Promise) {
  17029. return promisedFinally(maybePromise, reasonOrValue,
  17030. promise.isFulfilled());
  17031. }
  17032. }
  17033. if (promise.isRejected()) {
  17034. NEXT_FILTER.e = reasonOrValue;
  17035. return NEXT_FILTER;
  17036. }
  17037. else {
  17038. return reasonOrValue;
  17039. }
  17040. }
  17041. function tapHandler(value) {
  17042. var promise = this.promise;
  17043. var handler = this.handler;
  17044. var ret = promise._isBound()
  17045. ? handler.call(promise._boundTo, value)
  17046. : handler(value);
  17047. if (ret !== void 0) {
  17048. var maybePromise = Promise._cast(ret, void 0);
  17049. if (maybePromise instanceof Promise) {
  17050. return promisedFinally(maybePromise, value, true);
  17051. }
  17052. }
  17053. return value;
  17054. }
  17055. Promise.prototype._passThroughHandler =
  17056. function Promise$_passThroughHandler(handler, isFinally) {
  17057. if (typeof handler !== "function") return this.then();
  17058. var promiseAndHandler = {
  17059. promise: this,
  17060. handler: handler
  17061. };
  17062. return this._then(
  17063. isFinally ? finallyHandler : tapHandler,
  17064. isFinally ? finallyHandler : void 0, void 0,
  17065. promiseAndHandler, void 0);
  17066. };
  17067. Promise.prototype.lastly =
  17068. Promise.prototype["finally"] = function Promise$finally(handler) {
  17069. return this._passThroughHandler(handler, true);
  17070. };
  17071. Promise.prototype.tap = function Promise$tap(handler) {
  17072. return this._passThroughHandler(handler, false);
  17073. };
  17074. };
  17075. /***/ },
  17076. /* 117 */
  17077. /***/ function(module, exports, __webpack_require__) {
  17078. /**
  17079. * Copyright (c) 2014 Petka Antonov
  17080. *
  17081. * Permission is hereby granted, free of charge, to any person obtaining a copy
  17082. * of this software and associated documentation files (the "Software"), to deal
  17083. * in the Software without restriction, including without limitation the rights
  17084. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17085. * copies of the Software, and to permit persons to whom the Software is
  17086. * furnished to do so, subject to the following conditions:</p>
  17087. *
  17088. * The above copyright notice and this permission notice shall be included in
  17089. * all copies or substantial portions of the Software.
  17090. *
  17091. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17092. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17093. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17094. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17095. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17096. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17097. * THE SOFTWARE.
  17098. *
  17099. */
  17100. "use strict";
  17101. var util = __webpack_require__(108);
  17102. var isPrimitive = util.isPrimitive;
  17103. var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver;
  17104. module.exports = function(Promise) {
  17105. var returner = function Promise$_returner() {
  17106. return this;
  17107. };
  17108. var thrower = function Promise$_thrower() {
  17109. throw this;
  17110. };
  17111. var wrapper = function Promise$_wrapper(value, action) {
  17112. if (action === 1) {
  17113. return function Promise$_thrower() {
  17114. throw value;
  17115. };
  17116. }
  17117. else if (action === 2) {
  17118. return function Promise$_returner() {
  17119. return value;
  17120. };
  17121. }
  17122. };
  17123. Promise.prototype["return"] =
  17124. Promise.prototype.thenReturn =
  17125. function Promise$thenReturn(value) {
  17126. if (wrapsPrimitiveReceiver && isPrimitive(value)) {
  17127. return this._then(
  17128. wrapper(value, 2),
  17129. void 0,
  17130. void 0,
  17131. void 0,
  17132. void 0
  17133. );
  17134. }
  17135. return this._then(returner, void 0, void 0, value, void 0);
  17136. };
  17137. Promise.prototype["throw"] =
  17138. Promise.prototype.thenThrow =
  17139. function Promise$thenThrow(reason) {
  17140. if (wrapsPrimitiveReceiver && isPrimitive(reason)) {
  17141. return this._then(
  17142. wrapper(reason, 1),
  17143. void 0,
  17144. void 0,
  17145. void 0,
  17146. void 0
  17147. );
  17148. }
  17149. return this._then(thrower, void 0, void 0, reason, void 0);
  17150. };
  17151. };
  17152. /***/ },
  17153. /* 118 */
  17154. /***/ function(module, exports, __webpack_require__) {
  17155. /**
  17156. * Copyright (c) 2014 Petka Antonov
  17157. *
  17158. * Permission is hereby granted, free of charge, to any person obtaining a copy
  17159. * of this software and associated documentation files (the "Software"), to deal
  17160. * in the Software without restriction, including without limitation the rights
  17161. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17162. * copies of the Software, and to permit persons to whom the Software is
  17163. * furnished to do so, subject to the following conditions:</p>
  17164. *
  17165. * The above copyright notice and this permission notice shall be included in
  17166. * all copies or substantial portions of the Software.
  17167. *
  17168. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17169. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17170. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17171. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17172. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17173. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17174. * THE SOFTWARE.
  17175. *
  17176. */
  17177. "use strict";
  17178. module.exports = function(Promise, INTERNAL) {
  17179. var util = __webpack_require__(108);
  17180. var canAttach = __webpack_require__(110).canAttach;
  17181. var errorObj = util.errorObj;
  17182. var isObject = util.isObject;
  17183. function getThen(obj) {
  17184. try {
  17185. return obj.then;
  17186. }
  17187. catch(e) {
  17188. errorObj.e = e;
  17189. return errorObj;
  17190. }
  17191. }
  17192. function Promise$_Cast(obj, originalPromise) {
  17193. if (isObject(obj)) {
  17194. if (obj instanceof Promise) {
  17195. return obj;
  17196. }
  17197. else if (isAnyBluebirdPromise(obj)) {
  17198. var ret = new Promise(INTERNAL);
  17199. ret._setTrace(void 0);
  17200. obj._then(
  17201. ret._fulfillUnchecked,
  17202. ret._rejectUncheckedCheckError,
  17203. ret._progressUnchecked,
  17204. ret,
  17205. null
  17206. );
  17207. ret._setFollowing();
  17208. return ret;
  17209. }
  17210. var then = getThen(obj);
  17211. if (then === errorObj) {
  17212. if (originalPromise !== void 0 && canAttach(then.e)) {
  17213. originalPromise._attachExtraTrace(then.e);
  17214. }
  17215. return Promise.reject(then.e);
  17216. }
  17217. else if (typeof then === "function") {
  17218. return Promise$_doThenable(obj, then, originalPromise);
  17219. }
  17220. }
  17221. return obj;
  17222. }
  17223. var hasProp = {}.hasOwnProperty;
  17224. function isAnyBluebirdPromise(obj) {
  17225. return hasProp.call(obj, "_promise0");
  17226. }
  17227. function Promise$_doThenable(x, then, originalPromise) {
  17228. var resolver = Promise.defer();
  17229. var called = false;
  17230. try {
  17231. then.call(
  17232. x,
  17233. Promise$_resolveFromThenable,
  17234. Promise$_rejectFromThenable,
  17235. Promise$_progressFromThenable
  17236. );
  17237. }
  17238. catch(e) {
  17239. if (!called) {
  17240. called = true;
  17241. var trace = canAttach(e) ? e : new Error(e + "");
  17242. if (originalPromise !== void 0) {
  17243. originalPromise._attachExtraTrace(trace);
  17244. }
  17245. resolver.promise._reject(e, trace);
  17246. }
  17247. }
  17248. return resolver.promise;
  17249. function Promise$_resolveFromThenable(y) {
  17250. if (called) return;
  17251. called = true;
  17252. if (x === y) {
  17253. var e = Promise._makeSelfResolutionError();
  17254. if (originalPromise !== void 0) {
  17255. originalPromise._attachExtraTrace(e);
  17256. }
  17257. resolver.promise._reject(e, void 0);
  17258. return;
  17259. }
  17260. resolver.resolve(y);
  17261. }
  17262. function Promise$_rejectFromThenable(r) {
  17263. if (called) return;
  17264. called = true;
  17265. var trace = canAttach(r) ? r : new Error(r + "");
  17266. if (originalPromise !== void 0) {
  17267. originalPromise._attachExtraTrace(trace);
  17268. }
  17269. resolver.promise._reject(r, trace);
  17270. }
  17271. function Promise$_progressFromThenable(v) {
  17272. if (called) return;
  17273. var promise = resolver.promise;
  17274. if (typeof promise._progress === "function") {
  17275. promise._progress(v);
  17276. }
  17277. }
  17278. }
  17279. Promise._cast = Promise$_Cast;
  17280. };
  17281. /***/ },
  17282. /* 119 */
  17283. /***/ function(module, exports, __webpack_require__) {
  17284. /**
  17285. * Copyright (c) 2014 Petka Antonov
  17286. *
  17287. * Permission is hereby granted, free of charge, to any person obtaining a copy
  17288. * of this software and associated documentation files (the "Software"), to deal
  17289. * in the Software without restriction, including without limitation the rights
  17290. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17291. * copies of the Software, and to permit persons to whom the Software is
  17292. * furnished to do so, subject to the following conditions:</p>
  17293. *
  17294. * The above copyright notice and this permission notice shall be included in
  17295. * all copies or substantial portions of the Software.
  17296. *
  17297. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17298. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17299. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17300. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17301. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17302. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17303. * THE SOFTWARE.
  17304. *
  17305. */
  17306. "use strict";
  17307. module.exports = function(Promise) {
  17308. function PromiseInspection(promise) {
  17309. if (promise !== void 0) {
  17310. this._bitField = promise._bitField;
  17311. this._settledValue = promise.isResolved()
  17312. ? promise._settledValue
  17313. : void 0;
  17314. }
  17315. else {
  17316. this._bitField = 0;
  17317. this._settledValue = void 0;
  17318. }
  17319. }
  17320. PromiseInspection.prototype.isFulfilled =
  17321. Promise.prototype.isFulfilled = function Promise$isFulfilled() {
  17322. return (this._bitField & 268435456) > 0;
  17323. };
  17324. PromiseInspection.prototype.isRejected =
  17325. Promise.prototype.isRejected = function Promise$isRejected() {
  17326. return (this._bitField & 134217728) > 0;
  17327. };
  17328. PromiseInspection.prototype.isPending =
  17329. Promise.prototype.isPending = function Promise$isPending() {
  17330. return (this._bitField & 402653184) === 0;
  17331. };
  17332. PromiseInspection.prototype.value =
  17333. Promise.prototype.value = function Promise$value() {
  17334. if (!this.isFulfilled()) {
  17335. throw new TypeError("cannot get fulfillment value of a non-fulfilled promise");
  17336. }
  17337. return this._settledValue;
  17338. };
  17339. PromiseInspection.prototype.error =
  17340. Promise.prototype.reason = function Promise$reason() {
  17341. if (!this.isRejected()) {
  17342. throw new TypeError("cannot get rejection reason of a non-rejected promise");
  17343. }
  17344. return this._settledValue;
  17345. };
  17346. PromiseInspection.prototype.isResolved =
  17347. Promise.prototype.isResolved = function Promise$isResolved() {
  17348. return (this._bitField & 402653184) > 0;
  17349. };
  17350. Promise.prototype.inspect = function Promise$inspect() {
  17351. return new PromiseInspection(this);
  17352. };
  17353. Promise.PromiseInspection = PromiseInspection;
  17354. };
  17355. /***/ },
  17356. /* 120 */
  17357. /***/ function(module, exports, __webpack_require__) {
  17358. /**
  17359. * Copyright (c) 2014 Petka Antonov
  17360. *
  17361. * Permission is hereby granted, free of charge, to any person obtaining a copy
  17362. * of this software and associated documentation files (the "Software"), to deal
  17363. * in the Software without restriction, including without limitation the rights
  17364. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17365. * copies of the Software, and to permit persons to whom the Software is
  17366. * furnished to do so, subject to the following conditions:</p>
  17367. *
  17368. * The above copyright notice and this permission notice shall be included in
  17369. * all copies or substantial portions of the Software.
  17370. *
  17371. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17372. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17373. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17374. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17375. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17376. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17377. * THE SOFTWARE.
  17378. *
  17379. */
  17380. "use strict";
  17381. var global = __webpack_require__(107);
  17382. var setTimeout = function(fn, ms) {
  17383. var $_len = arguments.length;var args = new Array($_len - 2); for(var $_i = 2; $_i < $_len; ++$_i) {args[$_i - 2] = arguments[$_i];}
  17384. global.setTimeout(function(){
  17385. fn.apply(void 0, args);
  17386. }, ms);
  17387. };
  17388. module.exports = function(Promise, INTERNAL) {
  17389. var util = __webpack_require__(108);
  17390. var errors = __webpack_require__(110);
  17391. var apiRejection = __webpack_require__(115)(Promise);
  17392. var TimeoutError = Promise.TimeoutError;
  17393. var afterTimeout = function Promise$_afterTimeout(promise, message, ms) {
  17394. if (!promise.isPending()) return;
  17395. if (typeof message !== "string") {
  17396. message = "operation timed out after" + " " + ms + " ms"
  17397. }
  17398. var err = new TimeoutError(message);
  17399. errors.markAsOriginatingFromRejection(err);
  17400. promise._attachExtraTrace(err);
  17401. promise._rejectUnchecked(err);
  17402. };
  17403. var afterDelay = function Promise$_afterDelay(value, promise) {
  17404. promise._fulfill(value);
  17405. };
  17406. var delay = Promise.delay = function Promise$Delay(value, ms) {
  17407. if (ms === void 0) {
  17408. ms = value;
  17409. value = void 0;
  17410. }
  17411. ms = +ms;
  17412. var maybePromise = Promise._cast(value, void 0);
  17413. var promise = new Promise(INTERNAL);
  17414. if (maybePromise instanceof Promise) {
  17415. if (maybePromise._isBound()) {
  17416. promise._setBoundTo(maybePromise._boundTo);
  17417. }
  17418. if (maybePromise._cancellable()) {
  17419. promise._setCancellable();
  17420. promise._cancellationParent = maybePromise;
  17421. }
  17422. promise._setTrace(maybePromise);
  17423. promise._follow(maybePromise);
  17424. return promise.then(function(value) {
  17425. return Promise.delay(value, ms);
  17426. });
  17427. }
  17428. else {
  17429. promise._setTrace(void 0);
  17430. setTimeout(afterDelay, ms, value, promise);
  17431. }
  17432. return promise;
  17433. };
  17434. Promise.prototype.delay = function Promise$delay(ms) {
  17435. return delay(this, ms);
  17436. };
  17437. Promise.prototype.timeout = function Promise$timeout(ms, message) {
  17438. ms = +ms;
  17439. var ret = new Promise(INTERNAL);
  17440. ret._setTrace(this);
  17441. if (this._isBound()) ret._setBoundTo(this._boundTo);
  17442. if (this._cancellable()) {
  17443. ret._setCancellable();
  17444. ret._cancellationParent = this;
  17445. }
  17446. ret._follow(this);
  17447. setTimeout(afterTimeout, ms, ret, message, ms);
  17448. return ret;
  17449. };
  17450. };
  17451. /***/ },
  17452. /* 121 */
  17453. /***/ function(module, exports, __webpack_require__) {
  17454. /**
  17455. * Copyright (c) 2014 Petka Antonov
  17456. *
  17457. * Permission is hereby granted, free of charge, to any person obtaining a copy
  17458. * of this software and associated documentation files (the "Software"), to deal
  17459. * in the Software without restriction, including without limitation the rights
  17460. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17461. * copies of the Software, and to permit persons to whom the Software is
  17462. * furnished to do so, subject to the following conditions:</p>
  17463. *
  17464. * The above copyright notice and this permission notice shall be included in
  17465. * all copies or substantial portions of the Software.
  17466. *
  17467. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17468. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17469. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17470. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17471. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17472. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17473. * THE SOFTWARE.
  17474. *
  17475. */
  17476. "use strict";
  17477. module.exports = function(Promise, Promise$_CreatePromiseArray, PromiseArray) {
  17478. var SomePromiseArray = __webpack_require__(160)(PromiseArray);
  17479. function Promise$_Any(promises, useBound) {
  17480. var ret = Promise$_CreatePromiseArray(
  17481. promises,
  17482. SomePromiseArray,
  17483. useBound === true && promises._isBound()
  17484. ? promises._boundTo
  17485. : void 0
  17486. );
  17487. var promise = ret.promise();
  17488. if (promise.isRejected()) {
  17489. return promise;
  17490. }
  17491. ret.setHowMany(1);
  17492. ret.setUnwrap();
  17493. ret.init();
  17494. return promise;
  17495. }
  17496. Promise.any = function Promise$Any(promises) {
  17497. return Promise$_Any(promises, false);
  17498. };
  17499. Promise.prototype.any = function Promise$any() {
  17500. return Promise$_Any(this, true);
  17501. };
  17502. };
  17503. /***/ },
  17504. /* 122 */
  17505. /***/ function(module, exports, __webpack_require__) {
  17506. /**
  17507. * Copyright (c) 2014 Petka Antonov
  17508. *
  17509. * Permission is hereby granted, free of charge, to any person obtaining a copy
  17510. * of this software and associated documentation files (the "Software"), to deal
  17511. * in the Software without restriction, including without limitation the rights
  17512. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17513. * copies of the Software, and to permit persons to whom the Software is
  17514. * furnished to do so, subject to the following conditions:</p>
  17515. *
  17516. * The above copyright notice and this permission notice shall be included in
  17517. * all copies or substantial portions of the Software.
  17518. *
  17519. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17520. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17521. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17522. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17523. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17524. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17525. * THE SOFTWARE.
  17526. *
  17527. */
  17528. "use strict";
  17529. module.exports = function(Promise, INTERNAL) {
  17530. var apiRejection = __webpack_require__(115)(Promise);
  17531. var isArray = __webpack_require__(108).isArray;
  17532. var raceLater = function Promise$_raceLater(promise) {
  17533. return promise.then(function(array) {
  17534. return Promise$_Race(array, promise);
  17535. });
  17536. };
  17537. var hasOwn = {}.hasOwnProperty;
  17538. function Promise$_Race(promises, parent) {
  17539. var maybePromise = Promise._cast(promises, void 0);
  17540. if (maybePromise instanceof Promise) {
  17541. return raceLater(maybePromise);
  17542. }
  17543. else if (!isArray(promises)) {
  17544. return apiRejection("expecting an array, a promise or a thenable");
  17545. }
  17546. var ret = new Promise(INTERNAL);
  17547. ret._setTrace(parent);
  17548. if (parent !== void 0) {
  17549. if (parent._isBound()) {
  17550. ret._setBoundTo(parent._boundTo);
  17551. }
  17552. if (parent._cancellable()) {
  17553. ret._setCancellable();
  17554. ret._cancellationParent = parent;
  17555. }
  17556. }
  17557. var fulfill = ret._fulfill;
  17558. var reject = ret._reject;
  17559. for (var i = 0, len = promises.length; i < len; ++i) {
  17560. var val = promises[i];
  17561. if (val === void 0 && !(hasOwn.call(promises, i))) {
  17562. continue;
  17563. }
  17564. Promise.cast(val)._then(
  17565. fulfill,
  17566. reject,
  17567. void 0,
  17568. ret,
  17569. null
  17570. );
  17571. }
  17572. return ret;
  17573. }
  17574. Promise.race = function Promise$Race(promises) {
  17575. return Promise$_Race(promises, void 0);
  17576. };
  17577. Promise.prototype.race = function Promise$race() {
  17578. return Promise$_Race(this, void 0);
  17579. };
  17580. };
  17581. /***/ },
  17582. /* 123 */
  17583. /***/ function(module, exports, __webpack_require__) {
  17584. /**
  17585. * Copyright (c) 2014 Petka Antonov
  17586. *
  17587. * Permission is hereby granted, free of charge, to any person obtaining a copy
  17588. * of this software and associated documentation files (the "Software"), to deal
  17589. * in the Software without restriction, including without limitation the rights
  17590. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17591. * copies of the Software, and to permit persons to whom the Software is
  17592. * furnished to do so, subject to the following conditions:</p>
  17593. *
  17594. * The above copyright notice and this permission notice shall be included in
  17595. * all copies or substantial portions of the Software.
  17596. *
  17597. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17598. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17599. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17600. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17601. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17602. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17603. * THE SOFTWARE.
  17604. *
  17605. */
  17606. "use strict";
  17607. module.exports = function(Promise) {
  17608. Promise.prototype.call = function Promise$call(propertyName) {
  17609. var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}
  17610. return this._then(function(obj) {
  17611. return obj[propertyName].apply(obj, args);
  17612. },
  17613. void 0,
  17614. void 0,
  17615. void 0,
  17616. void 0
  17617. );
  17618. };
  17619. function Promise$getter(obj) {
  17620. var prop = typeof this === "string"
  17621. ? this
  17622. : ("" + this);
  17623. return obj[prop];
  17624. }
  17625. Promise.prototype.get = function Promise$get(propertyName) {
  17626. return this._then(
  17627. Promise$getter,
  17628. void 0,
  17629. void 0,
  17630. propertyName,
  17631. void 0
  17632. );
  17633. };
  17634. };
  17635. /***/ },
  17636. /* 124 */
  17637. /***/ function(module, exports, __webpack_require__) {
  17638. /**
  17639. * Copyright (c) 2014 Petka Antonov
  17640. *
  17641. * Permission is hereby granted, free of charge, to any person obtaining a copy
  17642. * of this software and associated documentation files (the "Software"), to deal
  17643. * in the Software without restriction, including without limitation the rights
  17644. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17645. * copies of the Software, and to permit persons to whom the Software is
  17646. * furnished to do so, subject to the following conditions:</p>
  17647. *
  17648. * The above copyright notice and this permission notice shall be included in
  17649. * all copies or substantial portions of the Software.
  17650. *
  17651. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17652. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17653. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17654. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17655. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17656. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17657. * THE SOFTWARE.
  17658. *
  17659. */
  17660. "use strict";
  17661. module.exports = function(Promise) {
  17662. var isArray = __webpack_require__(108).isArray;
  17663. function Promise$_filter(booleans) {
  17664. var values = this instanceof Promise ? this._settledValue : this;
  17665. var len = values.length;
  17666. var ret = new Array(len);
  17667. var j = 0;
  17668. for (var i = 0; i < len; ++i) {
  17669. if (booleans[i]) ret[j++] = values[i];
  17670. }
  17671. ret.length = j;
  17672. return ret;
  17673. }
  17674. var ref = {ref: null};
  17675. Promise.filter = function Promise$Filter(promises, fn) {
  17676. return Promise.map(promises, fn, ref)
  17677. ._then(Promise$_filter, void 0, void 0, ref.ref, void 0);
  17678. };
  17679. Promise.prototype.filter = function Promise$filter(fn) {
  17680. return this.map(fn, ref)
  17681. ._then(Promise$_filter, void 0, void 0, ref.ref, void 0);
  17682. };
  17683. };
  17684. /***/ },
  17685. /* 125 */
  17686. /***/ function(module, exports, __webpack_require__) {
  17687. /**
  17688. * Copyright (c) 2014 Petka Antonov
  17689. *
  17690. * Permission is hereby granted, free of charge, to any person obtaining a copy
  17691. * of this software and associated documentation files (the "Software"), to deal
  17692. * in the Software without restriction, including without limitation the rights
  17693. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17694. * copies of the Software, and to permit persons to whom the Software is
  17695. * furnished to do so, subject to the following conditions:</p>
  17696. *
  17697. * The above copyright notice and this permission notice shall be included in
  17698. * all copies or substantial portions of the Software.
  17699. *
  17700. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17701. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17702. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17703. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17704. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17705. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17706. * THE SOFTWARE.
  17707. *
  17708. */
  17709. "use strict";
  17710. module.exports = function(Promise, apiRejection, INTERNAL) {
  17711. var PromiseSpawn = __webpack_require__(161)(Promise, INTERNAL);
  17712. var errors = __webpack_require__(110);
  17713. var TypeError = errors.TypeError;
  17714. var deprecated = __webpack_require__(108).deprecated;
  17715. Promise.coroutine = function Promise$Coroutine(generatorFunction) {
  17716. if (typeof generatorFunction !== "function") {
  17717. throw new TypeError("generatorFunction must be a function");
  17718. }
  17719. var PromiseSpawn$ = PromiseSpawn;
  17720. return function () {
  17721. var generator = generatorFunction.apply(this, arguments);
  17722. var spawn = new PromiseSpawn$(void 0, void 0);
  17723. spawn._generator = generator;
  17724. spawn._next(void 0);
  17725. return spawn.promise();
  17726. };
  17727. };
  17728. Promise.coroutine.addYieldHandler = PromiseSpawn.addYieldHandler;
  17729. Promise.spawn = function Promise$Spawn(generatorFunction) {
  17730. deprecated("Promise.spawn is deprecated. Use Promise.coroutine instead.");
  17731. if (typeof generatorFunction !== "function") {
  17732. return apiRejection("generatorFunction must be a function");
  17733. }
  17734. var spawn = new PromiseSpawn(generatorFunction, this);
  17735. var ret = spawn.promise();
  17736. spawn._run(Promise.spawn);
  17737. return ret;
  17738. };
  17739. };
  17740. /***/ },
  17741. /* 126 */
  17742. /***/ function(module, exports, __webpack_require__) {
  17743. /**
  17744. * Copyright (c) 2014 Petka Antonov
  17745. *
  17746. * Permission is hereby granted, free of charge, to any person obtaining a copy
  17747. * of this software and associated documentation files (the "Software"), to deal
  17748. * in the Software without restriction, including without limitation the rights
  17749. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17750. * copies of the Software, and to permit persons to whom the Software is
  17751. * furnished to do so, subject to the following conditions:</p>
  17752. *
  17753. * The above copyright notice and this permission notice shall be included in
  17754. * all copies or substantial portions of the Software.
  17755. *
  17756. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17757. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17758. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17759. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17760. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17761. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17762. * THE SOFTWARE.
  17763. *
  17764. */
  17765. "use strict";
  17766. module.exports = function(Promise, PromiseArray, INTERNAL, apiRejection) {
  17767. var all = Promise.all;
  17768. var util = __webpack_require__(108);
  17769. var canAttach = __webpack_require__(110).canAttach;
  17770. var isArray = util.isArray;
  17771. var _cast = Promise._cast;
  17772. function unpack(values) {
  17773. return Promise$_Map(values, this[0], this[1], this[2]);
  17774. }
  17775. function Promise$_Map(promises, fn, useBound, ref) {
  17776. if (typeof fn !== "function") {
  17777. return apiRejection("fn must be a function");
  17778. }
  17779. var receiver = void 0;
  17780. if (useBound === true) {
  17781. if (promises._isBound()) {
  17782. receiver = promises._boundTo;
  17783. }
  17784. }
  17785. else if (useBound !== false) {
  17786. receiver = useBound;
  17787. }
  17788. var shouldUnwrapItems = ref !== void 0;
  17789. if (shouldUnwrapItems) ref.ref = promises;
  17790. if (promises instanceof Promise) {
  17791. var pack = [fn, receiver, ref];
  17792. return promises._then(unpack, void 0, void 0, pack, void 0);
  17793. }
  17794. else if (!isArray(promises)) {
  17795. return apiRejection("expecting an array, a promise or a thenable");
  17796. }
  17797. var promise = new Promise(INTERNAL);
  17798. if (receiver !== void 0) promise._setBoundTo(receiver);
  17799. promise._setTrace(void 0);
  17800. var mapping = new Mapping(promise,
  17801. fn,
  17802. promises,
  17803. receiver,
  17804. shouldUnwrapItems);
  17805. mapping.init();
  17806. return promise;
  17807. }
  17808. var pending = {};
  17809. function Mapping(promise, callback, items, receiver, shouldUnwrapItems) {
  17810. this.shouldUnwrapItems = shouldUnwrapItems;
  17811. this.index = 0;
  17812. this.items = items;
  17813. this.callback = callback;
  17814. this.receiver = receiver;
  17815. this.promise = promise;
  17816. this.result = new Array(items.length);
  17817. }
  17818. util.inherits(Mapping, PromiseArray);
  17819. Mapping.prototype.init = function Mapping$init() {
  17820. var items = this.items;
  17821. var len = items.length;
  17822. var result = this.result;
  17823. var isRejected = false;
  17824. for (var i = 0; i < len; ++i) {
  17825. var maybePromise = _cast(items[i], void 0);
  17826. if (maybePromise instanceof Promise) {
  17827. if (maybePromise.isPending()) {
  17828. result[i] = pending;
  17829. maybePromise._proxyPromiseArray(this, i);
  17830. }
  17831. else if (maybePromise.isFulfilled()) {
  17832. result[i] = maybePromise.value();
  17833. }
  17834. else {
  17835. maybePromise._unsetRejectionIsUnhandled();
  17836. if (!isRejected) {
  17837. this.reject(maybePromise.reason());
  17838. isRejected = true;
  17839. }
  17840. }
  17841. }
  17842. else {
  17843. result[i] = maybePromise;
  17844. }
  17845. }
  17846. if (!isRejected) this.iterate();
  17847. };
  17848. Mapping.prototype.isResolved = function Mapping$isResolved() {
  17849. return this.promise === null;
  17850. };
  17851. Mapping.prototype._promiseProgressed =
  17852. function Mapping$_promiseProgressed(value) {
  17853. if (this.isResolved()) return;
  17854. this.promise._progress(value);
  17855. };
  17856. Mapping.prototype._promiseFulfilled =
  17857. function Mapping$_promiseFulfilled(value, index) {
  17858. if (this.isResolved()) return;
  17859. this.result[index] = value;
  17860. if (this.shouldUnwrapItems) this.items[index] = value;
  17861. if (this.index === index) this.iterate();
  17862. };
  17863. Mapping.prototype._promiseRejected =
  17864. function Mapping$_promiseRejected(reason) {
  17865. this.reject(reason);
  17866. };
  17867. Mapping.prototype.reject = function Mapping$reject(reason) {
  17868. if (this.isResolved()) return;
  17869. var trace = canAttach(reason) ? reason : new Error(reason + "");
  17870. this.promise._attachExtraTrace(trace);
  17871. this.promise._reject(reason, trace);
  17872. };
  17873. Mapping.prototype.iterate = function Mapping$iterate() {
  17874. var i = this.index;
  17875. var items = this.items;
  17876. var result = this.result;
  17877. var len = items.length;
  17878. var result = this.result;
  17879. var receiver = this.receiver;
  17880. var callback = this.callback;
  17881. for (; i < len; ++i) {
  17882. var value = result[i];
  17883. if (value === pending) {
  17884. this.index = i;
  17885. return;
  17886. }
  17887. try { result[i] = callback.call(receiver, value, i, len); }
  17888. catch (e) { return this.reject(e); }
  17889. }
  17890. this.promise._follow(all(result));
  17891. this.items = this.result = this.callback = this.promise = null;
  17892. };
  17893. Promise.prototype.map = function Promise$map(fn, ref) {
  17894. return Promise$_Map(this, fn, true, ref);
  17895. };
  17896. Promise.map = function Promise$Map(promises, fn, ref) {
  17897. return Promise$_Map(promises, fn, false, ref);
  17898. };
  17899. };
  17900. /***/ },
  17901. /* 127 */
  17902. /***/ function(module, exports, __webpack_require__) {
  17903. /**
  17904. * Copyright (c) 2014 Petka Antonov
  17905. *
  17906. * Permission is hereby granted, free of charge, to any person obtaining a copy
  17907. * of this software and associated documentation files (the "Software"), to deal
  17908. * in the Software without restriction, including without limitation the rights
  17909. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17910. * copies of the Software, and to permit persons to whom the Software is
  17911. * furnished to do so, subject to the following conditions:</p>
  17912. *
  17913. * The above copyright notice and this permission notice shall be included in
  17914. * all copies or substantial portions of the Software.
  17915. *
  17916. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17917. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17918. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17919. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17920. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17921. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17922. * THE SOFTWARE.
  17923. *
  17924. */
  17925. "use strict";
  17926. module.exports = function(Promise) {
  17927. var util = __webpack_require__(108);
  17928. var async = __webpack_require__(109);
  17929. var tryCatch2 = util.tryCatch2;
  17930. var tryCatch1 = util.tryCatch1;
  17931. var errorObj = util.errorObj;
  17932. function thrower(r) {
  17933. throw r;
  17934. }
  17935. function Promise$_successAdapter(val, receiver) {
  17936. var nodeback = this;
  17937. var ret = val === void 0
  17938. ? tryCatch1(nodeback, receiver, null)
  17939. : tryCatch2(nodeback, receiver, null, val);
  17940. if (ret === errorObj) {
  17941. async.invokeLater(thrower, void 0, ret.e);
  17942. }
  17943. }
  17944. function Promise$_errorAdapter(reason, receiver) {
  17945. var nodeback = this;
  17946. var ret = tryCatch1(nodeback, receiver, reason);
  17947. if (ret === errorObj) {
  17948. async.invokeLater(thrower, void 0, ret.e);
  17949. }
  17950. }
  17951. Promise.prototype.nodeify = function Promise$nodeify(nodeback) {
  17952. if (typeof nodeback == "function") {
  17953. this._then(
  17954. Promise$_successAdapter,
  17955. Promise$_errorAdapter,
  17956. void 0,
  17957. nodeback,
  17958. this._isBound() ? this._boundTo : null
  17959. );
  17960. }
  17961. return this;
  17962. };
  17963. };
  17964. /***/ },
  17965. /* 128 */
  17966. /***/ function(module, exports, __webpack_require__) {
  17967. /**
  17968. * Copyright (c) 2014 Petka Antonov
  17969. *
  17970. * Permission is hereby granted, free of charge, to any person obtaining a copy
  17971. * of this software and associated documentation files (the "Software"), to deal
  17972. * in the Software without restriction, including without limitation the rights
  17973. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17974. * copies of the Software, and to permit persons to whom the Software is
  17975. * furnished to do so, subject to the following conditions:</p>
  17976. *
  17977. * The above copyright notice and this permission notice shall be included in
  17978. * all copies or substantial portions of the Software.
  17979. *
  17980. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17981. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17982. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17983. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17984. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17985. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17986. * THE SOFTWARE.
  17987. *
  17988. */
  17989. "use strict";
  17990. module.exports = function(Promise, INTERNAL) {
  17991. var THIS = {};
  17992. var util = __webpack_require__(108);
  17993. var es5 = __webpack_require__(157);
  17994. var nodebackForPromise = __webpack_require__(114)
  17995. ._nodebackForPromise;
  17996. var withAppended = util.withAppended;
  17997. var maybeWrapAsError = util.maybeWrapAsError;
  17998. var canEvaluate = util.canEvaluate;
  17999. var deprecated = util.deprecated;
  18000. var TypeError = __webpack_require__(110).TypeError;
  18001. var rasyncSuffix = new RegExp("Async" + "$");
  18002. function isPromisified(fn) {
  18003. return fn.__isPromisified__ === true;
  18004. }
  18005. function hasPromisified(obj, key) {
  18006. var containsKey = ((key + "Async") in obj);
  18007. return containsKey ? isPromisified(obj[key + "Async"])
  18008. : false;
  18009. }
  18010. function checkValid(ret) {
  18011. for (var i = 0; i < ret.length; i += 2) {
  18012. var key = ret[i];
  18013. if (rasyncSuffix.test(key)) {
  18014. var keyWithoutAsyncSuffix = key.replace(rasyncSuffix, "");
  18015. for (var j = 0; j < ret.length; j += 2) {
  18016. if (ret[j] === keyWithoutAsyncSuffix) {
  18017. throw new TypeError("Cannot promisify an API " +
  18018. "that has normal methods with Async-suffix");
  18019. }
  18020. }
  18021. }
  18022. }
  18023. }
  18024. var inheritedMethods = (function() {
  18025. if (es5.isES5) {
  18026. var create = Object.create;
  18027. var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  18028. return function(cur) {
  18029. var ret = [];
  18030. var visitedKeys = create(null);
  18031. var original = cur;
  18032. while (cur !== null) {
  18033. var keys = es5.keys(cur);
  18034. for (var i = 0, len = keys.length; i < len; ++i) {
  18035. var key = keys[i];
  18036. if (visitedKeys[key]) continue;
  18037. visitedKeys[key] = true;
  18038. var desc = getOwnPropertyDescriptor(cur, key);
  18039. if (desc != null &&
  18040. typeof desc.value === "function" &&
  18041. !isPromisified(desc.value) &&
  18042. !hasPromisified(original, key)) {
  18043. ret.push(key, desc.value);
  18044. }
  18045. }
  18046. cur = es5.getPrototypeOf(cur);
  18047. }
  18048. checkValid(ret);
  18049. return ret;
  18050. };
  18051. }
  18052. else {
  18053. return function(obj) {
  18054. var ret = [];
  18055. /*jshint forin:false */
  18056. for (var key in obj) {
  18057. var fn = obj[key];
  18058. if (typeof fn === "function" &&
  18059. !isPromisified(fn) &&
  18060. !hasPromisified(obj, key)) {
  18061. ret.push(key, fn);
  18062. }
  18063. }
  18064. checkValid(ret);
  18065. return ret;
  18066. };
  18067. }
  18068. })();
  18069. function switchCaseArgumentOrder(likelyArgumentCount) {
  18070. var ret = [likelyArgumentCount];
  18071. var min = Math.max(0, likelyArgumentCount - 1 - 5);
  18072. for(var i = likelyArgumentCount - 1; i >= min; --i) {
  18073. if (i === likelyArgumentCount) continue;
  18074. ret.push(i);
  18075. }
  18076. for(var i = likelyArgumentCount + 1; i <= 5; ++i) {
  18077. ret.push(i);
  18078. }
  18079. return ret;
  18080. }
  18081. function parameterDeclaration(parameterCount) {
  18082. var ret = new Array(parameterCount);
  18083. for(var i = 0; i < ret.length; ++i) {
  18084. ret[i] = "_arg" + i;
  18085. }
  18086. return ret.join(", ");
  18087. }
  18088. function parameterCount(fn) {
  18089. if (typeof fn.length === "number") {
  18090. return Math.max(Math.min(fn.length, 1023 + 1), 0);
  18091. }
  18092. return 0;
  18093. }
  18094. var rident = /^[a-z$_][a-z$_0-9]*$/i;
  18095. function propertyAccess(id) {
  18096. if (rident.test(id)) {
  18097. return "." + id;
  18098. }
  18099. else return "['" + id.replace(/(['\\])/g, "\\$1") + "']";
  18100. }
  18101. function makeNodePromisifiedEval(callback, receiver, originalName, fn) {
  18102. var newParameterCount = Math.max(0, parameterCount(fn) - 1);
  18103. var argumentOrder = switchCaseArgumentOrder(newParameterCount);
  18104. var callbackName = (typeof originalName === "string" ?
  18105. originalName + "Async" :
  18106. "promisified");
  18107. function generateCallForArgumentCount(count) {
  18108. var args = new Array(count);
  18109. for (var i = 0, len = args.length; i < len; ++i) {
  18110. args[i] = "arguments[" + i + "]";
  18111. }
  18112. var comma = count > 0 ? "," : "";
  18113. if (typeof callback === "string" &&
  18114. receiver === THIS) {
  18115. return "this" + propertyAccess(callback) + "("+args.join(",") +
  18116. comma +" fn);"+
  18117. "break;";
  18118. }
  18119. return (receiver === void 0
  18120. ? "callback("+args.join(",")+ comma +" fn);"
  18121. : "callback.call("+(receiver === THIS
  18122. ? "this"
  18123. : "receiver")+", "+args.join(",") + comma + " fn);") +
  18124. "break;";
  18125. }
  18126. if (!rident.test(callbackName)) {
  18127. callbackName = "promisified";
  18128. }
  18129. function generateArgumentSwitchCase() {
  18130. var ret = "";
  18131. for(var i = 0; i < argumentOrder.length; ++i) {
  18132. ret += "case " + argumentOrder[i] +":" +
  18133. generateCallForArgumentCount(argumentOrder[i]);
  18134. }
  18135. ret += "default: var args = new Array(len + 1);" +
  18136. "var i = 0;" +
  18137. "for (var i = 0; i < len; ++i) { " +
  18138. " args[i] = arguments[i];" +
  18139. "}" +
  18140. "args[i] = fn;" +
  18141. (typeof callback === "string"
  18142. ? "this" + propertyAccess(callback) + ".apply("
  18143. : "callback.apply(") +
  18144. (receiver === THIS ? "this" : "receiver") +
  18145. ", args); break;";
  18146. return ret;
  18147. }
  18148. return new Function("Promise", "callback", "receiver",
  18149. "withAppended", "maybeWrapAsError", "nodebackForPromise",
  18150. "INTERNAL",
  18151. "var ret = function " + callbackName +
  18152. "(" + parameterDeclaration(newParameterCount) + ") {\"use strict\";" +
  18153. "var len = arguments.length;" +
  18154. "var promise = new Promise(INTERNAL);"+
  18155. "promise._setTrace(void 0);" +
  18156. "var fn = nodebackForPromise(promise);"+
  18157. "try {" +
  18158. "switch(len) {" +
  18159. generateArgumentSwitchCase() +
  18160. "}" +
  18161. "}" +
  18162. "catch(e){ " +
  18163. "var wrapped = maybeWrapAsError(e);" +
  18164. "promise._attachExtraTrace(wrapped);" +
  18165. "promise._reject(wrapped);" +
  18166. "}" +
  18167. "return promise;" +
  18168. "" +
  18169. "}; ret.__isPromisified__ = true; return ret;"
  18170. )(Promise, callback, receiver, withAppended,
  18171. maybeWrapAsError, nodebackForPromise, INTERNAL);
  18172. }
  18173. function makeNodePromisifiedClosure(callback, receiver) {
  18174. function promisified() {
  18175. var _receiver = receiver;
  18176. if (receiver === THIS) _receiver = this;
  18177. if (typeof callback === "string") {
  18178. callback = _receiver[callback];
  18179. }
  18180. var promise = new Promise(INTERNAL);
  18181. promise._setTrace(void 0);
  18182. var fn = nodebackForPromise(promise);
  18183. try {
  18184. callback.apply(_receiver, withAppended(arguments, fn));
  18185. }
  18186. catch(e) {
  18187. var wrapped = maybeWrapAsError(e);
  18188. promise._attachExtraTrace(wrapped);
  18189. promise._reject(wrapped);
  18190. }
  18191. return promise;
  18192. }
  18193. promisified.__isPromisified__ = true;
  18194. return promisified;
  18195. }
  18196. var makeNodePromisified = canEvaluate
  18197. ? makeNodePromisifiedEval
  18198. : makeNodePromisifiedClosure;
  18199. function _promisify(callback, receiver, isAll) {
  18200. if (isAll) {
  18201. var methods = inheritedMethods(callback);
  18202. for (var i = 0, len = methods.length; i < len; i+= 2) {
  18203. var key = methods[i];
  18204. var fn = methods[i+1];
  18205. var promisifiedKey = key + "Async";
  18206. callback[promisifiedKey] = makeNodePromisified(key, THIS, key, fn);
  18207. }
  18208. util.toFastProperties(callback);
  18209. return callback;
  18210. }
  18211. else {
  18212. return makeNodePromisified(callback, receiver, void 0, callback);
  18213. }
  18214. }
  18215. Promise.promisify = function Promise$Promisify(fn, receiver) {
  18216. if (typeof fn === "object" && fn !== null) {
  18217. deprecated("Promise.promisify for promisifying entire objects is deprecated. Use Promise.promisifyAll instead.");
  18218. return _promisify(fn, receiver, true);
  18219. }
  18220. if (typeof fn !== "function") {
  18221. throw new TypeError("fn must be a function");
  18222. }
  18223. if (isPromisified(fn)) {
  18224. return fn;
  18225. }
  18226. return _promisify(
  18227. fn,
  18228. arguments.length < 2 ? THIS : receiver,
  18229. false);
  18230. };
  18231. Promise.promisifyAll = function Promise$PromisifyAll(target) {
  18232. if (typeof target !== "function" && typeof target !== "object") {
  18233. throw new TypeError("the target of promisifyAll must be an object or a function");
  18234. }
  18235. return _promisify(target, void 0, true);
  18236. };
  18237. };
  18238. /***/ },
  18239. /* 129 */
  18240. /***/ function(module, exports, __webpack_require__) {
  18241. /**
  18242. * Copyright (c) 2014 Petka Antonov
  18243. *
  18244. * Permission is hereby granted, free of charge, to any person obtaining a copy
  18245. * of this software and associated documentation files (the "Software"), to deal
  18246. * in the Software without restriction, including without limitation the rights
  18247. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  18248. * copies of the Software, and to permit persons to whom the Software is
  18249. * furnished to do so, subject to the following conditions:</p>
  18250. *
  18251. * The above copyright notice and this permission notice shall be included in
  18252. * all copies or substantial portions of the Software.
  18253. *
  18254. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18255. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18256. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18257. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18258. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18259. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18260. * THE SOFTWARE.
  18261. *
  18262. */
  18263. "use strict";
  18264. module.exports = function(Promise, PromiseArray) {
  18265. var PropertiesPromiseArray = __webpack_require__(162)(
  18266. Promise, PromiseArray);
  18267. var util = __webpack_require__(108);
  18268. var apiRejection = __webpack_require__(115)(Promise);
  18269. var isObject = util.isObject;
  18270. function Promise$_Props(promises, useBound) {
  18271. var ret;
  18272. var castValue = Promise._cast(promises, void 0);
  18273. if (!isObject(castValue)) {
  18274. return apiRejection("cannot await properties of a non-object");
  18275. }
  18276. else if (castValue instanceof Promise) {
  18277. ret = castValue._then(Promise.props, void 0, void 0,
  18278. void 0, void 0);
  18279. }
  18280. else {
  18281. ret = new PropertiesPromiseArray(
  18282. castValue,
  18283. useBound === true && castValue._isBound()
  18284. ? castValue._boundTo
  18285. : void 0
  18286. ).promise();
  18287. useBound = false;
  18288. }
  18289. if (useBound === true && castValue._isBound()) {
  18290. ret._setBoundTo(castValue._boundTo);
  18291. }
  18292. return ret;
  18293. }
  18294. Promise.prototype.props = function Promise$props() {
  18295. return Promise$_Props(this, true);
  18296. };
  18297. Promise.props = function Promise$Props(promises) {
  18298. return Promise$_Props(promises, false);
  18299. };
  18300. };
  18301. /***/ },
  18302. /* 130 */
  18303. /***/ function(module, exports, __webpack_require__) {
  18304. /**
  18305. * Copyright (c) 2014 Petka Antonov
  18306. *
  18307. * Permission is hereby granted, free of charge, to any person obtaining a copy
  18308. * of this software and associated documentation files (the "Software"), to deal
  18309. * in the Software without restriction, including without limitation the rights
  18310. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  18311. * copies of the Software, and to permit persons to whom the Software is
  18312. * furnished to do so, subject to the following conditions:</p>
  18313. *
  18314. * The above copyright notice and this permission notice shall be included in
  18315. * all copies or substantial portions of the Software.
  18316. *
  18317. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18318. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18319. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18320. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18321. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18322. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18323. * THE SOFTWARE.
  18324. *
  18325. */
  18326. "use strict";
  18327. module.exports = function(
  18328. Promise, Promise$_CreatePromiseArray,
  18329. PromiseArray, apiRejection, INTERNAL) {
  18330. function Reduction(callback, index, accum, items, receiver) {
  18331. this.promise = new Promise(INTERNAL);
  18332. this.index = index;
  18333. this.length = items.length;
  18334. this.items = items;
  18335. this.callback = callback;
  18336. this.receiver = receiver;
  18337. this.accum = accum;
  18338. }
  18339. Reduction.prototype.reject = function Reduction$reject(e) {
  18340. this.promise._reject(e);
  18341. };
  18342. Reduction.prototype.fulfill = function Reduction$fulfill(value, index) {
  18343. this.accum = value;
  18344. this.index = index + 1;
  18345. this.iterate();
  18346. };
  18347. Reduction.prototype.iterate = function Reduction$iterate() {
  18348. var i = this.index;
  18349. var len = this.length;
  18350. var items = this.items;
  18351. var result = this.accum;
  18352. var receiver = this.receiver;
  18353. var callback = this.callback;
  18354. for (; i < len; ++i) {
  18355. result = callback.call(receiver, result, items[i], i, len);
  18356. result = Promise._cast(result, void 0);
  18357. if (result instanceof Promise) {
  18358. result._then(
  18359. this.fulfill, this.reject, void 0, this, i);
  18360. return;
  18361. }
  18362. }
  18363. this.promise._fulfill(result);
  18364. };
  18365. function Promise$_reducer(fulfilleds, initialValue) {
  18366. var fn = this;
  18367. var receiver = void 0;
  18368. if (typeof fn !== "function") {
  18369. receiver = fn.receiver;
  18370. fn = fn.fn;
  18371. }
  18372. var len = fulfilleds.length;
  18373. var accum = void 0;
  18374. var startIndex = 0;
  18375. if (initialValue !== void 0) {
  18376. accum = initialValue;
  18377. startIndex = 0;
  18378. }
  18379. else {
  18380. startIndex = 1;
  18381. if (len > 0) accum = fulfilleds[0];
  18382. }
  18383. var i = startIndex;
  18384. if (i >= len) {
  18385. return accum;
  18386. }
  18387. var reduction = new Reduction(fn, i, accum, fulfilleds, receiver);
  18388. reduction.iterate();
  18389. return reduction.promise;
  18390. }
  18391. function Promise$_unpackReducer(fulfilleds) {
  18392. var fn = this.fn;
  18393. var initialValue = this.initialValue;
  18394. return Promise$_reducer.call(fn, fulfilleds, initialValue);
  18395. }
  18396. function Promise$_slowReduce(
  18397. promises, fn, initialValue, useBound) {
  18398. return initialValue._then(function(initialValue) {
  18399. return Promise$_Reduce(
  18400. promises, fn, initialValue, useBound);
  18401. }, void 0, void 0, void 0, void 0);
  18402. }
  18403. function Promise$_Reduce(promises, fn, initialValue, useBound) {
  18404. if (typeof fn !== "function") {
  18405. return apiRejection("fn must be a function");
  18406. }
  18407. if (useBound === true && promises._isBound()) {
  18408. fn = {
  18409. fn: fn,
  18410. receiver: promises._boundTo
  18411. };
  18412. }
  18413. if (initialValue !== void 0) {
  18414. if (initialValue instanceof Promise) {
  18415. if (initialValue.isFulfilled()) {
  18416. initialValue = initialValue._settledValue;
  18417. }
  18418. else {
  18419. return Promise$_slowReduce(promises,
  18420. fn, initialValue, useBound);
  18421. }
  18422. }
  18423. return Promise$_CreatePromiseArray(promises, PromiseArray,
  18424. useBound === true && promises._isBound()
  18425. ? promises._boundTo
  18426. : void 0)
  18427. .promise()
  18428. ._then(Promise$_unpackReducer, void 0, void 0, {
  18429. fn: fn,
  18430. initialValue: initialValue
  18431. }, void 0);
  18432. }
  18433. return Promise$_CreatePromiseArray(promises, PromiseArray,
  18434. useBound === true && promises._isBound()
  18435. ? promises._boundTo
  18436. : void 0).promise()
  18437. ._then(Promise$_reducer, void 0, void 0, fn, void 0);
  18438. }
  18439. Promise.reduce = function Promise$Reduce(promises, fn, initialValue) {
  18440. return Promise$_Reduce(promises, fn, initialValue, false);
  18441. };
  18442. Promise.prototype.reduce = function Promise$reduce(fn, initialValue) {
  18443. return Promise$_Reduce(this, fn, initialValue, true);
  18444. };
  18445. };
  18446. /***/ },
  18447. /* 131 */
  18448. /***/ function(module, exports, __webpack_require__) {
  18449. /**
  18450. * Copyright (c) 2014 Petka Antonov
  18451. *
  18452. * Permission is hereby granted, free of charge, to any person obtaining a copy
  18453. * of this software and associated documentation files (the "Software"), to deal
  18454. * in the Software without restriction, including without limitation the rights
  18455. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  18456. * copies of the Software, and to permit persons to whom the Software is
  18457. * furnished to do so, subject to the following conditions:</p>
  18458. *
  18459. * The above copyright notice and this permission notice shall be included in
  18460. * all copies or substantial portions of the Software.
  18461. *
  18462. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18463. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18464. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18465. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18466. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18467. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18468. * THE SOFTWARE.
  18469. *
  18470. */
  18471. "use strict";
  18472. module.exports =
  18473. function(Promise, Promise$_CreatePromiseArray, PromiseArray) {
  18474. var SettledPromiseArray = __webpack_require__(163)(
  18475. Promise, PromiseArray);
  18476. function Promise$_Settle(promises, useBound) {
  18477. return Promise$_CreatePromiseArray(
  18478. promises,
  18479. SettledPromiseArray,
  18480. useBound === true && promises._isBound()
  18481. ? promises._boundTo
  18482. : void 0
  18483. ).promise();
  18484. }
  18485. Promise.settle = function Promise$Settle(promises) {
  18486. return Promise$_Settle(promises, false);
  18487. };
  18488. Promise.prototype.settle = function Promise$settle() {
  18489. return Promise$_Settle(this, true);
  18490. };
  18491. };
  18492. /***/ },
  18493. /* 132 */
  18494. /***/ function(module, exports, __webpack_require__) {
  18495. /**
  18496. * Copyright (c) 2014 Petka Antonov
  18497. *
  18498. * Permission is hereby granted, free of charge, to any person obtaining a copy
  18499. * of this software and associated documentation files (the "Software"), to deal
  18500. * in the Software without restriction, including without limitation the rights
  18501. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  18502. * copies of the Software, and to permit persons to whom the Software is
  18503. * furnished to do so, subject to the following conditions:</p>
  18504. *
  18505. * The above copyright notice and this permission notice shall be included in
  18506. * all copies or substantial portions of the Software.
  18507. *
  18508. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18509. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18510. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18511. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18512. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18513. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18514. * THE SOFTWARE.
  18515. *
  18516. */
  18517. "use strict";
  18518. module.exports =
  18519. function(Promise, Promise$_CreatePromiseArray, PromiseArray, apiRejection) {
  18520. var SomePromiseArray = __webpack_require__(160)(PromiseArray);
  18521. function Promise$_Some(promises, howMany, useBound) {
  18522. if ((howMany | 0) !== howMany || howMany < 0) {
  18523. return apiRejection("expecting a positive integer");
  18524. }
  18525. var ret = Promise$_CreatePromiseArray(
  18526. promises,
  18527. SomePromiseArray,
  18528. useBound === true && promises._isBound()
  18529. ? promises._boundTo
  18530. : void 0
  18531. );
  18532. var promise = ret.promise();
  18533. if (promise.isRejected()) {
  18534. return promise;
  18535. }
  18536. ret.setHowMany(howMany);
  18537. ret.init();
  18538. return promise;
  18539. }
  18540. Promise.some = function Promise$Some(promises, howMany) {
  18541. return Promise$_Some(promises, howMany, false);
  18542. };
  18543. Promise.prototype.some = function Promise$some(count) {
  18544. return Promise$_Some(this, count, true);
  18545. };
  18546. };
  18547. /***/ },
  18548. /* 133 */
  18549. /***/ function(module, exports, __webpack_require__) {
  18550. /**
  18551. * Copyright (c) 2014 Petka Antonov
  18552. *
  18553. * Permission is hereby granted, free of charge, to any person obtaining a copy
  18554. * of this software and associated documentation files (the "Software"), to deal
  18555. * in the Software without restriction, including without limitation the rights
  18556. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  18557. * copies of the Software, and to permit persons to whom the Software is
  18558. * furnished to do so, subject to the following conditions:</p>
  18559. *
  18560. * The above copyright notice and this permission notice shall be included in
  18561. * all copies or substantial portions of the Software.
  18562. *
  18563. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18564. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18565. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18566. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18567. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18568. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18569. * THE SOFTWARE.
  18570. *
  18571. */
  18572. "use strict";
  18573. module.exports = function(Promise, isPromiseArrayProxy) {
  18574. var util = __webpack_require__(108);
  18575. var async = __webpack_require__(109);
  18576. var errors = __webpack_require__(110);
  18577. var tryCatch1 = util.tryCatch1;
  18578. var errorObj = util.errorObj;
  18579. Promise.prototype.progressed = function Promise$progressed(handler) {
  18580. return this._then(void 0, void 0, handler, void 0, void 0);
  18581. };
  18582. Promise.prototype._progress = function Promise$_progress(progressValue) {
  18583. if (this._isFollowingOrFulfilledOrRejected()) return;
  18584. this._progressUnchecked(progressValue);
  18585. };
  18586. Promise.prototype._progressHandlerAt =
  18587. function Promise$_progressHandlerAt(index) {
  18588. if (index === 0) return this._progressHandler0;
  18589. return this[index + 2 - 5];
  18590. };
  18591. Promise.prototype._doProgressWith =
  18592. function Promise$_doProgressWith(progression) {
  18593. var progressValue = progression.value;
  18594. var handler = progression.handler;
  18595. var promise = progression.promise;
  18596. var receiver = progression.receiver;
  18597. this._pushContext();
  18598. var ret = tryCatch1(handler, receiver, progressValue);
  18599. this._popContext();
  18600. if (ret === errorObj) {
  18601. if (ret.e != null &&
  18602. ret.e.name !== "StopProgressPropagation") {
  18603. var trace = errors.canAttach(ret.e)
  18604. ? ret.e : new Error(ret.e + "");
  18605. promise._attachExtraTrace(trace);
  18606. promise._progress(ret.e);
  18607. }
  18608. }
  18609. else if (ret instanceof Promise) {
  18610. ret._then(promise._progress, null, null, promise, void 0);
  18611. }
  18612. else {
  18613. promise._progress(ret);
  18614. }
  18615. };
  18616. Promise.prototype._progressUnchecked =
  18617. function Promise$_progressUnchecked(progressValue) {
  18618. if (!this.isPending()) return;
  18619. var len = this._length();
  18620. var progress = this._progress;
  18621. for (var i = 0; i < len; i += 5) {
  18622. var handler = this._progressHandlerAt(i);
  18623. var promise = this._promiseAt(i);
  18624. if (!(promise instanceof Promise)) {
  18625. var receiver = this._receiverAt(i);
  18626. if (typeof handler === "function") {
  18627. handler.call(receiver, progressValue, promise);
  18628. }
  18629. else if (receiver instanceof Promise && receiver._isProxied()) {
  18630. receiver._progressUnchecked(progressValue);
  18631. }
  18632. else if (isPromiseArrayProxy(receiver, promise)) {
  18633. receiver._promiseProgressed(progressValue, promise);
  18634. }
  18635. continue;
  18636. }
  18637. if (typeof handler === "function") {
  18638. async.invoke(this._doProgressWith, this, {
  18639. handler: handler,
  18640. promise: promise,
  18641. receiver: this._receiverAt(i),
  18642. value: progressValue
  18643. });
  18644. }
  18645. else {
  18646. async.invoke(progress, promise, progressValue);
  18647. }
  18648. }
  18649. };
  18650. };
  18651. /***/ },
  18652. /* 134 */
  18653. /***/ function(module, exports, __webpack_require__) {
  18654. /**
  18655. * Copyright (c) 2014 Petka Antonov
  18656. *
  18657. * Permission is hereby granted, free of charge, to any person obtaining a copy
  18658. * of this software and associated documentation files (the "Software"), to deal
  18659. * in the Software without restriction, including without limitation the rights
  18660. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  18661. * copies of the Software, and to permit persons to whom the Software is
  18662. * furnished to do so, subject to the following conditions:</p>
  18663. *
  18664. * The above copyright notice and this permission notice shall be included in
  18665. * all copies or substantial portions of the Software.
  18666. *
  18667. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18668. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18669. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18670. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18671. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18672. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18673. * THE SOFTWARE.
  18674. *
  18675. */
  18676. "use strict";
  18677. module.exports = function(Promise, INTERNAL) {
  18678. var errors = __webpack_require__(110);
  18679. var async = __webpack_require__(109);
  18680. var CancellationError = errors.CancellationError;
  18681. Promise.prototype._cancel = function Promise$_cancel() {
  18682. if (!this.isCancellable()) return this;
  18683. var parent;
  18684. var promiseToReject = this;
  18685. while ((parent = promiseToReject._cancellationParent) !== void 0 &&
  18686. parent.isCancellable()) {
  18687. promiseToReject = parent;
  18688. }
  18689. var err = new CancellationError();
  18690. promiseToReject._attachExtraTrace(err);
  18691. promiseToReject._rejectUnchecked(err);
  18692. };
  18693. Promise.prototype.cancel = function Promise$cancel() {
  18694. if (!this.isCancellable()) return this;
  18695. async.invokeLater(this._cancel, this, void 0);
  18696. return this;
  18697. };
  18698. Promise.prototype.cancellable = function Promise$cancellable() {
  18699. if (this._cancellable()) return this;
  18700. this._setCancellable();
  18701. this._cancellationParent = void 0;
  18702. return this;
  18703. };
  18704. Promise.prototype.uncancellable = function Promise$uncancellable() {
  18705. var ret = new Promise(INTERNAL);
  18706. ret._setTrace(this);
  18707. ret._follow(this);
  18708. ret._unsetCancellable();
  18709. if (this._isBound()) ret._setBoundTo(this._boundTo);
  18710. return ret;
  18711. };
  18712. Promise.prototype.fork =
  18713. function Promise$fork(didFulfill, didReject, didProgress) {
  18714. var ret = this._then(didFulfill, didReject, didProgress,
  18715. void 0, void 0);
  18716. ret._setCancellable();
  18717. ret._cancellationParent = void 0;
  18718. return ret;
  18719. };
  18720. };
  18721. /***/ },
  18722. /* 135 */
  18723. /***/ function(module, exports, __webpack_require__) {
  18724. module.exports = function (Buffer) {
  18725. //prototype class for hash functions
  18726. function Hash (blockSize, finalSize) {
  18727. this._block = new Buffer(blockSize) //new Uint32Array(blockSize/4)
  18728. this._finalSize = finalSize
  18729. this._blockSize = blockSize
  18730. this._len = 0
  18731. this._s = 0
  18732. }
  18733. Hash.prototype.init = function () {
  18734. this._s = 0
  18735. this._len = 0
  18736. }
  18737. Hash.prototype.update = function (data, enc) {
  18738. if ("string" === typeof data) {
  18739. enc = enc || "utf8"
  18740. data = new Buffer(data, enc)
  18741. }
  18742. var l = this._len += data.length
  18743. var s = this._s = (this._s || 0)
  18744. var f = 0
  18745. var buffer = this._block
  18746. while (s < l) {
  18747. var t = Math.min(data.length, f + this._blockSize - (s % this._blockSize))
  18748. var ch = (t - f)
  18749. for (var i = 0; i < ch; i++) {
  18750. buffer[(s % this._blockSize) + i] = data[i + f]
  18751. }
  18752. s += ch
  18753. f += ch
  18754. if ((s % this._blockSize) === 0) {
  18755. this._update(buffer)
  18756. }
  18757. }
  18758. this._s = s
  18759. return this
  18760. }
  18761. Hash.prototype.digest = function (enc) {
  18762. // Suppose the length of the message M, in bits, is l
  18763. var l = this._len * 8
  18764. // Append the bit 1 to the end of the message
  18765. this._block[this._len % this._blockSize] = 0x80
  18766. // and then k zero bits, where k is the smallest non-negative solution to the equation (l + 1 + k) === finalSize mod blockSize
  18767. this._block.fill(0, this._len % this._blockSize + 1)
  18768. if (l % (this._blockSize * 8) >= this._finalSize * 8) {
  18769. this._update(this._block)
  18770. this._block.fill(0)
  18771. }
  18772. // to this append the block which is equal to the number l written in binary
  18773. // TODO: handle case where l is > Math.pow(2, 29)
  18774. this._block.writeInt32BE(l, this._blockSize - 4)
  18775. var hash = this._update(this._block) || this._hash()
  18776. return enc ? hash.toString(enc) : hash
  18777. }
  18778. Hash.prototype._update = function () {
  18779. throw new Error('_update must be implemented by subclass')
  18780. }
  18781. return Hash
  18782. }
  18783. /***/ },
  18784. /* 136 */
  18785. /***/ function(module, exports, __webpack_require__) {
  18786. /*
  18787. * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
  18788. * in FIPS PUB 180-1
  18789. * Version 2.1a Copyright Paul Johnston 2000 - 2002.
  18790. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  18791. * Distributed under the BSD License
  18792. * See http://pajhome.org.uk/crypt/md5 for details.
  18793. */
  18794. var inherits = __webpack_require__(79).inherits
  18795. module.exports = function (Buffer, Hash) {
  18796. var A = 0|0
  18797. var B = 4|0
  18798. var C = 8|0
  18799. var D = 12|0
  18800. var E = 16|0
  18801. var W = new (typeof Int32Array === 'undefined' ? Array : Int32Array)(80)
  18802. var POOL = []
  18803. function Sha1 () {
  18804. if(POOL.length)
  18805. return POOL.pop().init()
  18806. if(!(this instanceof Sha1)) return new Sha1()
  18807. this._w = W
  18808. Hash.call(this, 16*4, 14*4)
  18809. this._h = null
  18810. this.init()
  18811. }
  18812. inherits(Sha1, Hash)
  18813. Sha1.prototype.init = function () {
  18814. this._a = 0x67452301
  18815. this._b = 0xefcdab89
  18816. this._c = 0x98badcfe
  18817. this._d = 0x10325476
  18818. this._e = 0xc3d2e1f0
  18819. Hash.prototype.init.call(this)
  18820. return this
  18821. }
  18822. Sha1.prototype._POOL = POOL
  18823. Sha1.prototype._update = function (X) {
  18824. var a, b, c, d, e, _a, _b, _c, _d, _e
  18825. a = _a = this._a
  18826. b = _b = this._b
  18827. c = _c = this._c
  18828. d = _d = this._d
  18829. e = _e = this._e
  18830. var w = this._w
  18831. for(var j = 0; j < 80; j++) {
  18832. var W = w[j] = j < 16 ? X.readInt32BE(j*4)
  18833. : rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1)
  18834. var t = add(
  18835. add(rol(a, 5), sha1_ft(j, b, c, d)),
  18836. add(add(e, W), sha1_kt(j))
  18837. )
  18838. e = d
  18839. d = c
  18840. c = rol(b, 30)
  18841. b = a
  18842. a = t
  18843. }
  18844. this._a = add(a, _a)
  18845. this._b = add(b, _b)
  18846. this._c = add(c, _c)
  18847. this._d = add(d, _d)
  18848. this._e = add(e, _e)
  18849. }
  18850. Sha1.prototype._hash = function () {
  18851. if(POOL.length < 100) POOL.push(this)
  18852. var H = new Buffer(20)
  18853. //console.log(this._a|0, this._b|0, this._c|0, this._d|0, this._e|0)
  18854. H.writeInt32BE(this._a|0, A)
  18855. H.writeInt32BE(this._b|0, B)
  18856. H.writeInt32BE(this._c|0, C)
  18857. H.writeInt32BE(this._d|0, D)
  18858. H.writeInt32BE(this._e|0, E)
  18859. return H
  18860. }
  18861. /*
  18862. * Perform the appropriate triplet combination function for the current
  18863. * iteration
  18864. */
  18865. function sha1_ft(t, b, c, d) {
  18866. if(t < 20) return (b & c) | ((~b) & d);
  18867. if(t < 40) return b ^ c ^ d;
  18868. if(t < 60) return (b & c) | (b & d) | (c & d);
  18869. return b ^ c ^ d;
  18870. }
  18871. /*
  18872. * Determine the appropriate additive constant for the current iteration
  18873. */
  18874. function sha1_kt(t) {
  18875. return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 :
  18876. (t < 60) ? -1894007588 : -899497514;
  18877. }
  18878. /*
  18879. * Add integers, wrapping at 2^32. This uses 16-bit operations internally
  18880. * to work around bugs in some JS interpreters.
  18881. * //dominictarr: this is 10 years old, so maybe this can be dropped?)
  18882. *
  18883. */
  18884. function add(x, y) {
  18885. return (x + y ) | 0
  18886. //lets see how this goes on testling.
  18887. // var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  18888. // var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  18889. // return (msw << 16) | (lsw & 0xFFFF);
  18890. }
  18891. /*
  18892. * Bitwise rotate a 32-bit number to the left.
  18893. */
  18894. function rol(num, cnt) {
  18895. return (num << cnt) | (num >>> (32 - cnt));
  18896. }
  18897. return Sha1
  18898. }
  18899. /***/ },
  18900. /* 137 */
  18901. /***/ function(module, exports, __webpack_require__) {
  18902. /**
  18903. * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
  18904. * in FIPS 180-2
  18905. * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
  18906. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  18907. *
  18908. */
  18909. var inherits = __webpack_require__(79).inherits
  18910. module.exports = function (Buffer, Hash) {
  18911. var K = [
  18912. 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
  18913. 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
  18914. 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
  18915. 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
  18916. 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
  18917. 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
  18918. 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
  18919. 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
  18920. 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
  18921. 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
  18922. 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
  18923. 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
  18924. 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
  18925. 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
  18926. 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
  18927. 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
  18928. ]
  18929. var W = new Array(64)
  18930. function Sha256() {
  18931. this.init()
  18932. this._w = W //new Array(64)
  18933. Hash.call(this, 16*4, 14*4)
  18934. }
  18935. inherits(Sha256, Hash)
  18936. Sha256.prototype.init = function () {
  18937. this._a = 0x6a09e667|0
  18938. this._b = 0xbb67ae85|0
  18939. this._c = 0x3c6ef372|0
  18940. this._d = 0xa54ff53a|0
  18941. this._e = 0x510e527f|0
  18942. this._f = 0x9b05688c|0
  18943. this._g = 0x1f83d9ab|0
  18944. this._h = 0x5be0cd19|0
  18945. this._len = this._s = 0
  18946. return this
  18947. }
  18948. function S (X, n) {
  18949. return (X >>> n) | (X << (32 - n));
  18950. }
  18951. function R (X, n) {
  18952. return (X >>> n);
  18953. }
  18954. function Ch (x, y, z) {
  18955. return ((x & y) ^ ((~x) & z));
  18956. }
  18957. function Maj (x, y, z) {
  18958. return ((x & y) ^ (x & z) ^ (y & z));
  18959. }
  18960. function Sigma0256 (x) {
  18961. return (S(x, 2) ^ S(x, 13) ^ S(x, 22));
  18962. }
  18963. function Sigma1256 (x) {
  18964. return (S(x, 6) ^ S(x, 11) ^ S(x, 25));
  18965. }
  18966. function Gamma0256 (x) {
  18967. return (S(x, 7) ^ S(x, 18) ^ R(x, 3));
  18968. }
  18969. function Gamma1256 (x) {
  18970. return (S(x, 17) ^ S(x, 19) ^ R(x, 10));
  18971. }
  18972. Sha256.prototype._update = function(M) {
  18973. var W = this._w
  18974. var a, b, c, d, e, f, g, h
  18975. var T1, T2
  18976. a = this._a | 0
  18977. b = this._b | 0
  18978. c = this._c | 0
  18979. d = this._d | 0
  18980. e = this._e | 0
  18981. f = this._f | 0
  18982. g = this._g | 0
  18983. h = this._h | 0
  18984. for (var j = 0; j < 64; j++) {
  18985. var w = W[j] = j < 16
  18986. ? M.readInt32BE(j * 4)
  18987. : Gamma1256(W[j - 2]) + W[j - 7] + Gamma0256(W[j - 15]) + W[j - 16]
  18988. T1 = h + Sigma1256(e) + Ch(e, f, g) + K[j] + w
  18989. T2 = Sigma0256(a) + Maj(a, b, c);
  18990. h = g; g = f; f = e; e = d + T1; d = c; c = b; b = a; a = T1 + T2;
  18991. }
  18992. this._a = (a + this._a) | 0
  18993. this._b = (b + this._b) | 0
  18994. this._c = (c + this._c) | 0
  18995. this._d = (d + this._d) | 0
  18996. this._e = (e + this._e) | 0
  18997. this._f = (f + this._f) | 0
  18998. this._g = (g + this._g) | 0
  18999. this._h = (h + this._h) | 0
  19000. };
  19001. Sha256.prototype._hash = function () {
  19002. var H = new Buffer(32)
  19003. H.writeInt32BE(this._a, 0)
  19004. H.writeInt32BE(this._b, 4)
  19005. H.writeInt32BE(this._c, 8)
  19006. H.writeInt32BE(this._d, 12)
  19007. H.writeInt32BE(this._e, 16)
  19008. H.writeInt32BE(this._f, 20)
  19009. H.writeInt32BE(this._g, 24)
  19010. H.writeInt32BE(this._h, 28)
  19011. return H
  19012. }
  19013. return Sha256
  19014. }
  19015. /***/ },
  19016. /* 138 */
  19017. /***/ function(module, exports, __webpack_require__) {
  19018. var inherits = __webpack_require__(79).inherits
  19019. module.exports = function (Buffer, Hash) {
  19020. var K = [
  19021. 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
  19022. 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
  19023. 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
  19024. 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
  19025. 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
  19026. 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
  19027. 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
  19028. 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
  19029. 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
  19030. 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
  19031. 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
  19032. 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
  19033. 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
  19034. 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
  19035. 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
  19036. 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
  19037. 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
  19038. 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
  19039. 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
  19040. 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
  19041. 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
  19042. 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
  19043. 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
  19044. 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
  19045. 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
  19046. 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
  19047. 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
  19048. 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
  19049. 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
  19050. 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
  19051. 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
  19052. 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
  19053. 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
  19054. 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
  19055. 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
  19056. 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
  19057. 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
  19058. 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
  19059. 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
  19060. 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
  19061. ]
  19062. var W = new Array(160)
  19063. function Sha512() {
  19064. this.init()
  19065. this._w = W
  19066. Hash.call(this, 128, 112)
  19067. }
  19068. inherits(Sha512, Hash)
  19069. Sha512.prototype.init = function () {
  19070. this._a = 0x6a09e667|0
  19071. this._b = 0xbb67ae85|0
  19072. this._c = 0x3c6ef372|0
  19073. this._d = 0xa54ff53a|0
  19074. this._e = 0x510e527f|0
  19075. this._f = 0x9b05688c|0
  19076. this._g = 0x1f83d9ab|0
  19077. this._h = 0x5be0cd19|0
  19078. this._al = 0xf3bcc908|0
  19079. this._bl = 0x84caa73b|0
  19080. this._cl = 0xfe94f82b|0
  19081. this._dl = 0x5f1d36f1|0
  19082. this._el = 0xade682d1|0
  19083. this._fl = 0x2b3e6c1f|0
  19084. this._gl = 0xfb41bd6b|0
  19085. this._hl = 0x137e2179|0
  19086. this._len = this._s = 0
  19087. return this
  19088. }
  19089. function S (X, Xl, n) {
  19090. return (X >>> n) | (Xl << (32 - n))
  19091. }
  19092. function Ch (x, y, z) {
  19093. return ((x & y) ^ ((~x) & z));
  19094. }
  19095. function Maj (x, y, z) {
  19096. return ((x & y) ^ (x & z) ^ (y & z));
  19097. }
  19098. Sha512.prototype._update = function(M) {
  19099. var W = this._w
  19100. var a, b, c, d, e, f, g, h
  19101. var al, bl, cl, dl, el, fl, gl, hl
  19102. a = this._a | 0
  19103. b = this._b | 0
  19104. c = this._c | 0
  19105. d = this._d | 0
  19106. e = this._e | 0
  19107. f = this._f | 0
  19108. g = this._g | 0
  19109. h = this._h | 0
  19110. al = this._al | 0
  19111. bl = this._bl | 0
  19112. cl = this._cl | 0
  19113. dl = this._dl | 0
  19114. el = this._el | 0
  19115. fl = this._fl | 0
  19116. gl = this._gl | 0
  19117. hl = this._hl | 0
  19118. for (var i = 0; i < 80; i++) {
  19119. var j = i * 2
  19120. var Wi, Wil
  19121. if (i < 16) {
  19122. Wi = W[j] = M.readInt32BE(j * 4)
  19123. Wil = W[j + 1] = M.readInt32BE(j * 4 + 4)
  19124. } else {
  19125. var x = W[j - 15*2]
  19126. var xl = W[j - 15*2 + 1]
  19127. var gamma0 = S(x, xl, 1) ^ S(x, xl, 8) ^ (x >>> 7)
  19128. var gamma0l = S(xl, x, 1) ^ S(xl, x, 8) ^ S(xl, x, 7)
  19129. x = W[j - 2*2]
  19130. xl = W[j - 2*2 + 1]
  19131. var gamma1 = S(x, xl, 19) ^ S(xl, x, 29) ^ (x >>> 6)
  19132. var gamma1l = S(xl, x, 19) ^ S(x, xl, 29) ^ S(xl, x, 6)
  19133. // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
  19134. var Wi7 = W[j - 7*2]
  19135. var Wi7l = W[j - 7*2 + 1]
  19136. var Wi16 = W[j - 16*2]
  19137. var Wi16l = W[j - 16*2 + 1]
  19138. Wil = gamma0l + Wi7l
  19139. Wi = gamma0 + Wi7 + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0)
  19140. Wil = Wil + gamma1l
  19141. Wi = Wi + gamma1 + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0)
  19142. Wil = Wil + Wi16l
  19143. Wi = Wi + Wi16 + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0)
  19144. W[j] = Wi
  19145. W[j + 1] = Wil
  19146. }
  19147. var maj = Maj(a, b, c)
  19148. var majl = Maj(al, bl, cl)
  19149. var sigma0h = S(a, al, 28) ^ S(al, a, 2) ^ S(al, a, 7)
  19150. var sigma0l = S(al, a, 28) ^ S(a, al, 2) ^ S(a, al, 7)
  19151. var sigma1h = S(e, el, 14) ^ S(e, el, 18) ^ S(el, e, 9)
  19152. var sigma1l = S(el, e, 14) ^ S(el, e, 18) ^ S(e, el, 9)
  19153. // t1 = h + sigma1 + ch + K[i] + W[i]
  19154. var Ki = K[j]
  19155. var Kil = K[j + 1]
  19156. var ch = Ch(e, f, g)
  19157. var chl = Ch(el, fl, gl)
  19158. var t1l = hl + sigma1l
  19159. var t1 = h + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0)
  19160. t1l = t1l + chl
  19161. t1 = t1 + ch + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0)
  19162. t1l = t1l + Kil
  19163. t1 = t1 + Ki + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0)
  19164. t1l = t1l + Wil
  19165. t1 = t1 + Wi + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0)
  19166. // t2 = sigma0 + maj
  19167. var t2l = sigma0l + majl
  19168. var t2 = sigma0h + maj + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0)
  19169. h = g
  19170. hl = gl
  19171. g = f
  19172. gl = fl
  19173. f = e
  19174. fl = el
  19175. el = (dl + t1l) | 0
  19176. e = (d + t1 + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0
  19177. d = c
  19178. dl = cl
  19179. c = b
  19180. cl = bl
  19181. b = a
  19182. bl = al
  19183. al = (t1l + t2l) | 0
  19184. a = (t1 + t2 + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0
  19185. }
  19186. this._al = (this._al + al) | 0
  19187. this._bl = (this._bl + bl) | 0
  19188. this._cl = (this._cl + cl) | 0
  19189. this._dl = (this._dl + dl) | 0
  19190. this._el = (this._el + el) | 0
  19191. this._fl = (this._fl + fl) | 0
  19192. this._gl = (this._gl + gl) | 0
  19193. this._hl = (this._hl + hl) | 0
  19194. this._a = (this._a + a + ((this._al >>> 0) < (al >>> 0) ? 1 : 0)) | 0
  19195. this._b = (this._b + b + ((this._bl >>> 0) < (bl >>> 0) ? 1 : 0)) | 0
  19196. this._c = (this._c + c + ((this._cl >>> 0) < (cl >>> 0) ? 1 : 0)) | 0
  19197. this._d = (this._d + d + ((this._dl >>> 0) < (dl >>> 0) ? 1 : 0)) | 0
  19198. this._e = (this._e + e + ((this._el >>> 0) < (el >>> 0) ? 1 : 0)) | 0
  19199. this._f = (this._f + f + ((this._fl >>> 0) < (fl >>> 0) ? 1 : 0)) | 0
  19200. this._g = (this._g + g + ((this._gl >>> 0) < (gl >>> 0) ? 1 : 0)) | 0
  19201. this._h = (this._h + h + ((this._hl >>> 0) < (hl >>> 0) ? 1 : 0)) | 0
  19202. }
  19203. Sha512.prototype._hash = function () {
  19204. var H = new Buffer(64)
  19205. function writeInt64BE(h, l, offset) {
  19206. H.writeInt32BE(h, offset)
  19207. H.writeInt32BE(l, offset + 4)
  19208. }
  19209. writeInt64BE(this._a, this._al, 0)
  19210. writeInt64BE(this._b, this._bl, 8)
  19211. writeInt64BE(this._c, this._cl, 16)
  19212. writeInt64BE(this._d, this._dl, 24)
  19213. writeInt64BE(this._e, this._el, 32)
  19214. writeInt64BE(this._f, this._fl, 40)
  19215. writeInt64BE(this._g, this._gl, 48)
  19216. writeInt64BE(this._h, this._hl, 56)
  19217. return H
  19218. }
  19219. return Sha512
  19220. }
  19221. /***/ },
  19222. /* 139 */
  19223. /***/ function(module, exports, __webpack_require__) {
  19224. "use strict";
  19225. var config = __webpack_require__(164).config;
  19226. var configure = __webpack_require__(164).configure;
  19227. var objectOrFunction = __webpack_require__(165).objectOrFunction;
  19228. var isFunction = __webpack_require__(165).isFunction;
  19229. var now = __webpack_require__(165).now;
  19230. var all = __webpack_require__(166).all;
  19231. var race = __webpack_require__(167).race;
  19232. var staticResolve = __webpack_require__(168).resolve;
  19233. var staticReject = __webpack_require__(169).reject;
  19234. var asap = __webpack_require__(170).asap;
  19235. var counter = 0;
  19236. config.async = asap; // default async is asap;
  19237. function Promise(resolver) {
  19238. if (!isFunction(resolver)) {
  19239. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  19240. }
  19241. if (!(this instanceof Promise)) {
  19242. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  19243. }
  19244. this._subscribers = [];
  19245. invokeResolver(resolver, this);
  19246. }
  19247. function invokeResolver(resolver, promise) {
  19248. function resolvePromise(value) {
  19249. resolve(promise, value);
  19250. }
  19251. function rejectPromise(reason) {
  19252. reject(promise, reason);
  19253. }
  19254. try {
  19255. resolver(resolvePromise, rejectPromise);
  19256. } catch(e) {
  19257. rejectPromise(e);
  19258. }
  19259. }
  19260. function invokeCallback(settled, promise, callback, detail) {
  19261. var hasCallback = isFunction(callback),
  19262. value, error, succeeded, failed;
  19263. if (hasCallback) {
  19264. try {
  19265. value = callback(detail);
  19266. succeeded = true;
  19267. } catch(e) {
  19268. failed = true;
  19269. error = e;
  19270. }
  19271. } else {
  19272. value = detail;
  19273. succeeded = true;
  19274. }
  19275. if (handleThenable(promise, value)) {
  19276. return;
  19277. } else if (hasCallback && succeeded) {
  19278. resolve(promise, value);
  19279. } else if (failed) {
  19280. reject(promise, error);
  19281. } else if (settled === FULFILLED) {
  19282. resolve(promise, value);
  19283. } else if (settled === REJECTED) {
  19284. reject(promise, value);
  19285. }
  19286. }
  19287. var PENDING = void 0;
  19288. var SEALED = 0;
  19289. var FULFILLED = 1;
  19290. var REJECTED = 2;
  19291. function subscribe(parent, child, onFulfillment, onRejection) {
  19292. var subscribers = parent._subscribers;
  19293. var length = subscribers.length;
  19294. subscribers[length] = child;
  19295. subscribers[length + FULFILLED] = onFulfillment;
  19296. subscribers[length + REJECTED] = onRejection;
  19297. }
  19298. function publish(promise, settled) {
  19299. var child, callback, subscribers = promise._subscribers, detail = promise._detail;
  19300. for (var i = 0; i < subscribers.length; i += 3) {
  19301. child = subscribers[i];
  19302. callback = subscribers[i + settled];
  19303. invokeCallback(settled, child, callback, detail);
  19304. }
  19305. promise._subscribers = null;
  19306. }
  19307. Promise.prototype = {
  19308. constructor: Promise,
  19309. _state: undefined,
  19310. _detail: undefined,
  19311. _subscribers: undefined,
  19312. then: function(onFulfillment, onRejection) {
  19313. var promise = this;
  19314. var thenPromise = new this.constructor(function() {});
  19315. if (this._state) {
  19316. var callbacks = arguments;
  19317. config.async(function invokePromiseCallback() {
  19318. invokeCallback(promise._state, thenPromise, callbacks[promise._state - 1], promise._detail);
  19319. });
  19320. } else {
  19321. subscribe(this, thenPromise, onFulfillment, onRejection);
  19322. }
  19323. return thenPromise;
  19324. },
  19325. 'catch': function(onRejection) {
  19326. return this.then(null, onRejection);
  19327. }
  19328. };
  19329. Promise.all = all;
  19330. Promise.race = race;
  19331. Promise.resolve = staticResolve;
  19332. Promise.reject = staticReject;
  19333. function handleThenable(promise, value) {
  19334. var then = null,
  19335. resolved;
  19336. try {
  19337. if (promise === value) {
  19338. throw new TypeError("A promises callback cannot return that same promise.");
  19339. }
  19340. if (objectOrFunction(value)) {
  19341. then = value.then;
  19342. if (isFunction(then)) {
  19343. then.call(value, function(val) {
  19344. if (resolved) { return true; }
  19345. resolved = true;
  19346. if (value !== val) {
  19347. resolve(promise, val);
  19348. } else {
  19349. fulfill(promise, val);
  19350. }
  19351. }, function(val) {
  19352. if (resolved) { return true; }
  19353. resolved = true;
  19354. reject(promise, val);
  19355. });
  19356. return true;
  19357. }
  19358. }
  19359. } catch (error) {
  19360. if (resolved) { return true; }
  19361. reject(promise, error);
  19362. return true;
  19363. }
  19364. return false;
  19365. }
  19366. function resolve(promise, value) {
  19367. if (promise === value) {
  19368. fulfill(promise, value);
  19369. } else if (!handleThenable(promise, value)) {
  19370. fulfill(promise, value);
  19371. }
  19372. }
  19373. function fulfill(promise, value) {
  19374. if (promise._state !== PENDING) { return; }
  19375. promise._state = SEALED;
  19376. promise._detail = value;
  19377. config.async(publishFulfillment, promise);
  19378. }
  19379. function reject(promise, reason) {
  19380. if (promise._state !== PENDING) { return; }
  19381. promise._state = SEALED;
  19382. promise._detail = reason;
  19383. config.async(publishRejection, promise);
  19384. }
  19385. function publishFulfillment(promise) {
  19386. publish(promise, promise._state = FULFILLED);
  19387. }
  19388. function publishRejection(promise) {
  19389. publish(promise, promise._state = REJECTED);
  19390. }
  19391. exports.Promise = Promise;
  19392. /***/ },
  19393. /* 140 */
  19394. /***/ function(module, exports, __webpack_require__) {
  19395. /* WEBPACK VAR INJECTION */(function(global) {"use strict";
  19396. /*global self*/
  19397. var RSVPPromise = __webpack_require__(139).Promise;
  19398. var isFunction = __webpack_require__(165).isFunction;
  19399. function polyfill() {
  19400. var local;
  19401. if (typeof global !== 'undefined') {
  19402. local = global;
  19403. } else if (typeof window !== 'undefined' && window.document) {
  19404. local = window;
  19405. } else {
  19406. local = self;
  19407. }
  19408. var es6PromiseSupport =
  19409. "Promise" in local &&
  19410. // Some of these methods are missing from
  19411. // Firefox/Chrome experimental implementations
  19412. "resolve" in local.Promise &&
  19413. "reject" in local.Promise &&
  19414. "all" in local.Promise &&
  19415. "race" in local.Promise &&
  19416. // Older version of the spec had a resolver object
  19417. // as the arg rather than a function
  19418. (function() {
  19419. var resolve;
  19420. new local.Promise(function(r) { resolve = r; });
  19421. return isFunction(resolve);
  19422. }());
  19423. if (!es6PromiseSupport) {
  19424. local.Promise = RSVPPromise;
  19425. }
  19426. }
  19427. exports.polyfill = polyfill;
  19428. /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
  19429. /***/ },
  19430. /* 141 */
  19431. /***/ function(module, exports, __webpack_require__) {
  19432. /* WEBPACK VAR INJECTION */(function(process) {// Copyright Joyent, Inc. and other Node contributors.
  19433. //
  19434. // Permission is hereby granted, free of charge, to any person obtaining a
  19435. // copy of this software and associated documentation files (the
  19436. // "Software"), to deal in the Software without restriction, including
  19437. // without limitation the rights to use, copy, modify, merge, publish,
  19438. // distribute, sublicense, and/or sell copies of the Software, and to permit
  19439. // persons to whom the Software is furnished to do so, subject to the
  19440. // following conditions:
  19441. //
  19442. // The above copyright notice and this permission notice shall be included
  19443. // in all copies or substantial portions of the Software.
  19444. //
  19445. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  19446. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19447. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  19448. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  19449. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  19450. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  19451. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  19452. // A bit simpler than readable streams.
  19453. // Implement an async ._write(chunk, cb), and it'll handle all
  19454. // the drain event emission and buffering.
  19455. module.exports = Writable;
  19456. /*<replacement>*/
  19457. var Buffer = __webpack_require__(47).Buffer;
  19458. /*</replacement>*/
  19459. Writable.WritableState = WritableState;
  19460. /*<replacement>*/
  19461. var util = __webpack_require__(178);
  19462. util.inherits = __webpack_require__(177);
  19463. /*</replacement>*/
  19464. var Stream = __webpack_require__(64);
  19465. util.inherits(Writable, Stream);
  19466. function WriteReq(chunk, encoding, cb) {
  19467. this.chunk = chunk;
  19468. this.encoding = encoding;
  19469. this.callback = cb;
  19470. }
  19471. function WritableState(options, stream) {
  19472. var Duplex = __webpack_require__(142);
  19473. options = options || {};
  19474. // the point at which write() starts returning false
  19475. // Note: 0 is a valid value, means that we always return false if
  19476. // the entire buffer is not flushed immediately on write()
  19477. var hwm = options.highWaterMark;
  19478. var defaultHwm = options.objectMode ? 16 : 16 * 1024;
  19479. this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
  19480. // object stream flag to indicate whether or not this stream
  19481. // contains buffers or objects.
  19482. this.objectMode = !!options.objectMode;
  19483. if (stream instanceof Duplex)
  19484. this.objectMode = this.objectMode || !!options.writableObjectMode;
  19485. // cast to ints.
  19486. this.highWaterMark = ~~this.highWaterMark;
  19487. this.needDrain = false;
  19488. // at the start of calling end()
  19489. this.ending = false;
  19490. // when end() has been called, and returned
  19491. this.ended = false;
  19492. // when 'finish' is emitted
  19493. this.finished = false;
  19494. // should we decode strings into buffers before passing to _write?
  19495. // this is here so that some node-core streams can optimize string
  19496. // handling at a lower level.
  19497. var noDecode = options.decodeStrings === false;
  19498. this.decodeStrings = !noDecode;
  19499. // Crypto is kind of old and crusty. Historically, its default string
  19500. // encoding is 'binary' so we have to make this configurable.
  19501. // Everything else in the universe uses 'utf8', though.
  19502. this.defaultEncoding = options.defaultEncoding || 'utf8';
  19503. // not an actual buffer we keep track of, but a measurement
  19504. // of how much we're waiting to get pushed to some underlying
  19505. // socket or file.
  19506. this.length = 0;
  19507. // a flag to see when we're in the middle of a write.
  19508. this.writing = false;
  19509. // when true all writes will be buffered until .uncork() call
  19510. this.corked = 0;
  19511. // a flag to be able to tell if the onwrite cb is called immediately,
  19512. // or on a later tick. We set this to true at first, because any
  19513. // actions that shouldn't happen until "later" should generally also
  19514. // not happen before the first write call.
  19515. this.sync = true;
  19516. // a flag to know if we're processing previously buffered items, which
  19517. // may call the _write() callback in the same tick, so that we don't
  19518. // end up in an overlapped onwrite situation.
  19519. this.bufferProcessing = false;
  19520. // the callback that's passed to _write(chunk,cb)
  19521. this.onwrite = function(er) {
  19522. onwrite(stream, er);
  19523. };
  19524. // the callback that the user supplies to write(chunk,encoding,cb)
  19525. this.writecb = null;
  19526. // the amount that is being written when _write is called.
  19527. this.writelen = 0;
  19528. this.buffer = [];
  19529. // number of pending user-supplied write callbacks
  19530. // this must be 0 before 'finish' can be emitted
  19531. this.pendingcb = 0;
  19532. // emit prefinish if the only thing we're waiting for is _write cbs
  19533. // This is relevant for synchronous Transform streams
  19534. this.prefinished = false;
  19535. // True if the error was already emitted and should not be thrown again
  19536. this.errorEmitted = false;
  19537. }
  19538. function Writable(options) {
  19539. var Duplex = __webpack_require__(142);
  19540. // Writable ctor is applied to Duplexes, though they're not
  19541. // instanceof Writable, they're instanceof Readable.
  19542. if (!(this instanceof Writable) && !(this instanceof Duplex))
  19543. return new Writable(options);
  19544. this._writableState = new WritableState(options, this);
  19545. // legacy.
  19546. this.writable = true;
  19547. Stream.call(this);
  19548. }
  19549. // Otherwise people can pipe Writable streams, which is just wrong.
  19550. Writable.prototype.pipe = function() {
  19551. this.emit('error', new Error('Cannot pipe. Not readable.'));
  19552. };
  19553. function writeAfterEnd(stream, state, cb) {
  19554. var er = new Error('write after end');
  19555. // TODO: defer error events consistently everywhere, not just the cb
  19556. stream.emit('error', er);
  19557. process.nextTick(function() {
  19558. cb(er);
  19559. });
  19560. }
  19561. // If we get something that is not a buffer, string, null, or undefined,
  19562. // and we're not in objectMode, then that's an error.
  19563. // Otherwise stream chunks are all considered to be of length=1, and the
  19564. // watermarks determine how many objects to keep in the buffer, rather than
  19565. // how many bytes or characters.
  19566. function validChunk(stream, state, chunk, cb) {
  19567. var valid = true;
  19568. if (!util.isBuffer(chunk) &&
  19569. !util.isString(chunk) &&
  19570. !util.isNullOrUndefined(chunk) &&
  19571. !state.objectMode) {
  19572. var er = new TypeError('Invalid non-string/buffer chunk');
  19573. stream.emit('error', er);
  19574. process.nextTick(function() {
  19575. cb(er);
  19576. });
  19577. valid = false;
  19578. }
  19579. return valid;
  19580. }
  19581. Writable.prototype.write = function(chunk, encoding, cb) {
  19582. var state = this._writableState;
  19583. var ret = false;
  19584. if (util.isFunction(encoding)) {
  19585. cb = encoding;
  19586. encoding = null;
  19587. }
  19588. if (util.isBuffer(chunk))
  19589. encoding = 'buffer';
  19590. else if (!encoding)
  19591. encoding = state.defaultEncoding;
  19592. if (!util.isFunction(cb))
  19593. cb = function() {};
  19594. if (state.ended)
  19595. writeAfterEnd(this, state, cb);
  19596. else if (validChunk(this, state, chunk, cb)) {
  19597. state.pendingcb++;
  19598. ret = writeOrBuffer(this, state, chunk, encoding, cb);
  19599. }
  19600. return ret;
  19601. };
  19602. Writable.prototype.cork = function() {
  19603. var state = this._writableState;
  19604. state.corked++;
  19605. };
  19606. Writable.prototype.uncork = function() {
  19607. var state = this._writableState;
  19608. if (state.corked) {
  19609. state.corked--;
  19610. if (!state.writing &&
  19611. !state.corked &&
  19612. !state.finished &&
  19613. !state.bufferProcessing &&
  19614. state.buffer.length)
  19615. clearBuffer(this, state);
  19616. }
  19617. };
  19618. function decodeChunk(state, chunk, encoding) {
  19619. if (!state.objectMode &&
  19620. state.decodeStrings !== false &&
  19621. util.isString(chunk)) {
  19622. chunk = new Buffer(chunk, encoding);
  19623. }
  19624. return chunk;
  19625. }
  19626. // if we're already writing something, then just put this
  19627. // in the queue, and wait our turn. Otherwise, call _write
  19628. // If we return false, then we need a drain event, so set that flag.
  19629. function writeOrBuffer(stream, state, chunk, encoding, cb) {
  19630. chunk = decodeChunk(state, chunk, encoding);
  19631. if (util.isBuffer(chunk))
  19632. encoding = 'buffer';
  19633. var len = state.objectMode ? 1 : chunk.length;
  19634. state.length += len;
  19635. var ret = state.length < state.highWaterMark;
  19636. // we must ensure that previous needDrain will not be reset to false.
  19637. if (!ret)
  19638. state.needDrain = true;
  19639. if (state.writing || state.corked)
  19640. state.buffer.push(new WriteReq(chunk, encoding, cb));
  19641. else
  19642. doWrite(stream, state, false, len, chunk, encoding, cb);
  19643. return ret;
  19644. }
  19645. function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  19646. state.writelen = len;
  19647. state.writecb = cb;
  19648. state.writing = true;
  19649. state.sync = true;
  19650. if (writev)
  19651. stream._writev(chunk, state.onwrite);
  19652. else
  19653. stream._write(chunk, encoding, state.onwrite);
  19654. state.sync = false;
  19655. }
  19656. function onwriteError(stream, state, sync, er, cb) {
  19657. if (sync)
  19658. process.nextTick(function() {
  19659. state.pendingcb--;
  19660. cb(er);
  19661. });
  19662. else {
  19663. state.pendingcb--;
  19664. cb(er);
  19665. }
  19666. stream._writableState.errorEmitted = true;
  19667. stream.emit('error', er);
  19668. }
  19669. function onwriteStateUpdate(state) {
  19670. state.writing = false;
  19671. state.writecb = null;
  19672. state.length -= state.writelen;
  19673. state.writelen = 0;
  19674. }
  19675. function onwrite(stream, er) {
  19676. var state = stream._writableState;
  19677. var sync = state.sync;
  19678. var cb = state.writecb;
  19679. onwriteStateUpdate(state);
  19680. if (er)
  19681. onwriteError(stream, state, sync, er, cb);
  19682. else {
  19683. // Check if we're actually ready to finish, but don't emit yet
  19684. var finished = needFinish(stream, state);
  19685. if (!finished &&
  19686. !state.corked &&
  19687. !state.bufferProcessing &&
  19688. state.buffer.length) {
  19689. clearBuffer(stream, state);
  19690. }
  19691. if (sync) {
  19692. process.nextTick(function() {
  19693. afterWrite(stream, state, finished, cb);
  19694. });
  19695. } else {
  19696. afterWrite(stream, state, finished, cb);
  19697. }
  19698. }
  19699. }
  19700. function afterWrite(stream, state, finished, cb) {
  19701. if (!finished)
  19702. onwriteDrain(stream, state);
  19703. state.pendingcb--;
  19704. cb();
  19705. finishMaybe(stream, state);
  19706. }
  19707. // Must force callback to be called on nextTick, so that we don't
  19708. // emit 'drain' before the write() consumer gets the 'false' return
  19709. // value, and has a chance to attach a 'drain' listener.
  19710. function onwriteDrain(stream, state) {
  19711. if (state.length === 0 && state.needDrain) {
  19712. state.needDrain = false;
  19713. stream.emit('drain');
  19714. }
  19715. }
  19716. // if there's something in the buffer waiting, then process it
  19717. function clearBuffer(stream, state) {
  19718. state.bufferProcessing = true;
  19719. if (stream._writev && state.buffer.length > 1) {
  19720. // Fast case, write everything using _writev()
  19721. var cbs = [];
  19722. for (var c = 0; c < state.buffer.length; c++)
  19723. cbs.push(state.buffer[c].callback);
  19724. // count the one we are adding, as well.
  19725. // TODO(isaacs) clean this up
  19726. state.pendingcb++;
  19727. doWrite(stream, state, true, state.length, state.buffer, '', function(err) {
  19728. for (var i = 0; i < cbs.length; i++) {
  19729. state.pendingcb--;
  19730. cbs[i](err);
  19731. }
  19732. });
  19733. // Clear buffer
  19734. state.buffer = [];
  19735. } else {
  19736. // Slow case, write chunks one-by-one
  19737. for (var c = 0; c < state.buffer.length; c++) {
  19738. var entry = state.buffer[c];
  19739. var chunk = entry.chunk;
  19740. var encoding = entry.encoding;
  19741. var cb = entry.callback;
  19742. var len = state.objectMode ? 1 : chunk.length;
  19743. doWrite(stream, state, false, len, chunk, encoding, cb);
  19744. // if we didn't call the onwrite immediately, then
  19745. // it means that we need to wait until it does.
  19746. // also, that means that the chunk and cb are currently
  19747. // being processed, so move the buffer counter past them.
  19748. if (state.writing) {
  19749. c++;
  19750. break;
  19751. }
  19752. }
  19753. if (c < state.buffer.length)
  19754. state.buffer = state.buffer.slice(c);
  19755. else
  19756. state.buffer.length = 0;
  19757. }
  19758. state.bufferProcessing = false;
  19759. }
  19760. Writable.prototype._write = function(chunk, encoding, cb) {
  19761. cb(new Error('not implemented'));
  19762. };
  19763. Writable.prototype._writev = null;
  19764. Writable.prototype.end = function(chunk, encoding, cb) {
  19765. var state = this._writableState;
  19766. if (util.isFunction(chunk)) {
  19767. cb = chunk;
  19768. chunk = null;
  19769. encoding = null;
  19770. } else if (util.isFunction(encoding)) {
  19771. cb = encoding;
  19772. encoding = null;
  19773. }
  19774. if (!util.isNullOrUndefined(chunk))
  19775. this.write(chunk, encoding);
  19776. // .end() fully uncorks
  19777. if (state.corked) {
  19778. state.corked = 1;
  19779. this.uncork();
  19780. }
  19781. // ignore unnecessary end() calls.
  19782. if (!state.ending && !state.finished)
  19783. endWritable(this, state, cb);
  19784. };
  19785. function needFinish(stream, state) {
  19786. return (state.ending &&
  19787. state.length === 0 &&
  19788. !state.finished &&
  19789. !state.writing);
  19790. }
  19791. function prefinish(stream, state) {
  19792. if (!state.prefinished) {
  19793. state.prefinished = true;
  19794. stream.emit('prefinish');
  19795. }
  19796. }
  19797. function finishMaybe(stream, state) {
  19798. var need = needFinish(stream, state);
  19799. if (need) {
  19800. if (state.pendingcb === 0) {
  19801. prefinish(stream, state);
  19802. state.finished = true;
  19803. stream.emit('finish');
  19804. } else
  19805. prefinish(stream, state);
  19806. }
  19807. return need;
  19808. }
  19809. function endWritable(stream, state, cb) {
  19810. state.ending = true;
  19811. finishMaybe(stream, state);
  19812. if (cb) {
  19813. if (state.finished)
  19814. process.nextTick(cb);
  19815. else
  19816. stream.once('finish', cb);
  19817. }
  19818. state.ended = true;
  19819. }
  19820. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(99)))
  19821. /***/ },
  19822. /* 142 */
  19823. /***/ function(module, exports, __webpack_require__) {
  19824. /* WEBPACK VAR INJECTION */(function(process) {// Copyright Joyent, Inc. and other Node contributors.
  19825. //
  19826. // Permission is hereby granted, free of charge, to any person obtaining a
  19827. // copy of this software and associated documentation files (the
  19828. // "Software"), to deal in the Software without restriction, including
  19829. // without limitation the rights to use, copy, modify, merge, publish,
  19830. // distribute, sublicense, and/or sell copies of the Software, and to permit
  19831. // persons to whom the Software is furnished to do so, subject to the
  19832. // following conditions:
  19833. //
  19834. // The above copyright notice and this permission notice shall be included
  19835. // in all copies or substantial portions of the Software.
  19836. //
  19837. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  19838. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19839. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  19840. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  19841. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  19842. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  19843. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  19844. // a duplex stream is just a stream that is both readable and writable.
  19845. // Since JS doesn't have multiple prototypal inheritance, this class
  19846. // prototypally inherits from Readable, and then parasitically from
  19847. // Writable.
  19848. module.exports = Duplex;
  19849. /*<replacement>*/
  19850. var objectKeys = Object.keys || function (obj) {
  19851. var keys = [];
  19852. for (var key in obj) keys.push(key);
  19853. return keys;
  19854. }
  19855. /*</replacement>*/
  19856. /*<replacement>*/
  19857. var util = __webpack_require__(178);
  19858. util.inherits = __webpack_require__(177);
  19859. /*</replacement>*/
  19860. var Readable = __webpack_require__(143);
  19861. var Writable = __webpack_require__(141);
  19862. util.inherits(Duplex, Readable);
  19863. forEach(objectKeys(Writable.prototype), function(method) {
  19864. if (!Duplex.prototype[method])
  19865. Duplex.prototype[method] = Writable.prototype[method];
  19866. });
  19867. function Duplex(options) {
  19868. if (!(this instanceof Duplex))
  19869. return new Duplex(options);
  19870. Readable.call(this, options);
  19871. Writable.call(this, options);
  19872. if (options && options.readable === false)
  19873. this.readable = false;
  19874. if (options && options.writable === false)
  19875. this.writable = false;
  19876. this.allowHalfOpen = true;
  19877. if (options && options.allowHalfOpen === false)
  19878. this.allowHalfOpen = false;
  19879. this.once('end', onend);
  19880. }
  19881. // the no-half-open enforcer
  19882. function onend() {
  19883. // if we allow half-open state, or if the writable side ended,
  19884. // then we're ok.
  19885. if (this.allowHalfOpen || this._writableState.ended)
  19886. return;
  19887. // no more data can be written.
  19888. // But allow more writes to happen in this tick.
  19889. process.nextTick(this.end.bind(this));
  19890. }
  19891. function forEach (xs, f) {
  19892. for (var i = 0, l = xs.length; i < l; i++) {
  19893. f(xs[i], i);
  19894. }
  19895. }
  19896. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(99)))
  19897. /***/ },
  19898. /* 143 */
  19899. /***/ function(module, exports, __webpack_require__) {
  19900. /* WEBPACK VAR INJECTION */(function(process) {// Copyright Joyent, Inc. and other Node contributors.
  19901. //
  19902. // Permission is hereby granted, free of charge, to any person obtaining a
  19903. // copy of this software and associated documentation files (the
  19904. // "Software"), to deal in the Software without restriction, including
  19905. // without limitation the rights to use, copy, modify, merge, publish,
  19906. // distribute, sublicense, and/or sell copies of the Software, and to permit
  19907. // persons to whom the Software is furnished to do so, subject to the
  19908. // following conditions:
  19909. //
  19910. // The above copyright notice and this permission notice shall be included
  19911. // in all copies or substantial portions of the Software.
  19912. //
  19913. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  19914. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19915. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  19916. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  19917. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  19918. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  19919. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  19920. module.exports = Readable;
  19921. /*<replacement>*/
  19922. var isArray = __webpack_require__(175);
  19923. /*</replacement>*/
  19924. /*<replacement>*/
  19925. var Buffer = __webpack_require__(47).Buffer;
  19926. /*</replacement>*/
  19927. Readable.ReadableState = ReadableState;
  19928. var EE = __webpack_require__(44).EventEmitter;
  19929. /*<replacement>*/
  19930. if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
  19931. return emitter.listeners(type).length;
  19932. };
  19933. /*</replacement>*/
  19934. var Stream = __webpack_require__(64);
  19935. /*<replacement>*/
  19936. var util = __webpack_require__(178);
  19937. util.inherits = __webpack_require__(177);
  19938. /*</replacement>*/
  19939. var StringDecoder;
  19940. /*<replacement>*/
  19941. var debug = __webpack_require__(171);
  19942. if (debug && debug.debuglog) {
  19943. debug = debug.debuglog('stream');
  19944. } else {
  19945. debug = function () {};
  19946. }
  19947. /*</replacement>*/
  19948. util.inherits(Readable, Stream);
  19949. function ReadableState(options, stream) {
  19950. var Duplex = __webpack_require__(142);
  19951. options = options || {};
  19952. // the point at which it stops calling _read() to fill the buffer
  19953. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  19954. var hwm = options.highWaterMark;
  19955. var defaultHwm = options.objectMode ? 16 : 16 * 1024;
  19956. this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
  19957. // cast to ints.
  19958. this.highWaterMark = ~~this.highWaterMark;
  19959. this.buffer = [];
  19960. this.length = 0;
  19961. this.pipes = null;
  19962. this.pipesCount = 0;
  19963. this.flowing = null;
  19964. this.ended = false;
  19965. this.endEmitted = false;
  19966. this.reading = false;
  19967. // a flag to be able to tell if the onwrite cb is called immediately,
  19968. // or on a later tick. We set this to true at first, because any
  19969. // actions that shouldn't happen until "later" should generally also
  19970. // not happen before the first write call.
  19971. this.sync = true;
  19972. // whenever we return null, then we set a flag to say
  19973. // that we're awaiting a 'readable' event emission.
  19974. this.needReadable = false;
  19975. this.emittedReadable = false;
  19976. this.readableListening = false;
  19977. // object stream flag. Used to make read(n) ignore n and to
  19978. // make all the buffer merging and length checks go away
  19979. this.objectMode = !!options.objectMode;
  19980. if (stream instanceof Duplex)
  19981. this.objectMode = this.objectMode || !!options.readableObjectMode;
  19982. // Crypto is kind of old and crusty. Historically, its default string
  19983. // encoding is 'binary' so we have to make this configurable.
  19984. // Everything else in the universe uses 'utf8', though.
  19985. this.defaultEncoding = options.defaultEncoding || 'utf8';
  19986. // when piping, we only care about 'readable' events that happen
  19987. // after read()ing all the bytes and not getting any pushback.
  19988. this.ranOut = false;
  19989. // the number of writers that are awaiting a drain event in .pipe()s
  19990. this.awaitDrain = 0;
  19991. // if true, a maybeReadMore has been scheduled
  19992. this.readingMore = false;
  19993. this.decoder = null;
  19994. this.encoding = null;
  19995. if (options.encoding) {
  19996. if (!StringDecoder)
  19997. StringDecoder = __webpack_require__(176).StringDecoder;
  19998. this.decoder = new StringDecoder(options.encoding);
  19999. this.encoding = options.encoding;
  20000. }
  20001. }
  20002. function Readable(options) {
  20003. var Duplex = __webpack_require__(142);
  20004. if (!(this instanceof Readable))
  20005. return new Readable(options);
  20006. this._readableState = new ReadableState(options, this);
  20007. // legacy
  20008. this.readable = true;
  20009. Stream.call(this);
  20010. }
  20011. // Manually shove something into the read() buffer.
  20012. // This returns true if the highWaterMark has not been hit yet,
  20013. // similar to how Writable.write() returns true if you should
  20014. // write() some more.
  20015. Readable.prototype.push = function(chunk, encoding) {
  20016. var state = this._readableState;
  20017. if (util.isString(chunk) && !state.objectMode) {
  20018. encoding = encoding || state.defaultEncoding;
  20019. if (encoding !== state.encoding) {
  20020. chunk = new Buffer(chunk, encoding);
  20021. encoding = '';
  20022. }
  20023. }
  20024. return readableAddChunk(this, state, chunk, encoding, false);
  20025. };
  20026. // Unshift should *always* be something directly out of read()
  20027. Readable.prototype.unshift = function(chunk) {
  20028. var state = this._readableState;
  20029. return readableAddChunk(this, state, chunk, '', true);
  20030. };
  20031. function readableAddChunk(stream, state, chunk, encoding, addToFront) {
  20032. var er = chunkInvalid(state, chunk);
  20033. if (er) {
  20034. stream.emit('error', er);
  20035. } else if (util.isNullOrUndefined(chunk)) {
  20036. state.reading = false;
  20037. if (!state.ended)
  20038. onEofChunk(stream, state);
  20039. } else if (state.objectMode || chunk && chunk.length > 0) {
  20040. if (state.ended && !addToFront) {
  20041. var e = new Error('stream.push() after EOF');
  20042. stream.emit('error', e);
  20043. } else if (state.endEmitted && addToFront) {
  20044. var e = new Error('stream.unshift() after end event');
  20045. stream.emit('error', e);
  20046. } else {
  20047. if (state.decoder && !addToFront && !encoding)
  20048. chunk = state.decoder.write(chunk);
  20049. if (!addToFront)
  20050. state.reading = false;
  20051. // if we want the data now, just emit it.
  20052. if (state.flowing && state.length === 0 && !state.sync) {
  20053. stream.emit('data', chunk);
  20054. stream.read(0);
  20055. } else {
  20056. // update the buffer info.
  20057. state.length += state.objectMode ? 1 : chunk.length;
  20058. if (addToFront)
  20059. state.buffer.unshift(chunk);
  20060. else
  20061. state.buffer.push(chunk);
  20062. if (state.needReadable)
  20063. emitReadable(stream);
  20064. }
  20065. maybeReadMore(stream, state);
  20066. }
  20067. } else if (!addToFront) {
  20068. state.reading = false;
  20069. }
  20070. return needMoreData(state);
  20071. }
  20072. // if it's past the high water mark, we can push in some more.
  20073. // Also, if we have no data yet, we can stand some
  20074. // more bytes. This is to work around cases where hwm=0,
  20075. // such as the repl. Also, if the push() triggered a
  20076. // readable event, and the user called read(largeNumber) such that
  20077. // needReadable was set, then we ought to push more, so that another
  20078. // 'readable' event will be triggered.
  20079. function needMoreData(state) {
  20080. return !state.ended &&
  20081. (state.needReadable ||
  20082. state.length < state.highWaterMark ||
  20083. state.length === 0);
  20084. }
  20085. // backwards compatibility.
  20086. Readable.prototype.setEncoding = function(enc) {
  20087. if (!StringDecoder)
  20088. StringDecoder = __webpack_require__(176).StringDecoder;
  20089. this._readableState.decoder = new StringDecoder(enc);
  20090. this._readableState.encoding = enc;
  20091. return this;
  20092. };
  20093. // Don't raise the hwm > 128MB
  20094. var MAX_HWM = 0x800000;
  20095. function roundUpToNextPowerOf2(n) {
  20096. if (n >= MAX_HWM) {
  20097. n = MAX_HWM;
  20098. } else {
  20099. // Get the next highest power of 2
  20100. n--;
  20101. for (var p = 1; p < 32; p <<= 1) n |= n >> p;
  20102. n++;
  20103. }
  20104. return n;
  20105. }
  20106. function howMuchToRead(n, state) {
  20107. if (state.length === 0 && state.ended)
  20108. return 0;
  20109. if (state.objectMode)
  20110. return n === 0 ? 0 : 1;
  20111. if (isNaN(n) || util.isNull(n)) {
  20112. // only flow one buffer at a time
  20113. if (state.flowing && state.buffer.length)
  20114. return state.buffer[0].length;
  20115. else
  20116. return state.length;
  20117. }
  20118. if (n <= 0)
  20119. return 0;
  20120. // If we're asking for more than the target buffer level,
  20121. // then raise the water mark. Bump up to the next highest
  20122. // power of 2, to prevent increasing it excessively in tiny
  20123. // amounts.
  20124. if (n > state.highWaterMark)
  20125. state.highWaterMark = roundUpToNextPowerOf2(n);
  20126. // don't have that much. return null, unless we've ended.
  20127. if (n > state.length) {
  20128. if (!state.ended) {
  20129. state.needReadable = true;
  20130. return 0;
  20131. } else
  20132. return state.length;
  20133. }
  20134. return n;
  20135. }
  20136. // you can override either this method, or the async _read(n) below.
  20137. Readable.prototype.read = function(n) {
  20138. debug('read', n);
  20139. var state = this._readableState;
  20140. var nOrig = n;
  20141. if (!util.isNumber(n) || n > 0)
  20142. state.emittedReadable = false;
  20143. // if we're doing read(0) to trigger a readable event, but we
  20144. // already have a bunch of data in the buffer, then just trigger
  20145. // the 'readable' event and move on.
  20146. if (n === 0 &&
  20147. state.needReadable &&
  20148. (state.length >= state.highWaterMark || state.ended)) {
  20149. debug('read: emitReadable', state.length, state.ended);
  20150. if (state.length === 0 && state.ended)
  20151. endReadable(this);
  20152. else
  20153. emitReadable(this);
  20154. return null;
  20155. }
  20156. n = howMuchToRead(n, state);
  20157. // if we've ended, and we're now clear, then finish it up.
  20158. if (n === 0 && state.ended) {
  20159. if (state.length === 0)
  20160. endReadable(this);
  20161. return null;
  20162. }
  20163. // All the actual chunk generation logic needs to be
  20164. // *below* the call to _read. The reason is that in certain
  20165. // synthetic stream cases, such as passthrough streams, _read
  20166. // may be a completely synchronous operation which may change
  20167. // the state of the read buffer, providing enough data when
  20168. // before there was *not* enough.
  20169. //
  20170. // So, the steps are:
  20171. // 1. Figure out what the state of things will be after we do
  20172. // a read from the buffer.
  20173. //
  20174. // 2. If that resulting state will trigger a _read, then call _read.
  20175. // Note that this may be asynchronous, or synchronous. Yes, it is
  20176. // deeply ugly to write APIs this way, but that still doesn't mean
  20177. // that the Readable class should behave improperly, as streams are
  20178. // designed to be sync/async agnostic.
  20179. // Take note if the _read call is sync or async (ie, if the read call
  20180. // has returned yet), so that we know whether or not it's safe to emit
  20181. // 'readable' etc.
  20182. //
  20183. // 3. Actually pull the requested chunks out of the buffer and return.
  20184. // if we need a readable event, then we need to do some reading.
  20185. var doRead = state.needReadable;
  20186. debug('need readable', doRead);
  20187. // if we currently have less than the highWaterMark, then also read some
  20188. if (state.length === 0 || state.length - n < state.highWaterMark) {
  20189. doRead = true;
  20190. debug('length less than watermark', doRead);
  20191. }
  20192. // however, if we've ended, then there's no point, and if we're already
  20193. // reading, then it's unnecessary.
  20194. if (state.ended || state.reading) {
  20195. doRead = false;
  20196. debug('reading or ended', doRead);
  20197. }
  20198. if (doRead) {
  20199. debug('do read');
  20200. state.reading = true;
  20201. state.sync = true;
  20202. // if the length is currently zero, then we *need* a readable event.
  20203. if (state.length === 0)
  20204. state.needReadable = true;
  20205. // call internal read method
  20206. this._read(state.highWaterMark);
  20207. state.sync = false;
  20208. }
  20209. // If _read pushed data synchronously, then `reading` will be false,
  20210. // and we need to re-evaluate how much data we can return to the user.
  20211. if (doRead && !state.reading)
  20212. n = howMuchToRead(nOrig, state);
  20213. var ret;
  20214. if (n > 0)
  20215. ret = fromList(n, state);
  20216. else
  20217. ret = null;
  20218. if (util.isNull(ret)) {
  20219. state.needReadable = true;
  20220. n = 0;
  20221. }
  20222. state.length -= n;
  20223. // If we have nothing in the buffer, then we want to know
  20224. // as soon as we *do* get something into the buffer.
  20225. if (state.length === 0 && !state.ended)
  20226. state.needReadable = true;
  20227. // If we tried to read() past the EOF, then emit end on the next tick.
  20228. if (nOrig !== n && state.ended && state.length === 0)
  20229. endReadable(this);
  20230. if (!util.isNull(ret))
  20231. this.emit('data', ret);
  20232. return ret;
  20233. };
  20234. function chunkInvalid(state, chunk) {
  20235. var er = null;
  20236. if (!util.isBuffer(chunk) &&
  20237. !util.isString(chunk) &&
  20238. !util.isNullOrUndefined(chunk) &&
  20239. !state.objectMode) {
  20240. er = new TypeError('Invalid non-string/buffer chunk');
  20241. }
  20242. return er;
  20243. }
  20244. function onEofChunk(stream, state) {
  20245. if (state.decoder && !state.ended) {
  20246. var chunk = state.decoder.end();
  20247. if (chunk && chunk.length) {
  20248. state.buffer.push(chunk);
  20249. state.length += state.objectMode ? 1 : chunk.length;
  20250. }
  20251. }
  20252. state.ended = true;
  20253. // emit 'readable' now to make sure it gets picked up.
  20254. emitReadable(stream);
  20255. }
  20256. // Don't emit readable right away in sync mode, because this can trigger
  20257. // another read() call => stack overflow. This way, it might trigger
  20258. // a nextTick recursion warning, but that's not so bad.
  20259. function emitReadable(stream) {
  20260. var state = stream._readableState;
  20261. state.needReadable = false;
  20262. if (!state.emittedReadable) {
  20263. debug('emitReadable', state.flowing);
  20264. state.emittedReadable = true;
  20265. if (state.sync)
  20266. process.nextTick(function() {
  20267. emitReadable_(stream);
  20268. });
  20269. else
  20270. emitReadable_(stream);
  20271. }
  20272. }
  20273. function emitReadable_(stream) {
  20274. debug('emit readable');
  20275. stream.emit('readable');
  20276. flow(stream);
  20277. }
  20278. // at this point, the user has presumably seen the 'readable' event,
  20279. // and called read() to consume some data. that may have triggered
  20280. // in turn another _read(n) call, in which case reading = true if
  20281. // it's in progress.
  20282. // However, if we're not ended, or reading, and the length < hwm,
  20283. // then go ahead and try to read some more preemptively.
  20284. function maybeReadMore(stream, state) {
  20285. if (!state.readingMore) {
  20286. state.readingMore = true;
  20287. process.nextTick(function() {
  20288. maybeReadMore_(stream, state);
  20289. });
  20290. }
  20291. }
  20292. function maybeReadMore_(stream, state) {
  20293. var len = state.length;
  20294. while (!state.reading && !state.flowing && !state.ended &&
  20295. state.length < state.highWaterMark) {
  20296. debug('maybeReadMore read 0');
  20297. stream.read(0);
  20298. if (len === state.length)
  20299. // didn't get any data, stop spinning.
  20300. break;
  20301. else
  20302. len = state.length;
  20303. }
  20304. state.readingMore = false;
  20305. }
  20306. // abstract method. to be overridden in specific implementation classes.
  20307. // call cb(er, data) where data is <= n in length.
  20308. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  20309. // arbitrary, and perhaps not very meaningful.
  20310. Readable.prototype._read = function(n) {
  20311. this.emit('error', new Error('not implemented'));
  20312. };
  20313. Readable.prototype.pipe = function(dest, pipeOpts) {
  20314. var src = this;
  20315. var state = this._readableState;
  20316. switch (state.pipesCount) {
  20317. case 0:
  20318. state.pipes = dest;
  20319. break;
  20320. case 1:
  20321. state.pipes = [state.pipes, dest];
  20322. break;
  20323. default:
  20324. state.pipes.push(dest);
  20325. break;
  20326. }
  20327. state.pipesCount += 1;
  20328. debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  20329. var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
  20330. dest !== process.stdout &&
  20331. dest !== process.stderr;
  20332. var endFn = doEnd ? onend : cleanup;
  20333. if (state.endEmitted)
  20334. process.nextTick(endFn);
  20335. else
  20336. src.once('end', endFn);
  20337. dest.on('unpipe', onunpipe);
  20338. function onunpipe(readable) {
  20339. debug('onunpipe');
  20340. if (readable === src) {
  20341. cleanup();
  20342. }
  20343. }
  20344. function onend() {
  20345. debug('onend');
  20346. dest.end();
  20347. }
  20348. // when the dest drains, it reduces the awaitDrain counter
  20349. // on the source. This would be more elegant with a .once()
  20350. // handler in flow(), but adding and removing repeatedly is
  20351. // too slow.
  20352. var ondrain = pipeOnDrain(src);
  20353. dest.on('drain', ondrain);
  20354. function cleanup() {
  20355. debug('cleanup');
  20356. // cleanup event handlers once the pipe is broken
  20357. dest.removeListener('close', onclose);
  20358. dest.removeListener('finish', onfinish);
  20359. dest.removeListener('drain', ondrain);
  20360. dest.removeListener('error', onerror);
  20361. dest.removeListener('unpipe', onunpipe);
  20362. src.removeListener('end', onend);
  20363. src.removeListener('end', cleanup);
  20364. src.removeListener('data', ondata);
  20365. // if the reader is waiting for a drain event from this
  20366. // specific writer, then it would cause it to never start
  20367. // flowing again.
  20368. // So, if this is awaiting a drain, then we just call it now.
  20369. // If we don't know, then assume that we are waiting for one.
  20370. if (state.awaitDrain &&
  20371. (!dest._writableState || dest._writableState.needDrain))
  20372. ondrain();
  20373. }
  20374. src.on('data', ondata);
  20375. function ondata(chunk) {
  20376. debug('ondata');
  20377. var ret = dest.write(chunk);
  20378. if (false === ret) {
  20379. debug('false write response, pause',
  20380. src._readableState.awaitDrain);
  20381. src._readableState.awaitDrain++;
  20382. src.pause();
  20383. }
  20384. }
  20385. // if the dest has an error, then stop piping into it.
  20386. // however, don't suppress the throwing behavior for this.
  20387. function onerror(er) {
  20388. debug('onerror', er);
  20389. unpipe();
  20390. dest.removeListener('error', onerror);
  20391. if (EE.listenerCount(dest, 'error') === 0)
  20392. dest.emit('error', er);
  20393. }
  20394. // This is a brutally ugly hack to make sure that our error handler
  20395. // is attached before any userland ones. NEVER DO THIS.
  20396. if (!dest._events || !dest._events.error)
  20397. dest.on('error', onerror);
  20398. else if (isArray(dest._events.error))
  20399. dest._events.error.unshift(onerror);
  20400. else
  20401. dest._events.error = [onerror, dest._events.error];
  20402. // Both close and finish should trigger unpipe, but only once.
  20403. function onclose() {
  20404. dest.removeListener('finish', onfinish);
  20405. unpipe();
  20406. }
  20407. dest.once('close', onclose);
  20408. function onfinish() {
  20409. debug('onfinish');
  20410. dest.removeListener('close', onclose);
  20411. unpipe();
  20412. }
  20413. dest.once('finish', onfinish);
  20414. function unpipe() {
  20415. debug('unpipe');
  20416. src.unpipe(dest);
  20417. }
  20418. // tell the dest that it's being piped to
  20419. dest.emit('pipe', src);
  20420. // start the flow if it hasn't been started already.
  20421. if (!state.flowing) {
  20422. debug('pipe resume');
  20423. src.resume();
  20424. }
  20425. return dest;
  20426. };
  20427. function pipeOnDrain(src) {
  20428. return function() {
  20429. var state = src._readableState;
  20430. debug('pipeOnDrain', state.awaitDrain);
  20431. if (state.awaitDrain)
  20432. state.awaitDrain--;
  20433. if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) {
  20434. state.flowing = true;
  20435. flow(src);
  20436. }
  20437. };
  20438. }
  20439. Readable.prototype.unpipe = function(dest) {
  20440. var state = this._readableState;
  20441. // if we're not piping anywhere, then do nothing.
  20442. if (state.pipesCount === 0)
  20443. return this;
  20444. // just one destination. most common case.
  20445. if (state.pipesCount === 1) {
  20446. // passed in one, but it's not the right one.
  20447. if (dest && dest !== state.pipes)
  20448. return this;
  20449. if (!dest)
  20450. dest = state.pipes;
  20451. // got a match.
  20452. state.pipes = null;
  20453. state.pipesCount = 0;
  20454. state.flowing = false;
  20455. if (dest)
  20456. dest.emit('unpipe', this);
  20457. return this;
  20458. }
  20459. // slow case. multiple pipe destinations.
  20460. if (!dest) {
  20461. // remove all.
  20462. var dests = state.pipes;
  20463. var len = state.pipesCount;
  20464. state.pipes = null;
  20465. state.pipesCount = 0;
  20466. state.flowing = false;
  20467. for (var i = 0; i < len; i++)
  20468. dests[i].emit('unpipe', this);
  20469. return this;
  20470. }
  20471. // try to find the right one.
  20472. var i = indexOf(state.pipes, dest);
  20473. if (i === -1)
  20474. return this;
  20475. state.pipes.splice(i, 1);
  20476. state.pipesCount -= 1;
  20477. if (state.pipesCount === 1)
  20478. state.pipes = state.pipes[0];
  20479. dest.emit('unpipe', this);
  20480. return this;
  20481. };
  20482. // set up data events if they are asked for
  20483. // Ensure readable listeners eventually get something
  20484. Readable.prototype.on = function(ev, fn) {
  20485. var res = Stream.prototype.on.call(this, ev, fn);
  20486. // If listening to data, and it has not explicitly been paused,
  20487. // then call resume to start the flow of data on the next tick.
  20488. if (ev === 'data' && false !== this._readableState.flowing) {
  20489. this.resume();
  20490. }
  20491. if (ev === 'readable' && this.readable) {
  20492. var state = this._readableState;
  20493. if (!state.readableListening) {
  20494. state.readableListening = true;
  20495. state.emittedReadable = false;
  20496. state.needReadable = true;
  20497. if (!state.reading) {
  20498. var self = this;
  20499. process.nextTick(function() {
  20500. debug('readable nexttick read 0');
  20501. self.read(0);
  20502. });
  20503. } else if (state.length) {
  20504. emitReadable(this, state);
  20505. }
  20506. }
  20507. }
  20508. return res;
  20509. };
  20510. Readable.prototype.addListener = Readable.prototype.on;
  20511. // pause() and resume() are remnants of the legacy readable stream API
  20512. // If the user uses them, then switch into old mode.
  20513. Readable.prototype.resume = function() {
  20514. var state = this._readableState;
  20515. if (!state.flowing) {
  20516. debug('resume');
  20517. state.flowing = true;
  20518. if (!state.reading) {
  20519. debug('resume read 0');
  20520. this.read(0);
  20521. }
  20522. resume(this, state);
  20523. }
  20524. return this;
  20525. };
  20526. function resume(stream, state) {
  20527. if (!state.resumeScheduled) {
  20528. state.resumeScheduled = true;
  20529. process.nextTick(function() {
  20530. resume_(stream, state);
  20531. });
  20532. }
  20533. }
  20534. function resume_(stream, state) {
  20535. state.resumeScheduled = false;
  20536. stream.emit('resume');
  20537. flow(stream);
  20538. if (state.flowing && !state.reading)
  20539. stream.read(0);
  20540. }
  20541. Readable.prototype.pause = function() {
  20542. debug('call pause flowing=%j', this._readableState.flowing);
  20543. if (false !== this._readableState.flowing) {
  20544. debug('pause');
  20545. this._readableState.flowing = false;
  20546. this.emit('pause');
  20547. }
  20548. return this;
  20549. };
  20550. function flow(stream) {
  20551. var state = stream._readableState;
  20552. debug('flow', state.flowing);
  20553. if (state.flowing) {
  20554. do {
  20555. var chunk = stream.read();
  20556. } while (null !== chunk && state.flowing);
  20557. }
  20558. }
  20559. // wrap an old-style stream as the async data source.
  20560. // This is *not* part of the readable stream interface.
  20561. // It is an ugly unfortunate mess of history.
  20562. Readable.prototype.wrap = function(stream) {
  20563. var state = this._readableState;
  20564. var paused = false;
  20565. var self = this;
  20566. stream.on('end', function() {
  20567. debug('wrapped end');
  20568. if (state.decoder && !state.ended) {
  20569. var chunk = state.decoder.end();
  20570. if (chunk && chunk.length)
  20571. self.push(chunk);
  20572. }
  20573. self.push(null);
  20574. });
  20575. stream.on('data', function(chunk) {
  20576. debug('wrapped data');
  20577. if (state.decoder)
  20578. chunk = state.decoder.write(chunk);
  20579. if (!chunk || !state.objectMode && !chunk.length)
  20580. return;
  20581. var ret = self.push(chunk);
  20582. if (!ret) {
  20583. paused = true;
  20584. stream.pause();
  20585. }
  20586. });
  20587. // proxy all the other methods.
  20588. // important when wrapping filters and duplexes.
  20589. for (var i in stream) {
  20590. if (util.isFunction(stream[i]) && util.isUndefined(this[i])) {
  20591. this[i] = function(method) { return function() {
  20592. return stream[method].apply(stream, arguments);
  20593. }}(i);
  20594. }
  20595. }
  20596. // proxy certain important events.
  20597. var events = ['error', 'close', 'destroy', 'pause', 'resume'];
  20598. forEach(events, function(ev) {
  20599. stream.on(ev, self.emit.bind(self, ev));
  20600. });
  20601. // when we try to consume some more bytes, simply unpause the
  20602. // underlying stream.
  20603. self._read = function(n) {
  20604. debug('wrapped _read', n);
  20605. if (paused) {
  20606. paused = false;
  20607. stream.resume();
  20608. }
  20609. };
  20610. return self;
  20611. };
  20612. // exposed for testing purposes only.
  20613. Readable._fromList = fromList;
  20614. // Pluck off n bytes from an array of buffers.
  20615. // Length is the combined lengths of all the buffers in the list.
  20616. function fromList(n, state) {
  20617. var list = state.buffer;
  20618. var length = state.length;
  20619. var stringMode = !!state.decoder;
  20620. var objectMode = !!state.objectMode;
  20621. var ret;
  20622. // nothing in the list, definitely empty.
  20623. if (list.length === 0)
  20624. return null;
  20625. if (length === 0)
  20626. ret = null;
  20627. else if (objectMode)
  20628. ret = list.shift();
  20629. else if (!n || n >= length) {
  20630. // read it all, truncate the array.
  20631. if (stringMode)
  20632. ret = list.join('');
  20633. else
  20634. ret = Buffer.concat(list, length);
  20635. list.length = 0;
  20636. } else {
  20637. // read just some of it.
  20638. if (n < list[0].length) {
  20639. // just take a part of the first list item.
  20640. // slice is the same for buffers and strings.
  20641. var buf = list[0];
  20642. ret = buf.slice(0, n);
  20643. list[0] = buf.slice(n);
  20644. } else if (n === list[0].length) {
  20645. // first list is a perfect match
  20646. ret = list.shift();
  20647. } else {
  20648. // complex case.
  20649. // we have enough to cover it, but it spans past the first buffer.
  20650. if (stringMode)
  20651. ret = '';
  20652. else
  20653. ret = new Buffer(n);
  20654. var c = 0;
  20655. for (var i = 0, l = list.length; i < l && c < n; i++) {
  20656. var buf = list[0];
  20657. var cpy = Math.min(n - c, buf.length);
  20658. if (stringMode)
  20659. ret += buf.slice(0, cpy);
  20660. else
  20661. buf.copy(ret, c, 0, cpy);
  20662. if (cpy < buf.length)
  20663. list[0] = buf.slice(cpy);
  20664. else
  20665. list.shift();
  20666. c += cpy;
  20667. }
  20668. }
  20669. }
  20670. return ret;
  20671. }
  20672. function endReadable(stream) {
  20673. var state = stream._readableState;
  20674. // If we get here before consuming all the bytes, then that is a
  20675. // bug in node. Should never happen.
  20676. if (state.length > 0)
  20677. throw new Error('endReadable called on non-empty stream');
  20678. if (!state.endEmitted) {
  20679. state.ended = true;
  20680. process.nextTick(function() {
  20681. // Check that we didn't get one last unshift.
  20682. if (!state.endEmitted && state.length === 0) {
  20683. state.endEmitted = true;
  20684. stream.readable = false;
  20685. stream.emit('end');
  20686. }
  20687. });
  20688. }
  20689. }
  20690. function forEach (xs, f) {
  20691. for (var i = 0, l = xs.length; i < l; i++) {
  20692. f(xs[i], i);
  20693. }
  20694. }
  20695. function indexOf (xs, x) {
  20696. for (var i = 0, l = xs.length; i < l; i++) {
  20697. if (xs[i] === x) return i;
  20698. }
  20699. return -1;
  20700. }
  20701. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(99)))
  20702. /***/ },
  20703. /* 144 */
  20704. /***/ function(module, exports, __webpack_require__) {
  20705. // Copyright Joyent, Inc. and other Node contributors.
  20706. //
  20707. // Permission is hereby granted, free of charge, to any person obtaining a
  20708. // copy of this software and associated documentation files (the
  20709. // "Software"), to deal in the Software without restriction, including
  20710. // without limitation the rights to use, copy, modify, merge, publish,
  20711. // distribute, sublicense, and/or sell copies of the Software, and to permit
  20712. // persons to whom the Software is furnished to do so, subject to the
  20713. // following conditions:
  20714. //
  20715. // The above copyright notice and this permission notice shall be included
  20716. // in all copies or substantial portions of the Software.
  20717. //
  20718. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  20719. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  20720. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  20721. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  20722. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  20723. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  20724. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  20725. // a transform stream is a readable/writable stream where you do
  20726. // something with the data. Sometimes it's called a "filter",
  20727. // but that's not a great name for it, since that implies a thing where
  20728. // some bits pass through, and others are simply ignored. (That would
  20729. // be a valid example of a transform, of course.)
  20730. //
  20731. // While the output is causally related to the input, it's not a
  20732. // necessarily symmetric or synchronous transformation. For example,
  20733. // a zlib stream might take multiple plain-text writes(), and then
  20734. // emit a single compressed chunk some time in the future.
  20735. //
  20736. // Here's how this works:
  20737. //
  20738. // The Transform stream has all the aspects of the readable and writable
  20739. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  20740. // internally, and returns false if there's a lot of pending writes
  20741. // buffered up. When you call read(), that calls _read(n) until
  20742. // there's enough pending readable data buffered up.
  20743. //
  20744. // In a transform stream, the written data is placed in a buffer. When
  20745. // _read(n) is called, it transforms the queued up data, calling the
  20746. // buffered _write cb's as it consumes chunks. If consuming a single
  20747. // written chunk would result in multiple output chunks, then the first
  20748. // outputted bit calls the readcb, and subsequent chunks just go into
  20749. // the read buffer, and will cause it to emit 'readable' if necessary.
  20750. //
  20751. // This way, back-pressure is actually determined by the reading side,
  20752. // since _read has to be called to start processing a new chunk. However,
  20753. // a pathological inflate type of transform can cause excessive buffering
  20754. // here. For example, imagine a stream where every byte of input is
  20755. // interpreted as an integer from 0-255, and then results in that many
  20756. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  20757. // 1kb of data being output. In this case, you could write a very small
  20758. // amount of input, and end up with a very large amount of output. In
  20759. // such a pathological inflating mechanism, there'd be no way to tell
  20760. // the system to stop doing the transform. A single 4MB write could
  20761. // cause the system to run out of memory.
  20762. //
  20763. // However, even in such a pathological case, only a single written chunk
  20764. // would be consumed, and then the rest would wait (un-transformed) until
  20765. // the results of the previous transformed chunk were consumed.
  20766. module.exports = Transform;
  20767. var Duplex = __webpack_require__(142);
  20768. /*<replacement>*/
  20769. var util = __webpack_require__(178);
  20770. util.inherits = __webpack_require__(177);
  20771. /*</replacement>*/
  20772. util.inherits(Transform, Duplex);
  20773. function TransformState(options, stream) {
  20774. this.afterTransform = function(er, data) {
  20775. return afterTransform(stream, er, data);
  20776. };
  20777. this.needTransform = false;
  20778. this.transforming = false;
  20779. this.writecb = null;
  20780. this.writechunk = null;
  20781. }
  20782. function afterTransform(stream, er, data) {
  20783. var ts = stream._transformState;
  20784. ts.transforming = false;
  20785. var cb = ts.writecb;
  20786. if (!cb)
  20787. return stream.emit('error', new Error('no writecb in Transform class'));
  20788. ts.writechunk = null;
  20789. ts.writecb = null;
  20790. if (!util.isNullOrUndefined(data))
  20791. stream.push(data);
  20792. if (cb)
  20793. cb(er);
  20794. var rs = stream._readableState;
  20795. rs.reading = false;
  20796. if (rs.needReadable || rs.length < rs.highWaterMark) {
  20797. stream._read(rs.highWaterMark);
  20798. }
  20799. }
  20800. function Transform(options) {
  20801. if (!(this instanceof Transform))
  20802. return new Transform(options);
  20803. Duplex.call(this, options);
  20804. this._transformState = new TransformState(options, this);
  20805. // when the writable side finishes, then flush out anything remaining.
  20806. var stream = this;
  20807. // start out asking for a readable event once data is transformed.
  20808. this._readableState.needReadable = true;
  20809. // we have implemented the _read method, and done the other things
  20810. // that Readable wants before the first _read call, so unset the
  20811. // sync guard flag.
  20812. this._readableState.sync = false;
  20813. this.once('prefinish', function() {
  20814. if (util.isFunction(this._flush))
  20815. this._flush(function(er) {
  20816. done(stream, er);
  20817. });
  20818. else
  20819. done(stream);
  20820. });
  20821. }
  20822. Transform.prototype.push = function(chunk, encoding) {
  20823. this._transformState.needTransform = false;
  20824. return Duplex.prototype.push.call(this, chunk, encoding);
  20825. };
  20826. // This is the part where you do stuff!
  20827. // override this function in implementation classes.
  20828. // 'chunk' is an input chunk.
  20829. //
  20830. // Call `push(newChunk)` to pass along transformed output
  20831. // to the readable side. You may call 'push' zero or more times.
  20832. //
  20833. // Call `cb(err)` when you are done with this chunk. If you pass
  20834. // an error, then that'll put the hurt on the whole operation. If you
  20835. // never call cb(), then you'll never get another chunk.
  20836. Transform.prototype._transform = function(chunk, encoding, cb) {
  20837. throw new Error('not implemented');
  20838. };
  20839. Transform.prototype._write = function(chunk, encoding, cb) {
  20840. var ts = this._transformState;
  20841. ts.writecb = cb;
  20842. ts.writechunk = chunk;
  20843. ts.writeencoding = encoding;
  20844. if (!ts.transforming) {
  20845. var rs = this._readableState;
  20846. if (ts.needTransform ||
  20847. rs.needReadable ||
  20848. rs.length < rs.highWaterMark)
  20849. this._read(rs.highWaterMark);
  20850. }
  20851. };
  20852. // Doesn't matter what the args are here.
  20853. // _transform does all the work.
  20854. // That we got here means that the readable side wants more data.
  20855. Transform.prototype._read = function(n) {
  20856. var ts = this._transformState;
  20857. if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) {
  20858. ts.transforming = true;
  20859. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  20860. } else {
  20861. // mark that we need a transform, so that any data that comes in
  20862. // will get processed, now that we've asked for it.
  20863. ts.needTransform = true;
  20864. }
  20865. };
  20866. function done(stream, er) {
  20867. if (er)
  20868. return stream.emit('error', er);
  20869. // if there's nothing in the write buffer, then that means
  20870. // that nothing more will ever be provided
  20871. var ws = stream._writableState;
  20872. var ts = stream._transformState;
  20873. if (ws.length)
  20874. throw new Error('calling transform done when ws.length != 0');
  20875. if (ts.transforming)
  20876. throw new Error('calling transform done when still transforming');
  20877. return stream.push(null);
  20878. }
  20879. /***/ },
  20880. /* 145 */
  20881. /***/ function(module, exports, __webpack_require__) {
  20882. // Copyright Joyent, Inc. and other Node contributors.
  20883. //
  20884. // Permission is hereby granted, free of charge, to any person obtaining a
  20885. // copy of this software and associated documentation files (the
  20886. // "Software"), to deal in the Software without restriction, including
  20887. // without limitation the rights to use, copy, modify, merge, publish,
  20888. // distribute, sublicense, and/or sell copies of the Software, and to permit
  20889. // persons to whom the Software is furnished to do so, subject to the
  20890. // following conditions:
  20891. //
  20892. // The above copyright notice and this permission notice shall be included
  20893. // in all copies or substantial portions of the Software.
  20894. //
  20895. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  20896. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  20897. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  20898. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  20899. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  20900. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  20901. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  20902. // a passthrough stream.
  20903. // basically just the most minimal sort of Transform stream.
  20904. // Every written chunk gets output as-is.
  20905. module.exports = PassThrough;
  20906. var Transform = __webpack_require__(144);
  20907. /*<replacement>*/
  20908. var util = __webpack_require__(178);
  20909. util.inherits = __webpack_require__(177);
  20910. /*</replacement>*/
  20911. util.inherits(PassThrough, Transform);
  20912. function PassThrough(options) {
  20913. if (!(this instanceof PassThrough))
  20914. return new PassThrough(options);
  20915. Transform.call(this, options);
  20916. }
  20917. PassThrough.prototype._transform = function(chunk, encoding, cb) {
  20918. cb(null, chunk);
  20919. };
  20920. /***/ },
  20921. /* 146 */
  20922. /***/ function(module, exports, __webpack_require__) {
  20923. if (typeof Object.create === 'function') {
  20924. // implementation from standard node.js 'util' module
  20925. module.exports = function inherits(ctor, superCtor) {
  20926. ctor.super_ = superCtor
  20927. ctor.prototype = Object.create(superCtor.prototype, {
  20928. constructor: {
  20929. value: ctor,
  20930. enumerable: false,
  20931. writable: true,
  20932. configurable: true
  20933. }
  20934. });
  20935. };
  20936. } else {
  20937. // old school shim for old browsers
  20938. module.exports = function inherits(ctor, superCtor) {
  20939. ctor.super_ = superCtor
  20940. var TempCtor = function () {}
  20941. TempCtor.prototype = superCtor.prototype
  20942. ctor.prototype = new TempCtor()
  20943. ctor.prototype.constructor = ctor
  20944. }
  20945. }
  20946. /***/ },
  20947. /* 147 */
  20948. /***/ function(module, exports, __webpack_require__) {
  20949. /* WEBPACK VAR INJECTION */(function(Buffer) {var uint_max = Math.pow(2, 32);
  20950. function fixup_uint32(x) {
  20951. var ret, x_pos;
  20952. ret = x > uint_max || x < 0 ? (x_pos = Math.abs(x) % uint_max, x < 0 ? uint_max - x_pos : x_pos) : x;
  20953. return ret;
  20954. }
  20955. function scrub_vec(v) {
  20956. var i, _i, _ref;
  20957. for (i = _i = 0, _ref = v.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
  20958. v[i] = 0;
  20959. }
  20960. return false;
  20961. }
  20962. function Global() {
  20963. var i;
  20964. this.SBOX = [];
  20965. this.INV_SBOX = [];
  20966. this.SUB_MIX = (function() {
  20967. var _i, _results;
  20968. _results = [];
  20969. for (i = _i = 0; _i < 4; i = ++_i) {
  20970. _results.push([]);
  20971. }
  20972. return _results;
  20973. })();
  20974. this.INV_SUB_MIX = (function() {
  20975. var _i, _results;
  20976. _results = [];
  20977. for (i = _i = 0; _i < 4; i = ++_i) {
  20978. _results.push([]);
  20979. }
  20980. return _results;
  20981. })();
  20982. this.init();
  20983. this.RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
  20984. }
  20985. Global.prototype.init = function() {
  20986. var d, i, sx, t, x, x2, x4, x8, xi, _i;
  20987. d = (function() {
  20988. var _i, _results;
  20989. _results = [];
  20990. for (i = _i = 0; _i < 256; i = ++_i) {
  20991. if (i < 128) {
  20992. _results.push(i << 1);
  20993. } else {
  20994. _results.push((i << 1) ^ 0x11b);
  20995. }
  20996. }
  20997. return _results;
  20998. })();
  20999. x = 0;
  21000. xi = 0;
  21001. for (i = _i = 0; _i < 256; i = ++_i) {
  21002. sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);
  21003. sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;
  21004. this.SBOX[x] = sx;
  21005. this.INV_SBOX[sx] = x;
  21006. x2 = d[x];
  21007. x4 = d[x2];
  21008. x8 = d[x4];
  21009. t = (d[sx] * 0x101) ^ (sx * 0x1010100);
  21010. this.SUB_MIX[0][x] = (t << 24) | (t >>> 8);
  21011. this.SUB_MIX[1][x] = (t << 16) | (t >>> 16);
  21012. this.SUB_MIX[2][x] = (t << 8) | (t >>> 24);
  21013. this.SUB_MIX[3][x] = t;
  21014. t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);
  21015. this.INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8);
  21016. this.INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16);
  21017. this.INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24);
  21018. this.INV_SUB_MIX[3][sx] = t;
  21019. if (x === 0) {
  21020. x = xi = 1;
  21021. } else {
  21022. x = x2 ^ d[d[d[x8 ^ x2]]];
  21023. xi ^= d[d[xi]];
  21024. }
  21025. }
  21026. return true;
  21027. };
  21028. var G = new Global();
  21029. AES.blockSize = 4 * 4;
  21030. AES.prototype.blockSize = AES.blockSize;
  21031. AES.keySize = 256 / 8;
  21032. AES.prototype.keySize = AES.keySize;
  21033. AES.ivSize = AES.blockSize;
  21034. AES.prototype.ivSize = AES.ivSize;
  21035. function bufferToArray(buf) {
  21036. var len = buf.length/4;
  21037. var out = new Array(len);
  21038. var i = -1;
  21039. while (++i < len) {
  21040. out[i] = buf.readUInt32BE(i * 4);
  21041. }
  21042. return out;
  21043. }
  21044. function AES(key) {
  21045. this._key = bufferToArray(key);
  21046. this._doReset();
  21047. }
  21048. AES.prototype._doReset = function() {
  21049. var invKsRow, keySize, keyWords, ksRow, ksRows, t, _i, _j;
  21050. keyWords = this._key;
  21051. keySize = keyWords.length;
  21052. this._nRounds = keySize + 6;
  21053. ksRows = (this._nRounds + 1) * 4;
  21054. this._keySchedule = [];
  21055. for (ksRow = _i = 0; 0 <= ksRows ? _i < ksRows : _i > ksRows; ksRow = 0 <= ksRows ? ++_i : --_i) {
  21056. this._keySchedule[ksRow] = ksRow < keySize ? keyWords[ksRow] : (t = this._keySchedule[ksRow - 1], (ksRow % keySize) === 0 ? (t = (t << 8) | (t >>> 24), t = (G.SBOX[t >>> 24] << 24) | (G.SBOX[(t >>> 16) & 0xff] << 16) | (G.SBOX[(t >>> 8) & 0xff] << 8) | G.SBOX[t & 0xff], t ^= G.RCON[(ksRow / keySize) | 0] << 24) : keySize > 6 && ksRow % keySize === 4 ? t = (G.SBOX[t >>> 24] << 24) | (G.SBOX[(t >>> 16) & 0xff] << 16) | (G.SBOX[(t >>> 8) & 0xff] << 8) | G.SBOX[t & 0xff] : void 0, this._keySchedule[ksRow - keySize] ^ t);
  21057. }
  21058. this._invKeySchedule = [];
  21059. for (invKsRow = _j = 0; 0 <= ksRows ? _j < ksRows : _j > ksRows; invKsRow = 0 <= ksRows ? ++_j : --_j) {
  21060. ksRow = ksRows - invKsRow;
  21061. t = this._keySchedule[ksRow - (invKsRow % 4 ? 0 : 4)];
  21062. this._invKeySchedule[invKsRow] = invKsRow < 4 || ksRow <= 4 ? t : G.INV_SUB_MIX[0][G.SBOX[t >>> 24]] ^ G.INV_SUB_MIX[1][G.SBOX[(t >>> 16) & 0xff]] ^ G.INV_SUB_MIX[2][G.SBOX[(t >>> 8) & 0xff]] ^ G.INV_SUB_MIX[3][G.SBOX[t & 0xff]];
  21063. }
  21064. return true;
  21065. };
  21066. AES.prototype.encryptBlock = function(M) {
  21067. M = bufferToArray(new Buffer(M));
  21068. var out = this._doCryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX);
  21069. var buf = new Buffer(16);
  21070. buf.writeUInt32BE(out[0], 0);
  21071. buf.writeUInt32BE(out[1], 4);
  21072. buf.writeUInt32BE(out[2], 8);
  21073. buf.writeUInt32BE(out[3], 12);
  21074. return buf;
  21075. };
  21076. AES.prototype.decryptBlock = function(M) {
  21077. M = bufferToArray(new Buffer(M));
  21078. var temp = [M[3], M[1]];
  21079. M[1] = temp[0];
  21080. M[3] = temp[1];
  21081. var out = this._doCryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX);
  21082. var buf = new Buffer(16);
  21083. buf.writeUInt32BE(out[0], 0);
  21084. buf.writeUInt32BE(out[3], 4);
  21085. buf.writeUInt32BE(out[2], 8);
  21086. buf.writeUInt32BE(out[1], 12);
  21087. return buf;
  21088. };
  21089. AES.prototype.scrub = function() {
  21090. scrub_vec(this._keySchedule);
  21091. scrub_vec(this._invKeySchedule);
  21092. scrub_vec(this._key);
  21093. };
  21094. AES.prototype._doCryptBlock = function(M, keySchedule, SUB_MIX, SBOX) {
  21095. var ksRow, round, s0, s1, s2, s3, t0, t1, t2, t3, _i, _ref;
  21096. s0 = M[0] ^ keySchedule[0];
  21097. s1 = M[1] ^ keySchedule[1];
  21098. s2 = M[2] ^ keySchedule[2];
  21099. s3 = M[3] ^ keySchedule[3];
  21100. ksRow = 4;
  21101. for (round = _i = 1, _ref = this._nRounds; 1 <= _ref ? _i < _ref : _i > _ref; round = 1 <= _ref ? ++_i : --_i) {
  21102. t0 = SUB_MIX[0][s0 >>> 24] ^ SUB_MIX[1][(s1 >>> 16) & 0xff] ^ SUB_MIX[2][(s2 >>> 8) & 0xff] ^ SUB_MIX[3][s3 & 0xff] ^ keySchedule[ksRow++];
  21103. t1 = SUB_MIX[0][s1 >>> 24] ^ SUB_MIX[1][(s2 >>> 16) & 0xff] ^ SUB_MIX[2][(s3 >>> 8) & 0xff] ^ SUB_MIX[3][s0 & 0xff] ^ keySchedule[ksRow++];
  21104. t2 = SUB_MIX[0][s2 >>> 24] ^ SUB_MIX[1][(s3 >>> 16) & 0xff] ^ SUB_MIX[2][(s0 >>> 8) & 0xff] ^ SUB_MIX[3][s1 & 0xff] ^ keySchedule[ksRow++];
  21105. t3 = SUB_MIX[0][s3 >>> 24] ^ SUB_MIX[1][(s0 >>> 16) & 0xff] ^ SUB_MIX[2][(s1 >>> 8) & 0xff] ^ SUB_MIX[3][s2 & 0xff] ^ keySchedule[ksRow++];
  21106. s0 = t0;
  21107. s1 = t1;
  21108. s2 = t2;
  21109. s3 = t3;
  21110. }
  21111. t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++];
  21112. t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++];
  21113. t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++];
  21114. t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++];
  21115. return [
  21116. fixup_uint32(t0),
  21117. fixup_uint32(t1),
  21118. fixup_uint32(t2),
  21119. fixup_uint32(t3)
  21120. ];
  21121. };
  21122. exports.AES = AES;
  21123. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(47).Buffer))
  21124. /***/ },
  21125. /* 148 */
  21126. /***/ function(module, exports, __webpack_require__) {
  21127. /* WEBPACK VAR INJECTION */(function(Buffer) {var Transform = __webpack_require__(64).Transform;
  21128. var inherits = __webpack_require__(173);
  21129. module.exports = CipherBase;
  21130. inherits(CipherBase, Transform);
  21131. function CipherBase() {
  21132. Transform.call(this);
  21133. }
  21134. CipherBase.prototype.update = function (data, inputEnd, outputEnc) {
  21135. this.write(data, inputEnd);
  21136. var outData = new Buffer('');
  21137. var chunk;
  21138. while ((chunk = this.read())) {
  21139. outData = Buffer.concat([outData, chunk]);
  21140. }
  21141. if (outputEnc) {
  21142. outData = outData.toString(outputEnc);
  21143. }
  21144. return outData;
  21145. };
  21146. CipherBase.prototype.final = function (outputEnc) {
  21147. this.end();
  21148. var outData = new Buffer('');
  21149. var chunk;
  21150. while ((chunk = this.read())) {
  21151. outData = Buffer.concat([outData, chunk]);
  21152. }
  21153. if (outputEnc) {
  21154. outData = outData.toString(outputEnc);
  21155. }
  21156. return outData;
  21157. };
  21158. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(47).Buffer))
  21159. /***/ },
  21160. /* 149 */
  21161. /***/ function(module, exports, __webpack_require__) {
  21162. /* WEBPACK VAR INJECTION */(function(Buffer) {
  21163. module.exports = function (crypto, password, keyLen, ivLen) {
  21164. keyLen = keyLen/8;
  21165. ivLen = ivLen || 0;
  21166. var ki = 0;
  21167. var ii = 0;
  21168. var key = new Buffer(keyLen);
  21169. var iv = new Buffer(ivLen);
  21170. var addmd = 0;
  21171. var md, md_buf;
  21172. var i;
  21173. while (true) {
  21174. md = crypto.createHash('md5');
  21175. if(addmd++ > 0) {
  21176. md.update(md_buf);
  21177. }
  21178. md.update(password);
  21179. md_buf = md.digest();
  21180. i = 0;
  21181. if(keyLen > 0) {
  21182. while(true) {
  21183. if(keyLen === 0) {
  21184. break;
  21185. }
  21186. if(i === md_buf.length) {
  21187. break;
  21188. }
  21189. key[ki++] = md_buf[i];
  21190. keyLen--;
  21191. i++;
  21192. }
  21193. }
  21194. if(ivLen > 0 && i !== md_buf.length) {
  21195. while(true) {
  21196. if(ivLen === 0) {
  21197. break;
  21198. }
  21199. if(i === md_buf.length) {
  21200. break;
  21201. }
  21202. iv[ii++] = md_buf[i];
  21203. ivLen--;
  21204. i++;
  21205. }
  21206. }
  21207. if(keyLen === 0 && ivLen === 0) {
  21208. break;
  21209. }
  21210. }
  21211. for(i=0;i<md_buf.length;i++) {
  21212. md_buf[i] = 0;
  21213. }
  21214. return {
  21215. key: key,
  21216. iv: iv
  21217. };
  21218. };
  21219. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(47).Buffer))
  21220. /***/ },
  21221. /* 150 */
  21222. /***/ function(module, exports, __webpack_require__) {
  21223. /* WEBPACK VAR INJECTION */(function(Buffer) {var aes = __webpack_require__(147);
  21224. var Transform = __webpack_require__(148);
  21225. var inherits = __webpack_require__(173);
  21226. inherits(StreamCipher, Transform);
  21227. module.exports = StreamCipher;
  21228. function StreamCipher(mode, key, iv, decrypt) {
  21229. if (!(this instanceof StreamCipher)) {
  21230. return new StreamCipher(mode, key, iv);
  21231. }
  21232. Transform.call(this);
  21233. this._cipher = new aes.AES(key);
  21234. this._prev = new Buffer(iv.length);
  21235. this._cache = new Buffer('');
  21236. this._secCache = new Buffer('');
  21237. this._decrypt = decrypt;
  21238. iv.copy(this._prev);
  21239. this._mode = mode;
  21240. }
  21241. StreamCipher.prototype._transform = function (chunk, _, next) {
  21242. next(null, this._mode.encrypt(this, chunk, this._decrypt));
  21243. };
  21244. StreamCipher.prototype._flush = function (next) {
  21245. this._cipher.scrub();
  21246. next();
  21247. };
  21248. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(47).Buffer))
  21249. /***/ },
  21250. /* 151 */
  21251. /***/ function(module, exports, __webpack_require__) {
  21252. exports.encrypt = function (self, block) {
  21253. return self._cipher.encryptBlock(block);
  21254. };
  21255. exports.decrypt = function (self, block) {
  21256. return self._cipher.decryptBlock(block);
  21257. };
  21258. /***/ },
  21259. /* 152 */
  21260. /***/ function(module, exports, __webpack_require__) {
  21261. var xor = __webpack_require__(172);
  21262. exports.encrypt = function (self, block) {
  21263. var data = xor(block, self._prev);
  21264. self._prev = self._cipher.encryptBlock(data);
  21265. return self._prev;
  21266. };
  21267. exports.decrypt = function (self, block) {
  21268. var pad = self._prev;
  21269. self._prev = block;
  21270. var out = self._cipher.decryptBlock(block);
  21271. return xor(out, pad);
  21272. };
  21273. /***/ },
  21274. /* 153 */
  21275. /***/ function(module, exports, __webpack_require__) {
  21276. /* WEBPACK VAR INJECTION */(function(Buffer) {var xor = __webpack_require__(172);
  21277. exports.encrypt = function (self, data, decrypt) {
  21278. var out = new Buffer('');
  21279. var len;
  21280. while (data.length) {
  21281. if (self._cache.length === 0) {
  21282. self._cache = self._cipher.encryptBlock(self._prev);
  21283. self._prev = new Buffer('');
  21284. }
  21285. if (self._cache.length <= data.length) {
  21286. len = self._cache.length;
  21287. out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)]);
  21288. data = data.slice(len);
  21289. } else {
  21290. out = Buffer.concat([out, encryptStart(self, data, decrypt)]);
  21291. break;
  21292. }
  21293. }
  21294. return out;
  21295. };
  21296. function encryptStart(self, data, decrypt) {
  21297. var len = data.length;
  21298. var out = xor(data, self._cache);
  21299. self._cache = self._cache.slice(len);
  21300. self._prev = Buffer.concat([self._prev, decrypt?data:out]);
  21301. return out;
  21302. }
  21303. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(47).Buffer))
  21304. /***/ },
  21305. /* 154 */
  21306. /***/ function(module, exports, __webpack_require__) {
  21307. /* WEBPACK VAR INJECTION */(function(Buffer) {var xor = __webpack_require__(172);
  21308. function getBlock(self) {
  21309. self._prev = self._cipher.encryptBlock(self._prev);
  21310. return self._prev;
  21311. }
  21312. exports.encrypt = function (self, chunk) {
  21313. while (self._cache.length < chunk.length) {
  21314. self._cache = Buffer.concat([self._cache, getBlock(self)]);
  21315. }
  21316. var pad = self._cache.slice(0, chunk.length);
  21317. self._cache = self._cache.slice(chunk.length);
  21318. return xor(chunk, pad);
  21319. };
  21320. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(47).Buffer))
  21321. /***/ },
  21322. /* 155 */
  21323. /***/ function(module, exports, __webpack_require__) {
  21324. /* WEBPACK VAR INJECTION */(function(Buffer) {var xor = __webpack_require__(172);
  21325. function getBlock(self) {
  21326. var out = self._cipher.encryptBlock(self._prev);
  21327. incr32(self._prev);
  21328. return out;
  21329. }
  21330. exports.encrypt = function (self, chunk) {
  21331. while (self._cache.length < chunk.length) {
  21332. self._cache = Buffer.concat([self._cache, getBlock(self)]);
  21333. }
  21334. var pad = self._cache.slice(0, chunk.length);
  21335. self._cache = self._cache.slice(chunk.length);
  21336. return xor(chunk, pad);
  21337. };
  21338. function incr32(iv) {
  21339. var len = iv.length;
  21340. var item;
  21341. while (len--) {
  21342. item = iv.readUInt8(len);
  21343. if (item === 255) {
  21344. iv.writeUInt8(0, len);
  21345. } else {
  21346. item++;
  21347. iv.writeUInt8(item, len);
  21348. break;
  21349. }
  21350. }
  21351. }
  21352. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(47).Buffer))
  21353. /***/ },
  21354. /* 156 */
  21355. /***/ function(module, exports, __webpack_require__) {
  21356. module.exports = __webpack_require__(174);
  21357. /***/ },
  21358. /* 157 */
  21359. /***/ function(module, exports, __webpack_require__) {
  21360. /**
  21361. * Copyright (c) 2014 Petka Antonov
  21362. *
  21363. * Permission is hereby granted, free of charge, to any person obtaining a copy
  21364. * of this software and associated documentation files (the "Software"), to deal
  21365. * in the Software without restriction, including without limitation the rights
  21366. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  21367. * copies of the Software, and to permit persons to whom the Software is
  21368. * furnished to do so, subject to the following conditions:</p>
  21369. *
  21370. * The above copyright notice and this permission notice shall be included in
  21371. * all copies or substantial portions of the Software.
  21372. *
  21373. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  21374. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21375. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21376. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21377. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21378. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21379. * THE SOFTWARE.
  21380. *
  21381. */
  21382. var isES5 = (function(){
  21383. "use strict";
  21384. return this === void 0;
  21385. })();
  21386. if (isES5) {
  21387. module.exports = {
  21388. freeze: Object.freeze,
  21389. defineProperty: Object.defineProperty,
  21390. keys: Object.keys,
  21391. getPrototypeOf: Object.getPrototypeOf,
  21392. isArray: Array.isArray,
  21393. isES5: isES5
  21394. };
  21395. }
  21396. else {
  21397. var has = {}.hasOwnProperty;
  21398. var str = {}.toString;
  21399. var proto = {}.constructor.prototype;
  21400. var ObjectKeys = function ObjectKeys(o) {
  21401. var ret = [];
  21402. for (var key in o) {
  21403. if (has.call(o, key)) {
  21404. ret.push(key);
  21405. }
  21406. }
  21407. return ret;
  21408. }
  21409. var ObjectDefineProperty = function ObjectDefineProperty(o, key, desc) {
  21410. o[key] = desc.value;
  21411. return o;
  21412. }
  21413. var ObjectFreeze = function ObjectFreeze(obj) {
  21414. return obj;
  21415. }
  21416. var ObjectGetPrototypeOf = function ObjectGetPrototypeOf(obj) {
  21417. try {
  21418. return Object(obj).constructor.prototype;
  21419. }
  21420. catch (e) {
  21421. return proto;
  21422. }
  21423. }
  21424. var ArrayIsArray = function ArrayIsArray(obj) {
  21425. try {
  21426. return str.call(obj) === "[object Array]";
  21427. }
  21428. catch(e) {
  21429. return false;
  21430. }
  21431. }
  21432. module.exports = {
  21433. isArray: ArrayIsArray,
  21434. keys: ObjectKeys,
  21435. defineProperty: ObjectDefineProperty,
  21436. freeze: ObjectFreeze,
  21437. getPrototypeOf: ObjectGetPrototypeOf,
  21438. isES5: isES5
  21439. };
  21440. }
  21441. /***/ },
  21442. /* 158 */
  21443. /***/ function(module, exports, __webpack_require__) {
  21444. /* WEBPACK VAR INJECTION */(function(process) {/**
  21445. * Copyright (c) 2014 Petka Antonov
  21446. *
  21447. * Permission is hereby granted, free of charge, to any person obtaining a copy
  21448. * of this software and associated documentation files (the "Software"), to deal
  21449. * in the Software without restriction, including without limitation the rights
  21450. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  21451. * copies of the Software, and to permit persons to whom the Software is
  21452. * furnished to do so, subject to the following conditions:</p>
  21453. *
  21454. * The above copyright notice and this permission notice shall be included in
  21455. * all copies or substantial portions of the Software.
  21456. *
  21457. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  21458. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21459. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21460. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21461. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21462. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21463. * THE SOFTWARE.
  21464. *
  21465. */
  21466. "use strict";
  21467. var global = __webpack_require__(107);
  21468. var schedule;
  21469. if (typeof process !== "undefined" && process !== null &&
  21470. typeof process.cwd === "function" &&
  21471. typeof process.nextTick === "function" &&
  21472. typeof process.version === "string") {
  21473. schedule = function Promise$_Scheduler(fn) {
  21474. process.nextTick(fn);
  21475. };
  21476. }
  21477. else if ((typeof global.MutationObserver === "function" ||
  21478. typeof global.WebkitMutationObserver === "function" ||
  21479. typeof global.WebKitMutationObserver === "function") &&
  21480. typeof document !== "undefined" &&
  21481. typeof document.createElement === "function") {
  21482. schedule = (function(){
  21483. var MutationObserver = global.MutationObserver ||
  21484. global.WebkitMutationObserver ||
  21485. global.WebKitMutationObserver;
  21486. var div = document.createElement("div");
  21487. var queuedFn = void 0;
  21488. var observer = new MutationObserver(
  21489. function Promise$_Scheduler() {
  21490. var fn = queuedFn;
  21491. queuedFn = void 0;
  21492. fn();
  21493. }
  21494. );
  21495. observer.observe(div, {
  21496. attributes: true
  21497. });
  21498. return function Promise$_Scheduler(fn) {
  21499. queuedFn = fn;
  21500. div.setAttribute("class", "foo");
  21501. };
  21502. })();
  21503. }
  21504. else if (typeof global.postMessage === "function" &&
  21505. typeof global.importScripts !== "function" &&
  21506. typeof global.addEventListener === "function" &&
  21507. typeof global.removeEventListener === "function") {
  21508. var MESSAGE_KEY = "bluebird_message_key_" + Math.random();
  21509. schedule = (function(){
  21510. var queuedFn = void 0;
  21511. function Promise$_Scheduler(e) {
  21512. if (e.source === global &&
  21513. e.data === MESSAGE_KEY) {
  21514. var fn = queuedFn;
  21515. queuedFn = void 0;
  21516. fn();
  21517. }
  21518. }
  21519. global.addEventListener("message", Promise$_Scheduler, false);
  21520. return function Promise$_Scheduler(fn) {
  21521. queuedFn = fn;
  21522. global.postMessage(
  21523. MESSAGE_KEY, "*"
  21524. );
  21525. };
  21526. })();
  21527. }
  21528. else if (typeof global.MessageChannel === "function") {
  21529. schedule = (function(){
  21530. var queuedFn = void 0;
  21531. var channel = new global.MessageChannel();
  21532. channel.port1.onmessage = function Promise$_Scheduler() {
  21533. var fn = queuedFn;
  21534. queuedFn = void 0;
  21535. fn();
  21536. };
  21537. return function Promise$_Scheduler(fn) {
  21538. queuedFn = fn;
  21539. channel.port2.postMessage(null);
  21540. };
  21541. })();
  21542. }
  21543. else if (global.setTimeout) {
  21544. schedule = function Promise$_Scheduler(fn) {
  21545. setTimeout(fn, 4);
  21546. };
  21547. }
  21548. else {
  21549. schedule = function Promise$_Scheduler(fn) {
  21550. fn();
  21551. };
  21552. }
  21553. module.exports = schedule;
  21554. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(99)))
  21555. /***/ },
  21556. /* 159 */
  21557. /***/ function(module, exports, __webpack_require__) {
  21558. /**
  21559. * Copyright (c) 2014 Petka Antonov
  21560. *
  21561. * Permission is hereby granted, free of charge, to any person obtaining a copy
  21562. * of this software and associated documentation files (the "Software"), to deal
  21563. * in the Software without restriction, including without limitation the rights
  21564. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  21565. * copies of the Software, and to permit persons to whom the Software is
  21566. * furnished to do so, subject to the following conditions:</p>
  21567. *
  21568. * The above copyright notice and this permission notice shall be included in
  21569. * all copies or substantial portions of the Software.
  21570. *
  21571. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  21572. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21573. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21574. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21575. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21576. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21577. * THE SOFTWARE.
  21578. *
  21579. */
  21580. "use strict";
  21581. function arrayCopy(src, srcIndex, dst, dstIndex, len) {
  21582. for (var j = 0; j < len; ++j) {
  21583. dst[j + dstIndex] = src[j + srcIndex];
  21584. }
  21585. }
  21586. function pow2AtLeast(n) {
  21587. n = n >>> 0;
  21588. n = n - 1;
  21589. n = n | (n >> 1);
  21590. n = n | (n >> 2);
  21591. n = n | (n >> 4);
  21592. n = n | (n >> 8);
  21593. n = n | (n >> 16);
  21594. return n + 1;
  21595. }
  21596. function getCapacity(capacity) {
  21597. if (typeof capacity !== "number") return 16;
  21598. return pow2AtLeast(
  21599. Math.min(
  21600. Math.max(16, capacity), 1073741824)
  21601. );
  21602. }
  21603. function Queue(capacity) {
  21604. this._capacity = getCapacity(capacity);
  21605. this._length = 0;
  21606. this._front = 0;
  21607. this._makeCapacity();
  21608. }
  21609. Queue.prototype._willBeOverCapacity =
  21610. function Queue$_willBeOverCapacity(size) {
  21611. return this._capacity < size;
  21612. };
  21613. Queue.prototype._pushOne = function Queue$_pushOne(arg) {
  21614. var length = this.length();
  21615. this._checkCapacity(length + 1);
  21616. var i = (this._front + length) & (this._capacity - 1);
  21617. this[i] = arg;
  21618. this._length = length + 1;
  21619. };
  21620. Queue.prototype.push = function Queue$push(fn, receiver, arg) {
  21621. var length = this.length() + 3;
  21622. if (this._willBeOverCapacity(length)) {
  21623. this._pushOne(fn);
  21624. this._pushOne(receiver);
  21625. this._pushOne(arg);
  21626. return;
  21627. }
  21628. var j = this._front + length - 3;
  21629. this._checkCapacity(length);
  21630. var wrapMask = this._capacity - 1;
  21631. this[(j + 0) & wrapMask] = fn;
  21632. this[(j + 1) & wrapMask] = receiver;
  21633. this[(j + 2) & wrapMask] = arg;
  21634. this._length = length;
  21635. };
  21636. Queue.prototype.shift = function Queue$shift() {
  21637. var front = this._front,
  21638. ret = this[front];
  21639. this[front] = void 0;
  21640. this._front = (front + 1) & (this._capacity - 1);
  21641. this._length--;
  21642. return ret;
  21643. };
  21644. Queue.prototype.length = function Queue$length() {
  21645. return this._length;
  21646. };
  21647. Queue.prototype._makeCapacity = function Queue$_makeCapacity() {
  21648. var len = this._capacity;
  21649. for (var i = 0; i < len; ++i) {
  21650. this[i] = void 0;
  21651. }
  21652. };
  21653. Queue.prototype._checkCapacity = function Queue$_checkCapacity(size) {
  21654. if (this._capacity < size) {
  21655. this._resizeTo(this._capacity << 3);
  21656. }
  21657. };
  21658. Queue.prototype._resizeTo = function Queue$_resizeTo(capacity) {
  21659. var oldFront = this._front;
  21660. var oldCapacity = this._capacity;
  21661. var oldQueue = new Array(oldCapacity);
  21662. var length = this.length();
  21663. arrayCopy(this, 0, oldQueue, 0, oldCapacity);
  21664. this._capacity = capacity;
  21665. this._makeCapacity();
  21666. this._front = 0;
  21667. if (oldFront + length <= oldCapacity) {
  21668. arrayCopy(oldQueue, oldFront, this, 0, length);
  21669. }
  21670. else { var lengthBeforeWrapping =
  21671. length - ((oldFront + length) & (oldCapacity - 1));
  21672. arrayCopy(oldQueue, oldFront, this, 0, lengthBeforeWrapping);
  21673. arrayCopy(oldQueue, 0, this, lengthBeforeWrapping,
  21674. length - lengthBeforeWrapping);
  21675. }
  21676. };
  21677. module.exports = Queue;
  21678. /***/ },
  21679. /* 160 */
  21680. /***/ function(module, exports, __webpack_require__) {
  21681. /**
  21682. * Copyright (c) 2014 Petka Antonov
  21683. *
  21684. * Permission is hereby granted, free of charge, to any person obtaining a copy
  21685. * of this software and associated documentation files (the "Software"), to deal
  21686. * in the Software without restriction, including without limitation the rights
  21687. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  21688. * copies of the Software, and to permit persons to whom the Software is
  21689. * furnished to do so, subject to the following conditions:</p>
  21690. *
  21691. * The above copyright notice and this permission notice shall be included in
  21692. * all copies or substantial portions of the Software.
  21693. *
  21694. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  21695. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21696. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21697. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21698. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21699. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21700. * THE SOFTWARE.
  21701. *
  21702. */
  21703. "use strict";
  21704. module.exports = function (PromiseArray) {
  21705. var util = __webpack_require__(108);
  21706. var RangeError = __webpack_require__(110).RangeError;
  21707. var inherits = util.inherits;
  21708. var isArray = util.isArray;
  21709. function SomePromiseArray(values, boundTo) {
  21710. this.constructor$(values, boundTo);
  21711. this._howMany = 0;
  21712. this._unwrap = false;
  21713. this._initialized = false;
  21714. }
  21715. inherits(SomePromiseArray, PromiseArray);
  21716. SomePromiseArray.prototype._init = function SomePromiseArray$_init() {
  21717. if (!this._initialized) {
  21718. return;
  21719. }
  21720. if (this._howMany === 0) {
  21721. this._resolve([]);
  21722. return;
  21723. }
  21724. this._init$(void 0, -2);
  21725. var isArrayResolved = isArray(this._values);
  21726. this._holes = isArrayResolved ? this._values.length - this.length() : 0;
  21727. if (!this._isResolved() &&
  21728. isArrayResolved &&
  21729. this._howMany > this._canPossiblyFulfill()) {
  21730. var message = "(Promise.some) input array contains less than " +
  21731. this._howMany + " promises";
  21732. this._reject(new RangeError(message));
  21733. }
  21734. };
  21735. SomePromiseArray.prototype.init = function SomePromiseArray$init() {
  21736. this._initialized = true;
  21737. this._init();
  21738. };
  21739. SomePromiseArray.prototype.setUnwrap = function SomePromiseArray$setUnwrap() {
  21740. this._unwrap = true;
  21741. };
  21742. SomePromiseArray.prototype.howMany = function SomePromiseArray$howMany() {
  21743. return this._howMany;
  21744. };
  21745. SomePromiseArray.prototype.setHowMany =
  21746. function SomePromiseArray$setHowMany(count) {
  21747. if (this._isResolved()) return;
  21748. this._howMany = count;
  21749. };
  21750. SomePromiseArray.prototype._promiseFulfilled =
  21751. function SomePromiseArray$_promiseFulfilled(value) {
  21752. if (this._isResolved()) return;
  21753. this._addFulfilled(value);
  21754. if (this._fulfilled() === this.howMany()) {
  21755. this._values.length = this.howMany();
  21756. if (this.howMany() === 1 && this._unwrap) {
  21757. this._resolve(this._values[0]);
  21758. }
  21759. else {
  21760. this._resolve(this._values);
  21761. }
  21762. }
  21763. };
  21764. SomePromiseArray.prototype._promiseRejected =
  21765. function SomePromiseArray$_promiseRejected(reason) {
  21766. if (this._isResolved()) return;
  21767. this._addRejected(reason);
  21768. if (this.howMany() > this._canPossiblyFulfill()) {
  21769. if (this._values.length === this.length()) {
  21770. this._reject([]);
  21771. }
  21772. else {
  21773. this._reject(this._values.slice(this.length() + this._holes));
  21774. }
  21775. }
  21776. };
  21777. SomePromiseArray.prototype._fulfilled = function SomePromiseArray$_fulfilled() {
  21778. return this._totalResolved;
  21779. };
  21780. SomePromiseArray.prototype._rejected = function SomePromiseArray$_rejected() {
  21781. return this._values.length - this.length() - this._holes;
  21782. };
  21783. SomePromiseArray.prototype._addRejected =
  21784. function SomePromiseArray$_addRejected(reason) {
  21785. this._values.push(reason);
  21786. };
  21787. SomePromiseArray.prototype._addFulfilled =
  21788. function SomePromiseArray$_addFulfilled(value) {
  21789. this._values[this._totalResolved++] = value;
  21790. };
  21791. SomePromiseArray.prototype._canPossiblyFulfill =
  21792. function SomePromiseArray$_canPossiblyFulfill() {
  21793. return this.length() - this._rejected();
  21794. };
  21795. return SomePromiseArray;
  21796. };
  21797. /***/ },
  21798. /* 161 */
  21799. /***/ function(module, exports, __webpack_require__) {
  21800. /**
  21801. * Copyright (c) 2014 Petka Antonov
  21802. *
  21803. * Permission is hereby granted, free of charge, to any person obtaining a copy
  21804. * of this software and associated documentation files (the "Software"), to deal
  21805. * in the Software without restriction, including without limitation the rights
  21806. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  21807. * copies of the Software, and to permit persons to whom the Software is
  21808. * furnished to do so, subject to the following conditions:</p>
  21809. *
  21810. * The above copyright notice and this permission notice shall be included in
  21811. * all copies or substantial portions of the Software.
  21812. *
  21813. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  21814. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21815. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21816. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21817. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21818. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21819. * THE SOFTWARE.
  21820. *
  21821. */
  21822. "use strict";
  21823. module.exports = function(Promise, INTERNAL) {
  21824. var errors = __webpack_require__(110);
  21825. var TypeError = errors.TypeError;
  21826. var util = __webpack_require__(108);
  21827. var isArray = util.isArray;
  21828. var errorObj = util.errorObj;
  21829. var tryCatch1 = util.tryCatch1;
  21830. var yieldHandlers = [];
  21831. function promiseFromYieldHandler(value) {
  21832. var _yieldHandlers = yieldHandlers;
  21833. var _errorObj = errorObj;
  21834. var _Promise = Promise;
  21835. var len = _yieldHandlers.length;
  21836. for (var i = 0; i < len; ++i) {
  21837. var result = tryCatch1(_yieldHandlers[i], void 0, value);
  21838. if (result === _errorObj) {
  21839. return _Promise.reject(_errorObj.e);
  21840. }
  21841. var maybePromise = _Promise._cast(result,
  21842. promiseFromYieldHandler, void 0);
  21843. if (maybePromise instanceof _Promise) return maybePromise;
  21844. }
  21845. return null;
  21846. }
  21847. function PromiseSpawn(generatorFunction, receiver) {
  21848. var promise = this._promise = new Promise(INTERNAL);
  21849. promise._setTrace(void 0);
  21850. this._generatorFunction = generatorFunction;
  21851. this._receiver = receiver;
  21852. this._generator = void 0;
  21853. }
  21854. PromiseSpawn.prototype.promise = function PromiseSpawn$promise() {
  21855. return this._promise;
  21856. };
  21857. PromiseSpawn.prototype._run = function PromiseSpawn$_run() {
  21858. this._generator = this._generatorFunction.call(this._receiver);
  21859. this._receiver =
  21860. this._generatorFunction = void 0;
  21861. this._next(void 0);
  21862. };
  21863. PromiseSpawn.prototype._continue = function PromiseSpawn$_continue(result) {
  21864. if (result === errorObj) {
  21865. this._generator = void 0;
  21866. var trace = errors.canAttach(result.e)
  21867. ? result.e : new Error(result.e + "");
  21868. this._promise._attachExtraTrace(trace);
  21869. this._promise._reject(result.e, trace);
  21870. return;
  21871. }
  21872. var value = result.value;
  21873. if (result.done === true) {
  21874. this._generator = void 0;
  21875. if (!this._promise._tryFollow(value)) {
  21876. this._promise._fulfill(value);
  21877. }
  21878. }
  21879. else {
  21880. var maybePromise = Promise._cast(value, PromiseSpawn$_continue, void 0);
  21881. if (!(maybePromise instanceof Promise)) {
  21882. if (isArray(maybePromise)) {
  21883. maybePromise = Promise.all(maybePromise);
  21884. }
  21885. else {
  21886. maybePromise = promiseFromYieldHandler(maybePromise);
  21887. }
  21888. if (maybePromise === null) {
  21889. this._throw(new TypeError("A value was yielded that could not be treated as a promise"));
  21890. return;
  21891. }
  21892. }
  21893. maybePromise._then(
  21894. this._next,
  21895. this._throw,
  21896. void 0,
  21897. this,
  21898. null
  21899. );
  21900. }
  21901. };
  21902. PromiseSpawn.prototype._throw = function PromiseSpawn$_throw(reason) {
  21903. if (errors.canAttach(reason))
  21904. this._promise._attachExtraTrace(reason);
  21905. this._continue(
  21906. tryCatch1(this._generator["throw"], this._generator, reason)
  21907. );
  21908. };
  21909. PromiseSpawn.prototype._next = function PromiseSpawn$_next(value) {
  21910. this._continue(
  21911. tryCatch1(this._generator.next, this._generator, value)
  21912. );
  21913. };
  21914. PromiseSpawn.addYieldHandler = function PromiseSpawn$AddYieldHandler(fn) {
  21915. if (typeof fn !== "function") throw new TypeError("fn must be a function");
  21916. yieldHandlers.push(fn);
  21917. };
  21918. return PromiseSpawn;
  21919. };
  21920. /***/ },
  21921. /* 162 */
  21922. /***/ function(module, exports, __webpack_require__) {
  21923. /**
  21924. * Copyright (c) 2014 Petka Antonov
  21925. *
  21926. * Permission is hereby granted, free of charge, to any person obtaining a copy
  21927. * of this software and associated documentation files (the "Software"), to deal
  21928. * in the Software without restriction, including without limitation the rights
  21929. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  21930. * copies of the Software, and to permit persons to whom the Software is
  21931. * furnished to do so, subject to the following conditions:</p>
  21932. *
  21933. * The above copyright notice and this permission notice shall be included in
  21934. * all copies or substantial portions of the Software.
  21935. *
  21936. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  21937. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21938. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21939. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21940. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21941. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21942. * THE SOFTWARE.
  21943. *
  21944. */
  21945. "use strict";
  21946. module.exports = function(Promise, PromiseArray) {
  21947. var util = __webpack_require__(108);
  21948. var inherits = util.inherits;
  21949. var es5 = __webpack_require__(157);
  21950. function PropertiesPromiseArray(obj, boundTo) {
  21951. var keys = es5.keys(obj);
  21952. var values = new Array(keys.length);
  21953. for (var i = 0, len = values.length; i < len; ++i) {
  21954. values[i] = obj[keys[i]];
  21955. }
  21956. this.constructor$(values, boundTo);
  21957. if (!this._isResolved()) {
  21958. for (var i = 0, len = keys.length; i < len; ++i) {
  21959. values.push(keys[i]);
  21960. }
  21961. }
  21962. }
  21963. inherits(PropertiesPromiseArray, PromiseArray);
  21964. PropertiesPromiseArray.prototype._init =
  21965. function PropertiesPromiseArray$_init() {
  21966. this._init$(void 0, -3) ;
  21967. };
  21968. PropertiesPromiseArray.prototype._promiseFulfilled =
  21969. function PropertiesPromiseArray$_promiseFulfilled(value, index) {
  21970. if (this._isResolved()) return;
  21971. this._values[index] = value;
  21972. var totalResolved = ++this._totalResolved;
  21973. if (totalResolved >= this._length) {
  21974. var val = {};
  21975. var keyOffset = this.length();
  21976. for (var i = 0, len = this.length(); i < len; ++i) {
  21977. val[this._values[i + keyOffset]] = this._values[i];
  21978. }
  21979. this._resolve(val);
  21980. }
  21981. };
  21982. PropertiesPromiseArray.prototype._promiseProgressed =
  21983. function PropertiesPromiseArray$_promiseProgressed(value, index) {
  21984. if (this._isResolved()) return;
  21985. this._promise._progress({
  21986. key: this._values[index + this.length()],
  21987. value: value
  21988. });
  21989. };
  21990. PromiseArray.PropertiesPromiseArray = PropertiesPromiseArray;
  21991. return PropertiesPromiseArray;
  21992. };
  21993. /***/ },
  21994. /* 163 */
  21995. /***/ function(module, exports, __webpack_require__) {
  21996. /**
  21997. * Copyright (c) 2014 Petka Antonov
  21998. *
  21999. * Permission is hereby granted, free of charge, to any person obtaining a copy
  22000. * of this software and associated documentation files (the "Software"), to deal
  22001. * in the Software without restriction, including without limitation the rights
  22002. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  22003. * copies of the Software, and to permit persons to whom the Software is
  22004. * furnished to do so, subject to the following conditions:</p>
  22005. *
  22006. * The above copyright notice and this permission notice shall be included in
  22007. * all copies or substantial portions of the Software.
  22008. *
  22009. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22010. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  22011. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22012. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22013. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22014. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22015. * THE SOFTWARE.
  22016. *
  22017. */
  22018. "use strict";
  22019. module.exports = function(Promise, PromiseArray) {
  22020. var PromiseInspection = Promise.PromiseInspection;
  22021. var util = __webpack_require__(108);
  22022. var inherits = util.inherits;
  22023. function SettledPromiseArray(values, boundTo) {
  22024. this.constructor$(values, boundTo);
  22025. }
  22026. inherits(SettledPromiseArray, PromiseArray);
  22027. SettledPromiseArray.prototype._promiseResolved =
  22028. function SettledPromiseArray$_promiseResolved(index, inspection) {
  22029. this._values[index] = inspection;
  22030. var totalResolved = ++this._totalResolved;
  22031. if (totalResolved >= this._length) {
  22032. this._resolve(this._values);
  22033. }
  22034. };
  22035. SettledPromiseArray.prototype._promiseFulfilled =
  22036. function SettledPromiseArray$_promiseFulfilled(value, index) {
  22037. if (this._isResolved()) return;
  22038. var ret = new PromiseInspection();
  22039. ret._bitField = 268435456;
  22040. ret._settledValue = value;
  22041. this._promiseResolved(index, ret);
  22042. };
  22043. SettledPromiseArray.prototype._promiseRejected =
  22044. function SettledPromiseArray$_promiseRejected(reason, index) {
  22045. if (this._isResolved()) return;
  22046. var ret = new PromiseInspection();
  22047. ret._bitField = 134217728;
  22048. ret._settledValue = reason;
  22049. this._promiseResolved(index, ret);
  22050. };
  22051. return SettledPromiseArray;
  22052. };
  22053. /***/ },
  22054. /* 164 */
  22055. /***/ function(module, exports, __webpack_require__) {
  22056. "use strict";
  22057. var config = {
  22058. instrument: false
  22059. };
  22060. function configure(name, value) {
  22061. if (arguments.length === 2) {
  22062. config[name] = value;
  22063. } else {
  22064. return config[name];
  22065. }
  22066. }
  22067. exports.config = config;
  22068. exports.configure = configure;
  22069. /***/ },
  22070. /* 165 */
  22071. /***/ function(module, exports, __webpack_require__) {
  22072. "use strict";
  22073. function objectOrFunction(x) {
  22074. return isFunction(x) || (typeof x === "object" && x !== null);
  22075. }
  22076. function isFunction(x) {
  22077. return typeof x === "function";
  22078. }
  22079. function isArray(x) {
  22080. return Object.prototype.toString.call(x) === "[object Array]";
  22081. }
  22082. // Date.now is not available in browsers < IE9
  22083. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility
  22084. var now = Date.now || function() { return new Date().getTime(); };
  22085. exports.objectOrFunction = objectOrFunction;
  22086. exports.isFunction = isFunction;
  22087. exports.isArray = isArray;
  22088. exports.now = now;
  22089. /***/ },
  22090. /* 166 */
  22091. /***/ function(module, exports, __webpack_require__) {
  22092. "use strict";
  22093. /* global toString */
  22094. var isArray = __webpack_require__(165).isArray;
  22095. var isFunction = __webpack_require__(165).isFunction;
  22096. /**
  22097. Returns a promise that is fulfilled when all the given promises have been
  22098. fulfilled, or rejected if any of them become rejected. The return promise
  22099. is fulfilled with an array that gives all the values in the order they were
  22100. passed in the `promises` array argument.
  22101. Example:
  22102. ```javascript
  22103. var promise1 = RSVP.resolve(1);
  22104. var promise2 = RSVP.resolve(2);
  22105. var promise3 = RSVP.resolve(3);
  22106. var promises = [ promise1, promise2, promise3 ];
  22107. RSVP.all(promises).then(function(array){
  22108. // The array here would be [ 1, 2, 3 ];
  22109. });
  22110. ```
  22111. If any of the `promises` given to `RSVP.all` are rejected, the first promise
  22112. that is rejected will be given as an argument to the returned promises's
  22113. rejection handler. For example:
  22114. Example:
  22115. ```javascript
  22116. var promise1 = RSVP.resolve(1);
  22117. var promise2 = RSVP.reject(new Error("2"));
  22118. var promise3 = RSVP.reject(new Error("3"));
  22119. var promises = [ promise1, promise2, promise3 ];
  22120. RSVP.all(promises).then(function(array){
  22121. // Code here never runs because there are rejected promises!
  22122. }, function(error) {
  22123. // error.message === "2"
  22124. });
  22125. ```
  22126. @method all
  22127. @for RSVP
  22128. @param {Array} promises
  22129. @param {String} label
  22130. @return {Promise} promise that is fulfilled when all `promises` have been
  22131. fulfilled, or rejected if any of them become rejected.
  22132. */
  22133. function all(promises) {
  22134. /*jshint validthis:true */
  22135. var Promise = this;
  22136. if (!isArray(promises)) {
  22137. throw new TypeError('You must pass an array to all.');
  22138. }
  22139. return new Promise(function(resolve, reject) {
  22140. var results = [], remaining = promises.length,
  22141. promise;
  22142. if (remaining === 0) {
  22143. resolve([]);
  22144. }
  22145. function resolver(index) {
  22146. return function(value) {
  22147. resolveAll(index, value);
  22148. };
  22149. }
  22150. function resolveAll(index, value) {
  22151. results[index] = value;
  22152. if (--remaining === 0) {
  22153. resolve(results);
  22154. }
  22155. }
  22156. for (var i = 0; i < promises.length; i++) {
  22157. promise = promises[i];
  22158. if (promise && isFunction(promise.then)) {
  22159. promise.then(resolver(i), reject);
  22160. } else {
  22161. resolveAll(i, promise);
  22162. }
  22163. }
  22164. });
  22165. }
  22166. exports.all = all;
  22167. /***/ },
  22168. /* 167 */
  22169. /***/ function(module, exports, __webpack_require__) {
  22170. "use strict";
  22171. /* global toString */
  22172. var isArray = __webpack_require__(165).isArray;
  22173. /**
  22174. `RSVP.race` allows you to watch a series of promises and act as soon as the
  22175. first promise given to the `promises` argument fulfills or rejects.
  22176. Example:
  22177. ```javascript
  22178. var promise1 = new RSVP.Promise(function(resolve, reject){
  22179. setTimeout(function(){
  22180. resolve("promise 1");
  22181. }, 200);
  22182. });
  22183. var promise2 = new RSVP.Promise(function(resolve, reject){
  22184. setTimeout(function(){
  22185. resolve("promise 2");
  22186. }, 100);
  22187. });
  22188. RSVP.race([promise1, promise2]).then(function(result){
  22189. // result === "promise 2" because it was resolved before promise1
  22190. // was resolved.
  22191. });
  22192. ```
  22193. `RSVP.race` is deterministic in that only the state of the first completed
  22194. promise matters. For example, even if other promises given to the `promises`
  22195. array argument are resolved, but the first completed promise has become
  22196. rejected before the other promises became fulfilled, the returned promise
  22197. will become rejected:
  22198. ```javascript
  22199. var promise1 = new RSVP.Promise(function(resolve, reject){
  22200. setTimeout(function(){
  22201. resolve("promise 1");
  22202. }, 200);
  22203. });
  22204. var promise2 = new RSVP.Promise(function(resolve, reject){
  22205. setTimeout(function(){
  22206. reject(new Error("promise 2"));
  22207. }, 100);
  22208. });
  22209. RSVP.race([promise1, promise2]).then(function(result){
  22210. // Code here never runs because there are rejected promises!
  22211. }, function(reason){
  22212. // reason.message === "promise2" because promise 2 became rejected before
  22213. // promise 1 became fulfilled
  22214. });
  22215. ```
  22216. @method race
  22217. @for RSVP
  22218. @param {Array} promises array of promises to observe
  22219. @param {String} label optional string for describing the promise returned.
  22220. Useful for tooling.
  22221. @return {Promise} a promise that becomes fulfilled with the value the first
  22222. completed promises is resolved with if the first completed promise was
  22223. fulfilled, or rejected with the reason that the first completed promise
  22224. was rejected with.
  22225. */
  22226. function race(promises) {
  22227. /*jshint validthis:true */
  22228. var Promise = this;
  22229. if (!isArray(promises)) {
  22230. throw new TypeError('You must pass an array to race.');
  22231. }
  22232. return new Promise(function(resolve, reject) {
  22233. var results = [], promise;
  22234. for (var i = 0; i < promises.length; i++) {
  22235. promise = promises[i];
  22236. if (promise && typeof promise.then === 'function') {
  22237. promise.then(resolve, reject);
  22238. } else {
  22239. resolve(promise);
  22240. }
  22241. }
  22242. });
  22243. }
  22244. exports.race = race;
  22245. /***/ },
  22246. /* 168 */
  22247. /***/ function(module, exports, __webpack_require__) {
  22248. "use strict";
  22249. function resolve(value) {
  22250. /*jshint validthis:true */
  22251. if (value && typeof value === 'object' && value.constructor === this) {
  22252. return value;
  22253. }
  22254. var Promise = this;
  22255. return new Promise(function(resolve) {
  22256. resolve(value);
  22257. });
  22258. }
  22259. exports.resolve = resolve;
  22260. /***/ },
  22261. /* 169 */
  22262. /***/ function(module, exports, __webpack_require__) {
  22263. "use strict";
  22264. /**
  22265. `RSVP.reject` returns a promise that will become rejected with the passed
  22266. `reason`. `RSVP.reject` is essentially shorthand for the following:
  22267. ```javascript
  22268. var promise = new RSVP.Promise(function(resolve, reject){
  22269. reject(new Error('WHOOPS'));
  22270. });
  22271. promise.then(function(value){
  22272. // Code here doesn't run because the promise is rejected!
  22273. }, function(reason){
  22274. // reason.message === 'WHOOPS'
  22275. });
  22276. ```
  22277. Instead of writing the above, your code now simply becomes the following:
  22278. ```javascript
  22279. var promise = RSVP.reject(new Error('WHOOPS'));
  22280. promise.then(function(value){
  22281. // Code here doesn't run because the promise is rejected!
  22282. }, function(reason){
  22283. // reason.message === 'WHOOPS'
  22284. });
  22285. ```
  22286. @method reject
  22287. @for RSVP
  22288. @param {Any} reason value that the returned promise will be rejected with.
  22289. @param {String} label optional string for identifying the returned promise.
  22290. Useful for tooling.
  22291. @return {Promise} a promise that will become rejected with the given
  22292. `reason`.
  22293. */
  22294. function reject(reason) {
  22295. /*jshint validthis:true */
  22296. var Promise = this;
  22297. return new Promise(function (resolve, reject) {
  22298. reject(reason);
  22299. });
  22300. }
  22301. exports.reject = reject;
  22302. /***/ },
  22303. /* 170 */
  22304. /***/ function(module, exports, __webpack_require__) {
  22305. /* WEBPACK VAR INJECTION */(function(global, process) {"use strict";
  22306. var browserGlobal = (typeof window !== 'undefined') ? window : {};
  22307. var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
  22308. var local = (typeof global !== 'undefined') ? global : (this === undefined? window:this);
  22309. // node
  22310. function useNextTick() {
  22311. return function() {
  22312. process.nextTick(flush);
  22313. };
  22314. }
  22315. function useMutationObserver() {
  22316. var iterations = 0;
  22317. var observer = new BrowserMutationObserver(flush);
  22318. var node = document.createTextNode('');
  22319. observer.observe(node, { characterData: true });
  22320. return function() {
  22321. node.data = (iterations = ++iterations % 2);
  22322. };
  22323. }
  22324. function useSetTimeout() {
  22325. return function() {
  22326. local.setTimeout(flush, 1);
  22327. };
  22328. }
  22329. var queue = [];
  22330. function flush() {
  22331. for (var i = 0; i < queue.length; i++) {
  22332. var tuple = queue[i];
  22333. var callback = tuple[0], arg = tuple[1];
  22334. callback(arg);
  22335. }
  22336. queue = [];
  22337. }
  22338. var scheduleFlush;
  22339. // Decide what async method to use to triggering processing of queued callbacks:
  22340. if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
  22341. scheduleFlush = useNextTick();
  22342. } else if (BrowserMutationObserver) {
  22343. scheduleFlush = useMutationObserver();
  22344. } else {
  22345. scheduleFlush = useSetTimeout();
  22346. }
  22347. function asap(callback, arg) {
  22348. var length = queue.push([callback, arg]);
  22349. if (length === 1) {
  22350. // If length is 1, that means that we need to schedule an async flush.
  22351. // If additional callbacks are queued before the queue is flushed, they
  22352. // will be processed by this flush that we are scheduling.
  22353. scheduleFlush();
  22354. }
  22355. }
  22356. exports.asap = asap;
  22357. /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(99)))
  22358. /***/ },
  22359. /* 171 */
  22360. /***/ function(module, exports, __webpack_require__) {
  22361. /* (ignored) */
  22362. /***/ },
  22363. /* 172 */
  22364. /***/ function(module, exports, __webpack_require__) {
  22365. /* WEBPACK VAR INJECTION */(function(Buffer) {module.exports = xor;
  22366. function xor(a, b) {
  22367. var len = Math.min(a.length, b.length);
  22368. var out = new Buffer(len);
  22369. var i = -1;
  22370. while (++i < len) {
  22371. out.writeUInt8(a[i] ^ b[i], i);
  22372. }
  22373. return out;
  22374. }
  22375. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(47).Buffer))
  22376. /***/ },
  22377. /* 173 */
  22378. /***/ function(module, exports, __webpack_require__) {
  22379. if (typeof Object.create === 'function') {
  22380. // implementation from standard node.js 'util' module
  22381. module.exports = function inherits(ctor, superCtor) {
  22382. ctor.super_ = superCtor
  22383. ctor.prototype = Object.create(superCtor.prototype, {
  22384. constructor: {
  22385. value: ctor,
  22386. enumerable: false,
  22387. writable: true,
  22388. configurable: true
  22389. }
  22390. });
  22391. };
  22392. } else {
  22393. // old school shim for old browsers
  22394. module.exports = function inherits(ctor, superCtor) {
  22395. ctor.super_ = superCtor
  22396. var TempCtor = function () {}
  22397. TempCtor.prototype = superCtor.prototype
  22398. ctor.prototype = new TempCtor()
  22399. ctor.prototype.constructor = ctor
  22400. }
  22401. }
  22402. /***/ },
  22403. /* 174 */
  22404. /***/ function(module, exports, __webpack_require__) {
  22405. /* WEBPACK VAR INJECTION */(function(process) {/**!
  22406. * agentkeepalive - lib/agent.js
  22407. *
  22408. * refer:
  22409. * * @atimb "Real keep-alive HTTP agent": https://gist.github.com/2963672
  22410. * * https://github.com/joyent/node/blob/master/lib/http.js
  22411. * * https://github.com/joyent/node/blob/master/lib/_http_agent.js
  22412. *
  22413. * Copyright(c) 2012 - 2013 fengmk2 <fengmk2@gmail.com>
  22414. * MIT Licensed
  22415. */
  22416. "use strict";
  22417. /**
  22418. * Module dependencies.
  22419. */
  22420. var http = __webpack_require__(30);
  22421. var https = __webpack_require__(46);
  22422. var util = __webpack_require__(79);
  22423. var debug;
  22424. if (process.env.NODE_DEBUG && /agentkeepalive/.test(process.env.NODE_DEBUG)) {
  22425. debug = function (x) {
  22426. console.error.apply(console, arguments);
  22427. };
  22428. } else {
  22429. debug = function () { };
  22430. }
  22431. var OriginalAgent = http.Agent;
  22432. if (process.version.indexOf('v0.8.') === 0 || process.version.indexOf('v0.10.') === 0) {
  22433. OriginalAgent = __webpack_require__(179).Agent;
  22434. debug('%s use _http_agent', process.version);
  22435. }
  22436. function Agent(options) {
  22437. options = options || {};
  22438. options.keepAlive = options.keepAlive !== false;
  22439. options.keepAliveMsecs = options.keepAliveMsecs || options.maxKeepAliveTime;
  22440. OriginalAgent.call(this, options);
  22441. var self = this;
  22442. // max requests per keepalive socket, default is 0, no limit.
  22443. self.maxKeepAliveRequests = parseInt(options.maxKeepAliveRequests, 10) || 0;
  22444. // max keep alive time, default 60 seconds.
  22445. // if set `keepAliveMsecs = 0`, will disable keepalive feature.
  22446. self.createSocketCount = 0;
  22447. self.timeoutSocketCount = 0;
  22448. self.requestFinishedCount = 0;
  22449. // override the `free` event listener
  22450. self.removeAllListeners('free');
  22451. self.on('free', function (socket, options) {
  22452. self.requestFinishedCount++;
  22453. socket._requestCount++;
  22454. var name = self.getName(options);
  22455. debug('agent.on(free)', name);
  22456. if (!self.isDestroyed(socket) &&
  22457. self.requests[name] && self.requests[name].length) {
  22458. self.requests[name].shift().onSocket(socket);
  22459. if (self.requests[name].length === 0) {
  22460. // don't leak
  22461. delete self.requests[name];
  22462. }
  22463. } else {
  22464. // If there are no pending requests, then put it in
  22465. // the freeSockets pool, but only if we're allowed to do so.
  22466. var req = socket._httpMessage;
  22467. if (req &&
  22468. req.shouldKeepAlive &&
  22469. !self.isDestroyed(socket) &&
  22470. self.options.keepAlive) {
  22471. var freeSockets = self.freeSockets[name];
  22472. var freeLen = freeSockets ? freeSockets.length : 0;
  22473. var count = freeLen;
  22474. if (self.sockets[name])
  22475. count += self.sockets[name].length;
  22476. if (count >= self.maxSockets || freeLen >= self.maxFreeSockets) {
  22477. self.removeSocket(socket, options);
  22478. socket.destroy();
  22479. } else {
  22480. freeSockets = freeSockets || [];
  22481. self.freeSockets[name] = freeSockets;
  22482. socket.setKeepAlive(true, self.keepAliveMsecs);
  22483. socket.unref && socket.unref();
  22484. socket._httpMessage = null;
  22485. self.removeSocket(socket, options);
  22486. freeSockets.push(socket);
  22487. // Avoid duplicitive timeout events by removing timeout listeners set on
  22488. // socket by previous requests. node does not do this normally because it
  22489. // assumes sockets are too short-lived for it to matter. It becomes a
  22490. // problem when sockets are being reused. Steps are being taken to fix
  22491. // this issue upstream in node v0.10.0.
  22492. //
  22493. // See https://github.com/joyent/node/commit/451ff1540ab536237e8d751d241d7fc3391a4087
  22494. if (self.keepAliveMsecs && socket._events && Array.isArray(socket._events.timeout)) {
  22495. socket.removeAllListeners('timeout');
  22496. // Restore the socket's setTimeout() that was remove as collateral
  22497. // damage.
  22498. socket.setTimeout(self.keepAliveMsecs, socket._maxKeepAliveTimeout);
  22499. }
  22500. }
  22501. } else {
  22502. self.removeSocket(socket, options);
  22503. socket.destroy();
  22504. }
  22505. }
  22506. });
  22507. }
  22508. util.inherits(Agent, OriginalAgent);
  22509. module.exports = Agent;
  22510. Agent.prototype.createSocket = function (req, options) {
  22511. var self = this;
  22512. var socket = OriginalAgent.prototype.createSocket.call(this, req, options);
  22513. socket._requestCount = 0;
  22514. if (self.keepAliveMsecs) {
  22515. socket._maxKeepAliveTimeout = function () {
  22516. debug('maxKeepAliveTimeout, socket destroy()');
  22517. socket.destroy();
  22518. self.timeoutSocketCount++;
  22519. };
  22520. socket.setTimeout(self.keepAliveMsecs, socket._maxKeepAliveTimeout);
  22521. // Disable Nagle's algorithm: http://blog.caustik.com/2012/04/08/scaling-node-js-to-100k-concurrent-connections/
  22522. socket.setNoDelay(true);
  22523. }
  22524. this.createSocketCount++;
  22525. return socket;
  22526. };
  22527. Agent.prototype.removeSocket = function (s, options) {
  22528. OriginalAgent.prototype.removeSocket.call(this, s, options);
  22529. var name = this.getName(options);
  22530. debug('removeSocket', name, 'destroyed:', this.isDestroyed(s));
  22531. if (this.isDestroyed(s) && this.freeSockets[name]) {
  22532. var index = this.freeSockets[name].indexOf(s);
  22533. if (index !== -1) {
  22534. this.freeSockets[name].splice(index, 1);
  22535. if (this.freeSockets[name].length === 0) {
  22536. // don't leak
  22537. delete this.freeSockets[name];
  22538. }
  22539. }
  22540. }
  22541. };
  22542. function HttpsAgent(options) {
  22543. Agent.call(this, options);
  22544. this.defaultPort = 443;
  22545. this.protocol = 'https:';
  22546. }
  22547. util.inherits(HttpsAgent, Agent);
  22548. HttpsAgent.prototype.createConnection = https.globalAgent.createConnection;
  22549. HttpsAgent.prototype.getName = function(options) {
  22550. var name = Agent.prototype.getName.call(this, options);
  22551. name += ':';
  22552. if (options.ca)
  22553. name += options.ca;
  22554. name += ':';
  22555. if (options.cert)
  22556. name += options.cert;
  22557. name += ':';
  22558. if (options.ciphers)
  22559. name += options.ciphers;
  22560. name += ':';
  22561. if (options.key)
  22562. name += options.key;
  22563. name += ':';
  22564. if (options.pfx)
  22565. name += options.pfx;
  22566. name += ':';
  22567. if (options.rejectUnauthorized !== undefined)
  22568. name += options.rejectUnauthorized;
  22569. return name;
  22570. };
  22571. Agent.HttpsAgent = HttpsAgent;
  22572. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(99)))
  22573. /***/ },
  22574. /* 175 */
  22575. /***/ function(module, exports, __webpack_require__) {
  22576. module.exports = Array.isArray || function (arr) {
  22577. return Object.prototype.toString.call(arr) == '[object Array]';
  22578. };
  22579. /***/ },
  22580. /* 176 */
  22581. /***/ function(module, exports, __webpack_require__) {
  22582. // Copyright Joyent, Inc. and other Node contributors.
  22583. //
  22584. // Permission is hereby granted, free of charge, to any person obtaining a
  22585. // copy of this software and associated documentation files (the
  22586. // "Software"), to deal in the Software without restriction, including
  22587. // without limitation the rights to use, copy, modify, merge, publish,
  22588. // distribute, sublicense, and/or sell copies of the Software, and to permit
  22589. // persons to whom the Software is furnished to do so, subject to the
  22590. // following conditions:
  22591. //
  22592. // The above copyright notice and this permission notice shall be included
  22593. // in all copies or substantial portions of the Software.
  22594. //
  22595. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  22596. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22597. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  22598. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  22599. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  22600. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  22601. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  22602. var Buffer = __webpack_require__(47).Buffer;
  22603. var isBufferEncoding = Buffer.isEncoding
  22604. || function(encoding) {
  22605. switch (encoding && encoding.toLowerCase()) {
  22606. case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;
  22607. default: return false;
  22608. }
  22609. }
  22610. function assertEncoding(encoding) {
  22611. if (encoding && !isBufferEncoding(encoding)) {
  22612. throw new Error('Unknown encoding: ' + encoding);
  22613. }
  22614. }
  22615. // StringDecoder provides an interface for efficiently splitting a series of
  22616. // buffers into a series of JS strings without breaking apart multi-byte
  22617. // characters. CESU-8 is handled as part of the UTF-8 encoding.
  22618. //
  22619. // @TODO Handling all encodings inside a single object makes it very difficult
  22620. // to reason about this code, so it should be split up in the future.
  22621. // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
  22622. // points as used by CESU-8.
  22623. var StringDecoder = exports.StringDecoder = function(encoding) {
  22624. this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
  22625. assertEncoding(encoding);
  22626. switch (this.encoding) {
  22627. case 'utf8':
  22628. // CESU-8 represents each of Surrogate Pair by 3-bytes
  22629. this.surrogateSize = 3;
  22630. break;
  22631. case 'ucs2':
  22632. case 'utf16le':
  22633. // UTF-16 represents each of Surrogate Pair by 2-bytes
  22634. this.surrogateSize = 2;
  22635. this.detectIncompleteChar = utf16DetectIncompleteChar;
  22636. break;
  22637. case 'base64':
  22638. // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
  22639. this.surrogateSize = 3;
  22640. this.detectIncompleteChar = base64DetectIncompleteChar;
  22641. break;
  22642. default:
  22643. this.write = passThroughWrite;
  22644. return;
  22645. }
  22646. // Enough space to store all bytes of a single character. UTF-8 needs 4
  22647. // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
  22648. this.charBuffer = new Buffer(6);
  22649. // Number of bytes received for the current incomplete multi-byte character.
  22650. this.charReceived = 0;
  22651. // Number of bytes expected for the current incomplete multi-byte character.
  22652. this.charLength = 0;
  22653. };
  22654. // write decodes the given buffer and returns it as JS string that is
  22655. // guaranteed to not contain any partial multi-byte characters. Any partial
  22656. // character found at the end of the buffer is buffered up, and will be
  22657. // returned when calling write again with the remaining bytes.
  22658. //
  22659. // Note: Converting a Buffer containing an orphan surrogate to a String
  22660. // currently works, but converting a String to a Buffer (via `new Buffer`, or
  22661. // Buffer#write) will replace incomplete surrogates with the unicode
  22662. // replacement character. See https://codereview.chromium.org/121173009/ .
  22663. StringDecoder.prototype.write = function(buffer) {
  22664. var charStr = '';
  22665. // if our last write ended with an incomplete multibyte character
  22666. while (this.charLength) {
  22667. // determine how many remaining bytes this buffer has to offer for this char
  22668. var available = (buffer.length >= this.charLength - this.charReceived) ?
  22669. this.charLength - this.charReceived :
  22670. buffer.length;
  22671. // add the new bytes to the char buffer
  22672. buffer.copy(this.charBuffer, this.charReceived, 0, available);
  22673. this.charReceived += available;
  22674. if (this.charReceived < this.charLength) {
  22675. // still not enough chars in this buffer? wait for more ...
  22676. return '';
  22677. }
  22678. // remove bytes belonging to the current character from the buffer
  22679. buffer = buffer.slice(available, buffer.length);
  22680. // get the character that was split
  22681. charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
  22682. // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
  22683. var charCode = charStr.charCodeAt(charStr.length - 1);
  22684. if (charCode >= 0xD800 && charCode <= 0xDBFF) {
  22685. this.charLength += this.surrogateSize;
  22686. charStr = '';
  22687. continue;
  22688. }
  22689. this.charReceived = this.charLength = 0;
  22690. // if there are no more bytes in this buffer, just emit our char
  22691. if (buffer.length === 0) {
  22692. return charStr;
  22693. }
  22694. break;
  22695. }
  22696. // determine and set charLength / charReceived
  22697. this.detectIncompleteChar(buffer);
  22698. var end = buffer.length;
  22699. if (this.charLength) {
  22700. // buffer the incomplete character bytes we got
  22701. buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
  22702. end -= this.charReceived;
  22703. }
  22704. charStr += buffer.toString(this.encoding, 0, end);
  22705. var end = charStr.length - 1;
  22706. var charCode = charStr.charCodeAt(end);
  22707. // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
  22708. if (charCode >= 0xD800 && charCode <= 0xDBFF) {
  22709. var size = this.surrogateSize;
  22710. this.charLength += size;
  22711. this.charReceived += size;
  22712. this.charBuffer.copy(this.charBuffer, size, 0, size);
  22713. buffer.copy(this.charBuffer, 0, 0, size);
  22714. return charStr.substring(0, end);
  22715. }
  22716. // or just emit the charStr
  22717. return charStr;
  22718. };
  22719. // detectIncompleteChar determines if there is an incomplete UTF-8 character at
  22720. // the end of the given buffer. If so, it sets this.charLength to the byte
  22721. // length that character, and sets this.charReceived to the number of bytes
  22722. // that are available for this character.
  22723. StringDecoder.prototype.detectIncompleteChar = function(buffer) {
  22724. // determine how many bytes we have to check at the end of this buffer
  22725. var i = (buffer.length >= 3) ? 3 : buffer.length;
  22726. // Figure out if one of the last i bytes of our buffer announces an
  22727. // incomplete char.
  22728. for (; i > 0; i--) {
  22729. var c = buffer[buffer.length - i];
  22730. // See http://en.wikipedia.org/wiki/UTF-8#Description
  22731. // 110XXXXX
  22732. if (i == 1 && c >> 5 == 0x06) {
  22733. this.charLength = 2;
  22734. break;
  22735. }
  22736. // 1110XXXX
  22737. if (i <= 2 && c >> 4 == 0x0E) {
  22738. this.charLength = 3;
  22739. break;
  22740. }
  22741. // 11110XXX
  22742. if (i <= 3 && c >> 3 == 0x1E) {
  22743. this.charLength = 4;
  22744. break;
  22745. }
  22746. }
  22747. this.charReceived = i;
  22748. };
  22749. StringDecoder.prototype.end = function(buffer) {
  22750. var res = '';
  22751. if (buffer && buffer.length)
  22752. res = this.write(buffer);
  22753. if (this.charReceived) {
  22754. var cr = this.charReceived;
  22755. var buf = this.charBuffer;
  22756. var enc = this.encoding;
  22757. res += buf.slice(0, cr).toString(enc);
  22758. }
  22759. return res;
  22760. };
  22761. function passThroughWrite(buffer) {
  22762. return buffer.toString(this.encoding);
  22763. }
  22764. function utf16DetectIncompleteChar(buffer) {
  22765. this.charReceived = buffer.length % 2;
  22766. this.charLength = this.charReceived ? 2 : 0;
  22767. }
  22768. function base64DetectIncompleteChar(buffer) {
  22769. this.charReceived = buffer.length % 3;
  22770. this.charLength = this.charReceived ? 3 : 0;
  22771. }
  22772. /***/ },
  22773. /* 177 */
  22774. /***/ function(module, exports, __webpack_require__) {
  22775. if (typeof Object.create === 'function') {
  22776. // implementation from standard node.js 'util' module
  22777. module.exports = function inherits(ctor, superCtor) {
  22778. ctor.super_ = superCtor
  22779. ctor.prototype = Object.create(superCtor.prototype, {
  22780. constructor: {
  22781. value: ctor,
  22782. enumerable: false,
  22783. writable: true,
  22784. configurable: true
  22785. }
  22786. });
  22787. };
  22788. } else {
  22789. // old school shim for old browsers
  22790. module.exports = function inherits(ctor, superCtor) {
  22791. ctor.super_ = superCtor
  22792. var TempCtor = function () {}
  22793. TempCtor.prototype = superCtor.prototype
  22794. ctor.prototype = new TempCtor()
  22795. ctor.prototype.constructor = ctor
  22796. }
  22797. }
  22798. /***/ },
  22799. /* 178 */
  22800. /***/ function(module, exports, __webpack_require__) {
  22801. /* WEBPACK VAR INJECTION */(function(Buffer) {// Copyright Joyent, Inc. and other Node contributors.
  22802. //
  22803. // Permission is hereby granted, free of charge, to any person obtaining a
  22804. // copy of this software and associated documentation files (the
  22805. // "Software"), to deal in the Software without restriction, including
  22806. // without limitation the rights to use, copy, modify, merge, publish,
  22807. // distribute, sublicense, and/or sell copies of the Software, and to permit
  22808. // persons to whom the Software is furnished to do so, subject to the
  22809. // following conditions:
  22810. //
  22811. // The above copyright notice and this permission notice shall be included
  22812. // in all copies or substantial portions of the Software.
  22813. //
  22814. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  22815. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22816. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  22817. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  22818. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  22819. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  22820. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  22821. // NOTE: These type checking functions intentionally don't use `instanceof`
  22822. // because it is fragile and can be easily faked with `Object.create()`.
  22823. function isArray(ar) {
  22824. return Array.isArray(ar);
  22825. }
  22826. exports.isArray = isArray;
  22827. function isBoolean(arg) {
  22828. return typeof arg === 'boolean';
  22829. }
  22830. exports.isBoolean = isBoolean;
  22831. function isNull(arg) {
  22832. return arg === null;
  22833. }
  22834. exports.isNull = isNull;
  22835. function isNullOrUndefined(arg) {
  22836. return arg == null;
  22837. }
  22838. exports.isNullOrUndefined = isNullOrUndefined;
  22839. function isNumber(arg) {
  22840. return typeof arg === 'number';
  22841. }
  22842. exports.isNumber = isNumber;
  22843. function isString(arg) {
  22844. return typeof arg === 'string';
  22845. }
  22846. exports.isString = isString;
  22847. function isSymbol(arg) {
  22848. return typeof arg === 'symbol';
  22849. }
  22850. exports.isSymbol = isSymbol;
  22851. function isUndefined(arg) {
  22852. return arg === void 0;
  22853. }
  22854. exports.isUndefined = isUndefined;
  22855. function isRegExp(re) {
  22856. return isObject(re) && objectToString(re) === '[object RegExp]';
  22857. }
  22858. exports.isRegExp = isRegExp;
  22859. function isObject(arg) {
  22860. return typeof arg === 'object' && arg !== null;
  22861. }
  22862. exports.isObject = isObject;
  22863. function isDate(d) {
  22864. return isObject(d) && objectToString(d) === '[object Date]';
  22865. }
  22866. exports.isDate = isDate;
  22867. function isError(e) {
  22868. return isObject(e) &&
  22869. (objectToString(e) === '[object Error]' || e instanceof Error);
  22870. }
  22871. exports.isError = isError;
  22872. function isFunction(arg) {
  22873. return typeof arg === 'function';
  22874. }
  22875. exports.isFunction = isFunction;
  22876. function isPrimitive(arg) {
  22877. return arg === null ||
  22878. typeof arg === 'boolean' ||
  22879. typeof arg === 'number' ||
  22880. typeof arg === 'string' ||
  22881. typeof arg === 'symbol' || // ES6 symbol
  22882. typeof arg === 'undefined';
  22883. }
  22884. exports.isPrimitive = isPrimitive;
  22885. function isBuffer(arg) {
  22886. return Buffer.isBuffer(arg);
  22887. }
  22888. exports.isBuffer = isBuffer;
  22889. function objectToString(o) {
  22890. return Object.prototype.toString.call(o);
  22891. }
  22892. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(47).Buffer))
  22893. /***/ },
  22894. /* 179 */
  22895. /***/ function(module, exports, __webpack_require__) {
  22896. /* WEBPACK VAR INJECTION */(function(process) {// Copyright Joyent, Inc. and other Node contributors.
  22897. //
  22898. // Permission is hereby granted, free of charge, to any person obtaining a
  22899. // copy of this software and associated documentation files (the
  22900. // "Software"), to deal in the Software without restriction, including
  22901. // without limitation the rights to use, copy, modify, merge, publish,
  22902. // distribute, sublicense, and/or sell copies of the Software, and to permit
  22903. // persons to whom the Software is furnished to do so, subject to the
  22904. // following conditions:
  22905. //
  22906. // The above copyright notice and this permission notice shall be included
  22907. // in all copies or substantial portions of the Software.
  22908. //
  22909. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  22910. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22911. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  22912. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  22913. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  22914. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  22915. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  22916. // copy from https://github.com/joyent/node/blob/master/lib/_http_agent.js
  22917. var net = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"net\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()));
  22918. var url = __webpack_require__(31);
  22919. var util = __webpack_require__(79);
  22920. var EventEmitter = __webpack_require__(44).EventEmitter;
  22921. // var ClientRequest = require('_http_client').ClientRequest;
  22922. // var debug = util.debuglog('http');
  22923. var ClientRequest = __webpack_require__(30).ClientRequest;
  22924. var debug;
  22925. if (process.env.NODE_DEBUG && /agentkeepalive/.test(process.env.NODE_DEBUG)) {
  22926. debug = function (x) {
  22927. console.error.apply(console, arguments);
  22928. };
  22929. } else {
  22930. debug = function () { };
  22931. }
  22932. // New Agent code.
  22933. // The largest departure from the previous implementation is that
  22934. // an Agent instance holds connections for a variable number of host:ports.
  22935. // Surprisingly, this is still API compatible as far as third parties are
  22936. // concerned. The only code that really notices the difference is the
  22937. // request object.
  22938. // Another departure is that all code related to HTTP parsing is in
  22939. // ClientRequest.onSocket(). The Agent is now *strictly*
  22940. // concerned with managing a connection pool.
  22941. function Agent(options) {
  22942. if (!(this instanceof Agent))
  22943. return new Agent(options);
  22944. EventEmitter.call(this);
  22945. var self = this;
  22946. self.defaultPort = 80;
  22947. self.protocol = 'http:';
  22948. self.options = util._extend({}, options);
  22949. // don't confuse net and make it think that we're connecting to a pipe
  22950. self.options.path = null;
  22951. self.requests = {};
  22952. self.sockets = {};
  22953. self.freeSockets = {};
  22954. self.keepAliveMsecs = self.options.keepAliveMsecs || 1000;
  22955. self.keepAlive = self.options.keepAlive || false;
  22956. self.maxSockets = self.options.maxSockets || Agent.defaultMaxSockets;
  22957. self.maxFreeSockets = self.options.maxFreeSockets || 256;
  22958. self.on('free', function(socket, options) {
  22959. var name = self.getName(options);
  22960. debug('agent.on(free)', name);
  22961. if (!self.isDestroyed(socket) &&
  22962. self.requests[name] && self.requests[name].length) {
  22963. self.requests[name].shift().onSocket(socket);
  22964. if (self.requests[name].length === 0) {
  22965. // don't leak
  22966. delete self.requests[name];
  22967. }
  22968. } else {
  22969. // If there are no pending requests, then put it in
  22970. // the freeSockets pool, but only if we're allowed to do so.
  22971. var req = socket._httpMessage;
  22972. if (req &&
  22973. req.shouldKeepAlive &&
  22974. !self.isDestroyed(socket) &&
  22975. self.options.keepAlive) {
  22976. var freeSockets = self.freeSockets[name];
  22977. var freeLen = freeSockets ? freeSockets.length : 0;
  22978. var count = freeLen;
  22979. if (self.sockets[name])
  22980. count += self.sockets[name].length;
  22981. if (count >= self.maxSockets || freeLen >= self.maxFreeSockets) {
  22982. self.removeSocket(socket, options);
  22983. socket.destroy();
  22984. } else {
  22985. freeSockets = freeSockets || [];
  22986. self.freeSockets[name] = freeSockets;
  22987. socket.setKeepAlive(true, self.keepAliveMsecs);
  22988. socket.unref && socket.unref();
  22989. socket._httpMessage = null;
  22990. self.removeSocket(socket, options);
  22991. freeSockets.push(socket);
  22992. }
  22993. } else {
  22994. self.removeSocket(socket, options);
  22995. socket.destroy();
  22996. }
  22997. }
  22998. });
  22999. }
  23000. util.inherits(Agent, EventEmitter);
  23001. exports.Agent = Agent;
  23002. Agent.defaultMaxSockets = Infinity;
  23003. Agent.prototype.createConnection = net.createConnection;
  23004. // Get the key for a given set of request options
  23005. Agent.prototype.getName = function(options) {
  23006. var name = '';
  23007. if (options.host)
  23008. name += options.host;
  23009. else
  23010. name += 'localhost';
  23011. name += ':';
  23012. if (options.port)
  23013. name += options.port;
  23014. name += ':';
  23015. if (options.localAddress)
  23016. name += options.localAddress;
  23017. name += ':';
  23018. return name;
  23019. };
  23020. Agent.prototype.addRequest = function(req, options) {
  23021. // Legacy API: addRequest(req, host, port, path)
  23022. if (typeof options === 'string') {
  23023. options = {
  23024. host: options,
  23025. port: arguments[2],
  23026. path: arguments[3]
  23027. };
  23028. }
  23029. var name = this.getName(options);
  23030. if (!this.sockets[name]) {
  23031. this.sockets[name] = [];
  23032. }
  23033. var freeLen = this.freeSockets[name] ? this.freeSockets[name].length : 0;
  23034. var sockLen = freeLen + this.sockets[name].length;
  23035. if (freeLen) {
  23036. // we have a free socket, so use that.
  23037. var socket = this.freeSockets[name].shift();
  23038. debug('have free socket');
  23039. // don't leak
  23040. if (!this.freeSockets[name].length)
  23041. delete this.freeSockets[name];
  23042. socket.ref && socket.ref();
  23043. req.onSocket(socket);
  23044. this.sockets[name].push(socket);
  23045. } else if (sockLen < this.maxSockets) {
  23046. debug('call onSocket', sockLen, freeLen);
  23047. // If we are under maxSockets create a new one.
  23048. req.onSocket(this.createSocket(req, options));
  23049. } else {
  23050. debug('wait for socket');
  23051. // We are over limit so we'll add it to the queue.
  23052. if (!this.requests[name]) {
  23053. this.requests[name] = [];
  23054. }
  23055. this.requests[name].push(req);
  23056. }
  23057. };
  23058. Agent.prototype.createSocket = function(req, options) {
  23059. var self = this;
  23060. options = util._extend({}, options);
  23061. options = util._extend(options, self.options);
  23062. options.servername = options.host;
  23063. if (req) {
  23064. var hostHeader = req.getHeader('host');
  23065. if (hostHeader) {
  23066. options.servername = hostHeader.replace(/:.*$/, '');
  23067. }
  23068. }
  23069. var name = self.getName(options);
  23070. debug('createConnection', name, options);
  23071. var s = self.createConnection(options);
  23072. if (!self.sockets[name]) {
  23073. self.sockets[name] = [];
  23074. }
  23075. this.sockets[name].push(s);
  23076. debug('sockets', name, this.sockets[name].length);
  23077. function onFree() {
  23078. self.emit('free', s, options);
  23079. }
  23080. s.on('free', onFree);
  23081. function onClose(err) {
  23082. debug('CLIENT socket onClose');
  23083. // This is the only place where sockets get removed from the Agent.
  23084. // If you want to remove a socket from the pool, just close it.
  23085. // All socket errors end in a close event anyway.
  23086. self.removeSocket(s, options);
  23087. }
  23088. s.on('close', onClose);
  23089. function onRemove() {
  23090. // We need this function for cases like HTTP 'upgrade'
  23091. // (defined by WebSockets) where we need to remove a socket from the
  23092. // pool because it'll be locked up indefinitely
  23093. debug('CLIENT socket onRemove');
  23094. self.removeSocket(s, options, 'agentRemove');
  23095. s.removeListener('close', onClose);
  23096. s.removeListener('free', onFree);
  23097. s.removeListener('agentRemove', onRemove);
  23098. }
  23099. s.on('agentRemove', onRemove);
  23100. return s;
  23101. };
  23102. Agent.prototype.removeSocket = function(s, options) {
  23103. var name = this.getName(options);
  23104. debug('removeSocket', name, 'destroyed:', this.isDestroyed(s));
  23105. var sets = [this.sockets];
  23106. if (this.isDestroyed(s)) {
  23107. // If the socket was destroyed, we need to remove it from the free buffers.
  23108. sets.push(this.freeSockets);
  23109. }
  23110. sets.forEach(function(sockets) {
  23111. if (sockets[name]) {
  23112. var index = sockets[name].indexOf(s);
  23113. if (index !== -1) {
  23114. sockets[name].splice(index, 1);
  23115. if (sockets[name].length === 0) {
  23116. // don't leak
  23117. delete sockets[name];
  23118. }
  23119. }
  23120. }
  23121. });
  23122. if (this.requests[name] && this.requests[name].length) {
  23123. debug('removeSocket, have a request, make a socket');
  23124. var req = this.requests[name][0];
  23125. // If we have pending requests and a socket gets closed make a new one
  23126. this.createSocket(req, options).emit('free');
  23127. }
  23128. };
  23129. Agent.prototype.destroy = function() {
  23130. var sets = [this.freeSockets, this.sockets];
  23131. sets.forEach(function(set) {
  23132. Object.keys(set).forEach(function(name) {
  23133. set[name].forEach(function(socket) {
  23134. socket.destroy();
  23135. });
  23136. });
  23137. });
  23138. };
  23139. Agent.prototype.request = function(options, cb) {
  23140. // if (util.isString(options)) {
  23141. // options = url.parse(options);
  23142. // }
  23143. if (typeof options === 'string') {
  23144. options = url.parse(options);
  23145. }
  23146. // don't try to do dns lookups of foo.com:8080, just foo.com
  23147. if (options.hostname) {
  23148. options.host = options.hostname;
  23149. }
  23150. if (options && options.path && / /.test(options.path)) {
  23151. // The actual regex is more like /[^A-Za-z0-9\-._~!$&'()*+,;=/:@]/
  23152. // with an additional rule for ignoring percentage-escaped characters
  23153. // but that's a) hard to capture in a regular expression that performs
  23154. // well, and b) possibly too restrictive for real-world usage. That's
  23155. // why it only scans for spaces because those are guaranteed to create
  23156. // an invalid request.
  23157. throw new TypeError('Request path contains unescaped characters.');
  23158. } else if (options.protocol && options.protocol !== this.protocol) {
  23159. throw new Error('Protocol:' + options.protocol + ' not supported.');
  23160. }
  23161. options = util._extend({
  23162. agent: this,
  23163. keepAlive: this.keepAlive
  23164. }, options);
  23165. // if it's false, then make a new one, just like this one.
  23166. if (options.agent === false)
  23167. options.agent = new this.constructor();
  23168. debug('agent.request', options);
  23169. return new ClientRequest(options, cb);
  23170. };
  23171. Agent.prototype.get = function(options, cb) {
  23172. var req = this.request(options, cb);
  23173. req.end();
  23174. return req;
  23175. };
  23176. Agent.prototype.isDestroyed = function(socket){
  23177. return socket.destroyed || socket._destroyed;
  23178. }
  23179. exports.globalAgent = new Agent();
  23180. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(99)))
  23181. /***/ }
  23182. /******/ ])
  23183. });