@tanstack/devtools-vite 0.8.1 → 0.8.2

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 (81) hide show
  1. package/dist/esm/plugin.d.ts +4 -74
  2. package/dist/esm/plugin.js +2 -12
  3. package/dist/esm/plugin.js.map +1 -1
  4. package/package.json +2 -6
  5. package/src/plugin.ts +25 -97
  6. package/dist/esm/ast-utils.d.ts +0 -11
  7. package/dist/esm/ast-utils.js +0 -44
  8. package/dist/esm/ast-utils.js.map +0 -1
  9. package/dist/esm/ast-utils.test.d.ts +0 -1
  10. package/dist/esm/devtools-packages.d.ts +0 -2
  11. package/dist/esm/devtools-packages.js +0 -15
  12. package/dist/esm/devtools-packages.js.map +0 -1
  13. package/dist/esm/devtools-packages.test.d.ts +0 -1
  14. package/dist/esm/editor.d.ts +0 -25
  15. package/dist/esm/editor.js +0 -20
  16. package/dist/esm/editor.js.map +0 -1
  17. package/dist/esm/editor.test.d.ts +0 -1
  18. package/dist/esm/enhance-logs.d.ts +0 -4
  19. package/dist/esm/enhance-logs.js +0 -51
  20. package/dist/esm/enhance-logs.js.map +0 -1
  21. package/dist/esm/enhance-logs.test.d.ts +0 -1
  22. package/dist/esm/inject-plugin.d.ts +0 -22
  23. package/dist/esm/inject-plugin.js +0 -179
  24. package/dist/esm/inject-plugin.js.map +0 -1
  25. package/dist/esm/inject-plugin.test.d.ts +0 -1
  26. package/dist/esm/inject-source.d.ts +0 -7
  27. package/dist/esm/inject-source.js +0 -114
  28. package/dist/esm/inject-source.js.map +0 -1
  29. package/dist/esm/inject-source.test.d.ts +0 -1
  30. package/dist/esm/matcher.d.ts +0 -1
  31. package/dist/esm/matcher.js +0 -13
  32. package/dist/esm/matcher.js.map +0 -1
  33. package/dist/esm/matcher.test.d.ts +0 -1
  34. package/dist/esm/offset-to-loc.d.ts +0 -14
  35. package/dist/esm/offset-to-loc.js +0 -29
  36. package/dist/esm/offset-to-loc.js.map +0 -1
  37. package/dist/esm/offset-to-loc.test.d.ts +0 -1
  38. package/dist/esm/package-manager.d.ts +0 -16
  39. package/dist/esm/package-manager.js +0 -98
  40. package/dist/esm/package-manager.js.map +0 -1
  41. package/dist/esm/remove-devtools.d.ts +0 -4
  42. package/dist/esm/remove-devtools.js +0 -96
  43. package/dist/esm/remove-devtools.js.map +0 -1
  44. package/dist/esm/remove-devtools.test.d.ts +0 -1
  45. package/dist/esm/runtime-bridge.d.ts +0 -31
  46. package/dist/esm/runtime-bridge.js +0 -75
  47. package/dist/esm/runtime-bridge.js.map +0 -1
  48. package/dist/esm/runtime-bridge.test.d.ts +0 -1
  49. package/dist/esm/utils.d.ts +0 -31
  50. package/dist/esm/utils.js +0 -155
  51. package/dist/esm/utils.js.map +0 -1
  52. package/dist/esm/utils.test.d.ts +0 -1
  53. package/dist/esm/virtual-console.d.ts +0 -19
  54. package/dist/esm/virtual-console.js +0 -336
  55. package/dist/esm/virtual-console.js.map +0 -1
  56. package/dist/esm/virtual-console.test.d.ts +0 -1
  57. package/src/ast-utils.test.ts +0 -109
  58. package/src/ast-utils.ts +0 -58
  59. package/src/devtools-packages.test.ts +0 -58
  60. package/src/devtools-packages.ts +0 -12
  61. package/src/editor.test.ts +0 -75
  62. package/src/editor.ts +0 -53
  63. package/src/enhance-logs.test.ts +0 -132
  64. package/src/enhance-logs.ts +0 -71
  65. package/src/inject-plugin.test.ts +0 -1139
  66. package/src/inject-plugin.ts +0 -300
  67. package/src/inject-source.test.ts +0 -939
  68. package/src/inject-source.ts +0 -235
  69. package/src/matcher.test.ts +0 -33
  70. package/src/matcher.ts +0 -19
  71. package/src/offset-to-loc.test.ts +0 -34
  72. package/src/offset-to-loc.ts +0 -39
  73. package/src/package-manager.ts +0 -181
  74. package/src/remove-devtools.test.ts +0 -607
  75. package/src/remove-devtools.ts +0 -190
  76. package/src/runtime-bridge.test.ts +0 -179
  77. package/src/runtime-bridge.ts +0 -113
  78. package/src/utils.test.ts +0 -184
  79. package/src/utils.ts +0 -247
  80. package/src/virtual-console.test.ts +0 -244
  81. package/src/virtual-console.ts +0 -341
