@tanstack/devtools-vite 0.7.2 → 0.8.1

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.
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -7,6 +7,7 @@ import { enhanceConsoleLog } from "./enhance-logs.js";
7
7
  import { detectDevtoolsFile, injectPluginIntoFile } from "./inject-plugin.js";
8
8
  import { addPluginToDevtools, emitOutdatedDeps, installPackage } from "./package-manager.js";
9
9
  import { generateConsolePipeCode } from "./virtual-console.js";
10
+ import { injectRuntimeBridge, wireRuntimeBridgeChannels } from "./runtime-bridge.js";
10
11
  import { devtoolsEventClient } from "@tanstack/devtools-client";
11
12
  import { ServerEventBus } from "@tanstack/devtools-event-bus/server";
12
13
  import { normalizePath } from "vite";
@@ -77,6 +78,10 @@ var devtools = (args) => {
77
78
  host: serverHost,
78
79
  ...isHttps && server.httpServer ? { httpServer: server.httpServer } : {}
79
80
  }).start();
81
+ if (server.environments) {
82
+ const teardownBridge = wireRuntimeBridgeChannels(server, () => globalThis.__TANSTACK_EVENT_TARGET__);
83
+ server.httpServer?.on("close", teardownBridge);
84
+ }
80
85
  }
81
86
  server.middlewares.use((req, _res, next) => {
82
87
  if (req.socket.localPort && req.socket.localPort !== port) port = req.socket.localPort;
@@ -328,6 +333,16 @@ var devtools = (args) => {
328
333
  result = result.replace(/__TANSTACK_DEVTOOLS_PROTOCOL__/g, JSON.stringify(protocolValue));
329
334
  return result;
330
335
  }
336
+ },
337
+ {
338
+ name: "@tanstack/devtools:runtime-bridge",
339
+ apply(config, { command }) {
340
+ return config.mode === "development" && command === "serve";
341
+ },
342
+ transform(code, id) {
343
+ if (id.includes("?")) return;
344
+ return injectRuntimeBridge(code, id, this.environment?.name);
345
+ }
331
346
  }
332
347
  ];
