@tanstack/devtools-vite 0.8.1 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/dist/esm/plugin.d.ts +4 -74
  2. package/dist/esm/plugin.js +2 -12
  3. package/dist/esm/plugin.js.map +1 -1
  4. package/package.json +2 -6
  5. package/src/plugin.ts +25 -97
  6. package/dist/esm/ast-utils.d.ts +0 -11
  7. package/dist/esm/ast-utils.js +0 -44
  8. package/dist/esm/ast-utils.js.map +0 -1
  9. package/dist/esm/ast-utils.test.d.ts +0 -1
  10. package/dist/esm/devtools-packages.d.ts +0 -2
  11. package/dist/esm/devtools-packages.js +0 -15
  12. package/dist/esm/devtools-packages.js.map +0 -1
  13. package/dist/esm/devtools-packages.test.d.ts +0 -1
  14. package/dist/esm/editor.d.ts +0 -25
  15. package/dist/esm/editor.js +0 -20
  16. package/dist/esm/editor.js.map +0 -1
  17. package/dist/esm/editor.test.d.ts +0 -1
  18. package/dist/esm/enhance-logs.d.ts +0 -4
  19. package/dist/esm/enhance-logs.js +0 -51
  20. package/dist/esm/enhance-logs.js.map +0 -1
  21. package/dist/esm/enhance-logs.test.d.ts +0 -1
  22. package/dist/esm/inject-plugin.d.ts +0 -22
  23. package/dist/esm/inject-plugin.js +0 -179
  24. package/dist/esm/inject-plugin.js.map +0 -1
  25. package/dist/esm/inject-plugin.test.d.ts +0 -1
  26. package/dist/esm/inject-source.d.ts +0 -7
  27. package/dist/esm/inject-source.js +0 -114
  28. package/dist/esm/inject-source.js.map +0 -1
  29. package/dist/esm/inject-source.test.d.ts +0 -1
  30. package/dist/esm/matcher.d.ts +0 -1
  31. package/dist/esm/matcher.js +0 -13
  32. package/dist/esm/matcher.js.map +0 -1
  33. package/dist/esm/matcher.test.d.ts +0 -1
  34. package/dist/esm/offset-to-loc.d.ts +0 -14
  35. package/dist/esm/offset-to-loc.js +0 -29
  36. package/dist/esm/offset-to-loc.js.map +0 -1
  37. package/dist/esm/offset-to-loc.test.d.ts +0 -1
  38. package/dist/esm/package-manager.d.ts +0 -16
  39. package/dist/esm/package-manager.js +0 -98
  40. package/dist/esm/package-manager.js.map +0 -1
  41. package/dist/esm/remove-devtools.d.ts +0 -4
  42. package/dist/esm/remove-devtools.js +0 -96
  43. package/dist/esm/remove-devtools.js.map +0 -1
  44. package/dist/esm/remove-devtools.test.d.ts +0 -1
  45. package/dist/esm/runtime-bridge.d.ts +0 -31
  46. package/dist/esm/runtime-bridge.js +0 -75
  47. package/dist/esm/runtime-bridge.js.map +0 -1
  48. package/dist/esm/runtime-bridge.test.d.ts +0 -1
  49. package/dist/esm/utils.d.ts +0 -31
  50. package/dist/esm/utils.js +0 -155
  51. package/dist/esm/utils.js.map +0 -1
  52. package/dist/esm/utils.test.d.ts +0 -1
  53. package/dist/esm/virtual-console.d.ts +0 -19
  54. package/dist/esm/virtual-console.js +0 -336
  55. package/dist/esm/virtual-console.js.map +0 -1
  56. package/dist/esm/virtual-console.test.d.ts +0 -1
  57. package/src/ast-utils.test.ts +0 -109
  58. package/src/ast-utils.ts +0 -58
  59. package/src/devtools-packages.test.ts +0 -58
  60. package/src/devtools-packages.ts +0 -12
  61. package/src/editor.test.ts +0 -75
  62. package/src/editor.ts +0 -53
  63. package/src/enhance-logs.test.ts +0 -132
  64. package/src/enhance-logs.ts +0 -71
  65. package/src/inject-plugin.test.ts +0 -1139
  66. package/src/inject-plugin.ts +0 -300
  67. package/src/inject-source.test.ts +0 -939
  68. package/src/inject-source.ts +0 -235
  69. package/src/matcher.test.ts +0 -33
  70. package/src/matcher.ts +0 -19
  71. package/src/offset-to-loc.test.ts +0 -34
  72. package/src/offset-to-loc.ts +0 -39
  73. package/src/package-manager.ts +0 -181
  74. package/src/remove-devtools.test.ts +0 -607
  75. package/src/remove-devtools.ts +0 -190
  76. package/src/runtime-bridge.test.ts +0 -179
  77. package/src/runtime-bridge.ts +0 -113
  78. package/src/utils.test.ts +0 -184
  79. package/src/utils.ts +0 -247
  80. package/src/virtual-console.test.ts +0 -244
  81. package/src/virtual-console.ts +0 -341
