@tanstack/devtools-vite 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/esm/ast-utils.d.ts +11 -0
  2. package/dist/esm/ast-utils.js +44 -0
  3. package/dist/esm/ast-utils.js.map +1 -0
  4. package/dist/esm/devtools-packages.d.ts +2 -0
  5. package/dist/esm/devtools-packages.js +15 -0
  6. package/dist/esm/devtools-packages.js.map +1 -0
  7. package/dist/esm/enhance-logs.d.ts +4 -1
  8. package/dist/esm/enhance-logs.js +35 -36
  9. package/dist/esm/enhance-logs.js.map +1 -1
  10. package/dist/esm/inject-plugin.d.ts +5 -4
  11. package/dist/esm/inject-plugin.js +114 -103
  12. package/dist/esm/inject-plugin.js.map +1 -1
  13. package/dist/esm/inject-source.d.ts +4 -1
  14. package/dist/esm/inject-source.js +92 -93
  15. package/dist/esm/inject-source.js.map +1 -1
  16. package/dist/esm/offset-to-loc.d.ts +14 -0
  17. package/dist/esm/offset-to-loc.js +29 -0
  18. package/dist/esm/offset-to-loc.js.map +1 -0
  19. package/dist/esm/plugin.js +23 -28
  20. package/dist/esm/plugin.js.map +1 -1
  21. package/dist/esm/remove-devtools.d.ts +4 -1
  22. package/dist/esm/remove-devtools.js +79 -86
  23. package/dist/esm/remove-devtools.js.map +1 -1
  24. package/package.json +3 -9
  25. package/skills/devtools-vite-plugin/SKILL.md +7 -7
  26. package/skills/devtools-vite-plugin/references/vite-options.md +2 -2
  27. package/src/ast-utils.ts +54 -0
  28. package/src/devtools-packages.ts +12 -0
  29. package/src/enhance-logs.ts +48 -78
  30. package/src/inject-plugin.test.ts +200 -147
  31. package/src/inject-plugin.ts +195 -238
  32. package/src/inject-source.test.ts +165 -115
  33. package/src/inject-source.ts +183 -231
  34. package/src/offset-to-loc.ts +39 -0
  35. package/src/plugin.ts +26 -28
  36. package/src/remove-devtools.test.ts +76 -57
  37. package/src/remove-devtools.ts +160 -168
  38. package/dist/esm/babel.d.ts +0 -18
  39. package/dist/esm/babel.js +0 -11
  40. package/dist/esm/babel.js.map +0 -1
  41. package/src/babel.ts +0 -18
@@ -1,246 +1,184 @@
1
1
  import { normalizePath } from 'vite'
2
- import { gen, parse, t, trav } from './babel'
2
+ import MagicString from 'magic-string'
3
+ import { parseSync } from 'oxc-parser'
4
+ import { createLocMapper } from './offset-to-loc'
3
5
  import { matcher } from './matcher'
4
- import type { types as Babel, NodePath } from '@babel/core'
5
- import type { ParseResult } from '@babel/parser'
6
+ import { forEachChild } from './ast-utils'
7
+ import type {
8
+ JSXElementName,
9
+ JSXOpeningElement,
10
+ Node,
11
+ ParamPattern,
12
+ } from 'oxc-parser'
13
+ import type { Loc } from './offset-to-loc'
6
14
 
