No Description

inliner.js 9.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. var fs = require('fs');
  2. var path = require('path');
  3. var http = require('http');
  4. var https = require('https');
  5. var url = require('url');
  6. var UrlRewriter = require('../images/url-rewriter');
  7. var Splitter = require('../text/splitter.js');
  8. var merge = function(source1, source2) {
  9. var target = {};
  10. for (var key1 in source1)
  11. target[key1] = source1[key1];
  12. for (var key2 in source2)
  13. target[key2] = source2[key2];
  14. return target;
  15. };
  16. module.exports = function Inliner(context, options) {
  17. var defaultOptions = {
  18. timeout: 5000,
  19. request: {}
  20. };
  21. var inlinerOptions = merge(defaultOptions, options || {});
  22. var process = function(data, options) {
  23. if (options.shallow) {
  24. options.shallow = false;
  25. options._shared.done.push(data);
  26. return processNext(options);
  27. }
  28. options._shared = options._shared || {
  29. done: [],
  30. left: []
  31. };
  32. var shared = options._shared;
  33. var nextStart = 0;
  34. var nextEnd = 0;
  35. var cursor = 0;
  36. var isComment = commentScanner(data);
  37. var afterContent = contentScanner(data);
  38. options.relativeTo = options.relativeTo || options.root;
  39. options._baseRelativeTo = options._baseRelativeTo || options.relativeTo;
  40. options.visited = options.visited || [];
  41. for (; nextEnd < data.length;) {
  42. nextStart = nextImportAt(data, cursor);
  43. if (nextStart == -1)
  44. break;
  45. if (isComment(nextStart)) {
  46. cursor = nextStart + 1;
  47. continue;
  48. }
  49. nextEnd = data.indexOf(';', nextStart);
  50. if (nextEnd == -1) {
  51. cursor = data.length;
  52. data = '';
  53. break;
  54. }
  55. shared.done.push(data.substring(0, nextStart));
  56. shared.left.unshift([data.substring(nextEnd + 1), options]);
  57. return afterContent(nextStart) ?
  58. processNext(options) :
  59. inline(data, nextStart, nextEnd, options);
  60. }
  61. // no @import matched in current data
  62. shared.done.push(data);
  63. return processNext(options);
  64. };
  65. var nextImportAt = function (data, cursor) {
  66. var nextLowerCase = data.indexOf('@import', cursor);
  67. var nextUpperCase = data.indexOf('@IMPORT', cursor);
  68. if (nextLowerCase > -1 && nextUpperCase == -1)
  69. return nextLowerCase;
  70. else if (nextLowerCase == -1 && nextUpperCase > -1)
  71. return nextUpperCase;
  72. else
  73. return Math.min(nextLowerCase, nextUpperCase);
  74. };
  75. var processNext = function(options) {
  76. if (options._shared.left.length > 0)
  77. return process.apply(null, options._shared.left.shift());
  78. else
  79. return options.whenDone(options._shared.done.join(''));
  80. };
  81. var commentScanner = function(data) {
  82. var commentRegex = /(\/\*(?!\*\/)[\s\S]*?\*\/)/;
  83. var lastStartIndex = 0;
  84. var lastEndIndex = 0;
  85. var noComments = false;
  86. // test whether an index is located within a comment
  87. var scanner = function(idx) {
  88. var comment;
  89. var localStartIndex = 0;
  90. var localEndIndex = 0;
  91. var globalStartIndex = 0;
  92. var globalEndIndex = 0;
  93. // return if we know there are no more comments
  94. if (noComments)
  95. return false;
  96. // idx can be still within last matched comment (many @import statements inside one comment)
  97. if (idx > lastStartIndex && idx < lastEndIndex)
  98. return true;
  99. comment = data.match(commentRegex);
  100. if (!comment) {
  101. noComments = true;
  102. return false;
  103. }
  104. // get the indexes relative to the current data chunk
  105. lastStartIndex = localStartIndex = comment.index;
  106. localEndIndex = localStartIndex + comment[0].length;
  107. // calculate the indexes relative to the full original data
  108. globalEndIndex = localEndIndex + lastEndIndex;
  109. globalStartIndex = globalEndIndex - comment[0].length;
  110. // chop off data up to and including current comment block
  111. data = data.substring(localEndIndex);
  112. lastEndIndex = globalEndIndex;
  113. // re-run scan if comment ended before the idx
  114. if (globalEndIndex < idx)
  115. return scanner(idx);
  116. return globalEndIndex > idx && idx > globalStartIndex;
  117. };
  118. return scanner;
  119. };
  120. var contentScanner = function(data) {
  121. var isComment = commentScanner(data);
  122. var firstContentIdx = -1;
  123. while (true) {
  124. firstContentIdx = data.indexOf('{', firstContentIdx + 1);
  125. if (firstContentIdx == -1 || !isComment(firstContentIdx))
  126. break;
  127. }
  128. return function(idx) {
  129. return firstContentIdx > -1 ?
  130. idx > firstContentIdx :
  131. false;
  132. };
  133. };
  134. var inline = function(data, nextStart, nextEnd, options) {
  135. options.shallow = data.indexOf('@shallow') > 0;
  136. var importDeclaration = data
  137. .substring(nextImportAt(data, nextStart) + '@import'.length + 1, nextEnd)
  138. .replace(/@shallow\)$/, ')')
  139. .trim();
  140. var viaUrl = importDeclaration.indexOf('url(') === 0;
  141. var urlStartsAt = viaUrl ? 4 : 0;
  142. var isQuoted = /^['"]/.exec(importDeclaration.substring(urlStartsAt, urlStartsAt + 2));
  143. var urlEndsAt = isQuoted ?
  144. importDeclaration.indexOf(isQuoted[0], urlStartsAt + 1) :
  145. new Splitter(' ').split(importDeclaration)[0].length - (viaUrl ? 1 : 0);
  146. var importedFile = importDeclaration
  147. .substring(urlStartsAt, urlEndsAt)
  148. .replace(/['"]/g, '')
  149. .replace(/\)$/, '')
  150. .trim();
  151. var mediaQuery = importDeclaration
  152. .substring(urlEndsAt + 1)
  153. .replace(/^\)/, '')
  154. .trim();
  155. var isRemote = options.isRemote ||
  156. /^(http|https):\/\//.test(importedFile) ||
  157. /^\/\//.test(importedFile);
  158. if (options.localOnly && isRemote) {
  159. context.warnings.push('Ignoring remote @import declaration of "' + importedFile + '" as no callback given.');
  160. restoreImport(importedFile, mediaQuery, options);
  161. return processNext(options);
  162. }
  163. var method = isRemote ? inlineRemoteResource : inlineLocalResource;
  164. return method(importedFile, mediaQuery, options);
  165. };
  166. var inlineRemoteResource = function(importedFile, mediaQuery, options) {
  167. var importedUrl = /^https?:\/\//.test(importedFile) ?
  168. importedFile :
  169. url.resolve(options.relativeTo, importedFile);
  170. if (importedUrl.indexOf('//') === 0)
  171. importedUrl = 'http:' + importedUrl;
  172. if (options.visited.indexOf(importedUrl) > -1)
  173. return processNext(options);
  174. if (context.debug)
  175. console.error('Inlining remote stylesheet: ' + importedUrl);
  176. options.visited.push(importedUrl);
  177. var get = importedUrl.indexOf('http://') === 0 ?
  178. http.get :
  179. https.get;
  180. var timedOut = false;
  181. var handleError = function(message) {
  182. context.errors.push('Broken @import declaration of "' + importedUrl + '" - ' + message);
  183. restoreImport(importedUrl, mediaQuery, options);
  184. processNext(options);
  185. };
  186. var requestOptions = merge(url.parse(importedUrl), inlinerOptions.request);
  187. get(requestOptions, function(res) {
  188. if (res.statusCode < 200 || res.statusCode > 399) {
  189. return handleError('error ' + res.statusCode);
  190. } else if (res.statusCode > 299) {
  191. var movedUrl = url.resolve(importedUrl, res.headers.location);
  192. return inlineRemoteResource(movedUrl, mediaQuery, options);
  193. }
  194. var chunks = [];
  195. var parsedUrl = url.parse(importedUrl);
  196. res.on('data', function(chunk) {
  197. chunks.push(chunk.toString());
  198. });
  199. res.on('end', function() {
  200. var importedData = chunks.join('');
  201. importedData = UrlRewriter.process(importedData, { toBase: importedUrl });
  202. if (mediaQuery.length > 0)
  203. importedData = '@media ' + mediaQuery + '{' + importedData + '}';
  204. process(importedData, {
  205. isRemote: true,
  206. relativeTo: parsedUrl.protocol + '//' + parsedUrl.host,
  207. _shared: options._shared,
  208. whenDone: options.whenDone,
  209. visited: options.visited,
  210. shallow: options.shallow
  211. });
  212. });
  213. })
  214. .on('error', function(res) {
  215. handleError(res.message);
  216. })
  217. .on('timeout', function() {
  218. // FIX: node 0.8 fires this event twice
  219. if (timedOut)
  220. return;
  221. handleError('timeout');
  222. timedOut = true;
  223. })
  224. .setTimeout(inlinerOptions.timeout);
  225. };
  226. var inlineLocalResource = function(importedFile, mediaQuery, options) {
  227. var relativeTo = importedFile[0] == '/' ?
  228. options.root :
  229. options.relativeTo;
  230. var fullPath = path.resolve(path.join(relativeTo, importedFile));
  231. if (!fs.existsSync(fullPath) || !fs.statSync(fullPath).isFile()) {
  232. context.errors.push('Broken @import declaration of "' + importedFile + '"');
  233. return processNext(options);
  234. }
  235. if (options.visited.indexOf(fullPath) > -1)
  236. return processNext(options);
  237. if (context.debug)
  238. console.error('Inlining local stylesheet: ' + fullPath);
  239. options.visited.push(fullPath);
  240. var importedData = fs.readFileSync(fullPath, 'utf8');
  241. var importRelativeTo = path.dirname(fullPath);
  242. importedData = UrlRewriter.process(importedData, {
  243. relative: true,
  244. fromBase: importRelativeTo,
  245. toBase: options._baseRelativeTo
  246. });
  247. if (mediaQuery.length > 0)
  248. importedData = '@media ' + mediaQuery + '{' + importedData + '}';
  249. return process(importedData, {
  250. root: options.root,
  251. relativeTo: importRelativeTo,
  252. _baseRelativeTo: options._baseRelativeTo,
  253. _shared: options._shared,
  254. visited: options.visited,
  255. whenDone: options.whenDone,
  256. localOnly: options.localOnly,
  257. shallow: options.shallow
  258. });
  259. };
  260. var restoreImport = function(importedUrl, mediaQuery, options) {
  261. var restoredImport = '@import url(' + importedUrl + ')' + (mediaQuery.length > 0 ? ' ' + mediaQuery : '') + ';';
  262. options._shared.done.push(restoredImport);
  263. };
  264. // Inlines all imports taking care of repetitions, unknown files, and circular dependencies
  265. return { process: process };
  266. };