css-uglifycss.js 24 KB

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