7
- const getPropsNameFromFunctionDeclaration = (
8
- functionDeclaration:
9
- | t.VariableDeclarator
10
- | t.FunctionExpression
11
- | t.FunctionDeclaration
12
- | t.ArrowFunctionExpression,
13
- ) => {
14
- let propsName: string | null = null
15
+ /**
16
+ * Extract the props name from a function's first parameter.
17
+ * Handles: `(props) => {}`, `({ ...props }) => {}`, `function(props) {}`
18
+ */
19
+ function getPropsName(params: Array<ParamPattern>): string | null {
20
+ const first = params[0]
21
+ if (!first) return null
15
22
 
16
- if (functionDeclaration.type === 'FunctionExpression') {
17
- const firstArgument = functionDeclaration.params[0]
18
- // handles (props) => {}
19
- if (firstArgument && firstArgument.type === 'Identifier') {
20
- propsName = firstArgument.name
21
- }
22
- // handles ({ ...props }) => {}
23
- if (firstArgument && firstArgument.type === 'ObjectPattern') {
24
- firstArgument.properties.forEach((prop) => {
25
- if (
26
- prop.type === 'RestElement' &&
27
- prop.argument.type === 'Identifier'
28
- ) {
29
- propsName = prop.argument.name
30
- }
31
- })
32
- }
33
- return propsName
34
- }
35
- if (functionDeclaration.type === 'ArrowFunctionExpression') {
36
- const firstArgument = functionDeclaration.params[0]
37
- // handles (props) => {}
38
- if (firstArgument && firstArgument.type === 'Identifier') {
39
- propsName = firstArgument.name
40
- }
41
- // handles ({ ...props }) => {}
42
- if (firstArgument && firstArgument.type === 'ObjectPattern') {
43
- firstArgument.properties.forEach((prop) => {
44
- if (
45
- prop.type === 'RestElement' &&
46
- prop.argument.type === 'Identifier'
47
- ) {
48
- propsName = prop.argument.name
49
- }
50
- })
51
- }
52
- return propsName
53
- }
54
- if (functionDeclaration.type === 'FunctionDeclaration') {
55
- const firstArgument = functionDeclaration.params[0]
56
- // handles (props) => {}
57
- if (firstArgument && firstArgument.type === 'Identifier') {
58
- propsName = firstArgument.name
59
- }
60
- // handles ({ ...props }) => {}
61
- if (firstArgument && firstArgument.type === 'ObjectPattern') {
62
- firstArgument.properties.forEach((prop) => {
63
- if (
64
- prop.type === 'RestElement' &&
65
- prop.argument.type === 'Identifier'
66
- ) {
67
- propsName = prop.argument.name
68
- }
69
- })
70
- }
71
- return propsName
72
- }
73
- // Arrow function case
74
- if (
75
- functionDeclaration.init?.type === 'ArrowFunctionExpression' ||
76
- functionDeclaration.init?.type === 'FunctionExpression'
77
- ) {
78
- const firstArgument = functionDeclaration.init.params[0]
79
- // handles (props) => {}
80
- if (firstArgument && firstArgument.type === 'Identifier') {
81
- propsName = firstArgument.name
82
- }
83
- // handles ({ ...props }) => {}
84
- if (firstArgument && firstArgument.type === 'ObjectPattern') {
85
- firstArgument.properties.forEach((prop) => {
86
- if (
87
- prop.type === 'RestElement' &&
88
- prop.argument.type === 'Identifier'
89
- ) {
90
- propsName = prop.argument.name
91
- }
92
- })
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
+ }
93
32
  }
94
33
  }
95
- return propsName
34
+
35
+ return null
96
36
  }
97
37
 
