livereload.js 37 KB

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