Open History to see the last commit
1import { normalizePath } from 'vite'
2import MagicString from 'magic-string'
3import { parseSync } from 'oxc-parser'
4import { createLocMapper } from './offset-to-loc'
5import { matcher } from './matcher'
6import { forEachChild } from './ast-utils'
7import type {
8 JSXElementName,
9 JSXOpeningElement,
10 Node,
11 ParamPattern,
12} from 'oxc-parser'
13import type { Loc } from './offset-to-loc'
14β
15/**
16 * Extract the props name from a function's first parameter.
17 * Handles: `(props) => {}`, `({ ...props }) => {}`, `function(props) {}`
18 */
19function getPropsName(params: Array<ParamPattern>): string | null {
20 const first = params[0]
21 if (!first) return null
22β
23 // (props) => {} or function(props) {}
24 if (first.type === 'Identifier') return first.name
25β
26 // ({ ...rest }) => {} or function({ ...rest }) {}
27 if (first.type === 'ObjectPattern') {
28 for (const prop of first.properties) {
29 if (prop.type === 'RestElement' && prop.argument.type === 'Identifier') {
30 return prop.argument.name
31 }
32 }
33 }
34β
35 return null
36}
37β
38/**
39 * Get the display name from a JSX element name node.
40 */
41function getNameOfElement(name: JSXElementName): string {
42 if (name.type === 'JSXIdentifier') return name.name
43 if (name.type === 'JSXMemberExpression') {
44 return `${getNameOfElement(name.object)}.${name.property.name}`
45 }
46 // JSXNamespacedName
47 return `${name.namespace.name}:${name.name.name}`
48}
49β
50/**
51 * Check whether a JSXOpeningElement should receive `data-tsd-source`.
52 */
53function shouldTransform(
54 node: JSXOpeningElement,
55 propsName: string | null,
56 ignorePatterns: Array<string | RegExp>,
57): boolean {
58 const nameOfElement = getNameOfElement(node.name)
59β
60 if (nameOfElement === 'Fragment' || nameOfElement === 'React.Fragment') {
61 return false
62 }
63 if (matcher(ignorePatterns, nameOfElement)) return false
64β
65 // Already annotated?
66 if (
67 node.attributes.some(
68 (a) =>
69 a.type === 'JSXAttribute' &&
70 a.name.type === 'JSXIdentifier' &&
71 a.name.name === 'data-tsd-source',
72 )
73 ) {
74 return false
75 }
76β
77 // Props spread?
78 if (
79 node.attributes.some(
80 (a) =>
81 a.type === 'JSXSpreadAttribute' &&
82 a.argument.type === 'Identifier' &&
83 a.argument.name === propsName,
84 )
85 ) {
86 return false
87 }
88β
89 return true
90}
91β
92function isFunctionLike(node: Node): boolean {
93 return (
94 node.type === 'FunctionDeclaration' ||
95 node.type === 'FunctionExpression' ||
96 node.type === 'ArrowFunctionExpression'
97 )
98}
99β
100/**
101 * Walk a subtree collecting JSXOpeningElements owned by the current function.
102 * Function-like nodes are traversal boundaries so inner components keep their
103 * own propsName context and aren't annotated with an outer function's props.
104 */
105function collectJsx(node: Node, out: Array<JSXOpeningElement>) {
106 if (node.type === 'JSXOpeningElement') {
107 out.push(node)
108 return
109 }
110 if (isFunctionLike(node)) return
111 forEachChild(node, (child) => collectJsx(child, out))
112}
113β
114/**
115 * Walk the AST to find all function-like nodes (in document order).
116 * For each, extract propsName and collect JSX elements from its body.
117 */
118function visitFunctions(
119 node: Node,
120 annotated: Set<number>,
121 file: string,
122 ignorePatterns: Array<string | RegExp>,
123 offsetToLoc: (offset: number) => Loc,
124 s: MagicString,
125 code: string,
126): boolean {
127 let didTransform = false
128β
129 const processFunction = (params: Array<ParamPattern>, body: Node) => {
130 const propsName = getPropsName(params)
131 const jsxNodes: Array<JSXOpeningElement> = []
132 collectJsx(body, jsxNodes)
133β
134 for (const jsx of jsxNodes) {
135 if (annotated.has(jsx.start)) continue
136 if (!shouldTransform(jsx, propsName, ignorePatterns)) continue
137β
138 const loc = offsetToLoc(jsx.start)
139 const attrStr = ` data-tsd-source="${file}:${loc.line}:${loc.column + 1}"`
140β
141 // Insert before '>' or '/>' at the end of the opening element
142 if (jsx.selfClosing) {
143 // ends with '/>' β insert before '/>'
144 s.appendLeft(jsx.end - 2, attrStr)
145 } else {
146 // ends with '>' β insert before '>'
147 s.appendLeft(jsx.end - 1, attrStr)
148 }
149β
150 annotated.add(jsx.start)
151 didTransform = true
152 }
153 }
154β
155 // Check if this node is a function-like node. Variable-initialized
156 // functions (`const Foo = () => {}`) are handled when forEachChild reaches
157 // their init, so VariableDeclaration doesn't need a special case here.
158 if (
159 node.type === 'FunctionDeclaration' ||
160 node.type === 'FunctionExpression'
161 ) {
162 if (node.body) processFunction(node.params, node.body)
163 } else if (node.type === 'ArrowFunctionExpression') {
164 processFunction(node.params, node.body)
165 }
166β
167 // Recurse into children to find nested functions
168 forEachChild(node, (child) => {
169 if (
170 visitFunctions(
171 child,
172 annotated,
173 file,
174 ignorePatterns,
175 offsetToLoc,
176 s,
177 code,
178 )
179 ) {
180 didTransform = true
181 }
182 })
183β
184 return didTransform
185}
186β
187export function addSourceToJsx(
188 code: string,
189 id: string,
190 ignore: {
191 files?: Array<string | RegExp>
192 components?: Array<string | RegExp>
193 } = {},
194) {
195 const filePath = id.split('?')[0]!
196 const location = filePath.replace(normalizePath(process.cwd()), '')
197β
198 const fileIgnored = matcher(ignore.files || [], location)
199 if (fileIgnored) return
200β
201 try {
202 const result = parseSync(filePath, code, {
203 sourceType: 'module',
204 lang: 'tsx',
205 })
206 if (result.errors.length > 0) return
207β
208 const offsetToLoc = createLocMapper(code)
209 const s = new MagicString(code)
210 const annotated = new Set<number>()
211β
212 const didTransform = visitFunctions(
213 result.program,
214 annotated,
215 location,
216 ignore.components || [],
217 offsetToLoc,
218 s,
219 code,
220 )
221β
222 if (!didTransform) return
223β
224 return {
225 code: s.toString(),
226 map: s.generateMap({
227 source: filePath,
228 file: id,
229 includeContent: true,
230 }),
231 }
232 } catch (e) {
233 return
234 }
235}