Open History to see the last commit
1import fs from 'node:fs/promises'
2import { normalizePath } from 'vite'
3import type { Connect } from 'vite'
4import type { IncomingMessage, ServerResponse } from 'node:http'
5import type { PackageJson } from '@tanstack/devtools-client'
6β
7type DevToolsRequestHandler = (data: any) => void
8β
9type 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β
19export 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β
135export 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β
146const 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β
155export 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β
169export 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 */
183export 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}