map-generator.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. 'use strict'
  2. let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js')
  3. let { dirname, relative, resolve, sep } = require('path')
  4. let { pathToFileURL } = require('url')
  5. let Input = require('./input')
  6. let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator)
  7. let pathAvailable = Boolean(dirname && resolve && relative && sep)
  8. class MapGenerator {
  9. constructor(stringify, root, opts, cssString) {
  10. this.stringify = stringify
  11. this.mapOpts = opts.map || {}
  12. this.root = root
  13. this.opts = opts
  14. this.css = cssString
  15. this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute
  16. }
  17. addAnnotation() {
  18. let content
  19. if (this.isInline()) {
  20. content =
  21. 'data:application/json;base64,' + this.toBase64(this.map.toString())
  22. } else if (typeof this.mapOpts.annotation === 'string') {
  23. content = this.mapOpts.annotation
  24. } else if (typeof this.mapOpts.annotation === 'function') {
  25. content = this.mapOpts.annotation(this.opts.to, this.root)
  26. } else {
  27. content = this.outputFile() + '.map'
  28. }
  29. let eol = '\n'
  30. if (this.css.includes('\r\n')) eol = '\r\n'
  31. this.css += eol + '/*# sourceMappingURL=' + content + ' */'
  32. }
  33. applyPrevMaps() {
  34. for (let prev of this.previous()) {
  35. let from = this.toUrl(this.path(prev.file))
  36. let root = prev.root || dirname(prev.file)
  37. let map
  38. if (this.mapOpts.sourcesContent === false) {
  39. map = new SourceMapConsumer(prev.text)
  40. if (map.sourcesContent) {
  41. map.sourcesContent = map.sourcesContent.map(() => null)
  42. }
  43. } else {
  44. map = prev.consumer()
  45. }
  46. this.map.applySourceMap(map, from, this.toUrl(this.path(root)))
  47. }
  48. }
  49. clearAnnotation() {
  50. if (this.mapOpts.annotation === false) return
  51. if (this.root) {
  52. let node
  53. for (let i = this.root.nodes.length - 1; i >= 0; i--) {
  54. node = this.root.nodes[i]
  55. if (node.type !== 'comment') continue
  56. if (node.text.indexOf('# sourceMappingURL=') === 0) {
  57. this.root.removeChild(i)
  58. }
  59. }
  60. } else if (this.css) {
  61. this.css = this.css.replace(/(\n)?\/\*#[\S\s]*?\*\/$/gm, '')
  62. }
  63. }
  64. generate() {
  65. this.clearAnnotation()
  66. if (pathAvailable && sourceMapAvailable && this.isMap()) {
  67. return this.generateMap()
  68. } else {
  69. let result = ''
  70. this.stringify(this.root, i => {
  71. result += i
  72. })
  73. return [result]
  74. }
  75. }
  76. generateMap() {
  77. if (this.root) {
  78. this.generateString()
  79. } else if (this.previous().length === 1) {
  80. let prev = this.previous()[0].consumer()
  81. prev.file = this.outputFile()
  82. this.map = SourceMapGenerator.fromSourceMap(prev)
  83. } else {
  84. this.map = new SourceMapGenerator({ file: this.outputFile() })
  85. this.map.addMapping({
  86. generated: { column: 0, line: 1 },
  87. original: { column: 0, line: 1 },
  88. source: this.opts.from
  89. ? this.toUrl(this.path(this.opts.from))
  90. : '<no source>'
  91. })
  92. }
  93. if (this.isSourcesContent()) this.setSourcesContent()
  94. if (this.root && this.previous().length > 0) this.applyPrevMaps()
  95. if (this.isAnnotation()) this.addAnnotation()
  96. if (this.isInline()) {
  97. return [this.css]
  98. } else {
  99. return [this.css, this.map]
  100. }
  101. }
  102. generateString() {
  103. this.css = ''
  104. this.map = new SourceMapGenerator({ file: this.outputFile() })
  105. let line = 1
  106. let column = 1
  107. let noSource = '<no source>'
  108. let mapping = {
  109. generated: { column: 0, line: 0 },
  110. original: { column: 0, line: 0 },
  111. source: ''
  112. }
  113. let lines, last
  114. this.stringify(this.root, (str, node, type) => {
  115. this.css += str
  116. if (node && type !== 'end') {
  117. mapping.generated.line = line
  118. mapping.generated.column = column - 1
  119. if (node.source && node.source.start) {
  120. mapping.source = this.sourcePath(node)
  121. mapping.original.line = node.source.start.line
  122. mapping.original.column = node.source.start.column - 1
  123. this.map.addMapping(mapping)
  124. } else {
  125. mapping.source = noSource
  126. mapping.original.line = 1
  127. mapping.original.column = 0
  128. this.map.addMapping(mapping)
  129. }
  130. }
  131. lines = str.match(/\n/g)
  132. if (lines) {
  133. line += lines.length
  134. last = str.lastIndexOf('\n')
  135. column = str.length - last
  136. } else {
  137. column += str.length
  138. }
  139. if (node && type !== 'start') {
  140. let p = node.parent || { raws: {} }
  141. let childless =
  142. node.type === 'decl' || (node.type === 'atrule' && !node.nodes)
  143. if (!childless || node !== p.last || p.raws.semicolon) {
  144. if (node.source && node.source.end) {
  145. mapping.source = this.sourcePath(node)
  146. mapping.original.line = node.source.end.line
  147. mapping.original.column = node.source.end.column - 1
  148. mapping.generated.line = line
  149. mapping.generated.column = column - 2
  150. this.map.addMapping(mapping)
  151. } else {
  152. mapping.source = noSource
  153. mapping.original.line = 1
  154. mapping.original.column = 0
  155. mapping.generated.line = line
  156. mapping.generated.column = column - 1
  157. this.map.addMapping(mapping)
  158. }
  159. }
  160. }
  161. })
  162. }
  163. isAnnotation() {
  164. if (this.isInline()) {
  165. return true
  166. }
  167. if (typeof this.mapOpts.annotation !== 'undefined') {
  168. return this.mapOpts.annotation
  169. }
  170. if (this.previous().length) {
  171. return this.previous().some(i => i.annotation)
  172. }
  173. return true
  174. }
  175. isInline() {
  176. if (typeof this.mapOpts.inline !== 'undefined') {
  177. return this.mapOpts.inline
  178. }
  179. let annotation = this.mapOpts.annotation
  180. if (typeof annotation !== 'undefined' && annotation !== true) {
  181. return false
  182. }
  183. if (this.previous().length) {
  184. return this.previous().some(i => i.inline)
  185. }
  186. return true
  187. }
  188. isMap() {
  189. if (typeof this.opts.map !== 'undefined') {
  190. return !!this.opts.map
  191. }
  192. return this.previous().length > 0
  193. }
  194. isSourcesContent() {
  195. if (typeof this.mapOpts.sourcesContent !== 'undefined') {
  196. return this.mapOpts.sourcesContent
  197. }
  198. if (this.previous().length) {
  199. return this.previous().some(i => i.withContent())
  200. }
  201. return true
  202. }
  203. outputFile() {
  204. if (this.opts.to) {
  205. return this.path(this.opts.to)
  206. } else if (this.opts.from) {
  207. return this.path(this.opts.from)
  208. } else {
  209. return 'to.css'
  210. }
  211. }
  212. path(file) {
  213. if (file.indexOf('<') === 0) return file
  214. if (/^\w+:\/\//.test(file)) return file
  215. if (this.mapOpts.absolute) return file
  216. let from = this.opts.to ? dirname(this.opts.to) : '.'
  217. if (typeof this.mapOpts.annotation === 'string') {
  218. from = dirname(resolve(from, this.mapOpts.annotation))
  219. }
  220. file = relative(from, file)
  221. return file
  222. }
  223. previous() {
  224. if (!this.previousMaps) {
  225. this.previousMaps = []
  226. if (this.root) {
  227. this.root.walk(node => {
  228. if (node.source && node.source.input.map) {
  229. let map = node.source.input.map
  230. if (!this.previousMaps.includes(map)) {
  231. this.previousMaps.push(map)
  232. }
  233. }
  234. })
  235. } else {
  236. let input = new Input(this.css, this.opts)
  237. if (input.map) this.previousMaps.push(input.map)
  238. }
  239. }
  240. return this.previousMaps
  241. }
  242. setSourcesContent() {
  243. let already = {}
  244. if (this.root) {
  245. this.root.walk(node => {
  246. if (node.source) {
  247. let from = node.source.input.from
  248. if (from && !already[from]) {
  249. already[from] = true
  250. let fromUrl = this.usesFileUrls
  251. ? this.toFileUrl(from)
  252. : this.toUrl(this.path(from))
  253. this.map.setSourceContent(fromUrl, node.source.input.css)
  254. }
  255. }
  256. })
  257. } else if (this.css) {
  258. let from = this.opts.from
  259. ? this.toUrl(this.path(this.opts.from))
  260. : '<no source>'
  261. this.map.setSourceContent(from, this.css)
  262. }
  263. }
  264. sourcePath(node) {
  265. if (this.mapOpts.from) {
  266. return this.toUrl(this.mapOpts.from)
  267. } else if (this.usesFileUrls) {
  268. return this.toFileUrl(node.source.input.from)
  269. } else {
  270. return this.toUrl(this.path(node.source.input.from))
  271. }
  272. }
  273. toBase64(str) {
  274. if (Buffer) {
  275. return Buffer.from(str).toString('base64')
  276. } else {
  277. return window.btoa(unescape(encodeURIComponent(str)))
  278. }
  279. }
  280. toFileUrl(path) {
  281. if (pathToFileURL) {
  282. return pathToFileURL(path).toString()
  283. } else {
  284. throw new Error(
  285. '`map.absolute` option is not available in this PostCSS build'
  286. )
  287. }
  288. }
  289. toUrl(path) {
  290. if (sep === '\\') {
  291. path = path.replace(/\\/g, '/')
  292. }
  293. return encodeURI(path).replace(/[#?]/g, encodeURIComponent)
  294. }
  295. }
  296. module.exports = MapGenerator