map-generator.js 9.9 KB

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