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.

31160 lines
930 KiB

9 years ago
  1. !function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.eve=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
  2. exports.Agent = _dereq_('./lib/Agent');
  3. exports.ServiceManager = _dereq_('./lib/ServiceManager');
  4. exports.TransportManager = _dereq_('./lib/TransportManager');
  5. exports.module = {
  6. BabbleModule: _dereq_('./lib/module/BabbleModule'),
  7. PatternModule: _dereq_('./lib/module/PatternModule'),
  8. RequestModule: _dereq_('./lib/module/RequestModule'),
  9. RPCModule: _dereq_('./lib/module/RPCModule')
  10. };
  11. exports.transport = {
  12. Transport: _dereq_('./lib/transport/Transport'),
  13. AMQPTransport: _dereq_('./lib/transport/amqp/AMQPTransport'),
  14. DistribusTransport: _dereq_('./lib/transport/distribus/DistribusTransport'),
  15. HTTPTransport: _dereq_('./lib/transport/http/HTTPTransport'),
  16. LocalTransport: _dereq_('./lib/transport/local/LocalTransport'),
  17. PubNubTransport: _dereq_('./lib/transport/pubnub/PubNubTransport'),
  18. WebSocketTransport: _dereq_('./lib/transport/websocket/WebSocketTransport'),
  19. connection: {
  20. Connection: _dereq_('./lib/transport/Connection'),
  21. AMQPConnection: _dereq_('./lib/transport/amqp/AMQPConnection'),
  22. DistribusConnection: _dereq_('./lib/transport/distribus/DistribusConnection'),
  23. HTTPConnection: _dereq_('./lib/transport/http/HTTPConnection'),
  24. LocalConnection: _dereq_('./lib/transport/local/LocalConnection'),
  25. PubNubConnection: _dereq_('./lib/transport/pubnub/PubNubConnection'),
  26. WebSocketConnection: _dereq_('./lib/transport/websocket/WebSocketConnection')
  27. }
  28. };
  29. exports.hypertimer = _dereq_('hypertimer');
  30. exports.util = _dereq_('./lib/util');
  31. // register all modules at the Agent
  32. exports.Agent.registerModule(exports.module.BabbleModule);
  33. exports.Agent.registerModule(exports.module.PatternModule);
  34. exports.Agent.registerModule(exports.module.RequestModule);
  35. exports.Agent.registerModule(exports.module.RPCModule);
  36. // register all transports at the TransportManager
  37. exports.TransportManager.registerType(exports.transport.AMQPTransport);
  38. exports.TransportManager.registerType(exports.transport.DistribusTransport);
  39. exports.TransportManager.registerType(exports.transport.HTTPTransport);
  40. exports.TransportManager.registerType(exports.transport.LocalTransport);
  41. exports.TransportManager.registerType(exports.transport.PubNubTransport);
  42. exports.TransportManager.registerType(exports.transport.WebSocketTransport);
  43. // load the default ServiceManager, a singleton, initialized with a LocalTransport
  44. exports.system = new exports.ServiceManager();
  45. exports.system.transports.add(new exports.transport.LocalTransport());
  46. // override Agent.getTransportById in order to support Agent.connect(transportId)
  47. exports.Agent.getTransportById = function (id) {
  48. return exports.system.transports.get(id);
  49. };
  50. },{"./lib/Agent":2,"./lib/ServiceManager":3,"./lib/TransportManager":4,"./lib/module/BabbleModule":5,"./lib/module/PatternModule":6,"./lib/module/RPCModule":7,"./lib/module/RequestModule":8,"./lib/transport/Connection":9,"./lib/transport/Transport":10,"./lib/transport/amqp/AMQPConnection":11,"./lib/transport/amqp/AMQPTransport":12,"./lib/transport/distribus/DistribusConnection":13,"./lib/transport/distribus/DistribusTransport":14,"./lib/transport/http/HTTPConnection":15,"./lib/transport/http/HTTPTransport":16,"./lib/transport/local/LocalConnection":17,"./lib/transport/local/LocalTransport":18,"./lib/transport/pubnub/PubNubConnection":19,"./lib/transport/pubnub/PubNubTransport":20,"./lib/transport/websocket/WebSocketConnection":21,"./lib/transport/websocket/WebSocketTransport":22,"./lib/util":23,"hypertimer":110}],2:[function(_dereq_,module,exports){
  51. 'use strict';
  52. var Promise = _dereq_('promise');
  53. var uuid = _dereq_('uuid-v4');
  54. var util = _dereq_('./util');
  55. /**
  56. * Agent
  57. * @param {string} [id] Id for the agent. If not provided, the agent
  58. * will be given a uuid.
  59. * @constructor
  60. */
  61. function Agent (id) {
  62. this.id = id ? id.toString() : uuid();
  63. // a list with all connected transports
  64. this.connections = [];
  65. this.defaultConnection = null;
  66. this.ready = Promise.resolve([]);
  67. }
  68. // an object with modules which can be used to extend the agent
  69. Agent.modules = {};
  70. /**
  71. * Register a new type of module. This module can then be loaded via
  72. * Agent.extend() and Agent.loadModule().
  73. * @param {Function} constructor A module constructor
  74. */
  75. Agent.registerModule = function (constructor) {
  76. var type = constructor.prototype.type;
  77. if (typeof constructor !== 'function') {
  78. throw new Error('Constructor function expected');
  79. }
  80. if (!type) {
  81. throw new Error('Field "prototype.type" missing in transport constructor');
  82. }
  83. if (type in Agent.modules) {
  84. if (Agent.modules[type] !== constructor) {
  85. throw new Error('Module of type "' + type + '" already exists');
  86. }
  87. }
  88. Agent.modules[type] = constructor;
  89. };
  90. /**
  91. * Get a transport by id.
  92. * This static method can be overloaded for example by the get function of
  93. * a singleton TransportManager.
  94. * @param {string} id
  95. * @return {Transport}
  96. */
  97. Agent.getTransportById = function (id) {
  98. throw new Error('Transport with id "' + id + '" not found');
  99. };
  100. /**
  101. * Extend an agent with modules (mixins).
  102. * The modules new functions are added to the Agent itself.
  103. * See also function `loadModule`.
  104. * @param {string | string[]} module A module name or an Array with module
  105. * names. Available modules:
  106. * 'pattern', 'request', 'babble'
  107. * @param {Object} [options] Additional options for loading the module
  108. * @return {Agent} Returns the agent itself
  109. */
  110. Agent.prototype.extend = function (module, options) {
  111. if (Array.isArray(module)) {
  112. var modules = [].concat(module);
  113. // order the modules such that 'pattern' comes first, this module must be
  114. // loaded before other modules ('request' specifically)
  115. modules.sort(function (a, b) {
  116. if (a == 'pattern') return -1;
  117. if (b == 'pattern') return 1;
  118. return 0;
  119. });
  120. // an array with module names
  121. for (var i = 0; i < modules.length; i++) {
  122. this.extend(modules[i], options)
  123. }
  124. }
  125. else {
  126. // a single module name
  127. var constructor = _getModuleConstructor(module);
  128. var instance = new constructor(this, options);
  129. var mixin = instance.mixin();
  130. // check for conflicts in the modules mixin functions
  131. var me = this;
  132. Object.keys(mixin).forEach(function (name) {
  133. if (me[name] !== undefined && name !== '_receive') {
  134. throw new Error('Conflict: agent already has a property "' + prop + '"');
  135. }
  136. });
  137. // extend the agent with all mixin functions provided by the module
  138. Object.keys(mixin).forEach(function (name) {
  139. me[name] = mixin[name];
  140. });
  141. }
  142. return this;
  143. };
  144. /**
  145. * Load a module onto an agent.
  146. * See also function `extend`.
  147. * @param {string | string[]} module A module name or an Array with module
  148. * names. Available modules:
  149. * 'pattern', 'request', 'babble'
  150. * @param {Object} [options] Additional options for loading the module
  151. * @return {Object} Returns the created module
  152. */
  153. Agent.prototype.loadModule = function (module, options) {
  154. var _options = options !== undefined ? Object.create(options) : {};
  155. _options.extend = false;
  156. var constructor = _getModuleConstructor(module);
  157. var instance = new constructor(this, options);
  158. var mixin = instance.mixin();
  159. // only replace the _receive function, do not add other mixin functions
  160. this._receive = mixin._receive;
  161. return instance;
  162. };
  163. /**
  164. * Get a module constructor by it's name.
  165. * Throws an error when the module is not found.
  166. * @param {string} name
  167. * @return {function} Returns the modules constructor function
  168. * @private
  169. */
  170. function _getModuleConstructor(name) {
  171. var constructor = Agent.modules[name];
  172. if (!constructor) {
  173. throw new Error('Unknown module "' + name + '". ' +
  174. 'Choose from: ' + Object.keys(Agent.modules).map(JSON.stringify).join(', '));
  175. }
  176. return constructor;
  177. }
  178. /**
  179. * Send a message to an agent
  180. * @param {string} to
  181. * to is either:
  182. * - A string "agentId", the id of the recipient. Will be send
  183. * via the default transport or when there is no default
  184. * transport via the first connected transport.
  185. * - A string "agentId@transportId" Only usable locally, not
  186. * for sharing an address with remote agents.
  187. * - A string "protocol://networkId/agentId". This is a sharable
  188. * identifier for an agent.
  189. * @param {*} message Message to be send
  190. * @return {Promise} Returns a promise which resolves when the message as
  191. * successfully been sent, or rejected when sending the
  192. * message failed
  193. */
  194. Agent.prototype.send = function(to, message) {
  195. var colon = to.indexOf('://');
  196. if (colon !== -1) {
  197. // to is an url like "protocol://networkId/agentId"
  198. var url = util.parseUrl(to);
  199. if (url.protocol == 'http' || url.protocol == 'ws' || url.protocol == 'https') { // TODO: ugly fixed listing here...
  200. return this._sendByProtocol(url.protocol, to, message);
  201. }
  202. else {
  203. return this._sendByNetworkId(url.domain, url.path, message);
  204. }
  205. }
  206. // TODO: deprecate this notation "agentId@transportId"?
  207. var at = to.indexOf('@');
  208. if (at != -1) {
  209. // to is an id like "agentId@transportId"
  210. var _to = to.substring(0, at);
  211. var _transportId = to.substring(at + 1);
  212. return this._sendByTransportId(_transportId, _to, message);
  213. }
  214. // to is an id like "agentId". Send via the default transport
  215. var conn = this.defaultConnection;
  216. if (conn) {
  217. return conn.send(to, message);
  218. }
  219. else {
  220. return Promise.reject(new Error('No transport found'));
  221. }
  222. };
  223. /**
  224. * Send a transport to an agent given a networkId
  225. * @param {string} networkId A network id
  226. * @param {string} to An agents id
  227. * @param {string} message Message to be send
  228. * @return {Promise} Returns a promise which resolves when the message as
  229. * successfully been sent, or rejected when sending the
  230. * message failed
  231. * @private
  232. */
  233. Agent.prototype._sendByNetworkId = function(networkId, to, message) {
  234. // TODO: change this.connections to a map with networkId as keys, much faster
  235. for (var i = 0; i < this.connections.length; i++) {
  236. var connection = this.connections[i];
  237. if (connection.transport.networkId == networkId) {
  238. return connection.send(to, message);
  239. }
  240. }
  241. return Promise.reject(new Error('No transport found with networkId "' + networkId + '"'));
  242. };
  243. /**
  244. * Send a message by a transport by protocol.
  245. * The message will be send via the first found transport having the specified
  246. * protocol.
  247. * @param {string} protocol A protocol, for example 'http' or 'ws'
  248. * @param {string} to An agents id
  249. * @param {string} message Message to be send
  250. * @return {Promise} Returns a promise which resolves when the message as
  251. * successfully been sent, or rejected when sending the
  252. * message failed
  253. * @private
  254. */
  255. Agent.prototype._sendByProtocol = function(protocol, to, message) {
  256. for (var i = 0; i < this.connections.length; i++) {
  257. var connection = this.connections[i];
  258. if (connection.transport.type == protocol) {
  259. return connection.send(to, message);
  260. }
  261. }
  262. return Promise.reject(new Error('No transport found for protocol "' + protocol + '"'));
  263. };
  264. /**
  265. * Send a transport to an agent via a specific transport
  266. * @param {string} transportId The configured id of a transport.
  267. * @param {string} to An agents id
  268. * @param {string} message Message to be send
  269. * @return {Promise} Returns a promise which resolves when the message as
  270. * successfully been sent, or rejected when sending the
  271. * message failed
  272. * @private
  273. */
  274. Agent.prototype._sendByTransportId = function(transportId, to, message) {
  275. for (var i = 0; i < this.connections.length; i++) {
  276. var connection = this.connections[i];
  277. if (connection.transport.id == transportId) {
  278. return connection.send(to, message);
  279. }
  280. }
  281. return Promise.reject(new Error('No transport found with id "' + transportId + '"'));
  282. };
  283. /**
  284. * Receive a message.
  285. * @param {string} from Id of sender
  286. * @param {*} message Received message, a JSON object (often a string)
  287. */
  288. Agent.prototype.receive = function(from, message) {
  289. // ... to be overloaded
  290. };
  291. /**
  292. * The method _receive is overloaded in a cascaded way by modules, and calls
  293. * the public method Agent.receive at the end of the chain.
  294. * @param {string} from Id of sender
  295. * @param {*} message Received message, a JSON object (often a string)
  296. * @returns {*} Returns the return value of Agent.receive
  297. * @private
  298. */
  299. Agent.prototype._receive = function (from, message) {
  300. return this.receive(from, message);
  301. };
  302. /**
  303. * Connect to a transport. The agent will subscribe itself to
  304. * messages sent to his id.
  305. * @param {string | Transport | Transport[] | string[]} transport
  306. * A Transport instance, or the id of a
  307. * transport loaded in eve.system.
  308. * @param {string} [id] An optional alternative id to be used
  309. * for the connection. By default, the agents
  310. * own id is used.
  311. * @return {Connection | Connection[]} Returns a connection or, in case of
  312. * multiple transports, returns an
  313. * array with connections. The connections
  314. * have a promise .ready which resolves
  315. * as soon as the connection is ready for
  316. * use.
  317. */
  318. Agent.prototype.connect = function(transport, id) {
  319. if (Array.isArray(transport)) {
  320. var me = this;
  321. return transport.map(function (_transport) {
  322. return me._connect(_transport, id);
  323. });
  324. }
  325. else if (typeof transport === 'string') {
  326. // get transport by id
  327. return this._connect(Agent.getTransportById(transport), id);
  328. }
  329. else {
  330. // a transport instance
  331. return this._connect(transport, id);
  332. }
  333. };
  334. /**
  335. * Connect to a transport
  336. * @param {Transport} transport A Transport instance
  337. * @param {string} [id] An optional alternative id to be used
  338. * for the connection. By default, the agents
  339. * own id is used.
  340. * @return {Connection} Returns a connection.
  341. * @private
  342. */
  343. Agent.prototype._connect = function (transport, id) {
  344. // create a receive function which is bound to the _receive function.
  345. // the _receive function can be replaced in by modules in a cascaded way,
  346. // and in the end calls this.receive of the agent.
  347. // note: we don't do receive = this._receive.bind(this) as the _receive
  348. // function can be overloaded after a connection is made.
  349. var me = this;
  350. var receive = function (from, message) {
  351. return me._receive(from, message);
  352. };
  353. var connection = transport.connect(id || this.id, receive);
  354. this.connections.push(connection);
  355. // set or replace the defaultConnection
  356. if (!this.defaultConnection) {
  357. this.defaultConnection = connection;
  358. }
  359. else if (transport['default']) {
  360. if (this.defaultConnection['default']) {
  361. throw new Error('Cannot connect to a second default transport');
  362. }
  363. this.defaultConnection = connection;
  364. }
  365. this._updateReady();
  366. return connection;
  367. };
  368. /**
  369. * Disconnect from one or multiple transports
  370. * @param {string | Transport | string[] | Transport[]} [transport]
  371. * A transport or an array with transports.
  372. * parameter transport can be an instance of a Transport, or the
  373. * id of a transport.
  374. * When transport is undefined, the agent will be disconnected
  375. * from all connected transports.
  376. */
  377. Agent.prototype.disconnect = function(transport) {
  378. var i, connection;
  379. if (!transport) {
  380. // disconnect all transports
  381. while (connection = this.connections[0]) {
  382. this._disconnect(connection);
  383. }
  384. }
  385. else if (Array.isArray(transport)) {
  386. // an array with transports
  387. i = 0;
  388. while (i < this.connections.length) {
  389. connection = this.connections[i];
  390. if (transport.indexOf(connection.transport) !== -1) {
  391. this._disconnect(connection);
  392. }
  393. else {
  394. i++;
  395. }
  396. }
  397. }
  398. else if (typeof transport === 'string') {
  399. // transport by id
  400. this.disconnect(Agent.getTransportById(transport));
  401. }
  402. else {
  403. // a single transport
  404. for (i = 0; i < this.connections.length; i++) {
  405. connection = this.connections[i];
  406. if (connection.transport === transport) {
  407. this._disconnect(connection);
  408. break;
  409. }
  410. }
  411. }
  412. };
  413. /**
  414. * Close a connection
  415. * @param {Connection} connection
  416. * @private
  417. */
  418. Agent.prototype._disconnect = function (connection) {
  419. // find the connection
  420. var index = this.connections.indexOf(connection);
  421. if (index !== -1) {
  422. // close the connection
  423. connection.close();
  424. // remove from the list with connections
  425. this.connections.splice(index, 1);
  426. // replace the defaultConnection if needed
  427. if (this.defaultConnection === connection) {
  428. this.defaultConnection = this.connections[this.connections.length - 1] || null;
  429. }
  430. }
  431. this._updateReady();
  432. };
  433. /**
  434. * Update the ready state of the agent
  435. * @private
  436. */
  437. Agent.prototype._updateReady = function () {
  438. // FIXME: we should not replace with a new Promise,
  439. // we have a problem when this.ready is requested before ready,
  440. // and another connection is opened before ready
  441. this.ready = Promise.all(this.connections.map(function (connection) {
  442. return connection.ready;
  443. }));
  444. };
  445. module.exports = Agent;
  446. },{"./util":23,"promise":114,"uuid-v4":125}],3:[function(_dereq_,module,exports){
  447. 'use strict';
  448. var seed = _dereq_('seed-random');
  449. var hypertimer = _dereq_('hypertimer');
  450. var TransportManager = _dereq_('./TransportManager');
  451. // map with known configuration properties
  452. var KNOWN_PROPERTIES = {
  453. transports: true,
  454. timer: true,
  455. random: true
  456. };
  457. function ServiceManager(config) {
  458. this.transports = new TransportManager();
  459. this.timer = hypertimer();
  460. this.random = Math.random;
  461. this.init(config);
  462. }
  463. /**
  464. * Initialize the service manager with services loaded from a configuration
  465. * object. All current services are unloaded and removed.
  466. * @param {Object} config
  467. */
  468. ServiceManager.prototype.init = function (config) {
  469. this.transports.clear();
  470. if (config) {
  471. if (config.transports) {
  472. this.transports.load(config.transports);
  473. }
  474. if (config.timer) {
  475. this.timer.config(config.timer);
  476. }
  477. if (config.random) {
  478. if (config.random.deterministic) {
  479. var key = config.random.seed || 'random seed';
  480. this.random = seed(key, config.random);
  481. }
  482. else {
  483. this.random = Math.random;
  484. }
  485. }
  486. for (var prop in config) {
  487. if (config.hasOwnProperty(prop) && !KNOWN_PROPERTIES[prop]) {
  488. // TODO: should log this warning via a configured logger
  489. console.log('WARNING: Unknown configuration option "' + prop + '"')
  490. }
  491. }
  492. }
  493. };
  494. /**
  495. * Clear all configured services
  496. */
  497. ServiceManager.prototype.clear = function () {
  498. this.transports.clear();
  499. };
  500. module.exports = ServiceManager;
  501. },{"./TransportManager":4,"hypertimer":110,"seed-random":124}],4:[function(_dereq_,module,exports){
  502. 'use strict';
  503. /**
  504. * A manager for loading and finding transports.
  505. * @param {Array} [config] Optional array containing configuration objects
  506. * for transports.
  507. * @constructor
  508. */
  509. function TransportManager(config) {
  510. this.transports = [];
  511. if (config) {
  512. this.load(config);
  513. }
  514. }
  515. // map with all registered types of transports
  516. // each transport must register itself at the TransportManager using registerType.
  517. TransportManager.types = {};
  518. /**
  519. * Register a new type of transport. This transport can then be loaded via
  520. * configuration.
  521. * @param {Transport.prototype} constructor A transport constructor
  522. */
  523. TransportManager.registerType = function (constructor) {
  524. var type = constructor.prototype.type;
  525. if (typeof constructor !== 'function') {
  526. throw new Error('Constructor function expected');
  527. }
  528. if (!type) {
  529. throw new Error('Field "prototype.type" missing in transport constructor');
  530. }
  531. if (type in TransportManager.types) {
  532. if (TransportManager.types[type] !== constructor) {
  533. throw new Error('Transport type "' + type + '" already exists');
  534. }
  535. }
  536. TransportManager.types[type] = constructor;
  537. };
  538. /**
  539. * Add a loaded transport to the manager
  540. * @param {Transport} transport
  541. * @return {Transport} returns the transport itself
  542. */
  543. TransportManager.prototype.add = function (transport) {
  544. this.transports.push(transport);
  545. return transport;
  546. };
  547. /**
  548. * Load one or multiple transports based on JSON configuration.
  549. * New transports will be appended to current transports.
  550. * @param {Object | Array} config
  551. * @return {Transport | Transport[]} Returns the loaded transport(s)
  552. */
  553. TransportManager.prototype.load = function (config) {
  554. if (Array.isArray(config)) {
  555. return config.map(this.load.bind(this));
  556. }
  557. var type = config.type;
  558. if (!type) {
  559. throw new Error('Property "type" missing');
  560. }
  561. var constructor = TransportManager.types[type];
  562. if (!constructor) {
  563. throw new Error('Unknown type of transport "' + type + '". ' +
  564. 'Choose from: ' + Object.keys(TransportManager.types).join(','))
  565. }
  566. var transport = new constructor(config);
  567. this.transports.push(transport);
  568. return transport;
  569. };
  570. /**
  571. * Unload a transport.
  572. * @param {Transport | Transport[] | string | string[]} transport
  573. * A Transport instance or the id of a transport, or an Array
  574. * with transports or transport ids.
  575. */
  576. TransportManager.prototype.unload = function (transport) {
  577. var _transport;
  578. if (typeof transport === 'string') {
  579. _transport = this.get(transport);
  580. }
  581. else if (Array.isArray(transport)) {
  582. for (var i = 0; i < transport.length; i++) {
  583. this.unload(transport[i]);
  584. }
  585. }
  586. else {
  587. _transport = transport;
  588. }
  589. if (_transport) {
  590. _transport.close();
  591. var index = this.transports.indexOf(_transport);
  592. if (index !== -1) {
  593. this.transports.splice(index, 1);
  594. }
  595. }
  596. };
  597. /**
  598. * Get a transport by its id. The transport must have been created with an id
  599. * @param {string} [id] The id of a transport
  600. * @return {Transport} Returns the transport when found. Throws an error
  601. * when not found.
  602. */
  603. TransportManager.prototype.get = function (id) {
  604. for (var i = 0; i < this.transports.length; i++) {
  605. var transport = this.transports[i];
  606. if (transport.id === id) {
  607. return transport;
  608. }
  609. }
  610. throw new Error('Transport with id "' + id + '" not found');
  611. };
  612. /**
  613. * Get all transports.
  614. * @return {Transport[]} Returns an array with all loaded transports.
  615. */
  616. TransportManager.prototype.getAll = function () {
  617. return this.transports.concat([]);
  618. };
  619. /**
  620. * Find transports by type.
  621. * @param {string} [type] Type of the transport. Choose from 'amqp',
  622. * 'distribus', 'local', 'pubnub'.
  623. * @return {Transport[]} When type is defined, the all transports of this
  624. * type are returned. When undefined, all transports
  625. * are returned.
  626. */
  627. TransportManager.prototype.getByType = function (type) {
  628. if (type) {
  629. if (!(type in TransportManager.types)) {
  630. throw new Error('Unknown type of transport "' + type + '". ' +
  631. 'Choose from: ' + Object.keys(TransportManager.types).join(','))
  632. }
  633. return this.transports.filter(function (transport) {
  634. return transport.type === type;
  635. });
  636. }
  637. else {
  638. return [].concat(this.transports);
  639. }
  640. };
  641. /**
  642. * Close all configured transports and remove them from the manager.
  643. */
  644. TransportManager.prototype.clear = function () {
  645. this.transports.forEach(function (transport) {
  646. transport.close();
  647. });
  648. this.transports = [];
  649. };
  650. module.exports = TransportManager;
  651. },{}],5:[function(_dereq_,module,exports){
  652. 'use strict';
  653. var babble = _dereq_('babble');
  654. /**
  655. * Create a Babble module for an agent.
  656. * The agents _receive function is wrapped into a new handler.
  657. * Creates a Babble instance with function `ask`, `tell`, `listen`, `listenOnce`
  658. * @param {Agent} agent
  659. * @param {Object} [options] Optional parameters. Not applicable for BabbleModule
  660. * @constructor
  661. */
  662. function BabbleModule(agent, options) {
  663. // create a new babbler
  664. var babbler = babble.babbler(agent.id);
  665. babbler.connect({
  666. connect: function (params) {},
  667. disconnect: function(token) {},
  668. send: function (to, message) {
  669. agent.send(to, message);
  670. }
  671. });
  672. this.babbler = babbler;
  673. // create a receive function for the agent
  674. var receiveOriginal = agent._receive;
  675. this._receive = function (from, message) {
  676. babbler._receive(message);
  677. // TODO: only propagate to receiveOriginal if the message is not handled by the babbler
  678. return receiveOriginal.call(agent, from, message);
  679. };
  680. }
  681. BabbleModule.prototype.type = 'babble';
  682. /**
  683. * Get a map with mixin functions
  684. * @return {{_receive: function, ask: function, tell: function, listen: function, listenOnce: function}}
  685. * Returns mixin function, which can be used to extend the agent.
  686. */
  687. BabbleModule.prototype.mixin = function () {
  688. var babbler = this.babbler;
  689. return {
  690. _receive: this._receive,
  691. ask: babbler.ask.bind(babbler),
  692. tell: babbler.tell.bind(babbler),
  693. listen: babbler.listen.bind(babbler),
  694. listenOnce: babbler.listenOnce.bind(babbler)
  695. }
  696. };
  697. module.exports = BabbleModule;
  698. },{"babble":40}],6:[function(_dereq_,module,exports){
  699. 'use strict';
  700. /**
  701. * Create a pattern listener onto an Agent.
  702. * A new handler is added to the agents _receiver function.
  703. * Creates a Pattern instance with functions `listen` and `unlisten`.
  704. * @param {Agent} agent
  705. * @param {Object} [options] Optional parameters. Can contain properties:
  706. * - stopPropagation: boolean
  707. * When false (default), a message
  708. * will be delivered at all
  709. * matching pattern listeners.
  710. * When true, a message will be
  711. * be delivered at the first
  712. * matching pattern listener only.
  713. */
  714. function PatternModule(agent, options) {
  715. this.agent = agent;
  716. this.stopPropagation = options && options.stopPropagation || false;
  717. this.receiveOriginal = agent._receive;
  718. this.listeners = [];
  719. }
  720. PatternModule.prototype.type = 'pattern';
  721. /**
  722. * Receive a message.
  723. * All pattern listeners will be checked against their patterns, and if there
  724. * is a match, the pattern listeners callback function is invoked.
  725. * @param {string} from Id of sender
  726. * @param {*} message Received message, a JSON object (often a string)
  727. */
  728. PatternModule.prototype.receive = function(from, message) {
  729. var response;
  730. var responses = [];
  731. for (var i = 0, ii = this.listeners.length; i < ii; i++) {
  732. var listener = this.listeners[i];
  733. var pattern = listener.pattern;
  734. var match = (pattern instanceof Function && pattern(message)) ||
  735. (pattern instanceof RegExp && pattern.test(message)) ||
  736. (pattern == message);
  737. if (match) {
  738. response = listener.callback.call(this.agent, from, message);
  739. responses.push(response);
  740. if (this.stopPropagation) {
  741. return responses[0];
  742. }
  743. }
  744. }
  745. response = this.receiveOriginal.call(this.agent, from, message);
  746. responses.push(response);
  747. return responses[0];
  748. };
  749. /**
  750. * Add a pattern listener for incoming messages
  751. * @param {string | RegExp | Function} pattern Message pattern
  752. * @param {Function} callback Callback function invoked when
  753. * a message matching the pattern
  754. * is received.
  755. * Invoked as callback(from, message)
  756. */
  757. PatternModule.prototype.listen = function(pattern, callback) {
  758. this.listeners.push({
  759. pattern: pattern,
  760. callback: callback
  761. });
  762. };
  763. /**
  764. * Remove a pattern listener for incoming messages
  765. * @param {string | RegExp | Function} pattern Message pattern
  766. * @param {Function} callback
  767. */
  768. PatternModule.prototype.unlisten = function(pattern, callback) {
  769. for (var i = 0, ii = this.listeners.length; i < ii; i++) {
  770. var listener = this.listeners[i];
  771. if (listener.pattern === pattern && listener.callback === callback) {
  772. this.listeners.splice(i, 1);
  773. break;
  774. }
  775. }
  776. };
  777. /**
  778. * Get a map with mixin functions
  779. * @return {{_receive: function, listen: function, unlisten: function}}
  780. * Returns mixin function, which can be used to extend the agent.
  781. */
  782. PatternModule.prototype.mixin = function () {
  783. return {
  784. _receive: this.receive.bind(this),
  785. listen: this.listen.bind(this),
  786. unlisten: this.unlisten.bind(this)
  787. }
  788. };
  789. module.exports = PatternModule;
  790. },{}],7:[function(_dereq_,module,exports){
  791. 'use strict';
  792. var uuid = _dereq_('uuid-v4');
  793. var Promise = _dereq_('promise');
  794. var util = _dereq_('../util');
  795. /**
  796. *
  797. * @param {Agent} agent
  798. * @param {Object} availableFunctions
  799. * @constructor
  800. */
  801. function RPCModule(agent, availableFunctions) {
  802. this.agent = agent;
  803. this.receiveOriginal = agent._receive;
  804. this.queue = {};
  805. this.promiseTimeout = 1500; // 1 second
  806. // check the available functions
  807. if (availableFunctions instanceof Array) {
  808. this.functionsFromArray(availableFunctions);
  809. }
  810. else if (availableFunctions instanceof Object) {
  811. this.availableFunctions = availableFunctions;
  812. }
  813. else {
  814. console.log('cannot use RPC with the supplied functions', availableFunctions);
  815. }
  816. }
  817. RPCModule.prototype.type = 'rpc';
  818. /**
  819. *
  820. * @param availableFunctions
  821. */
  822. RPCModule.prototype.functionsFromArray = function (availableFunctions) {
  823. this.availableFunctions = {};
  824. for (var i = 0; i < availableFunctions.length; i++) {
  825. var fn = availableFunctions[i];
  826. this.availableFunctions[fn] = this.agent[fn];
  827. }
  828. };
  829. /**
  830. *
  831. * @param to
  832. * @param message
  833. * @returns {Promise}
  834. */
  835. RPCModule.prototype.request = function (to, message) {
  836. var me = this;
  837. return new Promise(function (resolve, reject) {
  838. // prepare the envelope
  839. if (typeof message != 'object' ) {reject(new TypeError('Message must be an object'));}
  840. if (message.jsonrpc !== '2.0' ) {message.jsonrpc = '2.0';}
  841. if (message.id === undefined) {message.id = uuid();}
  842. if (message.method === undefined) {reject(new Error('Property "method" expected'));}
  843. if (message.params === undefined) {message.params = {};}
  844. // add the request to the list with requests in progress
  845. me.queue[message.id] = {
  846. resolve: resolve,
  847. reject: reject,
  848. timeout: setTimeout(function () {
  849. delete me.queue[message.id];
  850. reject(new Error('Timeout'));
  851. }, me.promiseTimeout)
  852. };
  853. var sendRequest = me.agent.send(to, message);
  854. if (util.isPromise(sendRequest) == true) {
  855. sendRequest.catch(function (err) {reject(err);});
  856. }
  857. });
  858. };
  859. /**
  860. *
  861. * @param from
  862. * @param message
  863. * @returns {*}
  864. */
  865. RPCModule.prototype.receive = function (from, message) {
  866. if (typeof message == 'object') {
  867. if (message.jsonrpc == '2.0') {
  868. this._receive(from, message);
  869. }
  870. else {
  871. this.receiveOriginal.call(this.agent, from, message);
  872. }
  873. }
  874. else {
  875. this.receiveOriginal.call(this.agent, from, message);
  876. }
  877. };
  878. /**
  879. *
  880. * @param from
  881. * @param message
  882. * @returns {*}
  883. * @private
  884. */
  885. RPCModule.prototype._receive = function (from, message) {
  886. // define structure of return message
  887. var returnMessage = {jsonrpc:'2.0', id:message.id};
  888. // check if this is a request
  889. if (message.method !== undefined) {
  890. // check is method is available for this agent
  891. var method = this.availableFunctions[message.method];
  892. if (method !== undefined) {
  893. var response = method.call(this.agent, message.params, from) || null;
  894. // check if response is a promise
  895. if (util.isPromise(response)) {
  896. var me = this;
  897. response
  898. .then(function (result) {
  899. returnMessage.result = result;
  900. me.agent.send(from, returnMessage)
  901. })
  902. .catch(function (error) {
  903. returnMessage.error = error.message || error.toString();
  904. me.agent.send(from, returnMessage);
  905. })
  906. }
  907. else {
  908. returnMessage.result = response;
  909. this.agent.send(from, returnMessage);
  910. }
  911. }
  912. else {
  913. var error = new Error('Cannot find function: ' + message.method);
  914. returnMessage.error = error.message || error.toString();
  915. this.agent.send(from, returnMessage);
  916. }
  917. }
  918. // check if this is a response
  919. else if (message.result !== undefined || message.error !== undefined) {
  920. var request = this.queue[message.id];
  921. if (request !== undefined) {
  922. // if an error is defined, reject promise
  923. if (message.error != undefined) { // null or undefined
  924. // FIXME: returned error should be an object {code: number, message: string}
  925. request.reject(new Error(message.error));
  926. }
  927. else {
  928. request.resolve(message.result);
  929. }
  930. }
  931. }
  932. else {
  933. // send error back to sender.
  934. var error = new Error('No method or result defined. Message:' + JSON.stringify(message));
  935. returnMessage.error = error.message || error.toString();
  936. // FIXME: returned error should be an object {code: number, message: string}
  937. this.agent.send(from, returnMessage);
  938. }
  939. };
  940. /**
  941. * Get a map with mixin functions
  942. * @return {{_receive: function, request: function}}
  943. * Returns mixin function, which can be used to extend the agent.
  944. */
  945. RPCModule.prototype.mixin = function () {
  946. return {
  947. _receive: this.receive.bind(this),
  948. request: this.request.bind(this)
  949. }
  950. };
  951. module.exports = RPCModule;
  952. },{"../util":23,"promise":114,"uuid-v4":125}],8:[function(_dereq_,module,exports){
  953. 'use strict';
  954. var uuid = _dereq_('uuid-v4');
  955. var Promise = _dereq_('promise');
  956. var util = _dereq_('../util');
  957. var TIMEOUT = 60000; // ms
  958. /**
  959. * Create a Request module.
  960. * The module attaches a handler to the agents _receive function.
  961. * Creates a Request instance with function `request`.
  962. * @param {Agent} agent
  963. * @param {Object} [options] Optional parameters. Can contain properties:
  964. * - timeout: number A timeout for responses in
  965. * milliseconds. 60000 ms by
  966. * default.
  967. */
  968. function RequestModule(agent, options) {
  969. this.agent = agent;
  970. this.receiveOriginal = agent._receive;
  971. this.timeout = options && options.timeout || TIMEOUT;
  972. this.queue = [];
  973. }
  974. RequestModule.prototype.type = 'request';
  975. /**
  976. * Event handler, handles incoming messages
  977. * @param {String} from Id of the sender
  978. * @param {*} message
  979. * @return {boolean} Returns true when a message is handled, else returns false
  980. */
  981. RequestModule.prototype.receive = function (from, message) {
  982. var agent = this.agent;
  983. if (typeof message === 'object') {
  984. var envelope = message;
  985. // match the request from the id in the response
  986. var request = this.queue[envelope.id];
  987. if (request) {
  988. // remove the request from the queue
  989. clearTimeout(request.timeout);
  990. delete this.queue[envelope.id];
  991. // resolve the requests promise with the response message
  992. if (envelope.error) {
  993. // TODO: turn this into an Error instance again
  994. request.reject(new Error(envelope.error));
  995. }
  996. else {
  997. request.resolve(envelope.message);
  998. }
  999. return true;
  1000. }
  1001. else if (message.type == 'request') {
  1002. try {
  1003. var response = this.receiveOriginal.call(agent, from, message.message);
  1004. if (util.isPromise(response)) {
  1005. // wait until the promise resolves
  1006. response
  1007. .then(function (result) {
  1008. agent.send(from, {type: 'request', id: message.id, message: result});
  1009. })
  1010. .catch(function (err) {
  1011. agent.send(from, {type: 'request', id: message.id, error: err.message || err.toString()});
  1012. });
  1013. }
  1014. else {
  1015. // immediately send a result
  1016. agent.send(from, {type: 'request', id: message.id, message: response });
  1017. }
  1018. }
  1019. catch (err) {
  1020. agent.send(from, {type: 'request', id: message.id, error: err.message || err.toString()});
  1021. }
  1022. }
  1023. }
  1024. else {
  1025. if (this.receiveOriginal) {
  1026. this.receiveOriginal.call(agent, from, message);
  1027. }
  1028. }
  1029. };
  1030. /**
  1031. * Send a request
  1032. * @param {string} to Id of the recipient
  1033. * @param {*} message
  1034. * @returns {Promise.<*, Error>} Returns a promise resolving with the response message
  1035. */
  1036. RequestModule.prototype.request = function (to, message) {
  1037. var me = this;
  1038. return new Promise(function (resolve, reject) {
  1039. // put the data in an envelope with id
  1040. var id = uuid();
  1041. var envelope = {
  1042. type: 'request',
  1043. id: id,
  1044. message: message
  1045. };
  1046. // add the request to the list with requests in progress
  1047. me.queue[id] = {
  1048. resolve: resolve,
  1049. reject: reject,
  1050. timeout: setTimeout(function () {
  1051. delete me.queue[id];
  1052. reject(new Error('Timeout'));
  1053. }, me.timeout)
  1054. };
  1055. me.agent.send(to, envelope)
  1056. .catch(function (err) {
  1057. reject(err);
  1058. });
  1059. });
  1060. };
  1061. /**
  1062. * Get a map with mixin functions
  1063. * @return {{_receive: function, request: function}}
  1064. * Returns mixin function, which can be used to extend the agent.
  1065. */
  1066. RequestModule.prototype.mixin = function () {
  1067. return {
  1068. _receive: this.receive.bind(this),
  1069. request: this.request.bind(this)
  1070. }
  1071. };
  1072. module.exports = RequestModule;
  1073. },{"../util":23,"promise":114,"uuid-v4":125}],9:[function(_dereq_,module,exports){
  1074. 'use strict';
  1075. var Promise = _dereq_('promise');
  1076. /**
  1077. * An abstract Transport connection
  1078. * @param {Transport} transport
  1079. * @param {string} id
  1080. * @param {function} receive
  1081. * @constructor
  1082. * @abstract
  1083. */
  1084. function Connection (transport, id, receive) {
  1085. throw new Error('Cannot create an abstract Connection');
  1086. }
  1087. Connection.prototype.ready = Promise.reject(new Error('Cannot get abstract property ready'));
  1088. /**
  1089. * Send a message to an agent.
  1090. * @param {string} to
  1091. * @param {*} message
  1092. * @return {Promise} returns a promise which resolves when the message has been sent
  1093. */
  1094. Connection.prototype.send = function (to, message) {
  1095. throw new Error('Cannot call abstract function send');
  1096. };
  1097. /**
  1098. * Close the connection, disconnect from the transport.
  1099. */
  1100. Connection.prototype.close = function () {
  1101. throw new Error('Cannot call abstract function "close"');
  1102. };
  1103. module.exports = Connection;
  1104. },{"promise":114}],10:[function(_dereq_,module,exports){
  1105. 'use strict';
  1106. /**
  1107. * Abstract prototype of a transport
  1108. * @param {Object} [config]
  1109. * @constructor
  1110. */
  1111. function Transport(config) {
  1112. this.id = config && config.id || null;
  1113. this['default'] = config && config['default'] || false;
  1114. }
  1115. Transport.prototype.type = null;
  1116. /**
  1117. * Connect an agent
  1118. * @param {String} id
  1119. * @param {Function} receive Invoked as receive(from, message)
  1120. * @return {Connection} Returns a connection
  1121. */
  1122. Transport.prototype.connect = function(id, receive) {
  1123. throw new Error('Cannot invoke abstract function "connect"');
  1124. };
  1125. /**
  1126. * Close the transport
  1127. */
  1128. Transport.prototype.close = function() {
  1129. throw new Error('Cannot invoke abstract function "close"');
  1130. };
  1131. module.exports = Transport;
  1132. },{}],11:[function(_dereq_,module,exports){
  1133. 'use strict';
  1134. var Promise = _dereq_('promise');
  1135. var Connection = _dereq_('../Connection');
  1136. /**
  1137. * A local connection.
  1138. * @param {AMQPTransport} transport
  1139. * @param {string | number} id
  1140. * @param {function} receive
  1141. * @constructor
  1142. */
  1143. function AMQPConnection(transport, id, receive) {
  1144. this.transport = transport;
  1145. this.id = id;
  1146. // ready state
  1147. this.ready = this.transport._connect(id, receive);
  1148. }
  1149. /**
  1150. * Send a message to an agent.
  1151. * @param {string} to
  1152. * @param {*} message
  1153. * @return {Promise} returns a promise which resolves when the message has been sent
  1154. */
  1155. AMQPConnection.prototype.send = function (to, message) {
  1156. var me = this;
  1157. return new Promise(function (resolve, reject) {
  1158. var msg = {
  1159. body: {
  1160. from: me.id,
  1161. to: to,
  1162. message: message
  1163. }
  1164. };
  1165. var options = {
  1166. //immediate: true
  1167. };
  1168. me.transport.exchange.publish(to, msg, options, function () {
  1169. // FIXME: callback is not called.
  1170. //console.log('sent', arguments)
  1171. });
  1172. resolve();
  1173. });
  1174. };
  1175. /**
  1176. * Close the connection
  1177. */
  1178. AMQPConnection.prototype.close = function () {
  1179. this.transport._close(this.id);
  1180. };
  1181. module.exports = AMQPConnection;
  1182. },{"../Connection":9,"promise":114}],12:[function(_dereq_,module,exports){
  1183. 'use strict';
  1184. var Promise = _dereq_('promise');
  1185. var Transport = _dereq_('./../Transport');
  1186. var AMQPConnection = _dereq_('./AMQPConnection');
  1187. /**
  1188. * Use AMQP as transport
  1189. * @param {Object} config Config can contain the following properties:
  1190. * - `id: string`
  1191. * - `url: string`
  1192. * - `host: string`
  1193. * The config must contain either `url` or `host`.
  1194. * For example: {url: 'amqp://localhost'} or
  1195. * {host: 'dev.rabbitmq.com'}
  1196. * @constructor
  1197. */
  1198. function AMQPTransport(config) {
  1199. this.id = config.id || null;
  1200. this.networkId = config.url || config.host || null;
  1201. this['default'] = config['default'] || false;
  1202. this.config = config;
  1203. this.connection = null;
  1204. this.exchange = null;
  1205. this.subscriptions = [];
  1206. }
  1207. AMQPTransport.prototype = new Transport();
  1208. AMQPTransport.prototype.type = 'amqp';
  1209. /**
  1210. * Connect an agent
  1211. * @param {String} id
  1212. * @param {Function} receive Invoked as receive(from, message)
  1213. * @return {AMQPConnection} Returns a connection.
  1214. */
  1215. AMQPTransport.prototype.connect = function(id, receive) {
  1216. return new AMQPConnection(this, id, receive);
  1217. };
  1218. /**
  1219. * Get an AMQP connection. If there is not yet a connection, a connection will
  1220. * be made.
  1221. * @param {Function} callback Invoked as callback(connection)
  1222. * @private
  1223. */
  1224. AMQPTransport.prototype._getConnection = function(callback) {
  1225. var me = this;
  1226. if (this.connection) {
  1227. // connection is available
  1228. callback(this.connection);
  1229. }
  1230. else {
  1231. if (this._onConnected) {
  1232. // connection is being opened but not yet ready
  1233. this._onConnected.push(callback);
  1234. }
  1235. else {
  1236. // no connection, create one
  1237. this._onConnected = [callback];
  1238. var amqp = _dereq_('amqp'); // lazy load the amqp library
  1239. var connection = amqp.createConnection(this.config);
  1240. connection.on('ready', function () {
  1241. var exchange = connection.exchange('', {confirm: true}, function () {
  1242. var _onConnected = me._onConnected;
  1243. delete me._onConnected;
  1244. me.connection = connection;
  1245. me.exchange = exchange;
  1246. _onConnected.forEach(function (callback) {
  1247. callback(me.connection);
  1248. });
  1249. });
  1250. });
  1251. }
  1252. }
  1253. };
  1254. /**
  1255. * Open a connection
  1256. * @param {string} id
  1257. * @param {Function} receive Invoked as receive(from, message)
  1258. */
  1259. AMQPTransport.prototype._connect = function(id, receive) {
  1260. var me = this;
  1261. return new Promise(function (resolve, reject) {
  1262. function subscribe(connection) {
  1263. var queue = connection.queue(id, {}, function() {
  1264. queue
  1265. .subscribe(function(message) {
  1266. var body = message.body;
  1267. receive(body.from, body.message);
  1268. })
  1269. .addCallback(function (ok) {
  1270. // register this subscription
  1271. me.subscriptions.push({
  1272. id: id,
  1273. consumerTag: ok.consumerTag
  1274. });
  1275. resolve(me);
  1276. });
  1277. });
  1278. }
  1279. me._getConnection(subscribe);
  1280. });
  1281. };
  1282. /**
  1283. * Close a connection an agent by its id
  1284. * @param {String} id
  1285. */
  1286. AMQPTransport.prototype._close = function(id) {
  1287. var i = 0;
  1288. while (i < this.subscriptions.length) {
  1289. var subscription = this.subscriptions[i];
  1290. if (subscription.id == id) {
  1291. // remove this entry
  1292. this.subscriptions.splice(i, 1);
  1293. }
  1294. else {
  1295. i++;
  1296. }
  1297. }
  1298. if (this.subscriptions.length == 0) {
  1299. // fully disconnect if there are no subscribers left
  1300. this.exchange.destroy();
  1301. this.connection.disconnect();
  1302. this.connection = null;
  1303. this.exchange = null;
  1304. }
  1305. };
  1306. /**
  1307. * Close the transport.
  1308. */
  1309. AMQPTransport.prototype.close = function() {
  1310. this.connection.destroy();
  1311. this.connection = null;
  1312. };
  1313. module.exports = AMQPTransport;
  1314. },{"./../Transport":10,"./AMQPConnection":11,"amqp":24,"promise":114}],13:[function(_dereq_,module,exports){
  1315. 'use strict';
  1316. var Promise = _dereq_('promise');
  1317. var Connection = _dereq_('../Connection');
  1318. /**
  1319. * A local connection.
  1320. * @param {DistribusTransport} transport
  1321. * @param {string | number} id
  1322. * @param {function} receive
  1323. * @constructor
  1324. */
  1325. function DistribusConnection(transport, id, receive) {
  1326. this.transport = transport;
  1327. this.id = id;
  1328. // create a peer
  1329. var peer = this.transport.host.create(id);
  1330. peer.on('message', receive);
  1331. // ready state
  1332. this.ready = Promise.resolve(this);
  1333. }
  1334. /**
  1335. * Send a message to an agent.
  1336. * @param {string} to
  1337. * @param {*} message
  1338. * @return {Promise} returns a promise which resolves when the message has been sent
  1339. */
  1340. DistribusConnection.prototype.send = function (to, message) {
  1341. return this.transport.host.send(this.id, to, message);
  1342. };
  1343. /**
  1344. * Close the connection
  1345. */
  1346. DistribusConnection.prototype.close = function () {
  1347. this.transport.host.remove(this.id);
  1348. };
  1349. module.exports = DistribusConnection;
  1350. },{"../Connection":9,"promise":114}],14:[function(_dereq_,module,exports){
  1351. 'use strict';
  1352. var distribus = _dereq_('distribus');
  1353. var Transport = _dereq_('./../Transport');
  1354. var DistribusConnection = _dereq_('./DistribusConnection');
  1355. /**
  1356. * Use distribus as transport
  1357. * @param {Object} config Config can contain the following properties:
  1358. * - `id: string`. Optional
  1359. * - `host: distribus.Host`. Optional
  1360. * If `host` is not provided,
  1361. * a new local distribus Host is created.
  1362. * @constructor
  1363. */
  1364. function DistribusTransport(config) {
  1365. this.id = config && config.id || null;
  1366. this['default'] = config && config['default'] || false;
  1367. this.host = config && config.host || new distribus.Host(config);
  1368. this.networkId = this.host.networkId; // FIXME: networkId can change when host connects to another host.
  1369. }
  1370. DistribusTransport.prototype = new Transport();
  1371. DistribusTransport.prototype.type = 'distribus';
  1372. /**
  1373. * Connect an agent
  1374. * @param {String} id
  1375. * @param {Function} receive Invoked as receive(from, message)
  1376. * @return {DistribusConnection} Returns a connection.
  1377. */
  1378. DistribusTransport.prototype.connect = function(id, receive) {
  1379. return new DistribusConnection(this, id, receive);
  1380. };
  1381. /**
  1382. * Close the transport.
  1383. */
  1384. DistribusTransport.prototype.close = function() {
  1385. this.host.close();
  1386. this.host = null;
  1387. };
  1388. module.exports = DistribusTransport;
  1389. },{"./../Transport":10,"./DistribusConnection":13,"distribus":67}],15:[function(_dereq_,module,exports){
  1390. 'use strict';
  1391. var Promise = _dereq_('promise');
  1392. var Connection = _dereq_('../Connection');
  1393. /**
  1394. * A HTTP connection.
  1395. * @param {HTTPTransport} transport
  1396. * @param {string | number} id
  1397. * @param {function} receive
  1398. * @constructor
  1399. */
  1400. function HTTPConnection(transport, id, receive) {
  1401. this.transport = transport;
  1402. this.id = id;
  1403. // register the agents receive function
  1404. if (this.id in this.transport.agents) {
  1405. throw new Error('Agent with id ' + id + ' already exists');
  1406. }
  1407. this.transport.agents[this.id] = receive;
  1408. // ready state
  1409. this.ready = Promise.resolve(this);
  1410. }
  1411. /**
  1412. * Send a message to an agent.
  1413. * @param {string} to
  1414. * @param {*} message
  1415. */
  1416. HTTPConnection.prototype.send = function (to, message) {
  1417. var fromURL = this.transport.url.replace(':id', this.id);
  1418. var isURL = to.indexOf('://') !== -1;
  1419. var toURL;
  1420. if (isURL) {
  1421. toURL = to;
  1422. }
  1423. else {
  1424. if (this.transport.remoteUrl !== undefined) {
  1425. toURL = this.transport.remoteUrl.replace(':id', to);
  1426. }
  1427. else {
  1428. console.log('ERROR: no remote URL specified. Cannot send over HTTP.', to);
  1429. }
  1430. }
  1431. return this.transport.send(fromURL, toURL, message);
  1432. };
  1433. /**
  1434. * Close the connection
  1435. */
  1436. HTTPConnection.prototype.close = function () {
  1437. delete this.transport.agents[this.id];
  1438. };
  1439. module.exports = HTTPConnection;
  1440. },{"../Connection":9,"promise":114}],16:[function(_dereq_,module,exports){
  1441. 'use strict';
  1442. var http = _dereq_('http');
  1443. var Promise = _dereq_('promise');
  1444. var Transport = _dereq_('./../Transport');
  1445. var HTTPConnection = _dereq_('./HTTPConnection');
  1446. var uuid = _dereq_('uuid-v4');
  1447. /**
  1448. * HTTP Transport layer:
  1449. *
  1450. * Supported Options:
  1451. *
  1452. * {Number} config.port Port to listen on.
  1453. * {String} config.path Path, with or without leading and trailing slash (/)
  1454. * {Boolean} config.localShortcut If the agentId exists locally, use local transport. (local)
  1455. *
  1456. * Address: http://127.0.0.1:PORTNUMBER/PATH
  1457. */
  1458. function HTTPTransport(config) {
  1459. this.id = config && config.id || null;
  1460. this.networkId = null;
  1461. this.agents = {};
  1462. this.outstandingRequests = {}; // these are received messages that are expecting a response
  1463. this.outstandingMessages = {};
  1464. this.url = config && config.url || "http://127.0.0.1:3000/agents/:id";
  1465. this.remoteUrl = config && config.remoteUrl;
  1466. this.localShortcut = (config && config.localShortcut === false) ? false : true;
  1467. this.httpTimeout = config && config.httpTimeout || 2000; // 1 second - timeout to send message
  1468. this.httpResponseTimeout = config && config.httpResponseTimeout || 200; // 0.5 second - timeout to expect reply after delivering request
  1469. this.regexHosts = /[http]{4}s?:\/\/([a-z\-\.A-Z0-9]*):?([0-9]*)(\/[a-z\/:A-Z0-9._\-% \\\(\)\*\+\.\^\$]*)/;
  1470. this.urlHostData = this.regexHosts.exec(this.url);
  1471. this.regexPath = this.getRegEx(this.urlHostData[3]);
  1472. this.port = config && config.port || this.urlHostData[2] || 3000;
  1473. this.path = this.urlHostData[3].replace(':id', '');
  1474. }
  1475. HTTPTransport.prototype = new Transport();
  1476. HTTPTransport.prototype.type = 'http';
  1477. HTTPTransport.prototype.getRegEx = function(url) {
  1478. return new RegExp(url.replace(/[\\\(\)\*\+\.\^\$]/g,function(match) {return '\\' + match;}).replace(':id','([:a-zA-Z_0-9]*)'));
  1479. };
  1480. function askAgent(url,method,params,callback, async) {
  1481. if (async === undefined) {
  1482. async = true;
  1483. }
  1484. // create post request
  1485. var POSTrequest = JSON.stringify({"id":0, "method": method, "params": params});
  1486. // create XMLHttpRequest object to send the POST request
  1487. var http = new XMLHttpRequest();
  1488. // insert the callback function. This is called when the message has been delivered and a response has been received
  1489. http.onreadystatechange = function () {
  1490. if (http.readyState == 4 && http.status == 200) {
  1491. if (callback === undefined || callback === null) {
  1492. }
  1493. else {
  1494. // launch callback function
  1495. callback(JSON.parse(http.responseText));
  1496. }
  1497. }
  1498. else if (http.readyState == 4 && http.status != 200) {
  1499. console.log("Make sure that the Node server has started.");
  1500. }
  1501. };
  1502. // open an asynchronous POST connection
  1503. http.open("POST", url, async);
  1504. // include header so the receiving code knows its a JSON object
  1505. http.setRequestHeader("Content-type", "application/json");
  1506. // send
  1507. http.send(POSTrequest);
  1508. }
  1509. /**
  1510. * Connect an agent
  1511. * @param {String} id
  1512. * @param {Function} receive Invoked as receive(from, message)
  1513. * @return {HTTPConnection} Returns a connection.
  1514. */
  1515. HTTPTransport.prototype.connect = function(id, receive) {
  1516. if (this.server === undefined) {
  1517. this.initiateServer();
  1518. }
  1519. this.outstandingRequests[id] = {};
  1520. this.outstandingMessages[id] = {};
  1521. return new HTTPConnection(this, id, receive);
  1522. };
  1523. /**
  1524. * Send a message to an agent
  1525. * @param {String} from Id of sender
  1526. * @param {String} to Id of addressed peer
  1527. * @param {String} message
  1528. */
  1529. HTTPTransport.prototype.send = function(from, to, message) {
  1530. var me = this;
  1531. return new Promise(function (resolve,reject) {
  1532. var hostData = me.regexHosts.exec(to);
  1533. var fromRegexpCheck = me.regexPath.exec(from);
  1534. var fromAgentId = fromRegexpCheck[1];
  1535. var outstandingMessageID = uuid();
  1536. // check for local shortcut possibility
  1537. if (me.localShortcut == true) {
  1538. var toRegexpCheck = me.regexPath.exec(to);
  1539. var toAgentId = toRegexpCheck[1];
  1540. var toPath = hostData[3].replace(toAgentId,"");
  1541. // check if the "to" address is on the same URL, port and path as the "from"
  1542. if ((hostData[1] == '127.0.0.1' && hostData[2] == me.urlHostData[2] && toPath == me.path) ||
  1543. (me.urlHostData[1] == hostData[1] && hostData[2] == me.urlHostData[2] && toPath == me.path)) {
  1544. // by definition true but check anyway
  1545. if (me.agents[toAgentId] !== undefined) {
  1546. me.agents[toAgentId](fromAgentId, message);
  1547. resolve();
  1548. return;
  1549. }
  1550. }
  1551. }
  1552. // stringify the message. If the message is an object, it can have an ID so it may be part of a req/rep.
  1553. if (typeof message == 'object') {
  1554. // check if the send is a reply to an outstanding request and if so, deliver
  1555. var outstanding = me.outstandingRequests[fromAgentId];
  1556. if (outstanding[message.id] !== undefined) {
  1557. var callback = outstanding[message.id];
  1558. callback.response.end(JSON.stringify(message));
  1559. clearTimeout(callback.timeout);
  1560. delete outstanding[message.id];
  1561. resolve();
  1562. return;
  1563. }
  1564. // stringify the message.
  1565. message = JSON.stringify(message)
  1566. }
  1567. // all post options
  1568. var options = {
  1569. host: hostData[1],
  1570. port: hostData[2],
  1571. path: hostData[3],
  1572. method: 'POST',
  1573. headers: {
  1574. 'x-eve-senderurl' : from, // used to get senderID
  1575. 'Content-type' : 'text/plain'
  1576. }
  1577. };
  1578. var request = http.request(options, function(res) {
  1579. res.setEncoding('utf8');
  1580. // message was delivered, clear the cannot deliver timeout.
  1581. clearTimeout(me.outstandingMessages[fromAgentId][outstandingMessageID].timeout);
  1582. // listen to incoming data
  1583. res.on('data', function (response) {
  1584. var parsedResponse;
  1585. try {parsedResponse = JSON.parse(response);} catch (err) {parsedResponse = response;}
  1586. if (typeof parsedResponse == 'object') {
  1587. if (parsedResponse.__httpError__ !== undefined) {
  1588. reject(new Error(parsedResponse.__httpError__));
  1589. return;
  1590. }
  1591. }
  1592. me.agents[fromAgentId](to, parsedResponse);
  1593. resolve();
  1594. });
  1595. });
  1596. me.outstandingMessages[fromAgentId][outstandingMessageID] = {
  1597. timeout: setTimeout(function () {
  1598. request.abort();
  1599. reject(new Error("Cannot connect to " + to))
  1600. }, me.httpTimeout),
  1601. reject: reject
  1602. };
  1603. request.on('error', function(e) {
  1604. reject(e);
  1605. });
  1606. // write data to request body
  1607. request.write(message);
  1608. request.end();
  1609. });
  1610. };
  1611. /**
  1612. * This is the HTTP equivalent of receiveMessage.
  1613. *
  1614. * @param request
  1615. * @param response
  1616. */
  1617. HTTPTransport.prototype.processRequest = function(request, response) {
  1618. var url = request.url;
  1619. // define headers
  1620. var headers = {};
  1621. headers['Access-Control-Allow-Origin'] = '*';
  1622. headers['Access-Control-Allow-Credentials'] = true;
  1623. headers['Content-Type'] = 'text/plain';
  1624. var regexpCheck = this.regexPath.exec(url);
  1625. if (regexpCheck !== null) {
  1626. var agentId = regexpCheck[1];
  1627. var senderId = 'unknown';
  1628. if (request.headers['x-eve-senderurl'] !== undefined) {
  1629. senderId = request.headers['x-eve-senderurl'];
  1630. }
  1631. var body = '';
  1632. request.on('data', function (data) {
  1633. body += data;
  1634. if (body.length > 1e6) { // 1e6 == 1MB
  1635. request.connection.destroy(); // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
  1636. }
  1637. });
  1638. var me = this;
  1639. request.on('end', function () {
  1640. var expectReply = false;
  1641. var message;
  1642. try {message = JSON.parse(body);} catch (err) {message = body;}
  1643. // check if JSON RPC
  1644. expectReply = message.jsonrpc && message.jsonrpc == '2.0' || expectReply;
  1645. // check if type == 'request'
  1646. expectReply = message.type && message.type == 'request' || expectReply;
  1647. response.writeHead(200, headers);
  1648. // construct callback
  1649. var callback = me.agents[agentId];
  1650. if (callback === undefined) {
  1651. var error = new Error('Agent: "' + agentId + '" does not exist.');
  1652. response.end(JSON.stringify({__httpError__:error.message || error.toString()}));
  1653. }
  1654. else {
  1655. if (expectReply == true) {
  1656. me.outstandingRequests[agentId][message.id] = {
  1657. response: response,
  1658. timeout: setTimeout(function () {
  1659. response.end("timeout");
  1660. delete me.outstandingRequests[agentId][message.id];
  1661. }, me.httpResponseTimeout)
  1662. };
  1663. callback(senderId, message);
  1664. }
  1665. else {
  1666. // if we're not expecting a response, we first close the connection, then receive the message
  1667. response.end('');
  1668. if (callback !== undefined) {
  1669. callback(senderId, message);
  1670. }
  1671. }
  1672. }
  1673. });
  1674. }
  1675. };
  1676. /**
  1677. * Configure a HTTP server listener
  1678. */
  1679. HTTPTransport.prototype.initiateServer = function() {
  1680. if (this.server === undefined) {
  1681. var me = this;
  1682. this.server = http.createServer(function (request, response) {
  1683. if (request.method == 'OPTIONS') {
  1684. var headers = {};
  1685. headers['Access-Control-Allow-Origin'] = '*';
  1686. headers['Access-Control-Allow-Methods'] = 'POST, OPTIONS';
  1687. headers['Access-Control-Allow-Credentials'] = true;
  1688. headers['Access-Control-Max-Age'] = '86400'; // 24 hours
  1689. headers['Access-Control-Allow-Headers'] = 'X-Requested-With, Access-Control-Allow-Origin, X-HTTP-Method-Override, Content-Type, Authorization, Accept';
  1690. // respond to the request
  1691. response.writeHead(200, headers);
  1692. response.end();
  1693. }
  1694. else if (request.method == 'POST') {
  1695. me.processRequest(request, response);
  1696. }
  1697. });
  1698. this.server.on('error', function(err) {
  1699. if (err.code == 'EADDRINUSE') {
  1700. throw new Error('ERROR: Could not start HTTP server. Port ' + me.port + ' is occupied.');
  1701. }
  1702. else {
  1703. throw new Error(err);
  1704. }
  1705. });
  1706. // Listen on port (default: 3000), IP defaults to 127.0.0.1
  1707. this.server.listen(this.port, function() {
  1708. // Put a friendly message on the terminal
  1709. console.log('Server listening at ', me.url);
  1710. });
  1711. }
  1712. else {
  1713. this.server.close();
  1714. this.server = undefined;
  1715. this.initiateServer();
  1716. }
  1717. };
  1718. /**
  1719. * Close the HTTP server
  1720. */
  1721. HTTPTransport.prototype.close = function() {
  1722. // close all open connections
  1723. for (var agentId in this.outstandingRequests) {
  1724. if (this.outstandingRequests.hasOwnProperty(agentId)) {
  1725. var agentRequests = this.outstandingRequests[agentId];
  1726. for (var messageId in agentRequests) {
  1727. if (agentRequests.hasOwnProperty(messageId)) {
  1728. var openMessage = agentRequests[messageId];
  1729. var error = new Error('Server shutting down.');
  1730. openMessage.response.end(JSON.stringify({__httpError__:error.message || error.toString()}));
  1731. }
  1732. }
  1733. }
  1734. }
  1735. // close server
  1736. if (this.server) {
  1737. this.server.close();
  1738. }
  1739. this.server = null;
  1740. };
  1741. module.exports = HTTPTransport;
  1742. },{"./../Transport":10,"./HTTPConnection":15,"http":138,"promise":114,"uuid-v4":125}],17:[function(_dereq_,module,exports){
  1743. 'use strict';
  1744. var Promise = _dereq_('promise');
  1745. var Connection = _dereq_('../Connection');
  1746. /**
  1747. * A local connection.
  1748. * @param {LocalTransport} transport
  1749. * @param {string | number} id
  1750. * @param {function} receive
  1751. * @constructor
  1752. */
  1753. function LocalConnection(transport, id, receive) {
  1754. this.transport = transport;
  1755. this.id = id;
  1756. // register the agents receive function
  1757. if (this.id in this.transport.agents) {
  1758. throw new Error('Agent with id ' + id + ' already exists');
  1759. }
  1760. this.transport.agents[this.id] = receive;
  1761. // ready state
  1762. this.ready = Promise.resolve(this);
  1763. }
  1764. /**
  1765. * Send a message to an agent.
  1766. * @param {string} to
  1767. * @param {*} message
  1768. * @return {Promise} returns a promise which resolves when the message has been sent
  1769. */
  1770. LocalConnection.prototype.send = function (to, message) {
  1771. var callback = this.transport.agents[to];
  1772. if (!callback) {
  1773. throw new Error('Agent with id ' + to + ' not found');
  1774. }
  1775. // invoke the agents receiver as callback(from, message)
  1776. callback(this.id, message);
  1777. return Promise.resolve();
  1778. };
  1779. /**
  1780. * Close the connection
  1781. */
  1782. LocalConnection.prototype.close = function () {
  1783. delete this.transport.agents[this.id];
  1784. };
  1785. module.exports = LocalConnection;
  1786. },{"../Connection":9,"promise":114}],18:[function(_dereq_,module,exports){
  1787. 'use strict';
  1788. var Transport = _dereq_('./../Transport');
  1789. var LocalConnection = _dereq_('./LocalConnection');
  1790. /**
  1791. * Create a local transport.
  1792. * @param {Object} config Config can contain the following properties:
  1793. * - `id: string`. Optional
  1794. * @constructor
  1795. */
  1796. function LocalTransport(config) {
  1797. this.id = config && config.id || null;
  1798. this.networkId = this.id || null;
  1799. this['default'] = config && config['default'] || false;
  1800. this.agents = {};
  1801. }
  1802. LocalTransport.prototype = new Transport();
  1803. LocalTransport.prototype.type = 'local';
  1804. /**
  1805. * Connect an agent
  1806. * @param {String} id
  1807. * @param {Function} receive Invoked as receive(from, message)
  1808. * @return {LocalConnection} Returns a promise which resolves when
  1809. * connected.
  1810. */
  1811. LocalTransport.prototype.connect = function(id, receive) {
  1812. return new LocalConnection(this, id, receive);
  1813. };
  1814. /**
  1815. * Close the transport. Removes all agent connections.
  1816. */
  1817. LocalTransport.prototype.close = function() {
  1818. this.agents = {};
  1819. };
  1820. module.exports = LocalTransport;
  1821. },{"./../Transport":10,"./LocalConnection":17}],19:[function(_dereq_,module,exports){
  1822. 'use strict';
  1823. var Promise = _dereq_('promise');
  1824. var Connection = _dereq_('../Connection');
  1825. /**
  1826. * A connection. The connection is ready when the property .ready resolves.
  1827. * @param {PubNubTransport} transport
  1828. * @param {string | number} id
  1829. * @param {function} receive
  1830. * @constructor
  1831. */
  1832. function PubNubConnection(transport, id, receive) {
  1833. this.id = id;
  1834. this.transport = transport;
  1835. // ready state
  1836. var me = this;
  1837. this.ready = new Promise(function (resolve, reject) {
  1838. transport.pubnub.subscribe({
  1839. channel: id,
  1840. message: function (message) {
  1841. receive(message.from, message.message);
  1842. },
  1843. connect: function () {
  1844. resolve(me);
  1845. }
  1846. });
  1847. });
  1848. }
  1849. /**
  1850. * Send a message to an agent.
  1851. * @param {string} to
  1852. * @param {*} message
  1853. * @return {Promise} returns a promise which resolves when the message has been sent
  1854. */
  1855. PubNubConnection.prototype.send = function (to, message) {
  1856. var me = this;
  1857. return new Promise(function (resolve, reject) {
  1858. me.transport.pubnub.publish({
  1859. channel: to,
  1860. message: {
  1861. from: me.id,
  1862. to: to,
  1863. message: message
  1864. },
  1865. callback: resolve,
  1866. error: reject
  1867. });
  1868. });
  1869. };
  1870. /**
  1871. * Close the connection
  1872. */
  1873. PubNubConnection.prototype.close = function () {
  1874. this.transport.pubnub.unsubscribe({
  1875. channel: this.id
  1876. });
  1877. };
  1878. module.exports = PubNubConnection;
  1879. },{"../Connection":9,"promise":114}],20:[function(_dereq_,module,exports){
  1880. 'use strict';
  1881. var Transport = _dereq_('./../Transport');
  1882. var PubNubConnection = _dereq_('./PubNubConnection');
  1883. /**
  1884. * Use pubnub as transport
  1885. * @param {Object} config Config can contain the following properties:
  1886. * - `id: string`. Optional
  1887. * - `publish_key: string`. Required
  1888. * - `subscribe_key: string`. Required
  1889. * @constructor
  1890. */
  1891. function PubNubTransport(config) {
  1892. this.id = config.id || null;
  1893. this.networkId = config.publish_key || null;
  1894. this['default'] = config['default'] || false;
  1895. this.pubnub = PUBNUB().init(config);
  1896. }
  1897. PubNubTransport.prototype = new Transport();
  1898. PubNubTransport.prototype.type = 'pubnub';
  1899. /**
  1900. * Connect an agent
  1901. * @param {String} id
  1902. * @param {Function} receive Invoked as receive(from, message)
  1903. * @return {PubNubConnection} Returns a connection
  1904. */
  1905. PubNubTransport.prototype.connect = function(id, receive) {
  1906. return new PubNubConnection(this, id, receive)
  1907. };
  1908. /**
  1909. * Close the transport.
  1910. */
  1911. PubNubTransport.prototype.close = function() {
  1912. // FIXME: how to correctly close a pubnub connection?
  1913. this.pubnub = null;
  1914. };
  1915. /**
  1916. * Load the PubNub library
  1917. * @returns {Object} PUBNUB
  1918. */
  1919. function PUBNUB() {
  1920. if (typeof window !== 'undefined') {
  1921. // browser
  1922. if (typeof window['PUBNUB'] === 'undefined') {
  1923. throw new Error('Please load pubnub first in the browser');
  1924. }
  1925. return window['PUBNUB'];
  1926. }
  1927. else {
  1928. // node.js
  1929. return _dereq_('pubnub');
  1930. }
  1931. }
  1932. module.exports = PubNubTransport;
  1933. },{"./../Transport":10,"./PubNubConnection":19,"pubnub":123}],21:[function(_dereq_,module,exports){
  1934. 'use strict';
  1935. var uuid = _dereq_('uuid-v4');
  1936. var Promise = _dereq_('promise');
  1937. var WebSocket = (typeof window !== 'undefined' && typeof window.WebSocket !== 'undefined') ?
  1938. window.WebSocket :
  1939. _dereq_('ws');
  1940. var util = _dereq_('../../util');
  1941. var Connection = _dereq_('../Connection');
  1942. /**
  1943. * A websocket connection.
  1944. * @param {WebSocketTransport} transport
  1945. * @param {string | number | null} url The url of the agent. The url must match
  1946. * the url of the WebSocket server.
  1947. * If url is null, a UUID id is generated as url.
  1948. * @param {function} receive
  1949. * @constructor
  1950. */
  1951. function WebSocketConnection(transport, url, receive) {
  1952. this.transport = transport;
  1953. this.url = url ? util.normalizeURL(url) : uuid();
  1954. this.receive = receive;
  1955. this.sockets = {};
  1956. this.closed = false;
  1957. this.reconnectTimers = {};
  1958. // ready state
  1959. this.ready = Promise.resolve(this);
  1960. }
  1961. /**
  1962. * Send a message to an agent.
  1963. * @param {string} to The WebSocket url of the receiver
  1964. * @param {*} message
  1965. * @return {Promise} Returns a promise which resolves when the message is sent,
  1966. * and rejects when sending the message failed
  1967. */
  1968. WebSocketConnection.prototype.send = function (to, message) {
  1969. //console.log('send', this.url, to, message); // TODO: cleanup
  1970. // deliver locally when possible
  1971. if (this.transport.localShortcut) {
  1972. var agent = this.transport.agents[to];
  1973. if (agent) {
  1974. try {
  1975. agent.receive(this.url, message);
  1976. return Promise.resolve();
  1977. }
  1978. catch (err) {
  1979. return Promise.reject(err);
  1980. }
  1981. }
  1982. }
  1983. // get or create a connection
  1984. var conn = this.sockets[to];
  1985. if (conn) {
  1986. try {
  1987. if (conn.readyState == conn.CONNECTING) {
  1988. // the connection is still opening
  1989. return new Promise(function (resolve, reject) {
  1990. conn.onopen.callback.push(function () {
  1991. conn.send(JSON.stringify(message));
  1992. resolve();
  1993. })
  1994. });
  1995. }
  1996. else if (conn.readyState == conn.OPEN) {
  1997. conn.send(JSON.stringify(message));
  1998. return Promise.resolve();
  1999. }
  2000. else {
  2001. // remove the connection
  2002. conn = null;
  2003. }
  2004. }
  2005. catch (err) {
  2006. return Promise.reject(err);
  2007. }
  2008. }
  2009. if (!conn) {
  2010. // try to open a connection
  2011. var me = this;
  2012. return new Promise(function (resolve, reject) {
  2013. me._connect(to, function (conn) {
  2014. conn.send(JSON.stringify(message));
  2015. resolve();
  2016. }, function (err) {
  2017. reject(new Error('Failed to connect to agent "' + to + '"'));
  2018. });
  2019. })
  2020. }
  2021. };
  2022. /**
  2023. * Open a websocket connection to an other agent. No messages are sent.
  2024. * @param {string} to Url of the remote agent.
  2025. * @returns {Promise.<WebSocketConnection, Error>}
  2026. * Returns a promise which resolves when the connection is
  2027. * established and rejects in case of an error.
  2028. */
  2029. WebSocketConnection.prototype.connect = function (to) {
  2030. var me = this;
  2031. return new Promise(function (resolve, reject) {
  2032. me._connect(to, function () {
  2033. resolve(me);
  2034. }, reject);
  2035. });
  2036. };
  2037. /**
  2038. * Open a websocket connection
  2039. * @param {String} to Url of the remote agent
  2040. * @param {function} [callback]
  2041. * @param {function} [errback]
  2042. * @param {boolean} [doReconnect=false]
  2043. * @returns {WebSocket}
  2044. * @private
  2045. */
  2046. WebSocketConnection.prototype._connect = function (to, callback, errback, doReconnect) {
  2047. var me = this;
  2048. var conn = new WebSocket(to + '?id=' + this.url);
  2049. // register the new socket
  2050. me.sockets[to] = conn;
  2051. conn.onopen = function () {
  2052. // Change doReconnect to true as soon as we have had an open connection
  2053. doReconnect = true;
  2054. conn.onopen.callbacks.forEach(function (cb) {
  2055. cb(conn);
  2056. });
  2057. conn.onopen.callbacks = [];
  2058. };
  2059. conn.onopen.callbacks = callback ? [callback] : [];
  2060. conn.onmessage = function (event) {
  2061. me.receive(to, JSON.parse(event.data));
  2062. };
  2063. conn.onclose = function () {
  2064. delete me.sockets[to];
  2065. if (doReconnect) {
  2066. me._reconnect(to);
  2067. }
  2068. };
  2069. conn.onerror = function (err) {
  2070. delete me.sockets[to];
  2071. if (errback) {
  2072. errback(err);
  2073. }
  2074. };
  2075. return conn;
  2076. };
  2077. /**
  2078. * Auto reconnect a broken connection
  2079. * @param {String} to Url of the remote agent
  2080. * @private
  2081. */
  2082. WebSocketConnection.prototype._reconnect = function (to) {
  2083. var me = this;
  2084. var doReconnect = true;
  2085. if (me.closed == false && me.reconnectTimers[to] == null) {
  2086. me.reconnectTimers[to] = setTimeout(function () {
  2087. delete me.reconnectTimers[to];
  2088. me._connect(to, null, null, doReconnect);
  2089. }, me.transport.reconnectDelay);
  2090. }
  2091. };
  2092. /**
  2093. * Register a websocket connection
  2094. * @param {String} from Url of the remote agent
  2095. * @param {WebSocket} conn WebSocket connection
  2096. * @returns {WebSocket} Returns the websocket itself
  2097. * @private
  2098. */
  2099. WebSocketConnection.prototype._onConnection = function (from, conn) {
  2100. var me = this;
  2101. conn.onmessage = function (event) {
  2102. me.receive(from, JSON.parse(event.data));
  2103. };
  2104. conn.onclose = function () {
  2105. // remove this connection from the sockets list
  2106. delete me.sockets[from];
  2107. };
  2108. conn.onerror = function (err) {
  2109. // TODO: what to do with errors?
  2110. delete me.sockets[from];
  2111. };
  2112. if (this.sockets[from]) {
  2113. // there is already a connection open with remote agent
  2114. // TODO: what to do with overwriting existing sockets?
  2115. this.sockets[from].close();
  2116. }
  2117. // register new connection
  2118. this.sockets[from] = conn;
  2119. return conn;
  2120. };
  2121. /**
  2122. * Get a list with all open sockets
  2123. * @return {String[]} Returns all open sockets
  2124. */
  2125. WebSocketConnection.prototype.list = function () {
  2126. return Object.keys(this.sockets);
  2127. };
  2128. /**
  2129. * Close the connection. All open sockets will be closed and the agent will
  2130. * be unregistered from the WebSocketTransport.
  2131. */
  2132. WebSocketConnection.prototype.close = function () {
  2133. this.closed = true;
  2134. // close all connections
  2135. for (var id in this.sockets) {
  2136. if (this.sockets.hasOwnProperty(id)) {
  2137. this.sockets[id].close();
  2138. }
  2139. }
  2140. this.sockets = {};
  2141. delete this.transport.agents[this.url];
  2142. };
  2143. module.exports = WebSocketConnection;
  2144. },{"../../util":23,"../Connection":9,"promise":114,"uuid-v4":125,"ws":126}],22:[function(_dereq_,module,exports){
  2145. 'use strict';
  2146. var urlModule = _dereq_('url');
  2147. var uuid = _dereq_('uuid-v4');
  2148. var Promise = _dereq_('promise');
  2149. var WebSocketServer = _dereq_('ws').Server;
  2150. var util = _dereq_('../../util');
  2151. var Transport = _dereq_('../Transport');
  2152. var WebSocketConnection = _dereq_('./WebSocketConnection');
  2153. /**
  2154. * Create a web socket transport.
  2155. * @param {Object} config Config can contain the following properties:
  2156. * - `id: string`. Optional
  2157. * - `default: boolean`. Optional
  2158. * - `url: string`. Optional. If provided,
  2159. * A WebSocket server is started on given
  2160. * url.
  2161. * - `localShortcut: boolean`. Optional. If true
  2162. * (default), messages to local agents are not
  2163. * send via WebSocket but delivered immediately
  2164. * - `reconnectDelay: number` Optional. Delay in
  2165. * milliseconds for reconnecting a broken
  2166. * connection. 10000 ms by default. Connections
  2167. * are only automatically reconnected after
  2168. * there has been an established connection.
  2169. * @constructor
  2170. */
  2171. function WebSocketTransport(config) {
  2172. this.id = config && config.id || null;
  2173. this.networkId = this.id || null;
  2174. this['default'] = config && config['default'] || false;
  2175. this.localShortcut = (config && config.localShortcut === false) ? false : true;
  2176. this.reconnectDelay = config && config.reconnectDelay || 10000;
  2177. this.url = config && config.url || null;
  2178. this.server = null;
  2179. if (this.url != null) {
  2180. var urlParts = urlModule.parse(this.url);
  2181. if (urlParts.protocol != 'ws:') throw new Error('Invalid protocol, "ws:" expected');
  2182. if (this.url.indexOf(':id') == -1) throw new Error('":id" placeholder missing in url');
  2183. this.address = urlParts.protocol + '//' + urlParts.host; // the url without path, for example 'ws://localhost:3000'
  2184. this.ready = this._initServer(this.url);
  2185. }
  2186. else {
  2187. this.address = null;
  2188. this.ready = Promise.resolve(this);
  2189. }
  2190. this.agents = {}; // WebSocketConnections of all registered agents. The keys are the urls of the agents
  2191. }
  2192. WebSocketTransport.prototype = new Transport();
  2193. WebSocketTransport.prototype.type = 'ws';
  2194. /**
  2195. * Build an url for given id. Example:
  2196. * var url = getUrl('agent1'); // 'ws://localhost:3000/agents/agent1'
  2197. * @param {String} id
  2198. * @return {String} Returns the url, or returns null when no url placeholder
  2199. * is defined.
  2200. */
  2201. WebSocketTransport.prototype.getUrl = function (id) {
  2202. return this.url ? this.url.replace(':id', id) : null;
  2203. };
  2204. /**
  2205. * Initialize a server on given url
  2206. * @param {String} url For example 'http://localhost:3000'
  2207. * @return {Promise} Returns a promise which resolves when the server is up
  2208. * and running
  2209. * @private
  2210. */
  2211. WebSocketTransport.prototype._initServer = function (url) {
  2212. var urlParts = urlModule.parse(url);
  2213. var port = urlParts.port || 80;
  2214. var me = this;
  2215. return new Promise(function (resolve, reject) {
  2216. me.server = new WebSocketServer({port: port}, function () {
  2217. resolve(me);
  2218. });
  2219. me.server.on('connection', me._onConnection.bind(me));
  2220. me.server.on('error', function (err) {
  2221. reject(err)
  2222. });
  2223. })
  2224. };
  2225. /**
  2226. * Handle a new connection. The connection is added to the addressed agent.
  2227. * @param {WebSocket} conn
  2228. * @private
  2229. */
  2230. WebSocketTransport.prototype._onConnection = function (conn) {
  2231. var url = conn.upgradeReq.url;
  2232. var urlParts = urlModule.parse(url, true);
  2233. var toPath = urlParts.pathname;
  2234. var to = util.normalizeURL(this.address + toPath);
  2235. // read sender id from query parameters or generate a random uuid
  2236. var queryParams = urlParts.query;
  2237. var from = queryParams.id || uuid();
  2238. // TODO: make a config option to allow/disallow anonymous connections?
  2239. //console.log('onConnection, to=', to, ', from=', from, ', agents:', Object.keys(this.agents)); // TODO: cleanup
  2240. var agent = this.agents[to];
  2241. if (agent) {
  2242. agent._onConnection(from, conn);
  2243. }
  2244. else {
  2245. // reject the connection
  2246. // conn.send('Error: Agent with id "' + to + '" not found'); // TODO: can we send back a message before closing?
  2247. conn.close();
  2248. }
  2249. };
  2250. /**
  2251. * Connect an agent
  2252. * @param {string} id The id or url of the agent. In case of an
  2253. * url, this url should match the url of the
  2254. * WebSocket server.
  2255. * @param {Function} receive Invoked as receive(from, message)
  2256. * @return {WebSocketConnection} Returns a promise which resolves when
  2257. * connected.
  2258. */
  2259. WebSocketTransport.prototype.connect = function(id, receive) {
  2260. var isURL = (id.indexOf('://') !== -1);
  2261. // FIXME: it's confusing right now what the final url will be based on the provided id...
  2262. var url = isURL ? id : (this.getUrl(id) || id);
  2263. if (url) url = util.normalizeURL(url);
  2264. // register the agents receive function
  2265. if (this.agents[url]) {
  2266. throw new Error('Agent with id ' + this.id + ' already exists');
  2267. }
  2268. var conn = new WebSocketConnection(this, url, receive);
  2269. this.agents[conn.url] = conn; // use conn.url, url can be changed when it was null
  2270. return conn;
  2271. };
  2272. /**
  2273. * Close the transport. Removes all agent connections.
  2274. */
  2275. WebSocketTransport.prototype.close = function() {
  2276. // close all connections
  2277. for (var id in this.agents) {
  2278. if (this.agents.hasOwnProperty(id)) {
  2279. this.agents[id].close();
  2280. }
  2281. }
  2282. this.agents = {};
  2283. // close the server
  2284. if (this.server) {
  2285. this.server.close();
  2286. }
  2287. };
  2288. module.exports = WebSocketTransport;
  2289. },{"../../util":23,"../Transport":10,"./WebSocketConnection":21,"promise":114,"url":157,"uuid-v4":125,"ws":126}],23:[function(_dereq_,module,exports){
  2290. 'use strict';
  2291. /**
  2292. * Test whether the provided value is a Promise.
  2293. * A value is marked as a Promise when it is an object containing functions
  2294. * `then` and `catch`.
  2295. * @param {*} value
  2296. * @return {boolean} Returns true when `value` is a Promise
  2297. */
  2298. exports.isPromise = function (value) {
  2299. return value &&
  2300. typeof value['then'] === 'function' &&
  2301. typeof value['catch'] === 'function'
  2302. };
  2303. /**
  2304. * Splits an url like "protocol://domain/path"
  2305. * @param {string} url
  2306. * @return {{protocol: string, domain: string, path: string} | null}
  2307. * Returns an object with properties protocol, domain, and path
  2308. * when there is a match. Returns null if no valid url.
  2309. *
  2310. */
  2311. exports.parseUrl = function (url) {
  2312. // match an url like "protocol://domain/path"
  2313. var match = /^([A-z]+):\/\/([^\/]+)(\/(.*)$|$)/.exec(url);
  2314. if (match) {
  2315. return {
  2316. protocol: match[1],
  2317. domain: match[2],
  2318. path: match[4]
  2319. }
  2320. }
  2321. return null;
  2322. };
  2323. /**
  2324. * Normalize a url. Removes trailing slash
  2325. * @param {string} url
  2326. * @return {string} Returns the normalized url
  2327. */
  2328. exports.normalizeURL = function (url) {
  2329. if (url[url.length - 1] == '/') {
  2330. return url.substring(0, url.length - 1);
  2331. }
  2332. else {
  2333. return url;
  2334. }
  2335. };
  2336. },{}],24:[function(_dereq_,module,exports){
  2337. 'use strict';
  2338. var Connection = _dereq_('./lib/connection');
  2339. module.exports = {
  2340. Connection: Connection,
  2341. createConnection: function (options, implOptions, readyCallback) {
  2342. var c = new Connection(options, implOptions, readyCallback);
  2343. c.connect();
  2344. return c;
  2345. }
  2346. };
  2347. },{"./lib/connection":28}],25:[function(_dereq_,module,exports){
  2348. // Copyright (c) 2008, Fair Oaks Labs, Inc.
  2349. // All rights reserved.
  2350. //
  2351. // Redistribution and use in source and binary forms, with or without modification, are
  2352. // permitted provided that the following conditions are met:
  2353. //
  2354. // * Redistributions of source code must retain the above copyright notice, this list
  2355. // of conditions and the following disclaimer.
  2356. // * Redistributions in binary form must reproduce the above copyright notice, this
  2357. // list of conditions and the following disclaimer in the documentation and/or other
  2358. // materials provided with the distribution.
  2359. // * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors may be
  2360. // used to endorse or promote products derived from this software without specific
  2361. // prior written permission.
  2362. //
  2363. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
  2364. // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  2365. // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
  2366. // THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  2367. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  2368. // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  2369. // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  2370. // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  2371. // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2372. // Modified from original JSPack <cbond@positrace.com>
  2373. exports.jspack = function (bigEndian) {
  2374. this.bigEndian = bigEndian;
  2375. }
  2376. exports.jspack.prototype._DeArray = function (a, p, l) {
  2377. return [a.slice(p, p + l)];
  2378. };
  2379. exports.jspack.prototype._EnArray = function (a, p, l, v) {
  2380. for (var i = 0; i < l; ++i) {
  2381. a[p + i] = v[i] ? v[i] : 0;
  2382. }
  2383. };
  2384. exports.jspack.prototype._DeChar = function (a, p) {
  2385. return String.fromCharCode(a[p]);
  2386. };
  2387. exports.jspack.prototype._EnChar = function (a, p, v) {
  2388. a[p] = v.charCodeAt(0);
  2389. };
  2390. exports.jspack.prototype._DeInt = function (a, p) {
  2391. var lsb = bigEndian ? format.len - 1 : 0;
  2392. var nsb = bigEndian ? -1 : 1;
  2393. var stp = lsb + nsb * format.len,
  2394. rv;
  2395. var ret = 0;
  2396. var i = lsb;
  2397. var f = 1;
  2398. while (i != stp) {
  2399. rv += a[p + i] * f;
  2400. i += nsb;
  2401. f *= 256;
  2402. }
  2403. if (format.signed) {
  2404. if ((rv & Math.pow(2, format.len * 8 - 1)) != 0) {
  2405. rv -= Math.pow(2, format.len * 8);
  2406. }
  2407. }
  2408. return rv;
  2409. };
  2410. exports.jspack.prototype._EnInt = function (a, p, v) {
  2411. var lsb = bigEndian ? format.len - 1 : 0;
  2412. var nsb = bigEndian ? -1 : 1;
  2413. var stp = lsb + nsb * format.len;
  2414. v = v < format.min ? format.min : ((v > format.max) ? format.max : v);
  2415. var i = lsb;
  2416. while (i != stp) {
  2417. a[p + i] = v & 0xff;
  2418. i += nsb;
  2419. v >>= 8;
  2420. }
  2421. };
  2422. exports.jspack.prototype._DeString = function (a, p, l) {
  2423. var rv = new Array(1);
  2424. for (i = 0; i < l; i++) {
  2425. rv[i] = String.fromCharCode(a[p + i]);
  2426. }
  2427. return rv.join('');
  2428. };
  2429. exports.jspack.prototype._EnString = function (a, p, l, v) {
  2430. for (var t, i = 0; i < l; ++i) {
  2431. t = v.charCodeAt(i);
  2432. if (!t) t = 0;
  2433. a[p + i] = t;
  2434. }
  2435. };
  2436. exports.jspack.prototype._De754 = function (a, p) {
  2437. var s, e, m, i, d, bits, bit, len, bias, max;
  2438. bit = format.bit;
  2439. len = format.len * 8 - format.bit - 1;
  2440. max = (1 << len) - 1;
  2441. bias = max >> 1;
  2442. i = bigEndian ? 0 : format.len - 1;
  2443. d = bigEndian ? 1 : -1;;
  2444. s = a[p + i];
  2445. i = i + d;
  2446. bits = -7;
  2447. e = s & ((1 << -bits) - 1);
  2448. s >>= -bits;
  2449. for (bits += len; bits > 0; bits -= 8) {
  2450. e = e * 256 + a[p + i];
  2451. i += d;
  2452. }
  2453. m = e & ((1 << -bits) - 1);
  2454. e >>= -bits;
  2455. for (bits += bit; bits > 0; bits -= 8) {
  2456. m = m * 256 + a[p + i];
  2457. i += d;
  2458. }
  2459. switch (e) {
  2460. case 0:
  2461. // Zero, or denormalized number
  2462. e = 1 - bias;
  2463. break;
  2464. case max:
  2465. // NaN, or +/-Infinity
  2466. return m ? NaN : ((s ? -1 : 1) * Infinity);
  2467. default:
  2468. // Normalized number
  2469. m = m + Math.pow(2, bit);
  2470. e = e - bias;
  2471. break;
  2472. }
  2473. return (s ? -1 : 1) * m * Math.pow(2, e - bit);
  2474. };
  2475. exports.jspack.prototype._En754 = function (a, p, v) {
  2476. var s, e, m, i, d, c, bit, len, bias, max;
  2477. bit = format.bit;
  2478. len = format.len * 8 - format.bit - 1;
  2479. max = (1 << len) - 1;
  2480. bias = max >> 1;
  2481. s = v < 0 ? 1 : 0;
  2482. v = Math.abs(v);
  2483. if (isNaN(v) || (v == Infinity)) {
  2484. m = isNaN(v) ? 1 : 0;
  2485. e = max;
  2486. } else {
  2487. e = Math.floor(Math.log(v) / Math.LN2); // Calculate log2 of the value
  2488. c = Math.pow(2, -e);
  2489. if (v * c < 1) {
  2490. e--;
  2491. c = c * 2;
  2492. }
  2493. // Round by adding 1/2 the significand's LSD
  2494. if (e + bias >= 1) {
  2495. v += format.rt / c; // Normalized: bit significand digits
  2496. } else {
  2497. v += format.rt * Math.pow(2, 1 - bias); // Denormalized: <= bit significand digits
  2498. }
  2499. if (v * c >= 2) {
  2500. e++;
  2501. c = c / 2; // Rounding can increment the exponent
  2502. }
  2503. if (e + bias >= max) { // overflow
  2504. m = 0;
  2505. e = max;
  2506. } else if (e + bias >= 1) { // normalized
  2507. m = (v * c - 1) * Math.pow(2, bit); // do not reorder this expression
  2508. e = e + bias;
  2509. } else {
  2510. // Denormalized - also catches the '0' case, somewhat by chance
  2511. m = v * Math.pow(2, bias - 1) * Math.pow(2, bit);
  2512. e = 0;
  2513. }
  2514. }
  2515. i = bigEndian ? format.len - 1 : 0;
  2516. d = bigEndian ? -1 : 1;;
  2517. while (bit >= 8) {
  2518. a[p + i] = m & 0xff;
  2519. i += d;
  2520. m /= 256;
  2521. bit -= 8;
  2522. }
  2523. e = (e << bit) | m;
  2524. for (len += bit; len > 0; len -= 8) {
  2525. a[p + i] = e & 0xff;
  2526. i += d;
  2527. e /= 256;
  2528. }
  2529. a[p + i - d] |= s * 128;
  2530. };
  2531. // Unpack a series of n formatements of size s from array a at offset p with fxn
  2532. exports.jspack.prototype._UnpackSeries = function (n, s, a, p) {
  2533. var fxn = format.de;
  2534. var ret = [];
  2535. for (var i = 0; i < n; i++) {
  2536. ret.push(fxn(a, p + i * s));
  2537. }
  2538. return ret;
  2539. };
  2540. // Pack a series of n formatements of size s from array v at offset i to array a at offset p with fxn
  2541. exports.jspack.prototype._PackSeries = function (n, s, a, p, v, i) {
  2542. var fxn = format.en;
  2543. for (o = 0; o < n; o++) {
  2544. fxn(a, p + o * s, v[i + o]);
  2545. }
  2546. };
  2547. // Unpack the octet array a, beginning at offset p, according to the fmt string
  2548. exports.jspack.prototype.Unpack = function (fmt, a, p) {
  2549. bigEndian = fmt.charAt(0) != '<';
  2550. if (p == undefined || p == null) p = 0;
  2551. var re = new RegExp(this._sPattern, 'g');
  2552. var ret = [];
  2553. for (var m; m = re.exec(fmt); /* */ ) {
  2554. var n;
  2555. if (m[1] == undefined || m[1] == '') n = 1;
  2556. else n = parseInt(m[1]);
  2557. var s = this._lenLut[m[2]];
  2558. if ((p + n * s) > a.length) return undefined;
  2559. switch (m[2]) {
  2560. case 'A':
  2561. case 's':
  2562. rv.push(this._formatLut[m[2]].de(a, p, n));
  2563. break;
  2564. case 'c':
  2565. case 'b':
  2566. case 'B':
  2567. case 'h':
  2568. case 'H':
  2569. case 'i':
  2570. case 'I':
  2571. case 'l':
  2572. case 'L':
  2573. case 'f':
  2574. case 'd':
  2575. format = this._formatLut[m[2]];
  2576. ret.push(this._UnpackSeries(n, s, a, p));
  2577. break;
  2578. }
  2579. p += n * s;
  2580. }
  2581. return Array.prototype.concat.apply([], ret);
  2582. };
  2583. // Pack the supplied values into the octet array a, beginning at offset p, according to the fmt string
  2584. exports.jspack.prototype.PackTo = function (fmt, a, p, values) {
  2585. bigEndian = (fmt.charAt(0) != '<');
  2586. var re = new RegExp(this._sPattern, 'g');
  2587. for (var m, i = 0; m = re.exec(fmt); /* */ ) {
  2588. var n;
  2589. if (m[1] == undefined || m[1] == '') n = 1;
  2590. else n = parseInt(m[1]);
  2591. var s = this._lenLut[m[2]];
  2592. if ((p + n * s) > a.length) return false;
  2593. switch (m[2]) {
  2594. case 'A':
  2595. case 's':
  2596. if ((i + 1) > values.length) return false;
  2597. this._formatLut[m[2]].en(a, p, n, values[i]);
  2598. i += 1;
  2599. break;
  2600. case 'c':
  2601. case 'b':
  2602. case 'B':
  2603. case 'h':
  2604. case 'H':
  2605. case 'i':
  2606. case 'I':
  2607. case 'l':
  2608. case 'L':
  2609. case 'f':
  2610. case 'd':
  2611. format = this._formatLut[m[2]];
  2612. if (i + n > values.length) return false;
  2613. this._PackSeries(n, s, a, p, values, i);
  2614. i += n;
  2615. break;
  2616. case 'x':
  2617. for (var j = 0; j < n; j++) {
  2618. a[p + j] = 0;
  2619. }
  2620. break;
  2621. }
  2622. p += n * s;
  2623. }
  2624. return a;
  2625. };
  2626. // Pack the supplied values into a new octet array, according to the fmt string
  2627. exports.jspack.prototype.Pack = function (fmt, values) {
  2628. return this.PackTo(fmt, new Array(this.CalcLength(fmt)), 0, values);
  2629. };
  2630. // Determine the number of bytes represented by the format string
  2631. exports.jspack.prototype.CalcLength = function (fmt) {
  2632. var re = new RegExp(this._sPattern, 'g');
  2633. var sz = 0;
  2634. while (match = re.exec(fmt)) {
  2635. var n;
  2636. if (match[1] == undefined || match[1] == '') n = 1;
  2637. else n = parseInt(match[1]);
  2638. sz += n * this._lenLut[match[2]];
  2639. }
  2640. return sz;
  2641. };
  2642. // Regular expression for counting digits
  2643. exports.jspack.prototype._sPattern = '(\\d+)?([AxcbBhHsfdiIlL])';
  2644. // Byte widths for associated formats
  2645. exports.jspack.prototype._lenLut = {
  2646. 'A': 1,
  2647. 'x': 1,
  2648. 'c': 1,
  2649. 'b': 1,
  2650. 'B': 1,
  2651. 'h': 2,
  2652. 'H': 2,
  2653. 's': 1,
  2654. 'f': 4,
  2655. 'd': 8,
  2656. 'i': 4,
  2657. 'I': 4,
  2658. 'l': 4,
  2659. 'L': 4
  2660. };
  2661. exports.jspack.prototype._formatLut = {
  2662. 'A': {
  2663. en: exports.jspack.prototype._EnArray,
  2664. de: exports.jspack.prototype._DeArray
  2665. },
  2666. 's': {
  2667. en: exports.jspack.prototype._EnString,
  2668. de: exports.jspack.prototype._DeString
  2669. },
  2670. 'c': {
  2671. en: exports.jspack.prototype._EnChar,
  2672. de: exports.jspack.prototype._DeChar
  2673. },
  2674. 'b': {
  2675. en: exports.jspack.prototype._EnInt,
  2676. de: exports.jspack.prototype._DeInt,
  2677. len: 1,
  2678. signed: true,
  2679. min: -Math.pow(2, 7),
  2680. max: Math.pow(2, 7) - 1
  2681. },
  2682. 'B': {
  2683. en: exports.jspack.prototype._EnInt,
  2684. de: exports.jspack.prototype._DeInt,
  2685. len: 1,
  2686. signed: false,
  2687. min: 0,
  2688. max: Math.pow(2, 8) - 1
  2689. },
  2690. 'h': {
  2691. en: exports.jspack.prototype._EnInt,
  2692. de: exports.jspack.prototype._DeInt,
  2693. len: 2,
  2694. signed: true,
  2695. min: -Math.pow(2, 15),
  2696. max: Math.pow(2, 15) - 1
  2697. },
  2698. 'H': {
  2699. en: exports.jspack.prototype._EnInt,
  2700. de: exports.jspack.prototype._DeInt,
  2701. len: 2,
  2702. signed: false,
  2703. min: 0,
  2704. max: Math.pow(2, 16) - 1
  2705. },
  2706. 'i': {
  2707. en: exports.jspack.prototype._EnInt,
  2708. de: exports.jspack.prototype._DeInt,
  2709. len: 4,
  2710. signed: true,
  2711. min: -Math.pow(2, 31),
  2712. max: Math.pow(2, 31) - 1
  2713. },
  2714. 'I': {
  2715. en: exports.jspack.prototype._EnInt,
  2716. de: exports.jspack.prototype._DeInt,
  2717. len: 4,
  2718. signed: false,
  2719. min: 0,
  2720. max: Math.pow(2, 32) - 1
  2721. },
  2722. 'l': {
  2723. en: exports.jspack.prototype._EnInt,
  2724. de: exports.jspack.prototype._DeInt,
  2725. len: 4,
  2726. signed: true,
  2727. min: -Math.pow(2, 31),
  2728. max: Math.pow(2, 31) - 1
  2729. },
  2730. 'L': {
  2731. en: exports.jspack.prototype._EnInt,
  2732. de: exports.jspack.prototype._DeInt,
  2733. len: 4,
  2734. signed: false,
  2735. min: 0,
  2736. max: Math.pow(2, 32) - 1
  2737. },
  2738. 'f': {
  2739. en: exports.jspack.prototype._En754,
  2740. de: exports.jspack.prototype._De754,
  2741. len: 4,
  2742. bit: 23,
  2743. rt: Math.pow(2, -24) - Math.pow(2, -77)
  2744. },
  2745. 'd': {
  2746. en: exports.jspack.prototype._En754,
  2747. de: exports.jspack.prototype._De754,
  2748. len: 8,
  2749. bit: 52,
  2750. rt: 0
  2751. }
  2752. };
  2753. },{}],26:[function(_dereq_,module,exports){
  2754. exports.constants = [
  2755. [1, "frameMethod"],
  2756. [2, "frameHeader"],
  2757. [3, "frameBody"],
  2758. [8, "frameHeartbeat"],
  2759. [200, "replySuccess"],
  2760. [206, "frameEnd"],
  2761. [311, "contentTooLarge"],
  2762. [313, "noConsumers"],
  2763. [320, "connectionForced"],
  2764. [402, "invalidPath"],
  2765. [403, "accessRefused"],
  2766. [404, "notFound"],
  2767. [405, "resourceLocked"],
  2768. [406, "preconditionFailed"],
  2769. [501, "frameError"],
  2770. [502, "syntaxError"],
  2771. [503, "commandInvalid"],
  2772. [504, "channelError"],
  2773. [505, "unexpectedFrame"],
  2774. [506, "resourceError"],
  2775. [530, "notAllowed"],
  2776. [540, "notImplemented"],
  2777. [541, "internalError"],
  2778. [4096, "frameMinSize"]
  2779. ];
  2780. exports.classes = [{
  2781. "name": "connection",
  2782. "index": 10,
  2783. "fields": [],
  2784. "methods": [{
  2785. "name": "start",
  2786. "index": 10,
  2787. "fields": [{
  2788. "name": "versionMajor",
  2789. "domain": "octet"
  2790. }, {
  2791. "name": "versionMinor",
  2792. "domain": "octet"
  2793. }, {
  2794. "name": "serverProperties",
  2795. "domain": "table"
  2796. }, {
  2797. "name": "mechanisms",
  2798. "domain": "longstr"
  2799. }, {
  2800. "name": "locales",
  2801. "domain": "longstr"
  2802. }]
  2803. }, {
  2804. "name": "startOk",
  2805. "index": 11,
  2806. "fields": [{
  2807. "name": "clientProperties",
  2808. "domain": "table"
  2809. }, {
  2810. "name": "mechanism",
  2811. "domain": "shortstr"
  2812. }, {
  2813. "name": "response",
  2814. "domain": "longstr"
  2815. }, {
  2816. "name": "locale",
  2817. "domain": "shortstr"
  2818. }]
  2819. }, {
  2820. "name": "secure",
  2821. "index": 20,
  2822. "fields": [{
  2823. "name": "challenge",
  2824. "domain": "longstr"
  2825. }]
  2826. }, {
  2827. "name": "secureOk",
  2828. "index": 21,
  2829. "fields": [{
  2830. "name": "response",
  2831. "domain": "longstr"
  2832. }]
  2833. }, {
  2834. "name": "tune",
  2835. "index": 30,
  2836. "fields": [{
  2837. "name": "channelMax",
  2838. "domain": "short"
  2839. }, {
  2840. "name": "frameMax",
  2841. "domain": "long"
  2842. }, {
  2843. "name": "heartbeat",
  2844. "domain": "short"
  2845. }]
  2846. }, {
  2847. "name": "tuneOk",
  2848. "index": 31,
  2849. "fields": [{
  2850. "name": "channelMax",
  2851. "domain": "short"
  2852. }, {
  2853. "name": "frameMax",
  2854. "domain": "long"
  2855. }, {
  2856. "name": "heartbeat",
  2857. "domain": "short"
  2858. }]
  2859. }, {
  2860. "name": "open",
  2861. "index": 40,
  2862. "fields": [{
  2863. "name": "virtualHost",
  2864. "domain": "shortstr"
  2865. }, {
  2866. "name": "reserved1",
  2867. "domain": "shortstr"
  2868. }, {
  2869. "name": "reserved2",
  2870. "domain": "bit"
  2871. }]
  2872. }, {
  2873. "name": "openOk",
  2874. "index": 41,
  2875. "fields": [{
  2876. "name": "reserved1",
  2877. "domain": "shortstr"
  2878. }]
  2879. }, {
  2880. "name": "close",
  2881. "index": 50,
  2882. "fields": [{
  2883. "name": "replyCode",
  2884. "domain": "short"
  2885. }, {
  2886. "name": "replyText",
  2887. "domain": "shortstr"
  2888. }, {
  2889. "name": "classId",
  2890. "domain": "short"
  2891. }, {
  2892. "name": "methodId",
  2893. "domain": "short"
  2894. }]
  2895. }, {
  2896. "name": "closeOk",
  2897. "index": 51,
  2898. "fields": []
  2899. }]
  2900. }, {
  2901. "name": "channel",
  2902. "index": 20,
  2903. "fields": [],
  2904. "methods": [{
  2905. "name": "open",
  2906. "index": 10,
  2907. "fields": [{
  2908. "name": "reserved1",
  2909. "domain": "shortstr"
  2910. }]
  2911. }, {
  2912. "name": "openOk",
  2913. "index": 11,
  2914. "fields": [{
  2915. "name": "reserved1",
  2916. "domain": "longstr"
  2917. }]
  2918. }, {
  2919. "name": "flow",
  2920. "index": 20,
  2921. "fields": [{
  2922. "name": "active",
  2923. "domain": "bit"
  2924. }]
  2925. }, {
  2926. "name": "flowOk",
  2927. "index": 21,
  2928. "fields": [{
  2929. "name": "active",
  2930. "domain": "bit"
  2931. }]
  2932. }, {
  2933. "name": "close",
  2934. "index": 40,
  2935. "fields": [{
  2936. "name": "replyCode",
  2937. "domain": "short"
  2938. }, {
  2939. "name": "replyText",
  2940. "domain": "shortstr"
  2941. }, {
  2942. "name": "classId",
  2943. "domain": "short"
  2944. }, {
  2945. "name": "methodId",
  2946. "domain": "short"
  2947. }]
  2948. }, {
  2949. "name": "closeOk",
  2950. "index": 41,
  2951. "fields": []
  2952. }]
  2953. }, {
  2954. "name": "exchange",
  2955. "index": 40,
  2956. "fields": [],
  2957. "methods": [{
  2958. "name": "declare",
  2959. "index": 10,
  2960. "fields": [{
  2961. "name": "reserved1",
  2962. "domain": "short"
  2963. }, {
  2964. "name": "exchange",
  2965. "domain": "shortstr"
  2966. }, {
  2967. "name": "type",
  2968. "domain": "shortstr"
  2969. }, {
  2970. "name": "passive",
  2971. "domain": "bit"
  2972. }, {
  2973. "name": "durable",
  2974. "domain": "bit"
  2975. }, {
  2976. "name": "autoDelete",
  2977. "domain": "bit"
  2978. }, {
  2979. "name": "reserved2",
  2980. "domain": "bit"
  2981. }, {
  2982. "name": "reserved3",
  2983. "domain": "bit"
  2984. }, {
  2985. "name": "noWait",
  2986. "domain": "bit"
  2987. }, {
  2988. "name": "arguments",
  2989. "domain": "table"
  2990. }]
  2991. }, {
  2992. "name": "declareOk",
  2993. "index": 11,
  2994. "fields": []
  2995. }, {
  2996. "name": "delete",
  2997. "index": 20,
  2998. "fields": [{
  2999. "name": "reserved1",
  3000. "domain": "short"
  3001. }, {
  3002. "name": "exchange",
  3003. "domain": "shortstr"
  3004. }, {
  3005. "name": "ifUnused",
  3006. "domain": "bit"
  3007. }, {
  3008. "name": "noWait",
  3009. "domain": "bit"
  3010. }]
  3011. }, {
  3012. "name": "deleteOk",
  3013. "index": 21,
  3014. "fields": []
  3015. }, {
  3016. "name": "bind",
  3017. "index": 30,
  3018. "fields": [{
  3019. "name": "reserved1",
  3020. "domain": "short"
  3021. }, {
  3022. "name": "destination",
  3023. "domain": "shortstr"
  3024. }, {
  3025. "name": "source",
  3026. "domain": "shortstr"
  3027. }, {
  3028. "name": "routingKey",
  3029. "domain": "shortstr"
  3030. }, {
  3031. "name": "noWait",
  3032. "domain": "bit"
  3033. }, {
  3034. "name": "arguments",
  3035. "domain": "table"
  3036. }]
  3037. }, {
  3038. "name": "bindOk",
  3039. "index": 31,
  3040. "fields": []
  3041. }, {
  3042. "name": "unbind",
  3043. "index": 40,
  3044. "fields": [{
  3045. "name": "reserved1",
  3046. "domain": "short"
  3047. }, {
  3048. "name": "destination",
  3049. "domain": "shortstr"
  3050. }, {
  3051. "name": "source",
  3052. "domain": "shortstr"
  3053. }, {
  3054. "name": "routingKey",
  3055. "domain": "shortstr"
  3056. }, {
  3057. "name": "noWait",
  3058. "domain": "bit"
  3059. }, {
  3060. "name": "arguments",
  3061. "domain": "table"
  3062. }]
  3063. }, {
  3064. "name": "unbindOk",
  3065. "index": 51,
  3066. "fields": []
  3067. }]
  3068. }, {
  3069. "name": "queue",
  3070. "index": 50,
  3071. "fields": [],
  3072. "methods": [{
  3073. "name": "declare",
  3074. "index": 10,
  3075. "fields": [{
  3076. "name": "reserved1",
  3077. "domain": "short"
  3078. }, {
  3079. "name": "queue",
  3080. "domain": "shortstr"
  3081. }, {
  3082. "name": "passive",
  3083. "domain": "bit"
  3084. }, {
  3085. "name": "durable",
  3086. "domain": "bit"
  3087. }, {
  3088. "name": "exclusive",
  3089. "domain": "bit"
  3090. }, {
  3091. "name": "autoDelete",
  3092. "domain": "bit"
  3093. }, {
  3094. "name": "noWait",
  3095. "domain": "bit"
  3096. }, {
  3097. "name": "arguments",
  3098. "domain": "table"
  3099. }]
  3100. }, {
  3101. "name": "declareOk",
  3102. "index": 11,
  3103. "fields": [{
  3104. "name": "queue",
  3105. "domain": "shortstr"
  3106. }, {
  3107. "name": "messageCount",
  3108. "domain": "long"
  3109. }, {
  3110. "name": "consumerCount",
  3111. "domain": "long"
  3112. }]
  3113. }, {
  3114. "name": "bind",
  3115. "index": 20,
  3116. "fields": [{
  3117. "name": "reserved1",
  3118. "domain": "short"
  3119. }, {
  3120. "name": "queue",
  3121. "domain": "shortstr"
  3122. }, {
  3123. "name": "exchange",
  3124. "domain": "shortstr"
  3125. }, {
  3126. "name": "routingKey",
  3127. "domain": "shortstr"
  3128. }, {
  3129. "name": "noWait",
  3130. "domain": "bit"
  3131. }, {
  3132. "name": "arguments",
  3133. "domain": "table"
  3134. }]
  3135. }, {
  3136. "name": "bindOk",
  3137. "index": 21,
  3138. "fields": []
  3139. }, {
  3140. "name": "unbind",
  3141. "index": 50,
  3142. "fields": [{
  3143. "name": "reserved1",
  3144. "domain": "short"
  3145. }, {
  3146. "name": "queue",
  3147. "domain": "shortstr"
  3148. }, {
  3149. "name": "exchange",
  3150. "domain": "shortstr"
  3151. }, {
  3152. "name": "routingKey",
  3153. "domain": "shortstr"
  3154. }, {
  3155. "name": "arguments",
  3156. "domain": "table"
  3157. }]
  3158. }, {
  3159. "name": "unbindOk",
  3160. "index": 51,
  3161. "fields": []
  3162. }, {
  3163. "name": "purge",
  3164. "index": 30,
  3165. "fields": [{
  3166. "name": "reserved1",
  3167. "domain": "short"
  3168. }, {
  3169. "name": "queue",
  3170. "domain": "shortstr"
  3171. }, {
  3172. "name": "noWait",
  3173. "domain": "bit"
  3174. }]
  3175. }, {
  3176. "name": "purgeOk",
  3177. "index": 31,
  3178. "fields": [{
  3179. "name": "messageCount",
  3180. "domain": "long"
  3181. }]
  3182. }, {
  3183. "name": "delete",
  3184. "index": 40,
  3185. "fields": [{
  3186. "name": "reserved1",
  3187. "domain": "short"
  3188. }, {
  3189. "name": "queue",
  3190. "domain": "shortstr"
  3191. }, {
  3192. "name": "ifUnused",
  3193. "domain": "bit"
  3194. }, {
  3195. "name": "ifEmpty",
  3196. "domain": "bit"
  3197. }, {
  3198. "name": "noWait",
  3199. "domain": "bit"
  3200. }]
  3201. }, {
  3202. "name": "deleteOk",
  3203. "index": 41,
  3204. "fields": [{
  3205. "name": "messageCount",
  3206. "domain": "long"
  3207. }]
  3208. }]
  3209. }, {
  3210. "name": "basic",
  3211. "index": 60,
  3212. "fields": [{
  3213. "name": "contentType",
  3214. "domain": "shortstr"
  3215. }, {
  3216. "name": "contentEncoding",
  3217. "domain": "shortstr"
  3218. }, {
  3219. "name": "headers",
  3220. "domain": "table"
  3221. }, {
  3222. "name": "deliveryMode",
  3223. "domain": "octet"
  3224. }, {
  3225. "name": "priority",
  3226. "domain": "octet"
  3227. }, {
  3228. "name": "correlationId",
  3229. "domain": "shortstr"
  3230. }, {
  3231. "name": "replyTo",
  3232. "domain": "shortstr"
  3233. }, {
  3234. "name": "expiration",
  3235. "domain": "shortstr"
  3236. }, {
  3237. "name": "messageId",
  3238. "domain": "shortstr"
  3239. }, {
  3240. "name": "timestamp",
  3241. "domain": "timestamp"
  3242. }, {
  3243. "name": "type",
  3244. "domain": "shortstr"
  3245. }, {
  3246. "name": "userId",
  3247. "domain": "shortstr"
  3248. }, {
  3249. "name": "appId",
  3250. "domain": "shortstr"
  3251. }, {
  3252. "name": "reserved",
  3253. "domain": "shortstr"
  3254. }],
  3255. "methods": [{
  3256. "name": "qos",
  3257. "index": 10,
  3258. "fields": [{
  3259. "name": "prefetchSize",
  3260. "domain": "long"
  3261. }, {
  3262. "name": "prefetchCount",
  3263. "domain": "short"
  3264. }, {
  3265. "name": "global",
  3266. "domain": "bit"
  3267. }]
  3268. }, {
  3269. "name": "qosOk",
  3270. "index": 11,
  3271. "fields": []
  3272. }, {
  3273. "name": "consume",
  3274. "index": 20,
  3275. "fields": [{
  3276. "name": "reserved1",
  3277. "domain": "short"
  3278. }, {
  3279. "name": "queue",
  3280. "domain": "shortstr"
  3281. }, {
  3282. "name": "consumerTag",
  3283. "domain": "shortstr"
  3284. }, {
  3285. "name": "noLocal",
  3286. "domain": "bit"
  3287. }, {
  3288. "name": "noAck",
  3289. "domain": "bit"
  3290. }, {
  3291. "name": "exclusive",
  3292. "domain": "bit"
  3293. }, {
  3294. "name": "noWait",
  3295. "domain": "bit"
  3296. }, {
  3297. "name": "arguments",
  3298. "domain": "table"
  3299. }]
  3300. }, {
  3301. "name": "consumeOk",
  3302. "index": 21,
  3303. "fields": [{
  3304. "name": "consumerTag",
  3305. "domain": "shortstr"
  3306. }]
  3307. }, {
  3308. "name": "cancel",
  3309. "index": 30,
  3310. "fields": [{
  3311. "name": "consumerTag",
  3312. "domain": "shortstr"
  3313. }, {
  3314. "name": "noWait",
  3315. "domain": "bit"
  3316. }]
  3317. }, {
  3318. "name": "cancelOk",
  3319. "index": 31,
  3320. "fields": [{
  3321. "name": "consumerTag",
  3322. "domain": "shortstr"
  3323. }]
  3324. }, {
  3325. "name": "publish",
  3326. "index": 40,
  3327. "fields": [{
  3328. "name": "reserved1",
  3329. "domain": "short"
  3330. }, {
  3331. "name": "exchange",
  3332. "domain": "shortstr"
  3333. }, {
  3334. "name": "routingKey",
  3335. "domain": "shortstr"
  3336. }, {
  3337. "name": "mandatory",
  3338. "domain": "bit"
  3339. }, {
  3340. "name": "immediate",
  3341. "domain": "bit"
  3342. }]
  3343. }, {
  3344. "name": "return",
  3345. "index": 50,
  3346. "fields": [{
  3347. "name": "replyCode",
  3348. "domain": "short"
  3349. }, {
  3350. "name": "replyText",
  3351. "domain": "shortstr"
  3352. }, {
  3353. "name": "exchange",
  3354. "domain": "shortstr"
  3355. }, {
  3356. "name": "routingKey",
  3357. "domain": "shortstr"
  3358. }]
  3359. }, {
  3360. "name": "deliver",
  3361. "index": 60,
  3362. "fields": [{
  3363. "name": "consumerTag",
  3364. "domain": "shortstr"
  3365. }, {
  3366. "name": "deliveryTag",
  3367. "domain": "longlong"
  3368. }, {
  3369. "name": "redelivered",
  3370. "domain": "bit"
  3371. }, {
  3372. "name": "exchange",
  3373. "domain": "shortstr"
  3374. }, {
  3375. "name": "routingKey",
  3376. "domain": "shortstr"
  3377. }]
  3378. }, {
  3379. "name": "get",
  3380. "index": 70,
  3381. "fields": [{
  3382. "name": "reserved1",
  3383. "domain": "short"
  3384. }, {
  3385. "name": "queue",
  3386. "domain": "shortstr"
  3387. }, {
  3388. "name": "noAck",
  3389. "domain": "bit"
  3390. }]
  3391. }, {
  3392. "name": "getOk",
  3393. "index": 71,
  3394. "fields": [{
  3395. "name": "deliveryTag",
  3396. "domain": "longlong"
  3397. }, {
  3398. "name": "redelivered",
  3399. "domain": "bit"
  3400. }, {
  3401. "name": "exchange",
  3402. "domain": "shortstr"
  3403. }, {
  3404. "name": "routingKey",
  3405. "domain": "shortstr"
  3406. }, {
  3407. "name": "messageCount",
  3408. "domain": "long"
  3409. }]
  3410. }, {
  3411. "name": "getEmpty",
  3412. "index": 72,
  3413. "fields": [{
  3414. "name": "reserved1",
  3415. "domain": "shortstr"
  3416. }]
  3417. }, {
  3418. "name": "ack",
  3419. "index": 80,
  3420. "fields": [{
  3421. "name": "deliveryTag",
  3422. "domain": "longlong"
  3423. }, {
  3424. "name": "multiple",
  3425. "domain": "bit"
  3426. }]
  3427. }, {
  3428. "name": "reject",
  3429. "index": 90,
  3430. "fields": [{
  3431. "name": "deliveryTag",
  3432. "domain": "longlong"
  3433. }, {
  3434. "name": "requeue",
  3435. "domain": "bit"
  3436. }]
  3437. }, {
  3438. "name": "recoverAsync",
  3439. "index": 100,
  3440. "fields": [{
  3441. "name": "requeue",
  3442. "domain": "bit"
  3443. }]
  3444. }, {
  3445. "name": "recover",
  3446. "index": 110,
  3447. "fields": [{
  3448. "name": "requeue",
  3449. "domain": "bit"
  3450. }]
  3451. }, {
  3452. "name": "recoverOk",
  3453. "index": 111,
  3454. "fields": []
  3455. }]
  3456. }, {
  3457. "name": "tx",
  3458. "index": 90,
  3459. "fields": [],
  3460. "methods": [{
  3461. "name": "select",
  3462. "index": 10,
  3463. "fields": []
  3464. }, {
  3465. "name": "selectOk",
  3466. "index": 11,
  3467. "fields": []
  3468. }, {
  3469. "name": "commit",
  3470. "index": 20,
  3471. "fields": []
  3472. }, {
  3473. "name": "commitOk",
  3474. "index": 21,
  3475. "fields": []
  3476. }, {
  3477. "name": "rollback",
  3478. "index": 30,
  3479. "fields": []
  3480. }, {
  3481. "name": "rollbackOk",
  3482. "index": 31,
  3483. "fields": []
  3484. }]
  3485. }, {
  3486. "name": "confirm",
  3487. "index": 85,
  3488. "fields": [],
  3489. "methods": [{
  3490. "name": "select",
  3491. "index": 10,
  3492. "fields": [{
  3493. "name": "noWait",
  3494. "domain": "bit"
  3495. }]
  3496. }, {
  3497. "name": "selectOk",
  3498. "index": 11,
  3499. "fields": []
  3500. }]
  3501. }];
  3502. },{}],27:[function(_dereq_,module,exports){
  3503. 'use strict';
  3504. var events = _dereq_('events');
  3505. var util = _dereq_('util');
  3506. var fs = _dereq_('fs');
  3507. var Promise = _dereq_('./promise').Promise;
  3508. var definitions = _dereq_('./definitions');
  3509. var methods = definitions.methods;
  3510. // This class is not exposed to the user. Queue and Exchange are subclasses
  3511. // of Channel. This just provides a task queue.
  3512. var Channel = module.exports = function Channel (connection, channel) {
  3513. events.EventEmitter.call(this);
  3514. // Unlimited listeners. Helps when e.g. publishing high-volume messages,
  3515. // 10 is far too low.
  3516. this.setMaxListeners(0);
  3517. this.channel = channel;
  3518. this.connection = connection;
  3519. this._tasks = [];
  3520. this.reconnect();
  3521. };
  3522. util.inherits(Channel, events.EventEmitter);
  3523. Channel.prototype.closeOK = function() {
  3524. this.connection._sendMethod(this.channel, methods.channelCloseOk, {reserved1: ""});
  3525. };
  3526. Channel.prototype.reconnect = function () {
  3527. this.connection._sendMethod(this.channel, methods.channelOpen, {reserved1: ""});
  3528. };
  3529. Channel.prototype._taskPush = function (reply, cb) {
  3530. var promise = new Promise();
  3531. this._tasks.push({
  3532. promise: promise,
  3533. reply: reply,
  3534. sent: false,
  3535. cb: cb
  3536. });
  3537. this._tasksFlush();
  3538. return promise;
  3539. };
  3540. Channel.prototype._tasksFlush = function () {
  3541. if (this.state != 'open') return;
  3542. for (var i = 0; i < this._tasks.length; i++) {
  3543. var task = this._tasks[i];
  3544. if (task.sent) continue;
  3545. task.cb();
  3546. task.sent = true;
  3547. if (!task.reply) {
  3548. // if we don't expect a reply, just delete it now
  3549. this._tasks.splice(i, 1);
  3550. i = i-1;
  3551. }
  3552. }
  3553. };
  3554. Channel.prototype._handleTaskReply = function (channel, method, args) {
  3555. var task, i;
  3556. for (i = 0; i < this._tasks.length; i++) {
  3557. if (this._tasks[i].reply == method) {
  3558. task = this._tasks[i];
  3559. this._tasks.splice(i, 1);
  3560. task.promise.emitSuccess(args);
  3561. this._tasksFlush();
  3562. return true;
  3563. }
  3564. }
  3565. return false;
  3566. };
  3567. Channel.prototype._onChannelMethod = function(channel, method, args) {
  3568. switch (method) {
  3569. case methods.channelCloseOk:
  3570. delete this.connection.channels[this.channel];
  3571. this.state = 'closed';
  3572. // TODO should this be falling through?
  3573. default:
  3574. this._onMethod(channel, method, args);
  3575. }
  3576. };
  3577. Channel.prototype.close = function(reason) {
  3578. this.state = 'closing';
  3579. this.connection._sendMethod(this.channel, methods.channelClose,
  3580. {'replyText': reason ? reason : 'Goodbye from node',
  3581. 'replyCode': 200,
  3582. 'classId': 0,
  3583. 'methodId': 0});
  3584. };
  3585. },{"./definitions":31,"./promise":35,"events":137,"fs":127,"util":159}],28:[function(_dereq_,module,exports){
  3586. (function (process,Buffer){
  3587. 'use strict';
  3588. var net = _dereq_('net');
  3589. var tls = _dereq_('tls');
  3590. var fs = _dereq_('fs');
  3591. var URL = _dereq_('url');
  3592. var _ = _dereq_('lodash');
  3593. var debug = _dereq_('./debug');
  3594. var EventEmitter = _dereq_('events').EventEmitter;
  3595. var util = _dereq_('util');
  3596. var serializer = _dereq_('./serializer');
  3597. var definitions = _dereq_('./definitions');
  3598. var methods = definitions.methods;
  3599. var methodTable = definitions.methodTable;
  3600. var classes = definitions.classes;
  3601. var Exchange = _dereq_('./exchange');
  3602. var Queue = _dereq_('./queue');
  3603. var AMQPParser = _dereq_('./parser');
  3604. var nodeAMQPVersion = _dereq_('../package').version;
  3605. var maxFrameBuffer = 131072; // 128k, same as rabbitmq (which was
  3606. // copying qpid)
  3607. var defaultPorts = { 'amqp': 5672, 'amqps': 5671 };
  3608. var defaultOptions = {
  3609. host: 'localhost',
  3610. port: defaultPorts['amqp'],
  3611. login: 'guest',
  3612. password: 'guest',
  3613. authMechanism: 'AMQPLAIN',
  3614. vhost: '/',
  3615. connectionTimeout: 10000,
  3616. ssl: {
  3617. enabled: false
  3618. }
  3619. };
  3620. var defaultSslOptions = {
  3621. port: defaultPorts['amqps'],
  3622. ssl: {
  3623. rejectUnauthorized: true
  3624. }
  3625. };
  3626. var defaultImplOptions = {
  3627. defaultExchangeName: '',
  3628. reconnect: true,
  3629. reconnectBackoffStrategy: 'linear',
  3630. reconnectExponentialLimit: 120000,
  3631. reconnectBackoffTime: 1000
  3632. };
  3633. var defaultClientProperties = {
  3634. version: nodeAMQPVersion,
  3635. platform: 'node-' + process.version,
  3636. product: 'node-amqp'
  3637. };
  3638. var Connection = module.exports = function Connection (connectionArgs, options, readyCallback) {
  3639. EventEmitter.call(this);
  3640. this.setOptions(connectionArgs);
  3641. this.setImplOptions(options);
  3642. if (typeof readyCallback === 'function') {
  3643. this._readyCallback = readyCallback;
  3644. }
  3645. this.connectionAttemptScheduled = false;
  3646. this._defaultExchange = null;
  3647. this.channelCounter = 0;
  3648. this._sendBuffer = new Buffer(maxFrameBuffer);
  3649. };
  3650. util.inherits(Connection, EventEmitter);
  3651. Connection.prototype.setOptions = function (options) {
  3652. var urlo = (options && options.url) ? this._parseURLOptions(options.url) : {};
  3653. var sslo = (options && options.ssl && options.ssl.enabled) ? defaultSslOptions : {};
  3654. this.options = _.extend({}, defaultOptions, sslo, urlo, options || {});
  3655. this.options.clientProperties = _.extend({}, defaultClientProperties, (options && options.clientProperties) || {});
  3656. };
  3657. Connection.prototype.setImplOptions = function (options) {
  3658. this.implOptions = _.extend({}, defaultImplOptions, options || {});
  3659. };
  3660. Connection.prototype.connect = function () {
  3661. // If this is our first connection, add listeners.
  3662. if (!this.socket) this.addAllListeners();
  3663. this._createSocket();
  3664. this._startHandshake();
  3665. };
  3666. Connection.prototype.reconnect = function () {
  3667. // Suspend activity on channels
  3668. for (var channel in this.channels) {
  3669. this.channels[channel].state = 'closed';
  3670. }
  3671. debug && debug("Connection lost, reconnecting...");
  3672. // Terminate socket activity
  3673. if (this.socket) this.socket.end();
  3674. this.connect();
  3675. };
  3676. Connection.prototype.disconnect = function () {
  3677. debug && debug("Sending disconnect request to server");
  3678. this._sendMethod(0, methods.connectionClose, {
  3679. 'replyText': 'client disconnect',
  3680. 'replyCode': 200,
  3681. 'classId': 0,
  3682. 'methodId': 0
  3683. });
  3684. };
  3685. Connection.prototype.addAllListeners = function() {
  3686. var self = this;
  3687. var connectEvent = this.options.ssl.enabled ? 'secureConnect' : 'connect';
  3688. self.addListener(connectEvent, function() {
  3689. // In the case where this is a reconnection, do not trample on the existing
  3690. // channels.
  3691. // For your reference, channel 0 is the control channel.
  3692. self.channels = self.channels || {0:self};
  3693. self.queues = self.queues || {};
  3694. self.exchanges = self.exchanges || {};
  3695. self.parser = new AMQPParser('0-9-1', 'client');
  3696. self.parser.onMethod = function (channel, method, args) {
  3697. self._onMethod(channel, method, args);
  3698. };
  3699. self.parser.onContent = function (channel, data) {
  3700. debug && debug(channel + " > content " + data.length);
  3701. if (self.channels[channel] && self.channels[channel]._onContent) {
  3702. self.channels[channel]._onContent(channel, data);
  3703. } else {
  3704. debug && debug("unhandled content: " + data);
  3705. }
  3706. };
  3707. self.parser.onContentHeader = function (channel, classInfo, weight, properties, size) {
  3708. debug && debug(channel + " > content header " + JSON.stringify([classInfo.name, weight, properties, size]));
  3709. if (self.channels[channel] && self.channels[channel]._onContentHeader) {
  3710. self.channels[channel]._onContentHeader(channel, classInfo, weight, properties, size);
  3711. } else {
  3712. debug && debug("unhandled content header");
  3713. }
  3714. };
  3715. self.parser.onHeartBeat = function () {
  3716. self.emit("heartbeat");
  3717. debug && debug("heartbeat");
  3718. };
  3719. self.parser.onError = function (e) {
  3720. self.emit("error", e);
  3721. self.emit("close");
  3722. };
  3723. // Remove readyEmitted flag so we can detect an auth error.
  3724. self.readyEmitted = false;
  3725. });
  3726. self.addListener('data', function (data) {
  3727. if(self.parser != null){
  3728. try {
  3729. self.parser.execute(data);
  3730. } catch (exception) {
  3731. self.emit('error', exception);
  3732. return;
  3733. }
  3734. }
  3735. self._inboundHeartbeatTimerReset();
  3736. });
  3737. var backoffTime = null;
  3738. self.addListener('error', function backoff(e) {
  3739. if (self._inboundHeartbeatTimer !== null) {
  3740. clearTimeout(self._inboundHeartbeatTimer);
  3741. self._inboundHeartbeatTimer = null;
  3742. }
  3743. if (self._outboundHeartbeatTimer !== null) {
  3744. clearTimeout(self._outboundHeartbeatTimer);
  3745. self._outboundHeartbeatTimer = null;
  3746. }
  3747. if (!self.connectionAttemptScheduled) {
  3748. // Set to true, as we are presently in the process of scheduling one.
  3749. self.connectionAttemptScheduled = true;
  3750. // Kill the socket, if it hasn't been killed already.
  3751. self.socket.end();
  3752. // Reset parser state
  3753. self.parser = null;
  3754. // In order for our reconnection to be seamless, we have to notify the
  3755. // channels that they are no longer connected so that nobody attempts
  3756. // to send messages which would be doomed to fail.
  3757. for (var channel in self.channels) {
  3758. if (channel !== 0) {
  3759. self.channels[channel].state = 'closed';
  3760. }
  3761. }
  3762. // Queues are channels (so we have already marked them as closed), but
  3763. // queues have special needs, since the subscriptions will no longer
  3764. // be known to the server when we reconnect. Mark the subscriptions as
  3765. // closed so that we can resubscribe them once we are reconnected.
  3766. for (var queue in self.queues) {
  3767. for (var index in self.queues[queue].consumerTagOptions) {
  3768. self.queues[queue].consumerTagOptions[index]['state'] = 'closed';
  3769. }
  3770. }
  3771. // Begin reconnection attempts
  3772. if (self.implOptions.reconnect) {
  3773. // Don't thrash, use a backoff strategy.
  3774. if (backoffTime === null) {
  3775. // This is the first time we've failed since a successful connection,
  3776. // so use the configured backoff time without any modification.
  3777. backoffTime = self.implOptions.reconnectBackoffTime;
  3778. } else if (self.implOptions.reconnectBackoffStrategy === 'exponential') {
  3779. // If you've configured exponential backoff, we'll double the
  3780. // backoff time each subsequent attempt until success.
  3781. backoffTime *= 2;
  3782. // limit the maxium timeout, to avoid potentially unlimited stalls
  3783. if(backoffTime > self.implOptions.reconnectExponentialLimit){
  3784. backoffTime = self.implOptions.reconnectExponentialLimit;
  3785. }
  3786. } else if (self.implOptions.reconnectBackoffStrategy === 'linear') {
  3787. // Linear strategy is the default. In this case, we will retry at a
  3788. // constant interval, so there's no need to change the backoff time
  3789. // between attempts.
  3790. } else {
  3791. // TODO should we warn people if they picked a nonexistent strategy?
  3792. }
  3793. setTimeout(function () {
  3794. // Set to false, so that if we fail in the reconnect attempt, we can
  3795. // schedule another one.
  3796. self.connectionAttemptScheduled = false;
  3797. self.reconnect();
  3798. }, backoffTime);
  3799. } else {
  3800. self.removeListener('error', backoff);
  3801. }
  3802. }
  3803. });
  3804. self.addListener('ready', function () {
  3805. // Reset the backoff time since we have successfully connected.
  3806. backoffTime = null;
  3807. if (self.implOptions.reconnect) {
  3808. // Reconnect any channels which were open.
  3809. _.each(self.channels, function(channel, index) {
  3810. // FIXME why is the index "0" instead of 0?
  3811. if (index !== "0") channel.reconnect();
  3812. });
  3813. }
  3814. // Set 'ready' flag for auth failure detection.
  3815. this.readyEmitted = true;
  3816. // Restart the heartbeat to the server
  3817. self._outboundHeartbeatTimerReset();
  3818. });
  3819. // Apparently, it is not possible to determine if an authentication error
  3820. // has occurred, but when the connection closes then we can HINT that a
  3821. // possible authentication error has occured. Although this may be a bug
  3822. // in the spec, handling it as a possible error is considerably better than
  3823. // failing silently.
  3824. self.addListener('end', function (){
  3825. if (!this.readyEmitted){
  3826. this.emit('error', new Error(
  3827. 'Connection ended: possibly due to an authentication failure.'
  3828. ));
  3829. }
  3830. });
  3831. };
  3832. Connection.prototype.heartbeat = function () {
  3833. if(this.socket.writable) this.write(new Buffer([8,0,0,0,0,0,0,206]));
  3834. };
  3835. // connection.exchange('my-exchange', { type: 'topic' });
  3836. // Options
  3837. // - type 'fanout', 'direct', or 'topic' (default)
  3838. // - passive (boolean)
  3839. // - durable (boolean)
  3840. // - autoDelete (boolean, default true)
  3841. Connection.prototype.exchange = function (name, options, openCallback) {
  3842. if (name === undefined) name = this.implOptions.defaultExchangeName;
  3843. if (!options) options = {};
  3844. if (name !== '' && options.type === undefined) options.type = 'topic';
  3845. try{
  3846. var channel = this.generateChannelId();
  3847. }catch(exception){
  3848. this.emit("error", exception);
  3849. return;
  3850. }
  3851. var exchange = new Exchange(this, channel, name, options, openCallback);
  3852. this.channels[channel] = exchange;
  3853. this.exchanges[name] = exchange;
  3854. return exchange;
  3855. };
  3856. // remove an exchange when it's closed (called from Exchange)
  3857. Connection.prototype.exchangeClosed = function (name) {
  3858. if (this.exchanges[name]) delete this.exchanges[name];
  3859. };
  3860. // Options
  3861. // - passive (boolean)
  3862. // - durable (boolean)
  3863. // - exclusive (boolean)
  3864. // - autoDelete (boolean, default true)
  3865. Connection.prototype.queue = function (name /* options, openCallback */) {
  3866. var options, callback;
  3867. if (typeof arguments[1] == 'object') {
  3868. options = arguments[1];
  3869. callback = arguments[2];
  3870. } else {
  3871. callback = arguments[1];
  3872. }
  3873. try{
  3874. var channel = this.generateChannelId();
  3875. }catch(exception){
  3876. this.emit("error", exception);
  3877. return;
  3878. }
  3879. var q = new Queue(this, channel, name, options, callback);
  3880. this.channels[channel] = q;
  3881. return q;
  3882. };
  3883. // remove a queue when it's closed (called from Queue)
  3884. Connection.prototype.queueClosed = function (name) {
  3885. if (this.queues[name]) delete this.queues[name];
  3886. };
  3887. // Publishes a message to the default exchange.
  3888. Connection.prototype.publish = function (routingKey, body, options, callback) {
  3889. if (!this._defaultExchange) this._defaultExchange = this.exchange();
  3890. return this._defaultExchange.publish(routingKey, body, options, callback);
  3891. };
  3892. Connection.prototype._bodyToBuffer = function (body) {
  3893. // Handles 3 cases
  3894. // - body is utf8 string
  3895. // - body is instance of Buffer
  3896. // - body is an object and its JSON representation is sent
  3897. // Does not handle the case for streaming bodies.
  3898. // Returns buffer.
  3899. if (typeof(body) == 'string') {
  3900. return [null, new Buffer(body, 'utf8')];
  3901. } else if (body instanceof Buffer) {
  3902. return [null, body];
  3903. } else {
  3904. var jsonBody = JSON.stringify(body);
  3905. debug && debug('sending json: ' + jsonBody);
  3906. var props = {contentType: 'application/json'};
  3907. return [props, new Buffer(jsonBody, 'utf8')];
  3908. }
  3909. };
  3910. Connection.prototype._inboundHeartbeatTimerReset = function () {
  3911. if (this._inboundHeartbeatTimer !== null) {
  3912. clearTimeout(this._inboundHeartbeatTimer);
  3913. this._inboundHeartbeatTimer = null;
  3914. }
  3915. if (this.options.heartbeat) {
  3916. var self = this;
  3917. var gracePeriod = 2 * this.options.heartbeat;
  3918. this._inboundHeartbeatTimer = setTimeout(function () {
  3919. if(self.socket.readable)
  3920. self.emit('error', new Error('no heartbeat or data in last ' + gracePeriod + ' seconds'));
  3921. }, gracePeriod * 1000);
  3922. }
  3923. };
  3924. Connection.prototype._outboundHeartbeatTimerReset = function () {
  3925. if (this._outboundHeartbeatTimer !== null) {
  3926. clearTimeout(this._outboundHeartbeatTimer);
  3927. this._outboundHeartbeatTimer = null;
  3928. }
  3929. if (this.socket.writable && this.options.heartbeat) {
  3930. var self = this;
  3931. this._outboundHeartbeatTimer = setTimeout(function () {
  3932. self.heartbeat();
  3933. self._outboundHeartbeatTimerReset();
  3934. }, 1000 * this.options.heartbeat);
  3935. }
  3936. };
  3937. Connection.prototype._onMethod = function (channel, method, args) {
  3938. debug && debug(channel + " > " + method.name + " " + JSON.stringify(args));
  3939. // Channel 0 is the control channel. If not zero then delegate to
  3940. // one of the channel objects.
  3941. if (channel > 0) {
  3942. if (!this.channels[channel]) {
  3943. debug && debug("Received message on untracked channel.");
  3944. return;
  3945. }
  3946. if (!this.channels[channel]._onChannelMethod) {
  3947. throw new Error('Channel ' + channel + ' has no _onChannelMethod method.');
  3948. }
  3949. this.channels[channel]._onChannelMethod(channel, method, args);
  3950. return;
  3951. }
  3952. // channel 0
  3953. switch (method) {
  3954. // 2. The server responds, after the version string, with the
  3955. // 'connectionStart' method (contains various useless information)
  3956. case methods.connectionStart:
  3957. // We check that they're serving us AMQP 0-9
  3958. if (args.versionMajor !== 0 && args.versionMinor != 9) {
  3959. this.socket.end();
  3960. this.emit('error', new Error("Bad server version"));
  3961. return;
  3962. }
  3963. this.serverProperties = args.serverProperties;
  3964. // 3. Then we reply with StartOk, containing our useless information.
  3965. this._sendMethod(0, methods.connectionStartOk, {
  3966. clientProperties: this.options.clientProperties,
  3967. mechanism: this.options.authMechanism,
  3968. response: {
  3969. LOGIN: this.options.login,
  3970. PASSWORD: this.options.password
  3971. },
  3972. locale: 'en_US'
  3973. });
  3974. break;
  3975. // 4. The server responds with a connectionTune request
  3976. case methods.connectionTune:
  3977. if (args.frameMax) {
  3978. debug && debug("tweaking maxFrameBuffer to " + args.frameMax);
  3979. maxFrameBuffer = args.frameMax;
  3980. }
  3981. // 5. We respond with connectionTuneOk
  3982. this._sendMethod(0, methods.connectionTuneOk, {
  3983. channelMax: 0,
  3984. frameMax: maxFrameBuffer,
  3985. heartbeat: this.options.heartbeat || 0
  3986. });
  3987. // 6. Then we have to send a connectionOpen request
  3988. this._sendMethod(0, methods.connectionOpen, {
  3989. virtualHost: this.options.vhost
  3990. // , capabilities: ''
  3991. // , insist: true
  3992. ,
  3993. reserved1: '',
  3994. reserved2: true
  3995. });
  3996. break;
  3997. case methods.connectionOpenOk:
  3998. // 7. Finally they respond with connectionOpenOk
  3999. // Whew! That's why they call it the Advanced MQP.
  4000. if (this._readyCallback) {
  4001. this._readyCallback(this);
  4002. this._readyCallback = null;
  4003. }
  4004. this.emit('ready');
  4005. break;
  4006. case methods.connectionClose:
  4007. var e = new Error(args.replyText);
  4008. e.code = args.replyCode;
  4009. if (!this.listeners('close').length) {
  4010. console.log('Unhandled connection error: ' + args.replyText);
  4011. }
  4012. this.socket.destroy(e);
  4013. break;
  4014. case methods.connectionCloseOk:
  4015. debug && debug("Received close-ok from server, closing socket");
  4016. this.socket.end();
  4017. break;
  4018. default:
  4019. throw new Error("Uncaught method '" + method.name + "' with args " +
  4020. JSON.stringify(args));
  4021. }
  4022. };
  4023. // Generate connection options from URI string formatted with amqp scheme.
  4024. Connection.prototype._parseURLOptions = function(connectionString) {
  4025. var opts = {};
  4026. opts.ssl = {};
  4027. var url = URL.parse(connectionString);
  4028. var scheme = url.protocol.substring(0, url.protocol.lastIndexOf(':'));
  4029. if (scheme != 'amqp' && scheme != 'amqps') {
  4030. throw new Error('Connection URI must use amqp or amqps scheme. ' +
  4031. 'For example, "amqp://bus.megacorp.internal:5766".');
  4032. }
  4033. opts.ssl.enabled = ('amqps' === scheme);
  4034. opts.host = url.hostname;
  4035. opts.port = url.port || defaultPorts[scheme];
  4036. if (url.auth) {
  4037. var auth = url.auth.split(':');
  4038. auth[0] && (opts.login = auth[0]);
  4039. auth[1] && (opts.password = auth[1]);
  4040. }
  4041. if (url.pathname) {
  4042. opts.vhost = unescape(url.pathname.substr(1));
  4043. }
  4044. return opts;
  4045. };
  4046. /*
  4047. *
  4048. * Connect helpers
  4049. *
  4050. */
  4051. // If you pass a array of hosts, lets choose a random host or the preferred host number, or then next one.
  4052. Connection.prototype._chooseHost = function() {
  4053. if(Array.isArray(this.options.host)){
  4054. if(this.hosti == null){
  4055. if(typeof this.options.hostPreference == 'number') {
  4056. this.hosti = (this.options.hostPreference < this.options.host.length) ?
  4057. this.options.hostPreference : this.options.host.length-1;
  4058. } else {
  4059. this.hosti = parseInt(Math.random() * this.options.host.length, 10);
  4060. }
  4061. } else {
  4062. // If this is already set, it looks like we want to choose another one.
  4063. // Add one to hosti but don't overflow it.
  4064. this.hosti = (this.hosti + 1) % this.options.host.length;
  4065. }
  4066. return this.options.host[this.hosti];
  4067. } else {
  4068. return this.options.host;
  4069. }
  4070. };
  4071. Connection.prototype._createSocket = function() {
  4072. var hostName = this._chooseHost(), self = this;
  4073. var options = {
  4074. port: this.options.port,
  4075. host: hostName
  4076. };
  4077. var resetConnectionTimeout = function () {
  4078. debug && debug('connected so resetting connection timeout');
  4079. this.setTimeout(0);
  4080. };
  4081. // Connect socket
  4082. if (this.options.ssl.enabled) {
  4083. debug && debug('making ssl connection');
  4084. options = _.extend(options, this._getSSLOptions());
  4085. this.socket = tls.connect(options, resetConnectionTimeout);
  4086. } else {
  4087. debug && debug('making non-ssl connection');
  4088. this.socket = net.connect(options, resetConnectionTimeout);
  4089. }
  4090. var connTimeout = this.options.connectionTimeout;
  4091. if (connTimeout) {
  4092. debug && debug('setting connection timeout to ' + connTimeout);
  4093. this.socket.setTimeout(connTimeout, function () {
  4094. debug && debug('connection timeout');
  4095. this.destroy();
  4096. var e = new Error('connection timeout');
  4097. e.name = 'TimeoutError';
  4098. self.emit('error', e);
  4099. });
  4100. }
  4101. // Proxy events.
  4102. // Note that if we don't attach a 'data' event, no data will flow.
  4103. var events = ['close', 'connect', 'data', 'drain', 'error', 'end', 'secureConnect', 'timeout'];
  4104. _.each(events, function(event){
  4105. self.socket.on(event, self.emit.bind(self, event));
  4106. });
  4107. // Proxy a few methods that we use / previously used.
  4108. var methods = ['end', 'destroy', 'write', 'pause', 'resume', 'setEncoding', 'ref', 'unref', 'address'];
  4109. _.each(methods, function(method){
  4110. self[method] = function(){
  4111. self.socket[method].apply(self.socket, arguments);
  4112. };
  4113. });
  4114. };
  4115. Connection.prototype._getSSLOptions = function() {
  4116. if (this.sslConnectionOptions) return this.sslConnectionOptions;
  4117. this.sslConnectionOptions = {};
  4118. if (this.options.ssl.keyFile) {
  4119. this.sslConnectionOptions.key = fs.readFileSync(this.options.ssl.keyFile);
  4120. }
  4121. if (this.options.ssl.certFile) {
  4122. this.sslConnectionOptions.cert = fs.readFileSync(this.options.ssl.certFile);
  4123. }
  4124. if (this.options.ssl.caFile) {
  4125. this.sslConnectionOptions.ca = fs.readFileSync(this.options.ssl.caFile);
  4126. }
  4127. this.sslConnectionOptions.rejectUnauthorized = this.options.ssl.rejectUnauthorized;
  4128. return this.sslConnectionOptions;
  4129. };
  4130. // Time to start the AMQP 7-way connection initialization handshake!
  4131. // 1. The client sends the server a version string
  4132. Connection.prototype._startHandshake = function() {
  4133. debug && debug("Initiating handshake...");
  4134. this.write("AMQP" + String.fromCharCode(0,0,9,1));
  4135. };
  4136. /*
  4137. *
  4138. * Parse helpers
  4139. *
  4140. */
  4141. Connection.prototype._sendBody = function (channel, body, properties) {
  4142. var r = this._bodyToBuffer(body);
  4143. var props = r[0], buffer = r[1];
  4144. properties = _.extend(props || {}, properties);
  4145. this._sendHeader(channel, buffer.length, properties);
  4146. var pos = 0, len = buffer.length;
  4147. var metaSize = 8; // headerBytes = 7, frameEndBytes = 1
  4148. var maxBodySize = maxFrameBuffer - metaSize;
  4149. while (len > 0) {
  4150. var bodySize = len < maxBodySize ? len : maxBodySize;
  4151. var frameSize = bodySize + metaSize;
  4152. var b = new Buffer(frameSize);
  4153. b.used = 0;
  4154. b[b.used++] = 3; // constants.frameBody
  4155. serializer.serializeInt(b, 2, channel);
  4156. serializer.serializeInt(b, 4, bodySize);
  4157. buffer.copy(b, b.used, pos, pos+bodySize);
  4158. b.used += bodySize;
  4159. b[b.used++] = 206; // constants.frameEnd;
  4160. this.write(b);
  4161. len -= bodySize;
  4162. pos += bodySize;
  4163. }
  4164. return;
  4165. };
  4166. // connection: the connection
  4167. // channel: the channel to send this on
  4168. // size: size in bytes of the following message
  4169. // properties: an object containing any of the following:
  4170. // - contentType (default 'application/octet-stream')
  4171. // - contentEncoding
  4172. // - headers
  4173. // - deliveryMode
  4174. // - priority (0-9)
  4175. // - correlationId
  4176. // - replyTo
  4177. // - expiration
  4178. // - messageId
  4179. // - timestamp
  4180. // - userId
  4181. // - appId
  4182. // - clusterId
  4183. Connection.prototype._sendHeader = function(channel, size, properties) {
  4184. var b = new Buffer(maxFrameBuffer); // FIXME allocating too much.
  4185. // use freelist?
  4186. b.used = 0;
  4187. var classInfo = classes[60]; // always basic class.
  4188. // 7 OCTET FRAME HEADER
  4189. b[b.used++] = 2; // constants.frameHeader
  4190. serializer.serializeInt(b, 2, channel);
  4191. var lengthStart = b.used;
  4192. serializer.serializeInt(b, 4, 0 /*dummy*/); // length
  4193. var bodyStart = b.used;
  4194. // HEADER'S BODY
  4195. serializer.serializeInt(b, 2, classInfo.index); // class 60 for Basic
  4196. serializer.serializeInt(b, 2, 0); // weight, always 0 for rabbitmq
  4197. serializer.serializeInt(b, 8, size); // byte size of body
  4198. // properties - first propertyFlags
  4199. properties = _.defaults(properties || {}, {contentType: 'application/octet-stream'});
  4200. var propertyFlags = 0;
  4201. for (var i = 0; i < classInfo.fields.length; i++) {
  4202. if (properties[classInfo.fields[i].name]) propertyFlags |= 1 << (15-i);
  4203. }
  4204. serializer.serializeInt(b, 2, propertyFlags);
  4205. // now the actual properties.
  4206. serializer.serializeFields(b, classInfo.fields, properties, false);
  4207. //serializeTable(b, properties);
  4208. var bodyEnd = b.used;
  4209. // Go back to the header and write in the length now that we know it.
  4210. b.used = lengthStart;
  4211. serializer.serializeInt(b, 4, bodyEnd - bodyStart);
  4212. b.used = bodyEnd;
  4213. // 1 OCTET END
  4214. b[b.used++] = 206; // constants.frameEnd;
  4215. var s = new Buffer(b.used);
  4216. b.copy(s);
  4217. //debug && debug('header sent: ' + JSON.stringify(s));
  4218. this.write(s);
  4219. };
  4220. Connection.prototype._sendMethod = function (channel, method, args) {
  4221. debug && debug(channel + " < " + method.name + " " + JSON.stringify(args));
  4222. var b = this._sendBuffer;
  4223. b.used = 0;
  4224. b[b.used++] = 1; // constants.frameMethod
  4225. serializer.serializeInt(b, 2, channel);
  4226. var lengthIndex = b.used;
  4227. serializer.serializeInt(b, 4, 42); // replace with actual length.
  4228. var startIndex = b.used;
  4229. serializer.serializeInt(b, 2, method.classIndex); // short, classId
  4230. serializer.serializeInt(b, 2, method.methodIndex); // short, methodId
  4231. serializer.serializeFields(b, method.fields, args, true);
  4232. var endIndex = b.used;
  4233. // write in the frame length now that we know it.
  4234. b.used = lengthIndex;
  4235. serializer.serializeInt(b, 4, endIndex - startIndex);
  4236. b.used = endIndex;
  4237. b[b.used++] = 206; // constants.frameEnd;
  4238. var c = new Buffer(b.used);
  4239. b.copy(c);
  4240. debug && debug("sending frame: " + c.toJSON());
  4241. this.write(c);
  4242. this._outboundHeartbeatTimerReset();
  4243. };
  4244. // tries to find the next available id slot for a channel
  4245. Connection.prototype.generateChannelId = function () {
  4246. // start from the last used slot id
  4247. var channelId = this.channelCounter;
  4248. while(true){
  4249. // use values in range of 1..65535
  4250. channelId = channelId % 65535 + 1;
  4251. if(!this.channels[channelId]){
  4252. break;
  4253. }
  4254. // after a full loop throw an Error
  4255. if(channelId == this.channelCounter){
  4256. throw new Error("No valid Channel Id values available");
  4257. }
  4258. }
  4259. this.channelCounter = channelId;
  4260. return this.channelCounter;
  4261. };
  4262. }).call(this,_dereq_("C:\\Users\\Alex\\AppData\\Roaming\\npm\\node_modules\\browserify\\node_modules\\insert-module-globals\\node_modules\\process\\browser.js"),_dereq_("buffer").Buffer)
  4263. },{"../package":39,"./debug":30,"./definitions":31,"./exchange":32,"./parser":34,"./queue":36,"./serializer":37,"C:\\Users\\Alex\\AppData\\Roaming\\npm\\node_modules\\browserify\\node_modules\\insert-module-globals\\node_modules\\process\\browser.js":144,"buffer":128,"events":137,"fs":127,"lodash":38,"net":127,"tls":127,"url":157,"util":159}],29:[function(_dereq_,module,exports){
  4264. module.exports = {
  4265. AMQPTypes: Object.freeze({
  4266. STRING: 'S'.charCodeAt(0)
  4267. , INTEGER: 'I'.charCodeAt(0)
  4268. , HASH: 'F'.charCodeAt(0)
  4269. , TIME: 'T'.charCodeAt(0)
  4270. , DECIMAL: 'D'.charCodeAt(0)
  4271. , BOOLEAN: 't'.charCodeAt(0)
  4272. , SIGNED_8BIT: 'b'.charCodeAt(0)
  4273. , SIGNED_16BIT: 's'.charCodeAt(0)
  4274. , SIGNED_64BIT: 'l'.charCodeAt(0)
  4275. , _32BIT_FLOAT: 'f'.charCodeAt(0)
  4276. , _64BIT_FLOAT: 'd'.charCodeAt(0)
  4277. , VOID: 'v'.charCodeAt(0)
  4278. , BYTE_ARRAY: 'x'.charCodeAt(0)
  4279. , ARRAY: 'A'.charCodeAt(0)
  4280. , TEN: '10'.charCodeAt(0)
  4281. , BOOLEAN_TRUE: '\x01'
  4282. , BOOLEAN_FALSE:'\x00'
  4283. })
  4284. , Indicators: Object.freeze({
  4285. FRAME_END: 206
  4286. })
  4287. , FrameType: Object.freeze({
  4288. METHOD: 1
  4289. , HEADER: 2
  4290. , BODY: 3
  4291. , HEARTBEAT: 8
  4292. })
  4293. }
  4294. },{}],30:[function(_dereq_,module,exports){
  4295. (function (process){
  4296. 'use strict';
  4297. var DEBUG = process.env['NODE_DEBUG_AMQP'];
  4298. // only define debug function in debugging mode
  4299. if (DEBUG) {
  4300. module.exports = function debug () {
  4301. console.error.apply(null, arguments);
  4302. };
  4303. } else {
  4304. module.exports = null;
  4305. }
  4306. }).call(this,_dereq_("C:\\Users\\Alex\\AppData\\Roaming\\npm\\node_modules\\browserify\\node_modules\\insert-module-globals\\node_modules\\process\\browser.js"))
  4307. },{"C:\\Users\\Alex\\AppData\\Roaming\\npm\\node_modules\\browserify\\node_modules\\insert-module-globals\\node_modules\\process\\browser.js":144}],31:[function(_dereq_,module,exports){
  4308. 'use strict';
  4309. var protocol = _dereq_('./amqp-definitions-0-9-1');
  4310. // a look up table for methods recieved
  4311. // indexed on class id, method id
  4312. var methodTable = {};
  4313. // methods keyed on their name
  4314. var methods = {};
  4315. // classes keyed on their index
  4316. var classes = {};
  4317. (function () { // anon scope for init
  4318. //debug("initializing amqp methods...");
  4319. for (var i = 0; i < protocol.classes.length; i++) {
  4320. var classInfo = protocol.classes[i];
  4321. classes[classInfo.index] = classInfo;
  4322. for (var j = 0; j < classInfo.methods.length; j++) {
  4323. var methodInfo = classInfo.methods[j];
  4324. var name = classInfo.name +
  4325. methodInfo.name[0].toUpperCase() +
  4326. methodInfo.name.slice(1);
  4327. //debug(name);
  4328. var method = {
  4329. name: name,
  4330. fields: methodInfo.fields,
  4331. methodIndex: methodInfo.index,
  4332. classIndex: classInfo.index
  4333. };
  4334. if (!methodTable[classInfo.index]) methodTable[classInfo.index] = {};
  4335. methodTable[classInfo.index][methodInfo.index] = method;
  4336. methods[name] = method;
  4337. }
  4338. }
  4339. })();
  4340. module.exports = {methods: methods, classes: classes, methodTable: methodTable};
  4341. },{"./amqp-definitions-0-9-1":26}],32:[function(_dereq_,module,exports){
  4342. 'use strict';
  4343. var events = _dereq_('events');
  4344. var util = _dereq_('util');
  4345. var net = _dereq_('net');
  4346. var tls = _dereq_('tls');
  4347. var fs = _dereq_('fs');
  4348. var _ = _dereq_('lodash');
  4349. var methods = _dereq_('./definitions').methods;
  4350. var Channel = _dereq_('./channel');
  4351. var Exchange = module.exports = function Exchange (connection, channel, name, options, openCallback) {
  4352. Channel.call(this, connection, channel);
  4353. this.name = name;
  4354. this.binds = 0; // keep track of queues bound
  4355. this.exchangeBinds = 0; // keep track of exchanges bound
  4356. this.sourceExchanges = {};
  4357. this.options = _.defaults(options || {}, {autoDelete: true});
  4358. this._openCallback = openCallback;
  4359. this._sequence = null;
  4360. this._unAcked = {};
  4361. this._addedExchangeErrorHandler = false;
  4362. };
  4363. util.inherits(Exchange, Channel);
  4364. // creates an error handler scoped to the given `exchange`
  4365. function createExchangeErrorHandlerFor (exchange) {
  4366. return function (err) {
  4367. if (!exchange.options.confirm) return;
  4368. for (var id in exchange._unAcked) {
  4369. var task = exchange._unAcked[id];
  4370. task.emit('ack error', err);
  4371. delete exchange._unAcked[id];
  4372. }
  4373. }
  4374. };
  4375. Exchange.prototype._onMethod = function (channel, method, args) {
  4376. this.emit(method.name, args);
  4377. if (this._handleTaskReply.apply(this, arguments))
  4378. return true;
  4379. var cb;
  4380. switch (method) {
  4381. case methods.channelOpenOk:
  4382. // Pre-baked exchanges don't need to be declared
  4383. if (/^$|(amq\.)/.test(this.name)) {
  4384. this.state = 'open';
  4385. // - issue #33 fix
  4386. if (this._openCallback) {
  4387. this._openCallback(this);
  4388. this._openCallback = null;
  4389. }
  4390. // --
  4391. this.emit('open');
  4392. // For if we want to delete a exchange,
  4393. // we dont care if all of the options match.
  4394. } else if (this.options.noDeclare) {
  4395. this.state = 'open';
  4396. if (this._openCallback) {
  4397. this._openCallback(this);
  4398. this._openCallback = null;
  4399. }
  4400. this.emit('open');
  4401. } else {
  4402. this.connection._sendMethod(channel, methods.exchangeDeclare,
  4403. { reserved1: 0
  4404. , reserved2: false
  4405. , reserved3: false
  4406. , exchange: this.name
  4407. , type: this.options.type || 'topic'
  4408. , passive: !!this.options.passive
  4409. , durable: !!this.options.durable
  4410. , autoDelete: !!this.options.autoDelete
  4411. , internal: !!this.options.internal
  4412. , noWait: false
  4413. , "arguments":this.options.arguments || {}
  4414. });
  4415. this.state = 'declaring';
  4416. }
  4417. break;
  4418. case methods.exchangeDeclareOk:
  4419. if (this.options.confirm) {
  4420. this.connection._sendMethod(channel, methods.confirmSelect,
  4421. { noWait: false });
  4422. } else {
  4423. this.state = 'open';
  4424. this.emit('open');
  4425. if (this._openCallback) {
  4426. this._openCallback(this);
  4427. this._openCallback = null;
  4428. }
  4429. }
  4430. break;
  4431. case methods.confirmSelectOk:
  4432. this._sequence = 1;
  4433. this.state = 'open';
  4434. this.emit('open');
  4435. if (this._openCallback) {
  4436. this._openCallback(this);
  4437. this._openCallback = null;
  4438. }
  4439. break;
  4440. case methods.channelClose:
  4441. this.state = "closed";
  4442. this.closeOK();
  4443. this.connection.exchangeClosed(this.name);
  4444. var e = new Error(args.replyText);
  4445. e.code = args.replyCode;
  4446. this.emit('error', e);
  4447. this.emit('close');
  4448. break;
  4449. case methods.channelCloseOk:
  4450. this.connection.exchangeClosed(this.name);
  4451. this.emit('close');
  4452. break;
  4453. case methods.basicAck:
  4454. this.emit('basic-ack', args);
  4455. var sequenceNumber = args.deliveryTag.readUInt32BE(4), tag;
  4456. if (sequenceNumber === 0 && args.multiple === true) {
  4457. // we must ack everything
  4458. for (tag in this._unAcked) {
  4459. this._unAcked[tag].emit('ack');
  4460. delete this._unAcked[tag];
  4461. }
  4462. } else if (sequenceNumber !== 0 && args.multiple === true) {
  4463. // we must ack everything before the delivery tag
  4464. for (tag in this._unAcked) {
  4465. if (tag <= sequenceNumber) {
  4466. this._unAcked[tag].emit('ack');
  4467. delete this._unAcked[tag];
  4468. }
  4469. }
  4470. } else if (this._unAcked[sequenceNumber] && args.multiple === false) {
  4471. // simple single ack
  4472. this._unAcked[sequenceNumber].emit('ack');
  4473. delete this._unAcked[sequenceNumber];
  4474. }
  4475. break;
  4476. case methods.basicReturn:
  4477. this.emit('basic-return', args);
  4478. break;
  4479. case methods.exchangeBindOk:
  4480. if (this._bindCallback) {
  4481. // setting this._bindCallback to null before calling the callback allows for a subsequent bind within the callback
  4482. cb = this._bindCallback;
  4483. this._bindCallback = null;
  4484. cb(this);
  4485. }
  4486. break;
  4487. case methods.exchangeUnbindOk:
  4488. if (this._unbindCallback) {
  4489. cb = this._unbindCallback;
  4490. this._unbindCallback = null;
  4491. cb(this);
  4492. }
  4493. break;
  4494. default:
  4495. throw new Error("Uncaught method '" + method.name + "' with args " +
  4496. JSON.stringify(args));
  4497. }
  4498. this._tasksFlush();
  4499. };
  4500. // exchange.publish('routing.key', 'body');
  4501. //
  4502. // the third argument can specify additional options
  4503. // - mandatory (boolean, default false)
  4504. // - immediate (boolean, default false)
  4505. // - contentType (default 'application/octet-stream')
  4506. // - contentEncoding
  4507. // - headers
  4508. // - deliveryMode
  4509. // - priority (0-9)
  4510. // - correlationId
  4511. // - replyTo
  4512. // - expiration
  4513. // - messageId
  4514. // - timestamp
  4515. // - userId
  4516. // - appId
  4517. // - clusterId
  4518. //
  4519. // the callback is optional and is only used when confirm is turned on for the exchange
  4520. Exchange.prototype.publish = function (routingKey, data, options, callback) {
  4521. var self = this;
  4522. options = _.extend({}, options || {});
  4523. options.routingKey = routingKey;
  4524. options.exchange = self.name;
  4525. options.mandatory = options.mandatory ? true : false;
  4526. options.immediate = options.immediate ? true : false;
  4527. options.reserved1 = 0;
  4528. var task = this._taskPush(null, function () {
  4529. self.connection._sendMethod(self.channel, methods.basicPublish, options);
  4530. // This interface is probably not appropriate for streaming large files.
  4531. // (Of course it's arguable about whether AMQP is the appropriate
  4532. // transport for large files.) The content header wants to know the size
  4533. // of the data before sending it - so there's no point in trying to have a
  4534. // general streaming interface - streaming messages of unknown size simply
  4535. // isn't possible with AMQP. This is all to say, don't send big messages.
  4536. // If you need to stream something large, chunk it yourself.
  4537. self.connection._sendBody(self.channel, data, options);
  4538. });
  4539. if (self.options.confirm) self._awaitConfirm(task, callback);
  4540. return task;
  4541. };
  4542. // registers tasks for confirms
  4543. Exchange.prototype._awaitConfirm = function _awaitConfirm (task, callback) {
  4544. if (!this._addedExchangeErrorHandler) {
  4545. this.on('error', createExchangeErrorHandlerFor(this));
  4546. this._addedExchangeErrorHandler = true;
  4547. }
  4548. task.sequence = this._sequence;
  4549. this._unAcked[this._sequence] = task;
  4550. this._sequence++;
  4551. if ('function' != typeof callback) return;
  4552. task.once('ack error', function (err) {
  4553. task.removeAllListeners();
  4554. callback(true, err);
  4555. });
  4556. task.once('ack', function () {
  4557. task.removeAllListeners();
  4558. callback(false);
  4559. });
  4560. };
  4561. // do any necessary cleanups eg. after queue destruction
  4562. Exchange.prototype.cleanup = function() {
  4563. if (this.binds === 0) { // don't keep reference open if unused
  4564. this.connection.exchangeClosed(this.name);
  4565. }
  4566. };
  4567. Exchange.prototype.destroy = function (ifUnused) {
  4568. var self = this;
  4569. return this._taskPush(methods.exchangeDeleteOk, function () {
  4570. self.connection.exchangeClosed(self.name);
  4571. self.connection._sendMethod(self.channel, methods.exchangeDelete,
  4572. { reserved1: 0
  4573. , exchange: self.name
  4574. , ifUnused: ifUnused ? true : false
  4575. , noWait: false
  4576. });
  4577. });
  4578. };
  4579. // E2E Unbind
  4580. // support RabbitMQ's exchange-to-exchange binding extension
  4581. // http://www.rabbitmq.com/e2e.html
  4582. Exchange.prototype.unbind = function (/* exchange, routingKey [, bindCallback] */) {
  4583. var self = this;
  4584. // Both arguments are required. The binding to the destination
  4585. // exchange/routingKey will be unbound.
  4586. var exchange = arguments[0]
  4587. , routingKey = arguments[1]
  4588. , callback = arguments[2]
  4589. ;
  4590. if (callback) this._unbindCallback = callback;
  4591. return this._taskPush(methods.exchangeUnbindOk, function () {
  4592. var source = exchange instanceof Exchange ? exchange.name : exchange;
  4593. var destination = self.name;
  4594. if (source in self.connection.exchanges) {
  4595. delete self.sourceExchanges[source];
  4596. self.connection.exchanges[source].exchangeBinds--;
  4597. }
  4598. self.connection._sendMethod(self.channel, methods.exchangeUnbind,
  4599. { reserved1: 0
  4600. , destination: destination
  4601. , source: source
  4602. , routingKey: routingKey
  4603. , noWait: false
  4604. , "arguments": {}
  4605. });
  4606. });
  4607. };
  4608. // E2E Bind
  4609. // support RabbitMQ's exchange-to-exchange binding extension
  4610. // http://www.rabbitmq.com/e2e.html
  4611. Exchange.prototype.bind = function (/* exchange, routingKey [, bindCallback] */) {
  4612. var self = this;
  4613. // Two arguments are required. The binding to the destination
  4614. // exchange/routingKey will be established.
  4615. var exchange = arguments[0]
  4616. , routingKey = arguments[1]
  4617. , callback = arguments[2]
  4618. ;
  4619. if (callback) this._bindCallback = callback;
  4620. var source = exchange instanceof Exchange ? exchange.name : exchange;
  4621. var destination = self.name;
  4622. if(source in self.connection.exchanges) {
  4623. self.sourceExchanges[source] = self.connection.exchanges[source];
  4624. self.connection.exchanges[source].exchangeBinds++;
  4625. }
  4626. self.connection._sendMethod(self.channel, methods.exchangeBind,
  4627. { reserved1: 0
  4628. , destination: destination
  4629. , source: source
  4630. , routingKey: routingKey
  4631. , noWait: false
  4632. , "arguments": {}
  4633. });
  4634. };
  4635. // E2E Bind
  4636. // support RabbitMQ's exchange-to-exchange binding extension
  4637. // http://www.rabbitmq.com/e2e.html
  4638. Exchange.prototype.bind_headers = function (/* exchange, routing [, bindCallback] */) {
  4639. var self = this;
  4640. // Two arguments are required. The binding to the destination
  4641. // exchange/routingKey will be established.
  4642. var exchange = arguments[0]
  4643. , routing = arguments[1]
  4644. , callback = arguments[2]
  4645. ;
  4646. if (callback) this._bindCallback = callback;
  4647. var source = exchange instanceof Exchange ? exchange.name : exchange;
  4648. var destination = self.name;
  4649. if (source in self.connection.exchanges) {
  4650. self.sourceExchanges[source] = self.connection.exchanges[source];
  4651. self.connection.exchanges[source].exchangeBinds++;
  4652. }
  4653. self.connection._sendMethod(self.channel, methods.exchangeBind,
  4654. { reserved1: 0
  4655. , destination: destination
  4656. , source: source
  4657. , routingKey: ''
  4658. , noWait: false
  4659. , "arguments": routing
  4660. });
  4661. };
  4662. },{"./channel":27,"./definitions":31,"events":137,"fs":127,"lodash":38,"net":127,"tls":127,"util":159}],33:[function(_dereq_,module,exports){
  4663. 'use strict';
  4664. var events = _dereq_('events'),
  4665. util = _dereq_('util'),
  4666. fs = _dereq_('fs'),
  4667. protocol,
  4668. definitions = _dereq_('./definitions');
  4669. // Properties:
  4670. // - routingKey
  4671. // - size
  4672. // - deliveryTag
  4673. //
  4674. // - contentType (default 'application/octet-stream')
  4675. // - contentEncoding
  4676. // - headers
  4677. // - deliveryMode
  4678. // - priority (0-9)
  4679. // - correlationId
  4680. // - replyTo
  4681. // - experation
  4682. // - messageId
  4683. // - timestamp
  4684. // - userId
  4685. // - appId
  4686. // - clusterId
  4687. var Message = module.exports = function Message (queue, args) {
  4688. var msgProperties = definitions.classes[60].fields;
  4689. events.EventEmitter.call(this);
  4690. this.queue = queue;
  4691. this.deliveryTag = args.deliveryTag;
  4692. this.redelivered = args.redelivered;
  4693. this.exchange = args.exchange;
  4694. this.routingKey = args.routingKey;
  4695. this.consumerTag = args.consumerTag;
  4696. for (var i=0, l=msgProperties.length; i<l; i++) {
  4697. if (args[msgProperties[i].name]) {
  4698. this[msgProperties[i].name] = args[msgProperties[i].name];
  4699. }
  4700. }
  4701. };
  4702. util.inherits(Message, events.EventEmitter);
  4703. // Acknowledge receipt of message.
  4704. // Set first arg to 'true' to acknowledge this and all previous messages
  4705. // received on this queue.
  4706. Message.prototype.acknowledge = function (all) {
  4707. this.queue.connection._sendMethod(this.queue.channel, definitions.methods.basicAck,
  4708. { reserved1: 0
  4709. , deliveryTag: this.deliveryTag
  4710. , multiple: all ? true : false
  4711. });
  4712. };
  4713. // Reject an incoming message.
  4714. // Set first arg to 'true' to requeue the message.
  4715. Message.prototype.reject = function (requeue) {
  4716. this.queue.connection._sendMethod(this.queue.channel, definitions.methods.basicReject,
  4717. { deliveryTag: this.deliveryTag
  4718. , requeue: requeue ? true : false
  4719. });
  4720. };
  4721. },{"./definitions":31,"events":137,"fs":127,"util":159}],34:[function(_dereq_,module,exports){
  4722. (function (Buffer){
  4723. 'use strict';
  4724. var events = _dereq_('events');
  4725. var util = _dereq_('util');
  4726. var net = _dereq_('net');
  4727. var tls = _dereq_('tls');
  4728. var fs = _dereq_('fs');
  4729. var debug = _dereq_('./debug');
  4730. var jspack = _dereq_('../jspack').jspack;
  4731. var AMQPTypes = _dereq_('./constants').AMQPTypes;
  4732. var Indicators = _dereq_('./constants').Indicators;
  4733. var FrameType = _dereq_('./constants').FrameType;
  4734. var definitions = _dereq_('./definitions');
  4735. var methodTable = definitions.methodTable;
  4736. var classes = definitions.classes;
  4737. // parser
  4738. var maxFrameBuffer = 131072; // 128k, same as rabbitmq (which was
  4739. // copying qpid)
  4740. // An interruptible AMQP parser.
  4741. //
  4742. // type is either 'server' or 'client'
  4743. // version is '0-9-1'.
  4744. //
  4745. // Instances of this class have several callbacks
  4746. // - onMethod(channel, method, args);
  4747. // - onHeartBeat()
  4748. // - onContent(channel, buffer);
  4749. // - onContentHeader(channel, class, weight, properties, size);
  4750. //
  4751. // This class does not subclass EventEmitter, in order to reduce the speed
  4752. // of emitting the callbacks. Since this is an internal class, that should
  4753. // be fine.
  4754. var AMQPParser = module.exports = function AMQPParser (version, type) {
  4755. this.isClient = (type == 'client');
  4756. this.state = this.isClient ? 'frameHeader' : 'protocolHeader';
  4757. if (version != '0-9-1') this.throwError("Unsupported protocol version");
  4758. var frameHeader = new Buffer(7);
  4759. frameHeader.used = 0;
  4760. var frameBuffer, frameType, frameChannel;
  4761. var self = this;
  4762. function header(data) {
  4763. var fh = frameHeader;
  4764. var needed = fh.length - fh.used;
  4765. data.copy(fh, fh.used, 0, data.length);
  4766. fh.used += data.length; // sloppy
  4767. if (fh.used >= fh.length) {
  4768. fh.read = 0;
  4769. frameType = fh[fh.read++];
  4770. frameChannel = parseInt(fh, 2);
  4771. var frameSize = parseInt(fh, 4);
  4772. fh.used = 0; // for reuse
  4773. if (frameSize > maxFrameBuffer) {
  4774. self.throwError("Oversized frame " + frameSize);
  4775. }
  4776. frameBuffer = new Buffer(frameSize);
  4777. frameBuffer.used = 0;
  4778. return frame(data.slice(needed));
  4779. }
  4780. else { // need more!
  4781. return header;
  4782. }
  4783. }
  4784. function frame(data) {
  4785. var fb = frameBuffer;
  4786. var needed = fb.length - fb.used;
  4787. var sourceEnd = (fb.length > data.length) ? data.length : fb.length;
  4788. data.copy(fb, fb.used, 0, sourceEnd);
  4789. fb.used += data.length;
  4790. if (data.length > needed) {
  4791. return frameEnd(data.slice(needed));
  4792. }
  4793. else if (data.length == needed) {
  4794. return frameEnd;
  4795. }
  4796. else {
  4797. return frame;
  4798. }
  4799. }
  4800. function frameEnd(data) {
  4801. if (data.length > 0) {
  4802. if (data[0] === Indicators.FRAME_END) {
  4803. switch (frameType) {
  4804. case FrameType.METHOD:
  4805. self._parseMethodFrame(frameChannel, frameBuffer);
  4806. break;
  4807. case FrameType.HEADER:
  4808. self._parseHeaderFrame(frameChannel, frameBuffer);
  4809. break;
  4810. case FrameType.BODY:
  4811. if (self.onContent) {
  4812. self.onContent(frameChannel, frameBuffer);
  4813. }
  4814. break;
  4815. case FrameType.HEARTBEAT:
  4816. debug && debug("heartbeat");
  4817. if (self.onHeartBeat) self.onHeartBeat();
  4818. break;
  4819. default:
  4820. self.throwError("Unhandled frame type " + frameType);
  4821. break;
  4822. }
  4823. return header(data.slice(1));
  4824. }
  4825. else {
  4826. self.throwError("Missing frame end marker");
  4827. }
  4828. }
  4829. else {
  4830. return frameEnd;
  4831. }
  4832. }
  4833. self.parse = header;
  4834. }
  4835. // If there's an error in the parser, call the onError handler or throw
  4836. AMQPParser.prototype.throwError = function (error) {
  4837. if (this.onError) this.onError(error);
  4838. else throw new Error(error);
  4839. };
  4840. // Everytime data is recieved on the socket, pass it to this function for
  4841. // parsing.
  4842. AMQPParser.prototype.execute = function (data) {
  4843. // This function only deals with dismantling and buffering the frames.
  4844. // It delegates to other functions for parsing the frame-body.
  4845. debug && debug('execute: ' + data.toString('hex'));
  4846. this.parse = this.parse(data);
  4847. };
  4848. // parse Network Byte Order integers. size can be 1,2,4,8
  4849. function parseInt (buffer, size) {
  4850. switch (size) {
  4851. case 1:
  4852. return buffer[buffer.read++];
  4853. case 2:
  4854. return (buffer[buffer.read++] << 8) + buffer[buffer.read++];
  4855. case 4:
  4856. return (buffer[buffer.read++] << 24) + (buffer[buffer.read++] << 16) +
  4857. (buffer[buffer.read++] << 8) + buffer[buffer.read++];
  4858. case 8:
  4859. return (buffer[buffer.read++] << 56) + (buffer[buffer.read++] << 48) +
  4860. (buffer[buffer.read++] << 40) + (buffer[buffer.read++] << 32) +
  4861. (buffer[buffer.read++] << 24) + (buffer[buffer.read++] << 16) +
  4862. (buffer[buffer.read++] << 8) + buffer[buffer.read++];
  4863. default:
  4864. throw new Error("cannot parse ints of that size");
  4865. }
  4866. }
  4867. function parseShortString (buffer) {
  4868. var length = buffer[buffer.read++];
  4869. var s = buffer.toString('utf8', buffer.read, buffer.read+length);
  4870. buffer.read += length;
  4871. return s;
  4872. }
  4873. function parseLongString (buffer) {
  4874. var length = parseInt(buffer, 4);
  4875. var s = buffer.slice(buffer.read, buffer.read + length);
  4876. buffer.read += length;
  4877. return s.toString();
  4878. }
  4879. function parseSignedInteger (buffer) {
  4880. var int = parseInt(buffer, 4);
  4881. if (int & 0x80000000) {
  4882. int |= 0xEFFFFFFF;
  4883. int = -int;
  4884. }
  4885. return int;
  4886. }
  4887. function parseValue (buffer) {
  4888. switch (buffer[buffer.read++]) {
  4889. case AMQPTypes.STRING:
  4890. return parseLongString(buffer);
  4891. case AMQPTypes.INTEGER:
  4892. return parseInt(buffer, 4);
  4893. case AMQPTypes.DECIMAL:
  4894. var dec = parseInt(buffer, 1);
  4895. var num = parseInt(buffer, 4);
  4896. return num / (dec * 10);
  4897. case AMQPTypes._64BIT_FLOAT:
  4898. var b = [];
  4899. for (var i = 0; i < 8; ++i)
  4900. b[i] = buffer[buffer.read++];
  4901. return (new jspack(true)).Unpack('d', b);
  4902. case AMQPTypes._32BIT_FLOAT:
  4903. var b = [];
  4904. for (var i = 0; i < 4; ++i)
  4905. b[i] = buffer[buffer.read++];
  4906. return (new jspack(true)).Unpack('f', b);
  4907. case AMQPTypes.TIME:
  4908. var int = parseInt(buffer, 8);
  4909. return (new Date()).setTime(int * 1000);
  4910. case AMQPTypes.HASH:
  4911. return parseTable(buffer);
  4912. case AMQPTypes.SIGNED_64BIT:
  4913. return parseInt(buffer, 8);
  4914. case AMQPTypes.BOOLEAN:
  4915. return (parseInt(buffer, 1) > 0);
  4916. case AMQPTypes.BYTE_ARRAY:
  4917. var len = parseInt(buffer, 4);
  4918. var buf = new Buffer(len);
  4919. buffer.copy(buf, 0, buffer.read, buffer.read + len);
  4920. buffer.read += len;
  4921. return buf;
  4922. case AMQPTypes.ARRAY:
  4923. var len = parseInt(buffer, 4);
  4924. var end = buffer.read + len;
  4925. var arr = [];
  4926. while (buffer.read < end) {
  4927. arr.push(parseValue(buffer));
  4928. }
  4929. return arr;
  4930. default:
  4931. throw new Error("Unknown field value type " + buffer[buffer.read-1]);
  4932. }
  4933. }
  4934. function parseTable (buffer) {
  4935. var length = buffer.read + parseInt(buffer, 4);
  4936. var table = {};
  4937. while (buffer.read < length) {
  4938. table[parseShortString(buffer)] = parseValue(buffer);
  4939. }
  4940. return table;
  4941. }
  4942. function parseFields (buffer, fields) {
  4943. var args = {};
  4944. var bitIndex = 0;
  4945. var value;
  4946. for (var i = 0; i < fields.length; i++) {
  4947. var field = fields[i];
  4948. //debug && debug("parsing field " + field.name + " of type " + field.domain);
  4949. switch (field.domain) {
  4950. case 'bit':
  4951. // 8 bits can be packed into one octet.
  4952. // XXX check if bitIndex greater than 7?
  4953. value = (buffer[buffer.read] & (1 << bitIndex)) ? true : false;
  4954. if (fields[i+1] && fields[i+1].domain == 'bit') {
  4955. bitIndex++;
  4956. } else {
  4957. bitIndex = 0;
  4958. buffer.read++;
  4959. }
  4960. break;
  4961. case 'octet':
  4962. value = buffer[buffer.read++];
  4963. break;
  4964. case 'short':
  4965. value = parseInt(buffer, 2);
  4966. break;
  4967. case 'long':
  4968. value = parseInt(buffer, 4);
  4969. break;
  4970. // In a previous version this shared code with 'longlong', which caused problems when passed Date
  4971. // integers. Nobody expects to pass a Buffer here, 53 bits is still 28 million years after 1970, we'll be fine.
  4972. case 'timestamp':
  4973. value = parseInt(buffer, 8);
  4974. break;
  4975. // JS doesn't support 64-bit Numbers, so we expect if you're using 'longlong' that you've
  4976. // used a Buffer instead
  4977. case 'longlong':
  4978. value = new Buffer(8);
  4979. for (var j = 0; j < 8; j++) {
  4980. value[j] = buffer[buffer.read++];
  4981. }
  4982. break;
  4983. case 'shortstr':
  4984. value = parseShortString(buffer);
  4985. break;
  4986. case 'longstr':
  4987. value = parseLongString(buffer);
  4988. break;
  4989. case 'table':
  4990. value = parseTable(buffer);
  4991. break;
  4992. default:
  4993. throw new Error("Unhandled parameter type " + field.domain);
  4994. }
  4995. //debug && debug("got " + value);
  4996. args[field.name] = value;
  4997. }
  4998. return args;
  4999. }
  5000. AMQPParser.prototype._parseMethodFrame = function (channel, buffer) {
  5001. buffer.read = 0;
  5002. var classId = parseInt(buffer, 2),
  5003. methodId = parseInt(buffer, 2);
  5004. // Make sure that this is a method that we understand.
  5005. if (!methodTable[classId] || !methodTable[classId][methodId]) {
  5006. this.throwError("Received unknown [classId, methodId] pair [" +
  5007. classId + ", " + methodId + "]");
  5008. }
  5009. var method = methodTable[classId][methodId];
  5010. if (!method) this.throwError("bad method?");
  5011. var args = parseFields(buffer, method.fields);
  5012. if (this.onMethod) {
  5013. debug && debug("Executing method", channel, method, args);
  5014. this.onMethod(channel, method, args);
  5015. }
  5016. };
  5017. AMQPParser.prototype._parseHeaderFrame = function (channel, buffer) {
  5018. buffer.read = 0;
  5019. var classIndex = parseInt(buffer, 2);
  5020. var weight = parseInt(buffer, 2);
  5021. var size = parseInt(buffer, 8);
  5022. var classInfo = classes[classIndex];
  5023. if (classInfo.fields.length > 15) {
  5024. this.throwError("TODO: support more than 15 properties");
  5025. }
  5026. var propertyFlags = parseInt(buffer, 2);
  5027. var fields = [];
  5028. for (var i = 0; i < classInfo.fields.length; i++) {
  5029. var field = classInfo.fields[i];
  5030. // groan.
  5031. if (propertyFlags & (1 << (15-i))) fields.push(field);
  5032. }
  5033. var properties = parseFields(buffer, fields);
  5034. if (this.onContentHeader) {
  5035. this.onContentHeader(channel, classInfo, weight, properties, size);
  5036. }
  5037. };
  5038. }).call(this,_dereq_("buffer").Buffer)
  5039. },{"../jspack":25,"./constants":29,"./debug":30,"./definitions":31,"buffer":128,"events":137,"fs":127,"net":127,"tls":127,"util":159}],35:[function(_dereq_,module,exports){
  5040. (function (process){
  5041. var events = _dereq_('events');
  5042. var inherits = _dereq_('util').inherits;
  5043. exports.Promise = function () {
  5044. events.EventEmitter.call(this);
  5045. this._blocking = false;
  5046. this.hasFired = false;
  5047. this.hasAcked = false;
  5048. this._values = undefined;
  5049. };
  5050. inherits(exports.Promise, events.EventEmitter);
  5051. exports.Promise.prototype.timeout = function(timeout) {
  5052. if (!timeout) {
  5053. return this._timeoutDuration;
  5054. }
  5055. this._timeoutDuration = timeout;
  5056. if (this.hasFired) return;
  5057. this._clearTimeout();
  5058. var self = this;
  5059. this._timer = setTimeout(function() {
  5060. self._timer = null;
  5061. if (self.hasFired) {
  5062. return;
  5063. }
  5064. self.emitError(new Error('timeout'));
  5065. }, timeout);
  5066. return this;
  5067. };
  5068. exports.Promise.prototype._clearTimeout = function() {
  5069. if (!this._timer) return;
  5070. clearTimeout(this._timer);
  5071. this._timer = null;
  5072. }
  5073. exports.Promise.prototype.emitSuccess = function() {
  5074. if (this.hasFired) return;
  5075. this.hasFired = 'success';
  5076. this._clearTimeout();
  5077. this._values = Array.prototype.slice.call(arguments);
  5078. this.emit.apply(this, ['success'].concat(this._values));
  5079. };
  5080. exports.Promise.prototype.emitError = function() {
  5081. if (this.hasFired) return;
  5082. this.hasFired = 'error';
  5083. this._clearTimeout();
  5084. this._values = Array.prototype.slice.call(arguments);
  5085. this.emit.apply(this, ['error'].concat(this._values));
  5086. if (this.listeners('error').length == 0) {
  5087. var self = this;
  5088. process.nextTick(function() {
  5089. if (self.listeners('error').length == 0) {
  5090. throw (self._values[0] instanceof Error)
  5091. ? self._values[0]
  5092. : new Error('Unhandled emitError: '+JSON.stringify(self._values));
  5093. }
  5094. });
  5095. }
  5096. };
  5097. exports.Promise.prototype.addCallback = function (listener) {
  5098. if (this.hasFired === 'success') {
  5099. listener.apply(this, this._values);
  5100. }
  5101. return this.addListener("success", listener);
  5102. };
  5103. exports.Promise.prototype.addErrback = function (listener) {
  5104. if (this.hasFired === 'error') {
  5105. listener.apply(this, this._values);
  5106. }
  5107. return this.addListener("error", listener);
  5108. };
  5109. }).call(this,_dereq_("C:\\Users\\Alex\\AppData\\Roaming\\npm\\node_modules\\browserify\\node_modules\\insert-module-globals\\node_modules\\process\\browser.js"))
  5110. },{"C:\\Users\\Alex\\AppData\\Roaming\\npm\\node_modules\\browserify\\node_modules\\insert-module-globals\\node_modules\\process\\browser.js":144,"events":137,"util":159}],36:[function(_dereq_,module,exports){
  5111. (function (process,Buffer){
  5112. 'use strict';
  5113. var util = _dereq_('util');
  5114. var fs = _dereq_('fs');
  5115. var _ = _dereq_('lodash');
  5116. var Channel = _dereq_('./channel');
  5117. var Exchange = _dereq_('./exchange');
  5118. var Message = _dereq_('./message');
  5119. var debug = _dereq_('./debug');
  5120. var definitions = _dereq_('./definitions');
  5121. var methods = definitions.methods;
  5122. var classes = definitions.classes;
  5123. var Queue = module.exports = function Queue (connection, channel, name, options, callback) {
  5124. Channel.call(this, connection, channel);
  5125. var self = this;
  5126. this.name = name;
  5127. this._bindings = {};
  5128. this.consumerTagListeners = {};
  5129. this.consumerTagOptions = {};
  5130. // route messages to subscribers based on consumerTag
  5131. this.on('rawMessage', function(message) {
  5132. if (message.consumerTag && self.consumerTagListeners[message.consumerTag]) {
  5133. self.consumerTagListeners[message.consumerTag](message);
  5134. }
  5135. });
  5136. this.options = { autoDelete: true, closeChannelOnUnsubscribe: false };
  5137. _.extend(this.options, options || {});
  5138. this._openCallback = callback;
  5139. };
  5140. util.inherits(Queue, Channel);
  5141. Queue.prototype.subscribeRaw = function (options, messageListener) {
  5142. var self = this;
  5143. // multiple method signatures
  5144. if (typeof options === "function") {
  5145. messageListener = options;
  5146. options = {};
  5147. }
  5148. var consumerTag = 'node-amqp-' + process.pid + '-' + Math.random();
  5149. this.consumerTagListeners[consumerTag] = messageListener;
  5150. options = options || {};
  5151. options['state'] = 'opening';
  5152. this.consumerTagOptions[consumerTag] = options;
  5153. if (options.prefetchCount !== undefined) {
  5154. self.connection._sendMethod(self.channel, methods.basicQos,
  5155. { reserved1: 0
  5156. , prefetchSize: 0
  5157. , prefetchCount: options.prefetchCount
  5158. , global: false
  5159. });
  5160. }
  5161. return this._taskPush(methods.basicConsumeOk, function () {
  5162. self.connection._sendMethod(self.channel, methods.basicConsume,
  5163. { reserved1: 0
  5164. , queue: self.name
  5165. , consumerTag: consumerTag
  5166. , noLocal: !!options.noLocal
  5167. , noAck: !!options.noAck
  5168. , exclusive: !!options.exclusive
  5169. , noWait: false
  5170. , "arguments": {}
  5171. });
  5172. self.consumerTagOptions[consumerTag]['state'] = 'open';
  5173. });
  5174. };
  5175. Queue.prototype.unsubscribe = function(consumerTag) {
  5176. var self = this;
  5177. return this._taskPush(methods.basicCancelOk, function () {
  5178. self.connection._sendMethod(self.channel, methods.basicCancel,
  5179. { reserved1: 0,
  5180. consumerTag: consumerTag,
  5181. noWait: false });
  5182. })
  5183. .addCallback(function () {
  5184. if (self.options.closeChannelOnUnsubscribe) {
  5185. self.close();
  5186. }
  5187. delete self.consumerTagListeners[consumerTag];
  5188. delete self.consumerTagOptions[consumerTag];
  5189. });
  5190. };
  5191. Queue.prototype.subscribe = function (options, messageListener) {
  5192. var self = this;
  5193. // Optional options
  5194. if (typeof options === "function") {
  5195. messageListener = options;
  5196. options = {};
  5197. }
  5198. options = _.defaults(options || {}, {
  5199. ack: false,
  5200. prefetchCount: 1,
  5201. routingKeyInPayload: self.connection.options.routingKeyInPayload,
  5202. deliveryTagInPayload: self.connection.options.deliveryTagInPayload
  5203. });
  5204. // basic consume
  5205. var rawOptions = {
  5206. noAck: !options.ack,
  5207. exclusive: options.exclusive
  5208. };
  5209. if (options.ack) {
  5210. rawOptions['prefetchCount'] = options.prefetchCount;
  5211. }
  5212. return this.subscribeRaw(rawOptions, function (m) {
  5213. var contentType = m.contentType;
  5214. if (contentType == null && m.headers && m.headers.properties) {
  5215. contentType = m.headers.properties.content_type;
  5216. }
  5217. var isJSON = contentType == 'text/json' ||
  5218. contentType == 'application/json';
  5219. var buffer;
  5220. if (isJSON) {
  5221. buffer = "";
  5222. } else {
  5223. buffer = new Buffer(m.size);
  5224. buffer.used = 0;
  5225. }
  5226. self._lastMessage = m;
  5227. m.addListener('data', function (d) {
  5228. if (isJSON) {
  5229. buffer += d.toString();
  5230. } else {
  5231. d.copy(buffer, buffer.used);
  5232. buffer.used += d.length;
  5233. }
  5234. });
  5235. m.addListener('end', function () {
  5236. var json, deliveryInfo = {}, msgProperties = classes[60].fields, i, l;
  5237. if (isJSON) {
  5238. try {
  5239. json = JSON.parse(buffer);
  5240. } catch (e) {
  5241. json = null;
  5242. deliveryInfo.parseError = e;
  5243. deliveryInfo.rawData = buffer;
  5244. }
  5245. } else {
  5246. json = { data: buffer, contentType: m.contentType };
  5247. }
  5248. for (i = 0, l = msgProperties.length; i<l; i++) {
  5249. if (m[msgProperties[i].name]) {
  5250. deliveryInfo[msgProperties[i].name] = m[msgProperties[i].name];
  5251. }
  5252. }
  5253. deliveryInfo.queue = m.queue ? m.queue.name : null;
  5254. deliveryInfo.deliveryTag = m.deliveryTag;
  5255. deliveryInfo.redelivered = m.redelivered;
  5256. deliveryInfo.exchange = m.exchange;
  5257. deliveryInfo.routingKey = m.routingKey;
  5258. deliveryInfo.consumerTag = m.consumerTag;
  5259. if (options.routingKeyInPayload) json._routingKey = m.routingKey;
  5260. if (options.deliveryTagInPayload) json._deliveryTag = m.deliveryTag;
  5261. var headers = {};
  5262. for (i in this.headers) {
  5263. if (this.headers.hasOwnProperty(i)) {
  5264. if (this.headers[i] instanceof Buffer) {
  5265. headers[i] = this.headers[i].toString();
  5266. } else {
  5267. headers[i] = this.headers[i];
  5268. }
  5269. }
  5270. }
  5271. if (messageListener) messageListener(json, headers, deliveryInfo, m);
  5272. self.emit('message', json, headers, deliveryInfo, m);
  5273. });
  5274. });
  5275. };
  5276. Queue.prototype.subscribeJSON = Queue.prototype.subscribe;
  5277. /* Acknowledges the last message */
  5278. Queue.prototype.shift = function (reject, requeue) {
  5279. if (this._lastMessage) {
  5280. if (reject) {
  5281. this._lastMessage.reject(requeue ? true : false);
  5282. } else {
  5283. this._lastMessage.acknowledge();
  5284. }
  5285. }
  5286. };
  5287. Queue.prototype.bind = function (exchange, routingKey, callback) {
  5288. var self = this;
  5289. // The first argument, exchange is optional.
  5290. // If not supplied the connection will use the 'amq.topic'
  5291. // exchange.
  5292. if (routingKey === undefined || _.isFunction(routingKey)) {
  5293. callback = routingKey;
  5294. routingKey = exchange;
  5295. exchange = 'amq.topic';
  5296. }
  5297. if (_.isFunction(callback)) this._bindCallback = callback;
  5298. var exchangeName = exchange instanceof Exchange ? exchange.name : exchange;
  5299. if (exchangeName in self.connection.exchanges) {
  5300. this.exchange = self.connection.exchanges[exchangeName];
  5301. this.exchange.binds++;
  5302. }
  5303. // Record this binding so we can restore it upon reconnect.
  5304. if (!this._bindings[exchangeName]) {
  5305. this._bindings[exchangeName] = {};
  5306. }
  5307. if (!this._bindings[exchangeName][routingKey]) {
  5308. this._bindings[exchangeName][routingKey] = 0;
  5309. }
  5310. this._bindings[exchangeName][routingKey]++;
  5311. self.connection._sendMethod(self.channel, methods.queueBind,
  5312. { reserved1: 0
  5313. , queue: self.name
  5314. , exchange: exchangeName
  5315. , routingKey: routingKey
  5316. , noWait: false
  5317. , "arguments": {}
  5318. });
  5319. };
  5320. Queue.prototype.unbind = function (exchange, routingKey) {
  5321. var self = this;
  5322. // The first argument, exchange is optional.
  5323. // If not supplied the connection will use the default 'amq.topic'
  5324. // exchange.
  5325. if (routingKey === undefined) {
  5326. routingKey = exchange;
  5327. exchange = 'amq.topic';
  5328. }
  5329. var exchangeName = exchange instanceof Exchange ? exchange.name : exchange;
  5330. // Decrement binding count.
  5331. this._bindings[exchangeName][routingKey]--;
  5332. if (!this._bindings[exchangeName][routingKey]) {
  5333. delete this._bindings[exchangeName][routingKey];
  5334. }
  5335. // If there are no more bindings to this exchange, delete the key for the exchange.
  5336. if (!_.keys(this._bindings[exchangeName]).length){
  5337. delete this._bindings[exchangeName];
  5338. }
  5339. return this._taskPush(methods.queueUnbindOk, function () {
  5340. self.connection._sendMethod(self.channel, methods.queueUnbind,
  5341. { reserved1: 0
  5342. , queue: self.name
  5343. , exchange: exchangeName
  5344. , routingKey: routingKey
  5345. , noWait: false
  5346. , "arguments": {}
  5347. });
  5348. });
  5349. };
  5350. Queue.prototype.bind_headers = function (/* [exchange,] matchingPairs */) {
  5351. var self = this;
  5352. // The first argument, exchange is optional.
  5353. // If not supplied the connection will use the default 'amq.headers'
  5354. // exchange.
  5355. var exchange, matchingPairs;
  5356. if (arguments.length == 2) {
  5357. exchange = arguments[0];
  5358. matchingPairs = arguments[1];
  5359. } else {
  5360. exchange = 'amq.headers';
  5361. matchingPairs = arguments[0];
  5362. }
  5363. return this._taskPush(methods.queueBindOk, function () {
  5364. var exchangeName = exchange instanceof Exchange ? exchange.name : exchange;
  5365. self.connection._sendMethod(self.channel, methods.queueBind,
  5366. { reserved1: 0
  5367. , queue: self.name
  5368. , exchange: exchangeName
  5369. , routingKey: ''
  5370. , noWait: false
  5371. , "arguments": matchingPairs
  5372. });
  5373. });
  5374. };
  5375. Queue.prototype.unbind_headers = function (/* [exchange,] matchingPairs */) {
  5376. var self = this;
  5377. // The first argument, exchange is optional.
  5378. // If not supplied the connection will use the default 'amq.topic'
  5379. // exchange.
  5380. var exchange, matchingPairs;
  5381. if (arguments.length === 2) {
  5382. exchange = arguments[0];
  5383. matchingPairs = arguments[1];
  5384. } else {
  5385. exchange = 'amq.headers';
  5386. matchingPairs = arguments[0];
  5387. }
  5388. return this._taskPush(methods.queueUnbindOk, function () {
  5389. var exchangeName = exchange instanceof Exchange ? exchange.name : exchange;
  5390. self.connection._sendMethod(self.channel, methods.queueUnbind,
  5391. { reserved1: 0
  5392. , queue: self.name
  5393. , exchange: exchangeName
  5394. , routingKey: ''
  5395. , noWait: false
  5396. , "arguments": matchingPairs
  5397. });
  5398. });
  5399. };
  5400. Queue.prototype.destroy = function (options) {
  5401. var self = this;
  5402. options = options || {};
  5403. return this._taskPush(methods.queueDeleteOk, function () {
  5404. self.connection.queueClosed(self.name);
  5405. if ('exchange' in self) {
  5406. self.exchange.binds--;
  5407. self.exchange.cleanup();
  5408. }
  5409. self.connection._sendMethod(self.channel, methods.queueDelete,
  5410. { reserved1: 0
  5411. , queue: self.name
  5412. , ifUnused: options.ifUnused ? true : false
  5413. , ifEmpty: options.ifEmpty ? true : false
  5414. , noWait: false
  5415. , "arguments": {}
  5416. });
  5417. });
  5418. };
  5419. Queue.prototype.purge = function() {
  5420. var self = this;
  5421. return this._taskPush(methods.queuePurgeOk, function () {
  5422. self.connection._sendMethod(self.channel, methods.queuePurge,
  5423. { reserved1 : 0,
  5424. queue: self.name,
  5425. noWait: false});
  5426. });
  5427. };
  5428. Queue.prototype._onMethod = function (channel, method, args) {
  5429. var self = this;
  5430. this.emit(method.name, args);
  5431. if (this._handleTaskReply.apply(this, arguments)) return;
  5432. switch (method) {
  5433. case methods.channelOpenOk:
  5434. if (this.options.noDeclare) {
  5435. this.state = 'open';
  5436. if (this._openCallback) {
  5437. this._openCallback(this);
  5438. this._openCallback = null;
  5439. }
  5440. this.emit('open');
  5441. } else {
  5442. if (this.name.indexOf('amq.') == 0) {
  5443. this.name = '';
  5444. }
  5445. this.connection._sendMethod(channel, methods.queueDeclare,
  5446. { reserved1: 0
  5447. , queue: this.name
  5448. , passive: !!this.options.passive
  5449. , durable: !!this.options.durable
  5450. , exclusive: !!this.options.exclusive
  5451. , autoDelete: !!this.options.autoDelete
  5452. , noWait: false
  5453. , "arguments": this.options.arguments || {}
  5454. });
  5455. this.state = "declare queue";
  5456. }
  5457. break;
  5458. case methods.queueDeclareOk:
  5459. this.state = 'open';
  5460. this.name = args.queue;
  5461. this.connection.queues[this.name] = this;
  5462. // Rebind to previously bound exchanges, if present.
  5463. // Important this is called *before* openCallback, otherwise bindings will happen twice.
  5464. // Run test-purge to make sure you got this right
  5465. _.each(this._bindings, function(exchange, exchangeName){
  5466. _.each(exchange, function(count, routingKey){
  5467. self.bind(exchangeName, routingKey);
  5468. });
  5469. });
  5470. // Call opening callback (passed in function)
  5471. // FIXME use eventemitter - maybe we call a namespaced event here
  5472. if (this._openCallback) {
  5473. this._openCallback(this, args.messageCount, args.consumerCount);
  5474. this._openCallback = null;
  5475. }
  5476. // TODO this is legacy interface, remove me
  5477. this.emit('open', args.queue, args.messageCount, args.consumerCount);
  5478. // If this is a reconnect, we must re-subscribe our queue listeners.
  5479. var consumerTags = Object.keys(this.consumerTagListeners);
  5480. for (var index in consumerTags) {
  5481. if (consumerTags.hasOwnProperty(index)) {
  5482. if (this.consumerTagOptions[consumerTags[index]]['state'] === 'closed') {
  5483. this.subscribeRaw(this.consumerTagOptions[consumerTags[index]], this.consumerTagListeners[consumerTags[index]]);
  5484. // Having called subscribeRaw, we are now a new consumer with a new consumerTag.
  5485. delete this.consumerTagListeners[consumerTags[index]];
  5486. delete this.consumerTagOptions[consumerTags[index]];
  5487. }
  5488. }
  5489. }
  5490. break;
  5491. case methods.basicConsumeOk:
  5492. debug && debug('basicConsumeOk', util.inspect(args, null));
  5493. break;
  5494. case methods.queueBindOk:
  5495. if (this._bindCallback) {
  5496. // setting this._bindCallback to null before calling the callback allows for a subsequent bind within the callback
  5497. // FIXME use eventemitter
  5498. var cb = this._bindCallback;
  5499. this._bindCallback = null;
  5500. cb(this);
  5501. }
  5502. break;
  5503. case methods.queueUnbindOk:
  5504. break;
  5505. case methods.basicQosOk:
  5506. break;
  5507. case methods.confirmSelectOk:
  5508. this._sequence = 1;
  5509. this.confirm = true;
  5510. break;
  5511. case methods.channelClose:
  5512. this.state = "closed";
  5513. this.closeOK();
  5514. this.connection.queueClosed(this.name);
  5515. var e = new Error(args.replyText);
  5516. e.code = args.replyCode;
  5517. this.emit('error', e);
  5518. this.emit('close');
  5519. break;
  5520. case methods.channelCloseOk:
  5521. this.connection.queueClosed(this.name);
  5522. this.emit('close');
  5523. break;
  5524. case methods.basicDeliver:
  5525. this.currentMessage = new Message(this, args);
  5526. break;
  5527. case methods.queueDeleteOk:
  5528. break;
  5529. case methods.basicCancel:
  5530. this.close("Closed due to basicCancel received on consumer (" + args.consumerTag + ")");
  5531. break;
  5532. default:
  5533. throw new Error("Uncaught method '" + method.name + "' with args " +
  5534. JSON.stringify(args) + "; tasks = " + JSON.stringify(this._tasks));
  5535. }
  5536. this._tasksFlush();
  5537. };
  5538. Queue.prototype._onContentHeader = function (channel, classInfo, weight, properties, size) {
  5539. _.extend(this.currentMessage, properties);
  5540. this.currentMessage.read = 0;
  5541. this.currentMessage.size = size;
  5542. this.emit('rawMessage', this.currentMessage);
  5543. if (size === 0) {
  5544. // If the message has no body, directly emit 'end'
  5545. this.currentMessage.emit('end');
  5546. }
  5547. };
  5548. Queue.prototype._onContent = function (channel, data) {
  5549. this.currentMessage.read += data.length;
  5550. this.currentMessage.emit('data', data);
  5551. if (this.currentMessage.read == this.currentMessage.size) {
  5552. this.currentMessage.emit('end');
  5553. }
  5554. };
  5555. Queue.prototype.flow = function(active) {
  5556. var self = this;
  5557. return this._taskPush(methods.channelFlowOk, function () {
  5558. self.connection._sendMethod(self.channel, methods.channelFlow, {'active': active });
  5559. });
  5560. };
  5561. }).call(this,_dereq_("C:\\Users\\Alex\\AppData\\Roaming\\npm\\node_modules\\browserify\\node_modules\\insert-module-globals\\node_modules\\process\\browser.js"),_dereq_("buffer").Buffer)
  5562. },{"./channel":27,"./debug":30,"./definitions":31,"./exchange":32,"./message":33,"C:\\Users\\Alex\\AppData\\Roaming\\npm\\node_modules\\browserify\\node_modules\\insert-module-globals\\node_modules\\process\\browser.js":144,"buffer":128,"fs":127,"lodash":38,"util":159}],37:[function(_dereq_,module,exports){
  5563. (function (Buffer){
  5564. 'use strict';
  5565. var jspack = _dereq_('../jspack').jspack;
  5566. var serializer = module.exports = {
  5567. serializeFloat: function(b, size, value, bigEndian) {
  5568. var jp = new jspack(bigEndian);
  5569. switch(size) {
  5570. case 4:
  5571. var x = jp.Pack('f', [value]);
  5572. for (var i = 0; i < x.length; ++i)
  5573. b[b.used++] = x[i];
  5574. break;
  5575. case 8:
  5576. var x = jp.Pack('d', [value]);
  5577. for (var i = 0; i < x.length; ++i)
  5578. b[b.used++] = x[i];
  5579. break;
  5580. default:
  5581. throw new Error("Unknown floating point size");
  5582. }
  5583. },
  5584. serializeInt: function (b, size, int) {
  5585. if (b.used + size > b.length) {
  5586. throw new Error("write out of bounds");
  5587. }
  5588. // Only 4 cases - just going to be explicit instead of looping.
  5589. switch (size) {
  5590. // octet
  5591. case 1:
  5592. b[b.used++] = int;
  5593. break;
  5594. // short
  5595. case 2:
  5596. b[b.used++] = (int & 0xFF00) >> 8;
  5597. b[b.used++] = (int & 0x00FF) >> 0;
  5598. break;
  5599. // long
  5600. case 4:
  5601. b[b.used++] = (int & 0xFF000000) >> 24;
  5602. b[b.used++] = (int & 0x00FF0000) >> 16;
  5603. b[b.used++] = (int & 0x0000FF00) >> 8;
  5604. b[b.used++] = (int & 0x000000FF) >> 0;
  5605. break;
  5606. // long long
  5607. case 8:
  5608. b[b.used++] = (int & 0xFF00000000000000) >> 56;
  5609. b[b.used++] = (int & 0x00FF000000000000) >> 48;
  5610. b[b.used++] = (int & 0x0000FF0000000000) >> 40;
  5611. b[b.used++] = (int & 0x000000FF00000000) >> 32;
  5612. b[b.used++] = (int & 0x00000000FF000000) >> 24;
  5613. b[b.used++] = (int & 0x0000000000FF0000) >> 16;
  5614. b[b.used++] = (int & 0x000000000000FF00) >> 8;
  5615. b[b.used++] = (int & 0x00000000000000FF) >> 0;
  5616. break;
  5617. default:
  5618. throw new Error("Bad size");
  5619. }
  5620. },
  5621. serializeShortString: function (b, string) {
  5622. if (typeof(string) != "string") {
  5623. throw new Error("param must be a string");
  5624. }
  5625. var byteLength = Buffer.byteLength(string, 'utf8');
  5626. if (byteLength > 0xFF) {
  5627. throw new Error("String too long for 'shortstr' parameter");
  5628. }
  5629. if (1 + byteLength + b.used >= b.length) {
  5630. throw new Error("Not enough space in buffer for 'shortstr'");
  5631. }
  5632. b[b.used++] = byteLength;
  5633. b.write(string, b.used, 'utf8');
  5634. b.used += byteLength;
  5635. },
  5636. serializeLongString: function(b, string) {
  5637. // we accept string, object, or buffer for this parameter.
  5638. // in the case of string we serialize it to utf8.
  5639. if (typeof(string) == 'string') {
  5640. var byteLength = Buffer.byteLength(string, 'utf8');
  5641. serializer.serializeInt(b, 4, byteLength);
  5642. b.write(string, b.used, 'utf8');
  5643. b.used += byteLength;
  5644. } else if (typeof(string) == 'object') {
  5645. serializer.serializeTable(b, string);
  5646. } else {
  5647. // data is Buffer
  5648. var byteLength = string.length;
  5649. serializer.serializeInt(b, 4, byteLength);
  5650. b.write(string, b.used); // memcpy
  5651. b.used += byteLength;
  5652. }
  5653. },
  5654. serializeDate: function(b, date) {
  5655. serializer.serializeInt(b, 8, date.valueOf() / 1000);
  5656. },
  5657. serializeBuffer: function(b, buffer) {
  5658. serializer.serializeInt(b, 4, buffer.length);
  5659. buffer.copy(b, b.used, 0);
  5660. b.used += buffer.length;
  5661. },
  5662. serializeBase64: function(b, buffer) {
  5663. serializer.serializeLongString(b, buffer.toString('base64'));
  5664. },
  5665. isBigInt: function(value) {
  5666. return value > 0xffffffff;
  5667. },
  5668. getCode: function(dec) {
  5669. var hexArray = "0123456789ABCDEF".split('');
  5670. var code1 = Math.floor(dec / 16);
  5671. var code2 = dec - code1 * 16;
  5672. return hexArray[code2];
  5673. },
  5674. isFloat: function(value){
  5675. return value === +value && value !== (value|0);
  5676. },
  5677. serializeValue: function(b, value) {
  5678. switch (typeof(value)) {
  5679. case 'string':
  5680. b[b.used++] = 'S'.charCodeAt(0);
  5681. serializer.serializeLongString(b, value);
  5682. break;
  5683. case 'number':
  5684. if (!serializer.isFloat(value)) {
  5685. if (serializer.isBigInt(value)) {
  5686. // 64-bit uint
  5687. b[b.used++] = 'l'.charCodeAt(0);
  5688. serializer.serializeInt(b, 8, value);
  5689. } else {
  5690. //32-bit uint
  5691. b[b.used++] = 'I'.charCodeAt(0);
  5692. serializer.serializeInt(b, 4, value);
  5693. }
  5694. } else {
  5695. //64-bit float
  5696. b[b.used++] = 'd'.charCodeAt(0);
  5697. serializer.serializeFloat(b, 8, value);
  5698. }
  5699. break;
  5700. case 'boolean':
  5701. b[b.used++] = 't'.charCodeAt(0);
  5702. b[b.used++] = value;
  5703. break;
  5704. default:
  5705. if (value instanceof Date) {
  5706. b[b.used++] = 'T'.charCodeAt(0);
  5707. serializer.serializeDate(b, value);
  5708. } else if (value instanceof Buffer) {
  5709. b[b.used++] = 'x'.charCodeAt(0);
  5710. serializer.serializeBuffer(b, value);
  5711. } else if (Array.isArray(value)) {
  5712. b[b.used++] = 'A'.charCodeAt(0);
  5713. serializer.serializeArray(b, value);
  5714. } else if (typeof(value) === 'object') {
  5715. b[b.used++] = 'F'.charCodeAt(0);
  5716. serializer.serializeTable(b, value);
  5717. } else {
  5718. throw new Error("unsupported type in amqp table: " + typeof(value));
  5719. }
  5720. }
  5721. },
  5722. serializeTable: function(b, object) {
  5723. if (typeof(object) != "object") {
  5724. throw new Error("param must be an object");
  5725. }
  5726. // Save our position so that we can go back and write the length of this table
  5727. // at the beginning of the packet (once we know how many entries there are).
  5728. var lengthIndex = b.used;
  5729. b.used += 4; // sizeof long
  5730. var startIndex = b.used;
  5731. for (var key in object) {
  5732. if (!object.hasOwnProperty(key)) continue;
  5733. serializer.serializeShortString(b, key);
  5734. serializer.serializeValue(b, object[key]);
  5735. }
  5736. var endIndex = b.used;
  5737. b.used = lengthIndex;
  5738. serializer.serializeInt(b, 4, endIndex - startIndex);
  5739. b.used = endIndex;
  5740. },
  5741. serializeArray: function(b, arr) {
  5742. // Save our position so that we can go back and write the byte length of this array
  5743. // at the beginning of the packet (once we have serialized all elements).
  5744. var lengthIndex = b.used;
  5745. b.used += 4; // sizeof long
  5746. var startIndex = b.used;
  5747. var len = arr.length;
  5748. for (var i = 0; i < len; i++) {
  5749. serializer.serializeValue(b, arr[i]);
  5750. }
  5751. var endIndex = b.used;
  5752. b.used = lengthIndex;
  5753. serializer.serializeInt(b, 4, endIndex - startIndex);
  5754. b.used = endIndex;
  5755. },
  5756. serializeFields: function(buffer, fields, args, strict) {
  5757. var bitField = 0;
  5758. var bitIndex = 0;
  5759. for (var i = 0; i < fields.length; i++) {
  5760. var field = fields[i];
  5761. var domain = field.domain;
  5762. if (!(field.name in args)) {
  5763. if (strict) {
  5764. throw new Error("Missing field '" + field.name + "' of type '" + domain + "' while executing AMQP method '" +
  5765. arguments.callee.caller.arguments[1].name + "'");
  5766. }
  5767. continue;
  5768. }
  5769. var param = args[field.name];
  5770. //debug("domain: " + domain + " param: " + param);
  5771. switch (domain) {
  5772. case 'bit':
  5773. if (typeof(param) != "boolean") {
  5774. throw new Error("Unmatched field " + JSON.stringify(field));
  5775. }
  5776. if (param) bitField |= (1 << bitIndex);
  5777. bitIndex++;
  5778. if (!fields[i+1] || fields[i+1].domain != 'bit') {
  5779. //debug('SET bit field ' + field.name + ' 0x' + bitField.toString(16));
  5780. buffer[buffer.used++] = bitField;
  5781. bitField = 0;
  5782. bitIndex = 0;
  5783. }
  5784. break;
  5785. case 'octet':
  5786. if (typeof(param) != "number" || param > 0xFF) {
  5787. throw new Error("Unmatched field " + JSON.stringify(field));
  5788. }
  5789. buffer[buffer.used++] = param;
  5790. break;
  5791. case 'short':
  5792. if (typeof(param) != "number" || param > 0xFFFF) {
  5793. throw new Error("Unmatched field " + JSON.stringify(field));
  5794. }
  5795. serializer.serializeInt(buffer, 2, param);
  5796. break;
  5797. case 'long':
  5798. if (typeof(param) != "number" || param > 0xFFFFFFFF) {
  5799. throw new Error("Unmatched field " + JSON.stringify(field));
  5800. }
  5801. serializer.serializeInt(buffer, 4, param);
  5802. break;
  5803. // In a previous version this shared code with 'longlong', which caused problems when passed Date
  5804. // integers. Nobody expects to pass a Buffer here, 53 bits is still 28 million years after 1970, we'll be fine.
  5805. case 'timestamp':
  5806. serializer.serializeInt(buffer, 8, param);
  5807. break;
  5808. case 'longlong':
  5809. for (var j = 0; j < 8; j++) {
  5810. buffer[buffer.used++] = param[j];
  5811. }
  5812. break;
  5813. case 'shortstr':
  5814. if (typeof(param) != "string" || param.length > 0xFF) {
  5815. throw new Error("Unmatched field " + JSON.stringify(field));
  5816. }
  5817. serializer.serializeShortString(buffer, param);
  5818. break;
  5819. case 'longstr':
  5820. serializer.serializeLongString(buffer, param);
  5821. break;
  5822. case 'table':
  5823. if (typeof(param) != "object") {
  5824. throw new Error("Unmatched field " + JSON.stringify(field));
  5825. }
  5826. serializer.serializeTable(buffer, param);
  5827. break;
  5828. default:
  5829. throw new Error("Unknown domain value type " + domain);
  5830. }
  5831. }
  5832. }
  5833. };
  5834. }).call(this,_dereq_("buffer").Buffer)
  5835. },{"../jspack":25,"buffer":128}],38:[function(_dereq_,module,exports){
  5836. (function (global){
  5837. /**
  5838. * @license
  5839. * Lo-Dash 1.3.1 (Custom Build) <http://lodash.com/>
  5840. * Build: `lodash modern -o ./dist/lodash.js`
  5841. * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
  5842. * Based on Underscore.js 1.4.4 <http://underscorejs.org/>
  5843. * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud Inc.
  5844. * Available under MIT license <http://lodash.com/license>
  5845. */
  5846. ;(function(window) {
  5847. /** Used as a safe reference for `undefined` in pre ES5 environments */
  5848. var undefined;
  5849. /** Used to pool arrays and objects used internally */
  5850. var arrayPool = [],
  5851. objectPool = [];
  5852. /** Used to generate unique IDs */
  5853. var idCounter = 0;
  5854. /** Used internally to indicate various things */
  5855. var indicatorObject = {};
  5856. /** Used to prefix keys to avoid issues with `__proto__` and properties on `Object.prototype` */
  5857. var keyPrefix = +new Date + '';
  5858. /** Used as the size when optimizations are enabled for large arrays */
  5859. var largeArraySize = 75;
  5860. /** Used as the max size of the `arrayPool` and `objectPool` */
  5861. var maxPoolSize = 40;
  5862. /** Used to match empty string literals in compiled template source */
  5863. var reEmptyStringLeading = /\b__p \+= '';/g,
  5864. reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
  5865. reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
  5866. /** Used to match HTML entities */
  5867. var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g;
  5868. /**
  5869. * Used to match ES6 template delimiters
  5870. * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-7.8.6
  5871. */
  5872. var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
  5873. /** Used to match regexp flags from their coerced string values */
  5874. var reFlags = /\w*$/;
  5875. /** Used to match "interpolate" template delimiters */
  5876. var reInterpolate = /<%=([\s\S]+?)%>/g;
  5877. /** Used to detect functions containing a `this` reference */
  5878. var reThis = (reThis = /\bthis\b/) && reThis.test(runInContext) && reThis;
  5879. /** Used to detect and test whitespace */
  5880. var whitespace = (
  5881. // whitespace
  5882. ' \t\x0B\f\xA0\ufeff' +
  5883. // line terminators
  5884. '\n\r\u2028\u2029' +
  5885. // unicode category "Zs" space separators
  5886. '\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000'
  5887. );
  5888. /** Used to match leading whitespace and zeros to be removed */
  5889. var reLeadingSpacesAndZeros = RegExp('^[' + whitespace + ']*0+(?=.$)');
  5890. /** Used to ensure capturing order of template delimiters */
  5891. var reNoMatch = /($^)/;
  5892. /** Used to match HTML characters */
  5893. var reUnescapedHtml = /[&<>"']/g;
  5894. /** Used to match unescaped characters in compiled string literals */
  5895. var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g;
  5896. /** Used to assign default `context` object properties */
  5897. var contextProps = [
  5898. 'Array', 'Boolean', 'Date', 'Function', 'Math', 'Number', 'Object',
  5899. 'RegExp', 'String', '_', 'attachEvent', 'clearTimeout', 'isFinite', 'isNaN',
  5900. 'parseInt', 'setImmediate', 'setTimeout'
  5901. ];
  5902. /** Used to make template sourceURLs easier to identify */
  5903. var templateCounter = 0;
  5904. /** `Object#toString` result shortcuts */
  5905. var argsClass = '[object Arguments]',
  5906. arrayClass = '[object Array]',
  5907. boolClass = '[object Boolean]',
  5908. dateClass = '[object Date]',
  5909. errorClass = '[object Error]',
  5910. funcClass = '[object Function]',
  5911. numberClass = '[object Number]',
  5912. objectClass = '[object Object]',
  5913. regexpClass = '[object RegExp]',
  5914. stringClass = '[object String]';
  5915. /** Used to identify object classifications that `_.clone` supports */
  5916. var cloneableClasses = {};
  5917. cloneableClasses[funcClass] = false;
  5918. cloneableClasses[argsClass] = cloneableClasses[arrayClass] =
  5919. cloneableClasses[boolClass] = cloneableClasses[dateClass] =
  5920. cloneableClasses[numberClass] = cloneableClasses[objectClass] =
  5921. cloneableClasses[regexpClass] = cloneableClasses[stringClass] = true;
  5922. /** Used to determine if values are of the language type Object */
  5923. var objectTypes = {
  5924. 'boolean': false,
  5925. 'function': true,
  5926. 'object': true,
  5927. 'number': false,
  5928. 'string': false,
  5929. 'undefined': false
  5930. };
  5931. /** Used to escape characters for inclusion in compiled string literals */
  5932. var stringEscapes = {
  5933. '\\': '\\',
  5934. "'": "'",
  5935. '\n': 'n',
  5936. '\r': 'r',
  5937. '\t': 't',
  5938. '\u2028': 'u2028',
  5939. '\u2029': 'u2029'
  5940. };
  5941. /** Detect free variable `exports` */
  5942. var freeExports = objectTypes[typeof exports] && exports;
  5943. /** Detect free variable `module` */
  5944. var freeModule = objectTypes[typeof module] && module && module.exports == freeExports && module;
  5945. /** Detect free variable `global`, from Node.js or Browserified code, and use it as `window` */
  5946. var freeGlobal = objectTypes[typeof global] && global;
  5947. if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
  5948. window = freeGlobal;
  5949. }
  5950. /*--------------------------------------------------------------------------*/
  5951. /**
  5952. * A basic implementation of `_.indexOf` without support for binary searches
  5953. * or `fromIndex` constraints.
  5954. *
  5955. * @private
  5956. * @param {Array} array The array to search.
  5957. * @param {Mixed} value The value to search for.
  5958. * @param {Number} [fromIndex=0] The index to search from.
  5959. * @returns {Number} Returns the index of the matched value or `-1`.
  5960. */
  5961. function basicIndexOf(array, value, fromIndex) {
  5962. var index = (fromIndex || 0) - 1,
  5963. length = array.length;
  5964. while (++index < length) {
  5965. if (array[index] === value) {
  5966. return index;
  5967. }
  5968. }
  5969. return -1;
  5970. }
  5971. /**
  5972. * An implementation of `_.contains` for cache objects that mimics the return
  5973. * signature of `_.indexOf` by returning `0` if the value is found, else `-1`.
  5974. *
  5975. * @private
  5976. * @param {Object} cache The cache object to inspect.
  5977. * @param {Mixed} value The value to search for.
  5978. * @returns {Number} Returns `0` if `value` is found, else `-1`.
  5979. */
  5980. function cacheIndexOf(cache, value) {
  5981. var type = typeof value;
  5982. cache = cache.cache;
  5983. if (type == 'boolean' || value == null) {
  5984. return cache[value];
  5985. }
  5986. if (type != 'number' && type != 'string') {
  5987. type = 'object';
  5988. }
  5989. var key = type == 'number' ? value : keyPrefix + value;
  5990. cache = cache[type] || (cache[type] = {});
  5991. return type == 'object'
  5992. ? (cache[key] && basicIndexOf(cache[key], value) > -1 ? 0 : -1)
  5993. : (cache[key] ? 0 : -1);
  5994. }
  5995. /**
  5996. * Adds a given `value` to the corresponding cache object.
  5997. *
  5998. * @private
  5999. * @param {Mixed} value The value to add to the cache.
  6000. */
  6001. function cachePush(value) {
  6002. var cache = this.cache,
  6003. type = typeof value;
  6004. if (type == 'boolean' || value == null) {
  6005. cache[value] = true;
  6006. } else {
  6007. if (type != 'number' && type != 'string') {
  6008. type = 'object';
  6009. }
  6010. var key = type == 'number' ? value : keyPrefix + value,
  6011. typeCache = cache[type] || (cache[type] = {});
  6012. if (type == 'object') {
  6013. if ((typeCache[key] || (typeCache[key] = [])).push(value) == this.array.length) {
  6014. cache[type] = false;
  6015. }
  6016. } else {
  6017. typeCache[key] = true;
  6018. }
  6019. }
  6020. }
  6021. /**
  6022. * Used by `_.max` and `_.min` as the default `callback` when a given
  6023. * `collection` is a string value.
  6024. *
  6025. * @private
  6026. * @param {String} value The character to inspect.
  6027. * @returns {Number} Returns the code unit of given character.
  6028. */
  6029. function charAtCallback(value) {
  6030. return value.charCodeAt(0);
  6031. }
  6032. /**
  6033. * Used by `sortBy` to compare transformed `collection` values, stable sorting
  6034. * them in ascending order.
  6035. *
  6036. * @private
  6037. * @param {Object} a The object to compare to `b`.
  6038. * @param {Object} b The object to compare to `a`.
  6039. * @returns {Number} Returns the sort order indicator of `1` or `-1`.
  6040. */
  6041. function compareAscending(a, b) {
  6042. var ai = a.index,
  6043. bi = b.index;
  6044. a = a.criteria;
  6045. b = b.criteria;
  6046. // ensure a stable sort in V8 and other engines
  6047. // http://code.google.com/p/v8/issues/detail?id=90
  6048. if (a !== b) {
  6049. if (a > b || typeof a == 'undefined') {
  6050. return 1;
  6051. }
  6052. if (a < b || typeof b == 'undefined') {
  6053. return -1;
  6054. }
  6055. }
  6056. return ai < bi ? -1 : 1;
  6057. }
  6058. /**
  6059. * Creates a cache object to optimize linear searches of large arrays.
  6060. *
  6061. * @private
  6062. * @param {Array} [array=[]] The array to search.
  6063. * @returns {Null|Object} Returns the cache object or `null` if caching should not be used.
  6064. */
  6065. function createCache(array) {
  6066. var index = -1,
  6067. length = array.length;
  6068. var cache = getObject();
  6069. cache['false'] = cache['null'] = cache['true'] = cache['undefined'] = false;
  6070. var result = getObject();
  6071. result.array = array;
  6072. result.cache = cache;
  6073. result.push = cachePush;
  6074. while (++index < length) {
  6075. result.push(array[index]);
  6076. }
  6077. return cache.object === false
  6078. ? (releaseObject(result), null)
  6079. : result;
  6080. }
  6081. /**
  6082. * Used by `template` to escape characters for inclusion in compiled
  6083. * string literals.
  6084. *
  6085. * @private
  6086. * @param {String} match The matched character to escape.
  6087. * @returns {String} Returns the escaped character.
  6088. */
  6089. function escapeStringChar(match) {
  6090. return '\\' + stringEscapes[match];
  6091. }
  6092. /**
  6093. * Gets an array from the array pool or creates a new one if the pool is empty.
  6094. *
  6095. * @private
  6096. * @returns {Array} The array from the pool.
  6097. */
  6098. function getArray() {
  6099. return arrayPool.pop() || [];
  6100. }
  6101. /**
  6102. * Gets an object from the object pool or creates a new one if the pool is empty.
  6103. *
  6104. * @private
  6105. * @returns {Object} The object from the pool.
  6106. */
  6107. function getObject() {
  6108. return objectPool.pop() || {
  6109. 'array': null,
  6110. 'cache': null,
  6111. 'criteria': null,
  6112. 'false': false,
  6113. 'index': 0,
  6114. 'leading': false,
  6115. 'maxWait': 0,
  6116. 'null': false,
  6117. 'number': null,
  6118. 'object': null,
  6119. 'push': null,
  6120. 'string': null,
  6121. 'trailing': false,
  6122. 'true': false,
  6123. 'undefined': false,
  6124. 'value': null
  6125. };
  6126. }
  6127. /**
  6128. * A no-operation function.
  6129. *
  6130. * @private
  6131. */
  6132. function noop() {
  6133. // no operation performed
  6134. }
  6135. /**
  6136. * Releases the given `array` back to the array pool.
  6137. *
  6138. * @private
  6139. * @param {Array} [array] The array to release.
  6140. */
  6141. function releaseArray(array) {
  6142. array.length = 0;
  6143. if (arrayPool.length < maxPoolSize) {
  6144. arrayPool.push(array);
  6145. }
  6146. }
  6147. /**
  6148. * Releases the given `object` back to the object pool.
  6149. *
  6150. * @private
  6151. * @param {Object} [object] The object to release.
  6152. */
  6153. function releaseObject(object) {
  6154. var cache = object.cache;
  6155. if (cache) {
  6156. releaseObject(cache);
  6157. }
  6158. object.array = object.cache = object.criteria = object.object = object.number = object.string = object.value = null;
  6159. if (objectPool.length < maxPoolSize) {
  6160. objectPool.push(object);
  6161. }
  6162. }
  6163. /**
  6164. * Slices the `collection` from the `start` index up to, but not including,
  6165. * the `end` index.
  6166. *
  6167. * Note: This function is used, instead of `Array#slice`, to support node lists
  6168. * in IE < 9 and to ensure dense arrays are returned.
  6169. *
  6170. * @private
  6171. * @param {Array|Object|String} collection The collection to slice.
  6172. * @param {Number} start The start index.
  6173. * @param {Number} end The end index.
  6174. * @returns {Array} Returns the new array.
  6175. */
  6176. function slice(array, start, end) {
  6177. start || (start = 0);
  6178. if (typeof end == 'undefined') {
  6179. end = array ? array.length : 0;
  6180. }
  6181. var index = -1,
  6182. length = end - start || 0,
  6183. result = Array(length < 0 ? 0 : length);
  6184. while (++index < length) {
  6185. result[index] = array[start + index];
  6186. }
  6187. return result;
  6188. }
  6189. /*--------------------------------------------------------------------------*/
  6190. /**
  6191. * Create a new `lodash` function using the given `context` object.
  6192. *
  6193. * @static
  6194. * @memberOf _
  6195. * @category Utilities
  6196. * @param {Object} [context=window] The context object.
  6197. * @returns {Function} Returns the `lodash` function.
  6198. */
  6199. function runInContext(context) {
  6200. // Avoid issues with some ES3 environments that attempt to use values, named
  6201. // after built-in constructors like `Object`, for the creation of literals.
  6202. // ES5 clears this up by stating that literals must use built-in constructors.
  6203. // See http://es5.github.com/#x11.1.5.
  6204. context = context ? _.defaults(window.Object(), context, _.pick(window, contextProps)) : window;
  6205. /** Native constructor references */
  6206. var Array = context.Array,
  6207. Boolean = context.Boolean,
  6208. Date = context.Date,
  6209. Function = context.Function,
  6210. Math = context.Math,
  6211. Number = context.Number,
  6212. Object = context.Object,
  6213. RegExp = context.RegExp,
  6214. String = context.String,
  6215. TypeError = context.TypeError;
  6216. /**
  6217. * Used for `Array` method references.
  6218. *
  6219. * Normally `Array.prototype` would suffice, however, using an array literal
  6220. * avoids issues in Narwhal.
  6221. */
  6222. var arrayRef = [];
  6223. /** Used for native method references */
  6224. var objectProto = Object.prototype,
  6225. stringProto = String.prototype;
  6226. /** Used to restore the original `_` reference in `noConflict` */
  6227. var oldDash = context._;
  6228. /** Used to detect if a method is native */
  6229. var reNative = RegExp('^' +
  6230. String(objectProto.valueOf)
  6231. .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
  6232. .replace(/valueOf|for [^\]]+/g, '.+?') + '$'
  6233. );
  6234. /** Native method shortcuts */
  6235. var ceil = Math.ceil,
  6236. clearTimeout = context.clearTimeout,
  6237. concat = arrayRef.concat,
  6238. floor = Math.floor,
  6239. fnToString = Function.prototype.toString,
  6240. getPrototypeOf = reNative.test(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf,
  6241. hasOwnProperty = objectProto.hasOwnProperty,
  6242. push = arrayRef.push,
  6243. propertyIsEnumerable = objectProto.propertyIsEnumerable,
  6244. setImmediate = context.setImmediate,
  6245. setTimeout = context.setTimeout,
  6246. toString = objectProto.toString;
  6247. /* Native method shortcuts for methods with the same name as other `lodash` methods */
  6248. var nativeBind = reNative.test(nativeBind = toString.bind) && nativeBind,
  6249. nativeCreate = reNative.test(nativeCreate = Object.create) && nativeCreate,
  6250. nativeIsArray = reNative.test(nativeIsArray = Array.isArray) && nativeIsArray,
  6251. nativeIsFinite = context.isFinite,
  6252. nativeIsNaN = context.isNaN,
  6253. nativeKeys = reNative.test(nativeKeys = Object.keys) && nativeKeys,
  6254. nativeMax = Math.max,
  6255. nativeMin = Math.min,
  6256. nativeParseInt = context.parseInt,
  6257. nativeRandom = Math.random,
  6258. nativeSlice = arrayRef.slice;
  6259. /** Detect various environments */
  6260. var isIeOpera = reNative.test(context.attachEvent),
  6261. isV8 = nativeBind && !/\n|true/.test(nativeBind + isIeOpera);
  6262. /** Used to lookup a built-in constructor by [[Class]] */
  6263. var ctorByClass = {};
  6264. ctorByClass[arrayClass] = Array;
  6265. ctorByClass[boolClass] = Boolean;
  6266. ctorByClass[dateClass] = Date;
  6267. ctorByClass[funcClass] = Function;
  6268. ctorByClass[objectClass] = Object;
  6269. ctorByClass[numberClass] = Number;
  6270. ctorByClass[regexpClass] = RegExp;
  6271. ctorByClass[stringClass] = String;
  6272. /*--------------------------------------------------------------------------*/
  6273. /**
  6274. * Creates a `lodash` object, which wraps the given `value`, to enable method
  6275. * chaining.
  6276. *
  6277. * In addition to Lo-Dash methods, wrappers also have the following `Array` methods:
  6278. * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`,
  6279. * and `unshift`
  6280. *
  6281. * Chaining is supported in custom builds as long as the `value` method is
  6282. * implicitly or explicitly included in the build.
  6283. *
  6284. * The chainable wrapper functions are:
  6285. * `after`, `assign`, `bind`, `bindAll`, `bindKey`, `chain`, `compact`,
  6286. * `compose`, `concat`, `countBy`, `createCallback`, `debounce`, `defaults`,
  6287. * `defer`, `delay`, `difference`, `filter`, `flatten`, `forEach`, `forIn`,
  6288. * `forOwn`, `functions`, `groupBy`, `initial`, `intersection`, `invert`,
  6289. * `invoke`, `keys`, `map`, `max`, `memoize`, `merge`, `min`, `object`, `omit`,
  6290. * `once`, `pairs`, `partial`, `partialRight`, `pick`, `pluck`, `push`, `range`,
  6291. * `reject`, `rest`, `reverse`, `shuffle`, `slice`, `sort`, `sortBy`, `splice`,
  6292. * `tap`, `throttle`, `times`, `toArray`, `transform`, `union`, `uniq`, `unshift`,
  6293. * `unzip`, `values`, `where`, `without`, `wrap`, and `zip`
  6294. *
  6295. * The non-chainable wrapper functions are:
  6296. * `clone`, `cloneDeep`, `contains`, `escape`, `every`, `find`, `has`,
  6297. * `identity`, `indexOf`, `isArguments`, `isArray`, `isBoolean`, `isDate`,
  6298. * `isElement`, `isEmpty`, `isEqual`, `isFinite`, `isFunction`, `isNaN`,
  6299. * `isNull`, `isNumber`, `isObject`, `isPlainObject`, `isRegExp`, `isString`,
  6300. * `isUndefined`, `join`, `lastIndexOf`, `mixin`, `noConflict`, `parseInt`,
  6301. * `pop`, `random`, `reduce`, `reduceRight`, `result`, `shift`, `size`, `some`,
  6302. * `sortedIndex`, `runInContext`, `template`, `unescape`, `uniqueId`, and `value`
  6303. *
  6304. * The wrapper functions `first` and `last` return wrapped values when `n` is
  6305. * passed, otherwise they return unwrapped values.
  6306. *
  6307. * @name _
  6308. * @constructor
  6309. * @alias chain
  6310. * @category Chaining
  6311. * @param {Mixed} value The value to wrap in a `lodash` instance.
  6312. * @returns {Object} Returns a `lodash` instance.
  6313. * @example
  6314. *
  6315. * var wrapped = _([1, 2, 3]);
  6316. *
  6317. * // returns an unwrapped value
  6318. * wrapped.reduce(function(sum, num) {
  6319. * return sum + num;
  6320. * });
  6321. * // => 6
  6322. *
  6323. * // returns a wrapped value
  6324. * var squares = wrapped.map(function(num) {
  6325. * return num * num;
  6326. * });
  6327. *
  6328. * _.isArray(squares);
  6329. * // => false
  6330. *
  6331. * _.isArray(squares.value());
  6332. * // => true
  6333. */
  6334. function lodash(value) {
  6335. // don't wrap if already wrapped, even if wrapped by a different `lodash` constructor
  6336. return (value && typeof value == 'object' && !isArray(value) && hasOwnProperty.call(value, '__wrapped__'))
  6337. ? value
  6338. : new lodashWrapper(value);
  6339. }
  6340. /**
  6341. * A fast path for creating `lodash` wrapper objects.
  6342. *
  6343. * @private
  6344. * @param {Mixed} value The value to wrap in a `lodash` instance.
  6345. * @returns {Object} Returns a `lodash` instance.
  6346. */
  6347. function lodashWrapper(value) {
  6348. this.__wrapped__ = value;
  6349. }
  6350. // ensure `new lodashWrapper` is an instance of `lodash`
  6351. lodashWrapper.prototype = lodash.prototype;
  6352. /**
  6353. * An object used to flag environments features.
  6354. *
  6355. * @static
  6356. * @memberOf _
  6357. * @type Object
  6358. */
  6359. var support = lodash.support = {};
  6360. /**
  6361. * Detect if `Function#bind` exists and is inferred to be fast (all but V8).
  6362. *
  6363. * @memberOf _.support
  6364. * @type Boolean
  6365. */
  6366. support.fastBind = nativeBind && !isV8;
  6367. /**
  6368. * By default, the template delimiters used by Lo-Dash are similar to those in
  6369. * embedded Ruby (ERB). Change the following template settings to use alternative
  6370. * delimiters.
  6371. *
  6372. * @static
  6373. * @memberOf _
  6374. * @type Object
  6375. */
  6376. lodash.templateSettings = {
  6377. /**
  6378. * Used to detect `data` property values to be HTML-escaped.
  6379. *
  6380. * @memberOf _.templateSettings
  6381. * @type RegExp
  6382. */
  6383. 'escape': /<%-([\s\S]+?)%>/g,
  6384. /**
  6385. * Used to detect code to be evaluated.
  6386. *
  6387. * @memberOf _.templateSettings
  6388. * @type RegExp
  6389. */
  6390. 'evaluate': /<%([\s\S]+?)%>/g,
  6391. /**
  6392. * Used to detect `data` property values to inject.
  6393. *
  6394. * @memberOf _.templateSettings
  6395. * @type RegExp
  6396. */
  6397. 'interpolate': reInterpolate,
  6398. /**
  6399. * Used to reference the data object in the template text.
  6400. *
  6401. * @memberOf _.templateSettings
  6402. * @type String
  6403. */
  6404. 'variable': '',
  6405. /**
  6406. * Used to import variables into the compiled template.
  6407. *
  6408. * @memberOf _.templateSettings
  6409. * @type Object
  6410. */
  6411. 'imports': {
  6412. /**
  6413. * A reference to the `lodash` function.
  6414. *
  6415. * @memberOf _.templateSettings.imports
  6416. * @type Function
  6417. */
  6418. '_': lodash
  6419. }
  6420. };
  6421. /*--------------------------------------------------------------------------*/
  6422. /**
  6423. * Creates a function that, when called, invokes `func` with the `this` binding
  6424. * of `thisArg` and prepends any `partialArgs` to the arguments passed to the
  6425. * bound function.
  6426. *
  6427. * @private
  6428. * @param {Function|String} func The function to bind or the method name.
  6429. * @param {Mixed} [thisArg] The `this` binding of `func`.
  6430. * @param {Array} partialArgs An array of arguments to be partially applied.
  6431. * @param {Object} [idicator] Used to indicate binding by key or partially
  6432. * applying arguments from the right.
  6433. * @returns {Function} Returns the new bound function.
  6434. */
  6435. function createBound(func, thisArg, partialArgs, indicator) {
  6436. var isFunc = isFunction(func),
  6437. isPartial = !partialArgs,
  6438. key = thisArg;
  6439. // juggle arguments
  6440. if (isPartial) {
  6441. var rightIndicator = indicator;
  6442. partialArgs = thisArg;
  6443. }
  6444. else if (!isFunc) {
  6445. if (!indicator) {
  6446. throw new TypeError;
  6447. }
  6448. thisArg = func;
  6449. }
  6450. function bound() {
  6451. // `Function#bind` spec
  6452. // http://es5.github.com/#x15.3.4.5
  6453. var args = arguments,
  6454. thisBinding = isPartial ? this : thisArg;
  6455. if (!isFunc) {
  6456. func = thisArg[key];
  6457. }
  6458. if (partialArgs.length) {
  6459. args = args.length
  6460. ? (args = nativeSlice.call(args), rightIndicator ? args.concat(partialArgs) : partialArgs.concat(args))
  6461. : partialArgs;
  6462. }
  6463. if (this instanceof bound) {
  6464. // ensure `new bound` is an instance of `func`
  6465. thisBinding = createObject(func.prototype);
  6466. // mimic the constructor's `return` behavior
  6467. // http://es5.github.com/#x13.2.2
  6468. var result = func.apply(thisBinding, args);
  6469. return isObject(result) ? result : thisBinding;
  6470. }
  6471. return func.apply(thisBinding, args);
  6472. }
  6473. return bound;
  6474. }
  6475. /**
  6476. * Creates a new object with the specified `prototype`.
  6477. *
  6478. * @private
  6479. * @param {Object} prototype The prototype object.
  6480. * @returns {Object} Returns the new object.
  6481. */
  6482. function createObject(prototype) {
  6483. return isObject(prototype) ? nativeCreate(prototype) : {};
  6484. }
  6485. /**
  6486. * Used by `escape` to convert characters to HTML entities.
  6487. *
  6488. * @private
  6489. * @param {String} match The matched character to escape.
  6490. * @returns {String} Returns the escaped character.
  6491. */
  6492. function escapeHtmlChar(match) {
  6493. return htmlEscapes[match];
  6494. }
  6495. /**
  6496. * Gets the appropriate "indexOf" function. If the `_.indexOf` method is
  6497. * customized, this method returns the custom method, otherwise it returns
  6498. * the `basicIndexOf` function.
  6499. *
  6500. * @private
  6501. * @returns {Function} Returns the "indexOf" function.
  6502. */
  6503. function getIndexOf(array, value, fromIndex) {
  6504. var result = (result = lodash.indexOf) === indexOf ? basicIndexOf : result;
  6505. return result;
  6506. }
  6507. /**
  6508. * Creates a function that juggles arguments, allowing argument overloading
  6509. * for `_.flatten` and `_.uniq`, before passing them to the given `func`.
  6510. *
  6511. * @private
  6512. * @param {Function} func The function to wrap.
  6513. * @returns {Function} Returns the new function.
  6514. */
  6515. function overloadWrapper(func) {
  6516. return function(array, flag, callback, thisArg) {
  6517. // juggle arguments
  6518. if (typeof flag != 'boolean' && flag != null) {
  6519. thisArg = callback;
  6520. callback = !(thisArg && thisArg[flag] === array) ? flag : undefined;
  6521. flag = false;
  6522. }
  6523. if (callback != null) {
  6524. callback = lodash.createCallback(callback, thisArg);
  6525. }
  6526. return func(array, flag, callback, thisArg);
  6527. };
  6528. }
  6529. /**
  6530. * A fallback implementation of `isPlainObject` which checks if a given `value`
  6531. * is an object created by the `Object` constructor, assuming objects created
  6532. * by the `Object` constructor have no inherited enumerable properties and that
  6533. * there are no `Object.prototype` extensions.
  6534. *
  6535. * @private
  6536. * @param {Mixed} value The value to check.
  6537. * @returns {Boolean} Returns `true`, if `value` is a plain object, else `false`.
  6538. */
  6539. function shimIsPlainObject(value) {
  6540. var ctor,
  6541. result;
  6542. // avoid non Object objects, `arguments` objects, and DOM elements
  6543. if (!(value && toString.call(value) == objectClass) ||
  6544. (ctor = value.constructor, isFunction(ctor) && !(ctor instanceof ctor))) {
  6545. return false;
  6546. }
  6547. // In most environments an object's own properties are iterated before
  6548. // its inherited properties. If the last iterated property is an object's
  6549. // own property then there are no inherited enumerable properties.
  6550. forIn(value, function(value, key) {
  6551. result = key;
  6552. });
  6553. return result === undefined || hasOwnProperty.call(value, result);
  6554. }
  6555. /**
  6556. * Used by `unescape` to convert HTML entities to characters.
  6557. *
  6558. * @private
  6559. * @param {String} match The matched character to unescape.
  6560. * @returns {String} Returns the unescaped character.
  6561. */
  6562. function unescapeHtmlChar(match) {
  6563. return htmlUnescapes[match];
  6564. }
  6565. /*--------------------------------------------------------------------------*/
  6566. /**
  6567. * Checks if `value` is an `arguments` object.
  6568. *
  6569. * @static
  6570. * @memberOf _
  6571. * @category Objects
  6572. * @param {Mixed} value The value to check.
  6573. * @returns {Boolean} Returns `true`, if the `value` is an `arguments` object, else `false`.
  6574. * @example
  6575. *
  6576. * (function() { return _.isArguments(arguments); })(1, 2, 3);
  6577. * // => true
  6578. *
  6579. * _.isArguments([1, 2, 3]);
  6580. * // => false
  6581. */
  6582. function isArguments(value) {
  6583. return toString.call(value) == argsClass;
  6584. }
  6585. /**
  6586. * Checks if `value` is an array.
  6587. *
  6588. * @static
  6589. * @memberOf _
  6590. * @category Objects
  6591. * @param {Mixed} value The value to check.
  6592. * @returns {Boolean} Returns `true`, if the `value` is an array, else `false`.
  6593. * @example
  6594. *
  6595. * (function() { return _.isArray(arguments); })();
  6596. * // => false
  6597. *
  6598. * _.isArray([1, 2, 3]);
  6599. * // => true
  6600. */
  6601. var isArray = nativeIsArray;
  6602. /**
  6603. * A fallback implementation of `Object.keys` which produces an array of the
  6604. * given object's own enumerable property names.
  6605. *
  6606. * @private
  6607. * @type Function
  6608. * @param {Object} object The object to inspect.
  6609. * @returns {Array} Returns a new array of property names.
  6610. */
  6611. var shimKeys = function (object) {
  6612. var index, iterable = object, result = [];
  6613. if (!iterable) return result;
  6614. if (!(objectTypes[typeof object])) return result;
  6615. for (index in iterable) {
  6616. if (hasOwnProperty.call(iterable, index)) {
  6617. result.push(index);
  6618. }
  6619. }
  6620. return result
  6621. };
  6622. /**
  6623. * Creates an array composed of the own enumerable property names of `object`.
  6624. *
  6625. * @static
  6626. * @memberOf _
  6627. * @category Objects
  6628. * @param {Object} object The object to inspect.
  6629. * @returns {Array} Returns a new array of property names.
  6630. * @example
  6631. *
  6632. * _.keys({ 'one': 1, 'two': 2, 'three': 3 });
  6633. * // => ['one', 'two', 'three'] (order is not guaranteed)
  6634. */
  6635. var keys = !nativeKeys ? shimKeys : function(object) {
  6636. if (!isObject(object)) {
  6637. return [];
  6638. }
  6639. return nativeKeys(object);
  6640. };
  6641. /**
  6642. * Used to convert characters to HTML entities:
  6643. *
  6644. * Though the `>` character is escaped for symmetry, characters like `>` and `/`
  6645. * don't require escaping in HTML and have no special meaning unless they're part
  6646. * of a tag or an unquoted attribute value.
  6647. * http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact")
  6648. */
  6649. var htmlEscapes = {
  6650. '&': '&amp;',
  6651. '<': '&lt;',
  6652. '>': '&gt;',
  6653. '"': '&quot;',
  6654. "'": '&#39;'
  6655. };
  6656. /** Used to convert HTML entities to characters */
  6657. var htmlUnescapes = invert(htmlEscapes);
  6658. /*--------------------------------------------------------------------------*/
  6659. /**
  6660. * Assigns own enumerable properties of source object(s) to the destination
  6661. * object. Subsequent sources will overwrite property assignments of previous
  6662. * sources. If a `callback` function is passed, it will be executed to produce
  6663. * the assigned values. The `callback` is bound to `thisArg` and invoked with
  6664. * two arguments; (objectValue, sourceValue).
  6665. *
  6666. * @static
  6667. * @memberOf _
  6668. * @type Function
  6669. * @alias extend
  6670. * @category Objects
  6671. * @param {Object} object The destination object.
  6672. * @param {Object} [source1, source2, ...] The source objects.
  6673. * @param {Function} [callback] The function to customize assigning values.
  6674. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  6675. * @returns {Object} Returns the destination object.
  6676. * @example
  6677. *
  6678. * _.assign({ 'name': 'moe' }, { 'age': 40 });
  6679. * // => { 'name': 'moe', 'age': 40 }
  6680. *
  6681. * var defaults = _.partialRight(_.assign, function(a, b) {
  6682. * return typeof a == 'undefined' ? b : a;
  6683. * });
  6684. *
  6685. * var food = { 'name': 'apple' };
  6686. * defaults(food, { 'name': 'banana', 'type': 'fruit' });
  6687. * // => { 'name': 'apple', 'type': 'fruit' }
  6688. */
  6689. var assign = function (object, source, guard) {
  6690. var index, iterable = object, result = iterable;
  6691. if (!iterable) return result;
  6692. var args = arguments,
  6693. argsIndex = 0,
  6694. argsLength = typeof guard == 'number' ? 2 : args.length;
  6695. if (argsLength > 3 && typeof args[argsLength - 2] == 'function') {
  6696. var callback = lodash.createCallback(args[--argsLength - 1], args[argsLength--], 2);
  6697. } else if (argsLength > 2 && typeof args[argsLength - 1] == 'function') {
  6698. callback = args[--argsLength];
  6699. }
  6700. while (++argsIndex < argsLength) {
  6701. iterable = args[argsIndex];
  6702. if (iterable && objectTypes[typeof iterable]) {
  6703. var ownIndex = -1,
  6704. ownProps = objectTypes[typeof iterable] && keys(iterable),
  6705. length = ownProps ? ownProps.length : 0;
  6706. while (++ownIndex < length) {
  6707. index = ownProps[ownIndex];
  6708. result[index] = callback ? callback(result[index], iterable[index]) : iterable[index];
  6709. }
  6710. }
  6711. }
  6712. return result
  6713. };
  6714. /**
  6715. * Creates a clone of `value`. If `deep` is `true`, nested objects will also
  6716. * be cloned, otherwise they will be assigned by reference. If a `callback`
  6717. * function is passed, it will be executed to produce the cloned values. If
  6718. * `callback` returns `undefined`, cloning will be handled by the method instead.
  6719. * The `callback` is bound to `thisArg` and invoked with one argument; (value).
  6720. *
  6721. * @static
  6722. * @memberOf _
  6723. * @category Objects
  6724. * @param {Mixed} value The value to clone.
  6725. * @param {Boolean} [deep=false] A flag to indicate a deep clone.
  6726. * @param {Function} [callback] The function to customize cloning values.
  6727. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  6728. * @param- {Array} [stackA=[]] Tracks traversed source objects.
  6729. * @param- {Array} [stackB=[]] Associates clones with source counterparts.
  6730. * @returns {Mixed} Returns the cloned `value`.
  6731. * @example
  6732. *
  6733. * var stooges = [
  6734. * { 'name': 'moe', 'age': 40 },
  6735. * { 'name': 'larry', 'age': 50 }
  6736. * ];
  6737. *
  6738. * var shallow = _.clone(stooges);
  6739. * shallow[0] === stooges[0];
  6740. * // => true
  6741. *
  6742. * var deep = _.clone(stooges, true);
  6743. * deep[0] === stooges[0];
  6744. * // => false
  6745. *
  6746. * _.mixin({
  6747. * 'clone': _.partialRight(_.clone, function(value) {
  6748. * return _.isElement(value) ? value.cloneNode(false) : undefined;
  6749. * })
  6750. * });
  6751. *
  6752. * var clone = _.clone(document.body);
  6753. * clone.childNodes.length;
  6754. * // => 0
  6755. */
  6756. function clone(value, deep, callback, thisArg, stackA, stackB) {
  6757. var result = value;
  6758. // allows working with "Collections" methods without using their `callback`
  6759. // argument, `index|key`, for this method's `callback`
  6760. if (typeof deep != 'boolean' && deep != null) {
  6761. thisArg = callback;
  6762. callback = deep;
  6763. deep = false;
  6764. }
  6765. if (typeof callback == 'function') {
  6766. callback = (typeof thisArg == 'undefined')
  6767. ? callback
  6768. : lodash.createCallback(callback, thisArg, 1);
  6769. result = callback(result);
  6770. if (typeof result != 'undefined') {
  6771. return result;
  6772. }
  6773. result = value;
  6774. }
  6775. // inspect [[Class]]
  6776. var isObj = isObject(result);
  6777. if (isObj) {
  6778. var className = toString.call(result);
  6779. if (!cloneableClasses[className]) {
  6780. return result;
  6781. }
  6782. var isArr = isArray(result);
  6783. }
  6784. // shallow clone
  6785. if (!isObj || !deep) {
  6786. return isObj
  6787. ? (isArr ? slice(result) : assign({}, result))
  6788. : result;
  6789. }
  6790. var ctor = ctorByClass[className];
  6791. switch (className) {
  6792. case boolClass:
  6793. case dateClass:
  6794. return new ctor(+result);
  6795. case numberClass:
  6796. case stringClass:
  6797. return new ctor(result);
  6798. case regexpClass:
  6799. return ctor(result.source, reFlags.exec(result));
  6800. }
  6801. // check for circular references and return corresponding clone
  6802. var initedStack = !stackA;
  6803. stackA || (stackA = getArray());
  6804. stackB || (stackB = getArray());
  6805. var length = stackA.length;
  6806. while (length--) {
  6807. if (stackA[length] == value) {
  6808. return stackB[length];
  6809. }
  6810. }
  6811. // init cloned object
  6812. result = isArr ? ctor(result.length) : {};
  6813. // add array properties assigned by `RegExp#exec`
  6814. if (isArr) {
  6815. if (hasOwnProperty.call(value, 'index')) {
  6816. result.index = value.index;
  6817. }
  6818. if (hasOwnProperty.call(value, 'input')) {
  6819. result.input = value.input;
  6820. }
  6821. }
  6822. // add the source value to the stack of traversed objects
  6823. // and associate it with its clone
  6824. stackA.push(value);
  6825. stackB.push(result);
  6826. // recursively populate clone (susceptible to call stack limits)
  6827. (isArr ? forEach : forOwn)(value, function(objValue, key) {
  6828. result[key] = clone(objValue, deep, callback, undefined, stackA, stackB);
  6829. });
  6830. if (initedStack) {
  6831. releaseArray(stackA);
  6832. releaseArray(stackB);
  6833. }
  6834. return result;
  6835. }
  6836. /**
  6837. * Creates a deep clone of `value`. If a `callback` function is passed,
  6838. * it will be executed to produce the cloned values. If `callback` returns
  6839. * `undefined`, cloning will be handled by the method instead. The `callback`
  6840. * is bound to `thisArg` and invoked with one argument; (value).
  6841. *
  6842. * Note: This method is loosely based on the structured clone algorithm. Functions
  6843. * and DOM nodes are **not** cloned. The enumerable properties of `arguments` objects and
  6844. * objects created by constructors other than `Object` are cloned to plain `Object` objects.
  6845. * See http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm.
  6846. *
  6847. * @static
  6848. * @memberOf _
  6849. * @category Objects
  6850. * @param {Mixed} value The value to deep clone.
  6851. * @param {Function} [callback] The function to customize cloning values.
  6852. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  6853. * @returns {Mixed} Returns the deep cloned `value`.
  6854. * @example
  6855. *
  6856. * var stooges = [
  6857. * { 'name': 'moe', 'age': 40 },
  6858. * { 'name': 'larry', 'age': 50 }
  6859. * ];
  6860. *
  6861. * var deep = _.cloneDeep(stooges);
  6862. * deep[0] === stooges[0];
  6863. * // => false
  6864. *
  6865. * var view = {
  6866. * 'label': 'docs',
  6867. * 'node': element
  6868. * };
  6869. *
  6870. * var clone = _.cloneDeep(view, function(value) {
  6871. * return _.isElement(value) ? value.cloneNode(true) : undefined;
  6872. * });
  6873. *
  6874. * clone.node == view.node;
  6875. * // => false
  6876. */
  6877. function cloneDeep(value, callback, thisArg) {
  6878. return clone(value, true, callback, thisArg);
  6879. }
  6880. /**
  6881. * Assigns own enumerable properties of source object(s) to the destination
  6882. * object for all destination properties that resolve to `undefined`. Once a
  6883. * property is set, additional defaults of the same property will be ignored.
  6884. *
  6885. * @static
  6886. * @memberOf _
  6887. * @type Function
  6888. * @category Objects
  6889. * @param {Object} object The destination object.
  6890. * @param {Object} [source1, source2, ...] The source objects.
  6891. * @param- {Object} [guard] Allows working with `_.reduce` without using its
  6892. * callback's `key` and `object` arguments as sources.
  6893. * @returns {Object} Returns the destination object.
  6894. * @example
  6895. *
  6896. * var food = { 'name': 'apple' };
  6897. * _.defaults(food, { 'name': 'banana', 'type': 'fruit' });
  6898. * // => { 'name': 'apple', 'type': 'fruit' }
  6899. */
  6900. var defaults = function (object, source, guard) {
  6901. var index, iterable = object, result = iterable;
  6902. if (!iterable) return result;
  6903. var args = arguments,
  6904. argsIndex = 0,
  6905. argsLength = typeof guard == 'number' ? 2 : args.length;
  6906. while (++argsIndex < argsLength) {
  6907. iterable = args[argsIndex];
  6908. if (iterable && objectTypes[typeof iterable]) {
  6909. var ownIndex = -1,
  6910. ownProps = objectTypes[typeof iterable] && keys(iterable),
  6911. length = ownProps ? ownProps.length : 0;
  6912. while (++ownIndex < length) {
  6913. index = ownProps[ownIndex];
  6914. if (typeof result[index] == 'undefined') result[index] = iterable[index];
  6915. }
  6916. }
  6917. }
  6918. return result
  6919. };
  6920. /**
  6921. * This method is similar to `_.find`, except that it returns the key of the
  6922. * element that passes the callback check, instead of the element itself.
  6923. *
  6924. * @static
  6925. * @memberOf _
  6926. * @category Objects
  6927. * @param {Object} object The object to search.
  6928. * @param {Function|Object|String} [callback=identity] The function called per
  6929. * iteration. If a property name or object is passed, it will be used to create
  6930. * a "_.pluck" or "_.where" style callback, respectively.
  6931. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  6932. * @returns {Mixed} Returns the key of the found element, else `undefined`.
  6933. * @example
  6934. *
  6935. * _.findKey({ 'a': 1, 'b': 2, 'c': 3, 'd': 4 }, function(num) {
  6936. * return num % 2 == 0;
  6937. * });
  6938. * // => 'b'
  6939. */
  6940. function findKey(object, callback, thisArg) {
  6941. var result;
  6942. callback = lodash.createCallback(callback, thisArg);
  6943. forOwn(object, function(value, key, object) {
  6944. if (callback(value, key, object)) {
  6945. result = key;
  6946. return false;
  6947. }
  6948. });
  6949. return result;
  6950. }
  6951. /**
  6952. * Iterates over `object`'s own and inherited enumerable properties, executing
  6953. * the `callback` for each property. The `callback` is bound to `thisArg` and
  6954. * invoked with three arguments; (value, key, object). Callbacks may exit iteration
  6955. * early by explicitly returning `false`.
  6956. *
  6957. * @static
  6958. * @memberOf _
  6959. * @type Function
  6960. * @category Objects
  6961. * @param {Object} object The object to iterate over.
  6962. * @param {Function} [callback=identity] The function called per iteration.
  6963. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  6964. * @returns {Object} Returns `object`.
  6965. * @example
  6966. *
  6967. * function Dog(name) {
  6968. * this.name = name;
  6969. * }
  6970. *
  6971. * Dog.prototype.bark = function() {
  6972. * alert('Woof, woof!');
  6973. * };
  6974. *
  6975. * _.forIn(new Dog('Dagny'), function(value, key) {
  6976. * alert(key);
  6977. * });
  6978. * // => alerts 'name' and 'bark' (order is not guaranteed)
  6979. */
  6980. var forIn = function (collection, callback, thisArg) {
  6981. var index, iterable = collection, result = iterable;
  6982. if (!iterable) return result;
  6983. if (!objectTypes[typeof iterable]) return result;
  6984. callback = callback && typeof thisArg == 'undefined' ? callback : lodash.createCallback(callback, thisArg);
  6985. for (index in iterable) {
  6986. if (callback(iterable[index], index, collection) === false) return result;
  6987. }
  6988. return result
  6989. };
  6990. /**
  6991. * Iterates over an object's own enumerable properties, executing the `callback`
  6992. * for each property. The `callback` is bound to `thisArg` and invoked with three
  6993. * arguments; (value, key, object). Callbacks may exit iteration early by explicitly
  6994. * returning `false`.
  6995. *
  6996. * @static
  6997. * @memberOf _
  6998. * @type Function
  6999. * @category Objects
  7000. * @param {Object} object The object to iterate over.
  7001. * @param {Function} [callback=identity] The function called per iteration.
  7002. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  7003. * @returns {Object} Returns `object`.
  7004. * @example
  7005. *
  7006. * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
  7007. * alert(key);
  7008. * });
  7009. * // => alerts '0', '1', and 'length' (order is not guaranteed)
  7010. */
  7011. var forOwn = function (collection, callback, thisArg) {
  7012. var index, iterable = collection, result = iterable;
  7013. if (!iterable) return result;
  7014. if (!objectTypes[typeof iterable]) return result;
  7015. callback = callback && typeof thisArg == 'undefined' ? callback : lodash.createCallback(callback, thisArg);
  7016. var ownIndex = -1,
  7017. ownProps = objectTypes[typeof iterable] && keys(iterable),
  7018. length = ownProps ? ownProps.length : 0;
  7019. while (++ownIndex < length) {
  7020. index = ownProps[ownIndex];
  7021. if (callback(iterable[index], index, collection) === false) return result;
  7022. }
  7023. return result
  7024. };
  7025. /**
  7026. * Creates a sorted array of all enumerable properties, own and inherited,
  7027. * of `object` that have function values.
  7028. *
  7029. * @static
  7030. * @memberOf _
  7031. * @alias methods
  7032. * @category Objects
  7033. * @param {Object} object The object to inspect.
  7034. * @returns {Array} Returns a new array of property names that have function values.
  7035. * @example
  7036. *
  7037. * _.functions(_);
  7038. * // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...]
  7039. */
  7040. function functions(object) {
  7041. var result = [];
  7042. forIn(object, function(value, key) {
  7043. if (isFunction(value)) {
  7044. result.push(key);
  7045. }
  7046. });
  7047. return result.sort();
  7048. }
  7049. /**
  7050. * Checks if the specified object `property` exists and is a direct property,
  7051. * instead of an inherited property.
  7052. *
  7053. * @static
  7054. * @memberOf _
  7055. * @category Objects
  7056. * @param {Object} object The object to check.
  7057. * @param {String} property The property to check for.
  7058. * @returns {Boolean} Returns `true` if key is a direct property, else `false`.
  7059. * @example
  7060. *
  7061. * _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b');
  7062. * // => true
  7063. */
  7064. function has(object, property) {
  7065. return object ? hasOwnProperty.call(object, property) : false;
  7066. }
  7067. /**
  7068. * Creates an object composed of the inverted keys and values of the given `object`.
  7069. *
  7070. * @static
  7071. * @memberOf _
  7072. * @category Objects
  7073. * @param {Object} object The object to invert.
  7074. * @returns {Object} Returns the created inverted object.
  7075. * @example
  7076. *
  7077. * _.invert({ 'first': 'moe', 'second': 'larry' });
  7078. * // => { 'moe': 'first', 'larry': 'second' }
  7079. */
  7080. function invert(object) {
  7081. var index = -1,
  7082. props = keys(object),
  7083. length = props.length,
  7084. result = {};
  7085. while (++index < length) {
  7086. var key = props[index];
  7087. result[object[key]] = key;
  7088. }
  7089. return result;
  7090. }
  7091. /**
  7092. * Checks if `value` is a boolean value.
  7093. *
  7094. * @static
  7095. * @memberOf _
  7096. * @category Objects
  7097. * @param {Mixed} value The value to check.
  7098. * @returns {Boolean} Returns `true`, if the `value` is a boolean value, else `false`.
  7099. * @example
  7100. *
  7101. * _.isBoolean(null);
  7102. * // => false
  7103. */
  7104. function isBoolean(value) {
  7105. return value === true || value === false || toString.call(value) == boolClass;
  7106. }
  7107. /**
  7108. * Checks if `value` is a date.
  7109. *
  7110. * @static
  7111. * @memberOf _
  7112. * @category Objects
  7113. * @param {Mixed} value The value to check.
  7114. * @returns {Boolean} Returns `true`, if the `value` is a date, else `false`.
  7115. * @example
  7116. *
  7117. * _.isDate(new Date);
  7118. * // => true
  7119. */
  7120. function isDate(value) {
  7121. return value ? (typeof value == 'object' && toString.call(value) == dateClass) : false;
  7122. }
  7123. /**
  7124. * Checks if `value` is a DOM element.
  7125. *
  7126. * @static
  7127. * @memberOf _
  7128. * @category Objects
  7129. * @param {Mixed} value The value to check.
  7130. * @returns {Boolean} Returns `true`, if the `value` is a DOM element, else `false`.
  7131. * @example
  7132. *
  7133. * _.isElement(document.body);
  7134. * // => true
  7135. */
  7136. function isElement(value) {
  7137. return value ? value.nodeType === 1 : false;
  7138. }
  7139. /**
  7140. * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a
  7141. * length of `0` and objects with no own enumerable properties are considered
  7142. * "empty".
  7143. *
  7144. * @static
  7145. * @memberOf _
  7146. * @category Objects
  7147. * @param {Array|Object|String} value The value to inspect.
  7148. * @returns {Boolean} Returns `true`, if the `value` is empty, else `false`.
  7149. * @example
  7150. *
  7151. * _.isEmpty([1, 2, 3]);
  7152. * // => false
  7153. *
  7154. * _.isEmpty({});
  7155. * // => true
  7156. *
  7157. * _.isEmpty('');
  7158. * // => true
  7159. */
  7160. function isEmpty(value) {
  7161. var result = true;
  7162. if (!value) {
  7163. return result;
  7164. }
  7165. var className = toString.call(value),
  7166. length = value.length;
  7167. if ((className == arrayClass || className == stringClass || className == argsClass ) ||
  7168. (className == objectClass && typeof length == 'number' && isFunction(value.splice))) {
  7169. return !length;
  7170. }
  7171. forOwn(value, function() {
  7172. return (result = false);
  7173. });
  7174. return result;
  7175. }
  7176. /**
  7177. * Performs a deep comparison between two values to determine if they are
  7178. * equivalent to each other. If `callback` is passed, it will be executed to
  7179. * compare values. If `callback` returns `undefined`, comparisons will be handled
  7180. * by the method instead. The `callback` is bound to `thisArg` and invoked with
  7181. * two arguments; (a, b).
  7182. *
  7183. * @static
  7184. * @memberOf _
  7185. * @category Objects
  7186. * @param {Mixed} a The value to compare.
  7187. * @param {Mixed} b The other value to compare.
  7188. * @param {Function} [callback] The function to customize comparing values.
  7189. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  7190. * @param- {Array} [stackA=[]] Tracks traversed `a` objects.
  7191. * @param- {Array} [stackB=[]] Tracks traversed `b` objects.
  7192. * @returns {Boolean} Returns `true`, if the values are equivalent, else `false`.
  7193. * @example
  7194. *
  7195. * var moe = { 'name': 'moe', 'age': 40 };
  7196. * var copy = { 'name': 'moe', 'age': 40 };
  7197. *
  7198. * moe == copy;
  7199. * // => false
  7200. *
  7201. * _.isEqual(moe, copy);
  7202. * // => true
  7203. *
  7204. * var words = ['hello', 'goodbye'];
  7205. * var otherWords = ['hi', 'goodbye'];
  7206. *
  7207. * _.isEqual(words, otherWords, function(a, b) {
  7208. * var reGreet = /^(?:hello|hi)$/i,
  7209. * aGreet = _.isString(a) && reGreet.test(a),
  7210. * bGreet = _.isString(b) && reGreet.test(b);
  7211. *
  7212. * return (aGreet || bGreet) ? (aGreet == bGreet) : undefined;
  7213. * });
  7214. * // => true
  7215. */
  7216. function isEqual(a, b, callback, thisArg, stackA, stackB) {
  7217. // used to indicate that when comparing objects, `a` has at least the properties of `b`
  7218. var whereIndicator = callback === indicatorObject;
  7219. if (typeof callback == 'function' && !whereIndicator) {
  7220. callback = lodash.createCallback(callback, thisArg, 2);
  7221. var result = callback(a, b);
  7222. if (typeof result != 'undefined') {
  7223. return !!result;
  7224. }
  7225. }
  7226. // exit early for identical values
  7227. if (a === b) {
  7228. // treat `+0` vs. `-0` as not equal
  7229. return a !== 0 || (1 / a == 1 / b);
  7230. }
  7231. var type = typeof a,
  7232. otherType = typeof b;
  7233. // exit early for unlike primitive values
  7234. if (a === a &&
  7235. (!a || (type != 'function' && type != 'object')) &&
  7236. (!b || (otherType != 'function' && otherType != 'object'))) {
  7237. return false;
  7238. }
  7239. // exit early for `null` and `undefined`, avoiding ES3's Function#call behavior
  7240. // http://es5.github.com/#x15.3.4.4
  7241. if (a == null || b == null) {
  7242. return a === b;
  7243. }
  7244. // compare [[Class]] names
  7245. var className = toString.call(a),
  7246. otherClass = toString.call(b);
  7247. if (className == argsClass) {
  7248. className = objectClass;
  7249. }
  7250. if (otherClass == argsClass) {
  7251. otherClass = objectClass;
  7252. }
  7253. if (className != otherClass) {
  7254. return false;
  7255. }
  7256. switch (className) {
  7257. case boolClass:
  7258. case dateClass:
  7259. // coerce dates and booleans to numbers, dates to milliseconds and booleans
  7260. // to `1` or `0`, treating invalid dates coerced to `NaN` as not equal
  7261. return +a == +b;
  7262. case numberClass:
  7263. // treat `NaN` vs. `NaN` as equal
  7264. return (a != +a)
  7265. ? b != +b
  7266. // but treat `+0` vs. `-0` as not equal
  7267. : (a == 0 ? (1 / a == 1 / b) : a == +b);
  7268. case regexpClass:
  7269. case stringClass:
  7270. // coerce regexes to strings (http://es5.github.com/#x15.10.6.4)
  7271. // treat string primitives and their corresponding object instances as equal
  7272. return a == String(b);
  7273. }
  7274. var isArr = className == arrayClass;
  7275. if (!isArr) {
  7276. // unwrap any `lodash` wrapped values
  7277. if (hasOwnProperty.call(a, '__wrapped__ ') || hasOwnProperty.call(b, '__wrapped__')) {
  7278. return isEqual(a.__wrapped__ || a, b.__wrapped__ || b, callback, thisArg, stackA, stackB);
  7279. }
  7280. // exit for functions and DOM nodes
  7281. if (className != objectClass) {
  7282. return false;
  7283. }
  7284. // in older versions of Opera, `arguments` objects have `Array` constructors
  7285. var ctorA = a.constructor,
  7286. ctorB = b.constructor;
  7287. // non `Object` object instances with different constructors are not equal
  7288. if (ctorA != ctorB && !(
  7289. isFunction(ctorA) && ctorA instanceof ctorA &&
  7290. isFunction(ctorB) && ctorB instanceof ctorB
  7291. )) {
  7292. return false;
  7293. }
  7294. }
  7295. // assume cyclic structures are equal
  7296. // the algorithm for detecting cyclic structures is adapted from ES 5.1
  7297. // section 15.12.3, abstract operation `JO` (http://es5.github.com/#x15.12.3)
  7298. var initedStack = !stackA;
  7299. stackA || (stackA = getArray());
  7300. stackB || (stackB = getArray());
  7301. var length = stackA.length;
  7302. while (length--) {
  7303. if (stackA[length] == a) {
  7304. return stackB[length] == b;
  7305. }
  7306. }
  7307. var size = 0;
  7308. result = true;
  7309. // add `a` and `b` to the stack of traversed objects
  7310. stackA.push(a);
  7311. stackB.push(b);
  7312. // recursively compare objects and arrays (susceptible to call stack limits)
  7313. if (isArr) {
  7314. length = a.length;
  7315. size = b.length;
  7316. // compare lengths to determine if a deep comparison is necessary
  7317. result = size == a.length;
  7318. if (!result && !whereIndicator) {
  7319. return result;
  7320. }
  7321. // deep compare the contents, ignoring non-numeric properties
  7322. while (size--) {
  7323. var index = length,
  7324. value = b[size];
  7325. if (whereIndicator) {
  7326. while (index--) {
  7327. if ((result = isEqual(a[index], value, callback, thisArg, stackA, stackB))) {
  7328. break;
  7329. }
  7330. }
  7331. } else if (!(result = isEqual(a[size], value, callback, thisArg, stackA, stackB))) {
  7332. break;
  7333. }
  7334. }
  7335. return result;
  7336. }
  7337. // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
  7338. // which, in this case, is more costly
  7339. forIn(b, function(value, key, b) {
  7340. if (hasOwnProperty.call(b, key)) {
  7341. // count the number of properties.
  7342. size++;
  7343. // deep compare each property value.
  7344. return (result = hasOwnProperty.call(a, key) && isEqual(a[key], value, callback, thisArg, stackA, stackB));
  7345. }
  7346. });
  7347. if (result && !whereIndicator) {
  7348. // ensure both objects have the same number of properties
  7349. forIn(a, function(value, key, a) {
  7350. if (hasOwnProperty.call(a, key)) {
  7351. // `size` will be `-1` if `a` has more properties than `b`
  7352. return (result = --size > -1);
  7353. }
  7354. });
  7355. }
  7356. if (initedStack) {
  7357. releaseArray(stackA);
  7358. releaseArray(stackB);
  7359. }
  7360. return result;
  7361. }
  7362. /**
  7363. * Checks if `value` is, or can be coerced to, a finite number.
  7364. *
  7365. * Note: This is not the same as native `isFinite`, which will return true for
  7366. * booleans and empty strings. See http://es5.github.com/#x15.1.2.5.
  7367. *
  7368. * @static
  7369. * @memberOf _
  7370. * @category Objects
  7371. * @param {Mixed} value The value to check.
  7372. * @returns {Boolean} Returns `true`, if the `value` is finite, else `false`.
  7373. * @example
  7374. *
  7375. * _.isFinite(-101);
  7376. * // => true
  7377. *
  7378. * _.isFinite('10');
  7379. * // => true
  7380. *
  7381. * _.isFinite(true);
  7382. * // => false
  7383. *
  7384. * _.isFinite('');
  7385. * // => false
  7386. *
  7387. * _.isFinite(Infinity);
  7388. * // => false
  7389. */
  7390. function isFinite(value) {
  7391. return nativeIsFinite(value) && !nativeIsNaN(parseFloat(value));
  7392. }
  7393. /**
  7394. * Checks if `value` is a function.
  7395. *
  7396. * @static
  7397. * @memberOf _
  7398. * @category Objects
  7399. * @param {Mixed} value The value to check.
  7400. * @returns {Boolean} Returns `true`, if the `value` is a function, else `false`.
  7401. * @example
  7402. *
  7403. * _.isFunction(_);
  7404. * // => true
  7405. */
  7406. function isFunction(value) {
  7407. return typeof value == 'function';
  7408. }
  7409. /**
  7410. * Checks if `value` is the language type of Object.
  7411. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  7412. *
  7413. * @static
  7414. * @memberOf _
  7415. * @category Objects
  7416. * @param {Mixed} value The value to check.
  7417. * @returns {Boolean} Returns `true`, if the `value` is an object, else `false`.
  7418. * @example
  7419. *
  7420. * _.isObject({});
  7421. * // => true
  7422. *
  7423. * _.isObject([1, 2, 3]);
  7424. * // => true
  7425. *
  7426. * _.isObject(1);
  7427. * // => false
  7428. */
  7429. function isObject(value) {
  7430. // check if the value is the ECMAScript language type of Object
  7431. // http://es5.github.com/#x8
  7432. // and avoid a V8 bug
  7433. // http://code.google.com/p/v8/issues/detail?id=2291
  7434. return !!(value && objectTypes[typeof value]);
  7435. }
  7436. /**
  7437. * Checks if `value` is `NaN`.
  7438. *
  7439. * Note: This is not the same as native `isNaN`, which will return `true` for
  7440. * `undefined` and other values. See http://es5.github.com/#x15.1.2.4.
  7441. *
  7442. * @static
  7443. * @memberOf _
  7444. * @category Objects
  7445. * @param {Mixed} value The value to check.
  7446. * @returns {Boolean} Returns `true`, if the `value` is `NaN`, else `false`.
  7447. * @example
  7448. *
  7449. * _.isNaN(NaN);
  7450. * // => true
  7451. *
  7452. * _.isNaN(new Number(NaN));
  7453. * // => true
  7454. *
  7455. * isNaN(undefined);
  7456. * // => true
  7457. *
  7458. * _.isNaN(undefined);
  7459. * // => false
  7460. */
  7461. function isNaN(value) {
  7462. // `NaN` as a primitive is the only value that is not equal to itself
  7463. // (perform the [[Class]] check first to avoid errors with some host objects in IE)
  7464. return isNumber(value) && value != +value
  7465. }
  7466. /**
  7467. * Checks if `value` is `null`.
  7468. *
  7469. * @static
  7470. * @memberOf _
  7471. * @category Objects
  7472. * @param {Mixed} value The value to check.
  7473. * @returns {Boolean} Returns `true`, if the `value` is `null`, else `false`.
  7474. * @example
  7475. *
  7476. * _.isNull(null);
  7477. * // => true
  7478. *
  7479. * _.isNull(undefined);
  7480. * // => false
  7481. */
  7482. function isNull(value) {
  7483. return value === null;
  7484. }
  7485. /**
  7486. * Checks if `value` is a number.
  7487. *
  7488. * @static
  7489. * @memberOf _
  7490. * @category Objects
  7491. * @param {Mixed} value The value to check.
  7492. * @returns {Boolean} Returns `true`, if the `value` is a number, else `false`.
  7493. * @example
  7494. *
  7495. * _.isNumber(8.4 * 5);
  7496. * // => true
  7497. */
  7498. function isNumber(value) {
  7499. return typeof value == 'number' || toString.call(value) == numberClass;
  7500. }
  7501. /**
  7502. * Checks if a given `value` is an object created by the `Object` constructor.
  7503. *
  7504. * @static
  7505. * @memberOf _
  7506. * @category Objects
  7507. * @param {Mixed} value The value to check.
  7508. * @returns {Boolean} Returns `true`, if `value` is a plain object, else `false`.
  7509. * @example
  7510. *
  7511. * function Stooge(name, age) {
  7512. * this.name = name;
  7513. * this.age = age;
  7514. * }
  7515. *
  7516. * _.isPlainObject(new Stooge('moe', 40));
  7517. * // => false
  7518. *
  7519. * _.isPlainObject([1, 2, 3]);
  7520. * // => false
  7521. *
  7522. * _.isPlainObject({ 'name': 'moe', 'age': 40 });
  7523. * // => true
  7524. */
  7525. var isPlainObject = function(value) {
  7526. if (!(value && toString.call(value) == objectClass)) {
  7527. return false;
  7528. }
  7529. var valueOf = value.valueOf,
  7530. objProto = typeof valueOf == 'function' && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto);
  7531. return objProto
  7532. ? (value == objProto || getPrototypeOf(value) == objProto)
  7533. : shimIsPlainObject(value);
  7534. };
  7535. /**
  7536. * Checks if `value` is a regular expression.
  7537. *
  7538. * @static
  7539. * @memberOf _
  7540. * @category Objects
  7541. * @param {Mixed} value The value to check.
  7542. * @returns {Boolean} Returns `true`, if the `value` is a regular expression, else `false`.
  7543. * @example
  7544. *
  7545. * _.isRegExp(/moe/);
  7546. * // => true
  7547. */
  7548. function isRegExp(value) {
  7549. return value ? (typeof value == 'object' && toString.call(value) == regexpClass) : false;
  7550. }
  7551. /**
  7552. * Checks if `value` is a string.
  7553. *
  7554. * @static
  7555. * @memberOf _
  7556. * @category Objects
  7557. * @param {Mixed} value The value to check.
  7558. * @returns {Boolean} Returns `true`, if the `value` is a string, else `false`.
  7559. * @example
  7560. *
  7561. * _.isString('moe');
  7562. * // => true
  7563. */
  7564. function isString(value) {
  7565. return typeof value == 'string' || toString.call(value) == stringClass;
  7566. }
  7567. /**
  7568. * Checks if `value` is `undefined`.
  7569. *
  7570. * @static
  7571. * @memberOf _
  7572. * @category Objects
  7573. * @param {Mixed} value The value to check.
  7574. * @returns {Boolean} Returns `true`, if the `value` is `undefined`, else `false`.
  7575. * @example
  7576. *
  7577. * _.isUndefined(void 0);
  7578. * // => true
  7579. */
  7580. function isUndefined(value) {
  7581. return typeof value == 'undefined';
  7582. }
  7583. /**
  7584. * Recursively merges own enumerable properties of the source object(s), that
  7585. * don't resolve to `undefined`, into the destination object. Subsequent sources
  7586. * will overwrite property assignments of previous sources. If a `callback` function
  7587. * is passed, it will be executed to produce the merged values of the destination
  7588. * and source properties. If `callback` returns `undefined`, merging will be
  7589. * handled by the method instead. The `callback` is bound to `thisArg` and
  7590. * invoked with two arguments; (objectValue, sourceValue).
  7591. *
  7592. * @static
  7593. * @memberOf _
  7594. * @category Objects
  7595. * @param {Object} object The destination object.
  7596. * @param {Object} [source1, source2, ...] The source objects.
  7597. * @param {Function} [callback] The function to customize merging properties.
  7598. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  7599. * @param- {Object} [deepIndicator] Indicates that `stackA` and `stackB` are
  7600. * arrays of traversed objects, instead of source objects.
  7601. * @param- {Array} [stackA=[]] Tracks traversed source objects.
  7602. * @param- {Array} [stackB=[]] Associates values with source counterparts.
  7603. * @returns {Object} Returns the destination object.
  7604. * @example
  7605. *
  7606. * var names = {
  7607. * 'stooges': [
  7608. * { 'name': 'moe' },
  7609. * { 'name': 'larry' }
  7610. * ]
  7611. * };
  7612. *
  7613. * var ages = {
  7614. * 'stooges': [
  7615. * { 'age': 40 },
  7616. * { 'age': 50 }
  7617. * ]
  7618. * };
  7619. *
  7620. * _.merge(names, ages);
  7621. * // => { 'stooges': [{ 'name': 'moe', 'age': 40 }, { 'name': 'larry', 'age': 50 }] }
  7622. *
  7623. * var food = {
  7624. * 'fruits': ['apple'],
  7625. * 'vegetables': ['beet']
  7626. * };
  7627. *
  7628. * var otherFood = {
  7629. * 'fruits': ['banana'],
  7630. * 'vegetables': ['carrot']
  7631. * };
  7632. *
  7633. * _.merge(food, otherFood, function(a, b) {
  7634. * return _.isArray(a) ? a.concat(b) : undefined;
  7635. * });
  7636. * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot] }
  7637. */
  7638. function merge(object, source, deepIndicator) {
  7639. var args = arguments,
  7640. index = 0,
  7641. length = 2;
  7642. if (!isObject(object)) {
  7643. return object;
  7644. }
  7645. if (deepIndicator === indicatorObject) {
  7646. var callback = args[3],
  7647. stackA = args[4],
  7648. stackB = args[5];
  7649. } else {
  7650. var initedStack = true;
  7651. stackA = getArray();
  7652. stackB = getArray();
  7653. // allows working with `_.reduce` and `_.reduceRight` without
  7654. // using their `callback` arguments, `index|key` and `collection`
  7655. if (typeof deepIndicator != 'number') {
  7656. length = args.length;
  7657. }
  7658. if (length > 3 && typeof args[length - 2] == 'function') {
  7659. callback = lodash.createCallback(args[--length - 1], args[length--], 2);
  7660. } else if (length > 2 && typeof args[length - 1] == 'function') {
  7661. callback = args[--length];
  7662. }
  7663. }
  7664. while (++index < length) {
  7665. (isArray(args[index]) ? forEach : forOwn)(args[index], function(source, key) {
  7666. var found,
  7667. isArr,
  7668. result = source,
  7669. value = object[key];
  7670. if (source && ((isArr = isArray(source)) || isPlainObject(source))) {
  7671. // avoid merging previously merged cyclic sources
  7672. var stackLength = stackA.length;
  7673. while (stackLength--) {
  7674. if ((found = stackA[stackLength] == source)) {
  7675. value = stackB[stackLength];
  7676. break;
  7677. }
  7678. }
  7679. if (!found) {
  7680. var isShallow;
  7681. if (callback) {
  7682. result = callback(value, source);
  7683. if ((isShallow = typeof result != 'undefined')) {
  7684. value = result;
  7685. }
  7686. }
  7687. if (!isShallow) {
  7688. value = isArr
  7689. ? (isArray(value) ? value : [])
  7690. : (isPlainObject(value) ? value : {});
  7691. }
  7692. // add `source` and associated `value` to the stack of traversed objects
  7693. stackA.push(source);
  7694. stackB.push(value);
  7695. // recursively merge objects and arrays (susceptible to call stack limits)
  7696. if (!isShallow) {
  7697. value = merge(value, source, indicatorObject, callback, stackA, stackB);
  7698. }
  7699. }
  7700. }
  7701. else {
  7702. if (callback) {
  7703. result = callback(value, source);
  7704. if (typeof result == 'undefined') {
  7705. result = source;
  7706. }
  7707. }
  7708. if (typeof result != 'undefined') {
  7709. value = result;
  7710. }
  7711. }
  7712. object[key] = value;
  7713. });
  7714. }
  7715. if (initedStack) {
  7716. releaseArray(stackA);
  7717. releaseArray(stackB);
  7718. }
  7719. return object;
  7720. }
  7721. /**
  7722. * Creates a shallow clone of `object` excluding the specified properties.
  7723. * Property names may be specified as individual arguments or as arrays of
  7724. * property names. If a `callback` function is passed, it will be executed
  7725. * for each property in the `object`, omitting the properties `callback`
  7726. * returns truthy for. The `callback` is bound to `thisArg` and invoked
  7727. * with three arguments; (value, key, object).
  7728. *
  7729. * @static
  7730. * @memberOf _
  7731. * @category Objects
  7732. * @param {Object} object The source object.
  7733. * @param {Function|String} callback|[prop1, prop2, ...] The properties to omit
  7734. * or the function called per iteration.
  7735. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  7736. * @returns {Object} Returns an object without the omitted properties.
  7737. * @example
  7738. *
  7739. * _.omit({ 'name': 'moe', 'age': 40 }, 'age');
  7740. * // => { 'name': 'moe' }
  7741. *
  7742. * _.omit({ 'name': 'moe', 'age': 40 }, function(value) {
  7743. * return typeof value == 'number';
  7744. * });
  7745. * // => { 'name': 'moe' }
  7746. */
  7747. function omit(object, callback, thisArg) {
  7748. var indexOf = getIndexOf(),
  7749. isFunc = typeof callback == 'function',
  7750. result = {};
  7751. if (isFunc) {
  7752. callback = lodash.createCallback(callback, thisArg);
  7753. } else {
  7754. var props = concat.apply(arrayRef, nativeSlice.call(arguments, 1));
  7755. }
  7756. forIn(object, function(value, key, object) {
  7757. if (isFunc
  7758. ? !callback(value, key, object)
  7759. : indexOf(props, key) < 0
  7760. ) {
  7761. result[key] = value;
  7762. }
  7763. });
  7764. return result;
  7765. }
  7766. /**
  7767. * Creates a two dimensional array of the given object's key-value pairs,
  7768. * i.e. `[[key1, value1], [key2, value2]]`.
  7769. *
  7770. * @static
  7771. * @memberOf _
  7772. * @category Objects
  7773. * @param {Object} object The object to inspect.
  7774. * @returns {Array} Returns new array of key-value pairs.
  7775. * @example
  7776. *
  7777. * _.pairs({ 'moe': 30, 'larry': 40 });
  7778. * // => [['moe', 30], ['larry', 40]] (order is not guaranteed)
  7779. */
  7780. function pairs(object) {
  7781. var index = -1,
  7782. props = keys(object),
  7783. length = props.length,
  7784. result = Array(length);
  7785. while (++index < length) {
  7786. var key = props[index];
  7787. result[index] = [key, object[key]];
  7788. }
  7789. return result;
  7790. }
  7791. /**
  7792. * Creates a shallow clone of `object` composed of the specified properties.
  7793. * Property names may be specified as individual arguments or as arrays of property
  7794. * names. If `callback` is passed, it will be executed for each property in the
  7795. * `object`, picking the properties `callback` returns truthy for. The `callback`
  7796. * is bound to `thisArg` and invoked with three arguments; (value, key, object).
  7797. *
  7798. * @static
  7799. * @memberOf _
  7800. * @category Objects
  7801. * @param {Object} object The source object.
  7802. * @param {Array|Function|String} callback|[prop1, prop2, ...] The function called
  7803. * per iteration or properties to pick, either as individual arguments or arrays.
  7804. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  7805. * @returns {Object} Returns an object composed of the picked properties.
  7806. * @example
  7807. *
  7808. * _.pick({ 'name': 'moe', '_userid': 'moe1' }, 'name');
  7809. * // => { 'name': 'moe' }
  7810. *
  7811. * _.pick({ 'name': 'moe', '_userid': 'moe1' }, function(value, key) {
  7812. * return key.charAt(0) != '_';
  7813. * });
  7814. * // => { 'name': 'moe' }
  7815. */
  7816. function pick(object, callback, thisArg) {
  7817. var result = {};
  7818. if (typeof callback != 'function') {
  7819. var index = -1,
  7820. props = concat.apply(arrayRef, nativeSlice.call(arguments, 1)),
  7821. length = isObject(object) ? props.length : 0;
  7822. while (++index < length) {
  7823. var key = props[index];
  7824. if (key in object) {
  7825. result[key] = object[key];
  7826. }
  7827. }
  7828. } else {
  7829. callback = lodash.createCallback(callback, thisArg);
  7830. forIn(object, function(value, key, object) {
  7831. if (callback(value, key, object)) {
  7832. result[key] = value;
  7833. }
  7834. });
  7835. }
  7836. return result;
  7837. }
  7838. /**
  7839. * An alternative to `_.reduce`, this method transforms an `object` to a new
  7840. * `accumulator` object which is the result of running each of its elements
  7841. * through the `callback`, with each `callback` execution potentially mutating
  7842. * the `accumulator` object. The `callback` is bound to `thisArg` and invoked
  7843. * with four arguments; (accumulator, value, key, object). Callbacks may exit
  7844. * iteration early by explicitly returning `false`.
  7845. *
  7846. * @static
  7847. * @memberOf _
  7848. * @category Objects
  7849. * @param {Array|Object} collection The collection to iterate over.
  7850. * @param {Function} [callback=identity] The function called per iteration.
  7851. * @param {Mixed} [accumulator] The custom accumulator value.
  7852. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  7853. * @returns {Mixed} Returns the accumulated value.
  7854. * @example
  7855. *
  7856. * var squares = _.transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function(result, num) {
  7857. * num *= num;
  7858. * if (num % 2) {
  7859. * return result.push(num) < 3;
  7860. * }
  7861. * });
  7862. * // => [1, 9, 25]
  7863. *
  7864. * var mapped = _.transform({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) {
  7865. * result[key] = num * 3;
  7866. * });
  7867. * // => { 'a': 3, 'b': 6, 'c': 9 }
  7868. */
  7869. function transform(object, callback, accumulator, thisArg) {
  7870. var isArr = isArray(object);
  7871. callback = lodash.createCallback(callback, thisArg, 4);
  7872. if (accumulator == null) {
  7873. if (isArr) {
  7874. accumulator = [];
  7875. } else {
  7876. var ctor = object && object.constructor,
  7877. proto = ctor && ctor.prototype;
  7878. accumulator = createObject(proto);
  7879. }
  7880. }
  7881. (isArr ? forEach : forOwn)(object, function(value, index, object) {
  7882. return callback(accumulator, value, index, object);
  7883. });
  7884. return accumulator;
  7885. }
  7886. /**
  7887. * Creates an array composed of the own enumerable property values of `object`.
  7888. *
  7889. * @static
  7890. * @memberOf _
  7891. * @category Objects
  7892. * @param {Object} object The object to inspect.
  7893. * @returns {Array} Returns a new array of property values.
  7894. * @example
  7895. *
  7896. * _.values({ 'one': 1, 'two': 2, 'three': 3 });
  7897. * // => [1, 2, 3] (order is not guaranteed)
  7898. */
  7899. function values(object) {
  7900. var index = -1,
  7901. props = keys(object),
  7902. length = props.length,
  7903. result = Array(length);
  7904. while (++index < length) {
  7905. result[index] = object[props[index]];
  7906. }
  7907. return result;
  7908. }
  7909. /*--------------------------------------------------------------------------*/
  7910. /**
  7911. * Creates an array of elements from the specified indexes, or keys, of the
  7912. * `collection`. Indexes may be specified as individual arguments or as arrays
  7913. * of indexes.
  7914. *
  7915. * @static
  7916. * @memberOf _
  7917. * @category Collections
  7918. * @param {Array|Object|String} collection The collection to iterate over.
  7919. * @param {Array|Number|String} [index1, index2, ...] The indexes of
  7920. * `collection` to retrieve, either as individual arguments or arrays.
  7921. * @returns {Array} Returns a new array of elements corresponding to the
  7922. * provided indexes.
  7923. * @example
  7924. *
  7925. * _.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]);
  7926. * // => ['a', 'c', 'e']
  7927. *
  7928. * _.at(['moe', 'larry', 'curly'], 0, 2);
  7929. * // => ['moe', 'curly']
  7930. */
  7931. function at(collection) {
  7932. var index = -1,
  7933. props = concat.apply(arrayRef, nativeSlice.call(arguments, 1)),
  7934. length = props.length,
  7935. result = Array(length);
  7936. while(++index < length) {
  7937. result[index] = collection[props[index]];
  7938. }
  7939. return result;
  7940. }
  7941. /**
  7942. * Checks if a given `target` element is present in a `collection` using strict
  7943. * equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used
  7944. * as the offset from the end of the collection.
  7945. *
  7946. * @static
  7947. * @memberOf _
  7948. * @alias include
  7949. * @category Collections
  7950. * @param {Array|Object|String} collection The collection to iterate over.
  7951. * @param {Mixed} target The value to check for.
  7952. * @param {Number} [fromIndex=0] The index to search from.
  7953. * @returns {Boolean} Returns `true` if the `target` element is found, else `false`.
  7954. * @example
  7955. *
  7956. * _.contains([1, 2, 3], 1);
  7957. * // => true
  7958. *
  7959. * _.contains([1, 2, 3], 1, 2);
  7960. * // => false
  7961. *
  7962. * _.contains({ 'name': 'moe', 'age': 40 }, 'moe');
  7963. * // => true
  7964. *
  7965. * _.contains('curly', 'ur');
  7966. * // => true
  7967. */
  7968. function contains(collection, target, fromIndex) {
  7969. var index = -1,
  7970. indexOf = getIndexOf(),
  7971. length = collection ? collection.length : 0,
  7972. result = false;
  7973. fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex) || 0;
  7974. if (length && typeof length == 'number') {
  7975. result = (isString(collection)
  7976. ? collection.indexOf(target, fromIndex)
  7977. : indexOf(collection, target, fromIndex)
  7978. ) > -1;
  7979. } else {
  7980. forOwn(collection, function(value) {
  7981. if (++index >= fromIndex) {
  7982. return !(result = value === target);
  7983. }
  7984. });
  7985. }
  7986. return result;
  7987. }
  7988. /**
  7989. * Creates an object composed of keys returned from running each element of the
  7990. * `collection` through the given `callback`. The corresponding value of each key
  7991. * is the number of times the key was returned by the `callback`. The `callback`
  7992. * is bound to `thisArg` and invoked with three arguments; (value, index|key, collection).
  7993. *
  7994. * If a property name is passed for `callback`, the created "_.pluck" style
  7995. * callback will return the property value of the given element.
  7996. *
  7997. * If an object is passed for `callback`, the created "_.where" style callback
  7998. * will return `true` for elements that have the properties of the given object,
  7999. * else `false`.
  8000. *
  8001. * @static
  8002. * @memberOf _
  8003. * @category Collections
  8004. * @param {Array|Object|String} collection The collection to iterate over.
  8005. * @param {Function|Object|String} [callback=identity] The function called per
  8006. * iteration. If a property name or object is passed, it will be used to create
  8007. * a "_.pluck" or "_.where" style callback, respectively.
  8008. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  8009. * @returns {Object} Returns the composed aggregate object.
  8010. * @example
  8011. *
  8012. * _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); });
  8013. * // => { '4': 1, '6': 2 }
  8014. *
  8015. * _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
  8016. * // => { '4': 1, '6': 2 }
  8017. *
  8018. * _.countBy(['one', 'two', 'three'], 'length');
  8019. * // => { '3': 2, '5': 1 }
  8020. */
  8021. function countBy(collection, callback, thisArg) {
  8022. var result = {};
  8023. callback = lodash.createCallback(callback, thisArg);
  8024. forEach(collection, function(value, key, collection) {
  8025. key = String(callback(value, key, collection));
  8026. (hasOwnProperty.call(result, key) ? result[key]++ : result[key] = 1);
  8027. });
  8028. return result;
  8029. }
  8030. /**
  8031. * Checks if the `callback` returns a truthy value for **all** elements of a
  8032. * `collection`. The `callback` is bound to `thisArg` and invoked with three
  8033. * arguments; (value, index|key, collection).
  8034. *
  8035. * If a property name is passed for `callback`, the created "_.pluck" style
  8036. * callback will return the property value of the given element.
  8037. *
  8038. * If an object is passed for `callback`, the created "_.where" style callback
  8039. * will return `true` for elements that have the properties of the given object,
  8040. * else `false`.
  8041. *
  8042. * @static
  8043. * @memberOf _
  8044. * @alias all
  8045. * @category Collections
  8046. * @param {Array|Object|String} collection The collection to iterate over.
  8047. * @param {Function|Object|String} [callback=identity] The function called per
  8048. * iteration. If a property name or object is passed, it will be used to create
  8049. * a "_.pluck" or "_.where" style callback, respectively.
  8050. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  8051. * @returns {Boolean} Returns `true` if all elements pass the callback check,
  8052. * else `false`.
  8053. * @example
  8054. *
  8055. * _.every([true, 1, null, 'yes'], Boolean);
  8056. * // => false
  8057. *
  8058. * var stooges = [
  8059. * { 'name': 'moe', 'age': 40 },
  8060. * { 'name': 'larry', 'age': 50 }
  8061. * ];
  8062. *
  8063. * // using "_.pluck" callback shorthand
  8064. * _.every(stooges, 'age');
  8065. * // => true
  8066. *
  8067. * // using "_.where" callback shorthand
  8068. * _.every(stooges, { 'age': 50 });
  8069. * // => false
  8070. */
  8071. function every(collection, callback, thisArg) {
  8072. var result = true;
  8073. callback = lodash.createCallback(callback, thisArg);
  8074. var index = -1,
  8075. length = collection ? collection.length : 0;
  8076. if (typeof length == 'number') {
  8077. while (++index < length) {
  8078. if (!(result = !!callback(collection[index], index, collection))) {
  8079. break;
  8080. }
  8081. }
  8082. } else {
  8083. forOwn(collection, function(value, index, collection) {
  8084. return (result = !!callback(value, index, collection));
  8085. });
  8086. }
  8087. return result;
  8088. }
  8089. /**
  8090. * Examines each element in a `collection`, returning an array of all elements
  8091. * the `callback` returns truthy for. The `callback` is bound to `thisArg` and
  8092. * invoked with three arguments; (value, index|key, collection).
  8093. *
  8094. * If a property name is passed for `callback`, the created "_.pluck" style
  8095. * callback will return the property value of the given element.
  8096. *
  8097. * If an object is passed for `callback`, the created "_.where" style callback
  8098. * will return `true` for elements that have the properties of the given object,
  8099. * else `false`.
  8100. *
  8101. * @static
  8102. * @memberOf _
  8103. * @alias select
  8104. * @category Collections
  8105. * @param {Array|Object|String} collection The collection to iterate over.
  8106. * @param {Function|Object|String} [callback=identity] The function called per
  8107. * iteration. If a property name or object is passed, it will be used to create
  8108. * a "_.pluck" or "_.where" style callback, respectively.
  8109. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  8110. * @returns {Array} Returns a new array of elements that passed the callback check.
  8111. * @example
  8112. *
  8113. * var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
  8114. * // => [2, 4, 6]
  8115. *
  8116. * var food = [
  8117. * { 'name': 'apple', 'organic': false, 'type': 'fruit' },
  8118. * { 'name': 'carrot', 'organic': true, 'type': 'vegetable' }
  8119. * ];
  8120. *
  8121. * // using "_.pluck" callback shorthand
  8122. * _.filter(food, 'organic');
  8123. * // => [{ 'name': 'carrot', 'organic': true, 'type': 'vegetable' }]
  8124. *
  8125. * // using "_.where" callback shorthand
  8126. * _.filter(food, { 'type': 'fruit' });
  8127. * // => [{ 'name': 'apple', 'organic': false, 'type': 'fruit' }]
  8128. */
  8129. function filter(collection, callback, thisArg) {
  8130. var result = [];
  8131. callback = lodash.createCallback(callback, thisArg);
  8132. var index = -1,
  8133. length = collection ? collection.length : 0;
  8134. if (typeof length == 'number') {
  8135. while (++index < length) {
  8136. var value = collection[index];
  8137. if (callback(value, index, collection)) {
  8138. result.push(value);
  8139. }
  8140. }
  8141. } else {
  8142. forOwn(collection, function(value, index, collection) {
  8143. if (callback(value, index, collection)) {
  8144. result.push(value);
  8145. }
  8146. });
  8147. }
  8148. return result;
  8149. }
  8150. /**
  8151. * Examines each element in a `collection`, returning the first that the `callback`
  8152. * returns truthy for. The `callback` is bound to `thisArg` and invoked with three
  8153. * arguments; (value, index|key, collection).
  8154. *
  8155. * If a property name is passed for `callback`, the created "_.pluck" style
  8156. * callback will return the property value of the given element.
  8157. *
  8158. * If an object is passed for `callback`, the created "_.where" style callback
  8159. * will return `true` for elements that have the properties of the given object,
  8160. * else `false`.
  8161. *
  8162. * @static
  8163. * @memberOf _
  8164. * @alias detect, findWhere
  8165. * @category Collections
  8166. * @param {Array|Object|String} collection The collection to iterate over.
  8167. * @param {Function|Object|String} [callback=identity] The function called per
  8168. * iteration. If a property name or object is passed, it will be used to create
  8169. * a "_.pluck" or "_.where" style callback, respectively.
  8170. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  8171. * @returns {Mixed} Returns the found element, else `undefined`.
  8172. * @example
  8173. *
  8174. * _.find([1, 2, 3, 4], function(num) {
  8175. * return num % 2 == 0;
  8176. * });
  8177. * // => 2
  8178. *
  8179. * var food = [
  8180. * { 'name': 'apple', 'organic': false, 'type': 'fruit' },
  8181. * { 'name': 'banana', 'organic': true, 'type': 'fruit' },
  8182. * { 'name': 'beet', 'organic': false, 'type': 'vegetable' }
  8183. * ];
  8184. *
  8185. * // using "_.where" callback shorthand
  8186. * _.find(food, { 'type': 'vegetable' });
  8187. * // => { 'name': 'beet', 'organic': false, 'type': 'vegetable' }
  8188. *
  8189. * // using "_.pluck" callback shorthand
  8190. * _.find(food, 'organic');
  8191. * // => { 'name': 'banana', 'organic': true, 'type': 'fruit' }
  8192. */
  8193. function find(collection, callback, thisArg) {
  8194. callback = lodash.createCallback(callback, thisArg);
  8195. var index = -1,
  8196. length = collection ? collection.length : 0;
  8197. if (typeof length == 'number') {
  8198. while (++index < length) {
  8199. var value = collection[index];
  8200. if (callback(value, index, collection)) {
  8201. return value;
  8202. }
  8203. }
  8204. } else {
  8205. var result;
  8206. forOwn(collection, function(value, index, collection) {
  8207. if (callback(value, index, collection)) {
  8208. result = value;
  8209. return false;
  8210. }
  8211. });
  8212. return result;
  8213. }
  8214. }
  8215. /**
  8216. * Iterates over a `collection`, executing the `callback` for each element in
  8217. * the `collection`. The `callback` is bound to `thisArg` and invoked with three
  8218. * arguments; (value, index|key, collection). Callbacks may exit iteration early
  8219. * by explicitly returning `false`.
  8220. *
  8221. * @static
  8222. * @memberOf _
  8223. * @alias each
  8224. * @category Collections
  8225. * @param {Array|Object|String} collection The collection to iterate over.
  8226. * @param {Function} [callback=identity] The function called per iteration.
  8227. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  8228. * @returns {Array|Object|String} Returns `collection`.
  8229. * @example
  8230. *
  8231. * _([1, 2, 3]).forEach(alert).join(',');
  8232. * // => alerts each number and returns '1,2,3'
  8233. *
  8234. * _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, alert);
  8235. * // => alerts each number value (order is not guaranteed)
  8236. */
  8237. function forEach(collection, callback, thisArg) {
  8238. var index = -1,
  8239. length = collection ? collection.length : 0;
  8240. callback = callback && typeof thisArg == 'undefined' ? callback : lodash.createCallback(callback, thisArg);
  8241. if (typeof length == 'number') {
  8242. while (++index < length) {
  8243. if (callback(collection[index], index, collection) === false) {
  8244. break;
  8245. }
  8246. }
  8247. } else {
  8248. forOwn(collection, callback);
  8249. }
  8250. return collection;
  8251. }
  8252. /**
  8253. * Creates an object composed of keys returned from running each element of the
  8254. * `collection` through the `callback`. The corresponding value of each key is
  8255. * an array of elements passed to `callback` that returned the key. The `callback`
  8256. * is bound to `thisArg` and invoked with three arguments; (value, index|key, collection).
  8257. *
  8258. * If a property name is passed for `callback`, the created "_.pluck" style
  8259. * callback will return the property value of the given element.
  8260. *
  8261. * If an object is passed for `callback`, the created "_.where" style callback
  8262. * will return `true` for elements that have the properties of the given object,
  8263. * else `false`
  8264. *
  8265. * @static
  8266. * @memberOf _
  8267. * @category Collections
  8268. * @param {Array|Object|String} collection The collection to iterate over.
  8269. * @param {Function|Object|String} [callback=identity] The function called per
  8270. * iteration. If a property name or object is passed, it will be used to create
  8271. * a "_.pluck" or "_.where" style callback, respectively.
  8272. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  8273. * @returns {Object} Returns the composed aggregate object.
  8274. * @example
  8275. *
  8276. * _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); });
  8277. * // => { '4': [4.2], '6': [6.1, 6.4] }
  8278. *
  8279. * _.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
  8280. * // => { '4': [4.2], '6': [6.1, 6.4] }
  8281. *
  8282. * // using "_.pluck" callback shorthand
  8283. * _.groupBy(['one', 'two', 'three'], 'length');
  8284. * // => { '3': ['one', 'two'], '5': ['three'] }
  8285. */
  8286. function groupBy(collection, callback, thisArg) {
  8287. var result = {};
  8288. callback = lodash.createCallback(callback, thisArg);
  8289. forEach(collection, function(value, key, collection) {
  8290. key = String(callback(value, key, collection));
  8291. (hasOwnProperty.call(result, key) ? result[key] : result[key] = []).push(value);
  8292. });
  8293. return result;
  8294. }
  8295. /**
  8296. * Invokes the method named by `methodName` on each element in the `collection`,
  8297. * returning an array of the results of each invoked method. Additional arguments
  8298. * will be passed to each invoked method. If `methodName` is a function, it will
  8299. * be invoked for, and `this` bound to, each element in the `collection`.
  8300. *
  8301. * @static
  8302. * @memberOf _
  8303. * @category Collections
  8304. * @param {Array|Object|String} collection The collection to iterate over.
  8305. * @param {Function|String} methodName The name of the method to invoke or
  8306. * the function invoked per iteration.
  8307. * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the method with.
  8308. * @returns {Array} Returns a new array of the results of each invoked method.
  8309. * @example
  8310. *
  8311. * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
  8312. * // => [[1, 5, 7], [1, 2, 3]]
  8313. *
  8314. * _.invoke([123, 456], String.prototype.split, '');
  8315. * // => [['1', '2', '3'], ['4', '5', '6']]
  8316. */
  8317. function invoke(collection, methodName) {
  8318. var args = nativeSlice.call(arguments, 2),
  8319. index = -1,
  8320. isFunc = typeof methodName == 'function',
  8321. length = collection ? collection.length : 0,
  8322. result = Array(typeof length == 'number' ? length : 0);
  8323. forEach(collection, function(value) {
  8324. result[++index] = (isFunc ? methodName : value[methodName]).apply(value, args);
  8325. });
  8326. return result;
  8327. }
  8328. /**
  8329. * Creates an array of values by running each element in the `collection`
  8330. * through the `callback`. The `callback` is bound to `thisArg` and invoked with
  8331. * three arguments; (value, index|key, collection).
  8332. *
  8333. * If a property name is passed for `callback`, the created "_.pluck" style
  8334. * callback will return the property value of the given element.
  8335. *
  8336. * If an object is passed for `callback`, the created "_.where" style callback
  8337. * will return `true` for elements that have the properties of the given object,
  8338. * else `false`.
  8339. *
  8340. * @static
  8341. * @memberOf _
  8342. * @alias collect
  8343. * @category Collections
  8344. * @param {Array|Object|String} collection The collection to iterate over.
  8345. * @param {Function|Object|String} [callback=identity] The function called per
  8346. * iteration. If a property name or object is passed, it will be used to create
  8347. * a "_.pluck" or "_.where" style callback, respectively.
  8348. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  8349. * @returns {Array} Returns a new array of the results of each `callback` execution.
  8350. * @example
  8351. *
  8352. * _.map([1, 2, 3], function(num) { return num * 3; });
  8353. * // => [3, 6, 9]
  8354. *
  8355. * _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; });
  8356. * // => [3, 6, 9] (order is not guaranteed)
  8357. *
  8358. * var stooges = [
  8359. * { 'name': 'moe', 'age': 40 },
  8360. * { 'name': 'larry', 'age': 50 }
  8361. * ];
  8362. *
  8363. * // using "_.pluck" callback shorthand
  8364. * _.map(stooges, 'name');
  8365. * // => ['moe', 'larry']
  8366. */
  8367. function map(collection, callback, thisArg) {
  8368. var index = -1,
  8369. length = collection ? collection.length : 0;
  8370. callback = lodash.createCallback(callback, thisArg);
  8371. if (typeof length == 'number') {
  8372. var result = Array(length);
  8373. while (++index < length) {
  8374. result[index] = callback(collection[index], index, collection);
  8375. }
  8376. } else {
  8377. result = [];
  8378. forOwn(collection, function(value, key, collection) {
  8379. result[++index] = callback(value, key, collection);
  8380. });
  8381. }
  8382. return result;
  8383. }
  8384. /**
  8385. * Retrieves the maximum value of an `array`. If `callback` is passed,
  8386. * it will be executed for each value in the `array` to generate the
  8387. * criterion by which the value is ranked. The `callback` is bound to
  8388. * `thisArg` and invoked with three arguments; (value, index, collection).
  8389. *
  8390. * If a property name is passed for `callback`, the created "_.pluck" style
  8391. * callback will return the property value of the given element.
  8392. *
  8393. * If an object is passed for `callback`, the created "_.where" style callback
  8394. * will return `true` for elements that have the properties of the given object,
  8395. * else `false`.
  8396. *
  8397. * @static
  8398. * @memberOf _
  8399. * @category Collections
  8400. * @param {Array|Object|String} collection The collection to iterate over.
  8401. * @param {Function|Object|String} [callback=identity] The function called per
  8402. * iteration. If a property name or object is passed, it will be used to create
  8403. * a "_.pluck" or "_.where" style callback, respectively.
  8404. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  8405. * @returns {Mixed} Returns the maximum value.
  8406. * @example
  8407. *
  8408. * _.max([4, 2, 8, 6]);
  8409. * // => 8
  8410. *
  8411. * var stooges = [
  8412. * { 'name': 'moe', 'age': 40 },
  8413. * { 'name': 'larry', 'age': 50 }
  8414. * ];
  8415. *
  8416. * _.max(stooges, function(stooge) { return stooge.age; });
  8417. * // => { 'name': 'larry', 'age': 50 };
  8418. *
  8419. * // using "_.pluck" callback shorthand
  8420. * _.max(stooges, 'age');
  8421. * // => { 'name': 'larry', 'age': 50 };
  8422. */
  8423. function max(collection, callback, thisArg) {
  8424. var computed = -Infinity,
  8425. result = computed;
  8426. if (!callback && isArray(collection)) {
  8427. var index = -1,
  8428. length = collection.length;
  8429. while (++index < length) {
  8430. var value = collection[index];
  8431. if (value > result) {
  8432. result = value;
  8433. }
  8434. }
  8435. } else {
  8436. callback = (!callback && isString(collection))
  8437. ? charAtCallback
  8438. : lodash.createCallback(callback, thisArg);
  8439. forEach(collection, function(value, index, collection) {
  8440. var current = callback(value, index, collection);
  8441. if (current > computed) {
  8442. computed = current;
  8443. result = value;
  8444. }
  8445. });
  8446. }
  8447. return result;
  8448. }
  8449. /**
  8450. * Retrieves the minimum value of an `array`. If `callback` is passed,
  8451. * it will be executed for each value in the `array` to generate the
  8452. * criterion by which the value is ranked. The `callback` is bound to `thisArg`
  8453. * and invoked with three arguments; (value, index, collection).
  8454. *
  8455. * If a property name is passed for `callback`, the created "_.pluck" style
  8456. * callback will return the property value of the given element.
  8457. *
  8458. * If an object is passed for `callback`, the created "_.where" style callback
  8459. * will return `true` for elements that have the properties of the given object,
  8460. * else `false`.
  8461. *
  8462. * @static
  8463. * @memberOf _
  8464. * @category Collections
  8465. * @param {Array|Object|String} collection The collection to iterate over.
  8466. * @param {Function|Object|String} [callback=identity] The function called per
  8467. * iteration. If a property name or object is passed, it will be used to create
  8468. * a "_.pluck" or "_.where" style callback, respectively.
  8469. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  8470. * @returns {Mixed} Returns the minimum value.
  8471. * @example
  8472. *
  8473. * _.min([4, 2, 8, 6]);
  8474. * // => 2
  8475. *
  8476. * var stooges = [
  8477. * { 'name': 'moe', 'age': 40 },
  8478. * { 'name': 'larry', 'age': 50 }
  8479. * ];
  8480. *
  8481. * _.min(stooges, function(stooge) { return stooge.age; });
  8482. * // => { 'name': 'moe', 'age': 40 };
  8483. *
  8484. * // using "_.pluck" callback shorthand
  8485. * _.min(stooges, 'age');
  8486. * // => { 'name': 'moe', 'age': 40 };
  8487. */
  8488. function min(collection, callback, thisArg) {
  8489. var computed = Infinity,
  8490. result = computed;
  8491. if (!callback && isArray(collection)) {
  8492. var index = -1,
  8493. length = collection.length;
  8494. while (++index < length) {
  8495. var value = collection[index];
  8496. if (value < result) {
  8497. result = value;
  8498. }
  8499. }
  8500. } else {
  8501. callback = (!callback && isString(collection))
  8502. ? charAtCallback
  8503. : lodash.createCallback(callback, thisArg);
  8504. forEach(collection, function(value, index, collection) {
  8505. var current = callback(value, index, collection);
  8506. if (current < computed) {
  8507. computed = current;
  8508. result = value;
  8509. }
  8510. });
  8511. }
  8512. return result;
  8513. }
  8514. /**
  8515. * Retrieves the value of a specified property from all elements in the `collection`.
  8516. *
  8517. * @static
  8518. * @memberOf _
  8519. * @type Function
  8520. * @category Collections
  8521. * @param {Array|Object|String} collection The collection to iterate over.
  8522. * @param {String} property The property to pluck.
  8523. * @returns {Array} Returns a new array of property values.
  8524. * @example
  8525. *
  8526. * var stooges = [
  8527. * { 'name': 'moe', 'age': 40 },
  8528. * { 'name': 'larry', 'age': 50 }
  8529. * ];
  8530. *
  8531. * _.pluck(stooges, 'name');
  8532. * // => ['moe', 'larry']
  8533. */
  8534. function pluck(collection, property) {
  8535. var index = -1,
  8536. length = collection ? collection.length : 0;
  8537. if (typeof length == 'number') {
  8538. var result = Array(length);
  8539. while (++index < length) {
  8540. result[index] = collection[index][property];
  8541. }
  8542. }
  8543. return result || map(collection, property);
  8544. }
  8545. /**
  8546. * Reduces a `collection` to a value which is the accumulated result of running
  8547. * each element in the `collection` through the `callback`, where each successive
  8548. * `callback` execution consumes the return value of the previous execution.
  8549. * If `accumulator` is not passed, the first element of the `collection` will be
  8550. * used as the initial `accumulator` value. The `callback` is bound to `thisArg`
  8551. * and invoked with four arguments; (accumulator, value, index|key, collection).
  8552. *
  8553. * @static
  8554. * @memberOf _
  8555. * @alias foldl, inject
  8556. * @category Collections
  8557. * @param {Array|Object|String} collection The collection to iterate over.
  8558. * @param {Function} [callback=identity] The function called per iteration.
  8559. * @param {Mixed} [accumulator] Initial value of the accumulator.
  8560. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  8561. * @returns {Mixed} Returns the accumulated value.
  8562. * @example
  8563. *
  8564. * var sum = _.reduce([1, 2, 3], function(sum, num) {
  8565. * return sum + num;
  8566. * });
  8567. * // => 6
  8568. *
  8569. * var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) {
  8570. * result[key] = num * 3;
  8571. * return result;
  8572. * }, {});
  8573. * // => { 'a': 3, 'b': 6, 'c': 9 }
  8574. */
  8575. function reduce(collection, callback, accumulator, thisArg) {
  8576. if (!collection) return accumulator;
  8577. var noaccum = arguments.length < 3;
  8578. callback = lodash.createCallback(callback, thisArg, 4);
  8579. var index = -1,
  8580. length = collection.length;
  8581. if (typeof length == 'number') {
  8582. if (noaccum) {
  8583. accumulator = collection[++index];
  8584. }
  8585. while (++index < length) {
  8586. accumulator = callback(accumulator, collection[index], index, collection);
  8587. }
  8588. } else {
  8589. forOwn(collection, function(value, index, collection) {
  8590. accumulator = noaccum
  8591. ? (noaccum = false, value)
  8592. : callback(accumulator, value, index, collection)
  8593. });
  8594. }
  8595. return accumulator;
  8596. }
  8597. /**
  8598. * This method is similar to `_.reduce`, except that it iterates over a
  8599. * `collection` from right to left.
  8600. *
  8601. * @static
  8602. * @memberOf _
  8603. * @alias foldr
  8604. * @category Collections
  8605. * @param {Array|Object|String} collection The collection to iterate over.
  8606. * @param {Function} [callback=identity] The function called per iteration.
  8607. * @param {Mixed} [accumulator] Initial value of the accumulator.
  8608. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  8609. * @returns {Mixed} Returns the accumulated value.
  8610. * @example
  8611. *
  8612. * var list = [[0, 1], [2, 3], [4, 5]];
  8613. * var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
  8614. * // => [4, 5, 2, 3, 0, 1]
  8615. */
  8616. function reduceRight(collection, callback, accumulator, thisArg) {
  8617. var iterable = collection,
  8618. length = collection ? collection.length : 0,
  8619. noaccum = arguments.length < 3;
  8620. if (typeof length != 'number') {
  8621. var props = keys(collection);
  8622. length = props.length;
  8623. }
  8624. callback = lodash.createCallback(callback, thisArg, 4);
  8625. forEach(collection, function(value, index, collection) {
  8626. index = props ? props[--length] : --length;
  8627. accumulator = noaccum
  8628. ? (noaccum = false, iterable[index])
  8629. : callback(accumulator, iterable[index], index, collection);
  8630. });
  8631. return accumulator;
  8632. }
  8633. /**
  8634. * The opposite of `_.filter`, this method returns the elements of a
  8635. * `collection` that `callback` does **not** return truthy for.
  8636. *
  8637. * If a property name is passed for `callback`, the created "_.pluck" style
  8638. * callback will return the property value of the given element.
  8639. *
  8640. * If an object is passed for `callback`, the created "_.where" style callback
  8641. * will return `true` for elements that have the properties of the given object,
  8642. * else `false`.
  8643. *
  8644. * @static
  8645. * @memberOf _
  8646. * @category Collections
  8647. * @param {Array|Object|String} collection The collection to iterate over.
  8648. * @param {Function|Object|String} [callback=identity] The function called per
  8649. * iteration. If a property name or object is passed, it will be used to create
  8650. * a "_.pluck" or "_.where" style callback, respectively.
  8651. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  8652. * @returns {Array} Returns a new array of elements that did **not** pass the
  8653. * callback check.
  8654. * @example
  8655. *
  8656. * var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
  8657. * // => [1, 3, 5]
  8658. *
  8659. * var food = [
  8660. * { 'name': 'apple', 'organic': false, 'type': 'fruit' },
  8661. * { 'name': 'carrot', 'organic': true, 'type': 'vegetable' }
  8662. * ];
  8663. *
  8664. * // using "_.pluck" callback shorthand
  8665. * _.reject(food, 'organic');
  8666. * // => [{ 'name': 'apple', 'organic': false, 'type': 'fruit' }]
  8667. *
  8668. * // using "_.where" callback shorthand
  8669. * _.reject(food, { 'type': 'fruit' });
  8670. * // => [{ 'name': 'carrot', 'organic': true, 'type': 'vegetable' }]
  8671. */
  8672. function reject(collection, callback, thisArg) {
  8673. callback = lodash.createCallback(callback, thisArg);
  8674. return filter(collection, function(value, index, collection) {
  8675. return !callback(value, index, collection);
  8676. });
  8677. }
  8678. /**
  8679. * Creates an array of shuffled `array` values, using a version of the
  8680. * Fisher-Yates shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle.
  8681. *
  8682. * @static
  8683. * @memberOf _
  8684. * @category Collections
  8685. * @param {Array|Object|String} collection The collection to shuffle.
  8686. * @returns {Array} Returns a new shuffled collection.
  8687. * @example
  8688. *
  8689. * _.shuffle([1, 2, 3, 4, 5, 6]);
  8690. * // => [4, 1, 6, 3, 5, 2]
  8691. */
  8692. function shuffle(collection) {
  8693. var index = -1,
  8694. length = collection ? collection.length : 0,
  8695. result = Array(typeof length == 'number' ? length : 0);
  8696. forEach(collection, function(value) {
  8697. var rand = floor(nativeRandom() * (++index + 1));
  8698. result[index] = result[rand];
  8699. result[rand] = value;
  8700. });
  8701. return result;
  8702. }
  8703. /**
  8704. * Gets the size of the `collection` by returning `collection.length` for arrays
  8705. * and array-like objects or the number of own enumerable properties for objects.
  8706. *
  8707. * @static
  8708. * @memberOf _
  8709. * @category Collections
  8710. * @param {Array|Object|String} collection The collection to inspect.
  8711. * @returns {Number} Returns `collection.length` or number of own enumerable properties.
  8712. * @example
  8713. *
  8714. * _.size([1, 2]);
  8715. * // => 2
  8716. *
  8717. * _.size({ 'one': 1, 'two': 2, 'three': 3 });
  8718. * // => 3
  8719. *
  8720. * _.size('curly');
  8721. * // => 5
  8722. */
  8723. function size(collection) {
  8724. var length = collection ? collection.length : 0;
  8725. return typeof length == 'number' ? length : keys(collection).length;
  8726. }
  8727. /**
  8728. * Checks if the `callback` returns a truthy value for **any** element of a
  8729. * `collection`. The function returns as soon as it finds passing value, and
  8730. * does not iterate over the entire `collection`. The `callback` is bound to
  8731. * `thisArg` and invoked with three arguments; (value, index|key, collection).
  8732. *
  8733. * If a property name is passed for `callback`, the created "_.pluck" style
  8734. * callback will return the property value of the given element.
  8735. *
  8736. * If an object is passed for `callback`, the created "_.where" style callback
  8737. * will return `true` for elements that have the properties of the given object,
  8738. * else `false`.
  8739. *
  8740. * @static
  8741. * @memberOf _
  8742. * @alias any
  8743. * @category Collections
  8744. * @param {Array|Object|String} collection The collection to iterate over.
  8745. * @param {Function|Object|String} [callback=identity] The function called per
  8746. * iteration. If a property name or object is passed, it will be used to create
  8747. * a "_.pluck" or "_.where" style callback, respectively.
  8748. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  8749. * @returns {Boolean} Returns `true` if any element passes the callback check,
  8750. * else `false`.
  8751. * @example
  8752. *
  8753. * _.some([null, 0, 'yes', false], Boolean);
  8754. * // => true
  8755. *
  8756. * var food = [
  8757. * { 'name': 'apple', 'organic': false, 'type': 'fruit' },
  8758. * { 'name': 'carrot', 'organic': true, 'type': 'vegetable' }
  8759. * ];
  8760. *
  8761. * // using "_.pluck" callback shorthand
  8762. * _.some(food, 'organic');
  8763. * // => true
  8764. *
  8765. * // using "_.where" callback shorthand
  8766. * _.some(food, { 'type': 'meat' });
  8767. * // => false
  8768. */
  8769. function some(collection, callback, thisArg) {
  8770. var result;
  8771. callback = lodash.createCallback(callback, thisArg);
  8772. var index = -1,
  8773. length = collection ? collection.length : 0;
  8774. if (typeof length == 'number') {
  8775. while (++index < length) {
  8776. if ((result = callback(collection[index], index, collection))) {
  8777. break;
  8778. }
  8779. }
  8780. } else {
  8781. forOwn(collection, function(value, index, collection) {
  8782. return !(result = callback(value, index, collection));
  8783. });
  8784. }
  8785. return !!result;
  8786. }
  8787. /**
  8788. * Creates an array of elements, sorted in ascending order by the results of
  8789. * running each element in the `collection` through the `callback`. This method
  8790. * performs a stable sort, that is, it will preserve the original sort order of
  8791. * equal elements. The `callback` is bound to `thisArg` and invoked with three
  8792. * arguments; (value, index|key, collection).
  8793. *
  8794. * If a property name is passed for `callback`, the created "_.pluck" style
  8795. * callback will return the property value of the given element.
  8796. *
  8797. * If an object is passed for `callback`, the created "_.where" style callback
  8798. * will return `true` for elements that have the properties of the given object,
  8799. * else `false`.
  8800. *
  8801. * @static
  8802. * @memberOf _
  8803. * @category Collections
  8804. * @param {Array|Object|String} collection The collection to iterate over.
  8805. * @param {Function|Object|String} [callback=identity] The function called per
  8806. * iteration. If a property name or object is passed, it will be used to create
  8807. * a "_.pluck" or "_.where" style callback, respectively.
  8808. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  8809. * @returns {Array} Returns a new array of sorted elements.
  8810. * @example
  8811. *
  8812. * _.sortBy([1, 2, 3], function(num) { return Math.sin(num); });
  8813. * // => [3, 1, 2]
  8814. *
  8815. * _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math);
  8816. * // => [3, 1, 2]
  8817. *
  8818. * // using "_.pluck" callback shorthand
  8819. * _.sortBy(['banana', 'strawberry', 'apple'], 'length');
  8820. * // => ['apple', 'banana', 'strawberry']
  8821. */
  8822. function sortBy(collection, callback, thisArg) {
  8823. var index = -1,
  8824. length = collection ? collection.length : 0,
  8825. result = Array(typeof length == 'number' ? length : 0);
  8826. callback = lodash.createCallback(callback, thisArg);
  8827. forEach(collection, function(value, key, collection) {
  8828. var object = result[++index] = getObject();
  8829. object.criteria = callback(value, key, collection);
  8830. object.index = index;
  8831. object.value = value;
  8832. });
  8833. length = result.length;
  8834. result.sort(compareAscending);
  8835. while (length--) {
  8836. var object = result[length];
  8837. result[length] = object.value;
  8838. releaseObject(object);
  8839. }
  8840. return result;
  8841. }
  8842. /**
  8843. * Converts the `collection` to an array.
  8844. *
  8845. * @static
  8846. * @memberOf _
  8847. * @category Collections
  8848. * @param {Array|Object|String} collection The collection to convert.
  8849. * @returns {Array} Returns the new converted array.
  8850. * @example
  8851. *
  8852. * (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
  8853. * // => [2, 3, 4]
  8854. */
  8855. function toArray(collection) {
  8856. if (collection && typeof collection.length == 'number') {
  8857. return slice(collection);
  8858. }
  8859. return values(collection);
  8860. }
  8861. /**
  8862. * Examines each element in a `collection`, returning an array of all elements
  8863. * that have the given `properties`. When checking `properties`, this method
  8864. * performs a deep comparison between values to determine if they are equivalent
  8865. * to each other.
  8866. *
  8867. * @static
  8868. * @memberOf _
  8869. * @type Function
  8870. * @category Collections
  8871. * @param {Array|Object|String} collection The collection to iterate over.
  8872. * @param {Object} properties The object of property values to filter by.
  8873. * @returns {Array} Returns a new array of elements that have the given `properties`.
  8874. * @example
  8875. *
  8876. * var stooges = [
  8877. * { 'name': 'moe', 'age': 40 },
  8878. * { 'name': 'larry', 'age': 50 }
  8879. * ];
  8880. *
  8881. * _.where(stooges, { 'age': 40 });
  8882. * // => [{ 'name': 'moe', 'age': 40 }]
  8883. */
  8884. var where = filter;
  8885. /*--------------------------------------------------------------------------*/
  8886. /**
  8887. * Creates an array with all falsey values of `array` removed. The values
  8888. * `false`, `null`, `0`, `""`, `undefined` and `NaN` are all falsey.
  8889. *
  8890. * @static
  8891. * @memberOf _
  8892. * @category Arrays
  8893. * @param {Array} array The array to compact.
  8894. * @returns {Array} Returns a new filtered array.
  8895. * @example
  8896. *
  8897. * _.compact([0, 1, false, 2, '', 3]);
  8898. * // => [1, 2, 3]
  8899. */
  8900. function compact(array) {
  8901. var index = -1,
  8902. length = array ? array.length : 0,
  8903. result = [];
  8904. while (++index < length) {
  8905. var value = array[index];
  8906. if (value) {
  8907. result.push(value);
  8908. }
  8909. }
  8910. return result;
  8911. }
  8912. /**
  8913. * Creates an array of `array` elements not present in the other arrays
  8914. * using strict equality for comparisons, i.e. `===`.
  8915. *
  8916. * @static
  8917. * @memberOf _
  8918. * @category Arrays
  8919. * @param {Array} array The array to process.
  8920. * @param {Array} [array1, array2, ...] Arrays to check.
  8921. * @returns {Array} Returns a new array of `array` elements not present in the
  8922. * other arrays.
  8923. * @example
  8924. *
  8925. * _.difference([1, 2, 3, 4, 5], [5, 2, 10]);
  8926. * // => [1, 3, 4]
  8927. */
  8928. function difference(array) {
  8929. var index = -1,
  8930. indexOf = getIndexOf(),
  8931. length = array ? array.length : 0,
  8932. seen = concat.apply(arrayRef, nativeSlice.call(arguments, 1)),
  8933. result = [];
  8934. var isLarge = length >= largeArraySize && indexOf === basicIndexOf;
  8935. if (isLarge) {
  8936. var cache = createCache(seen);
  8937. if (cache) {
  8938. indexOf = cacheIndexOf;
  8939. seen = cache;
  8940. } else {
  8941. isLarge = false;
  8942. }
  8943. }
  8944. while (++index < length) {
  8945. var value = array[index];
  8946. if (indexOf(seen, value) < 0) {
  8947. result.push(value);
  8948. }
  8949. }
  8950. if (isLarge) {
  8951. releaseObject(seen);
  8952. }
  8953. return result;
  8954. }
  8955. /**
  8956. * This method is similar to `_.find`, except that it returns the index of
  8957. * the element that passes the callback check, instead of the element itself.
  8958. *
  8959. * @static
  8960. * @memberOf _
  8961. * @category Arrays
  8962. * @param {Array} array The array to search.
  8963. * @param {Function|Object|String} [callback=identity] The function called per
  8964. * iteration. If a property name or object is passed, it will be used to create
  8965. * a "_.pluck" or "_.where" style callback, respectively.
  8966. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  8967. * @returns {Mixed} Returns the index of the found element, else `-1`.
  8968. * @example
  8969. *
  8970. * _.findIndex(['apple', 'banana', 'beet'], function(food) {
  8971. * return /^b/.test(food);
  8972. * });
  8973. * // => 1
  8974. */
  8975. function findIndex(array, callback, thisArg) {
  8976. var index = -1,
  8977. length = array ? array.length : 0;
  8978. callback = lodash.createCallback(callback, thisArg);
  8979. while (++index < length) {
  8980. if (callback(array[index], index, array)) {
  8981. return index;
  8982. }
  8983. }
  8984. return -1;
  8985. }
  8986. /**
  8987. * Gets the first element of the `array`. If a number `n` is passed, the first
  8988. * `n` elements of the `array` are returned. If a `callback` function is passed,
  8989. * elements at the beginning of the array are returned as long as the `callback`
  8990. * returns truthy. The `callback` is bound to `thisArg` and invoked with three
  8991. * arguments; (value, index, array).
  8992. *
  8993. * If a property name is passed for `callback`, the created "_.pluck" style
  8994. * callback will return the property value of the given element.
  8995. *
  8996. * If an object is passed for `callback`, the created "_.where" style callback
  8997. * will return `true` for elements that have the properties of the given object,
  8998. * else `false`.
  8999. *
  9000. * @static
  9001. * @memberOf _
  9002. * @alias head, take
  9003. * @category Arrays
  9004. * @param {Array} array The array to query.
  9005. * @param {Function|Object|Number|String} [callback|n] The function called
  9006. * per element or the number of elements to return. If a property name or
  9007. * object is passed, it will be used to create a "_.pluck" or "_.where"
  9008. * style callback, respectively.
  9009. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  9010. * @returns {Mixed} Returns the first element(s) of `array`.
  9011. * @example
  9012. *
  9013. * _.first([1, 2, 3]);
  9014. * // => 1
  9015. *
  9016. * _.first([1, 2, 3], 2);
  9017. * // => [1, 2]
  9018. *
  9019. * _.first([1, 2, 3], function(num) {
  9020. * return num < 3;
  9021. * });
  9022. * // => [1, 2]
  9023. *
  9024. * var food = [
  9025. * { 'name': 'banana', 'organic': true },
  9026. * { 'name': 'beet', 'organic': false },
  9027. * ];
  9028. *
  9029. * // using "_.pluck" callback shorthand
  9030. * _.first(food, 'organic');
  9031. * // => [{ 'name': 'banana', 'organic': true }]
  9032. *
  9033. * var food = [
  9034. * { 'name': 'apple', 'type': 'fruit' },
  9035. * { 'name': 'banana', 'type': 'fruit' },
  9036. * { 'name': 'beet', 'type': 'vegetable' }
  9037. * ];
  9038. *
  9039. * // using "_.where" callback shorthand
  9040. * _.first(food, { 'type': 'fruit' });
  9041. * // => [{ 'name': 'apple', 'type': 'fruit' }, { 'name': 'banana', 'type': 'fruit' }]
  9042. */
  9043. function first(array, callback, thisArg) {
  9044. if (array) {
  9045. var n = 0,
  9046. length = array.length;
  9047. if (typeof callback != 'number' && callback != null) {
  9048. var index = -1;
  9049. callback = lodash.createCallback(callback, thisArg);
  9050. while (++index < length && callback(array[index], index, array)) {
  9051. n++;
  9052. }
  9053. } else {
  9054. n = callback;
  9055. if (n == null || thisArg) {
  9056. return array[0];
  9057. }
  9058. }
  9059. return slice(array, 0, nativeMin(nativeMax(0, n), length));
  9060. }
  9061. }
  9062. /**
  9063. * Flattens a nested array (the nesting can be to any depth). If `isShallow`
  9064. * is truthy, `array` will only be flattened a single level. If `callback`
  9065. * is passed, each element of `array` is passed through a `callback` before
  9066. * flattening. The `callback` is bound to `thisArg` and invoked with three
  9067. * arguments; (value, index, array).
  9068. *
  9069. * If a property name is passed for `callback`, the created "_.pluck" style
  9070. * callback will return the property value of the given element.
  9071. *
  9072. * If an object is passed for `callback`, the created "_.where" style callback
  9073. * will return `true` for elements that have the properties of the given object,
  9074. * else `false`.
  9075. *
  9076. * @static
  9077. * @memberOf _
  9078. * @category Arrays
  9079. * @param {Array} array The array to flatten.
  9080. * @param {Boolean} [isShallow=false] A flag to indicate only flattening a single level.
  9081. * @param {Function|Object|String} [callback=identity] The function called per
  9082. * iteration. If a property name or object is passed, it will be used to create
  9083. * a "_.pluck" or "_.where" style callback, respectively.
  9084. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  9085. * @returns {Array} Returns a new flattened array.
  9086. * @example
  9087. *
  9088. * _.flatten([1, [2], [3, [[4]]]]);
  9089. * // => [1, 2, 3, 4];
  9090. *
  9091. * _.flatten([1, [2], [3, [[4]]]], true);
  9092. * // => [1, 2, 3, [[4]]];
  9093. *
  9094. * var stooges = [
  9095. * { 'name': 'curly', 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] },
  9096. * { 'name': 'moe', 'quotes': ['Spread out!', 'You knucklehead!'] }
  9097. * ];
  9098. *
  9099. * // using "_.pluck" callback shorthand
  9100. * _.flatten(stooges, 'quotes');
  9101. * // => ['Oh, a wise guy, eh?', 'Poifect!', 'Spread out!', 'You knucklehead!']
  9102. */
  9103. var flatten = overloadWrapper(function flatten(array, isShallow, callback) {
  9104. var index = -1,
  9105. length = array ? array.length : 0,
  9106. result = [];
  9107. while (++index < length) {
  9108. var value = array[index];
  9109. if (callback) {
  9110. value = callback(value, index, array);
  9111. }
  9112. // recursively flatten arrays (susceptible to call stack limits)
  9113. if (isArray(value)) {
  9114. push.apply(result, isShallow ? value : flatten(value));
  9115. } else {
  9116. result.push(value);
  9117. }
  9118. }
  9119. return result;
  9120. });
  9121. /**
  9122. * Gets the index at which the first occurrence of `value` is found using
  9123. * strict equality for comparisons, i.e. `===`. If the `array` is already
  9124. * sorted, passing `true` for `fromIndex` will run a faster binary search.
  9125. *
  9126. * @static
  9127. * @memberOf _
  9128. * @category Arrays
  9129. * @param {Array} array The array to search.
  9130. * @param {Mixed} value The value to search for.
  9131. * @param {Boolean|Number} [fromIndex=0] The index to search from or `true` to
  9132. * perform a binary search on a sorted `array`.
  9133. * @returns {Number} Returns the index of the matched value or `-1`.
  9134. * @example
  9135. *
  9136. * _.indexOf([1, 2, 3, 1, 2, 3], 2);
  9137. * // => 1
  9138. *
  9139. * _.indexOf([1, 2, 3, 1, 2, 3], 2, 3);
  9140. * // => 4
  9141. *
  9142. * _.indexOf([1, 1, 2, 2, 3, 3], 2, true);
  9143. * // => 2
  9144. */
  9145. function indexOf(array, value, fromIndex) {
  9146. if (typeof fromIndex == 'number') {
  9147. var length = array ? array.length : 0;
  9148. fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0);
  9149. } else if (fromIndex) {
  9150. var index = sortedIndex(array, value);
  9151. return array[index] === value ? index : -1;
  9152. }
  9153. return array ? basicIndexOf(array, value, fromIndex) : -1;
  9154. }
  9155. /**
  9156. * Gets all but the last element of `array`. If a number `n` is passed, the
  9157. * last `n` elements are excluded from the result. If a `callback` function
  9158. * is passed, elements at the end of the array are excluded from the result
  9159. * as long as the `callback` returns truthy. The `callback` is bound to
  9160. * `thisArg` and invoked with three arguments; (value, index, array).
  9161. *
  9162. * If a property name is passed for `callback`, the created "_.pluck" style
  9163. * callback will return the property value of the given element.
  9164. *
  9165. * If an object is passed for `callback`, the created "_.where" style callback
  9166. * will return `true` for elements that have the properties of the given object,
  9167. * else `false`.
  9168. *
  9169. * @static
  9170. * @memberOf _
  9171. * @category Arrays
  9172. * @param {Array} array The array to query.
  9173. * @param {Function|Object|Number|String} [callback|n=1] The function called
  9174. * per element or the number of elements to exclude. If a property name or
  9175. * object is passed, it will be used to create a "_.pluck" or "_.where"
  9176. * style callback, respectively.
  9177. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  9178. * @returns {Array} Returns a slice of `array`.
  9179. * @example
  9180. *
  9181. * _.initial([1, 2, 3]);
  9182. * // => [1, 2]
  9183. *
  9184. * _.initial([1, 2, 3], 2);
  9185. * // => [1]
  9186. *
  9187. * _.initial([1, 2, 3], function(num) {
  9188. * return num > 1;
  9189. * });
  9190. * // => [1]
  9191. *
  9192. * var food = [
  9193. * { 'name': 'beet', 'organic': false },
  9194. * { 'name': 'carrot', 'organic': true }
  9195. * ];
  9196. *
  9197. * // using "_.pluck" callback shorthand
  9198. * _.initial(food, 'organic');
  9199. * // => [{ 'name': 'beet', 'organic': false }]
  9200. *
  9201. * var food = [
  9202. * { 'name': 'banana', 'type': 'fruit' },
  9203. * { 'name': 'beet', 'type': 'vegetable' },
  9204. * { 'name': 'carrot', 'type': 'vegetable' }
  9205. * ];
  9206. *
  9207. * // using "_.where" callback shorthand
  9208. * _.initial(food, { 'type': 'vegetable' });
  9209. * // => [{ 'name': 'banana', 'type': 'fruit' }]
  9210. */
  9211. function initial(array, callback, thisArg) {
  9212. if (!array) {
  9213. return [];
  9214. }
  9215. var n = 0,
  9216. length = array.length;
  9217. if (typeof callback != 'number' && callback != null) {
  9218. var index = length;
  9219. callback = lodash.createCallback(callback, thisArg);
  9220. while (index-- && callback(array[index], index, array)) {
  9221. n++;
  9222. }
  9223. } else {
  9224. n = (callback == null || thisArg) ? 1 : callback || n;
  9225. }
  9226. return slice(array, 0, nativeMin(nativeMax(0, length - n), length));
  9227. }
  9228. /**
  9229. * Computes the intersection of all the passed-in arrays using strict equality
  9230. * for comparisons, i.e. `===`.
  9231. *
  9232. * @static
  9233. * @memberOf _
  9234. * @category Arrays
  9235. * @param {Array} [array1, array2, ...] Arrays to process.
  9236. * @returns {Array} Returns a new array of unique elements that are present
  9237. * in **all** of the arrays.
  9238. * @example
  9239. *
  9240. * _.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
  9241. * // => [1, 2]
  9242. */
  9243. function intersection(array) {
  9244. var args = arguments,
  9245. argsLength = args.length,
  9246. argsIndex = -1,
  9247. caches = getArray(),
  9248. index = -1,
  9249. indexOf = getIndexOf(),
  9250. length = array ? array.length : 0,
  9251. result = [],
  9252. seen = getArray();
  9253. while (++argsIndex < argsLength) {
  9254. var value = args[argsIndex];
  9255. caches[argsIndex] = indexOf === basicIndexOf &&
  9256. (value ? value.length : 0) >= largeArraySize &&
  9257. createCache(argsIndex ? args[argsIndex] : seen);
  9258. }
  9259. outer:
  9260. while (++index < length) {
  9261. var cache = caches[0];
  9262. value = array[index];
  9263. if ((cache ? cacheIndexOf(cache, value) : indexOf(seen, value)) < 0) {
  9264. argsIndex = argsLength;
  9265. (cache || seen).push(value);
  9266. while (--argsIndex) {
  9267. cache = caches[argsIndex];
  9268. if ((cache ? cacheIndexOf(cache, value) : indexOf(args[argsIndex], value)) < 0) {
  9269. continue outer;
  9270. }
  9271. }
  9272. result.push(value);
  9273. }
  9274. }
  9275. while (argsLength--) {
  9276. cache = caches[argsLength];
  9277. if (cache) {
  9278. releaseObject(cache);
  9279. }
  9280. }
  9281. releaseArray(caches);
  9282. releaseArray(seen);
  9283. return result;
  9284. }
  9285. /**
  9286. * Gets the last element of the `array`. If a number `n` is passed, the
  9287. * last `n` elements of the `array` are returned. If a `callback` function
  9288. * is passed, elements at the end of the array are returned as long as the
  9289. * `callback` returns truthy. The `callback` is bound to `thisArg` and
  9290. * invoked with three arguments;(value, index, array).
  9291. *
  9292. *
  9293. * If a property name is passed for `callback`, the created "_.pluck" style
  9294. * callback will return the property value of the given element.
  9295. *
  9296. * If an object is passed for `callback`, the created "_.where" style callback
  9297. * will return `true` for elements that have the properties of the given object,
  9298. * else `false`.
  9299. *
  9300. * @static
  9301. * @memberOf _
  9302. * @category Arrays
  9303. * @param {Array} array The array to query.
  9304. * @param {Function|Object|Number|String} [callback|n] The function called
  9305. * per element or the number of elements to return. If a property name or
  9306. * object is passed, it will be used to create a "_.pluck" or "_.where"
  9307. * style callback, respectively.
  9308. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  9309. * @returns {Mixed} Returns the last element(s) of `array`.
  9310. * @example
  9311. *
  9312. * _.last([1, 2, 3]);
  9313. * // => 3
  9314. *
  9315. * _.last([1, 2, 3], 2);
  9316. * // => [2, 3]
  9317. *
  9318. * _.last([1, 2, 3], function(num) {
  9319. * return num > 1;
  9320. * });
  9321. * // => [2, 3]
  9322. *
  9323. * var food = [
  9324. * { 'name': 'beet', 'organic': false },
  9325. * { 'name': 'carrot', 'organic': true }
  9326. * ];
  9327. *
  9328. * // using "_.pluck" callback shorthand
  9329. * _.last(food, 'organic');
  9330. * // => [{ 'name': 'carrot', 'organic': true }]
  9331. *
  9332. * var food = [
  9333. * { 'name': 'banana', 'type': 'fruit' },
  9334. * { 'name': 'beet', 'type': 'vegetable' },
  9335. * { 'name': 'carrot', 'type': 'vegetable' }
  9336. * ];
  9337. *
  9338. * // using "_.where" callback shorthand
  9339. * _.last(food, { 'type': 'vegetable' });
  9340. * // => [{ 'name': 'beet', 'type': 'vegetable' }, { 'name': 'carrot', 'type': 'vegetable' }]
  9341. */
  9342. function last(array, callback, thisArg) {
  9343. if (array) {
  9344. var n = 0,
  9345. length = array.length;
  9346. if (typeof callback != 'number' && callback != null) {
  9347. var index = length;
  9348. callback = lodash.createCallback(callback, thisArg);
  9349. while (index-- && callback(array[index], index, array)) {
  9350. n++;
  9351. }
  9352. } else {
  9353. n = callback;
  9354. if (n == null || thisArg) {
  9355. return array[length - 1];
  9356. }
  9357. }
  9358. return slice(array, nativeMax(0, length - n));
  9359. }
  9360. }
  9361. /**
  9362. * Gets the index at which the last occurrence of `value` is found using strict
  9363. * equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used
  9364. * as the offset from the end of the collection.
  9365. *
  9366. * @static
  9367. * @memberOf _
  9368. * @category Arrays
  9369. * @param {Array} array The array to search.
  9370. * @param {Mixed} value The value to search for.
  9371. * @param {Number} [fromIndex=array.length-1] The index to search from.
  9372. * @returns {Number} Returns the index of the matched value or `-1`.
  9373. * @example
  9374. *
  9375. * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
  9376. * // => 4
  9377. *
  9378. * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3);
  9379. * // => 1
  9380. */
  9381. function lastIndexOf(array, value, fromIndex) {
  9382. var index = array ? array.length : 0;
  9383. if (typeof fromIndex == 'number') {
  9384. index = (fromIndex < 0 ? nativeMax(0, index + fromIndex) : nativeMin(fromIndex, index - 1)) + 1;
  9385. }
  9386. while (index--) {
  9387. if (array[index] === value) {
  9388. return index;
  9389. }
  9390. }
  9391. return -1;
  9392. }
  9393. /**
  9394. * Creates an array of numbers (positive and/or negative) progressing from
  9395. * `start` up to but not including `end`.
  9396. *
  9397. * @static
  9398. * @memberOf _
  9399. * @category Arrays
  9400. * @param {Number} [start=0] The start of the range.
  9401. * @param {Number} end The end of the range.
  9402. * @param {Number} [step=1] The value to increment or decrement by.
  9403. * @returns {Array} Returns a new range array.
  9404. * @example
  9405. *
  9406. * _.range(10);
  9407. * // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  9408. *
  9409. * _.range(1, 11);
  9410. * // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  9411. *
  9412. * _.range(0, 30, 5);
  9413. * // => [0, 5, 10, 15, 20, 25]
  9414. *
  9415. * _.range(0, -10, -1);
  9416. * // => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
  9417. *
  9418. * _.range(0);
  9419. * // => []
  9420. */
  9421. function range(start, end, step) {
  9422. start = +start || 0;
  9423. step = +step || 1;
  9424. if (end == null) {
  9425. end = start;
  9426. start = 0;
  9427. }
  9428. // use `Array(length)` so V8 will avoid the slower "dictionary" mode
  9429. // http://youtu.be/XAqIpGU8ZZk#t=17m25s
  9430. var index = -1,
  9431. length = nativeMax(0, ceil((end - start) / step)),
  9432. result = Array(length);
  9433. while (++index < length) {
  9434. result[index] = start;
  9435. start += step;
  9436. }
  9437. return result;
  9438. }
  9439. /**
  9440. * The opposite of `_.initial`, this method gets all but the first value of
  9441. * `array`. If a number `n` is passed, the first `n` values are excluded from
  9442. * the result. If a `callback` function is passed, elements at the beginning
  9443. * of the array are excluded from the result as long as the `callback` returns
  9444. * truthy. The `callback` is bound to `thisArg` and invoked with three
  9445. * arguments; (value, index, array).
  9446. *
  9447. * If a property name is passed for `callback`, the created "_.pluck" style
  9448. * callback will return the property value of the given element.
  9449. *
  9450. * If an object is passed for `callback`, the created "_.where" style callback
  9451. * will return `true` for elements that have the properties of the given object,
  9452. * else `false`.
  9453. *
  9454. * @static
  9455. * @memberOf _
  9456. * @alias drop, tail
  9457. * @category Arrays
  9458. * @param {Array} array The array to query.
  9459. * @param {Function|Object|Number|String} [callback|n=1] The function called
  9460. * per element or the number of elements to exclude. If a property name or
  9461. * object is passed, it will be used to create a "_.pluck" or "_.where"
  9462. * style callback, respectively.
  9463. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  9464. * @returns {Array} Returns a slice of `array`.
  9465. * @example
  9466. *
  9467. * _.rest([1, 2, 3]);
  9468. * // => [2, 3]
  9469. *
  9470. * _.rest([1, 2, 3], 2);
  9471. * // => [3]
  9472. *
  9473. * _.rest([1, 2, 3], function(num) {
  9474. * return num < 3;
  9475. * });
  9476. * // => [3]
  9477. *
  9478. * var food = [
  9479. * { 'name': 'banana', 'organic': true },
  9480. * { 'name': 'beet', 'organic': false },
  9481. * ];
  9482. *
  9483. * // using "_.pluck" callback shorthand
  9484. * _.rest(food, 'organic');
  9485. * // => [{ 'name': 'beet', 'organic': false }]
  9486. *
  9487. * var food = [
  9488. * { 'name': 'apple', 'type': 'fruit' },
  9489. * { 'name': 'banana', 'type': 'fruit' },
  9490. * { 'name': 'beet', 'type': 'vegetable' }
  9491. * ];
  9492. *
  9493. * // using "_.where" callback shorthand
  9494. * _.rest(food, { 'type': 'fruit' });
  9495. * // => [{ 'name': 'beet', 'type': 'vegetable' }]
  9496. */
  9497. function rest(array, callback, thisArg) {
  9498. if (typeof callback != 'number' && callback != null) {
  9499. var n = 0,
  9500. index = -1,
  9501. length = array ? array.length : 0;
  9502. callback = lodash.createCallback(callback, thisArg);
  9503. while (++index < length && callback(array[index], index, array)) {
  9504. n++;
  9505. }
  9506. } else {
  9507. n = (callback == null || thisArg) ? 1 : nativeMax(0, callback);
  9508. }
  9509. return slice(array, n);
  9510. }
  9511. /**
  9512. * Uses a binary search to determine the smallest index at which the `value`
  9513. * should be inserted into `array` in order to maintain the sort order of the
  9514. * sorted `array`. If `callback` is passed, it will be executed for `value` and
  9515. * each element in `array` to compute their sort ranking. The `callback` is
  9516. * bound to `thisArg` and invoked with one argument; (value).
  9517. *
  9518. * If a property name is passed for `callback`, the created "_.pluck" style
  9519. * callback will return the property value of the given element.
  9520. *
  9521. * If an object is passed for `callback`, the created "_.where" style callback
  9522. * will return `true` for elements that have the properties of the given object,
  9523. * else `false`.
  9524. *
  9525. * @static
  9526. * @memberOf _
  9527. * @category Arrays
  9528. * @param {Array} array The array to inspect.
  9529. * @param {Mixed} value The value to evaluate.
  9530. * @param {Function|Object|String} [callback=identity] The function called per
  9531. * iteration. If a property name or object is passed, it will be used to create
  9532. * a "_.pluck" or "_.where" style callback, respectively.
  9533. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  9534. * @returns {Number} Returns the index at which the value should be inserted
  9535. * into `array`.
  9536. * @example
  9537. *
  9538. * _.sortedIndex([20, 30, 50], 40);
  9539. * // => 2
  9540. *
  9541. * // using "_.pluck" callback shorthand
  9542. * _.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
  9543. * // => 2
  9544. *
  9545. * var dict = {
  9546. * 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 }
  9547. * };
  9548. *
  9549. * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
  9550. * return dict.wordToNumber[word];
  9551. * });
  9552. * // => 2
  9553. *
  9554. * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
  9555. * return this.wordToNumber[word];
  9556. * }, dict);
  9557. * // => 2
  9558. */
  9559. function sortedIndex(array, value, callback, thisArg) {
  9560. var low = 0,
  9561. high = array ? array.length : low;
  9562. // explicitly reference `identity` for better inlining in Firefox
  9563. callback = callback ? lodash.createCallback(callback, thisArg, 1) : identity;
  9564. value = callback(value);
  9565. while (low < high) {
  9566. var mid = (low + high) >>> 1;
  9567. (callback(array[mid]) < value)
  9568. ? low = mid + 1
  9569. : high = mid;
  9570. }
  9571. return low;
  9572. }
  9573. /**
  9574. * Computes the union of the passed-in arrays using strict equality for
  9575. * comparisons, i.e. `===`.
  9576. *
  9577. * @static
  9578. * @memberOf _
  9579. * @category Arrays
  9580. * @param {Array} [array1, array2, ...] Arrays to process.
  9581. * @returns {Array} Returns a new array of unique values, in order, that are
  9582. * present in one or more of the arrays.
  9583. * @example
  9584. *
  9585. * _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
  9586. * // => [1, 2, 3, 101, 10]
  9587. */
  9588. function union(array) {
  9589. if (!isArray(array)) {
  9590. arguments[0] = array ? nativeSlice.call(array) : arrayRef;
  9591. }
  9592. return uniq(concat.apply(arrayRef, arguments));
  9593. }
  9594. /**
  9595. * Creates a duplicate-value-free version of the `array` using strict equality
  9596. * for comparisons, i.e. `===`. If the `array` is already sorted, passing `true`
  9597. * for `isSorted` will run a faster algorithm. If `callback` is passed, each
  9598. * element of `array` is passed through the `callback` before uniqueness is computed.
  9599. * The `callback` is bound to `thisArg` and invoked with three arguments; (value, index, array).
  9600. *
  9601. * If a property name is passed for `callback`, the created "_.pluck" style
  9602. * callback will return the property value of the given element.
  9603. *
  9604. * If an object is passed for `callback`, the created "_.where" style callback
  9605. * will return `true` for elements that have the properties of the given object,
  9606. * else `false`.
  9607. *
  9608. * @static
  9609. * @memberOf _
  9610. * @alias unique
  9611. * @category Arrays
  9612. * @param {Array} array The array to process.
  9613. * @param {Boolean} [isSorted=false] A flag to indicate that the `array` is already sorted.
  9614. * @param {Function|Object|String} [callback=identity] The function called per
  9615. * iteration. If a property name or object is passed, it will be used to create
  9616. * a "_.pluck" or "_.where" style callback, respectively.
  9617. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  9618. * @returns {Array} Returns a duplicate-value-free array.
  9619. * @example
  9620. *
  9621. * _.uniq([1, 2, 1, 3, 1]);
  9622. * // => [1, 2, 3]
  9623. *
  9624. * _.uniq([1, 1, 2, 2, 3], true);
  9625. * // => [1, 2, 3]
  9626. *
  9627. * _.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) { return letter.toLowerCase(); });
  9628. * // => ['A', 'b', 'C']
  9629. *
  9630. * _.uniq([1, 2.5, 3, 1.5, 2, 3.5], function(num) { return this.floor(num); }, Math);
  9631. * // => [1, 2.5, 3]
  9632. *
  9633. * // using "_.pluck" callback shorthand
  9634. * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
  9635. * // => [{ 'x': 1 }, { 'x': 2 }]
  9636. */
  9637. var uniq = overloadWrapper(function(array, isSorted, callback) {
  9638. var index = -1,
  9639. indexOf = getIndexOf(),
  9640. length = array ? array.length : 0,
  9641. result = [];
  9642. var isLarge = !isSorted && length >= largeArraySize && indexOf === basicIndexOf,
  9643. seen = (callback || isLarge) ? getArray() : result;
  9644. if (isLarge) {
  9645. var cache = createCache(seen);
  9646. if (cache) {
  9647. indexOf = cacheIndexOf;
  9648. seen = cache;
  9649. } else {
  9650. isLarge = false;
  9651. seen = callback ? seen : (releaseArray(seen), result);
  9652. }
  9653. }
  9654. while (++index < length) {
  9655. var value = array[index],
  9656. computed = callback ? callback(value, index, array) : value;
  9657. if (isSorted
  9658. ? !index || seen[seen.length - 1] !== computed
  9659. : indexOf(seen, computed) < 0
  9660. ) {
  9661. if (callback || isLarge) {
  9662. seen.push(computed);
  9663. }
  9664. result.push(value);
  9665. }
  9666. }
  9667. if (isLarge) {
  9668. releaseArray(seen.array);
  9669. releaseObject(seen);
  9670. } else if (callback) {
  9671. releaseArray(seen);
  9672. }
  9673. return result;
  9674. });
  9675. /**
  9676. * The inverse of `_.zip`, this method splits groups of elements into arrays
  9677. * composed of elements from each group at their corresponding indexes.
  9678. *
  9679. * @static
  9680. * @memberOf _
  9681. * @category Arrays
  9682. * @param {Array} array The array to process.
  9683. * @returns {Array} Returns a new array of the composed arrays.
  9684. * @example
  9685. *
  9686. * _.unzip([['moe', 30, true], ['larry', 40, false]]);
  9687. * // => [['moe', 'larry'], [30, 40], [true, false]];
  9688. */
  9689. function unzip(array) {
  9690. var index = -1,
  9691. length = array ? max(pluck(array, 'length')) : 0,
  9692. result = Array(length < 0 ? 0 : length);
  9693. while (++index < length) {
  9694. result[index] = pluck(array, index);
  9695. }
  9696. return result;
  9697. }
  9698. /**
  9699. * Creates an array with all occurrences of the passed values removed using
  9700. * strict equality for comparisons, i.e. `===`.
  9701. *
  9702. * @static
  9703. * @memberOf _
  9704. * @category Arrays
  9705. * @param {Array} array The array to filter.
  9706. * @param {Mixed} [value1, value2, ...] Values to remove.
  9707. * @returns {Array} Returns a new filtered array.
  9708. * @example
  9709. *
  9710. * _.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
  9711. * // => [2, 3, 4]
  9712. */
  9713. function without(array) {
  9714. return difference(array, nativeSlice.call(arguments, 1));
  9715. }
  9716. /**
  9717. * Groups the elements of each array at their corresponding indexes. Useful for
  9718. * separate data sources that are coordinated through matching array indexes.
  9719. * For a matrix of nested arrays, `_.zip.apply(...)` can transpose the matrix
  9720. * in a similar fashion.
  9721. *
  9722. * @static
  9723. * @memberOf _
  9724. * @category Arrays
  9725. * @param {Array} [array1, array2, ...] Arrays to process.
  9726. * @returns {Array} Returns a new array of grouped elements.
  9727. * @example
  9728. *
  9729. * _.zip(['moe', 'larry'], [30, 40], [true, false]);
  9730. * // => [['moe', 30, true], ['larry', 40, false]]
  9731. */
  9732. function zip(array) {
  9733. return array ? unzip(arguments) : [];
  9734. }
  9735. /**
  9736. * Creates an object composed from arrays of `keys` and `values`. Pass either
  9737. * a single two dimensional array, i.e. `[[key1, value1], [key2, value2]]`, or
  9738. * two arrays, one of `keys` and one of corresponding `values`.
  9739. *
  9740. * @static
  9741. * @memberOf _
  9742. * @alias object
  9743. * @category Arrays
  9744. * @param {Array} keys The array of keys.
  9745. * @param {Array} [values=[]] The array of values.
  9746. * @returns {Object} Returns an object composed of the given keys and
  9747. * corresponding values.
  9748. * @example
  9749. *
  9750. * _.zipObject(['moe', 'larry'], [30, 40]);
  9751. * // => { 'moe': 30, 'larry': 40 }
  9752. */
  9753. function zipObject(keys, values) {
  9754. var index = -1,
  9755. length = keys ? keys.length : 0,
  9756. result = {};
  9757. while (++index < length) {
  9758. var key = keys[index];
  9759. if (values) {
  9760. result[key] = values[index];
  9761. } else {
  9762. result[key[0]] = key[1];
  9763. }
  9764. }
  9765. return result;
  9766. }
  9767. /*--------------------------------------------------------------------------*/
  9768. /**
  9769. * If `n` is greater than `0`, a function is created that is restricted to
  9770. * executing `func`, with the `this` binding and arguments of the created
  9771. * function, only after it is called `n` times. If `n` is less than `1`,
  9772. * `func` is executed immediately, without a `this` binding or additional
  9773. * arguments, and its result is returned.
  9774. *
  9775. * @static
  9776. * @memberOf _
  9777. * @category Functions
  9778. * @param {Number} n The number of times the function must be called before
  9779. * it is executed.
  9780. * @param {Function} func The function to restrict.
  9781. * @returns {Function} Returns the new restricted function.
  9782. * @example
  9783. *
  9784. * var renderNotes = _.after(notes.length, render);
  9785. * _.forEach(notes, function(note) {
  9786. * note.asyncSave({ 'success': renderNotes });
  9787. * });
  9788. * // `renderNotes` is run once, after all notes have saved
  9789. */
  9790. function after(n, func) {
  9791. if (n < 1) {
  9792. return func();
  9793. }
  9794. return function() {
  9795. if (--n < 1) {
  9796. return func.apply(this, arguments);
  9797. }
  9798. };
  9799. }
  9800. /**
  9801. * Creates a function that, when called, invokes `func` with the `this`
  9802. * binding of `thisArg` and prepends any additional `bind` arguments to those
  9803. * passed to the bound function.
  9804. *
  9805. * @static
  9806. * @memberOf _
  9807. * @category Functions
  9808. * @param {Function} func The function to bind.
  9809. * @param {Mixed} [thisArg] The `this` binding of `func`.
  9810. * @param {Mixed} [arg1, arg2, ...] Arguments to be partially applied.
  9811. * @returns {Function} Returns the new bound function.
  9812. * @example
  9813. *
  9814. * var func = function(greeting) {
  9815. * return greeting + ' ' + this.name;
  9816. * };
  9817. *
  9818. * func = _.bind(func, { 'name': 'moe' }, 'hi');
  9819. * func();
  9820. * // => 'hi moe'
  9821. */
  9822. function bind(func, thisArg) {
  9823. // use `Function#bind` if it exists and is fast
  9824. // (in V8 `Function#bind` is slower except when partially applied)
  9825. return support.fastBind || (nativeBind && arguments.length > 2)
  9826. ? nativeBind.call.apply(nativeBind, arguments)
  9827. : createBound(func, thisArg, nativeSlice.call(arguments, 2));
  9828. }
  9829. /**
  9830. * Binds methods on `object` to `object`, overwriting the existing method.
  9831. * Method names may be specified as individual arguments or as arrays of method
  9832. * names. If no method names are provided, all the function properties of `object`
  9833. * will be bound.
  9834. *
  9835. * @static
  9836. * @memberOf _
  9837. * @category Functions
  9838. * @param {Object} object The object to bind and assign the bound methods to.
  9839. * @param {String} [methodName1, methodName2, ...] Method names on the object to bind.
  9840. * @returns {Object} Returns `object`.
  9841. * @example
  9842. *
  9843. * var view = {
  9844. * 'label': 'docs',
  9845. * 'onClick': function() { alert('clicked ' + this.label); }
  9846. * };
  9847. *
  9848. * _.bindAll(view);
  9849. * jQuery('#docs').on('click', view.onClick);
  9850. * // => alerts 'clicked docs', when the button is clicked
  9851. */
  9852. function bindAll(object) {
  9853. var funcs = arguments.length > 1 ? concat.apply(arrayRef, nativeSlice.call(arguments, 1)) : functions(object),
  9854. index = -1,
  9855. length = funcs.length;
  9856. while (++index < length) {
  9857. var key = funcs[index];
  9858. object[key] = bind(object[key], object);
  9859. }
  9860. return object;
  9861. }
  9862. /**
  9863. * Creates a function that, when called, invokes the method at `object[key]`
  9864. * and prepends any additional `bindKey` arguments to those passed to the bound
  9865. * function. This method differs from `_.bind` by allowing bound functions to
  9866. * reference methods that will be redefined or don't yet exist.
  9867. * See http://michaux.ca/articles/lazy-function-definition-pattern.
  9868. *
  9869. * @static
  9870. * @memberOf _
  9871. * @category Functions
  9872. * @param {Object} object The object the method belongs to.
  9873. * @param {String} key The key of the method.
  9874. * @param {Mixed} [arg1, arg2, ...] Arguments to be partially applied.
  9875. * @returns {Function} Returns the new bound function.
  9876. * @example
  9877. *
  9878. * var object = {
  9879. * 'name': 'moe',
  9880. * 'greet': function(greeting) {
  9881. * return greeting + ' ' + this.name;
  9882. * }
  9883. * };
  9884. *
  9885. * var func = _.bindKey(object, 'greet', 'hi');
  9886. * func();
  9887. * // => 'hi moe'
  9888. *
  9889. * object.greet = function(greeting) {
  9890. * return greeting + ', ' + this.name + '!';
  9891. * };
  9892. *
  9893. * func();
  9894. * // => 'hi, moe!'
  9895. */
  9896. function bindKey(object, key) {
  9897. return createBound(object, key, nativeSlice.call(arguments, 2), indicatorObject);
  9898. }
  9899. /**
  9900. * Creates a function that is the composition of the passed functions,
  9901. * where each function consumes the return value of the function that follows.
  9902. * For example, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`.
  9903. * Each function is executed with the `this` binding of the composed function.
  9904. *
  9905. * @static
  9906. * @memberOf _
  9907. * @category Functions
  9908. * @param {Function} [func1, func2, ...] Functions to compose.
  9909. * @returns {Function} Returns the new composed function.
  9910. * @example
  9911. *
  9912. * var greet = function(name) { return 'hi ' + name; };
  9913. * var exclaim = function(statement) { return statement + '!'; };
  9914. * var welcome = _.compose(exclaim, greet);
  9915. * welcome('moe');
  9916. * // => 'hi moe!'
  9917. */
  9918. function compose() {
  9919. var funcs = arguments;
  9920. return function() {
  9921. var args = arguments,
  9922. length = funcs.length;
  9923. while (length--) {
  9924. args = [funcs[length].apply(this, args)];
  9925. }
  9926. return args[0];
  9927. };
  9928. }
  9929. /**
  9930. * Produces a callback bound to an optional `thisArg`. If `func` is a property
  9931. * name, the created callback will return the property value for a given element.
  9932. * If `func` is an object, the created callback will return `true` for elements
  9933. * that contain the equivalent object properties, otherwise it will return `false`.
  9934. *
  9935. * Note: All Lo-Dash methods, that accept a `callback` argument, use `_.createCallback`.
  9936. *
  9937. * @static
  9938. * @memberOf _
  9939. * @category Functions
  9940. * @param {Mixed} [func=identity] The value to convert to a callback.
  9941. * @param {Mixed} [thisArg] The `this` binding of the created callback.
  9942. * @param {Number} [argCount=3] The number of arguments the callback accepts.
  9943. * @returns {Function} Returns a callback function.
  9944. * @example
  9945. *
  9946. * var stooges = [
  9947. * { 'name': 'moe', 'age': 40 },
  9948. * { 'name': 'larry', 'age': 50 }
  9949. * ];
  9950. *
  9951. * // wrap to create custom callback shorthands
  9952. * _.createCallback = _.wrap(_.createCallback, function(func, callback, thisArg) {
  9953. * var match = /^(.+?)__([gl]t)(.+)$/.exec(callback);
  9954. * return !match ? func(callback, thisArg) : function(object) {
  9955. * return match[2] == 'gt' ? object[match[1]] > match[3] : object[match[1]] < match[3];
  9956. * };
  9957. * });
  9958. *
  9959. * _.filter(stooges, 'age__gt45');
  9960. * // => [{ 'name': 'larry', 'age': 50 }]
  9961. *
  9962. * // create mixins with support for "_.pluck" and "_.where" callback shorthands
  9963. * _.mixin({
  9964. * 'toLookup': function(collection, callback, thisArg) {
  9965. * callback = _.createCallback(callback, thisArg);
  9966. * return _.reduce(collection, function(result, value, index, collection) {
  9967. * return (result[callback(value, index, collection)] = value, result);
  9968. * }, {});
  9969. * }
  9970. * });
  9971. *
  9972. * _.toLookup(stooges, 'name');
  9973. * // => { 'moe': { 'name': 'moe', 'age': 40 }, 'larry': { 'name': 'larry', 'age': 50 } }
  9974. */
  9975. function createCallback(func, thisArg, argCount) {
  9976. if (func == null) {
  9977. return identity;
  9978. }
  9979. var type = typeof func;
  9980. if (type != 'function') {
  9981. if (type != 'object') {
  9982. return function(object) {
  9983. return object[func];
  9984. };
  9985. }
  9986. var props = keys(func);
  9987. return function(object) {
  9988. var length = props.length,
  9989. result = false;
  9990. while (length--) {
  9991. if (!(result = isEqual(object[props[length]], func[props[length]], indicatorObject))) {
  9992. break;
  9993. }
  9994. }
  9995. return result;
  9996. };
  9997. }
  9998. if (typeof thisArg == 'undefined' || (reThis && !reThis.test(fnToString.call(func)))) {
  9999. return func;
  10000. }
  10001. if (argCount === 1) {
  10002. return function(value) {
  10003. return func.call(thisArg, value);
  10004. };
  10005. }
  10006. if (argCount === 2) {
  10007. return function(a, b) {
  10008. return func.call(thisArg, a, b);
  10009. };
  10010. }
  10011. if (argCount === 4) {
  10012. return function(accumulator, value, index, collection) {
  10013. return func.call(thisArg, accumulator, value, index, collection);
  10014. };
  10015. }
  10016. return function(value, index, collection) {
  10017. return func.call(thisArg, value, index, collection);
  10018. };
  10019. }
  10020. /**
  10021. * Creates a function that will delay the execution of `func` until after
  10022. * `wait` milliseconds have elapsed since the last time it was invoked. Pass
  10023. * an `options` object to indicate that `func` should be invoked on the leading
  10024. * and/or trailing edge of the `wait` timeout. Subsequent calls to the debounced
  10025. * function will return the result of the last `func` call.
  10026. *
  10027. * Note: If `leading` and `trailing` options are `true`, `func` will be called
  10028. * on the trailing edge of the timeout only if the the debounced function is
  10029. * invoked more than once during the `wait` timeout.
  10030. *
  10031. * @static
  10032. * @memberOf _
  10033. * @category Functions
  10034. * @param {Function} func The function to debounce.
  10035. * @param {Number} wait The number of milliseconds to delay.
  10036. * @param {Object} options The options object.
  10037. * [leading=false] A boolean to specify execution on the leading edge of the timeout.
  10038. * [maxWait] The maximum time `func` is allowed to be delayed before it's called.
  10039. * [trailing=true] A boolean to specify execution on the trailing edge of the timeout.
  10040. * @returns {Function} Returns the new debounced function.
  10041. * @example
  10042. *
  10043. * var lazyLayout = _.debounce(calculateLayout, 300);
  10044. * jQuery(window).on('resize', lazyLayout);
  10045. *
  10046. * jQuery('#postbox').on('click', _.debounce(sendMail, 200, {
  10047. * 'leading': true,
  10048. * 'trailing': false
  10049. * });
  10050. */
  10051. function debounce(func, wait, options) {
  10052. var args,
  10053. result,
  10054. thisArg,
  10055. callCount = 0,
  10056. lastCalled = 0,
  10057. maxWait = false,
  10058. maxTimeoutId = null,
  10059. timeoutId = null,
  10060. trailing = true;
  10061. function clear() {
  10062. clearTimeout(maxTimeoutId);
  10063. clearTimeout(timeoutId);
  10064. callCount = 0;
  10065. maxTimeoutId = timeoutId = null;
  10066. }
  10067. function delayed() {
  10068. var isCalled = trailing && (!leading || callCount > 1);
  10069. clear();
  10070. if (isCalled) {
  10071. if (maxWait !== false) {
  10072. lastCalled = new Date;
  10073. }
  10074. result = func.apply(thisArg, args);
  10075. }
  10076. }
  10077. function maxDelayed() {
  10078. clear();
  10079. if (trailing || (maxWait !== wait)) {
  10080. lastCalled = new Date;
  10081. result = func.apply(thisArg, args);
  10082. }
  10083. }
  10084. wait = nativeMax(0, wait || 0);
  10085. if (options === true) {
  10086. var leading = true;
  10087. trailing = false;
  10088. } else if (isObject(options)) {
  10089. leading = options.leading;
  10090. maxWait = 'maxWait' in options && nativeMax(wait, options.maxWait || 0);
  10091. trailing = 'trailing' in options ? options.trailing : trailing;
  10092. }
  10093. return function() {
  10094. args = arguments;
  10095. thisArg = this;
  10096. callCount++;
  10097. // avoid issues with Titanium and `undefined` timeout ids
  10098. // https://github.com/appcelerator/titanium_mobile/blob/3_1_0_GA/android/titanium/src/java/ti/modules/titanium/TitaniumModule.java#L185-L192
  10099. clearTimeout(timeoutId);
  10100. if (maxWait === false) {
  10101. if (leading && callCount < 2) {
  10102. result = func.apply(thisArg, args);
  10103. }
  10104. } else {
  10105. var now = new Date;
  10106. if (!maxTimeoutId && !leading) {
  10107. lastCalled = now;
  10108. }
  10109. var remaining = maxWait - (now - lastCalled);
  10110. if (remaining <= 0) {
  10111. clearTimeout(maxTimeoutId);
  10112. maxTimeoutId = null;
  10113. lastCalled = now;
  10114. result = func.apply(thisArg, args);
  10115. }
  10116. else if (!maxTimeoutId) {
  10117. maxTimeoutId = setTimeout(maxDelayed, remaining);
  10118. }
  10119. }
  10120. if (wait !== maxWait) {
  10121. timeoutId = setTimeout(delayed, wait);
  10122. }
  10123. return result;
  10124. };
  10125. }
  10126. /**
  10127. * Defers executing the `func` function until the current call stack has cleared.
  10128. * Additional arguments will be passed to `func` when it is invoked.
  10129. *
  10130. * @static
  10131. * @memberOf _
  10132. * @category Functions
  10133. * @param {Function} func The function to defer.
  10134. * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the function with.
  10135. * @returns {Number} Returns the timer id.
  10136. * @example
  10137. *
  10138. * _.defer(function() { alert('deferred'); });
  10139. * // returns from the function before `alert` is called
  10140. */
  10141. function defer(func) {
  10142. var args = nativeSlice.call(arguments, 1);
  10143. return setTimeout(function() { func.apply(undefined, args); }, 1);
  10144. }
  10145. // use `setImmediate` if it's available in Node.js
  10146. if (isV8 && freeModule && typeof setImmediate == 'function') {
  10147. defer = bind(setImmediate, context);
  10148. }
  10149. /**
  10150. * Executes the `func` function after `wait` milliseconds. Additional arguments
  10151. * will be passed to `func` when it is invoked.
  10152. *
  10153. * @static
  10154. * @memberOf _
  10155. * @category Functions
  10156. * @param {Function} func The function to delay.
  10157. * @param {Number} wait The number of milliseconds to delay execution.
  10158. * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the function with.
  10159. * @returns {Number} Returns the timer id.
  10160. * @example
  10161. *
  10162. * var log = _.bind(console.log, console);
  10163. * _.delay(log, 1000, 'logged later');
  10164. * // => 'logged later' (Appears after one second.)
  10165. */
  10166. function delay(func, wait) {
  10167. var args = nativeSlice.call(arguments, 2);
  10168. return setTimeout(function() { func.apply(undefined, args); }, wait);
  10169. }
  10170. /**
  10171. * Creates a function that memoizes the result of `func`. If `resolver` is
  10172. * passed, it will be used to determine the cache key for storing the result
  10173. * based on the arguments passed to the memoized function. By default, the first
  10174. * argument passed to the memoized function is used as the cache key. The `func`
  10175. * is executed with the `this` binding of the memoized function. The result
  10176. * cache is exposed as the `cache` property on the memoized function.
  10177. *
  10178. * @static
  10179. * @memberOf _
  10180. * @category Functions
  10181. * @param {Function} func The function to have its output memoized.
  10182. * @param {Function} [resolver] A function used to resolve the cache key.
  10183. * @returns {Function} Returns the new memoizing function.
  10184. * @example
  10185. *
  10186. * var fibonacci = _.memoize(function(n) {
  10187. * return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
  10188. * });
  10189. */
  10190. function memoize(func, resolver) {
  10191. function memoized() {
  10192. var cache = memoized.cache,
  10193. key = keyPrefix + (resolver ? resolver.apply(this, arguments) : arguments[0]);
  10194. return hasOwnProperty.call(cache, key)
  10195. ? cache[key]
  10196. : (cache[key] = func.apply(this, arguments));
  10197. }
  10198. memoized.cache = {};
  10199. return memoized;
  10200. }
  10201. /**
  10202. * Creates a function that is restricted to execute `func` once. Repeat calls to
  10203. * the function will return the value of the first call. The `func` is executed
  10204. * with the `this` binding of the created function.
  10205. *
  10206. * @static
  10207. * @memberOf _
  10208. * @category Functions
  10209. * @param {Function} func The function to restrict.
  10210. * @returns {Function} Returns the new restricted function.
  10211. * @example
  10212. *
  10213. * var initialize = _.once(createApplication);
  10214. * initialize();
  10215. * initialize();
  10216. * // `initialize` executes `createApplication` once
  10217. */
  10218. function once(func) {
  10219. var ran,
  10220. result;
  10221. return function() {
  10222. if (ran) {
  10223. return result;
  10224. }
  10225. ran = true;
  10226. result = func.apply(this, arguments);
  10227. // clear the `func` variable so the function may be garbage collected
  10228. func = null;
  10229. return result;
  10230. };
  10231. }
  10232. /**
  10233. * Creates a function that, when called, invokes `func` with any additional
  10234. * `partial` arguments prepended to those passed to the new function. This
  10235. * method is similar to `_.bind`, except it does **not** alter the `this` binding.
  10236. *
  10237. * @static
  10238. * @memberOf _
  10239. * @category Functions
  10240. * @param {Function} func The function to partially apply arguments to.
  10241. * @param {Mixed} [arg1, arg2, ...] Arguments to be partially applied.
  10242. * @returns {Function} Returns the new partially applied function.
  10243. * @example
  10244. *
  10245. * var greet = function(greeting, name) { return greeting + ' ' + name; };
  10246. * var hi = _.partial(greet, 'hi');
  10247. * hi('moe');
  10248. * // => 'hi moe'
  10249. */
  10250. function partial(func) {
  10251. return createBound(func, nativeSlice.call(arguments, 1));
  10252. }
  10253. /**
  10254. * This method is similar to `_.partial`, except that `partial` arguments are
  10255. * appended to those passed to the new function.
  10256. *
  10257. * @static
  10258. * @memberOf _
  10259. * @category Functions
  10260. * @param {Function} func The function to partially apply arguments to.
  10261. * @param {Mixed} [arg1, arg2, ...] Arguments to be partially applied.
  10262. * @returns {Function} Returns the new partially applied function.
  10263. * @example
  10264. *
  10265. * var defaultsDeep = _.partialRight(_.merge, _.defaults);
  10266. *
  10267. * var options = {
  10268. * 'variable': 'data',
  10269. * 'imports': { 'jq': $ }
  10270. * };
  10271. *
  10272. * defaultsDeep(options, _.templateSettings);
  10273. *
  10274. * options.variable
  10275. * // => 'data'
  10276. *
  10277. * options.imports
  10278. * // => { '_': _, 'jq': $ }
  10279. */
  10280. function partialRight(func) {
  10281. return createBound(func, nativeSlice.call(arguments, 1), null, indicatorObject);
  10282. }
  10283. /**
  10284. * Creates a function that, when executed, will only call the `func` function
  10285. * at most once per every `wait` milliseconds. Pass an `options` object to
  10286. * indicate that `func` should be invoked on the leading and/or trailing edge
  10287. * of the `wait` timeout. Subsequent calls to the throttled function will
  10288. * return the result of the last `func` call.
  10289. *
  10290. * Note: If `leading` and `trailing` options are `true`, `func` will be called
  10291. * on the trailing edge of the timeout only if the the throttled function is
  10292. * invoked more than once during the `wait` timeout.
  10293. *
  10294. * @static
  10295. * @memberOf _
  10296. * @category Functions
  10297. * @param {Function} func The function to throttle.
  10298. * @param {Number} wait The number of milliseconds to throttle executions to.
  10299. * @param {Object} options The options object.
  10300. * [leading=true] A boolean to specify execution on the leading edge of the timeout.
  10301. * [trailing=true] A boolean to specify execution on the trailing edge of the timeout.
  10302. * @returns {Function} Returns the new throttled function.
  10303. * @example
  10304. *
  10305. * var throttled = _.throttle(updatePosition, 100);
  10306. * jQuery(window).on('scroll', throttled);
  10307. *
  10308. * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
  10309. * 'trailing': false
  10310. * }));
  10311. */
  10312. function throttle(func, wait, options) {
  10313. var leading = true,
  10314. trailing = true;
  10315. if (options === false) {
  10316. leading = false;
  10317. } else if (isObject(options)) {
  10318. leading = 'leading' in options ? options.leading : leading;
  10319. trailing = 'trailing' in options ? options.trailing : trailing;
  10320. }
  10321. options = getObject();
  10322. options.leading = leading;
  10323. options.maxWait = wait;
  10324. options.trailing = trailing;
  10325. var result = debounce(func, wait, options);
  10326. releaseObject(options);
  10327. return result;
  10328. }
  10329. /**
  10330. * Creates a function that passes `value` to the `wrapper` function as its
  10331. * first argument. Additional arguments passed to the function are appended
  10332. * to those passed to the `wrapper` function. The `wrapper` is executed with
  10333. * the `this` binding of the created function.
  10334. *
  10335. * @static
  10336. * @memberOf _
  10337. * @category Functions
  10338. * @param {Mixed} value The value to wrap.
  10339. * @param {Function} wrapper The wrapper function.
  10340. * @returns {Function} Returns the new function.
  10341. * @example
  10342. *
  10343. * var hello = function(name) { return 'hello ' + name; };
  10344. * hello = _.wrap(hello, function(func) {
  10345. * return 'before, ' + func('moe') + ', after';
  10346. * });
  10347. * hello();
  10348. * // => 'before, hello moe, after'
  10349. */
  10350. function wrap(value, wrapper) {
  10351. return function() {
  10352. var args = [value];
  10353. push.apply(args, arguments);
  10354. return wrapper.apply(this, args);
  10355. };
  10356. }
  10357. /*--------------------------------------------------------------------------*/
  10358. /**
  10359. * Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their
  10360. * corresponding HTML entities.
  10361. *
  10362. * @static
  10363. * @memberOf _
  10364. * @category Utilities
  10365. * @param {String} string The string to escape.
  10366. * @returns {String} Returns the escaped string.
  10367. * @example
  10368. *
  10369. * _.escape('Moe, Larry & Curly');
  10370. * // => 'Moe, Larry &amp; Curly'
  10371. */
  10372. function escape(string) {
  10373. return string == null ? '' : String(string).replace(reUnescapedHtml, escapeHtmlChar);
  10374. }
  10375. /**
  10376. * This method returns the first argument passed to it.
  10377. *
  10378. * @static
  10379. * @memberOf _
  10380. * @category Utilities
  10381. * @param {Mixed} value Any value.
  10382. * @returns {Mixed} Returns `value`.
  10383. * @example
  10384. *
  10385. * var moe = { 'name': 'moe' };
  10386. * moe === _.identity(moe);
  10387. * // => true
  10388. */
  10389. function identity(value) {
  10390. return value;
  10391. }
  10392. /**
  10393. * Adds functions properties of `object` to the `lodash` function and chainable
  10394. * wrapper.
  10395. *
  10396. * @static
  10397. * @memberOf _
  10398. * @category Utilities
  10399. * @param {Object} object The object of function properties to add to `lodash`.
  10400. * @example
  10401. *
  10402. * _.mixin({
  10403. * 'capitalize': function(string) {
  10404. * return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
  10405. * }
  10406. * });
  10407. *
  10408. * _.capitalize('moe');
  10409. * // => 'Moe'
  10410. *
  10411. * _('moe').capitalize();
  10412. * // => 'Moe'
  10413. */
  10414. function mixin(object) {
  10415. forEach(functions(object), function(methodName) {
  10416. var func = lodash[methodName] = object[methodName];
  10417. lodash.prototype[methodName] = function() {
  10418. var value = this.__wrapped__,
  10419. args = [value];
  10420. push.apply(args, arguments);
  10421. var result = func.apply(lodash, args);
  10422. return (value && typeof value == 'object' && value === result)
  10423. ? this
  10424. : new lodashWrapper(result);
  10425. };
  10426. });
  10427. }
  10428. /**
  10429. * Reverts the '_' variable to its previous value and returns a reference to
  10430. * the `lodash` function.
  10431. *
  10432. * @static
  10433. * @memberOf _
  10434. * @category Utilities
  10435. * @returns {Function} Returns the `lodash` function.
  10436. * @example
  10437. *
  10438. * var lodash = _.noConflict();
  10439. */
  10440. function noConflict() {
  10441. context._ = oldDash;
  10442. return this;
  10443. }
  10444. /**
  10445. * Converts the given `value` into an integer of the specified `radix`.
  10446. * If `radix` is `undefined` or `0`, a `radix` of `10` is used unless the
  10447. * `value` is a hexadecimal, in which case a `radix` of `16` is used.
  10448. *
  10449. * Note: This method avoids differences in native ES3 and ES5 `parseInt`
  10450. * implementations. See http://es5.github.com/#E.
  10451. *
  10452. * @static
  10453. * @memberOf _
  10454. * @category Utilities
  10455. * @param {String} value The value to parse.
  10456. * @param {Number} [radix] The radix used to interpret the value to parse.
  10457. * @returns {Number} Returns the new integer value.
  10458. * @example
  10459. *
  10460. * _.parseInt('08');
  10461. * // => 8
  10462. */
  10463. var parseInt = nativeParseInt(whitespace + '08') == 8 ? nativeParseInt : function(value, radix) {
  10464. // Firefox and Opera still follow the ES3 specified implementation of `parseInt`
  10465. return nativeParseInt(isString(value) ? value.replace(reLeadingSpacesAndZeros, '') : value, radix || 0);
  10466. };
  10467. /**
  10468. * Produces a random number between `min` and `max` (inclusive). If only one
  10469. * argument is passed, a number between `0` and the given number will be returned.
  10470. *
  10471. * @static
  10472. * @memberOf _
  10473. * @category Utilities
  10474. * @param {Number} [min=0] The minimum possible value.
  10475. * @param {Number} [max=1] The maximum possible value.
  10476. * @returns {Number} Returns a random number.
  10477. * @example
  10478. *
  10479. * _.random(0, 5);
  10480. * // => a number between 0 and 5
  10481. *
  10482. * _.random(5);
  10483. * // => also a number between 0 and 5
  10484. */
  10485. function random(min, max) {
  10486. if (min == null && max == null) {
  10487. max = 1;
  10488. }
  10489. min = +min || 0;
  10490. if (max == null) {
  10491. max = min;
  10492. min = 0;
  10493. } else {
  10494. max = +max || 0;
  10495. }
  10496. var rand = nativeRandom();
  10497. return (min % 1 || max % 1)
  10498. ? min + nativeMin(rand * (max - min + parseFloat('1e-' + ((rand +'').length - 1))), max)
  10499. : min + floor(rand * (max - min + 1));
  10500. }
  10501. /**
  10502. * Resolves the value of `property` on `object`. If `property` is a function,
  10503. * it will be invoked with the `this` binding of `object` and its result returned,
  10504. * else the property value is returned. If `object` is falsey, then `undefined`
  10505. * is returned.
  10506. *
  10507. * @static
  10508. * @memberOf _
  10509. * @category Utilities
  10510. * @param {Object} object The object to inspect.
  10511. * @param {String} property The property to get the value of.
  10512. * @returns {Mixed} Returns the resolved value.
  10513. * @example
  10514. *
  10515. * var object = {
  10516. * 'cheese': 'crumpets',
  10517. * 'stuff': function() {
  10518. * return 'nonsense';
  10519. * }
  10520. * };
  10521. *
  10522. * _.result(object, 'cheese');
  10523. * // => 'crumpets'
  10524. *
  10525. * _.result(object, 'stuff');
  10526. * // => 'nonsense'
  10527. */
  10528. function result(object, property) {
  10529. var value = object ? object[property] : undefined;
  10530. return isFunction(value) ? object[property]() : value;
  10531. }
  10532. /**
  10533. * A micro-templating method that handles arbitrary delimiters, preserves
  10534. * whitespace, and correctly escapes quotes within interpolated code.
  10535. *
  10536. * Note: In the development build, `_.template` utilizes sourceURLs for easier
  10537. * debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
  10538. *
  10539. * For more information on precompiling templates see:
  10540. * http://lodash.com/#custom-builds
  10541. *
  10542. * For more information on Chrome extension sandboxes see:
  10543. * http://developer.chrome.com/stable/extensions/sandboxingEval.html
  10544. *
  10545. * @static
  10546. * @memberOf _
  10547. * @category Utilities
  10548. * @param {String} text The template text.
  10549. * @param {Object} data The data object used to populate the text.
  10550. * @param {Object} options The options object.
  10551. * escape - The "escape" delimiter regexp.
  10552. * evaluate - The "evaluate" delimiter regexp.
  10553. * interpolate - The "interpolate" delimiter regexp.
  10554. * sourceURL - The sourceURL of the template's compiled source.
  10555. * variable - The data object variable name.
  10556. * @returns {Function|String} Returns a compiled function when no `data` object
  10557. * is given, else it returns the interpolated text.
  10558. * @example
  10559. *
  10560. * // using a compiled template
  10561. * var compiled = _.template('hello <%= name %>');
  10562. * compiled({ 'name': 'moe' });
  10563. * // => 'hello moe'
  10564. *
  10565. * var list = '<% _.forEach(people, function(name) { %><li><%= name %></li><% }); %>';
  10566. * _.template(list, { 'people': ['moe', 'larry'] });
  10567. * // => '<li>moe</li><li>larry</li>'
  10568. *
  10569. * // using the "escape" delimiter to escape HTML in data property values
  10570. * _.template('<b><%- value %></b>', { 'value': '<script>' });
  10571. * // => '<b>&lt;script&gt;</b>'
  10572. *
  10573. * // using the ES6 delimiter as an alternative to the default "interpolate" delimiter
  10574. * _.template('hello ${ name }', { 'name': 'curly' });
  10575. * // => 'hello curly'
  10576. *
  10577. * // using the internal `print` function in "evaluate" delimiters
  10578. * _.template('<% print("hello " + epithet); %>!', { 'epithet': 'stooge' });
  10579. * // => 'hello stooge!'
  10580. *
  10581. * // using custom template delimiters
  10582. * _.templateSettings = {
  10583. * 'interpolate': /{{([\s\S]+?)}}/g
  10584. * };
  10585. *
  10586. * _.template('hello {{ name }}!', { 'name': 'mustache' });
  10587. * // => 'hello mustache!'
  10588. *
  10589. * // using the `sourceURL` option to specify a custom sourceURL for the template
  10590. * var compiled = _.template('hello <%= name %>', null, { 'sourceURL': '/basic/greeting.jst' });
  10591. * compiled(data);
  10592. * // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
  10593. *
  10594. * // using the `variable` option to ensure a with-statement isn't used in the compiled template
  10595. * var compiled = _.template('hi <%= data.name %>!', null, { 'variable': 'data' });
  10596. * compiled.source;
  10597. * // => function(data) {
  10598. * var __t, __p = '', __e = _.escape;
  10599. * __p += 'hi ' + ((__t = ( data.name )) == null ? '' : __t) + '!';
  10600. * return __p;
  10601. * }
  10602. *
  10603. * // using the `source` property to inline compiled templates for meaningful
  10604. * // line numbers in error messages and a stack trace
  10605. * fs.writeFileSync(path.join(cwd, 'jst.js'), '\
  10606. * var JST = {\
  10607. * "main": ' + _.template(mainText).source + '\
  10608. * };\
  10609. * ');
  10610. */
  10611. function template(text, data, options) {
  10612. // based on John Resig's `tmpl` implementation
  10613. // http://ejohn.org/blog/javascript-micro-templating/
  10614. // and Laura Doktorova's doT.js
  10615. // https://github.com/olado/doT
  10616. var settings = lodash.templateSettings;
  10617. text || (text = '');
  10618. // avoid missing dependencies when `iteratorTemplate` is not defined
  10619. options = defaults({}, options, settings);
  10620. var imports = defaults({}, options.imports, settings.imports),
  10621. importsKeys = keys(imports),
  10622. importsValues = values(imports);
  10623. var isEvaluating,
  10624. index = 0,
  10625. interpolate = options.interpolate || reNoMatch,
  10626. source = "__p += '";
  10627. // compile the regexp to match each delimiter
  10628. var reDelimiters = RegExp(
  10629. (options.escape || reNoMatch).source + '|' +
  10630. interpolate.source + '|' +
  10631. (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
  10632. (options.evaluate || reNoMatch).source + '|$'
  10633. , 'g');
  10634. text.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
  10635. interpolateValue || (interpolateValue = esTemplateValue);
  10636. // escape characters that cannot be included in string literals
  10637. source += text.slice(index, offset).replace(reUnescapedString, escapeStringChar);
  10638. // replace delimiters with snippets
  10639. if (escapeValue) {
  10640. source += "' +\n__e(" + escapeValue + ") +\n'";
  10641. }
  10642. if (evaluateValue) {
  10643. isEvaluating = true;
  10644. source += "';\n" + evaluateValue + ";\n__p += '";
  10645. }
  10646. if (interpolateValue) {
  10647. source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
  10648. }
  10649. index = offset + match.length;
  10650. // the JS engine embedded in Adobe products requires returning the `match`
  10651. // string in order to produce the correct `offset` value
  10652. return match;
  10653. });
  10654. source += "';\n";
  10655. // if `variable` is not specified, wrap a with-statement around the generated
  10656. // code to add the data object to the top of the scope chain
  10657. var variable = options.variable,
  10658. hasVariable = variable;
  10659. if (!hasVariable) {
  10660. variable = 'obj';
  10661. source = 'with (' + variable + ') {\n' + source + '\n}\n';
  10662. }
  10663. // cleanup code by stripping empty strings
  10664. source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
  10665. .replace(reEmptyStringMiddle, '$1')
  10666. .replace(reEmptyStringTrailing, '$1;');
  10667. // frame code as the function body
  10668. source = 'function(' + variable + ') {\n' +
  10669. (hasVariable ? '' : variable + ' || (' + variable + ' = {});\n') +
  10670. "var __t, __p = '', __e = _.escape" +
  10671. (isEvaluating
  10672. ? ', __j = Array.prototype.join;\n' +
  10673. "function print() { __p += __j.call(arguments, '') }\n"
  10674. : ';\n'
  10675. ) +
  10676. source +
  10677. 'return __p\n}';
  10678. // Use a sourceURL for easier debugging and wrap in a multi-line comment to
  10679. // avoid issues with Narwhal, IE conditional compilation, and the JS engine
  10680. // embedded in Adobe products.
  10681. // http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
  10682. var sourceURL = '\n/*\n//@ sourceURL=' + (options.sourceURL || '/lodash/template/source[' + (templateCounter++) + ']') + '\n*/';
  10683. try {
  10684. var result = Function(importsKeys, 'return ' + source + sourceURL).apply(undefined, importsValues);
  10685. } catch(e) {
  10686. e.source = source;
  10687. throw e;
  10688. }
  10689. if (data) {
  10690. return result(data);
  10691. }
  10692. // provide the compiled function's source via its `toString` method, in
  10693. // supported environments, or the `source` property as a convenience for
  10694. // inlining compiled templates during the build process
  10695. result.source = source;
  10696. return result;
  10697. }
  10698. /**
  10699. * Executes the `callback` function `n` times, returning an array of the results
  10700. * of each `callback` execution. The `callback` is bound to `thisArg` and invoked
  10701. * with one argument; (index).
  10702. *
  10703. * @static
  10704. * @memberOf _
  10705. * @category Utilities
  10706. * @param {Number} n The number of times to execute the callback.
  10707. * @param {Function} callback The function called per iteration.
  10708. * @param {Mixed} [thisArg] The `this` binding of `callback`.
  10709. * @returns {Array} Returns a new array of the results of each `callback` execution.
  10710. * @example
  10711. *
  10712. * var diceRolls = _.times(3, _.partial(_.random, 1, 6));
  10713. * // => [3, 6, 4]
  10714. *
  10715. * _.times(3, function(n) { mage.castSpell(n); });
  10716. * // => calls `mage.castSpell(n)` three times, passing `n` of `0`, `1`, and `2` respectively
  10717. *
  10718. * _.times(3, function(n) { this.cast(n); }, mage);
  10719. * // => also calls `mage.castSpell(n)` three times
  10720. */
  10721. function times(n, callback, thisArg) {
  10722. n = (n = +n) > -1 ? n : 0;
  10723. var index = -1,
  10724. result = Array(n);
  10725. callback = lodash.createCallback(callback, thisArg, 1);
  10726. while (++index < n) {
  10727. result[index] = callback(index);
  10728. }
  10729. return result;
  10730. }
  10731. /**
  10732. * The inverse of `_.escape`, this method converts the HTML entities
  10733. * `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;` in `string` to their
  10734. * corresponding characters.
  10735. *
  10736. * @static
  10737. * @memberOf _
  10738. * @category Utilities
  10739. * @param {String} string The string to unescape.
  10740. * @returns {String} Returns the unescaped string.
  10741. * @example
  10742. *
  10743. * _.unescape('Moe, Larry &amp; Curly');
  10744. * // => 'Moe, Larry & Curly'
  10745. */
  10746. function unescape(string) {
  10747. return string == null ? '' : String(string).replace(reEscapedHtml, unescapeHtmlChar);
  10748. }
  10749. /**
  10750. * Generates a unique ID. If `prefix` is passed, the ID will be appended to it.
  10751. *
  10752. * @static
  10753. * @memberOf _
  10754. * @category Utilities
  10755. * @param {String} [prefix] The value to prefix the ID with.
  10756. * @returns {String} Returns the unique ID.
  10757. * @example
  10758. *
  10759. * _.uniqueId('contact_');
  10760. * // => 'contact_104'
  10761. *
  10762. * _.uniqueId();
  10763. * // => '105'
  10764. */
  10765. function uniqueId(prefix) {
  10766. var id = ++idCounter;
  10767. return String(prefix == null ? '' : prefix) + id;
  10768. }
  10769. /*--------------------------------------------------------------------------*/
  10770. /**
  10771. * Invokes `interceptor` with the `value` as the first argument, and then
  10772. * returns `value`. The purpose of this method is to "tap into" a method chain,
  10773. * in order to perform operations on intermediate results within the chain.
  10774. *
  10775. * @static
  10776. * @memberOf _
  10777. * @category Chaining
  10778. * @param {Mixed} value The value to pass to `interceptor`.
  10779. * @param {Function} interceptor The function to invoke.
  10780. * @returns {Mixed} Returns `value`.
  10781. * @example
  10782. *
  10783. * _([1, 2, 3, 4])
  10784. * .filter(function(num) { return num % 2 == 0; })
  10785. * .tap(alert)
  10786. * .map(function(num) { return num * num; })
  10787. * .value();
  10788. * // => // [2, 4] (alerted)
  10789. * // => [4, 16]
  10790. */
  10791. function tap(value, interceptor) {
  10792. interceptor(value);
  10793. return value;
  10794. }
  10795. /**
  10796. * Produces the `toString` result of the wrapped value.
  10797. *
  10798. * @name toString
  10799. * @memberOf _
  10800. * @category Chaining
  10801. * @returns {String} Returns the string result.
  10802. * @example
  10803. *
  10804. * _([1, 2, 3]).toString();
  10805. * // => '1,2,3'
  10806. */
  10807. function wrapperToString() {
  10808. return String(this.__wrapped__);
  10809. }
  10810. /**
  10811. * Extracts the wrapped value.
  10812. *
  10813. * @name valueOf
  10814. * @memberOf _
  10815. * @alias value
  10816. * @category Chaining
  10817. * @returns {Mixed} Returns the wrapped value.
  10818. * @example
  10819. *
  10820. * _([1, 2, 3]).valueOf();
  10821. * // => [1, 2, 3]
  10822. */
  10823. function wrapperValueOf() {
  10824. return this.__wrapped__;
  10825. }
  10826. /*--------------------------------------------------------------------------*/
  10827. // add functions that return wrapped values when chaining
  10828. lodash.after = after;
  10829. lodash.assign = assign;
  10830. lodash.at = at;
  10831. lodash.bind = bind;
  10832. lodash.bindAll = bindAll;
  10833. lodash.bindKey = bindKey;
  10834. lodash.compact = compact;
  10835. lodash.compose = compose;
  10836. lodash.countBy = countBy;
  10837. lodash.createCallback = createCallback;
  10838. lodash.debounce = debounce;
  10839. lodash.defaults = defaults;
  10840. lodash.defer = defer;
  10841. lodash.delay = delay;
  10842. lodash.difference = difference;
  10843. lodash.filter = filter;
  10844. lodash.flatten = flatten;
  10845. lodash.forEach = forEach;
  10846. lodash.forIn = forIn;
  10847. lodash.forOwn = forOwn;
  10848. lodash.functions = functions;
  10849. lodash.groupBy = groupBy;
  10850. lodash.initial = initial;
  10851. lodash.intersection = intersection;
  10852. lodash.invert = invert;
  10853. lodash.invoke = invoke;
  10854. lodash.keys = keys;
  10855. lodash.map = map;
  10856. lodash.max = max;
  10857. lodash.memoize = memoize;
  10858. lodash.merge = merge;
  10859. lodash.min = min;
  10860. lodash.omit = omit;
  10861. lodash.once = once;
  10862. lodash.pairs = pairs;
  10863. lodash.partial = partial;
  10864. lodash.partialRight = partialRight;
  10865. lodash.pick = pick;
  10866. lodash.pluck = pluck;
  10867. lodash.range = range;
  10868. lodash.reject = reject;
  10869. lodash.rest = rest;
  10870. lodash.shuffle = shuffle;
  10871. lodash.sortBy = sortBy;
  10872. lodash.tap = tap;
  10873. lodash.throttle = throttle;
  10874. lodash.times = times;
  10875. lodash.toArray = toArray;
  10876. lodash.transform = transform;
  10877. lodash.union = union;
  10878. lodash.uniq = uniq;
  10879. lodash.unzip = unzip;
  10880. lodash.values = values;
  10881. lodash.where = where;
  10882. lodash.without = without;
  10883. lodash.wrap = wrap;
  10884. lodash.zip = zip;
  10885. lodash.zipObject = zipObject;
  10886. // add aliases
  10887. lodash.collect = map;
  10888. lodash.drop = rest;
  10889. lodash.each = forEach;
  10890. lodash.extend = assign;
  10891. lodash.methods = functions;
  10892. lodash.object = zipObject;
  10893. lodash.select = filter;
  10894. lodash.tail = rest;
  10895. lodash.unique = uniq;
  10896. // add functions to `lodash.prototype`
  10897. mixin(lodash);
  10898. // add Underscore compat
  10899. lodash.chain = lodash;
  10900. lodash.prototype.chain = function() { return this; };
  10901. /*--------------------------------------------------------------------------*/
  10902. // add functions that return unwrapped values when chaining
  10903. lodash.clone = clone;
  10904. lodash.cloneDeep = cloneDeep;
  10905. lodash.contains = contains;
  10906. lodash.escape = escape;
  10907. lodash.every = every;
  10908. lodash.find = find;
  10909. lodash.findIndex = findIndex;
  10910. lodash.findKey = findKey;
  10911. lodash.has = has;
  10912. lodash.identity = identity;
  10913. lodash.indexOf = indexOf;
  10914. lodash.isArguments = isArguments;
  10915. lodash.isArray = isArray;
  10916. lodash.isBoolean = isBoolean;
  10917. lodash.isDate = isDate;
  10918. lodash.isElement = isElement;
  10919. lodash.isEmpty = isEmpty;
  10920. lodash.isEqual = isEqual;
  10921. lodash.isFinite = isFinite;
  10922. lodash.isFunction = isFunction;
  10923. lodash.isNaN = isNaN;
  10924. lodash.isNull = isNull;
  10925. lodash.isNumber = isNumber;
  10926. lodash.isObject = isObject;
  10927. lodash.isPlainObject = isPlainObject;
  10928. lodash.isRegExp = isRegExp;
  10929. lodash.isString = isString;
  10930. lodash.isUndefined = isUndefined;
  10931. lodash.lastIndexOf = lastIndexOf;
  10932. lodash.mixin = mixin;
  10933. lodash.noConflict = noConflict;
  10934. lodash.parseInt = parseInt;
  10935. lodash.random = random;
  10936. lodash.reduce = reduce;
  10937. lodash.reduceRight = reduceRight;
  10938. lodash.result = result;
  10939. lodash.runInContext = runInContext;
  10940. lodash.size = size;
  10941. lodash.some = some;
  10942. lodash.sortedIndex = sortedIndex;
  10943. lodash.template = template;
  10944. lodash.unescape = unescape;
  10945. lodash.uniqueId = uniqueId;
  10946. // add aliases
  10947. lodash.all = every;
  10948. lodash.any = some;
  10949. lodash.detect = find;
  10950. lodash.findWhere = find;
  10951. lodash.foldl = reduce;
  10952. lodash.foldr = reduceRight;
  10953. lodash.include = contains;
  10954. lodash.inject = reduce;
  10955. forOwn(lodash, function(func, methodName) {
  10956. if (!lodash.prototype[methodName]) {
  10957. lodash.prototype[methodName] = function() {
  10958. var args = [this.__wrapped__];
  10959. push.apply(args, arguments);
  10960. return func.apply(lodash, args);
  10961. };
  10962. }
  10963. });
  10964. /*--------------------------------------------------------------------------*/
  10965. // add functions capable of returning wrapped and unwrapped values when chaining
  10966. lodash.first = first;
  10967. lodash.last = last;
  10968. // add aliases
  10969. lodash.take = first;
  10970. lodash.head = first;
  10971. forOwn(lodash, function(func, methodName) {
  10972. if (!lodash.prototype[methodName]) {
  10973. lodash.prototype[methodName]= function(callback, thisArg) {
  10974. var result = func(this.__wrapped__, callback, thisArg);
  10975. return callback == null || (thisArg && typeof callback != 'function')
  10976. ? result
  10977. : new lodashWrapper(result);
  10978. };
  10979. }
  10980. });
  10981. /*--------------------------------------------------------------------------*/
  10982. /**
  10983. * The semantic version number.
  10984. *
  10985. * @static
  10986. * @memberOf _
  10987. * @type String
  10988. */
  10989. lodash.VERSION = '1.3.1';
  10990. // add "Chaining" functions to the wrapper
  10991. lodash.prototype.toString = wrapperToString;
  10992. lodash.prototype.value = wrapperValueOf;
  10993. lodash.prototype.valueOf = wrapperValueOf;
  10994. // add `Array` functions that return unwrapped values
  10995. forEach(['join', 'pop', 'shift'], function(methodName) {
  10996. var func = arrayRef[methodName];
  10997. lodash.prototype[methodName] = function() {
  10998. return func.apply(this.__wrapped__, arguments);
  10999. };
  11000. });
  11001. // add `Array` functions that return the wrapped value
  11002. forEach(['push', 'reverse', 'sort', 'unshift'], function(methodName) {
  11003. var func = arrayRef[methodName];
  11004. lodash.prototype[methodName] = function() {
  11005. func.apply(this.__wrapped__, arguments);
  11006. return this;
  11007. };
  11008. });
  11009. // add `Array` functions that return new wrapped values
  11010. forEach(['concat', 'slice', 'splice'], function(methodName) {
  11011. var func = arrayRef[methodName];
  11012. lodash.prototype[methodName] = function() {
  11013. return new lodashWrapper(func.apply(this.__wrapped__, arguments));
  11014. };
  11015. });
  11016. return lodash;
  11017. }
  11018. /*--------------------------------------------------------------------------*/
  11019. // expose Lo-Dash
  11020. var _ = runInContext();
  11021. // some AMD build optimizers, like r.js, check for specific condition patterns like the following:
  11022. if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
  11023. // Expose Lo-Dash to the global object even when an AMD loader is present in
  11024. // case Lo-Dash was injected by a third-party script and not intended to be
  11025. // loaded as a module. The global assignment can be reverted in the Lo-Dash
  11026. // module via its `noConflict()` method.
  11027. window._ = _;
  11028. // define as an anonymous module so, through path mapping, it can be
  11029. // referenced as the "underscore" module
  11030. define(function() {
  11031. return _;
  11032. });
  11033. }
  11034. // check for `exports` after `define` in case a build optimizer adds an `exports` object
  11035. else if (freeExports && !freeExports.nodeType) {
  11036. // in Node.js or RingoJS v0.8.0+
  11037. if (freeModule) {
  11038. (freeModule.exports = _)._ = _;
  11039. }
  11040. // in Narwhal or RingoJS v0.7.0-
  11041. else {
  11042. freeExports._ = _;
  11043. }
  11044. }
  11045. else {
  11046. // in a browser or Rhino
  11047. window._ = _;
  11048. }
  11049. }(this));
  11050. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  11051. },{}],39:[function(_dereq_,module,exports){
  11052. module.exports={
  11053. "name": "amqp",
  11054. "description": "AMQP driver for node",
  11055. "keywords": [
  11056. "amqp"
  11057. ],
  11058. "version": "0.2.0",
  11059. "author": {
  11060. "name": "Ryan Dahl"
  11061. },
  11062. "contributors": [
  11063. {
  11064. "name": "Vasili Sviridov"
  11065. },
  11066. {
  11067. "name": "Theo Schlossnagle"
  11068. },
  11069. {
  11070. "name": "Vincent Desjardins"
  11071. },
  11072. {
  11073. "name": "Liang-Chi Hsieh"
  11074. },
  11075. {
  11076. "name": "Tim Baga"
  11077. },
  11078. {
  11079. "name": "Stéphane Alnet"
  11080. },
  11081. {
  11082. "name": "Alen Mujezinovic"
  11083. },
  11084. {
  11085. "name": "Michael Bridgen"
  11086. },
  11087. {
  11088. "name": "Chris Bond"
  11089. },
  11090. {
  11091. "name": "Andrei Vereha"
  11092. },
  11093. {
  11094. "name": "Mike Bardzinski"
  11095. },
  11096. {
  11097. "name": "James Carr"
  11098. },
  11099. {
  11100. "name": "David Barshow"
  11101. },
  11102. {
  11103. "name": "Jason Pincin"
  11104. },
  11105. {
  11106. "name": "Carl Hörberg"
  11107. }
  11108. ],
  11109. "repository": {
  11110. "type": "git",
  11111. "url": "git://github.com/postwait/node-amqp.git"
  11112. },
  11113. "bugs": {
  11114. "url": "http://github.com/postwait/node-amqp/issues"
  11115. },
  11116. "main": "./amqp",
  11117. "engines": {
  11118. "node": "0.4 || 0.6 || 0.8 || 0.9 || 0.10 || 0.11"
  11119. },
  11120. "licenses": [
  11121. {
  11122. "type": "MIT",
  11123. "url": "http://github.com/postwait/node-amqp/raw/master/LICENSE-MIT"
  11124. }
  11125. ],
  11126. "dependencies": {
  11127. "lodash": "~1.3.1"
  11128. },
  11129. "devDependencies": {
  11130. "optimist": "~0.6.0",
  11131. "longjohn": "~0.2.1"
  11132. },
  11133. "scripts": {
  11134. "test": "make test"
  11135. },
  11136. "_id": "amqp@0.2.0",
  11137. "dist": {
  11138. "shasum": "caed3d5a1ef5f419663f80dcf6e95312e5fca2ca",
  11139. "tarball": "http://registry.npmjs.org/amqp/-/amqp-0.2.0.tgz"
  11140. },
  11141. "_from": "amqp@^0.2.0",
  11142. "_npmVersion": "1.2.18",
  11143. "_npmUser": {
  11144. "name": "postwait",
  11145. "email": "jesus@omniti.com"
  11146. },
  11147. "maintainers": [
  11148. {
  11149. "name": "ry",
  11150. "email": "ry@tinyclouds.org"
  11151. },
  11152. {
  11153. "name": "postwait",
  11154. "email": "jesus@omniti.com"
  11155. }
  11156. ],
  11157. "directories": {},
  11158. "_shasum": "caed3d5a1ef5f419663f80dcf6e95312e5fca2ca",
  11159. "_resolved": "https://registry.npmjs.org/amqp/-/amqp-0.2.0.tgz",
  11160. "readme": "ERROR: No README data found!",
  11161. "homepage": "https://github.com/postwait/node-amqp"
  11162. }
  11163. },{}],40:[function(_dereq_,module,exports){
  11164. 'use strict';
  11165. module.exports = _dereq_('./lib/babble');
  11166. },{"./lib/babble":43}],41:[function(_dereq_,module,exports){
  11167. 'use strict';
  11168. var uuid = _dereq_('node-uuid');
  11169. var Promise = _dereq_('es6-promise').Promise;
  11170. var messagebus = _dereq_('./messagebus');
  11171. var Conversation = _dereq_('./Conversation');
  11172. var Block = _dereq_('./block/Block');
  11173. var Then = _dereq_('./block/Then');
  11174. var Tell = _dereq_('./block/Tell');
  11175. var Listen = _dereq_('./block/Listen');
  11176. _dereq_('./block/IIf'); // append iif function to Block
  11177. /**
  11178. * Babbler
  11179. * @param {String} id
  11180. * @constructor
  11181. */
  11182. function Babbler (id) {
  11183. if (!(this instanceof Babbler)) {
  11184. throw new SyntaxError('Constructor must be called with the new operator');
  11185. }
  11186. if (!id) {
  11187. throw new Error('id required');
  11188. }
  11189. this.id = id;
  11190. this.listeners = []; // Array.<Listen>
  11191. this.conversations = {}; // Array.<Array.<Conversation>> all open conversations
  11192. this.connect(); // automatically connect to the local message bus
  11193. }
  11194. /**
  11195. * Connect to a message bus
  11196. * @param {{connect: function, disconnect: function, send: function}} [bus]
  11197. * A messaging interface. Must have the following functions:
  11198. * - connect(params: {id: string,
  11199. * message: function, callback: function}) : string
  11200. * must return a token to disconnects again.
  11201. * parameter callback is optional.
  11202. * - disconnect(token: string)
  11203. * disconnect from a message bus.
  11204. * - send(id: string, message: *)
  11205. * send a message
  11206. * A number of interfaces is provided under babble.messagebus.
  11207. * Default interface is babble.messagebus['default']
  11208. * @return {Promise.<Babbler>} Returns a Promise which resolves when the
  11209. * babbler is connected.
  11210. */
  11211. Babbler.prototype.connect = function (bus) {
  11212. // disconnect (in case we are already connected)
  11213. this.disconnect();
  11214. if (!bus) {
  11215. bus = messagebus['default']();
  11216. }
  11217. // validate the message bus functions
  11218. if (typeof bus.connect !== 'function') {
  11219. throw new Error('message bus must contain a function ' +
  11220. 'connect(params: {id: string, callback: function}) : string');
  11221. }
  11222. if (typeof bus.disconnect !== 'function') {
  11223. throw new Error('message bus must contain a function ' +
  11224. 'disconnect(token: string)');
  11225. }
  11226. if (typeof bus.send !== 'function') {
  11227. throw new Error('message bus must contain a function ' +
  11228. 'send(params: {id: string, message: *})');
  11229. }
  11230. // we return a promise, but we run the message.connect function immediately
  11231. // (outside of the Promise), so that synchronous connects are done without
  11232. // the need to await the promise to resolve on the next tick.
  11233. var _resolve = null;
  11234. var connected = new Promise(function (resolve, reject) {
  11235. _resolve = resolve;
  11236. });
  11237. var token = bus.connect({
  11238. id: this.id,
  11239. message: this._receive.bind(this),
  11240. callback: _resolve
  11241. });
  11242. // link functions to disconnect and send
  11243. this.disconnect = function () {
  11244. bus.disconnect(token);
  11245. };
  11246. this.send = bus.send;
  11247. // return a promise
  11248. return connected;
  11249. };
  11250. /**
  11251. * Handle an incoming message
  11252. * @param {{id: string, from: string, to: string, message: string}} envelope
  11253. * @private
  11254. */
  11255. Babbler.prototype._receive = function (envelope) {
  11256. // ignore when envelope does not contain an id and message
  11257. if (!envelope || !('id' in envelope) || !('message' in envelope)) {
  11258. return;
  11259. }
  11260. // console.log('_receive', envelope) // TODO: cleanup
  11261. var me = this;
  11262. var id = envelope.id;
  11263. var conversations = this.conversations[id];
  11264. if (conversations && conversations.length) {
  11265. // directly deliver to all open conversations with this id
  11266. conversations.forEach(function (conversation) {
  11267. conversation.deliver(envelope);
  11268. })
  11269. }
  11270. else {
  11271. // start new conversations at each of the listeners
  11272. if (!conversations) {
  11273. conversations = [];
  11274. }
  11275. this.conversations[id] = conversations;
  11276. this.listeners.forEach(function (block) {
  11277. // create a new conversation
  11278. var conversation = new Conversation({
  11279. id: id,
  11280. self: me.id,
  11281. other: envelope.from,
  11282. context: {
  11283. from: envelope.from
  11284. },
  11285. send: me.send
  11286. });
  11287. // append this conversation to the list with conversations
  11288. conversations.push(conversation);
  11289. // deliver the first message to the new conversation
  11290. conversation.deliver(envelope);
  11291. // process the conversation
  11292. return me._process(block, conversation)
  11293. .then(function() {
  11294. // remove the conversation from the list again
  11295. var index = conversations.indexOf(conversation);
  11296. if (index !== -1) {
  11297. conversations.splice(index, 1);
  11298. }
  11299. if (conversations.length === 0) {
  11300. delete me.conversations[id];
  11301. }
  11302. });
  11303. });
  11304. }
  11305. };
  11306. /**
  11307. * Disconnect from the babblebox
  11308. */
  11309. Babbler.prototype.disconnect = function () {
  11310. // by default, do nothing. The disconnect function will be overwritten
  11311. // when the Babbler is connected to a message bus.
  11312. };
  11313. /**
  11314. * Send a message
  11315. * @param {String} to Id of a babbler
  11316. * @param {*} message Any message. Message must be a stringifiable JSON object.
  11317. */
  11318. Babbler.prototype.send = function (to, message) {
  11319. // send is overridden when running connect
  11320. throw new Error('Cannot send: not connected');
  11321. };
  11322. /**
  11323. * Listen for a specific event
  11324. *
  11325. * Providing a condition will only start the flow when condition is met,
  11326. * this is equivalent of doing `listen().iif(condition)`
  11327. *
  11328. * Providing a callback function is equivalent of doing either
  11329. * `listen(message).then(callback)` or `listen().iif(message).then(callback)`.
  11330. *
  11331. * @param {function | RegExp | String | *} [condition]
  11332. * @param {Function} [callback] Invoked as callback(message, context),
  11333. * where `message` is the just received message,
  11334. * and `context` is an object where state can be
  11335. * stored during a conversation. This is equivalent
  11336. * of doing `listen().then(callback)`
  11337. * @return {Block} block Start block of a control flow.
  11338. */
  11339. Babbler.prototype.listen = function (condition, callback) {
  11340. var listen = new Listen();
  11341. this.listeners.push(listen);
  11342. var block = listen;
  11343. if (condition) {
  11344. block = block.iif(condition);
  11345. }
  11346. if (callback) {
  11347. block = block.then(callback);
  11348. }
  11349. return block;
  11350. };
  11351. /**
  11352. * Listen for a specific event, and execute the flow once.
  11353. *
  11354. * Providing a condition will only start the flow when condition is met,
  11355. * this is equivalent of doing `listen().iif(condition)`
  11356. *
  11357. * Providing a callback function is equivalent of doing either
  11358. * `listen(message).then(callback)` or `listen().iif(message).then(callback)`.
  11359. *
  11360. * @param {function | RegExp | String | *} [condition]
  11361. * @param {Function} [callback] Invoked as callback(message, context),
  11362. * where `message` is the just received message,
  11363. * and `context` is an object where state can be
  11364. * stored during a conversation. This is equivalent
  11365. * of doing `listen().then(callback)`
  11366. * @return {Block} block Start block of a control flow.
  11367. */
  11368. Babbler.prototype.listenOnce = function (condition, callback) {
  11369. var listen = new Listen();
  11370. this.listeners.push(listen);
  11371. var me = this;
  11372. var block = listen;
  11373. if (condition) {
  11374. block = block.iif(condition);
  11375. }
  11376. block = block.then(function (message) {
  11377. // remove the flow from the listeners after fired once
  11378. var index = me.listeners.indexOf(listen);
  11379. if (index !== -1) {
  11380. me.listeners.splice(index, 1);
  11381. }
  11382. return message;
  11383. });
  11384. if (callback) {
  11385. block = block.then(callback);
  11386. }
  11387. return block;
  11388. };
  11389. /**
  11390. * Send a message to the other peer
  11391. * Creates a block Tell, and runs the block immediately.
  11392. * @param {String} to Babbler id
  11393. * @param {Function | *} message
  11394. * @return {Block} block Last block in the created control flow
  11395. */
  11396. Babbler.prototype.tell = function (to, message) {
  11397. var me = this;
  11398. var cid = uuid.v4(); // create an id for this conversation
  11399. // create a new conversation
  11400. var conversation = new Conversation({
  11401. id: cid,
  11402. self: this.id,
  11403. other: to,
  11404. context: {
  11405. from: to
  11406. },
  11407. send: me.send
  11408. });
  11409. this.conversations[cid] = [conversation];
  11410. var block = new Tell(message);
  11411. // run the Tell block on the next tick, when the conversation flow is created
  11412. setTimeout(function () {
  11413. me._process(block, conversation)
  11414. .then(function () {
  11415. // cleanup the conversation
  11416. delete me.conversations[cid];
  11417. })
  11418. }, 0);
  11419. return block;
  11420. };
  11421. /**
  11422. * Send a question, listen for a response.
  11423. * Creates two blocks: Tell and Listen, and runs them immediately.
  11424. * This is equivalent of doing `Babbler.tell(to, message).listen(callback)`
  11425. * @param {String} to Babbler id
  11426. * @param {* | Function} message A message or a callback returning a message.
  11427. * @param {Function} [callback] Invoked as callback(message, context),
  11428. * where `message` is the just received message,
  11429. * and `context` is an object where state can be
  11430. * stored during a conversation. This is equivalent
  11431. * of doing `listen().then(callback)`
  11432. * @return {Block} block Last block in the created control flow
  11433. */
  11434. Babbler.prototype.ask = function (to, message, callback) {
  11435. return this
  11436. .tell(to, message)
  11437. .listen(callback);
  11438. };
  11439. /**
  11440. * Process a flow starting with `block`, given a conversation
  11441. * @param {Block} block
  11442. * @param {Conversation} conversation
  11443. * @return {Promise.<Conversation>} Resolves when the conversation is finished
  11444. * @private
  11445. */
  11446. Babbler.prototype._process = function (block, conversation) {
  11447. return new Promise(function (resolve, reject) {
  11448. /**
  11449. * Process a block, given the conversation and a message which is chained
  11450. * from block to block.
  11451. * @param {Block} block
  11452. * @param {*} [message]
  11453. */
  11454. function process(block, message) {
  11455. //console.log('process', conversation.self, conversation.id, block.constructor.name, message) // TODO: cleanup
  11456. block.execute(conversation, message)
  11457. .then(function (next) {
  11458. if (next.block) {
  11459. // recursively evaluate the next block in the conversation flow
  11460. process(next.block, next.result);
  11461. }
  11462. else {
  11463. // we are done, this is the end of the conversation
  11464. resolve(conversation);
  11465. }
  11466. });
  11467. }
  11468. // process the first block
  11469. process(block);
  11470. });
  11471. };
  11472. module.exports = Babbler;
  11473. },{"./Conversation":42,"./block/Block":44,"./block/IIf":46,"./block/Listen":47,"./block/Tell":48,"./block/Then":49,"./messagebus":50,"es6-promise":52,"node-uuid":113}],42:[function(_dereq_,module,exports){
  11474. var uuid = _dereq_('node-uuid');
  11475. var Promise = _dereq_('es6-promise').Promise;
  11476. /**
  11477. * A conversation
  11478. * Holds meta data for a conversation between two peers
  11479. * @param {Object} [config] Configuration options:
  11480. * {string} [id] A unique id for the conversation. If not provided, a uuid is generated
  11481. * {string} self Id of the peer on this side of the conversation
  11482. * {string} other Id of the peer on the other side of the conversation
  11483. * {Object} [context] Context passed with all callbacks of the conversation
  11484. * {function(to: string, message: *): Promise} send Function to send a message
  11485. * @constructor
  11486. */
  11487. function Conversation (config) {
  11488. if (!(this instanceof Conversation)) {
  11489. throw new SyntaxError('Constructor must be called with the new operator');
  11490. }
  11491. // public properties
  11492. this.id = config && config.id || uuid.v4();
  11493. this.self = config && config.self || null;
  11494. this.other = config && config.other || null;
  11495. this.context = config && config.context || {};
  11496. // private properties
  11497. this._send = config && config.send || null;
  11498. this._inbox = []; // queue with received but not yet picked messages
  11499. this._receivers = []; // queue with handlers waiting for a new message
  11500. }
  11501. /**
  11502. * Send a message
  11503. * @param {*} message
  11504. * @return {Promise.<null>} Resolves when the message has been sent
  11505. */
  11506. Conversation.prototype.send = function (message) {
  11507. return this._send(this.other, {
  11508. id: this.id,
  11509. from: this.self,
  11510. to: this.other,
  11511. message: message
  11512. });
  11513. };
  11514. /**
  11515. * Deliver a message
  11516. * @param {{id: string, from: string, to: string, message: string}} envelope
  11517. */
  11518. Conversation.prototype.deliver = function (envelope) {
  11519. if (this._receivers.length) {
  11520. var receiver = this._receivers.shift();
  11521. receiver(envelope.message);
  11522. }
  11523. else {
  11524. this._inbox.push(envelope.message);
  11525. }
  11526. };
  11527. /**
  11528. * Receive a message.
  11529. * @returns {Promise.<*>} Resolves with a message as soon as a message
  11530. * is delivered.
  11531. */
  11532. Conversation.prototype.receive = function () {
  11533. var me = this;
  11534. if (this._inbox.length) {
  11535. return Promise.resolve(this._inbox.shift());
  11536. }
  11537. else {
  11538. return new Promise(function (resolve) {
  11539. me._receivers.push(resolve);
  11540. })
  11541. }
  11542. };
  11543. module.exports = Conversation;
  11544. },{"es6-promise":52,"node-uuid":113}],43:[function(_dereq_,module,exports){
  11545. 'use strict';
  11546. var Babbler = _dereq_('./Babbler');
  11547. var Tell = _dereq_('./block/Tell');
  11548. var Listen = _dereq_('./block/Listen');
  11549. var Then = _dereq_('./block/Then');
  11550. var Decision = _dereq_('./block/Decision');
  11551. var IIf = _dereq_('./block/IIf');
  11552. /**
  11553. * Create a new babbler
  11554. * @param {String} id
  11555. * @return {Babbler} babbler
  11556. */
  11557. exports.babbler = function (id) {
  11558. return new Babbler(id);
  11559. };
  11560. /**
  11561. * Create a control flow starting with a tell block
  11562. * @param {* | Function} [message] A static message or callback function
  11563. * returning a message dynamically.
  11564. * When `message` is a function, it will be
  11565. * invoked as callback(message, context),
  11566. * where `message` is the output from the
  11567. * previous block in the chain, and `context` is
  11568. * an object where state can be stored during a
  11569. * conversation.
  11570. * @return {Tell} tell
  11571. */
  11572. exports.tell = function (message) {
  11573. return new Tell(message);
  11574. };
  11575. /**
  11576. * Send a question, listen for a response.
  11577. * Creates two blocks: Tell and Listen.
  11578. * This is equivalent of doing `babble.tell(message).listen(callback)`
  11579. * @param {* | Function} message
  11580. * @param {Function} [callback] Invoked as callback(message, context),
  11581. * where `message` is the just received message,
  11582. * and `context` is an object where state can be
  11583. * stored during a conversation. This is equivalent
  11584. * of doing `listen().then(callback)`
  11585. * @return {Block} block Last block in the created control flow
  11586. */
  11587. exports.ask = function (message, callback) {
  11588. return exports
  11589. .tell(message)
  11590. .listen(callback);
  11591. };
  11592. /**
  11593. * Create a decision block and chain it to the current block.
  11594. *
  11595. * Syntax:
  11596. *
  11597. * decide(choices)
  11598. * decide(decision, choices)
  11599. *
  11600. * Where:
  11601. *
  11602. * {Function | Object} [decision]
  11603. * When a `decision` function is provided, the
  11604. * function is invoked as decision(message, context),
  11605. * where `message` is the output from the previous
  11606. * block in the chain, and `context` is an object
  11607. * where state can be stored during a conversation.
  11608. * The function must return the id for the next
  11609. * block in the control flow, which must be
  11610. * available in the provided `choices`.
  11611. * If `decision` is not provided, the next block
  11612. * will be mapped directly from the message.
  11613. * {Object.<String, Block>} choices
  11614. * A map with the possible next blocks in the flow
  11615. * The next block is selected by the id returned
  11616. * by the decision function.
  11617. *
  11618. * There is one special id for choices: 'default'. This id is called when either
  11619. * the decision function returns an id which does not match any of the available
  11620. * choices.
  11621. *
  11622. * @param {Function | Object} arg1 Can be {function} decision or {Object} choices
  11623. * @param {Object} [arg2] choices
  11624. * @return {Block} decision The created decision block
  11625. */
  11626. exports.decide = function (arg1, arg2) {
  11627. // TODO: test arguments.length > 2
  11628. return new Decision(arg1, arg2);
  11629. };
  11630. /**
  11631. * Listen for a message.
  11632. *
  11633. * Optionally a callback function can be provided, which is equivalent of
  11634. * doing `listen().then(callback)`.
  11635. *
  11636. * @param {Function} [callback] Invoked as callback(message, context),
  11637. * where `message` is the just received message,
  11638. * and `context` is an object where state can be
  11639. * stored during a conversation. This is equivalent
  11640. * of doing `listen().then(callback)`
  11641. * @return {Block} Returns the created Listen block
  11642. */
  11643. exports.listen = function(callback) {
  11644. var block = new Listen();
  11645. if (callback) {
  11646. return block.then(callback);
  11647. }
  11648. return block;
  11649. };
  11650. /**
  11651. * Create a control flow starting with a Then block
  11652. * @param {Function} callback Invoked as callback(message, context),
  11653. * where `message` is the output from the previous
  11654. * block in the chain, and `context` is an object
  11655. * where state can be stored during a conversation.
  11656. * @return {Then} then
  11657. */
  11658. exports.then = function (callback) {
  11659. return new Then(callback);
  11660. };
  11661. /**
  11662. * IIf
  11663. * Create an iif block, which checks a condition and continues either with
  11664. * the trueBlock or the falseBlock. The input message is passed to the next
  11665. * block in the flow.
  11666. *
  11667. * Can be used as follows:
  11668. * - When `condition` evaluates true:
  11669. * - when `trueBlock` is provided, the flow continues with `trueBlock`
  11670. * - else, when there is a block connected to the IIf block, the flow continues
  11671. * with that block.
  11672. * - When `condition` evaluates false:
  11673. * - when `falseBlock` is provided, the flow continues with `falseBlock`
  11674. *
  11675. * Syntax:
  11676. *
  11677. * new IIf(condition, trueBlock)
  11678. * new IIf(condition, trueBlock [, falseBlock])
  11679. * new IIf(condition).then(...)
  11680. *
  11681. * @param {Function | RegExp | *} condition A condition returning true or false
  11682. * In case of a function,
  11683. * the function is invoked as
  11684. * `condition(message, context)` and
  11685. * must return a boolean. In case of
  11686. * a RegExp, condition will be tested
  11687. * to return true. In other cases,
  11688. * non-strict equality is tested on
  11689. * the input.
  11690. * @param {Block} [trueBlock]
  11691. * @param {Block} [falseBlock]
  11692. * @returns {Block}
  11693. */
  11694. exports.iif = function (condition, trueBlock, falseBlock) {
  11695. return new IIf(condition, trueBlock, falseBlock);
  11696. };
  11697. // export the babbler prototype
  11698. exports.Babbler = Babbler;
  11699. // export all flow blocks
  11700. exports.block = {
  11701. Block: _dereq_('./block/Block'),
  11702. Then: _dereq_('./block/Then'),
  11703. Decision: _dereq_('./block/Decision'),
  11704. IIf: _dereq_('./block/IIf'),
  11705. Listen: _dereq_('./block/Listen'),
  11706. Tell: _dereq_('./block/Tell')
  11707. };
  11708. // export messagebus interfaces
  11709. exports.messagebus = _dereq_('./messagebus');
  11710. /**
  11711. * Babblify an actor. The babblified actor will be extended with functions
  11712. * `ask`, `tell`, and `listen`.
  11713. *
  11714. * Babble expects that messages sent via `actor.send(to, message)` will be
  11715. * delivered by the recipient on a function `actor.receive(from, message)`.
  11716. * Babble replaces the original `receive` with a new one, which is used to
  11717. * listen for all incoming messages. Messages ignored by babble are propagated
  11718. * to the original `receive` function.
  11719. *
  11720. * The actor can be restored in its original state using `unbabblify(actor)`.
  11721. *
  11722. * @param {Object} actor The actor to be babblified. Must be an object
  11723. * containing functions `send(to, message)` and
  11724. * `receive(from, message)`.
  11725. * @param {Object} [params] Optional parameters. Can contain properties:
  11726. * - id: string The id for the babbler
  11727. * - send: string The name of an alternative
  11728. * send function available on
  11729. * the actor.
  11730. * - receive: string The name of an alternative
  11731. * receive function available
  11732. * on the actor.
  11733. * @returns {Object} Returns the babblified actor.
  11734. */
  11735. exports.babblify = function (actor, params) {
  11736. var babblerId;
  11737. if (params && params.id !== undefined) {
  11738. babblerId = params.id;
  11739. }
  11740. else if (actor.id !== undefined) {
  11741. babblerId = actor.id
  11742. }
  11743. else {
  11744. throw new Error('Id missing. Ensure that either actor has a property "id", ' +
  11745. 'or provide an id as a property in second argument params')
  11746. }
  11747. // validate actor
  11748. ['ask', 'tell', 'listen'].forEach(function (prop) {
  11749. if (actor[prop] !== undefined) {
  11750. throw new Error('Conflict: actor already has a property "' + prop + '"');
  11751. }
  11752. });
  11753. var sendName = params && params.send || 'send';
  11754. if (typeof actor[sendName] !== 'function') {
  11755. throw new Error('Missing function. ' +
  11756. 'Function "' + sendName + '(to, message)" expected on actor or on params');
  11757. }
  11758. // create a new babbler
  11759. var babbler = exports.babbler(babblerId);
  11760. // attach receive function to the babbler
  11761. var receiveName = params && params.receive || 'receive';
  11762. var receiveOriginal = actor.hasOwnProperty(receiveName) ? actor[receiveName] : null;
  11763. if (receiveOriginal) {
  11764. actor[receiveName] = function (from, message) {
  11765. babbler._receive(message);
  11766. receiveOriginal.call(actor, from, message);
  11767. };
  11768. }
  11769. else {
  11770. actor[receiveName] = function (from, message) {
  11771. babbler._receive(message);
  11772. };
  11773. }
  11774. // attach send function to the babbler
  11775. babbler.send = function (to, message) {
  11776. // FIXME: there should be no need to send a message on next tick
  11777. setTimeout(function () {
  11778. actor[sendName](to, message)
  11779. }, 0)
  11780. };
  11781. // attach babbler functions and properties to the actor
  11782. actor.__babbler__ = {
  11783. babbler: babbler,
  11784. receive: receiveOriginal,
  11785. receiveName: receiveName
  11786. };
  11787. actor.ask = babbler.ask.bind(babbler);
  11788. actor.tell = babbler.tell.bind(babbler);
  11789. actor.listen = babbler.listen.bind(babbler);
  11790. actor.listenOnce = babbler.listenOnce.bind(babbler);
  11791. return actor;
  11792. };
  11793. /**
  11794. * Unbabblify an actor.
  11795. * @param {Object} actor
  11796. * @return {Object} Returns the unbabblified actor.
  11797. */
  11798. exports.unbabblify = function (actor) {
  11799. var __babbler__ = actor.__babbler__;
  11800. if (__babbler__) {
  11801. delete actor.__babbler__;
  11802. delete actor.ask;
  11803. delete actor.tell;
  11804. delete actor.listen;
  11805. delete actor.listenOnce;
  11806. delete actor[__babbler__.receiveName];
  11807. // restore any original receive method
  11808. if (__babbler__.receive) {
  11809. actor[__babbler__.receiveName] = __babbler__.receive;
  11810. }
  11811. }
  11812. return actor;
  11813. };
  11814. },{"./Babbler":41,"./block/Block":44,"./block/Decision":45,"./block/IIf":46,"./block/Listen":47,"./block/Tell":48,"./block/Then":49,"./messagebus":50}],44:[function(_dereq_,module,exports){
  11815. 'use strict';
  11816. /**
  11817. * Abstract control flow diagram block
  11818. * @constructor
  11819. */
  11820. function Block() {
  11821. this.next = null;
  11822. this.previous = null;
  11823. }
  11824. /**
  11825. * Execute the block
  11826. * @param {Conversation} conversation
  11827. * @param {*} message
  11828. * @return {Promise.<{result: *, block: Block}, Error>} next
  11829. */
  11830. Block.prototype.execute = function (conversation, message) {
  11831. throw new Error('Cannot run an abstract Block');
  11832. };
  11833. module.exports = Block;
  11834. },{}],45:[function(_dereq_,module,exports){
  11835. 'use strict';
  11836. var Promise = _dereq_('es6-promise').Promise;
  11837. var Block = _dereq_('./Block');
  11838. var isPromise =_dereq_('../util').isPromise;
  11839. _dereq_('./Then'); // extend Block with function then
  11840. /**
  11841. * Decision
  11842. * A decision is made by executing the provided callback function, which returns
  11843. * a next control flow block.
  11844. *
  11845. * Syntax:
  11846. *
  11847. * new Decision(choices)
  11848. * new Decision(decision, choices)
  11849. *
  11850. * Where:
  11851. *
  11852. * {Function | Object} [decision]
  11853. * When a `decision` function is provided, the
  11854. * function is invoked as decision(message, context),
  11855. * where `message` is the output from the previous
  11856. * block in the chain, and `context` is an object
  11857. * where state can be stored during a conversation.
  11858. * The function must return the id for the next
  11859. * block in the control flow, which must be
  11860. * available in the provided `choices`.
  11861. * If `decision` is not provided, the next block
  11862. * will be mapped directly from the message.
  11863. * {Object.<String, Block>} choices
  11864. * A map with the possible next blocks in the flow
  11865. * The next block is selected by the id returned
  11866. * by the decision function.
  11867. *
  11868. * There is one special id for choices: 'default'. This id is called when either
  11869. * the decision function returns an id which does not match any of the available
  11870. * choices.
  11871. *
  11872. * @param arg1
  11873. * @param arg2
  11874. * @constructor
  11875. * @extends {Block}
  11876. */
  11877. function Decision (arg1, arg2) {
  11878. var decision, choices;
  11879. if (!(this instanceof Decision)) {
  11880. throw new SyntaxError('Constructor must be called with the new operator');
  11881. }
  11882. if (typeof arg1 === 'function') {
  11883. decision = arg1;
  11884. choices = arg2;
  11885. }
  11886. else {
  11887. decision = null;
  11888. choices = arg1;
  11889. }
  11890. if (decision) {
  11891. if (typeof decision !== 'function') {
  11892. throw new TypeError('Parameter decision must be a function');
  11893. }
  11894. }
  11895. else {
  11896. decision = function (message, context) {
  11897. return message;
  11898. }
  11899. }
  11900. if (choices && (choices instanceof Function)) {
  11901. throw new TypeError('Parameter choices must be an object');
  11902. }
  11903. this.decision = decision;
  11904. this.choices = {};
  11905. // append all choices
  11906. if (choices) {
  11907. var me = this;
  11908. Object.keys(choices).forEach(function (id) {
  11909. me.addChoice(id, choices[id]);
  11910. });
  11911. }
  11912. }
  11913. Decision.prototype = Object.create(Block.prototype);
  11914. Decision.prototype.constructor = Decision;
  11915. /**
  11916. * Execute the block
  11917. * @param {Conversation} conversation
  11918. * @param {*} message
  11919. * @return {Promise.<{result: *, block: Block}, Error>} next
  11920. */
  11921. Decision.prototype.execute = function (conversation, message) {
  11922. var me = this;
  11923. var id = this.decision(message, conversation.context);
  11924. var resolve = isPromise(id) ? id : Promise.resolve(id);
  11925. return resolve.then(function (id) {
  11926. var next = me.choices[id];
  11927. if (!next) {
  11928. // there is no match, fall back on the default choice
  11929. next = me.choices['default'];
  11930. }
  11931. if (!next) {
  11932. throw new Error('Block with id "' + id + '" not found');
  11933. }
  11934. return {
  11935. result: message,
  11936. block: next
  11937. };
  11938. });
  11939. };
  11940. /**
  11941. * Add a choice to the decision block.
  11942. * The choice can be a new chain of blocks. The first block of the chain
  11943. * will be triggered when the this id comes out of the decision function.
  11944. * @param {String | 'default'} id
  11945. * @param {Block} block
  11946. * @return {Decision} self
  11947. */
  11948. Decision.prototype.addChoice = function (id, block) {
  11949. if (typeof id !== 'string') {
  11950. throw new TypeError('String expected as choice id');
  11951. }
  11952. if (!(block instanceof Block)) {
  11953. throw new TypeError('Block expected as choice');
  11954. }
  11955. if (id in this.choices) {
  11956. throw new Error('Choice with id "' + id + '" already exists');
  11957. }
  11958. // find the first block of the chain
  11959. var first = block;
  11960. while (first && first.previous) {
  11961. first = first.previous;
  11962. }
  11963. this.choices[id] = first;
  11964. return this;
  11965. };
  11966. /**
  11967. * Create a decision block and chain it to the current block.
  11968. * Returns the first block in the chain.
  11969. *
  11970. * Syntax:
  11971. *
  11972. * decide(choices)
  11973. * decide(decision, choices)
  11974. *
  11975. * Where:
  11976. *
  11977. * {Function | Object} [decision]
  11978. * When a `decision` function is provided, the
  11979. * function is invoked as decision(message, context),
  11980. * where `message` is the output from the previous
  11981. * block in the chain, and `context` is an object
  11982. * where state can be stored during a conversation.
  11983. * The function must return the id for the next
  11984. * block in the control flow, which must be
  11985. * available in the provided `choices`.
  11986. * If `decision` is not provided, the next block
  11987. * will be mapped directly from the message.
  11988. * {Object.<String, Block>} choices
  11989. * A map with the possible next blocks in the flow
  11990. * The next block is selected by the id returned
  11991. * by the decision function.
  11992. *
  11993. * There is one special id for choices: 'default'. This id is called when either
  11994. * the decision function returns an id which does not match any of the available
  11995. * choices.
  11996. *
  11997. * @param {Function | Object} arg1 Can be {function} decision or {Object} choices
  11998. * @param {Object} [arg2] choices
  11999. * @return {Block} first First block in the chain
  12000. */
  12001. Block.prototype.decide = function (arg1, arg2) {
  12002. var decision = new Decision(arg1, arg2);
  12003. return this.then(decision);
  12004. };
  12005. module.exports = Decision;
  12006. },{"../util":51,"./Block":44,"./Then":49,"es6-promise":52}],46:[function(_dereq_,module,exports){
  12007. 'use strict';
  12008. var Promise = _dereq_('es6-promise').Promise;
  12009. var Block = _dereq_('./Block');
  12010. var isPromise = _dereq_('../util').isPromise;
  12011. _dereq_('./Then'); // extend Block with function then
  12012. /**
  12013. * IIf
  12014. * Create an iif block, which checks a condition and continues either with
  12015. * the trueBlock or the falseBlock. The input message is passed to the next
  12016. * block in the flow.
  12017. *
  12018. * Can be used as follows:
  12019. * - When `condition` evaluates true:
  12020. * - when `trueBlock` is provided, the flow continues with `trueBlock`
  12021. * - else, when there is a block connected to the IIf block, the flow continues
  12022. * with that block.
  12023. * - When `condition` evaluates false:
  12024. * - when `falseBlock` is provided, the flow continues with `falseBlock`
  12025. *
  12026. * Syntax:
  12027. *
  12028. * new IIf(condition, trueBlock)
  12029. * new IIf(condition, trueBlock [, falseBlock])
  12030. * new IIf(condition).then(...)
  12031. *
  12032. * @param {Function | RegExp | *} condition A condition returning true or false
  12033. * In case of a function,
  12034. * the function is invoked as
  12035. * `condition(message, context)` and
  12036. * must return a boolean. In case of
  12037. * a RegExp, condition will be tested
  12038. * to return true. In other cases,
  12039. * non-strict equality is tested on
  12040. * the input.
  12041. * @param {Block} [trueBlock]
  12042. * @param {Block} [falseBlock]
  12043. * @constructor
  12044. * @extends {Block}
  12045. */
  12046. function IIf (condition, trueBlock, falseBlock) {
  12047. if (!(this instanceof IIf)) {
  12048. throw new SyntaxError('Constructor must be called with the new operator');
  12049. }
  12050. if (condition instanceof Function) {
  12051. this.condition = condition;
  12052. }
  12053. else if (condition instanceof RegExp) {
  12054. this.condition = function (message, context) {
  12055. return condition.test(message);
  12056. }
  12057. }
  12058. else {
  12059. this.condition = function (message, context) {
  12060. return message == condition;
  12061. }
  12062. }
  12063. if (trueBlock && !(trueBlock instanceof Block)) {
  12064. throw new TypeError('Parameter trueBlock must be a Block');
  12065. }
  12066. if (falseBlock && !(falseBlock instanceof Block)) {
  12067. throw new TypeError('Parameter falseBlock must be a Block');
  12068. }
  12069. this.trueBlock = trueBlock || null;
  12070. this.falseBlock = falseBlock || null;
  12071. }
  12072. IIf.prototype = Object.create(Block.prototype);
  12073. IIf.prototype.constructor = IIf;
  12074. /**
  12075. * Execute the block
  12076. * @param {Conversation} conversation
  12077. * @param {*} message
  12078. * @return {Promise.<{result: *, block: Block}, Error>} next
  12079. */
  12080. IIf.prototype.execute = function (conversation, message) {
  12081. var me = this;
  12082. var condition = this.condition(message, conversation.context);
  12083. var resolve = isPromise(condition) ? condition : Promise.resolve(condition);
  12084. return resolve.then(function (condition) {
  12085. var next = condition ? (me.trueBlock || me.next) : me.falseBlock;
  12086. return {
  12087. result: message,
  12088. block: next
  12089. };
  12090. });
  12091. };
  12092. /**
  12093. * IIf
  12094. * Create an iif block, which checks a condition and continues either with
  12095. * the trueBlock or the falseBlock. The input message is passed to the next
  12096. * block in the flow.
  12097. *
  12098. * Can be used as follows:
  12099. * - When `condition` evaluates true:
  12100. * - when `trueBlock` is provided, the flow continues with `trueBlock`
  12101. * - else, when there is a block connected to the IIf block, the flow continues
  12102. * with that block.
  12103. * - When `condition` evaluates false:
  12104. * - when `falseBlock` is provided, the flow continues with `falseBlock`
  12105. *
  12106. * Syntax:
  12107. *
  12108. * new IIf(condition, trueBlock)
  12109. * new IIf(condition, trueBlock [, falseBlock])
  12110. * new IIf(condition).then(...)
  12111. *
  12112. * @param {Function | RegExp | *} condition A condition returning true or false
  12113. * In case of a function,
  12114. * the function is invoked as
  12115. * `condition(message, context)` and
  12116. * must return a boolean. In case of
  12117. * a RegExp, condition will be tested
  12118. * to return true. In other cases,
  12119. * non-strict equality is tested on
  12120. * the input.
  12121. * @param {Block} [trueBlock]
  12122. * @param {Block} [falseBlock]
  12123. * @returns {Block} Returns the created IIf block
  12124. */
  12125. Block.prototype.iif = function (condition, trueBlock, falseBlock) {
  12126. var iif = new IIf(condition, trueBlock, falseBlock);
  12127. return this.then(iif);
  12128. };
  12129. module.exports = IIf;
  12130. },{"../util":51,"./Block":44,"./Then":49,"es6-promise":52}],47:[function(_dereq_,module,exports){
  12131. 'use strict';
  12132. var Promise = _dereq_('es6-promise').Promise;
  12133. var Block = _dereq_('./Block');
  12134. var Then = _dereq_('./Then');
  12135. /**
  12136. * Listen
  12137. * Wait until a message comes in from the connected peer, then continue
  12138. * with the next block in the control flow.
  12139. *
  12140. * @constructor
  12141. * @extends {Block}
  12142. */
  12143. function Listen () {
  12144. if (!(this instanceof Listen)) {
  12145. throw new SyntaxError('Constructor must be called with the new operator');
  12146. }
  12147. }
  12148. Listen.prototype = Object.create(Block.prototype);
  12149. Listen.prototype.constructor = Listen;
  12150. /**
  12151. * Execute the block
  12152. * @param {Conversation} conversation
  12153. * @param {*} [message] Message is ignored by Listen blocks
  12154. * @return {Promise.<{result: *, block: Block}, Error>} next
  12155. */
  12156. Listen.prototype.execute = function (conversation, message) {
  12157. var me = this;
  12158. // wait until a message is received
  12159. return conversation.receive()
  12160. .then(function (message) {
  12161. return {
  12162. result: message,
  12163. block: me.next
  12164. }
  12165. });
  12166. };
  12167. /**
  12168. * Create a Listen block and chain it to the current block
  12169. *
  12170. * Optionally a callback function can be provided, which is equivalent of
  12171. * doing `listen().then(callback)`.
  12172. *
  12173. * @param {Function} [callback] Executed as callback(message: *, context: Object)
  12174. * Must return a result
  12175. * @return {Block} Returns the appended block
  12176. */
  12177. Block.prototype.listen = function (callback) {
  12178. var listen = new Listen();
  12179. var block = this.then(listen);
  12180. if (callback) {
  12181. block = block.then(callback);
  12182. }
  12183. return block;
  12184. };
  12185. module.exports = Listen;
  12186. },{"./Block":44,"./Then":49,"es6-promise":52}],48:[function(_dereq_,module,exports){
  12187. 'use strict';
  12188. var Promise = _dereq_('es6-promise').Promise;
  12189. var Block = _dereq_('./Block');
  12190. var isPromise = _dereq_('../util').isPromise;
  12191. _dereq_('./Then'); // extend Block with function then
  12192. _dereq_('./Listen'); // extend Block with function listen
  12193. /**
  12194. * Tell
  12195. * Send a message to the other peer.
  12196. * @param {* | Function} message A static message or callback function
  12197. * returning a message dynamically.
  12198. * When `message` is a function, it will be
  12199. * invoked as callback(message, context),
  12200. * where `message` is the output from the
  12201. * previous block in the chain, and `context` is
  12202. * an object where state can be stored during a
  12203. * conversation.
  12204. * @constructor
  12205. * @extends {Block}
  12206. */
  12207. function Tell (message) {
  12208. if (!(this instanceof Tell)) {
  12209. throw new SyntaxError('Constructor must be called with the new operator');
  12210. }
  12211. this.message = message;
  12212. }
  12213. Tell.prototype = Object.create(Block.prototype);
  12214. Tell.prototype.constructor = Tell;
  12215. /**
  12216. * Execute the block
  12217. * @param {Conversation} conversation
  12218. * @param {*} [message] A message is ignored by the Tell block
  12219. * @return {Promise.<{result: *, block: Block}, Error>} next
  12220. */
  12221. Tell.prototype.execute = function (conversation, message) {
  12222. // resolve the message
  12223. var me = this;
  12224. var resolve;
  12225. if (typeof this.message === 'function') {
  12226. var result = this.message(message, conversation.context);
  12227. resolve = isPromise(result) ? result : Promise.resolve(result);
  12228. }
  12229. else {
  12230. resolve = Promise.resolve(this.message); // static string or value
  12231. }
  12232. return resolve
  12233. .then(function (result) {
  12234. var res = conversation.send(result);
  12235. var done = isPromise(res) ? res : Promise.resolve(res);
  12236. return done.then(function () {
  12237. return {
  12238. result: result,
  12239. block: me.next
  12240. };
  12241. });
  12242. });
  12243. };
  12244. /**
  12245. * Create a Tell block and chain it to the current block
  12246. * @param {* | Function} [message] A static message or callback function
  12247. * returning a message dynamically.
  12248. * When `message` is a function, it will be
  12249. * invoked as callback(message, context),
  12250. * where `message` is the output from the
  12251. * previous block in the chain, and `context` is
  12252. * an object where state can be stored during a
  12253. * conversation.
  12254. * @return {Block} Returns the appended block
  12255. */
  12256. Block.prototype.tell = function (message) {
  12257. var block = new Tell(message);
  12258. return this.then(block);
  12259. };
  12260. /**
  12261. * Send a question, listen for a response.
  12262. * Creates two blocks: Tell and Listen.
  12263. * This is equivalent of doing `babble.tell(message).listen(callback)`
  12264. * @param {* | Function} message
  12265. * @param {Function} [callback] Invoked as callback(message, context),
  12266. * where `message` is the just received message,
  12267. * and `context` is an object where state can be
  12268. * stored during a conversation. This is equivalent
  12269. * of doing `listen().then(callback)`
  12270. * @return {Block} Returns the appended block
  12271. */
  12272. Block.prototype.ask = function (message, callback) {
  12273. // FIXME: this doesn't work
  12274. return this
  12275. .tell(message)
  12276. .listen(callback);
  12277. };
  12278. module.exports = Tell;
  12279. },{"../util":51,"./Block":44,"./Listen":47,"./Then":49,"es6-promise":52}],49:[function(_dereq_,module,exports){
  12280. 'use strict';
  12281. var Promise = _dereq_('es6-promise').Promise;
  12282. var Block = _dereq_('./Block');
  12283. var isPromise = _dereq_('../util').isPromise;
  12284. /**
  12285. * Then
  12286. * Execute a callback function or a next block in the chain.
  12287. * @param {Function} callback Invoked as callback(message, context),
  12288. * where `message` is the output from the previous
  12289. * block in the chain, and `context` is an object
  12290. * where state can be stored during a conversation.
  12291. * @constructor
  12292. * @extends {Block}
  12293. */
  12294. function Then (callback) {
  12295. if (!(this instanceof Then)) {
  12296. throw new SyntaxError('Constructor must be called with the new operator');
  12297. }
  12298. if (!(typeof callback === 'function')) {
  12299. throw new TypeError('Parameter callback must be a Function');
  12300. }
  12301. this.callback = callback;
  12302. }
  12303. Then.prototype = Object.create(Block.prototype);
  12304. Then.prototype.constructor = Then;
  12305. /**
  12306. * Execute the block
  12307. * @param {Conversation} conversation
  12308. * @param {*} message
  12309. * @return {Promise.<{result: *, block: Block}, Error>} next
  12310. */
  12311. Then.prototype.execute = function (conversation, message) {
  12312. var me = this;
  12313. var result = this.callback(message, conversation.context);
  12314. var resolve = isPromise(result) ? result : Promise.resolve(result);
  12315. return resolve.then(function (result) {
  12316. return {
  12317. result: result,
  12318. block: me.next
  12319. }
  12320. });
  12321. };
  12322. /**
  12323. * Chain a block to the current block.
  12324. *
  12325. * When a function is provided, a Then block will be generated which
  12326. * executes the function. The function is invoked as callback(message, context),
  12327. * where `message` is the output from the previous block in the chain,
  12328. * and `context` is an object where state can be stored during a conversation.
  12329. *
  12330. * @param {Block | function} next A callback function or Block.
  12331. * @return {Block} Returns the appended block
  12332. */
  12333. Block.prototype.then = function (next) {
  12334. // turn a callback function into a Then block
  12335. if (typeof next === 'function') {
  12336. next = new Then(next);
  12337. }
  12338. if (!(next instanceof Block)) {
  12339. throw new TypeError('Parameter next must be a Block or function');
  12340. }
  12341. // append after the last block
  12342. next.previous = this;
  12343. this.next = next;
  12344. // return the appended block
  12345. return next;
  12346. };
  12347. module.exports = Then;
  12348. },{"../util":51,"./Block":44,"es6-promise":52}],50:[function(_dereq_,module,exports){
  12349. 'use strict';
  12350. var Promise = _dereq_('es6-promise').Promise;
  12351. // built-in messaging interfaces
  12352. /**
  12353. * pubsub-js messaging interface
  12354. * @returns {{connect: function, disconnect: function, send: function}}
  12355. */
  12356. exports['pubsub-js'] = function () {
  12357. var PubSub = _dereq_('pubsub-js');
  12358. return {
  12359. connect: function (params) {
  12360. var token = PubSub.subscribe(params.id, function (id, message) {
  12361. params.message(message);
  12362. });
  12363. if (typeof params.callback === 'function') {
  12364. params.callback();
  12365. }
  12366. return token;
  12367. },
  12368. disconnect: function(token) {
  12369. PubSub.unsubscribe(token);
  12370. },
  12371. send: function (to, message) {
  12372. PubSub.publish(to, message);
  12373. }
  12374. }
  12375. };
  12376. /**
  12377. * // pubnub messaging interface
  12378. * @param {{publish_key: string, subscribe_key: string}} params
  12379. * @returns {{connect: function, disconnect: function, send: function}}
  12380. */
  12381. exports['pubnub'] = function (params) {
  12382. var PUBNUB;
  12383. if (typeof window !== 'undefined') {
  12384. // browser
  12385. if (typeof window['PUBNUB'] === 'undefined') {
  12386. throw new Error('Please load pubnub first in the browser');
  12387. }
  12388. PUBNUB = window['PUBNUB'];
  12389. }
  12390. else {
  12391. // node.js
  12392. PUBNUB = _dereq_('pubnub');
  12393. }
  12394. var pubnub = PUBNUB.init(params);
  12395. return {
  12396. connect: function (params) {
  12397. pubnub.subscribe({
  12398. channel: params.id,
  12399. message: params.message,
  12400. connect: params.callback
  12401. });
  12402. return params.id;
  12403. },
  12404. disconnect: function (id) {
  12405. pubnub.unsubscribe(id);
  12406. },
  12407. send: function (to, message) {
  12408. return new Promise(function (resolve, reject) {
  12409. pubnub.publish({
  12410. channel: to,
  12411. message: message,
  12412. callback: resolve
  12413. });
  12414. })
  12415. }
  12416. }
  12417. };
  12418. // default interface
  12419. exports['default'] = exports['pubsub-js'];
  12420. },{"es6-promise":52,"pubnub":65,"pubsub-js":66}],51:[function(_dereq_,module,exports){
  12421. /**
  12422. * Test whether the provided value is a Promise.
  12423. * A value is marked as a Promise when it is an object containing functions
  12424. * `then` and `catch`.
  12425. * @param {*} value
  12426. * @return {boolean} Returns true when `value` is a Promise
  12427. */
  12428. exports.isPromise = function (value) {
  12429. return value &&
  12430. typeof value['then'] === 'function' &&
  12431. typeof value['catch'] === 'function'
  12432. };
  12433. },{}],52:[function(_dereq_,module,exports){
  12434. "use strict";
  12435. var Promise = _dereq_("./promise/promise").Promise;
  12436. var polyfill = _dereq_("./promise/polyfill").polyfill;
  12437. exports.Promise = Promise;
  12438. exports.polyfill = polyfill;
  12439. },{"./promise/polyfill":56,"./promise/promise":57}],53:[function(_dereq_,module,exports){
  12440. "use strict";
  12441. /* global toString */
  12442. var isArray = _dereq_("./utils").isArray;
  12443. var isFunction = _dereq_("./utils").isFunction;
  12444. /**
  12445. Returns a promise that is fulfilled when all the given promises have been
  12446. fulfilled, or rejected if any of them become rejected. The return promise
  12447. is fulfilled with an array that gives all the values in the order they were
  12448. passed in the `promises` array argument.
  12449. Example:
  12450. ```javascript
  12451. var promise1 = RSVP.resolve(1);
  12452. var promise2 = RSVP.resolve(2);
  12453. var promise3 = RSVP.resolve(3);
  12454. var promises = [ promise1, promise2, promise3 ];
  12455. RSVP.all(promises).then(function(array){
  12456. // The array here would be [ 1, 2, 3 ];
  12457. });
  12458. ```
  12459. If any of the `promises` given to `RSVP.all` are rejected, the first promise
  12460. that is rejected will be given as an argument to the returned promises's
  12461. rejection handler. For example:
  12462. Example:
  12463. ```javascript
  12464. var promise1 = RSVP.resolve(1);
  12465. var promise2 = RSVP.reject(new Error("2"));
  12466. var promise3 = RSVP.reject(new Error("3"));
  12467. var promises = [ promise1, promise2, promise3 ];
  12468. RSVP.all(promises).then(function(array){
  12469. // Code here never runs because there are rejected promises!
  12470. }, function(error) {
  12471. // error.message === "2"
  12472. });
  12473. ```
  12474. @method all
  12475. @for RSVP
  12476. @param {Array} promises
  12477. @param {String} label
  12478. @return {Promise} promise that is fulfilled when all `promises` have been
  12479. fulfilled, or rejected if any of them become rejected.
  12480. */
  12481. function all(promises) {
  12482. /*jshint validthis:true */
  12483. var Promise = this;
  12484. if (!isArray(promises)) {
  12485. throw new TypeError('You must pass an array to all.');
  12486. }
  12487. return new Promise(function(resolve, reject) {
  12488. var results = [], remaining = promises.length,
  12489. promise;
  12490. if (remaining === 0) {
  12491. resolve([]);
  12492. }
  12493. function resolver(index) {
  12494. return function(value) {
  12495. resolveAll(index, value);
  12496. };
  12497. }
  12498. function resolveAll(index, value) {
  12499. results[index] = value;
  12500. if (--remaining === 0) {
  12501. resolve(results);
  12502. }
  12503. }
  12504. for (var i = 0; i < promises.length; i++) {
  12505. promise = promises[i];
  12506. if (promise && isFunction(promise.then)) {
  12507. promise.then(resolver(i), reject);
  12508. } else {
  12509. resolveAll(i, promise);
  12510. }
  12511. }
  12512. });
  12513. }
  12514. exports.all = all;
  12515. },{"./utils":61}],54:[function(_dereq_,module,exports){
  12516. (function (process,global){
  12517. "use strict";
  12518. var browserGlobal = (typeof window !== 'undefined') ? window : {};
  12519. var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
  12520. var local = (typeof global !== 'undefined') ? global : (this === undefined? window:this);
  12521. // node
  12522. function useNextTick() {
  12523. return function() {
  12524. process.nextTick(flush);
  12525. };
  12526. }
  12527. function useMutationObserver() {
  12528. var iterations = 0;
  12529. var observer = new BrowserMutationObserver(flush);
  12530. var node = document.createTextNode('');
  12531. observer.observe(node, { characterData: true });
  12532. return function() {
  12533. node.data = (iterations = ++iterations % 2);
  12534. };
  12535. }
  12536. function useSetTimeout() {
  12537. return function() {
  12538. local.setTimeout(flush, 1);
  12539. };
  12540. }
  12541. var queue = [];
  12542. function flush() {
  12543. for (var i = 0; i < queue.length; i++) {
  12544. var tuple = queue[i];
  12545. var callback = tuple[0], arg = tuple[1];
  12546. callback(arg);
  12547. }
  12548. queue = [];
  12549. }
  12550. var scheduleFlush;
  12551. // Decide what async method to use to triggering processing of queued callbacks:
  12552. if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
  12553. scheduleFlush = useNextTick();
  12554. } else if (BrowserMutationObserver) {
  12555. scheduleFlush = useMutationObserver();
  12556. } else {
  12557. scheduleFlush = useSetTimeout();
  12558. }
  12559. function asap(callback, arg) {
  12560. var length = queue.push([callback, arg]);
  12561. if (length === 1) {
  12562. // If length is 1, that means that we need to schedule an async flush.
  12563. // If additional callbacks are queued before the queue is flushed, they
  12564. // will be processed by this flush that we are scheduling.
  12565. scheduleFlush();
  12566. }
  12567. }
  12568. exports.asap = asap;
  12569. }).call(this,_dereq_("C:\\Users\\Alex\\AppData\\Roaming\\npm\\node_modules\\browserify\\node_modules\\insert-module-globals\\node_modules\\process\\browser.js"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12570. },{"C:\\Users\\Alex\\AppData\\Roaming\\npm\\node_modules\\browserify\\node_modules\\insert-module-globals\\node_modules\\process\\browser.js":144}],55:[function(_dereq_,module,exports){
  12571. "use strict";
  12572. var config = {
  12573. instrument: false
  12574. };
  12575. function configure(name, value) {
  12576. if (arguments.length === 2) {
  12577. config[name] = value;
  12578. } else {
  12579. return config[name];
  12580. }
  12581. }
  12582. exports.config = config;
  12583. exports.configure = configure;
  12584. },{}],56:[function(_dereq_,module,exports){
  12585. (function (global){
  12586. "use strict";
  12587. /*global self*/
  12588. var RSVPPromise = _dereq_("./promise").Promise;
  12589. var isFunction = _dereq_("./utils").isFunction;
  12590. function polyfill() {
  12591. var local;
  12592. if (typeof global !== 'undefined') {
  12593. local = global;
  12594. } else if (typeof window !== 'undefined' && window.document) {
  12595. local = window;
  12596. } else {
  12597. local = self;
  12598. }
  12599. var es6PromiseSupport =
  12600. "Promise" in local &&
  12601. // Some of these methods are missing from
  12602. // Firefox/Chrome experimental implementations
  12603. "resolve" in local.Promise &&
  12604. "reject" in local.Promise &&
  12605. "all" in local.Promise &&
  12606. "race" in local.Promise &&
  12607. // Older version of the spec had a resolver object
  12608. // as the arg rather than a function
  12609. (function() {
  12610. var resolve;
  12611. new local.Promise(function(r) { resolve = r; });
  12612. return isFunction(resolve);
  12613. }());
  12614. if (!es6PromiseSupport) {
  12615. local.Promise = RSVPPromise;
  12616. }
  12617. }
  12618. exports.polyfill = polyfill;
  12619. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12620. },{"./promise":57,"./utils":61}],57:[function(_dereq_,module,exports){
  12621. "use strict";
  12622. var config = _dereq_("./config").config;
  12623. var configure = _dereq_("./config").configure;
  12624. var objectOrFunction = _dereq_("./utils").objectOrFunction;
  12625. var isFunction = _dereq_("./utils").isFunction;
  12626. var now = _dereq_("./utils").now;
  12627. var all = _dereq_("./all").all;
  12628. var race = _dereq_("./race").race;
  12629. var staticResolve = _dereq_("./resolve").resolve;
  12630. var staticReject = _dereq_("./reject").reject;
  12631. var asap = _dereq_("./asap").asap;
  12632. var counter = 0;
  12633. config.async = asap; // default async is asap;
  12634. function Promise(resolver) {
  12635. if (!isFunction(resolver)) {
  12636. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  12637. }
  12638. if (!(this instanceof Promise)) {
  12639. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  12640. }
  12641. this._subscribers = [];
  12642. invokeResolver(resolver, this);
  12643. }
  12644. function invokeResolver(resolver, promise) {
  12645. function resolvePromise(value) {
  12646. resolve(promise, value);
  12647. }
  12648. function rejectPromise(reason) {
  12649. reject(promise, reason);
  12650. }
  12651. try {
  12652. resolver(resolvePromise, rejectPromise);
  12653. } catch(e) {
  12654. rejectPromise(e);
  12655. }
  12656. }
  12657. function invokeCallback(settled, promise, callback, detail) {
  12658. var hasCallback = isFunction(callback),
  12659. value, error, succeeded, failed;
  12660. if (hasCallback) {
  12661. try {
  12662. value = callback(detail);
  12663. succeeded = true;
  12664. } catch(e) {
  12665. failed = true;
  12666. error = e;
  12667. }
  12668. } else {
  12669. value = detail;
  12670. succeeded = true;
  12671. }
  12672. if (handleThenable(promise, value)) {
  12673. return;
  12674. } else if (hasCallback && succeeded) {
  12675. resolve(promise, value);
  12676. } else if (failed) {
  12677. reject(promise, error);
  12678. } else if (settled === FULFILLED) {
  12679. resolve(promise, value);
  12680. } else if (settled === REJECTED) {
  12681. reject(promise, value);
  12682. }
  12683. }
  12684. var PENDING = void 0;
  12685. var SEALED = 0;
  12686. var FULFILLED = 1;
  12687. var REJECTED = 2;
  12688. function subscribe(parent, child, onFulfillment, onRejection) {
  12689. var subscribers = parent._subscribers;
  12690. var length = subscribers.length;
  12691. subscribers[length] = child;
  12692. subscribers[length + FULFILLED] = onFulfillment;
  12693. subscribers[length + REJECTED] = onRejection;
  12694. }
  12695. function publish(promise, settled) {
  12696. var child, callback, subscribers = promise._subscribers, detail = promise._detail;
  12697. for (var i = 0; i < subscribers.length; i += 3) {
  12698. child = subscribers[i];
  12699. callback = subscribers[i + settled];
  12700. invokeCallback(settled, child, callback, detail);
  12701. }
  12702. promise._subscribers = null;
  12703. }
  12704. Promise.prototype = {
  12705. constructor: Promise,
  12706. _state: undefined,
  12707. _detail: undefined,
  12708. _subscribers: undefined,
  12709. then: function(onFulfillment, onRejection) {
  12710. var promise = this;
  12711. var thenPromise = new this.constructor(function() {});
  12712. if (this._state) {
  12713. var callbacks = arguments;
  12714. config.async(function invokePromiseCallback() {
  12715. invokeCallback(promise._state, thenPromise, callbacks[promise._state - 1], promise._detail);
  12716. });
  12717. } else {
  12718. subscribe(this, thenPromise, onFulfillment, onRejection);
  12719. }
  12720. return thenPromise;
  12721. },
  12722. 'catch': function(onRejection) {
  12723. return this.then(null, onRejection);
  12724. }
  12725. };
  12726. Promise.all = all;
  12727. Promise.race = race;
  12728. Promise.resolve = staticResolve;
  12729. Promise.reject = staticReject;
  12730. function handleThenable(promise, value) {
  12731. var then = null,
  12732. resolved;
  12733. try {
  12734. if (promise === value) {
  12735. throw new TypeError("A promises callback cannot return that same promise.");
  12736. }
  12737. if (objectOrFunction(value)) {
  12738. then = value.then;
  12739. if (isFunction(then)) {
  12740. then.call(value, function(val) {
  12741. if (resolved) { return true; }
  12742. resolved = true;
  12743. if (value !== val) {
  12744. resolve(promise, val);
  12745. } else {
  12746. fulfill(promise, val);
  12747. }
  12748. }, function(val) {
  12749. if (resolved) { return true; }
  12750. resolved = true;
  12751. reject(promise, val);
  12752. });
  12753. return true;
  12754. }
  12755. }
  12756. } catch (error) {
  12757. if (resolved) { return true; }
  12758. reject(promise, error);
  12759. return true;
  12760. }
  12761. return false;
  12762. }
  12763. function resolve(promise, value) {
  12764. if (promise === value) {
  12765. fulfill(promise, value);
  12766. } else if (!handleThenable(promise, value)) {
  12767. fulfill(promise, value);
  12768. }
  12769. }
  12770. function fulfill(promise, value) {
  12771. if (promise._state !== PENDING) { return; }
  12772. promise._state = SEALED;
  12773. promise._detail = value;
  12774. config.async(publishFulfillment, promise);
  12775. }
  12776. function reject(promise, reason) {
  12777. if (promise._state !== PENDING) { return; }
  12778. promise._state = SEALED;
  12779. promise._detail = reason;
  12780. config.async(publishRejection, promise);
  12781. }
  12782. function publishFulfillment(promise) {
  12783. publish(promise, promise._state = FULFILLED);
  12784. }
  12785. function publishRejection(promise) {
  12786. publish(promise, promise._state = REJECTED);
  12787. }
  12788. exports.Promise = Promise;
  12789. },{"./all":53,"./asap":54,"./config":55,"./race":58,"./reject":59,"./resolve":60,"./utils":61}],58:[function(_dereq_,module,exports){
  12790. "use strict";
  12791. /* global toString */
  12792. var isArray = _dereq_("./utils").isArray;
  12793. /**
  12794. `RSVP.race` allows you to watch a series of promises and act as soon as the
  12795. first promise given to the `promises` argument fulfills or rejects.
  12796. Example:
  12797. ```javascript
  12798. var promise1 = new RSVP.Promise(function(resolve, reject){
  12799. setTimeout(function(){
  12800. resolve("promise 1");
  12801. }, 200);
  12802. });
  12803. var promise2 = new RSVP.Promise(function(resolve, reject){
  12804. setTimeout(function(){
  12805. resolve("promise 2");
  12806. }, 100);
  12807. });
  12808. RSVP.race([promise1, promise2]).then(function(result){
  12809. // result === "promise 2" because it was resolved before promise1
  12810. // was resolved.
  12811. });
  12812. ```
  12813. `RSVP.race` is deterministic in that only the state of the first completed
  12814. promise matters. For example, even if other promises given to the `promises`
  12815. array argument are resolved, but the first completed promise has become
  12816. rejected before the other promises became fulfilled, the returned promise
  12817. will become rejected:
  12818. ```javascript
  12819. var promise1 = new RSVP.Promise(function(resolve, reject){
  12820. setTimeout(function(){
  12821. resolve("promise 1");
  12822. }, 200);
  12823. });
  12824. var promise2 = new RSVP.Promise(function(resolve, reject){
  12825. setTimeout(function(){
  12826. reject(new Error("promise 2"));
  12827. }, 100);
  12828. });
  12829. RSVP.race([promise1, promise2]).then(function(result){
  12830. // Code here never runs because there are rejected promises!
  12831. }, function(reason){
  12832. // reason.message === "promise2" because promise 2 became rejected before
  12833. // promise 1 became fulfilled
  12834. });
  12835. ```
  12836. @method race
  12837. @for RSVP
  12838. @param {Array} promises array of promises to observe
  12839. @param {String} label optional string for describing the promise returned.
  12840. Useful for tooling.
  12841. @return {Promise} a promise that becomes fulfilled with the value the first
  12842. completed promises is resolved with if the first completed promise was
  12843. fulfilled, or rejected with the reason that the first completed promise
  12844. was rejected with.
  12845. */
  12846. function race(promises) {
  12847. /*jshint validthis:true */
  12848. var Promise = this;
  12849. if (!isArray(promises)) {
  12850. throw new TypeError('You must pass an array to race.');
  12851. }
  12852. return new Promise(function(resolve, reject) {
  12853. var results = [], promise;
  12854. for (var i = 0; i < promises.length; i++) {
  12855. promise = promises[i];
  12856. if (promise && typeof promise.then === 'function') {
  12857. promise.then(resolve, reject);
  12858. } else {
  12859. resolve(promise);
  12860. }
  12861. }
  12862. });
  12863. }
  12864. exports.race = race;
  12865. },{"./utils":61}],59:[function(_dereq_,module,exports){
  12866. "use strict";
  12867. /**
  12868. `RSVP.reject` returns a promise that will become rejected with the passed
  12869. `reason`. `RSVP.reject` is essentially shorthand for the following:
  12870. ```javascript
  12871. var promise = new RSVP.Promise(function(resolve, reject){
  12872. reject(new Error('WHOOPS'));
  12873. });
  12874. promise.then(function(value){
  12875. // Code here doesn't run because the promise is rejected!
  12876. }, function(reason){
  12877. // reason.message === 'WHOOPS'
  12878. });
  12879. ```
  12880. Instead of writing the above, your code now simply becomes the following:
  12881. ```javascript
  12882. var promise = RSVP.reject(new Error('WHOOPS'));
  12883. promise.then(function(value){
  12884. // Code here doesn't run because the promise is rejected!
  12885. }, function(reason){
  12886. // reason.message === 'WHOOPS'
  12887. });
  12888. ```
  12889. @method reject
  12890. @for RSVP
  12891. @param {Any} reason value that the returned promise will be rejected with.
  12892. @param {String} label optional string for identifying the returned promise.
  12893. Useful for tooling.
  12894. @return {Promise} a promise that will become rejected with the given
  12895. `reason`.
  12896. */
  12897. function reject(reason) {
  12898. /*jshint validthis:true */
  12899. var Promise = this;
  12900. return new Promise(function (resolve, reject) {
  12901. reject(reason);
  12902. });
  12903. }
  12904. exports.reject = reject;
  12905. },{}],60:[function(_dereq_,module,exports){
  12906. "use strict";
  12907. function resolve(value) {
  12908. /*jshint validthis:true */
  12909. if (value && typeof value === 'object' && value.constructor === this) {
  12910. return value;
  12911. }
  12912. var Promise = this;
  12913. return new Promise(function(resolve) {
  12914. resolve(value);
  12915. });
  12916. }
  12917. exports.resolve = resolve;
  12918. },{}],61:[function(_dereq_,module,exports){
  12919. "use strict";
  12920. function objectOrFunction(x) {
  12921. return isFunction(x) || (typeof x === "object" && x !== null);
  12922. }
  12923. function isFunction(x) {
  12924. return typeof x === "function";
  12925. }
  12926. function isArray(x) {
  12927. return Object.prototype.toString.call(x) === "[object Array]";
  12928. }
  12929. // Date.now is not available in browsers < IE9
  12930. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility
  12931. var now = Date.now || function() { return new Date().getTime(); };
  12932. exports.objectOrFunction = objectOrFunction;
  12933. exports.isFunction = isFunction;
  12934. exports.isArray = isArray;
  12935. exports.now = now;
  12936. },{}],62:[function(_dereq_,module,exports){
  12937. module.exports = _dereq_('./lib/agent');
  12938. },{"./lib/agent":64}],63:[function(_dereq_,module,exports){
  12939. (function (process){
  12940. // Copyright Joyent, Inc. and other Node contributors.
  12941. //
  12942. // Permission is hereby granted, free of charge, to any person obtaining a
  12943. // copy of this software and associated documentation files (the
  12944. // "Software"), to deal in the Software without restriction, including
  12945. // without limitation the rights to use, copy, modify, merge, publish,
  12946. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12947. // persons to whom the Software is furnished to do so, subject to the
  12948. // following conditions:
  12949. //
  12950. // The above copyright notice and this permission notice shall be included
  12951. // in all copies or substantial portions of the Software.
  12952. //
  12953. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12954. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12955. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12956. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12957. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12958. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12959. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12960. // copy from https://github.com/joyent/node/blob/master/lib/_http_agent.js
  12961. var net = _dereq_('net');
  12962. var url = _dereq_('url');
  12963. var util = _dereq_('util');
  12964. var EventEmitter = _dereq_('events').EventEmitter;
  12965. // var ClientRequest = require('_http_client').ClientRequest;
  12966. // var debug = util.debuglog('http');
  12967. var ClientRequest = _dereq_('http').ClientRequest;
  12968. var debug;
  12969. if (process.env.NODE_DEBUG && /agentkeepalive/.test(process.env.NODE_DEBUG)) {
  12970. debug = function (x) {
  12971. console.error.apply(console, arguments);
  12972. };
  12973. } else {
  12974. debug = function () { };
  12975. }
  12976. // New Agent code.
  12977. // The largest departure from the previous implementation is that
  12978. // an Agent instance holds connections for a variable number of host:ports.
  12979. // Surprisingly, this is still API compatible as far as third parties are
  12980. // concerned. The only code that really notices the difference is the
  12981. // request object.
  12982. // Another departure is that all code related to HTTP parsing is in
  12983. // ClientRequest.onSocket(). The Agent is now *strictly*
  12984. // concerned with managing a connection pool.
  12985. function Agent(options) {
  12986. if (!(this instanceof Agent))
  12987. return new Agent(options);
  12988. EventEmitter.call(this);
  12989. var self = this;
  12990. self.defaultPort = 80;
  12991. self.protocol = 'http:';
  12992. self.options = util._extend({}, options);
  12993. // don't confuse net and make it think that we're connecting to a pipe
  12994. self.options.path = null;
  12995. self.requests = {};
  12996. self.sockets = {};
  12997. self.freeSockets = {};
  12998. self.keepAliveMsecs = self.options.keepAliveMsecs || 1000;
  12999. self.keepAlive = self.options.keepAlive || false;
  13000. self.maxSockets = self.options.maxSockets || Agent.defaultMaxSockets;
  13001. self.maxFreeSockets = self.options.maxFreeSockets || 256;
  13002. self.on('free', function(socket, options) {
  13003. var name = self.getName(options);
  13004. debug('agent.on(free)', name);
  13005. if (!socket.destroyed &&
  13006. self.requests[name] && self.requests[name].length) {
  13007. self.requests[name].shift().onSocket(socket);
  13008. if (self.requests[name].length === 0) {
  13009. // don't leak
  13010. delete self.requests[name];
  13011. }
  13012. } else {
  13013. // If there are no pending requests, then put it in
  13014. // the freeSockets pool, but only if we're allowed to do so.
  13015. var req = socket._httpMessage;
  13016. if (req &&
  13017. req.shouldKeepAlive &&
  13018. !socket.destroyed &&
  13019. self.options.keepAlive) {
  13020. var freeSockets = self.freeSockets[name];
  13021. var freeLen = freeSockets ? freeSockets.length : 0;
  13022. var count = freeLen;
  13023. if (self.sockets[name])
  13024. count += self.sockets[name].length;
  13025. if (count >= self.maxSockets || freeLen >= self.maxFreeSockets) {
  13026. self.removeSocket(socket, options);
  13027. socket.destroy();
  13028. } else {
  13029. freeSockets = freeSockets || [];
  13030. self.freeSockets[name] = freeSockets;
  13031. socket.setKeepAlive(true, self.keepAliveMsecs);
  13032. socket.unref && socket.unref();
  13033. socket._httpMessage = null;
  13034. self.removeSocket(socket, options);
  13035. freeSockets.push(socket);
  13036. }
  13037. } else {
  13038. self.removeSocket(socket, options);
  13039. socket.destroy();
  13040. }
  13041. }
  13042. });
  13043. }
  13044. util.inherits(Agent, EventEmitter);
  13045. exports.Agent = Agent;
  13046. Agent.defaultMaxSockets = Infinity;
  13047. Agent.prototype.createConnection = net.createConnection;
  13048. // Get the key for a given set of request options
  13049. Agent.prototype.getName = function(options) {
  13050. var name = '';
  13051. if (options.host)
  13052. name += options.host;
  13053. else
  13054. name += 'localhost';
  13055. name += ':';
  13056. if (options.port)
  13057. name += options.port;
  13058. name += ':';
  13059. if (options.localAddress)
  13060. name += options.localAddress;
  13061. name += ':';
  13062. return name;
  13063. };
  13064. Agent.prototype.addRequest = function(req, options) {
  13065. // Legacy API: addRequest(req, host, port, path)
  13066. if (typeof options === 'string') {
  13067. options = {
  13068. host: options,
  13069. port: arguments[2],
  13070. path: arguments[3]
  13071. };
  13072. }
  13073. var name = this.getName(options);
  13074. if (!this.sockets[name]) {
  13075. this.sockets[name] = [];
  13076. }
  13077. var freeLen = this.freeSockets[name] ? this.freeSockets[name].length : 0;
  13078. var sockLen = freeLen + this.sockets[name].length;
  13079. if (freeLen) {
  13080. // we have a free socket, so use that.
  13081. var socket = this.freeSockets[name].shift();
  13082. debug('have free socket');
  13083. // don't leak
  13084. if (!this.freeSockets[name].length)
  13085. delete this.freeSockets[name];
  13086. socket.ref && socket.ref();
  13087. req.onSocket(socket);
  13088. this.sockets[name].push(socket);
  13089. } else if (sockLen < this.maxSockets) {
  13090. debug('call onSocket', sockLen, freeLen);
  13091. // If we are under maxSockets create a new one.
  13092. req.onSocket(this.createSocket(req, options));
  13093. } else {
  13094. debug('wait for socket');
  13095. // We are over limit so we'll add it to the queue.
  13096. if (!this.requests[name]) {
  13097. this.requests[name] = [];
  13098. }
  13099. this.requests[name].push(req);
  13100. }
  13101. };
  13102. Agent.prototype.createSocket = function(req, options) {
  13103. var self = this;
  13104. options = util._extend({}, options);
  13105. options = util._extend(options, self.options);
  13106. options.servername = options.host;
  13107. if (req) {
  13108. var hostHeader = req.getHeader('host');
  13109. if (hostHeader) {
  13110. options.servername = hostHeader.replace(/:.*$/, '');
  13111. }
  13112. }
  13113. var name = self.getName(options);
  13114. debug('createConnection', name, options);
  13115. var s = self.createConnection(options);
  13116. if (!self.sockets[name]) {
  13117. self.sockets[name] = [];
  13118. }
  13119. this.sockets[name].push(s);
  13120. debug('sockets', name, this.sockets[name].length);
  13121. function onFree() {
  13122. self.emit('free', s, options);
  13123. }
  13124. s.on('free', onFree);
  13125. function onClose(err) {
  13126. debug('CLIENT socket onClose');
  13127. // This is the only place where sockets get removed from the Agent.
  13128. // If you want to remove a socket from the pool, just close it.
  13129. // All socket errors end in a close event anyway.
  13130. self.removeSocket(s, options);
  13131. }
  13132. s.on('close', onClose);
  13133. function onRemove() {
  13134. // We need this function for cases like HTTP 'upgrade'
  13135. // (defined by WebSockets) where we need to remove a socket from the
  13136. // pool because it'll be locked up indefinitely
  13137. debug('CLIENT socket onRemove');
  13138. self.removeSocket(s, options, 'agentRemove');
  13139. s.removeListener('close', onClose);
  13140. s.removeListener('free', onFree);
  13141. s.removeListener('agentRemove', onRemove);
  13142. }
  13143. s.on('agentRemove', onRemove);
  13144. return s;
  13145. };
  13146. Agent.prototype.removeSocket = function(s, options) {
  13147. var name = this.getName(options);
  13148. debug('removeSocket', name, 'destroyed:', s.destroyed);
  13149. var sets = [this.sockets];
  13150. if (s.destroyed) {
  13151. // If the socket was destroyed, we need to remove it from the free buffers.
  13152. sets.push(this.freeSockets);
  13153. }
  13154. sets.forEach(function(sockets) {
  13155. if (sockets[name]) {
  13156. var index = sockets[name].indexOf(s);
  13157. if (index !== -1) {
  13158. sockets[name].splice(index, 1);
  13159. if (sockets[name].length === 0) {
  13160. // don't leak
  13161. delete sockets[name];
  13162. }
  13163. }
  13164. }
  13165. });
  13166. if (this.requests[name] && this.requests[name].length) {
  13167. debug('removeSocket, have a request, make a socket');
  13168. var req = this.requests[name][0];
  13169. // If we have pending requests and a socket gets closed make a new one
  13170. this.createSocket(req, options).emit('free');
  13171. }
  13172. };
  13173. Agent.prototype.destroy = function() {
  13174. var sets = [this.freeSockets, this.sockets];
  13175. sets.forEach(function(set) {
  13176. Object.keys(set).forEach(function(name) {
  13177. set[name].forEach(function(socket) {
  13178. socket.destroy();
  13179. });
  13180. });
  13181. });
  13182. };
  13183. Agent.prototype.request = function(options, cb) {
  13184. // if (util.isString(options)) {
  13185. // options = url.parse(options);
  13186. // }
  13187. if (typeof options === 'string') {
  13188. options = url.parse(options);
  13189. }
  13190. // don't try to do dns lookups of foo.com:8080, just foo.com
  13191. if (options.hostname) {
  13192. options.host = options.hostname;
  13193. }
  13194. if (options && options.path && / /.test(options.path)) {
  13195. // The actual regex is more like /[^A-Za-z0-9\-._~!$&'()*+,;=/:@]/
  13196. // with an additional rule for ignoring percentage-escaped characters
  13197. // but that's a) hard to capture in a regular expression that performs
  13198. // well, and b) possibly too restrictive for real-world usage. That's
  13199. // why it only scans for spaces because those are guaranteed to create
  13200. // an invalid request.
  13201. throw new TypeError('Request path contains unescaped characters.');
  13202. } else if (options.protocol && options.protocol !== this.protocol) {
  13203. throw new Error('Protocol:' + options.protocol + ' not supported.');
  13204. }
  13205. options = util._extend({
  13206. agent: this,
  13207. keepAlive: this.keepAlive
  13208. }, options);
  13209. // if it's false, then make a new one, just like this one.
  13210. if (options.agent === false)
  13211. options.agent = new this.constructor();
  13212. debug('agent.request', options);
  13213. return new ClientRequest(options, cb);
  13214. };
  13215. Agent.prototype.get = function(options, cb) {
  13216. var req = this.request(options, cb);
  13217. req.end();
  13218. return req;
  13219. };
  13220. exports.globalAgent = new Agent();
  13221. }).call(this,_dereq_("C:\\Users\\Alex\\AppData\\Roaming\\npm\\node_modules\\browserify\\node_modules\\insert-module-globals\\node_modules\\process\\browser.js"))
  13222. },{"C:\\Users\\Alex\\AppData\\Roaming\\npm\\node_modules\\browserify\\node_modules\\insert-module-globals\\node_modules\\process\\browser.js":144,"events":137,"http":138,"net":127,"url":157,"util":159}],64:[function(_dereq_,module,exports){
  13223. (function (process){
  13224. /**!
  13225. * agentkeepalive - lib/agent.js
  13226. *
  13227. * refer:
  13228. * * @atimb "Real keep-alive HTTP agent": https://gist.github.com/2963672
  13229. * * https://github.com/joyent/node/blob/master/lib/http.js
  13230. * * https://github.com/joyent/node/blob/master/lib/_http_agent.js
  13231. *
  13232. * Copyright(c) 2012 - 2013 fengmk2 <fengmk2@gmail.com>
  13233. * MIT Licensed
  13234. */
  13235. "use strict";
  13236. /**
  13237. * Module dependencies.
  13238. */
  13239. var http = _dereq_('http');
  13240. var https = _dereq_('https');
  13241. var util = _dereq_('util');
  13242. var debug;
  13243. if (process.env.NODE_DEBUG && /agentkeepalive/.test(process.env.NODE_DEBUG)) {
  13244. debug = function (x) {
  13245. console.error.apply(console, arguments);
  13246. };
  13247. } else {
  13248. debug = function () { };
  13249. }
  13250. var OriginalAgent = http.Agent;
  13251. if (process.version.indexOf('v0.8.') === 0 || process.version.indexOf('v0.10.') === 0) {
  13252. OriginalAgent = _dereq_('./_http_agent').Agent;
  13253. debug('%s use _http_agent', process.version);
  13254. }
  13255. function Agent(options) {
  13256. options = options || {};
  13257. options.keepAlive = options.keepAlive !== false;
  13258. options.keepAliveMsecs = options.keepAliveMsecs || options.maxKeepAliveTime;
  13259. OriginalAgent.call(this, options);
  13260. var self = this;
  13261. // max requests per keepalive socket, default is 0, no limit.
  13262. self.maxKeepAliveRequests = parseInt(options.maxKeepAliveRequests, 10) || 0;
  13263. // max keep alive time, default 60 seconds.
  13264. // if set `keepAliveMsecs = 0`, will disable keepalive feature.
  13265. self.createSocketCount = 0;
  13266. self.timeoutSocketCount = 0;
  13267. self.requestFinishedCount = 0;
  13268. // override the `free` event listener
  13269. self.removeAllListeners('free');
  13270. self.on('free', function (socket, options) {
  13271. self.requestFinishedCount++;
  13272. socket._requestCount++;
  13273. var name = self.getName(options);
  13274. debug('agent.on(free)', name);
  13275. if (!socket.destroyed &&
  13276. self.requests[name] && self.requests[name].length) {
  13277. self.requests[name].shift().onSocket(socket);
  13278. if (self.requests[name].length === 0) {
  13279. // don't leak
  13280. delete self.requests[name];
  13281. }
  13282. } else {
  13283. // If there are no pending requests, then put it in
  13284. // the freeSockets pool, but only if we're allowed to do so.
  13285. var req = socket._httpMessage;
  13286. if (req &&
  13287. req.shouldKeepAlive &&
  13288. !socket.destroyed &&
  13289. self.options.keepAlive) {
  13290. var freeSockets = self.freeSockets[name];
  13291. var freeLen = freeSockets ? freeSockets.length : 0;
  13292. var count = freeLen;
  13293. if (self.sockets[name])
  13294. count += self.sockets[name].length;
  13295. if (count >= self.maxSockets || freeLen >= self.maxFreeSockets) {
  13296. self.removeSocket(socket, options);
  13297. socket.destroy();
  13298. } else {
  13299. freeSockets = freeSockets || [];
  13300. self.freeSockets[name] = freeSockets;
  13301. socket.setKeepAlive(true, self.keepAliveMsecs);
  13302. socket.unref && socket.unref();
  13303. socket._httpMessage = null;
  13304. self.removeSocket(socket, options);
  13305. freeSockets.push(socket);
  13306. // Avoid duplicitive timeout events by removing timeout listeners set on
  13307. // socket by previous requests. node does not do this normally because it
  13308. // assumes sockets are too short-lived for it to matter. It becomes a
  13309. // problem when sockets are being reused. Steps are being taken to fix
  13310. // this issue upstream in node v0.10.0.
  13311. //
  13312. // See https://github.com/joyent/node/commit/451ff1540ab536237e8d751d241d7fc3391a4087
  13313. if (self.keepAliveMsecs && socket._events && Array.isArray(socket._events.timeout)) {
  13314. socket.removeAllListeners('timeout');
  13315. // Restore the socket's setTimeout() that was remove as collateral
  13316. // damage.
  13317. socket.setTimeout(self.keepAliveMsecs, socket._maxKeepAliveTimeout);
  13318. }
  13319. }
  13320. } else {
  13321. self.removeSocket(socket, options);
  13322. socket.destroy();
  13323. }
  13324. }
  13325. });
  13326. }
  13327. util.inherits(Agent, OriginalAgent);
  13328. module.exports = Agent;
  13329. Agent.prototype.createSocket = function (req, options) {
  13330. var self = this;
  13331. var socket = OriginalAgent.prototype.createSocket.call(this, req, options);
  13332. socket._requestCount = 0;
  13333. if (self.keepAliveMsecs) {
  13334. socket._maxKeepAliveTimeout = function () {
  13335. debug('maxKeepAliveTimeout, socket destroy()');
  13336. socket.destroy();
  13337. self.timeoutSocketCount++;
  13338. };
  13339. socket.setTimeout(self.keepAliveMsecs, socket._maxKeepAliveTimeout);
  13340. // Disable Nagle's algorithm: http://blog.caustik.com/2012/04/08/scaling-node-js-to-100k-concurrent-connections/
  13341. socket.setNoDelay(true);
  13342. }
  13343. this.createSocketCount++;
  13344. return socket;
  13345. };
  13346. Agent.prototype.removeSocket = function (s, options) {
  13347. OriginalAgent.prototype.removeSocket.call(this, s, options);
  13348. var name = this.getName(options);
  13349. debug('removeSocket', name, 'destroyed:', s.destroyed);
  13350. if (s.destroyed && this.freeSockets[name]) {
  13351. var index = this.freeSockets[name].indexOf(s);
  13352. if (index !== -1) {
  13353. this.freeSockets[name].splice(index, 1);
  13354. if (this.freeSockets[name].length === 0) {
  13355. // don't leak
  13356. delete this.freeSockets[name];
  13357. }
  13358. }
  13359. }
  13360. };
  13361. function HttpsAgent(options) {
  13362. Agent.call(this, options);
  13363. this.defaultPort = 443;
  13364. this.protocol = 'https:';
  13365. }
  13366. util.inherits(HttpsAgent, Agent);
  13367. HttpsAgent.prototype.createConnection = https.globalAgent.createConnection;
  13368. HttpsAgent.prototype.getName = function(options) {
  13369. var name = Agent.prototype.getName.call(this, options);
  13370. name += ':';
  13371. if (options.ca)
  13372. name += options.ca;
  13373. name += ':';
  13374. if (options.cert)
  13375. name += options.cert;
  13376. name += ':';
  13377. if (options.ciphers)
  13378. name += options.ciphers;
  13379. name += ':';
  13380. if (options.key)
  13381. name += options.key;
  13382. name += ':';
  13383. if (options.pfx)
  13384. name += options.pfx;
  13385. name += ':';
  13386. if (options.rejectUnauthorized !== undefined)
  13387. name += options.rejectUnauthorized;
  13388. return name;
  13389. };
  13390. Agent.HttpsAgent = HttpsAgent;
  13391. }).call(this,_dereq_("C:\\Users\\Alex\\AppData\\Roaming\\npm\\node_modules\\browserify\\node_modules\\insert-module-globals\\node_modules\\process\\browser.js"))
  13392. },{"./_http_agent":63,"C:\\Users\\Alex\\AppData\\Roaming\\npm\\node_modules\\browserify\\node_modules\\insert-module-globals\\node_modules\\process\\browser.js":144,"http":138,"https":142,"util":159}],65:[function(_dereq_,module,exports){
  13393. (function (Buffer){
  13394. // Version: 3.6.8
  13395. var NOW = 1
  13396. , READY = false
  13397. , READY_BUFFER = []
  13398. , PRESENCE_SUFFIX = '-pnpres'
  13399. , DEF_WINDOWING = 10 // MILLISECONDS.
  13400. , DEF_TIMEOUT = 10000 // MILLISECONDS.
  13401. , DEF_SUB_TIMEOUT = 310 // SECONDS.
  13402. , DEF_KEEPALIVE = 60 // SECONDS (FOR TIMESYNC).
  13403. , SECOND = 1000 // A THOUSAND MILLISECONDS.
  13404. , URLBIT = '/'
  13405. , PARAMSBIT = '&'
  13406. , PRESENCE_HB_THRESHOLD = 5
  13407. , PRESENCE_HB_DEFAULT = 30
  13408. , SDK_VER = '3.6.8'
  13409. , REPL = /{([\w\-]+)}/g;
  13410. /**
  13411. * UTILITIES
  13412. */
  13413. function unique() { return'x'+ ++NOW+''+(+new Date) }
  13414. function rnow() { return+new Date }
  13415. /**
  13416. * NEXTORIGIN
  13417. * ==========
  13418. * var next_origin = nextorigin();
  13419. */
  13420. var nextorigin = (function() {
  13421. var max = 20
  13422. , ori = Math.floor(Math.random() * max);
  13423. return function( origin, failover ) {
  13424. return origin.indexOf('pubsub.') > 0
  13425. && origin.replace(
  13426. 'pubsub', 'ps' + (
  13427. failover ? uuid().split('-')[0] :
  13428. (++ori < max? ori : ori=1)
  13429. ) ) || origin;
  13430. }
  13431. })();
  13432. /**
  13433. * Build Url
  13434. * =======
  13435. *
  13436. */
  13437. function build_url( url_components, url_params ) {
  13438. var url = url_components.join(URLBIT)
  13439. , params = [];
  13440. if (!url_params) return url;
  13441. each( url_params, function( key, value ) {
  13442. var value_str = (typeof value == 'object')?JSON['stringify'](value):value;
  13443. (typeof value != 'undefined' &&
  13444. value != null && encode(value_str).length > 0
  13445. ) && params.push(key + "=" + encode(value_str));
  13446. } );
  13447. url += "?" + params.join(PARAMSBIT);
  13448. return url;
  13449. }
  13450. /**
  13451. * UPDATER
  13452. * =======
  13453. * var timestamp = unique();
  13454. */
  13455. function updater( fun, rate ) {
  13456. var timeout
  13457. , last = 0
  13458. , runnit = function() {
  13459. if (last + rate > rnow()) {
  13460. clearTimeout(timeout);
  13461. timeout = setTimeout( runnit, rate );
  13462. }
  13463. else {
  13464. last = rnow();
  13465. fun();
  13466. }
  13467. };
  13468. return runnit;
  13469. }
  13470. /**
  13471. * GREP
  13472. * ====
  13473. * var list = grep( [1,2,3], function(item) { return item % 2 } )
  13474. */
  13475. function grep( list, fun ) {
  13476. var fin = [];
  13477. each( list || [], function(l) { fun(l) && fin.push(l) } );
  13478. return fin
  13479. }
  13480. /**
  13481. * SUPPLANT
  13482. * ========
  13483. * var text = supplant( 'Hello {name}!', { name : 'John' } )
  13484. */
  13485. function supplant( str, values ) {
  13486. return str.replace( REPL, function( _, match ) {
  13487. return values[match] || _
  13488. } );
  13489. }
  13490. /**
  13491. * timeout
  13492. * =======
  13493. * timeout( function(){}, 100 );
  13494. */
  13495. function timeout( fun, wait ) {
  13496. return setTimeout( fun, wait );
  13497. }
  13498. /**
  13499. * uuid
  13500. * ====
  13501. * var my_uuid = uuid();
  13502. */
  13503. function uuid(callback) {
  13504. var u = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,
  13505. function(c) {
  13506. var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
  13507. return v.toString(16);
  13508. });
  13509. if (callback) callback(u);
  13510. return u;
  13511. }
  13512. function isArray(arg) {
  13513. return !!arg && (Array.isArray && Array.isArray(arg) || typeof(arg.length) === "number")
  13514. }
  13515. /**
  13516. * EACH
  13517. * ====
  13518. * each( [1,2,3], function(item) { } )
  13519. */
  13520. function each( o, f) {
  13521. if ( !o || !f ) return;
  13522. if ( isArray(o) )
  13523. for ( var i = 0, l = o.length; i < l; )
  13524. f.call( o[i], o[i], i++ );
  13525. else
  13526. for ( var i in o )
  13527. o.hasOwnProperty &&
  13528. o.hasOwnProperty(i) &&
  13529. f.call( o[i], i, o[i] );
  13530. }
  13531. /**
  13532. * MAP
  13533. * ===
  13534. * var list = map( [1,2,3], function(item) { return item + 1 } )
  13535. */
  13536. function map( list, fun ) {
  13537. var fin = [];
  13538. each( list || [], function( k, v ) { fin.push(fun( k, v )) } );
  13539. return fin;
  13540. }
  13541. /**
  13542. * ENCODE
  13543. * ======
  13544. * var encoded_data = encode('path');
  13545. */
  13546. function encode(path) { return encodeURIComponent(path) }
  13547. /**
  13548. * Generate Subscription Channel List
  13549. * ==================================
  13550. * generate_channel_list(channels_object);
  13551. */
  13552. function generate_channel_list(channels, nopresence) {
  13553. var list = [];
  13554. each( channels, function( channel, status ) {
  13555. if (nopresence) {
  13556. if(channel.search('-pnpres') < 0) {
  13557. if (status.subscribed) list.push(channel);
  13558. }
  13559. } else {
  13560. if (status.subscribed) list.push(channel);
  13561. }
  13562. });
  13563. return list.sort();
  13564. }
  13565. // PUBNUB READY TO CONNECT
  13566. function ready() { timeout( function() {
  13567. if (READY) return;
  13568. READY = 1;
  13569. each( READY_BUFFER, function(connect) { connect() } );
  13570. }, SECOND ); }
  13571. function PNmessage(args) {
  13572. msg = args || {'apns' : {}},
  13573. msg['getPubnubMessage'] = function() {
  13574. var m = {};
  13575. if (Object.keys(msg['apns']).length) {
  13576. m['pn_apns'] = {
  13577. 'aps' : {
  13578. 'alert' : msg['apns']['alert'] ,
  13579. 'badge' : msg['apns']['badge']
  13580. }
  13581. }
  13582. for (var k in msg['apns']) {
  13583. m['pn_apns'][k] = msg['apns'][k];
  13584. }
  13585. var exclude1 = ['badge','alert'];
  13586. for (var k in exclude1) {
  13587. //console.log(exclude[k]);
  13588. delete m['pn_apns'][exclude1[k]];
  13589. }
  13590. }
  13591. if (msg['gcm']) {
  13592. m['pn_gcm'] = {
  13593. 'data' : msg['gcm']
  13594. }
  13595. }
  13596. for (var k in msg) {
  13597. m[k] = msg[k];
  13598. }
  13599. var exclude = ['apns','gcm','publish', 'channel','callback','error'];
  13600. for (var k in exclude) {
  13601. delete m[exclude[k]];
  13602. }
  13603. return m;
  13604. };
  13605. msg['publish'] = function() {
  13606. var m = msg.getPubnubMessage();
  13607. if (msg['pubnub'] && msg['channel']) {
  13608. msg['pubnub'].publish({
  13609. 'message' : m,
  13610. 'channel' : msg['channel'],
  13611. 'callback' : msg['callback'],
  13612. 'error' : msg['error']
  13613. })
  13614. }
  13615. };
  13616. return msg;
  13617. }
  13618. function PN_API(setup) {
  13619. var SUB_WINDOWING = +setup['windowing'] || DEF_WINDOWING
  13620. , SUB_TIMEOUT = (+setup['timeout'] || DEF_SUB_TIMEOUT) * SECOND
  13621. , KEEPALIVE = (+setup['keepalive'] || DEF_KEEPALIVE) * SECOND
  13622. , NOLEAVE = setup['noleave'] || 0
  13623. , PUBLISH_KEY = setup['publish_key'] || 'demo'
  13624. , SUBSCRIBE_KEY = setup['subscribe_key'] || 'demo'
  13625. , AUTH_KEY = setup['auth_key'] || ''
  13626. , SECRET_KEY = setup['secret_key'] || ''
  13627. , hmac_SHA256 = setup['hmac_SHA256']
  13628. , SSL = setup['ssl'] ? 's' : ''
  13629. , ORIGIN = 'http'+SSL+'://'+(setup['origin']||'pubsub.pubnub.com')
  13630. , STD_ORIGIN = nextorigin(ORIGIN)
  13631. , SUB_ORIGIN = nextorigin(ORIGIN)
  13632. , CONNECT = function(){}
  13633. , PUB_QUEUE = []
  13634. , TIME_DRIFT = 0
  13635. , SUB_CALLBACK = 0
  13636. , SUB_CHANNEL = 0
  13637. , SUB_RECEIVER = 0
  13638. , SUB_RESTORE = setup['restore'] || 0
  13639. , SUB_BUFF_WAIT = 0
  13640. , TIMETOKEN = 0
  13641. , RESUMED = false
  13642. , CHANNELS = {}
  13643. , STATE = {}
  13644. , PRESENCE_HB_TIMEOUT = null
  13645. , PRESENCE_HB = validate_presence_heartbeat(setup['heartbeat'] || setup['pnexpires'] || 0, setup['error'])
  13646. , PRESENCE_HB_INTERVAL = setup['heartbeat_interval'] || PRESENCE_HB - 3
  13647. , PRESENCE_HB_RUNNING = false
  13648. , NO_WAIT_FOR_PENDING = setup['no_wait_for_pending']
  13649. , COMPATIBLE_35 = setup['compatible_3.5'] || false
  13650. , xdr = setup['xdr']
  13651. , params = setup['params'] || {}
  13652. , error = setup['error'] || function() {}
  13653. , _is_online = setup['_is_online'] || function() { return 1 }
  13654. , jsonp_cb = setup['jsonp_cb'] || function() { return 0 }
  13655. , db = setup['db'] || {'get': function(){}, 'set': function(){}}
  13656. , CIPHER_KEY = setup['cipher_key']
  13657. , UUID = setup['uuid'] || ( db && db['get'](SUBSCRIBE_KEY+'uuid') || '');
  13658. var crypto_obj = setup['crypto_obj'] ||
  13659. {
  13660. 'encrypt' : function(a,key){ return a},
  13661. 'decrypt' : function(b,key){return b}
  13662. };
  13663. function _get_url_params(data) {
  13664. if (!data) data = {};
  13665. each( params , function( key, value ) {
  13666. if (!(key in data)) data[key] = value;
  13667. });
  13668. return data;
  13669. }
  13670. function _object_to_key_list(o) {
  13671. var l = []
  13672. each( o , function( key, value ) {
  13673. l.push(key);
  13674. });
  13675. return l;
  13676. }
  13677. function _object_to_key_list_sorted(o) {
  13678. return _object_to_key_list(o).sort();
  13679. }
  13680. function _get_pam_sign_input_from_params(params) {
  13681. var si = "";
  13682. var l = _object_to_key_list_sorted(params);
  13683. for (var i in l) {
  13684. var k = l[i]
  13685. si += k + "=" + encode(params[k]) ;
  13686. if (i != l.length - 1) si += "&"
  13687. }
  13688. return si;
  13689. }
  13690. function validate_presence_heartbeat(heartbeat, cur_heartbeat, error) {
  13691. var err = false;
  13692. if (typeof heartbeat === 'number') {
  13693. if (heartbeat > PRESENCE_HB_THRESHOLD || heartbeat == 0)
  13694. err = false;
  13695. else
  13696. err = true;
  13697. } else if(typeof heartbeat === 'boolean'){
  13698. if (!heartbeat) {
  13699. return 0;
  13700. } else {
  13701. return PRESENCE_HB_DEFAULT;
  13702. }
  13703. } else {
  13704. err = true;
  13705. }
  13706. if (err) {
  13707. error && error("Presence Heartbeat value invalid. Valid range ( x > " + PRESENCE_HB_THRESHOLD + " or x = 0). Current Value : " + (cur_heartbeat || PRESENCE_HB_THRESHOLD));
  13708. return cur_heartbeat || PRESENCE_HB_THRESHOLD;
  13709. } else return heartbeat;
  13710. }
  13711. function encrypt(input, key) {
  13712. return crypto_obj['encrypt'](input, key || CIPHER_KEY) || input;
  13713. }
  13714. function decrypt(input, key) {
  13715. return crypto_obj['decrypt'](input, key || CIPHER_KEY) ||
  13716. crypto_obj['decrypt'](input, CIPHER_KEY) ||
  13717. input;
  13718. }
  13719. function error_common(message, callback) {
  13720. callback && callback({ 'error' : message || "error occurred"});
  13721. error && error(message);
  13722. }
  13723. function _presence_heartbeat() {
  13724. clearTimeout(PRESENCE_HB_TIMEOUT);
  13725. if (!PRESENCE_HB_INTERVAL || PRESENCE_HB_INTERVAL >= 500 || PRESENCE_HB_INTERVAL < 1 || !generate_channel_list(CHANNELS,true).length){
  13726. PRESENCE_HB_RUNNING = false;
  13727. return;
  13728. }
  13729. PRESENCE_HB_RUNNING = true;
  13730. SELF['presence_heartbeat']({
  13731. 'callback' : function(r) {
  13732. PRESENCE_HB_TIMEOUT = timeout( _presence_heartbeat, (PRESENCE_HB_INTERVAL) * SECOND );
  13733. },
  13734. 'error' : function(e) {
  13735. error && error("Presence Heartbeat unable to reach Pubnub servers." + JSON.stringify(e));
  13736. PRESENCE_HB_TIMEOUT = timeout( _presence_heartbeat, (PRESENCE_HB_INTERVAL) * SECOND );
  13737. }
  13738. });
  13739. }
  13740. function start_presence_heartbeat() {
  13741. !PRESENCE_HB_RUNNING && _presence_heartbeat();
  13742. }
  13743. function publish(next) {
  13744. if (NO_WAIT_FOR_PENDING) {
  13745. if (!PUB_QUEUE.length) return;
  13746. } else {
  13747. if (next) PUB_QUEUE.sending = 0;
  13748. if ( PUB_QUEUE.sending || !PUB_QUEUE.length ) return;
  13749. PUB_QUEUE.sending = 1;
  13750. }
  13751. xdr(PUB_QUEUE.shift());
  13752. }
  13753. function each_channel(callback) {
  13754. var count = 0;
  13755. each( generate_channel_list(CHANNELS), function(channel) {
  13756. var chan = CHANNELS[channel];
  13757. if (!chan) return;
  13758. count++;
  13759. (callback||function(){})(chan);
  13760. } );
  13761. return count;
  13762. }
  13763. function _invoke_callback(response, callback, err) {
  13764. if (typeof response == 'object') {
  13765. if (response['error'] && response['message'] && response['payload']) {
  13766. err({'message' : response['message'], 'payload' : response['payload']});
  13767. return;
  13768. }
  13769. if (response['payload']) {
  13770. callback(response['payload']);
  13771. return;
  13772. }
  13773. }
  13774. callback(response);
  13775. }
  13776. function _invoke_error(response,err) {
  13777. if (typeof response == 'object' && response['error'] &&
  13778. response['message'] && response['payload']) {
  13779. err({'message' : response['message'], 'payload' : response['payload']});
  13780. } else err(response);
  13781. }
  13782. // Announce Leave Event
  13783. var SELF = {
  13784. 'LEAVE' : function( channel, blocking, callback, error ) {
  13785. var data = { 'uuid' : UUID, 'auth' : AUTH_KEY }
  13786. , origin = nextorigin(ORIGIN)
  13787. , callback = callback || function(){}
  13788. , err = error || function(){}
  13789. , jsonp = jsonp_cb();
  13790. // Prevent Leaving a Presence Channel
  13791. if (channel.indexOf(PRESENCE_SUFFIX) > 0) return true;
  13792. if (COMPATIBLE_35) {
  13793. if (!SSL) return false;
  13794. if (jsonp == '0') return false;
  13795. }
  13796. if (NOLEAVE) return false;
  13797. if (jsonp != '0') data['callback'] = jsonp;
  13798. xdr({
  13799. blocking : blocking || SSL,
  13800. timeout : 2000,
  13801. callback : jsonp,
  13802. data : _get_url_params(data),
  13803. success : function(response) {
  13804. _invoke_callback(response, callback, err);
  13805. },
  13806. fail : function(response) {
  13807. _invoke_error(response, err);
  13808. },
  13809. url : [
  13810. origin, 'v2', 'presence', 'sub_key',
  13811. SUBSCRIBE_KEY, 'channel', encode(channel), 'leave'
  13812. ]
  13813. });
  13814. return true;
  13815. },
  13816. 'set_resumed' : function(resumed) {
  13817. RESUMED = resumed;
  13818. },
  13819. 'get_cipher_key' : function() {
  13820. return CIPHER_KEY;
  13821. },
  13822. 'set_cipher_key' : function(key) {
  13823. CIPHER_KEY = key;
  13824. },
  13825. 'raw_encrypt' : function(input, key) {
  13826. return encrypt(input, key);
  13827. },
  13828. 'raw_decrypt' : function(input, key) {
  13829. return decrypt(input, key);
  13830. },
  13831. 'get_heartbeat' : function() {
  13832. return PRESENCE_HB;
  13833. },
  13834. 'set_heartbeat' : function(heartbeat) {
  13835. PRESENCE_HB = validate_presence_heartbeat(heartbeat, PRESENCE_HB_INTERVAL, error);
  13836. PRESENCE_HB_INTERVAL = (PRESENCE_HB - 3 >= 1)?PRESENCE_HB - 3:1;
  13837. CONNECT();
  13838. _presence_heartbeat();
  13839. },
  13840. 'get_heartbeat_interval' : function() {
  13841. return PRESENCE_HB_INTERVAL;
  13842. },
  13843. 'set_heartbeat_interval' : function(heartbeat_interval) {
  13844. PRESENCE_HB_INTERVAL = heartbeat_interval;
  13845. _presence_heartbeat();
  13846. },
  13847. 'get_version' : function() {
  13848. return SDK_VER;
  13849. },
  13850. 'getGcmMessageObject' : function(obj) {
  13851. return {
  13852. 'data' : obj
  13853. }
  13854. },
  13855. 'getApnsMessageObject' : function(obj) {
  13856. var x = {
  13857. 'aps' : { 'badge' : 1, 'alert' : ''}
  13858. }
  13859. for (k in obj) {
  13860. k[x] = obj[k];
  13861. }
  13862. return x;
  13863. },
  13864. 'newPnMessage' : function() {
  13865. var x = {};
  13866. if (gcm) x['pn_gcm'] = gcm;
  13867. if (apns) x['pn_apns'] = apns;
  13868. for ( k in n ) {
  13869. x[k] = n[k];
  13870. }
  13871. return x;
  13872. },
  13873. '_add_param' : function(key,val) {
  13874. params[key] = val;
  13875. },
  13876. /*
  13877. PUBNUB.history({
  13878. channel : 'my_chat_channel',
  13879. limit : 100,
  13880. callback : function(history) { }
  13881. });
  13882. */
  13883. 'history' : function( args, callback ) {
  13884. var callback = args['callback'] || callback
  13885. , count = args['count'] || args['limit'] || 100
  13886. , reverse = args['reverse'] || "false"
  13887. , err = args['error'] || function(){}
  13888. , auth_key = args['auth_key'] || AUTH_KEY
  13889. , cipher_key = args['cipher_key']
  13890. , channel = args['channel']
  13891. , start = args['start']
  13892. , end = args['end']
  13893. , include_token = args['include_token']
  13894. , params = {}
  13895. , jsonp = jsonp_cb();
  13896. // Make sure we have a Channel
  13897. if (!channel) return error('Missing Channel');
  13898. if (!callback) return error('Missing Callback');
  13899. if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
  13900. params['stringtoken'] = 'true';
  13901. params['count'] = count;
  13902. params['reverse'] = reverse;
  13903. params['auth'] = auth_key;
  13904. if (jsonp) params['callback'] = jsonp;
  13905. if (start) params['start'] = start;
  13906. if (end) params['end'] = end;
  13907. if (include_token) params['include_token'] = 'true';
  13908. // Send Message
  13909. xdr({
  13910. callback : jsonp,
  13911. data : _get_url_params(params),
  13912. success : function(response) {
  13913. if (typeof response == 'object' && response['error']) {
  13914. err({'message' : response['message'], 'payload' : response['payload']});
  13915. return;
  13916. }
  13917. var messages = response[0];
  13918. var decrypted_messages = [];
  13919. for (var a = 0; a < messages.length; a++) {
  13920. var new_message = decrypt(messages[a],cipher_key);
  13921. try {
  13922. decrypted_messages['push'](JSON['parse'](new_message));
  13923. } catch (e) {
  13924. decrypted_messages['push']((new_message));
  13925. }
  13926. }
  13927. callback([decrypted_messages, response[1], response[2]]);
  13928. },
  13929. fail : function(response) {
  13930. _invoke_error(response, err);
  13931. },
  13932. url : [
  13933. STD_ORIGIN, 'v2', 'history', 'sub-key',
  13934. SUBSCRIBE_KEY, 'channel', encode(channel)
  13935. ]
  13936. });
  13937. },
  13938. /*
  13939. PUBNUB.replay({
  13940. source : 'my_channel',
  13941. destination : 'new_channel'
  13942. });
  13943. */
  13944. 'replay' : function(args, callback) {
  13945. var callback = callback || args['callback'] || function(){}
  13946. , auth_key = args['auth_key'] || AUTH_KEY
  13947. , source = args['source']
  13948. , destination = args['destination']
  13949. , stop = args['stop']
  13950. , start = args['start']
  13951. , end = args['end']
  13952. , reverse = args['reverse']
  13953. , limit = args['limit']
  13954. , jsonp = jsonp_cb()
  13955. , data = {}
  13956. , url;
  13957. // Check User Input
  13958. if (!source) return error('Missing Source Channel');
  13959. if (!destination) return error('Missing Destination Channel');
  13960. if (!PUBLISH_KEY) return error('Missing Publish Key');
  13961. if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
  13962. // Setup URL Params
  13963. if (jsonp != '0') data['callback'] = jsonp;
  13964. if (stop) data['stop'] = 'all';
  13965. if (reverse) data['reverse'] = 'true';
  13966. if (start) data['start'] = start;
  13967. if (end) data['end'] = end;
  13968. if (limit) data['count'] = limit;
  13969. data['auth'] = auth_key;
  13970. // Compose URL Parts
  13971. url = [
  13972. STD_ORIGIN, 'v1', 'replay',
  13973. PUBLISH_KEY, SUBSCRIBE_KEY,
  13974. source, destination
  13975. ];
  13976. // Start (or Stop) Replay!
  13977. xdr({
  13978. callback : jsonp,
  13979. success : function(response) {
  13980. _invoke_callback(response, callback, err);
  13981. },
  13982. fail : function() { callback([ 0, 'Disconnected' ]) },
  13983. url : url,
  13984. data : _get_url_params(data)
  13985. });
  13986. },
  13987. /*
  13988. PUBNUB.auth('AJFLKAJSDKLA');
  13989. */
  13990. 'auth' : function(auth) {
  13991. AUTH_KEY = auth;
  13992. CONNECT();
  13993. },
  13994. /*
  13995. PUBNUB.time(function(time){ });
  13996. */
  13997. 'time' : function(callback) {
  13998. var jsonp = jsonp_cb();
  13999. xdr({
  14000. callback : jsonp,
  14001. data : _get_url_params({ 'uuid' : UUID, 'auth' : AUTH_KEY }),
  14002. timeout : SECOND * 5,
  14003. url : [STD_ORIGIN, 'time', jsonp],
  14004. success : function(response) { callback(response[0]) },
  14005. fail : function() { callback(0) }
  14006. });
  14007. },
  14008. /*
  14009. PUBNUB.publish({
  14010. channel : 'my_chat_channel',
  14011. message : 'hello!'
  14012. });
  14013. */
  14014. 'publish' : function( args, callback ) {
  14015. var msg = args['message'];
  14016. if (!msg) return error('Missing Message');
  14017. var callback = callback || args['callback'] || msg['callback'] || function(){}
  14018. , channel = args['channel'] || msg['channel']
  14019. , auth_key = args['auth_key'] || AUTH_KEY
  14020. , cipher_key = args['cipher_key']
  14021. , err = args['error'] || msg['error'] || function() {}
  14022. , post = args['post'] || false
  14023. , store = ('store_in_history' in args) ? args['store_in_history']: true
  14024. , jsonp = jsonp_cb()
  14025. , add_msg = 'push'
  14026. , url;
  14027. if (args['prepend']) add_msg = 'unshift'
  14028. if (!channel) return error('Missing Channel');
  14029. if (!PUBLISH_KEY) return error('Missing Publish Key');
  14030. if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
  14031. if (msg['getPubnubMessage']) {
  14032. msg = msg['getPubnubMessage']();
  14033. }
  14034. // If trying to send Object
  14035. msg = JSON['stringify'](encrypt(msg, cipher_key));
  14036. // Create URL
  14037. url = [
  14038. STD_ORIGIN, 'publish',
  14039. PUBLISH_KEY, SUBSCRIBE_KEY,
  14040. 0, encode(channel),
  14041. jsonp, encode(msg)
  14042. ];
  14043. params = { 'uuid' : UUID, 'auth' : auth_key }
  14044. if (!store) params['store'] ="0"
  14045. // Queue Message Send
  14046. PUB_QUEUE[add_msg]({
  14047. callback : jsonp,
  14048. timeout : SECOND * 5,
  14049. url : url,
  14050. data : _get_url_params(params),
  14051. fail : function(response){
  14052. _invoke_error(response, err);
  14053. publish(1);
  14054. },
  14055. success : function(response) {
  14056. _invoke_callback(response, callback, err);
  14057. publish(1);
  14058. },
  14059. mode : (post)?'POST':'GET'
  14060. });
  14061. // Send Message
  14062. publish();
  14063. },
  14064. /*
  14065. PUBNUB.unsubscribe({ channel : 'my_chat' });
  14066. */
  14067. 'unsubscribe' : function(args, callback) {
  14068. var channel = args['channel']
  14069. , callback = callback || args['callback'] || function(){}
  14070. , err = args['error'] || function(){};
  14071. TIMETOKEN = 0;
  14072. //SUB_RESTORE = 1; REVISIT !!!!
  14073. // Prepare Channel(s)
  14074. channel = map( (
  14075. channel.join ? channel.join(',') : ''+channel
  14076. ).split(','), function(channel) {
  14077. if (!CHANNELS[channel]) return;
  14078. return channel + ',' + channel + PRESENCE_SUFFIX;
  14079. } ).join(',');
  14080. // Iterate over Channels
  14081. each( channel.split(','), function(channel) {
  14082. var CB_CALLED = true;
  14083. if (!channel) return;
  14084. if (READY) {
  14085. CB_CALLED = SELF['LEAVE']( channel, 0 , callback, err);
  14086. }
  14087. if (!CB_CALLED) callback({action : "leave"});
  14088. CHANNELS[channel] = 0;
  14089. if (channel in STATE) delete STATE[channel];
  14090. } );
  14091. // Reset Connection if Count Less
  14092. CONNECT();
  14093. },
  14094. /*
  14095. PUBNUB.subscribe({
  14096. channel : 'my_chat'
  14097. callback : function(message) { }
  14098. });
  14099. */
  14100. 'subscribe' : function( args, callback ) {
  14101. var channel = args['channel']
  14102. , callback = callback || args['callback']
  14103. , callback = callback || args['message']
  14104. , auth_key = args['auth_key'] || AUTH_KEY
  14105. , connect = args['connect'] || function(){}
  14106. , reconnect = args['reconnect'] || function(){}
  14107. , disconnect = args['disconnect'] || function(){}
  14108. , errcb = args['error'] || function(){}
  14109. , idlecb = args['idle'] || function(){}
  14110. , presence = args['presence'] || 0
  14111. , noheresync = args['noheresync'] || 0
  14112. , backfill = args['backfill'] || 0
  14113. , timetoken = args['timetoken'] || 0
  14114. , sub_timeout = args['timeout'] || SUB_TIMEOUT
  14115. , windowing = args['windowing'] || SUB_WINDOWING
  14116. , state = args['state']
  14117. , heartbeat = args['heartbeat'] || args['pnexpires']
  14118. , restore = args['restore'] || SUB_RESTORE;
  14119. // Restore Enabled?
  14120. SUB_RESTORE = restore;
  14121. // Always Reset the TT
  14122. TIMETOKEN = timetoken;
  14123. // Make sure we have a Channel
  14124. if (!channel) return error('Missing Channel');
  14125. if (!callback) return error('Missing Callback');
  14126. if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
  14127. if (heartbeat || heartbeat === 0) {
  14128. SELF['set_heartbeat'](heartbeat);
  14129. }
  14130. // Setup Channel(s)
  14131. each( (channel.join ? channel.join(',') : ''+channel).split(','),
  14132. function(channel) {
  14133. var settings = CHANNELS[channel] || {};
  14134. // Store Channel State
  14135. CHANNELS[SUB_CHANNEL = channel] = {
  14136. name : channel,
  14137. connected : settings.connected,
  14138. disconnected : settings.disconnected,
  14139. subscribed : 1,
  14140. callback : SUB_CALLBACK = callback,
  14141. 'cipher_key' : args['cipher_key'],
  14142. connect : connect,
  14143. disconnect : disconnect,
  14144. reconnect : reconnect
  14145. };
  14146. if (state) {
  14147. if (channel in state) {
  14148. STATE[channel] = state[channel];
  14149. } else {
  14150. STATE[channel] = state;
  14151. }
  14152. }
  14153. // Presence Enabled?
  14154. if (!presence) return;
  14155. // Subscribe Presence Channel
  14156. SELF['subscribe']({
  14157. 'channel' : channel + PRESENCE_SUFFIX,
  14158. 'callback' : presence,
  14159. 'restore' : restore
  14160. });
  14161. // Presence Subscribed?
  14162. if (settings.subscribed) return;
  14163. // See Who's Here Now?
  14164. if (noheresync) return;
  14165. SELF['here_now']({
  14166. 'channel' : channel,
  14167. 'callback' : function(here) {
  14168. each( 'uuids' in here ? here['uuids'] : [],
  14169. function(uid) { presence( {
  14170. 'action' : 'join',
  14171. 'uuid' : uid,
  14172. 'timestamp' : Math.floor(rnow() / 1000),
  14173. 'occupancy' : here['occupancy'] || 1
  14174. }, here, channel ); } );
  14175. }
  14176. });
  14177. } );
  14178. // Test Network Connection
  14179. function _test_connection(success) {
  14180. if (success) {
  14181. // Begin Next Socket Connection
  14182. timeout( CONNECT, SECOND );
  14183. }
  14184. else {
  14185. // New Origin on Failed Connection
  14186. STD_ORIGIN = nextorigin( ORIGIN, 1 );
  14187. SUB_ORIGIN = nextorigin( ORIGIN, 1 );
  14188. // Re-test Connection
  14189. timeout( function() {
  14190. SELF['time'](_test_connection);
  14191. }, SECOND );
  14192. }
  14193. // Disconnect & Reconnect
  14194. each_channel(function(channel){
  14195. // Reconnect
  14196. if (success && channel.disconnected) {
  14197. channel.disconnected = 0;
  14198. return channel.reconnect(channel.name);
  14199. }
  14200. // Disconnect
  14201. if (!success && !channel.disconnected) {
  14202. channel.disconnected = 1;
  14203. channel.disconnect(channel.name);
  14204. }
  14205. });
  14206. }
  14207. // Evented Subscribe
  14208. function _connect() {
  14209. var jsonp = jsonp_cb()
  14210. , channels = generate_channel_list(CHANNELS).join(',');
  14211. // Stop Connection
  14212. if (!channels) return;
  14213. // Connect to PubNub Subscribe Servers
  14214. _reset_offline();
  14215. var data = _get_url_params({ 'uuid' : UUID, 'auth' : auth_key });
  14216. var st = JSON.stringify(STATE);
  14217. if (st.length > 2) data['state'] = JSON.stringify(STATE);
  14218. if (PRESENCE_HB) data['heartbeat'] = PRESENCE_HB;
  14219. start_presence_heartbeat();
  14220. SUB_RECEIVER = xdr({
  14221. timeout : sub_timeout,
  14222. callback : jsonp,
  14223. fail : function(response) {
  14224. _invoke_error(response, errcb);
  14225. //SUB_RECEIVER = null;
  14226. SELF['time'](_test_connection);
  14227. },
  14228. data : _get_url_params(data),
  14229. url : [
  14230. SUB_ORIGIN, 'subscribe',
  14231. SUBSCRIBE_KEY, encode(channels),
  14232. jsonp, TIMETOKEN
  14233. ],
  14234. success : function(messages) {
  14235. //SUB_RECEIVER = null;
  14236. // Check for Errors
  14237. if (!messages || (
  14238. typeof messages == 'object' &&
  14239. 'error' in messages &&
  14240. messages['error']
  14241. )) {
  14242. errcb(messages['error']);
  14243. return timeout( CONNECT, SECOND );
  14244. }
  14245. // User Idle Callback
  14246. idlecb(messages[1]);
  14247. // Restore Previous Connection Point if Needed
  14248. TIMETOKEN = !TIMETOKEN &&
  14249. SUB_RESTORE &&
  14250. db['get'](SUBSCRIBE_KEY) || messages[1];
  14251. // Connect
  14252. each_channel(function(channel){
  14253. if (channel.connected) return;
  14254. channel.connected = 1;
  14255. channel.connect(channel.name);
  14256. });
  14257. if (RESUMED && !SUB_RESTORE) {
  14258. TIMETOKEN = 0;
  14259. RESUMED = false;
  14260. // Update Saved Timetoken
  14261. db['set']( SUBSCRIBE_KEY, 0 );
  14262. timeout( _connect, windowing );
  14263. return;
  14264. }
  14265. // Invoke Memory Catchup and Receive Up to 100
  14266. // Previous Messages from the Queue.
  14267. if (backfill) {
  14268. TIMETOKEN = 10000;
  14269. backfill = 0;
  14270. }
  14271. // Update Saved Timetoken
  14272. db['set']( SUBSCRIBE_KEY, messages[1] );
  14273. // Route Channel <---> Callback for Message
  14274. var next_callback = (function() {
  14275. var channels = (messages.length>2?messages[2]:map(
  14276. generate_channel_list(CHANNELS), function(chan) { return map(
  14277. Array(messages[0].length)
  14278. .join(',').split(','),
  14279. function() { return chan; }
  14280. ) }).join(','));
  14281. var list = channels.split(',');
  14282. return function() {
  14283. var channel = list.shift()||SUB_CHANNEL;
  14284. return [
  14285. (CHANNELS[channel]||{})
  14286. .callback||SUB_CALLBACK,
  14287. channel.split(PRESENCE_SUFFIX)[0]
  14288. ];
  14289. };
  14290. })();
  14291. var latency = detect_latency(+messages[1]);
  14292. each( messages[0], function(msg) {
  14293. var next = next_callback();
  14294. var decrypted_msg = decrypt(msg,
  14295. (CHANNELS[next[1]])?CHANNELS[next[1]]['cipher_key']:null);
  14296. next[0]( decrypted_msg, messages, next[1], latency);
  14297. });
  14298. timeout( _connect, windowing );
  14299. }
  14300. });
  14301. }
  14302. CONNECT = function() {
  14303. _reset_offline();
  14304. timeout( _connect, windowing );
  14305. };
  14306. // Reduce Status Flicker
  14307. if (!READY) return READY_BUFFER.push(CONNECT);
  14308. // Connect Now
  14309. CONNECT();
  14310. },
  14311. /*
  14312. PUBNUB.here_now({ channel : 'my_chat', callback : fun });
  14313. */
  14314. 'here_now' : function( args, callback ) {
  14315. var callback = args['callback'] || callback
  14316. , err = args['error'] || function(){}
  14317. , auth_key = args['auth_key'] || AUTH_KEY
  14318. , channel = args['channel']
  14319. , jsonp = jsonp_cb()
  14320. , uuids = ('uuids' in args) ? args['uuids'] : true
  14321. , state = args['state']
  14322. , data = { 'uuid' : UUID, 'auth' : auth_key };
  14323. if (!uuids) data['disable_uuids'] = 1;
  14324. if (state) data['state'] = 1;
  14325. // Make sure we have a Channel
  14326. if (!callback) return error('Missing Callback');
  14327. if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
  14328. var url = [
  14329. STD_ORIGIN, 'v2', 'presence',
  14330. 'sub_key', SUBSCRIBE_KEY
  14331. ];
  14332. channel && url.push('channel') && url.push(encode(channel));
  14333. if (jsonp != '0') { data['callback'] = jsonp; }
  14334. xdr({
  14335. callback : jsonp,
  14336. data : _get_url_params(data),
  14337. success : function(response) {
  14338. _invoke_callback(response, callback, err);
  14339. },
  14340. fail : function(response) {
  14341. _invoke_error(response, err);
  14342. },
  14343. url : url
  14344. });
  14345. },
  14346. /*
  14347. PUBNUB.current_channels_by_uuid({ channel : 'my_chat', callback : fun });
  14348. */
  14349. 'where_now' : function( args, callback ) {
  14350. var callback = args['callback'] || callback
  14351. , err = args['error'] || function(){}
  14352. , auth_key = args['auth_key'] || AUTH_KEY
  14353. , jsonp = jsonp_cb()
  14354. , uuid = args['uuid'] || UUID
  14355. , data = { 'auth' : auth_key };
  14356. // Make sure we have a Channel
  14357. if (!callback) return error('Missing Callback');
  14358. if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
  14359. if (jsonp != '0') { data['callback'] = jsonp; }
  14360. xdr({
  14361. callback : jsonp,
  14362. data : _get_url_params(data),
  14363. success : function(response) {
  14364. _invoke_callback(response, callback, err);
  14365. },
  14366. fail : function(response) {
  14367. _invoke_error(response, err);
  14368. },
  14369. url : [
  14370. STD_ORIGIN, 'v2', 'presence',
  14371. 'sub_key', SUBSCRIBE_KEY,
  14372. 'uuid', encode(uuid)
  14373. ]
  14374. });
  14375. },
  14376. 'state' : function(args, callback) {
  14377. var callback = args['callback'] || callback || function(r) {}
  14378. , err = args['error'] || function(){}
  14379. , auth_key = args['auth_key'] || AUTH_KEY
  14380. , jsonp = jsonp_cb()
  14381. , state = args['state']
  14382. , uuid = args['uuid'] || UUID
  14383. , channel = args['channel']
  14384. , url
  14385. , data = _get_url_params({ 'auth' : auth_key });
  14386. // Make sure we have a Channel
  14387. if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
  14388. if (!uuid) return error('Missing UUID');
  14389. if (!channel) return error('Missing Channel');
  14390. if (jsonp != '0') { data['callback'] = jsonp; }
  14391. if (CHANNELS[channel] && CHANNELS[channel].subscribed && state) STATE[channel] = state;
  14392. data['state'] = JSON.stringify(state);
  14393. if (state) {
  14394. url = [
  14395. STD_ORIGIN, 'v2', 'presence',
  14396. 'sub-key', SUBSCRIBE_KEY,
  14397. 'channel', encode(channel),
  14398. 'uuid', uuid, 'data'
  14399. ]
  14400. } else {
  14401. url = [
  14402. STD_ORIGIN, 'v2', 'presence',
  14403. 'sub-key', SUBSCRIBE_KEY,
  14404. 'channel', encode(channel),
  14405. 'uuid', encode(uuid)
  14406. ]
  14407. }
  14408. xdr({
  14409. callback : jsonp,
  14410. data : _get_url_params(data),
  14411. success : function(response) {
  14412. _invoke_callback(response, callback, err);
  14413. },
  14414. fail : function(response) {
  14415. _invoke_error(response, err);
  14416. },
  14417. url : url
  14418. });
  14419. },
  14420. /*
  14421. PUBNUB.grant({
  14422. channel : 'my_chat',
  14423. callback : fun,
  14424. error : fun,
  14425. ttl : 24 * 60, // Minutes
  14426. read : true,
  14427. write : true,
  14428. auth_key : '3y8uiajdklytowsj'
  14429. });
  14430. */
  14431. 'grant' : function( args, callback ) {
  14432. var callback = args['callback'] || callback
  14433. , err = args['error'] || function(){}
  14434. , channel = args['channel']
  14435. , jsonp = jsonp_cb()
  14436. , ttl = args['ttl']
  14437. , r = (args['read'] )?"1":"0"
  14438. , w = (args['write'])?"1":"0"
  14439. , auth_key = args['auth_key'];
  14440. if (!callback) return error('Missing Callback');
  14441. if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
  14442. if (!PUBLISH_KEY) return error('Missing Publish Key');
  14443. if (!SECRET_KEY) return error('Missing Secret Key');
  14444. var timestamp = Math.floor(new Date().getTime() / 1000)
  14445. , sign_input = SUBSCRIBE_KEY + "\n" + PUBLISH_KEY + "\n"
  14446. + "grant" + "\n";
  14447. var data = {
  14448. 'w' : w,
  14449. 'r' : r,
  14450. 'timestamp' : timestamp
  14451. };
  14452. if (channel != 'undefined' && channel != null && channel.length > 0) data['channel'] = channel;
  14453. if (jsonp != '0') { data['callback'] = jsonp; }
  14454. if (ttl || ttl === 0) data['ttl'] = ttl;
  14455. if (auth_key) data['auth'] = auth_key;
  14456. data = _get_url_params(data)
  14457. if (!auth_key) delete data['auth'];
  14458. sign_input += _get_pam_sign_input_from_params(data);
  14459. var signature = hmac_SHA256( sign_input, SECRET_KEY );
  14460. signature = signature.replace( /\+/g, "-" );
  14461. signature = signature.replace( /\//g, "_" );
  14462. data['signature'] = signature;
  14463. xdr({
  14464. callback : jsonp,
  14465. data : data,
  14466. success : function(response) {
  14467. _invoke_callback(response, callback, err);
  14468. },
  14469. fail : function(response) {
  14470. _invoke_error(response, err);
  14471. },
  14472. url : [
  14473. STD_ORIGIN, 'v1', 'auth', 'grant' ,
  14474. 'sub-key', SUBSCRIBE_KEY
  14475. ]
  14476. });
  14477. },
  14478. /*
  14479. PUBNUB.audit({
  14480. channel : 'my_chat',
  14481. callback : fun,
  14482. error : fun,
  14483. read : true,
  14484. write : true,
  14485. auth_key : '3y8uiajdklytowsj'
  14486. });
  14487. */
  14488. 'audit' : function( args, callback ) {
  14489. var callback = args['callback'] || callback
  14490. , err = args['error'] || function(){}
  14491. , channel = args['channel']
  14492. , auth_key = args['auth_key']
  14493. , jsonp = jsonp_cb();
  14494. // Make sure we have a Channel
  14495. if (!callback) return error('Missing Callback');
  14496. if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
  14497. if (!PUBLISH_KEY) return error('Missing Publish Key');
  14498. if (!SECRET_KEY) return error('Missing Secret Key');
  14499. var timestamp = Math.floor(new Date().getTime() / 1000)
  14500. , sign_input = SUBSCRIBE_KEY + "\n"
  14501. + PUBLISH_KEY + "\n"
  14502. + "audit" + "\n";
  14503. var data = {'timestamp' : timestamp };
  14504. if (jsonp != '0') { data['callback'] = jsonp; }
  14505. if (channel != 'undefined' && channel != null && channel.length > 0) data['channel'] = channel;
  14506. if (auth_key) data['auth'] = auth_key;
  14507. data = _get_url_params(data)
  14508. if (!auth_key) delete data['auth'];
  14509. sign_input += _get_pam_sign_input_from_params(data);
  14510. var signature = hmac_SHA256( sign_input, SECRET_KEY );
  14511. signature = signature.replace( /\+/g, "-" );
  14512. signature = signature.replace( /\//g, "_" );
  14513. data['signature'] = signature;
  14514. xdr({
  14515. callback : jsonp,
  14516. data : data,
  14517. success : function(response) {
  14518. _invoke_callback(response, callback, err);
  14519. },
  14520. fail : function(response) {
  14521. _invoke_error(response, err);
  14522. },
  14523. url : [
  14524. STD_ORIGIN, 'v1', 'auth', 'audit' ,
  14525. 'sub-key', SUBSCRIBE_KEY
  14526. ]
  14527. });
  14528. },
  14529. /*
  14530. PUBNUB.revoke({
  14531. channel : 'my_chat',
  14532. callback : fun,
  14533. error : fun,
  14534. auth_key : '3y8uiajdklytowsj'
  14535. });
  14536. */
  14537. 'revoke' : function( args, callback ) {
  14538. args['read'] = false;
  14539. args['write'] = false;
  14540. SELF['grant']( args, callback );
  14541. },
  14542. 'set_uuid' : function(uuid) {
  14543. UUID = uuid;
  14544. CONNECT();
  14545. },
  14546. 'get_uuid' : function() {
  14547. return UUID;
  14548. },
  14549. 'presence_heartbeat' : function(args) {
  14550. var callback = args['callback'] || function() {}
  14551. var err = args['error'] || function() {}
  14552. var jsonp = jsonp_cb();
  14553. var data = { 'uuid' : UUID, 'auth' : AUTH_KEY };
  14554. var st = JSON['stringify'](STATE);
  14555. if (st.length > 2) data['state'] = JSON['stringify'](STATE);
  14556. if (PRESENCE_HB > 0 && PRESENCE_HB < 320) data['heartbeat'] = PRESENCE_HB;
  14557. if (jsonp != '0') { data['callback'] = jsonp; }
  14558. xdr({
  14559. callback : jsonp,
  14560. data : _get_url_params(data),
  14561. timeout : SECOND * 5,
  14562. url : [
  14563. STD_ORIGIN, 'v2', 'presence',
  14564. 'sub-key', SUBSCRIBE_KEY,
  14565. 'channel' , encode(generate_channel_list(CHANNELS, true)['join'](',')),
  14566. 'heartbeat'
  14567. ],
  14568. success : function(response) {
  14569. _invoke_callback(response, callback, err);
  14570. },
  14571. fail : function(response) { _invoke_error(response, err); }
  14572. });
  14573. },
  14574. // Expose PUBNUB Functions
  14575. 'xdr' : xdr,
  14576. 'ready' : ready,
  14577. 'db' : db,
  14578. 'uuid' : uuid,
  14579. 'map' : map,
  14580. 'each' : each,
  14581. 'each-channel' : each_channel,
  14582. 'grep' : grep,
  14583. 'offline' : function(){_reset_offline(1, { "message":"Offline. Please check your network settings." })},
  14584. 'supplant' : supplant,
  14585. 'now' : rnow,
  14586. 'unique' : unique,
  14587. 'updater' : updater
  14588. };
  14589. function _poll_online() {
  14590. _is_online() || _reset_offline( 1, {
  14591. "error" : "Offline. Please check your network settings. "
  14592. });
  14593. timeout( _poll_online, SECOND );
  14594. }
  14595. function _poll_online2() {
  14596. SELF['time'](function(success){
  14597. detect_time_detla( function(){}, success );
  14598. success || _reset_offline( 1, {
  14599. "error" : "Heartbeat failed to connect to Pubnub Servers." +
  14600. "Please check your network settings."
  14601. });
  14602. timeout( _poll_online2, KEEPALIVE );
  14603. });
  14604. }
  14605. function _reset_offline(err, msg) {
  14606. SUB_RECEIVER && SUB_RECEIVER(err, msg);
  14607. SUB_RECEIVER = null;
  14608. }
  14609. if (!UUID) UUID = SELF['uuid']();
  14610. db['set']( SUBSCRIBE_KEY + 'uuid', UUID );
  14611. timeout( _poll_online, SECOND );
  14612. timeout( _poll_online2, KEEPALIVE );
  14613. PRESENCE_HB_TIMEOUT = timeout( start_presence_heartbeat, ( PRESENCE_HB_INTERVAL - 3 ) * SECOND ) ;
  14614. // Detect Age of Message
  14615. function detect_latency(tt) {
  14616. var adjusted_time = rnow() - TIME_DRIFT;
  14617. return adjusted_time - tt / 10000;
  14618. }
  14619. detect_time_detla();
  14620. function detect_time_detla( cb, time ) {
  14621. var stime = rnow();
  14622. time && calculate(time) || SELF['time'](calculate);
  14623. function calculate(time) {
  14624. if (!time) return;
  14625. var ptime = time / 10000
  14626. , latency = (rnow() - stime) / 2;
  14627. TIME_DRIFT = rnow() - (ptime + latency);
  14628. cb && cb(TIME_DRIFT);
  14629. }
  14630. }
  14631. return SELF;
  14632. }
  14633. /* ---------------------------------------------------------------------------
  14634. WAIT! - This file depends on instructions from the PUBNUB Cloud.
  14635. http://www.pubnub.com/account
  14636. --------------------------------------------------------------------------- */
  14637. /* ---------------------------------------------------------------------------
  14638. PubNub Real-time Cloud-Hosted Push API and Push Notification Client Frameworks
  14639. Copyright (c) 2011 TopMambo Inc.
  14640. http://www.pubnub.com/
  14641. http://www.pubnub.com/terms
  14642. --------------------------------------------------------------------------- */
  14643. /* ---------------------------------------------------------------------------
  14644. Permission is hereby granted, free of charge, to any person obtaining a copy
  14645. of this software and associated documentation files (the "Software"), to deal
  14646. in the Software without restriction, including without limitation the rights
  14647. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  14648. copies of the Software, and to permit persons to whom the Software is
  14649. furnished to do so, subject to the following conditions:
  14650. The above copyright notice and this permission notice shall be included in
  14651. all copies or substantial portions of the Software.
  14652. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14653. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14654. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14655. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  14656. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  14657. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  14658. THE SOFTWARE.
  14659. --------------------------------------------------------------------------- */
  14660. /**
  14661. * UTIL LOCALS
  14662. */
  14663. var NOW = 1
  14664. , http = _dereq_('http')
  14665. , https = _dereq_('https')
  14666. , keepAliveAgent = new (keepAliveIsEmbedded() ? http.Agent : _dereq_('agentkeepalive'))({
  14667. keepAlive: true,
  14668. keepAliveMsecs: 300000,
  14669. maxSockets: 5
  14670. })
  14671. , XHRTME = 310000
  14672. , DEF_TIMEOUT = 10000
  14673. , SECOND = 1000
  14674. , PNSDK = 'PubNub-JS-' + 'Nodejs' + '/' + '3.6.8'
  14675. , crypto = _dereq_('crypto')
  14676. , proxy = null
  14677. , XORIGN = 1;
  14678. function get_hmac_SHA256(data, key) {
  14679. return crypto.createHmac('sha256',
  14680. new Buffer(key, 'utf8')).update(data).digest('base64');
  14681. }
  14682. /**
  14683. * ERROR
  14684. * ===
  14685. * error('message');
  14686. */
  14687. function error(message) { console['error'](message) }
  14688. /**
  14689. * Request
  14690. * =======
  14691. * xdr({
  14692. * url : ['http://www.blah.com/url'],
  14693. * success : function(response) {},
  14694. * fail : function() {}
  14695. * });
  14696. */
  14697. function xdr( setup ) {
  14698. var request
  14699. , response
  14700. , success = setup.success || function(){}
  14701. , fail = setup.fail || function(){}
  14702. , origin = setup.origin || 'pubsub.pubnub.com'
  14703. , ssl = setup.ssl
  14704. , failed = 0
  14705. , complete = 0
  14706. , loaded = 0
  14707. , mode = setup['mode'] || 'GET'
  14708. , data = setup['data'] || {}
  14709. , xhrtme = setup.timeout || DEF_TIMEOUT
  14710. , body = ''
  14711. , finished = function() {
  14712. if (loaded) return;
  14713. loaded = 1;
  14714. clearTimeout(timer);
  14715. try { response = JSON['parse'](body); }
  14716. catch (r) { return done(1); }
  14717. success(response);
  14718. }
  14719. , done = function(failed, response) {
  14720. if (complete) return;
  14721. complete = 1;
  14722. clearTimeout(timer);
  14723. if (request) {
  14724. request.on('error', function(){});
  14725. request.on('data', function(){});
  14726. request.on('end', function(){});
  14727. request.abort && request.abort();
  14728. request = null;
  14729. }
  14730. failed && fail(response);
  14731. }
  14732. , timer = timeout( function(){done(1);} , xhrtme );
  14733. data['pnsdk'] = PNSDK;
  14734. var options = {};
  14735. var headers = {};
  14736. var payload = '';
  14737. if (mode == 'POST')
  14738. payload = decodeURIComponent(setup.url.pop());
  14739. var url = build_url( setup.url, data );
  14740. if (!ssl) ssl = (url.split('://')[0] == 'https')?true:false;
  14741. url = '/' + url.split('/').slice(3).join('/');
  14742. var origin = setup.url[0].split("//")[1]
  14743. options.hostname = proxy ? proxy.hostname : setup.url[0].split("//")[1];
  14744. options.port = proxy ? proxy.port : ssl ? 443 : 80;
  14745. options.path = proxy ? "http://" + origin + url:url;
  14746. options.headers = proxy ? { 'Host': origin }:null;
  14747. options.method = mode;
  14748. options.keepAlive= !!keepAliveAgent;
  14749. options.agent = keepAliveAgent;
  14750. options.body = payload;
  14751. _dereq_('http').globalAgent.maxSockets = Infinity;
  14752. try {
  14753. request = (ssl ? https : http)['request'](options, function(response) {
  14754. response.setEncoding('utf8');
  14755. response.on( 'error', function(){console.log('error');done(1, body || { "error" : "Network Connection Error"})});
  14756. response.on( 'abort', function(){console.log('abort');done(1, body || { "error" : "Network Connection Error"})});
  14757. response.on( 'data', function (chunk) {
  14758. if (chunk) body += chunk;
  14759. } );
  14760. response.on( 'end', function(){
  14761. var statusCode = response.statusCode;
  14762. switch(statusCode) {
  14763. case 401:
  14764. case 402:
  14765. case 403:
  14766. try {
  14767. response = JSON['parse'](body);
  14768. done(1,response);
  14769. }
  14770. catch (r) { return done(1, body); }
  14771. return;
  14772. default:
  14773. break;
  14774. }
  14775. finished();
  14776. });
  14777. });
  14778. request.timeout = xhrtme;
  14779. request.on( 'error', function() {
  14780. done( 1, {"error":"Network Connection Error"} );
  14781. } );
  14782. if (mode == 'POST') request.write(payload);
  14783. request.end();
  14784. } catch(e) {
  14785. done(0);
  14786. return xdr(setup);
  14787. }
  14788. return done;
  14789. }
  14790. /**
  14791. * LOCAL STORAGE
  14792. */
  14793. var db = (function(){
  14794. var store = {};
  14795. return {
  14796. 'get' : function(key) {
  14797. return store[key];
  14798. },
  14799. 'set' : function( key, value ) {
  14800. store[key] = value;
  14801. }
  14802. };
  14803. })();
  14804. function crypto_obj() {
  14805. var iv = "0123456789012345";
  14806. function get_padded_key(key) {
  14807. return crypto.createHash('sha256').update(key).digest("hex").slice(0,32);
  14808. }
  14809. return {
  14810. 'encrypt' : function(input, key) {
  14811. if (!key) return input;
  14812. var plain_text = JSON['stringify'](input);
  14813. var cipher = crypto.createCipheriv('aes-256-cbc', get_padded_key(key), iv);
  14814. var base_64_encrypted = cipher.update(plain_text, 'utf8', 'base64') + cipher.final('base64');
  14815. return base_64_encrypted || input;
  14816. },
  14817. 'decrypt' : function(input, key) {
  14818. if (!key) return input;
  14819. var decipher = crypto.createDecipheriv('aes-256-cbc', get_padded_key(key), iv);
  14820. try {
  14821. var decrypted = decipher.update(input, 'base64', 'utf8') + decipher.final('utf8');
  14822. } catch (e) {
  14823. return null;
  14824. }
  14825. return JSON.parse(decrypted);
  14826. }
  14827. }
  14828. }
  14829. function keepAliveIsEmbedded() {
  14830. return 'EventEmitter' in http.Agent.super_;
  14831. }
  14832. var CREATE_PUBNUB = function(setup) {
  14833. proxy = setup['proxy'];
  14834. setup['xdr'] = xdr;
  14835. setup['db'] = db;
  14836. setup['error'] = setup['error'] || error;
  14837. setup['hmac_SHA256'] = get_hmac_SHA256;
  14838. setup['crypto_obj'] = crypto_obj();
  14839. setup['params'] = {'pnsdk' : PNSDK};
  14840. if (setup['keepAlive'] === false) {
  14841. keepAliveAgent = undefined;
  14842. }
  14843. SELF = function(setup) {
  14844. return CREATE_PUBNUB(setup);
  14845. }
  14846. var PN = PN_API(setup);
  14847. for (var prop in PN) {
  14848. if (PN.hasOwnProperty(prop)) {
  14849. SELF[prop] = PN[prop];
  14850. }
  14851. }
  14852. SELF.init = SELF;
  14853. SELF.secure = SELF;
  14854. SELF.ready();
  14855. return SELF;
  14856. }
  14857. CREATE_PUBNUB.init = CREATE_PUBNUB;
  14858. CREATE_PUBNUB.unique = unique
  14859. CREATE_PUBNUB.secure = CREATE_PUBNUB;
  14860. module.exports = CREATE_PUBNUB
  14861. module.exports.PNmessage = PNmessage;
  14862. }).call(this,_dereq_("buffer").Buffer)
  14863. },{"agentkeepalive":62,"buffer":128,"crypto":132,"http":138,"https":142}],66:[function(_dereq_,module,exports){
  14864. /*
  14865. Copyright (c) 2010,2011,2012,2013 Morgan Roderick http://roderick.dk
  14866. License: MIT - http://mrgnrdrck.mit-license.org
  14867. https://github.com/mroderick/PubSubJS
  14868. */
  14869. /*jslint white:true, plusplus:true, stupid:true*/
  14870. /*global
  14871. setTimeout,
  14872. module,
  14873. exports,
  14874. define,
  14875. require,
  14876. window
  14877. */
  14878. (function(root, factory){
  14879. 'use strict';
  14880. // CommonJS
  14881. if (typeof exports === 'object' && module){
  14882. module.exports = factory();
  14883. // AMD
  14884. } else if (typeof define === 'function' && define.amd){
  14885. define(factory);
  14886. // Browser
  14887. } else {
  14888. root.PubSub = factory();
  14889. }
  14890. }( ( typeof window === 'object' && window ) || this, function(){
  14891. 'use strict';
  14892. var PubSub = {},
  14893. messages = {},
  14894. lastUid = -1;
  14895. function hasKeys(obj){
  14896. var key;
  14897. for (key in obj){
  14898. if ( obj.hasOwnProperty(key) ){
  14899. return true;
  14900. }
  14901. }
  14902. return false;
  14903. }
  14904. /**
  14905. * Returns a function that throws the passed exception, for use as argument for setTimeout
  14906. * @param { Object } ex An Error object
  14907. */
  14908. function throwException( ex ){
  14909. return function reThrowException(){
  14910. throw ex;
  14911. };
  14912. }
  14913. function callSubscriberWithDelayedExceptions( subscriber, message, data ){
  14914. try {
  14915. subscriber( message, data );
  14916. } catch( ex ){
  14917. setTimeout( throwException( ex ), 0);
  14918. }
  14919. }
  14920. function callSubscriberWithImmediateExceptions( subscriber, message, data ){
  14921. subscriber( message, data );
  14922. }
  14923. function deliverMessage( originalMessage, matchedMessage, data, immediateExceptions ){
  14924. var subscribers = messages[matchedMessage],
  14925. callSubscriber = immediateExceptions ? callSubscriberWithImmediateExceptions : callSubscriberWithDelayedExceptions,
  14926. s;
  14927. if ( !messages.hasOwnProperty( matchedMessage ) ) {
  14928. return;
  14929. }
  14930. for (s in subscribers){
  14931. if ( subscribers.hasOwnProperty(s)){
  14932. callSubscriber( subscribers[s], originalMessage, data );
  14933. }
  14934. }
  14935. }
  14936. function createDeliveryFunction( message, data, immediateExceptions ){
  14937. return function deliverNamespaced(){
  14938. var topic = String( message ),
  14939. position = topic.lastIndexOf( '.' );
  14940. // deliver the message as it is now
  14941. deliverMessage(message, message, data, immediateExceptions);
  14942. // trim the hierarchy and deliver message to each level
  14943. while( position !== -1 ){
  14944. topic = topic.substr( 0, position );
  14945. position = topic.lastIndexOf('.');
  14946. deliverMessage( message, topic, data );
  14947. }
  14948. };
  14949. }
  14950. function messageHasSubscribers( message ){
  14951. var topic = String( message ),
  14952. found = Boolean(messages.hasOwnProperty( topic ) && hasKeys(messages[topic])),
  14953. position = topic.lastIndexOf( '.' );
  14954. while ( !found && position !== -1 ){
  14955. topic = topic.substr( 0, position );
  14956. position = topic.lastIndexOf( '.' );
  14957. found = Boolean(messages.hasOwnProperty( topic ) && hasKeys(messages[topic]));
  14958. }
  14959. return found;
  14960. }
  14961. function publish( message, data, sync, immediateExceptions ){
  14962. var deliver = createDeliveryFunction( message, data, immediateExceptions ),
  14963. hasSubscribers = messageHasSubscribers( message );
  14964. if ( !hasSubscribers ){
  14965. return false;
  14966. }
  14967. if ( sync === true ){
  14968. deliver();
  14969. } else {
  14970. setTimeout( deliver, 0 );
  14971. }
  14972. return true;
  14973. }
  14974. /**
  14975. * PubSub.publish( message[, data] ) -> Boolean
  14976. * - message (String): The message to publish
  14977. * - data: The data to pass to subscribers
  14978. * Publishes the the message, passing the data to it's subscribers
  14979. **/
  14980. PubSub.publish = function( message, data ){
  14981. return publish( message, data, false, PubSub.immediateExceptions );
  14982. };
  14983. /**
  14984. * PubSub.publishSync( message[, data] ) -> Boolean
  14985. * - message (String): The message to publish
  14986. * - data: The data to pass to subscribers
  14987. * Publishes the the message synchronously, passing the data to it's subscribers
  14988. **/
  14989. PubSub.publishSync = function( message, data ){
  14990. return publish( message, data, true, PubSub.immediateExceptions );
  14991. };
  14992. /**
  14993. * PubSub.subscribe( message, func ) -> String
  14994. * - message (String): The message to subscribe to
  14995. * - func (Function): The function to call when a new message is published
  14996. * Subscribes the passed function to the passed message. Every returned token is unique and should be stored if
  14997. * you need to unsubscribe
  14998. **/
  14999. PubSub.subscribe = function( message, func ){
  15000. if ( typeof func !== 'function'){
  15001. return false;
  15002. }
  15003. // message is not registered yet
  15004. if ( !messages.hasOwnProperty( message ) ){
  15005. messages[message] = {};
  15006. }
  15007. // forcing token as String, to allow for future expansions without breaking usage
  15008. // and allow for easy use as key names for the 'messages' object
  15009. var token = 'uid_' + String(++lastUid);
  15010. messages[message][token] = func;
  15011. // return token for unsubscribing
  15012. return token;
  15013. };
  15014. /**
  15015. * PubSub.unsubscribe( tokenOrFunction ) -> String | Boolean
  15016. * - tokenOrFunction (String|Function): The token of the function to unsubscribe or func passed in on subscribe
  15017. * Unsubscribes a specific subscriber from a specific message using the unique token
  15018. * or if using Function as argument, it will remove all subscriptions with that function
  15019. **/
  15020. PubSub.unsubscribe = function( tokenOrFunction ){
  15021. var isToken = typeof tokenOrFunction === 'string',
  15022. result = false,
  15023. m, message, t, token;
  15024. for ( m in messages ){
  15025. if ( messages.hasOwnProperty( m ) ){
  15026. message = messages[m];
  15027. if ( isToken && message[tokenOrFunction] ){
  15028. delete message[tokenOrFunction];
  15029. result = tokenOrFunction;
  15030. // tokens are unique, so we can just stop here
  15031. break;
  15032. } else if (!isToken) {
  15033. for ( t in message ){
  15034. if (message.hasOwnProperty(t) && message[t] === tokenOrFunction){
  15035. delete message[t];
  15036. result = true;
  15037. }
  15038. }
  15039. }
  15040. }
  15041. }
  15042. return result;
  15043. };
  15044. return PubSub;
  15045. }));
  15046. },{}],67:[function(_dereq_,module,exports){
  15047. exports.Host = _dereq_('./lib/Host');
  15048. exports.Promise = _dereq_('./lib/Promise');
  15049. },{"./lib/Host":68,"./lib/Promise":70}],68:[function(_dereq_,module,exports){
  15050. var WebSocket = _dereq_('ws');
  15051. var WebSocketServer = _dereq_('ws').Server;
  15052. var uuid = _dereq_('node-uuid');
  15053. var Promise = _dereq_('./Promise');
  15054. var requestify = _dereq_('./requestify');
  15055. var Peer = _dereq_('./Peer');
  15056. /**
  15057. * Host
  15058. * @param {Object} [options] Available options: see Host.config
  15059. */
  15060. function Host(options) {
  15061. var me = this;
  15062. // peers and cached peer addresses
  15063. this.peers = {}; // local peers
  15064. this.addresses = {}; // cached addresses of peers located on other hosts
  15065. // pubsub
  15066. this.channels = {}; // keys are the channels, values are arrays with callbacks of subscribers
  15067. // default options
  15068. this.options = {
  15069. reconnectTimeout: 5 * 60 * 1000, // give up reconnecting after 5 minutes
  15070. reconnectDelay: 1000, // try reconnecting after one second
  15071. reconnectDecay: 2
  15072. };
  15073. // server properties
  15074. this.server = null;
  15075. this.address = null;
  15076. this.port = null;
  15077. this.connections = {}; // List with open connections, key is the url and value is the connection
  15078. this.timers = {}; // reconnect timers
  15079. /**
  15080. * Send a message from one peer to another
  15081. * @param {string} from Id of the sending peer
  15082. * @param {string} to Id of the receiving peer
  15083. * @param {*} message JSON message
  15084. * @returns {Promise.<null, Error>} Resolves when sent
  15085. */
  15086. this.send = function (from, to, message) {
  15087. // see if the peer lives on the same host
  15088. var peer = me.peers[to];
  15089. if (peer) {
  15090. peer.emit('message', from, message);
  15091. return Promise.resolve(null);
  15092. }
  15093. // find the remote host where the recipient is located
  15094. return me.find(to)
  15095. .then(function (url) {
  15096. var conn = me.connections[url];
  15097. if (conn) {
  15098. var request = {
  15099. method: 'send',
  15100. params: {
  15101. from: from,
  15102. to: to,
  15103. message: message
  15104. }
  15105. };
  15106. // TODO: there is a maximum callstack issue when queuing a lot of notifications
  15107. return conn.request(request) // the send request returns null
  15108. //return conn.notify(request) // the send request returns null
  15109. .catch(function (err) {
  15110. // FIXME: use a protocol for errors, use error code
  15111. if (err.toString().indexOf('Error: Peer not found') === 0) {
  15112. // this peer was deleted. Remove it from cache
  15113. delete me.addresses[to];
  15114. throw _peerNotFoundError(to);
  15115. }
  15116. })
  15117. }
  15118. else {
  15119. throw _peerUnreachable(to, url);
  15120. }
  15121. });
  15122. };
  15123. this.config(options);
  15124. }
  15125. /**
  15126. * Apply configuration options to the host, and/or retrieve the current
  15127. * configuration.
  15128. * @param {Object} [options] Available options:
  15129. * - networkId An id for the distribus
  15130. * network. A Host can only
  15131. * connect to other hosts with
  15132. * the same id. networkId cannot
  15133. * be changed once set.
  15134. * - reconnectTimeout Timeout in milliseconds for
  15135. * giving up reconnecting.
  15136. * 5 minutes by default
  15137. * - reconnectDelay Initial delay for trying to
  15138. * reconnect. for consecutive
  15139. * reconnect trials, the delay
  15140. * decays with a factor
  15141. * `reconnectDecay`.
  15142. * 1 second by default.
  15143. * - reconnectDecay Decay for the reconnect
  15144. * delay. 2 by default.
  15145. * @return {Object} Returns the current configuration
  15146. */
  15147. Host.prototype.config = function (options) {
  15148. // apply new options
  15149. if (options) {
  15150. _merge(this.options, options);
  15151. // apply networkId
  15152. if (options.networkId) {
  15153. if (this.networkId !== null) {
  15154. this.networkId = options.networkId;
  15155. }
  15156. else {
  15157. throw new Error('Cannot replace networkId once set');
  15158. }
  15159. }
  15160. }
  15161. // return a copy of the options
  15162. return _merge({}, this.options);
  15163. };
  15164. /**
  15165. * Create a new peer.
  15166. * Throws an error when a peer with the same id already exists on this host.
  15167. * Does not check whether this id exists on any remote host (use Host.find(id)
  15168. * to validate this before creating a peer, or even better, use a uuid to
  15169. * prevent id collisions).
  15170. * @param {string} id The id for the new peer
  15171. * @return {Peer} Returns the created peer
  15172. */
  15173. Host.prototype.create = function (id) {
  15174. if (id in this.peers) {
  15175. throw new Error('Id already exists (id: ' + id +')');
  15176. }
  15177. var peer = new Peer(id, this.send);
  15178. this.peers[id] = peer;
  15179. return peer;
  15180. };
  15181. /**
  15182. * Remove a peer from the host
  15183. * @param {Peer | string} peer A peer or the id of a peer
  15184. */
  15185. Host.prototype.remove = function (peer) {
  15186. if (peer instanceof Peer) { // a peer instance
  15187. delete this.peers[peer.id];
  15188. }
  15189. else if (peer) { // a string with the peers id
  15190. delete this.peers[peer];
  15191. }
  15192. };
  15193. /**
  15194. * Get a local peer by its id
  15195. * @param {string} id The id of an existing peer
  15196. * @return {Peer | null} returns the peer, or returns null when not existing.
  15197. */
  15198. Host.prototype.get = function (id) {
  15199. return this.peers[id] || null;
  15200. };
  15201. /**
  15202. * Find the host of a peer by it's id
  15203. * @param {string} id Id of a peer
  15204. * @return {Promise.<string | null, Error>} The url of the peers host.
  15205. * Returns null if the found host has no url.
  15206. * Throws an error if not found.
  15207. */
  15208. Host.prototype.find = function (id) {
  15209. var me = this;
  15210. // check if this is a local peer
  15211. if (id in me.peers) {
  15212. return Promise.resolve(me.url || null);
  15213. }
  15214. // check if this id is already in cache
  15215. var url = me.addresses[id];
  15216. if (url) {
  15217. // yes, we already have the address
  15218. return Promise.resolve(url);
  15219. }
  15220. // search on other hosts
  15221. return new Promise(function (resolve, reject) {
  15222. // TODO: send requests in small batches, not all at once
  15223. // send a find request to a host
  15224. var found = false;
  15225. function _find(url) {
  15226. var conn = me.connections[url];
  15227. return conn.request({method: 'find', params: {id: id}})
  15228. .then(function (url) {
  15229. if (url && !found) {
  15230. // we found the peer
  15231. found = true;
  15232. // put this address in cache
  15233. // TODO: limit the number of cached addresses. When exceeding the limit, store on disk in a temporary db
  15234. me.addresses[id] = url;
  15235. // return the found url
  15236. resolve(url);
  15237. }
  15238. });
  15239. }
  15240. // ask all connected hosts if they host this peer
  15241. var results = Object.keys(me.connections).map(_find);
  15242. // if all requests are finished and the peer is not found, reject with an error
  15243. Promise.all(results)
  15244. .then(function () {
  15245. if (!found || results.length == 0) {
  15246. reject(_peerNotFoundError(id));
  15247. }
  15248. });
  15249. });
  15250. };
  15251. /**
  15252. * Start listening on a socket.
  15253. * @param {string} address
  15254. * @param {number} port
  15255. * @return {Promise.<Host, Error>} Returns itself when connected
  15256. */
  15257. Host.prototype.listen = function (address, port) {
  15258. var me = this;
  15259. return new Promise(function (resolve, reject) {
  15260. if (me.server) {
  15261. reject(new Error('Server already listening'));
  15262. return;
  15263. }
  15264. me.server = new WebSocketServer({port: port}, function () {
  15265. me.address = address;
  15266. me.port = port;
  15267. me.url = 'ws://' + address + ':' + port;
  15268. resolve(me);
  15269. });
  15270. me.server.on('connection', function (conn) {
  15271. conn = requestify(conn);
  15272. conn.onerror = function (err) {
  15273. // TODO: what to do with errors?
  15274. };
  15275. conn.onclose = function () {
  15276. // remove this connection from the connections list
  15277. // (we do not yet forget the cached peers)
  15278. var url = me._findUrl(conn);
  15279. delete me.connections[url];
  15280. me.timers[url] = setTimeout(function () {
  15281. delete me.timers[url];
  15282. // clear cache
  15283. me._forgetPeers(url);
  15284. }, me.options.reconnectTimeout);
  15285. };
  15286. conn.onrequest = function (request) {
  15287. return me._onRequest(conn, request);
  15288. };
  15289. });
  15290. me.server.on('error', function (err) {
  15291. reject(err)
  15292. });
  15293. });
  15294. };
  15295. /**
  15296. * Handle a request
  15297. * @param {WebSocket} conn
  15298. * @param {Object} request
  15299. * @returns {Promise}
  15300. * @private
  15301. */
  15302. Host.prototype._onRequest = function (conn, request) {
  15303. var me = this;
  15304. var url;
  15305. switch (request.method) {
  15306. case 'greeting':
  15307. url = request.params && request.params.url;
  15308. var networkId = request.params.networkId || null;
  15309. if (networkId === null || networkId === me.networkId) {
  15310. if (url && !(url in this.connections)) {
  15311. this.connections[url] = conn;
  15312. return this._broadcastJoin(url)
  15313. .then(function () {
  15314. return Promise.resolve({networkId: me.networkId})
  15315. });
  15316. }
  15317. else {
  15318. return Promise.resolve({networkId: me.networkId});
  15319. }
  15320. }
  15321. else {
  15322. return Promise.reject(new Error('Network id mismatch (' + networkId + ' !== ' + me.networkId + ')'));
  15323. }
  15324. case 'join':
  15325. url = request.params && request.params.url;
  15326. return this.join(url)
  15327. .then(function (host) {
  15328. return Promise.resolve();
  15329. });
  15330. case 'goodbye':
  15331. url = this._findUrl(conn);
  15332. this._forgetPeers(url);
  15333. this._disconnect(url);
  15334. return Promise.resolve('goodbye');
  15335. case 'hosts':
  15336. // connect to all newly retrieved urls
  15337. if (request.params && request.params.urls) {
  15338. this.join(request.params.urls);
  15339. }
  15340. // return a list with the urls of all known hosts
  15341. return Promise.resolve(Object.keys(this.connections));
  15342. case 'find': // find a peer
  15343. var id = request.params && request.params.id;
  15344. return Promise.resolve(this.peers[id] ? this.url : null);
  15345. case 'send':
  15346. var from = request.params && request.params.from;
  15347. var to = request.params && request.params.to;
  15348. var message = request.params && request.params.message;
  15349. // TODO: validate whether all parameters are there
  15350. var peer = this.peers[to];
  15351. if (peer) {
  15352. peer.emit('message', from, message);
  15353. return Promise.resolve(null);
  15354. }
  15355. else {
  15356. return Promise.reject(_peerNotFoundError(to).toString());
  15357. }
  15358. case 'publish':
  15359. var channel = request.params && request.params.channel;
  15360. var message = request.params && request.params.message;
  15361. this._publish(channel, message);
  15362. return Promise.resolve({
  15363. result: null,
  15364. error: null
  15365. });
  15366. case 'ping':
  15367. return Promise.resolve({
  15368. result: request.params,
  15369. error: null
  15370. });
  15371. default:
  15372. return Promise.reject('Unknown method "' + request.method + '"');
  15373. }
  15374. };
  15375. /**
  15376. * Find an url from a connection
  15377. * @param {WebSocket} conn
  15378. * @return {String | null} url
  15379. * @private
  15380. */
  15381. Host.prototype._findUrl = function (conn) {
  15382. // search by instance
  15383. for (var url in this.connections) {
  15384. if (this.connections.hasOwnProperty(url) && this.connections[url] === conn) {
  15385. return url;
  15386. }
  15387. }
  15388. return null;
  15389. };
  15390. /**
  15391. * Remove all cached peers of given
  15392. * @param {string} url Url of a host for which to forget the cached peers
  15393. * @private
  15394. */
  15395. Host.prototype._forgetPeers = function (url) {
  15396. // remove all cached peers
  15397. for (var id in this.addresses) {
  15398. if (this.addresses.hasOwnProperty(id) && this.addresses[id] === url) {
  15399. delete this.addresses[id];
  15400. }
  15401. }
  15402. };
  15403. /**
  15404. * Join an other Host.
  15405. * A host can only join another host when having the same id, or having no id
  15406. * defined. In the latter case, the host will orphan the id of the host it
  15407. * connects to.
  15408. * @param {string} url For example 'ws://localhost:3000'
  15409. * @return {Promise.<Host, Error>} Returns itself when joined
  15410. */
  15411. Host.prototype.join = function (url) {
  15412. var me = this;
  15413. if (url && !(url in me.connections)) {
  15414. return me._connect(url)
  15415. .then(function () {
  15416. // broadcast the join request to all known hosts
  15417. return me._broadcastJoin(url);
  15418. })
  15419. .then(function (urls) {
  15420. // return the host itself as last result in the promise chain
  15421. return me;
  15422. });
  15423. // TODO: handle connection error
  15424. }
  15425. else {
  15426. // already known url. ignore this join
  15427. // FIXME: it is possible that this connection is still being established
  15428. return Promise.resolve(me);
  15429. }
  15430. };
  15431. /**
  15432. * Open a connection to an other host and add the host to the list of connected
  15433. * hosts.
  15434. * @param {String} url
  15435. * @returns {Promise.<WebSocket, Error>} Returns the established connection
  15436. * @private
  15437. */
  15438. Host.prototype._connect = function(url) {
  15439. var me = this;
  15440. return new Promise(function (resolve, reject) {
  15441. // open a web socket
  15442. var conn = new WebSocket(url);
  15443. requestify(conn);
  15444. me.connections[url] = conn;
  15445. conn.onrequest = function (request) {
  15446. return me._onRequest(conn, request);
  15447. };
  15448. conn.onclose = function () {
  15449. if (me.connections[url]) {
  15450. // remove the connection from the list
  15451. delete me.connections[url];
  15452. // schedule reconnection
  15453. me._reconnect(url);
  15454. }
  15455. };
  15456. conn.onopen = function () {
  15457. // send a greeting with the hosts url
  15458. conn.request({method: 'greeting', params: { url: me.url, networkId: me.networkId } })
  15459. .then(function (params) {
  15460. me.networkId = params.networkId;
  15461. resolve(conn);
  15462. })
  15463. .catch(function (err) {
  15464. // greeting rejected
  15465. delete me.connections[url];
  15466. conn.close();
  15467. reject(err);
  15468. });
  15469. };
  15470. conn.onerror = function (err) {
  15471. delete me.connections[url];
  15472. reject(err);
  15473. conn.close();
  15474. };
  15475. });
  15476. };
  15477. /**
  15478. * Reconnect with a host
  15479. * @param {String} url Url of the host to which to reconnect
  15480. * @private
  15481. */
  15482. Host.prototype._reconnect = function (url) {
  15483. var me = this;
  15484. var start = new Date().valueOf();
  15485. function scheduleReconnect(delay, trial) {
  15486. me.timers[url] = setTimeout(function () {
  15487. delete me.timers[url];
  15488. var now = new Date().valueOf();
  15489. if (now - start < me.options.reconnectTimeout) {
  15490. // reconnect
  15491. me._connect(url)
  15492. .catch(function (err) {
  15493. // schedule next reconnect trial
  15494. scheduleReconnect(delay / me.options.reconnectDecay, trial + 1);
  15495. });
  15496. }
  15497. else {
  15498. // give up trying to reconnect
  15499. me._forgetPeers(url);
  15500. }
  15501. }, delay);
  15502. }
  15503. // schedule reconnection after a delay
  15504. scheduleReconnect(me.options.reconnectDelay, 0);
  15505. };
  15506. /**
  15507. * Forward a join message to all known hosts
  15508. * @param {string} url For example 'ws://localhost:3000'
  15509. * @return {Promise.<String[], Error>} returns the joined urls
  15510. */
  15511. Host.prototype._broadcastJoin = function (url) {
  15512. // TODO: implement a more efficient broadcast mechanism
  15513. var me = this;
  15514. var urls = Object.keys(me.connections)
  15515. .filter(function (u) {
  15516. return u !== url
  15517. });
  15518. function join (existingUrl) {
  15519. var conn = me.connections[existingUrl];
  15520. return conn.request({method: 'join', params: {'url': url}})
  15521. .catch(function (err) {
  15522. // TODO: what to do with failed requests? Right now we ignore them
  15523. })
  15524. .then(function () {
  15525. // return the url where the join is broadcasted to
  15526. return existingUrl;
  15527. })
  15528. }
  15529. // send a join request to all known hosts
  15530. return Promise.all(urls.map(join));
  15531. };
  15532. /**
  15533. * Stop listening on currently a socket
  15534. * @return {Promise.<Host, Error>} Returns itself
  15535. */
  15536. Host.prototype.close = function () {
  15537. var me = this;
  15538. // TODO: create a flag while closing? and opening?
  15539. if (this.server) {
  15540. // close the host, and clean up cache
  15541. function closeHost() {
  15542. // close the host itself
  15543. me.addresses = {};
  15544. if (me.server) {
  15545. me.server.close();
  15546. me.server = null;
  15547. me.address = null;
  15548. me.port = null;
  15549. me.url = null;
  15550. }
  15551. return me;
  15552. }
  15553. // close all connections
  15554. var urls = Object.keys(this.connections);
  15555. return Promise.all(urls.map(function (url) {
  15556. return me._disconnect(url);
  15557. })).then(closeHost);
  15558. }
  15559. else {
  15560. // no socket open. resolve immediately
  15561. Promise.resolve(this);
  15562. }
  15563. };
  15564. /**
  15565. * Close the connection with a host. Note: peers are not removed from cache
  15566. * @param {string} url Url of a connected host
  15567. * @return {Promise.<undefined, Error>} Resolves a promise when closed
  15568. * @private
  15569. */
  15570. Host.prototype._disconnect = function (url) {
  15571. var conn = this.connections[url];
  15572. if (conn) {
  15573. delete this.connections[url];
  15574. if (this.timers[url]) {
  15575. clearTimeout(this.timers[url]);
  15576. delete this.timers[url];
  15577. }
  15578. // send a goodbye message
  15579. return conn.request({method: 'goodbye'})
  15580. .catch(function (err) {
  15581. // ignore failing to send goodbye
  15582. })
  15583. // then close the connection
  15584. .then(function () {
  15585. conn.close();
  15586. });
  15587. }
  15588. else {
  15589. Promise.resolve();
  15590. }
  15591. };
  15592. /**
  15593. * Publish a message via a channel. All listeners subscribed to this channel
  15594. * will be triggered, both listeners on this host as well as connected hosts.
  15595. * @param {string} channel The name of the channel
  15596. * @param {*} message A message, can be any type. Must be serializable JSON.
  15597. */
  15598. Host.prototype.publish = function (channel, message) {
  15599. // trigger local subscribers
  15600. this._publish(channel, message);
  15601. // send the message to all connected hosts
  15602. for (var url in this.connections) {
  15603. if (this.connections.hasOwnProperty(url)) {
  15604. var connection = this.connections[url];
  15605. connection.notify({
  15606. method: 'publish',
  15607. params: {
  15608. channel: channel,
  15609. message: message
  15610. }
  15611. });
  15612. }
  15613. }
  15614. // TODO: improve efficiency by having the hosts share the channels for which
  15615. // they have subscribers, so we only have to send a message to a
  15616. // particular host when it has subscribers to the channel.
  15617. };
  15618. /**
  15619. * Publish a channel to all subscribers on this host.
  15620. * @param {string} channel The name of the channel
  15621. * @param {*} message A message, can be any type. Must be serializable JSON.
  15622. * @private
  15623. */
  15624. Host.prototype._publish = function (channel, message) {
  15625. // trigger local subscribers
  15626. var callbacks = this.channels[channel];
  15627. if (callbacks) {
  15628. callbacks.forEach(function (callback) {
  15629. callback(message);
  15630. });
  15631. }
  15632. };
  15633. /**
  15634. * Subscribe to a channel.
  15635. * @param {string} channel The name of the channel
  15636. * @param {function} callback Called as callback(message)
  15637. */
  15638. Host.prototype.subscribe = function (channel, callback) {
  15639. // TODO: implement support for wildcards, like subscribing to "foo.*" or something like that
  15640. var callbacks = this.channels[channel];
  15641. if (!callbacks) {
  15642. callbacks = [];
  15643. this.channels[channel] = callbacks;
  15644. }
  15645. callbacks.push(callback);
  15646. };
  15647. /**
  15648. * Unsubscribe from a channel.
  15649. * @param {string} channel The name of the channel
  15650. * @param {function} callback A callback used before to subscribe
  15651. */
  15652. Host.prototype.unsubscribe = function (channel, callback) {
  15653. var callbacks = this.channels[channel];
  15654. if (callbacks) {
  15655. var index = callbacks.indexOf(callback);
  15656. if (index !== -1) {
  15657. callbacks.splice(index, 1);
  15658. if (callbacks.length === 0) {
  15659. delete this.channels[channel];
  15660. }
  15661. }
  15662. }
  15663. };
  15664. /**
  15665. * Merge object b into object a: copy all properties of b to a
  15666. * @param {Object} a
  15667. * @param {Object} b
  15668. * @return {Object} returns the merged a
  15669. * @private
  15670. */
  15671. function _merge (a, b) {
  15672. for (var prop in b) {
  15673. if (b.hasOwnProperty(prop)) {
  15674. a[prop] = b[prop];
  15675. }
  15676. }
  15677. return a;
  15678. }
  15679. /**
  15680. * Create an Error "Peer not found"
  15681. * @param {string} id The id of the peer
  15682. * @return {Error}
  15683. * @private
  15684. */
  15685. function _peerNotFoundError(id) {
  15686. return new Error('Peer not found (id: ' + id + ')');
  15687. }
  15688. /**
  15689. * Create an Error "Peer unreachable"
  15690. * @param {string} id The id of the peer
  15691. * @param {string} url Url of the peers host
  15692. * @return {Error}
  15693. * @private
  15694. */
  15695. function _peerUnreachable(id, url) {
  15696. return new Error('Peer unreachable (id: ' + id + ', url: ' + url + ')');
  15697. }
  15698. // TODO: implement a function list() which returns the id's of all peers in the system
  15699. module.exports = Host;
  15700. },{"./Peer":69,"./Promise":70,"./requestify":71,"node-uuid":113,"ws":109}],69:[function(_dereq_,module,exports){
  15701. //var Emitter = require('emitter-component');
  15702. /**
  15703. * Peer
  15704. * A peer can send and receive messages via a connected message bus
  15705. * @param {string} id
  15706. * @param {function(string, string, *)} send A function to send a message to an other peer
  15707. */
  15708. function Peer(id, send) {
  15709. this.id = id;
  15710. this._send = send;
  15711. this.listeners = {};
  15712. }
  15713. /**
  15714. * Send a message to another peer
  15715. * @param {string} to Id of the recipient
  15716. * @param {*} message Message to be send, can be JSON
  15717. * @returns {Promise.<null, Error>} Resolves when sent
  15718. */
  15719. Peer.prototype.send = function (to, message) {
  15720. return this._send(this.id, to, message);
  15721. };
  15722. // Extend the Peer with event emitter functionality
  15723. //Emitter(Peer.prototype);
  15724. // TODO: complete this custom event emitter, it's about 5 times as fast as Emitter because its not slicing arguments
  15725. /**
  15726. * Register an event listener
  15727. * @param {string} event Available events: 'message'
  15728. * @param {Function} callback Callback function, called as callback(from, message)
  15729. */
  15730. Peer.prototype.on = function (event, callback) {
  15731. if (!(event in this.listeners)) this.listeners[event] = [];
  15732. this.listeners[event].push(callback);
  15733. };
  15734. // TODO: implement off
  15735. /**
  15736. * Emit an event
  15737. * @param {string} event For example 'message'
  15738. * @param {string} from Id of the sender, for example 'peer1'
  15739. * @param {*} message A message, can be any type. Must be serializable JSON.
  15740. */
  15741. Peer.prototype.emit = function (event, from, message) {
  15742. var listeners = this.listeners[event];
  15743. if (listeners) {
  15744. for (var i = 0, ii = listeners.length; i < ii; i++) {
  15745. var listener = listeners[i];
  15746. listener(from, message);
  15747. }
  15748. }
  15749. };
  15750. module.exports = Peer;
  15751. },{}],70:[function(_dereq_,module,exports){
  15752. // Return a promise implementation.
  15753. module.exports = _dereq_('bluebird');
  15754. },{"bluebird":74}],71:[function(_dereq_,module,exports){
  15755. var uuid = _dereq_('node-uuid'),
  15756. Promise = _dereq_('./Promise');
  15757. var TIMEOUT = 60000; // ms
  15758. // TODO: make timeout a configuration setting
  15759. /**
  15760. * Wrap a socket in a request/response handling layer.
  15761. * Requests are wrapped in an envelope with id and data, and responses
  15762. * are packed in an envelope with this same id and response data.
  15763. *
  15764. * The socket is extended with functions:
  15765. * request(data: *) : Promise.<*, Error>
  15766. * onrequest(data: *) : Promise.<*, Error>
  15767. *
  15768. * @param {WebSocket} socket
  15769. * @return {WebSocket} requestified socket
  15770. */
  15771. function requestify (socket) {
  15772. return (function () {
  15773. var queue = {}; // queue with requests in progress
  15774. if ('request' in socket) {
  15775. throw new Error('Socket already has a request property');
  15776. }
  15777. var requestified = socket;
  15778. /**
  15779. * Event handler, handles incoming messages
  15780. * @param {Object} event
  15781. */
  15782. socket.onmessage = function (event) {
  15783. var data = event.data;
  15784. if (data.charAt(0) == '{') {
  15785. var envelope = JSON.parse(data);
  15786. // match the request from the id in the response
  15787. var request = queue[envelope.id];
  15788. if (request) {
  15789. // handle an incoming response
  15790. clearTimeout(request.timeout);
  15791. delete queue[envelope.id];
  15792. // resolve the promise with response data
  15793. if (envelope.error) {
  15794. // TODO: implement a smarter way to serialize and deserialize errors
  15795. request.reject(new Error(envelope.error));
  15796. }
  15797. else {
  15798. request.resolve(envelope.message);
  15799. }
  15800. }
  15801. else {
  15802. if ('id' in envelope) {
  15803. try {
  15804. // handle an incoming request
  15805. requestified.onrequest(envelope.message)
  15806. .then(function (message) {
  15807. var response = {
  15808. id: envelope.id,
  15809. message: message,
  15810. error: null
  15811. };
  15812. socket.send(JSON.stringify(response));
  15813. })
  15814. .catch(function (error) {
  15815. var response = {
  15816. id: envelope.id,
  15817. message: null,
  15818. error: error.message || error.toString()
  15819. };
  15820. socket.send(JSON.stringify(response));
  15821. });
  15822. }
  15823. catch (err) {
  15824. var response = {
  15825. id: envelope.id,
  15826. message: null,
  15827. error: err.message || err.toString()
  15828. };
  15829. socket.send(JSON.stringify(response));
  15830. }
  15831. }
  15832. else {
  15833. // handle incoming notification (we don't do anything with the response)
  15834. requestified.onrequest(envelope.message);
  15835. }
  15836. }
  15837. }
  15838. };
  15839. /**
  15840. * Send a request
  15841. * @param {*} message
  15842. * @returns {Promise.<*, Error>} Returns a promise resolving with the response message
  15843. */
  15844. requestified.request = function (message) {
  15845. return new Promise(function (resolve, reject) {
  15846. // put the data in an envelope with id
  15847. var id = uuid.v1();
  15848. var envelope = {
  15849. id: id,
  15850. message: message
  15851. };
  15852. // add the request to the list with requests in progress
  15853. queue[id] = {
  15854. resolve: resolve,
  15855. reject: reject,
  15856. timeout: setTimeout(function () {
  15857. delete queue[id];
  15858. reject(new Error('Timeout'));
  15859. }, TIMEOUT)
  15860. };
  15861. socket.send(JSON.stringify(envelope));
  15862. });
  15863. };
  15864. /**
  15865. * Send a notification. A notification does not receive a response.
  15866. * @param {*} message
  15867. * @returns {Promise.<null, Error>} Returns a promise resolving with the null
  15868. * when the notification has been sent.
  15869. */
  15870. requestified.notify = function (message) {
  15871. return new Promise(function (resolve, reject) {
  15872. // put the data in an envelope
  15873. var envelope = {
  15874. // we don't add an id, so we send this as notification instead of a request
  15875. message: message
  15876. };
  15877. socket.send(JSON.stringify(envelope), function () {
  15878. resolve(null);
  15879. });
  15880. });
  15881. };
  15882. /**
  15883. * Handle an incoming request.
  15884. * @param {*} message Request message
  15885. * @returns {Promise.<*, Error>} Resolves with a response message
  15886. */
  15887. requestified.onrequest = function (message) {
  15888. // this function must be implemented by the socket
  15889. return Promise.reject('No onrequest handler implemented');
  15890. };
  15891. // TODO: disable send and onmessage on the requestified socket
  15892. return requestified;
  15893. })();
  15894. }
  15895. module.exports = requestify;
  15896. },{"./Promise":70,"node-uuid":113}],72:[function(_dereq_,module,exports){
  15897. /**
  15898. * Copyright (c) 2014 Petka Antonov
  15899. *
  15900. * Permission is hereby granted, free of charge, to any person obtaining a copy
  15901. * of this software and associated documentation files (the "Software"), to deal
  15902. * in the Software without restriction, including without limitation the rights
  15903. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15904. * copies of the Software, and to permit persons to whom the Software is
  15905. * furnished to do so, subject to the following conditions:</p>
  15906. *
  15907. * The above copyright notice and this permission notice shall be included in
  15908. * all copies or substantial portions of the Software.
  15909. *
  15910. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15911. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15912. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15913. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15914. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  15915. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  15916. * THE SOFTWARE.
  15917. *
  15918. */
  15919. "use strict";
  15920. module.exports = function(Promise, Promise$_CreatePromiseArray, PromiseArray) {
  15921. var SomePromiseArray = _dereq_("./some_promise_array.js")(PromiseArray);
  15922. function Promise$_Any(promises, useBound) {
  15923. var ret = Promise$_CreatePromiseArray(
  15924. promises,
  15925. SomePromiseArray,
  15926. useBound === true && promises._isBound()
  15927. ? promises._boundTo
  15928. : void 0
  15929. );
  15930. var promise = ret.promise();
  15931. if (promise.isRejected()) {
  15932. return promise;
  15933. }
  15934. ret.setHowMany(1);
  15935. ret.setUnwrap();
  15936. ret.init();
  15937. return promise;
  15938. }
  15939. Promise.any = function Promise$Any(promises) {
  15940. return Promise$_Any(promises, false);
  15941. };
  15942. Promise.prototype.any = function Promise$any() {
  15943. return Promise$_Any(this, true);
  15944. };
  15945. };
  15946. },{"./some_promise_array.js":104}],73:[function(_dereq_,module,exports){
  15947. /**
  15948. * Copyright (c) 2014 Petka Antonov
  15949. *
  15950. * Permission is hereby granted, free of charge, to any person obtaining a copy
  15951. * of this software and associated documentation files (the "Software"), to deal
  15952. * in the Software without restriction, including without limitation the rights
  15953. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15954. * copies of the Software, and to permit persons to whom the Software is
  15955. * furnished to do so, subject to the following conditions:</p>
  15956. *
  15957. * The above copyright notice and this permission notice shall be included in
  15958. * all copies or substantial portions of the Software.
  15959. *
  15960. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15961. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15962. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15963. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15964. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  15965. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  15966. * THE SOFTWARE.
  15967. *
  15968. */
  15969. "use strict";
  15970. var schedule = _dereq_("./schedule.js");
  15971. var Queue = _dereq_("./queue.js");
  15972. var errorObj = _dereq_("./util.js").errorObj;
  15973. var tryCatch1 = _dereq_("./util.js").tryCatch1;
  15974. var process = _dereq_("./global.js").process;
  15975. function Async() {
  15976. this._isTickUsed = false;
  15977. this._length = 0;
  15978. this._lateBuffer = new Queue();
  15979. this._functionBuffer = new Queue(25000 * 3);
  15980. var self = this;
  15981. this.consumeFunctionBuffer = function Async$consumeFunctionBuffer() {
  15982. self._consumeFunctionBuffer();
  15983. };
  15984. }
  15985. Async.prototype.haveItemsQueued = function Async$haveItemsQueued() {
  15986. return this._length > 0;
  15987. };
  15988. Async.prototype.invokeLater = function Async$invokeLater(fn, receiver, arg) {
  15989. if (process !== void 0 &&
  15990. process.domain != null &&
  15991. !fn.domain) {
  15992. fn = process.domain.bind(fn);
  15993. }
  15994. this._lateBuffer.push(fn, receiver, arg);
  15995. this._queueTick();
  15996. };
  15997. Async.prototype.invoke = function Async$invoke(fn, receiver, arg) {
  15998. if (process !== void 0 &&
  15999. process.domain != null &&
  16000. !fn.domain) {
  16001. fn = process.domain.bind(fn);
  16002. }
  16003. var functionBuffer = this._functionBuffer;
  16004. functionBuffer.push(fn, receiver, arg);
  16005. this._length = functionBuffer.length();
  16006. this._queueTick();
  16007. };
  16008. Async.prototype._consumeFunctionBuffer =
  16009. function Async$_consumeFunctionBuffer() {
  16010. var functionBuffer = this._functionBuffer;
  16011. while(functionBuffer.length() > 0) {
  16012. var fn = functionBuffer.shift();
  16013. var receiver = functionBuffer.shift();
  16014. var arg = functionBuffer.shift();
  16015. fn.call(receiver, arg);
  16016. }
  16017. this._reset();
  16018. this._consumeLateBuffer();
  16019. };
  16020. Async.prototype._consumeLateBuffer = function Async$_consumeLateBuffer() {
  16021. var buffer = this._lateBuffer;
  16022. while(buffer.length() > 0) {
  16023. var fn = buffer.shift();
  16024. var receiver = buffer.shift();
  16025. var arg = buffer.shift();
  16026. var res = tryCatch1(fn, receiver, arg);
  16027. if (res === errorObj) {
  16028. this._queueTick();
  16029. if (fn.domain != null) {
  16030. fn.domain.emit("error", res.e);
  16031. }
  16032. else {
  16033. throw res.e;
  16034. }
  16035. }
  16036. }
  16037. };
  16038. Async.prototype._queueTick = function Async$_queue() {
  16039. if (!this._isTickUsed) {
  16040. schedule(this.consumeFunctionBuffer);
  16041. this._isTickUsed = true;
  16042. }
  16043. };
  16044. Async.prototype._reset = function Async$_reset() {
  16045. this._isTickUsed = false;
  16046. this._length = 0;
  16047. };
  16048. module.exports = new Async();
  16049. },{"./global.js":86,"./queue.js":97,"./schedule.js":100,"./util.js":108}],74:[function(_dereq_,module,exports){
  16050. /**
  16051. * Copyright (c) 2014 Petka Antonov
  16052. *
  16053. * Permission is hereby granted, free of charge, to any person obtaining a copy
  16054. * of this software and associated documentation files (the "Software"), to deal
  16055. * in the Software without restriction, including without limitation the rights
  16056. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  16057. * copies of the Software, and to permit persons to whom the Software is
  16058. * furnished to do so, subject to the following conditions:</p>
  16059. *
  16060. * The above copyright notice and this permission notice shall be included in
  16061. * all copies or substantial portions of the Software.
  16062. *
  16063. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16064. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16065. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16066. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16067. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16068. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  16069. * THE SOFTWARE.
  16070. *
  16071. */
  16072. "use strict";
  16073. var Promise = _dereq_("./promise.js")();
  16074. module.exports = Promise;
  16075. },{"./promise.js":90}],75:[function(_dereq_,module,exports){
  16076. /**
  16077. * Copyright (c) 2014 Petka Antonov
  16078. *
  16079. * Permission is hereby granted, free of charge, to any person obtaining a copy
  16080. * of this software and associated documentation files (the "Software"), to deal
  16081. * in the Software without restriction, including without limitation the rights
  16082. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  16083. * copies of the Software, and to permit persons to whom the Software is
  16084. * furnished to do so, subject to the following conditions:</p>
  16085. *
  16086. * The above copyright notice and this permission notice shall be included in
  16087. * all copies or substantial portions of the Software.
  16088. *
  16089. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16090. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16091. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16092. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16093. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16094. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  16095. * THE SOFTWARE.
  16096. *
  16097. */
  16098. "use strict";
  16099. module.exports = function(Promise) {
  16100. Promise.prototype.call = function Promise$call(propertyName) {
  16101. var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}
  16102. return this._then(function(obj) {
  16103. return obj[propertyName].apply(obj, args);
  16104. },
  16105. void 0,
  16106. void 0,
  16107. void 0,
  16108. void 0
  16109. );
  16110. };
  16111. function Promise$getter(obj) {
  16112. var prop = typeof this === "string"
  16113. ? this
  16114. : ("" + this);
  16115. return obj[prop];
  16116. }
  16117. Promise.prototype.get = function Promise$get(propertyName) {
  16118. return this._then(
  16119. Promise$getter,
  16120. void 0,
  16121. void 0,
  16122. propertyName,
  16123. void 0
  16124. );
  16125. };
  16126. };
  16127. },{}],76:[function(_dereq_,module,exports){
  16128. /**
  16129. * Copyright (c) 2014 Petka Antonov
  16130. *
  16131. * Permission is hereby granted, free of charge, to any person obtaining a copy
  16132. * of this software and associated documentation files (the "Software"), to deal
  16133. * in the Software without restriction, including without limitation the rights
  16134. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  16135. * copies of the Software, and to permit persons to whom the Software is
  16136. * furnished to do so, subject to the following conditions:</p>
  16137. *
  16138. * The above copyright notice and this permission notice shall be included in
  16139. * all copies or substantial portions of the Software.
  16140. *
  16141. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16142. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16143. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16144. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16145. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16146. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  16147. * THE SOFTWARE.
  16148. *
  16149. */
  16150. "use strict";
  16151. module.exports = function(Promise, INTERNAL) {
  16152. var errors = _dereq_("./errors.js");
  16153. var async = _dereq_("./async.js");
  16154. var CancellationError = errors.CancellationError;
  16155. Promise.prototype._cancel = function Promise$_cancel() {
  16156. if (!this.isCancellable()) return this;
  16157. var parent;
  16158. var promiseToReject = this;
  16159. while ((parent = promiseToReject._cancellationParent) !== void 0 &&
  16160. parent.isCancellable()) {
  16161. promiseToReject = parent;
  16162. }
  16163. var err = new CancellationError();
  16164. promiseToReject._attachExtraTrace(err);
  16165. promiseToReject._rejectUnchecked(err);
  16166. };
  16167. Promise.prototype.cancel = function Promise$cancel() {
  16168. if (!this.isCancellable()) return this;
  16169. async.invokeLater(this._cancel, this, void 0);
  16170. return this;
  16171. };
  16172. Promise.prototype.cancellable = function Promise$cancellable() {
  16173. if (this._cancellable()) return this;
  16174. this._setCancellable();
  16175. this._cancellationParent = void 0;
  16176. return this;
  16177. };
  16178. Promise.prototype.uncancellable = function Promise$uncancellable() {
  16179. var ret = new Promise(INTERNAL);
  16180. ret._setTrace(this);
  16181. ret._follow(this);
  16182. ret._unsetCancellable();
  16183. if (this._isBound()) ret._setBoundTo(this._boundTo);
  16184. return ret;
  16185. };
  16186. Promise.prototype.fork =
  16187. function Promise$fork(didFulfill, didReject, didProgress) {
  16188. var ret = this._then(didFulfill, didReject, didProgress,
  16189. void 0, void 0);
  16190. ret._setCancellable();
  16191. ret._cancellationParent = void 0;
  16192. return ret;
  16193. };
  16194. };
  16195. },{"./async.js":73,"./errors.js":80}],77:[function(_dereq_,module,exports){
  16196. /**
  16197. * Copyright (c) 2014 Petka Antonov
  16198. *
  16199. * Permission is hereby granted, free of charge, to any person obtaining a copy
  16200. * of this software and associated documentation files (the "Software"), to deal
  16201. * in the Software without restriction, including without limitation the rights
  16202. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  16203. * copies of the Software, and to permit persons to whom the Software is
  16204. * furnished to do so, subject to the following conditions:</p>
  16205. *
  16206. * The above copyright notice and this permission notice shall be included in
  16207. * all copies or substantial portions of the Software.
  16208. *
  16209. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16210. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16211. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16212. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16213. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16214. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  16215. * THE SOFTWARE.
  16216. *
  16217. */
  16218. "use strict";
  16219. module.exports = function() {
  16220. var inherits = _dereq_("./util.js").inherits;
  16221. var defineProperty = _dereq_("./es5.js").defineProperty;
  16222. var rignore = new RegExp(
  16223. "\\b(?:[a-zA-Z0-9.]+\\$_\\w+|" +
  16224. "tryCatch(?:1|2|Apply)|new \\w*PromiseArray|" +
  16225. "\\w*PromiseArray\\.\\w*PromiseArray|" +
  16226. "setTimeout|CatchFilter\\$_\\w+|makeNodePromisified|processImmediate|" +
  16227. "process._tickCallback|nextTick|Async\\$\\w+)\\b"
  16228. );
  16229. var rtraceline = null;
  16230. var formatStack = null;
  16231. function formatNonError(obj) {
  16232. var str;
  16233. if (typeof obj === "function") {
  16234. str = "[function " +
  16235. (obj.name || "anonymous") +
  16236. "]";
  16237. }
  16238. else {
  16239. str = obj.toString();
  16240. var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
  16241. if (ruselessToString.test(str)) {
  16242. try {
  16243. var newStr = JSON.stringify(obj);
  16244. str = newStr;
  16245. }
  16246. catch(e) {
  16247. }
  16248. }
  16249. if (str.length === 0) {
  16250. str = "(empty array)";
  16251. }
  16252. }
  16253. return ("(<" + snip(str) + ">, no stack trace)");
  16254. }
  16255. function snip(str) {
  16256. var maxChars = 41;
  16257. if (str.length < maxChars) {
  16258. return str;
  16259. }
  16260. return str.substr(0, maxChars - 3) + "...";
  16261. }
  16262. function CapturedTrace(ignoreUntil, isTopLevel) {
  16263. this.captureStackTrace(CapturedTrace, isTopLevel);
  16264. }
  16265. inherits(CapturedTrace, Error);
  16266. CapturedTrace.prototype.captureStackTrace =
  16267. function CapturedTrace$captureStackTrace(ignoreUntil, isTopLevel) {
  16268. captureStackTrace(this, ignoreUntil, isTopLevel);
  16269. };
  16270. CapturedTrace.possiblyUnhandledRejection =
  16271. function CapturedTrace$PossiblyUnhandledRejection(reason) {
  16272. if (typeof console === "object") {
  16273. var message;
  16274. if (typeof reason === "object" || typeof reason === "function") {
  16275. var stack = reason.stack;
  16276. message = "Possibly unhandled " + formatStack(stack, reason);
  16277. }
  16278. else {
  16279. message = "Possibly unhandled " + String(reason);
  16280. }
  16281. if (typeof console.error === "function" ||
  16282. typeof console.error === "object") {
  16283. console.error(message);
  16284. }
  16285. else if (typeof console.log === "function" ||
  16286. typeof console.log === "object") {
  16287. console.log(message);
  16288. }
  16289. }
  16290. };
  16291. CapturedTrace.combine = function CapturedTrace$Combine(current, prev) {
  16292. var curLast = current.length - 1;
  16293. for (var i = prev.length - 1; i >= 0; --i) {
  16294. var line = prev[i];
  16295. if (current[curLast] === line) {
  16296. current.pop();
  16297. curLast--;
  16298. }
  16299. else {
  16300. break;
  16301. }
  16302. }
  16303. current.push("From previous event:");
  16304. var lines = current.concat(prev);
  16305. var ret = [];
  16306. for (var i = 0, len = lines.length; i < len; ++i) {
  16307. if ((rignore.test(lines[i]) ||
  16308. (i > 0 && !rtraceline.test(lines[i])) &&
  16309. lines[i] !== "From previous event:")
  16310. ) {
  16311. continue;
  16312. }
  16313. ret.push(lines[i]);
  16314. }
  16315. return ret;
  16316. };
  16317. CapturedTrace.isSupported = function CapturedTrace$IsSupported() {
  16318. return typeof captureStackTrace === "function";
  16319. };
  16320. var captureStackTrace = (function stackDetection() {
  16321. if (typeof Error.stackTraceLimit === "number" &&
  16322. typeof Error.captureStackTrace === "function") {
  16323. rtraceline = /^\s*at\s*/;
  16324. formatStack = function(stack, error) {
  16325. if (typeof stack === "string") return stack;
  16326. if (error.name !== void 0 &&
  16327. error.message !== void 0) {
  16328. return error.name + ". " + error.message;
  16329. }
  16330. return formatNonError(error);
  16331. };
  16332. var captureStackTrace = Error.captureStackTrace;
  16333. return function CapturedTrace$_captureStackTrace(
  16334. receiver, ignoreUntil) {
  16335. captureStackTrace(receiver, ignoreUntil);
  16336. };
  16337. }
  16338. var err = new Error();
  16339. if (typeof err.stack === "string" &&
  16340. typeof "".startsWith === "function" &&
  16341. (err.stack.startsWith("stackDetection@")) &&
  16342. stackDetection.name === "stackDetection") {
  16343. defineProperty(Error, "stackTraceLimit", {
  16344. writable: true,
  16345. enumerable: false,
  16346. configurable: false,
  16347. value: 25
  16348. });
  16349. rtraceline = /@/;
  16350. var rline = /[@\n]/;
  16351. formatStack = function(stack, error) {
  16352. if (typeof stack === "string") {
  16353. return (error.name + ". " + error.message + "\n" + stack);
  16354. }
  16355. if (error.name !== void 0 &&
  16356. error.message !== void 0) {
  16357. return error.name + ". " + error.message;
  16358. }
  16359. return formatNonError(error);
  16360. };
  16361. return function captureStackTrace(o) {
  16362. var stack = new Error().stack;
  16363. var split = stack.split(rline);
  16364. var len = split.length;
  16365. var ret = "";
  16366. for (var i = 0; i < len; i += 2) {
  16367. ret += split[i];
  16368. ret += "@";
  16369. ret += split[i + 1];
  16370. ret += "\n";
  16371. }
  16372. o.stack = ret;
  16373. };
  16374. }
  16375. else {
  16376. formatStack = function(stack, error) {
  16377. if (typeof stack === "string") return stack;
  16378. if ((typeof error === "object" ||
  16379. typeof error === "function") &&
  16380. error.name !== void 0 &&
  16381. error.message !== void 0) {
  16382. return error.name + ". " + error.message;
  16383. }
  16384. return formatNonError(error);
  16385. };
  16386. return null;
  16387. }
  16388. })();
  16389. return CapturedTrace;
  16390. };
  16391. },{"./es5.js":82,"./util.js":108}],78:[function(_dereq_,module,exports){
  16392. /**
  16393. * Copyright (c) 2014 Petka Antonov
  16394. *
  16395. * Permission is hereby granted, free of charge, to any person obtaining a copy
  16396. * of this software and associated documentation files (the "Software"), to deal
  16397. * in the Software without restriction, including without limitation the rights
  16398. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  16399. * copies of the Software, and to permit persons to whom the Software is
  16400. * furnished to do so, subject to the following conditions:</p>
  16401. *
  16402. * The above copyright notice and this permission notice shall be included in
  16403. * all copies or substantial portions of the Software.
  16404. *
  16405. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16406. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16407. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16408. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16409. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16410. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  16411. * THE SOFTWARE.
  16412. *
  16413. */
  16414. "use strict";
  16415. module.exports = function(NEXT_FILTER) {
  16416. var util = _dereq_("./util.js");
  16417. var errors = _dereq_("./errors.js");
  16418. var tryCatch1 = util.tryCatch1;
  16419. var errorObj = util.errorObj;
  16420. var keys = _dereq_("./es5.js").keys;
  16421. var TypeError = errors.TypeError;
  16422. function CatchFilter(instances, callback, promise) {
  16423. this._instances = instances;
  16424. this._callback = callback;
  16425. this._promise = promise;
  16426. }
  16427. function CatchFilter$_safePredicate(predicate, e) {
  16428. var safeObject = {};
  16429. var retfilter = tryCatch1(predicate, safeObject, e);
  16430. if (retfilter === errorObj) return retfilter;
  16431. var safeKeys = keys(safeObject);
  16432. if (safeKeys.length) {
  16433. errorObj.e = new TypeError(
  16434. "Catch filter must inherit from Error "
  16435. + "or be a simple predicate function");
  16436. return errorObj;
  16437. }
  16438. return retfilter;
  16439. }
  16440. CatchFilter.prototype.doFilter = function CatchFilter$_doFilter(e) {
  16441. var cb = this._callback;
  16442. var promise = this._promise;
  16443. var boundTo = promise._isBound() ? promise._boundTo : void 0;
  16444. for (var i = 0, len = this._instances.length; i < len; ++i) {
  16445. var item = this._instances[i];
  16446. var itemIsErrorType = item === Error ||
  16447. (item != null && item.prototype instanceof Error);
  16448. if (itemIsErrorType && e instanceof item) {
  16449. var ret = tryCatch1(cb, boundTo, e);
  16450. if (ret === errorObj) {
  16451. NEXT_FILTER.e = ret.e;
  16452. return NEXT_FILTER;
  16453. }
  16454. return ret;
  16455. } else if (typeof item === "function" && !itemIsErrorType) {
  16456. var shouldHandle = CatchFilter$_safePredicate(item, e);
  16457. if (shouldHandle === errorObj) {
  16458. var trace = errors.canAttach(errorObj.e)
  16459. ? errorObj.e
  16460. : new Error(errorObj.e + "");
  16461. this._promise._attachExtraTrace(trace);
  16462. e = errorObj.e;
  16463. break;
  16464. } else if (shouldHandle) {
  16465. var ret = tryCatch1(cb, boundTo, e);
  16466. if (ret === errorObj) {
  16467. NEXT_FILTER.e = ret.e;
  16468. return NEXT_FILTER;
  16469. }
  16470. return ret;
  16471. }
  16472. }
  16473. }
  16474. NEXT_FILTER.e = e;
  16475. return NEXT_FILTER;
  16476. };
  16477. return CatchFilter;
  16478. };
  16479. },{"./errors.js":80,"./es5.js":82,"./util.js":108}],79:[function(_dereq_,module,exports){
  16480. /**
  16481. * Copyright (c) 2014 Petka Antonov
  16482. *
  16483. * Permission is hereby granted, free of charge, to any person obtaining a copy
  16484. * of this software and associated documentation files (the "Software"), to deal
  16485. * in the Software without restriction, including without limitation the rights
  16486. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  16487. * copies of the Software, and to permit persons to whom the Software is
  16488. * furnished to do so, subject to the following conditions:</p>
  16489. *
  16490. * The above copyright notice and this permission notice shall be included in
  16491. * all copies or substantial portions of the Software.
  16492. *
  16493. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16494. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16495. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16496. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16497. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16498. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  16499. * THE SOFTWARE.
  16500. *
  16501. */
  16502. "use strict";
  16503. var util = _dereq_("./util.js");
  16504. var isPrimitive = util.isPrimitive;
  16505. var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver;
  16506. module.exports = function(Promise) {
  16507. var returner = function Promise$_returner() {
  16508. return this;
  16509. };
  16510. var thrower = function Promise$_thrower() {
  16511. throw this;
  16512. };
  16513. var wrapper = function Promise$_wrapper(value, action) {
  16514. if (action === 1) {
  16515. return function Promise$_thrower() {
  16516. throw value;
  16517. };
  16518. }
  16519. else if (action === 2) {
  16520. return function Promise$_returner() {
  16521. return value;
  16522. };
  16523. }
  16524. };
  16525. Promise.prototype["return"] =
  16526. Promise.prototype.thenReturn =
  16527. function Promise$thenReturn(value) {
  16528. if (wrapsPrimitiveReceiver && isPrimitive(value)) {
  16529. return this._then(
  16530. wrapper(value, 2),
  16531. void 0,
  16532. void 0,
  16533. void 0,
  16534. void 0
  16535. );
  16536. }
  16537. return this._then(returner, void 0, void 0, value, void 0);
  16538. };
  16539. Promise.prototype["throw"] =
  16540. Promise.prototype.thenThrow =
  16541. function Promise$thenThrow(reason) {
  16542. if (wrapsPrimitiveReceiver && isPrimitive(reason)) {
  16543. return this._then(
  16544. wrapper(reason, 1),
  16545. void 0,
  16546. void 0,
  16547. void 0,
  16548. void 0
  16549. );
  16550. }
  16551. return this._then(thrower, void 0, void 0, reason, void 0);
  16552. };
  16553. };
  16554. },{"./util.js":108}],80:[function(_dereq_,module,exports){
  16555. /**
  16556. * Copyright (c) 2014 Petka Antonov
  16557. *
  16558. * Permission is hereby granted, free of charge, to any person obtaining a copy
  16559. * of this software and associated documentation files (the "Software"), to deal
  16560. * in the Software without restriction, including without limitation the rights
  16561. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  16562. * copies of the Software, and to permit persons to whom the Software is
  16563. * furnished to do so, subject to the following conditions:</p>
  16564. *
  16565. * The above copyright notice and this permission notice shall be included in
  16566. * all copies or substantial portions of the Software.
  16567. *
  16568. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16569. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16570. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16571. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16572. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16573. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  16574. * THE SOFTWARE.
  16575. *
  16576. */
  16577. "use strict";
  16578. var global = _dereq_("./global.js");
  16579. var Objectfreeze = _dereq_("./es5.js").freeze;
  16580. var util = _dereq_("./util.js");
  16581. var inherits = util.inherits;
  16582. var notEnumerableProp = util.notEnumerableProp;
  16583. var Error = global.Error;
  16584. function markAsOriginatingFromRejection(e) {
  16585. try {
  16586. notEnumerableProp(e, "isAsync", true);
  16587. }
  16588. catch(ignore) {}
  16589. }
  16590. function originatesFromRejection(e) {
  16591. if (e == null) return false;
  16592. return ((e instanceof RejectionError) ||
  16593. e["isAsync"] === true);
  16594. }
  16595. function isError(obj) {
  16596. return obj instanceof Error;
  16597. }
  16598. function canAttach(obj) {
  16599. return isError(obj);
  16600. }
  16601. function subError(nameProperty, defaultMessage) {
  16602. function SubError(message) {
  16603. if (!(this instanceof SubError)) return new SubError(message);
  16604. this.message = typeof message === "string" ? message : defaultMessage;
  16605. this.name = nameProperty;
  16606. if (Error.captureStackTrace) {
  16607. Error.captureStackTrace(this, this.constructor);
  16608. }
  16609. }
  16610. inherits(SubError, Error);
  16611. return SubError;
  16612. }
  16613. var TypeError = global.TypeError;
  16614. if (typeof TypeError !== "function") {
  16615. TypeError = subError("TypeError", "type error");
  16616. }
  16617. var RangeError = global.RangeError;
  16618. if (typeof RangeError !== "function") {
  16619. RangeError = subError("RangeError", "range error");
  16620. }
  16621. var CancellationError = subError("CancellationError", "cancellation error");
  16622. var TimeoutError = subError("TimeoutError", "timeout error");
  16623. function RejectionError(message) {
  16624. this.name = "RejectionError";
  16625. this.message = message;
  16626. this.cause = message;
  16627. this.isAsync = true;
  16628. if (message instanceof Error) {
  16629. this.message = message.message;
  16630. this.stack = message.stack;
  16631. }
  16632. else if (Error.captureStackTrace) {
  16633. Error.captureStackTrace(this, this.constructor);
  16634. }
  16635. }
  16636. inherits(RejectionError, Error);
  16637. var key = "__BluebirdErrorTypes__";
  16638. var errorTypes = global[key];
  16639. if (!errorTypes) {
  16640. errorTypes = Objectfreeze({
  16641. CancellationError: CancellationError,
  16642. TimeoutError: TimeoutError,
  16643. RejectionError: RejectionError
  16644. });
  16645. notEnumerableProp(global, key, errorTypes);
  16646. }
  16647. module.exports = {
  16648. Error: Error,
  16649. TypeError: TypeError,
  16650. RangeError: RangeError,
  16651. CancellationError: errorTypes.CancellationError,
  16652. RejectionError: errorTypes.RejectionError,
  16653. TimeoutError: errorTypes.TimeoutError,
  16654. originatesFromRejection: originatesFromRejection,
  16655. markAsOriginatingFromRejection: markAsOriginatingFromRejection,
  16656. canAttach: canAttach
  16657. };
  16658. },{"./es5.js":82,"./global.js":86,"./util.js":108}],81:[function(_dereq_,module,exports){
  16659. /**
  16660. * Copyright (c) 2014 Petka Antonov
  16661. *
  16662. * Permission is hereby granted, free of charge, to any person obtaining a copy
  16663. * of this software and associated documentation files (the "Software"), to deal
  16664. * in the Software without restriction, including without limitation the rights
  16665. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  16666. * copies of the Software, and to permit persons to whom the Software is
  16667. * furnished to do so, subject to the following conditions:</p>
  16668. *
  16669. * The above copyright notice and this permission notice shall be included in
  16670. * all copies or substantial portions of the Software.
  16671. *
  16672. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16673. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16674. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16675. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16676. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16677. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  16678. * THE SOFTWARE.
  16679. *
  16680. */
  16681. "use strict";
  16682. module.exports = function(Promise) {
  16683. var TypeError = _dereq_('./errors.js').TypeError;
  16684. function apiRejection(msg) {
  16685. var error = new TypeError(msg);
  16686. var ret = Promise.rejected(error);
  16687. var parent = ret._peekContext();
  16688. if (parent != null) {
  16689. parent._attachExtraTrace(error);
  16690. }
  16691. return ret;
  16692. }
  16693. return apiRejection;
  16694. };
  16695. },{"./errors.js":80}],82:[function(_dereq_,module,exports){
  16696. /**
  16697. * Copyright (c) 2014 Petka Antonov
  16698. *
  16699. * Permission is hereby granted, free of charge, to any person obtaining a copy
  16700. * of this software and associated documentation files (the "Software"), to deal
  16701. * in the Software without restriction, including without limitation the rights
  16702. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  16703. * copies of the Software, and to permit persons to whom the Software is
  16704. * furnished to do so, subject to the following conditions:</p>
  16705. *
  16706. * The above copyright notice and this permission notice shall be included in
  16707. * all copies or substantial portions of the Software.
  16708. *
  16709. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16710. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16711. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16712. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16713. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16714. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  16715. * THE SOFTWARE.
  16716. *
  16717. */
  16718. var isES5 = (function(){
  16719. "use strict";
  16720. return this === void 0;
  16721. })();
  16722. if (isES5) {
  16723. module.exports = {
  16724. freeze: Object.freeze,
  16725. defineProperty: Object.defineProperty,
  16726. keys: Object.keys,
  16727. getPrototypeOf: Object.getPrototypeOf,
  16728. isArray: Array.isArray,
  16729. isES5: isES5
  16730. };
  16731. }
  16732. else {
  16733. var has = {}.hasOwnProperty;
  16734. var str = {}.toString;
  16735. var proto = {}.constructor.prototype;
  16736. var ObjectKeys = function ObjectKeys(o) {
  16737. var ret = [];
  16738. for (var key in o) {
  16739. if (has.call(o, key)) {
  16740. ret.push(key);
  16741. }
  16742. }
  16743. return ret;
  16744. }
  16745. var ObjectDefineProperty = function ObjectDefineProperty(o, key, desc) {
  16746. o[key] = desc.value;
  16747. return o;
  16748. }
  16749. var ObjectFreeze = function ObjectFreeze(obj) {
  16750. return obj;
  16751. }
  16752. var ObjectGetPrototypeOf = function ObjectGetPrototypeOf(obj) {
  16753. try {
  16754. return Object(obj).constructor.prototype;
  16755. }
  16756. catch (e) {
  16757. return proto;
  16758. }
  16759. }
  16760. var ArrayIsArray = function ArrayIsArray(obj) {
  16761. try {
  16762. return str.call(obj) === "[object Array]";
  16763. }
  16764. catch(e) {
  16765. return false;
  16766. }
  16767. }
  16768. module.exports = {
  16769. isArray: ArrayIsArray,
  16770. keys: ObjectKeys,
  16771. defineProperty: ObjectDefineProperty,
  16772. freeze: ObjectFreeze,
  16773. getPrototypeOf: ObjectGetPrototypeOf,
  16774. isES5: isES5
  16775. };
  16776. }
  16777. },{}],83:[function(_dereq_,module,exports){
  16778. /**
  16779. * Copyright (c) 2014 Petka Antonov
  16780. *
  16781. * Permission is hereby granted, free of charge, to any person obtaining a copy
  16782. * of this software and associated documentation files (the "Software"), to deal
  16783. * in the Software without restriction, including without limitation the rights
  16784. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  16785. * copies of the Software, and to permit persons to whom the Software is
  16786. * furnished to do so, subject to the following conditions:</p>
  16787. *
  16788. * The above copyright notice and this permission notice shall be included in
  16789. * all copies or substantial portions of the Software.
  16790. *
  16791. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16792. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16793. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16794. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16795. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16796. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  16797. * THE SOFTWARE.
  16798. *
  16799. */
  16800. "use strict";
  16801. module.exports = function(Promise) {
  16802. var isArray = _dereq_("./util.js").isArray;
  16803. function Promise$_filter(booleans) {
  16804. var values = this instanceof Promise ? this._settledValue : this;
  16805. var len = values.length;
  16806. var ret = new Array(len);
  16807. var j = 0;
  16808. for (var i = 0; i < len; ++i) {
  16809. if (booleans[i]) ret[j++] = values[i];
  16810. }
  16811. ret.length = j;
  16812. return ret;
  16813. }
  16814. var ref = {ref: null};
  16815. Promise.filter = function Promise$Filter(promises, fn) {
  16816. return Promise.map(promises, fn, ref)
  16817. ._then(Promise$_filter, void 0, void 0, ref.ref, void 0);
  16818. };
  16819. Promise.prototype.filter = function Promise$filter(fn) {
  16820. return this.map(fn, ref)
  16821. ._then(Promise$_filter, void 0, void 0, ref.ref, void 0);
  16822. };
  16823. };
  16824. },{"./util.js":108}],84:[function(_dereq_,module,exports){
  16825. /**
  16826. * Copyright (c) 2014 Petka Antonov
  16827. *
  16828. * Permission is hereby granted, free of charge, to any person obtaining a copy
  16829. * of this software and associated documentation files (the "Software"), to deal
  16830. * in the Software without restriction, including without limitation the rights
  16831. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  16832. * copies of the Software, and to permit persons to whom the Software is
  16833. * furnished to do so, subject to the following conditions:</p>
  16834. *
  16835. * The above copyright notice and this permission notice shall be included in
  16836. * all copies or substantial portions of the Software.
  16837. *
  16838. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16839. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16840. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16841. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16842. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16843. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  16844. * THE SOFTWARE.
  16845. *
  16846. */
  16847. "use strict";
  16848. module.exports = function(Promise, NEXT_FILTER) {
  16849. var util = _dereq_("./util.js");
  16850. var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver;
  16851. var isPrimitive = util.isPrimitive;
  16852. var thrower = util.thrower;
  16853. function returnThis() {
  16854. return this;
  16855. }
  16856. function throwThis() {
  16857. throw this;
  16858. }
  16859. function return$(r) {
  16860. return function Promise$_returner() {
  16861. return r;
  16862. };
  16863. }
  16864. function throw$(r) {
  16865. return function Promise$_thrower() {
  16866. throw r;
  16867. };
  16868. }
  16869. function promisedFinally(ret, reasonOrValue, isFulfilled) {
  16870. var then;
  16871. if (wrapsPrimitiveReceiver && isPrimitive(reasonOrValue)) {
  16872. then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue);
  16873. }
  16874. else {
  16875. then = isFulfilled ? returnThis : throwThis;
  16876. }
  16877. return ret._then(then, thrower, void 0, reasonOrValue, void 0);
  16878. }
  16879. function finallyHandler(reasonOrValue) {
  16880. var promise = this.promise;
  16881. var handler = this.handler;
  16882. var ret = promise._isBound()
  16883. ? handler.call(promise._boundTo)
  16884. : handler();
  16885. if (ret !== void 0) {
  16886. var maybePromise = Promise._cast(ret, void 0);
  16887. if (maybePromise instanceof Promise) {
  16888. return promisedFinally(maybePromise, reasonOrValue,
  16889. promise.isFulfilled());
  16890. }
  16891. }
  16892. if (promise.isRejected()) {
  16893. NEXT_FILTER.e = reasonOrValue;
  16894. return NEXT_FILTER;
  16895. }
  16896. else {
  16897. return reasonOrValue;
  16898. }
  16899. }
  16900. function tapHandler(value) {
  16901. var promise = this.promise;
  16902. var handler = this.handler;
  16903. var ret = promise._isBound()
  16904. ? handler.call(promise._boundTo, value)
  16905. : handler(value);
  16906. if (ret !== void 0) {
  16907. var maybePromise = Promise._cast(ret, void 0);
  16908. if (maybePromise instanceof Promise) {
  16909. return promisedFinally(maybePromise, value, true);
  16910. }
  16911. }
  16912. return value;
  16913. }
  16914. Promise.prototype._passThroughHandler =
  16915. function Promise$_passThroughHandler(handler, isFinally) {
  16916. if (typeof handler !== "function") return this.then();
  16917. var promiseAndHandler = {
  16918. promise: this,
  16919. handler: handler
  16920. };
  16921. return this._then(
  16922. isFinally ? finallyHandler : tapHandler,
  16923. isFinally ? finallyHandler : void 0, void 0,
  16924. promiseAndHandler, void 0);
  16925. };
  16926. Promise.prototype.lastly =
  16927. Promise.prototype["finally"] = function Promise$finally(handler) {
  16928. return this._passThroughHandler(handler, true);
  16929. };
  16930. Promise.prototype.tap = function Promise$tap(handler) {
  16931. return this._passThroughHandler(handler, false);
  16932. };
  16933. };
  16934. },{"./util.js":108}],85:[function(_dereq_,module,exports){
  16935. /**
  16936. * Copyright (c) 2014 Petka Antonov
  16937. *
  16938. * Permission is hereby granted, free of charge, to any person obtaining a copy
  16939. * of this software and associated documentation files (the "Software"), to deal
  16940. * in the Software without restriction, including without limitation the rights
  16941. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  16942. * copies of the Software, and to permit persons to whom the Software is
  16943. * furnished to do so, subject to the following conditions:</p>
  16944. *
  16945. * The above copyright notice and this permission notice shall be included in
  16946. * all copies or substantial portions of the Software.
  16947. *
  16948. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16949. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16950. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16951. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16952. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16953. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  16954. * THE SOFTWARE.
  16955. *
  16956. */
  16957. "use strict";
  16958. module.exports = function(Promise, apiRejection, INTERNAL) {
  16959. var PromiseSpawn = _dereq_("./promise_spawn.js")(Promise, INTERNAL);
  16960. var errors = _dereq_("./errors.js");
  16961. var TypeError = errors.TypeError;
  16962. var deprecated = _dereq_("./util.js").deprecated;
  16963. Promise.coroutine = function Promise$Coroutine(generatorFunction) {
  16964. if (typeof generatorFunction !== "function") {
  16965. throw new TypeError("generatorFunction must be a function");
  16966. }
  16967. var PromiseSpawn$ = PromiseSpawn;
  16968. return function () {
  16969. var generator = generatorFunction.apply(this, arguments);
  16970. var spawn = new PromiseSpawn$(void 0, void 0);
  16971. spawn._generator = generator;
  16972. spawn._next(void 0);
  16973. return spawn.promise();
  16974. };
  16975. };
  16976. Promise.coroutine.addYieldHandler = PromiseSpawn.addYieldHandler;
  16977. Promise.spawn = function Promise$Spawn(generatorFunction) {
  16978. deprecated("Promise.spawn is deprecated. Use Promise.coroutine instead.");
  16979. if (typeof generatorFunction !== "function") {
  16980. return apiRejection("generatorFunction must be a function");
  16981. }
  16982. var spawn = new PromiseSpawn(generatorFunction, this);
  16983. var ret = spawn.promise();
  16984. spawn._run(Promise.spawn);
  16985. return ret;
  16986. };
  16987. };
  16988. },{"./errors.js":80,"./promise_spawn.js":93,"./util.js":108}],86:[function(_dereq_,module,exports){
  16989. (function (global){
  16990. /**
  16991. * Copyright (c) 2014 Petka Antonov
  16992. *
  16993. * Permission is hereby granted, free of charge, to any person obtaining a copy
  16994. * of this software and associated documentation files (the "Software"), to deal
  16995. * in the Software without restriction, including without limitation the rights
  16996. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  16997. * copies of the Software, and to permit persons to whom the Software is
  16998. * furnished to do so, subject to the following conditions:</p>
  16999. *
  17000. * The above copyright notice and this permission notice shall be included in
  17001. * all copies or substantial portions of the Software.
  17002. *
  17003. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17004. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17005. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17006. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17007. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17008. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17009. * THE SOFTWARE.
  17010. *
  17011. */
  17012. module.exports = (function() {
  17013. if (this !== void 0) return this;
  17014. try {return global;}
  17015. catch(e) {}
  17016. try {return window;}
  17017. catch(e) {}
  17018. try {return self;}
  17019. catch(e) {}
  17020. })();
  17021. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  17022. },{}],87:[function(_dereq_,module,exports){
  17023. /**
  17024. * Copyright (c) 2014 Petka Antonov
  17025. *
  17026. * Permission is hereby granted, free of charge, to any person obtaining a copy
  17027. * of this software and associated documentation files (the "Software"), to deal
  17028. * in the Software without restriction, including without limitation the rights
  17029. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17030. * copies of the Software, and to permit persons to whom the Software is
  17031. * furnished to do so, subject to the following conditions:</p>
  17032. *
  17033. * The above copyright notice and this permission notice shall be included in
  17034. * all copies or substantial portions of the Software.
  17035. *
  17036. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17037. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17038. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17039. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17040. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17041. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17042. * THE SOFTWARE.
  17043. *
  17044. */
  17045. "use strict";
  17046. module.exports = function(Promise, PromiseArray, INTERNAL, apiRejection) {
  17047. var all = Promise.all;
  17048. var util = _dereq_("./util.js");
  17049. var canAttach = _dereq_("./errors.js").canAttach;
  17050. var isArray = util.isArray;
  17051. var _cast = Promise._cast;
  17052. function unpack(values) {
  17053. return Promise$_Map(values, this[0], this[1], this[2]);
  17054. }
  17055. function Promise$_Map(promises, fn, useBound, ref) {
  17056. if (typeof fn !== "function") {
  17057. return apiRejection("fn must be a function");
  17058. }
  17059. var receiver = void 0;
  17060. if (useBound === true) {
  17061. if (promises._isBound()) {
  17062. receiver = promises._boundTo;
  17063. }
  17064. }
  17065. else if (useBound !== false) {
  17066. receiver = useBound;
  17067. }
  17068. var shouldUnwrapItems = ref !== void 0;
  17069. if (shouldUnwrapItems) ref.ref = promises;
  17070. if (promises instanceof Promise) {
  17071. var pack = [fn, receiver, ref];
  17072. return promises._then(unpack, void 0, void 0, pack, void 0);
  17073. }
  17074. else if (!isArray(promises)) {
  17075. return apiRejection("expecting an array, a promise or a thenable");
  17076. }
  17077. var promise = new Promise(INTERNAL);
  17078. if (receiver !== void 0) promise._setBoundTo(receiver);
  17079. promise._setTrace(void 0);
  17080. var mapping = new Mapping(promise,
  17081. fn,
  17082. promises,
  17083. receiver,
  17084. shouldUnwrapItems);
  17085. mapping.init();
  17086. return promise;
  17087. }
  17088. var pending = {};
  17089. function Mapping(promise, callback, items, receiver, shouldUnwrapItems) {
  17090. this.shouldUnwrapItems = shouldUnwrapItems;
  17091. this.index = 0;
  17092. this.items = items;
  17093. this.callback = callback;
  17094. this.receiver = receiver;
  17095. this.promise = promise;
  17096. this.result = new Array(items.length);
  17097. }
  17098. util.inherits(Mapping, PromiseArray);
  17099. Mapping.prototype.init = function Mapping$init() {
  17100. var items = this.items;
  17101. var len = items.length;
  17102. var result = this.result;
  17103. var isRejected = false;
  17104. for (var i = 0; i < len; ++i) {
  17105. var maybePromise = _cast(items[i], void 0);
  17106. if (maybePromise instanceof Promise) {
  17107. if (maybePromise.isPending()) {
  17108. result[i] = pending;
  17109. maybePromise._proxyPromiseArray(this, i);
  17110. }
  17111. else if (maybePromise.isFulfilled()) {
  17112. result[i] = maybePromise.value();
  17113. }
  17114. else {
  17115. maybePromise._unsetRejectionIsUnhandled();
  17116. if (!isRejected) {
  17117. this.reject(maybePromise.reason());
  17118. isRejected = true;
  17119. }
  17120. }
  17121. }
  17122. else {
  17123. result[i] = maybePromise;
  17124. }
  17125. }
  17126. if (!isRejected) this.iterate();
  17127. };
  17128. Mapping.prototype.isResolved = function Mapping$isResolved() {
  17129. return this.promise === null;
  17130. };
  17131. Mapping.prototype._promiseProgressed =
  17132. function Mapping$_promiseProgressed(value) {
  17133. if (this.isResolved()) return;
  17134. this.promise._progress(value);
  17135. };
  17136. Mapping.prototype._promiseFulfilled =
  17137. function Mapping$_promiseFulfilled(value, index) {
  17138. if (this.isResolved()) return;
  17139. this.result[index] = value;
  17140. if (this.shouldUnwrapItems) this.items[index] = value;
  17141. if (this.index === index) this.iterate();
  17142. };
  17143. Mapping.prototype._promiseRejected =
  17144. function Mapping$_promiseRejected(reason) {
  17145. this.reject(reason);
  17146. };
  17147. Mapping.prototype.reject = function Mapping$reject(reason) {
  17148. if (this.isResolved()) return;
  17149. var trace = canAttach(reason) ? reason : new Error(reason + "");
  17150. this.promise._attachExtraTrace(trace);
  17151. this.promise._reject(reason, trace);
  17152. };
  17153. Mapping.prototype.iterate = function Mapping$iterate() {
  17154. var i = this.index;
  17155. var items = this.items;
  17156. var result = this.result;
  17157. var len = items.length;
  17158. var result = this.result;
  17159. var receiver = this.receiver;
  17160. var callback = this.callback;
  17161. for (; i < len; ++i) {
  17162. var value = result[i];
  17163. if (value === pending) {
  17164. this.index = i;
  17165. return;
  17166. }
  17167. try { result[i] = callback.call(receiver, value, i, len); }
  17168. catch (e) { return this.reject(e); }
  17169. }
  17170. this.promise._follow(all(result));
  17171. this.items = this.result = this.callback = this.promise = null;
  17172. };
  17173. Promise.prototype.map = function Promise$map(fn, ref) {
  17174. return Promise$_Map(this, fn, true, ref);
  17175. };
  17176. Promise.map = function Promise$Map(promises, fn, ref) {
  17177. return Promise$_Map(promises, fn, false, ref);
  17178. };
  17179. };
  17180. },{"./errors.js":80,"./util.js":108}],88:[function(_dereq_,module,exports){
  17181. /**
  17182. * Copyright (c) 2014 Petka Antonov
  17183. *
  17184. * Permission is hereby granted, free of charge, to any person obtaining a copy
  17185. * of this software and associated documentation files (the "Software"), to deal
  17186. * in the Software without restriction, including without limitation the rights
  17187. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17188. * copies of the Software, and to permit persons to whom the Software is
  17189. * furnished to do so, subject to the following conditions:</p>
  17190. *
  17191. * The above copyright notice and this permission notice shall be included in
  17192. * all copies or substantial portions of the Software.
  17193. *
  17194. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17195. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17196. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17197. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17198. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17199. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17200. * THE SOFTWARE.
  17201. *
  17202. */
  17203. "use strict";
  17204. module.exports = function(Promise) {
  17205. var util = _dereq_("./util.js");
  17206. var async = _dereq_("./async.js");
  17207. var tryCatch2 = util.tryCatch2;
  17208. var tryCatch1 = util.tryCatch1;
  17209. var errorObj = util.errorObj;
  17210. function thrower(r) {
  17211. throw r;
  17212. }
  17213. function Promise$_successAdapter(val, receiver) {
  17214. var nodeback = this;
  17215. var ret = val === void 0
  17216. ? tryCatch1(nodeback, receiver, null)
  17217. : tryCatch2(nodeback, receiver, null, val);
  17218. if (ret === errorObj) {
  17219. async.invokeLater(thrower, void 0, ret.e);
  17220. }
  17221. }
  17222. function Promise$_errorAdapter(reason, receiver) {
  17223. var nodeback = this;
  17224. var ret = tryCatch1(nodeback, receiver, reason);
  17225. if (ret === errorObj) {
  17226. async.invokeLater(thrower, void 0, ret.e);
  17227. }
  17228. }
  17229. Promise.prototype.nodeify = function Promise$nodeify(nodeback) {
  17230. if (typeof nodeback == "function") {
  17231. this._then(
  17232. Promise$_successAdapter,
  17233. Promise$_errorAdapter,
  17234. void 0,
  17235. nodeback,
  17236. this._isBound() ? this._boundTo : null
  17237. );
  17238. }
  17239. return this;
  17240. };
  17241. };
  17242. },{"./async.js":73,"./util.js":108}],89:[function(_dereq_,module,exports){
  17243. /**
  17244. * Copyright (c) 2014 Petka Antonov
  17245. *
  17246. * Permission is hereby granted, free of charge, to any person obtaining a copy
  17247. * of this software and associated documentation files (the "Software"), to deal
  17248. * in the Software without restriction, including without limitation the rights
  17249. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17250. * copies of the Software, and to permit persons to whom the Software is
  17251. * furnished to do so, subject to the following conditions:</p>
  17252. *
  17253. * The above copyright notice and this permission notice shall be included in
  17254. * all copies or substantial portions of the Software.
  17255. *
  17256. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17257. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17258. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17259. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17260. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17261. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17262. * THE SOFTWARE.
  17263. *
  17264. */
  17265. "use strict";
  17266. module.exports = function(Promise, isPromiseArrayProxy) {
  17267. var util = _dereq_("./util.js");
  17268. var async = _dereq_("./async.js");
  17269. var errors = _dereq_("./errors.js");
  17270. var tryCatch1 = util.tryCatch1;
  17271. var errorObj = util.errorObj;
  17272. Promise.prototype.progressed = function Promise$progressed(handler) {
  17273. return this._then(void 0, void 0, handler, void 0, void 0);
  17274. };
  17275. Promise.prototype._progress = function Promise$_progress(progressValue) {
  17276. if (this._isFollowingOrFulfilledOrRejected()) return;
  17277. this._progressUnchecked(progressValue);
  17278. };
  17279. Promise.prototype._progressHandlerAt =
  17280. function Promise$_progressHandlerAt(index) {
  17281. if (index === 0) return this._progressHandler0;
  17282. return this[index + 2 - 5];
  17283. };
  17284. Promise.prototype._doProgressWith =
  17285. function Promise$_doProgressWith(progression) {
  17286. var progressValue = progression.value;
  17287. var handler = progression.handler;
  17288. var promise = progression.promise;
  17289. var receiver = progression.receiver;
  17290. this._pushContext();
  17291. var ret = tryCatch1(handler, receiver, progressValue);
  17292. this._popContext();
  17293. if (ret === errorObj) {
  17294. if (ret.e != null &&
  17295. ret.e.name !== "StopProgressPropagation") {
  17296. var trace = errors.canAttach(ret.e)
  17297. ? ret.e : new Error(ret.e + "");
  17298. promise._attachExtraTrace(trace);
  17299. promise._progress(ret.e);
  17300. }
  17301. }
  17302. else if (ret instanceof Promise) {
  17303. ret._then(promise._progress, null, null, promise, void 0);
  17304. }
  17305. else {
  17306. promise._progress(ret);
  17307. }
  17308. };
  17309. Promise.prototype._progressUnchecked =
  17310. function Promise$_progressUnchecked(progressValue) {
  17311. if (!this.isPending()) return;
  17312. var len = this._length();
  17313. var progress = this._progress;
  17314. for (var i = 0; i < len; i += 5) {
  17315. var handler = this._progressHandlerAt(i);
  17316. var promise = this._promiseAt(i);
  17317. if (!(promise instanceof Promise)) {
  17318. var receiver = this._receiverAt(i);
  17319. if (typeof handler === "function") {
  17320. handler.call(receiver, progressValue, promise);
  17321. }
  17322. else if (receiver instanceof Promise && receiver._isProxied()) {
  17323. receiver._progressUnchecked(progressValue);
  17324. }
  17325. else if (isPromiseArrayProxy(receiver, promise)) {
  17326. receiver._promiseProgressed(progressValue, promise);
  17327. }
  17328. continue;
  17329. }
  17330. if (typeof handler === "function") {
  17331. async.invoke(this._doProgressWith, this, {
  17332. handler: handler,
  17333. promise: promise,
  17334. receiver: this._receiverAt(i),
  17335. value: progressValue
  17336. });
  17337. }
  17338. else {
  17339. async.invoke(progress, promise, progressValue);
  17340. }
  17341. }
  17342. };
  17343. };
  17344. },{"./async.js":73,"./errors.js":80,"./util.js":108}],90:[function(_dereq_,module,exports){
  17345. (function (process){
  17346. /**
  17347. * Copyright (c) 2014 Petka Antonov
  17348. *
  17349. * Permission is hereby granted, free of charge, to any person obtaining a copy
  17350. * of this software and associated documentation files (the "Software"), to deal
  17351. * in the Software without restriction, including without limitation the rights
  17352. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17353. * copies of the Software, and to permit persons to whom the Software is
  17354. * furnished to do so, subject to the following conditions:</p>
  17355. *
  17356. * The above copyright notice and this permission notice shall be included in
  17357. * all copies or substantial portions of the Software.
  17358. *
  17359. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17360. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17361. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17362. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17363. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17364. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17365. * THE SOFTWARE.
  17366. *
  17367. */
  17368. "use strict";
  17369. module.exports = function() {
  17370. var global = _dereq_("./global.js");
  17371. var util = _dereq_("./util.js");
  17372. var async = _dereq_("./async.js");
  17373. var errors = _dereq_("./errors.js");
  17374. var INTERNAL = function(){};
  17375. var APPLY = {};
  17376. var NEXT_FILTER = {e: null};
  17377. var PromiseArray = _dereq_("./promise_array.js")(Promise, INTERNAL);
  17378. var CapturedTrace = _dereq_("./captured_trace.js")();
  17379. var CatchFilter = _dereq_("./catch_filter.js")(NEXT_FILTER);
  17380. var PromiseResolver = _dereq_("./promise_resolver.js");
  17381. var isArray = util.isArray;
  17382. var errorObj = util.errorObj;
  17383. var tryCatch1 = util.tryCatch1;
  17384. var tryCatch2 = util.tryCatch2;
  17385. var tryCatchApply = util.tryCatchApply;
  17386. var RangeError = errors.RangeError;
  17387. var TypeError = errors.TypeError;
  17388. var CancellationError = errors.CancellationError;
  17389. var TimeoutError = errors.TimeoutError;
  17390. var RejectionError = errors.RejectionError;
  17391. var originatesFromRejection = errors.originatesFromRejection;
  17392. var markAsOriginatingFromRejection = errors.markAsOriginatingFromRejection;
  17393. var canAttach = errors.canAttach;
  17394. var thrower = util.thrower;
  17395. var apiRejection = _dereq_("./errors_api_rejection")(Promise);
  17396. var makeSelfResolutionError = function Promise$_makeSelfResolutionError() {
  17397. return new TypeError("circular promise resolution chain");
  17398. };
  17399. function isPromise(obj) {
  17400. if (obj === void 0) return false;
  17401. return obj instanceof Promise;
  17402. }
  17403. function isPromiseArrayProxy(receiver, promiseSlotValue) {
  17404. if (receiver instanceof PromiseArray) {
  17405. return promiseSlotValue >= 0;
  17406. }
  17407. return false;
  17408. }
  17409. function Promise(resolver) {
  17410. if (typeof resolver !== "function") {
  17411. throw new TypeError("the promise constructor requires a resolver function");
  17412. }
  17413. if (this.constructor !== Promise) {
  17414. throw new TypeError("the promise constructor cannot be invoked directly");
  17415. }
  17416. this._bitField = 0;
  17417. this._fulfillmentHandler0 = void 0;
  17418. this._rejectionHandler0 = void 0;
  17419. this._promise0 = void 0;
  17420. this._receiver0 = void 0;
  17421. this._settledValue = void 0;
  17422. this._boundTo = void 0;
  17423. if (resolver !== INTERNAL) this._resolveFromResolver(resolver);
  17424. }
  17425. Promise.prototype.bind = function Promise$bind(thisArg) {
  17426. var ret = new Promise(INTERNAL);
  17427. ret._setTrace(this);
  17428. ret._follow(this);
  17429. ret._setBoundTo(thisArg);
  17430. if (this._cancellable()) {
  17431. ret._setCancellable();
  17432. ret._cancellationParent = this;
  17433. }
  17434. return ret;
  17435. };
  17436. Promise.prototype.toString = function Promise$toString() {
  17437. return "[object Promise]";
  17438. };
  17439. Promise.prototype.caught = Promise.prototype["catch"] =
  17440. function Promise$catch(fn) {
  17441. var len = arguments.length;
  17442. if (len > 1) {
  17443. var catchInstances = new Array(len - 1),
  17444. j = 0, i;
  17445. for (i = 0; i < len - 1; ++i) {
  17446. var item = arguments[i];
  17447. if (typeof item === "function") {
  17448. catchInstances[j++] = item;
  17449. }
  17450. else {
  17451. var catchFilterTypeError =
  17452. new TypeError(
  17453. "A catch filter must be an error constructor "
  17454. + "or a filter function");
  17455. this._attachExtraTrace(catchFilterTypeError);
  17456. async.invoke(this._reject, this, catchFilterTypeError);
  17457. return;
  17458. }
  17459. }
  17460. catchInstances.length = j;
  17461. fn = arguments[i];
  17462. this._resetTrace();
  17463. var catchFilter = new CatchFilter(catchInstances, fn, this);
  17464. return this._then(void 0, catchFilter.doFilter, void 0,
  17465. catchFilter, void 0);
  17466. }
  17467. return this._then(void 0, fn, void 0, void 0, void 0);
  17468. };
  17469. Promise.prototype.then =
  17470. function Promise$then(didFulfill, didReject, didProgress) {
  17471. return this._then(didFulfill, didReject, didProgress,
  17472. void 0, void 0);
  17473. };
  17474. Promise.prototype.done =
  17475. function Promise$done(didFulfill, didReject, didProgress) {
  17476. var promise = this._then(didFulfill, didReject, didProgress,
  17477. void 0, void 0);
  17478. promise._setIsFinal();
  17479. };
  17480. Promise.prototype.spread = function Promise$spread(didFulfill, didReject) {
  17481. return this._then(didFulfill, didReject, void 0,
  17482. APPLY, void 0);
  17483. };
  17484. Promise.prototype.isCancellable = function Promise$isCancellable() {
  17485. return !this.isResolved() &&
  17486. this._cancellable();
  17487. };
  17488. Promise.prototype.toJSON = function Promise$toJSON() {
  17489. var ret = {
  17490. isFulfilled: false,
  17491. isRejected: false,
  17492. fulfillmentValue: void 0,
  17493. rejectionReason: void 0
  17494. };
  17495. if (this.isFulfilled()) {
  17496. ret.fulfillmentValue = this._settledValue;
  17497. ret.isFulfilled = true;
  17498. }
  17499. else if (this.isRejected()) {
  17500. ret.rejectionReason = this._settledValue;
  17501. ret.isRejected = true;
  17502. }
  17503. return ret;
  17504. };
  17505. Promise.prototype.all = function Promise$all() {
  17506. return Promise$_all(this, true);
  17507. };
  17508. Promise.is = isPromise;
  17509. function Promise$_all(promises, useBound) {
  17510. return Promise$_CreatePromiseArray(
  17511. promises,
  17512. PromiseArray,
  17513. useBound === true && promises._isBound()
  17514. ? promises._boundTo
  17515. : void 0
  17516. ).promise();
  17517. }
  17518. Promise.all = function Promise$All(promises) {
  17519. return Promise$_all(promises, false);
  17520. };
  17521. Promise.join = function Promise$Join() {
  17522. var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];}
  17523. return Promise$_CreatePromiseArray(args, PromiseArray, void 0).promise();
  17524. };
  17525. Promise.resolve = Promise.fulfilled =
  17526. function Promise$Resolve(value) {
  17527. var ret = new Promise(INTERNAL);
  17528. ret._setTrace(void 0);
  17529. if (ret._tryFollow(value)) {
  17530. return ret;
  17531. }
  17532. ret._cleanValues();
  17533. ret._setFulfilled();
  17534. ret._settledValue = value;
  17535. return ret;
  17536. };
  17537. Promise.reject = Promise.rejected = function Promise$Reject(reason) {
  17538. var ret = new Promise(INTERNAL);
  17539. ret._setTrace(void 0);
  17540. markAsOriginatingFromRejection(reason);
  17541. ret._cleanValues();
  17542. ret._setRejected();
  17543. ret._settledValue = reason;
  17544. if (!canAttach(reason)) {
  17545. var trace = new Error(reason + "");
  17546. ret._setCarriedStackTrace(trace);
  17547. }
  17548. ret._ensurePossibleRejectionHandled();
  17549. return ret;
  17550. };
  17551. Promise.prototype.error = function Promise$_error(fn) {
  17552. return this.caught(originatesFromRejection, fn);
  17553. };
  17554. Promise.prototype._resolveFromSyncValue =
  17555. function Promise$_resolveFromSyncValue(value) {
  17556. if (value === errorObj) {
  17557. this._cleanValues();
  17558. this._setRejected();
  17559. this._settledValue = value.e;
  17560. this._ensurePossibleRejectionHandled();
  17561. }
  17562. else {
  17563. var maybePromise = Promise._cast(value, void 0);
  17564. if (maybePromise instanceof Promise) {
  17565. this._follow(maybePromise);
  17566. }
  17567. else {
  17568. this._cleanValues();
  17569. this._setFulfilled();
  17570. this._settledValue = value;
  17571. }
  17572. }
  17573. };
  17574. Promise.method = function Promise$_Method(fn) {
  17575. if (typeof fn !== "function") {
  17576. throw new TypeError("fn must be a function");
  17577. }
  17578. return function Promise$_method() {
  17579. var value;
  17580. switch(arguments.length) {
  17581. case 0: value = tryCatch1(fn, this, void 0); break;
  17582. case 1: value = tryCatch1(fn, this, arguments[0]); break;
  17583. case 2: value = tryCatch2(fn, this, arguments[0], arguments[1]); break;
  17584. default:
  17585. var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];}
  17586. value = tryCatchApply(fn, args, this); break;
  17587. }
  17588. var ret = new Promise(INTERNAL);
  17589. ret._setTrace(void 0);
  17590. ret._resolveFromSyncValue(value);
  17591. return ret;
  17592. };
  17593. };
  17594. Promise.attempt = Promise["try"] = function Promise$_Try(fn, args, ctx) {
  17595. if (typeof fn !== "function") {
  17596. return apiRejection("fn must be a function");
  17597. }
  17598. var value = isArray(args)
  17599. ? tryCatchApply(fn, args, ctx)
  17600. : tryCatch1(fn, ctx, args);
  17601. var ret = new Promise(INTERNAL);
  17602. ret._setTrace(void 0);
  17603. ret._resolveFromSyncValue(value);
  17604. return ret;
  17605. };
  17606. Promise.defer = Promise.pending = function Promise$Defer() {
  17607. var promise = new Promise(INTERNAL);
  17608. promise._setTrace(void 0);
  17609. return new PromiseResolver(promise);
  17610. };
  17611. Promise.bind = function Promise$Bind(thisArg) {
  17612. var ret = new Promise(INTERNAL);
  17613. ret._setTrace(void 0);
  17614. ret._setFulfilled();
  17615. ret._setBoundTo(thisArg);
  17616. return ret;
  17617. };
  17618. Promise.cast = function Promise$_Cast(obj) {
  17619. var ret = Promise._cast(obj, void 0);
  17620. if (!(ret instanceof Promise)) {
  17621. return Promise.resolve(ret);
  17622. }
  17623. return ret;
  17624. };
  17625. Promise.onPossiblyUnhandledRejection =
  17626. function Promise$OnPossiblyUnhandledRejection(fn) {
  17627. CapturedTrace.possiblyUnhandledRejection = typeof fn === "function"
  17628. ? fn : void 0;
  17629. };
  17630. var unhandledRejectionHandled;
  17631. Promise.onUnhandledRejectionHandled =
  17632. function Promise$onUnhandledRejectionHandled(fn) {
  17633. unhandledRejectionHandled = typeof fn === "function" ? fn : void 0;
  17634. };
  17635. var debugging = false || !!(
  17636. typeof process !== "undefined" &&
  17637. typeof process.execPath === "string" &&
  17638. typeof process.env === "object" &&
  17639. (process.env["BLUEBIRD_DEBUG"] ||
  17640. process.env["NODE_ENV"] === "development")
  17641. );
  17642. Promise.longStackTraces = function Promise$LongStackTraces() {
  17643. if (async.haveItemsQueued() &&
  17644. debugging === false
  17645. ) {
  17646. throw new Error("cannot enable long stack traces after promises have been created");
  17647. }
  17648. debugging = CapturedTrace.isSupported();
  17649. };
  17650. Promise.hasLongStackTraces = function Promise$HasLongStackTraces() {
  17651. return debugging && CapturedTrace.isSupported();
  17652. };
  17653. Promise.prototype._setProxyHandlers =
  17654. function Promise$_setProxyHandlers(receiver, promiseSlotValue) {
  17655. var index = this._length();
  17656. if (index >= 524287 - 5) {
  17657. index = 0;
  17658. this._setLength(0);
  17659. }
  17660. if (index === 0) {
  17661. this._promise0 = promiseSlotValue;
  17662. this._receiver0 = receiver;
  17663. }
  17664. else {
  17665. var i = index - 5;
  17666. this[i + 3] = promiseSlotValue;
  17667. this[i + 4] = receiver;
  17668. this[i + 0] =
  17669. this[i + 1] =
  17670. this[i + 2] = void 0;
  17671. }
  17672. this._setLength(index + 5);
  17673. };
  17674. Promise.prototype._proxyPromiseArray =
  17675. function Promise$_proxyPromiseArray(promiseArray, index) {
  17676. this._setProxyHandlers(promiseArray, index);
  17677. };
  17678. Promise.prototype._proxyPromise = function Promise$_proxyPromise(promise) {
  17679. promise._setProxied();
  17680. this._setProxyHandlers(promise, -1);
  17681. };
  17682. Promise.prototype._then =
  17683. function Promise$_then(
  17684. didFulfill,
  17685. didReject,
  17686. didProgress,
  17687. receiver,
  17688. internalData
  17689. ) {
  17690. var haveInternalData = internalData !== void 0;
  17691. var ret = haveInternalData ? internalData : new Promise(INTERNAL);
  17692. if (debugging && !haveInternalData) {
  17693. var haveSameContext = this._peekContext() === this._traceParent;
  17694. ret._traceParent = haveSameContext ? this._traceParent : this;
  17695. ret._setTrace(this);
  17696. }
  17697. if (!haveInternalData && this._isBound()) {
  17698. ret._setBoundTo(this._boundTo);
  17699. }
  17700. var callbackIndex =
  17701. this._addCallbacks(didFulfill, didReject, didProgress, ret, receiver);
  17702. if (!haveInternalData && this._cancellable()) {
  17703. ret._setCancellable();
  17704. ret._cancellationParent = this;
  17705. }
  17706. if (this.isResolved()) {
  17707. async.invoke(this._queueSettleAt, this, callbackIndex);
  17708. }
  17709. return ret;
  17710. };
  17711. Promise.prototype._length = function Promise$_length() {
  17712. return this._bitField & 524287;
  17713. };
  17714. Promise.prototype._isFollowingOrFulfilledOrRejected =
  17715. function Promise$_isFollowingOrFulfilledOrRejected() {
  17716. return (this._bitField & 939524096) > 0;
  17717. };
  17718. Promise.prototype._isFollowing = function Promise$_isFollowing() {
  17719. return (this._bitField & 536870912) === 536870912;
  17720. };
  17721. Promise.prototype._setLength = function Promise$_setLength(len) {
  17722. this._bitField = (this._bitField & -524288) |
  17723. (len & 524287);
  17724. };
  17725. Promise.prototype._setFulfilled = function Promise$_setFulfilled() {
  17726. this._bitField = this._bitField | 268435456;
  17727. };
  17728. Promise.prototype._setRejected = function Promise$_setRejected() {
  17729. this._bitField = this._bitField | 134217728;
  17730. };
  17731. Promise.prototype._setFollowing = function Promise$_setFollowing() {
  17732. this._bitField = this._bitField | 536870912;
  17733. };
  17734. Promise.prototype._setIsFinal = function Promise$_setIsFinal() {
  17735. this._bitField = this._bitField | 33554432;
  17736. };
  17737. Promise.prototype._isFinal = function Promise$_isFinal() {
  17738. return (this._bitField & 33554432) > 0;
  17739. };
  17740. Promise.prototype._cancellable = function Promise$_cancellable() {
  17741. return (this._bitField & 67108864) > 0;
  17742. };
  17743. Promise.prototype._setCancellable = function Promise$_setCancellable() {
  17744. this._bitField = this._bitField | 67108864;
  17745. };
  17746. Promise.prototype._unsetCancellable = function Promise$_unsetCancellable() {
  17747. this._bitField = this._bitField & (~67108864);
  17748. };
  17749. Promise.prototype._setRejectionIsUnhandled =
  17750. function Promise$_setRejectionIsUnhandled() {
  17751. this._bitField = this._bitField | 2097152;
  17752. };
  17753. Promise.prototype._unsetRejectionIsUnhandled =
  17754. function Promise$_unsetRejectionIsUnhandled() {
  17755. this._bitField = this._bitField & (~2097152);
  17756. if (this._isUnhandledRejectionNotified()) {
  17757. this._unsetUnhandledRejectionIsNotified();
  17758. this._notifyUnhandledRejectionIsHandled();
  17759. }
  17760. };
  17761. Promise.prototype._isRejectionUnhandled =
  17762. function Promise$_isRejectionUnhandled() {
  17763. return (this._bitField & 2097152) > 0;
  17764. };
  17765. Promise.prototype._setUnhandledRejectionIsNotified =
  17766. function Promise$_setUnhandledRejectionIsNotified() {
  17767. this._bitField = this._bitField | 524288;
  17768. };
  17769. Promise.prototype._unsetUnhandledRejectionIsNotified =
  17770. function Promise$_unsetUnhandledRejectionIsNotified() {
  17771. this._bitField = this._bitField & (~524288);
  17772. };
  17773. Promise.prototype._isUnhandledRejectionNotified =
  17774. function Promise$_isUnhandledRejectionNotified() {
  17775. return (this._bitField & 524288) > 0;
  17776. };
  17777. Promise.prototype._setCarriedStackTrace =
  17778. function Promise$_setCarriedStackTrace(capturedTrace) {
  17779. this._bitField = this._bitField | 1048576;
  17780. this._fulfillmentHandler0 = capturedTrace;
  17781. };
  17782. Promise.prototype._unsetCarriedStackTrace =
  17783. function Promise$_unsetCarriedStackTrace() {
  17784. this._bitField = this._bitField & (~1048576);
  17785. this._fulfillmentHandler0 = void 0;
  17786. };
  17787. Promise.prototype._isCarryingStackTrace =
  17788. function Promise$_isCarryingStackTrace() {
  17789. return (this._bitField & 1048576) > 0;
  17790. };
  17791. Promise.prototype._getCarriedStackTrace =
  17792. function Promise$_getCarriedStackTrace() {
  17793. return this._isCarryingStackTrace()
  17794. ? this._fulfillmentHandler0
  17795. : void 0;
  17796. };
  17797. Promise.prototype._receiverAt = function Promise$_receiverAt(index) {
  17798. var ret;
  17799. if (index === 0) {
  17800. ret = this._receiver0;
  17801. }
  17802. else {
  17803. ret = this[index + 4 - 5];
  17804. }
  17805. if (this._isBound() && ret === void 0) {
  17806. return this._boundTo;
  17807. }
  17808. return ret;
  17809. };
  17810. Promise.prototype._promiseAt = function Promise$_promiseAt(index) {
  17811. if (index === 0) return this._promise0;
  17812. return this[index + 3 - 5];
  17813. };
  17814. Promise.prototype._fulfillmentHandlerAt =
  17815. function Promise$_fulfillmentHandlerAt(index) {
  17816. if (index === 0) return this._fulfillmentHandler0;
  17817. return this[index + 0 - 5];
  17818. };
  17819. Promise.prototype._rejectionHandlerAt =
  17820. function Promise$_rejectionHandlerAt(index) {
  17821. if (index === 0) return this._rejectionHandler0;
  17822. return this[index + 1 - 5];
  17823. };
  17824. Promise.prototype._unsetAt = function Promise$_unsetAt(index) {
  17825. if (index === 0) {
  17826. this._rejectionHandler0 =
  17827. this._progressHandler0 =
  17828. this._promise0 =
  17829. this._receiver0 = void 0;
  17830. if (!this._isCarryingStackTrace()) {
  17831. this._fulfillmentHandler0 = void 0;
  17832. }
  17833. }
  17834. else {
  17835. this[index - 5 + 0] =
  17836. this[index - 5 + 1] =
  17837. this[index - 5 + 2] =
  17838. this[index - 5 + 3] =
  17839. this[index - 5 + 4] = void 0;
  17840. }
  17841. };
  17842. Promise.prototype._resolveFromResolver =
  17843. function Promise$_resolveFromResolver(resolver) {
  17844. var promise = this;
  17845. this._setTrace(void 0);
  17846. this._pushContext();
  17847. function Promise$_resolver(val) {
  17848. if (promise._tryFollow(val)) {
  17849. return;
  17850. }
  17851. promise._fulfill(val);
  17852. }
  17853. function Promise$_rejecter(val) {
  17854. var trace = canAttach(val) ? val : new Error(val + "");
  17855. promise._attachExtraTrace(trace);
  17856. markAsOriginatingFromRejection(val);
  17857. promise._reject(val, trace === val ? void 0 : trace);
  17858. }
  17859. var r = tryCatch2(resolver, void 0, Promise$_resolver, Promise$_rejecter);
  17860. this._popContext();
  17861. if (r !== void 0 && r === errorObj) {
  17862. var e = r.e;
  17863. var trace = canAttach(e) ? e : new Error(e + "");
  17864. promise._reject(e, trace);
  17865. }
  17866. };
  17867. Promise.prototype._addCallbacks = function Promise$_addCallbacks(
  17868. fulfill,
  17869. reject,
  17870. progress,
  17871. promise,
  17872. receiver
  17873. ) {
  17874. var index = this._length();
  17875. if (index >= 524287 - 5) {
  17876. index = 0;
  17877. this._setLength(0);
  17878. }
  17879. if (index === 0) {
  17880. this._promise0 = promise;
  17881. if (receiver !== void 0) this._receiver0 = receiver;
  17882. if (typeof fulfill === "function" && !this._isCarryingStackTrace())
  17883. this._fulfillmentHandler0 = fulfill;
  17884. if (typeof reject === "function") this._rejectionHandler0 = reject;
  17885. if (typeof progress === "function") this._progressHandler0 = progress;
  17886. }
  17887. else {
  17888. var i = index - 5;
  17889. this[i + 3] = promise;
  17890. this[i + 4] = receiver;
  17891. this[i + 0] = typeof fulfill === "function"
  17892. ? fulfill : void 0;
  17893. this[i + 1] = typeof reject === "function"
  17894. ? reject : void 0;
  17895. this[i + 2] = typeof progress === "function"
  17896. ? progress : void 0;
  17897. }
  17898. this._setLength(index + 5);
  17899. return index;
  17900. };
  17901. Promise.prototype._setBoundTo = function Promise$_setBoundTo(obj) {
  17902. if (obj !== void 0) {
  17903. this._bitField = this._bitField | 8388608;
  17904. this._boundTo = obj;
  17905. }
  17906. else {
  17907. this._bitField = this._bitField & (~8388608);
  17908. }
  17909. };
  17910. Promise.prototype._isBound = function Promise$_isBound() {
  17911. return (this._bitField & 8388608) === 8388608;
  17912. };
  17913. Promise.prototype._spreadSlowCase =
  17914. function Promise$_spreadSlowCase(targetFn, promise, values, boundTo) {
  17915. var promiseForAll =
  17916. Promise$_CreatePromiseArray
  17917. (values, PromiseArray, boundTo)
  17918. .promise()
  17919. ._then(function() {
  17920. return targetFn.apply(boundTo, arguments);
  17921. }, void 0, void 0, APPLY, void 0);
  17922. promise._follow(promiseForAll);
  17923. };
  17924. Promise.prototype._callSpread =
  17925. function Promise$_callSpread(handler, promise, value, localDebugging) {
  17926. var boundTo = this._isBound() ? this._boundTo : void 0;
  17927. if (isArray(value)) {
  17928. for (var i = 0, len = value.length; i < len; ++i) {
  17929. if (isPromise(Promise._cast(value[i], void 0))) {
  17930. this._spreadSlowCase(handler, promise, value, boundTo);
  17931. return;
  17932. }
  17933. }
  17934. }
  17935. if (localDebugging) promise._pushContext();
  17936. return tryCatchApply(handler, value, boundTo);
  17937. };
  17938. Promise.prototype._callHandler =
  17939. function Promise$_callHandler(
  17940. handler, receiver, promise, value, localDebugging) {
  17941. var x;
  17942. if (receiver === APPLY && !this.isRejected()) {
  17943. x = this._callSpread(handler, promise, value, localDebugging);
  17944. }
  17945. else {
  17946. if (localDebugging) promise._pushContext();
  17947. x = tryCatch1(handler, receiver, value);
  17948. }
  17949. if (localDebugging) promise._popContext();
  17950. return x;
  17951. };
  17952. Promise.prototype._settlePromiseFromHandler =
  17953. function Promise$_settlePromiseFromHandler(
  17954. handler, receiver, value, promise
  17955. ) {
  17956. if (!isPromise(promise)) {
  17957. handler.call(receiver, value, promise);
  17958. return;
  17959. }
  17960. var localDebugging = debugging;
  17961. var x = this._callHandler(handler, receiver,
  17962. promise, value, localDebugging);
  17963. if (promise._isFollowing()) return;
  17964. if (x === errorObj || x === promise || x === NEXT_FILTER) {
  17965. var err = x === promise
  17966. ? makeSelfResolutionError()
  17967. : x.e;
  17968. var trace = canAttach(err) ? err : new Error(err + "");
  17969. if (x !== NEXT_FILTER) promise._attachExtraTrace(trace);
  17970. promise._rejectUnchecked(err, trace);
  17971. }
  17972. else {
  17973. var castValue = Promise._cast(x, promise);
  17974. if (isPromise(castValue)) {
  17975. if (castValue.isRejected() &&
  17976. !castValue._isCarryingStackTrace() &&
  17977. !canAttach(castValue._settledValue)) {
  17978. var trace = new Error(castValue._settledValue + "");
  17979. promise._attachExtraTrace(trace);
  17980. castValue._setCarriedStackTrace(trace);
  17981. }
  17982. promise._follow(castValue);
  17983. if (castValue._cancellable()) {
  17984. promise._cancellationParent = castValue;
  17985. promise._setCancellable();
  17986. }
  17987. }
  17988. else {
  17989. promise._fulfillUnchecked(x);
  17990. }
  17991. }
  17992. };
  17993. Promise.prototype._follow =
  17994. function Promise$_follow(promise) {
  17995. this._setFollowing();
  17996. if (promise.isPending()) {
  17997. if (promise._cancellable() ) {
  17998. this._cancellationParent = promise;
  17999. this._setCancellable();
  18000. }
  18001. promise._proxyPromise(this);
  18002. }
  18003. else if (promise.isFulfilled()) {
  18004. this._fulfillUnchecked(promise._settledValue);
  18005. }
  18006. else {
  18007. this._rejectUnchecked(promise._settledValue,
  18008. promise._getCarriedStackTrace());
  18009. }
  18010. if (promise._isRejectionUnhandled()) promise._unsetRejectionIsUnhandled();
  18011. if (debugging &&
  18012. promise._traceParent == null) {
  18013. promise._traceParent = this;
  18014. }
  18015. };
  18016. Promise.prototype._tryFollow =
  18017. function Promise$_tryFollow(value) {
  18018. if (this._isFollowingOrFulfilledOrRejected() ||
  18019. value === this) {
  18020. return false;
  18021. }
  18022. var maybePromise = Promise._cast(value, void 0);
  18023. if (!isPromise(maybePromise)) {
  18024. return false;
  18025. }
  18026. this._follow(maybePromise);
  18027. return true;
  18028. };
  18029. Promise.prototype._resetTrace = function Promise$_resetTrace() {
  18030. if (debugging) {
  18031. this._trace = new CapturedTrace(this._peekContext() === void 0);
  18032. }
  18033. };
  18034. Promise.prototype._setTrace = function Promise$_setTrace(parent) {
  18035. if (debugging) {
  18036. var context = this._peekContext();
  18037. this._traceParent = context;
  18038. var isTopLevel = context === void 0;
  18039. if (parent !== void 0 &&
  18040. parent._traceParent === context) {
  18041. this._trace = parent._trace;
  18042. }
  18043. else {
  18044. this._trace = new CapturedTrace(isTopLevel);
  18045. }
  18046. }
  18047. return this;
  18048. };
  18049. Promise.prototype._attachExtraTrace =
  18050. function Promise$_attachExtraTrace(error) {
  18051. if (debugging) {
  18052. var promise = this;
  18053. var stack = error.stack;
  18054. stack = typeof stack === "string"
  18055. ? stack.split("\n") : [];
  18056. var headerLineCount = 1;
  18057. while(promise != null &&
  18058. promise._trace != null) {
  18059. stack = CapturedTrace.combine(
  18060. stack,
  18061. promise._trace.stack.split("\n")
  18062. );
  18063. promise = promise._traceParent;
  18064. }
  18065. var max = Error.stackTraceLimit + headerLineCount;
  18066. var len = stack.length;
  18067. if (len > max) {
  18068. stack.length = max;
  18069. }
  18070. if (stack.length <= headerLineCount) {
  18071. error.stack = "(No stack trace)";
  18072. }
  18073. else {
  18074. error.stack = stack.join("\n");
  18075. }
  18076. }
  18077. };
  18078. Promise.prototype._cleanValues = function Promise$_cleanValues() {
  18079. if (this._cancellable()) {
  18080. this._cancellationParent = void 0;
  18081. }
  18082. };
  18083. Promise.prototype._fulfill = function Promise$_fulfill(value) {
  18084. if (this._isFollowingOrFulfilledOrRejected()) return;
  18085. this._fulfillUnchecked(value);
  18086. };
  18087. Promise.prototype._reject =
  18088. function Promise$_reject(reason, carriedStackTrace) {
  18089. if (this._isFollowingOrFulfilledOrRejected()) return;
  18090. this._rejectUnchecked(reason, carriedStackTrace);
  18091. };
  18092. Promise.prototype._settlePromiseAt = function Promise$_settlePromiseAt(index) {
  18093. var handler = this.isFulfilled()
  18094. ? this._fulfillmentHandlerAt(index)
  18095. : this._rejectionHandlerAt(index);
  18096. var value = this._settledValue;
  18097. var receiver = this._receiverAt(index);
  18098. var promise = this._promiseAt(index);
  18099. if (typeof handler === "function") {
  18100. this._settlePromiseFromHandler(handler, receiver, value, promise);
  18101. }
  18102. else {
  18103. var done = false;
  18104. var isFulfilled = this.isFulfilled();
  18105. if (receiver !== void 0) {
  18106. if (receiver instanceof Promise &&
  18107. receiver._isProxied()) {
  18108. receiver._unsetProxied();
  18109. if (isFulfilled) receiver._fulfillUnchecked(value);
  18110. else receiver._rejectUnchecked(value,
  18111. this._getCarriedStackTrace());
  18112. done = true;
  18113. }
  18114. else if (isPromiseArrayProxy(receiver, promise)) {
  18115. if (isFulfilled) receiver._promiseFulfilled(value, promise);
  18116. else receiver._promiseRejected(value, promise);
  18117. done = true;
  18118. }
  18119. }
  18120. if (!done) {
  18121. if (isFulfilled) promise._fulfill(value);
  18122. else promise._reject(value, this._getCarriedStackTrace());
  18123. }
  18124. }
  18125. if (index >= 256) {
  18126. this._queueGC();
  18127. }
  18128. };
  18129. Promise.prototype._isProxied = function Promise$_isProxied() {
  18130. return (this._bitField & 4194304) === 4194304;
  18131. };
  18132. Promise.prototype._setProxied = function Promise$_setProxied() {
  18133. this._bitField = this._bitField | 4194304;
  18134. };
  18135. Promise.prototype._unsetProxied = function Promise$_unsetProxied() {
  18136. this._bitField = this._bitField & (~4194304);
  18137. };
  18138. Promise.prototype._isGcQueued = function Promise$_isGcQueued() {
  18139. return (this._bitField & -1073741824) === -1073741824;
  18140. };
  18141. Promise.prototype._setGcQueued = function Promise$_setGcQueued() {
  18142. this._bitField = this._bitField | -1073741824;
  18143. };
  18144. Promise.prototype._unsetGcQueued = function Promise$_unsetGcQueued() {
  18145. this._bitField = this._bitField & (~-1073741824);
  18146. };
  18147. Promise.prototype._queueGC = function Promise$_queueGC() {
  18148. if (this._isGcQueued()) return;
  18149. this._setGcQueued();
  18150. async.invokeLater(this._gc, this, void 0);
  18151. };
  18152. Promise.prototype._gc = function Promise$gc() {
  18153. var len = this._length();
  18154. this._unsetAt(0);
  18155. for (var i = 0; i < len; i++) {
  18156. delete this[i];
  18157. }
  18158. this._setLength(0);
  18159. this._unsetGcQueued();
  18160. };
  18161. Promise.prototype._queueSettleAt = function Promise$_queueSettleAt(index) {
  18162. if (this._isRejectionUnhandled()) this._unsetRejectionIsUnhandled();
  18163. async.invoke(this._settlePromiseAt, this, index);
  18164. };
  18165. Promise.prototype._fulfillUnchecked =
  18166. function Promise$_fulfillUnchecked(value) {
  18167. if (!this.isPending()) return;
  18168. if (value === this) {
  18169. var err = makeSelfResolutionError();
  18170. this._attachExtraTrace(err);
  18171. return this._rejectUnchecked(err, void 0);
  18172. }
  18173. this._cleanValues();
  18174. this._setFulfilled();
  18175. this._settledValue = value;
  18176. var len = this._length();
  18177. if (len > 0) {
  18178. async.invoke(this._settlePromises, this, len);
  18179. }
  18180. };
  18181. Promise.prototype._rejectUncheckedCheckError =
  18182. function Promise$_rejectUncheckedCheckError(reason) {
  18183. var trace = canAttach(reason) ? reason : new Error(reason + "");
  18184. this._rejectUnchecked(reason, trace === reason ? void 0 : trace);
  18185. };
  18186. Promise.prototype._rejectUnchecked =
  18187. function Promise$_rejectUnchecked(reason, trace) {
  18188. if (!this.isPending()) return;
  18189. if (reason === this) {
  18190. var err = makeSelfResolutionError();
  18191. this._attachExtraTrace(err);
  18192. return this._rejectUnchecked(err);
  18193. }
  18194. this._cleanValues();
  18195. this._setRejected();
  18196. this._settledValue = reason;
  18197. if (this._isFinal()) {
  18198. async.invokeLater(thrower, void 0, trace === void 0 ? reason : trace);
  18199. return;
  18200. }
  18201. var len = this._length();
  18202. if (trace !== void 0) this._setCarriedStackTrace(trace);
  18203. if (len > 0) {
  18204. async.invoke(this._rejectPromises, this, null);
  18205. }
  18206. else {
  18207. this._ensurePossibleRejectionHandled();
  18208. }
  18209. };
  18210. Promise.prototype._rejectPromises = function Promise$_rejectPromises() {
  18211. this._settlePromises();
  18212. this._unsetCarriedStackTrace();
  18213. };
  18214. Promise.prototype._settlePromises = function Promise$_settlePromises() {
  18215. var len = this._length();
  18216. for (var i = 0; i < len; i+= 5) {
  18217. this._settlePromiseAt(i);
  18218. }
  18219. };
  18220. Promise.prototype._ensurePossibleRejectionHandled =
  18221. function Promise$_ensurePossibleRejectionHandled() {
  18222. this._setRejectionIsUnhandled();
  18223. if (CapturedTrace.possiblyUnhandledRejection !== void 0) {
  18224. async.invokeLater(this._notifyUnhandledRejection, this, void 0);
  18225. }
  18226. };
  18227. Promise.prototype._notifyUnhandledRejectionIsHandled =
  18228. function Promise$_notifyUnhandledRejectionIsHandled() {
  18229. if (typeof unhandledRejectionHandled === "function") {
  18230. async.invokeLater(unhandledRejectionHandled, void 0, this);
  18231. }
  18232. };
  18233. Promise.prototype._notifyUnhandledRejection =
  18234. function Promise$_notifyUnhandledRejection() {
  18235. if (this._isRejectionUnhandled()) {
  18236. var reason = this._settledValue;
  18237. var trace = this._getCarriedStackTrace();
  18238. this._setUnhandledRejectionIsNotified();
  18239. if (trace !== void 0) {
  18240. this._unsetCarriedStackTrace();
  18241. reason = trace;
  18242. }
  18243. if (typeof CapturedTrace.possiblyUnhandledRejection === "function") {
  18244. CapturedTrace.possiblyUnhandledRejection(reason, this);
  18245. }
  18246. }
  18247. };
  18248. var contextStack = [];
  18249. Promise.prototype._peekContext = function Promise$_peekContext() {
  18250. var lastIndex = contextStack.length - 1;
  18251. if (lastIndex >= 0) {
  18252. return contextStack[lastIndex];
  18253. }
  18254. return void 0;
  18255. };
  18256. Promise.prototype._pushContext = function Promise$_pushContext() {
  18257. if (!debugging) return;
  18258. contextStack.push(this);
  18259. };
  18260. Promise.prototype._popContext = function Promise$_popContext() {
  18261. if (!debugging) return;
  18262. contextStack.pop();
  18263. };
  18264. function Promise$_CreatePromiseArray(
  18265. promises, PromiseArrayConstructor, boundTo) {
  18266. var list = null;
  18267. if (isArray(promises)) {
  18268. list = promises;
  18269. }
  18270. else {
  18271. list = Promise._cast(promises, void 0);
  18272. if (list !== promises) {
  18273. list._setBoundTo(boundTo);
  18274. }
  18275. else if (!isPromise(list)) {
  18276. list = null;
  18277. }
  18278. }
  18279. if (list !== null) {
  18280. return new PromiseArrayConstructor(list, boundTo);
  18281. }
  18282. return {
  18283. promise: function() {return apiRejection("expecting an array, a promise or a thenable");}
  18284. };
  18285. }
  18286. var old = global.Promise;
  18287. Promise.noConflict = function() {
  18288. if (global.Promise === Promise) {
  18289. global.Promise = old;
  18290. }
  18291. return Promise;
  18292. };
  18293. if (!CapturedTrace.isSupported()) {
  18294. Promise.longStackTraces = function(){};
  18295. debugging = false;
  18296. }
  18297. Promise._makeSelfResolutionError = makeSelfResolutionError;
  18298. _dereq_("./finally.js")(Promise, NEXT_FILTER);
  18299. _dereq_("./direct_resolve.js")(Promise);
  18300. _dereq_("./thenables.js")(Promise, INTERNAL);
  18301. _dereq_("./synchronous_inspection.js")(Promise);
  18302. Promise.RangeError = RangeError;
  18303. Promise.CancellationError = CancellationError;
  18304. Promise.TimeoutError = TimeoutError;
  18305. Promise.TypeError = TypeError;
  18306. Promise.RejectionError = RejectionError;
  18307. util.toFastProperties(Promise);
  18308. util.toFastProperties(Promise.prototype);
  18309. _dereq_('./timers.js')(Promise,INTERNAL);
  18310. _dereq_('./any.js')(Promise,Promise$_CreatePromiseArray,PromiseArray);
  18311. _dereq_('./race.js')(Promise,INTERNAL);
  18312. _dereq_('./call_get.js')(Promise);
  18313. _dereq_('./filter.js')(Promise,Promise$_CreatePromiseArray,PromiseArray,apiRejection);
  18314. _dereq_('./generators.js')(Promise,apiRejection,INTERNAL);
  18315. _dereq_('./map.js')(Promise,PromiseArray,INTERNAL,apiRejection);
  18316. _dereq_('./nodeify.js')(Promise);
  18317. _dereq_('./promisify.js')(Promise,INTERNAL);
  18318. _dereq_('./props.js')(Promise,PromiseArray);
  18319. _dereq_('./reduce.js')(Promise,Promise$_CreatePromiseArray,PromiseArray,apiRejection,INTERNAL);
  18320. _dereq_('./settle.js')(Promise,Promise$_CreatePromiseArray,PromiseArray);
  18321. _dereq_('./some.js')(Promise,Promise$_CreatePromiseArray,PromiseArray,apiRejection);
  18322. _dereq_('./progress.js')(Promise,isPromiseArrayProxy);
  18323. _dereq_('./cancel.js')(Promise,INTERNAL);
  18324. Promise.prototype = Promise.prototype;
  18325. return Promise;
  18326. };
  18327. }).call(this,_dereq_("C:\\Users\\Alex\\AppData\\Roaming\\npm\\node_modules\\browserify\\node_modules\\insert-module-globals\\node_modules\\process\\browser.js"))
  18328. },{"./any.js":72,"./async.js":73,"./call_get.js":75,"./cancel.js":76,"./captured_trace.js":77,"./catch_filter.js":78,"./direct_resolve.js":79,"./errors.js":80,"./errors_api_rejection":81,"./filter.js":83,"./finally.js":84,"./generators.js":85,"./global.js":86,"./map.js":87,"./nodeify.js":88,"./progress.js":89,"./promise_array.js":91,"./promise_resolver.js":92,"./promisify.js":94,"./props.js":96,"./race.js":98,"./reduce.js":99,"./settle.js":101,"./some.js":103,"./synchronous_inspection.js":105,"./thenables.js":106,"./timers.js":107,"./util.js":108,"C:\\Users\\Alex\\AppData\\Roaming\\npm\\node_modules\\browserify\\node_modules\\insert-module-globals\\node_modules\\process\\browser.js":144}],91:[function(_dereq_,module,exports){
  18329. /**
  18330. * Copyright (c) 2014 Petka Antonov
  18331. *
  18332. * Permission is hereby granted, free of charge, to any person obtaining a copy
  18333. * of this software and associated documentation files (the "Software"), to deal
  18334. * in the Software without restriction, including without limitation the rights
  18335. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  18336. * copies of the Software, and to permit persons to whom the Software is
  18337. * furnished to do so, subject to the following conditions:</p>
  18338. *
  18339. * The above copyright notice and this permission notice shall be included in
  18340. * all copies or substantial portions of the Software.
  18341. *
  18342. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18343. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18344. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18345. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18346. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18347. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18348. * THE SOFTWARE.
  18349. *
  18350. */
  18351. "use strict";
  18352. module.exports = function(Promise, INTERNAL) {
  18353. var canAttach = _dereq_("./errors.js").canAttach;
  18354. var util = _dereq_("./util.js");
  18355. var async = _dereq_("./async.js");
  18356. var hasOwn = {}.hasOwnProperty;
  18357. var isArray = util.isArray;
  18358. function toResolutionValue(val) {
  18359. switch(val) {
  18360. case -1: return void 0;
  18361. case -2: return [];
  18362. case -3: return {};
  18363. }
  18364. }
  18365. function PromiseArray(values, boundTo) {
  18366. var promise = this._promise = new Promise(INTERNAL);
  18367. var parent = void 0;
  18368. if (values instanceof Promise) {
  18369. parent = values;
  18370. if (values._cancellable()) {
  18371. promise._setCancellable();
  18372. promise._cancellationParent = values;
  18373. }
  18374. if (values._isBound()) {
  18375. promise._setBoundTo(boundTo);
  18376. }
  18377. }
  18378. promise._setTrace(parent);
  18379. this._values = values;
  18380. this._length = 0;
  18381. this._totalResolved = 0;
  18382. this._init(void 0, -2);
  18383. }
  18384. PromiseArray.PropertiesPromiseArray = function() {};
  18385. PromiseArray.prototype.length = function PromiseArray$length() {
  18386. return this._length;
  18387. };
  18388. PromiseArray.prototype.promise = function PromiseArray$promise() {
  18389. return this._promise;
  18390. };
  18391. PromiseArray.prototype._init =
  18392. function PromiseArray$_init(_, resolveValueIfEmpty) {
  18393. var values = this._values;
  18394. if (values instanceof Promise) {
  18395. if (values.isFulfilled()) {
  18396. values = values._settledValue;
  18397. if (!isArray(values)) {
  18398. var err = new Promise.TypeError("expecting an array, a promise or a thenable");
  18399. this.__hardReject__(err);
  18400. return;
  18401. }
  18402. this._values = values;
  18403. }
  18404. else if (values.isPending()) {
  18405. values._then(
  18406. this._init,
  18407. this._reject,
  18408. void 0,
  18409. this,
  18410. resolveValueIfEmpty
  18411. );
  18412. return;
  18413. }
  18414. else {
  18415. values._unsetRejectionIsUnhandled();
  18416. this._reject(values._settledValue);
  18417. return;
  18418. }
  18419. }
  18420. if (values.length === 0) {
  18421. this._resolve(toResolutionValue(resolveValueIfEmpty));
  18422. return;
  18423. }
  18424. var len = values.length;
  18425. var newLen = len;
  18426. var newValues;
  18427. if (this instanceof PromiseArray.PropertiesPromiseArray) {
  18428. newValues = this._values;
  18429. }
  18430. else {
  18431. newValues = new Array(len);
  18432. }
  18433. var isDirectScanNeeded = false;
  18434. for (var i = 0; i < len; ++i) {
  18435. var promise = values[i];
  18436. if (promise === void 0 && !hasOwn.call(values, i)) {
  18437. newLen--;
  18438. continue;
  18439. }
  18440. var maybePromise = Promise._cast(promise, void 0);
  18441. if (maybePromise instanceof Promise) {
  18442. if (maybePromise.isPending()) {
  18443. maybePromise._proxyPromiseArray(this, i);
  18444. }
  18445. else {
  18446. maybePromise._unsetRejectionIsUnhandled();
  18447. isDirectScanNeeded = true;
  18448. }
  18449. }
  18450. else {
  18451. isDirectScanNeeded = true;
  18452. }
  18453. newValues[i] = maybePromise;
  18454. }
  18455. if (newLen === 0) {
  18456. if (resolveValueIfEmpty === -2) {
  18457. this._resolve(newValues);
  18458. }
  18459. else {
  18460. this._resolve(toResolutionValue(resolveValueIfEmpty));
  18461. }
  18462. return;
  18463. }
  18464. this._values = newValues;
  18465. this._length = newLen;
  18466. if (isDirectScanNeeded) {
  18467. var scanMethod = newLen === len
  18468. ? this._scanDirectValues
  18469. : this._scanDirectValuesHoled;
  18470. async.invoke(scanMethod, this, len);
  18471. }
  18472. };
  18473. PromiseArray.prototype._settlePromiseAt =
  18474. function PromiseArray$_settlePromiseAt(index) {
  18475. var value = this._values[index];
  18476. if (!(value instanceof Promise)) {
  18477. this._promiseFulfilled(value, index);
  18478. }
  18479. else if (value.isFulfilled()) {
  18480. this._promiseFulfilled(value._settledValue, index);
  18481. }
  18482. else if (value.isRejected()) {
  18483. this._promiseRejected(value._settledValue, index);
  18484. }
  18485. };
  18486. PromiseArray.prototype._scanDirectValuesHoled =
  18487. function PromiseArray$_scanDirectValuesHoled(len) {
  18488. for (var i = 0; i < len; ++i) {
  18489. if (this._isResolved()) {
  18490. break;
  18491. }
  18492. if (hasOwn.call(this._values, i)) {
  18493. this._settlePromiseAt(i);
  18494. }
  18495. }
  18496. };
  18497. PromiseArray.prototype._scanDirectValues =
  18498. function PromiseArray$_scanDirectValues(len) {
  18499. for (var i = 0; i < len; ++i) {
  18500. if (this._isResolved()) {
  18501. break;
  18502. }
  18503. this._settlePromiseAt(i);
  18504. }
  18505. };
  18506. PromiseArray.prototype._isResolved = function PromiseArray$_isResolved() {
  18507. return this._values === null;
  18508. };
  18509. PromiseArray.prototype._resolve = function PromiseArray$_resolve(value) {
  18510. this._values = null;
  18511. this._promise._fulfill(value);
  18512. };
  18513. PromiseArray.prototype.__hardReject__ =
  18514. PromiseArray.prototype._reject = function PromiseArray$_reject(reason) {
  18515. this._values = null;
  18516. var trace = canAttach(reason) ? reason : new Error(reason + "");
  18517. this._promise._attachExtraTrace(trace);
  18518. this._promise._reject(reason, trace);
  18519. };
  18520. PromiseArray.prototype._promiseProgressed =
  18521. function PromiseArray$_promiseProgressed(progressValue, index) {
  18522. if (this._isResolved()) return;
  18523. this._promise._progress({
  18524. index: index,
  18525. value: progressValue
  18526. });
  18527. };
  18528. PromiseArray.prototype._promiseFulfilled =
  18529. function PromiseArray$_promiseFulfilled(value, index) {
  18530. if (this._isResolved()) return;
  18531. this._values[index] = value;
  18532. var totalResolved = ++this._totalResolved;
  18533. if (totalResolved >= this._length) {
  18534. this._resolve(this._values);
  18535. }
  18536. };
  18537. PromiseArray.prototype._promiseRejected =
  18538. function PromiseArray$_promiseRejected(reason, index) {
  18539. if (this._isResolved()) return;
  18540. this._totalResolved++;
  18541. this._reject(reason);
  18542. };
  18543. return PromiseArray;
  18544. };
  18545. },{"./async.js":73,"./errors.js":80,"./util.js":108}],92:[function(_dereq_,module,exports){
  18546. /**
  18547. * Copyright (c) 2014 Petka Antonov
  18548. *
  18549. * Permission is hereby granted, free of charge, to any person obtaining a copy
  18550. * of this software and associated documentation files (the "Software"), to deal
  18551. * in the Software without restriction, including without limitation the rights
  18552. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  18553. * copies of the Software, and to permit persons to whom the Software is
  18554. * furnished to do so, subject to the following conditions:</p>
  18555. *
  18556. * The above copyright notice and this permission notice shall be included in
  18557. * all copies or substantial portions of the Software.
  18558. *
  18559. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18560. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18561. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18562. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18563. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18564. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18565. * THE SOFTWARE.
  18566. *
  18567. */
  18568. "use strict";
  18569. var util = _dereq_("./util.js");
  18570. var maybeWrapAsError = util.maybeWrapAsError;
  18571. var errors = _dereq_("./errors.js");
  18572. var TimeoutError = errors.TimeoutError;
  18573. var RejectionError = errors.RejectionError;
  18574. var async = _dereq_("./async.js");
  18575. var haveGetters = util.haveGetters;
  18576. var es5 = _dereq_("./es5.js");
  18577. function isUntypedError(obj) {
  18578. return obj instanceof Error &&
  18579. es5.getPrototypeOf(obj) === Error.prototype;
  18580. }
  18581. function wrapAsRejectionError(obj) {
  18582. var ret;
  18583. if (isUntypedError(obj)) {
  18584. ret = new RejectionError(obj);
  18585. }
  18586. else {
  18587. ret = obj;
  18588. }
  18589. errors.markAsOriginatingFromRejection(ret);
  18590. return ret;
  18591. }
  18592. function nodebackForPromise(promise) {
  18593. function PromiseResolver$_callback(err, value) {
  18594. if (promise === null) return;
  18595. if (err) {
  18596. var wrapped = wrapAsRejectionError(maybeWrapAsError(err));
  18597. promise._attachExtraTrace(wrapped);
  18598. promise._reject(wrapped);
  18599. }
  18600. else {
  18601. if (arguments.length > 2) {
  18602. var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}
  18603. promise._fulfill(args);
  18604. }
  18605. else {
  18606. promise._fulfill(value);
  18607. }
  18608. }
  18609. promise = null;
  18610. }
  18611. return PromiseResolver$_callback;
  18612. }
  18613. var PromiseResolver;
  18614. if (!haveGetters) {
  18615. PromiseResolver = function PromiseResolver(promise) {
  18616. this.promise = promise;
  18617. this.asCallback = nodebackForPromise(promise);
  18618. this.callback = this.asCallback;
  18619. };
  18620. }
  18621. else {
  18622. PromiseResolver = function PromiseResolver(promise) {
  18623. this.promise = promise;
  18624. };
  18625. }
  18626. if (haveGetters) {
  18627. var prop = {
  18628. get: function() {
  18629. return nodebackForPromise(this.promise);
  18630. }
  18631. };
  18632. es5.defineProperty(PromiseResolver.prototype, "asCallback", prop);
  18633. es5.defineProperty(PromiseResolver.prototype, "callback", prop);
  18634. }
  18635. PromiseResolver._nodebackForPromise = nodebackForPromise;
  18636. PromiseResolver.prototype.toString = function PromiseResolver$toString() {
  18637. return "[object PromiseResolver]";
  18638. };
  18639. PromiseResolver.prototype.resolve =
  18640. PromiseResolver.prototype.fulfill = function PromiseResolver$resolve(value) {
  18641. var promise = this.promise;
  18642. if ((promise === void 0) || (promise._tryFollow === void 0)) {
  18643. throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.");
  18644. }
  18645. if (promise._tryFollow(value)) {
  18646. return;
  18647. }
  18648. async.invoke(promise._fulfill, promise, value);
  18649. };
  18650. PromiseResolver.prototype.reject = function PromiseResolver$reject(reason) {
  18651. var promise = this.promise;
  18652. if ((promise === void 0) || (promise._attachExtraTrace === void 0)) {
  18653. throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.");
  18654. }
  18655. errors.markAsOriginatingFromRejection(reason);
  18656. var trace = errors.canAttach(reason) ? reason : new Error(reason + "");
  18657. promise._attachExtraTrace(trace);
  18658. async.invoke(promise._reject, promise, reason);
  18659. if (trace !== reason) {
  18660. async.invoke(this._setCarriedStackTrace, this, trace);
  18661. }
  18662. };
  18663. PromiseResolver.prototype.progress =
  18664. function PromiseResolver$progress(value) {
  18665. async.invoke(this.promise._progress, this.promise, value);
  18666. };
  18667. PromiseResolver.prototype.cancel = function PromiseResolver$cancel() {
  18668. async.invoke(this.promise.cancel, this.promise, void 0);
  18669. };
  18670. PromiseResolver.prototype.timeout = function PromiseResolver$timeout() {
  18671. this.reject(new TimeoutError("timeout"));
  18672. };
  18673. PromiseResolver.prototype.isResolved = function PromiseResolver$isResolved() {
  18674. return this.promise.isResolved();
  18675. };
  18676. PromiseResolver.prototype.toJSON = function PromiseResolver$toJSON() {
  18677. return this.promise.toJSON();
  18678. };
  18679. PromiseResolver.prototype._setCarriedStackTrace =
  18680. function PromiseResolver$_setCarriedStackTrace(trace) {
  18681. if (this.promise.isRejected()) {
  18682. this.promise._setCarriedStackTrace(trace);
  18683. }
  18684. };
  18685. module.exports = PromiseResolver;
  18686. },{"./async.js":73,"./errors.js":80,"./es5.js":82,"./util.js":108}],93:[function(_dereq_,module,exports){
  18687. /**
  18688. * Copyright (c) 2014 Petka Antonov
  18689. *
  18690. * Permission is hereby granted, free of charge, to any person obtaining a copy
  18691. * of this software and associated documentation files (the "Software"), to deal
  18692. * in the Software without restriction, including without limitation the rights
  18693. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  18694. * copies of the Software, and to permit persons to whom the Software is
  18695. * furnished to do so, subject to the following conditions:</p>
  18696. *
  18697. * The above copyright notice and this permission notice shall be included in
  18698. * all copies or substantial portions of the Software.
  18699. *
  18700. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18701. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18702. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18703. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18704. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18705. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18706. * THE SOFTWARE.
  18707. *
  18708. */
  18709. "use strict";
  18710. module.exports = function(Promise, INTERNAL) {
  18711. var errors = _dereq_("./errors.js");
  18712. var TypeError = errors.TypeError;
  18713. var util = _dereq_("./util.js");
  18714. var isArray = util.isArray;
  18715. var errorObj = util.errorObj;
  18716. var tryCatch1 = util.tryCatch1;
  18717. var yieldHandlers = [];
  18718. function promiseFromYieldHandler(value) {
  18719. var _yieldHandlers = yieldHandlers;
  18720. var _errorObj = errorObj;
  18721. var _Promise = Promise;
  18722. var len = _yieldHandlers.length;
  18723. for (var i = 0; i < len; ++i) {
  18724. var result = tryCatch1(_yieldHandlers[i], void 0, value);
  18725. if (result === _errorObj) {
  18726. return _Promise.reject(_errorObj.e);
  18727. }
  18728. var maybePromise = _Promise._cast(result,
  18729. promiseFromYieldHandler, void 0);
  18730. if (maybePromise instanceof _Promise) return maybePromise;
  18731. }
  18732. return null;
  18733. }
  18734. function PromiseSpawn(generatorFunction, receiver) {
  18735. var promise = this._promise = new Promise(INTERNAL);
  18736. promise._setTrace(void 0);
  18737. this._generatorFunction = generatorFunction;
  18738. this._receiver = receiver;
  18739. this._generator = void 0;
  18740. }
  18741. PromiseSpawn.prototype.promise = function PromiseSpawn$promise() {
  18742. return this._promise;
  18743. };
  18744. PromiseSpawn.prototype._run = function PromiseSpawn$_run() {
  18745. this._generator = this._generatorFunction.call(this._receiver);
  18746. this._receiver =
  18747. this._generatorFunction = void 0;
  18748. this._next(void 0);
  18749. };
  18750. PromiseSpawn.prototype._continue = function PromiseSpawn$_continue(result) {
  18751. if (result === errorObj) {
  18752. this._generator = void 0;
  18753. var trace = errors.canAttach(result.e)
  18754. ? result.e : new Error(result.e + "");
  18755. this._promise._attachExtraTrace(trace);
  18756. this._promise._reject(result.e, trace);
  18757. return;
  18758. }
  18759. var value = result.value;
  18760. if (result.done === true) {
  18761. this._generator = void 0;
  18762. if (!this._promise._tryFollow(value)) {
  18763. this._promise._fulfill(value);
  18764. }
  18765. }
  18766. else {
  18767. var maybePromise = Promise._cast(value, PromiseSpawn$_continue, void 0);
  18768. if (!(maybePromise instanceof Promise)) {
  18769. if (isArray(maybePromise)) {
  18770. maybePromise = Promise.all(maybePromise);
  18771. }
  18772. else {
  18773. maybePromise = promiseFromYieldHandler(maybePromise);
  18774. }
  18775. if (maybePromise === null) {
  18776. this._throw(new TypeError("A value was yielded that could not be treated as a promise"));
  18777. return;
  18778. }
  18779. }
  18780. maybePromise._then(
  18781. this._next,
  18782. this._throw,
  18783. void 0,
  18784. this,
  18785. null
  18786. );
  18787. }
  18788. };
  18789. PromiseSpawn.prototype._throw = function PromiseSpawn$_throw(reason) {
  18790. if (errors.canAttach(reason))
  18791. this._promise._attachExtraTrace(reason);
  18792. this._continue(
  18793. tryCatch1(this._generator["throw"], this._generator, reason)
  18794. );
  18795. };
  18796. PromiseSpawn.prototype._next = function PromiseSpawn$_next(value) {
  18797. this._continue(
  18798. tryCatch1(this._generator.next, this._generator, value)
  18799. );
  18800. };
  18801. PromiseSpawn.addYieldHandler = function PromiseSpawn$AddYieldHandler(fn) {
  18802. if (typeof fn !== "function") throw new TypeError("fn must be a function");
  18803. yieldHandlers.push(fn);
  18804. };
  18805. return PromiseSpawn;
  18806. };
  18807. },{"./errors.js":80,"./util.js":108}],94:[function(_dereq_,module,exports){
  18808. /**
  18809. * Copyright (c) 2014 Petka Antonov
  18810. *
  18811. * Permission is hereby granted, free of charge, to any person obtaining a copy
  18812. * of this software and associated documentation files (the "Software"), to deal
  18813. * in the Software without restriction, including without limitation the rights
  18814. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  18815. * copies of the Software, and to permit persons to whom the Software is
  18816. * furnished to do so, subject to the following conditions:</p>
  18817. *
  18818. * The above copyright notice and this permission notice shall be included in
  18819. * all copies or substantial portions of the Software.
  18820. *
  18821. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18822. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18823. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18824. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18825. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18826. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18827. * THE SOFTWARE.
  18828. *
  18829. */
  18830. "use strict";
  18831. module.exports = function(Promise, INTERNAL) {
  18832. var THIS = {};
  18833. var util = _dereq_("./util.js");
  18834. var es5 = _dereq_("./es5.js");
  18835. var nodebackForPromise = _dereq_("./promise_resolver.js")
  18836. ._nodebackForPromise;
  18837. var withAppended = util.withAppended;
  18838. var maybeWrapAsError = util.maybeWrapAsError;
  18839. var canEvaluate = util.canEvaluate;
  18840. var deprecated = util.deprecated;
  18841. var TypeError = _dereq_("./errors").TypeError;
  18842. var rasyncSuffix = new RegExp("Async" + "$");
  18843. function isPromisified(fn) {
  18844. return fn.__isPromisified__ === true;
  18845. }
  18846. function hasPromisified(obj, key) {
  18847. var containsKey = ((key + "Async") in obj);
  18848. return containsKey ? isPromisified(obj[key + "Async"])
  18849. : false;
  18850. }
  18851. function checkValid(ret) {
  18852. for (var i = 0; i < ret.length; i += 2) {
  18853. var key = ret[i];
  18854. if (rasyncSuffix.test(key)) {
  18855. var keyWithoutAsyncSuffix = key.replace(rasyncSuffix, "");
  18856. for (var j = 0; j < ret.length; j += 2) {
  18857. if (ret[j] === keyWithoutAsyncSuffix) {
  18858. throw new TypeError("Cannot promisify an API " +
  18859. "that has normal methods with Async-suffix");
  18860. }
  18861. }
  18862. }
  18863. }
  18864. }
  18865. var inheritedMethods = (function() {
  18866. if (es5.isES5) {
  18867. var create = Object.create;
  18868. var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  18869. return function(cur) {
  18870. var ret = [];
  18871. var visitedKeys = create(null);
  18872. var original = cur;
  18873. while (cur !== null) {
  18874. var keys = es5.keys(cur);
  18875. for (var i = 0, len = keys.length; i < len; ++i) {
  18876. var key = keys[i];
  18877. if (visitedKeys[key]) continue;
  18878. visitedKeys[key] = true;
  18879. var desc = getOwnPropertyDescriptor(cur, key);
  18880. if (desc != null &&
  18881. typeof desc.value === "function" &&
  18882. !isPromisified(desc.value) &&
  18883. !hasPromisified(original, key)) {
  18884. ret.push(key, desc.value);
  18885. }
  18886. }
  18887. cur = es5.getPrototypeOf(cur);
  18888. }
  18889. checkValid(ret);
  18890. return ret;
  18891. };
  18892. }
  18893. else {
  18894. return function(obj) {
  18895. var ret = [];
  18896. /*jshint forin:false */
  18897. for (var key in obj) {
  18898. var fn = obj[key];
  18899. if (typeof fn === "function" &&
  18900. !isPromisified(fn) &&
  18901. !hasPromisified(obj, key)) {
  18902. ret.push(key, fn);
  18903. }
  18904. }
  18905. checkValid(ret);
  18906. return ret;
  18907. };
  18908. }
  18909. })();
  18910. function switchCaseArgumentOrder(likelyArgumentCount) {
  18911. var ret = [likelyArgumentCount];
  18912. var min = Math.max(0, likelyArgumentCount - 1 - 5);
  18913. for(var i = likelyArgumentCount - 1; i >= min; --i) {
  18914. if (i === likelyArgumentCount) continue;
  18915. ret.push(i);
  18916. }
  18917. for(var i = likelyArgumentCount + 1; i <= 5; ++i) {
  18918. ret.push(i);
  18919. }
  18920. return ret;
  18921. }
  18922. function parameterDeclaration(parameterCount) {
  18923. var ret = new Array(parameterCount);
  18924. for(var i = 0; i < ret.length; ++i) {
  18925. ret[i] = "_arg" + i;
  18926. }
  18927. return ret.join(", ");
  18928. }
  18929. function parameterCount(fn) {
  18930. if (typeof fn.length === "number") {
  18931. return Math.max(Math.min(fn.length, 1023 + 1), 0);
  18932. }
  18933. return 0;
  18934. }
  18935. var rident = /^[a-z$_][a-z$_0-9]*$/i;
  18936. function propertyAccess(id) {
  18937. if (rident.test(id)) {
  18938. return "." + id;
  18939. }
  18940. else return "['" + id.replace(/(['\\])/g, "\\$1") + "']";
  18941. }
  18942. function makeNodePromisifiedEval(callback, receiver, originalName, fn) {
  18943. var newParameterCount = Math.max(0, parameterCount(fn) - 1);
  18944. var argumentOrder = switchCaseArgumentOrder(newParameterCount);
  18945. var callbackName = (typeof originalName === "string" ?
  18946. originalName + "Async" :
  18947. "promisified");
  18948. function generateCallForArgumentCount(count) {
  18949. var args = new Array(count);
  18950. for (var i = 0, len = args.length; i < len; ++i) {
  18951. args[i] = "arguments[" + i + "]";
  18952. }
  18953. var comma = count > 0 ? "," : "";
  18954. if (typeof callback === "string" &&
  18955. receiver === THIS) {
  18956. return "this" + propertyAccess(callback) + "("+args.join(",") +
  18957. comma +" fn);"+
  18958. "break;";
  18959. }
  18960. return (receiver === void 0
  18961. ? "callback("+args.join(",")+ comma +" fn);"
  18962. : "callback.call("+(receiver === THIS
  18963. ? "this"
  18964. : "receiver")+", "+args.join(",") + comma + " fn);") +
  18965. "break;";
  18966. }
  18967. if (!rident.test(callbackName)) {
  18968. callbackName = "promisified";
  18969. }
  18970. function generateArgumentSwitchCase() {
  18971. var ret = "";
  18972. for(var i = 0; i < argumentOrder.length; ++i) {
  18973. ret += "case " + argumentOrder[i] +":" +
  18974. generateCallForArgumentCount(argumentOrder[i]);
  18975. }
  18976. ret += "default: var args = new Array(len + 1);" +
  18977. "var i = 0;" +
  18978. "for (var i = 0; i < len; ++i) { " +
  18979. " args[i] = arguments[i];" +
  18980. "}" +
  18981. "args[i] = fn;" +
  18982. (typeof callback === "string"
  18983. ? "this" + propertyAccess(callback) + ".apply("
  18984. : "callback.apply(") +
  18985. (receiver === THIS ? "this" : "receiver") +
  18986. ", args); break;";
  18987. return ret;
  18988. }
  18989. return new Function("Promise", "callback", "receiver",
  18990. "withAppended", "maybeWrapAsError", "nodebackForPromise",
  18991. "INTERNAL",
  18992. "var ret = function " + callbackName +
  18993. "(" + parameterDeclaration(newParameterCount) + ") {\"use strict\";" +
  18994. "var len = arguments.length;" +
  18995. "var promise = new Promise(INTERNAL);"+
  18996. "promise._setTrace(void 0);" +
  18997. "var fn = nodebackForPromise(promise);"+
  18998. "try {" +
  18999. "switch(len) {" +
  19000. generateArgumentSwitchCase() +
  19001. "}" +
  19002. "}" +
  19003. "catch(e){ " +
  19004. "var wrapped = maybeWrapAsError(e);" +
  19005. "promise._attachExtraTrace(wrapped);" +
  19006. "promise._reject(wrapped);" +
  19007. "}" +
  19008. "return promise;" +
  19009. "" +
  19010. "}; ret.__isPromisified__ = true; return ret;"
  19011. )(Promise, callback, receiver, withAppended,
  19012. maybeWrapAsError, nodebackForPromise, INTERNAL);
  19013. }
  19014. function makeNodePromisifiedClosure(callback, receiver) {
  19015. function promisified() {
  19016. var _receiver = receiver;
  19017. if (receiver === THIS) _receiver = this;
  19018. if (typeof callback === "string") {
  19019. callback = _receiver[callback];
  19020. }
  19021. var promise = new Promise(INTERNAL);
  19022. promise._setTrace(void 0);
  19023. var fn = nodebackForPromise(promise);
  19024. try {
  19025. callback.apply(_receiver, withAppended(arguments, fn));
  19026. }
  19027. catch(e) {
  19028. var wrapped = maybeWrapAsError(e);
  19029. promise._attachExtraTrace(wrapped);
  19030. promise._reject(wrapped);
  19031. }
  19032. return promise;
  19033. }
  19034. promisified.__isPromisified__ = true;
  19035. return promisified;
  19036. }
  19037. var makeNodePromisified = canEvaluate
  19038. ? makeNodePromisifiedEval
  19039. : makeNodePromisifiedClosure;
  19040. function _promisify(callback, receiver, isAll) {
  19041. if (isAll) {
  19042. var methods = inheritedMethods(callback);
  19043. for (var i = 0, len = methods.length; i < len; i+= 2) {
  19044. var key = methods[i];
  19045. var fn = methods[i+1];
  19046. var promisifiedKey = key + "Async";
  19047. callback[promisifiedKey] = makeNodePromisified(key, THIS, key, fn);
  19048. }
  19049. util.toFastProperties(callback);
  19050. return callback;
  19051. }
  19052. else {
  19053. return makeNodePromisified(callback, receiver, void 0, callback);
  19054. }
  19055. }
  19056. Promise.promisify = function Promise$Promisify(fn, receiver) {
  19057. if (typeof fn === "object" && fn !== null) {
  19058. deprecated("Promise.promisify for promisifying entire objects is deprecated. Use Promise.promisifyAll instead.");
  19059. return _promisify(fn, receiver, true);
  19060. }
  19061. if (typeof fn !== "function") {
  19062. throw new TypeError("fn must be a function");
  19063. }
  19064. if (isPromisified(fn)) {
  19065. return fn;
  19066. }
  19067. return _promisify(
  19068. fn,
  19069. arguments.length < 2 ? THIS : receiver,
  19070. false);
  19071. };
  19072. Promise.promisifyAll = function Promise$PromisifyAll(target) {
  19073. if (typeof target !== "function" && typeof target !== "object") {
  19074. throw new TypeError("the target of promisifyAll must be an object or a function");
  19075. }
  19076. return _promisify(target, void 0, true);
  19077. };
  19078. };
  19079. },{"./errors":80,"./es5.js":82,"./promise_resolver.js":92,"./util.js":108}],95:[function(_dereq_,module,exports){
  19080. /**
  19081. * Copyright (c) 2014 Petka Antonov
  19082. *
  19083. * Permission is hereby granted, free of charge, to any person obtaining a copy
  19084. * of this software and associated documentation files (the "Software"), to deal
  19085. * in the Software without restriction, including without limitation the rights
  19086. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  19087. * copies of the Software, and to permit persons to whom the Software is
  19088. * furnished to do so, subject to the following conditions:</p>
  19089. *
  19090. * The above copyright notice and this permission notice shall be included in
  19091. * all copies or substantial portions of the Software.
  19092. *
  19093. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19094. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19095. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19096. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19097. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19098. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19099. * THE SOFTWARE.
  19100. *
  19101. */
  19102. "use strict";
  19103. module.exports = function(Promise, PromiseArray) {
  19104. var util = _dereq_("./util.js");
  19105. var inherits = util.inherits;
  19106. var es5 = _dereq_("./es5.js");
  19107. function PropertiesPromiseArray(obj, boundTo) {
  19108. var keys = es5.keys(obj);
  19109. var values = new Array(keys.length);
  19110. for (var i = 0, len = values.length; i < len; ++i) {
  19111. values[i] = obj[keys[i]];
  19112. }
  19113. this.constructor$(values, boundTo);
  19114. if (!this._isResolved()) {
  19115. for (var i = 0, len = keys.length; i < len; ++i) {
  19116. values.push(keys[i]);
  19117. }
  19118. }
  19119. }
  19120. inherits(PropertiesPromiseArray, PromiseArray);
  19121. PropertiesPromiseArray.prototype._init =
  19122. function PropertiesPromiseArray$_init() {
  19123. this._init$(void 0, -3) ;
  19124. };
  19125. PropertiesPromiseArray.prototype._promiseFulfilled =
  19126. function PropertiesPromiseArray$_promiseFulfilled(value, index) {
  19127. if (this._isResolved()) return;
  19128. this._values[index] = value;
  19129. var totalResolved = ++this._totalResolved;
  19130. if (totalResolved >= this._length) {
  19131. var val = {};
  19132. var keyOffset = this.length();
  19133. for (var i = 0, len = this.length(); i < len; ++i) {
  19134. val[this._values[i + keyOffset]] = this._values[i];
  19135. }
  19136. this._resolve(val);
  19137. }
  19138. };
  19139. PropertiesPromiseArray.prototype._promiseProgressed =
  19140. function PropertiesPromiseArray$_promiseProgressed(value, index) {
  19141. if (this._isResolved()) return;
  19142. this._promise._progress({
  19143. key: this._values[index + this.length()],
  19144. value: value
  19145. });
  19146. };
  19147. PromiseArray.PropertiesPromiseArray = PropertiesPromiseArray;
  19148. return PropertiesPromiseArray;
  19149. };
  19150. },{"./es5.js":82,"./util.js":108}],96:[function(_dereq_,module,exports){
  19151. /**
  19152. * Copyright (c) 2014 Petka Antonov
  19153. *
  19154. * Permission is hereby granted, free of charge, to any person obtaining a copy
  19155. * of this software and associated documentation files (the "Software"), to deal
  19156. * in the Software without restriction, including without limitation the rights
  19157. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  19158. * copies of the Software, and to permit persons to whom the Software is
  19159. * furnished to do so, subject to the following conditions:</p>
  19160. *
  19161. * The above copyright notice and this permission notice shall be included in
  19162. * all copies or substantial portions of the Software.
  19163. *
  19164. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19165. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19166. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19167. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19168. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19169. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19170. * THE SOFTWARE.
  19171. *
  19172. */
  19173. "use strict";
  19174. module.exports = function(Promise, PromiseArray) {
  19175. var PropertiesPromiseArray = _dereq_("./properties_promise_array.js")(
  19176. Promise, PromiseArray);
  19177. var util = _dereq_("./util.js");
  19178. var apiRejection = _dereq_("./errors_api_rejection")(Promise);
  19179. var isObject = util.isObject;
  19180. function Promise$_Props(promises, useBound) {
  19181. var ret;
  19182. var castValue = Promise._cast(promises, void 0);
  19183. if (!isObject(castValue)) {
  19184. return apiRejection("cannot await properties of a non-object");
  19185. }
  19186. else if (castValue instanceof Promise) {
  19187. ret = castValue._then(Promise.props, void 0, void 0,
  19188. void 0, void 0);
  19189. }
  19190. else {
  19191. ret = new PropertiesPromiseArray(
  19192. castValue,
  19193. useBound === true && castValue._isBound()
  19194. ? castValue._boundTo
  19195. : void 0
  19196. ).promise();
  19197. useBound = false;
  19198. }
  19199. if (useBound === true && castValue._isBound()) {
  19200. ret._setBoundTo(castValue._boundTo);
  19201. }
  19202. return ret;
  19203. }
  19204. Promise.prototype.props = function Promise$props() {
  19205. return Promise$_Props(this, true);
  19206. };
  19207. Promise.props = function Promise$Props(promises) {
  19208. return Promise$_Props(promises, false);
  19209. };
  19210. };
  19211. },{"./errors_api_rejection":81,"./properties_promise_array.js":95,"./util.js":108}],97:[function(_dereq_,module,exports){
  19212. /**
  19213. * Copyright (c) 2014 Petka Antonov
  19214. *
  19215. * Permission is hereby granted, free of charge, to any person obtaining a copy
  19216. * of this software and associated documentation files (the "Software"), to deal
  19217. * in the Software without restriction, including without limitation the rights
  19218. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  19219. * copies of the Software, and to permit persons to whom the Software is
  19220. * furnished to do so, subject to the following conditions:</p>
  19221. *
  19222. * The above copyright notice and this permission notice shall be included in
  19223. * all copies or substantial portions of the Software.
  19224. *
  19225. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19226. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19227. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19228. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19229. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19230. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19231. * THE SOFTWARE.
  19232. *
  19233. */
  19234. "use strict";
  19235. function arrayCopy(src, srcIndex, dst, dstIndex, len) {
  19236. for (var j = 0; j < len; ++j) {
  19237. dst[j + dstIndex] = src[j + srcIndex];
  19238. }
  19239. }
  19240. function pow2AtLeast(n) {
  19241. n = n >>> 0;
  19242. n = n - 1;
  19243. n = n | (n >> 1);
  19244. n = n | (n >> 2);
  19245. n = n | (n >> 4);
  19246. n = n | (n >> 8);
  19247. n = n | (n >> 16);
  19248. return n + 1;
  19249. }
  19250. function getCapacity(capacity) {
  19251. if (typeof capacity !== "number") return 16;
  19252. return pow2AtLeast(
  19253. Math.min(
  19254. Math.max(16, capacity), 1073741824)
  19255. );
  19256. }
  19257. function Queue(capacity) {
  19258. this._capacity = getCapacity(capacity);
  19259. this._length = 0;
  19260. this._front = 0;
  19261. this._makeCapacity();
  19262. }
  19263. Queue.prototype._willBeOverCapacity =
  19264. function Queue$_willBeOverCapacity(size) {
  19265. return this._capacity < size;
  19266. };
  19267. Queue.prototype._pushOne = function Queue$_pushOne(arg) {
  19268. var length = this.length();
  19269. this._checkCapacity(length + 1);
  19270. var i = (this._front + length) & (this._capacity - 1);
  19271. this[i] = arg;
  19272. this._length = length + 1;
  19273. };
  19274. Queue.prototype.push = function Queue$push(fn, receiver, arg) {
  19275. var length = this.length() + 3;
  19276. if (this._willBeOverCapacity(length)) {
  19277. this._pushOne(fn);
  19278. this._pushOne(receiver);
  19279. this._pushOne(arg);
  19280. return;
  19281. }
  19282. var j = this._front + length - 3;
  19283. this._checkCapacity(length);
  19284. var wrapMask = this._capacity - 1;
  19285. this[(j + 0) & wrapMask] = fn;
  19286. this[(j + 1) & wrapMask] = receiver;
  19287. this[(j + 2) & wrapMask] = arg;
  19288. this._length = length;
  19289. };
  19290. Queue.prototype.shift = function Queue$shift() {
  19291. var front = this._front,
  19292. ret = this[front];
  19293. this[front] = void 0;
  19294. this._front = (front + 1) & (this._capacity - 1);
  19295. this._length--;
  19296. return ret;
  19297. };
  19298. Queue.prototype.length = function Queue$length() {
  19299. return this._length;
  19300. };
  19301. Queue.prototype._makeCapacity = function Queue$_makeCapacity() {
  19302. var len = this._capacity;
  19303. for (var i = 0; i < len; ++i) {
  19304. this[i] = void 0;
  19305. }
  19306. };
  19307. Queue.prototype._checkCapacity = function Queue$_checkCapacity(size) {
  19308. if (this._capacity < size) {
  19309. this._resizeTo(this._capacity << 3);
  19310. }
  19311. };
  19312. Queue.prototype._resizeTo = function Queue$_resizeTo(capacity) {
  19313. var oldFront = this._front;
  19314. var oldCapacity = this._capacity;
  19315. var oldQueue = new Array(oldCapacity);
  19316. var length = this.length();
  19317. arrayCopy(this, 0, oldQueue, 0, oldCapacity);
  19318. this._capacity = capacity;
  19319. this._makeCapacity();
  19320. this._front = 0;
  19321. if (oldFront + length <= oldCapacity) {
  19322. arrayCopy(oldQueue, oldFront, this, 0, length);
  19323. }
  19324. else { var lengthBeforeWrapping =
  19325. length - ((oldFront + length) & (oldCapacity - 1));
  19326. arrayCopy(oldQueue, oldFront, this, 0, lengthBeforeWrapping);
  19327. arrayCopy(oldQueue, 0, this, lengthBeforeWrapping,
  19328. length - lengthBeforeWrapping);
  19329. }
  19330. };
  19331. module.exports = Queue;
  19332. },{}],98:[function(_dereq_,module,exports){
  19333. /**
  19334. * Copyright (c) 2014 Petka Antonov
  19335. *
  19336. * Permission is hereby granted, free of charge, to any person obtaining a copy
  19337. * of this software and associated documentation files (the "Software"), to deal
  19338. * in the Software without restriction, including without limitation the rights
  19339. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  19340. * copies of the Software, and to permit persons to whom the Software is
  19341. * furnished to do so, subject to the following conditions:</p>
  19342. *
  19343. * The above copyright notice and this permission notice shall be included in
  19344. * all copies or substantial portions of the Software.
  19345. *
  19346. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19347. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19348. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19349. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19350. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19351. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19352. * THE SOFTWARE.
  19353. *
  19354. */
  19355. "use strict";
  19356. module.exports = function(Promise, INTERNAL) {
  19357. var apiRejection = _dereq_("./errors_api_rejection.js")(Promise);
  19358. var isArray = _dereq_("./util.js").isArray;
  19359. var raceLater = function Promise$_raceLater(promise) {
  19360. return promise.then(function(array) {
  19361. return Promise$_Race(array, promise);
  19362. });
  19363. };
  19364. var hasOwn = {}.hasOwnProperty;
  19365. function Promise$_Race(promises, parent) {
  19366. var maybePromise = Promise._cast(promises, void 0);
  19367. if (maybePromise instanceof Promise) {
  19368. return raceLater(maybePromise);
  19369. }
  19370. else if (!isArray(promises)) {
  19371. return apiRejection("expecting an array, a promise or a thenable");
  19372. }
  19373. var ret = new Promise(INTERNAL);
  19374. ret._setTrace(parent);
  19375. if (parent !== void 0) {
  19376. if (parent._isBound()) {
  19377. ret._setBoundTo(parent._boundTo);
  19378. }
  19379. if (parent._cancellable()) {
  19380. ret._setCancellable();
  19381. ret._cancellationParent = parent;
  19382. }
  19383. }
  19384. var fulfill = ret._fulfill;
  19385. var reject = ret._reject;
  19386. for (var i = 0, len = promises.length; i < len; ++i) {
  19387. var val = promises[i];
  19388. if (val === void 0 && !(hasOwn.call(promises, i))) {
  19389. continue;
  19390. }
  19391. Promise.cast(val)._then(
  19392. fulfill,
  19393. reject,
  19394. void 0,
  19395. ret,
  19396. null
  19397. );
  19398. }
  19399. return ret;
  19400. }
  19401. Promise.race = function Promise$Race(promises) {
  19402. return Promise$_Race(promises, void 0);
  19403. };
  19404. Promise.prototype.race = function Promise$race() {
  19405. return Promise$_Race(this, void 0);
  19406. };
  19407. };
  19408. },{"./errors_api_rejection.js":81,"./util.js":108}],99:[function(_dereq_,module,exports){
  19409. /**
  19410. * Copyright (c) 2014 Petka Antonov
  19411. *
  19412. * Permission is hereby granted, free of charge, to any person obtaining a copy
  19413. * of this software and associated documentation files (the "Software"), to deal
  19414. * in the Software without restriction, including without limitation the rights
  19415. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  19416. * copies of the Software, and to permit persons to whom the Software is
  19417. * furnished to do so, subject to the following conditions:</p>
  19418. *
  19419. * The above copyright notice and this permission notice shall be included in
  19420. * all copies or substantial portions of the Software.
  19421. *
  19422. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19423. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19424. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19425. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19426. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19427. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19428. * THE SOFTWARE.
  19429. *
  19430. */
  19431. "use strict";
  19432. module.exports = function(
  19433. Promise, Promise$_CreatePromiseArray,
  19434. PromiseArray, apiRejection, INTERNAL) {
  19435. function Reduction(callback, index, accum, items, receiver) {
  19436. this.promise = new Promise(INTERNAL);
  19437. this.index = index;
  19438. this.length = items.length;
  19439. this.items = items;
  19440. this.callback = callback;
  19441. this.receiver = receiver;
  19442. this.accum = accum;
  19443. }
  19444. Reduction.prototype.reject = function Reduction$reject(e) {
  19445. this.promise._reject(e);
  19446. };
  19447. Reduction.prototype.fulfill = function Reduction$fulfill(value, index) {
  19448. this.accum = value;
  19449. this.index = index + 1;
  19450. this.iterate();
  19451. };
  19452. Reduction.prototype.iterate = function Reduction$iterate() {
  19453. var i = this.index;
  19454. var len = this.length;
  19455. var items = this.items;
  19456. var result = this.accum;
  19457. var receiver = this.receiver;
  19458. var callback = this.callback;
  19459. for (; i < len; ++i) {
  19460. result = callback.call(receiver, result, items[i], i, len);
  19461. result = Promise._cast(result, void 0);
  19462. if (result instanceof Promise) {
  19463. result._then(
  19464. this.fulfill, this.reject, void 0, this, i);
  19465. return;
  19466. }
  19467. }
  19468. this.promise._fulfill(result);
  19469. };
  19470. function Promise$_reducer(fulfilleds, initialValue) {
  19471. var fn = this;
  19472. var receiver = void 0;
  19473. if (typeof fn !== "function") {
  19474. receiver = fn.receiver;
  19475. fn = fn.fn;
  19476. }
  19477. var len = fulfilleds.length;
  19478. var accum = void 0;
  19479. var startIndex = 0;
  19480. if (initialValue !== void 0) {
  19481. accum = initialValue;
  19482. startIndex = 0;
  19483. }
  19484. else {
  19485. startIndex = 1;
  19486. if (len > 0) accum = fulfilleds[0];
  19487. }
  19488. var i = startIndex;
  19489. if (i >= len) {
  19490. return accum;
  19491. }
  19492. var reduction = new Reduction(fn, i, accum, fulfilleds, receiver);
  19493. reduction.iterate();
  19494. return reduction.promise;
  19495. }
  19496. function Promise$_unpackReducer(fulfilleds) {
  19497. var fn = this.fn;
  19498. var initialValue = this.initialValue;
  19499. return Promise$_reducer.call(fn, fulfilleds, initialValue);
  19500. }
  19501. function Promise$_slowReduce(
  19502. promises, fn, initialValue, useBound) {
  19503. return initialValue._then(function(initialValue) {
  19504. return Promise$_Reduce(
  19505. promises, fn, initialValue, useBound);
  19506. }, void 0, void 0, void 0, void 0);
  19507. }
  19508. function Promise$_Reduce(promises, fn, initialValue, useBound) {
  19509. if (typeof fn !== "function") {
  19510. return apiRejection("fn must be a function");
  19511. }
  19512. if (useBound === true && promises._isBound()) {
  19513. fn = {
  19514. fn: fn,
  19515. receiver: promises._boundTo
  19516. };
  19517. }
  19518. if (initialValue !== void 0) {
  19519. if (initialValue instanceof Promise) {
  19520. if (initialValue.isFulfilled()) {
  19521. initialValue = initialValue._settledValue;
  19522. }
  19523. else {
  19524. return Promise$_slowReduce(promises,
  19525. fn, initialValue, useBound);
  19526. }
  19527. }
  19528. return Promise$_CreatePromiseArray(promises, PromiseArray,
  19529. useBound === true && promises._isBound()
  19530. ? promises._boundTo
  19531. : void 0)
  19532. .promise()
  19533. ._then(Promise$_unpackReducer, void 0, void 0, {
  19534. fn: fn,
  19535. initialValue: initialValue
  19536. }, void 0);
  19537. }
  19538. return Promise$_CreatePromiseArray(promises, PromiseArray,
  19539. useBound === true && promises._isBound()
  19540. ? promises._boundTo
  19541. : void 0).promise()
  19542. ._then(Promise$_reducer, void 0, void 0, fn, void 0);
  19543. }
  19544. Promise.reduce = function Promise$Reduce(promises, fn, initialValue) {
  19545. return Promise$_Reduce(promises, fn, initialValue, false);
  19546. };
  19547. Promise.prototype.reduce = function Promise$reduce(fn, initialValue) {
  19548. return Promise$_Reduce(this, fn, initialValue, true);
  19549. };
  19550. };
  19551. },{}],100:[function(_dereq_,module,exports){
  19552. (function (process){
  19553. /**
  19554. * Copyright (c) 2014 Petka Antonov
  19555. *
  19556. * Permission is hereby granted, free of charge, to any person obtaining a copy
  19557. * of this software and associated documentation files (the "Software"), to deal
  19558. * in the Software without restriction, including without limitation the rights
  19559. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  19560. * copies of the Software, and to permit persons to whom the Software is
  19561. * furnished to do so, subject to the following conditions:</p>
  19562. *
  19563. * The above copyright notice and this permission notice shall be included in
  19564. * all copies or substantial portions of the Software.
  19565. *
  19566. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19567. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19568. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19569. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19570. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19571. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19572. * THE SOFTWARE.
  19573. *
  19574. */
  19575. "use strict";
  19576. var global = _dereq_("./global.js");
  19577. var schedule;
  19578. if (typeof process !== "undefined" && process !== null &&
  19579. typeof process.cwd === "function" &&
  19580. typeof process.nextTick === "function" &&
  19581. typeof process.version === "string") {
  19582. schedule = function Promise$_Scheduler(fn) {
  19583. process.nextTick(fn);
  19584. };
  19585. }
  19586. else if ((typeof global.MutationObserver === "function" ||
  19587. typeof global.WebkitMutationObserver === "function" ||
  19588. typeof global.WebKitMutationObserver === "function") &&
  19589. typeof document !== "undefined" &&
  19590. typeof document.createElement === "function") {
  19591. schedule = (function(){
  19592. var MutationObserver = global.MutationObserver ||
  19593. global.WebkitMutationObserver ||
  19594. global.WebKitMutationObserver;
  19595. var div = document.createElement("div");
  19596. var queuedFn = void 0;
  19597. var observer = new MutationObserver(
  19598. function Promise$_Scheduler() {
  19599. var fn = queuedFn;
  19600. queuedFn = void 0;
  19601. fn();
  19602. }
  19603. );
  19604. observer.observe(div, {
  19605. attributes: true
  19606. });
  19607. return function Promise$_Scheduler(fn) {
  19608. queuedFn = fn;
  19609. div.setAttribute("class", "foo");
  19610. };
  19611. })();
  19612. }
  19613. else if (typeof global.postMessage === "function" &&
  19614. typeof global.importScripts !== "function" &&
  19615. typeof global.addEventListener === "function" &&
  19616. typeof global.removeEventListener === "function") {
  19617. var MESSAGE_KEY = "bluebird_message_key_" + Math.random();
  19618. schedule = (function(){
  19619. var queuedFn = void 0;
  19620. function Promise$_Scheduler(e) {
  19621. if (e.source === global &&
  19622. e.data === MESSAGE_KEY) {
  19623. var fn = queuedFn;
  19624. queuedFn = void 0;
  19625. fn();
  19626. }
  19627. }
  19628. global.addEventListener("message", Promise$_Scheduler, false);
  19629. return function Promise$_Scheduler(fn) {
  19630. queuedFn = fn;
  19631. global.postMessage(
  19632. MESSAGE_KEY, "*"
  19633. );
  19634. };
  19635. })();
  19636. }
  19637. else if (typeof global.MessageChannel === "function") {
  19638. schedule = (function(){
  19639. var queuedFn = void 0;
  19640. var channel = new global.MessageChannel();
  19641. channel.port1.onmessage = function Promise$_Scheduler() {
  19642. var fn = queuedFn;
  19643. queuedFn = void 0;
  19644. fn();
  19645. };
  19646. return function Promise$_Scheduler(fn) {
  19647. queuedFn = fn;
  19648. channel.port2.postMessage(null);
  19649. };
  19650. })();
  19651. }
  19652. else if (global.setTimeout) {
  19653. schedule = function Promise$_Scheduler(fn) {
  19654. setTimeout(fn, 4);
  19655. };
  19656. }
  19657. else {
  19658. schedule = function Promise$_Scheduler(fn) {
  19659. fn();
  19660. };
  19661. }
  19662. module.exports = schedule;
  19663. }).call(this,_dereq_("C:\\Users\\Alex\\AppData\\Roaming\\npm\\node_modules\\browserify\\node_modules\\insert-module-globals\\node_modules\\process\\browser.js"))
  19664. },{"./global.js":86,"C:\\Users\\Alex\\AppData\\Roaming\\npm\\node_modules\\browserify\\node_modules\\insert-module-globals\\node_modules\\process\\browser.js":144}],101:[function(_dereq_,module,exports){
  19665. /**
  19666. * Copyright (c) 2014 Petka Antonov
  19667. *
  19668. * Permission is hereby granted, free of charge, to any person obtaining a copy
  19669. * of this software and associated documentation files (the "Software"), to deal
  19670. * in the Software without restriction, including without limitation the rights
  19671. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  19672. * copies of the Software, and to permit persons to whom the Software is
  19673. * furnished to do so, subject to the following conditions:</p>
  19674. *
  19675. * The above copyright notice and this permission notice shall be included in
  19676. * all copies or substantial portions of the Software.
  19677. *
  19678. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19679. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19680. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19681. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19682. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19683. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19684. * THE SOFTWARE.
  19685. *
  19686. */
  19687. "use strict";
  19688. module.exports =
  19689. function(Promise, Promise$_CreatePromiseArray, PromiseArray) {
  19690. var SettledPromiseArray = _dereq_("./settled_promise_array.js")(
  19691. Promise, PromiseArray);
  19692. function Promise$_Settle(promises, useBound) {
  19693. return Promise$_CreatePromiseArray(
  19694. promises,
  19695. SettledPromiseArray,
  19696. useBound === true && promises._isBound()
  19697. ? promises._boundTo
  19698. : void 0
  19699. ).promise();
  19700. }
  19701. Promise.settle = function Promise$Settle(promises) {
  19702. return Promise$_Settle(promises, false);
  19703. };
  19704. Promise.prototype.settle = function Promise$settle() {
  19705. return Promise$_Settle(this, true);
  19706. };
  19707. };
  19708. },{"./settled_promise_array.js":102}],102:[function(_dereq_,module,exports){
  19709. /**
  19710. * Copyright (c) 2014 Petka Antonov
  19711. *
  19712. * Permission is hereby granted, free of charge, to any person obtaining a copy
  19713. * of this software and associated documentation files (the "Software"), to deal
  19714. * in the Software without restriction, including without limitation the rights
  19715. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  19716. * copies of the Software, and to permit persons to whom the Software is
  19717. * furnished to do so, subject to the following conditions:</p>
  19718. *
  19719. * The above copyright notice and this permission notice shall be included in
  19720. * all copies or substantial portions of the Software.
  19721. *
  19722. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19723. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19724. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19725. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19726. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19727. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19728. * THE SOFTWARE.
  19729. *
  19730. */
  19731. "use strict";
  19732. module.exports = function(Promise, PromiseArray) {
  19733. var PromiseInspection = Promise.PromiseInspection;
  19734. var util = _dereq_("./util.js");
  19735. var inherits = util.inherits;
  19736. function SettledPromiseArray(values, boundTo) {
  19737. this.constructor$(values, boundTo);
  19738. }
  19739. inherits(SettledPromiseArray, PromiseArray);
  19740. SettledPromiseArray.prototype._promiseResolved =
  19741. function SettledPromiseArray$_promiseResolved(index, inspection) {
  19742. this._values[index] = inspection;
  19743. var totalResolved = ++this._totalResolved;
  19744. if (totalResolved >= this._length) {
  19745. this._resolve(this._values);
  19746. }
  19747. };
  19748. SettledPromiseArray.prototype._promiseFulfilled =
  19749. function SettledPromiseArray$_promiseFulfilled(value, index) {
  19750. if (this._isResolved()) return;
  19751. var ret = new PromiseInspection();
  19752. ret._bitField = 268435456;
  19753. ret._settledValue = value;
  19754. this._promiseResolved(index, ret);
  19755. };
  19756. SettledPromiseArray.prototype._promiseRejected =
  19757. function SettledPromiseArray$_promiseRejected(reason, index) {
  19758. if (this._isResolved()) return;
  19759. var ret = new PromiseInspection();
  19760. ret._bitField = 134217728;
  19761. ret._settledValue = reason;
  19762. this._promiseResolved(index, ret);
  19763. };
  19764. return SettledPromiseArray;
  19765. };
  19766. },{"./util.js":108}],103:[function(_dereq_,module,exports){
  19767. /**
  19768. * Copyright (c) 2014 Petka Antonov
  19769. *
  19770. * Permission is hereby granted, free of charge, to any person obtaining a copy
  19771. * of this software and associated documentation files (the "Software"), to deal
  19772. * in the Software without restriction, including without limitation the rights
  19773. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  19774. * copies of the Software, and to permit persons to whom the Software is
  19775. * furnished to do so, subject to the following conditions:</p>
  19776. *
  19777. * The above copyright notice and this permission notice shall be included in
  19778. * all copies or substantial portions of the Software.
  19779. *
  19780. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19781. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19782. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19783. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19784. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19785. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19786. * THE SOFTWARE.
  19787. *
  19788. */
  19789. "use strict";
  19790. module.exports =
  19791. function(Promise, Promise$_CreatePromiseArray, PromiseArray, apiRejection) {
  19792. var SomePromiseArray = _dereq_("./some_promise_array.js")(PromiseArray);
  19793. function Promise$_Some(promises, howMany, useBound) {
  19794. if ((howMany | 0) !== howMany || howMany < 0) {
  19795. return apiRejection("expecting a positive integer");
  19796. }
  19797. var ret = Promise$_CreatePromiseArray(
  19798. promises,
  19799. SomePromiseArray,
  19800. useBound === true && promises._isBound()
  19801. ? promises._boundTo
  19802. : void 0
  19803. );
  19804. var promise = ret.promise();
  19805. if (promise.isRejected()) {
  19806. return promise;
  19807. }
  19808. ret.setHowMany(howMany);
  19809. ret.init();
  19810. return promise;
  19811. }
  19812. Promise.some = function Promise$Some(promises, howMany) {
  19813. return Promise$_Some(promises, howMany, false);
  19814. };
  19815. Promise.prototype.some = function Promise$some(count) {
  19816. return Promise$_Some(this, count, true);
  19817. };
  19818. };
  19819. },{"./some_promise_array.js":104}],104:[function(_dereq_,module,exports){
  19820. /**
  19821. * Copyright (c) 2014 Petka Antonov
  19822. *
  19823. * Permission is hereby granted, free of charge, to any person obtaining a copy
  19824. * of this software and associated documentation files (the "Software"), to deal
  19825. * in the Software without restriction, including without limitation the rights
  19826. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  19827. * copies of the Software, and to permit persons to whom the Software is
  19828. * furnished to do so, subject to the following conditions:</p>
  19829. *
  19830. * The above copyright notice and this permission notice shall be included in
  19831. * all copies or substantial portions of the Software.
  19832. *
  19833. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19834. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19835. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19836. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19837. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19838. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19839. * THE SOFTWARE.
  19840. *
  19841. */
  19842. "use strict";
  19843. module.exports = function (PromiseArray) {
  19844. var util = _dereq_("./util.js");
  19845. var RangeError = _dereq_("./errors.js").RangeError;
  19846. var inherits = util.inherits;
  19847. var isArray = util.isArray;
  19848. function SomePromiseArray(values, boundTo) {
  19849. this.constructor$(values, boundTo);
  19850. this._howMany = 0;
  19851. this._unwrap = false;
  19852. this._initialized = false;
  19853. }
  19854. inherits(SomePromiseArray, PromiseArray);
  19855. SomePromiseArray.prototype._init = function SomePromiseArray$_init() {
  19856. if (!this._initialized) {
  19857. return;
  19858. }
  19859. if (this._howMany === 0) {
  19860. this._resolve([]);
  19861. return;
  19862. }
  19863. this._init$(void 0, -2);
  19864. var isArrayResolved = isArray(this._values);
  19865. this._holes = isArrayResolved ? this._values.length - this.length() : 0;
  19866. if (!this._isResolved() &&
  19867. isArrayResolved &&
  19868. this._howMany > this._canPossiblyFulfill()) {
  19869. var message = "(Promise.some) input array contains less than " +
  19870. this._howMany + " promises";
  19871. this._reject(new RangeError(message));
  19872. }
  19873. };
  19874. SomePromiseArray.prototype.init = function SomePromiseArray$init() {
  19875. this._initialized = true;
  19876. this._init();
  19877. };
  19878. SomePromiseArray.prototype.setUnwrap = function SomePromiseArray$setUnwrap() {
  19879. this._unwrap = true;
  19880. };
  19881. SomePromiseArray.prototype.howMany = function SomePromiseArray$howMany() {
  19882. return this._howMany;
  19883. };
  19884. SomePromiseArray.prototype.setHowMany =
  19885. function SomePromiseArray$setHowMany(count) {
  19886. if (this._isResolved()) return;
  19887. this._howMany = count;
  19888. };
  19889. SomePromiseArray.prototype._promiseFulfilled =
  19890. function SomePromiseArray$_promiseFulfilled(value) {
  19891. if (this._isResolved()) return;
  19892. this._addFulfilled(value);
  19893. if (this._fulfilled() === this.howMany()) {
  19894. this._values.length = this.howMany();
  19895. if (this.howMany() === 1 && this._unwrap) {
  19896. this._resolve(this._values[0]);
  19897. }
  19898. else {
  19899. this._resolve(this._values);
  19900. }
  19901. }
  19902. };
  19903. SomePromiseArray.prototype._promiseRejected =
  19904. function SomePromiseArray$_promiseRejected(reason) {
  19905. if (this._isResolved()) return;
  19906. this._addRejected(reason);
  19907. if (this.howMany() > this._canPossiblyFulfill()) {
  19908. if (this._values.length === this.length()) {
  19909. this._reject([]);
  19910. }
  19911. else {
  19912. this._reject(this._values.slice(this.length() + this._holes));
  19913. }
  19914. }
  19915. };
  19916. SomePromiseArray.prototype._fulfilled = function SomePromiseArray$_fulfilled() {
  19917. return this._totalResolved;
  19918. };
  19919. SomePromiseArray.prototype._rejected = function SomePromiseArray$_rejected() {
  19920. return this._values.length - this.length() - this._holes;
  19921. };
  19922. SomePromiseArray.prototype._addRejected =
  19923. function SomePromiseArray$_addRejected(reason) {
  19924. this._values.push(reason);
  19925. };
  19926. SomePromiseArray.prototype._addFulfilled =
  19927. function SomePromiseArray$_addFulfilled(value) {
  19928. this._values[this._totalResolved++] = value;
  19929. };
  19930. SomePromiseArray.prototype._canPossiblyFulfill =
  19931. function SomePromiseArray$_canPossiblyFulfill() {
  19932. return this.length() - this._rejected();
  19933. };
  19934. return SomePromiseArray;
  19935. };
  19936. },{"./errors.js":80,"./util.js":108}],105:[function(_dereq_,module,exports){
  19937. /**
  19938. * Copyright (c) 2014 Petka Antonov
  19939. *
  19940. * Permission is hereby granted, free of charge, to any person obtaining a copy
  19941. * of this software and associated documentation files (the "Software"), to deal
  19942. * in the Software without restriction, including without limitation the rights
  19943. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  19944. * copies of the Software, and to permit persons to whom the Software is
  19945. * furnished to do so, subject to the following conditions:</p>
  19946. *
  19947. * The above copyright notice and this permission notice shall be included in
  19948. * all copies or substantial portions of the Software.
  19949. *
  19950. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19951. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19952. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19953. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19954. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19955. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19956. * THE SOFTWARE.
  19957. *
  19958. */
  19959. "use strict";
  19960. module.exports = function(Promise) {
  19961. function PromiseInspection(promise) {
  19962. if (promise !== void 0) {
  19963. this._bitField = promise._bitField;
  19964. this._settledValue = promise.isResolved()
  19965. ? promise._settledValue
  19966. : void 0;
  19967. }
  19968. else {
  19969. this._bitField = 0;
  19970. this._settledValue = void 0;
  19971. }
  19972. }
  19973. PromiseInspection.prototype.isFulfilled =
  19974. Promise.prototype.isFulfilled = function Promise$isFulfilled() {
  19975. return (this._bitField & 268435456) > 0;
  19976. };
  19977. PromiseInspection.prototype.isRejected =
  19978. Promise.prototype.isRejected = function Promise$isRejected() {
  19979. return (this._bitField & 134217728) > 0;
  19980. };
  19981. PromiseInspection.prototype.isPending =
  19982. Promise.prototype.isPending = function Promise$isPending() {
  19983. return (this._bitField & 402653184) === 0;
  19984. };
  19985. PromiseInspection.prototype.value =
  19986. Promise.prototype.value = function Promise$value() {
  19987. if (!this.isFulfilled()) {
  19988. throw new TypeError("cannot get fulfillment value of a non-fulfilled promise");
  19989. }
  19990. return this._settledValue;
  19991. };
  19992. PromiseInspection.prototype.error =
  19993. Promise.prototype.reason = function Promise$reason() {
  19994. if (!this.isRejected()) {
  19995. throw new TypeError("cannot get rejection reason of a non-rejected promise");
  19996. }
  19997. return this._settledValue;
  19998. };
  19999. PromiseInspection.prototype.isResolved =
  20000. Promise.prototype.isResolved = function Promise$isResolved() {
  20001. return (this._bitField & 402653184) > 0;
  20002. };
  20003. Promise.prototype.inspect = function Promise$inspect() {
  20004. return new PromiseInspection(this);
  20005. };
  20006. Promise.PromiseInspection = PromiseInspection;
  20007. };
  20008. },{}],106:[function(_dereq_,module,exports){
  20009. /**
  20010. * Copyright (c) 2014 Petka Antonov
  20011. *
  20012. * Permission is hereby granted, free of charge, to any person obtaining a copy
  20013. * of this software and associated documentation files (the "Software"), to deal
  20014. * in the Software without restriction, including without limitation the rights
  20015. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  20016. * copies of the Software, and to permit persons to whom the Software is
  20017. * furnished to do so, subject to the following conditions:</p>
  20018. *
  20019. * The above copyright notice and this permission notice shall be included in
  20020. * all copies or substantial portions of the Software.
  20021. *
  20022. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20023. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20024. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20025. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20026. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20027. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20028. * THE SOFTWARE.
  20029. *
  20030. */
  20031. "use strict";
  20032. module.exports = function(Promise, INTERNAL) {
  20033. var util = _dereq_("./util.js");
  20034. var canAttach = _dereq_("./errors.js").canAttach;
  20035. var errorObj = util.errorObj;
  20036. var isObject = util.isObject;
  20037. function getThen(obj) {
  20038. try {
  20039. return obj.then;
  20040. }
  20041. catch(e) {
  20042. errorObj.e = e;
  20043. return errorObj;
  20044. }
  20045. }
  20046. function Promise$_Cast(obj, originalPromise) {
  20047. if (isObject(obj)) {
  20048. if (obj instanceof Promise) {
  20049. return obj;
  20050. }
  20051. else if (isAnyBluebirdPromise(obj)) {
  20052. var ret = new Promise(INTERNAL);
  20053. ret._setTrace(void 0);
  20054. obj._then(
  20055. ret._fulfillUnchecked,
  20056. ret._rejectUncheckedCheckError,
  20057. ret._progressUnchecked,
  20058. ret,
  20059. null
  20060. );
  20061. ret._setFollowing();
  20062. return ret;
  20063. }
  20064. var then = getThen(obj);
  20065. if (then === errorObj) {
  20066. if (originalPromise !== void 0 && canAttach(then.e)) {
  20067. originalPromise._attachExtraTrace(then.e);
  20068. }
  20069. return Promise.reject(then.e);
  20070. }
  20071. else if (typeof then === "function") {
  20072. return Promise$_doThenable(obj, then, originalPromise);
  20073. }
  20074. }
  20075. return obj;
  20076. }
  20077. var hasProp = {}.hasOwnProperty;
  20078. function isAnyBluebirdPromise(obj) {
  20079. return hasProp.call(obj, "_promise0");
  20080. }
  20081. function Promise$_doThenable(x, then, originalPromise) {
  20082. var resolver = Promise.defer();
  20083. var called = false;
  20084. try {
  20085. then.call(
  20086. x,
  20087. Promise$_resolveFromThenable,
  20088. Promise$_rejectFromThenable,
  20089. Promise$_progressFromThenable
  20090. );
  20091. }
  20092. catch(e) {
  20093. if (!called) {
  20094. called = true;
  20095. var trace = canAttach(e) ? e : new Error(e + "");
  20096. if (originalPromise !== void 0) {
  20097. originalPromise._attachExtraTrace(trace);
  20098. }
  20099. resolver.promise._reject(e, trace);
  20100. }
  20101. }
  20102. return resolver.promise;
  20103. function Promise$_resolveFromThenable(y) {
  20104. if (called) return;
  20105. called = true;
  20106. if (x === y) {
  20107. var e = Promise._makeSelfResolutionError();
  20108. if (originalPromise !== void 0) {
  20109. originalPromise._attachExtraTrace(e);
  20110. }
  20111. resolver.promise._reject(e, void 0);
  20112. return;
  20113. }
  20114. resolver.resolve(y);
  20115. }
  20116. function Promise$_rejectFromThenable(r) {
  20117. if (called) return;
  20118. called = true;
  20119. var trace = canAttach(r) ? r : new Error(r + "");
  20120. if (originalPromise !== void 0) {
  20121. originalPromise._attachExtraTrace(trace);
  20122. }
  20123. resolver.promise._reject(r, trace);
  20124. }
  20125. function Promise$_progressFromThenable(v) {
  20126. if (called) return;
  20127. var promise = resolver.promise;
  20128. if (typeof promise._progress === "function") {
  20129. promise._progress(v);
  20130. }
  20131. }
  20132. }
  20133. Promise._cast = Promise$_Cast;
  20134. };
  20135. },{"./errors.js":80,"./util.js":108}],107:[function(_dereq_,module,exports){
  20136. /**
  20137. * Copyright (c) 2014 Petka Antonov
  20138. *
  20139. * Permission is hereby granted, free of charge, to any person obtaining a copy
  20140. * of this software and associated documentation files (the "Software"), to deal
  20141. * in the Software without restriction, including without limitation the rights
  20142. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  20143. * copies of the Software, and to permit persons to whom the Software is
  20144. * furnished to do so, subject to the following conditions:</p>
  20145. *
  20146. * The above copyright notice and this permission notice shall be included in
  20147. * all copies or substantial portions of the Software.
  20148. *
  20149. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20150. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20151. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20152. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20153. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20154. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20155. * THE SOFTWARE.
  20156. *
  20157. */
  20158. "use strict";
  20159. var global = _dereq_("./global.js");
  20160. var setTimeout = function(fn, ms) {
  20161. var $_len = arguments.length;var args = new Array($_len - 2); for(var $_i = 2; $_i < $_len; ++$_i) {args[$_i - 2] = arguments[$_i];}
  20162. global.setTimeout(function(){
  20163. fn.apply(void 0, args);
  20164. }, ms);
  20165. };
  20166. module.exports = function(Promise, INTERNAL) {
  20167. var util = _dereq_("./util.js");
  20168. var errors = _dereq_("./errors.js");
  20169. var apiRejection = _dereq_("./errors_api_rejection")(Promise);
  20170. var TimeoutError = Promise.TimeoutError;
  20171. var afterTimeout = function Promise$_afterTimeout(promise, message, ms) {
  20172. if (!promise.isPending()) return;
  20173. if (typeof message !== "string") {
  20174. message = "operation timed out after" + " " + ms + " ms"
  20175. }
  20176. var err = new TimeoutError(message);
  20177. errors.markAsOriginatingFromRejection(err);
  20178. promise._attachExtraTrace(err);
  20179. promise._rejectUnchecked(err);
  20180. };
  20181. var afterDelay = function Promise$_afterDelay(value, promise) {
  20182. promise._fulfill(value);
  20183. };
  20184. var delay = Promise.delay = function Promise$Delay(value, ms) {
  20185. if (ms === void 0) {
  20186. ms = value;
  20187. value = void 0;
  20188. }
  20189. ms = +ms;
  20190. var maybePromise = Promise._cast(value, void 0);
  20191. var promise = new Promise(INTERNAL);
  20192. if (maybePromise instanceof Promise) {
  20193. if (maybePromise._isBound()) {
  20194. promise._setBoundTo(maybePromise._boundTo);
  20195. }
  20196. if (maybePromise._cancellable()) {
  20197. promise._setCancellable();
  20198. promise._cancellationParent = maybePromise;
  20199. }
  20200. promise._setTrace(maybePromise);
  20201. promise._follow(maybePromise);
  20202. return promise.then(function(value) {
  20203. return Promise.delay(value, ms);
  20204. });
  20205. }
  20206. else {
  20207. promise._setTrace(void 0);
  20208. setTimeout(afterDelay, ms, value, promise);
  20209. }
  20210. return promise;
  20211. };
  20212. Promise.prototype.delay = function Promise$delay(ms) {
  20213. return delay(this, ms);
  20214. };
  20215. Promise.prototype.timeout = function Promise$timeout(ms, message) {
  20216. ms = +ms;
  20217. var ret = new Promise(INTERNAL);
  20218. ret._setTrace(this);
  20219. if (this._isBound()) ret._setBoundTo(this._boundTo);
  20220. if (this._cancellable()) {
  20221. ret._setCancellable();
  20222. ret._cancellationParent = this;
  20223. }
  20224. ret._follow(this);
  20225. setTimeout(afterTimeout, ms, ret, message, ms);
  20226. return ret;
  20227. };
  20228. };
  20229. },{"./errors.js":80,"./errors_api_rejection":81,"./global.js":86,"./util.js":108}],108:[function(_dereq_,module,exports){
  20230. /**
  20231. * Copyright (c) 2014 Petka Antonov
  20232. *
  20233. * Permission is hereby granted, free of charge, to any person obtaining a copy
  20234. * of this software and associated documentation files (the "Software"), to deal
  20235. * in the Software without restriction, including without limitation the rights
  20236. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  20237. * copies of the Software, and to permit persons to whom the Software is
  20238. * furnished to do so, subject to the following conditions:</p>
  20239. *
  20240. * The above copyright notice and this permission notice shall be included in
  20241. * all copies or substantial portions of the Software.
  20242. *
  20243. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20244. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20245. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20246. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20247. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20248. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20249. * THE SOFTWARE.
  20250. *
  20251. */
  20252. "use strict";
  20253. var global = _dereq_("./global.js");
  20254. var es5 = _dereq_("./es5.js");
  20255. var haveGetters = (function(){
  20256. try {
  20257. var o = {};
  20258. es5.defineProperty(o, "f", {
  20259. get: function () {
  20260. return 3;
  20261. }
  20262. });
  20263. return o.f === 3;
  20264. }
  20265. catch (e) {
  20266. return false;
  20267. }
  20268. })();
  20269. var canEvaluate = (function() {
  20270. if (typeof window !== "undefined" && window !== null &&
  20271. typeof window.document !== "undefined" &&
  20272. typeof navigator !== "undefined" && navigator !== null &&
  20273. typeof navigator.appName === "string" &&
  20274. window === global) {
  20275. return false;
  20276. }
  20277. return true;
  20278. })();
  20279. function deprecated(msg) {
  20280. if (typeof console !== "undefined" && console !== null &&
  20281. typeof console.warn === "function") {
  20282. console.warn("Bluebird: " + msg);
  20283. }
  20284. }
  20285. var errorObj = {e: {}};
  20286. function tryCatch1(fn, receiver, arg) {
  20287. try {
  20288. return fn.call(receiver, arg);
  20289. }
  20290. catch (e) {
  20291. errorObj.e = e;
  20292. return errorObj;
  20293. }
  20294. }
  20295. function tryCatch2(fn, receiver, arg, arg2) {
  20296. try {
  20297. return fn.call(receiver, arg, arg2);
  20298. }
  20299. catch (e) {
  20300. errorObj.e = e;
  20301. return errorObj;
  20302. }
  20303. }
  20304. function tryCatchApply(fn, args, receiver) {
  20305. try {
  20306. return fn.apply(receiver, args);
  20307. }
  20308. catch (e) {
  20309. errorObj.e = e;
  20310. return errorObj;
  20311. }
  20312. }
  20313. var inherits = function(Child, Parent) {
  20314. var hasProp = {}.hasOwnProperty;
  20315. function T() {
  20316. this.constructor = Child;
  20317. this.constructor$ = Parent;
  20318. for (var propertyName in Parent.prototype) {
  20319. if (hasProp.call(Parent.prototype, propertyName) &&
  20320. propertyName.charAt(propertyName.length-1) !== "$"
  20321. ) {
  20322. this[propertyName + "$"] = Parent.prototype[propertyName];
  20323. }
  20324. }
  20325. }
  20326. T.prototype = Parent.prototype;
  20327. Child.prototype = new T();
  20328. return Child.prototype;
  20329. };
  20330. function asString(val) {
  20331. return typeof val === "string" ? val : ("" + val);
  20332. }
  20333. function isPrimitive(val) {
  20334. return val == null || val === true || val === false ||
  20335. typeof val === "string" || typeof val === "number";
  20336. }
  20337. function isObject(value) {
  20338. return !isPrimitive(value);
  20339. }
  20340. function maybeWrapAsError(maybeError) {
  20341. if (!isPrimitive(maybeError)) return maybeError;
  20342. return new Error(asString(maybeError));
  20343. }
  20344. function withAppended(target, appendee) {
  20345. var len = target.length;
  20346. var ret = new Array(len + 1);
  20347. var i;
  20348. for (i = 0; i < len; ++i) {
  20349. ret[i] = target[i];
  20350. }
  20351. ret[i] = appendee;
  20352. return ret;
  20353. }
  20354. function notEnumerableProp(obj, name, value) {
  20355. if (isPrimitive(obj)) return obj;
  20356. var descriptor = {
  20357. value: value,
  20358. configurable: true,
  20359. enumerable: false,
  20360. writable: true
  20361. };
  20362. es5.defineProperty(obj, name, descriptor);
  20363. return obj;
  20364. }
  20365. var wrapsPrimitiveReceiver = (function() {
  20366. return this !== "string";
  20367. }).call("string");
  20368. function thrower(r) {
  20369. throw r;
  20370. }
  20371. function toFastProperties(obj) {
  20372. /*jshint -W027*/
  20373. function f() {}
  20374. f.prototype = obj;
  20375. return f;
  20376. eval(obj);
  20377. }
  20378. var ret = {
  20379. thrower: thrower,
  20380. isArray: es5.isArray,
  20381. haveGetters: haveGetters,
  20382. notEnumerableProp: notEnumerableProp,
  20383. isPrimitive: isPrimitive,
  20384. isObject: isObject,
  20385. canEvaluate: canEvaluate,
  20386. deprecated: deprecated,
  20387. errorObj: errorObj,
  20388. tryCatch1: tryCatch1,
  20389. tryCatch2: tryCatch2,
  20390. tryCatchApply: tryCatchApply,
  20391. inherits: inherits,
  20392. withAppended: withAppended,
  20393. asString: asString,
  20394. maybeWrapAsError: maybeWrapAsError,
  20395. wrapsPrimitiveReceiver: wrapsPrimitiveReceiver,
  20396. toFastProperties: toFastProperties
  20397. };
  20398. module.exports = ret;
  20399. },{"./es5.js":82,"./global.js":86}],109:[function(_dereq_,module,exports){
  20400. /**
  20401. * Module dependencies.
  20402. */
  20403. var global = (function() { return this; })();
  20404. /**
  20405. * WebSocket constructor.
  20406. */
  20407. var WebSocket = global.WebSocket || global.MozWebSocket;
  20408. /**
  20409. * Module exports.
  20410. */
  20411. module.exports = WebSocket ? ws : null;
  20412. /**
  20413. * WebSocket constructor.
  20414. *
  20415. * The third `opts` options object gets ignored in web browsers, since it's
  20416. * non-standard, and throws a TypeError if passed to the constructor.
  20417. * See: https://github.com/einaros/ws/issues/227
  20418. *
  20419. * @param {String} uri
  20420. * @param {Array} protocols (optional)
  20421. * @param {Object) opts (optional)
  20422. * @api public
  20423. */
  20424. function ws(uri, protocols, opts) {
  20425. var instance;
  20426. if (protocols) {
  20427. instance = new WebSocket(uri, protocols);
  20428. } else {
  20429. instance = new WebSocket(uri);
  20430. }
  20431. return instance;
  20432. }
  20433. if (WebSocket) ws.prototype = WebSocket.prototype;
  20434. },{}],110:[function(_dereq_,module,exports){
  20435. module.exports = _dereq_('./lib/hypertimer');
  20436. },{"./lib/hypertimer":111}],111:[function(_dereq_,module,exports){
  20437. var util = _dereq_('./util');
  20438. // enum for type of timeout
  20439. var TYPE = {
  20440. TIMEOUT: 0,
  20441. INTERVAL: 1,
  20442. TRIGGER: 2
  20443. };
  20444. var DISCRETE = 'discrete';
  20445. /**
  20446. * Create a new hypertimer
  20447. * @param {Object} [options] The following options are available:
  20448. * rate: number | 'discrete'
  20449. * The rate of speed of hyper time with
  20450. * respect to real-time in milliseconds
  20451. * per millisecond. Rate must be a
  20452. * positive number, or 'discrete' to
  20453. * run in discrete time (jumping from
  20454. * event to event). By default, rate is 1.
  20455. * deterministic: boolean
  20456. * If true (default), simultaneous events
  20457. * are executed in a deterministic order.
  20458. */
  20459. function hypertimer(options) {
  20460. // options
  20461. var rate = 1; // number of milliseconds per milliseconds
  20462. var deterministic = true; // run simultaneous events in a deterministic order
  20463. // properties
  20464. var running = false; // true when running
  20465. var realTime = null; // timestamp. the moment in real-time when hyperTime was set
  20466. var hyperTime = null; // timestamp. the start time in hyper-time
  20467. var timeouts = []; // array with all running timeouts
  20468. var current = {}; // the timeouts currently in progress (callback is being executed)
  20469. var timeoutId = null; // currently running timer
  20470. var idSeq = 0; // counter for unique timeout id's
  20471. // exported timer object with public functions and variables
  20472. var timer = {};
  20473. /**
  20474. * Change configuration options of the hypertimer, or retrieve current
  20475. * configuration.
  20476. * @param {Object} [options] The following options are available:
  20477. * rate: number | 'discrete'
  20478. * The rate of speed of hyper time with
  20479. * respect to real-time in milliseconds
  20480. * per millisecond. Rate must be a
  20481. * positive number, or 'discrete' to
  20482. * run in discrete time (jumping from
  20483. * event to event). By default, rate is 1.
  20484. * deterministic: boolean
  20485. * If true (default), simultaneous events
  20486. * are executed in a deterministic order.
  20487. * @return {Object} Returns the applied configuration
  20488. */
  20489. timer.config = function(options) {
  20490. if (options) {
  20491. if ('rate' in options) {
  20492. var newRate = (options.rate === DISCRETE) ? DISCRETE : Number(options.rate);
  20493. if (newRate !== DISCRETE && (isNaN(newRate) || newRate <= 0)) {
  20494. throw new TypeError('rate must be a positive number or the string "discrete"');
  20495. }
  20496. hyperTime = timer.now();
  20497. realTime = util.nowReal();
  20498. rate = newRate;
  20499. }
  20500. if ('deterministic' in options) {
  20501. deterministic = options.deterministic ? true : false;
  20502. }
  20503. }
  20504. // reschedule running timeouts
  20505. _schedule();
  20506. // return a copy of the configuration options
  20507. return {
  20508. rate: rate,
  20509. deterministic: deterministic
  20510. };
  20511. };
  20512. /**
  20513. * Set the time of the timer. To get the current time, use getTime() or now().
  20514. * @param {number | Date} time The time in hyper-time.
  20515. */
  20516. timer.setTime = function (time) {
  20517. if (time instanceof Date) {
  20518. hyperTime = time.valueOf();
  20519. }
  20520. else {
  20521. var newTime = Number(time);
  20522. if (isNaN(newTime)) {
  20523. throw new TypeError('time must be a Date or number');
  20524. }
  20525. hyperTime = newTime;
  20526. }
  20527. // reschedule running timeouts
  20528. _schedule();
  20529. };
  20530. /**
  20531. * Returns the current time of the timer as a number.
  20532. * See also getTime().
  20533. * @return {number} The time
  20534. */
  20535. timer.now = function () {
  20536. if (rate === DISCRETE) {
  20537. return hyperTime;
  20538. }
  20539. else {
  20540. if (running) {
  20541. // TODO: implement performance.now() / process.hrtime(time) for high precision calculation of time interval
  20542. var realInterval = util.nowReal() - realTime;
  20543. var hyperInterval = realInterval * rate;
  20544. return hyperTime + hyperInterval;
  20545. }
  20546. else {
  20547. return hyperTime;
  20548. }
  20549. }
  20550. };
  20551. /**
  20552. * Continue the timer.
  20553. */
  20554. timer['continue'] = function() {
  20555. realTime = util.nowReal();
  20556. running = true;
  20557. // reschedule running timeouts
  20558. _schedule();
  20559. };
  20560. /**
  20561. * Pause the timer. The timer can be continued again with `continue()`
  20562. */
  20563. timer.pause = function() {
  20564. hyperTime = timer.now();
  20565. realTime = null;
  20566. running = false;
  20567. // reschedule running timeouts (pauses them)
  20568. _schedule();
  20569. };
  20570. /**
  20571. * Returns the current time of the timer as Date.
  20572. * See also now().
  20573. * @return {Date} The time
  20574. */
  20575. // rename to getTime
  20576. timer.getTime = function() {
  20577. return new Date(timer.now());
  20578. };
  20579. /**
  20580. * Get the value of the hypertimer. This function returns the result of getTime().
  20581. * @return {Date} current time
  20582. */
  20583. timer.valueOf = timer.getTime;
  20584. /**
  20585. * Return a string representation of the current hyper-time.
  20586. * @returns {string} String representation
  20587. */
  20588. timer.toString = function () {
  20589. return timer.getTime().toString();
  20590. };
  20591. /**
  20592. * Set a timeout, which is triggered when the timeout occurs in hyper-time.
  20593. * See also setTrigger.
  20594. * @param {Function} callback Function executed when delay is exceeded.
  20595. * @param {number} delay The delay in milliseconds. When the delay is
  20596. * smaller or equal to zero, the callback is
  20597. * triggered immediately.
  20598. * @return {number} Returns a timeoutId which can be used to cancel the
  20599. * timeout using clearTimeout().
  20600. */
  20601. timer.setTimeout = function(callback, delay) {
  20602. var id = idSeq++;
  20603. var timestamp = timer.now() + delay;
  20604. if (isNaN(timestamp)) {
  20605. throw new TypeError('delay must be a number');
  20606. }
  20607. // add a new timeout to the queue
  20608. _queueTimeout({
  20609. id: id,
  20610. type: TYPE.TIMEOUT,
  20611. time: timestamp,
  20612. callback: callback
  20613. });
  20614. // reschedule the timeouts
  20615. _schedule();
  20616. return id;
  20617. };
  20618. /**
  20619. * Set a trigger, which is triggered when the timeout occurs in hyper-time.
  20620. * See also getTimeout.
  20621. * @param {Function} callback Function executed when timeout occurs.
  20622. * @param {Date | number} time An absolute moment in time (Date) when the
  20623. * callback will be triggered. When the date is
  20624. * a Date in the past, the callback is triggered
  20625. * immediately.
  20626. * @return {number} Returns a triggerId which can be used to cancel the
  20627. * trigger using clearTrigger().
  20628. */
  20629. timer.setTrigger = function (callback, time) {
  20630. var id = idSeq++;
  20631. var timestamp = Number(time);
  20632. if (isNaN(timestamp)) {
  20633. throw new TypeError('time must be a Date or number');
  20634. }
  20635. // add a new timeout to the queue
  20636. _queueTimeout({
  20637. id: id,
  20638. type: TYPE.TRIGGER,
  20639. time: timestamp,
  20640. callback: callback
  20641. });
  20642. // reschedule the timeouts
  20643. _schedule();
  20644. return id;
  20645. };
  20646. /**
  20647. * Trigger a callback every interval. Optionally, a start date can be provided
  20648. * to specify the first time the callback must be triggered.
  20649. * See also setTimeout and setTrigger.
  20650. * @param {Function} callback Function executed when delay is exceeded.
  20651. * @param {number} interval Interval in milliseconds. When interval
  20652. * is smaller than zero or is infinity, the
  20653. * interval will be set to zero and triggered
  20654. * with a maximum rate.
  20655. * @param {Date | number} [firstTime] An absolute moment in time (Date) when the
  20656. * callback will be triggered the first time.
  20657. * By default, firstTime = now() + interval.
  20658. * @return {number} Returns a intervalId which can be used to cancel the
  20659. * trigger using clearInterval().
  20660. */
  20661. timer.setInterval = function(callback, interval, firstTime) {
  20662. var id = idSeq++;
  20663. var _interval = Number(interval);
  20664. if (isNaN(_interval)) {
  20665. throw new TypeError('interval must be a number');
  20666. }
  20667. if (_interval < 0 || !isFinite(_interval)) {
  20668. _interval = 0;
  20669. }
  20670. var timestamp;
  20671. if (firstTime != undefined) {
  20672. timestamp = Number(firstTime);
  20673. if (isNaN(timestamp)) {
  20674. throw new TypeError('firstTime must be a Date or number');
  20675. }
  20676. }
  20677. else {
  20678. // firstTime is undefined or null
  20679. timestamp = (timer.now() + _interval);
  20680. }
  20681. // add a new timeout to the queue
  20682. _queueTimeout({
  20683. id: id,
  20684. type: TYPE.INTERVAL,
  20685. interval: _interval,
  20686. time: timestamp,
  20687. firstTime: timestamp,
  20688. occurrence: 0,
  20689. callback: callback
  20690. });
  20691. // reschedule the timeouts
  20692. _schedule();
  20693. return id;
  20694. };
  20695. /**
  20696. * Cancel a timeout
  20697. * @param {number} timeoutId The id of a timeout
  20698. */
  20699. timer.clearTimeout = function(timeoutId) {
  20700. // test whether timeout is currently being executed
  20701. if (current[timeoutId]) {
  20702. delete current[timeoutId];
  20703. return;
  20704. }
  20705. // find the timeout in the queue
  20706. for (var i = 0; i < timeouts.length; i++) {
  20707. if (timeouts[i].id === timeoutId) {
  20708. // remove this timeout from the queue
  20709. timeouts.splice(i, 1);
  20710. // reschedule timeouts
  20711. _schedule();
  20712. break;
  20713. }
  20714. }
  20715. };
  20716. /**
  20717. * Cancel a trigger
  20718. * @param {number} triggerId The id of a trigger
  20719. */
  20720. timer.clearTrigger = timer.clearTimeout;
  20721. timer.clearInterval = timer.clearTimeout;
  20722. /**
  20723. * Returns a list with the id's of all timeouts
  20724. * @returns {number[]} Timeout id's
  20725. */
  20726. timer.list = function () {
  20727. return timeouts.map(function (timeout) {
  20728. return timeout.id;
  20729. });
  20730. };
  20731. /**
  20732. * Clear all timeouts
  20733. */
  20734. timer.clear = function () {
  20735. // empty the queue
  20736. current = {};
  20737. timeouts = [];
  20738. // reschedule
  20739. _schedule();
  20740. };
  20741. /**
  20742. * Add a timeout to the queue. After the queue has been changed, the queue
  20743. * must be rescheduled by executing _reschedule()
  20744. * @param {{id: number, type: number, time: number, callback: Function}} timeout
  20745. * @private
  20746. */
  20747. function _queueTimeout(timeout) {
  20748. // insert the new timeout at the right place in the array, sorted by time
  20749. if (timeouts.length > 0) {
  20750. var i = timeouts.length - 1;
  20751. while (i >= 0 && timeouts[i].time > timeout.time) {
  20752. i--;
  20753. }
  20754. // insert the new timeout in the queue. Note that the timeout is
  20755. // inserted *after* existing timeouts with the exact *same* time,
  20756. // so the order in which they are executed is deterministic
  20757. timeouts.splice(i + 1, 0, timeout);
  20758. }
  20759. else {
  20760. // queue is empty, append the new timeout
  20761. timeouts.push(timeout);
  20762. }
  20763. }
  20764. /**
  20765. * Execute a timeout
  20766. * @param {{id: number, type: number, time: number, callback: function}} timeout
  20767. * @param {function} [callback]
  20768. * The callback is executed when the timeout's callback is
  20769. * finished. Called without parameters
  20770. * @private
  20771. */
  20772. function _execTimeout(timeout, callback) {
  20773. // store the timeout in the queue with timeouts in progress
  20774. // it can be cleared when a clearTimeout is executed inside the callback
  20775. current[timeout.id] = timeout;
  20776. function finish() {
  20777. // in case of an interval we have to reschedule on next cycle
  20778. // interval must not be cleared while executing the callback
  20779. if (timeout.type === TYPE.INTERVAL && current[timeout.id]) {
  20780. timeout.occurrence++;
  20781. timeout.time = timeout.firstTime + timeout.occurrence * timeout.interval;
  20782. _queueTimeout(timeout);
  20783. }
  20784. // remove the timeout from the queue with timeouts in progress
  20785. delete current[timeout.id];
  20786. if (typeof callback === 'function') callback();
  20787. }
  20788. // execute the callback
  20789. try {
  20790. if (timeout.callback.length == 0) {
  20791. // synchronous timeout, like `timer.setTimeout(function () {...}, delay)`
  20792. timeout.callback();
  20793. finish();
  20794. } else {
  20795. // asynchronous timeout, like `timer.setTimeout(function (done) {...; done(); }, delay)`
  20796. timeout.callback(finish);
  20797. }
  20798. } catch (err) {
  20799. // silently ignore errors thrown by the callback
  20800. finish();
  20801. }
  20802. }
  20803. /**
  20804. * Remove all timeouts occurring before or on the provided time from the
  20805. * queue and return them.
  20806. * @param {number} time A timestamp
  20807. * @returns {Array} returns an array containing all expired timeouts
  20808. * @private
  20809. */
  20810. function _getExpiredTimeouts(time) {
  20811. var i = 0;
  20812. while (i < timeouts.length && ((timeouts[i].time <= time) || !isFinite(timeouts[i].time))) {
  20813. i++;
  20814. }
  20815. var expired = timeouts.splice(0, i);
  20816. if (deterministic == false) {
  20817. // the array with expired timeouts is in deterministic order
  20818. // shuffle them
  20819. util.shuffle(expired);
  20820. }
  20821. return expired;
  20822. }
  20823. /**
  20824. * Reschedule all queued timeouts
  20825. * @private
  20826. */
  20827. function _schedule() {
  20828. // do not _schedule when there are timeouts in progress
  20829. // this can be the case with async timeouts in discrete time.
  20830. // _schedule will be executed again when all async timeouts are finished.
  20831. if (rate === DISCRETE && Object.keys(current).length > 0) {
  20832. return;
  20833. }
  20834. var next = timeouts[0];
  20835. // cancel timer when running
  20836. if (timeoutId) {
  20837. clearTimeout(timeoutId);
  20838. timeoutId = null;
  20839. }
  20840. if (running && next) {
  20841. // schedule next timeout
  20842. var time = next.time;
  20843. var delay = time - timer.now();
  20844. var realDelay = (rate === DISCRETE) ? 0 : delay / rate;
  20845. function onTimeout() {
  20846. // when running in discrete time, update the hyperTime to the time
  20847. // of the current event
  20848. if (rate === DISCRETE) {
  20849. hyperTime = time;
  20850. }
  20851. // grab all expired timeouts from the queue
  20852. var expired = _getExpiredTimeouts(time);
  20853. // note: expired.length can never be zero (on every change of the queue, we reschedule)
  20854. // execute all expired timeouts
  20855. if (rate === DISCRETE) {
  20856. // in discrete time, we execute all expired timeouts serially,
  20857. // and wait for their completion in order to guarantee deterministic
  20858. // order of execution
  20859. function next() {
  20860. var timeout = expired.shift();
  20861. if (timeout) {
  20862. _execTimeout(timeout, next);
  20863. }
  20864. else {
  20865. // schedule the next round
  20866. _schedule();
  20867. }
  20868. }
  20869. next();
  20870. }
  20871. else {
  20872. // in continuous time, we fire all timeouts in parallel,
  20873. // and don't await their completion (they can do async operations)
  20874. expired.forEach(_execTimeout);
  20875. // schedule the next round
  20876. _schedule();
  20877. }
  20878. }
  20879. timeoutId = setTimeout(onTimeout, realDelay);
  20880. }
  20881. }
  20882. Object.defineProperty(timer, 'running', {
  20883. get: function () {
  20884. return running;
  20885. }
  20886. });
  20887. timer.config(options); // apply options
  20888. timer.setTime(util.nowReal()); // set time as current real time
  20889. timer.continue(); // start the timer
  20890. return timer;
  20891. }
  20892. module.exports = hypertimer;
  20893. },{"./util":112}],112:[function(_dereq_,module,exports){
  20894. /* istanbul ignore else */
  20895. if (typeof Date.now === 'function') {
  20896. /**
  20897. * Helper function to get the current time
  20898. * @return {number} Current time
  20899. */
  20900. exports.nowReal = function () {
  20901. return Date.now();
  20902. }
  20903. }
  20904. else {
  20905. /**
  20906. * Helper function to get the current time
  20907. * @return {number} Current time
  20908. */
  20909. exports.nowReal = function () {
  20910. return new Date().valueOf();
  20911. }
  20912. }
  20913. /**
  20914. * Shuffle an array
  20915. *
  20916. * + Jonas Raoni Soares Silva
  20917. * @ http://jsfromhell.com/array/shuffle [v1.0]
  20918. *
  20919. * @param {Array} o Array to be shuffled
  20920. * @returns {Array} Returns the shuffled array
  20921. */
  20922. exports.shuffle = function (o){
  20923. for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
  20924. return o;
  20925. };
  20926. },{}],113:[function(_dereq_,module,exports){
  20927. (function (Buffer){
  20928. // uuid.js
  20929. //
  20930. // Copyright (c) 2010-2012 Robert Kieffer
  20931. // MIT License - http://opensource.org/licenses/mit-license.php
  20932. (function() {
  20933. var _global = this;
  20934. // Unique ID creation requires a high quality random # generator. We feature
  20935. // detect to determine the best RNG source, normalizing to a function that
  20936. // returns 128-bits of randomness, since that's what's usually required
  20937. var _rng;
  20938. // Node.js crypto-based RNG - http://nodejs.org/docs/v0.6.2/api/crypto.html
  20939. //
  20940. // Moderately fast, high quality
  20941. if (typeof(_dereq_) == 'function') {
  20942. try {
  20943. var _rb = _dereq_('crypto').randomBytes;
  20944. _rng = _rb && function() {return _rb(16);};
  20945. } catch(e) {}
  20946. }
  20947. if (!_rng && _global.crypto && crypto.getRandomValues) {
  20948. // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto
  20949. //
  20950. // Moderately fast, high quality
  20951. var _rnds8 = new Uint8Array(16);
  20952. _rng = function whatwgRNG() {
  20953. crypto.getRandomValues(_rnds8);
  20954. return _rnds8;
  20955. };
  20956. }
  20957. if (!_rng) {
  20958. // Math.random()-based (RNG)
  20959. //
  20960. // If all else fails, use Math.random(). It's fast, but is of unspecified
  20961. // quality.
  20962. var _rnds = new Array(16);
  20963. _rng = function() {
  20964. for (var i = 0, r; i < 16; i++) {
  20965. if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
  20966. _rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
  20967. }
  20968. return _rnds;
  20969. };
  20970. }
  20971. // Buffer class to use
  20972. var BufferClass = typeof(Buffer) == 'function' ? Buffer : Array;
  20973. // Maps for number <-> hex string conversion
  20974. var _byteToHex = [];
  20975. var _hexToByte = {};
  20976. for (var i = 0; i < 256; i++) {
  20977. _byteToHex[i] = (i + 0x100).toString(16).substr(1);
  20978. _hexToByte[_byteToHex[i]] = i;
  20979. }
  20980. // **`parse()` - Parse a UUID into it's component bytes**
  20981. function parse(s, buf, offset) {
  20982. var i = (buf && offset) || 0, ii = 0;
  20983. buf = buf || [];
  20984. s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {
  20985. if (ii < 16) { // Don't overflow!
  20986. buf[i + ii++] = _hexToByte[oct];
  20987. }
  20988. });
  20989. // Zero out remaining bytes if string was short
  20990. while (ii < 16) {
  20991. buf[i + ii++] = 0;
  20992. }
  20993. return buf;
  20994. }
  20995. // **`unparse()` - Convert UUID byte array (ala parse()) into a string**
  20996. function unparse(buf, offset) {
  20997. var i = offset || 0, bth = _byteToHex;
  20998. return bth[buf[i++]] + bth[buf[i++]] +
  20999. bth[buf[i++]] + bth[buf[i++]] + '-' +
  21000. bth[buf[i++]] + bth[buf[i++]] + '-' +
  21001. bth[buf[i++]] + bth[buf[i++]] + '-' +
  21002. bth[buf[i++]] + bth[buf[i++]] + '-' +
  21003. bth[buf[i++]] + bth[buf[i++]] +
  21004. bth[buf[i++]] + bth[buf[i++]] +
  21005. bth[buf[i++]] + bth[buf[i++]];
  21006. }
  21007. // **`v1()` - Generate time-based UUID**
  21008. //
  21009. // Inspired by https://github.com/LiosK/UUID.js
  21010. // and http://docs.python.org/library/uuid.html
  21011. // random #'s we need to init node and clockseq
  21012. var _seedBytes = _rng();
  21013. // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
  21014. var _nodeId = [
  21015. _seedBytes[0] | 0x01,
  21016. _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]
  21017. ];
  21018. // Per 4.2.2, randomize (14 bit) clockseq
  21019. var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;
  21020. // Previous uuid creation time
  21021. var _lastMSecs = 0, _lastNSecs = 0;
  21022. // See https://github.com/broofa/node-uuid for API details
  21023. function v1(options, buf, offset) {
  21024. var i = buf && offset || 0;
  21025. var b = buf || [];
  21026. options = options || {};
  21027. var clockseq = options.clockseq != null ? options.clockseq : _clockseq;
  21028. // UUID timestamps are 100 nano-second units since the Gregorian epoch,
  21029. // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
  21030. // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
  21031. // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
  21032. var msecs = options.msecs != null ? options.msecs : new Date().getTime();
  21033. // Per 4.2.1.2, use count of uuid's generated during the current clock
  21034. // cycle to simulate higher resolution clock
  21035. var nsecs = options.nsecs != null ? options.nsecs : _lastNSecs + 1;
  21036. // Time since last uuid creation (in msecs)
  21037. var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
  21038. // Per 4.2.1.2, Bump clockseq on clock regression
  21039. if (dt < 0 && options.clockseq == null) {
  21040. clockseq = clockseq + 1 & 0x3fff;
  21041. }
  21042. // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
  21043. // time interval
  21044. if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) {
  21045. nsecs = 0;
  21046. }
  21047. // Per 4.2.1.2 Throw error if too many uuids are requested
  21048. if (nsecs >= 10000) {
  21049. throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
  21050. }
  21051. _lastMSecs = msecs;
  21052. _lastNSecs = nsecs;
  21053. _clockseq = clockseq;
  21054. // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
  21055. msecs += 12219292800000;
  21056. // `time_low`
  21057. var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
  21058. b[i++] = tl >>> 24 & 0xff;
  21059. b[i++] = tl >>> 16 & 0xff;
  21060. b[i++] = tl >>> 8 & 0xff;
  21061. b[i++] = tl & 0xff;
  21062. // `time_mid`
  21063. var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
  21064. b[i++] = tmh >>> 8 & 0xff;
  21065. b[i++] = tmh & 0xff;
  21066. // `time_high_and_version`
  21067. b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
  21068. b[i++] = tmh >>> 16 & 0xff;
  21069. // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
  21070. b[i++] = clockseq >>> 8 | 0x80;
  21071. // `clock_seq_low`
  21072. b[i++] = clockseq & 0xff;
  21073. // `node`
  21074. var node = options.node || _nodeId;
  21075. for (var n = 0; n < 6; n++) {
  21076. b[i + n] = node[n];
  21077. }
  21078. return buf ? buf : unparse(b);
  21079. }
  21080. // **`v4()` - Generate random UUID**
  21081. // See https://github.com/broofa/node-uuid for API details
  21082. function v4(options, buf, offset) {
  21083. // Deprecated - 'format' argument, as supported in v1.2
  21084. var i = buf && offset || 0;
  21085. if (typeof(options) == 'string') {
  21086. buf = options == 'binary' ? new BufferClass(16) : null;
  21087. options = null;
  21088. }
  21089. options = options || {};
  21090. var rnds = options.random || (options.rng || _rng)();
  21091. // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
  21092. rnds[6] = (rnds[6] & 0x0f) | 0x40;
  21093. rnds[8] = (rnds[8] & 0x3f) | 0x80;
  21094. // Copy bytes to buffer, if provided
  21095. if (buf) {
  21096. for (var ii = 0; ii < 16; ii++) {
  21097. buf[i + ii] = rnds[ii];
  21098. }
  21099. }
  21100. return buf || unparse(rnds);
  21101. }
  21102. // Export public API
  21103. var uuid = v4;
  21104. uuid.v1 = v1;
  21105. uuid.v4 = v4;
  21106. uuid.parse = parse;
  21107. uuid.unparse = unparse;
  21108. uuid.BufferClass = BufferClass;
  21109. if (typeof define === 'function' && define.amd) {
  21110. // Publish as AMD module
  21111. define(function() {return uuid;});
  21112. } else if (typeof(module) != 'undefined' && module.exports) {
  21113. // Publish as node.js module
  21114. module.exports = uuid;
  21115. } else {
  21116. // Publish as global (in browsers)
  21117. var _previousRoot = _global.uuid;
  21118. // **`noConflict()` - (browser only) to reset global 'uuid' var**
  21119. uuid.noConflict = function() {
  21120. _global.uuid = _previousRoot;
  21121. return uuid;
  21122. };
  21123. _global.uuid = uuid;
  21124. }
  21125. }).call(this);
  21126. }).call(this,_dereq_("buffer").Buffer)
  21127. },{"buffer":128,"crypto":132}],114:[function(_dereq_,module,exports){
  21128. 'use strict';
  21129. module.exports = _dereq_('./lib/core.js')
  21130. _dereq_('./lib/done.js')
  21131. _dereq_('./lib/es6-extensions.js')
  21132. _dereq_('./lib/node-extensions.js')
  21133. },{"./lib/core.js":115,"./lib/done.js":116,"./lib/es6-extensions.js":117,"./lib/node-extensions.js":118}],115:[function(_dereq_,module,exports){
  21134. 'use strict';
  21135. var asap = _dereq_('asap')
  21136. module.exports = Promise;
  21137. function Promise(fn) {
  21138. if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new')
  21139. if (typeof fn !== 'function') throw new TypeError('not a function')
  21140. var state = null
  21141. var value = null
  21142. var deferreds = []
  21143. var self = this
  21144. this.then = function(onFulfilled, onRejected) {
  21145. return new self.constructor(function(resolve, reject) {
  21146. handle(new Handler(onFulfilled, onRejected, resolve, reject))
  21147. })
  21148. }
  21149. function handle(deferred) {
  21150. if (state === null) {
  21151. deferreds.push(deferred)
  21152. return
  21153. }
  21154. asap(function() {
  21155. var cb = state ? deferred.onFulfilled : deferred.onRejected
  21156. if (cb === null) {
  21157. (state ? deferred.resolve : deferred.reject)(value)
  21158. return
  21159. }
  21160. var ret
  21161. try {
  21162. ret = cb(value)
  21163. }
  21164. catch (e) {
  21165. deferred.reject(e)
  21166. return
  21167. }
  21168. deferred.resolve(ret)
  21169. })
  21170. }
  21171. function resolve(newValue) {
  21172. try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
  21173. if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.')
  21174. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  21175. var then = newValue.then
  21176. if (typeof then === 'function') {
  21177. doResolve(then.bind(newValue), resolve, reject)
  21178. return
  21179. }
  21180. }
  21181. state = true
  21182. value = newValue
  21183. finale()
  21184. } catch (e) { reject(e) }
  21185. }
  21186. function reject(newValue) {
  21187. state = false
  21188. value = newValue
  21189. finale()
  21190. }
  21191. function finale() {
  21192. for (var i = 0, len = deferreds.length; i < len; i++)
  21193. handle(deferreds[i])
  21194. deferreds = null
  21195. }
  21196. doResolve(fn, resolve, reject)
  21197. }
  21198. function Handler(onFulfilled, onRejected, resolve, reject){
  21199. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null
  21200. this.onRejected = typeof onRejected === 'function' ? onRejected : null
  21201. this.resolve = resolve
  21202. this.reject = reject
  21203. }
  21204. /**
  21205. * Take a potentially misbehaving resolver function and make sure
  21206. * onFulfilled and onRejected are only called once.
  21207. *
  21208. * Makes no guarantees about asynchrony.
  21209. */
  21210. function doResolve(fn, onFulfilled, onRejected) {
  21211. var done = false;
  21212. try {
  21213. fn(function (value) {
  21214. if (done) return
  21215. done = true
  21216. onFulfilled(value)
  21217. }, function (reason) {
  21218. if (done) return
  21219. done = true
  21220. onRejected(reason)
  21221. })
  21222. } catch (ex) {
  21223. if (done) return
  21224. done = true
  21225. onRejected(ex)
  21226. }
  21227. }
  21228. },{"asap":119}],116:[function(_dereq_,module,exports){
  21229. 'use strict';
  21230. var Promise = _dereq_('./core.js')
  21231. var asap = _dereq_('asap')
  21232. module.exports = Promise
  21233. Promise.prototype.done = function (onFulfilled, onRejected) {
  21234. var self = arguments.length ? this.then.apply(this, arguments) : this
  21235. self.then(null, function (err) {
  21236. asap(function () {
  21237. throw err
  21238. })
  21239. })
  21240. }
  21241. },{"./core.js":115,"asap":119}],117:[function(_dereq_,module,exports){
  21242. 'use strict';
  21243. //This file contains the ES6 extensions to the core Promises/A+ API
  21244. var Promise = _dereq_('./core.js')
  21245. var asap = _dereq_('asap')
  21246. module.exports = Promise
  21247. /* Static Functions */
  21248. function ValuePromise(value) {
  21249. this.then = function (onFulfilled) {
  21250. if (typeof onFulfilled !== 'function') return this
  21251. return new Promise(function (resolve, reject) {
  21252. asap(function () {
  21253. try {
  21254. resolve(onFulfilled(value))
  21255. } catch (ex) {
  21256. reject(ex);
  21257. }
  21258. })
  21259. })
  21260. }
  21261. }
  21262. ValuePromise.prototype = Promise.prototype
  21263. var TRUE = new ValuePromise(true)
  21264. var FALSE = new ValuePromise(false)
  21265. var NULL = new ValuePromise(null)
  21266. var UNDEFINED = new ValuePromise(undefined)
  21267. var ZERO = new ValuePromise(0)
  21268. var EMPTYSTRING = new ValuePromise('')
  21269. Promise.resolve = function (value) {
  21270. if (value instanceof Promise) return value
  21271. if (value === null) return NULL
  21272. if (value === undefined) return UNDEFINED
  21273. if (value === true) return TRUE
  21274. if (value === false) return FALSE
  21275. if (value === 0) return ZERO
  21276. if (value === '') return EMPTYSTRING
  21277. if (typeof value === 'object' || typeof value === 'function') {
  21278. try {
  21279. var then = value.then
  21280. if (typeof then === 'function') {
  21281. return new Promise(then.bind(value))
  21282. }
  21283. } catch (ex) {
  21284. return new Promise(function (resolve, reject) {
  21285. reject(ex)
  21286. })
  21287. }
  21288. }
  21289. return new ValuePromise(value)
  21290. }
  21291. Promise.all = function (arr) {
  21292. var args = Array.prototype.slice.call(arr)
  21293. return new Promise(function (resolve, reject) {
  21294. if (args.length === 0) return resolve([])
  21295. var remaining = args.length
  21296. function res(i, val) {
  21297. try {
  21298. if (val && (typeof val === 'object' || typeof val === 'function')) {
  21299. var then = val.then
  21300. if (typeof then === 'function') {
  21301. then.call(val, function (val) { res(i, val) }, reject)
  21302. return
  21303. }
  21304. }
  21305. args[i] = val
  21306. if (--remaining === 0) {
  21307. resolve(args);
  21308. }
  21309. } catch (ex) {
  21310. reject(ex)
  21311. }
  21312. }
  21313. for (var i = 0; i < args.length; i++) {
  21314. res(i, args[i])
  21315. }
  21316. })
  21317. }
  21318. Promise.reject = function (value) {
  21319. return new Promise(function (resolve, reject) {
  21320. reject(value);
  21321. });
  21322. }
  21323. Promise.race = function (values) {
  21324. return new Promise(function (resolve, reject) {
  21325. values.forEach(function(value){
  21326. Promise.resolve(value).then(resolve, reject);
  21327. })
  21328. });
  21329. }
  21330. /* Prototype Methods */
  21331. Promise.prototype['catch'] = function (onRejected) {
  21332. return this.then(null, onRejected);
  21333. }
  21334. },{"./core.js":115,"asap":119}],118:[function(_dereq_,module,exports){
  21335. 'use strict';
  21336. //This file contains then/promise specific extensions that are only useful for node.js interop
  21337. var Promise = _dereq_('./core.js')
  21338. var asap = _dereq_('asap')
  21339. module.exports = Promise
  21340. /* Static Functions */
  21341. Promise.denodeify = function (fn, argumentCount) {
  21342. argumentCount = argumentCount || Infinity
  21343. return function () {
  21344. var self = this
  21345. var args = Array.prototype.slice.call(arguments)
  21346. return new Promise(function (resolve, reject) {
  21347. while (args.length && args.length > argumentCount) {
  21348. args.pop()
  21349. }
  21350. args.push(function (err, res) {
  21351. if (err) reject(err)
  21352. else resolve(res)
  21353. })
  21354. fn.apply(self, args)
  21355. })
  21356. }
  21357. }
  21358. Promise.nodeify = function (fn) {
  21359. return function () {
  21360. var args = Array.prototype.slice.call(arguments)
  21361. var callback = typeof args[args.length - 1] === 'function' ? args.pop() : null
  21362. var ctx = this
  21363. try {
  21364. return fn.apply(this, arguments).nodeify(callback, ctx)
  21365. } catch (ex) {
  21366. if (callback === null || typeof callback == 'undefined') {
  21367. return new Promise(function (resolve, reject) { reject(ex) })
  21368. } else {
  21369. asap(function () {
  21370. callback.call(ctx, ex)
  21371. })
  21372. }
  21373. }
  21374. }
  21375. }
  21376. Promise.prototype.nodeify = function (callback, ctx) {
  21377. if (typeof callback != 'function') return this
  21378. this.then(function (value) {
  21379. asap(function () {
  21380. callback.call(ctx, null, value)
  21381. })
  21382. }, function (err) {
  21383. asap(function () {
  21384. callback.call(ctx, err)
  21385. })
  21386. })
  21387. }
  21388. },{"./core.js":115,"asap":119}],119:[function(_dereq_,module,exports){
  21389. (function (process){
  21390. // Use the fastest possible means to execute a task in a future turn
  21391. // of the event loop.
  21392. // linked list of tasks (single, with head node)
  21393. var head = {task: void 0, next: null};
  21394. var tail = head;
  21395. var flushing = false;
  21396. var requestFlush = void 0;
  21397. var isNodeJS = false;
  21398. function flush() {
  21399. /* jshint loopfunc: true */
  21400. while (head.next) {
  21401. head = head.next;
  21402. var task = head.task;
  21403. head.task = void 0;
  21404. var domain = head.domain;
  21405. if (domain) {
  21406. head.domain = void 0;
  21407. domain.enter();
  21408. }
  21409. try {
  21410. task();
  21411. } catch (e) {
  21412. if (isNodeJS) {
  21413. // In node, uncaught exceptions are considered fatal errors.
  21414. // Re-throw them synchronously to interrupt flushing!
  21415. // Ensure continuation if the uncaught exception is suppressed
  21416. // listening "uncaughtException" events (as domains does).
  21417. // Continue in next event to avoid tick recursion.
  21418. if (domain) {
  21419. domain.exit();
  21420. }
  21421. setTimeout(flush, 0);
  21422. if (domain) {
  21423. domain.enter();
  21424. }
  21425. throw e;
  21426. } else {
  21427. // In browsers, uncaught exceptions are not fatal.
  21428. // Re-throw them asynchronously to avoid slow-downs.
  21429. setTimeout(function() {
  21430. throw e;
  21431. }, 0);
  21432. }
  21433. }
  21434. if (domain) {
  21435. domain.exit();
  21436. }
  21437. }
  21438. flushing = false;
  21439. }
  21440. if (typeof process !== "undefined" && process.nextTick) {
  21441. // Node.js before 0.9. Note that some fake-Node environments, like the
  21442. // Mocha test runner, introduce a `process` global without a `nextTick`.
  21443. isNodeJS = true;
  21444. requestFlush = function () {
  21445. process.nextTick(flush);
  21446. };
  21447. } else if (typeof setImmediate === "function") {
  21448. // In IE10, Node.js 0.9+, or https://github.com/NobleJS/setImmediate
  21449. if (typeof window !== "undefined") {
  21450. requestFlush = setImmediate.bind(window, flush);
  21451. } else {
  21452. requestFlush = function () {
  21453. setImmediate(flush);
  21454. };
  21455. }
  21456. } else if (typeof MessageChannel !== "undefined") {
  21457. // modern browsers
  21458. // http://www.nonblocking.io/2011/06/windownexttick.html
  21459. var channel = new MessageChannel();
  21460. channel.port1.onmessage = flush;
  21461. requestFlush = function () {
  21462. channel.port2.postMessage(0);
  21463. };
  21464. } else {
  21465. // old browsers
  21466. requestFlush = function () {
  21467. setTimeout(flush, 0);
  21468. };
  21469. }
  21470. function asap(task) {
  21471. tail = tail.next = {
  21472. task: task,
  21473. domain: isNodeJS && process.domain,
  21474. next: null
  21475. };
  21476. if (!flushing) {
  21477. flushing = true;
  21478. requestFlush();
  21479. }
  21480. };
  21481. module.exports = asap;
  21482. }).call(this,_dereq_("C:\\Users\\Alex\\AppData\\Roaming\\npm\\node_modules\\browserify\\node_modules\\insert-module-globals\\node_modules\\process\\browser.js"))
  21483. },{"C:\\Users\\Alex\\AppData\\Roaming\\npm\\node_modules\\browserify\\node_modules\\insert-module-globals\\node_modules\\process\\browser.js":144}],120:[function(_dereq_,module,exports){
  21484. module.exports=_dereq_(62)
  21485. },{"./lib/agent":122}],121:[function(_dereq_,module,exports){
  21486. module.exports=_dereq_(63)
  21487. },{"C:\\Users\\Alex\\AppData\\Roaming\\npm\\node_modules\\browserify\\node_modules\\insert-module-globals\\node_modules\\process\\browser.js":144,"events":137,"http":138,"net":127,"url":157,"util":159}],122:[function(_dereq_,module,exports){
  21488. module.exports=_dereq_(64)
  21489. },{"./_http_agent":121,"C:\\Users\\Alex\\AppData\\Roaming\\npm\\node_modules\\browserify\\node_modules\\insert-module-globals\\node_modules\\process\\browser.js":144,"http":138,"https":142,"util":159}],123:[function(_dereq_,module,exports){
  21490. module.exports=_dereq_(65)
  21491. },{"agentkeepalive":120,"buffer":128,"crypto":132,"http":138,"https":142}],124:[function(_dereq_,module,exports){
  21492. (function (global){
  21493. 'use strict';
  21494. var width = 256;// each RC4 output is 0 <= x < 256
  21495. var chunks = 6;// at least six RC4 outputs for each double
  21496. var digits = 52;// there are 52 significant digits in a double
  21497. var pool = [];// pool: entropy pool starts empty
  21498. var GLOBAL = typeof global === 'undefined' ? window : global;
  21499. //
  21500. // The following constants are related to IEEE 754 limits.
  21501. //
  21502. var startdenom = Math.pow(width, chunks),
  21503. significance = Math.pow(2, digits),
  21504. overflow = significance * 2,
  21505. mask = width - 1;
  21506. var oldRandom = Math.random;
  21507. //
  21508. // seedrandom()
  21509. // This is the seedrandom function described above.
  21510. //
  21511. module.exports = function(seed, options) {
  21512. if (options && options.global === true) {
  21513. options.global = false;
  21514. Math.random = module.exports(seed, options);
  21515. options.global = true;
  21516. return Math.random;
  21517. }
  21518. var use_entropy = (options && options.entropy) || false;
  21519. var key = [];
  21520. // Flatten the seed string or build one from local entropy if needed.
  21521. var shortseed = mixkey(flatten(
  21522. use_entropy ? [seed, tostring(pool)] :
  21523. 0 in arguments ? seed : autoseed(), 3), key);
  21524. // Use the seed to initialize an ARC4 generator.
  21525. var arc4 = new ARC4(key);
  21526. // Mix the randomness into accumulated entropy.
  21527. mixkey(tostring(arc4.S), pool);
  21528. // Override Math.random
  21529. // This function returns a random double in [0, 1) that contains
  21530. // randomness in every bit of the mantissa of the IEEE 754 value.
  21531. return function() { // Closure to return a random double:
  21532. var n = arc4.g(chunks), // Start with a numerator n < 2 ^ 48
  21533. d = startdenom, // and denominator d = 2 ^ 48.
  21534. x = 0; // and no 'extra last byte'.
  21535. while (n < significance) { // Fill up all significant digits by
  21536. n = (n + x) * width; // shifting numerator and
  21537. d *= width; // denominator and generating a
  21538. x = arc4.g(1); // new least-significant-byte.
  21539. }
  21540. while (n >= overflow) { // To avoid rounding up, before adding
  21541. n /= 2; // last byte, shift everything
  21542. d /= 2; // right using integer Math until
  21543. x >>>= 1; // we have exactly the desired bits.
  21544. }
  21545. return (n + x) / d; // Form the number within [0, 1).
  21546. };
  21547. };
  21548. module.exports.resetGlobal = function () {
  21549. Math.random = oldRandom;
  21550. };
  21551. //
  21552. // ARC4
  21553. //
  21554. // An ARC4 implementation. The constructor takes a key in the form of
  21555. // an array of at most (width) integers that should be 0 <= x < (width).
  21556. //
  21557. // The g(count) method returns a pseudorandom integer that concatenates
  21558. // the next (count) outputs from ARC4. Its return value is a number x
  21559. // that is in the range 0 <= x < (width ^ count).
  21560. //
  21561. /** @constructor */
  21562. function ARC4(key) {
  21563. var t, keylen = key.length,
  21564. me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];
  21565. // The empty key [] is treated as [0].
  21566. if (!keylen) { key = [keylen++]; }
  21567. // Set up S using the standard key scheduling algorithm.
  21568. while (i < width) {
  21569. s[i] = i++;
  21570. }
  21571. for (i = 0; i < width; i++) {
  21572. s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))];
  21573. s[j] = t;
  21574. }
  21575. // The "g" method returns the next (count) outputs as one number.
  21576. (me.g = function(count) {
  21577. // Using instance members instead of closure state nearly doubles speed.
  21578. var t, r = 0,
  21579. i = me.i, j = me.j, s = me.S;
  21580. while (count--) {
  21581. t = s[i = mask & (i + 1)];
  21582. r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))];
  21583. }
  21584. me.i = i; me.j = j;
  21585. return r;
  21586. // For robust unpredictability discard an initial batch of values.
  21587. // See http://www.rsa.com/rsalabs/node.asp?id=2009
  21588. })(width);
  21589. }
  21590. //
  21591. // flatten()
  21592. // Converts an object tree to nested arrays of strings.
  21593. //
  21594. function flatten(obj, depth) {
  21595. var result = [], typ = (typeof obj)[0], prop;
  21596. if (depth && typ == 'o') {
  21597. for (prop in obj) {
  21598. try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}
  21599. }
  21600. }
  21601. return (result.length ? result : typ == 's' ? obj : obj + '\0');
  21602. }
  21603. //
  21604. // mixkey()
  21605. // Mixes a string seed into a key that is an array of integers, and
  21606. // returns a shortened string seed that is equivalent to the result key.
  21607. //
  21608. function mixkey(seed, key) {
  21609. var stringseed = seed + '', smear, j = 0;
  21610. while (j < stringseed.length) {
  21611. key[mask & j] =
  21612. mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++));
  21613. }
  21614. return tostring(key);
  21615. }
  21616. //
  21617. // autoseed()
  21618. // Returns an object for autoseeding, using window.crypto if available.
  21619. //
  21620. /** @param {Uint8Array=} seed */
  21621. function autoseed(seed) {
  21622. try {
  21623. GLOBAL.crypto.getRandomValues(seed = new Uint8Array(width));
  21624. return tostring(seed);
  21625. } catch (e) {
  21626. return [+new Date, GLOBAL, GLOBAL.navigator && GLOBAL.navigator.plugins,
  21627. GLOBAL.screen, tostring(pool)];
  21628. }
  21629. }
  21630. //
  21631. // tostring()
  21632. // Converts an array of charcodes to a string
  21633. //
  21634. function tostring(a) {
  21635. return String.fromCharCode.apply(0, a);
  21636. }
  21637. //
  21638. // When seedrandom.js is loaded, we immediately mix a few bits
  21639. // from the built-in RNG into the entropy pool. Because we do
  21640. // not want to intefere with determinstic PRNG state later,
  21641. // seedrandom will not call Math.random on its own again after
  21642. // initialization.
  21643. //
  21644. mixkey(Math.random(), pool);
  21645. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  21646. },{}],125:[function(_dereq_,module,exports){
  21647. exports = module.exports = function() {
  21648. var ret = '', value;
  21649. for (var i = 0; i < 32; i++) {
  21650. value = exports.random() * 16 | 0;
  21651. // Insert the hypens
  21652. if (i > 4 && i < 21 && ! (i % 4)) {
  21653. ret += '-';
  21654. }
  21655. // Add the next random character
  21656. ret += (
  21657. (i === 12) ? 4 : (
  21658. (i === 16) ? (value & 3 | 8) : value
  21659. )
  21660. ).toString(16);
  21661. }
  21662. return ret;
  21663. };
  21664. var uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
  21665. exports.isUUID = function(uuid) {
  21666. return uuidRegex.test(uuid);
  21667. };
  21668. exports.random = function() {
  21669. return Math.random();
  21670. };
  21671. },{}],126:[function(_dereq_,module,exports){
  21672. module.exports=_dereq_(109)
  21673. },{}],127:[function(_dereq_,module,exports){
  21674. },{}],128:[function(_dereq_,module,exports){
  21675. /*!
  21676. * The buffer module from node.js, for the browser.
  21677. *
  21678. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  21679. * @license MIT
  21680. */
  21681. var base64 = _dereq_('base64-js')
  21682. var ieee754 = _dereq_('ieee754')
  21683. exports.Buffer = Buffer
  21684. exports.SlowBuffer = Buffer
  21685. exports.INSPECT_MAX_BYTES = 50
  21686. Buffer.poolSize = 8192
  21687. /**
  21688. * If `Buffer._useTypedArrays`:
  21689. * === true Use Uint8Array implementation (fastest)
  21690. * === false Use Object implementation (compatible down to IE6)
  21691. */
  21692. Buffer._useTypedArrays = (function () {
  21693. // Detect if browser supports Typed Arrays. Supported browsers are IE 10+, Firefox 4+,
  21694. // Chrome 7+, Safari 5.1+, Opera 11.6+, iOS 4.2+. If the browser does not support adding
  21695. // properties to `Uint8Array` instances, then that's the same as no `Uint8Array` support
  21696. // because we need to be able to add all the node Buffer API methods. This is an issue
  21697. // in Firefox 4-29. Now fixed: https://bugzilla.mozilla.org/show_bug.cgi?id=695438
  21698. try {
  21699. var buf = new ArrayBuffer(0)
  21700. var arr = new Uint8Array(buf)
  21701. arr.foo = function () { return 42 }
  21702. return 42 === arr.foo() &&
  21703. typeof arr.subarray === 'function' // Chrome 9-10 lack `subarray`
  21704. } catch (e) {
  21705. return false
  21706. }
  21707. })()
  21708. /**
  21709. * Class: Buffer
  21710. * =============
  21711. *
  21712. * The Buffer constructor returns instances of `Uint8Array` that are augmented
  21713. * with function properties for all the node `Buffer` API functions. We use
  21714. * `Uint8Array` so that square bracket notation works as expected -- it returns
  21715. * a single octet.
  21716. *
  21717. * By augmenting the instances, we can avoid modifying the `Uint8Array`
  21718. * prototype.
  21719. */
  21720. function Buffer (subject, encoding, noZero) {
  21721. if (!(this instanceof Buffer))
  21722. return new Buffer(subject, encoding, noZero)
  21723. var type = typeof subject
  21724. // Workaround: node's base64 implementation allows for non-padded strings
  21725. // while base64-js does not.
  21726. if (encoding === 'base64' && type === 'string') {
  21727. subject = stringtrim(subject)
  21728. while (subject.length % 4 !== 0) {
  21729. subject = subject + '='
  21730. }
  21731. }
  21732. // Find the length
  21733. var length
  21734. if (type === 'number')
  21735. length = coerce(subject)
  21736. else if (type === 'string')
  21737. length = Buffer.byteLength(subject, encoding)
  21738. else if (type === 'object')
  21739. length = coerce(subject.length) // assume that object is array-like
  21740. else
  21741. throw new Error('First argument needs to be a number, array or string.')
  21742. var buf
  21743. if (Buffer._useTypedArrays) {
  21744. // Preferred: Return an augmented `Uint8Array` instance for best performance
  21745. buf = Buffer._augment(new Uint8Array(length))
  21746. } else {
  21747. // Fallback: Return THIS instance of Buffer (created by `new`)
  21748. buf = this
  21749. buf.length = length
  21750. buf._isBuffer = true
  21751. }
  21752. var i
  21753. if (Buffer._useTypedArrays && typeof subject.byteLength === 'number') {
  21754. // Speed optimization -- use set if we're copying from a typed array
  21755. buf._set(subject)
  21756. } else if (isArrayish(subject)) {
  21757. // Treat array-ish objects as a byte array
  21758. for (i = 0; i < length; i++) {
  21759. if (Buffer.isBuffer(subject))
  21760. buf[i] = subject.readUInt8(i)
  21761. else
  21762. buf[i] = subject[i]
  21763. }
  21764. } else if (type === 'string') {
  21765. buf.write(subject, 0, encoding)
  21766. } else if (type === 'number' && !Buffer._useTypedArrays && !noZero) {
  21767. for (i = 0; i < length; i++) {
  21768. buf[i] = 0
  21769. }
  21770. }
  21771. return buf
  21772. }
  21773. // STATIC METHODS
  21774. // ==============
  21775. Buffer.isEncoding = function (encoding) {
  21776. switch (String(encoding).toLowerCase()) {
  21777. case 'hex':
  21778. case 'utf8':
  21779. case 'utf-8':
  21780. case 'ascii':
  21781. case 'binary':
  21782. case 'base64':
  21783. case 'raw':
  21784. case 'ucs2':
  21785. case 'ucs-2':
  21786. case 'utf16le':
  21787. case 'utf-16le':
  21788. return true
  21789. default:
  21790. return false
  21791. }
  21792. }
  21793. Buffer.isBuffer = function (b) {
  21794. return !!(b !== null && b !== undefined && b._isBuffer)
  21795. }
  21796. Buffer.byteLength = function (str, encoding) {
  21797. var ret
  21798. str = str + ''
  21799. switch (encoding || 'utf8') {
  21800. case 'hex':
  21801. ret = str.length / 2
  21802. break
  21803. case 'utf8':
  21804. case 'utf-8':
  21805. ret = utf8ToBytes(str).length
  21806. break
  21807. case 'ascii':
  21808. case 'binary':
  21809. case 'raw':
  21810. ret = str.length
  21811. break
  21812. case 'base64':
  21813. ret = base64ToBytes(str).length
  21814. break
  21815. case 'ucs2':
  21816. case 'ucs-2':
  21817. case 'utf16le':
  21818. case 'utf-16le':
  21819. ret = str.length * 2
  21820. break
  21821. default:
  21822. throw new Error('Unknown encoding')
  21823. }
  21824. return ret
  21825. }
  21826. Buffer.concat = function (list, totalLength) {
  21827. assert(isArray(list), 'Usage: Buffer.concat(list, [totalLength])\n' +
  21828. 'list should be an Array.')
  21829. if (list.length === 0) {
  21830. return new Buffer(0)
  21831. } else if (list.length === 1) {
  21832. return list[0]
  21833. }
  21834. var i
  21835. if (typeof totalLength !== 'number') {
  21836. totalLength = 0
  21837. for (i = 0; i < list.length; i++) {
  21838. totalLength += list[i].length
  21839. }
  21840. }
  21841. var buf = new Buffer(totalLength)
  21842. var pos = 0
  21843. for (i = 0; i < list.length; i++) {
  21844. var item = list[i]
  21845. item.copy(buf, pos)
  21846. pos += item.length
  21847. }
  21848. return buf
  21849. }
  21850. // BUFFER INSTANCE METHODS
  21851. // =======================
  21852. function _hexWrite (buf, string, offset, length) {
  21853. offset = Number(offset) || 0
  21854. var remaining = buf.length - offset
  21855. if (!length) {
  21856. length = remaining
  21857. } else {
  21858. length = Number(length)
  21859. if (length > remaining) {
  21860. length = remaining
  21861. }
  21862. }
  21863. // must be an even number of digits
  21864. var strLen = string.length
  21865. assert(strLen % 2 === 0, 'Invalid hex string')
  21866. if (length > strLen / 2) {
  21867. length = strLen / 2
  21868. }
  21869. for (var i = 0; i < length; i++) {
  21870. var byte = parseInt(string.substr(i * 2, 2), 16)
  21871. assert(!isNaN(byte), 'Invalid hex string')
  21872. buf[offset + i] = byte
  21873. }
  21874. Buffer._charsWritten = i * 2
  21875. return i
  21876. }
  21877. function _utf8Write (buf, string, offset, length) {
  21878. var charsWritten = Buffer._charsWritten =
  21879. blitBuffer(utf8ToBytes(string), buf, offset, length)
  21880. return charsWritten
  21881. }
  21882. function _asciiWrite (buf, string, offset, length) {
  21883. var charsWritten = Buffer._charsWritten =
  21884. blitBuffer(asciiToBytes(string), buf, offset, length)
  21885. return charsWritten
  21886. }
  21887. function _binaryWrite (buf, string, offset, length) {
  21888. return _asciiWrite(buf, string, offset, length)
  21889. }
  21890. function _base64Write (buf, string, offset, length) {
  21891. var charsWritten = Buffer._charsWritten =
  21892. blitBuffer(base64ToBytes(string), buf, offset, length)
  21893. return charsWritten
  21894. }
  21895. function _utf16leWrite (buf, string, offset, length) {
  21896. var charsWritten = Buffer._charsWritten =
  21897. blitBuffer(utf16leToBytes(string), buf, offset, length)
  21898. return charsWritten
  21899. }
  21900. Buffer.prototype.write = function (string, offset, length, encoding) {
  21901. // Support both (string, offset, length, encoding)
  21902. // and the legacy (string, encoding, offset, length)
  21903. if (isFinite(offset)) {
  21904. if (!isFinite(length)) {
  21905. encoding = length
  21906. length = undefined
  21907. }
  21908. } else { // legacy
  21909. var swap = encoding
  21910. encoding = offset
  21911. offset = length
  21912. length = swap
  21913. }
  21914. offset = Number(offset) || 0
  21915. var remaining = this.length - offset
  21916. if (!length) {
  21917. length = remaining
  21918. } else {
  21919. length = Number(length)
  21920. if (length > remaining) {
  21921. length = remaining
  21922. }
  21923. }
  21924. encoding = String(encoding || 'utf8').toLowerCase()
  21925. var ret
  21926. switch (encoding) {
  21927. case 'hex':
  21928. ret = _hexWrite(this, string, offset, length)
  21929. break
  21930. case 'utf8':
  21931. case 'utf-8':
  21932. ret = _utf8Write(this, string, offset, length)
  21933. break
  21934. case 'ascii':
  21935. ret = _asciiWrite(this, string, offset, length)
  21936. break
  21937. case 'binary':
  21938. ret = _binaryWrite(this, string, offset, length)
  21939. break
  21940. case 'base64':
  21941. ret = _base64Write(this, string, offset, length)
  21942. break
  21943. case 'ucs2':
  21944. case 'ucs-2':
  21945. case 'utf16le':
  21946. case 'utf-16le':
  21947. ret = _utf16leWrite(this, string, offset, length)
  21948. break
  21949. default:
  21950. throw new Error('Unknown encoding')
  21951. }
  21952. return ret
  21953. }
  21954. Buffer.prototype.toString = function (encoding, start, end) {
  21955. var self = this
  21956. encoding = String(encoding || 'utf8').toLowerCase()
  21957. start = Number(start) || 0
  21958. end = (end !== undefined)
  21959. ? Number(end)
  21960. : end = self.length
  21961. // Fastpath empty strings
  21962. if (end === start)
  21963. return ''
  21964. var ret
  21965. switch (encoding) {
  21966. case 'hex':
  21967. ret = _hexSlice(self, start, end)
  21968. break
  21969. case 'utf8':
  21970. case 'utf-8':
  21971. ret = _utf8Slice(self, start, end)
  21972. break
  21973. case 'ascii':
  21974. ret = _asciiSlice(self, start, end)
  21975. break
  21976. case 'binary':
  21977. ret = _binarySlice(self, start, end)
  21978. break
  21979. case 'base64':
  21980. ret = _base64Slice(self, start, end)
  21981. break
  21982. case 'ucs2':
  21983. case 'ucs-2':
  21984. case 'utf16le':
  21985. case 'utf-16le':
  21986. ret = _utf16leSlice(self, start, end)
  21987. break
  21988. default:
  21989. throw new Error('Unknown encoding')
  21990. }
  21991. return ret
  21992. }
  21993. Buffer.prototype.toJSON = function () {
  21994. return {
  21995. type: 'Buffer',
  21996. data: Array.prototype.slice.call(this._arr || this, 0)
  21997. }
  21998. }
  21999. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  22000. Buffer.prototype.copy = function (target, target_start, start, end) {
  22001. var source = this
  22002. if (!start) start = 0
  22003. if (!end && end !== 0) end = this.length
  22004. if (!target_start) target_start = 0
  22005. // Copy 0 bytes; we're done
  22006. if (end === start) return
  22007. if (target.length === 0 || source.length === 0) return
  22008. // Fatal error conditions
  22009. assert(end >= start, 'sourceEnd < sourceStart')
  22010. assert(target_start >= 0 && target_start < target.length,
  22011. 'targetStart out of bounds')
  22012. assert(start >= 0 && start < source.length, 'sourceStart out of bounds')
  22013. assert(end >= 0 && end <= source.length, 'sourceEnd out of bounds')
  22014. // Are we oob?
  22015. if (end > this.length)
  22016. end = this.length
  22017. if (target.length - target_start < end - start)
  22018. end = target.length - target_start + start
  22019. var len = end - start
  22020. if (len < 100 || !Buffer._useTypedArrays) {
  22021. for (var i = 0; i < len; i++)
  22022. target[i + target_start] = this[i + start]
  22023. } else {
  22024. target._set(this.subarray(start, start + len), target_start)
  22025. }
  22026. }
  22027. function _base64Slice (buf, start, end) {
  22028. if (start === 0 && end === buf.length) {
  22029. return base64.fromByteArray(buf)
  22030. } else {
  22031. return base64.fromByteArray(buf.slice(start, end))
  22032. }
  22033. }
  22034. function _utf8Slice (buf, start, end) {
  22035. var res = ''
  22036. var tmp = ''
  22037. end = Math.min(buf.length, end)
  22038. for (var i = start; i < end; i++) {
  22039. if (buf[i] <= 0x7F) {
  22040. res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i])
  22041. tmp = ''
  22042. } else {
  22043. tmp += '%' + buf[i].toString(16)
  22044. }
  22045. }
  22046. return res + decodeUtf8Char(tmp)
  22047. }
  22048. function _asciiSlice (buf, start, end) {
  22049. var ret = ''
  22050. end = Math.min(buf.length, end)
  22051. for (var i = start; i < end; i++)
  22052. ret += String.fromCharCode(buf[i])
  22053. return ret
  22054. }
  22055. function _binarySlice (buf, start, end) {
  22056. return _asciiSlice(buf, start, end)
  22057. }
  22058. function _hexSlice (buf, start, end) {
  22059. var len = buf.length
  22060. if (!start || start < 0) start = 0
  22061. if (!end || end < 0 || end > len) end = len
  22062. var out = ''
  22063. for (var i = start; i < end; i++) {
  22064. out += toHex(buf[i])
  22065. }
  22066. return out
  22067. }
  22068. function _utf16leSlice (buf, start, end) {
  22069. var bytes = buf.slice(start, end)
  22070. var res = ''
  22071. for (var i = 0; i < bytes.length; i += 2) {
  22072. res += String.fromCharCode(bytes[i] + bytes[i+1] * 256)
  22073. }
  22074. return res
  22075. }
  22076. Buffer.prototype.slice = function (start, end) {
  22077. var len = this.length
  22078. start = clamp(start, len, 0)
  22079. end = clamp(end, len, len)
  22080. if (Buffer._useTypedArrays) {
  22081. return Buffer._augment(this.subarray(start, end))
  22082. } else {
  22083. var sliceLen = end - start
  22084. var newBuf = new Buffer(sliceLen, undefined, true)
  22085. for (var i = 0; i < sliceLen; i++) {
  22086. newBuf[i] = this[i + start]
  22087. }
  22088. return newBuf
  22089. }
  22090. }
  22091. // `get` will be removed in Node 0.13+
  22092. Buffer.prototype.get = function (offset) {
  22093. console.log('.get() is deprecated. Access using array indexes instead.')
  22094. return this.readUInt8(offset)
  22095. }
  22096. // `set` will be removed in Node 0.13+
  22097. Buffer.prototype.set = function (v, offset) {
  22098. console.log('.set() is deprecated. Access using array indexes instead.')
  22099. return this.writeUInt8(v, offset)
  22100. }
  22101. Buffer.prototype.readUInt8 = function (offset, noAssert) {
  22102. if (!noAssert) {
  22103. assert(offset !== undefined && offset !== null, 'missing offset')
  22104. assert(offset < this.length, 'Trying to read beyond buffer length')
  22105. }
  22106. if (offset >= this.length)
  22107. return
  22108. return this[offset]
  22109. }
  22110. function _readUInt16 (buf, offset, littleEndian, noAssert) {
  22111. if (!noAssert) {
  22112. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  22113. assert(offset !== undefined && offset !== null, 'missing offset')
  22114. assert(offset + 1 < buf.length, 'Trying to read beyond buffer length')
  22115. }
  22116. var len = buf.length
  22117. if (offset >= len)
  22118. return
  22119. var val
  22120. if (littleEndian) {
  22121. val = buf[offset]
  22122. if (offset + 1 < len)
  22123. val |= buf[offset + 1] << 8
  22124. } else {
  22125. val = buf[offset] << 8
  22126. if (offset + 1 < len)
  22127. val |= buf[offset + 1]
  22128. }
  22129. return val
  22130. }
  22131. Buffer.prototype.readUInt16LE = function (offset, noAssert) {
  22132. return _readUInt16(this, offset, true, noAssert)
  22133. }
  22134. Buffer.prototype.readUInt16BE = function (offset, noAssert) {
  22135. return _readUInt16(this, offset, false, noAssert)
  22136. }
  22137. function _readUInt32 (buf, offset, littleEndian, noAssert) {
  22138. if (!noAssert) {
  22139. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  22140. assert(offset !== undefined && offset !== null, 'missing offset')
  22141. assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
  22142. }
  22143. var len = buf.length
  22144. if (offset >= len)
  22145. return
  22146. var val
  22147. if (littleEndian) {
  22148. if (offset + 2 < len)
  22149. val = buf[offset + 2] << 16
  22150. if (offset + 1 < len)
  22151. val |= buf[offset + 1] << 8
  22152. val |= buf[offset]
  22153. if (offset + 3 < len)
  22154. val = val + (buf[offset + 3] << 24 >>> 0)
  22155. } else {
  22156. if (offset + 1 < len)
  22157. val = buf[offset + 1] << 16
  22158. if (offset + 2 < len)
  22159. val |= buf[offset + 2] << 8
  22160. if (offset + 3 < len)
  22161. val |= buf[offset + 3]
  22162. val = val + (buf[offset] << 24 >>> 0)
  22163. }
  22164. return val
  22165. }
  22166. Buffer.prototype.readUInt32LE = function (offset, noAssert) {
  22167. return _readUInt32(this, offset, true, noAssert)
  22168. }
  22169. Buffer.prototype.readUInt32BE = function (offset, noAssert) {
  22170. return _readUInt32(this, offset, false, noAssert)
  22171. }
  22172. Buffer.prototype.readInt8 = function (offset, noAssert) {
  22173. if (!noAssert) {
  22174. assert(offset !== undefined && offset !== null,
  22175. 'missing offset')
  22176. assert(offset < this.length, 'Trying to read beyond buffer length')
  22177. }
  22178. if (offset >= this.length)
  22179. return
  22180. var neg = this[offset] & 0x80
  22181. if (neg)
  22182. return (0xff - this[offset] + 1) * -1
  22183. else
  22184. return this[offset]
  22185. }
  22186. function _readInt16 (buf, offset, littleEndian, noAssert) {
  22187. if (!noAssert) {
  22188. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  22189. assert(offset !== undefined && offset !== null, 'missing offset')
  22190. assert(offset + 1 < buf.length, 'Trying to read beyond buffer length')
  22191. }
  22192. var len = buf.length
  22193. if (offset >= len)
  22194. return
  22195. var val = _readUInt16(buf, offset, littleEndian, true)
  22196. var neg = val & 0x8000
  22197. if (neg)
  22198. return (0xffff - val + 1) * -1
  22199. else
  22200. return val
  22201. }
  22202. Buffer.prototype.readInt16LE = function (offset, noAssert) {
  22203. return _readInt16(this, offset, true, noAssert)
  22204. }
  22205. Buffer.prototype.readInt16BE = function (offset, noAssert) {
  22206. return _readInt16(this, offset, false, noAssert)
  22207. }
  22208. function _readInt32 (buf, offset, littleEndian, noAssert) {
  22209. if (!noAssert) {
  22210. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  22211. assert(offset !== undefined && offset !== null, 'missing offset')
  22212. assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
  22213. }
  22214. var len = buf.length
  22215. if (offset >= len)
  22216. return
  22217. var val = _readUInt32(buf, offset, littleEndian, true)
  22218. var neg = val & 0x80000000
  22219. if (neg)
  22220. return (0xffffffff - val + 1) * -1
  22221. else
  22222. return val
  22223. }
  22224. Buffer.prototype.readInt32LE = function (offset, noAssert) {
  22225. return _readInt32(this, offset, true, noAssert)
  22226. }
  22227. Buffer.prototype.readInt32BE = function (offset, noAssert) {
  22228. return _readInt32(this, offset, false, noAssert)
  22229. }
  22230. function _readFloat (buf, offset, littleEndian, noAssert) {
  22231. if (!noAssert) {
  22232. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  22233. assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
  22234. }
  22235. return ieee754.read(buf, offset, littleEndian, 23, 4)
  22236. }
  22237. Buffer.prototype.readFloatLE = function (offset, noAssert) {
  22238. return _readFloat(this, offset, true, noAssert)
  22239. }
  22240. Buffer.prototype.readFloatBE = function (offset, noAssert) {
  22241. return _readFloat(this, offset, false, noAssert)
  22242. }
  22243. function _readDouble (buf, offset, littleEndian, noAssert) {
  22244. if (!noAssert) {
  22245. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  22246. assert(offset + 7 < buf.length, 'Trying to read beyond buffer length')
  22247. }
  22248. return ieee754.read(buf, offset, littleEndian, 52, 8)
  22249. }
  22250. Buffer.prototype.readDoubleLE = function (offset, noAssert) {
  22251. return _readDouble(this, offset, true, noAssert)
  22252. }
  22253. Buffer.prototype.readDoubleBE = function (offset, noAssert) {
  22254. return _readDouble(this, offset, false, noAssert)
  22255. }
  22256. Buffer.prototype.writeUInt8 = function (value, offset, noAssert) {
  22257. if (!noAssert) {
  22258. assert(value !== undefined && value !== null, 'missing value')
  22259. assert(offset !== undefined && offset !== null, 'missing offset')
  22260. assert(offset < this.length, 'trying to write beyond buffer length')
  22261. verifuint(value, 0xff)
  22262. }
  22263. if (offset >= this.length) return
  22264. this[offset] = value
  22265. }
  22266. function _writeUInt16 (buf, value, offset, littleEndian, noAssert) {
  22267. if (!noAssert) {
  22268. assert(value !== undefined && value !== null, 'missing value')
  22269. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  22270. assert(offset !== undefined && offset !== null, 'missing offset')
  22271. assert(offset + 1 < buf.length, 'trying to write beyond buffer length')
  22272. verifuint(value, 0xffff)
  22273. }
  22274. var len = buf.length
  22275. if (offset >= len)
  22276. return
  22277. for (var i = 0, j = Math.min(len - offset, 2); i < j; i++) {
  22278. buf[offset + i] =
  22279. (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  22280. (littleEndian ? i : 1 - i) * 8
  22281. }
  22282. }
  22283. Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) {
  22284. _writeUInt16(this, value, offset, true, noAssert)
  22285. }
  22286. Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) {
  22287. _writeUInt16(this, value, offset, false, noAssert)
  22288. }
  22289. function _writeUInt32 (buf, value, offset, littleEndian, noAssert) {
  22290. if (!noAssert) {
  22291. assert(value !== undefined && value !== null, 'missing value')
  22292. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  22293. assert(offset !== undefined && offset !== null, 'missing offset')
  22294. assert(offset + 3 < buf.length, 'trying to write beyond buffer length')
  22295. verifuint(value, 0xffffffff)
  22296. }
  22297. var len = buf.length
  22298. if (offset >= len)
  22299. return
  22300. for (var i = 0, j = Math.min(len - offset, 4); i < j; i++) {
  22301. buf[offset + i] =
  22302. (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  22303. }
  22304. }
  22305. Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) {
  22306. _writeUInt32(this, value, offset, true, noAssert)
  22307. }
  22308. Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) {
  22309. _writeUInt32(this, value, offset, false, noAssert)
  22310. }
  22311. Buffer.prototype.writeInt8 = function (value, offset, noAssert) {
  22312. if (!noAssert) {
  22313. assert(value !== undefined && value !== null, 'missing value')
  22314. assert(offset !== undefined && offset !== null, 'missing offset')
  22315. assert(offset < this.length, 'Trying to write beyond buffer length')
  22316. verifsint(value, 0x7f, -0x80)
  22317. }
  22318. if (offset >= this.length)
  22319. return
  22320. if (value >= 0)
  22321. this.writeUInt8(value, offset, noAssert)
  22322. else
  22323. this.writeUInt8(0xff + value + 1, offset, noAssert)
  22324. }
  22325. function _writeInt16 (buf, value, offset, littleEndian, noAssert) {
  22326. if (!noAssert) {
  22327. assert(value !== undefined && value !== null, 'missing value')
  22328. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  22329. assert(offset !== undefined && offset !== null, 'missing offset')
  22330. assert(offset + 1 < buf.length, 'Trying to write beyond buffer length')
  22331. verifsint(value, 0x7fff, -0x8000)
  22332. }
  22333. var len = buf.length
  22334. if (offset >= len)
  22335. return
  22336. if (value >= 0)
  22337. _writeUInt16(buf, value, offset, littleEndian, noAssert)
  22338. else
  22339. _writeUInt16(buf, 0xffff + value + 1, offset, littleEndian, noAssert)
  22340. }
  22341. Buffer.prototype.writeInt16LE = function (value, offset, noAssert) {
  22342. _writeInt16(this, value, offset, true, noAssert)
  22343. }
  22344. Buffer.prototype.writeInt16BE = function (value, offset, noAssert) {
  22345. _writeInt16(this, value, offset, false, noAssert)
  22346. }
  22347. function _writeInt32 (buf, value, offset, littleEndian, noAssert) {
  22348. if (!noAssert) {
  22349. assert(value !== undefined && value !== null, 'missing value')
  22350. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  22351. assert(offset !== undefined && offset !== null, 'missing offset')
  22352. assert(offset + 3 < buf.length, 'Trying to write beyond buffer length')
  22353. verifsint(value, 0x7fffffff, -0x80000000)
  22354. }
  22355. var len = buf.length
  22356. if (offset >= len)
  22357. return
  22358. if (value >= 0)
  22359. _writeUInt32(buf, value, offset, littleEndian, noAssert)
  22360. else
  22361. _writeUInt32(buf, 0xffffffff + value + 1, offset, littleEndian, noAssert)
  22362. }
  22363. Buffer.prototype.writeInt32LE = function (value, offset, noAssert) {
  22364. _writeInt32(this, value, offset, true, noAssert)
  22365. }
  22366. Buffer.prototype.writeInt32BE = function (value, offset, noAssert) {
  22367. _writeInt32(this, value, offset, false, noAssert)
  22368. }
  22369. function _writeFloat (buf, value, offset, littleEndian, noAssert) {
  22370. if (!noAssert) {
  22371. assert(value !== undefined && value !== null, 'missing value')
  22372. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  22373. assert(offset !== undefined && offset !== null, 'missing offset')
  22374. assert(offset + 3 < buf.length, 'Trying to write beyond buffer length')
  22375. verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38)
  22376. }
  22377. var len = buf.length
  22378. if (offset >= len)
  22379. return
  22380. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  22381. }
  22382. Buffer.prototype.writeFloatLE = function (value, offset, noAssert) {
  22383. _writeFloat(this, value, offset, true, noAssert)
  22384. }
  22385. Buffer.prototype.writeFloatBE = function (value, offset, noAssert) {
  22386. _writeFloat(this, value, offset, false, noAssert)
  22387. }
  22388. function _writeDouble (buf, value, offset, littleEndian, noAssert) {
  22389. if (!noAssert) {
  22390. assert(value !== undefined && value !== null, 'missing value')
  22391. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  22392. assert(offset !== undefined && offset !== null, 'missing offset')
  22393. assert(offset + 7 < buf.length,
  22394. 'Trying to write beyond buffer length')
  22395. verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308)
  22396. }
  22397. var len = buf.length
  22398. if (offset >= len)
  22399. return
  22400. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  22401. }
  22402. Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) {
  22403. _writeDouble(this, value, offset, true, noAssert)
  22404. }
  22405. Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) {
  22406. _writeDouble(this, value, offset, false, noAssert)
  22407. }
  22408. // fill(value, start=0, end=buffer.length)
  22409. Buffer.prototype.fill = function (value, start, end) {
  22410. if (!value) value = 0
  22411. if (!start) start = 0
  22412. if (!end) end = this.length
  22413. if (typeof value === 'string') {
  22414. value = value.charCodeAt(0)
  22415. }
  22416. assert(typeof value === 'number' && !isNaN(value), 'value is not a number')
  22417. assert(end >= start, 'end < start')
  22418. // Fill 0 bytes; we're done
  22419. if (end === start) return
  22420. if (this.length === 0) return
  22421. assert(start >= 0 && start < this.length, 'start out of bounds')
  22422. assert(end >= 0 && end <= this.length, 'end out of bounds')
  22423. for (var i = start; i < end; i++) {
  22424. this[i] = value
  22425. }
  22426. }
  22427. Buffer.prototype.inspect = function () {
  22428. var out = []
  22429. var len = this.length
  22430. for (var i = 0; i < len; i++) {
  22431. out[i] = toHex(this[i])
  22432. if (i === exports.INSPECT_MAX_BYTES) {
  22433. out[i + 1] = '...'
  22434. break
  22435. }
  22436. }
  22437. return '<Buffer ' + out.join(' ') + '>'
  22438. }
  22439. /**
  22440. * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
  22441. * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
  22442. */
  22443. Buffer.prototype.toArrayBuffer = function () {
  22444. if (typeof Uint8Array !== 'undefined') {
  22445. if (Buffer._useTypedArrays) {
  22446. return (new Buffer(this)).buffer
  22447. } else {
  22448. var buf = new Uint8Array(this.length)
  22449. for (var i = 0, len = buf.length; i < len; i += 1)
  22450. buf[i] = this[i]
  22451. return buf.buffer
  22452. }
  22453. } else {
  22454. throw new Error('Buffer.toArrayBuffer not supported in this browser')
  22455. }
  22456. }
  22457. // HELPER FUNCTIONS
  22458. // ================
  22459. function stringtrim (str) {
  22460. if (str.trim) return str.trim()
  22461. return str.replace(/^\s+|\s+$/g, '')
  22462. }
  22463. var BP = Buffer.prototype
  22464. /**
  22465. * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
  22466. */
  22467. Buffer._augment = function (arr) {
  22468. arr._isBuffer = true
  22469. // save reference to original Uint8Array get/set methods before overwriting
  22470. arr._get = arr.get
  22471. arr._set = arr.set
  22472. // deprecated, will be removed in node 0.13+
  22473. arr.get = BP.get
  22474. arr.set = BP.set
  22475. arr.write = BP.write
  22476. arr.toString = BP.toString
  22477. arr.toLocaleString = BP.toString
  22478. arr.toJSON = BP.toJSON
  22479. arr.copy = BP.copy
  22480. arr.slice = BP.slice
  22481. arr.readUInt8 = BP.readUInt8
  22482. arr.readUInt16LE = BP.readUInt16LE
  22483. arr.readUInt16BE = BP.readUInt16BE
  22484. arr.readUInt32LE = BP.readUInt32LE
  22485. arr.readUInt32BE = BP.readUInt32BE
  22486. arr.readInt8 = BP.readInt8
  22487. arr.readInt16LE = BP.readInt16LE
  22488. arr.readInt16BE = BP.readInt16BE
  22489. arr.readInt32LE = BP.readInt32LE
  22490. arr.readInt32BE = BP.readInt32BE
  22491. arr.readFloatLE = BP.readFloatLE
  22492. arr.readFloatBE = BP.readFloatBE
  22493. arr.readDoubleLE = BP.readDoubleLE
  22494. arr.readDoubleBE = BP.readDoubleBE
  22495. arr.writeUInt8 = BP.writeUInt8
  22496. arr.writeUInt16LE = BP.writeUInt16LE
  22497. arr.writeUInt16BE = BP.writeUInt16BE
  22498. arr.writeUInt32LE = BP.writeUInt32LE
  22499. arr.writeUInt32BE = BP.writeUInt32BE
  22500. arr.writeInt8 = BP.writeInt8
  22501. arr.writeInt16LE = BP.writeInt16LE
  22502. arr.writeInt16BE = BP.writeInt16BE
  22503. arr.writeInt32LE = BP.writeInt32LE
  22504. arr.writeInt32BE = BP.writeInt32BE
  22505. arr.writeFloatLE = BP.writeFloatLE
  22506. arr.writeFloatBE = BP.writeFloatBE
  22507. arr.writeDoubleLE = BP.writeDoubleLE
  22508. arr.writeDoubleBE = BP.writeDoubleBE
  22509. arr.fill = BP.fill
  22510. arr.inspect = BP.inspect
  22511. arr.toArrayBuffer = BP.toArrayBuffer
  22512. return arr
  22513. }
  22514. // slice(start, end)
  22515. function clamp (index, len, defaultValue) {
  22516. if (typeof index !== 'number') return defaultValue
  22517. index = ~~index; // Coerce to integer.
  22518. if (index >= len) return len
  22519. if (index >= 0) return index
  22520. index += len
  22521. if (index >= 0) return index
  22522. return 0
  22523. }
  22524. function coerce (length) {
  22525. // Coerce length to a number (possibly NaN), round up
  22526. // in case it's fractional (e.g. 123.456) then do a
  22527. // double negate to coerce a NaN to 0. Easy, right?
  22528. length = ~~Math.ceil(+length)
  22529. return length < 0 ? 0 : length
  22530. }
  22531. function isArray (subject) {
  22532. return (Array.isArray || function (subject) {
  22533. return Object.prototype.toString.call(subject) === '[object Array]'
  22534. })(subject)
  22535. }
  22536. function isArrayish (subject) {
  22537. return isArray(subject) || Buffer.isBuffer(subject) ||
  22538. subject && typeof subject === 'object' &&
  22539. typeof subject.length === 'number'
  22540. }
  22541. function toHex (n) {
  22542. if (n < 16) return '0' + n.toString(16)
  22543. return n.toString(16)
  22544. }
  22545. function utf8ToBytes (str) {
  22546. var byteArray = []
  22547. for (var i = 0; i < str.length; i++) {
  22548. var b = str.charCodeAt(i)
  22549. if (b <= 0x7F)
  22550. byteArray.push(str.charCodeAt(i))
  22551. else {
  22552. var start = i
  22553. if (b >= 0xD800 && b <= 0xDFFF) i++
  22554. var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%')
  22555. for (var j = 0; j < h.length; j++)
  22556. byteArray.push(parseInt(h[j], 16))
  22557. }
  22558. }
  22559. return byteArray
  22560. }
  22561. function asciiToBytes (str) {
  22562. var byteArray = []
  22563. for (var i = 0; i < str.length; i++) {
  22564. // Node's code seems to be doing this and not & 0x7F..
  22565. byteArray.push(str.charCodeAt(i) & 0xFF)
  22566. }
  22567. return byteArray
  22568. }
  22569. function utf16leToBytes (str) {
  22570. var c, hi, lo
  22571. var byteArray = []
  22572. for (var i = 0; i < str.length; i++) {
  22573. c = str.charCodeAt(i)
  22574. hi = c >> 8
  22575. lo = c % 256
  22576. byteArray.push(lo)
  22577. byteArray.push(hi)
  22578. }
  22579. return byteArray
  22580. }
  22581. function base64ToBytes (str) {
  22582. return base64.toByteArray(str)
  22583. }
  22584. function blitBuffer (src, dst, offset, length) {
  22585. var pos
  22586. for (var i = 0; i < length; i++) {
  22587. if ((i + offset >= dst.length) || (i >= src.length))
  22588. break
  22589. dst[i + offset] = src[i]
  22590. }
  22591. return i
  22592. }
  22593. function decodeUtf8Char (str) {
  22594. try {
  22595. return decodeURIComponent(str)
  22596. } catch (err) {
  22597. return String.fromCharCode(0xFFFD) // UTF 8 invalid char
  22598. }
  22599. }
  22600. /*
  22601. * We have to make sure that the value is a valid integer. This means that it
  22602. * is non-negative. It has no fractional component and that it does not
  22603. * exceed the maximum allowed value.
  22604. */
  22605. function verifuint (value, max) {
  22606. assert(typeof value === 'number', 'cannot write a non-number as a number')
  22607. assert(value >= 0, 'specified a negative value for writing an unsigned value')
  22608. assert(value <= max, 'value is larger than maximum value for type')
  22609. assert(Math.floor(value) === value, 'value has a fractional component')
  22610. }
  22611. function verifsint (value, max, min) {
  22612. assert(typeof value === 'number', 'cannot write a non-number as a number')
  22613. assert(value <= max, 'value larger than maximum allowed value')
  22614. assert(value >= min, 'value smaller than minimum allowed value')
  22615. assert(Math.floor(value) === value, 'value has a fractional component')
  22616. }
  22617. function verifIEEE754 (value, max, min) {
  22618. assert(typeof value === 'number', 'cannot write a non-number as a number')
  22619. assert(value <= max, 'value larger than maximum allowed value')
  22620. assert(value >= min, 'value smaller than minimum allowed value')
  22621. }
  22622. function assert (test, message) {
  22623. if (!test) throw new Error(message || 'Failed assertion')
  22624. }
  22625. },{"base64-js":129,"ieee754":130}],129:[function(_dereq_,module,exports){
  22626. var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  22627. ;(function (exports) {
  22628. 'use strict';
  22629. var Arr = (typeof Uint8Array !== 'undefined')
  22630. ? Uint8Array
  22631. : Array
  22632. var ZERO = '0'.charCodeAt(0)
  22633. var PLUS = '+'.charCodeAt(0)
  22634. var SLASH = '/'.charCodeAt(0)
  22635. var NUMBER = '0'.charCodeAt(0)
  22636. var LOWER = 'a'.charCodeAt(0)
  22637. var UPPER = 'A'.charCodeAt(0)
  22638. function decode (elt) {
  22639. var code = elt.charCodeAt(0)
  22640. if (code === PLUS)
  22641. return 62 // '+'
  22642. if (code === SLASH)
  22643. return 63 // '/'
  22644. if (code < NUMBER)
  22645. return -1 //no match
  22646. if (code < NUMBER + 10)
  22647. return code - NUMBER + 26 + 26
  22648. if (code < UPPER + 26)
  22649. return code - UPPER
  22650. if (code < LOWER + 26)
  22651. return code - LOWER + 26
  22652. }
  22653. function b64ToByteArray (b64) {
  22654. var i, j, l, tmp, placeHolders, arr
  22655. if (b64.length % 4 > 0) {
  22656. throw new Error('Invalid string. Length must be a multiple of 4')
  22657. }
  22658. // the number of equal signs (place holders)
  22659. // if there are two placeholders, than the two characters before it
  22660. // represent one byte
  22661. // if there is only one, then the three characters before it represent 2 bytes
  22662. // this is just a cheap hack to not do indexOf twice
  22663. var len = b64.length
  22664. placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
  22665. // base64 is 4/3 + up to two characters of the original data
  22666. arr = new Arr(b64.length * 3 / 4 - placeHolders)
  22667. // if there are placeholders, only get up to the last complete 4 chars
  22668. l = placeHolders > 0 ? b64.length - 4 : b64.length
  22669. var L = 0
  22670. function push (v) {
  22671. arr[L++] = v
  22672. }
  22673. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  22674. tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
  22675. push((tmp & 0xFF0000) >> 16)
  22676. push((tmp & 0xFF00) >> 8)
  22677. push(tmp & 0xFF)
  22678. }
  22679. if (placeHolders === 2) {
  22680. tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
  22681. push(tmp & 0xFF)
  22682. } else if (placeHolders === 1) {
  22683. tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
  22684. push((tmp >> 8) & 0xFF)
  22685. push(tmp & 0xFF)
  22686. }
  22687. return arr
  22688. }
  22689. function uint8ToBase64 (uint8) {
  22690. var i,
  22691. extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
  22692. output = "",
  22693. temp, length
  22694. function encode (num) {
  22695. return lookup.charAt(num)
  22696. }
  22697. function tripletToBase64 (num) {
  22698. return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
  22699. }
  22700. // go through the array every three bytes, we'll deal with trailing stuff later
  22701. for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
  22702. temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
  22703. output += tripletToBase64(temp)
  22704. }
  22705. // pad the end with zeros, but make sure to not forget the extra bytes
  22706. switch (extraBytes) {
  22707. case 1:
  22708. temp = uint8[uint8.length - 1]
  22709. output += encode(temp >> 2)
  22710. output += encode((temp << 4) & 0x3F)
  22711. output += '=='
  22712. break
  22713. case 2:
  22714. temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
  22715. output += encode(temp >> 10)
  22716. output += encode((temp >> 4) & 0x3F)
  22717. output += encode((temp << 2) & 0x3F)
  22718. output += '='
  22719. break
  22720. }
  22721. return output
  22722. }
  22723. module.exports.toByteArray = b64ToByteArray
  22724. module.exports.fromByteArray = uint8ToBase64
  22725. }())
  22726. },{}],130:[function(_dereq_,module,exports){
  22727. exports.read = function(buffer, offset, isLE, mLen, nBytes) {
  22728. var e, m,
  22729. eLen = nBytes * 8 - mLen - 1,
  22730. eMax = (1 << eLen) - 1,
  22731. eBias = eMax >> 1,
  22732. nBits = -7,
  22733. i = isLE ? (nBytes - 1) : 0,
  22734. d = isLE ? -1 : 1,
  22735. s = buffer[offset + i];
  22736. i += d;
  22737. e = s & ((1 << (-nBits)) - 1);
  22738. s >>= (-nBits);
  22739. nBits += eLen;
  22740. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8);
  22741. m = e & ((1 << (-nBits)) - 1);
  22742. e >>= (-nBits);
  22743. nBits += mLen;
  22744. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8);
  22745. if (e === 0) {
  22746. e = 1 - eBias;
  22747. } else if (e === eMax) {
  22748. return m ? NaN : ((s ? -1 : 1) * Infinity);
  22749. } else {
  22750. m = m + Math.pow(2, mLen);
  22751. e = e - eBias;
  22752. }
  22753. return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
  22754. };
  22755. exports.write = function(buffer, value, offset, isLE, mLen, nBytes) {
  22756. var e, m, c,
  22757. eLen = nBytes * 8 - mLen - 1,
  22758. eMax = (1 << eLen) - 1,
  22759. eBias = eMax >> 1,
  22760. rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
  22761. i = isLE ? 0 : (nBytes - 1),
  22762. d = isLE ? 1 : -1,
  22763. s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
  22764. value = Math.abs(value);
  22765. if (isNaN(value) || value === Infinity) {
  22766. m = isNaN(value) ? 1 : 0;
  22767. e = eMax;
  22768. } else {
  22769. e = Math.floor(Math.log(value) / Math.LN2);
  22770. if (value * (c = Math.pow(2, -e)) < 1) {
  22771. e--;
  22772. c *= 2;
  22773. }
  22774. if (e + eBias >= 1) {
  22775. value += rt / c;
  22776. } else {
  22777. value += rt * Math.pow(2, 1 - eBias);
  22778. }
  22779. if (value * c >= 2) {
  22780. e++;
  22781. c /= 2;
  22782. }
  22783. if (e + eBias >= eMax) {
  22784. m = 0;
  22785. e = eMax;
  22786. } else if (e + eBias >= 1) {
  22787. m = (value * c - 1) * Math.pow(2, mLen);
  22788. e = e + eBias;
  22789. } else {
  22790. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
  22791. e = 0;
  22792. }
  22793. }
  22794. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8);
  22795. e = (e << mLen) | m;
  22796. eLen += mLen;
  22797. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8);
  22798. buffer[offset + i - d] |= s * 128;
  22799. };
  22800. },{}],131:[function(_dereq_,module,exports){
  22801. var Buffer = _dereq_('buffer').Buffer;
  22802. var intSize = 4;
  22803. var zeroBuffer = new Buffer(intSize); zeroBuffer.fill(0);
  22804. var chrsz = 8;
  22805. function toArray(buf, bigEndian) {
  22806. if ((buf.length % intSize) !== 0) {
  22807. var len = buf.length + (intSize - (buf.length % intSize));
  22808. buf = Buffer.concat([buf, zeroBuffer], len);
  22809. }
  22810. var arr = [];
  22811. var fn = bigEndian ? buf.readInt32BE : buf.readInt32LE;
  22812. for (var i = 0; i < buf.length; i += intSize) {
  22813. arr.push(fn.call(buf, i));
  22814. }
  22815. return arr;
  22816. }
  22817. function toBuffer(arr, size, bigEndian) {
  22818. var buf = new Buffer(size);
  22819. var fn = bigEndian ? buf.writeInt32BE : buf.writeInt32LE;
  22820. for (var i = 0; i < arr.length; i++) {
  22821. fn.call(buf, arr[i], i * 4, true);
  22822. }
  22823. return buf;
  22824. }
  22825. function hash(buf, fn, hashSize, bigEndian) {
  22826. if (!Buffer.isBuffer(buf)) buf = new Buffer(buf);
  22827. var arr = fn(toArray(buf, bigEndian), buf.length * chrsz);
  22828. return toBuffer(arr, hashSize, bigEndian);
  22829. }
  22830. module.exports = { hash: hash };
  22831. },{"buffer":128}],132:[function(_dereq_,module,exports){
  22832. var Buffer = _dereq_('buffer').Buffer
  22833. var sha = _dereq_('./sha')
  22834. var sha256 = _dereq_('./sha256')
  22835. var rng = _dereq_('./rng')
  22836. var md5 = _dereq_('./md5')
  22837. var algorithms = {
  22838. sha1: sha,
  22839. sha256: sha256,
  22840. md5: md5
  22841. }
  22842. var blocksize = 64
  22843. var zeroBuffer = new Buffer(blocksize); zeroBuffer.fill(0)
  22844. function hmac(fn, key, data) {
  22845. if(!Buffer.isBuffer(key)) key = new Buffer(key)
  22846. if(!Buffer.isBuffer(data)) data = new Buffer(data)
  22847. if(key.length > blocksize) {
  22848. key = fn(key)
  22849. } else if(key.length < blocksize) {
  22850. key = Buffer.concat([key, zeroBuffer], blocksize)
  22851. }
  22852. var ipad = new Buffer(blocksize), opad = new Buffer(blocksize)
  22853. for(var i = 0; i < blocksize; i++) {
  22854. ipad[i] = key[i] ^ 0x36
  22855. opad[i] = key[i] ^ 0x5C
  22856. }
  22857. var hash = fn(Buffer.concat([ipad, data]))
  22858. return fn(Buffer.concat([opad, hash]))
  22859. }
  22860. function hash(alg, key) {
  22861. alg = alg || 'sha1'
  22862. var fn = algorithms[alg]
  22863. var bufs = []
  22864. var length = 0
  22865. if(!fn) error('algorithm:', alg, 'is not yet supported')
  22866. return {
  22867. update: function (data) {
  22868. if(!Buffer.isBuffer(data)) data = new Buffer(data)
  22869. bufs.push(data)
  22870. length += data.length
  22871. return this
  22872. },
  22873. digest: function (enc) {
  22874. var buf = Buffer.concat(bufs)
  22875. var r = key ? hmac(fn, key, buf) : fn(buf)
  22876. bufs = null
  22877. return enc ? r.toString(enc) : r
  22878. }
  22879. }
  22880. }
  22881. function error () {
  22882. var m = [].slice.call(arguments).join(' ')
  22883. throw new Error([
  22884. m,
  22885. 'we accept pull requests',
  22886. 'http://github.com/dominictarr/crypto-browserify'
  22887. ].join('\n'))
  22888. }
  22889. exports.createHash = function (alg) { return hash(alg) }
  22890. exports.createHmac = function (alg, key) { return hash(alg, key) }
  22891. exports.randomBytes = function(size, callback) {
  22892. if (callback && callback.call) {
  22893. try {
  22894. callback.call(this, undefined, new Buffer(rng(size)))
  22895. } catch (err) { callback(err) }
  22896. } else {
  22897. return new Buffer(rng(size))
  22898. }
  22899. }
  22900. function each(a, f) {
  22901. for(var i in a)
  22902. f(a[i], i)
  22903. }
  22904. // the least I can do is make error messages for the rest of the node.js/crypto api.
  22905. each(['createCredentials'
  22906. , 'createCipher'
  22907. , 'createCipheriv'
  22908. , 'createDecipher'
  22909. , 'createDecipheriv'
  22910. , 'createSign'
  22911. , 'createVerify'
  22912. , 'createDiffieHellman'
  22913. , 'pbkdf2'], function (name) {
  22914. exports[name] = function () {
  22915. error('sorry,', name, 'is not implemented yet')
  22916. }
  22917. })
  22918. },{"./md5":133,"./rng":134,"./sha":135,"./sha256":136,"buffer":128}],133:[function(_dereq_,module,exports){
  22919. /*
  22920. * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
  22921. * Digest Algorithm, as defined in RFC 1321.
  22922. * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
  22923. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  22924. * Distributed under the BSD License
  22925. * See http://pajhome.org.uk/crypt/md5 for more info.
  22926. */
  22927. var helpers = _dereq_('./helpers');
  22928. /*
  22929. * Perform a simple self-test to see if the VM is working
  22930. */
  22931. function md5_vm_test()
  22932. {
  22933. return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
  22934. }
  22935. /*
  22936. * Calculate the MD5 of an array of little-endian words, and a bit length
  22937. */
  22938. function core_md5(x, len)
  22939. {
  22940. /* append padding */
  22941. x[len >> 5] |= 0x80 << ((len) % 32);
  22942. x[(((len + 64) >>> 9) << 4) + 14] = len;
  22943. var a = 1732584193;
  22944. var b = -271733879;
  22945. var c = -1732584194;
  22946. var d = 271733878;
  22947. for(var i = 0; i < x.length; i += 16)
  22948. {
  22949. var olda = a;
  22950. var oldb = b;
  22951. var oldc = c;
  22952. var oldd = d;
  22953. a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
  22954. d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
  22955. c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
  22956. b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
  22957. a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
  22958. d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
  22959. c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
  22960. b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
  22961. a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
  22962. d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
  22963. c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
  22964. b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
  22965. a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
  22966. d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
  22967. c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
  22968. b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
  22969. a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
  22970. d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
  22971. c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
  22972. b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
  22973. a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
  22974. d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
  22975. c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
  22976. b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
  22977. a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
  22978. d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
  22979. c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
  22980. b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
  22981. a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
  22982. d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
  22983. c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
  22984. b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
  22985. a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
  22986. d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
  22987. c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
  22988. b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
  22989. a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
  22990. d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
  22991. c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
  22992. b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
  22993. a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
  22994. d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
  22995. c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
  22996. b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
  22997. a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
  22998. d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
  22999. c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
  23000. b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
  23001. a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
  23002. d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
  23003. c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
  23004. b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
  23005. a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
  23006. d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
  23007. c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
  23008. b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
  23009. a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
  23010. d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
  23011. c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
  23012. b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
  23013. a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
  23014. d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
  23015. c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
  23016. b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
  23017. a = safe_add(a, olda);
  23018. b = safe_add(b, oldb);
  23019. c = safe_add(c, oldc);
  23020. d = safe_add(d, oldd);
  23021. }
  23022. return Array(a, b, c, d);
  23023. }
  23024. /*
  23025. * These functions implement the four basic operations the algorithm uses.
  23026. */
  23027. function md5_cmn(q, a, b, x, s, t)
  23028. {
  23029. return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
  23030. }
  23031. function md5_ff(a, b, c, d, x, s, t)
  23032. {
  23033. return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
  23034. }
  23035. function md5_gg(a, b, c, d, x, s, t)
  23036. {
  23037. return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
  23038. }
  23039. function md5_hh(a, b, c, d, x, s, t)
  23040. {
  23041. return md5_cmn(b ^ c ^ d, a, b, x, s, t);
  23042. }
  23043. function md5_ii(a, b, c, d, x, s, t)
  23044. {
  23045. return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
  23046. }
  23047. /*
  23048. * Add integers, wrapping at 2^32. This uses 16-bit operations internally
  23049. * to work around bugs in some JS interpreters.
  23050. */
  23051. function safe_add(x, y)
  23052. {
  23053. var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  23054. var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  23055. return (msw << 16) | (lsw & 0xFFFF);
  23056. }
  23057. /*
  23058. * Bitwise rotate a 32-bit number to the left.
  23059. */
  23060. function bit_rol(num, cnt)
  23061. {
  23062. return (num << cnt) | (num >>> (32 - cnt));
  23063. }
  23064. module.exports = function md5(buf) {
  23065. return helpers.hash(buf, core_md5, 16);
  23066. };
  23067. },{"./helpers":131}],134:[function(_dereq_,module,exports){
  23068. // Original code adapted from Robert Kieffer.
  23069. // details at https://github.com/broofa/node-uuid
  23070. (function() {
  23071. var _global = this;
  23072. var mathRNG, whatwgRNG;
  23073. // NOTE: Math.random() does not guarantee "cryptographic quality"
  23074. mathRNG = function(size) {
  23075. var bytes = new Array(size);
  23076. var r;
  23077. for (var i = 0, r; i < size; i++) {
  23078. if ((i & 0x03) == 0) r = Math.random() * 0x100000000;
  23079. bytes[i] = r >>> ((i & 0x03) << 3) & 0xff;
  23080. }
  23081. return bytes;
  23082. }
  23083. if (_global.crypto && crypto.getRandomValues) {
  23084. whatwgRNG = function(size) {
  23085. var bytes = new Uint8Array(size);
  23086. crypto.getRandomValues(bytes);
  23087. return bytes;
  23088. }
  23089. }
  23090. module.exports = whatwgRNG || mathRNG;
  23091. }())
  23092. },{}],135:[function(_dereq_,module,exports){
  23093. /*
  23094. * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
  23095. * in FIPS PUB 180-1
  23096. * Version 2.1a Copyright Paul Johnston 2000 - 2002.
  23097. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  23098. * Distributed under the BSD License
  23099. * See http://pajhome.org.uk/crypt/md5 for details.
  23100. */
  23101. var helpers = _dereq_('./helpers');
  23102. /*
  23103. * Calculate the SHA-1 of an array of big-endian words, and a bit length
  23104. */
  23105. function core_sha1(x, len)
  23106. {
  23107. /* append padding */
  23108. x[len >> 5] |= 0x80 << (24 - len % 32);
  23109. x[((len + 64 >> 9) << 4) + 15] = len;
  23110. var w = Array(80);
  23111. var a = 1732584193;
  23112. var b = -271733879;
  23113. var c = -1732584194;
  23114. var d = 271733878;
  23115. var e = -1009589776;
  23116. for(var i = 0; i < x.length; i += 16)
  23117. {
  23118. var olda = a;
  23119. var oldb = b;
  23120. var oldc = c;
  23121. var oldd = d;
  23122. var olde = e;
  23123. for(var j = 0; j < 80; j++)
  23124. {
  23125. if(j < 16) w[j] = x[i + j];
  23126. else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
  23127. var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
  23128. safe_add(safe_add(e, w[j]), sha1_kt(j)));
  23129. e = d;
  23130. d = c;
  23131. c = rol(b, 30);
  23132. b = a;
  23133. a = t;
  23134. }
  23135. a = safe_add(a, olda);
  23136. b = safe_add(b, oldb);
  23137. c = safe_add(c, oldc);
  23138. d = safe_add(d, oldd);
  23139. e = safe_add(e, olde);
  23140. }
  23141. return Array(a, b, c, d, e);
  23142. }
  23143. /*
  23144. * Perform the appropriate triplet combination function for the current
  23145. * iteration
  23146. */
  23147. function sha1_ft(t, b, c, d)
  23148. {
  23149. if(t < 20) return (b & c) | ((~b) & d);
  23150. if(t < 40) return b ^ c ^ d;
  23151. if(t < 60) return (b & c) | (b & d) | (c & d);
  23152. return b ^ c ^ d;
  23153. }
  23154. /*
  23155. * Determine the appropriate additive constant for the current iteration
  23156. */
  23157. function sha1_kt(t)
  23158. {
  23159. return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 :
  23160. (t < 60) ? -1894007588 : -899497514;
  23161. }
  23162. /*
  23163. * Add integers, wrapping at 2^32. This uses 16-bit operations internally
  23164. * to work around bugs in some JS interpreters.
  23165. */
  23166. function safe_add(x, y)
  23167. {
  23168. var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  23169. var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  23170. return (msw << 16) | (lsw & 0xFFFF);
  23171. }
  23172. /*
  23173. * Bitwise rotate a 32-bit number to the left.
  23174. */
  23175. function rol(num, cnt)
  23176. {
  23177. return (num << cnt) | (num >>> (32 - cnt));
  23178. }
  23179. module.exports = function sha1(buf) {
  23180. return helpers.hash(buf, core_sha1, 20, true);
  23181. };
  23182. },{"./helpers":131}],136:[function(_dereq_,module,exports){
  23183. /**
  23184. * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
  23185. * in FIPS 180-2
  23186. * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
  23187. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  23188. *
  23189. */
  23190. var helpers = _dereq_('./helpers');
  23191. var safe_add = function(x, y) {
  23192. var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  23193. var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  23194. return (msw << 16) | (lsw & 0xFFFF);
  23195. };
  23196. var S = function(X, n) {
  23197. return (X >>> n) | (X << (32 - n));
  23198. };
  23199. var R = function(X, n) {
  23200. return (X >>> n);
  23201. };
  23202. var Ch = function(x, y, z) {
  23203. return ((x & y) ^ ((~x) & z));
  23204. };
  23205. var Maj = function(x, y, z) {
  23206. return ((x & y) ^ (x & z) ^ (y & z));
  23207. };
  23208. var Sigma0256 = function(x) {
  23209. return (S(x, 2) ^ S(x, 13) ^ S(x, 22));
  23210. };
  23211. var Sigma1256 = function(x) {
  23212. return (S(x, 6) ^ S(x, 11) ^ S(x, 25));
  23213. };
  23214. var Gamma0256 = function(x) {
  23215. return (S(x, 7) ^ S(x, 18) ^ R(x, 3));
  23216. };
  23217. var Gamma1256 = function(x) {
  23218. return (S(x, 17) ^ S(x, 19) ^ R(x, 10));
  23219. };
  23220. var core_sha256 = function(m, l) {
  23221. var K = new Array(0x428A2F98,0x71374491,0xB5C0FBCF,0xE9B5DBA5,0x3956C25B,0x59F111F1,0x923F82A4,0xAB1C5ED5,0xD807AA98,0x12835B01,0x243185BE,0x550C7DC3,0x72BE5D74,0x80DEB1FE,0x9BDC06A7,0xC19BF174,0xE49B69C1,0xEFBE4786,0xFC19DC6,0x240CA1CC,0x2DE92C6F,0x4A7484AA,0x5CB0A9DC,0x76F988DA,0x983E5152,0xA831C66D,0xB00327C8,0xBF597FC7,0xC6E00BF3,0xD5A79147,0x6CA6351,0x14292967,0x27B70A85,0x2E1B2138,0x4D2C6DFC,0x53380D13,0x650A7354,0x766A0ABB,0x81C2C92E,0x92722C85,0xA2BFE8A1,0xA81A664B,0xC24B8B70,0xC76C51A3,0xD192E819,0xD6990624,0xF40E3585,0x106AA070,0x19A4C116,0x1E376C08,0x2748774C,0x34B0BCB5,0x391C0CB3,0x4ED8AA4A,0x5B9CCA4F,0x682E6FF3,0x748F82EE,0x78A5636F,0x84C87814,0x8CC70208,0x90BEFFFA,0xA4506CEB,0xBEF9A3F7,0xC67178F2);
  23222. var HASH = new Array(0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19);
  23223. var W = new Array(64);
  23224. var a, b, c, d, e, f, g, h, i, j;
  23225. var T1, T2;
  23226. /* append padding */
  23227. m[l >> 5] |= 0x80 << (24 - l % 32);
  23228. m[((l + 64 >> 9) << 4) + 15] = l;
  23229. for (var i = 0; i < m.length; i += 16) {
  23230. a = HASH[0]; b = HASH[1]; c = HASH[2]; d = HASH[3]; e = HASH[4]; f = HASH[5]; g = HASH[6]; h = HASH[7];
  23231. for (var j = 0; j < 64; j++) {
  23232. if (j < 16) {
  23233. W[j] = m[j + i];
  23234. } else {
  23235. W[j] = safe_add(safe_add(safe_add(Gamma1256(W[j - 2]), W[j - 7]), Gamma0256(W[j - 15])), W[j - 16]);
  23236. }
  23237. T1 = safe_add(safe_add(safe_add(safe_add(h, Sigma1256(e)), Ch(e, f, g)), K[j]), W[j]);
  23238. T2 = safe_add(Sigma0256(a), Maj(a, b, c));
  23239. h = g; g = f; f = e; e = safe_add(d, T1); d = c; c = b; b = a; a = safe_add(T1, T2);
  23240. }
  23241. HASH[0] = safe_add(a, HASH[0]); HASH[1] = safe_add(b, HASH[1]); HASH[2] = safe_add(c, HASH[2]); HASH[3] = safe_add(d, HASH[3]);
  23242. HASH[4] = safe_add(e, HASH[4]); HASH[5] = safe_add(f, HASH[5]); HASH[6] = safe_add(g, HASH[6]); HASH[7] = safe_add(h, HASH[7]);
  23243. }
  23244. return HASH;
  23245. };
  23246. module.exports = function sha256(buf) {
  23247. return helpers.hash(buf, core_sha256, 32, true);
  23248. };
  23249. },{"./helpers":131}],137:[function(_dereq_,module,exports){
  23250. // Copyright Joyent, Inc. and other Node contributors.
  23251. //
  23252. // Permission is hereby granted, free of charge, to any person obtaining a
  23253. // copy of this software and associated documentation files (the
  23254. // "Software"), to deal in the Software without restriction, including
  23255. // without limitation the rights to use, copy, modify, merge, publish,
  23256. // distribute, sublicense, and/or sell copies of the Software, and to permit
  23257. // persons to whom the Software is furnished to do so, subject to the
  23258. // following conditions:
  23259. //
  23260. // The above copyright notice and this permission notice shall be included
  23261. // in all copies or substantial portions of the Software.
  23262. //
  23263. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  23264. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23265. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  23266. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  23267. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  23268. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  23269. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  23270. function EventEmitter() {
  23271. this._events = this._events || {};
  23272. this._maxListeners = this._maxListeners || undefined;
  23273. }
  23274. module.exports = EventEmitter;
  23275. // Backwards-compat with node 0.10.x
  23276. EventEmitter.EventEmitter = EventEmitter;
  23277. EventEmitter.prototype._events = undefined;
  23278. EventEmitter.prototype._maxListeners = undefined;
  23279. // By default EventEmitters will print a warning if more than 10 listeners are
  23280. // added to it. This is a useful default which helps finding memory leaks.
  23281. EventEmitter.defaultMaxListeners = 10;
  23282. // Obviously not all Emitters should be limited to 10. This function allows
  23283. // that to be increased. Set to zero for unlimited.
  23284. EventEmitter.prototype.setMaxListeners = function(n) {
  23285. if (!isNumber(n) || n < 0 || isNaN(n))
  23286. throw TypeError('n must be a positive number');
  23287. this._maxListeners = n;
  23288. return this;
  23289. };
  23290. EventEmitter.prototype.emit = function(type) {
  23291. var er, handler, len, args, i, listeners;
  23292. if (!this._events)
  23293. this._events = {};
  23294. // If there is no 'error' event listener then throw.
  23295. if (type === 'error') {
  23296. if (!this._events.error ||
  23297. (isObject(this._events.error) && !this._events.error.length)) {
  23298. er = arguments[1];
  23299. if (er instanceof Error) {
  23300. throw er; // Unhandled 'error' event
  23301. } else {
  23302. throw TypeError('Uncaught, unspecified "error" event.');
  23303. }
  23304. return false;
  23305. }
  23306. }
  23307. handler = this._events[type];
  23308. if (isUndefined(handler))
  23309. return false;
  23310. if (isFunction(handler)) {
  23311. switch (arguments.length) {
  23312. // fast cases
  23313. case 1:
  23314. handler.call(this);
  23315. break;
  23316. case 2:
  23317. handler.call(this, arguments[1]);
  23318. break;
  23319. case 3:
  23320. handler.call(this, arguments[1], arguments[2]);
  23321. break;
  23322. // slower
  23323. default:
  23324. len = arguments.length;
  23325. args = new Array(len - 1);
  23326. for (i = 1; i < len; i++)
  23327. args[i - 1] = arguments[i];
  23328. handler.apply(this, args);
  23329. }
  23330. } else if (isObject(handler)) {
  23331. len = arguments.length;
  23332. args = new Array(len - 1);
  23333. for (i = 1; i < len; i++)
  23334. args[i - 1] = arguments[i];
  23335. listeners = handler.slice();
  23336. len = listeners.length;
  23337. for (i = 0; i < len; i++)
  23338. listeners[i].apply(this, args);
  23339. }
  23340. return true;
  23341. };
  23342. EventEmitter.prototype.addListener = function(type, listener) {
  23343. var m;
  23344. if (!isFunction(listener))
  23345. throw TypeError('listener must be a function');
  23346. if (!this._events)
  23347. this._events = {};
  23348. // To avoid recursion in the case that type === "newListener"! Before
  23349. // adding it to the listeners, first emit "newListener".
  23350. if (this._events.newListener)
  23351. this.emit('newListener', type,
  23352. isFunction(listener.listener) ?
  23353. listener.listener : listener);
  23354. if (!this._events[type])
  23355. // Optimize the case of one listener. Don't need the extra array object.
  23356. this._events[type] = listener;
  23357. else if (isObject(this._events[type]))
  23358. // If we've already got an array, just append.
  23359. this._events[type].push(listener);
  23360. else
  23361. // Adding the second element, need to change to array.
  23362. this._events[type] = [this._events[type], listener];
  23363. // Check for listener leak
  23364. if (isObject(this._events[type]) && !this._events[type].warned) {
  23365. var m;
  23366. if (!isUndefined(this._maxListeners)) {
  23367. m = this._maxListeners;
  23368. } else {
  23369. m = EventEmitter.defaultMaxListeners;
  23370. }
  23371. if (m && m > 0 && this._events[type].length > m) {
  23372. this._events[type].warned = true;
  23373. console.error('(node) warning: possible EventEmitter memory ' +
  23374. 'leak detected. %d listeners added. ' +
  23375. 'Use emitter.setMaxListeners() to increase limit.',
  23376. this._events[type].length);
  23377. console.trace();
  23378. }
  23379. }
  23380. return this;
  23381. };
  23382. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  23383. EventEmitter.prototype.once = function(type, listener) {
  23384. if (!isFunction(listener))
  23385. throw TypeError('listener must be a function');
  23386. var fired = false;
  23387. function g() {
  23388. this.removeListener(type, g);
  23389. if (!fired) {
  23390. fired = true;
  23391. listener.apply(this, arguments);
  23392. }
  23393. }
  23394. g.listener = listener;
  23395. this.on(type, g);
  23396. return this;
  23397. };
  23398. // emits a 'removeListener' event iff the listener was removed
  23399. EventEmitter.prototype.removeListener = function(type, listener) {
  23400. var list, position, length, i;
  23401. if (!isFunction(listener))
  23402. throw TypeError('listener must be a function');
  23403. if (!this._events || !this._events[type])
  23404. return this;
  23405. list = this._events[type];
  23406. length = list.length;
  23407. position = -1;
  23408. if (list === listener ||
  23409. (isFunction(list.listener) && list.listener === listener)) {
  23410. delete this._events[type];
  23411. if (this._events.removeListener)
  23412. this.emit('removeListener', type, listener);
  23413. } else if (isObject(list)) {
  23414. for (i = length; i-- > 0;) {
  23415. if (list[i] === listener ||
  23416. (list[i].listener && list[i].listener === listener)) {
  23417. position = i;
  23418. break;
  23419. }
  23420. }
  23421. if (position < 0)
  23422. return this;
  23423. if (list.length === 1) {
  23424. list.length = 0;
  23425. delete this._events[type];
  23426. } else {
  23427. list.splice(position, 1);
  23428. }
  23429. if (this._events.removeListener)
  23430. this.emit('removeListener', type, listener);
  23431. }
  23432. return this;
  23433. };
  23434. EventEmitter.prototype.removeAllListeners = function(type) {
  23435. var key, listeners;
  23436. if (!this._events)
  23437. return this;
  23438. // not listening for removeListener, no need to emit
  23439. if (!this._events.removeListener) {
  23440. if (arguments.length === 0)
  23441. this._events = {};
  23442. else if (this._events[type])
  23443. delete this._events[type];
  23444. return this;
  23445. }
  23446. // emit removeListener for all listeners on all events
  23447. if (arguments.length === 0) {
  23448. for (key in this._events) {
  23449. if (key === 'removeListener') continue;
  23450. this.removeAllListeners(key);
  23451. }
  23452. this.removeAllListeners('removeListener');
  23453. this._events = {};
  23454. return this;
  23455. }
  23456. listeners = this._events[type];
  23457. if (isFunction(listeners)) {
  23458. this.removeListener(type, listeners);
  23459. } else {
  23460. // LIFO order
  23461. while (listeners.length)
  23462. this.removeListener(type, listeners[listeners.length - 1]);
  23463. }
  23464. delete this._events[type];
  23465. return this;
  23466. };
  23467. EventEmitter.prototype.listeners = function(type) {
  23468. var ret;
  23469. if (!this._events || !this._events[type])
  23470. ret = [];
  23471. else if (isFunction(this._events[type]))
  23472. ret = [this._events[type]];
  23473. else
  23474. ret = this._events[type].slice();
  23475. return ret;
  23476. };
  23477. EventEmitter.listenerCount = function(emitter, type) {
  23478. var ret;
  23479. if (!emitter._events || !emitter._events[type])
  23480. ret = 0;
  23481. else if (isFunction(emitter._events[type]))
  23482. ret = 1;
  23483. else
  23484. ret = emitter._events[type].length;
  23485. return ret;
  23486. };
  23487. function isFunction(arg) {
  23488. return typeof arg === 'function';
  23489. }
  23490. function isNumber(arg) {
  23491. return typeof arg === 'number';
  23492. }
  23493. function isObject(arg) {
  23494. return typeof arg === 'object' && arg !== null;
  23495. }
  23496. function isUndefined(arg) {
  23497. return arg === void 0;
  23498. }
  23499. },{}],138:[function(_dereq_,module,exports){
  23500. var http = module.exports;
  23501. var EventEmitter = _dereq_('events').EventEmitter;
  23502. var Request = _dereq_('./lib/request');
  23503. var url = _dereq_('url')
  23504. http.request = function (params, cb) {
  23505. if (typeof params === 'string') {
  23506. params = url.parse(params)
  23507. }
  23508. if (!params) params = {};
  23509. if (!params.host && !params.port) {
  23510. params.port = parseInt(window.location.port, 10);
  23511. }
  23512. if (!params.host && params.hostname) {
  23513. params.host = params.hostname;
  23514. }
  23515. if (!params.scheme) params.scheme = window.location.protocol.split(':')[0];
  23516. if (!params.host) {
  23517. params.host = window.location.hostname || window.location.host;
  23518. }
  23519. if (/:/.test(params.host)) {
  23520. if (!params.port) {
  23521. params.port = params.host.split(':')[1];
  23522. }
  23523. params.host = params.host.split(':')[0];
  23524. }
  23525. if (!params.port) params.port = params.scheme == 'https' ? 443 : 80;
  23526. var req = new Request(new xhrHttp, params);
  23527. if (cb) req.on('response', cb);
  23528. return req;
  23529. };
  23530. http.get = function (params, cb) {
  23531. params.method = 'GET';
  23532. var req = http.request(params, cb);
  23533. req.end();
  23534. return req;
  23535. };
  23536. http.Agent = function () {};
  23537. http.Agent.defaultMaxSockets = 4;
  23538. var xhrHttp = (function () {
  23539. if (typeof window === 'undefined') {
  23540. throw new Error('no window object present');
  23541. }
  23542. else if (window.XMLHttpRequest) {
  23543. return window.XMLHttpRequest;
  23544. }
  23545. else if (window.ActiveXObject) {
  23546. var axs = [
  23547. 'Msxml2.XMLHTTP.6.0',
  23548. 'Msxml2.XMLHTTP.3.0',
  23549. 'Microsoft.XMLHTTP'
  23550. ];
  23551. for (var i = 0; i < axs.length; i++) {
  23552. try {
  23553. var ax = new(window.ActiveXObject)(axs[i]);
  23554. return function () {
  23555. if (ax) {
  23556. var ax_ = ax;
  23557. ax = null;
  23558. return ax_;
  23559. }
  23560. else {
  23561. return new(window.ActiveXObject)(axs[i]);
  23562. }
  23563. };
  23564. }
  23565. catch (e) {}
  23566. }
  23567. throw new Error('ajax not supported in this browser')
  23568. }
  23569. else {
  23570. throw new Error('ajax not supported in this browser');
  23571. }
  23572. })();
  23573. http.STATUS_CODES = {
  23574. 100 : 'Continue',
  23575. 101 : 'Switching Protocols',
  23576. 102 : 'Processing', // RFC 2518, obsoleted by RFC 4918
  23577. 200 : 'OK',
  23578. 201 : 'Created',
  23579. 202 : 'Accepted',
  23580. 203 : 'Non-Authoritative Information',
  23581. 204 : 'No Content',
  23582. 205 : 'Reset Content',
  23583. 206 : 'Partial Content',
  23584. 207 : 'Multi-Status', // RFC 4918
  23585. 300 : 'Multiple Choices',
  23586. 301 : 'Moved Permanently',
  23587. 302 : 'Moved Temporarily',
  23588. 303 : 'See Other',
  23589. 304 : 'Not Modified',
  23590. 305 : 'Use Proxy',
  23591. 307 : 'Temporary Redirect',
  23592. 400 : 'Bad Request',
  23593. 401 : 'Unauthorized',
  23594. 402 : 'Payment Required',
  23595. 403 : 'Forbidden',
  23596. 404 : 'Not Found',
  23597. 405 : 'Method Not Allowed',
  23598. 406 : 'Not Acceptable',
  23599. 407 : 'Proxy Authentication Required',
  23600. 408 : 'Request Time-out',
  23601. 409 : 'Conflict',
  23602. 410 : 'Gone',
  23603. 411 : 'Length Required',
  23604. 412 : 'Precondition Failed',
  23605. 413 : 'Request Entity Too Large',
  23606. 414 : 'Request-URI Too Large',
  23607. 415 : 'Unsupported Media Type',
  23608. 416 : 'Requested Range Not Satisfiable',
  23609. 417 : 'Expectation Failed',
  23610. 418 : 'I\'m a teapot', // RFC 2324
  23611. 422 : 'Unprocessable Entity', // RFC 4918
  23612. 423 : 'Locked', // RFC 4918
  23613. 424 : 'Failed Dependency', // RFC 4918
  23614. 425 : 'Unordered Collection', // RFC 4918
  23615. 426 : 'Upgrade Required', // RFC 2817
  23616. 428 : 'Precondition Required', // RFC 6585
  23617. 429 : 'Too Many Requests', // RFC 6585
  23618. 431 : 'Request Header Fields Too Large',// RFC 6585
  23619. 500 : 'Internal Server Error',
  23620. 501 : 'Not Implemented',
  23621. 502 : 'Bad Gateway',
  23622. 503 : 'Service Unavailable',
  23623. 504 : 'Gateway Time-out',
  23624. 505 : 'HTTP Version Not Supported',
  23625. 506 : 'Variant Also Negotiates', // RFC 2295
  23626. 507 : 'Insufficient Storage', // RFC 4918
  23627. 509 : 'Bandwidth Limit Exceeded',
  23628. 510 : 'Not Extended', // RFC 2774
  23629. 511 : 'Network Authentication Required' // RFC 6585
  23630. };
  23631. },{"./lib/request":139,"events":137,"url":157}],139:[function(_dereq_,module,exports){
  23632. var Stream = _dereq_('stream');
  23633. var Response = _dereq_('./response');
  23634. var Base64 = _dereq_('Base64');
  23635. var inherits = _dereq_('inherits');
  23636. var Request = module.exports = function (xhr, params) {
  23637. var self = this;
  23638. self.writable = true;
  23639. self.xhr = xhr;
  23640. self.body = [];
  23641. self.uri = (params.scheme || 'http') + '://'
  23642. + params.host
  23643. + (params.port ? ':' + params.port : '')
  23644. + (params.path || '/')
  23645. ;
  23646. if (typeof params.withCredentials === 'undefined') {
  23647. params.withCredentials = true;
  23648. }
  23649. try { xhr.withCredentials = params.withCredentials }
  23650. catch (e) {}
  23651. xhr.open(
  23652. params.method || 'GET',
  23653. self.uri,
  23654. true
  23655. );
  23656. self._headers = {};
  23657. if (params.headers) {
  23658. var keys = objectKeys(params.headers);
  23659. for (var i = 0; i < keys.length; i++) {
  23660. var key = keys[i];
  23661. if (!self.isSafeRequestHeader(key)) continue;
  23662. var value = params.headers[key];
  23663. self.setHeader(key, value);
  23664. }
  23665. }
  23666. if (params.auth) {
  23667. //basic auth
  23668. this.setHeader('Authorization', 'Basic ' + Base64.btoa(params.auth));
  23669. }
  23670. var res = new Response;
  23671. res.on('close', function () {
  23672. self.emit('close');
  23673. });
  23674. res.on('ready', function () {
  23675. self.emit('response', res);
  23676. });
  23677. xhr.onreadystatechange = function () {
  23678. // Fix for IE9 bug
  23679. // SCRIPT575: Could not complete the operation due to error c00c023f
  23680. // It happens when a request is aborted, calling the success callback anyway with readyState === 4
  23681. if (xhr.__aborted) return;
  23682. res.handle(xhr);
  23683. };
  23684. };
  23685. inherits(Request, Stream);
  23686. Request.prototype.setHeader = function (key, value) {
  23687. this._headers[key.toLowerCase()] = value
  23688. };
  23689. Request.prototype.getHeader = function (key) {
  23690. return this._headers[key.toLowerCase()]
  23691. };
  23692. Request.prototype.removeHeader = function (key) {
  23693. delete this._headers[key.toLowerCase()]
  23694. };
  23695. Request.prototype.write = function (s) {
  23696. this.body.push(s);
  23697. };
  23698. Request.prototype.destroy = function (s) {
  23699. this.xhr.__aborted = true;
  23700. this.xhr.abort();
  23701. this.emit('close');
  23702. };
  23703. Request.prototype.end = function (s) {
  23704. if (s !== undefined) this.body.push(s);
  23705. var keys = objectKeys(this._headers);
  23706. for (var i = 0; i < keys.length; i++) {
  23707. var key = keys[i];
  23708. var value = this._headers[key];
  23709. if (isArray(value)) {
  23710. for (var j = 0; j < value.length; j++) {
  23711. this.xhr.setRequestHeader(key, value[j]);
  23712. }
  23713. }
  23714. else this.xhr.setRequestHeader(key, value)
  23715. }
  23716. if (this.body.length === 0) {
  23717. this.xhr.send('');
  23718. }
  23719. else if (typeof this.body[0] === 'string') {
  23720. this.xhr.send(this.body.join(''));
  23721. }
  23722. else if (isArray(this.body[0])) {
  23723. var body = [];
  23724. for (var i = 0; i < this.body.length; i++) {
  23725. body.push.apply(body, this.body[i]);
  23726. }
  23727. this.xhr.send(body);
  23728. }
  23729. else if (/Array/.test(Object.prototype.toString.call(this.body[0]))) {
  23730. var len = 0;
  23731. for (var i = 0; i < this.body.length; i++) {
  23732. len += this.body[i].length;
  23733. }
  23734. var body = new(this.body[0].constructor)(len);
  23735. var k = 0;
  23736. for (var i = 0; i < this.body.length; i++) {
  23737. var b = this.body[i];
  23738. for (var j = 0; j < b.length; j++) {
  23739. body[k++] = b[j];
  23740. }
  23741. }
  23742. this.xhr.send(body);
  23743. }
  23744. else {
  23745. var body = '';
  23746. for (var i = 0; i < this.body.length; i++) {
  23747. body += this.body[i].toString();
  23748. }
  23749. this.xhr.send(body);
  23750. }
  23751. };
  23752. // Taken from http://dxr.mozilla.org/mozilla/mozilla-central/content/base/src/nsXMLHttpRequest.cpp.html
  23753. Request.unsafeHeaders = [
  23754. "accept-charset",
  23755. "accept-encoding",
  23756. "access-control-request-headers",
  23757. "access-control-request-method",
  23758. "connection",
  23759. "content-length",
  23760. "cookie",
  23761. "cookie2",
  23762. "content-transfer-encoding",
  23763. "date",
  23764. "expect",
  23765. "host",
  23766. "keep-alive",
  23767. "origin",
  23768. "referer",
  23769. "te",
  23770. "trailer",
  23771. "transfer-encoding",
  23772. "upgrade",
  23773. "user-agent",
  23774. "via"
  23775. ];
  23776. Request.prototype.isSafeRequestHeader = function (headerName) {
  23777. if (!headerName) return false;
  23778. return indexOf(Request.unsafeHeaders, headerName.toLowerCase()) === -1;
  23779. };
  23780. var objectKeys = Object.keys || function (obj) {
  23781. var keys = [];
  23782. for (var key in obj) keys.push(key);
  23783. return keys;
  23784. };
  23785. var isArray = Array.isArray || function (xs) {
  23786. return Object.prototype.toString.call(xs) === '[object Array]';
  23787. };
  23788. var indexOf = function (xs, x) {
  23789. if (xs.indexOf) return xs.indexOf(x);
  23790. for (var i = 0; i < xs.length; i++) {
  23791. if (xs[i] === x) return i;
  23792. }
  23793. return -1;
  23794. };
  23795. },{"./response":140,"Base64":141,"inherits":143,"stream":150}],140:[function(_dereq_,module,exports){
  23796. var Stream = _dereq_('stream');
  23797. var util = _dereq_('util');
  23798. var Response = module.exports = function (res) {
  23799. this.offset = 0;
  23800. this.readable = true;
  23801. };
  23802. util.inherits(Response, Stream);
  23803. var capable = {
  23804. streaming : true,
  23805. status2 : true
  23806. };
  23807. function parseHeaders (res) {
  23808. var lines = res.getAllResponseHeaders().split(/\r?\n/);
  23809. var headers = {};
  23810. for (var i = 0; i < lines.length; i++) {
  23811. var line = lines[i];
  23812. if (line === '') continue;
  23813. var m = line.match(/^([^:]+):\s*(.*)/);
  23814. if (m) {
  23815. var key = m[1].toLowerCase(), value = m[2];
  23816. if (headers[key] !== undefined) {
  23817. if (isArray(headers[key])) {
  23818. headers[key].push(value);
  23819. }
  23820. else {
  23821. headers[key] = [ headers[key], value ];
  23822. }
  23823. }
  23824. else {
  23825. headers[key] = value;
  23826. }
  23827. }
  23828. else {
  23829. headers[line] = true;
  23830. }
  23831. }
  23832. return headers;
  23833. }
  23834. Response.prototype.getResponse = function (xhr) {
  23835. var respType = String(xhr.responseType).toLowerCase();
  23836. if (respType === 'blob') return xhr.responseBlob || xhr.response;
  23837. if (respType === 'arraybuffer') return xhr.response;
  23838. return xhr.responseText;
  23839. }
  23840. Response.prototype.getHeader = function (key) {
  23841. return this.headers[key.toLowerCase()];
  23842. };
  23843. Response.prototype.handle = function (res) {
  23844. if (res.readyState === 2 && capable.status2) {
  23845. try {
  23846. this.statusCode = res.status;
  23847. this.headers = parseHeaders(res);
  23848. }
  23849. catch (err) {
  23850. capable.status2 = false;
  23851. }
  23852. if (capable.status2) {
  23853. this.emit('ready');
  23854. }
  23855. }
  23856. else if (capable.streaming && res.readyState === 3) {
  23857. try {
  23858. if (!this.statusCode) {
  23859. this.statusCode = res.status;
  23860. this.headers = parseHeaders(res);
  23861. this.emit('ready');
  23862. }
  23863. }
  23864. catch (err) {}
  23865. try {
  23866. this._emitData(res);
  23867. }
  23868. catch (err) {
  23869. capable.streaming = false;
  23870. }
  23871. }
  23872. else if (res.readyState === 4) {
  23873. if (!this.statusCode) {
  23874. this.statusCode = res.status;
  23875. this.emit('ready');
  23876. }
  23877. this._emitData(res);
  23878. if (res.error) {
  23879. this.emit('error', this.getResponse(res));
  23880. }
  23881. else this.emit('end');
  23882. this.emit('close');
  23883. }
  23884. };
  23885. Response.prototype._emitData = function (res) {
  23886. var respBody = this.getResponse(res);
  23887. if (respBody.toString().match(/ArrayBuffer/)) {
  23888. this.emit('data', new Uint8Array(respBody, this.offset));
  23889. this.offset = respBody.byteLength;
  23890. return;
  23891. }
  23892. if (respBody.length > this.offset) {
  23893. this.emit('data', respBody.slice(this.offset));
  23894. this.offset = respBody.length;
  23895. }
  23896. };
  23897. var isArray = Array.isArray || function (xs) {
  23898. return Object.prototype.toString.call(xs) === '[object Array]';
  23899. };
  23900. },{"stream":150,"util":159}],141:[function(_dereq_,module,exports){
  23901. ;(function () {
  23902. var object = typeof exports != 'undefined' ? exports : this; // #8: web workers
  23903. var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  23904. function InvalidCharacterError(message) {
  23905. this.message = message;
  23906. }
  23907. InvalidCharacterError.prototype = new Error;
  23908. InvalidCharacterError.prototype.name = 'InvalidCharacterError';
  23909. // encoder
  23910. // [https://gist.github.com/999166] by [https://github.com/nignag]
  23911. object.btoa || (
  23912. object.btoa = function (input) {
  23913. for (
  23914. // initialize result and counter
  23915. var block, charCode, idx = 0, map = chars, output = '';
  23916. // if the next input index does not exist:
  23917. // change the mapping table to "="
  23918. // check if d has no fractional digits
  23919. input.charAt(idx | 0) || (map = '=', idx % 1);
  23920. // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8
  23921. output += map.charAt(63 & block >> 8 - idx % 1 * 8)
  23922. ) {
  23923. charCode = input.charCodeAt(idx += 3/4);
  23924. if (charCode > 0xFF) {
  23925. throw new InvalidCharacterError("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
  23926. }
  23927. block = block << 8 | charCode;
  23928. }
  23929. return output;
  23930. });
  23931. // decoder
  23932. // [https://gist.github.com/1020396] by [https://github.com/atk]
  23933. object.atob || (
  23934. object.atob = function (input) {
  23935. input = input.replace(/=+$/, '');
  23936. if (input.length % 4 == 1) {
  23937. throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded.");
  23938. }
  23939. for (
  23940. // initialize result and counters
  23941. var bc = 0, bs, buffer, idx = 0, output = '';
  23942. // get next character
  23943. buffer = input.charAt(idx++);
  23944. // character found in table? initialize bit storage and add its ascii value;
  23945. ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
  23946. // and if not first of each 4 characters,
  23947. // convert the first 8 bits to one ascii character
  23948. bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
  23949. ) {
  23950. // try to find character in table (0-63, not found => -1)
  23951. buffer = chars.indexOf(buffer);
  23952. }
  23953. return output;
  23954. });
  23955. }());
  23956. },{}],142:[function(_dereq_,module,exports){
  23957. var http = _dereq_('http');
  23958. var https = module.exports;
  23959. for (var key in http) {
  23960. if (http.hasOwnProperty(key)) https[key] = http[key];
  23961. };
  23962. https.request = function (params, cb) {
  23963. if (!params) params = {};
  23964. params.scheme = 'https';
  23965. return http.request.call(this, params, cb);
  23966. }
  23967. },{"http":138}],143:[function(_dereq_,module,exports){
  23968. if (typeof Object.create === 'function') {
  23969. // implementation from standard node.js 'util' module
  23970. module.exports = function inherits(ctor, superCtor) {
  23971. ctor.super_ = superCtor
  23972. ctor.prototype = Object.create(superCtor.prototype, {
  23973. constructor: {
  23974. value: ctor,
  23975. enumerable: false,
  23976. writable: true,
  23977. configurable: true
  23978. }
  23979. });
  23980. };
  23981. } else {
  23982. // old school shim for old browsers
  23983. module.exports = function inherits(ctor, superCtor) {
  23984. ctor.super_ = superCtor
  23985. var TempCtor = function () {}
  23986. TempCtor.prototype = superCtor.prototype
  23987. ctor.prototype = new TempCtor()
  23988. ctor.prototype.constructor = ctor
  23989. }
  23990. }
  23991. },{}],144:[function(_dereq_,module,exports){
  23992. // shim for using process in browser
  23993. var process = module.exports = {};
  23994. process.nextTick = (function () {
  23995. var canSetImmediate = typeof window !== 'undefined'
  23996. && window.setImmediate;
  23997. var canPost = typeof window !== 'undefined'
  23998. && window.postMessage && window.addEventListener
  23999. ;
  24000. if (canSetImmediate) {
  24001. return function (f) { return window.setImmediate(f) };
  24002. }
  24003. if (canPost) {
  24004. var queue = [];
  24005. window.addEventListener('message', function (ev) {
  24006. var source = ev.source;
  24007. if ((source === window || source === null) && ev.data === 'process-tick') {
  24008. ev.stopPropagation();
  24009. if (queue.length > 0) {
  24010. var fn = queue.shift();
  24011. fn();
  24012. }
  24013. }
  24014. }, true);
  24015. return function nextTick(fn) {
  24016. queue.push(fn);
  24017. window.postMessage('process-tick', '*');
  24018. };
  24019. }
  24020. return function nextTick(fn) {
  24021. setTimeout(fn, 0);
  24022. };
  24023. })();
  24024. process.title = 'browser';
  24025. process.browser = true;
  24026. process.env = {};
  24027. process.argv = [];
  24028. function noop() {}
  24029. process.on = noop;
  24030. process.once = noop;
  24031. process.off = noop;
  24032. process.emit = noop;
  24033. process.binding = function (name) {
  24034. throw new Error('process.binding is not supported');
  24035. }
  24036. // TODO(shtylman)
  24037. process.cwd = function () { return '/' };
  24038. process.chdir = function (dir) {
  24039. throw new Error('process.chdir is not supported');
  24040. };
  24041. },{}],145:[function(_dereq_,module,exports){
  24042. (function (global){
  24043. /*! http://mths.be/punycode v1.2.4 by @mathias */
  24044. ;(function(root) {
  24045. /** Detect free variables */
  24046. var freeExports = typeof exports == 'object' && exports;
  24047. var freeModule = typeof module == 'object' && module &&
  24048. module.exports == freeExports && module;
  24049. var freeGlobal = typeof global == 'object' && global;
  24050. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  24051. root = freeGlobal;
  24052. }
  24053. /**
  24054. * The `punycode` object.
  24055. * @name punycode
  24056. * @type Object
  24057. */
  24058. var punycode,
  24059. /** Highest positive signed 32-bit float value */
  24060. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  24061. /** Bootstring parameters */
  24062. base = 36,
  24063. tMin = 1,
  24064. tMax = 26,
  24065. skew = 38,
  24066. damp = 700,
  24067. initialBias = 72,
  24068. initialN = 128, // 0x80
  24069. delimiter = '-', // '\x2D'
  24070. /** Regular expressions */
  24071. regexPunycode = /^xn--/,
  24072. regexNonASCII = /[^ -~]/, // unprintable ASCII chars + non-ASCII chars
  24073. regexSeparators = /\x2E|\u3002|\uFF0E|\uFF61/g, // RFC 3490 separators
  24074. /** Error messages */
  24075. errors = {
  24076. 'overflow': 'Overflow: input needs wider integers to process',
  24077. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  24078. 'invalid-input': 'Invalid input'
  24079. },
  24080. /** Convenience shortcuts */
  24081. baseMinusTMin = base - tMin,
  24082. floor = Math.floor,
  24083. stringFromCharCode = String.fromCharCode,
  24084. /** Temporary variable */
  24085. key;
  24086. /*--------------------------------------------------------------------------*/
  24087. /**
  24088. * A generic error utility function.
  24089. * @private
  24090. * @param {String} type The error type.
  24091. * @returns {Error} Throws a `RangeError` with the applicable error message.
  24092. */
  24093. function error(type) {
  24094. throw RangeError(errors[type]);
  24095. }
  24096. /**
  24097. * A generic `Array#map` utility function.
  24098. * @private
  24099. * @param {Array} array The array to iterate over.
  24100. * @param {Function} callback The function that gets called for every array
  24101. * item.
  24102. * @returns {Array} A new array of values returned by the callback function.
  24103. */
  24104. function map(array, fn) {
  24105. var length = array.length;
  24106. while (length--) {
  24107. array[length] = fn(array[length]);
  24108. }
  24109. return array;
  24110. }
  24111. /**
  24112. * A simple `Array#map`-like wrapper to work with domain name strings.
  24113. * @private
  24114. * @param {String} domain The domain name.
  24115. * @param {Function} callback The function that gets called for every
  24116. * character.
  24117. * @returns {Array} A new string of characters returned by the callback
  24118. * function.
  24119. */
  24120. function mapDomain(string, fn) {
  24121. return map(string.split(regexSeparators), fn).join('.');
  24122. }
  24123. /**
  24124. * Creates an array containing the numeric code points of each Unicode
  24125. * character in the string. While JavaScript uses UCS-2 internally,
  24126. * this function will convert a pair of surrogate halves (each of which
  24127. * UCS-2 exposes as separate characters) into a single code point,
  24128. * matching UTF-16.
  24129. * @see `punycode.ucs2.encode`
  24130. * @see <http://mathiasbynens.be/notes/javascript-encoding>
  24131. * @memberOf punycode.ucs2
  24132. * @name decode
  24133. * @param {String} string The Unicode input string (UCS-2).
  24134. * @returns {Array} The new array of code points.
  24135. */
  24136. function ucs2decode(string) {
  24137. var output = [],
  24138. counter = 0,
  24139. length = string.length,
  24140. value,
  24141. extra;
  24142. while (counter < length) {
  24143. value = string.charCodeAt(counter++);
  24144. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  24145. // high surrogate, and there is a next character
  24146. extra = string.charCodeAt(counter++);
  24147. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  24148. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  24149. } else {
  24150. // unmatched surrogate; only append this code unit, in case the next
  24151. // code unit is the high surrogate of a surrogate pair
  24152. output.push(value);
  24153. counter--;
  24154. }
  24155. } else {
  24156. output.push(value);
  24157. }
  24158. }
  24159. return output;
  24160. }
  24161. /**
  24162. * Creates a string based on an array of numeric code points.
  24163. * @see `punycode.ucs2.decode`
  24164. * @memberOf punycode.ucs2
  24165. * @name encode
  24166. * @param {Array} codePoints The array of numeric code points.
  24167. * @returns {String} The new Unicode string (UCS-2).
  24168. */
  24169. function ucs2encode(array) {
  24170. return map(array, function(value) {
  24171. var output = '';
  24172. if (value > 0xFFFF) {
  24173. value -= 0x10000;
  24174. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  24175. value = 0xDC00 | value & 0x3FF;
  24176. }
  24177. output += stringFromCharCode(value);
  24178. return output;
  24179. }).join('');
  24180. }
  24181. /**
  24182. * Converts a basic code point into a digit/integer.
  24183. * @see `digitToBasic()`
  24184. * @private
  24185. * @param {Number} codePoint The basic numeric code point value.
  24186. * @returns {Number} The numeric value of a basic code point (for use in
  24187. * representing integers) in the range `0` to `base - 1`, or `base` if
  24188. * the code point does not represent a value.
  24189. */
  24190. function basicToDigit(codePoint) {
  24191. if (codePoint - 48 < 10) {
  24192. return codePoint - 22;
  24193. }
  24194. if (codePoint - 65 < 26) {
  24195. return codePoint - 65;
  24196. }
  24197. if (codePoint - 97 < 26) {
  24198. return codePoint - 97;
  24199. }
  24200. return base;
  24201. }
  24202. /**
  24203. * Converts a digit/integer into a basic code point.
  24204. * @see `basicToDigit()`
  24205. * @private
  24206. * @param {Number} digit The numeric value of a basic code point.
  24207. * @returns {Number} The basic code point whose value (when used for
  24208. * representing integers) is `digit`, which needs to be in the range
  24209. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  24210. * used; else, the lowercase form is used. The behavior is undefined
  24211. * if `flag` is non-zero and `digit` has no uppercase form.
  24212. */
  24213. function digitToBasic(digit, flag) {
  24214. // 0..25 map to ASCII a..z or A..Z
  24215. // 26..35 map to ASCII 0..9
  24216. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  24217. }
  24218. /**
  24219. * Bias adaptation function as per section 3.4 of RFC 3492.
  24220. * http://tools.ietf.org/html/rfc3492#section-3.4
  24221. * @private
  24222. */
  24223. function adapt(delta, numPoints, firstTime) {
  24224. var k = 0;
  24225. delta = firstTime ? floor(delta / damp) : delta >> 1;
  24226. delta += floor(delta / numPoints);
  24227. for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  24228. delta = floor(delta / baseMinusTMin);
  24229. }
  24230. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  24231. }
  24232. /**
  24233. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  24234. * symbols.
  24235. * @memberOf punycode
  24236. * @param {String} input The Punycode string of ASCII-only symbols.
  24237. * @returns {String} The resulting string of Unicode symbols.
  24238. */
  24239. function decode(input) {
  24240. // Don't use UCS-2
  24241. var output = [],
  24242. inputLength = input.length,
  24243. out,
  24244. i = 0,
  24245. n = initialN,
  24246. bias = initialBias,
  24247. basic,
  24248. j,
  24249. index,
  24250. oldi,
  24251. w,
  24252. k,
  24253. digit,
  24254. t,
  24255. /** Cached calculation results */
  24256. baseMinusT;
  24257. // Handle the basic code points: let `basic` be the number of input code
  24258. // points before the last delimiter, or `0` if there is none, then copy
  24259. // the first basic code points to the output.
  24260. basic = input.lastIndexOf(delimiter);
  24261. if (basic < 0) {
  24262. basic = 0;
  24263. }
  24264. for (j = 0; j < basic; ++j) {
  24265. // if it's not a basic code point
  24266. if (input.charCodeAt(j) >= 0x80) {
  24267. error('not-basic');
  24268. }
  24269. output.push(input.charCodeAt(j));
  24270. }
  24271. // Main decoding loop: start just after the last delimiter if any basic code
  24272. // points were copied; start at the beginning otherwise.
  24273. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
  24274. // `index` is the index of the next character to be consumed.
  24275. // Decode a generalized variable-length integer into `delta`,
  24276. // which gets added to `i`. The overflow checking is easier
  24277. // if we increase `i` as we go, then subtract off its starting
  24278. // value at the end to obtain `delta`.
  24279. for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
  24280. if (index >= inputLength) {
  24281. error('invalid-input');
  24282. }
  24283. digit = basicToDigit(input.charCodeAt(index++));
  24284. if (digit >= base || digit > floor((maxInt - i) / w)) {
  24285. error('overflow');
  24286. }
  24287. i += digit * w;
  24288. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  24289. if (digit < t) {
  24290. break;
  24291. }
  24292. baseMinusT = base - t;
  24293. if (w > floor(maxInt / baseMinusT)) {
  24294. error('overflow');
  24295. }
  24296. w *= baseMinusT;
  24297. }
  24298. out = output.length + 1;
  24299. bias = adapt(i - oldi, out, oldi == 0);
  24300. // `i` was supposed to wrap around from `out` to `0`,
  24301. // incrementing `n` each time, so we'll fix that now:
  24302. if (floor(i / out) > maxInt - n) {
  24303. error('overflow');
  24304. }
  24305. n += floor(i / out);
  24306. i %= out;
  24307. // Insert `n` at position `i` of the output
  24308. output.splice(i++, 0, n);
  24309. }
  24310. return ucs2encode(output);
  24311. }
  24312. /**
  24313. * Converts a string of Unicode symbols to a Punycode string of ASCII-only
  24314. * symbols.
  24315. * @memberOf punycode
  24316. * @param {String} input The string of Unicode symbols.
  24317. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  24318. */
  24319. function encode(input) {
  24320. var n,
  24321. delta,
  24322. handledCPCount,
  24323. basicLength,
  24324. bias,
  24325. j,
  24326. m,
  24327. q,
  24328. k,
  24329. t,
  24330. currentValue,
  24331. output = [],
  24332. /** `inputLength` will hold the number of code points in `input`. */
  24333. inputLength,
  24334. /** Cached calculation results */
  24335. handledCPCountPlusOne,
  24336. baseMinusT,
  24337. qMinusT;
  24338. // Convert the input in UCS-2 to Unicode
  24339. input = ucs2decode(input);
  24340. // Cache the length
  24341. inputLength = input.length;
  24342. // Initialize the state
  24343. n = initialN;
  24344. delta = 0;
  24345. bias = initialBias;
  24346. // Handle the basic code points
  24347. for (j = 0; j < inputLength; ++j) {
  24348. currentValue = input[j];
  24349. if (currentValue < 0x80) {
  24350. output.push(stringFromCharCode(currentValue));
  24351. }
  24352. }
  24353. handledCPCount = basicLength = output.length;
  24354. // `handledCPCount` is the number of code points that have been handled;
  24355. // `basicLength` is the number of basic code points.
  24356. // Finish the basic string - if it is not empty - with a delimiter
  24357. if (basicLength) {
  24358. output.push(delimiter);
  24359. }
  24360. // Main encoding loop:
  24361. while (handledCPCount < inputLength) {
  24362. // All non-basic code points < n have been handled already. Find the next
  24363. // larger one:
  24364. for (m = maxInt, j = 0; j < inputLength; ++j) {
  24365. currentValue = input[j];
  24366. if (currentValue >= n && currentValue < m) {
  24367. m = currentValue;
  24368. }
  24369. }
  24370. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  24371. // but guard against overflow
  24372. handledCPCountPlusOne = handledCPCount + 1;
  24373. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  24374. error('overflow');
  24375. }
  24376. delta += (m - n) * handledCPCountPlusOne;
  24377. n = m;
  24378. for (j = 0; j < inputLength; ++j) {
  24379. currentValue = input[j];
  24380. if (currentValue < n && ++delta > maxInt) {
  24381. error('overflow');
  24382. }
  24383. if (currentValue == n) {
  24384. // Represent delta as a generalized variable-length integer
  24385. for (q = delta, k = base; /* no condition */; k += base) {
  24386. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  24387. if (q < t) {
  24388. break;
  24389. }
  24390. qMinusT = q - t;
  24391. baseMinusT = base - t;
  24392. output.push(
  24393. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  24394. );
  24395. q = floor(qMinusT / baseMinusT);
  24396. }
  24397. output.push(stringFromCharCode(digitToBasic(q, 0)));
  24398. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  24399. delta = 0;
  24400. ++handledCPCount;
  24401. }
  24402. }
  24403. ++delta;
  24404. ++n;
  24405. }
  24406. return output.join('');
  24407. }
  24408. /**
  24409. * Converts a Punycode string representing a domain name to Unicode. Only the
  24410. * Punycoded parts of the domain name will be converted, i.e. it doesn't
  24411. * matter if you call it on a string that has already been converted to
  24412. * Unicode.
  24413. * @memberOf punycode
  24414. * @param {String} domain The Punycode domain name to convert to Unicode.
  24415. * @returns {String} The Unicode representation of the given Punycode
  24416. * string.
  24417. */
  24418. function toUnicode(domain) {
  24419. return mapDomain(domain, function(string) {
  24420. return regexPunycode.test(string)
  24421. ? decode(string.slice(4).toLowerCase())
  24422. : string;
  24423. });
  24424. }
  24425. /**
  24426. * Converts a Unicode string representing a domain name to Punycode. Only the
  24427. * non-ASCII parts of the domain name will be converted, i.e. it doesn't
  24428. * matter if you call it with a domain that's already in ASCII.
  24429. * @memberOf punycode
  24430. * @param {String} domain The domain name to convert, as a Unicode string.
  24431. * @returns {String} The Punycode representation of the given domain name.
  24432. */
  24433. function toASCII(domain) {
  24434. return mapDomain(domain, function(string) {
  24435. return regexNonASCII.test(string)
  24436. ? 'xn--' + encode(string)
  24437. : string;
  24438. });
  24439. }
  24440. /*--------------------------------------------------------------------------*/
  24441. /** Define the public API */
  24442. punycode = {
  24443. /**
  24444. * A string representing the current Punycode.js version number.
  24445. * @memberOf punycode
  24446. * @type String
  24447. */
  24448. 'version': '1.2.4',
  24449. /**
  24450. * An object of methods to convert from JavaScript's internal character
  24451. * representation (UCS-2) to Unicode code points, and back.
  24452. * @see <http://mathiasbynens.be/notes/javascript-encoding>
  24453. * @memberOf punycode
  24454. * @type Object
  24455. */
  24456. 'ucs2': {
  24457. 'decode': ucs2decode,
  24458. 'encode': ucs2encode
  24459. },
  24460. 'decode': decode,
  24461. 'encode': encode,
  24462. 'toASCII': toASCII,
  24463. 'toUnicode': toUnicode
  24464. };
  24465. /** Expose `punycode` */
  24466. // Some AMD build optimizers, like r.js, check for specific condition patterns
  24467. // like the following:
  24468. if (
  24469. typeof define == 'function' &&
  24470. typeof define.amd == 'object' &&
  24471. define.amd
  24472. ) {
  24473. define('punycode', function() {
  24474. return punycode;
  24475. });
  24476. } else if (freeExports && !freeExports.nodeType) {
  24477. if (freeModule) { // in Node.js or RingoJS v0.8.0+
  24478. freeModule.exports = punycode;
  24479. } else { // in Narwhal or RingoJS v0.7.0-
  24480. for (key in punycode) {
  24481. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  24482. }
  24483. }
  24484. } else { // in Rhino or a web browser
  24485. root.punycode = punycode;
  24486. }
  24487. }(this));
  24488. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  24489. },{}],146:[function(_dereq_,module,exports){
  24490. // Copyright Joyent, Inc. and other Node contributors.
  24491. //
  24492. // Permission is hereby granted, free of charge, to any person obtaining a
  24493. // copy of this software and associated documentation files (the
  24494. // "Software"), to deal in the Software without restriction, including
  24495. // without limitation the rights to use, copy, modify, merge, publish,
  24496. // distribute, sublicense, and/or sell copies of the Software, and to permit
  24497. // persons to whom the Software is furnished to do so, subject to the
  24498. // following conditions:
  24499. //
  24500. // The above copyright notice and this permission notice shall be included
  24501. // in all copies or substantial portions of the Software.
  24502. //
  24503. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  24504. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24505. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  24506. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  24507. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  24508. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  24509. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  24510. 'use strict';
  24511. // If obj.hasOwnProperty has been overridden, then calling
  24512. // obj.hasOwnProperty(prop) will break.
  24513. // See: https://github.com/joyent/node/issues/1707
  24514. function hasOwnProperty(obj, prop) {
  24515. return Object.prototype.hasOwnProperty.call(obj, prop);
  24516. }
  24517. module.exports = function(qs, sep, eq, options) {
  24518. sep = sep || '&';
  24519. eq = eq || '=';
  24520. var obj = {};
  24521. if (typeof qs !== 'string' || qs.length === 0) {
  24522. return obj;
  24523. }
  24524. var regexp = /\+/g;
  24525. qs = qs.split(sep);
  24526. var maxKeys = 1000;
  24527. if (options && typeof options.maxKeys === 'number') {
  24528. maxKeys = options.maxKeys;
  24529. }
  24530. var len = qs.length;
  24531. // maxKeys <= 0 means that we should not limit keys count
  24532. if (maxKeys > 0 && len > maxKeys) {
  24533. len = maxKeys;
  24534. }
  24535. for (var i = 0; i < len; ++i) {
  24536. var x = qs[i].replace(regexp, '%20'),
  24537. idx = x.indexOf(eq),
  24538. kstr, vstr, k, v;
  24539. if (idx >= 0) {
  24540. kstr = x.substr(0, idx);
  24541. vstr = x.substr(idx + 1);
  24542. } else {
  24543. kstr = x;
  24544. vstr = '';
  24545. }
  24546. k = decodeURIComponent(kstr);
  24547. v = decodeURIComponent(vstr);
  24548. if (!hasOwnProperty(obj, k)) {
  24549. obj[k] = v;
  24550. } else if (isArray(obj[k])) {
  24551. obj[k].push(v);
  24552. } else {
  24553. obj[k] = [obj[k], v];
  24554. }
  24555. }
  24556. return obj;
  24557. };
  24558. var isArray = Array.isArray || function (xs) {
  24559. return Object.prototype.toString.call(xs) === '[object Array]';
  24560. };
  24561. },{}],147:[function(_dereq_,module,exports){
  24562. // Copyright Joyent, Inc. and other Node contributors.
  24563. //
  24564. // Permission is hereby granted, free of charge, to any person obtaining a
  24565. // copy of this software and associated documentation files (the
  24566. // "Software"), to deal in the Software without restriction, including
  24567. // without limitation the rights to use, copy, modify, merge, publish,
  24568. // distribute, sublicense, and/or sell copies of the Software, and to permit
  24569. // persons to whom the Software is furnished to do so, subject to the
  24570. // following conditions:
  24571. //
  24572. // The above copyright notice and this permission notice shall be included
  24573. // in all copies or substantial portions of the Software.
  24574. //
  24575. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  24576. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24577. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  24578. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  24579. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  24580. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  24581. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  24582. 'use strict';
  24583. var stringifyPrimitive = function(v) {
  24584. switch (typeof v) {
  24585. case 'string':
  24586. return v;
  24587. case 'boolean':
  24588. return v ? 'true' : 'false';
  24589. case 'number':
  24590. return isFinite(v) ? v : '';
  24591. default:
  24592. return '';
  24593. }
  24594. };
  24595. module.exports = function(obj, sep, eq, name) {
  24596. sep = sep || '&';
  24597. eq = eq || '=';
  24598. if (obj === null) {
  24599. obj = undefined;
  24600. }
  24601. if (typeof obj === 'object') {
  24602. return map(objectKeys(obj), function(k) {
  24603. var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
  24604. if (isArray(obj[k])) {
  24605. return obj[k].map(function(v) {
  24606. return ks + encodeURIComponent(stringifyPrimitive(v));
  24607. }).join(sep);
  24608. } else {
  24609. return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
  24610. }
  24611. }).join(sep);
  24612. }
  24613. if (!name) return '';
  24614. return encodeURIComponent(stringifyPrimitive(name)) + eq +
  24615. encodeURIComponent(stringifyPrimitive(obj));
  24616. };
  24617. var isArray = Array.isArray || function (xs) {
  24618. return Object.prototype.toString.call(xs) === '[object Array]';
  24619. };
  24620. function map (xs, f) {
  24621. if (xs.map) return xs.map(f);
  24622. var res = [];
  24623. for (var i = 0; i < xs.length; i++) {
  24624. res.push(f(xs[i], i));
  24625. }
  24626. return res;
  24627. }
  24628. var objectKeys = Object.keys || function (obj) {
  24629. var res = [];
  24630. for (var key in obj) {
  24631. if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
  24632. }
  24633. return res;
  24634. };
  24635. },{}],148:[function(_dereq_,module,exports){
  24636. 'use strict';
  24637. exports.decode = exports.parse = _dereq_('./decode');
  24638. exports.encode = exports.stringify = _dereq_('./encode');
  24639. },{"./decode":146,"./encode":147}],149:[function(_dereq_,module,exports){
  24640. // Copyright Joyent, Inc. and other Node contributors.
  24641. //
  24642. // Permission is hereby granted, free of charge, to any person obtaining a
  24643. // copy of this software and associated documentation files (the
  24644. // "Software"), to deal in the Software without restriction, including
  24645. // without limitation the rights to use, copy, modify, merge, publish,
  24646. // distribute, sublicense, and/or sell copies of the Software, and to permit
  24647. // persons to whom the Software is furnished to do so, subject to the
  24648. // following conditions:
  24649. //
  24650. // The above copyright notice and this permission notice shall be included
  24651. // in all copies or substantial portions of the Software.
  24652. //
  24653. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  24654. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24655. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  24656. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  24657. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  24658. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  24659. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  24660. // a duplex stream is just a stream that is both readable and writable.
  24661. // Since JS doesn't have multiple prototypal inheritance, this class
  24662. // prototypally inherits from Readable, and then parasitically from
  24663. // Writable.
  24664. module.exports = Duplex;
  24665. var inherits = _dereq_('inherits');
  24666. var setImmediate = _dereq_('process/browser.js').nextTick;
  24667. var Readable = _dereq_('./readable.js');
  24668. var Writable = _dereq_('./writable.js');
  24669. inherits(Duplex, Readable);
  24670. Duplex.prototype.write = Writable.prototype.write;
  24671. Duplex.prototype.end = Writable.prototype.end;
  24672. Duplex.prototype._write = Writable.prototype._write;
  24673. function Duplex(options) {
  24674. if (!(this instanceof Duplex))
  24675. return new Duplex(options);
  24676. Readable.call(this, options);
  24677. Writable.call(this, options);
  24678. if (options && options.readable === false)
  24679. this.readable = false;
  24680. if (options && options.writable === false)
  24681. this.writable = false;
  24682. this.allowHalfOpen = true;
  24683. if (options && options.allowHalfOpen === false)
  24684. this.allowHalfOpen = false;
  24685. this.once('end', onend);
  24686. }
  24687. // the no-half-open enforcer
  24688. function onend() {
  24689. // if we allow half-open state, or if the writable side ended,
  24690. // then we're ok.
  24691. if (this.allowHalfOpen || this._writableState.ended)
  24692. return;
  24693. // no more data can be written.
  24694. // But allow more writes to happen in this tick.
  24695. var self = this;
  24696. setImmediate(function () {
  24697. self.end();
  24698. });
  24699. }
  24700. },{"./readable.js":153,"./writable.js":155,"inherits":143,"process/browser.js":151}],150:[function(_dereq_,module,exports){
  24701. // Copyright Joyent, Inc. and other Node contributors.
  24702. //
  24703. // Permission is hereby granted, free of charge, to any person obtaining a
  24704. // copy of this software and associated documentation files (the
  24705. // "Software"), to deal in the Software without restriction, including
  24706. // without limitation the rights to use, copy, modify, merge, publish,
  24707. // distribute, sublicense, and/or sell copies of the Software, and to permit
  24708. // persons to whom the Software is furnished to do so, subject to the
  24709. // following conditions:
  24710. //
  24711. // The above copyright notice and this permission notice shall be included
  24712. // in all copies or substantial portions of the Software.
  24713. //
  24714. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  24715. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24716. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  24717. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  24718. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  24719. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  24720. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  24721. module.exports = Stream;
  24722. var EE = _dereq_('events').EventEmitter;
  24723. var inherits = _dereq_('inherits');
  24724. inherits(Stream, EE);
  24725. Stream.Readable = _dereq_('./readable.js');
  24726. Stream.Writable = _dereq_('./writable.js');
  24727. Stream.Duplex = _dereq_('./duplex.js');
  24728. Stream.Transform = _dereq_('./transform.js');
  24729. Stream.PassThrough = _dereq_('./passthrough.js');
  24730. // Backwards-compat with node 0.4.x
  24731. Stream.Stream = Stream;
  24732. // old-style streams. Note that the pipe method (the only relevant
  24733. // part of this class) is overridden in the Readable class.
  24734. function Stream() {
  24735. EE.call(this);
  24736. }
  24737. Stream.prototype.pipe = function(dest, options) {
  24738. var source = this;
  24739. function ondata(chunk) {
  24740. if (dest.writable) {
  24741. if (false === dest.write(chunk) && source.pause) {
  24742. source.pause();
  24743. }
  24744. }
  24745. }
  24746. source.on('data', ondata);
  24747. function ondrain() {
  24748. if (source.readable && source.resume) {
  24749. source.resume();
  24750. }
  24751. }
  24752. dest.on('drain', ondrain);
  24753. // If the 'end' option is not supplied, dest.end() will be called when
  24754. // source gets the 'end' or 'close' events. Only dest.end() once.
  24755. if (!dest._isStdio && (!options || options.end !== false)) {
  24756. source.on('end', onend);
  24757. source.on('close', onclose);
  24758. }
  24759. var didOnEnd = false;
  24760. function onend() {
  24761. if (didOnEnd) return;
  24762. didOnEnd = true;
  24763. dest.end();
  24764. }
  24765. function onclose() {
  24766. if (didOnEnd) return;
  24767. didOnEnd = true;
  24768. if (typeof dest.destroy === 'function') dest.destroy();
  24769. }
  24770. // don't leave dangling pipes when there are errors.
  24771. function onerror(er) {
  24772. cleanup();
  24773. if (EE.listenerCount(this, 'error') === 0) {
  24774. throw er; // Unhandled stream error in pipe.
  24775. }
  24776. }
  24777. source.on('error', onerror);
  24778. dest.on('error', onerror);
  24779. // remove all the event listeners that were added.
  24780. function cleanup() {
  24781. source.removeListener('data', ondata);
  24782. dest.removeListener('drain', ondrain);
  24783. source.removeListener('end', onend);
  24784. source.removeListener('close', onclose);
  24785. source.removeListener('error', onerror);
  24786. dest.removeListener('error', onerror);
  24787. source.removeListener('end', cleanup);
  24788. source.removeListener('close', cleanup);
  24789. dest.removeListener('close', cleanup);
  24790. }
  24791. source.on('end', cleanup);
  24792. source.on('close', cleanup);
  24793. dest.on('close', cleanup);
  24794. dest.emit('pipe', source);
  24795. // Allow for unix-like usage: A.pipe(B).pipe(C)
  24796. return dest;
  24797. };
  24798. },{"./duplex.js":149,"./passthrough.js":152,"./readable.js":153,"./transform.js":154,"./writable.js":155,"events":137,"inherits":143}],151:[function(_dereq_,module,exports){
  24799. // shim for using process in browser
  24800. var process = module.exports = {};
  24801. process.nextTick = (function () {
  24802. var canSetImmediate = typeof window !== 'undefined'
  24803. && window.setImmediate;
  24804. var canPost = typeof window !== 'undefined'
  24805. && window.postMessage && window.addEventListener
  24806. ;
  24807. if (canSetImmediate) {
  24808. return function (f) { return window.setImmediate(f) };
  24809. }
  24810. if (canPost) {
  24811. var queue = [];
  24812. window.addEventListener('message', function (ev) {
  24813. var source = ev.source;
  24814. if ((source === window || source === null) && ev.data === 'process-tick') {
  24815. ev.stopPropagation();
  24816. if (queue.length > 0) {
  24817. var fn = queue.shift();
  24818. fn();
  24819. }
  24820. }
  24821. }, true);
  24822. return function nextTick(fn) {
  24823. queue.push(fn);
  24824. window.postMessage('process-tick', '*');
  24825. };
  24826. }
  24827. return function nextTick(fn) {
  24828. setTimeout(fn, 0);
  24829. };
  24830. })();
  24831. process.title = 'browser';
  24832. process.browser = true;
  24833. process.env = {};
  24834. process.argv = [];
  24835. process.binding = function (name) {
  24836. throw new Error('process.binding is not supported');
  24837. }
  24838. // TODO(shtylman)
  24839. process.cwd = function () { return '/' };
  24840. process.chdir = function (dir) {
  24841. throw new Error('process.chdir is not supported');
  24842. };
  24843. },{}],152:[function(_dereq_,module,exports){
  24844. // Copyright Joyent, Inc. and other Node contributors.
  24845. //
  24846. // Permission is hereby granted, free of charge, to any person obtaining a
  24847. // copy of this software and associated documentation files (the
  24848. // "Software"), to deal in the Software without restriction, including
  24849. // without limitation the rights to use, copy, modify, merge, publish,
  24850. // distribute, sublicense, and/or sell copies of the Software, and to permit
  24851. // persons to whom the Software is furnished to do so, subject to the
  24852. // following conditions:
  24853. //
  24854. // The above copyright notice and this permission notice shall be included
  24855. // in all copies or substantial portions of the Software.
  24856. //
  24857. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  24858. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24859. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  24860. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  24861. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  24862. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  24863. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  24864. // a passthrough stream.
  24865. // basically just the most minimal sort of Transform stream.
  24866. // Every written chunk gets output as-is.
  24867. module.exports = PassThrough;
  24868. var Transform = _dereq_('./transform.js');
  24869. var inherits = _dereq_('inherits');
  24870. inherits(PassThrough, Transform);
  24871. function PassThrough(options) {
  24872. if (!(this instanceof PassThrough))
  24873. return new PassThrough(options);
  24874. Transform.call(this, options);
  24875. }
  24876. PassThrough.prototype._transform = function(chunk, encoding, cb) {
  24877. cb(null, chunk);
  24878. };
  24879. },{"./transform.js":154,"inherits":143}],153:[function(_dereq_,module,exports){
  24880. (function (process){
  24881. // Copyright Joyent, Inc. and other Node contributors.
  24882. //
  24883. // Permission is hereby granted, free of charge, to any person obtaining a
  24884. // copy of this software and associated documentation files (the
  24885. // "Software"), to deal in the Software without restriction, including
  24886. // without limitation the rights to use, copy, modify, merge, publish,
  24887. // distribute, sublicense, and/or sell copies of the Software, and to permit
  24888. // persons to whom the Software is furnished to do so, subject to the
  24889. // following conditions:
  24890. //
  24891. // The above copyright notice and this permission notice shall be included
  24892. // in all copies or substantial portions of the Software.
  24893. //
  24894. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  24895. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24896. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  24897. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  24898. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  24899. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  24900. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  24901. module.exports = Readable;
  24902. Readable.ReadableState = ReadableState;
  24903. var EE = _dereq_('events').EventEmitter;
  24904. var Stream = _dereq_('./index.js');
  24905. var Buffer = _dereq_('buffer').Buffer;
  24906. var setImmediate = _dereq_('process/browser.js').nextTick;
  24907. var StringDecoder;
  24908. var inherits = _dereq_('inherits');
  24909. inherits(Readable, Stream);
  24910. function ReadableState(options, stream) {
  24911. options = options || {};
  24912. // the point at which it stops calling _read() to fill the buffer
  24913. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  24914. var hwm = options.highWaterMark;
  24915. this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
  24916. // cast to ints.
  24917. this.highWaterMark = ~~this.highWaterMark;
  24918. this.buffer = [];
  24919. this.length = 0;
  24920. this.pipes = null;
  24921. this.pipesCount = 0;
  24922. this.flowing = false;
  24923. this.ended = false;
  24924. this.endEmitted = false;
  24925. this.reading = false;
  24926. // In streams that never have any data, and do push(null) right away,
  24927. // the consumer can miss the 'end' event if they do some I/O before
  24928. // consuming the stream. So, we don't emit('end') until some reading
  24929. // happens.
  24930. this.calledRead = false;
  24931. // a flag to be able to tell if the onwrite cb is called immediately,
  24932. // or on a later tick. We set this to true at first, becuase any
  24933. // actions that shouldn't happen until "later" should generally also
  24934. // not happen before the first write call.
  24935. this.sync = true;
  24936. // whenever we return null, then we set a flag to say
  24937. // that we're awaiting a 'readable' event emission.
  24938. this.needReadable = false;
  24939. this.emittedReadable = false;
  24940. this.readableListening = false;
  24941. // object stream flag. Used to make read(n) ignore n and to
  24942. // make all the buffer merging and length checks go away
  24943. this.objectMode = !!options.objectMode;
  24944. // Crypto is kind of old and crusty. Historically, its default string
  24945. // encoding is 'binary' so we have to make this configurable.
  24946. // Everything else in the universe uses 'utf8', though.
  24947. this.defaultEncoding = options.defaultEncoding || 'utf8';
  24948. // when piping, we only care about 'readable' events that happen
  24949. // after read()ing all the bytes and not getting any pushback.
  24950. this.ranOut = false;
  24951. // the number of writers that are awaiting a drain event in .pipe()s
  24952. this.awaitDrain = 0;
  24953. // if true, a maybeReadMore has been scheduled
  24954. this.readingMore = false;
  24955. this.decoder = null;
  24956. this.encoding = null;
  24957. if (options.encoding) {
  24958. if (!StringDecoder)
  24959. StringDecoder = _dereq_('string_decoder').StringDecoder;
  24960. this.decoder = new StringDecoder(options.encoding);
  24961. this.encoding = options.encoding;
  24962. }
  24963. }
  24964. function Readable(options) {
  24965. if (!(this instanceof Readable))
  24966. return new Readable(options);
  24967. this._readableState = new ReadableState(options, this);
  24968. // legacy
  24969. this.readable = true;
  24970. Stream.call(this);
  24971. }
  24972. // Manually shove something into the read() buffer.
  24973. // This returns true if the highWaterMark has not been hit yet,
  24974. // similar to how Writable.write() returns true if you should
  24975. // write() some more.
  24976. Readable.prototype.push = function(chunk, encoding) {
  24977. var state = this._readableState;
  24978. if (typeof chunk === 'string' && !state.objectMode) {
  24979. encoding = encoding || state.defaultEncoding;
  24980. if (encoding !== state.encoding) {
  24981. chunk = new Buffer(chunk, encoding);
  24982. encoding = '';
  24983. }
  24984. }
  24985. return readableAddChunk(this, state, chunk, encoding, false);
  24986. };
  24987. // Unshift should *always* be something directly out of read()
  24988. Readable.prototype.unshift = function(chunk) {
  24989. var state = this._readableState;
  24990. return readableAddChunk(this, state, chunk, '', true);
  24991. };
  24992. function readableAddChunk(stream, state, chunk, encoding, addToFront) {
  24993. var er = chunkInvalid(state, chunk);
  24994. if (er) {
  24995. stream.emit('error', er);
  24996. } else if (chunk === null || chunk === undefined) {
  24997. state.reading = false;
  24998. if (!state.ended)
  24999. onEofChunk(stream, state);
  25000. } else if (state.objectMode || chunk && chunk.length > 0) {
  25001. if (state.ended && !addToFront) {
  25002. var e = new Error('stream.push() after EOF');
  25003. stream.emit('error', e);
  25004. } else if (state.endEmitted && addToFront) {
  25005. var e = new Error('stream.unshift() after end event');
  25006. stream.emit('error', e);
  25007. } else {
  25008. if (state.decoder && !addToFront && !encoding)
  25009. chunk = state.decoder.write(chunk);
  25010. // update the buffer info.
  25011. state.length += state.objectMode ? 1 : chunk.length;
  25012. if (addToFront) {
  25013. state.buffer.unshift(chunk);
  25014. } else {
  25015. state.reading = false;
  25016. state.buffer.push(chunk);
  25017. }
  25018. if (state.needReadable)
  25019. emitReadable(stream);
  25020. maybeReadMore(stream, state);
  25021. }
  25022. } else if (!addToFront) {
  25023. state.reading = false;
  25024. }
  25025. return needMoreData(state);
  25026. }
  25027. // if it's past the high water mark, we can push in some more.
  25028. // Also, if we have no data yet, we can stand some
  25029. // more bytes. This is to work around cases where hwm=0,
  25030. // such as the repl. Also, if the push() triggered a
  25031. // readable event, and the user called read(largeNumber) such that
  25032. // needReadable was set, then we ought to push more, so that another
  25033. // 'readable' event will be triggered.
  25034. function needMoreData(state) {
  25035. return !state.ended &&
  25036. (state.needReadable ||
  25037. state.length < state.highWaterMark ||
  25038. state.length === 0);
  25039. }
  25040. // backwards compatibility.
  25041. Readable.prototype.setEncoding = function(enc) {
  25042. if (!StringDecoder)
  25043. StringDecoder = _dereq_('string_decoder').StringDecoder;
  25044. this._readableState.decoder = new StringDecoder(enc);
  25045. this._readableState.encoding = enc;
  25046. };
  25047. // Don't raise the hwm > 128MB
  25048. var MAX_HWM = 0x800000;
  25049. function roundUpToNextPowerOf2(n) {
  25050. if (n >= MAX_HWM) {
  25051. n = MAX_HWM;
  25052. } else {
  25053. // Get the next highest power of 2
  25054. n--;
  25055. for (var p = 1; p < 32; p <<= 1) n |= n >> p;
  25056. n++;
  25057. }
  25058. return n;
  25059. }
  25060. function howMuchToRead(n, state) {
  25061. if (state.length === 0 && state.ended)
  25062. return 0;
  25063. if (state.objectMode)
  25064. return n === 0 ? 0 : 1;
  25065. if (isNaN(n) || n === null) {
  25066. // only flow one buffer at a time
  25067. if (state.flowing && state.buffer.length)
  25068. return state.buffer[0].length;
  25069. else
  25070. return state.length;
  25071. }
  25072. if (n <= 0)
  25073. return 0;
  25074. // If we're asking for more than the target buffer level,
  25075. // then raise the water mark. Bump up to the next highest
  25076. // power of 2, to prevent increasing it excessively in tiny
  25077. // amounts.
  25078. if (n > state.highWaterMark)
  25079. state.highWaterMark = roundUpToNextPowerOf2(n);
  25080. // don't have that much. return null, unless we've ended.
  25081. if (n > state.length) {
  25082. if (!state.ended) {
  25083. state.needReadable = true;
  25084. return 0;
  25085. } else
  25086. return state.length;
  25087. }
  25088. return n;
  25089. }
  25090. // you can override either this method, or the async _read(n) below.
  25091. Readable.prototype.read = function(n) {
  25092. var state = this._readableState;
  25093. state.calledRead = true;
  25094. var nOrig = n;
  25095. if (typeof n !== 'number' || n > 0)
  25096. state.emittedReadable = false;
  25097. // if we're doing read(0) to trigger a readable event, but we
  25098. // already have a bunch of data in the buffer, then just trigger
  25099. // the 'readable' event and move on.
  25100. if (n === 0 &&
  25101. state.needReadable &&
  25102. (state.length >= state.highWaterMark || state.ended)) {
  25103. emitReadable(this);
  25104. return null;
  25105. }
  25106. n = howMuchToRead(n, state);
  25107. // if we've ended, and we're now clear, then finish it up.
  25108. if (n === 0 && state.ended) {
  25109. if (state.length === 0)
  25110. endReadable(this);
  25111. return null;
  25112. }
  25113. // All the actual chunk generation logic needs to be
  25114. // *below* the call to _read. The reason is that in certain
  25115. // synthetic stream cases, such as passthrough streams, _read
  25116. // may be a completely synchronous operation which may change
  25117. // the state of the read buffer, providing enough data when
  25118. // before there was *not* enough.
  25119. //
  25120. // So, the steps are:
  25121. // 1. Figure out what the state of things will be after we do
  25122. // a read from the buffer.
  25123. //
  25124. // 2. If that resulting state will trigger a _read, then call _read.
  25125. // Note that this may be asynchronous, or synchronous. Yes, it is
  25126. // deeply ugly to write APIs this way, but that still doesn't mean
  25127. // that the Readable class should behave improperly, as streams are
  25128. // designed to be sync/async agnostic.
  25129. // Take note if the _read call is sync or async (ie, if the read call
  25130. // has returned yet), so that we know whether or not it's safe to emit
  25131. // 'readable' etc.
  25132. //
  25133. // 3. Actually pull the requested chunks out of the buffer and return.
  25134. // if we need a readable event, then we need to do some reading.
  25135. var doRead = state.needReadable;
  25136. // if we currently have less than the highWaterMark, then also read some
  25137. if (state.length - n <= state.highWaterMark)
  25138. doRead = true;
  25139. // however, if we've ended, then there's no point, and if we're already
  25140. // reading, then it's unnecessary.
  25141. if (state.ended || state.reading)
  25142. doRead = false;
  25143. if (doRead) {
  25144. state.reading = true;
  25145. state.sync = true;
  25146. // if the length is currently zero, then we *need* a readable event.
  25147. if (state.length === 0)
  25148. state.needReadable = true;
  25149. // call internal read method
  25150. this._read(state.highWaterMark);
  25151. state.sync = false;
  25152. }
  25153. // If _read called its callback synchronously, then `reading`
  25154. // will be false, and we need to re-evaluate how much data we
  25155. // can return to the user.
  25156. if (doRead && !state.reading)
  25157. n = howMuchToRead(nOrig, state);
  25158. var ret;
  25159. if (n > 0)
  25160. ret = fromList(n, state);
  25161. else
  25162. ret = null;
  25163. if (ret === null) {
  25164. state.needReadable = true;
  25165. n = 0;
  25166. }
  25167. state.length -= n;
  25168. // If we have nothing in the buffer, then we want to know
  25169. // as soon as we *do* get something into the buffer.
  25170. if (state.length === 0 && !state.ended)
  25171. state.needReadable = true;
  25172. // If we happened to read() exactly the remaining amount in the
  25173. // buffer, and the EOF has been seen at this point, then make sure
  25174. // that we emit 'end' on the very next tick.
  25175. if (state.ended && !state.endEmitted && state.length === 0)
  25176. endReadable(this);
  25177. return ret;
  25178. };
  25179. function chunkInvalid(state, chunk) {
  25180. var er = null;
  25181. if (!Buffer.isBuffer(chunk) &&
  25182. 'string' !== typeof chunk &&
  25183. chunk !== null &&
  25184. chunk !== undefined &&
  25185. !state.objectMode &&
  25186. !er) {
  25187. er = new TypeError('Invalid non-string/buffer chunk');
  25188. }
  25189. return er;
  25190. }
  25191. function onEofChunk(stream, state) {
  25192. if (state.decoder && !state.ended) {
  25193. var chunk = state.decoder.end();
  25194. if (chunk && chunk.length) {
  25195. state.buffer.push(chunk);
  25196. state.length += state.objectMode ? 1 : chunk.length;
  25197. }
  25198. }
  25199. state.ended = true;
  25200. // if we've ended and we have some data left, then emit
  25201. // 'readable' now to make sure it gets picked up.
  25202. if (state.length > 0)
  25203. emitReadable(stream);
  25204. else
  25205. endReadable(stream);
  25206. }
  25207. // Don't emit readable right away in sync mode, because this can trigger
  25208. // another read() call => stack overflow. This way, it might trigger
  25209. // a nextTick recursion warning, but that's not so bad.
  25210. function emitReadable(stream) {
  25211. var state = stream._readableState;
  25212. state.needReadable = false;
  25213. if (state.emittedReadable)
  25214. return;
  25215. state.emittedReadable = true;
  25216. if (state.sync)
  25217. setImmediate(function() {
  25218. emitReadable_(stream);
  25219. });
  25220. else
  25221. emitReadable_(stream);
  25222. }
  25223. function emitReadable_(stream) {
  25224. stream.emit('readable');
  25225. }
  25226. // at this point, the user has presumably seen the 'readable' event,
  25227. // and called read() to consume some data. that may have triggered
  25228. // in turn another _read(n) call, in which case reading = true if
  25229. // it's in progress.
  25230. // However, if we're not ended, or reading, and the length < hwm,
  25231. // then go ahead and try to read some more preemptively.
  25232. function maybeReadMore(stream, state) {
  25233. if (!state.readingMore) {
  25234. state.readingMore = true;
  25235. setImmediate(function() {
  25236. maybeReadMore_(stream, state);
  25237. });
  25238. }
  25239. }
  25240. function maybeReadMore_(stream, state) {
  25241. var len = state.length;
  25242. while (!state.reading && !state.flowing && !state.ended &&
  25243. state.length < state.highWaterMark) {
  25244. stream.read(0);
  25245. if (len === state.length)
  25246. // didn't get any data, stop spinning.
  25247. break;
  25248. else
  25249. len = state.length;
  25250. }
  25251. state.readingMore = false;
  25252. }
  25253. // abstract method. to be overridden in specific implementation classes.
  25254. // call cb(er, data) where data is <= n in length.
  25255. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  25256. // arbitrary, and perhaps not very meaningful.
  25257. Readable.prototype._read = function(n) {
  25258. this.emit('error', new Error('not implemented'));
  25259. };
  25260. Readable.prototype.pipe = function(dest, pipeOpts) {
  25261. var src = this;
  25262. var state = this._readableState;
  25263. switch (state.pipesCount) {
  25264. case 0:
  25265. state.pipes = dest;
  25266. break;
  25267. case 1:
  25268. state.pipes = [state.pipes, dest];
  25269. break;
  25270. default:
  25271. state.pipes.push(dest);
  25272. break;
  25273. }
  25274. state.pipesCount += 1;
  25275. var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
  25276. dest !== process.stdout &&
  25277. dest !== process.stderr;
  25278. var endFn = doEnd ? onend : cleanup;
  25279. if (state.endEmitted)
  25280. setImmediate(endFn);
  25281. else
  25282. src.once('end', endFn);
  25283. dest.on('unpipe', onunpipe);
  25284. function onunpipe(readable) {
  25285. if (readable !== src) return;
  25286. cleanup();
  25287. }
  25288. function onend() {
  25289. dest.end();
  25290. }
  25291. // when the dest drains, it reduces the awaitDrain counter
  25292. // on the source. This would be more elegant with a .once()
  25293. // handler in flow(), but adding and removing repeatedly is
  25294. // too slow.
  25295. var ondrain = pipeOnDrain(src);
  25296. dest.on('drain', ondrain);
  25297. function cleanup() {
  25298. // cleanup event handlers once the pipe is broken
  25299. dest.removeListener('close', onclose);
  25300. dest.removeListener('finish', onfinish);
  25301. dest.removeListener('drain', ondrain);
  25302. dest.removeListener('error', onerror);
  25303. dest.removeListener('unpipe', onunpipe);
  25304. src.removeListener('end', onend);
  25305. src.removeListener('end', cleanup);
  25306. // if the reader is waiting for a drain event from this
  25307. // specific writer, then it would cause it to never start
  25308. // flowing again.
  25309. // So, if this is awaiting a drain, then we just call it now.
  25310. // If we don't know, then assume that we are waiting for one.
  25311. if (!dest._writableState || dest._writableState.needDrain)
  25312. ondrain();
  25313. }
  25314. // if the dest has an error, then stop piping into it.
  25315. // however, don't suppress the throwing behavior for this.
  25316. // check for listeners before emit removes one-time listeners.
  25317. var errListeners = EE.listenerCount(dest, 'error');
  25318. function onerror(er) {
  25319. unpipe();
  25320. if (errListeners === 0 && EE.listenerCount(dest, 'error') === 0)
  25321. dest.emit('error', er);
  25322. }
  25323. dest.once('error', onerror);
  25324. // Both close and finish should trigger unpipe, but only once.
  25325. function onclose() {
  25326. dest.removeListener('finish', onfinish);
  25327. unpipe();
  25328. }
  25329. dest.once('close', onclose);
  25330. function onfinish() {
  25331. dest.removeListener('close', onclose);
  25332. unpipe();
  25333. }
  25334. dest.once('finish', onfinish);
  25335. function unpipe() {
  25336. src.unpipe(dest);
  25337. }
  25338. // tell the dest that it's being piped to
  25339. dest.emit('pipe', src);
  25340. // start the flow if it hasn't been started already.
  25341. if (!state.flowing) {
  25342. // the handler that waits for readable events after all
  25343. // the data gets sucked out in flow.
  25344. // This would be easier to follow with a .once() handler
  25345. // in flow(), but that is too slow.
  25346. this.on('readable', pipeOnReadable);
  25347. state.flowing = true;
  25348. setImmediate(function() {
  25349. flow(src);
  25350. });
  25351. }
  25352. return dest;
  25353. };
  25354. function pipeOnDrain(src) {
  25355. return function() {
  25356. var dest = this;
  25357. var state = src._readableState;
  25358. state.awaitDrain--;
  25359. if (state.awaitDrain === 0)
  25360. flow(src);
  25361. };
  25362. }
  25363. function flow(src) {
  25364. var state = src._readableState;
  25365. var chunk;
  25366. state.awaitDrain = 0;
  25367. function write(dest, i, list) {
  25368. var written = dest.write(chunk);
  25369. if (false === written) {
  25370. state.awaitDrain++;
  25371. }
  25372. }
  25373. while (state.pipesCount && null !== (chunk = src.read())) {
  25374. if (state.pipesCount === 1)
  25375. write(state.pipes, 0, null);
  25376. else
  25377. forEach(state.pipes, write);
  25378. src.emit('data', chunk);
  25379. // if anyone needs a drain, then we have to wait for that.
  25380. if (state.awaitDrain > 0)
  25381. return;
  25382. }
  25383. // if every destination was unpiped, either before entering this
  25384. // function, or in the while loop, then stop flowing.
  25385. //
  25386. // NB: This is a pretty rare edge case.
  25387. if (state.pipesCount === 0) {
  25388. state.flowing = false;
  25389. // if there were data event listeners added, then switch to old mode.
  25390. if (EE.listenerCount(src, 'data') > 0)
  25391. emitDataEvents(src);
  25392. return;
  25393. }
  25394. // at this point, no one needed a drain, so we just ran out of data
  25395. // on the next readable event, start it over again.
  25396. state.ranOut = true;
  25397. }
  25398. function pipeOnReadable() {
  25399. if (this._readableState.ranOut) {
  25400. this._readableState.ranOut = false;
  25401. flow(this);
  25402. }
  25403. }
  25404. Readable.prototype.unpipe = function(dest) {
  25405. var state = this._readableState;
  25406. // if we're not piping anywhere, then do nothing.
  25407. if (state.pipesCount === 0)
  25408. return this;
  25409. // just one destination. most common case.
  25410. if (state.pipesCount === 1) {
  25411. // passed in one, but it's not the right one.
  25412. if (dest && dest !== state.pipes)
  25413. return this;
  25414. if (!dest)
  25415. dest = state.pipes;
  25416. // got a match.
  25417. state.pipes = null;
  25418. state.pipesCount = 0;
  25419. this.removeListener('readable', pipeOnReadable);
  25420. state.flowing = false;
  25421. if (dest)
  25422. dest.emit('unpipe', this);
  25423. return this;
  25424. }
  25425. // slow case. multiple pipe destinations.
  25426. if (!dest) {
  25427. // remove all.
  25428. var dests = state.pipes;
  25429. var len = state.pipesCount;
  25430. state.pipes = null;
  25431. state.pipesCount = 0;
  25432. this.removeListener('readable', pipeOnReadable);
  25433. state.flowing = false;
  25434. for (var i = 0; i < len; i++)
  25435. dests[i].emit('unpipe', this);
  25436. return this;
  25437. }
  25438. // try to find the right one.
  25439. var i = indexOf(state.pipes, dest);
  25440. if (i === -1)
  25441. return this;
  25442. state.pipes.splice(i, 1);
  25443. state.pipesCount -= 1;
  25444. if (state.pipesCount === 1)
  25445. state.pipes = state.pipes[0];
  25446. dest.emit('unpipe', this);
  25447. return this;
  25448. };
  25449. // set up data events if they are asked for
  25450. // Ensure readable listeners eventually get something
  25451. Readable.prototype.on = function(ev, fn) {
  25452. var res = Stream.prototype.on.call(this, ev, fn);
  25453. if (ev === 'data' && !this._readableState.flowing)
  25454. emitDataEvents(this);
  25455. if (ev === 'readable' && this.readable) {
  25456. var state = this._readableState;
  25457. if (!state.readableListening) {
  25458. state.readableListening = true;
  25459. state.emittedReadable = false;
  25460. state.needReadable = true;
  25461. if (!state.reading) {
  25462. this.read(0);
  25463. } else if (state.length) {
  25464. emitReadable(this, state);
  25465. }
  25466. }
  25467. }
  25468. return res;
  25469. };
  25470. Readable.prototype.addListener = Readable.prototype.on;
  25471. // pause() and resume() are remnants of the legacy readable stream API
  25472. // If the user uses them, then switch into old mode.
  25473. Readable.prototype.resume = function() {
  25474. emitDataEvents(this);
  25475. this.read(0);
  25476. this.emit('resume');
  25477. };
  25478. Readable.prototype.pause = function() {
  25479. emitDataEvents(this, true);
  25480. this.emit('pause');
  25481. };
  25482. function emitDataEvents(stream, startPaused) {
  25483. var state = stream._readableState;
  25484. if (state.flowing) {
  25485. // https://github.com/isaacs/readable-stream/issues/16
  25486. throw new Error('Cannot switch to old mode now.');
  25487. }
  25488. var paused = startPaused || false;
  25489. var readable = false;
  25490. // convert to an old-style stream.
  25491. stream.readable = true;
  25492. stream.pipe = Stream.prototype.pipe;
  25493. stream.on = stream.addListener = Stream.prototype.on;
  25494. stream.on('readable', function() {
  25495. readable = true;
  25496. var c;
  25497. while (!paused && (null !== (c = stream.read())))
  25498. stream.emit('data', c);
  25499. if (c === null) {
  25500. readable = false;
  25501. stream._readableState.needReadable = true;
  25502. }
  25503. });
  25504. stream.pause = function() {
  25505. paused = true;
  25506. this.emit('pause');
  25507. };
  25508. stream.resume = function() {
  25509. paused = false;
  25510. if (readable)
  25511. setImmediate(function() {
  25512. stream.emit('readable');
  25513. });
  25514. else
  25515. this.read(0);
  25516. this.emit('resume');
  25517. };
  25518. // now make it start, just in case it hadn't already.
  25519. stream.emit('readable');
  25520. }
  25521. // wrap an old-style stream as the async data source.
  25522. // This is *not* part of the readable stream interface.
  25523. // It is an ugly unfortunate mess of history.
  25524. Readable.prototype.wrap = function(stream) {
  25525. var state = this._readableState;
  25526. var paused = false;
  25527. var self = this;
  25528. stream.on('end', function() {
  25529. if (state.decoder && !state.ended) {
  25530. var chunk = state.decoder.end();
  25531. if (chunk && chunk.length)
  25532. self.push(chunk);
  25533. }
  25534. self.push(null);
  25535. });
  25536. stream.on('data', function(chunk) {
  25537. if (state.decoder)
  25538. chunk = state.decoder.write(chunk);
  25539. if (!chunk || !state.objectMode && !chunk.length)
  25540. return;
  25541. var ret = self.push(chunk);
  25542. if (!ret) {
  25543. paused = true;
  25544. stream.pause();
  25545. }
  25546. });
  25547. // proxy all the other methods.
  25548. // important when wrapping filters and duplexes.
  25549. for (var i in stream) {
  25550. if (typeof stream[i] === 'function' &&
  25551. typeof this[i] === 'undefined') {
  25552. this[i] = function(method) { return function() {
  25553. return stream[method].apply(stream, arguments);
  25554. }}(i);
  25555. }
  25556. }
  25557. // proxy certain important events.
  25558. var events = ['error', 'close', 'destroy', 'pause', 'resume'];
  25559. forEach(events, function(ev) {
  25560. stream.on(ev, function (x) {
  25561. return self.emit.apply(self, ev, x);
  25562. });
  25563. });
  25564. // when we try to consume some more bytes, simply unpause the
  25565. // underlying stream.
  25566. self._read = function(n) {
  25567. if (paused) {
  25568. paused = false;
  25569. stream.resume();
  25570. }
  25571. };
  25572. return self;
  25573. };
  25574. // exposed for testing purposes only.
  25575. Readable._fromList = fromList;
  25576. // Pluck off n bytes from an array of buffers.
  25577. // Length is the combined lengths of all the buffers in the list.
  25578. function fromList(n, state) {
  25579. var list = state.buffer;
  25580. var length = state.length;
  25581. var stringMode = !!state.decoder;
  25582. var objectMode = !!state.objectMode;
  25583. var ret;
  25584. // nothing in the list, definitely empty.
  25585. if (list.length === 0)
  25586. return null;
  25587. if (length === 0)
  25588. ret = null;
  25589. else if (objectMode)
  25590. ret = list.shift();
  25591. else if (!n || n >= length) {
  25592. // read it all, truncate the array.
  25593. if (stringMode)
  25594. ret = list.join('');
  25595. else
  25596. ret = Buffer.concat(list, length);
  25597. list.length = 0;
  25598. } else {
  25599. // read just some of it.
  25600. if (n < list[0].length) {
  25601. // just take a part of the first list item.
  25602. // slice is the same for buffers and strings.
  25603. var buf = list[0];
  25604. ret = buf.slice(0, n);
  25605. list[0] = buf.slice(n);
  25606. } else if (n === list[0].length) {
  25607. // first list is a perfect match
  25608. ret = list.shift();
  25609. } else {
  25610. // complex case.
  25611. // we have enough to cover it, but it spans past the first buffer.
  25612. if (stringMode)
  25613. ret = '';
  25614. else
  25615. ret = new Buffer(n);
  25616. var c = 0;
  25617. for (var i = 0, l = list.length; i < l && c < n; i++) {
  25618. var buf = list[0];
  25619. var cpy = Math.min(n - c, buf.length);
  25620. if (stringMode)
  25621. ret += buf.slice(0, cpy);
  25622. else
  25623. buf.copy(ret, c, 0, cpy);
  25624. if (cpy < buf.length)
  25625. list[0] = buf.slice(cpy);
  25626. else
  25627. list.shift();
  25628. c += cpy;
  25629. }
  25630. }
  25631. }
  25632. return ret;
  25633. }
  25634. function endReadable(stream) {
  25635. var state = stream._readableState;
  25636. // If we get here before consuming all the bytes, then that is a
  25637. // bug in node. Should never happen.
  25638. if (state.length > 0)
  25639. throw new Error('endReadable called on non-empty stream');
  25640. if (!state.endEmitted && state.calledRead) {
  25641. state.ended = true;
  25642. setImmediate(function() {
  25643. // Check that we didn't get one last unshift.
  25644. if (!state.endEmitted && state.length === 0) {
  25645. state.endEmitted = true;
  25646. stream.readable = false;
  25647. stream.emit('end');
  25648. }
  25649. });
  25650. }
  25651. }
  25652. function forEach (xs, f) {
  25653. for (var i = 0, l = xs.length; i < l; i++) {
  25654. f(xs[i], i);
  25655. }
  25656. }
  25657. function indexOf (xs, x) {
  25658. for (var i = 0, l = xs.length; i < l; i++) {
  25659. if (xs[i] === x) return i;
  25660. }
  25661. return -1;
  25662. }
  25663. }).call(this,_dereq_("C:\\Users\\Alex\\AppData\\Roaming\\npm\\node_modules\\browserify\\node_modules\\insert-module-globals\\node_modules\\process\\browser.js"))
  25664. },{"./index.js":150,"C:\\Users\\Alex\\AppData\\Roaming\\npm\\node_modules\\browserify\\node_modules\\insert-module-globals\\node_modules\\process\\browser.js":144,"buffer":128,"events":137,"inherits":143,"process/browser.js":151,"string_decoder":156}],154:[function(_dereq_,module,exports){
  25665. // Copyright Joyent, Inc. and other Node contributors.
  25666. //
  25667. // Permission is hereby granted, free of charge, to any person obtaining a
  25668. // copy of this software and associated documentation files (the
  25669. // "Software"), to deal in the Software without restriction, including
  25670. // without limitation the rights to use, copy, modify, merge, publish,
  25671. // distribute, sublicense, and/or sell copies of the Software, and to permit
  25672. // persons to whom the Software is furnished to do so, subject to the
  25673. // following conditions:
  25674. //
  25675. // The above copyright notice and this permission notice shall be included
  25676. // in all copies or substantial portions of the Software.
  25677. //
  25678. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  25679. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25680. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  25681. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  25682. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  25683. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  25684. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  25685. // a transform stream is a readable/writable stream where you do
  25686. // something with the data. Sometimes it's called a "filter",
  25687. // but that's not a great name for it, since that implies a thing where
  25688. // some bits pass through, and others are simply ignored. (That would
  25689. // be a valid example of a transform, of course.)
  25690. //
  25691. // While the output is causally related to the input, it's not a
  25692. // necessarily symmetric or synchronous transformation. For example,
  25693. // a zlib stream might take multiple plain-text writes(), and then
  25694. // emit a single compressed chunk some time in the future.
  25695. //
  25696. // Here's how this works:
  25697. //
  25698. // The Transform stream has all the aspects of the readable and writable
  25699. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  25700. // internally, and returns false if there's a lot of pending writes
  25701. // buffered up. When you call read(), that calls _read(n) until
  25702. // there's enough pending readable data buffered up.
  25703. //
  25704. // In a transform stream, the written data is placed in a buffer. When
  25705. // _read(n) is called, it transforms the queued up data, calling the
  25706. // buffered _write cb's as it consumes chunks. If consuming a single
  25707. // written chunk would result in multiple output chunks, then the first
  25708. // outputted bit calls the readcb, and subsequent chunks just go into
  25709. // the read buffer, and will cause it to emit 'readable' if necessary.
  25710. //
  25711. // This way, back-pressure is actually determined by the reading side,
  25712. // since _read has to be called to start processing a new chunk. However,
  25713. // a pathological inflate type of transform can cause excessive buffering
  25714. // here. For example, imagine a stream where every byte of input is
  25715. // interpreted as an integer from 0-255, and then results in that many
  25716. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  25717. // 1kb of data being output. In this case, you could write a very small
  25718. // amount of input, and end up with a very large amount of output. In
  25719. // such a pathological inflating mechanism, there'd be no way to tell
  25720. // the system to stop doing the transform. A single 4MB write could
  25721. // cause the system to run out of memory.
  25722. //
  25723. // However, even in such a pathological case, only a single written chunk
  25724. // would be consumed, and then the rest would wait (un-transformed) until
  25725. // the results of the previous transformed chunk were consumed.
  25726. module.exports = Transform;
  25727. var Duplex = _dereq_('./duplex.js');
  25728. var inherits = _dereq_('inherits');
  25729. inherits(Transform, Duplex);
  25730. function TransformState(options, stream) {
  25731. this.afterTransform = function(er, data) {
  25732. return afterTransform(stream, er, data);
  25733. };
  25734. this.needTransform = false;
  25735. this.transforming = false;
  25736. this.writecb = null;
  25737. this.writechunk = null;
  25738. }
  25739. function afterTransform(stream, er, data) {
  25740. var ts = stream._transformState;
  25741. ts.transforming = false;
  25742. var cb = ts.writecb;
  25743. if (!cb)
  25744. return stream.emit('error', new Error('no writecb in Transform class'));
  25745. ts.writechunk = null;
  25746. ts.writecb = null;
  25747. if (data !== null && data !== undefined)
  25748. stream.push(data);
  25749. if (cb)
  25750. cb(er);
  25751. var rs = stream._readableState;
  25752. rs.reading = false;
  25753. if (rs.needReadable || rs.length < rs.highWaterMark) {
  25754. stream._read(rs.highWaterMark);
  25755. }
  25756. }
  25757. function Transform(options) {
  25758. if (!(this instanceof Transform))
  25759. return new Transform(options);
  25760. Duplex.call(this, options);
  25761. var ts = this._transformState = new TransformState(options, this);
  25762. // when the writable side finishes, then flush out anything remaining.
  25763. var stream = this;
  25764. // start out asking for a readable event once data is transformed.
  25765. this._readableState.needReadable = true;
  25766. // we have implemented the _read method, and done the other things
  25767. // that Readable wants before the first _read call, so unset the
  25768. // sync guard flag.
  25769. this._readableState.sync = false;
  25770. this.once('finish', function() {
  25771. if ('function' === typeof this._flush)
  25772. this._flush(function(er) {
  25773. done(stream, er);
  25774. });
  25775. else
  25776. done(stream);
  25777. });
  25778. }
  25779. Transform.prototype.push = function(chunk, encoding) {
  25780. this._transformState.needTransform = false;
  25781. return Duplex.prototype.push.call(this, chunk, encoding);
  25782. };
  25783. // This is the part where you do stuff!
  25784. // override this function in implementation classes.
  25785. // 'chunk' is an input chunk.
  25786. //
  25787. // Call `push(newChunk)` to pass along transformed output
  25788. // to the readable side. You may call 'push' zero or more times.
  25789. //
  25790. // Call `cb(err)` when you are done with this chunk. If you pass
  25791. // an error, then that'll put the hurt on the whole operation. If you
  25792. // never call cb(), then you'll never get another chunk.
  25793. Transform.prototype._transform = function(chunk, encoding, cb) {
  25794. throw new Error('not implemented');
  25795. };
  25796. Transform.prototype._write = function(chunk, encoding, cb) {
  25797. var ts = this._transformState;
  25798. ts.writecb = cb;
  25799. ts.writechunk = chunk;
  25800. ts.writeencoding = encoding;
  25801. if (!ts.transforming) {
  25802. var rs = this._readableState;
  25803. if (ts.needTransform ||
  25804. rs.needReadable ||
  25805. rs.length < rs.highWaterMark)
  25806. this._read(rs.highWaterMark);
  25807. }
  25808. };
  25809. // Doesn't matter what the args are here.
  25810. // _transform does all the work.
  25811. // That we got here means that the readable side wants more data.
  25812. Transform.prototype._read = function(n) {
  25813. var ts = this._transformState;
  25814. if (ts.writechunk && ts.writecb && !ts.transforming) {
  25815. ts.transforming = true;
  25816. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  25817. } else {
  25818. // mark that we need a transform, so that any data that comes in
  25819. // will get processed, now that we've asked for it.
  25820. ts.needTransform = true;
  25821. }
  25822. };
  25823. function done(stream, er) {
  25824. if (er)
  25825. return stream.emit('error', er);
  25826. // if there's nothing in the write buffer, then that means
  25827. // that nothing more will ever be provided
  25828. var ws = stream._writableState;
  25829. var rs = stream._readableState;
  25830. var ts = stream._transformState;
  25831. if (ws.length)
  25832. throw new Error('calling transform done when ws.length != 0');
  25833. if (ts.transforming)
  25834. throw new Error('calling transform done when still transforming');
  25835. return stream.push(null);
  25836. }
  25837. },{"./duplex.js":149,"inherits":143}],155:[function(_dereq_,module,exports){
  25838. // Copyright Joyent, Inc. and other Node contributors.
  25839. //
  25840. // Permission is hereby granted, free of charge, to any person obtaining a
  25841. // copy of this software and associated documentation files (the
  25842. // "Software"), to deal in the Software without restriction, including
  25843. // without limitation the rights to use, copy, modify, merge, publish,
  25844. // distribute, sublicense, and/or sell copies of the Software, and to permit
  25845. // persons to whom the Software is furnished to do so, subject to the
  25846. // following conditions:
  25847. //
  25848. // The above copyright notice and this permission notice shall be included
  25849. // in all copies or substantial portions of the Software.
  25850. //
  25851. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  25852. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25853. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  25854. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  25855. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  25856. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  25857. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  25858. // A bit simpler than readable streams.
  25859. // Implement an async ._write(chunk, cb), and it'll handle all
  25860. // the drain event emission and buffering.
  25861. module.exports = Writable;
  25862. Writable.WritableState = WritableState;
  25863. var isUint8Array = typeof Uint8Array !== 'undefined'
  25864. ? function (x) { return x instanceof Uint8Array }
  25865. : function (x) {
  25866. return x && x.constructor && x.constructor.name === 'Uint8Array'
  25867. }
  25868. ;
  25869. var isArrayBuffer = typeof ArrayBuffer !== 'undefined'
  25870. ? function (x) { return x instanceof ArrayBuffer }
  25871. : function (x) {
  25872. return x && x.constructor && x.constructor.name === 'ArrayBuffer'
  25873. }
  25874. ;
  25875. var inherits = _dereq_('inherits');
  25876. var Stream = _dereq_('./index.js');
  25877. var setImmediate = _dereq_('process/browser.js').nextTick;
  25878. var Buffer = _dereq_('buffer').Buffer;
  25879. inherits(Writable, Stream);
  25880. function WriteReq(chunk, encoding, cb) {
  25881. this.chunk = chunk;
  25882. this.encoding = encoding;
  25883. this.callback = cb;
  25884. }
  25885. function WritableState(options, stream) {
  25886. options = options || {};
  25887. // the point at which write() starts returning false
  25888. // Note: 0 is a valid value, means that we always return false if
  25889. // the entire buffer is not flushed immediately on write()
  25890. var hwm = options.highWaterMark;
  25891. this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
  25892. // object stream flag to indicate whether or not this stream
  25893. // contains buffers or objects.
  25894. this.objectMode = !!options.objectMode;
  25895. // cast to ints.
  25896. this.highWaterMark = ~~this.highWaterMark;
  25897. this.needDrain = false;
  25898. // at the start of calling end()
  25899. this.ending = false;
  25900. // when end() has been called, and returned
  25901. this.ended = false;
  25902. // when 'finish' is emitted
  25903. this.finished = false;
  25904. // should we decode strings into buffers before passing to _write?
  25905. // this is here so that some node-core streams can optimize string
  25906. // handling at a lower level.
  25907. var noDecode = options.decodeStrings === false;
  25908. this.decodeStrings = !noDecode;
  25909. // Crypto is kind of old and crusty. Historically, its default string
  25910. // encoding is 'binary' so we have to make this configurable.
  25911. // Everything else in the universe uses 'utf8', though.
  25912. this.defaultEncoding = options.defaultEncoding || 'utf8';
  25913. // not an actual buffer we keep track of, but a measurement
  25914. // of how much we're waiting to get pushed to some underlying
  25915. // socket or file.
  25916. this.length = 0;
  25917. // a flag to see when we're in the middle of a write.
  25918. this.writing = false;
  25919. // a flag to be able to tell if the onwrite cb is called immediately,
  25920. // or on a later tick. We set this to true at first, becuase any
  25921. // actions that shouldn't happen until "later" should generally also
  25922. // not happen before the first write call.
  25923. this.sync = true;
  25924. // a flag to know if we're processing previously buffered items, which
  25925. // may call the _write() callback in the same tick, so that we don't
  25926. // end up in an overlapped onwrite situation.
  25927. this.bufferProcessing = false;
  25928. // the callback that's passed to _write(chunk,cb)
  25929. this.onwrite = function(er) {
  25930. onwrite(stream, er);
  25931. };
  25932. // the callback that the user supplies to write(chunk,encoding,cb)
  25933. this.writecb = null;
  25934. // the amount that is being written when _write is called.
  25935. this.writelen = 0;
  25936. this.buffer = [];
  25937. }
  25938. function Writable(options) {
  25939. // Writable ctor is applied to Duplexes, though they're not
  25940. // instanceof Writable, they're instanceof Readable.
  25941. if (!(this instanceof Writable) && !(this instanceof Stream.Duplex))
  25942. return new Writable(options);
  25943. this._writableState = new WritableState(options, this);
  25944. // legacy.
  25945. this.writable = true;
  25946. Stream.call(this);
  25947. }
  25948. // Otherwise people can pipe Writable streams, which is just wrong.
  25949. Writable.prototype.pipe = function() {
  25950. this.emit('error', new Error('Cannot pipe. Not readable.'));
  25951. };
  25952. function writeAfterEnd(stream, state, cb) {
  25953. var er = new Error('write after end');
  25954. // TODO: defer error events consistently everywhere, not just the cb
  25955. stream.emit('error', er);
  25956. setImmediate(function() {
  25957. cb(er);
  25958. });
  25959. }
  25960. // If we get something that is not a buffer, string, null, or undefined,
  25961. // and we're not in objectMode, then that's an error.
  25962. // Otherwise stream chunks are all considered to be of length=1, and the
  25963. // watermarks determine how many objects to keep in the buffer, rather than
  25964. // how many bytes or characters.
  25965. function validChunk(stream, state, chunk, cb) {
  25966. var valid = true;
  25967. if (!Buffer.isBuffer(chunk) &&
  25968. 'string' !== typeof chunk &&
  25969. chunk !== null &&
  25970. chunk !== undefined &&
  25971. !state.objectMode) {
  25972. var er = new TypeError('Invalid non-string/buffer chunk');
  25973. stream.emit('error', er);
  25974. setImmediate(function() {
  25975. cb(er);
  25976. });
  25977. valid = false;
  25978. }
  25979. return valid;
  25980. }
  25981. Writable.prototype.write = function(chunk, encoding, cb) {
  25982. var state = this._writableState;
  25983. var ret = false;
  25984. if (typeof encoding === 'function') {
  25985. cb = encoding;
  25986. encoding = null;
  25987. }
  25988. if (!Buffer.isBuffer(chunk) && isUint8Array(chunk))
  25989. chunk = new Buffer(chunk);
  25990. if (isArrayBuffer(chunk) && typeof Uint8Array !== 'undefined')
  25991. chunk = new Buffer(new Uint8Array(chunk));
  25992. if (Buffer.isBuffer(chunk))
  25993. encoding = 'buffer';
  25994. else if (!encoding)
  25995. encoding = state.defaultEncoding;
  25996. if (typeof cb !== 'function')
  25997. cb = function() {};
  25998. if (state.ended)
  25999. writeAfterEnd(this, state, cb);
  26000. else if (validChunk(this, state, chunk, cb))
  26001. ret = writeOrBuffer(this, state, chunk, encoding, cb);
  26002. return ret;
  26003. };
  26004. function decodeChunk(state, chunk, encoding) {
  26005. if (!state.objectMode &&
  26006. state.decodeStrings !== false &&
  26007. typeof chunk === 'string') {
  26008. chunk = new Buffer(chunk, encoding);
  26009. }
  26010. return chunk;
  26011. }
  26012. // if we're already writing something, then just put this
  26013. // in the queue, and wait our turn. Otherwise, call _write
  26014. // If we return false, then we need a drain event, so set that flag.
  26015. function writeOrBuffer(stream, state, chunk, encoding, cb) {
  26016. chunk = decodeChunk(state, chunk, encoding);
  26017. var len = state.objectMode ? 1 : chunk.length;
  26018. state.length += len;
  26019. var ret = state.length < state.highWaterMark;
  26020. state.needDrain = !ret;
  26021. if (state.writing)
  26022. state.buffer.push(new WriteReq(chunk, encoding, cb));
  26023. else
  26024. doWrite(stream, state, len, chunk, encoding, cb);
  26025. return ret;
  26026. }
  26027. function doWrite(stream, state, len, chunk, encoding, cb) {
  26028. state.writelen = len;
  26029. state.writecb = cb;
  26030. state.writing = true;
  26031. state.sync = true;
  26032. stream._write(chunk, encoding, state.onwrite);
  26033. state.sync = false;
  26034. }
  26035. function onwriteError(stream, state, sync, er, cb) {
  26036. if (sync)
  26037. setImmediate(function() {
  26038. cb(er);
  26039. });
  26040. else
  26041. cb(er);
  26042. stream.emit('error', er);
  26043. }
  26044. function onwriteStateUpdate(state) {
  26045. state.writing = false;
  26046. state.writecb = null;
  26047. state.length -= state.writelen;
  26048. state.writelen = 0;
  26049. }
  26050. function onwrite(stream, er) {
  26051. var state = stream._writableState;
  26052. var sync = state.sync;
  26053. var cb = state.writecb;
  26054. onwriteStateUpdate(state);
  26055. if (er)
  26056. onwriteError(stream, state, sync, er, cb);
  26057. else {
  26058. // Check if we're actually ready to finish, but don't emit yet
  26059. var finished = needFinish(stream, state);
  26060. if (!finished && !state.bufferProcessing && state.buffer.length)
  26061. clearBuffer(stream, state);
  26062. if (sync) {
  26063. setImmediate(function() {
  26064. afterWrite(stream, state, finished, cb);
  26065. });
  26066. } else {
  26067. afterWrite(stream, state, finished, cb);
  26068. }
  26069. }
  26070. }
  26071. function afterWrite(stream, state, finished, cb) {
  26072. if (!finished)
  26073. onwriteDrain(stream, state);
  26074. cb();
  26075. if (finished)
  26076. finishMaybe(stream, state);
  26077. }
  26078. // Must force callback to be called on nextTick, so that we don't
  26079. // emit 'drain' before the write() consumer gets the 'false' return
  26080. // value, and has a chance to attach a 'drain' listener.
  26081. function onwriteDrain(stream, state) {
  26082. if (state.length === 0 && state.needDrain) {
  26083. state.needDrain = false;
  26084. stream.emit('drain');
  26085. }
  26086. }
  26087. // if there's something in the buffer waiting, then process it
  26088. function clearBuffer(stream, state) {
  26089. state.bufferProcessing = true;
  26090. for (var c = 0; c < state.buffer.length; c++) {
  26091. var entry = state.buffer[c];
  26092. var chunk = entry.chunk;
  26093. var encoding = entry.encoding;
  26094. var cb = entry.callback;
  26095. var len = state.objectMode ? 1 : chunk.length;
  26096. doWrite(stream, state, len, chunk, encoding, cb);
  26097. // if we didn't call the onwrite immediately, then
  26098. // it means that we need to wait until it does.
  26099. // also, that means that the chunk and cb are currently
  26100. // being processed, so move the buffer counter past them.
  26101. if (state.writing) {
  26102. c++;
  26103. break;
  26104. }
  26105. }
  26106. state.bufferProcessing = false;
  26107. if (c < state.buffer.length)
  26108. state.buffer = state.buffer.slice(c);
  26109. else
  26110. state.buffer.length = 0;
  26111. }
  26112. Writable.prototype._write = function(chunk, encoding, cb) {
  26113. cb(new Error('not implemented'));
  26114. };
  26115. Writable.prototype.end = function(chunk, encoding, cb) {
  26116. var state = this._writableState;
  26117. if (typeof chunk === 'function') {
  26118. cb = chunk;
  26119. chunk = null;
  26120. encoding = null;
  26121. } else if (typeof encoding === 'function') {
  26122. cb = encoding;
  26123. encoding = null;
  26124. }
  26125. if (typeof chunk !== 'undefined' && chunk !== null)
  26126. this.write(chunk, encoding);
  26127. // ignore unnecessary end() calls.
  26128. if (!state.ending && !state.finished)
  26129. endWritable(this, state, cb);
  26130. };
  26131. function needFinish(stream, state) {
  26132. return (state.ending &&
  26133. state.length === 0 &&
  26134. !state.finished &&
  26135. !state.writing);
  26136. }
  26137. function finishMaybe(stream, state) {
  26138. var need = needFinish(stream, state);
  26139. if (need) {
  26140. state.finished = true;
  26141. stream.emit('finish');
  26142. }
  26143. return need;
  26144. }
  26145. function endWritable(stream, state, cb) {
  26146. state.ending = true;
  26147. finishMaybe(stream, state);
  26148. if (cb) {
  26149. if (state.finished)
  26150. setImmediate(cb);
  26151. else
  26152. stream.once('finish', cb);
  26153. }
  26154. state.ended = true;
  26155. }
  26156. },{"./index.js":150,"buffer":128,"inherits":143,"process/browser.js":151}],156:[function(_dereq_,module,exports){
  26157. // Copyright Joyent, Inc. and other Node contributors.
  26158. //
  26159. // Permission is hereby granted, free of charge, to any person obtaining a
  26160. // copy of this software and associated documentation files (the
  26161. // "Software"), to deal in the Software without restriction, including
  26162. // without limitation the rights to use, copy, modify, merge, publish,
  26163. // distribute, sublicense, and/or sell copies of the Software, and to permit
  26164. // persons to whom the Software is furnished to do so, subject to the
  26165. // following conditions:
  26166. //
  26167. // The above copyright notice and this permission notice shall be included
  26168. // in all copies or substantial portions of the Software.
  26169. //
  26170. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  26171. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26172. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  26173. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  26174. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  26175. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  26176. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  26177. var Buffer = _dereq_('buffer').Buffer;
  26178. function assertEncoding(encoding) {
  26179. if (encoding && !Buffer.isEncoding(encoding)) {
  26180. throw new Error('Unknown encoding: ' + encoding);
  26181. }
  26182. }
  26183. var StringDecoder = exports.StringDecoder = function(encoding) {
  26184. this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
  26185. assertEncoding(encoding);
  26186. switch (this.encoding) {
  26187. case 'utf8':
  26188. // CESU-8 represents each of Surrogate Pair by 3-bytes
  26189. this.surrogateSize = 3;
  26190. break;
  26191. case 'ucs2':
  26192. case 'utf16le':
  26193. // UTF-16 represents each of Surrogate Pair by 2-bytes
  26194. this.surrogateSize = 2;
  26195. this.detectIncompleteChar = utf16DetectIncompleteChar;
  26196. break;
  26197. case 'base64':
  26198. // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
  26199. this.surrogateSize = 3;
  26200. this.detectIncompleteChar = base64DetectIncompleteChar;
  26201. break;
  26202. default:
  26203. this.write = passThroughWrite;
  26204. return;
  26205. }
  26206. this.charBuffer = new Buffer(6);
  26207. this.charReceived = 0;
  26208. this.charLength = 0;
  26209. };
  26210. StringDecoder.prototype.write = function(buffer) {
  26211. var charStr = '';
  26212. var offset = 0;
  26213. // if our last write ended with an incomplete multibyte character
  26214. while (this.charLength) {
  26215. // determine how many remaining bytes this buffer has to offer for this char
  26216. var i = (buffer.length >= this.charLength - this.charReceived) ?
  26217. this.charLength - this.charReceived :
  26218. buffer.length;
  26219. // add the new bytes to the char buffer
  26220. buffer.copy(this.charBuffer, this.charReceived, offset, i);
  26221. this.charReceived += (i - offset);
  26222. offset = i;
  26223. if (this.charReceived < this.charLength) {
  26224. // still not enough chars in this buffer? wait for more ...
  26225. return '';
  26226. }
  26227. // get the character that was split
  26228. charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
  26229. // lead surrogate (D800-DBFF) is also the incomplete character
  26230. var charCode = charStr.charCodeAt(charStr.length - 1);
  26231. if (charCode >= 0xD800 && charCode <= 0xDBFF) {
  26232. this.charLength += this.surrogateSize;
  26233. charStr = '';
  26234. continue;
  26235. }
  26236. this.charReceived = this.charLength = 0;
  26237. // if there are no more bytes in this buffer, just emit our char
  26238. if (i == buffer.length) return charStr;
  26239. // otherwise cut off the characters end from the beginning of this buffer
  26240. buffer = buffer.slice(i, buffer.length);
  26241. break;
  26242. }
  26243. var lenIncomplete = this.detectIncompleteChar(buffer);
  26244. var end = buffer.length;
  26245. if (this.charLength) {
  26246. // buffer the incomplete character bytes we got
  26247. buffer.copy(this.charBuffer, 0, buffer.length - lenIncomplete, end);
  26248. this.charReceived = lenIncomplete;
  26249. end -= lenIncomplete;
  26250. }
  26251. charStr += buffer.toString(this.encoding, 0, end);
  26252. var end = charStr.length - 1;
  26253. var charCode = charStr.charCodeAt(end);
  26254. // lead surrogate (D800-DBFF) is also the incomplete character
  26255. if (charCode >= 0xD800 && charCode <= 0xDBFF) {
  26256. var size = this.surrogateSize;
  26257. this.charLength += size;
  26258. this.charReceived += size;
  26259. this.charBuffer.copy(this.charBuffer, size, 0, size);
  26260. this.charBuffer.write(charStr.charAt(charStr.length - 1), this.encoding);
  26261. return charStr.substring(0, end);
  26262. }
  26263. // or just emit the charStr
  26264. return charStr;
  26265. };
  26266. StringDecoder.prototype.detectIncompleteChar = function(buffer) {
  26267. // determine how many bytes we have to check at the end of this buffer
  26268. var i = (buffer.length >= 3) ? 3 : buffer.length;
  26269. // Figure out if one of the last i bytes of our buffer announces an
  26270. // incomplete char.
  26271. for (; i > 0; i--) {
  26272. var c = buffer[buffer.length - i];
  26273. // See http://en.wikipedia.org/wiki/UTF-8#Description
  26274. // 110XXXXX
  26275. if (i == 1 && c >> 5 == 0x06) {
  26276. this.charLength = 2;
  26277. break;
  26278. }
  26279. // 1110XXXX
  26280. if (i <= 2 && c >> 4 == 0x0E) {
  26281. this.charLength = 3;
  26282. break;
  26283. }
  26284. // 11110XXX
  26285. if (i <= 3 && c >> 3 == 0x1E) {
  26286. this.charLength = 4;
  26287. break;
  26288. }
  26289. }
  26290. return i;
  26291. };
  26292. StringDecoder.prototype.end = function(buffer) {
  26293. var res = '';
  26294. if (buffer && buffer.length)
  26295. res = this.write(buffer);
  26296. if (this.charReceived) {
  26297. var cr = this.charReceived;
  26298. var buf = this.charBuffer;
  26299. var enc = this.encoding;
  26300. res += buf.slice(0, cr).toString(enc);
  26301. }
  26302. return res;
  26303. };
  26304. function passThroughWrite(buffer) {
  26305. return buffer.toString(this.encoding);
  26306. }
  26307. function utf16DetectIncompleteChar(buffer) {
  26308. var incomplete = this.charReceived = buffer.length % 2;
  26309. this.charLength = incomplete ? 2 : 0;
  26310. return incomplete;
  26311. }
  26312. function base64DetectIncompleteChar(buffer) {
  26313. var incomplete = this.charReceived = buffer.length % 3;
  26314. this.charLength = incomplete ? 3 : 0;
  26315. return incomplete;
  26316. }
  26317. },{"buffer":128}],157:[function(_dereq_,module,exports){
  26318. // Copyright Joyent, Inc. and other Node contributors.
  26319. //
  26320. // Permission is hereby granted, free of charge, to any person obtaining a
  26321. // copy of this software and associated documentation files (the
  26322. // "Software"), to deal in the Software without restriction, including
  26323. // without limitation the rights to use, copy, modify, merge, publish,
  26324. // distribute, sublicense, and/or sell copies of the Software, and to permit
  26325. // persons to whom the Software is furnished to do so, subject to the
  26326. // following conditions:
  26327. //
  26328. // The above copyright notice and this permission notice shall be included
  26329. // in all copies or substantial portions of the Software.
  26330. //
  26331. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  26332. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26333. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  26334. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  26335. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  26336. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  26337. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  26338. var punycode = _dereq_('punycode');
  26339. exports.parse = urlParse;
  26340. exports.resolve = urlResolve;
  26341. exports.resolveObject = urlResolveObject;
  26342. exports.format = urlFormat;
  26343. exports.Url = Url;
  26344. function Url() {
  26345. this.protocol = null;
  26346. this.slashes = null;
  26347. this.auth = null;
  26348. this.host = null;
  26349. this.port = null;
  26350. this.hostname = null;
  26351. this.hash = null;
  26352. this.search = null;
  26353. this.query = null;
  26354. this.pathname = null;
  26355. this.path = null;
  26356. this.href = null;
  26357. }
  26358. // Reference: RFC 3986, RFC 1808, RFC 2396
  26359. // define these here so at least they only have to be
  26360. // compiled once on the first module load.
  26361. var protocolPattern = /^([a-z0-9.+-]+:)/i,
  26362. portPattern = /:[0-9]*$/,
  26363. // RFC 2396: characters reserved for delimiting URLs.
  26364. // We actually just auto-escape these.
  26365. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
  26366. // RFC 2396: characters not allowed for various reasons.
  26367. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
  26368. // Allowed by RFCs, but cause of XSS attacks. Always escape these.
  26369. autoEscape = ['\''].concat(unwise),
  26370. // Characters that are never ever allowed in a hostname.
  26371. // Note that any invalid chars are also handled, but these
  26372. // are the ones that are *expected* to be seen, so we fast-path
  26373. // them.
  26374. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
  26375. hostEndingChars = ['/', '?', '#'],
  26376. hostnameMaxLen = 255,
  26377. hostnamePartPattern = /^[a-z0-9A-Z_-]{0,63}$/,
  26378. hostnamePartStart = /^([a-z0-9A-Z_-]{0,63})(.*)$/,
  26379. // protocols that can allow "unsafe" and "unwise" chars.
  26380. unsafeProtocol = {
  26381. 'javascript': true,
  26382. 'javascript:': true
  26383. },
  26384. // protocols that never have a hostname.
  26385. hostlessProtocol = {
  26386. 'javascript': true,
  26387. 'javascript:': true
  26388. },
  26389. // protocols that always contain a // bit.
  26390. slashedProtocol = {
  26391. 'http': true,
  26392. 'https': true,
  26393. 'ftp': true,
  26394. 'gopher': true,
  26395. 'file': true,
  26396. 'http:': true,
  26397. 'https:': true,
  26398. 'ftp:': true,
  26399. 'gopher:': true,
  26400. 'file:': true
  26401. },
  26402. querystring = _dereq_('querystring');
  26403. function urlParse(url, parseQueryString, slashesDenoteHost) {
  26404. if (url && isObject(url) && url instanceof Url) return url;
  26405. var u = new Url;
  26406. u.parse(url, parseQueryString, slashesDenoteHost);
  26407. return u;
  26408. }
  26409. Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  26410. if (!isString(url)) {
  26411. throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
  26412. }
  26413. var rest = url;
  26414. // trim before proceeding.
  26415. // This is to support parse stuff like " http://foo.com \n"
  26416. rest = rest.trim();
  26417. var proto = protocolPattern.exec(rest);
  26418. if (proto) {
  26419. proto = proto[0];
  26420. var lowerProto = proto.toLowerCase();
  26421. this.protocol = lowerProto;
  26422. rest = rest.substr(proto.length);
  26423. }
  26424. // figure out if it's got a host
  26425. // user@server is *always* interpreted as a hostname, and url
  26426. // resolution will treat //foo/bar as host=foo,path=bar because that's
  26427. // how the browser resolves relative URLs.
  26428. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
  26429. var slashes = rest.substr(0, 2) === '//';
  26430. if (slashes && !(proto && hostlessProtocol[proto])) {
  26431. rest = rest.substr(2);
  26432. this.slashes = true;
  26433. }
  26434. }
  26435. if (!hostlessProtocol[proto] &&
  26436. (slashes || (proto && !slashedProtocol[proto]))) {
  26437. // there's a hostname.
  26438. // the first instance of /, ?, ;, or # ends the host.
  26439. //
  26440. // If there is an @ in the hostname, then non-host chars *are* allowed
  26441. // to the left of the last @ sign, unless some host-ending character
  26442. // comes *before* the @-sign.
  26443. // URLs are obnoxious.
  26444. //
  26445. // ex:
  26446. // http://a@b@c/ => user:a@b host:c
  26447. // http://a@b?@c => user:a host:c path:/?@c
  26448. // v0.12 TODO(isaacs): This is not quite how Chrome does things.
  26449. // Review our test case against browsers more comprehensively.
  26450. // find the first instance of any hostEndingChars
  26451. var hostEnd = -1;
  26452. for (var i = 0; i < hostEndingChars.length; i++) {
  26453. var hec = rest.indexOf(hostEndingChars[i]);
  26454. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  26455. hostEnd = hec;
  26456. }
  26457. // at this point, either we have an explicit point where the
  26458. // auth portion cannot go past, or the last @ char is the decider.
  26459. var auth, atSign;
  26460. if (hostEnd === -1) {
  26461. // atSign can be anywhere.
  26462. atSign = rest.lastIndexOf('@');
  26463. } else {
  26464. // atSign must be in auth portion.
  26465. // http://a@b/c@d => host:b auth:a path:/c@d
  26466. atSign = rest.lastIndexOf('@', hostEnd);
  26467. }
  26468. // Now we have a portion which is definitely the auth.
  26469. // Pull that off.
  26470. if (atSign !== -1) {
  26471. auth = rest.slice(0, atSign);
  26472. rest = rest.slice(atSign + 1);
  26473. this.auth = decodeURIComponent(auth);
  26474. }
  26475. // the host is the remaining to the left of the first non-host char
  26476. hostEnd = -1;
  26477. for (var i = 0; i < nonHostChars.length; i++) {
  26478. var hec = rest.indexOf(nonHostChars[i]);
  26479. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  26480. hostEnd = hec;
  26481. }
  26482. // if we still have not hit it, then the entire thing is a host.
  26483. if (hostEnd === -1)
  26484. hostEnd = rest.length;
  26485. this.host = rest.slice(0, hostEnd);
  26486. rest = rest.slice(hostEnd);
  26487. // pull out port.
  26488. this.parseHost();
  26489. // we've indicated that there is a hostname,
  26490. // so even if it's empty, it has to be present.
  26491. this.hostname = this.hostname || '';
  26492. // if hostname begins with [ and ends with ]
  26493. // assume that it's an IPv6 address.
  26494. var ipv6Hostname = this.hostname[0] === '[' &&
  26495. this.hostname[this.hostname.length - 1] === ']';
  26496. // validate a little.
  26497. if (!ipv6Hostname) {
  26498. var hostparts = this.hostname.split(/\./);
  26499. for (var i = 0, l = hostparts.length; i < l; i++) {
  26500. var part = hostparts[i];
  26501. if (!part) continue;
  26502. if (!part.match(hostnamePartPattern)) {
  26503. var newpart = '';
  26504. for (var j = 0, k = part.length; j < k; j++) {
  26505. if (part.charCodeAt(j) > 127) {
  26506. // we replace non-ASCII char with a temporary placeholder
  26507. // we need this to make sure size of hostname is not
  26508. // broken by replacing non-ASCII by nothing
  26509. newpart += 'x';
  26510. } else {
  26511. newpart += part[j];
  26512. }
  26513. }
  26514. // we test again with ASCII char only
  26515. if (!newpart.match(hostnamePartPattern)) {
  26516. var validParts = hostparts.slice(0, i);
  26517. var notHost = hostparts.slice(i + 1);
  26518. var bit = part.match(hostnamePartStart);
  26519. if (bit) {
  26520. validParts.push(bit[1]);
  26521. notHost.unshift(bit[2]);
  26522. }
  26523. if (notHost.length) {
  26524. rest = '/' + notHost.join('.') + rest;
  26525. }
  26526. this.hostname = validParts.join('.');
  26527. break;
  26528. }
  26529. }
  26530. }
  26531. }
  26532. if (this.hostname.length > hostnameMaxLen) {
  26533. this.hostname = '';
  26534. } else {
  26535. // hostnames are always lower case.
  26536. this.hostname = this.hostname.toLowerCase();
  26537. }
  26538. if (!ipv6Hostname) {
  26539. // IDNA Support: Returns a puny coded representation of "domain".
  26540. // It only converts the part of the domain name that
  26541. // has non ASCII characters. I.e. it dosent matter if
  26542. // you call it with a domain that already is in ASCII.
  26543. var domainArray = this.hostname.split('.');
  26544. var newOut = [];
  26545. for (var i = 0; i < domainArray.length; ++i) {
  26546. var s = domainArray[i];
  26547. newOut.push(s.match(/[^A-Za-z0-9_-]/) ?
  26548. 'xn--' + punycode.encode(s) : s);
  26549. }
  26550. this.hostname = newOut.join('.');
  26551. }
  26552. var p = this.port ? ':' + this.port : '';
  26553. var h = this.hostname || '';
  26554. this.host = h + p;
  26555. this.href += this.host;
  26556. // strip [ and ] from the hostname
  26557. // the host field still retains them, though
  26558. if (ipv6Hostname) {
  26559. this.hostname = this.hostname.substr(1, this.hostname.length - 2);
  26560. if (rest[0] !== '/') {
  26561. rest = '/' + rest;
  26562. }
  26563. }
  26564. }
  26565. // now rest is set to the post-host stuff.
  26566. // chop off any delim chars.
  26567. if (!unsafeProtocol[lowerProto]) {
  26568. // First, make 100% sure that any "autoEscape" chars get
  26569. // escaped, even if encodeURIComponent doesn't think they
  26570. // need to be.
  26571. for (var i = 0, l = autoEscape.length; i < l; i++) {
  26572. var ae = autoEscape[i];
  26573. var esc = encodeURIComponent(ae);
  26574. if (esc === ae) {
  26575. esc = escape(ae);
  26576. }
  26577. rest = rest.split(ae).join(esc);
  26578. }
  26579. }
  26580. // chop off from the tail first.
  26581. var hash = rest.indexOf('#');
  26582. if (hash !== -1) {
  26583. // got a fragment string.
  26584. this.hash = rest.substr(hash);
  26585. rest = rest.slice(0, hash);
  26586. }
  26587. var qm = rest.indexOf('?');
  26588. if (qm !== -1) {
  26589. this.search = rest.substr(qm);
  26590. this.query = rest.substr(qm + 1);
  26591. if (parseQueryString) {
  26592. this.query = querystring.parse(this.query);
  26593. }
  26594. rest = rest.slice(0, qm);
  26595. } else if (parseQueryString) {
  26596. // no query string, but parseQueryString still requested
  26597. this.search = '';
  26598. this.query = {};
  26599. }
  26600. if (rest) this.pathname = rest;
  26601. if (slashedProtocol[lowerProto] &&
  26602. this.hostname && !this.pathname) {
  26603. this.pathname = '/';
  26604. }
  26605. //to support http.request
  26606. if (this.pathname || this.search) {
  26607. var p = this.pathname || '';
  26608. var s = this.search || '';
  26609. this.path = p + s;
  26610. }
  26611. // finally, reconstruct the href based on what has been validated.
  26612. this.href = this.format();
  26613. return this;
  26614. };
  26615. // format a parsed object into a url string
  26616. function urlFormat(obj) {
  26617. // ensure it's an object, and not a string url.
  26618. // If it's an obj, this is a no-op.
  26619. // this way, you can call url_format() on strings
  26620. // to clean up potentially wonky urls.
  26621. if (isString(obj)) obj = urlParse(obj);
  26622. if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
  26623. return obj.format();
  26624. }
  26625. Url.prototype.format = function() {
  26626. var auth = this.auth || '';
  26627. if (auth) {
  26628. auth = encodeURIComponent(auth);
  26629. auth = auth.replace(/%3A/i, ':');
  26630. auth += '@';
  26631. }
  26632. var protocol = this.protocol || '',
  26633. pathname = this.pathname || '',
  26634. hash = this.hash || '',
  26635. host = false,
  26636. query = '';
  26637. if (this.host) {
  26638. host = auth + this.host;
  26639. } else if (this.hostname) {
  26640. host = auth + (this.hostname.indexOf(':') === -1 ?
  26641. this.hostname :
  26642. '[' + this.hostname + ']');
  26643. if (this.port) {
  26644. host += ':' + this.port;
  26645. }
  26646. }
  26647. if (this.query &&
  26648. isObject(this.query) &&
  26649. Object.keys(this.query).length) {
  26650. query = querystring.stringify(this.query);
  26651. }
  26652. var search = this.search || (query && ('?' + query)) || '';
  26653. if (protocol && protocol.substr(-1) !== ':') protocol += ':';
  26654. // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
  26655. // unless they had them to begin with.
  26656. if (this.slashes ||
  26657. (!protocol || slashedProtocol[protocol]) && host !== false) {
  26658. host = '//' + (host || '');
  26659. if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  26660. } else if (!host) {
  26661. host = '';
  26662. }
  26663. if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  26664. if (search && search.charAt(0) !== '?') search = '?' + search;
  26665. pathname = pathname.replace(/[?#]/g, function(match) {
  26666. return encodeURIComponent(match);
  26667. });
  26668. search = search.replace('#', '%23');
  26669. return protocol + host + pathname + search + hash;
  26670. };
  26671. function urlResolve(source, relative) {
  26672. return urlParse(source, false, true).resolve(relative);
  26673. }
  26674. Url.prototype.resolve = function(relative) {
  26675. return this.resolveObject(urlParse(relative, false, true)).format();
  26676. };
  26677. function urlResolveObject(source, relative) {
  26678. if (!source) return relative;
  26679. return urlParse(source, false, true).resolveObject(relative);
  26680. }
  26681. Url.prototype.resolveObject = function(relative) {
  26682. if (isString(relative)) {
  26683. var rel = new Url();
  26684. rel.parse(relative, false, true);
  26685. relative = rel;
  26686. }
  26687. var result = new Url();
  26688. Object.keys(this).forEach(function(k) {
  26689. result[k] = this[k];
  26690. }, this);
  26691. // hash is always overridden, no matter what.
  26692. // even href="" will remove it.
  26693. result.hash = relative.hash;
  26694. // if the relative url is empty, then there's nothing left to do here.
  26695. if (relative.href === '') {
  26696. result.href = result.format();
  26697. return result;
  26698. }
  26699. // hrefs like //foo/bar always cut to the protocol.
  26700. if (relative.slashes && !relative.protocol) {
  26701. // take everything except the protocol from relative
  26702. Object.keys(relative).forEach(function(k) {
  26703. if (k !== 'protocol')
  26704. result[k] = relative[k];
  26705. });
  26706. //urlParse appends trailing / to urls like http://www.example.com
  26707. if (slashedProtocol[result.protocol] &&
  26708. result.hostname && !result.pathname) {
  26709. result.path = result.pathname = '/';
  26710. }
  26711. result.href = result.format();
  26712. return result;
  26713. }
  26714. if (relative.protocol && relative.protocol !== result.protocol) {
  26715. // if it's a known url protocol, then changing
  26716. // the protocol does weird things
  26717. // first, if it's not file:, then we MUST have a host,
  26718. // and if there was a path
  26719. // to begin with, then we MUST have a path.
  26720. // if it is file:, then the host is dropped,
  26721. // because that's known to be hostless.
  26722. // anything else is assumed to be absolute.
  26723. if (!slashedProtocol[relative.protocol]) {
  26724. Object.keys(relative).forEach(function(k) {
  26725. result[k] = relative[k];
  26726. });
  26727. result.href = result.format();
  26728. return result;
  26729. }
  26730. result.protocol = relative.protocol;
  26731. if (!relative.host && !hostlessProtocol[relative.protocol]) {
  26732. var relPath = (relative.pathname || '').split('/');
  26733. while (relPath.length && !(relative.host = relPath.shift()));
  26734. if (!relative.host) relative.host = '';
  26735. if (!relative.hostname) relative.hostname = '';
  26736. if (relPath[0] !== '') relPath.unshift('');
  26737. if (relPath.length < 2) relPath.unshift('');
  26738. result.pathname = relPath.join('/');
  26739. } else {
  26740. result.pathname = relative.pathname;
  26741. }
  26742. result.search = relative.search;
  26743. result.query = relative.query;
  26744. result.host = relative.host || '';
  26745. result.auth = relative.auth;
  26746. result.hostname = relative.hostname || relative.host;
  26747. result.port = relative.port;
  26748. // to support http.request
  26749. if (result.pathname || result.search) {
  26750. var p = result.pathname || '';
  26751. var s = result.search || '';
  26752. result.path = p + s;
  26753. }
  26754. result.slashes = result.slashes || relative.slashes;
  26755. result.href = result.format();
  26756. return result;
  26757. }
  26758. var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
  26759. isRelAbs = (
  26760. relative.host ||
  26761. relative.pathname && relative.pathname.charAt(0) === '/'
  26762. ),
  26763. mustEndAbs = (isRelAbs || isSourceAbs ||
  26764. (result.host && relative.pathname)),
  26765. removeAllDots = mustEndAbs,
  26766. srcPath = result.pathname && result.pathname.split('/') || [],
  26767. relPath = relative.pathname && relative.pathname.split('/') || [],
  26768. psychotic = result.protocol && !slashedProtocol[result.protocol];
  26769. // if the url is a non-slashed url, then relative
  26770. // links like ../.. should be able
  26771. // to crawl up to the hostname, as well. This is strange.
  26772. // result.protocol has already been set by now.
  26773. // Later on, put the first path part into the host field.
  26774. if (psychotic) {
  26775. result.hostname = '';
  26776. result.port = null;
  26777. if (result.host) {
  26778. if (srcPath[0] === '') srcPath[0] = result.host;
  26779. else srcPath.unshift(result.host);
  26780. }
  26781. result.host = '';
  26782. if (relative.protocol) {
  26783. relative.hostname = null;
  26784. relative.port = null;
  26785. if (relative.host) {
  26786. if (relPath[0] === '') relPath[0] = relative.host;
  26787. else relPath.unshift(relative.host);
  26788. }
  26789. relative.host = null;
  26790. }
  26791. mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  26792. }
  26793. if (isRelAbs) {
  26794. // it's absolute.
  26795. result.host = (relative.host || relative.host === '') ?
  26796. relative.host : result.host;
  26797. result.hostname = (relative.hostname || relative.hostname === '') ?
  26798. relative.hostname : result.hostname;
  26799. result.search = relative.search;
  26800. result.query = relative.query;
  26801. srcPath = relPath;
  26802. // fall through to the dot-handling below.
  26803. } else if (relPath.length) {
  26804. // it's relative
  26805. // throw away the existing file, and take the new path instead.
  26806. if (!srcPath) srcPath = [];
  26807. srcPath.pop();
  26808. srcPath = srcPath.concat(relPath);
  26809. result.search = relative.search;
  26810. result.query = relative.query;
  26811. } else if (!isNullOrUndefined(relative.search)) {
  26812. // just pull out the search.
  26813. // like href='?foo'.
  26814. // Put this after the other two cases because it simplifies the booleans
  26815. if (psychotic) {
  26816. result.hostname = result.host = srcPath.shift();
  26817. //occationaly the auth can get stuck only in host
  26818. //this especialy happens in cases like
  26819. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  26820. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  26821. result.host.split('@') : false;
  26822. if (authInHost) {
  26823. result.auth = authInHost.shift();
  26824. result.host = result.hostname = authInHost.shift();
  26825. }
  26826. }
  26827. result.search = relative.search;
  26828. result.query = relative.query;
  26829. //to support http.request
  26830. if (!isNull(result.pathname) || !isNull(result.search)) {
  26831. result.path = (result.pathname ? result.pathname : '') +
  26832. (result.search ? result.search : '');
  26833. }
  26834. result.href = result.format();
  26835. return result;
  26836. }
  26837. if (!srcPath.length) {
  26838. // no path at all. easy.
  26839. // we've already handled the other stuff above.
  26840. result.pathname = null;
  26841. //to support http.request
  26842. if (result.search) {
  26843. result.path = '/' + result.search;
  26844. } else {
  26845. result.path = null;
  26846. }
  26847. result.href = result.format();
  26848. return result;
  26849. }
  26850. // if a url ENDs in . or .., then it must get a trailing slash.
  26851. // however, if it ends in anything else non-slashy,
  26852. // then it must NOT get a trailing slash.
  26853. var last = srcPath.slice(-1)[0];
  26854. var hasTrailingSlash = (
  26855. (result.host || relative.host) && (last === '.' || last === '..') ||
  26856. last === '');
  26857. // strip single dots, resolve double dots to parent dir
  26858. // if the path tries to go above the root, `up` ends up > 0
  26859. var up = 0;
  26860. for (var i = srcPath.length; i >= 0; i--) {
  26861. last = srcPath[i];
  26862. if (last == '.') {
  26863. srcPath.splice(i, 1);
  26864. } else if (last === '..') {
  26865. srcPath.splice(i, 1);
  26866. up++;
  26867. } else if (up) {
  26868. srcPath.splice(i, 1);
  26869. up--;
  26870. }
  26871. }
  26872. // if the path is allowed to go above the root, restore leading ..s
  26873. if (!mustEndAbs && !removeAllDots) {
  26874. for (; up--; up) {
  26875. srcPath.unshift('..');
  26876. }
  26877. }
  26878. if (mustEndAbs && srcPath[0] !== '' &&
  26879. (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
  26880. srcPath.unshift('');
  26881. }
  26882. if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
  26883. srcPath.push('');
  26884. }
  26885. var isAbsolute = srcPath[0] === '' ||
  26886. (srcPath[0] && srcPath[0].charAt(0) === '/');
  26887. // put the host back
  26888. if (psychotic) {
  26889. result.hostname = result.host = isAbsolute ? '' :
  26890. srcPath.length ? srcPath.shift() : '';
  26891. //occationaly the auth can get stuck only in host
  26892. //this especialy happens in cases like
  26893. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  26894. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  26895. result.host.split('@') : false;
  26896. if (authInHost) {
  26897. result.auth = authInHost.shift();
  26898. result.host = result.hostname = authInHost.shift();
  26899. }
  26900. }
  26901. mustEndAbs = mustEndAbs || (result.host && srcPath.length);
  26902. if (mustEndAbs && !isAbsolute) {
  26903. srcPath.unshift('');
  26904. }
  26905. if (!srcPath.length) {
  26906. result.pathname = null;
  26907. result.path = null;
  26908. } else {
  26909. result.pathname = srcPath.join('/');
  26910. }
  26911. //to support request.http
  26912. if (!isNull(result.pathname) || !isNull(result.search)) {
  26913. result.path = (result.pathname ? result.pathname : '') +
  26914. (result.search ? result.search : '');
  26915. }
  26916. result.auth = relative.auth || result.auth;
  26917. result.slashes = result.slashes || relative.slashes;
  26918. result.href = result.format();
  26919. return result;
  26920. };
  26921. Url.prototype.parseHost = function() {
  26922. var host = this.host;
  26923. var port = portPattern.exec(host);
  26924. if (port) {
  26925. port = port[0];
  26926. if (port !== ':') {
  26927. this.port = port.substr(1);
  26928. }
  26929. host = host.substr(0, host.length - port.length);
  26930. }
  26931. if (host) this.hostname = host;
  26932. };
  26933. function isString(arg) {
  26934. return typeof arg === "string";
  26935. }
  26936. function isObject(arg) {
  26937. return typeof arg === 'object' && arg !== null;
  26938. }
  26939. function isNull(arg) {
  26940. return arg === null;
  26941. }
  26942. function isNullOrUndefined(arg) {
  26943. return arg == null;
  26944. }
  26945. },{"punycode":145,"querystring":148}],158:[function(_dereq_,module,exports){
  26946. module.exports = function isBuffer(arg) {
  26947. return arg && typeof arg === 'object'
  26948. && typeof arg.copy === 'function'
  26949. && typeof arg.fill === 'function'
  26950. && typeof arg.readUInt8 === 'function';
  26951. }
  26952. },{}],159:[function(_dereq_,module,exports){
  26953. (function (process,global){
  26954. // Copyright Joyent, Inc. and other Node contributors.
  26955. //
  26956. // Permission is hereby granted, free of charge, to any person obtaining a
  26957. // copy of this software and associated documentation files (the
  26958. // "Software"), to deal in the Software without restriction, including
  26959. // without limitation the rights to use, copy, modify, merge, publish,
  26960. // distribute, sublicense, and/or sell copies of the Software, and to permit
  26961. // persons to whom the Software is furnished to do so, subject to the
  26962. // following conditions:
  26963. //
  26964. // The above copyright notice and this permission notice shall be included
  26965. // in all copies or substantial portions of the Software.
  26966. //
  26967. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  26968. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26969. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  26970. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  26971. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  26972. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  26973. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  26974. var formatRegExp = /%[sdj%]/g;
  26975. exports.format = function(f) {
  26976. if (!isString(f)) {
  26977. var objects = [];
  26978. for (var i = 0; i < arguments.length; i++) {
  26979. objects.push(inspect(arguments[i]));
  26980. }
  26981. return objects.join(' ');
  26982. }
  26983. var i = 1;
  26984. var args = arguments;
  26985. var len = args.length;
  26986. var str = String(f).replace(formatRegExp, function(x) {
  26987. if (x === '%%') return '%';
  26988. if (i >= len) return x;
  26989. switch (x) {
  26990. case '%s': return String(args[i++]);
  26991. case '%d': return Number(args[i++]);
  26992. case '%j':
  26993. try {
  26994. return JSON.stringify(args[i++]);
  26995. } catch (_) {
  26996. return '[Circular]';
  26997. }
  26998. default:
  26999. return x;
  27000. }
  27001. });
  27002. for (var x = args[i]; i < len; x = args[++i]) {
  27003. if (isNull(x) || !isObject(x)) {
  27004. str += ' ' + x;
  27005. } else {
  27006. str += ' ' + inspect(x);
  27007. }
  27008. }
  27009. return str;
  27010. };
  27011. // Mark that a method should not be used.
  27012. // Returns a modified function which warns once by default.
  27013. // If --no-deprecation is set, then it is a no-op.
  27014. exports.deprecate = function(fn, msg) {
  27015. // Allow for deprecating things in the process of starting up.
  27016. if (isUndefined(global.process)) {
  27017. return function() {
  27018. return exports.deprecate(fn, msg).apply(this, arguments);
  27019. };
  27020. }
  27021. if (process.noDeprecation === true) {
  27022. return fn;
  27023. }
  27024. var warned = false;
  27025. function deprecated() {
  27026. if (!warned) {
  27027. if (process.throwDeprecation) {
  27028. throw new Error(msg);
  27029. } else if (process.traceDeprecation) {
  27030. console.trace(msg);
  27031. } else {
  27032. console.error(msg);
  27033. }
  27034. warned = true;
  27035. }
  27036. return fn.apply(this, arguments);
  27037. }
  27038. return deprecated;
  27039. };
  27040. var debugs = {};
  27041. var debugEnviron;
  27042. exports.debuglog = function(set) {
  27043. if (isUndefined(debugEnviron))
  27044. debugEnviron = process.env.NODE_DEBUG || '';
  27045. set = set.toUpperCase();
  27046. if (!debugs[set]) {
  27047. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  27048. var pid = process.pid;
  27049. debugs[set] = function() {
  27050. var msg = exports.format.apply(exports, arguments);
  27051. console.error('%s %d: %s', set, pid, msg);
  27052. };
  27053. } else {
  27054. debugs[set] = function() {};
  27055. }
  27056. }
  27057. return debugs[set];
  27058. };
  27059. /**
  27060. * Echos the value of a value. Trys to print the value out
  27061. * in the best way possible given the different types.
  27062. *
  27063. * @param {Object} obj The object to print out.
  27064. * @param {Object} opts Optional options object that alters the output.
  27065. */
  27066. /* legacy: obj, showHidden, depth, colors*/
  27067. function inspect(obj, opts) {
  27068. // default options
  27069. var ctx = {
  27070. seen: [],
  27071. stylize: stylizeNoColor
  27072. };
  27073. // legacy...
  27074. if (arguments.length >= 3) ctx.depth = arguments[2];
  27075. if (arguments.length >= 4) ctx.colors = arguments[3];
  27076. if (isBoolean(opts)) {
  27077. // legacy...
  27078. ctx.showHidden = opts;
  27079. } else if (opts) {
  27080. // got an "options" object
  27081. exports._extend(ctx, opts);
  27082. }
  27083. // set default options
  27084. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  27085. if (isUndefined(ctx.depth)) ctx.depth = 2;
  27086. if (isUndefined(ctx.colors)) ctx.colors = false;
  27087. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  27088. if (ctx.colors) ctx.stylize = stylizeWithColor;
  27089. return formatValue(ctx, obj, ctx.depth);
  27090. }
  27091. exports.inspect = inspect;
  27092. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  27093. inspect.colors = {
  27094. 'bold' : [1, 22],
  27095. 'italic' : [3, 23],
  27096. 'underline' : [4, 24],
  27097. 'inverse' : [7, 27],
  27098. 'white' : [37, 39],
  27099. 'grey' : [90, 39],
  27100. 'black' : [30, 39],
  27101. 'blue' : [34, 39],
  27102. 'cyan' : [36, 39],
  27103. 'green' : [32, 39],
  27104. 'magenta' : [35, 39],
  27105. 'red' : [31, 39],
  27106. 'yellow' : [33, 39]
  27107. };
  27108. // Don't use 'blue' not visible on cmd.exe
  27109. inspect.styles = {
  27110. 'special': 'cyan',
  27111. 'number': 'yellow',
  27112. 'boolean': 'yellow',
  27113. 'undefined': 'grey',
  27114. 'null': 'bold',
  27115. 'string': 'green',
  27116. 'date': 'magenta',
  27117. // "name": intentionally not styling
  27118. 'regexp': 'red'
  27119. };
  27120. function stylizeWithColor(str, styleType) {
  27121. var style = inspect.styles[styleType];
  27122. if (style) {
  27123. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  27124. '\u001b[' + inspect.colors[style][1] + 'm';
  27125. } else {
  27126. return str;
  27127. }
  27128. }
  27129. function stylizeNoColor(str, styleType) {
  27130. return str;
  27131. }
  27132. function arrayToHash(array) {
  27133. var hash = {};
  27134. array.forEach(function(val, idx) {
  27135. hash[val] = true;
  27136. });
  27137. return hash;
  27138. }
  27139. function formatValue(ctx, value, recurseTimes) {
  27140. // Provide a hook for user-specified inspect functions.
  27141. // Check that value is an object with an inspect function on it
  27142. if (ctx.customInspect &&
  27143. value &&
  27144. isFunction(value.inspect) &&
  27145. // Filter out the util module, it's inspect function is special
  27146. value.inspect !== exports.inspect &&
  27147. // Also filter out any prototype objects using the circular check.
  27148. !(value.constructor && value.constructor.prototype === value)) {
  27149. var ret = value.inspect(recurseTimes, ctx);
  27150. if (!isString(ret)) {
  27151. ret = formatValue(ctx, ret, recurseTimes);
  27152. }
  27153. return ret;
  27154. }
  27155. // Primitive types cannot have properties
  27156. var primitive = formatPrimitive(ctx, value);
  27157. if (primitive) {
  27158. return primitive;
  27159. }
  27160. // Look up the keys of the object.
  27161. var keys = Object.keys(value);
  27162. var visibleKeys = arrayToHash(keys);
  27163. if (ctx.showHidden) {
  27164. keys = Object.getOwnPropertyNames(value);
  27165. }
  27166. // IE doesn't make error fields non-enumerable
  27167. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  27168. if (isError(value)
  27169. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  27170. return formatError(value);
  27171. }
  27172. // Some type of object without properties can be shortcutted.
  27173. if (keys.length === 0) {
  27174. if (isFunction(value)) {
  27175. var name = value.name ? ': ' + value.name : '';
  27176. return ctx.stylize('[Function' + name + ']', 'special');
  27177. }
  27178. if (isRegExp(value)) {
  27179. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  27180. }
  27181. if (isDate(value)) {
  27182. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  27183. }
  27184. if (isError(value)) {
  27185. return formatError(value);
  27186. }
  27187. }
  27188. var base = '', array = false, braces = ['{', '}'];
  27189. // Make Array say that they are Array
  27190. if (isArray(value)) {
  27191. array = true;
  27192. braces = ['[', ']'];
  27193. }
  27194. // Make functions say that they are functions
  27195. if (isFunction(value)) {
  27196. var n = value.name ? ': ' + value.name : '';
  27197. base = ' [Function' + n + ']';
  27198. }
  27199. // Make RegExps say that they are RegExps
  27200. if (isRegExp(value)) {
  27201. base = ' ' + RegExp.prototype.toString.call(value);
  27202. }
  27203. // Make dates with properties first say the date
  27204. if (isDate(value)) {
  27205. base = ' ' + Date.prototype.toUTCString.call(value);
  27206. }
  27207. // Make error with message first say the error
  27208. if (isError(value)) {
  27209. base = ' ' + formatError(value);
  27210. }
  27211. if (keys.length === 0 && (!array || value.length == 0)) {
  27212. return braces[0] + base + braces[1];
  27213. }
  27214. if (recurseTimes < 0) {
  27215. if (isRegExp(value)) {
  27216. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  27217. } else {
  27218. return ctx.stylize('[Object]', 'special');
  27219. }
  27220. }
  27221. ctx.seen.push(value);
  27222. var output;
  27223. if (array) {
  27224. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  27225. } else {
  27226. output = keys.map(function(key) {
  27227. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  27228. });
  27229. }
  27230. ctx.seen.pop();
  27231. return reduceToSingleString(output, base, braces);
  27232. }
  27233. function formatPrimitive(ctx, value) {
  27234. if (isUndefined(value))
  27235. return ctx.stylize('undefined', 'undefined');
  27236. if (isString(value)) {
  27237. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  27238. .replace(/'/g, "\\'")
  27239. .replace(/\\"/g, '"') + '\'';
  27240. return ctx.stylize(simple, 'string');
  27241. }
  27242. if (isNumber(value))
  27243. return ctx.stylize('' + value, 'number');
  27244. if (isBoolean(value))
  27245. return ctx.stylize('' + value, 'boolean');
  27246. // For some reason typeof null is "object", so special case here.
  27247. if (isNull(value))
  27248. return ctx.stylize('null', 'null');
  27249. }
  27250. function formatError(value) {
  27251. return '[' + Error.prototype.toString.call(value) + ']';
  27252. }
  27253. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  27254. var output = [];
  27255. for (var i = 0, l = value.length; i < l; ++i) {
  27256. if (hasOwnProperty(value, String(i))) {
  27257. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  27258. String(i), true));
  27259. } else {
  27260. output.push('');
  27261. }
  27262. }
  27263. keys.forEach(function(key) {
  27264. if (!key.match(/^\d+$/)) {
  27265. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  27266. key, true));
  27267. }
  27268. });
  27269. return output;
  27270. }
  27271. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  27272. var name, str, desc;
  27273. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  27274. if (desc.get) {
  27275. if (desc.set) {
  27276. str = ctx.stylize('[Getter/Setter]', 'special');
  27277. } else {
  27278. str = ctx.stylize('[Getter]', 'special');
  27279. }
  27280. } else {
  27281. if (desc.set) {
  27282. str = ctx.stylize('[Setter]', 'special');
  27283. }
  27284. }
  27285. if (!hasOwnProperty(visibleKeys, key)) {
  27286. name = '[' + key + ']';
  27287. }
  27288. if (!str) {
  27289. if (ctx.seen.indexOf(desc.value) < 0) {
  27290. if (isNull(recurseTimes)) {
  27291. str = formatValue(ctx, desc.value, null);
  27292. } else {
  27293. str = formatValue(ctx, desc.value, recurseTimes - 1);
  27294. }
  27295. if (str.indexOf('\n') > -1) {
  27296. if (array) {
  27297. str = str.split('\n').map(function(line) {
  27298. return ' ' + line;
  27299. }).join('\n').substr(2);
  27300. } else {
  27301. str = '\n' + str.split('\n').map(function(line) {
  27302. return ' ' + line;
  27303. }).join('\n');
  27304. }
  27305. }
  27306. } else {
  27307. str = ctx.stylize('[Circular]', 'special');
  27308. }
  27309. }
  27310. if (isUndefined(name)) {
  27311. if (array && key.match(/^\d+$/)) {
  27312. return str;
  27313. }
  27314. name = JSON.stringify('' + key);
  27315. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  27316. name = name.substr(1, name.length - 2);
  27317. name = ctx.stylize(name, 'name');
  27318. } else {
  27319. name = name.replace(/'/g, "\\'")
  27320. .replace(/\\"/g, '"')
  27321. .replace(/(^"|"$)/g, "'");
  27322. name = ctx.stylize(name, 'string');
  27323. }
  27324. }
  27325. return name + ': ' + str;
  27326. }
  27327. function reduceToSingleString(output, base, braces) {
  27328. var numLinesEst = 0;
  27329. var length = output.reduce(function(prev, cur) {
  27330. numLinesEst++;
  27331. if (cur.indexOf('\n') >= 0) numLinesEst++;
  27332. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  27333. }, 0);
  27334. if (length > 60) {
  27335. return braces[0] +
  27336. (base === '' ? '' : base + '\n ') +
  27337. ' ' +
  27338. output.join(',\n ') +
  27339. ' ' +
  27340. braces[1];
  27341. }
  27342. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  27343. }
  27344. // NOTE: These type checking functions intentionally don't use `instanceof`
  27345. // because it is fragile and can be easily faked with `Object.create()`.
  27346. function isArray(ar) {
  27347. return Array.isArray(ar);
  27348. }
  27349. exports.isArray = isArray;
  27350. function isBoolean(arg) {
  27351. return typeof arg === 'boolean';
  27352. }
  27353. exports.isBoolean = isBoolean;
  27354. function isNull(arg) {
  27355. return arg === null;
  27356. }
  27357. exports.isNull = isNull;
  27358. function isNullOrUndefined(arg) {
  27359. return arg == null;
  27360. }
  27361. exports.isNullOrUndefined = isNullOrUndefined;
  27362. function isNumber(arg) {
  27363. return typeof arg === 'number';
  27364. }
  27365. exports.isNumber = isNumber;
  27366. function isString(arg) {
  27367. return typeof arg === 'string';
  27368. }
  27369. exports.isString = isString;
  27370. function isSymbol(arg) {
  27371. return typeof arg === 'symbol';
  27372. }
  27373. exports.isSymbol = isSymbol;
  27374. function isUndefined(arg) {
  27375. return arg === void 0;
  27376. }
  27377. exports.isUndefined = isUndefined;
  27378. function isRegExp(re) {
  27379. return isObject(re) && objectToString(re) === '[object RegExp]';
  27380. }
  27381. exports.isRegExp = isRegExp;
  27382. function isObject(arg) {
  27383. return typeof arg === 'object' && arg !== null;
  27384. }
  27385. exports.isObject = isObject;
  27386. function isDate(d) {
  27387. return isObject(d) && objectToString(d) === '[object Date]';
  27388. }
  27389. exports.isDate = isDate;
  27390. function isError(e) {
  27391. return isObject(e) &&
  27392. (objectToString(e) === '[object Error]' || e instanceof Error);
  27393. }
  27394. exports.isError = isError;
  27395. function isFunction(arg) {
  27396. return typeof arg === 'function';
  27397. }
  27398. exports.isFunction = isFunction;
  27399. function isPrimitive(arg) {
  27400. return arg === null ||
  27401. typeof arg === 'boolean' ||
  27402. typeof arg === 'number' ||
  27403. typeof arg === 'string' ||
  27404. typeof arg === 'symbol' || // ES6 symbol
  27405. typeof arg === 'undefined';
  27406. }
  27407. exports.isPrimitive = isPrimitive;
  27408. exports.isBuffer = _dereq_('./support/isBuffer');
  27409. function objectToString(o) {
  27410. return Object.prototype.toString.call(o);
  27411. }
  27412. function pad(n) {
  27413. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  27414. }
  27415. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  27416. 'Oct', 'Nov', 'Dec'];
  27417. // 26 Feb 16:19:34
  27418. function timestamp() {
  27419. var d = new Date();
  27420. var time = [pad(d.getHours()),
  27421. pad(d.getMinutes()),
  27422. pad(d.getSeconds())].join(':');
  27423. return [d.getDate(), months[d.getMonth()], time].join(' ');
  27424. }
  27425. // log is just a thin wrapper to console.log that prepends a timestamp
  27426. exports.log = function() {
  27427. console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
  27428. };
  27429. /**
  27430. * Inherit the prototype methods from one constructor into another.
  27431. *
  27432. * The Function.prototype.inherits from lang.js rewritten as a standalone
  27433. * function (not on Function.prototype). NOTE: If this file is to be loaded
  27434. * during bootstrapping this function needs to be rewritten using some native
  27435. * functions as prototype setup using normal JavaScript does not work as
  27436. * expected during bootstrapping (see mirror.js in r114903).
  27437. *
  27438. * @param {function} ctor Constructor function which needs to inherit the
  27439. * prototype.
  27440. * @param {function} superCtor Constructor function to inherit prototype from.
  27441. */
  27442. exports.inherits = _dereq_('inherits');
  27443. exports._extend = function(origin, add) {
  27444. // Don't do anything if add isn't an object
  27445. if (!add || !isObject(add)) return origin;
  27446. var keys = Object.keys(add);
  27447. var i = keys.length;
  27448. while (i--) {
  27449. origin[keys[i]] = add[keys[i]];
  27450. }
  27451. return origin;
  27452. };
  27453. function hasOwnProperty(obj, prop) {
  27454. return Object.prototype.hasOwnProperty.call(obj, prop);
  27455. }
  27456. }).call(this,_dereq_("C:\\Users\\Alex\\AppData\\Roaming\\npm\\node_modules\\browserify\\node_modules\\insert-module-globals\\node_modules\\process\\browser.js"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  27457. },{"./support/isBuffer":158,"C:\\Users\\Alex\\AppData\\Roaming\\npm\\node_modules\\browserify\\node_modules\\insert-module-globals\\node_modules\\process\\browser.js":144,"inherits":143}]},{},[1])
  27458. (1)
  27459. });