|
| 1 | +import { normalizePath } from 'vite' |
| 2 | +import { gen, parse, t, trav } from './babel' |
| 3 | +import type { types as Babel } from '@babel/core' |
| 4 | +import type { ParseResult } from '@babel/parser' |
| 5 | + |
| 6 | +const transform = (ast: ParseResult<Babel.File>, file: string) => { |
| 7 | + let didTransform = false |
| 8 | + trav(ast, { |
| 9 | + JSXOpeningElement(path) { |
| 10 | + const loc = path.node.loc |
| 11 | + if (!loc) return |
| 12 | + const line = loc.start.line |
| 13 | + const column = loc.start.column |
| 14 | + |
| 15 | + // Inject data-source as a string: "<file>:<line>:<column>" |
| 16 | + path.node.attributes.push( |
| 17 | + t.jsxAttribute( |
| 18 | + t.jsxIdentifier('data-tsd-source'), |
| 19 | + t.stringLiteral(`${file}:${line}:${column}`), |
| 20 | + ), |
| 21 | + ) |
| 22 | + |
| 23 | + didTransform = true |
| 24 | + }, |
| 25 | + }) |
| 26 | + |
| 27 | + return didTransform |
| 28 | +} |
| 29 | + |
| 30 | +export function addSourceToJsx(code: string, id: string) { |
| 31 | + const [filePath] = id.split('?') |
| 32 | + // eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain |
| 33 | + const location = filePath?.replace(normalizePath(process.cwd()), '')! |
| 34 | + |
| 35 | + try { |
| 36 | + const ast = parse(code, { |
| 37 | + sourceType: 'module', |
| 38 | + plugins: ['jsx', 'typescript'], |
| 39 | + }) |
| 40 | + const didTransform = transform(ast, location) |
| 41 | + if (!didTransform) { |
| 42 | + return { code } |
| 43 | + } |
| 44 | + return gen(ast, { |
| 45 | + sourceMaps: true, |
| 46 | + filename: id, |
| 47 | + sourceFileName: filePath, |
| 48 | + }) |
| 49 | + } catch (e) { |
| 50 | + return { code } |
| 51 | + } |
| 52 | +} |
0 commit comments