@@ -1,76 +1,6 @@
1
+ import { TanStackDevtoolsConfig } from '@tanstack/devtools-bundler-core';
1
2
  import { Plugin } from 'vite';
2
- import { EditorConfig } from './editor.js';
3
- import { ServerEventBusConfig } from '@tanstack/devtools-event-bus/server';
4
- export type ConsoleLevel = 'log' | 'warn' | 'error' | 'info' | 'debug';
5
- export type TanStackDevtoolsViteConfig = {
6
- /**
7
- * Configuration for the editor integration. Defaults to opening in VS code
8
- */
9
- editor?: EditorConfig;
10
- /**
11
- * The configuration options for the server event bus
12
- */
13
- eventBusConfig?: ServerEventBusConfig & {
14
- /**
15
- * Should the server event bus be enabled or not
16
- * @default true
17
- */
18
- enabled?: boolean;
19
- };
20
- /**
21
- * Configuration for enhanced logging.
22
- */
23
- enhancedLogs?: {
24
- /**
25
- * Whether to enable enhanced logging.
26
- * @default true
27
- */
28
- enabled: boolean;
29
- };
30
- /**
31
- * Whether to remove devtools from the production build.
32
- * @default true
33
- */
34
- removeDevtoolsOnBuild?: boolean;
35
- /**
36
- * Whether to log information to the console.
37
- * @default true
38
- */
39
- logging?: boolean;
40
- /**
41
- * Configuration for source injection.
42
- */
43
- injectSource?: {
44
- /**
45
- * Whether to enable source injection via data-tsd-source.
46
- * @default true
47
- */
48
- enabled: boolean;
49
- /**
50
- * List of files or patterns to ignore for source injection.
51
- */
52
- ignore?: {
53
- files?: Array<string | RegExp>;
54
- components?: Array<string | RegExp>;
55
- };
56
- };
57
- /**
58
- * Configuration for console piping between client and server.
59
- * When enabled, console logs from the client will appear in the terminal,
60
- * and server logs will appear in the browser console.
61
- */
62
- consolePiping?: {
63
- /**
64
- * Whether to enable console piping.
65
- * @default true
66
- */
67
- enabled?: boolean;
68
- /**
69
- * Which console methods to pipe.
70
- * @default ['log', 'warn', 'error', 'info', 'debug']
71
- */
72
- levels?: Array<ConsoleLevel>;
73
- };
74
- };
75
- export declare const defineDevtoolsConfig: (config: TanStackDevtoolsViteConfig) => TanStackDevtoolsViteConfig;
3
+ export type { ConsoleLevel } from '@tanstack/devtools-bundler-core';
4
+ export type TanStackDevtoolsViteConfig = TanStackDevtoolsConfig;
5
+ export declare const defineDevtoolsConfig: (config: TanStackDevtoolsViteConfig) => TanStackDevtoolsConfig;
76
6
  export declare const devtools: (args?: TanStackDevtoolsViteConfig) => Array<Plugin>;
