livereload.js 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204
  1. (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  2. (function() {
  3. var Connector, PROTOCOL_6, PROTOCOL_7, Parser, Version, ref;
  4. ref = require('./protocol'), Parser = ref.Parser, PROTOCOL_6 = ref.PROTOCOL_6, PROTOCOL_7 = ref.PROTOCOL_7;
  5. Version = "2.4.0";
  6. exports.Connector = Connector = (function() {
  7. function Connector(options, WebSocket, Timer, handlers) {
  8. var path;
  9. this.options = options;
  10. this.WebSocket = WebSocket;
  11. this.Timer = Timer;
  12. this.handlers = handlers;
  13. path = this.options.path ? "" + this.options.path : "livereload";
  14. this._uri = "ws" + (this.options.https ? "s" : "") + "://" + this.options.host + ":" + this.options.port + "/" + path;
  15. this._nextDelay = this.options.mindelay;
  16. this._connectionDesired = false;
  17. this.protocol = 0;
  18. this.protocolParser = new Parser({
  19. connected: (function(_this) {
  20. return function(protocol) {
  21. _this.protocol = protocol;
  22. _this._handshakeTimeout.stop();
  23. _this._nextDelay = _this.options.mindelay;
  24. _this._disconnectionReason = 'broken';
  25. return _this.handlers.connected(_this.protocol);
  26. };
  27. })(this),
  28. error: (function(_this) {
  29. return function(e) {
  30. _this.handlers.error(e);
  31. return _this._closeOnError();
  32. };
  33. })(this),
  34. message: (function(_this) {
  35. return function(message) {
  36. return _this.handlers.message(message);
  37. };
  38. })(this)
  39. });
  40. this._handshakeTimeout = new this.Timer((function(_this) {
  41. return function() {
  42. if (!_this._isSocketConnected()) {
  43. return;
  44. }
  45. _this._disconnectionReason = 'handshake-timeout';
  46. return _this.socket.close();
  47. };
  48. })(this));
  49. this._reconnectTimer = new this.Timer((function(_this) {
  50. return function() {
  51. if (!_this._connectionDesired) {
  52. return;
  53. }
  54. return _this.connect();
  55. };
  56. })(this));
  57. this.connect();
  58. }
  59. Connector.prototype._isSocketConnected = function() {
  60. return this.socket && this.socket.readyState === this.WebSocket.OPEN;
  61. };
  62. Connector.prototype.connect = function() {
  63. this._connectionDesired = true;
  64. if (this._isSocketConnected()) {
  65. return;
  66. }
  67. this._reconnectTimer.stop();
  68. this._disconnectionReason = 'cannot-connect';
  69. this.protocolParser.reset();
  70. this.handlers.connecting();
  71. this.socket = new this.WebSocket(this._uri);
  72. this.socket.onopen = (function(_this) {
  73. return function(e) {
  74. return _this._onopen(e);
  75. };
  76. })(this);
  77. this.socket.onclose = (function(_this) {
  78. return function(e) {
  79. return _this._onclose(e);
  80. };
  81. })(this);
  82. this.socket.onmessage = (function(_this) {
  83. return function(e) {
  84. return _this._onmessage(e);
  85. };
  86. })(this);
  87. return this.socket.onerror = (function(_this) {
  88. return function(e) {
  89. return _this._onerror(e);
  90. };
  91. })(this);
  92. };
  93. Connector.prototype.disconnect = function() {
  94. this._connectionDesired = false;
  95. this._reconnectTimer.stop();
  96. if (!this._isSocketConnected()) {
  97. return;
  98. }
  99. this._disconnectionReason = 'manual';
  100. return this.socket.close();
  101. };
  102. Connector.prototype._scheduleReconnection = function() {
  103. if (!this._connectionDesired) {
  104. return;
  105. }
  106. if (!this._reconnectTimer.running) {
  107. this._reconnectTimer.start(this._nextDelay);
  108. return this._nextDelay = Math.min(this.options.maxdelay, this._nextDelay * 2);
  109. }
  110. };
  111. Connector.prototype.sendCommand = function(command) {
  112. if (this.protocol == null) {
  113. return;
  114. }
  115. return this._sendCommand(command);
  116. };
  117. Connector.prototype._sendCommand = function(command) {
  118. return this.socket.send(JSON.stringify(command));
  119. };
  120. Connector.prototype._closeOnError = function() {
  121. this._handshakeTimeout.stop();
  122. this._disconnectionReason = 'error';
  123. return this.socket.close();
  124. };
  125. Connector.prototype._onopen = function(e) {
  126. var hello;
  127. this.handlers.socketConnected();
  128. this._disconnectionReason = 'handshake-failed';
  129. hello = {
  130. command: 'hello',
  131. protocols: [PROTOCOL_6, PROTOCOL_7]
  132. };
  133. hello.ver = Version;
  134. if (this.options.ext) {
  135. hello.ext = this.options.ext;
  136. }
  137. if (this.options.extver) {
  138. hello.extver = this.options.extver;
  139. }
  140. if (this.options.snipver) {
  141. hello.snipver = this.options.snipver;
  142. }
  143. this._sendCommand(hello);
  144. return this._handshakeTimeout.start(this.options.handshake_timeout);
  145. };
  146. Connector.prototype._onclose = function(e) {
  147. this.protocol = 0;
  148. this.handlers.disconnected(this._disconnectionReason, this._nextDelay);
  149. return this._scheduleReconnection();
  150. };
  151. Connector.prototype._onerror = function(e) {};
  152. Connector.prototype._onmessage = function(e) {
  153. return this.protocolParser.process(e.data);
  154. };
  155. return Connector;
  156. })();
  157. }).call(this);
  158. },{"./protocol":6}],2:[function(require,module,exports){
  159. (function() {
  160. var CustomEvents;
  161. CustomEvents = {
  162. bind: function(element, eventName, handler) {
  163. if (element.addEventListener) {
  164. return element.addEventListener(eventName, handler, false);
  165. } else if (element.attachEvent) {
  166. element[eventName] = 1;
  167. return element.attachEvent('onpropertychange', function(event) {
  168. if (event.propertyName === eventName) {
  169. return handler();
  170. }
  171. });
  172. } else {
  173. throw new Error("Attempt to attach custom event " + eventName + " to something which isn't a DOMElement");
  174. }
  175. },
  176. fire: function(element, eventName) {
  177. var event;
  178. if (element.addEventListener) {
  179. event = document.createEvent('HTMLEvents');
  180. event.initEvent(eventName, true, true);
  181. return document.dispatchEvent(event);
  182. } else if (element.attachEvent) {
  183. if (element[eventName]) {
  184. return element[eventName]++;
  185. }
  186. } else {
  187. throw new Error("Attempt to fire custom event " + eventName + " on something which isn't a DOMElement");
  188. }
  189. }
  190. };
  191. exports.bind = CustomEvents.bind;
  192. exports.fire = CustomEvents.fire;
  193. }).call(this);
  194. },{}],3:[function(require,module,exports){
  195. (function() {
  196. var LessPlugin;
  197. module.exports = LessPlugin = (function() {
  198. LessPlugin.identifier = 'less';
  199. LessPlugin.version = '1.0';
  200. function LessPlugin(window, host) {
  201. this.window = window;
  202. this.host = host;
  203. }
  204. LessPlugin.prototype.reload = function(path, options) {
  205. if (this.window.less && this.window.less.refresh) {
  206. if (path.match(/\.less$/i)) {
  207. return this.reloadLess(path);
  208. }
  209. if (options.originalPath.match(/\.less$/i)) {
  210. return this.reloadLess(options.originalPath);
  211. }
  212. }
  213. return false;
  214. };
  215. LessPlugin.prototype.reloadLess = function(path) {
  216. var i, len, link, links;
  217. links = (function() {
  218. var i, len, ref, results;
  219. ref = document.getElementsByTagName('link');
  220. results = [];
  221. for (i = 0, len = ref.length; i < len; i++) {
  222. link = ref[i];
  223. if (link.href && link.rel.match(/^stylesheet\/less$/i) || (link.rel.match(/stylesheet/i) && link.type.match(/^text\/(x-)?less$/i))) {
  224. results.push(link);
  225. }
  226. }
  227. return results;
  228. })();
  229. if (links.length === 0) {
  230. return false;
  231. }
  232. for (i = 0, len = links.length; i < len; i++) {
  233. link = links[i];
  234. link.href = this.host.generateCacheBustUrl(link.href);
  235. }
  236. this.host.console.log("LiveReload is asking LESS to recompile all stylesheets");
  237. this.window.less.refresh(true);
  238. return true;
  239. };
  240. LessPlugin.prototype.analyze = function() {
  241. return {
  242. disable: !!(this.window.less && this.window.less.refresh)
  243. };
  244. };
  245. return LessPlugin;
  246. })();
  247. }).call(this);
  248. },{}],4:[function(require,module,exports){
  249. (function() {
  250. var Connector, LiveReload, Options, ProtocolError, Reloader, Timer,
  251. hasProp = {}.hasOwnProperty;
  252. Connector = require('./connector').Connector;
  253. Timer = require('./timer').Timer;
  254. Options = require('./options').Options;
  255. Reloader = require('./reloader').Reloader;
  256. ProtocolError = require('./protocol').ProtocolError;
  257. exports.LiveReload = LiveReload = (function() {
  258. function LiveReload(window1) {
  259. var k, ref, v;
  260. this.window = window1;
  261. this.listeners = {};
  262. this.plugins = [];
  263. this.pluginIdentifiers = {};
  264. this.console = this.window.console && this.window.console.log && this.window.console.error ? this.window.location.href.match(/LR-verbose/) ? this.window.console : {
  265. log: function() {},
  266. error: this.window.console.error.bind(this.window.console)
  267. } : {
  268. log: function() {},
  269. error: function() {}
  270. };
  271. if (!(this.WebSocket = this.window.WebSocket || this.window.MozWebSocket)) {
  272. this.console.error("LiveReload disabled because the browser does not seem to support web sockets");
  273. return;
  274. }
  275. if ('LiveReloadOptions' in window) {
  276. this.options = new Options();
  277. ref = window['LiveReloadOptions'];
  278. for (k in ref) {
  279. if (!hasProp.call(ref, k)) continue;
  280. v = ref[k];
  281. this.options.set(k, v);
  282. }
  283. } else {
  284. this.options = Options.extract(this.window.document);
  285. if (!this.options) {
  286. this.console.error("LiveReload disabled because it could not find its own <SCRIPT> tag");
  287. return;
  288. }
  289. }
  290. this.reloader = new Reloader(this.window, this.console, Timer);
  291. this.connector = new Connector(this.options, this.WebSocket, Timer, {
  292. connecting: (function(_this) {
  293. return function() {};
  294. })(this),
  295. socketConnected: (function(_this) {
  296. return function() {};
  297. })(this),
  298. connected: (function(_this) {
  299. return function(protocol) {
  300. var base;
  301. if (typeof (base = _this.listeners).connect === "function") {
  302. base.connect();
  303. }
  304. _this.log("LiveReload is connected to " + _this.options.host + ":" + _this.options.port + " (protocol v" + protocol + ").");
  305. return _this.analyze();
  306. };
  307. })(this),
  308. error: (function(_this) {
  309. return function(e) {
  310. if (e instanceof ProtocolError) {
  311. if (typeof console !== "undefined" && console !== null) {
  312. return console.log(e.message + ".");
  313. }
  314. } else {
  315. if (typeof console !== "undefined" && console !== null) {
  316. return console.log("LiveReload internal error: " + e.message);
  317. }
  318. }
  319. };
  320. })(this),
  321. disconnected: (function(_this) {
  322. return function(reason, nextDelay) {
  323. var base;
  324. if (typeof (base = _this.listeners).disconnect === "function") {
  325. base.disconnect();
  326. }
  327. switch (reason) {
  328. case 'cannot-connect':
  329. return _this.log("LiveReload cannot connect to " + _this.options.host + ":" + _this.options.port + ", will retry in " + nextDelay + " sec.");
  330. case 'broken':
  331. return _this.log("LiveReload disconnected from " + _this.options.host + ":" + _this.options.port + ", reconnecting in " + nextDelay + " sec.");
  332. case 'handshake-timeout':
  333. return _this.log("LiveReload cannot connect to " + _this.options.host + ":" + _this.options.port + " (handshake timeout), will retry in " + nextDelay + " sec.");
  334. case 'handshake-failed':
  335. return _this.log("LiveReload cannot connect to " + _this.options.host + ":" + _this.options.port + " (handshake failed), will retry in " + nextDelay + " sec.");
  336. case 'manual':
  337. break;
  338. case 'error':
  339. break;
  340. default:
  341. return _this.log("LiveReload disconnected from " + _this.options.host + ":" + _this.options.port + " (" + reason + "), reconnecting in " + nextDelay + " sec.");
  342. }
  343. };
  344. })(this),
  345. message: (function(_this) {
  346. return function(message) {
  347. switch (message.command) {
  348. case 'reload':
  349. return _this.performReload(message);
  350. case 'alert':
  351. return _this.performAlert(message);
  352. }
  353. };
  354. })(this)
  355. });
  356. this.initialized = true;
  357. }
  358. LiveReload.prototype.on = function(eventName, handler) {
  359. return this.listeners[eventName] = handler;
  360. };
  361. LiveReload.prototype.log = function(message) {
  362. return this.console.log("" + message);
  363. };
  364. LiveReload.prototype.performReload = function(message) {
  365. var ref, ref1, ref2;
  366. this.log("LiveReload received reload request: " + (JSON.stringify(message, null, 2)));
  367. return this.reloader.reload(message.path, {
  368. liveCSS: (ref = message.liveCSS) != null ? ref : true,
  369. liveImg: (ref1 = message.liveImg) != null ? ref1 : true,
  370. reloadMissingCSS: (ref2 = message.reloadMissingCSS) != null ? ref2 : true,
  371. originalPath: message.originalPath || '',
  372. overrideURL: message.overrideURL || '',
  373. serverURL: "http://" + this.options.host + ":" + this.options.port
  374. });
  375. };
  376. LiveReload.prototype.performAlert = function(message) {
  377. return alert(message.message);
  378. };
  379. LiveReload.prototype.shutDown = function() {
  380. var base;
  381. if (!this.initialized) {
  382. return;
  383. }
  384. this.connector.disconnect();
  385. this.log("LiveReload disconnected.");
  386. return typeof (base = this.listeners).shutdown === "function" ? base.shutdown() : void 0;
  387. };
  388. LiveReload.prototype.hasPlugin = function(identifier) {
  389. return !!this.pluginIdentifiers[identifier];
  390. };
  391. LiveReload.prototype.addPlugin = function(pluginClass) {
  392. var plugin;
  393. if (!this.initialized) {
  394. return;
  395. }
  396. if (this.hasPlugin(pluginClass.identifier)) {
  397. return;
  398. }
  399. this.pluginIdentifiers[pluginClass.identifier] = true;
  400. plugin = new pluginClass(this.window, {
  401. _livereload: this,
  402. _reloader: this.reloader,
  403. _connector: this.connector,
  404. console: this.console,
  405. Timer: Timer,
  406. generateCacheBustUrl: (function(_this) {
  407. return function(url) {
  408. return _this.reloader.generateCacheBustUrl(url);
  409. };
  410. })(this)
  411. });
  412. this.plugins.push(plugin);
  413. this.reloader.addPlugin(plugin);
  414. };
  415. LiveReload.prototype.analyze = function() {
  416. var i, len, plugin, pluginData, pluginsData, ref;
  417. if (!this.initialized) {
  418. return;
  419. }
  420. if (!(this.connector.protocol >= 7)) {
  421. return;
  422. }
  423. pluginsData = {};
  424. ref = this.plugins;
  425. for (i = 0, len = ref.length; i < len; i++) {
  426. plugin = ref[i];
  427. pluginsData[plugin.constructor.identifier] = pluginData = (typeof plugin.analyze === "function" ? plugin.analyze() : void 0) || {};
  428. pluginData.version = plugin.constructor.version;
  429. }
  430. this.connector.sendCommand({
  431. command: 'info',
  432. plugins: pluginsData,
  433. url: this.window.location.href
  434. });
  435. };
  436. return LiveReload;
  437. })();
  438. }).call(this);
  439. },{"./connector":1,"./options":5,"./protocol":6,"./reloader":7,"./timer":9}],5:[function(require,module,exports){
  440. (function() {
  441. var Options;
  442. exports.Options = Options = (function() {
  443. function Options() {
  444. this.https = false;
  445. this.host = null;
  446. this.port = 35729;
  447. this.snipver = null;
  448. this.ext = null;
  449. this.extver = null;
  450. this.mindelay = 1000;
  451. this.maxdelay = 60000;
  452. this.handshake_timeout = 5000;
  453. }
  454. Options.prototype.set = function(name, value) {
  455. if (typeof value === 'undefined') {
  456. return;
  457. }
  458. if (!isNaN(+value)) {
  459. value = +value;
  460. }
  461. return this[name] = value;
  462. };
  463. return Options;
  464. })();
  465. Options.extract = function(document) {
  466. var element, i, j, keyAndValue, len, len1, m, mm, options, pair, ref, ref1, src;
  467. ref = document.getElementsByTagName('script');
  468. for (i = 0, len = ref.length; i < len; i++) {
  469. element = ref[i];
  470. if ((src = element.src) && (m = src.match(/^[^:]+:\/\/(.*)\/z?livereload\.js(?:\?(.*))?$/))) {
  471. options = new Options();
  472. options.https = src.indexOf("https") === 0;
  473. if (mm = m[1].match(/^([^\/:]+)(?::(\d+))?(\/+.*)?$/)) {
  474. options.host = mm[1];
  475. if (mm[2]) {
  476. options.port = parseInt(mm[2], 10);
  477. }
  478. }
  479. if (m[2]) {
  480. ref1 = m[2].split('&');
  481. for (j = 0, len1 = ref1.length; j < len1; j++) {
  482. pair = ref1[j];
  483. if ((keyAndValue = pair.split('=')).length > 1) {
  484. options.set(keyAndValue[0].replace(/-/g, '_'), keyAndValue.slice(1).join('='));
  485. }
  486. }
  487. }
  488. return options;
  489. }
  490. }
  491. return null;
  492. };
  493. }).call(this);
  494. },{}],6:[function(require,module,exports){
  495. (function() {
  496. var PROTOCOL_6, PROTOCOL_7, Parser, ProtocolError,
  497. indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
  498. exports.PROTOCOL_6 = PROTOCOL_6 = 'http://livereload.com/protocols/official-6';
  499. exports.PROTOCOL_7 = PROTOCOL_7 = 'http://livereload.com/protocols/official-7';
  500. exports.ProtocolError = ProtocolError = (function() {
  501. function ProtocolError(reason, data) {
  502. this.message = "LiveReload protocol error (" + reason + ") after receiving data: \"" + data + "\".";
  503. }
  504. return ProtocolError;
  505. })();
  506. exports.Parser = Parser = (function() {
  507. function Parser(handlers) {
  508. this.handlers = handlers;
  509. this.reset();
  510. }
  511. Parser.prototype.reset = function() {
  512. return this.protocol = null;
  513. };
  514. Parser.prototype.process = function(data) {
  515. var command, e, error, message, options, ref;
  516. try {
  517. if (this.protocol == null) {
  518. if (data.match(/^!!ver:([\d.]+)$/)) {
  519. this.protocol = 6;
  520. } else if (message = this._parseMessage(data, ['hello'])) {
  521. if (!message.protocols.length) {
  522. throw new ProtocolError("no protocols specified in handshake message");
  523. } else if (indexOf.call(message.protocols, PROTOCOL_7) >= 0) {
  524. this.protocol = 7;
  525. } else if (indexOf.call(message.protocols, PROTOCOL_6) >= 0) {
  526. this.protocol = 6;
  527. } else {
  528. throw new ProtocolError("no supported protocols found");
  529. }
  530. }
  531. return this.handlers.connected(this.protocol);
  532. } else if (this.protocol === 6) {
  533. message = JSON.parse(data);
  534. if (!message.length) {
  535. throw new ProtocolError("protocol 6 messages must be arrays");
  536. }
  537. command = message[0], options = message[1];
  538. if (command !== 'refresh') {
  539. throw new ProtocolError("unknown protocol 6 command");
  540. }
  541. return this.handlers.message({
  542. command: 'reload',
  543. path: options.path,
  544. liveCSS: (ref = options.apply_css_live) != null ? ref : true
  545. });
  546. } else {
  547. message = this._parseMessage(data, ['reload', 'alert']);
  548. return this.handlers.message(message);
  549. }
  550. } catch (error) {
  551. e = error;
  552. if (e instanceof ProtocolError) {
  553. return this.handlers.error(e);
  554. } else {
  555. throw e;
  556. }
  557. }
  558. };
  559. Parser.prototype._parseMessage = function(data, validCommands) {
  560. var e, error, message, ref;
  561. try {
  562. message = JSON.parse(data);
  563. } catch (error) {
  564. e = error;
  565. throw new ProtocolError('unparsable JSON', data);
  566. }
  567. if (!message.command) {
  568. throw new ProtocolError('missing "command" key', data);
  569. }
  570. if (ref = message.command, indexOf.call(validCommands, ref) < 0) {
  571. throw new ProtocolError("invalid command '" + message.command + "', only valid commands are: " + (validCommands.join(', ')) + ")", data);
  572. }
  573. return message;
  574. };
  575. return Parser;
  576. })();
  577. }).call(this);
  578. },{}],7:[function(require,module,exports){
  579. (function() {
  580. var IMAGE_STYLES, Reloader, numberOfMatchingSegments, pathFromUrl, pathsMatch, pickBestMatch, splitUrl;
  581. splitUrl = function(url) {
  582. var comboSign, hash, index, params;
  583. if ((index = url.indexOf('#')) >= 0) {
  584. hash = url.slice(index);
  585. url = url.slice(0, index);
  586. } else {
  587. hash = '';
  588. }
  589. comboSign = url.indexOf('??');
  590. if (comboSign >= 0) {
  591. if (comboSign + 1 !== url.lastIndexOf('?')) {
  592. index = url.lastIndexOf('?');
  593. }
  594. } else {
  595. index = url.indexOf('?');
  596. }
  597. if (index >= 0) {
  598. params = url.slice(index);
  599. url = url.slice(0, index);
  600. } else {
  601. params = '';
  602. }
  603. return {
  604. url: url,
  605. params: params,
  606. hash: hash
  607. };
  608. };
  609. pathFromUrl = function(url) {
  610. var path;
  611. url = splitUrl(url).url;
  612. if (url.indexOf('file://') === 0) {
  613. path = url.replace(/^file:\/\/(localhost)?/, '');
  614. } else {
  615. path = url.replace(/^([^:]+:)?\/\/([^:\/]+)(:\d*)?\//, '/');
  616. }
  617. return decodeURIComponent(path);
  618. };
  619. pickBestMatch = function(path, objects, pathFunc) {
  620. var bestMatch, i, len1, object, score;
  621. bestMatch = {
  622. score: 0
  623. };
  624. for (i = 0, len1 = objects.length; i < len1; i++) {
  625. object = objects[i];
  626. score = numberOfMatchingSegments(path, pathFunc(object));
  627. if (score > bestMatch.score) {
  628. bestMatch = {
  629. object: object,
  630. score: score
  631. };
  632. }
  633. }
  634. if (bestMatch.score > 0) {
  635. return bestMatch;
  636. } else {
  637. return null;
  638. }
  639. };
  640. numberOfMatchingSegments = function(path1, path2) {
  641. var comps1, comps2, eqCount, len;
  642. path1 = path1.replace(/^\/+/, '').toLowerCase();
  643. path2 = path2.replace(/^\/+/, '').toLowerCase();
  644. if (path1 === path2) {
  645. return 10000;
  646. }
  647. comps1 = path1.split('/').reverse();
  648. comps2 = path2.split('/').reverse();
  649. len = Math.min(comps1.length, comps2.length);
  650. eqCount = 0;
  651. while (eqCount < len && comps1[eqCount] === comps2[eqCount]) {
  652. ++eqCount;
  653. }
  654. return eqCount;
  655. };
  656. pathsMatch = function(path1, path2) {
  657. return numberOfMatchingSegments(path1, path2) > 0;
  658. };
  659. IMAGE_STYLES = [
  660. {
  661. selector: 'background',
  662. styleNames: ['backgroundImage']
  663. }, {
  664. selector: 'border',
  665. styleNames: ['borderImage', 'webkitBorderImage', 'MozBorderImage']
  666. }
  667. ];
  668. exports.Reloader = Reloader = (function() {
  669. function Reloader(window, console, Timer) {
  670. this.window = window;
  671. this.console = console;
  672. this.Timer = Timer;
  673. this.document = this.window.document;
  674. this.importCacheWaitPeriod = 200;
  675. this.plugins = [];
  676. }
  677. Reloader.prototype.addPlugin = function(plugin) {
  678. return this.plugins.push(plugin);
  679. };
  680. Reloader.prototype.analyze = function(callback) {
  681. return results;
  682. };
  683. Reloader.prototype.reload = function(path, options) {
  684. var base, i, len1, plugin, ref;
  685. this.options = options;
  686. if ((base = this.options).stylesheetReloadTimeout == null) {
  687. base.stylesheetReloadTimeout = 15000;
  688. }
  689. ref = this.plugins;
  690. for (i = 0, len1 = ref.length; i < len1; i++) {
  691. plugin = ref[i];
  692. if (plugin.reload && plugin.reload(path, options)) {
  693. return;
  694. }
  695. }
  696. if (options.liveCSS && path.match(/\.css(?:\.map)?$/i)) {
  697. if (this.reloadStylesheet(path)) {
  698. return;
  699. }
  700. }
  701. if (options.liveImg && path.match(/\.(jpe?g|png|gif)$/i)) {
  702. this.reloadImages(path);
  703. return;
  704. }
  705. if (options.isChromeExtension) {
  706. this.reloadChromeExtension();
  707. return;
  708. }
  709. return this.reloadPage();
  710. };
  711. Reloader.prototype.reloadPage = function() {
  712. return this.window.document.location.reload();
  713. };
  714. Reloader.prototype.reloadChromeExtension = function() {
  715. return this.window.chrome.runtime.reload();
  716. };
  717. Reloader.prototype.reloadImages = function(path) {
  718. var expando, i, img, j, k, len1, len2, len3, len4, m, ref, ref1, ref2, ref3, results1, selector, styleNames, styleSheet;
  719. expando = this.generateUniqueString();
  720. ref = this.document.images;
  721. for (i = 0, len1 = ref.length; i < len1; i++) {
  722. img = ref[i];
  723. if (pathsMatch(path, pathFromUrl(img.src))) {
  724. img.src = this.generateCacheBustUrl(img.src, expando);
  725. }
  726. }
  727. if (this.document.querySelectorAll) {
  728. for (j = 0, len2 = IMAGE_STYLES.length; j < len2; j++) {
  729. ref1 = IMAGE_STYLES[j], selector = ref1.selector, styleNames = ref1.styleNames;
  730. ref2 = this.document.querySelectorAll("[style*=" + selector + "]");
  731. for (k = 0, len3 = ref2.length; k < len3; k++) {
  732. img = ref2[k];
  733. this.reloadStyleImages(img.style, styleNames, path, expando);
  734. }
  735. }
  736. }
  737. if (this.document.styleSheets) {
  738. ref3 = this.document.styleSheets;
  739. results1 = [];
  740. for (m = 0, len4 = ref3.length; m < len4; m++) {
  741. styleSheet = ref3[m];
  742. results1.push(this.reloadStylesheetImages(styleSheet, path, expando));
  743. }
  744. return results1;
  745. }
  746. };
  747. Reloader.prototype.reloadStylesheetImages = function(styleSheet, path, expando) {
  748. var e, error, i, j, len1, len2, rule, rules, styleNames;
  749. try {
  750. rules = styleSheet != null ? styleSheet.cssRules : void 0;
  751. } catch (error) {
  752. e = error;
  753. }
  754. if (!rules) {
  755. return;
  756. }
  757. for (i = 0, len1 = rules.length; i < len1; i++) {
  758. rule = rules[i];
  759. switch (rule.type) {
  760. case CSSRule.IMPORT_RULE:
  761. this.reloadStylesheetImages(rule.styleSheet, path, expando);
  762. break;
  763. case CSSRule.STYLE_RULE:
  764. for (j = 0, len2 = IMAGE_STYLES.length; j < len2; j++) {
  765. styleNames = IMAGE_STYLES[j].styleNames;
  766. this.reloadStyleImages(rule.style, styleNames, path, expando);
  767. }
  768. break;
  769. case CSSRule.MEDIA_RULE:
  770. this.reloadStylesheetImages(rule, path, expando);
  771. }
  772. }
  773. };
  774. Reloader.prototype.reloadStyleImages = function(style, styleNames, path, expando) {
  775. var i, len1, newValue, styleName, value;
  776. for (i = 0, len1 = styleNames.length; i < len1; i++) {
  777. styleName = styleNames[i];
  778. value = style[styleName];
  779. if (typeof value === 'string') {
  780. newValue = value.replace(/\burl\s*\(([^)]*)\)/, (function(_this) {
  781. return function(match, src) {
  782. if (pathsMatch(path, pathFromUrl(src))) {
  783. return "url(" + (_this.generateCacheBustUrl(src, expando)) + ")";
  784. } else {
  785. return match;
  786. }
  787. };
  788. })(this));
  789. if (newValue !== value) {
  790. style[styleName] = newValue;
  791. }
  792. }
  793. }
  794. };
  795. Reloader.prototype.reloadStylesheet = function(path) {
  796. var i, imported, j, k, len1, len2, len3, len4, link, links, m, match, ref, ref1, style;
  797. links = (function() {
  798. var i, len1, ref, results1;
  799. ref = this.document.getElementsByTagName('link');
  800. results1 = [];
  801. for (i = 0, len1 = ref.length; i < len1; i++) {
  802. link = ref[i];
  803. if (link.rel.match(/^stylesheet$/i) && !link.__LiveReload_pendingRemoval) {
  804. results1.push(link);
  805. }
  806. }
  807. return results1;
  808. }).call(this);
  809. imported = [];
  810. ref = this.document.getElementsByTagName('style');
  811. for (i = 0, len1 = ref.length; i < len1; i++) {
  812. style = ref[i];
  813. if (style.sheet) {
  814. this.collectImportedStylesheets(style, style.sheet, imported);
  815. }
  816. }
  817. for (j = 0, len2 = links.length; j < len2; j++) {
  818. link = links[j];
  819. this.collectImportedStylesheets(link, link.sheet, imported);
  820. }
  821. if (this.window.StyleFix && this.document.querySelectorAll) {
  822. ref1 = this.document.querySelectorAll('style[data-href]');
  823. for (k = 0, len3 = ref1.length; k < len3; k++) {
  824. style = ref1[k];
  825. links.push(style);
  826. }
  827. }
  828. this.console.log("LiveReload found " + links.length + " LINKed stylesheets, " + imported.length + " @imported stylesheets");
  829. match = pickBestMatch(path, links.concat(imported), (function(_this) {
  830. return function(l) {
  831. return pathFromUrl(_this.linkHref(l));
  832. };
  833. })(this));
  834. if (match) {
  835. if (match.object.rule) {
  836. this.console.log("LiveReload is reloading imported stylesheet: " + match.object.href);
  837. this.reattachImportedRule(match.object);
  838. } else {
  839. this.console.log("LiveReload is reloading stylesheet: " + (this.linkHref(match.object)));
  840. this.reattachStylesheetLink(match.object);
  841. }
  842. } else {
  843. if (this.options.reloadMissingCSS) {
  844. this.console.log("LiveReload will reload all stylesheets because path '" + path + "' did not match any specific one. To disable this behavior, set 'options.reloadMissingCSS' to 'false'.");
  845. for (m = 0, len4 = links.length; m < len4; m++) {
  846. link = links[m];
  847. this.reattachStylesheetLink(link);
  848. }
  849. } else {
  850. this.console.log("LiveReload will not reload path '" + path + "' because the stylesheet was not found on the page and 'options.reloadMissingCSS' was set to 'false'.");
  851. }
  852. }
  853. return true;
  854. };
  855. Reloader.prototype.collectImportedStylesheets = function(link, styleSheet, result) {
  856. var e, error, i, index, len1, rule, rules;
  857. try {
  858. rules = styleSheet != null ? styleSheet.cssRules : void 0;
  859. } catch (error) {
  860. e = error;
  861. }
  862. if (rules && rules.length) {
  863. for (index = i = 0, len1 = rules.length; i < len1; index = ++i) {
  864. rule = rules[index];
  865. switch (rule.type) {
  866. case CSSRule.CHARSET_RULE:
  867. continue;
  868. case CSSRule.IMPORT_RULE:
  869. result.push({
  870. link: link,
  871. rule: rule,
  872. index: index,
  873. href: rule.href
  874. });
  875. this.collectImportedStylesheets(link, rule.styleSheet, result);
  876. break;
  877. default:
  878. break;
  879. }
  880. }
  881. }
  882. };
  883. Reloader.prototype.waitUntilCssLoads = function(clone, func) {
  884. var callbackExecuted, executeCallback, poll;
  885. callbackExecuted = false;
  886. executeCallback = (function(_this) {
  887. return function() {
  888. if (callbackExecuted) {
  889. return;
  890. }
  891. callbackExecuted = true;
  892. return func();
  893. };
  894. })(this);
  895. clone.onload = (function(_this) {
  896. return function() {
  897. _this.console.log("LiveReload: the new stylesheet has finished loading");
  898. _this.knownToSupportCssOnLoad = true;
  899. return executeCallback();
  900. };
  901. })(this);
  902. if (!this.knownToSupportCssOnLoad) {
  903. (poll = (function(_this) {
  904. return function() {
  905. if (clone.sheet) {
  906. _this.console.log("LiveReload is polling until the new CSS finishes loading...");
  907. return executeCallback();
  908. } else {
  909. return _this.Timer.start(50, poll);
  910. }
  911. };
  912. })(this))();
  913. }
  914. return this.Timer.start(this.options.stylesheetReloadTimeout, executeCallback);
  915. };
  916. Reloader.prototype.linkHref = function(link) {
  917. return link.href || link.getAttribute('data-href');
  918. };
  919. Reloader.prototype.reattachStylesheetLink = function(link) {
  920. var clone, parent;
  921. if (link.__LiveReload_pendingRemoval) {
  922. return;
  923. }
  924. link.__LiveReload_pendingRemoval = true;
  925. if (link.tagName === 'STYLE') {
  926. clone = this.document.createElement('link');
  927. clone.rel = 'stylesheet';
  928. clone.media = link.media;
  929. clone.disabled = link.disabled;
  930. } else {
  931. clone = link.cloneNode(false);
  932. }
  933. clone.href = this.generateCacheBustUrl(this.linkHref(link));
  934. parent = link.parentNode;
  935. if (parent.lastChild === link) {
  936. parent.appendChild(clone);
  937. } else {
  938. parent.insertBefore(clone, link.nextSibling);
  939. }
  940. return this.waitUntilCssLoads(clone, (function(_this) {
  941. return function() {
  942. var additionalWaitingTime;
  943. if (/AppleWebKit/.test(navigator.userAgent)) {
  944. additionalWaitingTime = 5;
  945. } else {
  946. additionalWaitingTime = 200;
  947. }
  948. return _this.Timer.start(additionalWaitingTime, function() {
  949. var ref;
  950. if (!link.parentNode) {
  951. return;
  952. }
  953. link.parentNode.removeChild(link);
  954. clone.onreadystatechange = null;
  955. return (ref = _this.window.StyleFix) != null ? ref.link(clone) : void 0;
  956. });
  957. };
  958. })(this));
  959. };
  960. Reloader.prototype.reattachImportedRule = function(arg) {
  961. var href, index, link, media, newRule, parent, rule, tempLink;
  962. rule = arg.rule, index = arg.index, link = arg.link;
  963. parent = rule.parentStyleSheet;
  964. href = this.generateCacheBustUrl(rule.href);
  965. media = rule.media.length ? [].join.call(rule.media, ', ') : '';
  966. newRule = "@import url(\"" + href + "\") " + media + ";";
  967. rule.__LiveReload_newHref = href;
  968. tempLink = this.document.createElement("link");
  969. tempLink.rel = 'stylesheet';
  970. tempLink.href = href;
  971. tempLink.__LiveReload_pendingRemoval = true;
  972. if (link.parentNode) {
  973. link.parentNode.insertBefore(tempLink, link);
  974. }
  975. return this.Timer.start(this.importCacheWaitPeriod, (function(_this) {
  976. return function() {
  977. if (tempLink.parentNode) {
  978. tempLink.parentNode.removeChild(tempLink);
  979. }
  980. if (rule.__LiveReload_newHref !== href) {
  981. return;
  982. }
  983. parent.insertRule(newRule, index);
  984. parent.deleteRule(index + 1);
  985. rule = parent.cssRules[index];
  986. rule.__LiveReload_newHref = href;
  987. return _this.Timer.start(_this.importCacheWaitPeriod, function() {
  988. if (rule.__LiveReload_newHref !== href) {
  989. return;
  990. }
  991. parent.insertRule(newRule, index);
  992. return parent.deleteRule(index + 1);
  993. });
  994. };
  995. })(this));
  996. };
  997. Reloader.prototype.generateUniqueString = function() {
  998. return 'livereload=' + Date.now();
  999. };
  1000. Reloader.prototype.generateCacheBustUrl = function(url, expando) {
  1001. var hash, oldParams, originalUrl, params, ref;
  1002. if (expando == null) {
  1003. expando = this.generateUniqueString();
  1004. }
  1005. ref = splitUrl(url), url = ref.url, hash = ref.hash, oldParams = ref.params;
  1006. if (this.options.overrideURL) {
  1007. if (url.indexOf(this.options.serverURL) < 0) {
  1008. originalUrl = url;
  1009. url = this.options.serverURL + this.options.overrideURL + "?url=" + encodeURIComponent(url);
  1010. this.console.log("LiveReload is overriding source URL " + originalUrl + " with " + url);
  1011. }
  1012. }
  1013. params = oldParams.replace(/(\?|&)livereload=(\d+)/, function(match, sep) {
  1014. return "" + sep + expando;
  1015. });
  1016. if (params === oldParams) {
  1017. if (oldParams.length === 0) {
  1018. params = "?" + expando;
  1019. } else {
  1020. params = oldParams + "&" + expando;
  1021. }
  1022. }
  1023. return url + params + hash;
  1024. };
  1025. return Reloader;
  1026. })();
  1027. }).call(this);
  1028. },{}],8:[function(require,module,exports){
  1029. (function() {
  1030. var CustomEvents, LiveReload, k;
  1031. CustomEvents = require('./customevents');
  1032. LiveReload = window.LiveReload = new (require('./livereload').LiveReload)(window);
  1033. for (k in window) {
  1034. if (k.match(/^LiveReloadPlugin/)) {
  1035. LiveReload.addPlugin(window[k]);
  1036. }
  1037. }
  1038. LiveReload.addPlugin(require('./less'));
  1039. LiveReload.on('shutdown', function() {
  1040. return delete window.LiveReload;
  1041. });
  1042. LiveReload.on('connect', function() {
  1043. return CustomEvents.fire(document, 'LiveReloadConnect');
  1044. });
  1045. LiveReload.on('disconnect', function() {
  1046. return CustomEvents.fire(document, 'LiveReloadDisconnect');
  1047. });
  1048. CustomEvents.bind(document, 'LiveReloadShutDown', function() {
  1049. return LiveReload.shutDown();
  1050. });
  1051. }).call(this);
  1052. },{"./customevents":2,"./less":3,"./livereload":4}],9:[function(require,module,exports){
  1053. (function() {
  1054. var Timer;
  1055. exports.Timer = Timer = (function() {
  1056. function Timer(func1) {
  1057. this.func = func1;
  1058. this.running = false;
  1059. this.id = null;
  1060. this._handler = (function(_this) {
  1061. return function() {
  1062. _this.running = false;
  1063. _this.id = null;
  1064. return _this.func();
  1065. };
  1066. })(this);
  1067. }
  1068. Timer.prototype.start = function(timeout) {
  1069. if (this.running) {
  1070. clearTimeout(this.id);
  1071. }
  1072. this.id = setTimeout(this._handler, timeout);
  1073. return this.running = true;
  1074. };
  1075. Timer.prototype.stop = function() {
  1076. if (this.running) {
  1077. clearTimeout(this.id);
  1078. this.running = false;
  1079. return this.id = null;
  1080. }
  1081. };
  1082. return Timer;
  1083. })();
  1084. Timer.start = function(timeout, func) {
  1085. return setTimeout(func, timeout);
  1086. };
  1087. }).call(this);
  1088. },{}]},{},[8]);