98
- const getNameOfElement = (
99
- element: t.JSXIdentifier | t.JSXMemberExpression | t.JSXNamespacedName,
100
- ): string => {
101
- if (element.type === 'JSXIdentifier') {
102
- return element.name
103
- }
104
- if (element.type === 'JSXMemberExpression') {
105
- return `${getNameOfElement(element.object)}.${getNameOfElement(element.property)}`
38
+ /**
39
+ * Get the display name from a JSX element name node.
40
+ */
41
+ function 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}`
106
45
  }
107
-
108
- return `${element.namespace.name}:${element.name.name}`
46
+ // JSXNamespacedName
47
+ return `${name.namespace.name}:${name.name.name}`
109
48
  }
110
49
 
111
- const transformJSX = (
112
- element: NodePath<t.JSXOpeningElement>,
50
+ /**
51
+ * Check whether a JSXOpeningElement should receive `data-tsd-source`.
52
+ */
53
+ function shouldTransform(
54
+ node: JSXOpeningElement,
113
55
  propsName: string | null,
114
- file: string,
115
56
  ignorePatterns: Array<string | RegExp>,
116
- ) => {
117
- const loc = element.node.loc
118
- if (!loc) return
119
- const line = loc.start.line
120
- const column = loc.start.column
121
- const nameOfElement = getNameOfElement(element.node.name)
122
- const isIgnored = matcher(ignorePatterns, nameOfElement)
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?
123
66
  if (
124
- nameOfElement === 'Fragment' ||
125
- nameOfElement === 'React.Fragment' ||
126
- isIgnored
67
+ node.attributes.some(
68
+ (a) =>
69
+ a.type === 'JSXAttribute' &&
70
+ a.name.type === 'JSXIdentifier' &&
71
+ a.name.name === 'data-tsd-source',
72
+ )
127
73
  ) {
128
- return
74
+ return false
129
75
  }
130
- const hasDataSource = element.node.attributes.some(
131
- (attr) =>
132
- attr.type === 'JSXAttribute' &&
133
- attr.name.type === 'JSXIdentifier' &&
134
- attr.name.name === 'data-tsd-source',
135
- )
136
- // Check if props are spread
137
- const hasSpread = element.node.attributes.some(
138
- (attr) =>
139
- attr.type === 'JSXSpreadAttribute' &&
140
- attr.argument.type === 'Identifier' &&
141
- attr.argument.name === propsName,
142
- )
143
76
 
144
- if (hasSpread || hasDataSource) {
145
- // Do not inject if props are spread
146
- return
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
147
87
  }
148
88
 
149
- // Inject data-source as a string: "<file>:<line>:<column>"
150
- element.node.attributes.push(
151
- t.jsxAttribute(
152
- t.jsxIdentifier('data-tsd-source'),
153
- t.stringLiteral(`${file}:${line}:${column + 1}`),
154
- ),
89
+ return true
90
+ }
91
+
92
+ function isFunctionLike(node: Node): boolean {
93
+ return (
94
+ node.type === 'FunctionDeclaration' ||
95
+ node.type === 'FunctionExpression' ||
96
+ node.type === 'ArrowFunctionExpression'
155
97
  )
98
+ }
156
99
 
157
- return true
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
+ */
105
+ function 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))
158
112
  }
159
113
 
160
- const transform = (
161
- ast: ParseResult<Babel.File>,
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
+ */
118
+ function visitFunctions(
119
+ node: Node,
120
+ annotated: Set<number>,
162
121
  file: string,
163
122
  ignorePatterns: Array<string | RegExp>,
164
- ) => {
123
+ offsetToLoc: (offset: number) => Loc,
124
+ s: MagicString,
125
+ code: string,
126
+ ): boolean {
165
127
  let didTransform = false
166
128
 
167
- trav(ast, {
168
- FunctionDeclaration(functionDeclaration) {
169
- const propsName = getPropsNameFromFunctionDeclaration(
170
- functionDeclaration.node,
171
- )
172
- functionDeclaration.traverse({
173
- JSXOpeningElement(element) {
174
- const transformed = transformJSX(
175
- element,
176
- propsName,
177
- file,
178
- ignorePatterns,
179
- )
180
- if (transformed) {
181
- didTransform = true
182
- }
183
- },
184
- })
185
- },
186
- ArrowFunctionExpression(path) {
187
- const propsName = getPropsNameFromFunctionDeclaration(path.node)
188
- path.traverse({
189
- JSXOpeningElement(element) {
190
- const transformed = transformJSX(
191
- element,
192
- propsName,
193
- file,
194
- ignorePatterns,
195
- )
196
- if (transformed) {
197
- didTransform = true
198
- }
199
- },
200
- })
201
- },
202
- FunctionExpression(path) {
203
- const propsName = getPropsNameFromFunctionDeclaration(path.node)
204
- path.traverse({
205
- JSXOpeningElement(element) {
206
- const transformed = transformJSX(
207
- element,
208
- propsName,
209
- file,
210
- ignorePatterns,
211
- )
212
- if (transformed) {
213
- didTransform = true
214
- }
215
- },
216
- })
217
- },
218
- VariableDeclaration(path) {
219
- const functionDeclaration = path.node.declarations.find((decl) => {
220
- return (
221
- decl.init?.type === 'ArrowFunctionExpression' ||
222
- decl.init?.type === 'FunctionExpression'
223
- )
224
- })
225
- if (!functionDeclaration) {
226
- return
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)
227
148
  }
228
- const propsName = getPropsNameFromFunctionDeclaration(functionDeclaration)
229
149
 
230
- path.traverse({
231
- JSXOpeningElement(element) {
232
- const transformed = transformJSX(
233
- element,
234
- propsName,
235
- file,
236
- ignorePatterns,
237
- )
238
- if (transformed) {
239
- didTransform = true
240
- }
241
- },
242
- })
243
- },
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
+ }
244
182
  })
245
183
 
246
184
  return didTransform
@@ -254,29 +192,43 @@ export function addSourceToJsx(
254
192
  components?: Array<string | RegExp>
255
193
  } = {},
256
194
  ) {
257
- const [filePath] = id.split('?')
258
- // eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain
259
- const location = filePath?.replace(normalizePath(process.cwd()), '')!
195
+ const filePath = id.split('?')[0]!
196
+ const location = filePath.replace(normalizePath(process.cwd()), '')
260
197
 
261
198
  const fileIgnored = matcher(ignore.files || [], location)
262
- if (fileIgnored) {
263
- return
264
- }
199
+ if (fileIgnored) return
200
+
265
201
  try {
266
- const ast = parse(code, {
202
+ const result = parseSync(filePath, code, {
267
203
  sourceType: 'module',
268
- plugins: ['jsx', 'typescript'],
204
+ lang: 'tsx',
269
205
  })
270
- const didTransform = transform(ast, location, ignore.components || [])
271
- if (!didTransform) {
272
- return
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
+ }),
273
231
  }
274
- return gen(ast, {
275
- sourceMaps: true,
276
- retainLines: true,
277
- filename: id,
278
- sourceFileName: filePath,
279
- })
280
232
  } catch (e) {
281
233
  return
282
234
  }
@@ -0,0 +1,39 @@
1
+ export interface Loc {
2
+ /** 1-based line number */
3
+ line: number
4
+ /** 0-based column offset */
5
+ column: number
6
+ }
7
+
8
+ /**
9
+ * Pre-compute line start offsets for fast byte-offset to line/column conversion.
10
+ * Returns a function that maps a byte offset to `{ line, column }`.
11
+ *
12
+ * Build: O(n) single pass over the source string.
13
+ * Lookup: O(log n) binary search.
14
+ */
15
+ export function createLocMapper(source: string): (offset: number) => Loc {
16
+ const lineStarts: Array<number> = [0]
17
+ for (let i = 0; i < source.length; i++) {
18
+ if (source.charCodeAt(i) === 10 /* \n */) {
19
+ lineStarts.push(i + 1)
20
+ }
21
+ }
22
+
23
+ return (offset: number): Loc => {
24
+ let lo = 0
25
+ let hi = lineStarts.length - 1
26
+ while (lo < hi) {
27
+ const mid = (lo + hi + 1) >> 1
28
+ if (lineStarts[mid]! <= offset) {
29
+ lo = mid
30
+ } else {
31
+ hi = mid - 1
32
+ }
33
+ }
34
+ return {
35
+ line: lo + 1,
36
+ column: offset - lineStarts[lo]!,
37
+ }
38
+ }
39
+ }
package/src/plugin.ts CHANGED
@@ -12,6 +12,7 @@ import { removeDevtools } from './remove-devtools'
12
12
  import { addSourceToJsx } from './inject-source'
13
13
  import { enhanceConsoleLog } from './enhance-logs'
14
14
  import { detectDevtoolsFile, injectPluginIntoFile } from './inject-plugin'
15
+ import { TANSTACK_DEVTOOLS_PACKAGES } from './devtools-packages'
15
16
  import {
16
17
  addPluginToDevtools,
17
18
  emitOutdatedDeps,
@@ -318,17 +319,10 @@ export const devtools = (args?: TanStackDevtoolsViteConfig): Array<Plugin> => {
318
319
  },
319
320
  enforce: 'pre',
320
321
  transform(code, id) {
321
- const devtoolPackages = [
322
- '@tanstack/react-devtools',
323
- '@tanstack/preact-devtools',
324
- '@tanstack/solid-devtools',
325
- '@tanstack/vue-devtools',
326
- '@tanstack/devtools',
327
- ]
328
322
  if (
329
323
  id.includes('node_modules') ||
330
324
  id.includes('?raw') ||
331
- !devtoolPackages.some((pkg) => code.includes(pkg))
325
+ !TANSTACK_DEVTOOLS_PACKAGES.some((pkg) => code.includes(pkg))
332
326
  )
333
327
  return
334
328
  const transform = removeDevtools(code, id)
@@ -546,6 +540,30 @@ export const devtools = (args?: TanStackDevtoolsViteConfig): Array<Plugin> => {
546
540
  }
547
541
  },
548
542
  },
543
+ // Enhanced logs must run BEFORE console-pipe-transform: the latter
544
+ // prepends a multi-line IIFE to root entry files, which would shift
545
+ // every line number computed by the oxc-parser AST and produce
546
+ // "Go to Source" links pointing past the end of the user's file.
547
+ {
548
+ name: '@tanstack/devtools:better-console-logs',
549
+ enforce: 'pre',
550
+ apply(config) {
551
+ return config.mode === 'development' && enhancedLogsConfig.enabled
552
+ },
553
+ transform: {
554
+ filter: {
555
+ id: {
556
+ exclude: [/node_modules/, /\?raw/, /\/dist\//, /\/build\//],
557
+ },
558
+ code: {
559
+ include: 'console.',
560
+ },
561
+ },
562
+ handler(code, id) {
563
+ return enhanceConsoleLog(code, id, port)
564
+ },
565
+ },
566
+ },
549
567
  // Inject console piping code into entry files (both client and server)
550
568
  {
551
569
  name: '@tanstack/devtools:console-pipe-transform',
@@ -592,26 +610,6 @@ export const devtools = (args?: TanStackDevtoolsViteConfig): Array<Plugin> => {
592
610
  },
593
611
  },
594
612
  },
595
- {
596
- name: '@tanstack/devtools:better-console-logs',
597
- enforce: 'pre',
598
- apply(config) {
599
- return config.mode === 'development' && enhancedLogsConfig.enabled
600
- },
601
- transform: {
602
- filter: {
603
- id: {
604
- exclude: [/node_modules/, /\?raw/, /\/dist\//, /\/build\//],
605
- },
606
- code: {
607
- include: 'console.',
608
- },
609
- },
610
- handler(code, id) {
611
- return enhanceConsoleLog(code, id, port)
612
- },
613
- },
614
- },
615
613
  {
616
614
  name: '@tanstack/devtools:inject-plugin',
617
615
  apply(config, { command }) {