package/src/utils.ts DELETED
@@ -1,247 +0,0 @@
1
- import fs from 'node:fs/promises'
2
- import { normalizePath } from 'vite'
3
- import type { Connect } from 'vite'
4
- import type { IncomingMessage, ServerResponse } from 'node:http'
5
- import type { PackageJson } from '@tanstack/devtools-client'
6
-
7
- type DevToolsRequestHandler = (data: any) => void
8
-
9
- type DevToolsViteRequestOptions = {
10
- onOpenSource?: DevToolsRequestHandler
11
- onConsolePipe?: (entries: Array<any>) => void
12
- onServerConsolePipe?: (entries: Array<any>) => void
13
- onConsolePipeSSE?: (
14
- res: ServerResponse<IncomingMessage>,
15
- req: Connect.IncomingMessage,
16
- ) => void
17
- }
18
-
19
- export const handleDevToolsViteRequest = (
20
- req: Connect.IncomingMessage,
21
- res: ServerResponse<IncomingMessage>,
22
- next: Connect.NextFunction,
23
- cbOrOptions: DevToolsRequestHandler | DevToolsViteRequestOptions,
24
- ) => {
25
- // Normalize to options object for backward compatibility
26
- const options: DevToolsViteRequestOptions =
27
- typeof cbOrOptions === 'function'
28
- ? { onOpenSource: cbOrOptions }
29
- : cbOrOptions
30
-
31
- // Handle open-source requests
32
- if (req.url?.includes('__tsd/open-source')) {
33
- const searchParams = new URLSearchParams(req.url.split('?')[1])
34
-
35
- const source = searchParams.get('source')
36
- if (!source) {
37
- return
38
- }
39
-
40
- const parsed = parseOpenSourceParam(source)
41
- if (!parsed) {
42
- return
43
- }
44
- const { file, line, column } = parsed
45
-
46
- options.onOpenSource?.({
47
- type: 'open-source',
48
- routine: 'open-source',
49
- data: {
50
- source: file ? normalizePath(`${process.cwd()}/${file}`) : undefined,
51
- line,
52
- column,
53
- },
54
- })
55
- res.setHeader('Content-Type', 'text/html')
56
- res.write(`<script> window.close(); </script>`)
57
- res.end()
58
- return
59
- }
60
-
61
- // Handle console-pipe SSE endpoint (browser subscribes to server logs)
62
- if (req.url?.includes('__tsd/console-pipe/sse') && req.method === 'GET') {
63
- if (options.onConsolePipeSSE) {
64
- options.onConsolePipeSSE(res, req)
65
- return
66
- }
67
- return next()
68
- }
69
-
70
- // Handle server console-pipe POST endpoint (from app server runtime)
71
- if (req.url?.includes('__tsd/console-pipe/server') && req.method === 'POST') {
72
- if (options.onServerConsolePipe) {
73
- let body = ''
74
- req.on('data', (chunk: Buffer) => {
75
- body += chunk.toString()
76
- })
77
- req.on('end', () => {
78
- try {
79
- const { entries } = JSON.parse(body)
80
- options.onServerConsolePipe!(entries)
81
- res.statusCode = 200
82
- res.end('OK')
83
- } catch {
84
- res.statusCode = 400
85
- res.end('Bad Request')
86
- }
87
- })
88
- return
89
- }
90
- return next()
91
- }
92
-
93
- // Handle console-pipe POST endpoint (from client)
94
- if (req.url?.includes('__tsd/console-pipe') && req.method === 'POST') {
95
- if (options.onConsolePipe) {
96
- let body = ''
97
- req.on('data', (chunk: Buffer) => {
98
- body += chunk.toString()
99
- })
100
- req.on('end', () => {
101
- try {
102
- const { entries } = JSON.parse(body)
103
- options.onConsolePipe!(entries)
104
- res.statusCode = 200
105
- res.end('OK')
106
- } catch {
107
- res.statusCode = 400
108
- res.end('Bad Request')
109
- }
110
- })
111
- return
112
- }
113
- return next()
114
- }
115
-
116
- if (!req.url?.includes('__tsd')) {
117
- return next()
118
- }
119
-
120
- const chunks: Array<any> = []
121
- req.on('data', (chunk) => {
122
- chunks.push(chunk)
123
- })
124
- req.on('end', () => {
125
- const dataToParse = Buffer.concat(chunks)
126
- try {
127
- const parsedData = JSON.parse(dataToParse.toString())
128
- options.onOpenSource?.(parsedData)
129
- } catch (e) {}
130
- res.write('OK')
131
- res.end()
132
- })
133
- }
134
-
135
- export const parseOpenSourceParam = (source: string) => {
136
- // Capture everything up to the last two colon-separated numeric parts as the file.
137
- // This supports filenames that may themselves contain colons.
138
- const parts = source.match(/^(.+):(\d+):(\d+)$/)
139
-
140
- if (!parts) return null
141
-
142
- const [, file, line, column] = parts
143
- return { file, line, column }
144
- }
145
-
146
- const tryReadFile = async (filePath: string) => {
147
- try {
148
- const data = await fs.readFile(filePath, 'utf-8')
149
- return data
150
- } catch (error) {
151
- return null
152
- }
153
- }
154
-
155
- export const tryParseJson = <T extends any>(
156
- jsonString: string | null | undefined,
157
- ) => {
158
- if (!jsonString) {
159
- return null
160
- }
161
- try {
162
- const result = JSON.parse(jsonString)
163
- return result as T
164
- } catch (error) {
165
- return null
166
- }
167
- }
168
-
169
- export const readPackageJson = async () =>
170
- tryParseJson<PackageJson>(await tryReadFile(process.cwd() + '/package.json'))
171
-
172
- /**
173
- * Extracts and formats the source location from enhanced client console logs.
174
- * Instead of stripping the prefix entirely, we extract the file:line:column
175
- * from the "Go to Source" URL and use that as a prefix.
176
- *
177
- * Enhanced logs format (two variants):
178
- * 1. ['%cLOG%c %cGo to Source: http://...?source=%2Fsrc%2F...%c \n → ', 'color:...', 'color:...', 'color:...', 'color:...', 'message']
179
- * 2. ['\x1b[...]%s\x1b[...]', '%cLOG%c %cGo to Source: ...%c \n → ', 'color:...', 'color:...', 'color:...', 'color:...', 'message']
180
- *
181
- * Output: ['src/components/Header.tsx:26:13', 'message']
182
- */
183
- export const stripEnhancedLogPrefix = (
184
- args: Array<unknown>,
185
- formatSourceLocation?: (location: string) => unknown,
186
- ): Array<unknown> => {
187
- if (args.length === 0) return args
188
-
189
- // Find the arg that contains the Go to Source URL
190
- let sourceArgIndex = -1
191
- for (let i = 0; i < args.length; i++) {
192
- const arg = args[i]
193
- if (typeof arg === 'string' && arg.includes('__tsd/open-source?source=')) {
194
- sourceArgIndex = i
195
- break
196
- }
197
- }
198
-
199
- // If no source URL found, return args as-is (not an enhanced log)
200
- if (sourceArgIndex === -1) {
201
- return args
202
- }
203
-
204
- const sourceArg = args[sourceArgIndex] as string
205
-
206
- // Extract the source from the "Go to Source" URL
207
- // URL format: http://localhost:3000/__tsd/open-source?source=%2Fsrc%2Ffile.tsx%3A26%3A13%c
208
- // Note: The URL ends with %c which is a console format specifier, not URL encoding
209
- let sourceLocation = ''
210
- const sourceMatch = sourceArg.match(/source=([^&\s]+?)%c/)
211
- if (sourceMatch?.[1]) {
212
- try {
213
- sourceLocation = decodeURIComponent(sourceMatch[1])
214
- // Remove leading slash if present
215
- if (sourceLocation.startsWith('/')) {
216
- sourceLocation = sourceLocation.slice(1)
217
- }
218
- } catch {
219
- // If decoding fails, leave it empty
220
- }
221
- }
222
-
223
- // Count %c markers in the source arg to know how many style args follow it
224
- const styleCount = (sourceArg.match(/%c/g) || []).length
225
-
226
- // The actual user args start after the source arg and all its style args
227
- const userArgsStart = sourceArgIndex + 1 + styleCount
228
-
229
- // Build the result: source location prefix + remaining args (the actual user data)
230
- const result: Array<unknown> = []
231
-
232
- // Add source location as prefix if we found one
233
- if (sourceLocation) {
234
- result.push(
235
- formatSourceLocation
236
- ? formatSourceLocation(sourceLocation)
237
- : sourceLocation,
238
- )
239
- }
240
-
241
- // Add remaining args (the actual user data)
242
- for (let i = userArgsStart; i < args.length; i++) {
243
- result.push(args[i])
244
- }
245
-
246
- return result.length > 0 ? result : args
247
- }
@@ -1,244 +0,0 @@
1
- import { afterEach, describe, expect, test, vi } from 'vitest'
2
- import { generateConsolePipeCode } from './virtual-console'
3
-
4
- const TEST_VITE_URL = 'http://localhost:5173'
5
-
6
- afterEach(() => {
7
- vi.useRealTimers()
8
- vi.unstubAllGlobals()
9
- delete (window as any).__TSD_CONSOLE_PIPE_INITIALIZED__
10
- })
11
-
12
- function setupWarnConsolePipe() {
13
- const originalWarn = console.warn
14
- const originalWarnMock = vi.fn()
15
- const fetchMock = vi.fn().mockResolvedValue(undefined)
16
- const eventSourceUrls: Array<string> = []
17
-
18
- class MockEventSource {
19
- onmessage: ((event: MessageEvent) => void) | null = null
20
- onerror: (() => void) | null = null
21
-
22
- constructor(url: string) {
23
- eventSourceUrls.push(url)
24
- }
25
- }
26
-
27
- console.warn = originalWarnMock
28
- vi.stubGlobal('fetch', fetchMock)
29
- vi.stubGlobal('EventSource', MockEventSource)
30
-
31
- const code = generateConsolePipeCode(['warn'], TEST_VITE_URL)
32
- new Function(code)()
33
-
34
- return {
35
- eventSourceUrls,
36
- fetchMock,
37
- originalWarnMock,
38
- restore: () => {
39
- console.warn = originalWarn
40
- },
41
- }
42
- }
43
-
44
- function getFirstFetchBody(fetchMock: ReturnType<typeof vi.fn>) {
45
- const [, init] = fetchMock.mock.calls[0]!
46
- return JSON.parse(init.body)
47
- }
48
-
49
- describe('virtual-console', () => {
50
- test('generates inline code with specified levels', () => {
51
- const code = generateConsolePipeCode(['log', 'error'], TEST_VITE_URL)
52
-
53
- expect(code).toContain('["log","error"]')
54
- expect(code).toContain('originalConsole')
55
- expect(code).toContain('__TSD_CONSOLE_PIPE_INITIALIZED__')
56
- })
57
-
58
- test('uses fetch to send client logs', () => {
59
- const code = generateConsolePipeCode(['log'], TEST_VITE_URL)
60
-
61
- expect(code).toContain('/__tsd/console-pipe')
62
- expect(code).toContain("method: 'POST'")
63
- })
64
-
65
- test('uses SSE to receive server logs', () => {
66
- const code = generateConsolePipeCode(['log'], TEST_VITE_URL)
67
-
68
- expect(code).toContain("new EventSource('/__tsd/console-pipe/sse')")
69
- })
70
-
71
- test('includes environment detection', () => {
72
- const code = generateConsolePipeCode(['log'], TEST_VITE_URL)
73
-
74
- expect(code).toContain("typeof window === 'undefined'")
75
- expect(code).toContain('isServer')
76
- })
77
-
78
- test('includes batcher configuration', () => {
79
- const code = generateConsolePipeCode(['log'], TEST_VITE_URL)
80
-
81
- expect(code).toContain('BATCH_WAIT')
82
- expect(code).toContain('BATCH_MAX_SIZE')
83
- })
84
-
85
- test('includes flush functionality', () => {
86
- const code = generateConsolePipeCode(['log'], TEST_VITE_URL)
87
-
88
- expect(code).toContain('flushBatch')
89
- })
90
-
91
- test('includes beforeunload listener for browser', () => {
92
- const code = generateConsolePipeCode(['log'], TEST_VITE_URL)
93
-
94
- expect(code).toContain('beforeunload')
95
- })
96
-
97
- test('wraps code in IIFE', () => {
98
- const code = generateConsolePipeCode(['log'], TEST_VITE_URL)
99
-
100
- expect(code).toContain('(function __tsdConsolePipe()')
101
- expect(code).toContain('})();')
102
- })
103
-
104
- test('has no external imports', () => {
105
- const code = generateConsolePipeCode(['log'], TEST_VITE_URL)
106
-
107
- expect(code).not.toContain('import ')
108
- })
109
-
110
- test('includes vite server URL for server piping', () => {
111
- const code = generateConsolePipeCode(['log'], TEST_VITE_URL)
112
-
113
- expect(code).toContain(TEST_VITE_URL)
114
- expect(code).toContain('/__tsd/console-pipe/server')
115
- })
116
-
117
- test('serializes DOM elements before sending logs', async () => {
118
- vi.useFakeTimers()
119
-
120
- const { eventSourceUrls, fetchMock, originalWarnMock, restore } =
121
- setupWarnConsolePipe()
122
-
123
- try {
124
- const button = document.createElement('button')
125
- button.id = 'save'
126
- button.className = 'primary'
127
- button.type = 'button'
128
- button.setAttribute('data-testid', 'save-button')
129
-
130
- console.warn('gesture warning', button)
131
-
132
- await vi.advanceTimersByTimeAsync(100)
133
-
134
- expect(originalWarnMock).toHaveBeenCalledWith('gesture warning', button)
135
- expect(eventSourceUrls).toEqual(['/__tsd/console-pipe/sse'])
136
- expect(fetchMock).toHaveBeenCalledTimes(1)
137
-
138
- const body = getFirstFetchBody(fetchMock)
139
-
140
- expect(body.entries[0]).toMatchObject({
141
- level: 'warn',
142
- source: 'client',
143
- args: [
144
- 'gesture warning',
145
- '<button id="save" class="primary" type="button" data-testid="save-button">',
146
- ],
147
- })
148
- } finally {
149
- restore()
150
- }
151
- })
152
-
153
- test('serializes circular refs and Error objects before sending logs', async () => {
154
- vi.useFakeTimers()
155
-
156
- const { fetchMock, originalWarnMock, restore } = setupWarnConsolePipe()
157
-
158
- try {
159
- const circular: Record<string, unknown> = { name: 'root' }
160
- circular.self = circular
161
- const error = new Error('boom')
162
-
163
- console.warn('complex warning', circular, error)
164
-
165
- await vi.advanceTimersByTimeAsync(100)
166
-
167
- expect(originalWarnMock).toHaveBeenCalledWith(
168
- 'complex warning',
169
- circular,
170
- error,
171
- )
172
- expect(fetchMock).toHaveBeenCalledTimes(1)
173
-
174
- const body = getFirstFetchBody(fetchMock)
175
-
176
- expect(body.entries[0].args[1]).toEqual({
177
- name: 'root',
178
- self: '[Circular]',
179
- })
180
- expect(body.entries[0].args[2]).toMatchObject({
181
- name: 'Error',
182
- message: 'boom',
183
- })
184
- expect(typeof body.entries[0].args[2].stack).toBe('string')
185
- } finally {
186
- restore()
187
- }
188
- })
189
-
190
- test('limits large console payloads before sending logs', async () => {
191
- vi.useFakeTimers()
192
-
193
- const { fetchMock, restore } = setupWarnConsolePipe()
194
-
195
- try {
196
- const longArray = Array.from({ length: 101 }, (_, index) => index)
197
- const manyKeys: Record<string, number> = {}
198
- for (let index = 0; index < 101; index++) {
199
- manyKeys['key' + index] = index
200
- }
201
- const longString = 'x'.repeat(10001)
202
- const typedArray = new Uint8Array(1024)
203
- const deepObject = {
204
- a: {
205
- b: {
206
- c: {
207
- d: {
208
- e: {
209
- f: {
210
- g: 'too deep',
211
- },
212
- },
213
- },
214
- },
215
- },
216
- },
217
- }
218
-
219
- console.warn(
220
- 'large payload',
221
- longArray,
222
- manyKeys,
223
- longString,
224
- typedArray,
225
- deepObject,
226
- )
227
-
228
- await vi.advanceTimersByTimeAsync(100)
229
-
230
- const body = getFirstFetchBody(fetchMock)
231
-
232
- expect(body.entries[0].args[1]).toHaveLength(101)
233
- expect(body.entries[0].args[1][100]).toBe('... (1 more)')
234
- expect(Object.keys(body.entries[0].args[2])).toHaveLength(101)
235
- expect(body.entries[0].args[2]['...']).toBe('(1 more keys)')
236
- expect(body.entries[0].args[3].startsWith('x'.repeat(10000))).toBe(true)
237
- expect(body.entries[0].args[3]).toContain('... (1 more chars)')
238
- expect(body.entries[0].args[4]).toBe('[Uint8Array(1024)]')
239
- expect(body.entries[0].args[5].a.b.c.d.e.f).toBe('[MaxDepth]')
240
- } finally {
241
- restore()
242
- }
243
- })
244
- })