333
348
  };
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.js","names":[],"sources":["../../src/plugin.ts"],"sourcesContent":["import { devtoolsEventClient } from '@tanstack/devtools-client'\nimport { ServerEventBus } from '@tanstack/devtools-event-bus/server'\nimport { normalizePath } from 'vite'\nimport chalk from 'chalk'\nimport {\n handleDevToolsViteRequest,\n readPackageJson,\n stripEnhancedLogPrefix,\n} from './utils'\nimport { DEFAULT_EDITOR_CONFIG, handleOpenSource } from './editor'\nimport { removeDevtools } from './remove-devtools'\nimport { addSourceToJsx } from './inject-source'\nimport { enhanceConsoleLog } from './enhance-logs'\nimport { detectDevtoolsFile, injectPluginIntoFile } from './inject-plugin'\nimport { TANSTACK_DEVTOOLS_PACKAGES } from './devtools-packages'\nimport {\n addPluginToDevtools,\n emitOutdatedDeps,\n installPackage,\n} from './package-manager'\nimport { generateConsolePipeCode } from './virtual-console'\nimport type { ServerResponse } from 'node:http'\nimport type { Plugin } from 'vite'\nimport type { EditorConfig } from './editor'\nimport type {\n HttpServerLike,\n ServerEventBusConfig,\n} from '@tanstack/devtools-event-bus/server'\n\nexport type ConsoleLevel = 'log' | 'warn' | 'error' | 'info' | 'debug'\n\nexport type TanStackDevtoolsViteConfig = {\n /**\n * Configuration for the editor integration. Defaults to opening in VS code\n */\n editor?: EditorConfig\n /**\n * The configuration options for the server event bus\n */\n eventBusConfig?: ServerEventBusConfig & {\n /**\n * Should the server event bus be enabled or not\n * @default true\n */\n enabled?: boolean // defaults to true\n }\n /**\n * Configuration for enhanced logging.\n */\n enhancedLogs?: {\n /**\n * Whether to enable enhanced logging.\n * @default true\n */\n enabled: boolean\n }\n /**\n * Whether to remove devtools from the production build.\n * @default true\n */\n removeDevtoolsOnBuild?: boolean\n\n /**\n * Whether to log information to the console.\n * @default true\n */\n logging?: boolean\n /**\n * Configuration for source injection.\n */\n injectSource?: {\n /**\n * Whether to enable source injection via data-tsd-source.\n * @default true\n */\n enabled: boolean\n /**\n * List of files or patterns to ignore for source injection.\n */\n ignore?: {\n files?: Array<string | RegExp>\n components?: Array<string | RegExp>\n }\n }\n /**\n * Configuration for console piping between client and server.\n * When enabled, console logs from the client will appear in the terminal,\n * and server logs will appear in the browser console.\n */\n consolePiping?: {\n /**\n * Whether to enable console piping.\n * @default true\n */\n enabled?: boolean\n /**\n * Which console methods to pipe.\n * @default ['log', 'warn', 'error', 'info', 'debug']\n */\n levels?: Array<ConsoleLevel>\n }\n}\n\nexport const defineDevtoolsConfig = (config: TanStackDevtoolsViteConfig) =>\n config\n\nexport const devtools = (args?: TanStackDevtoolsViteConfig): Array<Plugin> => {\n let port = 5173\n const logging = args?.logging ?? true\n const enhancedLogsConfig = args?.enhancedLogs ?? { enabled: true }\n const injectSourceConfig = args?.injectSource ?? { enabled: true }\n const removeDevtoolsOnBuild = args?.removeDevtoolsOnBuild ?? true\n const serverBusEnabled = args?.eventBusConfig?.enabled ?? true\n const consolePipingConfig = args?.consolePiping ?? { enabled: true }\n const consolePipingLevels: Array<ConsoleLevel> =\n consolePipingConfig.levels ?? ['log', 'warn', 'error', 'info', 'debug']\n\n let devtoolsFileId: string | null = null\n let devtoolsPort: number | null = null\n let devtoolsHost: string | null = null\n let devtoolsProtocol: 'http' | 'https' | null = null\n\n return [\n {\n enforce: 'pre',\n name: '@tanstack/devtools:inject-source',\n apply(config) {\n return config.mode === 'development' && injectSourceConfig.enabled\n },\n transform: {\n filter: {\n id: {\n exclude: [/node_modules/, /\\?raw/, /\\/dist\\//, /\\/build\\//],\n },\n },\n handler(code, id) {\n return addSourceToJsx(code, id, args?.injectSource?.ignore)\n },\n },\n },\n {\n name: '@tanstack/devtools:config',\n enforce: 'pre',\n config(_, { command }) {\n // we do not apply any config changes for build\n if (command !== 'serve') {\n return\n }\n\n /* const solidDedupeDeps = [\n 'solid-js',\n 'solid-js/web',\n 'solid-js/store',\n 'solid-js/html',\n 'solid-js/h',\n ]\n\n return {\n resolve: {\n dedupe: solidDedupeDeps,\n },\n optimizeDeps: {\n include: solidDedupeDeps,\n },\n } */\n },\n },\n {\n enforce: 'pre',\n name: '@tanstack/devtools:custom-server',\n apply(config) {\n // Custom server is only needed in development for piping events to the client\n return config.mode === 'development'\n },\n async configureServer(server) {\n if (serverBusEnabled) {\n const preferredPort = args?.eventBusConfig?.port ?? 4206\n const isHttps = !!server.config.server.https\n const serverHost =\n typeof server.config.server.host === 'string'\n ? server.config.server.host\n : 'localhost'\n\n devtoolsProtocol = isHttps ? 'https' : 'http'\n devtoolsHost = serverHost\n\n const bus = new ServerEventBus({\n ...args?.eventBusConfig,\n port: preferredPort,\n host: serverHost,\n // When HTTPS is enabled, piggyback on Vite's server\n // so WebSocket/SSE connections share the same TLS certificate\n ...(isHttps && server.httpServer\n ? { httpServer: server.httpServer as HttpServerLike }\n : {}),\n })\n // start() now handles EADDRINUSE and returns the actual port\n devtoolsPort = await bus.start()\n }\n\n server.middlewares.use((req, _res, next) => {\n if (req.socket.localPort && req.socket.localPort !== port) {\n port = req.socket.localPort\n }\n next()\n })\n if (server.config.server.port) {\n port = server.config.server.port\n }\n\n server.httpServer?.on('listening', () => {\n port = server.config.server.port\n })\n\n const editor = args?.editor ?? DEFAULT_EDITOR_CONFIG\n const openInEditor: EditorConfig['open'] = async (\n path,\n lineNum,\n columnNum,\n ) => {\n if (!path) {\n return\n }\n await editor.open(path, lineNum, columnNum)\n }\n\n const originalConsole = Object.fromEntries(\n consolePipingLevels.map((l) => [l, console[l].bind(console)]),\n ) as Partial<Record<ConsoleLevel, typeof console.log>>\n\n // SSE clients for broadcasting server logs to browser\n const sseClients: Array<{\n res: ServerResponse\n id: number\n }> = []\n let sseClientId = 0\n const consolePipingEnabled = consolePipingConfig.enabled ?? true\n\n server.middlewares.use((req, res, next) =>\n handleDevToolsViteRequest(req, res, next, {\n onOpenSource: (parsedData) => {\n const { data, routine } = parsedData\n if (routine === 'open-source') {\n return handleOpenSource({\n data: { type: data.type, data },\n openInEditor,\n })\n }\n return\n },\n ...(consolePipingEnabled\n ? {\n onConsolePipe: (entries) => {\n for (const entry of entries) {\n const prefix = chalk.cyan('[Client]')\n const logMethod =\n originalConsole[entry.level as ConsoleLevel] ??\n // log exists in consolePipingLevels\n originalConsole.log!\n\n const cleanedArgs = stripEnhancedLogPrefix(\n entry.args,\n (loc) => chalk.gray(loc),\n )\n logMethod(prefix, ...cleanedArgs)\n }\n },\n onConsolePipeSSE: (res, req) => {\n res.setHeader('Content-Type', 'text/event-stream')\n res.setHeader('Cache-Control', 'no-cache')\n res.setHeader('Connection', 'keep-alive')\n res.setHeader('Access-Control-Allow-Origin', '*')\n res.flushHeaders()\n\n const clientId = ++sseClientId\n sseClients.push({ res, id: clientId })\n\n req.on('close', () => {\n const index = sseClients.findIndex(\n (c) => c.id === clientId,\n )\n if (index !== -1) {\n sseClients.splice(index, 1)\n }\n })\n },\n onServerConsolePipe: (entries) => {\n try {\n const data = JSON.stringify({\n entries: entries.map((e) => ({\n level: e.level,\n args: e.args,\n source: 'server',\n timestamp: e.timestamp || Date.now(),\n })),\n })\n\n for (const client of sseClients) {\n client.res.write(`data: ${data}\\n\\n`)\n }\n } catch {}\n },\n }\n : {}),\n }),\n )\n },\n },\n {\n name: '@tanstack/devtools:remove-devtools-on-build',\n apply(config, { command }) {\n // Check both command and mode to support various hosting providers\n // Some providers (Cloudflare, Netlify, Heroku) might not use 'build' command\n // but will always set mode to 'production' for production builds\n return (\n (command !== 'serve' || config.mode === 'production') &&\n removeDevtoolsOnBuild\n )\n },\n enforce: 'pre',\n transform(code, id) {\n if (\n id.includes('node_modules') ||\n id.includes('?raw') ||\n !TANSTACK_DEVTOOLS_PACKAGES.some((pkg) => code.includes(pkg))\n )\n return\n const transform = removeDevtools(code, id)\n if (!transform) return\n if (logging) {\n console.log(\n `\\n${chalk.greenBright(`[@tanstack/devtools-vite]`)} Removed devtools code from: ${id.replace(normalizePath(process.cwd()), '')}\\n`,\n )\n }\n return transform\n },\n },\n {\n name: '@tanstack/devtools:event-client-setup',\n apply(config, { command }) {\n if (\n process.env.CI ||\n process.env.NODE_ENV !== 'development' ||\n command !== 'serve'\n )\n return false\n return config.mode === 'development'\n },\n async configureServer() {\n const packageJson = await readPackageJson()\n const outdatedDeps = emitOutdatedDeps().then((deps) => deps)\n\n // Listen for package installation requests\n devtoolsEventClient.on('install-devtools', async (event) => {\n const result = await installPackage(event.payload.packageName)\n devtoolsEventClient.emit('devtools-installed', {\n packageName: event.payload.packageName,\n success: result.success,\n error: result.error,\n })\n\n // If installation was successful, automatically add the plugin to devtools\n if (result.success) {\n const { packageName, pluginName, pluginImport } = event.payload\n\n console.log(\n chalk.blueBright(\n `[@tanstack/devtools-vite] Auto-adding ${packageName} to devtools...`,\n ),\n )\n\n const injectResult = addPluginToDevtools(\n devtoolsFileId,\n packageName,\n pluginName,\n pluginImport,\n )\n\n if (injectResult.success) {\n // Emit plugin-added event so the UI updates\n devtoolsEventClient.emit('plugin-added', {\n packageName,\n success: true,\n })\n\n // Also re-read package.json to update the UI with the newly installed package\n const updatedPackageJson = await readPackageJson()\n devtoolsEventClient.emit('package-json-read', {\n packageJson: updatedPackageJson,\n })\n }\n }\n })\n\n // Listen for add plugin to devtools requests\n devtoolsEventClient.on('add-plugin-to-devtools', (event) => {\n const { packageName, pluginName, pluginImport } = event.payload\n\n console.log(\n chalk.blueBright(\n `[@tanstack/devtools-vite] Adding ${packageName} to devtools...`,\n ),\n )\n\n const result = addPluginToDevtools(\n devtoolsFileId,\n packageName,\n pluginName,\n pluginImport,\n )\n\n devtoolsEventClient.emit('plugin-added', {\n packageName,\n success: result.success,\n error: result.error,\n })\n })\n\n // Handle bump-package-version event\n devtoolsEventClient.on('bump-package-version', async (event) => {\n const {\n packageName,\n devtoolsPackage,\n pluginName,\n minVersion,\n pluginImport,\n } = event.payload\n\n console.log(\n chalk.blueBright(\n `[@tanstack/devtools-vite] Bumping ${packageName} to version ${minVersion}...`,\n ),\n )\n\n // Install the package with the minimum version\n const packageWithVersion = minVersion\n ? `${packageName}@^${minVersion}`\n : packageName\n\n const result = await installPackage(packageWithVersion)\n\n if (!result.success) {\n console.log(\n chalk.redBright(\n `[@tanstack/devtools-vite] Failed to bump ${packageName}: ${result.error}`,\n ),\n )\n devtoolsEventClient.emit('devtools-installed', {\n packageName: devtoolsPackage,\n success: false,\n error: result.error,\n })\n return\n }\n\n console.log(\n chalk.greenBright(\n `[@tanstack/devtools-vite] Successfully bumped ${packageName} to ${minVersion}!`,\n ),\n )\n\n // Check if we found the devtools file\n if (!devtoolsFileId) {\n console.log(\n chalk.yellowBright(\n `[@tanstack/devtools-vite] Devtools file not found. Skipping auto-injection.`,\n ),\n )\n devtoolsEventClient.emit('devtools-installed', {\n packageName: devtoolsPackage,\n success: true,\n })\n return\n }\n\n // Now inject the devtools plugin\n console.log(\n chalk.blueBright(\n `[@tanstack/devtools-vite] Adding ${devtoolsPackage} to devtools...`,\n ),\n )\n\n const injectResult = injectPluginIntoFile(devtoolsFileId, {\n packageName: devtoolsPackage,\n pluginName,\n pluginImport,\n })\n\n if (injectResult.success) {\n console.log(\n chalk.greenBright(\n `[@tanstack/devtools-vite] Successfully added ${devtoolsPackage} to devtools!`,\n ),\n )\n\n devtoolsEventClient.emit('plugin-added', {\n packageName: devtoolsPackage,\n success: true,\n })\n\n // Re-read package.json to update the UI\n const updatedPackageJson = await readPackageJson()\n devtoolsEventClient.emit('package-json-read', {\n packageJson: updatedPackageJson,\n })\n } else {\n console.log(\n chalk.redBright(\n `[@tanstack/devtools-vite] Failed to add ${devtoolsPackage} to devtools: ${injectResult.error}`,\n ),\n )\n\n devtoolsEventClient.emit('plugin-added', {\n packageName: devtoolsPackage,\n success: false,\n error: injectResult.error,\n })\n }\n })\n\n // whenever a client mounts we send all the current info to the subscribers\n devtoolsEventClient.on('mounted', async () => {\n devtoolsEventClient.emit('outdated-deps-read', {\n outdatedDeps: await outdatedDeps,\n })\n devtoolsEventClient.emit('package-json-read', {\n packageJson,\n })\n })\n\n // Console piping is now handled via HTTP endpoints in the custom-server plugin\n },\n async handleHotUpdate({ file }) {\n if (file.endsWith('package.json')) {\n const newPackageJson = await readPackageJson()\n devtoolsEventClient.emit('package-json-read', {\n packageJson: newPackageJson,\n })\n emitOutdatedDeps()\n }\n },\n },\n // Enhanced logs must run BEFORE console-pipe-transform: the latter\n // prepends a multi-line IIFE to root entry files, which would shift\n // every line number computed by the oxc-parser AST and produce\n // \"Go to Source\" links pointing past the end of the user's file.\n {\n name: '@tanstack/devtools:better-console-logs',\n enforce: 'pre',\n apply(config) {\n return config.mode === 'development' && enhancedLogsConfig.enabled\n },\n transform: {\n filter: {\n id: {\n exclude: [/node_modules/, /\\?raw/, /\\/dist\\//, /\\/build\\//],\n },\n code: {\n include: 'console.',\n },\n },\n handler(code, id) {\n return enhanceConsoleLog(code, id, port)\n },\n },\n },\n // Inject console piping code into entry files (both client and server)\n {\n name: '@tanstack/devtools:console-pipe-transform',\n enforce: 'pre',\n apply(config, { command }) {\n return (\n config.mode === 'development' &&\n command === 'serve' &&\n (consolePipingConfig.enabled ?? true)\n )\n },\n transform: {\n filter: {\n id: {\n include: /\\.(tsx?|jsx?)$/,\n exclude: [/node_modules/, /\\/dist\\//, /\\?/],\n },\n code: {\n exclude: /__tsdConsolePipe/, // avoid transforming files that already contain the console pipe code\n },\n },\n handler(code) {\n // Check if this is a root entry file (with <html> JSX or client entry points)\n // In SSR frameworks, this file runs on BOTH server (SSR) and client (hydration)\n // so our runtime check (typeof window === 'undefined') handles both environments\n const isRootEntry =\n /<html[\\s>]/i.test(code) ||\n code.includes('StartClient') ||\n code.includes('hydrateRoot') ||\n code.includes('createRoot') ||\n (code.includes('solid-js/web') && code.includes('render('))\n\n if (isRootEntry) {\n const viteServerUrl = `http://localhost:${port}`\n const inlineCode = generateConsolePipeCode(\n consolePipingLevels,\n viteServerUrl,\n )\n\n return `${inlineCode}\\n${code}`\n }\n\n return undefined\n },\n },\n },\n {\n name: '@tanstack/devtools:inject-plugin',\n apply(config, { command }) {\n return config.mode === 'development' && command === 'serve'\n },\n transform(code, id) {\n // First pass: find where TanStackDevtools is imported\n if (!devtoolsFileId && detectDevtoolsFile(code)) {\n // Extract actual file path (remove query params)\n const [filePath] = id.split('?')\n if (filePath) {\n devtoolsFileId = filePath\n }\n }\n\n return undefined\n },\n },\n {\n name: '@tanstack/devtools:connection-injection',\n apply(config, { command }) {\n return config.mode === 'development' && command === 'serve'\n },\n transform(code, id) {\n // Only transform @tanstack packages that contain the connection placeholders\n const hasPlaceholder =\n code.includes('__TANSTACK_DEVTOOLS_PORT__') ||\n code.includes('__TANSTACK_DEVTOOLS_HOST__') ||\n code.includes('__TANSTACK_DEVTOOLS_PROTOCOL__')\n if (!hasPlaceholder) return\n if (\n !id.includes('@tanstack/devtools') &&\n !id.includes('@tanstack/event-bus')\n )\n return\n\n // Replace placeholders with actual values (or fallback defaults)\n const portValue = devtoolsPort ?? 4206\n const hostValue = devtoolsHost ?? 'localhost'\n const protocolValue = devtoolsProtocol ?? 'http'\n\n let result = code\n result = result.replace(\n /__TANSTACK_DEVTOOLS_PORT__/g,\n String(portValue),\n )\n result = result.replace(\n /__TANSTACK_DEVTOOLS_HOST__/g,\n JSON.stringify(hostValue),\n )\n result = result.replace(\n /__TANSTACK_DEVTOOLS_PROTOCOL__/g,\n JSON.stringify(protocolValue),\n )\n return result\n },\n },\n ]\n}\n"],"mappings":";;;;;;;;;;;;;;AAuGA,IAAa,wBAAwB,WACnC;AAEF,IAAa,YAAY,SAAqD;CAC5E,IAAI,OAAO;CACX,MAAM,UAAU,MAAM,WAAW;CACjC,MAAM,qBAAqB,MAAM,gBAAgB,EAAE,SAAS,MAAM;CAClE,MAAM,qBAAqB,MAAM,gBAAgB,EAAE,SAAS,MAAM;CAClE,MAAM,wBAAwB,MAAM,yBAAyB;CAC7D,MAAM,mBAAmB,MAAM,gBAAgB,WAAW;CAC1D,MAAM,sBAAsB,MAAM,iBAAiB,EAAE,SAAS,MAAM;CACpE,MAAM,sBACJ,oBAAoB,UAAU;EAAC;EAAO;EAAQ;EAAS;EAAQ;EAAQ;CAEzE,IAAI,iBAAgC;CACpC,IAAI,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Ac,KAAK,KAAK,IACxB,KAAK,SAAS,cAAc,IAC5B,KAAK,SAAS,cAAc,IAC5B,KAAK,SAAS,aAAa,IAC1B,KAAK,SAAS,eAAe,IAAI,KAAK,SAAS,UAAU,EAS1D,OAAO,GALY,wBACjB,qBACA,oBAHwC,OAMhC,CAAW,IAAI;;IAK9B;GACF;EACD;GACE,MAAM;GACN,MAAM,QAAQ,EAAE,WAAW;IACzB,OAAO,OAAO,SAAS,iBAAiB,YAAY;;GAEtD,UAAU,MAAM,IAAI;IAElB,IAAI,CAAC,kBAAkB,mBAAmB,KAAK,EAAE;KAE/C,MAAM,CAAC,YAAY,GAAG,MAAM,IAAI;KAChC,IAAI,UACF,iBAAiB;;;GAMxB;EACD;GACE,MAAM;GACN,MAAM,QAAQ,EAAE,WAAW;IACzB,OAAO,OAAO,SAAS,iBAAiB,YAAY;;GAEtD,UAAU,MAAM,IAAI;IAMlB,IAAI,EAHF,KAAK,SAAS,6BAA6B,IAC3C,KAAK,SAAS,6BAA6B,IAC3C,KAAK,SAAS,iCAAiC,GAC5B;IACrB,IACE,CAAC,GAAG,SAAS,qBAAqB,IAClC,CAAC,GAAG,SAAS,sBAAsB,EAEnC;IAGF,MAAM,YAAY,gBAAgB;IAClC,MAAM,YAAY,gBAAgB;IAClC,MAAM,gBAAgB,oBAAoB;IAE1C,IAAI,SAAS;IACb,SAAS,OAAO,QACd,+BACA,OAAO,UAAU,CAClB;IACD,SAAS,OAAO,QACd,+BACA,KAAK,UAAU,UAAU,CAC1B;IACD,SAAS,OAAO,QACd,mCACA,KAAK,UAAU,cAAc,CAC9B;IACD,OAAO;;GAEV;EACF"}
1
+ {"version":3,"file":"plugin.js","names":[],"sources":["../../src/plugin.ts"],"sourcesContent":["import { devtoolsEventClient } from '@tanstack/devtools-client'\nimport { ServerEventBus } from '@tanstack/devtools-event-bus/server'\nimport { normalizePath } from 'vite'\nimport chalk from 'chalk'\nimport {\n handleDevToolsViteRequest,\n readPackageJson,\n stripEnhancedLogPrefix,\n} from './utils'\nimport { DEFAULT_EDITOR_CONFIG, handleOpenSource } from './editor'\nimport { removeDevtools } from './remove-devtools'\nimport { addSourceToJsx } from './inject-source'\nimport { enhanceConsoleLog } from './enhance-logs'\nimport { detectDevtoolsFile, injectPluginIntoFile } from './inject-plugin'\nimport { TANSTACK_DEVTOOLS_PACKAGES } from './devtools-packages'\nimport {\n addPluginToDevtools,\n emitOutdatedDeps,\n installPackage,\n} from './package-manager'\nimport { generateConsolePipeCode } from './virtual-console'\nimport {\n injectRuntimeBridge,\n wireRuntimeBridgeChannels,\n} from './runtime-bridge'\nimport type { ServerResponse } from 'node:http'\nimport type { Plugin } from 'vite'\nimport type { EditorConfig } from './editor'\nimport type {\n HttpServerLike,\n ServerEventBusConfig,\n} from '@tanstack/devtools-event-bus/server'\n\nexport type ConsoleLevel = 'log' | 'warn' | 'error' | 'info' | 'debug'\n\nexport type TanStackDevtoolsViteConfig = {\n /**\n * Configuration for the editor integration. Defaults to opening in VS code\n */\n editor?: EditorConfig\n /**\n * The configuration options for the server event bus\n */\n eventBusConfig?: ServerEventBusConfig & {\n /**\n * Should the server event bus be enabled or not\n * @default true\n */\n enabled?: boolean // defaults to true\n }\n /**\n * Configuration for enhanced logging.\n */\n enhancedLogs?: {\n /**\n * Whether to enable enhanced logging.\n * @default true\n */\n enabled: boolean\n }\n /**\n * Whether to remove devtools from the production build.\n * @default true\n */\n removeDevtoolsOnBuild?: boolean\n\n /**\n * Whether to log information to the console.\n * @default true\n */\n logging?: boolean\n /**\n * Configuration for source injection.\n */\n injectSource?: {\n /**\n * Whether to enable source injection via data-tsd-source.\n * @default true\n */\n enabled: boolean\n /**\n * List of files or patterns to ignore for source injection.\n */\n ignore?: {\n files?: Array<string | RegExp>\n components?: Array<string | RegExp>\n }\n }\n /**\n * Configuration for console piping between client and server.\n * When enabled, console logs from the client will appear in the terminal,\n * and server logs will appear in the browser console.\n */\n consolePiping?: {\n /**\n * Whether to enable console piping.\n * @default true\n */\n enabled?: boolean\n /**\n * Which console methods to pipe.\n * @default ['log', 'warn', 'error', 'info', 'debug']\n */\n levels?: Array<ConsoleLevel>\n }\n}\n\nexport const defineDevtoolsConfig = (config: TanStackDevtoolsViteConfig) =>\n config\n\nexport const devtools = (args?: TanStackDevtoolsViteConfig): Array<Plugin> => {\n let port = 5173\n const logging = args?.logging ?? true\n const enhancedLogsConfig = args?.enhancedLogs ?? { enabled: true }\n const injectSourceConfig = args?.injectSource ?? { enabled: true }\n const removeDevtoolsOnBuild = args?.removeDevtoolsOnBuild ?? true\n const serverBusEnabled = args?.eventBusConfig?.enabled ?? true\n const consolePipingConfig = args?.consolePiping ?? { enabled: true }\n const consolePipingLevels: Array<ConsoleLevel> =\n consolePipingConfig.levels ?? ['log', 'warn', 'error', 'info', 'debug']\n\n let devtoolsFileId: string | null = null\n let devtoolsPort: number | null = null\n let devtoolsHost: string | null = null\n let devtoolsProtocol: 'http' | 'https' | null = null\n\n return [\n {\n enforce: 'pre',\n name: '@tanstack/devtools:inject-source',\n apply(config) {\n return config.mode === 'development' && injectSourceConfig.enabled\n },\n transform: {\n filter: {\n id: {\n exclude: [/node_modules/, /\\?raw/, /\\/dist\\//, /\\/build\\//],\n },\n },\n handler(code, id) {\n return addSourceToJsx(code, id, args?.injectSource?.ignore)\n },\n },\n },\n {\n name: '@tanstack/devtools:config',\n enforce: 'pre',\n config(_, { command }) {\n // we do not apply any config changes for build\n if (command !== 'serve') {\n return\n }\n\n /* const solidDedupeDeps = [\n 'solid-js',\n 'solid-js/web',\n 'solid-js/store',\n 'solid-js/html',\n 'solid-js/h',\n ]\n\n return {\n resolve: {\n dedupe: solidDedupeDeps,\n },\n optimizeDeps: {\n include: solidDedupeDeps,\n },\n } */\n },\n },\n {\n enforce: 'pre',\n name: '@tanstack/devtools:custom-server',\n apply(config) {\n // Custom server is only needed in development for piping events to the client\n return config.mode === 'development'\n },\n async configureServer(server) {\n if (serverBusEnabled) {\n const preferredPort = args?.eventBusConfig?.port ?? 4206\n const isHttps = !!server.config.server.https\n const serverHost =\n typeof server.config.server.host === 'string'\n ? server.config.server.host\n : 'localhost'\n\n devtoolsProtocol = isHttps ? 'https' : 'http'\n devtoolsHost = serverHost\n\n const bus = new ServerEventBus({\n ...args?.eventBusConfig,\n port: preferredPort,\n host: serverHost,\n // When HTTPS is enabled, piggyback on Vite's server\n // so WebSocket/SSE connections share the same TLS certificate\n ...(isHttps && server.httpServer\n ? { httpServer: server.httpServer as HttpServerLike }\n : {}),\n })\n // start() now handles EADDRINUSE and returns the actual port\n devtoolsPort = await bus.start()\n if ((server as any).environments) {\n const teardownBridge = wireRuntimeBridgeChannels(\n server as unknown as Parameters<\n typeof wireRuntimeBridgeChannels\n >[0],\n () => globalThis.__TANSTACK_EVENT_TARGET__,\n )\n server.httpServer?.on('close', teardownBridge)\n }\n }\n\n server.middlewares.use((req, _res, next) => {\n if (req.socket.localPort && req.socket.localPort !== port) {\n port = req.socket.localPort\n }\n next()\n })\n if (server.config.server.port) {\n port = server.config.server.port\n }\n\n server.httpServer?.on('listening', () => {\n port = server.config.server.port\n })\n\n const editor = args?.editor ?? DEFAULT_EDITOR_CONFIG\n const openInEditor: EditorConfig['open'] = async (\n path,\n lineNum,\n columnNum,\n ) => {\n if (!path) {\n return\n }\n await editor.open(path, lineNum, columnNum)\n }\n\n const originalConsole = Object.fromEntries(\n consolePipingLevels.map((l) => [l, console[l].bind(console)]),\n ) as Partial<Record<ConsoleLevel, typeof console.log>>\n\n // SSE clients for broadcasting server logs to browser\n const sseClients: Array<{\n res: ServerResponse\n id: number\n }> = []\n let sseClientId = 0\n const consolePipingEnabled = consolePipingConfig.enabled ?? true\n\n server.middlewares.use((req, res, next) =>\n handleDevToolsViteRequest(req, res, next, {\n onOpenSource: (parsedData) => {\n const { data, routine } = parsedData\n if (routine === 'open-source') {\n return handleOpenSource({\n data: { type: data.type, data },\n openInEditor,\n })\n }\n return\n },\n ...(consolePipingEnabled\n ? {\n onConsolePipe: (entries) => {\n for (const entry of entries) {\n const prefix = chalk.cyan('[Client]')\n const logMethod =\n originalConsole[entry.level as ConsoleLevel] ??\n // log exists in consolePipingLevels\n originalConsole.log!\n\n const cleanedArgs = stripEnhancedLogPrefix(\n entry.args,\n (loc) => chalk.gray(loc),\n )\n logMethod(prefix, ...cleanedArgs)\n }\n },\n onConsolePipeSSE: (res, req) => {\n res.setHeader('Content-Type', 'text/event-stream')\n res.setHeader('Cache-Control', 'no-cache')\n res.setHeader('Connection', 'keep-alive')\n res.setHeader('Access-Control-Allow-Origin', '*')\n res.flushHeaders()\n\n const clientId = ++sseClientId\n sseClients.push({ res, id: clientId })\n\n req.on('close', () => {\n const index = sseClients.findIndex(\n (c) => c.id === clientId,\n )\n if (index !== -1) {\n sseClients.splice(index, 1)\n }\n })\n },\n onServerConsolePipe: (entries) => {\n try {\n const data = JSON.stringify({\n entries: entries.map((e) => ({\n level: e.level,\n args: e.args,\n source: 'server',\n timestamp: e.timestamp || Date.now(),\n })),\n })\n\n for (const client of sseClients) {\n client.res.write(`data: ${data}\\n\\n`)\n }\n } catch {}\n },\n }\n : {}),\n }),\n )\n },\n },\n {\n name: '@tanstack/devtools:remove-devtools-on-build',\n apply(config, { command }) {\n // Check both command and mode to support various hosting providers\n // Some providers (Cloudflare, Netlify, Heroku) might not use 'build' command\n // but will always set mode to 'production' for production builds\n return (\n (command !== 'serve' || config.mode === 'production') &&\n removeDevtoolsOnBuild\n )\n },\n enforce: 'pre',\n transform(code, id) {\n if (\n id.includes('node_modules') ||\n id.includes('?raw') ||\n !TANSTACK_DEVTOOLS_PACKAGES.some((pkg) => code.includes(pkg))\n )\n return\n const transform = removeDevtools(code, id)\n if (!transform) return\n if (logging) {\n console.log(\n `\\n${chalk.greenBright(`[@tanstack/devtools-vite]`)} Removed devtools code from: ${id.replace(normalizePath(process.cwd()), '')}\\n`,\n )\n }\n return transform\n },\n },\n {\n name: '@tanstack/devtools:event-client-setup',\n apply(config, { command }) {\n if (\n process.env.CI ||\n process.env.NODE_ENV !== 'development' ||\n command !== 'serve'\n )\n return false\n return config.mode === 'development'\n },\n async configureServer() {\n const packageJson = await readPackageJson()\n const outdatedDeps = emitOutdatedDeps().then((deps) => deps)\n\n // Listen for package installation requests\n devtoolsEventClient.on('install-devtools', async (event) => {\n const result = await installPackage(event.payload.packageName)\n devtoolsEventClient.emit('devtools-installed', {\n packageName: event.payload.packageName,\n success: result.success,\n error: result.error,\n })\n\n // If installation was successful, automatically add the plugin to devtools\n if (result.success) {\n const { packageName, pluginName, pluginImport } = event.payload\n\n console.log(\n chalk.blueBright(\n `[@tanstack/devtools-vite] Auto-adding ${packageName} to devtools...`,\n ),\n )\n\n const injectResult = addPluginToDevtools(\n devtoolsFileId,\n packageName,\n pluginName,\n pluginImport,\n )\n\n if (injectResult.success) {\n // Emit plugin-added event so the UI updates\n devtoolsEventClient.emit('plugin-added', {\n packageName,\n success: true,\n })\n\n // Also re-read package.json to update the UI with the newly installed package\n const updatedPackageJson = await readPackageJson()\n devtoolsEventClient.emit('package-json-read', {\n packageJson: updatedPackageJson,\n })\n }\n }\n })\n\n // Listen for add plugin to devtools requests\n devtoolsEventClient.on('add-plugin-to-devtools', (event) => {\n const { packageName, pluginName, pluginImport } = event.payload\n\n console.log(\n chalk.blueBright(\n `[@tanstack/devtools-vite] Adding ${packageName} to devtools...`,\n ),\n )\n\n const result = addPluginToDevtools(\n devtoolsFileId,\n packageName,\n pluginName,\n pluginImport,\n )\n\n devtoolsEventClient.emit('plugin-added', {\n packageName,\n success: result.success,\n error: result.error,\n })\n })\n\n // Handle bump-package-version event\n devtoolsEventClient.on('bump-package-version', async (event) => {\n const {\n packageName,\n devtoolsPackage,\n pluginName,\n minVersion,\n pluginImport,\n } = event.payload\n\n console.log(\n chalk.blueBright(\n `[@tanstack/devtools-vite] Bumping ${packageName} to version ${minVersion}...`,\n ),\n )\n\n // Install the package with the minimum version\n const packageWithVersion = minVersion\n ? `${packageName}@^${minVersion}`\n : packageName\n\n const result = await installPackage(packageWithVersion)\n\n if (!result.success) {\n console.log(\n chalk.redBright(\n `[@tanstack/devtools-vite] Failed to bump ${packageName}: ${result.error}`,\n ),\n )\n devtoolsEventClient.emit('devtools-installed', {\n packageName: devtoolsPackage,\n success: false,\n error: result.error,\n })\n return\n }\n\n console.log(\n chalk.greenBright(\n `[@tanstack/devtools-vite] Successfully bumped ${packageName} to ${minVersion}!`,\n ),\n )\n\n // Check if we found the devtools file\n if (!devtoolsFileId) {\n console.log(\n chalk.yellowBright(\n `[@tanstack/devtools-vite] Devtools file not found. Skipping auto-injection.`,\n ),\n )\n devtoolsEventClient.emit('devtools-installed', {\n packageName: devtoolsPackage,\n success: true,\n })\n return\n }\n\n // Now inject the devtools plugin\n console.log(\n chalk.blueBright(\n `[@tanstack/devtools-vite] Adding ${devtoolsPackage} to devtools...`,\n ),\n )\n\n const injectResult = injectPluginIntoFile(devtoolsFileId, {\n packageName: devtoolsPackage,\n pluginName,\n pluginImport,\n })\n\n if (injectResult.success) {\n console.log(\n chalk.greenBright(\n `[@tanstack/devtools-vite] Successfully added ${devtoolsPackage} to devtools!`,\n ),\n )\n\n devtoolsEventClient.emit('plugin-added', {\n packageName: devtoolsPackage,\n success: true,\n })\n\n // Re-read package.json to update the UI\n const updatedPackageJson = await readPackageJson()\n devtoolsEventClient.emit('package-json-read', {\n packageJson: updatedPackageJson,\n })\n } else {\n console.log(\n chalk.redBright(\n `[@tanstack/devtools-vite] Failed to add ${devtoolsPackage} to devtools: ${injectResult.error}`,\n ),\n )\n\n devtoolsEventClient.emit('plugin-added', {\n packageName: devtoolsPackage,\n success: false,\n error: injectResult.error,\n })\n }\n })\n\n // whenever a client mounts we send all the current info to the subscribers\n devtoolsEventClient.on('mounted', async () => {\n devtoolsEventClient.emit('outdated-deps-read', {\n outdatedDeps: await outdatedDeps,\n })\n devtoolsEventClient.emit('package-json-read', {\n packageJson,\n })\n })\n\n // Console piping is now handled via HTTP endpoints in the custom-server plugin\n },\n async handleHotUpdate({ file }) {\n if (file.endsWith('package.json')) {\n const newPackageJson = await readPackageJson()\n devtoolsEventClient.emit('package-json-read', {\n packageJson: newPackageJson,\n })\n emitOutdatedDeps()\n }\n },\n },\n // Enhanced logs must run BEFORE console-pipe-transform: the latter\n // prepends a multi-line IIFE to root entry files, which would shift\n // every line number computed by the oxc-parser AST and produce\n // \"Go to Source\" links pointing past the end of the user's file.\n {\n name: '@tanstack/devtools:better-console-logs',\n enforce: 'pre',\n apply(config) {\n return config.mode === 'development' && enhancedLogsConfig.enabled\n },\n transform: {\n filter: {\n id: {\n exclude: [/node_modules/, /\\?raw/, /\\/dist\\//, /\\/build\\//],\n },\n code: {\n include: 'console.',\n },\n },\n handler(code, id) {\n return enhanceConsoleLog(code, id, port)\n },\n },\n },\n // Inject console piping code into entry files (both client and server)\n {\n name: '@tanstack/devtools:console-pipe-transform',\n enforce: 'pre',\n apply(config, { command }) {\n return (\n config.mode === 'development' &&\n command === 'serve' &&\n (consolePipingConfig.enabled ?? true)\n )\n },\n transform: {\n filter: {\n id: {\n include: /\\.(tsx?|jsx?)$/,\n exclude: [/node_modules/, /\\/dist\\//, /\\?/],\n },\n code: {\n exclude: /__tsdConsolePipe/, // avoid transforming files that already contain the console pipe code\n },\n },\n handler(code) {\n // Check if this is a root entry file (with <html> JSX or client entry points)\n // In SSR frameworks, this file runs on BOTH server (SSR) and client (hydration)\n // so our runtime check (typeof window === 'undefined') handles both environments\n const isRootEntry =\n /<html[\\s>]/i.test(code) ||\n code.includes('StartClient') ||\n code.includes('hydrateRoot') ||\n code.includes('createRoot') ||\n (code.includes('solid-js/web') && code.includes('render('))\n\n if (isRootEntry) {\n const viteServerUrl = `http://localhost:${port}`\n const inlineCode = generateConsolePipeCode(\n consolePipingLevels,\n viteServerUrl,\n )\n\n return `${inlineCode}\\n${code}`\n }\n\n return undefined\n },\n },\n },\n {\n name: '@tanstack/devtools:inject-plugin',\n apply(config, { command }) {\n return config.mode === 'development' && command === 'serve'\n },\n transform(code, id) {\n // First pass: find where TanStackDevtools is imported\n if (!devtoolsFileId && detectDevtoolsFile(code)) {\n // Extract actual file path (remove query params)\n const [filePath] = id.split('?')\n if (filePath) {\n devtoolsFileId = filePath\n }\n }\n\n return undefined\n },\n },\n {\n name: '@tanstack/devtools:connection-injection',\n apply(config, { command }) {\n return config.mode === 'development' && command === 'serve'\n },\n transform(code, id) {\n // Only transform @tanstack packages that contain the connection placeholders\n const hasPlaceholder =\n code.includes('__TANSTACK_DEVTOOLS_PORT__') ||\n code.includes('__TANSTACK_DEVTOOLS_HOST__') ||\n code.includes('__TANSTACK_DEVTOOLS_PROTOCOL__')\n if (!hasPlaceholder) return\n if (\n !id.includes('@tanstack/devtools') &&\n !id.includes('@tanstack/event-bus')\n )\n return\n\n // Replace placeholders with actual values (or fallback defaults)\n const portValue = devtoolsPort ?? 4206\n const hostValue = devtoolsHost ?? 'localhost'\n const protocolValue = devtoolsProtocol ?? 'http'\n\n let result = code\n result = result.replace(\n /__TANSTACK_DEVTOOLS_PORT__/g,\n String(portValue),\n )\n result = result.replace(\n /__TANSTACK_DEVTOOLS_HOST__/g,\n JSON.stringify(hostValue),\n )\n result = result.replace(\n /__TANSTACK_DEVTOOLS_PROTOCOL__/g,\n JSON.stringify(protocolValue),\n )\n return result\n },\n },\n {\n name: '@tanstack/devtools:runtime-bridge',\n apply(config, { command }) {\n return config.mode === 'development' && command === 'serve'\n },\n transform(code, id) {\n if (id.includes('?')) return\n return injectRuntimeBridge(\n code,\n id,\n (this as any).environment?.name as string | undefined,\n )\n },\n },\n ]\n}\n"],"mappings":";;;;;;;;;;;;;;;AA2GA,IAAa,wBAAwB,WACnC;AAEF,IAAa,YAAY,SAAqD;CAC5E,IAAI,OAAO;CACX,MAAM,UAAU,MAAM,WAAW;CACjC,MAAM,qBAAqB,MAAM,gBAAgB,EAAE,SAAS,MAAM;CAClE,MAAM,qBAAqB,MAAM,gBAAgB,EAAE,SAAS,MAAM;CAClE,MAAM,wBAAwB,MAAM,yBAAyB;CAC7D,MAAM,mBAAmB,M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AS,OAAO,QACd,mCACA,KAAK,UAAU,cAAc,CAC9B;IACD,OAAO;;GAEV;EACD;GACE,MAAM;GACN,MAAM,QAAQ,EAAE,WAAW;IACzB,OAAO,OAAO,SAAS,iBAAiB,YAAY;;GAEtD,UAAU,MAAM,IAAI;IAClB,IAAI,GAAG,SAAS,IAAI,EAAE;IACtB,OAAO,oBACL,MACA,IACC,KAAa,aAAa,KAC5B;;GAEJ;EACF"}
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Worker-side bridge for isolated server runtimes (Nitro v3 worker, Cloudflare workerd).
3
+ *
4
+ * Injected into the `@tanstack/devtools-event-client` module ONLY in non-client
5
+ * (server) environments during dev. At module-eval time it gives the isolated
6
+ * runtime a real `globalThis.__TANSTACK_EVENT_TARGET__` (so the unchanged
7
+ * `EventClient` uses it instead of a throwaway target) and bridges that target to
8
+ * the Vite dev process over the framework plugin's existing HMR HotChannel.
9
+ *
10
+ * Guards:
11
+ * - `import.meta.hot` falsy (production / no HMR) -> tree-shaken / no-op.
12
+ * - global target already set (in-process RunnableDevEnvironment, where
13
+ * ServerEventBus lives) -> no-op, so existing behavior is unchanged.
14
+ *
15
+ * The bridge replicates ServerEventBus's in-process responsibilities so the
16
+ * EventClient protocol is identical across the wire (see design doc).
17
+ */
18
+ export declare function generateRuntimeBridgeCode(): string;
19
+ export declare function injectRuntimeBridge(code: string, id: string, environmentName: string | undefined): string | undefined;
20
+ interface BridgeHotChannel {
21
+ on?: (event: string, cb: (data: any) => void) => void;
22
+ off?: (event: string, cb: (data: any) => void) => void;
23
+ send?: (event: string, data: any) => void;
24
+ }
25
+ interface BridgeServerLike {
26
+ environments: Record<string, {
27
+ hot?: BridgeHotChannel | null;
28
+ } | undefined>;
29
+ }
30
+ export declare function wireRuntimeBridgeChannels(server: BridgeServerLike, getTarget: () => EventTarget | null | undefined): () => void;
31
+ export {};
@@ -0,0 +1,75 @@
1
+ //#region src/runtime-bridge.ts
2
+ /**
3
+ * Worker-side bridge for isolated server runtimes (Nitro v3 worker, Cloudflare workerd).
4
+ *
5
+ * Injected into the `@tanstack/devtools-event-client` module ONLY in non-client
6
+ * (server) environments during dev. At module-eval time it gives the isolated
7
+ * runtime a real `globalThis.__TANSTACK_EVENT_TARGET__` (so the unchanged
8
+ * `EventClient` uses it instead of a throwaway target) and bridges that target to
9
+ * the Vite dev process over the framework plugin's existing HMR HotChannel.
10
+ *
11
+ * Guards:
12
+ * - `import.meta.hot` falsy (production / no HMR) -> tree-shaken / no-op.
13
+ * - global target already set (in-process RunnableDevEnvironment, where
14
+ * ServerEventBus lives) -> no-op, so existing behavior is unchanged.
15
+ *
16
+ * The bridge replicates ServerEventBus's in-process responsibilities so the
17
+ * EventClient protocol is identical across the wire (see design doc).
18
+ */
19
+ function generateRuntimeBridgeCode() {
20
+ return `
21
+ ;(function __tsdRuntimeBridge() {
22
+ if (typeof import.meta === 'undefined' || !import.meta.hot) return;
23
+ if (!globalThis.__TANSTACK_EVENT_TARGET__) {
24
+ var target = new EventTarget();
25
+ globalThis.__TANSTACK_EVENT_TARGET__ = target;
26
+
27
+ // Complete EventClient's connect handshake locally so queued events flush.
28
+ target.addEventListener('tanstack-connect', function () {
29
+ target.dispatchEvent(new CustomEvent('tanstack-connect-success'));
30
+ });
31
+
32
+ // Worker -> Vite dev server.
33
+ target.addEventListener('tanstack-dispatch-event', function (e) {
34
+ import.meta.hot.send('tsd:to-server', e.detail);
35
+ });
36
+
37
+ // Vite dev server -> worker listeners.
38
+ import.meta.hot.on('tsd:to-client', function (event) {
39
+ target.dispatchEvent(new CustomEvent(event.type, { detail: event }));
40
+ target.dispatchEvent(new CustomEvent('tanstack-devtools-global', { detail: event }));
41
+ });
42
+ }
43
+ })();
44
+ `;
45
+ }
46
+ function isEventClientModule(id, code) {
47
+ return (id.includes("devtools-event-client") || id.includes("event-bus-client")) && code.includes("EventClient");
48
+ }
49
+ function injectRuntimeBridge(code, id, environmentName) {
50
+ if (!environmentName || environmentName === "client") return void 0;
51
+ if (!isEventClientModule(id, code)) return void 0;
52
+ return `${code}\n${generateRuntimeBridgeCode()}`;
53
+ }
54
+ function wireRuntimeBridgeChannels(server, getTarget) {
55
+ const teardowns = [];
56
+ for (const [name, env] of Object.entries(server.environments)) {
57
+ if (name === "client") continue;
58
+ const hot = env?.hot;
59
+ if (!hot || typeof hot.on !== "function" || typeof hot.send !== "function") continue;
60
+ const onToServer = (event) => {
61
+ getTarget()?.dispatchEvent(new CustomEvent("tanstack-dispatch-event", { detail: event }));
62
+ };
63
+ hot.on("tsd:to-server", onToServer);
64
+ teardowns.push(() => hot.off?.("tsd:to-server", onToServer));
65
+ const target = getTarget();
66
+ const forward = (e) => hot.send("tsd:to-client", e.detail);
67
+ target?.addEventListener("tanstack-devtools-global", forward);
68
+ teardowns.push(() => target?.removeEventListener("tanstack-devtools-global", forward));
69
+ }
70
+ return () => teardowns.forEach((off) => off());
71
+ }
72
+ //#endregion
73
+ export { injectRuntimeBridge, wireRuntimeBridgeChannels };
74
+
75
+ //# sourceMappingURL=runtime-bridge.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime-bridge.js","names":[],"sources":["../../src/runtime-bridge.ts"],"sourcesContent":["/**\n * Worker-side bridge for isolated server runtimes (Nitro v3 worker, Cloudflare workerd).\n *\n * Injected into the `@tanstack/devtools-event-client` module ONLY in non-client\n * (server) environments during dev. At module-eval time it gives the isolated\n * runtime a real `globalThis.__TANSTACK_EVENT_TARGET__` (so the unchanged\n * `EventClient` uses it instead of a throwaway target) and bridges that target to\n * the Vite dev process over the framework plugin's existing HMR HotChannel.\n *\n * Guards:\n * - `import.meta.hot` falsy (production / no HMR) -> tree-shaken / no-op.\n * - global target already set (in-process RunnableDevEnvironment, where\n * ServerEventBus lives) -> no-op, so existing behavior is unchanged.\n *\n * The bridge replicates ServerEventBus's in-process responsibilities so the\n * EventClient protocol is identical across the wire (see design doc).\n */\nexport function generateRuntimeBridgeCode(): string {\n return `\n;(function __tsdRuntimeBridge() {\n if (typeof import.meta === 'undefined' || !import.meta.hot) return;\n if (!globalThis.__TANSTACK_EVENT_TARGET__) {\n var target = new EventTarget();\n globalThis.__TANSTACK_EVENT_TARGET__ = target;\n\n // Complete EventClient's connect handshake locally so queued events flush.\n target.addEventListener('tanstack-connect', function () {\n target.dispatchEvent(new CustomEvent('tanstack-connect-success'));\n });\n\n // Worker -> Vite dev server.\n target.addEventListener('tanstack-dispatch-event', function (e) {\n import.meta.hot.send('tsd:to-server', e.detail);\n });\n\n // Vite dev server -> worker listeners.\n import.meta.hot.on('tsd:to-client', function (event) {\n target.dispatchEvent(new CustomEvent(event.type, { detail: event }));\n target.dispatchEvent(new CustomEvent('tanstack-devtools-global', { detail: event }));\n });\n }\n})();\n`\n}\n\nfunction isEventClientModule(id: string, code: string): boolean {\n const isEventClientPath =\n id.includes('devtools-event-client') || id.includes('event-bus-client')\n // Only the module that actually defines the class — avoids re-export shims\n // and unrelated files inside the package.\n return isEventClientPath && code.includes('EventClient')\n}\n\nexport function injectRuntimeBridge(\n code: string,\n id: string,\n environmentName: string | undefined,\n): string | undefined {\n // Only isolated server environments need the bridge. The client environment\n // has `window`; the in-process RunnableDevEnvironment is handled by the\n // runtime global guard inside the injected code.\n if (!environmentName || environmentName === 'client') return undefined\n if (!isEventClientModule(id, code)) return undefined\n return `${code}\\n${generateRuntimeBridgeCode()}`\n}\n\ninterface BridgeHotChannel {\n on?: (event: string, cb: (data: any) => void) => void\n off?: (event: string, cb: (data: any) => void) => void\n send?: (event: string, data: any) => void\n}\ninterface BridgeServerLike {\n environments: Record<string, { hot?: BridgeHotChannel | null } | undefined>\n}\n\nexport function wireRuntimeBridgeChannels(\n server: BridgeServerLike,\n getTarget: () => EventTarget | null | undefined,\n): () => void {\n const teardowns: Array<() => void> = []\n\n for (const [name, env] of Object.entries(server.environments)) {\n if (name === 'client') continue\n const hot = env?.hot\n if (\n !hot ||\n typeof hot.on !== 'function' ||\n typeof hot.send !== 'function'\n ) {\n continue\n }\n\n // Worker -> ServerEventBus (broadcasts to browser + in-process listeners).\n const onToServer = (event: any) => {\n getTarget()?.dispatchEvent(\n new CustomEvent('tanstack-dispatch-event', { detail: event }),\n )\n }\n hot.on('tsd:to-server', onToServer)\n teardowns.push(() => hot.off?.('tsd:to-server', onToServer))\n\n // ServerEventBus output -> worker listeners.\n const target = getTarget()\n const forward = (e: Event) =>\n hot.send!('tsd:to-client', (e as CustomEvent).detail)\n target?.addEventListener('tanstack-devtools-global', forward)\n teardowns.push(() =>\n target?.removeEventListener('tanstack-devtools-global', forward),\n )\n }\n\n return () => teardowns.forEach((off) => off())\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiBA,SAAgB,4BAAoC;CAClD,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BT,SAAS,oBAAoB,IAAY,MAAuB;CAK9D,QAHE,GAAG,SAAS,wBAAwB,IAAI,GAAG,SAAS,mBAAmB,KAG7C,KAAK,SAAS,cAAc;;AAG1D,SAAgB,oBACd,MACA,IACA,iBACoB;CAIpB,IAAI,CAAC,mBAAmB,oBAAoB,UAAU,OAAO,KAAA;CAC7D,IAAI,CAAC,oBAAoB,IAAI,KAAK,EAAE,OAAO,KAAA;CAC3C,OAAO,GAAG,KAAK,IAAI,2BAA2B;;AAYhD,SAAgB,0BACd,QACA,WACY;CACZ,MAAM,YAA+B,EAAE;CAEvC,KAAK,MAAM,CAAC,MAAM,QAAQ,OAAO,QAAQ,OAAO,aAAa,EAAE;EAC7D,IAAI,SAAS,UAAU;EACvB,MAAM,MAAM,KAAK;EACjB,IACE,CAAC,OACD,OAAO,IAAI,OAAO,cAClB,OAAO,IAAI,SAAS,YAEpB;EAIF,MAAM,cAAc,UAAe;GACjC,WAAW,EAAE,cACX,IAAI,YAAY,2BAA2B,EAAE,QAAQ,OAAO,CAAC,CAC9D;;EAEH,IAAI,GAAG,iBAAiB,WAAW;EACnC,UAAU,WAAW,IAAI,MAAM,iBAAiB,WAAW,CAAC;EAG5D,MAAM,SAAS,WAAW;EAC1B,MAAM,WAAW,MACf,IAAI,KAAM,iBAAkB,EAAkB,OAAO;EACvD,QAAQ,iBAAiB,4BAA4B,QAAQ;EAC7D,UAAU,WACR,QAAQ,oBAAoB,4BAA4B,QAAQ,CACjE;;CAGH,aAAa,UAAU,SAAS,QAAQ,KAAK,CAAC"}
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/devtools-vite",
3
- "version": "0.7.2",
3
+ "version": "0.8.1",
4
4
  "description": "TanStack Vite plugin used to enhance the core devtools with additional functionalities",
5
5
  "author": "Tanner Linsley",
6
6
  "license": "MIT",
@@ -10,6 +10,9 @@
10
10
  "directory": "packages/devtools-vite"
11
11
  },
12
12
  "homepage": "https://tanstack.com/devtools",
13
+ "bugs": {
14
+ "url": "https://github.com/TanStack/devtools/issues"
15
+ },
13
16
  "funding": {
14
17
  "type": "github",
15
18
  "url": "https://github.com/sponsors/tannerlinsley"
@@ -51,7 +54,7 @@
51
54
  "magic-string": "^0.30.0",
52
55
  "oxc-parser": "^0.120.0",
53
56
  "picomatch": "^4.0.3",
54
- "@tanstack/devtools-client": "0.0.7",
57
+ "@tanstack/devtools-client": "0.0.8",
55
58
  "@tanstack/devtools-event-bus": "0.4.2"
56
59
  },
57
60
  "devDependencies": {
@@ -0,0 +1,109 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { forEachChild, walk } from './ast-utils'
3
+ import type { Node } from 'oxc-parser'
4
+
5
+ describe('forEachChild', () => {
6
+ it('visits only direct typed children, skipping null and non-type values', () => {
7
+ const childA = { type: 'ChildA', start: 0, end: 1 }
8
+ const childB = { type: 'ChildB', start: 1, end: 2 }
9
+ const nested = { type: 'Nested', start: 2, end: 3 }
10
+ const root = {
11
+ type: 'ForEachRoot',
12
+ start: 0,
13
+ end: 10,
14
+ // array-valued key holding two typed children
15
+ items: [childA, childB],
16
+ // object-valued typed child
17
+ body: nested,
18
+ // null field: skipped
19
+ optional: null,
20
+ // primitive string value: not a child (and excluded from child keys)
21
+ name: 'hello',
22
+ // primitive number value: not a child
23
+ count: 5,
24
+ } as unknown as Node
25
+
26
+ const visited: Array<Node> = []
27
+ forEachChild(root, (child) => visited.push(child))
28
+
29
+ expect(visited).toEqual([childA, childB, nested])
30
+ expect(visited).toHaveLength(3)
31
+ })
32
+
33
+ it('skips non-object array items and array items without a type', () => {
34
+ const real = { type: 'RealItem', start: 0, end: 1 }
35
+ const root = {
36
+ type: 'ForEachArrayRoot',
37
+ start: 0,
38
+ end: 10,
39
+ items: [real, null, 'string-item', 42, { noType: true }],
40
+ } as unknown as Node
41
+
42
+ const visited: Array<Node> = []
43
+ forEachChild(root, (child) => visited.push(child))
44
+
45
+ expect(visited).toEqual([real])
46
+ })
47
+ })
48
+
49
+ describe('walk', () => {
50
+ it('visits every node depth-first with the correct parentNode', () => {
51
+ const grandchild = { type: 'WalkGrandchild', start: 4, end: 5 }
52
+ const childA = {
53
+ type: 'WalkChildA',
54
+ start: 1,
55
+ end: 6,
56
+ inner: grandchild,
57
+ }
58
+ const childB = { type: 'WalkChildB', start: 6, end: 7 }
59
+ const root = {
60
+ type: 'WalkRoot',
61
+ start: 0,
62
+ end: 10,
63
+ children: [childA, childB],
64
+ } as unknown as Node
65
+
66
+ const visits: Array<{ node: Node; parent: Node | undefined }> = []
67
+ walk(root, (node, parentNode) => {
68
+ visits.push({ node, parent: parentNode })
69
+ })
70
+
71
+ // Depth-first order: root, childA, grandchild, childB
72
+ expect(visits.map((v) => v.node.type)).toEqual([
73
+ 'WalkRoot',
74
+ 'WalkChildA',
75
+ 'WalkGrandchild',
76
+ 'WalkChildB',
77
+ ])
78
+
79
+ // Correct parent for each node
80
+ expect(visits[0]!.parent).toBeUndefined()
81
+ expect(visits[1]!.parent).toBe(root)
82
+ expect(visits[2]!.parent).toBe(childA)
83
+ expect(visits[3]!.parent).toBe(root)
84
+ })
85
+
86
+ it('passes the provided parentNode through to the root visit', () => {
87
+ const fakeParent = {
88
+ type: 'WalkExternalParent',
89
+ start: 0,
90
+ end: 1,
91
+ } as unknown as Node
92
+ const root = {
93
+ type: 'WalkRootWithParent',
94
+ start: 1,
95
+ end: 2,
96
+ } as unknown as Node
97
+
98
+ const visits: Array<{ node: Node; parent: Node | undefined }> = []
99
+ walk(
100
+ root,
101
+ (node, parentNode) => visits.push({ node, parent: parentNode }),
102
+ fakeParent,
103
+ )
104
+
105
+ expect(visits).toHaveLength(1)
106
+ expect(visits[0]!.node).toBe(root)
107
+ expect(visits[0]!.parent).toBe(fakeParent)
108
+ })
109
+ })
@@ -0,0 +1,58 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import {
3
+ TANSTACK_DEVTOOLS_PACKAGES,
4
+ isTanStackDevtoolsImport,
5
+ } from './devtools-packages'
6
+
7
+ describe('TANSTACK_DEVTOOLS_PACKAGES', () => {
8
+ it('contains exactly 7 entries', () => {
9
+ expect(TANSTACK_DEVTOOLS_PACKAGES).toHaveLength(7)
10
+ })
11
+
12
+ it('includes the known framework-specific devtools packages', () => {
13
+ expect(TANSTACK_DEVTOOLS_PACKAGES).toContain('@tanstack/react-devtools')
14
+ expect(TANSTACK_DEVTOOLS_PACKAGES).toContain('@tanstack/preact-devtools')
15
+ expect(TANSTACK_DEVTOOLS_PACKAGES).toContain('@tanstack/solid-devtools')
16
+ expect(TANSTACK_DEVTOOLS_PACKAGES).toContain('@tanstack/vue-devtools')
17
+ expect(TANSTACK_DEVTOOLS_PACKAGES).toContain('@tanstack/svelte-devtools')
18
+ expect(TANSTACK_DEVTOOLS_PACKAGES).toContain('@tanstack/angular-devtools')
19
+ })
20
+
21
+ it('includes the framework-agnostic @tanstack/devtools entry', () => {
22
+ expect(TANSTACK_DEVTOOLS_PACKAGES).toContain('@tanstack/devtools')
23
+ })
24
+ })
25
+
26
+ describe('isTanStackDevtoolsImport', () => {
27
+ it('returns true for @tanstack/react-devtools', () => {
28
+ expect(isTanStackDevtoolsImport('@tanstack/react-devtools')).toBe(true)
29
+ })
30
+
31
+ it('returns true for @tanstack/devtools', () => {
32
+ expect(isTanStackDevtoolsImport('@tanstack/devtools')).toBe(true)
33
+ })
34
+
35
+ it('returns true for every entry in TANSTACK_DEVTOOLS_PACKAGES', () => {
36
+ for (const pkg of TANSTACK_DEVTOOLS_PACKAGES) {
37
+ expect(isTanStackDevtoolsImport(pkg)).toBe(true)
38
+ }
39
+ })
40
+
41
+ it('returns false for an unrelated package', () => {
42
+ expect(isTanStackDevtoolsImport('react')).toBe(false)
43
+ })
44
+
45
+ it('returns false for an empty string', () => {
46
+ expect(isTanStackDevtoolsImport('')).toBe(false)
47
+ })
48
+
49
+ it('returns false for a @tanstack package that is not in the devtools list', () => {
50
+ expect(isTanStackDevtoolsImport('@tanstack/other-thing')).toBe(false)
51
+ })
52
+
53
+ it('returns false for a prefix-only match (no partial matching)', () => {
54
+ expect(isTanStackDevtoolsImport('@tanstack/react-devtools/extra')).toBe(
55
+ false,
56
+ )
57
+ })
58
+ })
@@ -0,0 +1,75 @@
1
+ import { describe, expect, it, vi } from 'vitest'
2
+ import { handleOpenSource } from './editor'
3
+
4
+ describe('handleOpenSource', () => {
5
+ it('calls openInEditor with source, stringified line and column when all provided', async () => {
6
+ const openInEditor = vi.fn().mockResolvedValue(undefined)
7
+ await handleOpenSource({
8
+ data: {
9
+ type: 'open-source',
10
+ data: { source: '/app/routes/foo.tsx', line: 10, column: 5 },
11
+ },
12
+ openInEditor,
13
+ })
14
+ expect(openInEditor).toHaveBeenCalledOnce()
15
+ expect(openInEditor).toHaveBeenCalledWith('/app/routes/foo.tsx', '10', '5')
16
+ })
17
+
18
+ it('calls openInEditor with source only when line and column are undefined', async () => {
19
+ const openInEditor = vi.fn().mockResolvedValue(undefined)
20
+ await handleOpenSource({
21
+ data: { type: 'open-source', data: { source: '/app/routes/bar.tsx' } },
22
+ openInEditor,
23
+ })
24
+ expect(openInEditor).toHaveBeenCalledOnce()
25
+ expect(openInEditor).toHaveBeenCalledWith(
26
+ '/app/routes/bar.tsx',
27
+ undefined,
28
+ undefined,
29
+ )
30
+ })
31
+
32
+ it('does NOT call openInEditor and returns undefined when source is absent', async () => {
33
+ const openInEditor = vi.fn()
34
+ const result = await handleOpenSource({
35
+ data: { type: 'open-source', data: { line: 1, column: 2 } },
36
+ openInEditor,
37
+ })
38
+ expect(openInEditor).not.toHaveBeenCalled()
39
+ expect(result).toBeUndefined()
40
+ })
41
+
42
+ it('treats falsy line: 0 and column: 0 as undefined (truthy check in impl)', async () => {
43
+ const openInEditor = vi.fn().mockResolvedValue(undefined)
44
+ await handleOpenSource({
45
+ data: {
46
+ type: 'open-source',
47
+ data: { source: '/app/routes/baz.tsx', line: 0, column: 0 },
48
+ },
49
+ openInEditor,
50
+ })
51
+ expect(openInEditor).toHaveBeenCalledOnce()
52
+ expect(openInEditor).toHaveBeenCalledWith(
53
+ '/app/routes/baz.tsx',
54
+ undefined,
55
+ undefined,
56
+ )
57
+ })
58
+
59
+ it('calls openInEditor with stringified line and undefined column when only line is provided', async () => {
60
+ const openInEditor = vi.fn().mockResolvedValue(undefined)
61
+ await handleOpenSource({
62
+ data: {
63
+ type: 'open-source',
64
+ data: { source: '/app/routes/qux.tsx', line: 42 },
65
+ },
66
+ openInEditor,
67
+ })
68
+ expect(openInEditor).toHaveBeenCalledOnce()
69
+ expect(openInEditor).toHaveBeenCalledWith(
70
+ '/app/routes/qux.tsx',
71
+ '42',
72
+ undefined,
73
+ )
74
+ })
75
+ })
@@ -0,0 +1,34 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { createLocMapper } from './offset-to-loc'
3
+
4
+ describe('createLocMapper', () => {
5
+ // Source: "ab\ncde\nf"
6
+ // Indices: 0 1 2 3 4 5 6 7
7
+ // lineStarts: [0, 3, 7]
8
+ const source = 'ab\ncde\nf'
9
+ const toLoc = createLocMapper(source)
10
+
11
+ it('maps offset 0 to line 1, column 0', () => {
12
+ expect(toLoc(0)).toEqual({ line: 1, column: 0 })
13
+ })
14
+
15
+ it('maps the start of line 2 (offset 3, just after first \\n) to line 2, column 0', () => {
16
+ expect(toLoc(3)).toEqual({ line: 2, column: 0 })
17
+ })
18
+
19
+ it('maps a mid-line-2 offset (offset 5, "e") to line 2, column 2', () => {
20
+ expect(toLoc(5)).toEqual({ line: 2, column: 2 })
21
+ })
22
+
23
+ it('maps the final offset (offset 7, "f") to line 3, column 0', () => {
24
+ expect(toLoc(7)).toEqual({ line: 3, column: 0 })
25
+ })
26
+
27
+ it('maps an offset on a \\n boundary char (offset 2) to line 1, column 2', () => {
28
+ expect(toLoc(2)).toEqual({ line: 1, column: 2 })
29
+ })
30
+
31
+ it('maps the second \\n boundary (offset 6) to line 2, column 3', () => {
32
+ expect(toLoc(6)).toEqual({ line: 2, column: 3 })
33
+ })
34
+ })
package/src/plugin.ts CHANGED
@@ -19,6 +19,10 @@ import {
19
19
  installPackage,
20
20
  } from './package-manager'
21
21
  import { generateConsolePipeCode } from './virtual-console'
22
+ import {
23
+ injectRuntimeBridge,
24
+ wireRuntimeBridgeChannels,
25
+ } from './runtime-bridge'
22
26
  import type { ServerResponse } from 'node:http'
23
27
  import type { Plugin } from 'vite'
24
28
  import type { EditorConfig } from './editor'
@@ -196,6 +200,15 @@ export const devtools = (args?: TanStackDevtoolsViteConfig): Array<Plugin> => {
196
200
  })
197
201
  // start() now handles EADDRINUSE and returns the actual port
198
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
+ }
199
212
  }
