parse.ts 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. import {
  2. NodeTypes,
  3. ElementNode,
  4. SourceLocation,
  5. CompilerError,
  6. TextModes
  7. } from '@vue/compiler-core'
  8. import { RawSourceMap, SourceMapGenerator } from 'source-map'
  9. import { generateCodeFrame } from '@vue/shared'
  10. import { TemplateCompiler } from './compileTemplate'
  11. import * as CompilerDOM from '@vue/compiler-dom'
  12. export interface SFCParseOptions {
  13. filename?: string
  14. sourceMap?: boolean
  15. sourceRoot?: string
  16. pad?: boolean | 'line' | 'space'
  17. compiler?: TemplateCompiler
  18. }
  19. export interface SFCBlock {
  20. type: string
  21. content: string
  22. attrs: Record<string, string | true>
  23. loc: SourceLocation
  24. map?: RawSourceMap
  25. lang?: string
  26. src?: string
  27. }
  28. export interface SFCTemplateBlock extends SFCBlock {
  29. type: 'template'
  30. functional?: boolean
  31. }
  32. export interface SFCScriptBlock extends SFCBlock {
  33. type: 'script'
  34. }
  35. export interface SFCStyleBlock extends SFCBlock {
  36. type: 'style'
  37. scoped?: boolean
  38. module?: string | boolean
  39. }
  40. export interface SFCDescriptor {
  41. filename: string
  42. template: SFCTemplateBlock | null
  43. script: SFCScriptBlock | null
  44. styles: SFCStyleBlock[]
  45. customBlocks: SFCBlock[]
  46. }
  47. export interface SFCParseResult {
  48. descriptor: SFCDescriptor
  49. errors: CompilerError[]
  50. }
  51. const SFC_CACHE_MAX_SIZE = 500
  52. const sourceToSFC =
  53. __GLOBAL__ || __ESM_BROWSER__
  54. ? new Map<string, SFCParseResult>()
  55. : (new (require('lru-cache'))(SFC_CACHE_MAX_SIZE) as Map<
  56. string,
  57. SFCParseResult
  58. >)
  59. export function parse(
  60. source: string,
  61. {
  62. sourceMap = true,
  63. filename = 'component.vue',
  64. sourceRoot = '',
  65. pad = false,
  66. compiler = CompilerDOM
  67. }: SFCParseOptions = {}
  68. ): SFCParseResult {
  69. const sourceKey =
  70. source + sourceMap + filename + sourceRoot + pad + compiler.parse
  71. const cache = sourceToSFC.get(sourceKey)
  72. if (cache) {
  73. return cache
  74. }
  75. const descriptor: SFCDescriptor = {
  76. filename,
  77. template: null,
  78. script: null,
  79. styles: [],
  80. customBlocks: []
  81. }
  82. const errors: CompilerError[] = []
  83. const ast = compiler.parse(source, {
  84. // there are no components at SFC parsing level
  85. isNativeTag: () => true,
  86. // preserve all whitespaces
  87. isPreTag: () => true,
  88. getTextMode: ({ tag, props }, parent) => {
  89. // all top level elements except <template> are parsed as raw text
  90. // containers
  91. if (
  92. (!parent && tag !== 'template') ||
  93. // <template lang="xxx"> should also be treated as raw text
  94. props.some(
  95. p =>
  96. p.type === NodeTypes.ATTRIBUTE &&
  97. p.name === 'lang' &&
  98. p.value &&
  99. p.value.content !== 'html'
  100. )
  101. ) {
  102. return TextModes.RAWTEXT
  103. } else {
  104. return TextModes.DATA
  105. }
  106. },
  107. onError: e => {
  108. errors.push(e)
  109. }
  110. })
  111. ast.children.forEach(node => {
  112. if (node.type !== NodeTypes.ELEMENT) {
  113. return
  114. }
  115. if (!node.children.length && !hasSrc(node)) {
  116. return
  117. }
  118. switch (node.tag) {
  119. case 'template':
  120. if (!descriptor.template) {
  121. descriptor.template = createBlock(
  122. node,
  123. source,
  124. false
  125. ) as SFCTemplateBlock
  126. } else {
  127. warnDuplicateBlock(source, filename, node)
  128. }
  129. break
  130. case 'script':
  131. if (!descriptor.script) {
  132. descriptor.script = createBlock(node, source, pad) as SFCScriptBlock
  133. } else {
  134. warnDuplicateBlock(source, filename, node)
  135. }
  136. break
  137. case 'style':
  138. descriptor.styles.push(createBlock(node, source, pad) as SFCStyleBlock)
  139. break
  140. default:
  141. descriptor.customBlocks.push(createBlock(node, source, pad))
  142. break
  143. }
  144. })
  145. if (sourceMap) {
  146. const genMap = (block: SFCBlock | null) => {
  147. if (block && !block.src) {
  148. block.map = generateSourceMap(
  149. filename,
  150. source,
  151. block.content,
  152. sourceRoot,
  153. !pad || block.type === 'template' ? block.loc.start.line - 1 : 0
  154. )
  155. }
  156. }
  157. genMap(descriptor.template)
  158. genMap(descriptor.script)
  159. descriptor.styles.forEach(genMap)
  160. }
  161. const result = {
  162. descriptor,
  163. errors
  164. }
  165. sourceToSFC.set(sourceKey, result)
  166. return result
  167. }
  168. function warnDuplicateBlock(
  169. source: string,
  170. filename: string,
  171. node: ElementNode
  172. ) {
  173. const codeFrame = generateCodeFrame(
  174. source,
  175. node.loc.start.offset,
  176. node.loc.end.offset
  177. )
  178. const location = `${filename}:${node.loc.start.line}:${node.loc.start.column}`
  179. console.warn(
  180. `Single file component can contain only one ${
  181. node.tag
  182. } element (${location}):\n\n${codeFrame}`
  183. )
  184. }
  185. function createBlock(
  186. node: ElementNode,
  187. source: string,
  188. pad: SFCParseOptions['pad']
  189. ): SFCBlock {
  190. const type = node.tag
  191. let { start, end } = node.loc
  192. let content = ''
  193. if (node.children.length) {
  194. start = node.children[0].loc.start
  195. end = node.children[node.children.length - 1].loc.end
  196. content = source.slice(start.offset, end.offset)
  197. }
  198. const loc = {
  199. source: content,
  200. start,
  201. end
  202. }
  203. const attrs: Record<string, string | true> = {}
  204. const block: SFCBlock = {
  205. type,
  206. content,
  207. loc,
  208. attrs
  209. }
  210. if (pad) {
  211. block.content = padContent(source, block, pad) + block.content
  212. }
  213. node.props.forEach(p => {
  214. if (p.type === NodeTypes.ATTRIBUTE) {
  215. attrs[p.name] = p.value ? p.value.content || true : true
  216. if (p.name === 'lang') {
  217. block.lang = p.value && p.value.content
  218. } else if (p.name === 'src') {
  219. block.src = p.value && p.value.content
  220. } else if (type === 'style') {
  221. if (p.name === 'scoped') {
  222. ;(block as SFCStyleBlock).scoped = true
  223. } else if (p.name === 'module') {
  224. ;(block as SFCStyleBlock).module = attrs[p.name]
  225. }
  226. } else if (type === 'template' && p.name === 'functional') {
  227. ;(block as SFCTemplateBlock).functional = true
  228. }
  229. }
  230. })
  231. return block
  232. }
  233. const splitRE = /\r?\n/g
  234. const emptyRE = /^(?:\/\/)?\s*$/
  235. const replaceRE = /./g
  236. function generateSourceMap(
  237. filename: string,
  238. source: string,
  239. generated: string,
  240. sourceRoot: string,
  241. lineOffset: number
  242. ): RawSourceMap {
  243. const map = new SourceMapGenerator({
  244. file: filename.replace(/\\/g, '/'),
  245. sourceRoot: sourceRoot.replace(/\\/g, '/')
  246. })
  247. map.setSourceContent(filename, source)
  248. generated.split(splitRE).forEach((line, index) => {
  249. if (!emptyRE.test(line)) {
  250. const originalLine = index + 1 + lineOffset
  251. const generatedLine = index + 1
  252. for (let i = 0; i < line.length; i++) {
  253. if (!/\s/.test(line[i])) {
  254. map.addMapping({
  255. source: filename,
  256. original: {
  257. line: originalLine,
  258. column: i
  259. },
  260. generated: {
  261. line: generatedLine,
  262. column: i
  263. }
  264. })
  265. }
  266. }
  267. }
  268. })
  269. return JSON.parse(map.toString())
  270. }
  271. function padContent(
  272. content: string,
  273. block: SFCBlock,
  274. pad: SFCParseOptions['pad']
  275. ): string {
  276. content = content.slice(0, block.loc.start.offset)
  277. if (pad === 'space') {
  278. return content.replace(replaceRE, ' ')
  279. } else {
  280. const offset = content.split(splitRE).length
  281. const padChar = block.type === 'script' && !block.lang ? '//\n' : '\n'
  282. return Array(offset).join(padChar)
  283. }
  284. }
  285. function hasSrc(node: ElementNode) {
  286. return node.props.some(p => {
  287. if (p.type !== NodeTypes.ATTRIBUTE) {
  288. return false
  289. }
  290. return p.name === 'src'
  291. })
  292. }