index.mjs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. import autoprefixer from 'autoprefixer';
  2. import browserslist from 'browserslist';
  3. import cssdb from 'cssdb';
  4. import postcss$1 from 'postcss';
  5. import postcssAttributeCaseInsensitive from 'postcss-attribute-case-insensitive';
  6. import postcssBlankPseudo from 'css-blank-pseudo/postcss';
  7. import postcssColorFunctionalNotation from 'postcss-color-functional-notation';
  8. import postcssColorGray from 'postcss-color-gray';
  9. import postcssColorHexAlpha from 'postcss-color-hex-alpha';
  10. import postcssColorModFunction from 'postcss-color-mod-function';
  11. import postcssColorRebeccapurple from 'postcss-color-rebeccapurple';
  12. import postcssCustomMedia from 'postcss-custom-media';
  13. import postcssCustomProperties from 'postcss-custom-properties';
  14. import postcssCustomSelectors from 'postcss-custom-selectors';
  15. import postcssDirPseudoClass from 'postcss-dir-pseudo-class';
  16. import postcssDoublePositionGradients from 'postcss-double-position-gradients';
  17. import postcssEnvFunction from 'postcss-env-function';
  18. import postcssFocusVisible from 'postcss-focus-visible';
  19. import postcssFocusWithin from 'postcss-focus-within';
  20. import postcssFontVariant from 'postcss-font-variant';
  21. import postcssGapProperties from 'postcss-gap-properties';
  22. import postcssHasPseudo from 'css-has-pseudo/postcss';
  23. import postcssImageSetPolyfill from 'postcss-image-set-function';
  24. import postcssInitial from 'postcss-initial';
  25. import postcssLabFunction from 'postcss-lab-function';
  26. import postcssLogical from 'postcss-logical';
  27. import postcssMediaMinmax from 'postcss-media-minmax';
  28. import postcssNesting from 'postcss-nesting';
  29. import postcssOverflowShorthand from 'postcss-overflow-shorthand';
  30. import postcssPageBreak from 'postcss-page-break';
  31. import postcssPlace from 'postcss-place';
  32. import postcssPrefersColorScheme from 'css-prefers-color-scheme/postcss';
  33. import postcssPseudoClassAnyLink from 'postcss-pseudo-class-any-link';
  34. import postcssReplaceOverflowWrap from 'postcss-replace-overflow-wrap';
  35. import postcssSelectorMatches from 'postcss-selector-matches';
  36. import postcssSelectorNot from 'postcss-selector-not';
  37. import { features, feature } from 'caniuse-lite';
  38. import fs from 'fs';
  39. import path from 'path';
  40. var postcssFontFamilySystemUi = postcss$1.plugin('postcss-system-ui-font', () => root => {
  41. root.walkDecls(propertyRegExp, decl => {
  42. decl.value = decl.value.replace(systemUiMatch, systemUiReplace);
  43. });
  44. });
  45. const propertyRegExp = /(?:^(?:-|\\002d){2})|(?:^font(?:-family)?$)/i;
  46. const whitespace = '[\\f\\n\\r\\x09\\x20]';
  47. const systemUiFamily = ['system-ui',
  48. /* macOS 10.11-10.12 */
  49. '-apple-system',
  50. /* Windows 6+ */
  51. 'Segoe UI',
  52. /* Android 4+ */
  53. 'Roboto',
  54. /* Ubuntu 10.10+ */
  55. 'Ubuntu',
  56. /* Gnome 3+ */
  57. 'Cantarell',
  58. /* KDE Plasma 5+ */
  59. 'Noto Sans',
  60. /* fallback */
  61. 'sans-serif'];
  62. const systemUiMatch = new RegExp(`(^|,|${whitespace}+)(?:system-ui${whitespace}*)(?:,${whitespace}*(?:${systemUiFamily.join('|')})${whitespace}*)?(,|$)`, 'i');
  63. const systemUiReplace = `$1${systemUiFamily.join(', ')}$2`;
  64. var plugins = {
  65. 'all-property': postcssInitial,
  66. 'any-link-pseudo-class': postcssPseudoClassAnyLink,
  67. 'blank-pseudo-class': postcssBlankPseudo,
  68. 'break-properties': postcssPageBreak,
  69. 'case-insensitive-attributes': postcssAttributeCaseInsensitive,
  70. 'color-functional-notation': postcssColorFunctionalNotation,
  71. 'color-mod-function': postcssColorModFunction,
  72. 'custom-media-queries': postcssCustomMedia,
  73. 'custom-properties': postcssCustomProperties,
  74. 'custom-selectors': postcssCustomSelectors,
  75. 'dir-pseudo-class': postcssDirPseudoClass,
  76. 'double-position-gradients': postcssDoublePositionGradients,
  77. 'environment-variables': postcssEnvFunction,
  78. 'focus-visible-pseudo-class': postcssFocusVisible,
  79. 'focus-within-pseudo-class': postcssFocusWithin,
  80. 'font-variant-property': postcssFontVariant,
  81. 'gap-properties': postcssGapProperties,
  82. 'gray-function': postcssColorGray,
  83. 'has-pseudo-class': postcssHasPseudo,
  84. 'hexadecimal-alpha-notation': postcssColorHexAlpha,
  85. 'image-set-function': postcssImageSetPolyfill,
  86. 'lab-function': postcssLabFunction,
  87. 'logical-properties-and-values': postcssLogical,
  88. 'matches-pseudo-class': postcssSelectorMatches,
  89. 'media-query-ranges': postcssMediaMinmax,
  90. 'nesting-rules': postcssNesting,
  91. 'not-pseudo-class': postcssSelectorNot,
  92. 'overflow-property': postcssOverflowShorthand,
  93. 'overflow-wrap-property': postcssReplaceOverflowWrap,
  94. 'place-properties': postcssPlace,
  95. 'prefers-color-scheme-query': postcssPrefersColorScheme,
  96. 'rebeccapurple-color': postcssColorRebeccapurple,
  97. 'system-ui-font-family': postcssFontFamilySystemUi
  98. };
  99. // return a list of features to be inserted before or after cssdb features
  100. function getTransformedInsertions(insertions, placement) {
  101. return Object.keys(insertions).map(id => [].concat(insertions[id]).map(plugin => ({
  102. [placement]: true,
  103. plugin,
  104. id
  105. }))).reduce((array, feature) => array.concat(feature), []);
  106. }
  107. function getUnsupportedBrowsersByFeature(feature$1) {
  108. const caniuseFeature = features[feature$1]; // if feature support can be determined
  109. if (caniuseFeature) {
  110. const stats = feature(caniuseFeature).stats; // return an array of browsers and versions that do not support the feature
  111. const results = Object.keys(stats).reduce((browsers, browser) => browsers.concat(Object.keys(stats[browser]).filter(version => stats[browser][version].indexOf('y') !== 0).map(version => `${browser} ${version}`)), []);
  112. return results;
  113. } else {
  114. // otherwise, return that the feature does not work in any browser
  115. return ['> 0%'];
  116. }
  117. }
  118. // ids ordered by required execution, then alphabetically
  119. var idsByExecutionOrder = ['custom-media-queries', 'custom-properties', 'environment-variables', // run environment-variables here to access transpiled custom media params and properties
  120. 'image-set-function', // run images-set-function before nesting-rules so that it may fix nested media
  121. 'media-query-ranges', // run media-query-range and
  122. 'prefers-color-scheme-query', // run prefers-color-scheme-query here to prevent duplicate transpilation after nesting-rules
  123. 'nesting-rules', 'custom-selectors', // run custom-selectors after nesting-rules to correctly transpile &:--custom-selector
  124. 'any-link-pseudo-class', 'case-insensitive-attributes', 'focus-visible-pseudo-class', 'focus-within-pseudo-class', 'matches-pseudo-class', // run matches-pseudo-class and
  125. 'not-pseudo-class', // run not-pseudo-class after other selectors have been transpiled
  126. 'logical-properties-and-values', // run logical-properties-and-values before dir-pseudo-class
  127. 'dir-pseudo-class', 'all-property', // run all-property before other property polyfills
  128. 'color-functional-notation', 'double-position-gradients', 'gray-function', 'hexadecimal-alpha-notation', 'lab-function', 'rebeccapurple-color', 'color-mod-function', // run color-mod after other color modifications have finished
  129. 'blank-pseudo-class', 'break-properties', 'font-variant-property', 'has-pseudo-class', 'gap-properties', 'overflow-property', 'overflow-wrap-property', 'place-properties', 'system-ui-font-family'];
  130. function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
  131. try {
  132. var info = gen[key](arg);
  133. var value = info.value;
  134. } catch (error) {
  135. reject(error);
  136. return;
  137. }
  138. if (info.done) {
  139. resolve(value);
  140. } else {
  141. Promise.resolve(value).then(_next, _throw);
  142. }
  143. }
  144. function _asyncToGenerator(fn) {
  145. return function () {
  146. var self = this,
  147. args = arguments;
  148. return new Promise(function (resolve, reject) {
  149. var gen = fn.apply(self, args);
  150. function _next(value) {
  151. asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
  152. }
  153. function _throw(err) {
  154. asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
  155. }
  156. _next(undefined);
  157. });
  158. };
  159. }
  160. /* Write Exports to CSS File
  161. /* ========================================================================== */
  162. function getCustomMediaAsCss(customMedia) {
  163. const cssContent = Object.keys(customMedia).reduce((cssLines, name) => {
  164. cssLines.push(`@custom-media ${name} ${customMedia[name]};`);
  165. return cssLines;
  166. }, []).join('\n');
  167. const css = `${cssContent}\n`;
  168. return css;
  169. }
  170. function getCustomPropertiesAsCss(customProperties) {
  171. const cssContent = Object.keys(customProperties).reduce((cssLines, name) => {
  172. cssLines.push(`\t${name}: ${customProperties[name]};`);
  173. return cssLines;
  174. }, []).join('\n');
  175. const css = `:root {\n${cssContent}\n}\n`;
  176. return css;
  177. }
  178. function getCustomSelectorsAsCss(customSelectors) {
  179. const cssContent = Object.keys(customSelectors).reduce((cssLines, name) => {
  180. cssLines.push(`@custom-selector ${name} ${customSelectors[name]};`);
  181. return cssLines;
  182. }, []).join('\n');
  183. const css = `${cssContent}\n`;
  184. return css;
  185. }
  186. function writeExportsToCssFile(_x, _x2, _x3, _x4) {
  187. return _writeExportsToCssFile.apply(this, arguments);
  188. }
  189. /* Write Exports to JSON file
  190. /* ========================================================================== */
  191. function _writeExportsToCssFile() {
  192. _writeExportsToCssFile = _asyncToGenerator(function* (to, customMedia, customProperties, customSelectors) {
  193. const customPropertiesAsCss = getCustomPropertiesAsCss(customProperties);
  194. const customMediaAsCss = getCustomMediaAsCss(customMedia);
  195. const customSelectorsAsCss = getCustomSelectorsAsCss(customSelectors);
  196. const css = `${customMediaAsCss}\n${customSelectorsAsCss}\n${customPropertiesAsCss}`;
  197. yield writeFile(to, css);
  198. });
  199. return _writeExportsToCssFile.apply(this, arguments);
  200. }
  201. function writeExportsToJsonFile(_x5, _x6, _x7, _x8) {
  202. return _writeExportsToJsonFile.apply(this, arguments);
  203. }
  204. /* Write Exports to Common JS file
  205. /* ========================================================================== */
  206. function _writeExportsToJsonFile() {
  207. _writeExportsToJsonFile = _asyncToGenerator(function* (to, customMedia, customProperties, customSelectors) {
  208. const jsonContent = JSON.stringify({
  209. 'custom-media': customMedia,
  210. 'custom-properties': customProperties,
  211. 'custom-selectors': customSelectors
  212. }, null, ' ');
  213. const json = `${jsonContent}\n`;
  214. yield writeFile(to, json);
  215. });
  216. return _writeExportsToJsonFile.apply(this, arguments);
  217. }
  218. function getObjectWithKeyAsCjs(key, object) {
  219. const jsContents = Object.keys(object).reduce((jsLines, name) => {
  220. jsLines.push(`\t\t'${escapeForJS(name)}': '${escapeForJS(object[name])}'`);
  221. return jsLines;
  222. }, []).join(',\n');
  223. const cjs = `\n\t${key}: {\n${jsContents}\n\t}`;
  224. return cjs;
  225. }
  226. function writeExportsToCjsFile(_x9, _x10, _x11, _x12) {
  227. return _writeExportsToCjsFile.apply(this, arguments);
  228. }
  229. /* Write Exports to Module JS file
  230. /* ========================================================================== */
  231. function _writeExportsToCjsFile() {
  232. _writeExportsToCjsFile = _asyncToGenerator(function* (to, customMedia, customProperties, customSelectors) {
  233. const customMediaAsCjs = getObjectWithKeyAsCjs('customMedia', customMedia);
  234. const customPropertiesAsCjs = getObjectWithKeyAsCjs('customProperties', customProperties);
  235. const customSelectorsAsCjs = getObjectWithKeyAsCjs('customSelectors', customSelectors);
  236. const cjs = `module.exports = {${customMediaAsCjs},${customPropertiesAsCjs},${customSelectorsAsCjs}\n};\n`;
  237. yield writeFile(to, cjs);
  238. });
  239. return _writeExportsToCjsFile.apply(this, arguments);
  240. }
  241. function getObjectWithKeyAsMjs(key, object) {
  242. const mjsContents = Object.keys(object).reduce((mjsLines, name) => {
  243. mjsLines.push(`\t'${escapeForJS(name)}': '${escapeForJS(object[name])}'`);
  244. return mjsLines;
  245. }, []).join(',\n');
  246. const mjs = `export const ${key} = {\n${mjsContents}\n};\n`;
  247. return mjs;
  248. }
  249. function writeExportsToMjsFile(_x13, _x14, _x15, _x16) {
  250. return _writeExportsToMjsFile.apply(this, arguments);
  251. }
  252. /* Write Exports to Exports
  253. /* ========================================================================== */
  254. function _writeExportsToMjsFile() {
  255. _writeExportsToMjsFile = _asyncToGenerator(function* (to, customMedia, customProperties, customSelectors) {
  256. const customMediaAsMjs = getObjectWithKeyAsMjs('customMedia', customMedia);
  257. const customPropertiesAsMjs = getObjectWithKeyAsMjs('customProperties', customProperties);
  258. const customSelectorsAsMjs = getObjectWithKeyAsMjs('customSelectors', customSelectors);
  259. const mjs = `${customMediaAsMjs}\n${customPropertiesAsMjs}\n${customSelectorsAsMjs}`;
  260. yield writeFile(to, mjs);
  261. });
  262. return _writeExportsToMjsFile.apply(this, arguments);
  263. }
  264. function writeToExports(customExports, destinations) {
  265. return Promise.all([].concat(destinations).map( /*#__PURE__*/function () {
  266. var _ref = _asyncToGenerator(function* (destination) {
  267. if (destination instanceof Function) {
  268. yield destination({
  269. customMedia: getObjectWithStringifiedKeys(customExports.customMedia),
  270. customProperties: getObjectWithStringifiedKeys(customExports.customProperties),
  271. customSelectors: getObjectWithStringifiedKeys(customExports.customSelectors)
  272. });
  273. } else {
  274. // read the destination as an object
  275. const opts = destination === Object(destination) ? destination : {
  276. to: String(destination)
  277. }; // transformer for Exports into a JSON-compatible object
  278. const toJSON = opts.toJSON || getObjectWithStringifiedKeys;
  279. if ('customMedia' in opts || 'customProperties' in opts || 'customSelectors' in opts) {
  280. // write directly to an object as customProperties
  281. opts.customMedia = toJSON(customExports.customMedia);
  282. opts.customProperties = toJSON(customExports.customProperties);
  283. opts.customSelectors = toJSON(customExports.customSelectors);
  284. } else if ('custom-media' in opts || 'custom-properties' in opts || 'custom-selectors' in opts) {
  285. // write directly to an object as custom-properties
  286. opts['custom-media'] = toJSON(customExports.customMedia);
  287. opts['custom-properties'] = toJSON(customExports.customProperties);
  288. opts['custom-selectors'] = toJSON(customExports.customSelectors);
  289. } else {
  290. // destination pathname
  291. const to = String(opts.to || ''); // type of file being written to
  292. const type = (opts.type || path.extname(opts.to).slice(1)).toLowerCase(); // transformed Exports
  293. const customMediaJSON = toJSON(customExports.customMedia);
  294. const customPropertiesJSON = toJSON(customExports.customProperties);
  295. const customSelectorsJSON = toJSON(customExports.customSelectors);
  296. if (type === 'css') {
  297. yield writeExportsToCssFile(to, customMediaJSON, customPropertiesJSON, customSelectorsJSON);
  298. }
  299. if (type === 'js') {
  300. yield writeExportsToCjsFile(to, customMediaJSON, customPropertiesJSON, customSelectorsJSON);
  301. }
  302. if (type === 'json') {
  303. yield writeExportsToJsonFile(to, customMediaJSON, customPropertiesJSON, customSelectorsJSON);
  304. }
  305. if (type === 'mjs') {
  306. yield writeExportsToMjsFile(to, customMediaJSON, customPropertiesJSON, customSelectorsJSON);
  307. }
  308. }
  309. }
  310. });
  311. return function (_x17) {
  312. return _ref.apply(this, arguments);
  313. };
  314. }()));
  315. }
  316. /* Helper utilities
  317. /* ========================================================================== */
  318. function getObjectWithStringifiedKeys(object) {
  319. return Object.keys(object).reduce((objectJSON, key) => {
  320. objectJSON[key] = String(object[key]);
  321. return objectJSON;
  322. }, {});
  323. }
  324. function writeFile(to, text) {
  325. return new Promise((resolve, reject) => {
  326. fs.writeFile(to, text, error => {
  327. if (error) {
  328. reject(error);
  329. } else {
  330. resolve();
  331. }
  332. });
  333. });
  334. }
  335. function escapeForJS(string) {
  336. return string.replace(/\\([\s\S])|(')/g, '\\$1$2').replace(/\n/g, '\\n').replace(/\r/g, '\\r');
  337. }
  338. var postcss = postcss$1.plugin('postcss-preset-env', opts => {
  339. // initialize options
  340. const features = Object(Object(opts).features);
  341. const insertBefore = Object(Object(opts).insertBefore);
  342. const insertAfter = Object(Object(opts).insertAfter);
  343. const browsers = Object(opts).browsers;
  344. const stage = 'stage' in Object(opts) ? opts.stage === false ? 5 : parseInt(opts.stage) || 0 : 2;
  345. const autoprefixerOptions = Object(opts).autoprefixer;
  346. const sharedOpts = initializeSharedOpts(Object(opts));
  347. const stagedAutoprefixer = autoprefixerOptions === false ? () => {} : autoprefixer(Object.assign({
  348. overrideBrowserslist: browsers
  349. }, autoprefixerOptions)); // polyfillable features (those with an available postcss plugin)
  350. const polyfillableFeatures = cssdb.concat( // additional features to be inserted before cssdb features
  351. getTransformedInsertions(insertBefore, 'insertBefore'), // additional features to be inserted after cssdb features
  352. getTransformedInsertions(insertAfter, 'insertAfter')).filter( // inserted features or features with an available postcss plugin
  353. feature => feature.insertBefore || feature.id in plugins).sort( // features sorted by execution order and then insertion order
  354. (a, b) => idsByExecutionOrder.indexOf(a.id) - idsByExecutionOrder.indexOf(b.id) || (a.insertBefore ? -1 : b.insertBefore ? 1 : 0) || (a.insertAfter ? 1 : b.insertAfter ? -1 : 0)).map( // polyfillable features as an object
  355. feature => {
  356. // target browsers for the polyfill
  357. const unsupportedBrowsers = getUnsupportedBrowsersByFeature(feature.caniuse);
  358. return feature.insertBefore || feature.insertAfter ? {
  359. browsers: unsupportedBrowsers,
  360. plugin: feature.plugin,
  361. id: `${feature.insertBefore ? 'before' : 'after'}-${feature.id}`,
  362. stage: 6
  363. } : {
  364. browsers: unsupportedBrowsers,
  365. plugin: plugins[feature.id],
  366. id: feature.id,
  367. stage: feature.stage
  368. };
  369. }); // staged features (those at or above the selected stage)
  370. const stagedFeatures = polyfillableFeatures.filter(feature => feature.id in features ? features[feature.id] : feature.stage >= stage).map(feature => ({
  371. browsers: feature.browsers,
  372. plugin: typeof feature.plugin.process === 'function' ? features[feature.id] === true ? sharedOpts // if the plugin is enabled and has shared options
  373. ? feature.plugin(Object.assign({}, sharedOpts)) // otherwise, if the plugin is enabled
  374. : feature.plugin() : sharedOpts // if the plugin has shared options and individual options
  375. ? feature.plugin(Object.assign({}, sharedOpts, features[feature.id])) // if the plugin has individual options
  376. : feature.plugin(Object.assign({}, features[feature.id])) // if the plugin is already initialized
  377. : feature.plugin,
  378. id: feature.id
  379. })); // browsers supported by the configuration
  380. const supportedBrowsers = browserslist(browsers, {
  381. ignoreUnknownVersions: true
  382. }); // features supported by the stage and browsers
  383. const supportedFeatures = stagedFeatures.filter(feature => supportedBrowsers.some(supportedBrowser => browserslist(feature.browsers, {
  384. ignoreUnknownVersions: true
  385. }).some(polyfillBrowser => polyfillBrowser === supportedBrowser)));
  386. return (root, result) => {
  387. const majorVersion = parseInt(result.processor.version.split('.')[0]);
  388. if (majorVersion > 7) {
  389. console.log('');
  390. console.log(`
  391. ┌─────────────────────────────────────────────────────────────────────────────────┐
  392. │ │
  393. │ This version of postcss-preset-env is not optimised to work with PostCSS 8. │
  394. │ Please update to version 7 of PostCSS Preset Env. │
  395. │ │
  396. │ If you find issues, you can report it at: │
  397. │ https://github.com/csstools/postcss-plugins/issues/new/choose │
  398. │ │
  399. └─────────────────────────────────────────────────────────────────────────────────┘
  400. `);
  401. console.log('');
  402. } // polyfills run in execution order
  403. const polyfills = supportedFeatures.reduce((promise, feature) => promise.then(() => feature.plugin(result.root, result)), Promise.resolve()).then(() => stagedAutoprefixer(result.root, result)).then(() => {
  404. if (Object(opts).exportTo) {
  405. writeToExports(sharedOpts.exportTo, opts.exportTo);
  406. }
  407. });
  408. return polyfills;
  409. };
  410. });
  411. const initializeSharedOpts = opts => {
  412. if ('importFrom' in opts || 'exportTo' in opts || 'preserve' in opts) {
  413. const sharedOpts = {};
  414. if ('importFrom' in opts) {
  415. sharedOpts.importFrom = opts.importFrom;
  416. }
  417. if ('exportTo' in opts) {
  418. sharedOpts.exportTo = {
  419. customMedia: {},
  420. customProperties: {},
  421. customSelectors: {}
  422. };
  423. }
  424. if ('preserve' in opts) {
  425. sharedOpts.preserve = opts.preserve;
  426. }
  427. return sharedOpts;
  428. }
  429. return false;
  430. };
  431. export default postcss;
  432. //# sourceMappingURL=index.mjs.map