@@ -1,17 +1,7 @@
1
- import { handleDevToolsViteRequest, readPackageJson, stripEnhancedLogPrefix } from "./utils.js";
2
- import { DEFAULT_EDITOR_CONFIG, handleOpenSource } from "./editor.js";
3
- import { TANSTACK_DEVTOOLS_PACKAGES } from "./devtools-packages.js";
4
- import { removeDevtools } from "./remove-devtools.js";
5
- import { addSourceToJsx } from "./inject-source.js";
6
- import { enhanceConsoleLog } from "./enhance-logs.js";
7
- import { detectDevtoolsFile, injectPluginIntoFile } from "./inject-plugin.js";
8
- import { addPluginToDevtools, emitOutdatedDeps, installPackage } from "./package-manager.js";
9
- import { generateConsolePipeCode } from "./virtual-console.js";
10
- import { injectRuntimeBridge, wireRuntimeBridgeChannels } from "./runtime-bridge.js";
11
1
  import { devtoolsEventClient } from "@tanstack/devtools-client";
12
2
  import { ServerEventBus } from "@tanstack/devtools-event-bus/server";
13
- import { normalizePath } from "vite";
14
3
  import chalk from "chalk";
4
+ import { DEFAULT_EDITOR_CONFIG, TANSTACK_DEVTOOLS_PACKAGES, addPluginToDevtools, addSourceToJsx, detectDevtoolsFile, emitOutdatedDeps, enhanceConsoleLog, generateConsolePipeCode, handleDevToolsRequest, handleOpenSource, injectPluginIntoFile, injectRuntimeBridge, installPackage, normalizePath, readPackageJson, removeDevtools, stripEnhancedLogPrefix, wireRuntimeBridgeChannels } from "@tanstack/devtools-bundler-core";
15
5
  //#region src/plugin.ts
16
6
  var defineDevtoolsConfig = (config) => config;
