PageRenderTime 66ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/Examples/node_modules/socket.io-client/dist/socket.io.js

https://bitbucket.org/larchange/game
JavaScript | 3787 lines | 2850 code | 327 blank | 610 comment | 225 complexity | d097f31a9a340c75ea9ccd782187ca2c MD5 | raw file
Possible License(s): MIT, BSD-3-Clause, Apache-2.0

Large files files are truncated, but you can click here to view the full file

  1. /*! Socket.IO.js build:0.9.5, development. Copyright(c) 2011 LearnBoost <dev@learnboost.com> MIT Licensed */
  2. /**
  3. * socket.io
  4. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  5. * MIT Licensed
  6. */
  7. (function (exports, global) {
  8. /**
  9. * IO namespace.
  10. *
  11. * @namespace
  12. */
  13. var io = exports;
  14. /**
  15. * Socket.IO version
  16. *
  17. * @api public
  18. */
  19. io.version = '0.9.5';
  20. /**
  21. * Protocol implemented.
  22. *
  23. * @api public
  24. */
  25. io.protocol = 1;
  26. /**
  27. * Available transports, these will be populated with the available transports
  28. *
  29. * @api public
  30. */
  31. io.transports = [];
  32. /**
  33. * Keep track of jsonp callbacks.
  34. *
  35. * @api private
  36. */
  37. io.j = [];
  38. /**
  39. * Keep track of our io.Sockets
  40. *
  41. * @api private
  42. */
  43. io.sockets = {};
  44. /**
  45. * Manages connections to hosts.
  46. *
  47. * @param {String} uri
  48. * @Param {Boolean} force creation of new socket (defaults to false)
  49. * @api public
  50. */
  51. io.connect = function (host, details) {
  52. var uri = io.util.parseUri(host)
  53. , uuri
  54. , socket;
  55. if (global && global.location) {
  56. uri.protocol = uri.protocol || global.location.protocol.slice(0, -1);
  57. uri.host = uri.host || (global.document
  58. ? global.document.domain : global.location.hostname);
  59. uri.port = uri.port || global.location.port;
  60. }
  61. uuri = io.util.uniqueUri(uri);
  62. var options = {
  63. host: uri.host
  64. , secure: 'https' == uri.protocol
  65. , port: uri.port || ('https' == uri.protocol ? 443 : 80)
  66. , query: uri.query || ''
  67. };
  68. io.util.merge(options, details);
  69. if (options['force new connection'] || !io.sockets[uuri]) {
  70. socket = new io.Socket(options);
  71. }
  72. if (!options['force new connection'] && socket) {
  73. io.sockets[uuri] = socket;
  74. }
  75. socket = socket || io.sockets[uuri];
  76. // if path is different from '' or /
  77. return socket.of(uri.path.length > 1 ? uri.path : '');
  78. };
  79. })('object' === typeof module ? module.exports : (this.io = {}), this);
  80. /**
  81. * socket.io
  82. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  83. * MIT Licensed
  84. */
  85. (function (exports, global) {
  86. /**
  87. * Utilities namespace.
  88. *
  89. * @namespace
  90. */
  91. var util = exports.util = {};
  92. /**
  93. * Parses an URI
  94. *
  95. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  96. * @api public
  97. */
  98. var re = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  99. var parts = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password',
  100. 'host', 'port', 'relative', 'path', 'directory', 'file', 'query',
  101. 'anchor'];
  102. util.parseUri = function (str) {
  103. var m = re.exec(str || '')
  104. , uri = {}
  105. , i = 14;
  106. while (i--) {
  107. uri[parts[i]] = m[i] || '';
  108. }
  109. return uri;
  110. };
  111. /**
  112. * Produces a unique url that identifies a Socket.IO connection.
  113. *
  114. * @param {Object} uri
  115. * @api public
  116. */
  117. util.uniqueUri = function (uri) {
  118. var protocol = uri.protocol
  119. , host = uri.host
  120. , port = uri.port;
  121. if ('document' in global) {
  122. host = host || document.domain;
  123. port = port || (protocol == 'https'
  124. && document.location.protocol !== 'https:' ? 443 : document.location.port);
  125. } else {
  126. host = host || 'localhost';
  127. if (!port && protocol == 'https') {
  128. port = 443;
  129. }
  130. }
  131. return (protocol || 'http') + '://' + host + ':' + (port || 80);
  132. };
  133. /**
  134. * Mergest 2 query strings in to once unique query string
  135. *
  136. * @param {String} base
  137. * @param {String} addition
  138. * @api public
  139. */
  140. util.query = function (base, addition) {
  141. var query = util.chunkQuery(base || '')
  142. , components = [];
  143. util.merge(query, util.chunkQuery(addition || ''));
  144. for (var part in query) {
  145. if (query.hasOwnProperty(part)) {
  146. components.push(part + '=' + query[part]);
  147. }
  148. }
  149. return components.length ? '?' + components.join('&') : '';
  150. };
  151. /**
  152. * Transforms a querystring in to an object
  153. *
  154. * @param {String} qs
  155. * @api public
  156. */
  157. util.chunkQuery = function (qs) {
  158. var query = {}
  159. , params = qs.split('&')
  160. , i = 0
  161. , l = params.length
  162. , kv;
  163. for (; i < l; ++i) {
  164. kv = params[i].split('=');
  165. if (kv[0]) {
  166. query[kv[0]] = kv[1];
  167. }
  168. }
  169. return query;
  170. };
  171. /**
  172. * Executes the given function when the page is loaded.
  173. *
  174. * io.util.load(function () { console.log('page loaded'); });
  175. *
  176. * @param {Function} fn
  177. * @api public
  178. */
  179. var pageLoaded = false;
  180. util.load = function (fn) {
  181. if ('document' in global && document.readyState === 'complete' || pageLoaded) {
  182. return fn();
  183. }
  184. util.on(global, 'load', fn, false);
  185. };
  186. /**
  187. * Adds an event.
  188. *
  189. * @api private
  190. */
  191. util.on = function (element, event, fn, capture) {
  192. if (element.attachEvent) {
  193. element.attachEvent('on' + event, fn);
  194. } else if (element.addEventListener) {
  195. element.addEventListener(event, fn, capture);
  196. }
  197. };
  198. /**
  199. * Generates the correct `XMLHttpRequest` for regular and cross domain requests.
  200. *
  201. * @param {Boolean} [xdomain] Create a request that can be used cross domain.
  202. * @returns {XMLHttpRequest|false} If we can create a XMLHttpRequest.
  203. * @api private
  204. */
  205. util.request = function (xdomain) {
  206. if (xdomain && 'undefined' != typeof XDomainRequest) {
  207. return new XDomainRequest();
  208. }
  209. if ('undefined' != typeof XMLHttpRequest && (!xdomain || util.ua.hasCORS)) {
  210. return new XMLHttpRequest();
  211. }
  212. if (!xdomain) {
  213. try {
  214. return new window[(['Active'].concat('Object').join('X'))]('Microsoft.XMLHTTP');
  215. } catch(e) { }
  216. }
  217. return null;
  218. };
  219. /**
  220. * XHR based transport constructor.
  221. *
  222. * @constructor
  223. * @api public
  224. */
  225. /**
  226. * Change the internal pageLoaded value.
  227. */
  228. if ('undefined' != typeof window) {
  229. util.load(function () {
  230. pageLoaded = true;
  231. });
  232. }
  233. /**
  234. * Defers a function to ensure a spinner is not displayed by the browser
  235. *
  236. * @param {Function} fn
  237. * @api public
  238. */
  239. util.defer = function (fn) {
  240. if (!util.ua.webkit || 'undefined' != typeof importScripts) {
  241. return fn();
  242. }
  243. util.load(function () {
  244. setTimeout(fn, 100);
  245. });
  246. };
  247. /**
  248. * Merges two objects.
  249. *
  250. * @api public
  251. */
  252. util.merge = function merge (target, additional, deep, lastseen) {
  253. var seen = lastseen || []
  254. , depth = typeof deep == 'undefined' ? 2 : deep
  255. , prop;
  256. for (prop in additional) {
  257. if (additional.hasOwnProperty(prop) && util.indexOf(seen, prop) < 0) {
  258. if (typeof target[prop] !== 'object' || !depth) {
  259. target[prop] = additional[prop];
  260. seen.push(additional[prop]);
  261. } else {
  262. util.merge(target[prop], additional[prop], depth - 1, seen);
  263. }
  264. }
  265. }
  266. return target;
  267. };
  268. /**
  269. * Merges prototypes from objects
  270. *
  271. * @api public
  272. */
  273. util.mixin = function (ctor, ctor2) {
  274. util.merge(ctor.prototype, ctor2.prototype);
  275. };
  276. /**
  277. * Shortcut for prototypical and static inheritance.
  278. *
  279. * @api private
  280. */
  281. util.inherit = function (ctor, ctor2) {
  282. function f() {};
  283. f.prototype = ctor2.prototype;
  284. ctor.prototype = new f;
  285. };
  286. /**
  287. * Checks if the given object is an Array.
  288. *
  289. * io.util.isArray([]); // true
  290. * io.util.isArray({}); // false
  291. *
  292. * @param Object obj
  293. * @api public
  294. */
  295. util.isArray = Array.isArray || function (obj) {
  296. return Object.prototype.toString.call(obj) === '[object Array]';
  297. };
  298. /**
  299. * Intersects values of two arrays into a third
  300. *
  301. * @api public
  302. */
  303. util.intersect = function (arr, arr2) {
  304. var ret = []
  305. , longest = arr.length > arr2.length ? arr : arr2
  306. , shortest = arr.length > arr2.length ? arr2 : arr;
  307. for (var i = 0, l = shortest.length; i < l; i++) {
  308. if (~util.indexOf(longest, shortest[i]))
  309. ret.push(shortest[i]);
  310. }
  311. return ret;
  312. }
  313. /**
  314. * Array indexOf compatibility.
  315. *
  316. * @see bit.ly/a5Dxa2
  317. * @api public
  318. */
  319. util.indexOf = function (arr, o, i) {
  320. for (var j = arr.length, i = i < 0 ? i + j < 0 ? 0 : i + j : i || 0;
  321. i < j && arr[i] !== o; i++) {}
  322. return j <= i ? -1 : i;
  323. };
  324. /**
  325. * Converts enumerables to array.
  326. *
  327. * @api public
  328. */
  329. util.toArray = function (enu) {
  330. var arr = [];
  331. for (var i = 0, l = enu.length; i < l; i++)
  332. arr.push(enu[i]);
  333. return arr;
  334. };
  335. /**
  336. * UA / engines detection namespace.
  337. *
  338. * @namespace
  339. */
  340. util.ua = {};
  341. /**
  342. * Whether the UA supports CORS for XHR.
  343. *
  344. * @api public
  345. */
  346. util.ua.hasCORS = 'undefined' != typeof XMLHttpRequest && (function () {
  347. try {
  348. var a = new XMLHttpRequest();
  349. } catch (e) {
  350. return false;
  351. }
  352. return a.withCredentials != undefined;
  353. })();
  354. /**
  355. * Detect webkit.
  356. *
  357. * @api public
  358. */
  359. util.ua.webkit = 'undefined' != typeof navigator
  360. && /webkit/i.test(navigator.userAgent);
  361. })('undefined' != typeof io ? io : module.exports, this);
  362. /**
  363. * socket.io
  364. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  365. * MIT Licensed
  366. */
  367. (function (exports, io) {
  368. /**
  369. * Expose constructor.
  370. */
  371. exports.EventEmitter = EventEmitter;
  372. /**
  373. * Event emitter constructor.
  374. *
  375. * @api public.
  376. */
  377. function EventEmitter () {};
  378. /**
  379. * Adds a listener
  380. *
  381. * @api public
  382. */
  383. EventEmitter.prototype.on = function (name, fn) {
  384. if (!this.$events) {
  385. this.$events = {};
  386. }
  387. if (!this.$events[name]) {
  388. this.$events[name] = fn;
  389. } else if (io.util.isArray(this.$events[name])) {
  390. this.$events[name].push(fn);
  391. } else {
  392. this.$events[name] = [this.$events[name], fn];
  393. }
  394. return this;
  395. };
  396. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  397. /**
  398. * Adds a volatile listener.
  399. *
  400. * @api public
  401. */
  402. EventEmitter.prototype.once = function (name, fn) {
  403. var self = this;
  404. function on () {
  405. self.removeListener(name, on);
  406. fn.apply(this, arguments);
  407. };
  408. on.listener = fn;
  409. this.on(name, on);
  410. return this;
  411. };
  412. /**
  413. * Removes a listener.
  414. *
  415. * @api public
  416. */
  417. EventEmitter.prototype.removeListener = function (name, fn) {
  418. if (this.$events && this.$events[name]) {
  419. var list = this.$events[name];
  420. if (io.util.isArray(list)) {
  421. var pos = -1;
  422. for (var i = 0, l = list.length; i < l; i++) {
  423. if (list[i] === fn || (list[i].listener && list[i].listener === fn)) {
  424. pos = i;
  425. break;
  426. }
  427. }
  428. if (pos < 0) {
  429. return this;
  430. }
  431. list.splice(pos, 1);
  432. if (!list.length) {
  433. delete this.$events[name];
  434. }
  435. } else if (list === fn || (list.listener && list.listener === fn)) {
  436. delete this.$events[name];
  437. }
  438. }
  439. return this;
  440. };
  441. /**
  442. * Removes all listeners for an event.
  443. *
  444. * @api public
  445. */
  446. EventEmitter.prototype.removeAllListeners = function (name) {
  447. // TODO: enable this when node 0.5 is stable
  448. //if (name === undefined) {
  449. //this.$events = {};
  450. //return this;
  451. //}
  452. if (this.$events && this.$events[name]) {
  453. this.$events[name] = null;
  454. }
  455. return this;
  456. };
  457. /**
  458. * Gets all listeners for a certain event.
  459. *
  460. * @api publci
  461. */
  462. EventEmitter.prototype.listeners = function (name) {
  463. if (!this.$events) {
  464. this.$events = {};
  465. }
  466. if (!this.$events[name]) {
  467. this.$events[name] = [];
  468. }
  469. if (!io.util.isArray(this.$events[name])) {
  470. this.$events[name] = [this.$events[name]];
  471. }
  472. return this.$events[name];
  473. };
  474. /**
  475. * Emits an event.
  476. *
  477. * @api public
  478. */
  479. EventEmitter.prototype.emit = function (name) {
  480. if (!this.$events) {
  481. return false;
  482. }
  483. var handler = this.$events[name];
  484. if (!handler) {
  485. return false;
  486. }
  487. var args = Array.prototype.slice.call(arguments, 1);
  488. if ('function' == typeof handler) {
  489. handler.apply(this, args);
  490. } else if (io.util.isArray(handler)) {
  491. var listeners = handler.slice();
  492. for (var i = 0, l = listeners.length; i < l; i++) {
  493. listeners[i].apply(this, args);
  494. }
  495. } else {
  496. return false;
  497. }
  498. return true;
  499. };
  500. })(
  501. 'undefined' != typeof io ? io : module.exports
  502. , 'undefined' != typeof io ? io : module.parent.exports
  503. );
  504. /**
  505. * socket.io
  506. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  507. * MIT Licensed
  508. */
  509. /**
  510. * Based on JSON2 (http://www.JSON.org/js.html).
  511. */
  512. (function (exports, nativeJSON) {
  513. "use strict";
  514. // use native JSON if it's available
  515. if (nativeJSON && nativeJSON.parse){
  516. return exports.JSON = {
  517. parse: nativeJSON.parse
  518. , stringify: nativeJSON.stringify
  519. }
  520. }
  521. var JSON = exports.JSON = {};
  522. function f(n) {
  523. // Format integers to have at least two digits.
  524. return n < 10 ? '0' + n : n;
  525. }
  526. function date(d, key) {
  527. return isFinite(d.valueOf()) ?
  528. d.getUTCFullYear() + '-' +
  529. f(d.getUTCMonth() + 1) + '-' +
  530. f(d.getUTCDate()) + 'T' +
  531. f(d.getUTCHours()) + ':' +
  532. f(d.getUTCMinutes()) + ':' +
  533. f(d.getUTCSeconds()) + 'Z' : null;
  534. };
  535. var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
  536. escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
  537. gap,
  538. indent,
  539. meta = { // table of character substitutions
  540. '\b': '\\b',
  541. '\t': '\\t',
  542. '\n': '\\n',
  543. '\f': '\\f',
  544. '\r': '\\r',
  545. '"' : '\\"',
  546. '\\': '\\\\'
  547. },
  548. rep;
  549. function quote(string) {
  550. // If the string contains no control characters, no quote characters, and no
  551. // backslash characters, then we can safely slap some quotes around it.
  552. // Otherwise we must also replace the offending characters with safe escape
  553. // sequences.
  554. escapable.lastIndex = 0;
  555. return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
  556. var c = meta[a];
  557. return typeof c === 'string' ? c :
  558. '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  559. }) + '"' : '"' + string + '"';
  560. }
  561. function str(key, holder) {
  562. // Produce a string from holder[key].
  563. var i, // The loop counter.
  564. k, // The member key.
  565. v, // The member value.
  566. length,
  567. mind = gap,
  568. partial,
  569. value = holder[key];
  570. // If the value has a toJSON method, call it to obtain a replacement value.
  571. if (value instanceof Date) {
  572. value = date(key);
  573. }
  574. // If we were called with a replacer function, then call the replacer to
  575. // obtain a replacement value.
  576. if (typeof rep === 'function') {
  577. value = rep.call(holder, key, value);
  578. }
  579. // What happens next depends on the value's type.
  580. switch (typeof value) {
  581. case 'string':
  582. return quote(value);
  583. case 'number':
  584. // JSON numbers must be finite. Encode non-finite numbers as null.
  585. return isFinite(value) ? String(value) : 'null';
  586. case 'boolean':
  587. case 'null':
  588. // If the value is a boolean or null, convert it to a string. Note:
  589. // typeof null does not produce 'null'. The case is included here in
  590. // the remote chance that this gets fixed someday.
  591. return String(value);
  592. // If the type is 'object', we might be dealing with an object or an array or
  593. // null.
  594. case 'object':
  595. // Due to a specification blunder in ECMAScript, typeof null is 'object',
  596. // so watch out for that case.
  597. if (!value) {
  598. return 'null';
  599. }
  600. // Make an array to hold the partial results of stringifying this object value.
  601. gap += indent;
  602. partial = [];
  603. // Is the value an array?
  604. if (Object.prototype.toString.apply(value) === '[object Array]') {
  605. // The value is an array. Stringify every element. Use null as a placeholder
  606. // for non-JSON values.
  607. length = value.length;
  608. for (i = 0; i < length; i += 1) {
  609. partial[i] = str(i, value) || 'null';
  610. }
  611. // Join all of the elements together, separated with commas, and wrap them in
  612. // brackets.
  613. v = partial.length === 0 ? '[]' : gap ?
  614. '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' :
  615. '[' + partial.join(',') + ']';
  616. gap = mind;
  617. return v;
  618. }
  619. // If the replacer is an array, use it to select the members to be stringified.
  620. if (rep && typeof rep === 'object') {
  621. length = rep.length;
  622. for (i = 0; i < length; i += 1) {
  623. if (typeof rep[i] === 'string') {
  624. k = rep[i];
  625. v = str(k, value);
  626. if (v) {
  627. partial.push(quote(k) + (gap ? ': ' : ':') + v);
  628. }
  629. }
  630. }
  631. } else {
  632. // Otherwise, iterate through all of the keys in the object.
  633. for (k in value) {
  634. if (Object.prototype.hasOwnProperty.call(value, k)) {
  635. v = str(k, value);
  636. if (v) {
  637. partial.push(quote(k) + (gap ? ': ' : ':') + v);
  638. }
  639. }
  640. }
  641. }
  642. // Join all of the member texts together, separated with commas,
  643. // and wrap them in braces.
  644. v = partial.length === 0 ? '{}' : gap ?
  645. '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' :
  646. '{' + partial.join(',') + '}';
  647. gap = mind;
  648. return v;
  649. }
  650. }
  651. // If the JSON object does not yet have a stringify method, give it one.
  652. JSON.stringify = function (value, replacer, space) {
  653. // The stringify method takes a value and an optional replacer, and an optional
  654. // space parameter, and returns a JSON text. The replacer can be a function
  655. // that can replace values, or an array of strings that will select the keys.
  656. // A default replacer method can be provided. Use of the space parameter can
  657. // produce text that is more easily readable.
  658. var i;
  659. gap = '';
  660. indent = '';
  661. // If the space parameter is a number, make an indent string containing that
  662. // many spaces.
  663. if (typeof space === 'number') {
  664. for (i = 0; i < space; i += 1) {
  665. indent += ' ';
  666. }
  667. // If the space parameter is a string, it will be used as the indent string.
  668. } else if (typeof space === 'string') {
  669. indent = space;
  670. }
  671. // If there is a replacer, it must be a function or an array.
  672. // Otherwise, throw an error.
  673. rep = replacer;
  674. if (replacer && typeof replacer !== 'function' &&
  675. (typeof replacer !== 'object' ||
  676. typeof replacer.length !== 'number')) {
  677. throw new Error('JSON.stringify');
  678. }
  679. // Make a fake root object containing our value under the key of ''.
  680. // Return the result of stringifying the value.
  681. return str('', {'': value});
  682. };
  683. // If the JSON object does not yet have a parse method, give it one.
  684. JSON.parse = function (text, reviver) {
  685. // The parse method takes a text and an optional reviver function, and returns
  686. // a JavaScript value if the text is a valid JSON text.
  687. var j;
  688. function walk(holder, key) {
  689. // The walk method is used to recursively walk the resulting structure so
  690. // that modifications can be made.
  691. var k, v, value = holder[key];
  692. if (value && typeof value === 'object') {
  693. for (k in value) {
  694. if (Object.prototype.hasOwnProperty.call(value, k)) {
  695. v = walk(value, k);
  696. if (v !== undefined) {
  697. value[k] = v;
  698. } else {
  699. delete value[k];
  700. }
  701. }
  702. }
  703. }
  704. return reviver.call(holder, key, value);
  705. }
  706. // Parsing happens in four stages. In the first stage, we replace certain
  707. // Unicode characters with escape sequences. JavaScript handles many characters
  708. // incorrectly, either silently deleting them, or treating them as line endings.
  709. text = String(text);
  710. cx.lastIndex = 0;
  711. if (cx.test(text)) {
  712. text = text.replace(cx, function (a) {
  713. return '\\u' +
  714. ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  715. });
  716. }
  717. // In the second stage, we run the text against regular expressions that look
  718. // for non-JSON patterns. We are especially concerned with '()' and 'new'
  719. // because they can cause invocation, and '=' because it can cause mutation.
  720. // But just to be safe, we want to reject all unexpected forms.
  721. // We split the second stage into 4 regexp operations in order to work around
  722. // crippling inefficiencies in IE's and Safari's regexp engines. First we
  723. // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
  724. // replace all simple value tokens with ']' characters. Third, we delete all
  725. // open brackets that follow a colon or comma or that begin the text. Finally,
  726. // we look to see that the remaining characters are only whitespace or ']' or
  727. // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
  728. if (/^[\],:{}\s]*$/
  729. .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
  730. .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
  731. .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
  732. // In the third stage we use the eval function to compile the text into a
  733. // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
  734. // in JavaScript: it can begin a block or an object literal. We wrap the text
  735. // in parens to eliminate the ambiguity.
  736. j = eval('(' + text + ')');
  737. // In the optional fourth stage, we recursively walk the new structure, passing
  738. // each name/value pair to a reviver function for possible transformation.
  739. return typeof reviver === 'function' ?
  740. walk({'': j}, '') : j;
  741. }
  742. // If the text is not JSON parseable, then a SyntaxError is thrown.
  743. throw new SyntaxError('JSON.parse');
  744. };
  745. })(
  746. 'undefined' != typeof io ? io : module.exports
  747. , typeof JSON !== 'undefined' ? JSON : undefined
  748. );
  749. /**
  750. * socket.io
  751. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  752. * MIT Licensed
  753. */
  754. (function (exports, io) {
  755. /**
  756. * Parser namespace.
  757. *
  758. * @namespace
  759. */
  760. var parser = exports.parser = {};
  761. /**
  762. * Packet types.
  763. */
  764. var packets = parser.packets = [
  765. 'disconnect'
  766. , 'connect'
  767. , 'heartbeat'
  768. , 'message'
  769. , 'json'
  770. , 'event'
  771. , 'ack'
  772. , 'error'
  773. , 'noop'
  774. ];
  775. /**
  776. * Errors reasons.
  777. */
  778. var reasons = parser.reasons = [
  779. 'transport not supported'
  780. , 'client not handshaken'
  781. , 'unauthorized'
  782. ];
  783. /**
  784. * Errors advice.
  785. */
  786. var advice = parser.advice = [
  787. 'reconnect'
  788. ];
  789. /**
  790. * Shortcuts.
  791. */
  792. var JSON = io.JSON
  793. , indexOf = io.util.indexOf;
  794. /**
  795. * Encodes a packet.
  796. *
  797. * @api private
  798. */
  799. parser.encodePacket = function (packet) {
  800. var type = indexOf(packets, packet.type)
  801. , id = packet.id || ''
  802. , endpoint = packet.endpoint || ''
  803. , ack = packet.ack
  804. , data = null;
  805. switch (packet.type) {
  806. case 'error':
  807. var reason = packet.reason ? indexOf(reasons, packet.reason) : ''
  808. , adv = packet.advice ? indexOf(advice, packet.advice) : '';
  809. if (reason !== '' || adv !== '')
  810. data = reason + (adv !== '' ? ('+' + adv) : '');
  811. break;
  812. case 'message':
  813. if (packet.data !== '')
  814. data = packet.data;
  815. break;
  816. case 'event':
  817. var ev = { name: packet.name };
  818. if (packet.args && packet.args.length) {
  819. ev.args = packet.args;
  820. }
  821. data = JSON.stringify(ev);
  822. break;
  823. case 'json':
  824. data = JSON.stringify(packet.data);
  825. break;
  826. case 'connect':
  827. if (packet.qs)
  828. data = packet.qs;
  829. break;
  830. case 'ack':
  831. data = packet.ackId
  832. + (packet.args && packet.args.length
  833. ? '+' + JSON.stringify(packet.args) : '');
  834. break;
  835. }
  836. // construct packet with required fragments
  837. var encoded = [
  838. type
  839. , id + (ack == 'data' ? '+' : '')
  840. , endpoint
  841. ];
  842. // data fragment is optional
  843. if (data !== null && data !== undefined)
  844. encoded.push(data);
  845. return encoded.join(':');
  846. };
  847. /**
  848. * Encodes multiple messages (payload).
  849. *
  850. * @param {Array} messages
  851. * @api private
  852. */
  853. parser.encodePayload = function (packets) {
  854. var decoded = '';
  855. if (packets.length == 1)
  856. return packets[0];
  857. for (var i = 0, l = packets.length; i < l; i++) {
  858. var packet = packets[i];
  859. decoded += '\ufffd' + packet.length + '\ufffd' + packets[i];
  860. }
  861. return decoded;
  862. };
  863. /**
  864. * Decodes a packet
  865. *
  866. * @api private
  867. */
  868. var regexp = /([^:]+):([0-9]+)?(\+)?:([^:]+)?:?([\s\S]*)?/;
  869. parser.decodePacket = function (data) {
  870. var pieces = data.match(regexp);
  871. if (!pieces) return {};
  872. var id = pieces[2] || ''
  873. , data = pieces[5] || ''
  874. , packet = {
  875. type: packets[pieces[1]]
  876. , endpoint: pieces[4] || ''
  877. };
  878. // whether we need to acknowledge the packet
  879. if (id) {
  880. packet.id = id;
  881. if (pieces[3])
  882. packet.ack = 'data';
  883. else
  884. packet.ack = true;
  885. }
  886. // handle different packet types
  887. switch (packet.type) {
  888. case 'error':
  889. var pieces = data.split('+');
  890. packet.reason = reasons[pieces[0]] || '';
  891. packet.advice = advice[pieces[1]] || '';
  892. break;
  893. case 'message':
  894. packet.data = data || '';
  895. break;
  896. case 'event':
  897. try {
  898. var opts = JSON.parse(data);
  899. packet.name = opts.name;
  900. packet.args = opts.args;
  901. } catch (e) { }
  902. packet.args = packet.args || [];
  903. break;
  904. case 'json':
  905. try {
  906. packet.data = JSON.parse(data);
  907. } catch (e) { }
  908. break;
  909. case 'connect':
  910. packet.qs = data || '';
  911. break;
  912. case 'ack':
  913. var pieces = data.match(/^([0-9]+)(\+)?(.*)/);
  914. if (pieces) {
  915. packet.ackId = pieces[1];
  916. packet.args = [];
  917. if (pieces[3]) {
  918. try {
  919. packet.args = pieces[3] ? JSON.parse(pieces[3]) : [];
  920. } catch (e) { }
  921. }
  922. }
  923. break;
  924. case 'disconnect':
  925. case 'heartbeat':
  926. break;
  927. };
  928. return packet;
  929. };
  930. /**
  931. * Decodes data payload. Detects multiple messages
  932. *
  933. * @return {Array} messages
  934. * @api public
  935. */
  936. parser.decodePayload = function (data) {
  937. // IE doesn't like data[i] for unicode chars, charAt works fine
  938. if (data.charAt(0) == '\ufffd') {
  939. var ret = [];
  940. for (var i = 1, length = ''; i < data.length; i++) {
  941. if (data.charAt(i) == '\ufffd') {
  942. ret.push(parser.decodePacket(data.substr(i + 1).substr(0, length)));
  943. i += Number(length) + 1;
  944. length = '';
  945. } else {
  946. length += data.charAt(i);
  947. }
  948. }
  949. return ret;
  950. } else {
  951. return [parser.decodePacket(data)];
  952. }
  953. };
  954. })(
  955. 'undefined' != typeof io ? io : module.exports
  956. , 'undefined' != typeof io ? io : module.parent.exports
  957. );
  958. /**
  959. * socket.io
  960. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  961. * MIT Licensed
  962. */
  963. (function (exports, io) {
  964. /**
  965. * Expose constructor.
  966. */
  967. exports.Transport = Transport;
  968. /**
  969. * This is the transport template for all supported transport methods.
  970. *
  971. * @constructor
  972. * @api public
  973. */
  974. function Transport (socket, sessid) {
  975. this.socket = socket;
  976. this.sessid = sessid;
  977. };
  978. /**
  979. * Apply EventEmitter mixin.
  980. */
  981. io.util.mixin(Transport, io.EventEmitter);
  982. /**
  983. * Handles the response from the server. When a new response is received
  984. * it will automatically update the timeout, decode the message and
  985. * forwards the response to the onMessage function for further processing.
  986. *
  987. * @param {String} data Response from the server.
  988. * @api private
  989. */
  990. Transport.prototype.onData = function (data) {
  991. this.clearCloseTimeout();
  992. // If the connection in currently open (or in a reopening state) reset the close
  993. // timeout since we have just received data. This check is necessary so
  994. // that we don't reset the timeout on an explicitly disconnected connection.
  995. if (this.socket.connected || this.socket.connecting || this.socket.reconnecting) {
  996. this.setCloseTimeout();
  997. }
  998. if (data !== '') {
  999. // todo: we should only do decodePayload for xhr transports
  1000. var msgs = io.parser.decodePayload(data);
  1001. if (msgs && msgs.length) {
  1002. for (var i = 0, l = msgs.length; i < l; i++) {
  1003. this.onPacket(msgs[i]);
  1004. }
  1005. }
  1006. }
  1007. return this;
  1008. };
  1009. /**
  1010. * Handles packets.
  1011. *
  1012. * @api private
  1013. */
  1014. Transport.prototype.onPacket = function (packet) {
  1015. this.socket.setHeartbeatTimeout();
  1016. if (packet.type == 'heartbeat') {
  1017. return this.onHeartbeat();
  1018. }
  1019. if (packet.type == 'connect' && packet.endpoint == '') {
  1020. this.onConnect();
  1021. }
  1022. if (packet.type == 'error' && packet.advice == 'reconnect') {
  1023. this.open = false;
  1024. }
  1025. this.socket.onPacket(packet);
  1026. return this;
  1027. };
  1028. /**
  1029. * Sets close timeout
  1030. *
  1031. * @api private
  1032. */
  1033. Transport.prototype.setCloseTimeout = function () {
  1034. if (!this.closeTimeout) {
  1035. var self = this;
  1036. this.closeTimeout = setTimeout(function () {
  1037. self.onDisconnect();
  1038. }, this.socket.closeTimeout);
  1039. }
  1040. };
  1041. /**
  1042. * Called when transport disconnects.
  1043. *
  1044. * @api private
  1045. */
  1046. Transport.prototype.onDisconnect = function () {
  1047. if (this.close && this.open) this.close();
  1048. this.clearTimeouts();
  1049. this.socket.onDisconnect();
  1050. return this;
  1051. };
  1052. /**
  1053. * Called when transport connects
  1054. *
  1055. * @api private
  1056. */
  1057. Transport.prototype.onConnect = function () {
  1058. this.socket.onConnect();
  1059. return this;
  1060. }
  1061. /**
  1062. * Clears close timeout
  1063. *
  1064. * @api private
  1065. */
  1066. Transport.prototype.clearCloseTimeout = function () {
  1067. if (this.closeTimeout) {
  1068. clearTimeout(this.closeTimeout);
  1069. this.closeTimeout = null;
  1070. }
  1071. };
  1072. /**
  1073. * Clear timeouts
  1074. *
  1075. * @api private
  1076. */
  1077. Transport.prototype.clearTimeouts = function () {
  1078. this.clearCloseTimeout();
  1079. if (this.reopenTimeout) {
  1080. clearTimeout(this.reopenTimeout);
  1081. }
  1082. };
  1083. /**
  1084. * Sends a packet
  1085. *
  1086. * @param {Object} packet object.
  1087. * @api private
  1088. */
  1089. Transport.prototype.packet = function (packet) {
  1090. this.send(io.parser.encodePacket(packet));
  1091. };
  1092. /**
  1093. * Send the received heartbeat message back to server. So the server
  1094. * knows we are still connected.
  1095. *
  1096. * @param {String} heartbeat Heartbeat response from the server.
  1097. * @api private
  1098. */
  1099. Transport.prototype.onHeartbeat = function (heartbeat) {
  1100. this.packet({ type: 'heartbeat' });
  1101. };
  1102. /**
  1103. * Called when the transport opens.
  1104. *
  1105. * @api private
  1106. */
  1107. Transport.prototype.onOpen = function () {
  1108. this.open = true;
  1109. this.clearCloseTimeout();
  1110. this.socket.onOpen();
  1111. };
  1112. /**
  1113. * Notifies the base when the connection with the Socket.IO server
  1114. * has been disconnected.
  1115. *
  1116. * @api private
  1117. */
  1118. Transport.prototype.onClose = function () {
  1119. var self = this;
  1120. /* FIXME: reopen delay causing a infinit loop
  1121. this.reopenTimeout = setTimeout(function () {
  1122. self.open();
  1123. }, this.socket.options['reopen delay']);*/
  1124. this.open = false;
  1125. this.socket.onClose();
  1126. this.onDisconnect();
  1127. };
  1128. /**
  1129. * Generates a connection url based on the Socket.IO URL Protocol.
  1130. * See <https://github.com/learnboost/socket.io-node/> for more details.
  1131. *
  1132. * @returns {String} Connection url
  1133. * @api private
  1134. */
  1135. Transport.prototype.prepareUrl = function () {
  1136. var options = this.socket.options;
  1137. return this.scheme() + '://'
  1138. + options.host + ':' + options.port + '/'
  1139. + options.resource + '/' + io.protocol
  1140. + '/' + this.name + '/' + this.sessid;
  1141. };
  1142. /**
  1143. * Checks if the transport is ready to start a connection.
  1144. *
  1145. * @param {Socket} socket The socket instance that needs a transport
  1146. * @param {Function} fn The callback
  1147. * @api private
  1148. */
  1149. Transport.prototype.ready = function (socket, fn) {
  1150. fn.call(this);
  1151. };
  1152. })(
  1153. 'undefined' != typeof io ? io : module.exports
  1154. , 'undefined' != typeof io ? io : module.parent.exports
  1155. );
  1156. /**
  1157. * socket.io
  1158. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  1159. * MIT Licensed
  1160. */
  1161. (function (exports, io, global) {
  1162. /**
  1163. * Expose constructor.
  1164. */
  1165. exports.Socket = Socket;
  1166. /**
  1167. * Create a new `Socket.IO client` which can establish a persistent
  1168. * connection with a Socket.IO enabled server.
  1169. *
  1170. * @api public
  1171. */
  1172. function Socket (options) {
  1173. this.options = {
  1174. port: 80
  1175. , secure: false
  1176. , document: 'document' in global ? document : false
  1177. , resource: 'socket.io'
  1178. , transports: io.transports
  1179. , 'connect timeout': 10000
  1180. , 'try multiple transports': true
  1181. , 'reconnect': true
  1182. , 'reconnection delay': 500
  1183. , 'reconnection limit': Infinity
  1184. , 'reopen delay': 3000
  1185. , 'max reconnection attempts': 10
  1186. , 'sync disconnect on unload': true
  1187. , 'auto connect': true
  1188. , 'flash policy port': 10843
  1189. };
  1190. io.util.merge(this.options, options);
  1191. this.connected = false;
  1192. this.open = false;
  1193. this.connecting = false;
  1194. this.reconnecting = false;
  1195. this.namespaces = {};
  1196. this.buffer = [];
  1197. this.doBuffer = false;
  1198. if (this.options['sync disconnect on unload'] &&
  1199. (!this.isXDomain() || io.util.ua.hasCORS)) {
  1200. var self = this;
  1201. io.util.on(global, 'unload', function () {
  1202. self.disconnectSync();
  1203. }, false);
  1204. }
  1205. if (this.options['auto connect']) {
  1206. this.connect();
  1207. }
  1208. };
  1209. /**
  1210. * Apply EventEmitter mixin.
  1211. */
  1212. io.util.mixin(Socket, io.EventEmitter);
  1213. /**
  1214. * Returns a namespace listener/emitter for this socket
  1215. *
  1216. * @api public
  1217. */
  1218. Socket.prototype.of = function (name) {
  1219. if (!this.namespaces[name]) {
  1220. this.namespaces[name] = new io.SocketNamespace(this, name);
  1221. if (name !== '') {
  1222. this.namespaces[name].packet({ type: 'connect' });
  1223. }
  1224. }
  1225. return this.namespaces[name];
  1226. };
  1227. /**
  1228. * Emits the given event to the Socket and all namespaces
  1229. *
  1230. * @api private
  1231. */
  1232. Socket.prototype.publish = function () {
  1233. this.emit.apply(this, arguments);
  1234. var nsp;
  1235. for (var i in this.namespaces) {
  1236. if (this.namespaces.hasOwnProperty(i)) {
  1237. nsp = this.of(i);
  1238. nsp.$emit.apply(nsp, arguments);
  1239. }
  1240. }
  1241. };
  1242. /**
  1243. * Performs the handshake
  1244. *
  1245. * @api private
  1246. */
  1247. function empty () { };
  1248. Socket.prototype.handshake = function (fn) {
  1249. var self = this
  1250. , options = this.options;
  1251. function complete (data) {
  1252. if (data instanceof Error) {
  1253. self.onError(data.message);
  1254. } else {
  1255. fn.apply(null, data.split(':'));
  1256. }
  1257. };
  1258. var url = [
  1259. 'http' + (options.secure ? 's' : '') + ':/'
  1260. , options.host + ':' + options.port
  1261. , options.resource
  1262. , io.protocol
  1263. , io.util.query(this.options.query, 't=' + +new Date)
  1264. ].join('/');
  1265. if (this.isXDomain() && !io.util.ua.hasCORS) {
  1266. var insertAt = document.getElementsByTagName('script')[0]
  1267. , script = document.createElement('script');
  1268. script.src = url + '&jsonp=' + io.j.length;
  1269. insertAt.parentNode.insertBefore(script, insertAt);
  1270. io.j.push(function (data) {
  1271. complete(data);
  1272. script.parentNode.removeChild(script);
  1273. });
  1274. } else {
  1275. var xhr = io.util.request();
  1276. xhr.open('GET', url, true);
  1277. xhr.withCredentials = true;
  1278. xhr.onreadystatechange = function () {
  1279. if (xhr.readyState == 4) {
  1280. xhr.onreadystatechange = empty;
  1281. if (xhr.status == 200) {
  1282. complete(xhr.responseText);
  1283. } else {
  1284. !self.reconnecting && self.onError(xhr.responseText);
  1285. }
  1286. }
  1287. };
  1288. xhr.send(null);
  1289. }
  1290. };
  1291. /**
  1292. * Find an available transport based on the options supplied in the constructor.
  1293. *
  1294. * @api private
  1295. */
  1296. Socket.prototype.getTransport = function (override) {
  1297. var transports = override || this.transports, match;
  1298. for (var i = 0, transport; transport = transports[i]; i++) {
  1299. if (io.Transport[transport]
  1300. && io.Transport[transport].check(this)
  1301. && (!this.isXDomain() || io.Transport[transport].xdomainCheck())) {
  1302. return new io.Transport[transport](this, this.sessionid);
  1303. }
  1304. }
  1305. return null;
  1306. };
  1307. /**
  1308. * Connects to the server.
  1309. *
  1310. * @param {Function} [fn] Callback.
  1311. * @returns {io.Socket}
  1312. * @api public
  1313. */
  1314. Socket.prototype.connect = function (fn) {
  1315. if (this.connecting) {
  1316. return this;
  1317. }
  1318. var self = this;
  1319. this.handshake(function (sid, heartbeat, close, transports) {
  1320. self.sessionid = sid;
  1321. self.closeTimeout = close * 1000;
  1322. self.heartbeatTimeout = heartbeat * 1000;
  1323. self.transports = transports ? io.util.intersect(
  1324. transports.split(',')
  1325. , self.options.transports
  1326. ) : self.options.transports;
  1327. self.setHeartbeatTimeout();
  1328. function connect (transports){
  1329. if (self.transport) self.transport.clearTimeouts();
  1330. self.transport = self.getTransport(transports);
  1331. if (!self.transport) return self.publish('connect_failed');
  1332. // once the transport is ready
  1333. self.transport.ready(self, function () {
  1334. self.connecting = true;
  1335. self.publish('connecting', self.transport.name);
  1336. self.transport.open();
  1337. if (self.options['connect timeout']) {
  1338. self.connectTimeoutTimer = setTimeout(function () {
  1339. if (!self.connected) {
  1340. self.connecting = false;
  1341. if (self.options['try multiple transports']) {
  1342. if (!self.remainingTransports) {
  1343. self.remainingTransports = self.transports.slice(0);
  1344. }
  1345. var remaining = self.remainingTransports;
  1346. while (remaining.length > 0 && remaining.splice(0,1)[0] !=
  1347. self.transport.name) {}
  1348. if (remaining.length){
  1349. connect(remaining);
  1350. } else {
  1351. self.publish('connect_failed');
  1352. }
  1353. }
  1354. }
  1355. }, self.options['connect timeout']);
  1356. }
  1357. });
  1358. }
  1359. connect(self.transports);
  1360. self.once('connect', function (){
  1361. clearTimeout(self.connectTimeoutTimer);
  1362. fn && typeof fn == 'function' && fn();
  1363. });
  1364. });
  1365. return this;
  1366. };
  1367. /**
  1368. * Clears and sets a new heartbeat timeout using the value given by the
  1369. * server during the handshake.
  1370. *
  1371. * @api private
  1372. */
  1373. Socket.prototype.setHeartbeatTimeout = function () {
  1374. clearTimeout(this.heartbeatTimeoutTimer);
  1375. var self = this;
  1376. this.heartbeatTimeoutTimer = setTimeout(function () {
  1377. self.transport.onClose();
  1378. }, this.heartbeatTimeout);
  1379. };
  1380. /**
  1381. * Sends a message.
  1382. *
  1383. * @param {Object} data packet.
  1384. * @returns {io.Socket}
  1385. * @api public
  1386. */
  1387. Socket.prototype.packet = function (data) {
  1388. if (this.connected && !this.doBuffer) {
  1389. this.transport.packet(data);
  1390. } else {
  1391. this.buffer.push(data);
  1392. }
  1393. return this;
  1394. };
  1395. /**
  1396. * Sets buffer state
  1397. *
  1398. * @api private
  1399. */
  1400. Socket.prototype.setBuffer = function (v) {
  1401. this.doBuffer = v;
  1402. if (!v && this.connected && this.buffer.length) {
  1403. this.transport.payload(this.buffer);
  1404. this.buffer = [];
  1405. }
  1406. };
  1407. /**
  1408. * Disconnect the established connect.
  1409. *
  1410. * @returns {io.Socket}
  1411. * @api public
  1412. */
  1413. Socket.prototype.disconnect = function () {
  1414. if (this.connected || this.connecting) {
  1415. if (this.open) {
  1416. this.of('').packet({ type: 'disconnect' });
  1417. }
  1418. // handle disconnection immediately
  1419. this.onDisconnect('booted');
  1420. }
  1421. return this;
  1422. };
  1423. /**
  1424. * Disconnects the socket with a sync XHR.
  1425. *
  1426. * @api private
  1427. */
  1428. Socket.prototype.disconnectSync = function () {
  1429. // ensure disconnection
  1430. var xhr = io.util.request()
  1431. , uri = this.resource + '/' + io.protocol + '/' + this.sessionid;
  1432. xhr.open('GET', uri, true);
  1433. // handle disconnection immediately
  1434. this.onDisconnect('booted');
  1435. };
  1436. /**
  1437. * Check if we need to use cross domain enabled transports. Cross domain would
  1438. * be a different port or different domain name.
  1439. *
  1440. * @returns {Boolean}
  1441. * @api private
  1442. */
  1443. Socket.prototype.isXDomain = function () {
  1444. var port = global.location.port ||
  1445. ('https:' == global.location.protocol ? 443 : 80);
  1446. return this.options.host !== global.location.hostname
  1447. || this.options.port != port;
  1448. };
  1449. /**
  1450. * Called upon handshake.
  1451. *
  1452. * @api private
  1453. */
  1454. Socket.prototype.onConnect = function () {
  1455. if (!this.connected) {
  1456. this.connected = true;
  1457. this.connecting = false;
  1458. if (!this.doBuffer) {
  1459. // make sure to flush the buffer
  1460. this.setBuffer(false);
  1461. }
  1462. this.emit('connect');
  1463. }
  1464. };
  1465. /**
  1466. * Called when the transport opens
  1467. *
  1468. * @api private
  1469. */
  1470. Socket.prototype.onOpen = function () {
  1471. this.open = true;
  1472. };
  1473. /**
  1474. * Called when the transport closes.
  1475. *
  1476. * @api private
  1477. */
  1478. Socket.prototype.onClose = function () {
  1479. this.open = false;
  1480. clearTimeout(this.heartbeatTimeoutTimer);
  1481. };
  1482. /**
  1483. * Called when the transport first opens a connection
  1484. *
  1485. * @param text
  1486. */
  1487. Socket.prototype.onPacket = function (packet) {
  1488. this.of(packet.endpoint).onPacket(packet);
  1489. };
  1490. /**
  1491. * Handles an error.
  1492. *
  1493. * @api private
  1494. */
  1495. Socket.prototype.onError = function (err) {
  1496. if (err && err.advice) {
  1497. if (err.advice === 'reconnect' && (this.connected || this.connecting)) {
  1498. this.disconnect();
  1499. if (this.options.reconnect) {
  1500. this.reconnect();
  1501. }
  1502. }
  1503. }
  1504. this.publish('error', err && err.reason ? err.reason : err);
  1505. };
  1506. /**
  1507. * Called when the transport disconnects.
  1508. *
  1509. * @api private
  1510. */
  1511. Socket.prototype.onDisconnect = function (reason) {
  1512. var wasConnected = this.connected
  1513. , wasConnecting = this.connecting;
  1514. this.connected = false;
  1515. this.connecting = false;
  1516. this.open = false;
  1517. if (wasConnected || wasConnecting) {
  1518. this.transport.close();
  1519. this.transport.clearTimeouts();
  1520. if (wasConnected) {
  1521. this.publish('disconnect', reason);
  1522. if ('booted' != reason && this.options.reconnect && !this.reconnecting) {
  1523. this.reconnect();
  1524. }
  1525. }
  1526. }
  1527. };
  1528. /**
  1529. * Called upon reconnection.
  1530. *
  1531. * @api private
  1532. */
  1533. Socket.prototype.reconnect = function () {
  1534. this.reconnecting = true;
  1535. this.reconnectionAttempts = 0;
  1536. this.reconnectionDelay = this.options['reconnection delay'];
  1537. var self = this
  1538. , maxAttempts = this.options['max reconnection attempts']
  1539. , tryMultiple = this.options['try multiple transports']
  1540. , limit = this.options['reconnection limit'];
  1541. function reset () {
  1542. if (self.connected) {
  1543. for (var i in self.namespaces) {
  1544. if (self.namespaces.hasOwnProperty(i) && '' !== i) {
  1545. self.namespaces[i].packet({ type: 'connect' });
  1546. }
  1547. }
  1548. self.publish('reconnect', self.transport.name, self.reconnectionAttempts);
  1549. }
  1550. clearTimeout(self.reconnectionTimer);
  1551. self.removeListener('connect_failed', maybeReconnect);
  1552. self.removeListener('connect', maybeReconnect);
  1553. self.reconnecting = false;
  1554. delete self.reconnectionAttempts;
  1555. delete self.reconnectionDelay;
  1556. delete self.reconnectionTimer;
  1557. delete self.redoTransports;
  1558. self.options['try multiple transports'] = tryMultiple;
  1559. };
  1560. function maybeReconnect () {
  1561. if (!self.reconnecting) {
  1562. return;
  1563. }
  1564. if (self.connected) {
  1565. return reset();
  1566. };
  1567. if (self.connecting && self.reconnecting) {
  1568. return self.reconnectionTimer = setTimeout(maybeReconnect, 1000);
  1569. }
  1570. if (self.reconnectionAttempts++ >= maxAttempts) {
  1571. if (!self.redoTransports) {
  1572. self.on('connect_failed', maybeReconnect);
  1573. self.options['try multiple transports'] = true;
  1574. self.transport = self.getTransport();
  1575. self.redoTransports = true;
  1576. self.connect();
  1577. } else {
  1578. self.publish('reconnect_failed');
  1579. reset();
  1580. }
  1581. } else {
  1582. if (self.reconnectionDelay < limit) {
  1583. self.reconnectionDelay *= 2; // exponential back off
  1584. }
  1585. self.connect();
  1586. self.publish('reconnecting', self.reconnectionDelay, self.reconnectionAttempts);
  1587. self.reconnectionTimer = setTimeout(maybeReconnect, self.reconnectionDelay);
  1588. }
  1589. };
  1590. this.options['try multiple transports'] = false;
  1591. this.reconnectionTimer = setTimeout(maybeReconnect, this.reconnectionDelay);
  1592. this.on('connect', maybeReconnect);
  1593. };
  1594. })(
  1595. 'undefined' != typeof io ? io : module.exports
  1596. , 'undefined' != typeof io ? io : module.parent.exports
  1597. , this
  1598. );
  1599. /**
  1600. * socket.io
  1601. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  1602. * MIT Licensed
  1603. */
  1604. (function (exports, io) {
  1605. /**
  1606. * Expose constructor.
  1607. */
  1608. exports.SocketNamespace = SocketNamespace;
  1609. /**
  1610. * Socket namespace constructor.
  1611. *
  1612. * @constructor
  1613. * @api public
  1614. */
  1615. function SocketNamespace (socket, name) {
  1616. this.socket = socket;
  1617. this.name = name || '';
  1618. this.flags = {};
  1619. this.json = new Flag(this, 'json');
  1620. this.ackPackets = 0;
  1621. this.acks = {};
  1622. };
  1623. /**
  1624. * Apply EventEmitter mixin.
  1625. */
  1626. io.util.mixin(SocketNamespace, io.EventEmitter);
  1627. /**
  1628. * Copies emit since we override it
  1629. *
  1630. * @api private
  1631. */
  1632. SocketNamespace.prototype.$emit = io.EventEmitter.prototype.emit;
  1633. /**
  1634. * Creates a new namespace, by proxying the request to the socket. This
  1635. * allows us to use the synax as we do on the server.
  1636. *
  1637. * @api public
  1638. */
  1639. SocketNamespace.prototype.of = function () {
  1640. return this.socket.of.apply(this.socket, arguments);
  1641. };
  1642. /**
  1643. * Sends a packet.
  1644. *
  1645. * @api private
  1646. */
  1647. SocketNamespace.prototype.packet = function (packet) {
  1648. packet.endpoint = this.name;
  1649. this.socket.packet(packet);
  1650. this.flags = {};
  1651. return this;
  1652. };
  1653. /**
  1654. * Sends a message
  1655. *
  1656. * @api public
  1657. */
  1658. SocketNamespace.prototype.send = function (data, fn) {
  1659. var packet = {
  1660. type: this.flags.json ? 'json' : 'message'
  1661. , data: data
  1662. };
  1663. if ('function' == typeof fn) {
  1664. packet.id = ++this.ackPackets;
  1665. packet.ack = true;
  1666. this.acks[packet.id] = fn;
  1667. }
  1668. return this.packet(packet);
  1669. };
  1670. /**
  1671. * Emits an event
  1672. *
  1673. * @api public
  1674. */
  1675. SocketNamespace.prototype.emit = function (name) {
  1676. var args = Array.prototype.slice.call(arguments, 1)
  1677. , lastArg = args[args.length - 1]
  1678. , packet = {
  1679. type: 'event'
  1680. , name: name
  1681. };
  1682. if ('function' == typeof lastArg) {
  1683. packet.id = ++this.ackPackets;
  1684. packet.ack = 'data';
  1685. this.acks[packet.id] = lastArg;
  1686. args = args.slice(0, args.length - 1);
  1687. }
  1688. packet.args = args;
  1689. return this.packet(packet);
  1690. };
  1691. /**
  1692. * Disconnects the namespace
  1693. *
  1694. * @api private
  1695. */
  1696. SocketNamespace.prototype.disconnect = function () {
  1697. if (this.name === '') {
  1698. this.socket.disconnect();
  1699. } else {
  1700. this.packet({ type: 'disconnect' });
  1701. this.$emit('disconnect');
  1702. }
  1703. return this;
  1704. };
  1705. /**
  1706. * Handles a packet
  1707. *
  1708. * @api private
  1709. */
  1710. SocketNamespace.prototype.onPacket = function (packet) {
  1711. var self = this;
  1712. function ack () {
  1713. self.packet({
  1714. type: 'ack'
  1715. , args: io.util.toArray(arguments)
  1716. , ackId: packet.id
  1717. });
  1718. };
  1719. switch (packet.type) {
  1720. case 'connect':
  1721. this.$emit('connect');
  1722. break;
  1723. case 'disconnect':
  1724. if (this.name === '') {
  1725. this.socket.onDisconnect(packet.reason || 'booted');
  1726. } else {
  1727. this.$emit('disconnect', packet.reason);
  1728. }
  1729. break;
  1730. case 'message':
  1731. case 'json':
  1732. var params = ['message', packet.data];
  1733. if (packet.ack == 'data') {
  1734. params.push(ack);
  1735. } else if (packet.ack) {
  1736. this.packet({ type: 'ack', ackId: packet.id });
  1737. }
  1738. this.$emit.apply(this, params);
  1739. break;
  1740. case 'event':
  1741. var params = [packet.name].concat(packet.args);
  1742. if (packet.ack == 'data')
  1743. params.push(ack);
  1744. this

Large files files are truncated, but you can click here to view the full file