index.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. "use strict"
  2. // builtin tooling
  3. const path = require("path")
  4. // internal tooling
  5. const joinMedia = require("./lib/join-media")
  6. const joinLayer = require("./lib/join-layer")
  7. const resolveId = require("./lib/resolve-id")
  8. const loadContent = require("./lib/load-content")
  9. const processContent = require("./lib/process-content")
  10. const parseStatements = require("./lib/parse-statements")
  11. const assignLayerNames = require("./lib/assign-layer-names")
  12. const dataURL = require("./lib/data-url")
  13. function AtImport(options) {
  14. options = {
  15. root: process.cwd(),
  16. path: [],
  17. skipDuplicates: true,
  18. resolve: resolveId,
  19. load: loadContent,
  20. plugins: [],
  21. addModulesDirectories: [],
  22. nameLayer: null,
  23. ...options,
  24. }
  25. options.root = path.resolve(options.root)
  26. // convert string to an array of a single element
  27. if (typeof options.path === "string") options.path = [options.path]
  28. if (!Array.isArray(options.path)) options.path = []
  29. options.path = options.path.map(p => path.resolve(options.root, p))
  30. return {
  31. postcssPlugin: "postcss-import",
  32. Once(styles, { result, atRule, postcss }) {
  33. const state = {
  34. importedFiles: {},
  35. hashFiles: {},
  36. rootFilename: null,
  37. anonymousLayerCounter: 0,
  38. }
  39. if (styles.source?.input?.file) {
  40. state.rootFilename = styles.source.input.file
  41. state.importedFiles[styles.source.input.file] = {}
  42. }
  43. if (options.plugins && !Array.isArray(options.plugins)) {
  44. throw new Error("plugins option must be an array")
  45. }
  46. if (options.nameLayer && typeof options.nameLayer !== "function") {
  47. throw new Error("nameLayer option must be a function")
  48. }
  49. return parseStyles(result, styles, options, state, [], []).then(
  50. bundle => {
  51. applyRaws(bundle)
  52. applyMedia(bundle)
  53. applyStyles(bundle, styles)
  54. }
  55. )
  56. function applyRaws(bundle) {
  57. bundle.forEach((stmt, index) => {
  58. if (index === 0) return
  59. if (stmt.parent) {
  60. const { before } = stmt.parent.node.raws
  61. if (stmt.type === "nodes") stmt.nodes[0].raws.before = before
  62. else stmt.node.raws.before = before
  63. } else if (stmt.type === "nodes") {
  64. stmt.nodes[0].raws.before = stmt.nodes[0].raws.before || "\n"
  65. }
  66. })
  67. }
  68. function applyMedia(bundle) {
  69. bundle.forEach(stmt => {
  70. if (
  71. (!stmt.media.length && !stmt.layer.length) ||
  72. stmt.type === "charset"
  73. ) {
  74. return
  75. }
  76. if (stmt.layer.length > 1) {
  77. assignLayerNames(stmt.layer, stmt.node, state, options)
  78. }
  79. if (stmt.type === "import") {
  80. const parts = [stmt.fullUri]
  81. const media = stmt.media.join(", ")
  82. if (stmt.layer.length) {
  83. const layerName = stmt.layer.join(".")
  84. let layerParams = "layer"
  85. if (layerName) {
  86. layerParams = `layer(${layerName})`
  87. }
  88. parts.push(layerParams)
  89. }
  90. if (media) {
  91. parts.push(media)
  92. }
  93. stmt.node.params = parts.join(" ")
  94. } else if (stmt.type === "media") {
  95. if (stmt.layer.length) {
  96. const layerNode = atRule({
  97. name: "layer",
  98. params: stmt.layer.join("."),
  99. source: stmt.node.source,
  100. })
  101. if (stmt.parentMedia?.length) {
  102. const mediaNode = atRule({
  103. name: "media",
  104. params: stmt.parentMedia.join(", "),
  105. source: stmt.node.source,
  106. })
  107. mediaNode.append(layerNode)
  108. layerNode.append(stmt.node)
  109. stmt.node = mediaNode
  110. } else {
  111. layerNode.append(stmt.node)
  112. stmt.node = layerNode
  113. }
  114. } else {
  115. stmt.node.params = stmt.media.join(", ")
  116. }
  117. } else {
  118. const { nodes } = stmt
  119. const { parent } = nodes[0]
  120. let outerAtRule
  121. let innerAtRule
  122. if (stmt.media.length && stmt.layer.length) {
  123. const mediaNode = atRule({
  124. name: "media",
  125. params: stmt.media.join(", "),
  126. source: parent.source,
  127. })
  128. const layerNode = atRule({
  129. name: "layer",
  130. params: stmt.layer.join("."),
  131. source: parent.source,
  132. })
  133. mediaNode.append(layerNode)
  134. innerAtRule = layerNode
  135. outerAtRule = mediaNode
  136. } else if (stmt.media.length) {
  137. const mediaNode = atRule({
  138. name: "media",
  139. params: stmt.media.join(", "),
  140. source: parent.source,
  141. })
  142. innerAtRule = mediaNode
  143. outerAtRule = mediaNode
  144. } else if (stmt.layer.length) {
  145. const layerNode = atRule({
  146. name: "layer",
  147. params: stmt.layer.join("."),
  148. source: parent.source,
  149. })
  150. innerAtRule = layerNode
  151. outerAtRule = layerNode
  152. }
  153. parent.insertBefore(nodes[0], outerAtRule)
  154. // remove nodes
  155. nodes.forEach(node => {
  156. node.parent = undefined
  157. })
  158. // better output
  159. nodes[0].raws.before = nodes[0].raws.before || "\n"
  160. // wrap new rules with media query and/or layer at rule
  161. innerAtRule.append(nodes)
  162. stmt.type = "media"
  163. stmt.node = outerAtRule
  164. delete stmt.nodes
  165. }
  166. })
  167. }
  168. function applyStyles(bundle, styles) {
  169. styles.nodes = []
  170. // Strip additional statements.
  171. bundle.forEach(stmt => {
  172. if (["charset", "import", "media"].includes(stmt.type)) {
  173. stmt.node.parent = undefined
  174. styles.append(stmt.node)
  175. } else if (stmt.type === "nodes") {
  176. stmt.nodes.forEach(node => {
  177. node.parent = undefined
  178. styles.append(node)
  179. })
  180. }
  181. })
  182. }
  183. function parseStyles(result, styles, options, state, media, layer) {
  184. const statements = parseStatements(result, styles)
  185. return Promise.resolve(statements)
  186. .then(stmts => {
  187. // process each statement in series
  188. return stmts.reduce((promise, stmt) => {
  189. return promise.then(() => {
  190. stmt.media = joinMedia(media, stmt.media || [])
  191. stmt.parentMedia = media
  192. stmt.layer = joinLayer(layer, stmt.layer || [])
  193. // skip protocol base uri (protocol://url) or protocol-relative
  194. if (
  195. stmt.type !== "import" ||
  196. /^(?:[a-z]+:)?\/\//i.test(stmt.uri)
  197. ) {
  198. return
  199. }
  200. if (options.filter && !options.filter(stmt.uri)) {
  201. // rejected by filter
  202. return
  203. }
  204. return resolveImportId(result, stmt, options, state)
  205. })
  206. }, Promise.resolve())
  207. })
  208. .then(() => {
  209. let charset
  210. const imports = []
  211. const bundle = []
  212. function handleCharset(stmt) {
  213. if (!charset) charset = stmt
  214. // charsets aren't case-sensitive, so convert to lower case to compare
  215. else if (
  216. stmt.node.params.toLowerCase() !==
  217. charset.node.params.toLowerCase()
  218. ) {
  219. throw new Error(
  220. `Incompatable @charset statements:
  221. ${stmt.node.params} specified in ${stmt.node.source.input.file}
  222. ${charset.node.params} specified in ${charset.node.source.input.file}`
  223. )
  224. }
  225. }
  226. // squash statements and their children
  227. statements.forEach(stmt => {
  228. if (stmt.type === "charset") handleCharset(stmt)
  229. else if (stmt.type === "import") {
  230. if (stmt.children) {
  231. stmt.children.forEach((child, index) => {
  232. if (child.type === "import") imports.push(child)
  233. else if (child.type === "charset") handleCharset(child)
  234. else bundle.push(child)
  235. // For better output
  236. if (index === 0) child.parent = stmt
  237. })
  238. } else imports.push(stmt)
  239. } else if (stmt.type === "media" || stmt.type === "nodes") {
  240. bundle.push(stmt)
  241. }
  242. })
  243. return charset
  244. ? [charset, ...imports.concat(bundle)]
  245. : imports.concat(bundle)
  246. })
  247. }
  248. function resolveImportId(result, stmt, options, state) {
  249. if (dataURL.isValid(stmt.uri)) {
  250. return loadImportContent(result, stmt, stmt.uri, options, state).then(
  251. result => {
  252. stmt.children = result
  253. }
  254. )
  255. }
  256. const atRule = stmt.node
  257. let sourceFile
  258. if (atRule.source?.input?.file) {
  259. sourceFile = atRule.source.input.file
  260. }
  261. const base = sourceFile
  262. ? path.dirname(atRule.source.input.file)
  263. : options.root
  264. return Promise.resolve(options.resolve(stmt.uri, base, options))
  265. .then(paths => {
  266. if (!Array.isArray(paths)) paths = [paths]
  267. // Ensure that each path is absolute:
  268. return Promise.all(
  269. paths.map(file => {
  270. return !path.isAbsolute(file)
  271. ? resolveId(file, base, options)
  272. : file
  273. })
  274. )
  275. })
  276. .then(resolved => {
  277. // Add dependency messages:
  278. resolved.forEach(file => {
  279. result.messages.push({
  280. type: "dependency",
  281. plugin: "postcss-import",
  282. file,
  283. parent: sourceFile,
  284. })
  285. })
  286. return Promise.all(
  287. resolved.map(file => {
  288. return loadImportContent(result, stmt, file, options, state)
  289. })
  290. )
  291. })
  292. .then(result => {
  293. // Merge loaded statements
  294. stmt.children = result.reduce((result, statements) => {
  295. return statements ? result.concat(statements) : result
  296. }, [])
  297. })
  298. }
  299. function loadImportContent(result, stmt, filename, options, state) {
  300. const atRule = stmt.node
  301. const { media, layer } = stmt
  302. assignLayerNames(layer, atRule, state, options)
  303. if (options.skipDuplicates) {
  304. // skip files already imported at the same scope
  305. if (state.importedFiles[filename]?.[media]?.[layer]) {
  306. return
  307. }
  308. // save imported files to skip them next time
  309. if (!state.importedFiles[filename]) {
  310. state.importedFiles[filename] = {}
  311. }
  312. if (!state.importedFiles[filename][media]) {
  313. state.importedFiles[filename][media] = {}
  314. }
  315. state.importedFiles[filename][media][layer] = true
  316. }
  317. return Promise.resolve(options.load(filename, options)).then(
  318. content => {
  319. if (content.trim() === "") {
  320. result.warn(`${filename} is empty`, { node: atRule })
  321. return
  322. }
  323. // skip previous imported files not containing @import rules
  324. if (state.hashFiles[content]?.[media]?.[layer]) {
  325. return
  326. }
  327. return processContent(
  328. result,
  329. content,
  330. filename,
  331. options,
  332. postcss
  333. ).then(importedResult => {
  334. const styles = importedResult.root
  335. result.messages = result.messages.concat(importedResult.messages)
  336. if (options.skipDuplicates) {
  337. const hasImport = styles.some(child => {
  338. return child.type === "atrule" && child.name === "import"
  339. })
  340. if (!hasImport) {
  341. // save hash files to skip them next time
  342. if (!state.hashFiles[content]) {
  343. state.hashFiles[content] = {}
  344. }
  345. if (!state.hashFiles[content][media]) {
  346. state.hashFiles[content][media] = {}
  347. }
  348. state.hashFiles[content][media][layer] = true
  349. }
  350. }
  351. // recursion: import @import from imported file
  352. return parseStyles(result, styles, options, state, media, layer)
  353. })
  354. }
  355. )
  356. }
  357. },
  358. }
  359. }
  360. AtImport.postcss = true
  361. module.exports = AtImport