Skip to content
Source
Sign inSign up
TanStack/devtools
Open History to see the last commit

plugin.ts

698 lines22.0 KB

1import { devtoolsEventClient } from '@tanstack/devtools-client'
2import { ServerEventBus } from '@tanstack/devtools-event-bus/server'
3import { normalizePath } from 'vite'
4import chalk from 'chalk'
5import {
6 handleDevToolsViteRequest,
7 readPackageJson,
8 stripEnhancedLogPrefix,
9} from './utils'
10import { DEFAULT_EDITOR_CONFIG, handleOpenSource } from './editor'
11import { removeDevtools } from './remove-devtools'
12import { addSourceToJsx } from './inject-source'
13import { enhanceConsoleLog } from './enhance-logs'
14import { detectDevtoolsFile, injectPluginIntoFile } from './inject-plugin'
15import { TANSTACK_DEVTOOLS_PACKAGES } from './devtools-packages'
16import {
17 addPluginToDevtools,
18 emitOutdatedDeps,
19 installPackage,
20} from './package-manager'
21import { generateConsolePipeCode } from './virtual-console'
22import {
23 injectRuntimeBridge,
24 wireRuntimeBridgeChannels,
25} from './runtime-bridge'
26import type { ServerResponse } from 'node:http'
27import type { Plugin } from 'vite'
28import type { EditorConfig } from './editor'
29import type {
30 HttpServerLike,
31 ServerEventBusConfig,
32} from '@tanstack/devtools-event-bus/server'
33​
34export type ConsoleLevel = 'log' | 'warn' | 'error' | 'info' | 'debug'
35​
36export type TanStackDevtoolsViteConfig = {
37 /**
38 * Configuration for the editor integration. Defaults to opening in VS code
39 */
40 editor?: EditorConfig
41 /**
42 * The configuration options for the server event bus
43 */
44 eventBusConfig?: ServerEventBusConfig & {
45 /**
46 * Should the server event bus be enabled or not
47 * @default true
48 */
49 enabled?: boolean // defaults to true
50 }
51 /**
52 * Configuration for enhanced logging.
53 */
54 enhancedLogs?: {
55 /**
56 * Whether to enable enhanced logging.
57 * @default true
58 */
59 enabled: boolean
60 }
61 /**
62 * Whether to remove devtools from the production build.
63 * @default true
64 */
65 removeDevtoolsOnBuild?: boolean
66​
67 /**
68 * Whether to log information to the console.
69 * @default true
70 */
71 logging?: boolean
72 /**
73 * Configuration for source injection.
74 */
75 injectSource?: {
76 /**
77 * Whether to enable source injection via data-tsd-source.
78 * @default true
79 */
80 enabled: boolean
81 /**
82 * List of files or patterns to ignore for source injection.
83 */
84 ignore?: {
85 files?: Array<string | RegExp>
86 components?: Array<string | RegExp>
87 }
88 }
89 /**
90 * Configuration for console piping between client and server.
91 * When enabled, console logs from the client will appear in the terminal,
92 * and server logs will appear in the browser console.
93 */
94 consolePiping?: {
95 /**
96 * Whether to enable console piping.
97 * @default true
98 */
99 enabled?: boolean
100 /**
101 * Which console methods to pipe.
102 * @default ['log', 'warn', 'error', 'info', 'debug']
103 */
104 levels?: Array<ConsoleLevel>
105 }
107​
108export const defineDevtoolsConfig = (config: TanStackDevtoolsViteConfig) =>
109 config
110​
111export const devtools = (args?: TanStackDevtoolsViteConfig): Array<Plugin> => {
112 let port = 5173
113 const logging = args?.logging ?? true
114 const enhancedLogsConfig = args?.enhancedLogs ?? { enabled: true }
115 const injectSourceConfig = args?.injectSource ?? { enabled: true }
116 const removeDevtoolsOnBuild = args?.removeDevtoolsOnBuild ?? true
117 const serverBusEnabled = args?.eventBusConfig?.enabled ?? true
118 const consolePipingConfig = args?.consolePiping ?? { enabled: true }
119 const consolePipingLevels: Array<ConsoleLevel> =
120 consolePipingConfig.levels ?? ['log', 'warn', 'error', 'info', 'debug']
121​
122 let devtoolsFileId: string | null = null
123 let devtoolsPort: number | null = null
124 let devtoolsHost: string | null = null
125 let devtoolsProtocol: 'http' | 'https' | null = null
126​
127 return [
128 {
129 enforce: 'pre',
130 name: '@tanstack/devtools:inject-source',
131 apply(config) {
132 return config.mode === 'development' && injectSourceConfig.enabled
133 },
134 transform: {
135 filter: {
136 id: {
137 exclude: [/node_modules/, /\?raw/, /\/dist\//, /\/build\//],
138 },
139 },
140 handler(code, id) {
141 return addSourceToJsx(code, id, args?.injectSource?.ignore)
142 },
143 },
144 },
145 {
146 name: '@tanstack/devtools:config',
147 enforce: 'pre',
148 config(_, { command }) {
149 // we do not apply any config changes for build
150 if (command !== 'serve') {
151 return
152 }
153​
154 /* const solidDedupeDeps = [
155 'solid-js',
156 'solid-js/web',
157 'solid-js/store',
158 'solid-js/html',
159 'solid-js/h',
160 ]
161​
162 return {
163 resolve: {
164 dedupe: solidDedupeDeps,
165 },
166 optimizeDeps: {
167 include: solidDedupeDeps,
168 },
169 } */
170 },
171 },
172 {
173 enforce: 'pre',
174 name: '@tanstack/devtools:custom-server',
175 apply(config) {
176 // Custom server is only needed in development for piping events to the client
177 return config.mode === 'development'
178 },
179 async configureServer(server) {
180 if (serverBusEnabled) {
181 const preferredPort = args?.eventBusConfig?.port ?? 4206
182 const isHttps = !!server.config.server.https
183 const serverHost =
184 typeof server.config.server.host === 'string'
185 ? server.config.server.host
186 : 'localhost'
187​
188 devtoolsProtocol = isHttps ? 'https' : 'http'
189 devtoolsHost = serverHost
190​
191 const bus = new ServerEventBus({
192 ...args?.eventBusConfig,
193 port: preferredPort,
194 host: serverHost,
195 // When HTTPS is enabled, piggyback on Vite's server
196 // so WebSocket/SSE connections share the same TLS certificate
197 ...(isHttps && server.httpServer
198 ? { httpServer: server.httpServer as HttpServerLike }
199 : {}),
200 })
201 // start() now handles EADDRINUSE and returns the actual port
202 devtoolsPort = await bus.start()
203 if ((server as any).environments) {
204 const teardownBridge = wireRuntimeBridgeChannels(
205 server as unknown as Parameters<
206 typeof wireRuntimeBridgeChannels
207 >[0],
208 () => globalThis.__TANSTACK_EVENT_TARGET__,
209 )
210 server.httpServer?.on('close', teardownBridge)
211 }
212 }
213​
214 server.middlewares.use((req, _res, next) => {
215 if (req.socket.localPort && req.socket.localPort !== port) {
216 port = req.socket.localPort
217 }
218 next()
219 })
220 if (server.config.server.port) {
221 port = server.config.server.port
222 }
223​
224 server.httpServer?.on('listening', () => {
225 port = server.config.server.port
226 })
227​
228 const editor = args?.editor ?? DEFAULT_EDITOR_CONFIG
229 const openInEditor: EditorConfig['open'] = async (
230 path,
231 lineNum,
232 columnNum,
233 ) => {
234 if (!path) {
235 return
236 }
237 await editor.open(path, lineNum, columnNum)
238 }
239​
240 const originalConsole = Object.fromEntries(
241 consolePipingLevels.map((l) => [l, console[l].bind(console)]),
242 ) as Partial<Record<ConsoleLevel, typeof console.log>>
243​
244 // SSE clients for broadcasting server logs to browser
245 const sseClients: Array<{
246 res: ServerResponse
247 id: number
248 }> = []
249 let sseClientId = 0
250 const consolePipingEnabled = consolePipingConfig.enabled ?? true
251​
252 server.middlewares.use((req, res, next) =>
253 handleDevToolsViteRequest(req, res, next, {
254 onOpenSource: (parsedData) => {
255 const { data, routine } = parsedData
256 if (routine === 'open-source') {
257 return handleOpenSource({
258 data: { type: data.type, data },
259 openInEditor,
260 })
261 }
262 return
263 },
264 ...(consolePipingEnabled
265 ? {
266 onConsolePipe: (entries) => {
267 for (const entry of entries) {
268 const prefix = chalk.cyan('[Client]')
269 const logMethod =
270 originalConsole[entry.level as ConsoleLevel] ??
271 // log exists in consolePipingLevels
272 originalConsole.log!
273​
274 const cleanedArgs = stripEnhancedLogPrefix(
275 entry.args,
276 (loc) => chalk.gray(loc),
277 )
278 logMethod(prefix, ...cleanedArgs)
279 }
280 },
281 onConsolePipeSSE: (res, req) => {
282 res.setHeader('Content-Type', 'text/event-stream')
283 res.setHeader('Cache-Control', 'no-cache')
284 res.setHeader('Connection', 'keep-alive')
285 res.setHeader('Access-Control-Allow-Origin', '*')
286 res.flushHeaders()
287​
288 const clientId = ++sseClientId
289 sseClients.push({ res, id: clientId })
290​
291 req.on('close', () => {
292 const index = sseClients.findIndex(
293 (c) => c.id === clientId,
294 )
295 if (index !== -1) {
296 sseClients.splice(index, 1)
297 }
298 })
299 },
300 onServerConsolePipe: (entries) => {
301 try {
302 const data = JSON.stringify({
303 entries: entries.map((e) => ({
304 level: e.level,
305 args: e.args,
306 source: 'server',
307 timestamp: e.timestamp || Date.now(),
308 })),
309 })
310​
311 for (const client of sseClients) {
312 client.res.write(`data: ${data}\n\n`)
313 }
314 } catch {}
315 },
316 }
317 : {}),
318 }),
319 )
320 },
321 },
322 {
323 name: '@tanstack/devtools:remove-devtools-on-build',
324 apply(config, { command }) {
325 // Check both command and mode to support various hosting providers
326 // Some providers (Cloudflare, Netlify, Heroku) might not use 'build' command
327 // but will always set mode to 'production' for production builds
328 return (
329 (command !== 'serve' || config.mode === 'production') &&
330 removeDevtoolsOnBuild
331 )
332 },
333 enforce: 'pre',
334 transform(code, id) {
335 if (
336 id.includes('node_modules') ||
337 id.includes('?raw') ||
338 !TANSTACK_DEVTOOLS_PACKAGES.some((pkg) => code.includes(pkg))
339 )
340 return
341 const transform = removeDevtools(code, id)
342 if (!transform) return
343 if (logging) {
344 console.log(
345 `\n${chalk.greenBright(`[@tanstack/devtools-vite]`)} Removed devtools code from: ${id.replace(normalizePath(process.cwd()), '')}\n`,
346 )
347 }
348 return transform
349 },
350 },
351 {
352 name: '@tanstack/devtools:event-client-setup',
353 apply(config, { command }) {
354 if (
355 process.env.CI ||
356 process.env.NODE_ENV !== 'development' ||
357 command !== 'serve'
358 )
359 return false
360 return config.mode === 'development'
361 },
362 async configureServer() {
363 const packageJson = await readPackageJson()
364 const outdatedDeps = emitOutdatedDeps().then((deps) => deps)
365​
366 // Listen for package installation requests
367 devtoolsEventClient.on('install-devtools', async (event) => {
368 const result = await installPackage(event.payload.packageName)
369 devtoolsEventClient.emit('devtools-installed', {
370 packageName: event.payload.packageName,
371 success: result.success,
372 error: result.error,
373 })
374​
375 // If installation was successful, automatically add the plugin to devtools
376 if (result.success) {
377 const { packageName, pluginName, pluginImport } = event.payload
378​
379 console.log(
380 chalk.blueBright(
381 `[@tanstack/devtools-vite] Auto-adding ${packageName} to devtools...`,
382 ),
383 )
384​
385 const injectResult = addPluginToDevtools(
386 devtoolsFileId,
387 packageName,
388 pluginName,
389 pluginImport,
390 )
391​
392 if (injectResult.success) {
393 // Emit plugin-added event so the UI updates
394 devtoolsEventClient.emit('plugin-added', {
395 packageName,
396 success: true,
397 })
398​
399 // Also re-read package.json to update the UI with the newly installed package
400 const updatedPackageJson = await readPackageJson()
401 devtoolsEventClient.emit('package-json-read', {
402 packageJson: updatedPackageJson,
403 })
404 }
405 }
406 })
407​
408 // Listen for add plugin to devtools requests
409 devtoolsEventClient.on('add-plugin-to-devtools', (event) => {
410 const { packageName, pluginName, pluginImport } = event.payload
411​
412 console.log(
413 chalk.blueBright(
414 `[@tanstack/devtools-vite] Adding ${packageName} to devtools...`,
415 ),
416 )
417​
418 const result = addPluginToDevtools(
419 devtoolsFileId,
420 packageName,
421 pluginName,
422 pluginImport,
423 )
424​
425 devtoolsEventClient.emit('plugin-added', {
426 packageName,
427 success: result.success,
428 error: result.error,
429 })
430 })
431​
432 // Handle bump-package-version event
433 devtoolsEventClient.on('bump-package-version', async (event) => {
434 const {
435 packageName,
436 devtoolsPackage,
437 pluginName,
438 minVersion,
439 pluginImport,
440 } = event.payload
441​
442 console.log(
443 chalk.blueBright(
444 `[@tanstack/devtools-vite] Bumping ${packageName} to version ${minVersion}...`,
445 ),
446 )
447​
448 // Install the package with the minimum version
449 const packageWithVersion = minVersion
450 ? `${packageName}@^${minVersion}`
451 : packageName
452​
453 const result = await installPackage(packageWithVersion)
454​
455 if (!result.success) {
456 console.log(
457 chalk.redBright(
458 `[@tanstack/devtools-vite] Failed to bump ${packageName}: ${result.error}`,
459 ),
460 )
461 devtoolsEventClient.emit('devtools-installed', {
462 packageName: devtoolsPackage,
463 success: false,
464 error: result.error,
465 })
466 return
467 }
468​
469 console.log(
470 chalk.greenBright(
471 `[@tanstack/devtools-vite] Successfully bumped ${packageName} to ${minVersion}!`,
472 ),
473 )
474​
475 // Check if we found the devtools file
476 if (!devtoolsFileId) {
477 console.log(
478 chalk.yellowBright(
479 `[@tanstack/devtools-vite] Devtools file not found. Skipping auto-injection.`,
480 ),
481 )
482 devtoolsEventClient.emit('devtools-installed', {
483 packageName: devtoolsPackage,
484 success: true,
485 })
486 return
487 }
488​
489 // Now inject the devtools plugin
490 console.log(
491 chalk.blueBright(
492 `[@tanstack/devtools-vite] Adding ${devtoolsPackage} to devtools...`,
493 ),
494 )
495​
496 const injectResult = injectPluginIntoFile(devtoolsFileId, {
497 packageName: devtoolsPackage,
498 pluginName,
499 pluginImport,
500 })
501​
502 if (injectResult.success) {
503 console.log(
504 chalk.greenBright(
505 `[@tanstack/devtools-vite] Successfully added ${devtoolsPackage} to devtools!`,
506 ),
507 )
508​
509 devtoolsEventClient.emit('plugin-added', {
510 packageName: devtoolsPackage,
511 success: true,
512 })
513​
514 // Re-read package.json to update the UI
515 const updatedPackageJson = await readPackageJson()
516 devtoolsEventClient.emit('package-json-read', {
517 packageJson: updatedPackageJson,
518 })
519 } else {
520 console.log(
521 chalk.redBright(
522 `[@tanstack/devtools-vite] Failed to add ${devtoolsPackage} to devtools: ${injectResult.error}`,
523 ),
524 )
525​
526 devtoolsEventClient.emit('plugin-added', {
527 packageName: devtoolsPackage,
528 success: false,
529 error: injectResult.error,
530 })
531 }
532 })
533​
534 // whenever a client mounts we send all the current info to the subscribers
535 devtoolsEventClient.on('mounted', async () => {
536 devtoolsEventClient.emit('outdated-deps-read', {
537 outdatedDeps: await outdatedDeps,
538 })
539 devtoolsEventClient.emit('package-json-read', {
540 packageJson,
541 })
542 })
543​
544 // Console piping is now handled via HTTP endpoints in the custom-server plugin
545 },
546 async handleHotUpdate({ file }) {
547 if (file.endsWith('package.json')) {
548 const newPackageJson = await readPackageJson()
549 devtoolsEventClient.emit('package-json-read', {
550 packageJson: newPackageJson,
551 })
552 emitOutdatedDeps()
553 }
554 },
555 },
556 // Enhanced logs must run BEFORE console-pipe-transform: the latter
557 // prepends a multi-line IIFE to root entry files, which would shift
558 // every line number computed by the oxc-parser AST and produce
559 // "Go to Source" links pointing past the end of the user's file.
560 {
561 name: '@tanstack/devtools:better-console-logs',
562 enforce: 'pre',
563 apply(config) {
564 return config.mode === 'development' && enhancedLogsConfig.enabled
565 },
566 transform: {
567 filter: {
568 id: {
569 exclude: [/node_modules/, /\?raw/, /\/dist\//, /\/build\//],
570 },
571 code: {
572 include: 'console.',
573 },
574 },
575 handler(code, id) {
576 return enhanceConsoleLog(code, id, port)
577 },
578 },
579 },
580 // Inject console piping code into entry files (both client and server)
581 {
582 name: '@tanstack/devtools:console-pipe-transform',
583 enforce: 'pre',
584 apply(config, { command }) {
585 return (
586 config.mode === 'development' &&
587 command === 'serve' &&
588 (consolePipingConfig.enabled ?? true)
589 )
590 },
591 transform: {
592 filter: {
593 id: {
594 include: /\.(tsx?|jsx?)$/,
595 exclude: [/node_modules/, /\/dist\//, /\?/],
596 },
597 code: {
598 exclude: /__tsdConsolePipe/, // avoid transforming files that already contain the console pipe code
599 },
600 },
601 handler(code) {
602 // Check if this is a root entry file (with <html> JSX or client entry points)
603 // In SSR frameworks, this file runs on BOTH server (SSR) and client (hydration)
604 // so our runtime check (typeof window === 'undefined') handles both environments
605 const isRootEntry =
606 /<html[\s>]/i.test(code) ||
607 code.includes('StartClient') ||
608 code.includes('hydrateRoot') ||
609 code.includes('createRoot') ||
610 (code.includes('solid-js/web') && code.includes('render('))
611​
612 if (isRootEntry) {
613 const viteServerUrl = `http://localhost:${port}`
614 const inlineCode = generateConsolePipeCode(
615 consolePipingLevels,
616 viteServerUrl,
617 )
618​
619 return `${inlineCode}\n${code}`
620 }
621​
622 return undefined
623 },
624 },
625 },
626 {
627 name: '@tanstack/devtools:inject-plugin',
628 apply(config, { command }) {
629 return config.mode === 'development' && command === 'serve'
630 },
631 transform(code, id) {
632 // First pass: find where TanStackDevtools is imported
633 if (!devtoolsFileId && detectDevtoolsFile(code)) {
634 // Extract actual file path (remove query params)
635 const [filePath] = id.split('?')
636 if (filePath) {
637 devtoolsFileId = filePath
638 }
639 }
640​
641 return undefined
642 },
643 },
644 {
645 name: '@tanstack/devtools:connection-injection',
646 apply(config, { command }) {
647 return config.mode === 'development' && command === 'serve'
648 },
649 transform(code, id) {
650 // Only transform @tanstack packages that contain the connection placeholders
651 const hasPlaceholder =
652 code.includes('__TANSTACK_DEVTOOLS_PORT__') ||
653 code.includes('__TANSTACK_DEVTOOLS_HOST__') ||
654 code.includes('__TANSTACK_DEVTOOLS_PROTOCOL__')
655 if (!hasPlaceholder) return
656 if (
657 !id.includes('@tanstack/devtools') &&
658 !id.includes('@tanstack/event-bus')
659 )
660 return
661​
662 // Replace placeholders with actual values (or fallback defaults)
663 const portValue = devtoolsPort ?? 4206
664 const hostValue = devtoolsHost ?? 'localhost'
665 const protocolValue = devtoolsProtocol ?? 'http'
666​
667 let result = code
668 result = result.replace(
669 /__TANSTACK_DEVTOOLS_PORT__/g,
670 String(portValue),
671 )
672 result = result.replace(
673 /__TANSTACK_DEVTOOLS_HOST__/g,
674 JSON.stringify(hostValue),
675 )
676 result = result.replace(
677 /__TANSTACK_DEVTOOLS_PROTOCOL__/g,
678 JSON.stringify(protocolValue),
679 )
680 return result
681 },
682 },
683 {
684 name: '@tanstack/devtools:runtime-bridge',
685 apply(config, { command }) {
686 return config.mode === 'development' && command === 'serve'
687 },
688 transform(code, id) {
689 if (id.includes('?')) return
690 return injectRuntimeBridge(
691 code,
692 id,
693 (this as any).environment?.name as string | undefined,
694 )
695 },
696 },
697 ]