css-minifier.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  1. /**
  2. * UglifyCSS
  3. * Port of YUI CSS Compressor to Vanilla JS
  4. * Author: Gildas Lormeau
  5. * MIT licenced
  6. */
  7. /**
  8. * UglifyCSS
  9. * Port of YUI CSS Compressor to NodeJS
  10. * Author: Franck Marcia - https://github.com/fmarcia
  11. * MIT licenced
  12. */
  13. /**
  14. * cssmin.js
  15. * Author: Stoyan Stefanov - http://phpied.com/
  16. * This is a JavaScript port of the CSS minification tool
  17. * distributed with YUICompressor, itself a port
  18. * of the cssmin utility by Isaac Schlueter - http://foohack.com/
  19. * Permission is hereby granted to use the JavaScript version under the same
  20. * conditions as the YUICompressor (original YUICompressor note below).
  21. */
  22. /**
  23. * YUI Compressor
  24. * http://developer.yahoo.com/yui/compressor/
  25. * Author: Julien Lecomte - http://www.julienlecomte.net/
  26. * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
  27. * The copyrights embodied in the content of this file are licensed
  28. * by Yahoo! Inc. under the BSD (revised) open source license.
  29. */
  30. this.uglifycss = this.uglifycss || (() => {
  31. /**
  32. * @type {string} - placeholder prefix
  33. */
  34. const ___PRESERVED_TOKEN_ = "___PRESERVED_TOKEN_";
  35. /**
  36. * @typedef {object} options - UglifyCSS options
  37. * @property {number} [maxLineLen=0] - Maximum line length of uglified CSS
  38. * @property {boolean} [expandVars=false] - Expand variables
  39. * @property {boolean} [uglyComments=false] - Removes newlines within preserved comments
  40. * @property {boolean} [cuteComments=false] - Preserves newlines within and around preserved comments
  41. * @property {boolean} [debug=false] - Prints full error stack on error
  42. * @property {string} [output=''] - Output file name
  43. */
  44. /**
  45. * @type {options} - UglifyCSS options
  46. */
  47. const defaultOptions = {
  48. maxLineLen: 0,
  49. expandVars: false,
  50. uglyComments: false,
  51. cuteComments: false,
  52. debug: false,
  53. output: ""
  54. };
  55. const REGEXP_DATA_URI = /url\(\s*(["']?)data:/g;
  56. const REGEXP_WHITE_SPACES = /\s+/g;
  57. const REGEXP_NEW_LINE = /\n/g;
  58. /**
  59. * extractDataUrls replaces all data urls with tokens before we start
  60. * compressing, to avoid performance issues running some of the subsequent
  61. * regexes against large strings chunks.
  62. *
  63. * @param {string} css - CSS content
  64. * @param {string[]} preservedTokens - Global array of tokens to preserve
  65. *
  66. * @return {string} Processed CSS
  67. */
  68. function extractDataUrls(css, preservedTokens) {
  69. // Leave data urls alone to increase parse performance.
  70. const pattern = REGEXP_DATA_URI;
  71. const maxIndex = css.length - 1;
  72. const sb = [];
  73. let appendIndex = 0, match;
  74. // Since we need to account for non-base64 data urls, we need to handle
  75. // ' and ) being part of the data string. Hence switching to indexOf,
  76. // to determine whether or not we have matching string terminators and
  77. // handling sb appends directly, instead of using matcher.append* methods.
  78. while ((match = pattern.exec(css)) !== null) {
  79. const startIndex = match.index + 4; // 'url('.length()
  80. let terminator = match[1]; // ', " or empty (not quoted)
  81. if (terminator.length === 0) {
  82. terminator = ")";
  83. }
  84. let foundTerminator = false, endIndex = pattern.lastIndex - 1;
  85. while (foundTerminator === false && endIndex + 1 <= maxIndex) {
  86. endIndex = css.indexOf(terminator, endIndex + 1);
  87. // endIndex == 0 doesn't really apply here
  88. if ((endIndex > 0) && (css.charAt(endIndex - 1) !== "\\")) {
  89. foundTerminator = true;
  90. if (")" != terminator) {
  91. endIndex = css.indexOf(")", endIndex);
  92. }
  93. }
  94. }
  95. // Enough searching, start moving stuff over to the buffer
  96. sb.push(css.substring(appendIndex, match.index));
  97. if (foundTerminator) {
  98. let token = css.substring(startIndex, endIndex);
  99. const parts = token.split(",");
  100. if (parts.length > 1 && parts[0].slice(-7) == ";base64") {
  101. token = token.replace(REGEXP_WHITE_SPACES, "");
  102. } else {
  103. token = token.replace(REGEXP_NEW_LINE, " ");
  104. token = token.replace(REGEXP_WHITE_SPACES, " ");
  105. token = token.replace(REGEXP_PRESERVE_HSLA1, "");
  106. }
  107. preservedTokens.push(token);
  108. const preserver = "url(" + ___PRESERVED_TOKEN_ + (preservedTokens.length - 1) + "___)";
  109. sb.push(preserver);
  110. appendIndex = endIndex + 1;
  111. } else {
  112. // No end terminator found, re-add the whole match. Should we throw/warn here?
  113. sb.push(css.substring(match.index, pattern.lastIndex));
  114. appendIndex = pattern.lastIndex;
  115. }
  116. }
  117. sb.push(css.substring(appendIndex));
  118. return sb.join("");
  119. }
  120. const REGEXP_HEX_COLORS = /(=\s*?["']?)?#([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])(\}|[^0-9a-f{][^{]*?\})/gi;
  121. /**
  122. * compressHexColors compresses hex color values of the form #AABBCC to #ABC.
  123. *
  124. * DOES NOT compress CSS ID selectors which match the above pattern (which would
  125. * break things), like #AddressForm { ... }
  126. *
  127. * DOES NOT compress IE filters, which have hex color values (which would break
  128. * things), like chroma(color='#FFFFFF');
  129. *
  130. * DOES NOT compress invalid hex values, like background-color: #aabbccdd
  131. *
  132. * @param {string} css - CSS content
  133. *
  134. * @return {string} Processed CSS
  135. */
  136. function compressHexColors(css) {
  137. // Look for hex colors inside { ... } (to avoid IDs) and which don't have a =, or a " in front of them (to avoid filters)
  138. const pattern = REGEXP_HEX_COLORS;
  139. const sb = [];
  140. let index = 0, match;
  141. while ((match = pattern.exec(css)) !== null) {
  142. sb.push(css.substring(index, match.index));
  143. const isFilter = match[1];
  144. if (isFilter) {
  145. // Restore, maintain case, otherwise filter will break
  146. sb.push(match[1] + "#" + (match[2] + match[3] + match[4] + match[5] + match[6] + match[7]));
  147. } else {
  148. if (match[2].toLowerCase() == match[3].toLowerCase() &&
  149. match[4].toLowerCase() == match[5].toLowerCase() &&
  150. match[6].toLowerCase() == match[7].toLowerCase()) {
  151. // Compress.
  152. sb.push("#" + (match[3] + match[5] + match[7]).toLowerCase());
  153. } else {
  154. // Non compressible color, restore but lower case.
  155. sb.push("#" + (match[2] + match[3] + match[4] + match[5] + match[6] + match[7]).toLowerCase());
  156. }
  157. }
  158. index = pattern.lastIndex = pattern.lastIndex - match[8].length;
  159. }
  160. sb.push(css.substring(index));
  161. return sb.join("");
  162. }
  163. const REGEXP_KEYFRAMES = /@[a-z0-9-_]*keyframes\s+[a-z0-9-_]+\s*{/gi;
  164. const REGEXP_WHITE_SPACE = /(^\s|\s$)/g;
  165. /** keyframes preserves 0 followed by unit in keyframes steps
  166. *
  167. * @param {string} content - CSS content
  168. * @param {string[]} preservedTokens - Global array of tokens to preserve
  169. *
  170. * @return {string} Processed CSS
  171. */
  172. function keyframes(content, preservedTokens) {
  173. const pattern = REGEXP_KEYFRAMES;
  174. let index = 0, buffer;
  175. const preserve = (part, i) => {
  176. part = part.replace(REGEXP_WHITE_SPACE, "");
  177. if (part.charAt(0) === "0") {
  178. preservedTokens.push(part);
  179. buffer[i] = ___PRESERVED_TOKEN_ + (preservedTokens.length - 1) + "___";
  180. }
  181. };
  182. while (true) { // eslint-disable-line no-constant-condition
  183. let level = 0;
  184. buffer = "";
  185. let startIndex = content.slice(index).search(pattern);
  186. if (startIndex < 0) {
  187. break;
  188. }
  189. index += startIndex;
  190. startIndex = index;
  191. const len = content.length;
  192. const buffers = [];
  193. for (; index < len; ++index) {
  194. const ch = content.charAt(index);
  195. if (ch === "{") {
  196. if (level === 0) {
  197. buffers.push(buffer.replace(REGEXP_WHITE_SPACE, ""));
  198. } else if (level === 1) {
  199. buffer = buffer.split(",");
  200. buffer.forEach(preserve);
  201. buffers.push(buffer.join(",").replace(REGEXP_WHITE_SPACE, ""));
  202. }
  203. buffer = "";
  204. level += 1;
  205. } else if (ch === "}") {
  206. if (level === 2) {
  207. buffers.push("{" + buffer.replace(REGEXP_WHITE_SPACE, "") + "}");
  208. buffer = "";
  209. } else if (level === 1) {
  210. content = content.slice(0, startIndex) +
  211. buffers.shift() + "{" +
  212. buffers.join("") +
  213. content.slice(index);
  214. break;
  215. }
  216. level -= 1;
  217. }
  218. if (level < 0) {
  219. break;
  220. } else if (ch !== "{" && ch !== "}") {
  221. buffer += ch;
  222. }
  223. }
  224. }
  225. return content;
  226. }
  227. /**
  228. * collectComments collects all comment blocks and return new content with comment placeholders
  229. *
  230. * @param {string} content - CSS content
  231. * @param {string[]} comments - Global array of extracted comments
  232. *
  233. * @return {string} Processed CSS
  234. */
  235. function collectComments(content, comments) {
  236. const table = [];
  237. let from = 0, end;
  238. while (true) { // eslint-disable-line no-constant-condition
  239. const start = content.indexOf("/*", from);
  240. if (start > -1) {
  241. end = content.indexOf("*/", start + 2);
  242. if (end > -1) {
  243. comments.push(content.slice(start + 2, end));
  244. table.push(content.slice(from, start));
  245. table.push("/*___PRESERVE_CANDIDATE_COMMENT_" + (comments.length - 1) + "___*/");
  246. from = end + 2;
  247. } else {
  248. // unterminated comment
  249. end = -2;
  250. break;
  251. }
  252. } else {
  253. break;
  254. }
  255. }
  256. table.push(content.slice(end + 2));
  257. return table.join("");
  258. }
  259. /**
  260. * processString uglifies a CSS string
  261. *
  262. * @param {string} content - CSS string
  263. * @param {options} options - UglifyCSS options
  264. *
  265. * @return {string} Uglified result
  266. */
  267. // const REGEXP_EMPTY_RULES = /[^};{/]+\{\}/g;
  268. const REGEXP_PRESERVE_STRING = /("([^\\"]|\\.|\\)*")|('([^\\']|\\.|\\)*')/g;
  269. const REGEXP_MINIFY_ALPHA = /progid:DXImageTransform.Microsoft.Alpha\(Opacity=/gi;
  270. const REGEXP_PRESERVE_TOKEN1 = /\r\n/g;
  271. const REGEXP_PRESERVE_TOKEN2 = /[\r\n]/g;
  272. const REGEXP_VARIABLES = /@variables\s*\{\s*([^}]+)\s*\}/g;
  273. const REGEXP_VARIABLE = /\s*([a-z0-9-]+)\s*:\s*([^;}]+)\s*/gi;
  274. const REGEXP_VARIABLE_VALUE = /var\s*\(\s*([^)]+)\s*\)/g;
  275. const REGEXP_PRESERVE_CALC = /calc\(([^;}]*)\)/g;
  276. const REGEXP_TRIM = /(^\s*|\s*$)/g;
  277. const REGEXP_PRESERVE_CALC2 = /\( /g;
  278. const REGEXP_PRESERVE_CALC3 = / \)/g;
  279. const REGEXP_PRESERVE_MATRIX = /\s*filter:\s*progid:DXImageTransform.Microsoft.Matrix\(([^)]+)\);/g;
  280. const REGEXP_REMOVE_SPACES = /(^|\})(([^{:])+:)+([^{]*{)/g;
  281. const REGEXP_REMOVE_SPACES2 = /\s+([!{};:>+()\],])/g;
  282. const REGEXP_RESTORE_SPACE_IMPORTANT = /!important/g;
  283. const REGEXP_PSEUDOCLASSCOLON = /___PSEUDOCLASSCOLON___/g;
  284. const REGEXP_COLUMN = /:/g;
  285. const REGEXP_PRESERVE_ZERO_UNIT = /\s*(animation|animation-delay|animation-duration|transition|transition-delay|transition-duration):\s*([^;}]+)/gi;
  286. const REGEXP_PRESERVE_ZERO_UNIT1 = /(^|\D)0?\.?0(m?s)/gi;
  287. const REGEXP_PRESERVE_FLEX = /\s*(flex|flex-basis):\s*([^;}]+)/gi;
  288. const REGEXP_SPACES = /\s+/;
  289. const REGEXP_PRESERVE_HSLA = /(hsla?)\(([^)]+)\)/g;
  290. const REGEXP_PRESERVE_HSLA1 = /(^\s+|\s+$)/g;
  291. const REGEXP_RETAIN_SPACE_IE6 = /:first-(line|letter)(\{|,)/gi;
  292. const REGEXP_CHARSET = /^(.*)(@charset)( "[^"]*";)/gi;
  293. const REGEXP_REMOVE_SECOND_CHARSET = /^((\s*)(@charset)( [^;]+;\s*))+/gi;
  294. const REGEXP_LOWERCASE_DIRECTIVES = /@(font-face|import|(?:-(?:atsc|khtml|moz|ms|o|wap|webkit)-)?keyframe|media|page|namespace)/gi;
  295. const REGEXP_LOWERCASE_PSEUDO_ELEMENTS = /:(active|after|before|checked|disabled|empty|enabled|first-(?:child|of-type)|focus|hover|last-(?:child|of-type)|link|only-(?:child|of-type)|root|:selection|target|visited)/gi;
  296. const REGEXP_CHARSET2 = /^(.*)(@charset "[^"]*";)/g;
  297. const REGEXP_CHARSET3 = /^(\s*@charset [^;]+;\s*)+/g;
  298. const REGEXP_LOWERCASE_FUNCTIONS = /:(lang|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|(?:-(?:atsc|khtml|moz|ms|o|wap|webkit)-)?any)\(/gi;
  299. const REGEXP_LOWERCASE_FUNCTIONS2 = /([:,( ]\s*)(attr|color-stop|from|rgba|to|url|(?:-(?:atsc|khtml|moz|ms|o|wap|webkit)-)?(?:calc|max|min|(?:repeating-)?(?:linear|radial)-gradient)|-webkit-gradient)/gi;
  300. const REGEXP_NEWLINE1 = /\s*\/\*/g;
  301. const REGEXP_NEWLINE2 = /\*\/\s*/g;
  302. const REGEXP_RESTORE_SPACE1 = /\band\(/gi;
  303. const REGEXP_RESTORE_SPACE2 = /([^:])not\(/gi;
  304. const REGEXP_REMOVE_SPACES3 = /([!{}:;>+([,])\s+/g;
  305. const REGEXP_REMOVE_SEMI_COLUMNS = /;+\}/g;
  306. const REGEXP_REPLACE_ZERO = /(^|[^.0-9\\])(?:0?\.)?0(?:ex|ch|r?em|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|g?rad|turn|m?s|k?Hz|dpi|dpcm|dppx|%)(?![a-z0-9])/gi;
  307. const REGEXP_REPLACE_ZERO_DOT = /([0-9])\.0(ex|ch|r?em|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|g?rad|turn|m?s|k?Hz|dpi|dpcm|dppx|%| |;)/gi;
  308. const REGEXP_REPLACE_4_ZEROS = /:0 0 0 0(;|\})/g;
  309. const REGEXP_REPLACE_3_ZEROS = /:0 0 0(;|\})/g;
  310. const REGEXP_REPLACE_2_ZEROS = /:0 0(;|\})/g;
  311. const REGEXP_REPLACE_1_ZERO = /(background-position|transform-origin|webkit-transform-origin|moz-transform-origin|o-transform-origin|ms-transform-origin|box-shadow):0(;|\})/gi;
  312. const REGEXP_REPLACE_ZERO_DOT_DECIMAL = /(:|\s)0+\.(\d+)/g;
  313. const REGEXP_REPLACE_RGB = /rgb\s*\(\s*([0-9,\s]+)\s*\)/gi;
  314. const REGEXP_REPLACE_BORDER_ZERO = /(border|border-top|border-right|border-bottom|border-left|outline|background):none(;|\})/gi;
  315. const REGEXP_REPLACE_IE_OPACITY = /progid:DXImageTransform\.Microsoft\.Alpha\(Opacity=/gi;
  316. const REGEXP_REPLACE_QUERY_FRACTION = /\(([-A-Za-z]+):([0-9]+)\/([0-9]+)\)/g;
  317. const REGEXP_QUERY_FRACTION = /___QUERY_FRACTION___/g;
  318. const REGEXP_REPLACE_SEMI_COLUMNS = /;;+/g;
  319. const REGEXP_REPLACE_HASH_COLOR = /(:|\s)(#f00)(;|})/g;
  320. const REGEXP_PRESERVED_NEWLINE = /___PRESERVED_NEWLINE___/g;
  321. const REGEXP_REPLACE_HASH_COLOR_SHORT1 = /(:|\s)(#000080)(;|})/g;
  322. const REGEXP_REPLACE_HASH_COLOR_SHORT2 = /(:|\s)(#808080)(;|})/g;
  323. const REGEXP_REPLACE_HASH_COLOR_SHORT3 = /(:|\s)(#808000)(;|})/g;
  324. const REGEXP_REPLACE_HASH_COLOR_SHORT4 = /(:|\s)(#800080)(;|})/g;
  325. const REGEXP_REPLACE_HASH_COLOR_SHORT5 = /(:|\s)(#c0c0c0)(;|})/g;
  326. const REGEXP_REPLACE_HASH_COLOR_SHORT6 = /(:|\s)(#008080)(;|})/g;
  327. const REGEXP_REPLACE_HASH_COLOR_SHORT7 = /(:|\s)(#ffa500)(;|})/g;
  328. const REGEXP_REPLACE_HASH_COLOR_SHORT8 = /(:|\s)(#800000)(;|})/g;
  329. function processString(content = "", options = defaultOptions) {
  330. const comments = [];
  331. const preservedTokens = [];
  332. let pattern;
  333. content = extractDataUrls(content, preservedTokens);
  334. content = collectComments(content, comments);
  335. // preserve strings so their content doesn't get accidentally minified
  336. pattern = REGEXP_PRESERVE_STRING;
  337. content = content.replace(pattern, token => {
  338. const quote = token.substring(0, 1);
  339. token = token.slice(1, -1);
  340. // maybe the string contains a comment-like substring or more? put'em back then
  341. if (token.indexOf("___PRESERVE_CANDIDATE_COMMENT_") >= 0) {
  342. for (let i = 0, len = comments.length; i < len; i += 1) {
  343. token = token.replace("___PRESERVE_CANDIDATE_COMMENT_" + i + "___", comments[i]);
  344. }
  345. }
  346. // minify alpha opacity in filter strings
  347. token = token.replace(REGEXP_MINIFY_ALPHA, "alpha(opacity=");
  348. preservedTokens.push(token);
  349. return quote + ___PRESERVED_TOKEN_ + (preservedTokens.length - 1) + "___" + quote;
  350. });
  351. // strings are safe, now wrestle the comments
  352. for (let i = 0, len = comments.length; i < len; i += 1) {
  353. const token = comments[i];
  354. const placeholder = "___PRESERVE_CANDIDATE_COMMENT_" + i + "___";
  355. // ! in the first position of the comment means preserve
  356. // so push to the preserved tokens keeping the !
  357. if (token.charAt(0) === "!") {
  358. if (options.cuteComments) {
  359. preservedTokens.push(token.substring(1).replace(REGEXP_PRESERVE_TOKEN1, "\n"));
  360. } else if (options.uglyComments) {
  361. preservedTokens.push(token.substring(1).replace(REGEXP_PRESERVE_TOKEN2, ""));
  362. } else {
  363. preservedTokens.push(token);
  364. }
  365. content = content.replace(placeholder, ___PRESERVED_TOKEN_ + (preservedTokens.length - 1) + "___");
  366. continue;
  367. }
  368. // \ in the last position looks like hack for Mac/IE5
  369. // shorten that to /*\*/ and the next one to /**/
  370. if (token.charAt(token.length - 1) === "\\") {
  371. preservedTokens.push("\\");
  372. content = content.replace(placeholder, ___PRESERVED_TOKEN_ + (preservedTokens.length - 1) + "___");
  373. i = i + 1; // attn: advancing the loop
  374. preservedTokens.push("");
  375. content = content.replace(
  376. "___PRESERVE_CANDIDATE_COMMENT_" + i + "___",
  377. ___PRESERVED_TOKEN_ + (preservedTokens.length - 1) + "___"
  378. );
  379. continue;
  380. }
  381. // keep empty comments after child selectors (IE7 hack)
  382. // e.g. html >/**/ body
  383. if (token.length === 0) {
  384. const startIndex = content.indexOf(placeholder);
  385. if (startIndex > 2) {
  386. if (content.charAt(startIndex - 3) === ">") {
  387. preservedTokens.push("");
  388. content = content.replace(placeholder, ___PRESERVED_TOKEN_ + (preservedTokens.length - 1) + "___");
  389. }
  390. }
  391. }
  392. // in all other cases kill the comment
  393. content = content.replace(`/*${placeholder}*/`, "");
  394. }
  395. // parse simple @variables blocks and remove them
  396. if (options.expandVars) {
  397. const vars = {};
  398. pattern = REGEXP_VARIABLES;
  399. content = content.replace(pattern, (_, f1) => {
  400. pattern = REGEXP_VARIABLE;
  401. f1.replace(pattern, (_, f1, f2) => {
  402. if (f1 && f2) {
  403. vars[f1] = f2;
  404. }
  405. return "";
  406. });
  407. return "";
  408. });
  409. // replace var(x) with the value of x
  410. pattern = REGEXP_VARIABLE_VALUE;
  411. content = content.replace(pattern, (_, f1) => {
  412. return vars[f1] || "none";
  413. });
  414. }
  415. // normalize all whitespace strings to single spaces. Easier to work with that way.
  416. content = content.replace(REGEXP_WHITE_SPACES, " ");
  417. // preserve formulas in calc() before removing spaces
  418. pattern = REGEXP_PRESERVE_CALC;
  419. content = content.replace(pattern, (_, f1) => {
  420. preservedTokens.push(
  421. "calc(" +
  422. f1.replace(REGEXP_TRIM, "")
  423. .replace(REGEXP_PRESERVE_CALC2, "(")
  424. .replace(REGEXP_PRESERVE_CALC3, ")") +
  425. ")"
  426. );
  427. return ___PRESERVED_TOKEN_ + (preservedTokens.length - 1) + "___";
  428. });
  429. // preserve matrix
  430. pattern = REGEXP_PRESERVE_MATRIX;
  431. content = content.replace(pattern, (_, f1) => {
  432. preservedTokens.push(f1);
  433. return "filter:progid:DXImageTransform.Microsoft.Matrix(" + ___PRESERVED_TOKEN_ + (preservedTokens.length - 1) + "___);";
  434. });
  435. // remove the spaces before the things that should not have spaces before them.
  436. // but, be careful not to turn 'p :link {...}' into 'p:link{...}'
  437. // swap out any pseudo-class colons with the token, and then swap back.
  438. pattern = REGEXP_REMOVE_SPACES;
  439. content = content.replace(pattern, token => token.replace(REGEXP_COLUMN, "___PSEUDOCLASSCOLON___"));
  440. // remove spaces before the things that should not have spaces before them.
  441. content = content.replace(REGEXP_REMOVE_SPACES2, "$1");
  442. // restore spaces for !important
  443. content = content.replace(REGEXP_RESTORE_SPACE_IMPORTANT, " !important");
  444. // bring back the colon
  445. content = content.replace(REGEXP_PSEUDOCLASSCOLON, ":");
  446. // preserve 0 followed by a time unit for properties using time units
  447. pattern = REGEXP_PRESERVE_ZERO_UNIT;
  448. content = content.replace(pattern, (_, f1, f2) => {
  449. f2 = f2.replace(REGEXP_PRESERVE_ZERO_UNIT1, (_, g1, g2) => {
  450. preservedTokens.push("0" + g2);
  451. return g1 + ___PRESERVED_TOKEN_ + (preservedTokens.length - 1) + "___";
  452. });
  453. return f1 + ":" + f2;
  454. });
  455. // preserve unit for flex-basis within flex and flex-basis (ie10 bug)
  456. pattern = REGEXP_PRESERVE_FLEX;
  457. content = content.replace(pattern, (_, f1, f2) => {
  458. let f2b = f2.split(REGEXP_SPACES);
  459. preservedTokens.push(f2b.pop());
  460. f2b.push(___PRESERVED_TOKEN_ + (preservedTokens.length - 1) + "___");
  461. f2b = f2b.join(" ");
  462. return `${f1}:${f2b}`;
  463. });
  464. // preserve 0% in hsl and hsla color definitions
  465. content = content.replace(REGEXP_PRESERVE_HSLA, (_, f1, f2) => {
  466. const f0 = [];
  467. f2.split(",").forEach(part => {
  468. part = part.replace(REGEXP_PRESERVE_HSLA1, "");
  469. if (part === "0%") {
  470. preservedTokens.push("0%");
  471. f0.push(___PRESERVED_TOKEN_ + (preservedTokens.length - 1) + "___");
  472. } else {
  473. f0.push(part);
  474. }
  475. });
  476. return f1 + "(" + f0.join(",") + ")";
  477. });
  478. // preserve 0 followed by unit in keyframes steps (WIP)
  479. content = keyframes(content, preservedTokens);
  480. // retain space for special IE6 cases
  481. content = content.replace(REGEXP_RETAIN_SPACE_IE6, (_, f1, f2) => ":first-" + f1.toLowerCase() + " " + f2);
  482. // newlines before and after the end of a preserved comment
  483. if (options.cuteComments) {
  484. content = content.replace(REGEXP_NEWLINE1, "___PRESERVED_NEWLINE___/*");
  485. content = content.replace(REGEXP_NEWLINE2, "*/___PRESERVED_NEWLINE___");
  486. // no space after the end of a preserved comment
  487. } else {
  488. content = content.replace(REGEXP_NEWLINE2, "*/");
  489. }
  490. // If there are multiple @charset directives, push them to the top of the file.
  491. pattern = REGEXP_CHARSET;
  492. content = content.replace(pattern, (_, f1, f2, f3) => f2.toLowerCase() + f3 + f1);
  493. // When all @charset are at the top, remove the second and after (as they are completely ignored).
  494. pattern = REGEXP_REMOVE_SECOND_CHARSET;
  495. content = content.replace(pattern, (_, __, f2, f3, f4) => f2 + f3.toLowerCase() + f4);
  496. // lowercase some popular @directives (@charset is done right above)
  497. pattern = REGEXP_LOWERCASE_DIRECTIVES;
  498. content = content.replace(pattern, (_, f1) => "@" + f1.toLowerCase());
  499. // lowercase some more common pseudo-elements
  500. pattern = REGEXP_LOWERCASE_PSEUDO_ELEMENTS;
  501. content = content.replace(pattern, (_, f1) => ":" + f1.toLowerCase());
  502. // if there is a @charset, then only allow one, and push to the top of the file.
  503. content = content.replace(REGEXP_CHARSET2, "$2$1");
  504. content = content.replace(REGEXP_CHARSET3, "$1");
  505. // lowercase some more common functions
  506. pattern = REGEXP_LOWERCASE_FUNCTIONS;
  507. content = content.replace(pattern, (_, f1) => ":" + f1.toLowerCase() + "(");
  508. // lower case some common function that can be values
  509. // NOTE: rgb() isn't useful as we replace with #hex later, as well as and() is already done for us right after this
  510. pattern = REGEXP_LOWERCASE_FUNCTIONS2;
  511. content = content.replace(pattern, (_, f1, f2) => f1 + f2.toLowerCase());
  512. // put the space back in some cases, to support stuff like
  513. // @media screen and (-webkit-min-device-pixel-ratio:0){
  514. content = content.replace(REGEXP_RESTORE_SPACE1, "and (");
  515. content = content.replace(REGEXP_RESTORE_SPACE2, "$1not (");
  516. // remove the spaces after the things that should not have spaces after them.
  517. content = content.replace(REGEXP_REMOVE_SPACES3, "$1");
  518. // remove unnecessary semicolons
  519. content = content.replace(REGEXP_REMOVE_SEMI_COLUMNS, "}");
  520. // replace 0(px,em,%) with 0.
  521. content = content.replace(REGEXP_REPLACE_ZERO, "$10");
  522. // Replace x.0(px,em,%) with x(px,em,%).
  523. content = content.replace(REGEXP_REPLACE_ZERO_DOT, "$1$2");
  524. // replace 0 0 0 0; with 0.
  525. content = content.replace(REGEXP_REPLACE_4_ZEROS, ":0$1");
  526. content = content.replace(REGEXP_REPLACE_3_ZEROS, ":0$1");
  527. content = content.replace(REGEXP_REPLACE_2_ZEROS, ":0$1");
  528. // replace background-position:0; with background-position:0 0;
  529. // same for transform-origin and box-shadow
  530. pattern = REGEXP_REPLACE_1_ZERO;
  531. content = content.replace(pattern, (_, f1, f2) => f1.toLowerCase() + ":0 0" + f2);
  532. // replace 0.6 to .6, but only when preceded by : or a white-space
  533. content = content.replace(REGEXP_REPLACE_ZERO_DOT_DECIMAL, "$1.$2");
  534. // shorten colors from rgb(51,102,153) to #336699
  535. // this makes it more likely that it'll get further compressed in the next step.
  536. pattern = REGEXP_REPLACE_RGB;
  537. content = content.replace(pattern, (_, f1) => {
  538. let rgbcolors = f1.split(","), hexcolor = "#";
  539. for (let i = 0; i < rgbcolors.length; i += 1) {
  540. let val = parseInt(rgbcolors[i], 10);
  541. if (val < 16) {
  542. hexcolor += "0";
  543. }
  544. if (val > 255) {
  545. val = 255;
  546. }
  547. hexcolor += val.toString(16);
  548. }
  549. return hexcolor;
  550. });
  551. // Shorten colors from #AABBCC to #ABC.
  552. content = compressHexColors(content);
  553. // Replace #f00 -> red
  554. content = content.replace(REGEXP_REPLACE_HASH_COLOR, "$1red$3");
  555. // Replace other short color keywords
  556. content = content.replace(REGEXP_REPLACE_HASH_COLOR_SHORT1, "$1navy$3");
  557. content = content.replace(REGEXP_REPLACE_HASH_COLOR_SHORT2, "$1gray$3");
  558. content = content.replace(REGEXP_REPLACE_HASH_COLOR_SHORT3, "$1olive$3");
  559. content = content.replace(REGEXP_REPLACE_HASH_COLOR_SHORT4, "$1purple$3");
  560. content = content.replace(REGEXP_REPLACE_HASH_COLOR_SHORT5, "$1silver$3");
  561. content = content.replace(REGEXP_REPLACE_HASH_COLOR_SHORT6, "$1teal$3");
  562. content = content.replace(REGEXP_REPLACE_HASH_COLOR_SHORT7, "$1orange$3");
  563. content = content.replace(REGEXP_REPLACE_HASH_COLOR_SHORT8, "$1maroon$3");
  564. // border: none -> border:0
  565. pattern = REGEXP_REPLACE_BORDER_ZERO;
  566. content = content.replace(pattern, (_, f1, f2) => f1.toLowerCase() + ":0" + f2);
  567. // shorter opacity IE filter
  568. content = content.replace(REGEXP_REPLACE_IE_OPACITY, "alpha(opacity=");
  569. // Find a fraction that is used for Opera's -o-device-pixel-ratio query
  570. // Add token to add the '\' back in later
  571. content = content.replace(REGEXP_REPLACE_QUERY_FRACTION, "($1:$2___QUERY_FRACTION___$3)");
  572. // remove empty rules.
  573. // content = content.replace(REGEXP_EMPTY_RULES, "");
  574. // Add '\' back to fix Opera -o-device-pixel-ratio query
  575. content = content.replace(REGEXP_QUERY_FRACTION, "/");
  576. // some source control tools don't like it when files containing lines longer
  577. // than, say 8000 characters, are checked in. The linebreak option is used in
  578. // that case to split long lines after a specific column.
  579. if (options.maxLineLen > 0) {
  580. const lines = [];
  581. let line = [];
  582. for (let i = 0, len = content.length; i < len; i += 1) {
  583. const ch = content.charAt(i);
  584. line.push(ch);
  585. if (ch === "}" && line.length > options.maxLineLen) {
  586. lines.push(line.join(""));
  587. line = [];
  588. }
  589. }
  590. if (line.length) {
  591. lines.push(line.join(""));
  592. }
  593. content = lines.join("\n");
  594. }
  595. // replace multiple semi-colons in a row by a single one
  596. // see SF bug #1980989
  597. content = content.replace(REGEXP_REPLACE_SEMI_COLUMNS, ";");
  598. // trim the final string (for any leading or trailing white spaces)
  599. content = content.replace(REGEXP_TRIM, "");
  600. // restore preserved tokens
  601. for (let i = preservedTokens.length - 1; i >= 0; i--) {
  602. content = content.replace(___PRESERVED_TOKEN_ + i + "___", preservedTokens[i], "g");
  603. }
  604. // restore preserved newlines
  605. content = content.replace(REGEXP_PRESERVED_NEWLINE, "\n");
  606. // return
  607. return content;
  608. }
  609. return {
  610. defaultOptions,
  611. processString
  612. };
  613. })();