17
7
  var devtools = (args) => {
@@ -100,7 +90,7 @@ var devtools = (args) => {
100
90
  const sseClients = [];
101
91
  let sseClientId = 0;
102
92
  const consolePipingEnabled = consolePipingConfig.enabled ?? true;
103
- server.middlewares.use((req, res, next) => handleDevToolsViteRequest(req, res, next, {
93
+ server.middlewares.use((req, res, next) => handleDevToolsRequest(req, res, next, {
104
94
  onOpenSource: (parsedData) => {
105
95
  const { data, routine } = parsedData;
106
96
  if (routine === "open-source") return handleOpenSource({
@@ -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 {\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,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,eAA8B;CAClC,IAAI,eAA8B;CAClC,IAAI,mBAA4C;CAEhD,OAAO;EACL;GACE,SAAS;GACT,MAAM;GACN,MAAM,QAAQ;IACZ,OAAO,OAAO,SAAS,iBAAiB,mBAAmB;;GAE7D,WAAW;IACT,QAAQ,EACN,IAAI,EACF,SAAS;KAAC;KAAgB;KAAS;KAAY;KAAY,EAC5D,EACF;IACD,QAAQ,MAAM,IAAI;KAChB,OAAO,eAAe,MAAM,IAAI,MAAM,cAAc,OAAO;;IAE9D;GACF;EACD;GACE,MAAM;GACN,SAAS;GACT,OAAO,GAAG,EAAE,WAAW;IAErB,IAAI,YAAY,SACd;;GAoBL;EACD;GACE,SAAS;GACT,MAAM;GACN,MAAM,QAAQ;IAEZ,OAAO,OAAO,SAAS;;GAEzB,MAAM,gBAAgB,QAAQ;IAC5B,IAAI,kBAAkB;KACpB,MAAM,gBAAgB,MAAM,gBAAgB,QAAQ;KACpD,MAAM,UAAU,CAAC,CAAC,O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B,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;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"}
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 chalk from 'chalk'\nimport {\n DEFAULT_EDITOR_CONFIG,\n TANSTACK_DEVTOOLS_PACKAGES,\n addPluginToDevtools,\n addSourceToJsx,\n detectDevtoolsFile,\n emitOutdatedDeps,\n enhanceConsoleLog,\n generateConsolePipeCode,\n handleDevToolsRequest,\n handleOpenSource,\n injectPluginIntoFile,\n injectRuntimeBridge,\n installPackage,\n normalizePath,\n readPackageJson,\n removeDevtools,\n stripEnhancedLogPrefix,\n wireRuntimeBridgeChannels,\n} from '@tanstack/devtools-bundler-core'\nimport type {\n ConsoleLevel,\n EditorConfig,\n TanStackDevtoolsConfig,\n} from '@tanstack/devtools-bundler-core'\nimport type { ServerResponse } from 'node:http'\nimport type { Plugin } from 'vite'\nimport type { HttpServerLike } from '@tanstack/devtools-event-bus/server'\n\nexport type { ConsoleLevel } from '@tanstack/devtools-bundler-core'\nexport type TanStackDevtoolsViteConfig = TanStackDevtoolsConfig\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 handleDevToolsRequest(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":";;;;;AAmCA,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,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,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;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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/devtools-vite",
3
- "version": "0.8.1",
3
+ "version": "0.8.2",
4
4
  "description": "TanStack Vite plugin used to enhance the core devtools with additional functionalities",
5
5
  "author": "Tanner Linsley",
6
6
  "license": "MIT",
@@ -50,15 +50,11 @@
50
50
  },
51
51
  "dependencies": {
52
52
  "chalk": "^5.6.2",
53
- "launch-editor": "^2.11.1",
54
- "magic-string": "^0.30.0",
55
- "oxc-parser": "^0.120.0",
56
- "picomatch": "^4.0.3",
53
+ "@tanstack/devtools-bundler-core": "0.1.0",
57
54
  "@tanstack/devtools-client": "0.0.8",
58
55
  "@tanstack/devtools-event-bus": "0.4.2"
59
56
  },
60
57
  "devDependencies": {
61
- "@types/picomatch": "^4.0.2",
62
58
  "happy-dom": "^20.0.0"
63
59
  },
64
60
  "scripts": {
package/src/plugin.ts CHANGED
@@ -1,109 +1,37 @@
1
1
  import { devtoolsEventClient } from '@tanstack/devtools-client'
2
2
  import { ServerEventBus } from '@tanstack/devtools-event-bus/server'
3
- import { normalizePath } from 'vite'
4
3
  import chalk from 'chalk'
5
4
  import {
6
- handleDevToolsViteRequest,
7
- readPackageJson,
8
- stripEnhancedLogPrefix,
9
- } from './utils'
10
- import { DEFAULT_EDITOR_CONFIG, handleOpenSource } from './editor'
11
- import { removeDevtools } from './remove-devtools'
12
- import { addSourceToJsx } from './inject-source'
13
- import { enhanceConsoleLog } from './enhance-logs'
14
- import { detectDevtoolsFile, injectPluginIntoFile } from './inject-plugin'
15
- import { TANSTACK_DEVTOOLS_PACKAGES } from './devtools-packages'
16
- import {
5
+ DEFAULT_EDITOR_CONFIG,
6
+ TANSTACK_DEVTOOLS_PACKAGES,
17
7
  addPluginToDevtools,
8
+ addSourceToJsx,
9
+ detectDevtoolsFile,
18
10
  emitOutdatedDeps,
19
- installPackage,
20
- } from './package-manager'
21
- import { generateConsolePipeCode } from './virtual-console'
22
- import {
11
+ enhanceConsoleLog,
12
+ generateConsolePipeCode,
13
+ handleDevToolsRequest,
14
+ handleOpenSource,
15
+ injectPluginIntoFile,
23
16
  injectRuntimeBridge,
17
+ installPackage,
18
+ normalizePath,
19
+ readPackageJson,
20
+ removeDevtools,
21
+ stripEnhancedLogPrefix,
24
22
  wireRuntimeBridgeChannels,
25
- } from './runtime-bridge'
23
+ } from '@tanstack/devtools-bundler-core'
24
+ import type {
25
+ ConsoleLevel,
26
+ EditorConfig,
27
+ TanStackDevtoolsConfig,
28
+ } from '@tanstack/devtools-bundler-core'
26
29
  import type { ServerResponse } from 'node:http'
27
30
  import type { Plugin } from 'vite'
28
- import type { EditorConfig } from './editor'
29
- import type {
30
- HttpServerLike,
31
- ServerEventBusConfig,
32
- } from '@tanstack/devtools-event-bus/server'
33
-
34
- export type ConsoleLevel = 'log' | 'warn' | 'error' | 'info' | 'debug'
35
-
36
- export 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
- }
106
- }
31
+ import type { HttpServerLike } from '@tanstack/devtools-event-bus/server'
32
+
33
+ export type { ConsoleLevel } from '@tanstack/devtools-bundler-core'
34
+ export type TanStackDevtoolsViteConfig = TanStackDevtoolsConfig
107
35
 
108
36
  export const defineDevtoolsConfig = (config: TanStackDevtoolsViteConfig) =>
109
37
  config
@@ -250,7 +178,7 @@ export const devtools = (args?: TanStackDevtoolsViteConfig): Array<Plugin> => {
250
178
  const consolePipingEnabled = consolePipingConfig.enabled ?? true
251
179
 
252
180
  server.middlewares.use((req, res, next) =>
253
- handleDevToolsViteRequest(req, res, next, {
181
+ handleDevToolsRequest(req, res, next, {
254
182
  onOpenSource: (parsedData) => {
255
183
  const { data, routine } = parsedData
256
184
  if (routine === 'open-source') {
@@ -1,11 +0,0 @@
1
- import { Node } from 'oxc-parser';
2
- /**
3
- * Iterate over the direct child nodes of an AST node.
4
- * Uses a per-type cache of which keys hold child nodes to avoid
5
- * allocating Object.entries() arrays on every call.
6
- */
7
- export declare function forEachChild(node: Node, callback: (child: Node) => void): void;
8
- /**
9
- * Recursively walk AST nodes, calling `visitor` for each node with a `type`.
10
- */
11
- export declare function walk(node: Node, visitor: (node: Node, parentNode?: Node) => void, parentNode?: Node): void;
@@ -1,44 +0,0 @@
1
- //#region src/ast-utils.ts
2
- /**
3
- * Cache of keys that hold child nodes (objects/arrays) per AST node type.
4
- * Since oxc-parser produces AST via JSON.parse, every instance of a given
5
- * node type has the same set of keys, so we only need to discover them once.
6
- */
7
- var childKeysCache = /* @__PURE__ */ new Map();
8
- function getChildKeys(node) {
9
- let keys = childKeysCache.get(node.type);
10
- if (keys) return keys;
11
- keys = [];
12
- for (const key in node) {
13
- if (key === "type" || key === "start" || key === "end") continue;
14
- if (typeof node[key] === "object") keys.push(key);
15
- }
16
- childKeysCache.set(node.type, keys);
17
- return keys;
18
- }
19
- /**
20
- * Iterate over the direct child nodes of an AST node.
21
- * Uses a per-type cache of which keys hold child nodes to avoid
22
- * allocating Object.entries() arrays on every call.
23
- */
24
- function forEachChild(node, callback) {
25
- const keys = getChildKeys(node);
26
- for (const key of keys) {
27
- const value = node[key];
28
- if (value === null) continue;
29
- if (Array.isArray(value)) {
30
- for (const item of value) if (typeof item === "object" && item !== null && "type" in item) callback(item);
31
- } else if ("type" in value) callback(value);
32
- }
33
- }
34
- /**
35
- * Recursively walk AST nodes, calling `visitor` for each node with a `type`.
36
- */
37
- function walk(node, visitor, parentNode) {
38
- visitor(node, parentNode);
39
- forEachChild(node, (child) => walk(child, visitor, node));
40
- }
41
- //#endregion
42
- export { forEachChild, walk };
43
-
44
- //# sourceMappingURL=ast-utils.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ast-utils.js","names":[],"sources":["../../src/ast-utils.ts"],"sourcesContent":["import type { Node } from 'oxc-parser'\n\n/**\n * Cache of keys that hold child nodes (objects/arrays) per AST node type.\n * Since oxc-parser produces AST via JSON.parse, every instance of a given\n * node type has the same set of keys, so we only need to discover them once.\n */\nconst childKeysCache = new Map<string, Array<string>>()\n\nfunction getChildKeys(node: Node): Array<string> {\n let keys = childKeysCache.get(node.type)\n if (keys) return keys\n\n keys = []\n for (const key in node) {\n if (key === 'type' || key === 'start' || key === 'end') continue\n // typeof null === 'object', so nullable node fields get cached too\n if (typeof (node as any)[key] === 'object') {\n keys.push(key)\n }\n }\n childKeysCache.set(node.type, keys)\n return keys\n}\n\n/**\n * Iterate over the direct child nodes of an AST node.\n * Uses a per-type cache of which keys hold child nodes to avoid\n * allocating Object.entries() arrays on every call.\n */\nexport function forEachChild(node: Node, callback: (child: Node) => void) {\n const keys = getChildKeys(node)\n for (const key of keys) {\n const value = (node as any)[key]\n if (value === null) continue\n if (Array.isArray(value)) {\n for (const item of value) {\n if (typeof item === 'object' && item !== null && 'type' in item) {\n callback(item)\n }\n }\n } else if ('type' in value) {\n callback(value as Node)\n }\n }\n}\n\n/**\n * Recursively walk AST nodes, calling `visitor` for each node with a `type`.\n */\nexport function walk(\n node: Node,\n visitor: (node: Node, parentNode?: Node) => void,\n parentNode?: Node,\n) {\n visitor(node, parentNode)\n forEachChild(node, (child) => walk(child, visitor, node))\n}\n"],"mappings":";;;;;;AAOA,IAAM,iCAAiB,IAAI,KAA4B;AAEvD,SAAS,aAAa,MAA2B;CAC/C,IAAI,OAAO,eAAe,IAAI,KAAK,KAAK;CACxC,IAAI,MAAM,OAAO;CAEjB,OAAO,EAAE;CACT,KAAK,MAAM,OAAO,MAAM;EACtB,IAAI,QAAQ,UAAU,QAAQ,WAAW,QAAQ,OAAO;EAExD,IAAI,OAAQ,KAAa,SAAS,UAChC,KAAK,KAAK,IAAI;;CAGlB,eAAe,IAAI,KAAK,MAAM,KAAK;CACnC,OAAO;;;;;;;AAQT,SAAgB,aAAa,MAAY,UAAiC;CACxE,MAAM,OAAO,aAAa,KAAK;CAC/B,KAAK,MAAM,OAAO,MAAM;EACtB,MAAM,QAAS,KAAa;EAC5B,IAAI,UAAU,MAAM;EACpB,IAAI,MAAM,QAAQ,MAAM;QACjB,MAAM,QAAQ,OACjB,IAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,UAAU,MACzD,SAAS,KAAK;SAGb,IAAI,UAAU,OACnB,SAAS,MAAc;;;;;;AAQ7B,SAAgB,KACd,MACA,SACA,YACA;CACA,QAAQ,MAAM,WAAW;CACzB,aAAa,OAAO,UAAU,KAAK,OAAO,SAAS,KAAK,CAAC"}
@@ -1 +0,0 @@
1
- export {};
@@ -1,2 +0,0 @@
1
- export declare const TANSTACK_DEVTOOLS_PACKAGES: readonly ["@tanstack/react-devtools", "@tanstack/preact-devtools", "@tanstack/solid-devtools", "@tanstack/vue-devtools", "@tanstack/svelte-devtools", "@tanstack/angular-devtools", "@tanstack/devtools"];
2
- export declare const isTanStackDevtoolsImport: (source: string) => boolean;
@@ -1,15 +0,0 @@
1
- //#region src/devtools-packages.ts
2
- var TANSTACK_DEVTOOLS_PACKAGES = [
3
- "@tanstack/react-devtools",
4
- "@tanstack/preact-devtools",
5
- "@tanstack/solid-devtools",
6
- "@tanstack/vue-devtools",
7
- "@tanstack/svelte-devtools",
8
- "@tanstack/angular-devtools",
9
- "@tanstack/devtools"
10
- ];
11
- var isTanStackDevtoolsImport = (source) => TANSTACK_DEVTOOLS_PACKAGES.includes(source);
12
- //#endregion
13
- export { TANSTACK_DEVTOOLS_PACKAGES, isTanStackDevtoolsImport };
14
-
15
- //# sourceMappingURL=devtools-packages.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"devtools-packages.js","names":[],"sources":["../../src/devtools-packages.ts"],"sourcesContent":["export const TANSTACK_DEVTOOLS_PACKAGES = [\n '@tanstack/react-devtools',\n '@tanstack/preact-devtools',\n '@tanstack/solid-devtools',\n '@tanstack/vue-devtools',\n '@tanstack/svelte-devtools',\n '@tanstack/angular-devtools',\n '@tanstack/devtools',\n] as const\n\nexport const isTanStackDevtoolsImport = (source: string): boolean =>\n (TANSTACK_DEVTOOLS_PACKAGES as ReadonlyArray<string>).includes(source)\n"],"mappings":";AAAA,IAAa,6BAA6B;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAED,IAAa,4BAA4B,WACtC,2BAAqD,SAAS,OAAO"}
@@ -1 +0,0 @@
1
- export {};
@@ -1,25 +0,0 @@
1
- type OpenSourceData = {
2
- type: 'open-source';
3
- data: {
4
- /** The source file to open */
5
- source?: string;
6
- /** The react router route ID, usually discovered via the hook useMatches */
7
- routeID?: string;
8
- /** The line number in the source file */
9
- line?: number;
10
- /** The column number in the source file */
11
- column?: number;
12
- };
13
- };
14
- export type EditorConfig = {
15
- /** The name of the editor, used for debugging purposes */
16
- name: string;
17
- /** Callback to open a file in the editor */
18
- open: (path: string, lineNumber: string | undefined, columnNumber?: string) => Promise<void>;
19
- };
20
- export declare const DEFAULT_EDITOR_CONFIG: EditorConfig;
21
- export declare const handleOpenSource: ({ data, openInEditor, }: {
22
- data: OpenSourceData;
23
- openInEditor: EditorConfig["open"];
24
- }) => Promise<void>;
25
- export {};
@@ -1,20 +0,0 @@
1
- //#region src/editor.ts
2
- var DEFAULT_EDITOR_CONFIG = {
3
- name: "VSCode",
4
- open: async (path, lineNumber, columnNumber) => {
5
- const launch = (await import("launch-editor")).default;
6
- launch(`${path}${lineNumber ? `:${lineNumber}` : ""}${columnNumber ? `:${columnNumber}` : ""}`, void 0, (filename, err) => {
7
- console.warn(`Failed to open ${filename} in editor: ${err}`);
8
- });
9
- }
10
- };
11
- var handleOpenSource = async ({ data, openInEditor }) => {
12
- const { source, line, column } = data.data;
13
- const lineNum = line ? `${line}` : void 0;
14
- const columnNum = column ? `${column}` : void 0;
15
- if (source) return openInEditor(source, lineNum, columnNum);
16
- };
17
- //#endregion
18
- export { DEFAULT_EDITOR_CONFIG, handleOpenSource };
19
-
20
- //# sourceMappingURL=editor.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"editor.js","names":[],"sources":["../../src/editor.ts"],"sourcesContent":["type OpenSourceData = {\n type: 'open-source'\n data: {\n /** The source file to open */\n source?: string\n /** The react router route ID, usually discovered via the hook useMatches */\n routeID?: string\n /** The line number in the source file */\n line?: number\n /** The column number in the source file */\n column?: number\n }\n}\n\nexport type EditorConfig = {\n /** The name of the editor, used for debugging purposes */\n name: string\n /** Callback to open a file in the editor */\n open: (\n path: string,\n lineNumber: string | undefined,\n columnNumber?: string,\n ) => Promise<void>\n}\n\nexport const DEFAULT_EDITOR_CONFIG: EditorConfig = {\n name: 'VSCode',\n open: async (path, lineNumber, columnNumber) => {\n const launch = (await import('launch-editor')).default\n launch(\n `${path}${lineNumber ? `:${lineNumber}` : ''}${columnNumber ? `:${columnNumber}` : ''}`,\n undefined,\n (filename, err) => {\n console.warn(`Failed to open ${filename} in editor: ${err}`)\n },\n )\n },\n}\n\nexport const handleOpenSource = async ({\n data,\n openInEditor,\n}: {\n data: OpenSourceData\n openInEditor: EditorConfig['open']\n}) => {\n const { source, line, column } = data.data\n const lineNum = line ? `${line}` : undefined\n const columnNum = column ? `${column}` : undefined\n if (source) {\n return openInEditor(source, lineNum, columnNum)\n }\n}\n"],"mappings":";AAyBA,IAAa,wBAAsC;CACjD,MAAM;CACN,MAAM,OAAO,MAAM,YAAY,iBAAiB;EAC9C,MAAM,UAAU,MAAM,OAAO,kBAAkB;EAC/C,OACE,GAAG,OAAO,aAAa,IAAI,eAAe,KAAK,eAAe,IAAI,iBAAiB,MACnF,KAAA,IACC,UAAU,QAAQ;GACjB,QAAQ,KAAK,kBAAkB,SAAS,cAAc,MAAM;IAE/D;;CAEJ;AAED,IAAa,mBAAmB,OAAO,EACrC,MACA,mBAII;CACJ,MAAM,EAAE,QAAQ,MAAM,WAAW,KAAK;CACtC,MAAM,UAAU,OAAO,GAAG,SAAS,KAAA;CACnC,MAAM,YAAY,SAAS,GAAG,WAAW,KAAA;CACzC,IAAI,QACF,OAAO,aAAa,QAAQ,SAAS,UAAU"}
@@ -1 +0,0 @@
1
- export {};
@@ -1,4 +0,0 @@
1
- export declare function enhanceConsoleLog(code: string, id: string, port: number): {
2
- code: string;
3
- map: import('magic-string').SourceMap;
4
- } | undefined;
@@ -1,51 +0,0 @@
1
- import { walk } from "./ast-utils.js";
2
- import { createLocMapper } from "./offset-to-loc.js";
3
- import { normalizePath } from "vite";
4
- import chalk from "chalk";
5
- import MagicString from "magic-string";
6
- import { parseSync } from "oxc-parser";
7
- //#region src/enhance-logs.ts
8
- function escapeForStringLiteral(str) {
9
- return str.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n");
10
- }
11
- function enhanceConsoleLog(code, id, port) {
12
- const filePath = id.split("?")[0];
13
- const location = filePath.replace(normalizePath(process.cwd()), "");
14
- try {
15
- const result = parseSync(filePath, code, {
16
- sourceType: "module",
17
- lang: "tsx"
18
- });
19
- if (result.errors.length > 0) return;
20
- const offsetToLoc = createLocMapper(code);
21
- const s = new MagicString(code);
22
- walk(result.program, (node) => {
23
- if (node.type !== "CallExpression") return;
24
- const callee = node.callee;
25
- if (callee.type === "MemberExpression" && !callee.computed && callee.object.type === "Identifier" && callee.object.name === "console" && callee.property.type === "Identifier" && (callee.property.name === "log" || callee.property.name === "error")) {
26
- const loc = offsetToLoc(node.start);
27
- const [lineNumber, column] = [loc.line, loc.column];
28
- const finalPath = `${location}:${lineNumber}:${column + 1}`;
29
- const spreadStr = `...(typeof window === "undefined" ? ${`["${escapeForStringLiteral(`${chalk.magenta("LOG")} ${chalk.blueBright(`${finalPath}`)}\n → `)}"]`} : ${`["%cLOG%c %c${`Go to Source: http://localhost:${port}/__tsd/open-source?source=${encodeURIComponent(finalPath)}`}%c \\n \\u2192 ","color:#A0A","color:#FFF","color:#55F","color:#FFF"]`}), `;
30
- let parenOffset = callee.end;
31
- while (parenOffset < code.length && code[parenOffset] !== "(") parenOffset++;
32
- s.appendRight(parenOffset + 1, spreadStr);
33
- }
34
- });
35
- if (!s.hasChanged()) return;
36
- return {
37
- code: s.toString(),
38
- map: s.generateMap({
39
- source: filePath,
40
- file: id,
41
- includeContent: true
42
- })
43
- };
44
- } catch (e) {
45
- return;
46
- }
47
- }
48
- //#endregion
49
- export { enhanceConsoleLog };
50
-
51
- //# sourceMappingURL=enhance-logs.js.map