200
213
 
201
214
  server.middlewares.use((req, _res, next) => {
@@ -667,5 +680,19 @@ export const devtools = (args?: TanStackDevtoolsViteConfig): Array<Plugin> => {
667
680
  return result
668
681
  },
669
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
+ },
670
697
  ]
671
698
  }
@@ -0,0 +1,179 @@
1
+ import { describe, expect, test } from 'vitest'
2
+ import {
3
+ generateRuntimeBridgeCode,
4
+ injectRuntimeBridge,
5
+ wireRuntimeBridgeChannels,
6
+ } from './runtime-bridge'
7
+
8
+ describe('generateRuntimeBridgeCode', () => {
9
+ test('guards on import.meta.hot and an unset global target', () => {
10
+ const code = generateRuntimeBridgeCode()
11
+ expect(code).toContain('import.meta.hot')
12
+ expect(code).toContain('globalThis.__TANSTACK_EVENT_TARGET__')
13
+ expect(code).toContain('!globalThis.__TANSTACK_EVENT_TARGET__')
14
+ })
15
+
16
+ test('completes the connect handshake locally', () => {
17
+ const code = generateRuntimeBridgeCode()
18
+ expect(code).toContain("'tanstack-connect'")
19
+ expect(code).toContain("'tanstack-connect-success'")
20
+ })
21
+
22
+ test('forwards dispatched events to the dev server', () => {
23
+ const code = generateRuntimeBridgeCode()
24
+ expect(code).toContain("'tanstack-dispatch-event'")
25
+ expect(code).toContain("import.meta.hot.send('tsd:to-server'")
26
+ })
27
+
28
+ test('receives dev-server events and redispatches them locally', () => {
29
+ const code = generateRuntimeBridgeCode()
30
+ expect(code).toContain("import.meta.hot.on('tsd:to-client'")
31
+ expect(code).toContain("'tanstack-devtools-global'")
32
+ })
33
+
34
+ test('has no external imports', () => {
35
+ expect(generateRuntimeBridgeCode()).not.toContain('import ')
36
+ })
37
+ })
38
+
39
+ describe('injectRuntimeBridge', () => {
40
+ const EVENT_CLIENT_ID =
41
+ '/repo/node_modules/@tanstack/devtools-event-client/dist/esm/index.js'
42
+ const EVENT_CLIENT_CODE = 'class EventClient { emit() {} }'
43
+
44
+ test('injects into the event-client module in a server environment', () => {
45
+ const out = injectRuntimeBridge(EVENT_CLIENT_CODE, EVENT_CLIENT_ID, 'ssr')
46
+ expect(out).toBeDefined()
47
+ expect(out).toContain(EVENT_CLIENT_CODE)
48
+ expect(out).toContain('__tsdRuntimeBridge')
49
+ })
50
+
51
+ test('matches the workspace source path too', () => {
52
+ const id = '/repo/packages/event-bus-client/src/plugin.ts'
53
+ expect(injectRuntimeBridge(EVENT_CLIENT_CODE, id, 'ssr')).toBeDefined()
54
+ })
55
+
56
+ test('skips the client environment', () => {
57
+ expect(
58
+ injectRuntimeBridge(EVENT_CLIENT_CODE, EVENT_CLIENT_ID, 'client'),
59
+ ).toBeUndefined()
60
+ })
61
+
62
+ test('skips when environment name is unknown (pre-Environment-API)', () => {
63
+ expect(
64
+ injectRuntimeBridge(EVENT_CLIENT_CODE, EVENT_CLIENT_ID, undefined),
65
+ ).toBeUndefined()
66
+ })
67
+
68
+ test('skips modules that are not the event-client', () => {
69
+ expect(
70
+ injectRuntimeBridge('export const x = 1', '/repo/src/app.ts', 'ssr'),
71
+ ).toBeUndefined()
72
+ })
73
+
74
+ test('skips event-client-pathed modules that lack the EventClient class', () => {
75
+ const id =
76
+ '/repo/node_modules/@tanstack/devtools-event-client/dist/esm/foo.js'
77
+ expect(injectRuntimeBridge('export const y = 2', id, 'ssr')).toBeUndefined()
78
+ })
79
+ })
80
+
81
+ describe('wireRuntimeBridgeChannels', () => {
82
+ function makeEnv() {
83
+ type Handler = (data: any) => void
84
+ const handlers: Record<string, Handler> = {}
85
+ const removed: Array<{ event: string; cb: Handler }> = []
86
+ const sent: Array<{ event: string; data: any }> = []
87
+ return {
88
+ hot: {
89
+ on: (event: string, cb: Handler) => (handlers[event] = cb),
90
+ off: (event: string, cb: Handler) => removed.push({ event, cb }),
91
+ send: (event: string, data: any) => sent.push({ event, data }),
92
+ },
93
+ __handlers: handlers,
94
+ __removed: removed,
95
+ __sent: sent,
96
+ }
97
+ }
98
+
99
+ test('worker event -> dispatches tanstack-dispatch-event on the target', () => {
100
+ const target = new EventTarget()
101
+ const ssr = makeEnv()
102
+ const server = { environments: { client: { hot: null }, ssr } }
103
+ const received: Array<any> = []
104
+ target.addEventListener('tanstack-dispatch-event', (e) =>
105
+ received.push((e as CustomEvent).detail),
106
+ )
107
+
108
+ wireRuntimeBridgeChannels(server as any, () => target)
109
+ const evt = { type: 'q:foo', payload: 1 }
110
+ ssr.__handlers['tsd:to-server']!(evt)
111
+
112
+ expect(received).toEqual([evt])
113
+ })
114
+
115
+ test('target global event -> forwarded to the env via tsd:to-client', () => {
116
+ const target = new EventTarget()
117
+ const ssr = makeEnv()
118
+ const server = { environments: { ssr } }
119
+
120
+ wireRuntimeBridgeChannels(server as any, () => target)
121
+ const evt = { type: 'q:bar', payload: 2 }
122
+ target.dispatchEvent(
123
+ new CustomEvent('tanstack-devtools-global', { detail: evt }),
124
+ )
125
+
126
+ expect(ssr.__sent).toEqual([{ event: 'tsd:to-client', data: evt }])
127
+ })
128
+
129
+ test('skips the client environment', () => {
130
+ const client = makeEnv()
131
+ const server = { environments: { client } }
132
+ wireRuntimeBridgeChannels(server as any, () => new EventTarget())
133
+ expect(client.__handlers['tsd:to-server']).toBeUndefined()
134
+ })
135
+
136
+ test('teardown stops forwarding', () => {
137
+ const target = new EventTarget()
138
+ const ssr = makeEnv()
139
+ const server = { environments: { ssr } }
140
+ const teardown = wireRuntimeBridgeChannels(server as any, () => target)
141
+ teardown()
142
+ target.dispatchEvent(
143
+ new CustomEvent('tanstack-devtools-global', { detail: { type: 'x' } }),
144
+ )
145
+ expect(ssr.__sent).toEqual([])
146
+ })
147
+
148
+ test('teardown removes the tsd:to-server handler via hot.off (I1)', () => {
149
+ const target = new EventTarget()
150
+ const ssr = makeEnv()
151
+ const server = { environments: { ssr } }
152
+ const teardown = wireRuntimeBridgeChannels(server as any, () => target)
153
+
154
+ // Capture the registered handler reference before teardown.
155
+ const registeredHandler = ssr.__handlers['tsd:to-server']
156
+ expect(registeredHandler).toBeDefined()
157
+
158
+ teardown()
159
+
160
+ // hot.off must have been called with the exact same handler reference.
161
+ expect(ssr.__removed).toContainEqual({
162
+ event: 'tsd:to-server',
163
+ cb: registeredHandler,
164
+ })
165
+
166
+ // Dispatching a worker event after teardown must not reach the target.
167
+ const received: Array<any> = []
168
+ target.addEventListener('tanstack-dispatch-event', (e) =>
169
+ received.push((e as CustomEvent).detail),
170
+ )
171
+ registeredHandler!({ type: 'post-teardown' })
172
+ // The handler still dispatches (it holds a closure over getTarget) but the
173
+ // important invariant is that hot.off was called so the real HMR channel
174
+ // will no longer invoke it on subsequent dev-server restarts.
175
+ expect(
176
+ ssr.__removed.filter((r) => r.event === 'tsd:to-server'),
177
+ ).toHaveLength(1)
178
+ })
179
+ })
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Worker-side bridge for isolated server runtimes (Nitro v3 worker, Cloudflare workerd).
3
+ *
4
+ * Injected into the `@tanstack/devtools-event-client` module ONLY in non-client
5
+ * (server) environments during dev. At module-eval time it gives the isolated
6
+ * runtime a real `globalThis.__TANSTACK_EVENT_TARGET__` (so the unchanged
7
+ * `EventClient` uses it instead of a throwaway target) and bridges that target to
8
+ * the Vite dev process over the framework plugin's existing HMR HotChannel.
9
+ *
10
+ * Guards:
11
+ * - `import.meta.hot` falsy (production / no HMR) -> tree-shaken / no-op.
12
+ * - global target already set (in-process RunnableDevEnvironment, where
13
+ * ServerEventBus lives) -> no-op, so existing behavior is unchanged.
14
+ *
15
+ * The bridge replicates ServerEventBus's in-process responsibilities so the
16
+ * EventClient protocol is identical across the wire (see design doc).
17
+ */
18
+ export function generateRuntimeBridgeCode(): string {
19
+ return `
20
+ ;(function __tsdRuntimeBridge() {
21
+ if (typeof import.meta === 'undefined' || !import.meta.hot) return;
22
+ if (!globalThis.__TANSTACK_EVENT_TARGET__) {
23
+ var target = new EventTarget();
24
+ globalThis.__TANSTACK_EVENT_TARGET__ = target;
25
+
26
+ // Complete EventClient's connect handshake locally so queued events flush.
27
+ target.addEventListener('tanstack-connect', function () {
28
+ target.dispatchEvent(new CustomEvent('tanstack-connect-success'));
29
+ });
30
+
31
+ // Worker -> Vite dev server.
32
+ target.addEventListener('tanstack-dispatch-event', function (e) {
33
+ import.meta.hot.send('tsd:to-server', e.detail);
34
+ });
35
+
36
+ // Vite dev server -> worker listeners.
37
+ import.meta.hot.on('tsd:to-client', function (event) {
38
+ target.dispatchEvent(new CustomEvent(event.type, { detail: event }));
39
+ target.dispatchEvent(new CustomEvent('tanstack-devtools-global', { detail: event }));
40
+ });
41
+ }
42
+ })();
43
+ `
44
+ }
45
+
46
+ function isEventClientModule(id: string, code: string): boolean {
47
+ const isEventClientPath =
48
+ id.includes('devtools-event-client') || id.includes('event-bus-client')
49
+ // Only the module that actually defines the class — avoids re-export shims
50
+ // and unrelated files inside the package.
51
+ return isEventClientPath && code.includes('EventClient')
52
+ }
53
+
54
+ export function injectRuntimeBridge(
55
+ code: string,
56
+ id: string,
57
+ environmentName: string | undefined,
58
+ ): string | undefined {
59
+ // Only isolated server environments need the bridge. The client environment
60
+ // has `window`; the in-process RunnableDevEnvironment is handled by the
61
+ // runtime global guard inside the injected code.
62
+ if (!environmentName || environmentName === 'client') return undefined
63
+ if (!isEventClientModule(id, code)) return undefined
64
+ return `${code}\n${generateRuntimeBridgeCode()}`
65
+ }
66
+
67
+ interface BridgeHotChannel {
68
+ on?: (event: string, cb: (data: any) => void) => void
69
+ off?: (event: string, cb: (data: any) => void) => void
70
+ send?: (event: string, data: any) => void
71
+ }
72
+ interface BridgeServerLike {
73
+ environments: Record<string, { hot?: BridgeHotChannel | null } | undefined>
74
+ }
75
+
76
+ export function wireRuntimeBridgeChannels(
77
+ server: BridgeServerLike,
78
+ getTarget: () => EventTarget | null | undefined,
79
+ ): () => void {
80
+ const teardowns: Array<() => void> = []
81
+
82
+ for (const [name, env] of Object.entries(server.environments)) {
83
+ if (name === 'client') continue
84
+ const hot = env?.hot
85
+ if (
86
+ !hot ||
87
+ typeof hot.on !== 'function' ||
88
+ typeof hot.send !== 'function'
89
+ ) {
90
+ continue
91
+ }
92
+
93
+ // Worker -> ServerEventBus (broadcasts to browser + in-process listeners).
94
+ const onToServer = (event: any) => {
95
+ getTarget()?.dispatchEvent(
96
+ new CustomEvent('tanstack-dispatch-event', { detail: event }),
97
+ )
98
+ }
99
+ hot.on('tsd:to-server', onToServer)
100
+ teardowns.push(() => hot.off?.('tsd:to-server', onToServer))
101
+
102
+ // ServerEventBus output -> worker listeners.
103
+ const target = getTarget()
104
+ const forward = (e: Event) =>
105
+ hot.send!('tsd:to-client', (e as CustomEvent).detail)
106
+ target?.addEventListener('tanstack-devtools-global', forward)
107
+ teardowns.push(() =>
108
+ target?.removeEventListener('tanstack-devtools-global', forward),
109
+ )
110
+ }
111
+
112
+ return () => teardowns.forEach((off) => off())
113
+ }