Open History to see the last commit
1import { readFileSync, writeFileSync } from 'node:fs'
2import MagicString from 'magic-string'
3import { parseSync } from 'oxc-parser'
4import { walk } from './ast-utils'
5import { isTanStackDevtoolsImport } from './devtools-packages'
6import type { Node } from 'oxc-parser'
7import type { PluginInjection } from '@tanstack/devtools-client'
8β
9/**
10 * Detects if a file imports TanStack devtools packages
11 */
12const detectDevtoolsImport = (code: string): boolean => {
13 try {
14 const result = parseSync('input.tsx', code, {
15 sourceType: 'module',
16 lang: 'tsx',
17 })
18 if (result.errors.length > 0) return false
19β
20 let hasDevtoolsImport = false
21β
22 walk(result.program, (node) => {
23 if (hasDevtoolsImport) return
24 if (
25 node.type === 'ImportDeclaration' &&
26 isTanStackDevtoolsImport(node.source.value)
27 ) {
28 hasDevtoolsImport = true
29 }
30 })
31β
32 return hasDevtoolsImport
33 } catch (e) {
34 return false
35 }
36}
37β
38/**
39 * Finds the TanStackDevtools component name in the file
40 * Handles renamed imports and namespace imports
41 */
42export const findDevtoolsComponentName = (code: string): string | null => {
43 try {
44 const result = parseSync('input.tsx', code, {
45 sourceType: 'module',
46 lang: 'tsx',
47 })
48 if (result.errors.length > 0) return null
49β
50 let componentName: string | null = null
51β
52 walk(result.program, (node) => {
53 if (componentName) return
54 if (node.type !== 'ImportDeclaration') return
55 if (!isTanStackDevtoolsImport(node.source.value)) return
56β
57 for (const spec of node.specifiers) {
58 // import { TanStackDevtools } or import { TanStackDevtools as X }
59 if (
60 spec.type === 'ImportSpecifier' &&
61 spec.imported.type === 'Identifier' &&
62 spec.imported.name === 'TanStackDevtools'
63 ) {
64 componentName = spec.local.name
65 return
66 }
67 // import * as X from '...'
68 if (spec.type === 'ImportNamespaceSpecifier') {
69 componentName = `${spec.local.name}.TanStackDevtools`
70 return
71 }
72 }
73 })
74β
75 return componentName
76 } catch (e) {
77 return null
78 }
79}
80β
81/**
82 * Check if a plugin already exists in the array expression
83 */
84function pluginExists(
85 code: string,
86 node: Node,
87 importName: string,
88 displayName: string,
89 pluginType: string,
90): boolean {
91 if (node.type !== 'ArrayExpression') return false
92β
93 for (const element of node.elements) {
94 if (!element) continue
95β
96 if (pluginType === 'function') {
97 if (
98 element.type === 'CallExpression' &&
99 element.callee.type === 'Identifier' &&
100 element.callee.name === importName
101 ) {
102 return true
103 }
104 } else {
105 if (element.type !== 'ObjectExpression') continue
106 for (const prop of element.properties) {
107 if (
108 prop.type === 'Property' &&
109 prop.key.type === 'Identifier' &&
110 prop.key.name === 'name' &&
111 prop.value.type === 'Literal' &&
112 code.slice(prop.value.start + 1, prop.value.end - 1) === displayName
113 ) {
114 return true
115 }
116 }
117 }
118 }
119β
120 return false
121}
122β
123function buildPluginString(
124 importName: string,
125 displayName: string,
126 pluginType: string,
127): string {
128 if (pluginType === 'function') {
129 return `${importName}()`
130 }
131 return `{ name: ${JSON.stringify(displayName)}, render: <${importName} /> }`
132}
133β
134export const transformAndInject = (
135 code: string,
136 injection: PluginInjection,
137 devtoolsComponentName: string,
138): { code: string; transformed: boolean } | null => {
139 const importName = injection.pluginImport?.importName
140 const pluginType = injection.pluginImport?.type || 'jsx'
141 const displayName = injection.pluginName
142β
143 if (!importName) {
144 return null
145 }
146β
147 try {
148 const result = parseSync('input.tsx', code, {
149 sourceType: 'module',
150 lang: 'tsx',
151 })
152 if (result.errors.length > 0) return null
153β
154 const s = new MagicString(code)
155 const isNamespaceImport = devtoolsComponentName.includes('.')
156β
157 walk(result.program, (node) => {
158 if (node.type !== 'JSXOpeningElement') return
159β
160 let matches = false
161 if (isNamespaceImport) {
162 if (node.name.type === 'JSXMemberExpression') {
163 const fullName = `${node.name.object.type === 'JSXIdentifier' ? node.name.object.name : ''}.${node.name.property.name}`
164 matches = fullName === devtoolsComponentName
165 }
166 } else {
167 matches =
168 node.name.type === 'JSXIdentifier' &&
169 node.name.name === devtoolsComponentName
170 }
171β
172 if (!matches) return
173β
174 // Find the plugins prop
175 const pluginsProp = node.attributes.find(
176 (attr) =>
177 attr.type === 'JSXAttribute' &&
178 attr.name.type === 'JSXIdentifier' &&
179 attr.name.name === 'plugins',
180 )
181β
182 if (pluginsProp && pluginsProp.type === 'JSXAttribute') {
183 if (
184 pluginsProp.value &&
185 pluginsProp.value.type === 'JSXExpressionContainer'
186 ) {
187 const expression = pluginsProp.value.expression
188 if (expression.type === 'ArrayExpression') {
189 if (
190 !pluginExists(
191 code,
192 expression,
193 importName,
194 displayName,
195 pluginType,
196 )
197 ) {
198 const pluginStr = buildPluginString(
199 importName,
200 displayName,
201 pluginType,
202 )
203 // Insert before closing ']'
204 const arrayEnd = expression.end - 1
205 let prefix = ''
206 if (expression.elements.length > 0) {
207 const arrayContent = code.slice(expression.start + 1, arrayEnd)
208 prefix = arrayContent.trimEnd().endsWith(',') ? ' ' : ', '
209 }
210 s.appendLeft(arrayEnd, prefix + pluginStr)
211 }
212 }
213 }
214 } else {
215 // No plugins prop β create one
216 const pluginStr = buildPluginString(importName, displayName, pluginType)
217 const attrStr = ` plugins={[${pluginStr}]}`
218 if (node.selfClosing) {
219 s.appendLeft(node.end - 2, attrStr)
220 } else {
221 s.appendLeft(node.end - 1, attrStr)
222 }
223 }
224 })
225β
226 // Add import at the top of the file if transform happened
227 if (s.hasChanged()) {
228 const state = { lastImportEnd: 0, alreadyImported: false }
229 walk(result.program, (n) => {
230 if (n.type !== 'ImportDeclaration') return
231 if (n.end > state.lastImportEnd) state.lastImportEnd = n.end
232 if (n.source.value !== injection.packageName) return
233 for (const spec of n.specifiers) {
234 if (
235 spec.type === 'ImportSpecifier' &&
236 spec.imported.type === 'Identifier' &&
237 spec.imported.name === importName
238 ) {
239 state.alreadyImported = true
240 }
241 }
242 })
243 if (!state.alreadyImported) {
244 const importStr = `\nimport { ${importName} } from ${JSON.stringify(injection.packageName)};`
245 s.appendRight(state.lastImportEnd, importStr)
246 }
247 }
248β
249 return { code: s.toString(), transformed: s.hasChanged() }
250 } catch (e) {
251 return null
252 }
253}
254β
255/**
256 * Detects if a file contains TanStack devtools import
257 */
258export function detectDevtoolsFile(code: string): boolean {
259 return detectDevtoolsImport(code)
260}
261β
262/**
263 * Injects a plugin into the TanStackDevtools component in a file
264 * Reads the file, transforms it, and writes it back
265 */
266export function injectPluginIntoFile(
267 filePath: string,
268 injection: PluginInjection,
269): { success: boolean; error?: string } {
270 try {
271 const code = readFileSync(filePath, 'utf-8')
272β
273 const devtoolsComponentName = findDevtoolsComponentName(code)
274 if (!devtoolsComponentName) {
275 return {
276 success: false,
277 error: 'Could not find TanStackDevtools import',
278 }
279 }
280β
281 const result = transformAndInject(code, injection, devtoolsComponentName)
282β
283 if (!result?.transformed) {
284 return {
285 success: false,
286 error: 'Plugin already exists or no TanStackDevtools component found',
287 }
288 }
289β
290 writeFileSync(filePath, result.code, 'utf-8')
291β
292 return { success: true }
293 } catch (e) {
294 console.error('Error injecting plugin:', e)
295 return {
296 success: false,
297 error: e instanceof Error ? e.message : 'Unknown error',
298 }
299 }
300}