index.cjs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. var postcssBrowserComments = require('postcss-browser-comments');
  2. var Module = require('module');
  3. var path = require('path');
  4. var fs = require('fs');
  5. var postcss = require('postcss');
  6. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  7. var postcssBrowserComments__default = /*#__PURE__*/_interopDefaultLegacy(postcssBrowserComments);
  8. var Module__default = /*#__PURE__*/_interopDefaultLegacy(Module);
  9. var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
  10. var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
  11. var postcss__default = /*#__PURE__*/_interopDefaultLegacy(postcss);
  12. const assign = (...objects) => Object.assign(...objects);
  13. const create = (...objects) => assign(Object.create(null), ...objects);
  14. const currentFilename = __filename;
  15. const currentDirname = path__default['default'].dirname(currentFilename); // get resolved filenames for normalize.css
  16. const normalizeCSS = resolve('@csstools/normalize.css');
  17. const normalizeDir = path__default['default'].dirname(normalizeCSS);
  18. const normalizeOpinionatedCSS = path__default['default'].join(normalizeDir, 'opinionated.css'); // get resolved filenames for sanitize.css
  19. const sanitizeCSS = resolve('sanitize.css');
  20. const sanitizeDir = path__default['default'].dirname(sanitizeCSS);
  21. const sanitizeAssetsCSS = path__default['default'].join(sanitizeDir, 'assets.css');
  22. const sanitizeFormsCSS = path__default['default'].join(sanitizeDir, 'forms.css');
  23. const sanitizeReduceMotionCSS = path__default['default'].join(sanitizeDir, 'reduce-motion.css');
  24. const sanitizeTypographyCSS = path__default['default'].join(sanitizeDir, 'typography.css');
  25. const sanitizeSystemUiCSS = path__default['default'].join(sanitizeDir, 'system-ui.css');
  26. const sanitizeUiMonospace = path__default['default'].join(sanitizeDir, 'ui-monospace.css'); // export a hashmap of css library filenames
  27. const parsableFilenames = create({
  28. [normalizeCSS]: true,
  29. [normalizeOpinionatedCSS]: true,
  30. [sanitizeCSS]: true,
  31. [sanitizeAssetsCSS]: true,
  32. [sanitizeFormsCSS]: true,
  33. [sanitizeReduceMotionCSS]: true,
  34. [sanitizeTypographyCSS]: true,
  35. [sanitizeSystemUiCSS]: true,
  36. [sanitizeUiMonospace]: true
  37. }); // export a hashmap of css library filenames by id
  38. const resolvedFilenamesById = create({
  39. 'normalize': [normalizeCSS],
  40. 'normalize/opinionated': [normalizeOpinionatedCSS],
  41. 'normalize/*': [normalizeOpinionatedCSS],
  42. 'sanitize': [sanitizeCSS],
  43. 'sanitize/assets': [sanitizeAssetsCSS],
  44. 'sanitize/forms': [sanitizeCSS, sanitizeFormsCSS],
  45. 'sanitize/page': [sanitizeAssetsCSS],
  46. // deprecated; remaining for v10.0.0 compatibility
  47. 'sanitize/reduce-motion': [sanitizeCSS, sanitizeReduceMotionCSS],
  48. 'sanitize/system-ui': [sanitizeCSS, sanitizeSystemUiCSS],
  49. 'sanitize/typography': [sanitizeCSS, sanitizeTypographyCSS],
  50. 'sanitize/ui-monospace': [sanitizeCSS, sanitizeUiMonospace],
  51. 'sanitize/*': [sanitizeCSS, sanitizeFormsCSS]
  52. }); // get the resolved filename of a package/module
  53. function resolve(id) {
  54. return resolve[id] = resolve[id] || Module__default['default']._resolveFilename(id, {
  55. id: currentFilename,
  56. filename: currentFilename,
  57. paths: Module__default['default']._nodeModulePaths(currentDirname)
  58. });
  59. }
  60. const cache$1 = create();
  61. async function readFile(filename) {
  62. filename = path__default['default'].resolve(filename);
  63. cache$1[filename] = cache$1[filename] || create();
  64. return new Promise((resolve, reject) => fs__default['default'].stat(filename, (statsError, {
  65. mtime
  66. }) => statsError ? reject(statsError) : mtime === cache$1[filename].mtime ? resolve(cache$1[filename].data) : fs__default['default'].readFile(filename, 'utf8', (readFileError, data) => readFileError ? reject(readFileError) : resolve((cache$1[filename] = {
  67. data,
  68. mtime
  69. }).data))));
  70. }
  71. const cache = create(null);
  72. var parse = ((filename, transformer) => readFile(filename).then( // cache the parsed css root
  73. css => cache[css] = cache[css] || postcss__default['default'].parse(css, {
  74. from: filename
  75. })).then( // clone the cached root
  76. root => root.clone()).then( // transform the cloned root
  77. clone => Promise.resolve(transformer(clone)).then( // resolve the cloned root
  78. () => clone)));
  79. var postcssImportNormalize = (commentsTransformer => opts => {
  80. opts = create(opts); // return an postcss-import configuration
  81. return create({
  82. load(filename, importOptions) {
  83. return filename in parsableFilenames // parse the file (the file and css are conservatively cached)
  84. ? parse(filename, commentsTransformer).then(root => root.toResult({
  85. to: filename,
  86. map: true
  87. }).css) : typeof opts.load === 'function' // otherwise, use the override loader
  88. ? opts.load.call(null, filename, importOptions) // otherwise, return the (conservatively cached) contents of the file
  89. : readFile(filename);
  90. },
  91. resolve(id, basedir, importOptions) {
  92. // get the css id by removing css extensions
  93. const cssId = id.replace(cssExtRegExp$1, '');
  94. return cssId in resolvedFilenamesById // return the known resolved path for the css id
  95. ? resolvedFilenamesById[cssId] : typeof opts.resolve === 'function' // otherwise, use the override resolver
  96. ? opts.resolve.call(null, id, basedir, importOptions) // otherwise, return the id to be resolved by postcss-import
  97. : id;
  98. }
  99. });
  100. });
  101. const cssExtRegExp$1 = /\.css\b/g;
  102. const postcssPlugin = (commentsTransformer, opts) => root => {
  103. const promises = [];
  104. const insertedFilenames = {}; // use @import insertion point
  105. root.walkAtRules(importRegExp, atrule => {
  106. // get name as a fallback value for the library (e.g. @import-normalize is like @import "normalize.css")
  107. const name = atrule.name.match(importRegExp)[1]; // get url from "library", 'library', url("library"), url('library'), or the fallback value
  108. const url = (atrule.params.match(paramsRegExp) || []).slice(1).find(part => part) || name;
  109. if (url) {
  110. // get the css id by removing css extensions
  111. const cssId = url.replace(cssExtRegExp, '');
  112. if (cssId in resolvedFilenamesById) {
  113. // promise the library import is replaced with its contents
  114. promises.push(Promise.all(resolvedFilenamesById[cssId].filter( // ignore filenames that have already been inserted
  115. filename => insertedFilenames[filename] = opts.allowDuplicates || !(filename in insertedFilenames)).map( // parse the file (the file and css are conservatively cached)
  116. filename => parse(filename, commentsTransformer))).then(roots => {
  117. if (roots.length) {
  118. // combine all the library nodes returned by the parsed files
  119. const nodes = roots.reduce((all, root) => all.concat(root.nodes), []); // replace the import with all the library nodes
  120. atrule.replaceWith(...nodes);
  121. }
  122. }));
  123. }
  124. }
  125. });
  126. return Promise.all([].concat( // promise the library imports are replaced with their contents
  127. promises, // promise certain libraries are prepended
  128. Promise.all([].concat(opts.forceImport || []).reduce( // filter the id to be a known id or boolean true
  129. (all, id) => {
  130. if (id === true) {
  131. all.push(...resolvedFilenamesById.normalize);
  132. } else if (typeof id === 'string') {
  133. const cssId = id.replace(cssExtRegExp, '');
  134. if (cssId in resolvedFilenamesById) {
  135. all.push(...resolvedFilenamesById[cssId]);
  136. }
  137. }
  138. return all;
  139. }, []).filter( // ignore filenames that have already been inserted
  140. filename => insertedFilenames[filename] = opts.allowDuplicates || !(filename in insertedFilenames)).map( // parse the file (the file and css are conservatively cached)
  141. filename => parse(filename, commentsTransformer))).then(roots => {
  142. if (roots.length) {
  143. // combine all the library nodes returned by the parsed files
  144. const nodes = roots.reduce((all, root) => all.concat(root.nodes), []); // prepend the stylesheet with all the library nodes
  145. root.prepend(...nodes);
  146. }
  147. })));
  148. };
  149. const cssExtRegExp = /\.css\b/g;
  150. const importRegExp = /^import(?:-(normalize|sanitize))?$/;
  151. const paramsRegExp = /^\s*(?:url\((?:"(.+)"|'(.+)')\)|"(.+)"|'(.+)')[\W\w]*$/;
  152. const plugin = opts => {
  153. opts = create(opts);
  154. const commentsTransformer = postcssBrowserComments__default['default'](opts).Once;
  155. const normalizeTransformer = postcssPlugin(commentsTransformer, opts);
  156. const postcssImportConfig = postcssImportNormalize(commentsTransformer);
  157. return {
  158. postcssPlugin: 'postcss-normalize',
  159. Once(root) {
  160. return normalizeTransformer(root);
  161. },
  162. postcssImport: postcssImportConfig
  163. };
  164. };
  165. plugin.postcss = true;
  166. module.exports = plugin;