Open History to see the last commit
1import type { ConsoleLevel } from './plugin'
2β
3// export const VIRTUAL_MODULE_ID = 'virtual:tanstack-devtools-console'
4// export const RESOLVED_VIRTUAL_MODULE_ID = '\0' + VIRTUAL_MODULE_ID
5β
6/**
7 * Generates inline code to inject into entry files (both client and server).
8 * This code detects the environment at runtime and:
9 *
10 * CLIENT:
11 * 1. Store original console methods
12 * 2. Create batched wrappers that POST to server via fetch
13 * 3. Override global console with the wrapped methods
14 * 4. Listen for server console logs via SSE
15 *
16 * SERVER (Nitro/Vinxi runtime):
17 * 1. Store original console methods
18 * 2. Create batched wrappers that POST to Vite dev server
19 * 3. Override global console - original logging still happens, just also pipes to Vite
20 *
21 * Returns the inline code as a string - no imports needed since we use fetch.
22 */
23export function generateConsolePipeCode(
24 levels: Array<ConsoleLevel>,
25 viteServerUrl: string,
26): string {
27 const levelsArray = JSON.stringify(levels)
28β
29 return `
30;(function __tsdConsolePipe() {
31 // Detect environment
32 var isServer = typeof window === 'undefined';
33 var envKey = isServer ? '__TSD_SERVER_CONSOLE_PIPE_INITIALIZED__' : '__TSD_CONSOLE_PIPE_INITIALIZED__';
34 var globalObj = isServer ? globalThis : window;
36 // Only run once per environment
37 if (globalObj[envKey]) return;
38 globalObj[envKey] = true;
39β
40 var CONSOLE_LEVELS = ${levelsArray};
41 var VITE_SERVER_URL = ${JSON.stringify(viteServerUrl)};
42β
43 // Store original console methods before we override them
44 var originalConsole = {};
45 for (var i = 0; i < CONSOLE_LEVELS.length; i++) {
46 var level = CONSOLE_LEVELS[i];
47 originalConsole[level] = console[level].bind(console);
48 }
49β
50 // Simple inline batcher implementation
51 var batchedEntries = [];
52 var batchTimeout = null;
53 var BATCH_WAIT = isServer ? 50 : 100;
54 var BATCH_MAX_SIZE = isServer ? 20 : 50;
55β
56 function flushBatch() {
57 if (batchedEntries.length === 0) return;
59 var entries = batchedEntries;
60 batchedEntries = [];
61 batchTimeout = null;
63 // Determine endpoint based on environment
64 var endpoint = isServer
65 ? VITE_SERVER_URL + '/__tsd/console-pipe/server'
66 : '/__tsd/console-pipe';
68 // Send to Vite server via fetch
69 fetch(endpoint, {
70 method: 'POST',
71 headers: { 'Content-Type': 'application/json' },
72 body: JSON.stringify({ entries: entries }),
73 }).catch(function( ) {
74 // Swallow errors
75 });
76 }
77β
78 function addToBatch(entry) {
79 batchedEntries.push(entry);
81 if (batchedEntries.length >= BATCH_MAX_SIZE) {
82 if (batchTimeout) {
83 clearTimeout(batchTimeout);
84 batchTimeout = null;
85 }
86 flushBatch();
87 } else if (!batchTimeout) {
88 batchTimeout = setTimeout(flushBatch, BATCH_WAIT);
89 }
90 }
91β
92 var MAX_DEPTH = 6;
93 var MAX_ARRAY_LEN = 100;
94 var MAX_OBJECT_KEYS = 100;
95 var MAX_STRING_LENGTH = 10000;
96β
97 function truncateString(value) {
98 if (value.length <= MAX_STRING_LENGTH) return value;
99 return value.slice(0, MAX_STRING_LENGTH) + '... (' + (value.length - MAX_STRING_LENGTH) + ' more chars)';
100 }
101β
102 function formatDomElement(element) {
103 var tagName = element.tagName ? element.tagName.toLowerCase() : 'element';
104 var output = '<' + tagName;
105 var attrs = ['id', 'class', 'name', 'type', 'role', 'aria-label', 'data-testid'];
106β
107 for (var attrIndex = 0; attrIndex < attrs.length; attrIndex++) {
108 var attrName = attrs[attrIndex];
109 var attrValue = element.getAttribute && element.getAttribute(attrName);
110 if (attrValue) {
111 output += ' ' + attrName + '="' + truncateString(String(attrValue)).replace(/"/g, '"') + '"';
112 }
113 }
114β
115 return output + '>';
116 }
117β
118 function getObjectTypeName(arg) {
119 return arg && arg.constructor && arg.constructor.name ? arg.constructor.name : 'Object';
120 }
121β
122 function formatArrayBufferView(arg) {
123 var length = typeof arg.length === 'number' ? arg.length : arg.byteLength;
124 return '[' + getObjectTypeName(arg) + '(' + length + ')]';
125 }
126β
127 function serializeConsoleArg(arg, seen, depth) {
128 if (depth === undefined) depth = 0;
129 if (arg === undefined) return 'undefined';
130 if (arg === null) return null;
131β
132 var argType = typeof arg;
133β
134 if (argType === 'function') return '[Function' + (arg.name ? ': ' + arg.name : '') + ']';
135 if (argType === 'symbol') return arg.toString();
136 if (argType === 'bigint') return arg.toString() + 'n';
137 if (argType === 'string') return truncateString(arg);
138 if (argType !== 'object') return arg;
139β
140 if (!isServer) {
141 if (
142 arg.nodeType === 1 &&
143 typeof arg.tagName === 'string' &&
144 typeof arg.getAttribute === 'function'
145 ) {
146 return formatDomElement(arg);
147 }
148 if (arg.nodeType === 9) {
149 return '[Document]';
150 }
151 if (typeof Window !== 'undefined' && arg instanceof Window) {
152 return '[Window]';
153 }
154 if (typeof Event !== 'undefined' && arg instanceof Event) {
155 return {
156 type: arg.type,
157 target: serializeConsoleArg(arg.target, seen, depth + 1),
158 currentTarget: serializeConsoleArg(arg.currentTarget, seen, depth + 1),
159 defaultPrevented: arg.defaultPrevented,
160 };
161 }
162 if (typeof Node !== 'undefined' && arg instanceof Node) {
163 return '[Node: ' + arg.nodeName + ']';
164 }
165 }
166β
167 if (arg instanceof Error) {
168 return {
169 name: arg.name,
170 message: truncateString(arg.message),
171 stack: arg.stack ? truncateString(arg.stack) : arg.stack,
172 };
173 }
174β
175 if (arg instanceof Date) {
176 return arg.toISOString();
177 }
178β
179 if (arg instanceof RegExp) {
180 return arg.toString();
181 }
182β
183 if (typeof ArrayBuffer !== 'undefined') {
184 if (ArrayBuffer.isView && ArrayBuffer.isView(arg)) {
185 return formatArrayBufferView(arg);
186 }
187 if (arg instanceof ArrayBuffer) {
188 return '[ArrayBuffer(' + arg.byteLength + ')]';
189 }
190 }
191β
192 if (typeof SharedArrayBuffer !== 'undefined' && arg instanceof SharedArrayBuffer) {
193 return '[SharedArrayBuffer(' + arg.byteLength + ')]';
194 }
195β
196 if (depth >= MAX_DEPTH) {
197 return '[MaxDepth]';
198 }
199β
200 if (seen.indexOf(arg) !== -1) {
201 return '[Circular]';
202 }
203β
204 seen.push(arg);
205β
206 if (Array.isArray(arg)) {
207 var arrayResult = [];
208 var arrayLength = Math.min(arg.length, MAX_ARRAY_LEN);
209 for (var arrayIndex = 0; arrayIndex < arrayLength; arrayIndex++) {
210 arrayResult.push(serializeConsoleArg(arg[arrayIndex], seen, depth + 1));
211 }
212 if (arg.length > MAX_ARRAY_LEN) {
213 arrayResult.push('... (' + (arg.length - MAX_ARRAY_LEN) + ' more)');
214 }
215 seen.pop();
216 return arrayResult;
217 }
218β
219 var objectResult = {};
220 var keys = Object.keys(arg);
221 var keyLength = Math.min(keys.length, MAX_OBJECT_KEYS);
222 for (var keyIndex = 0; keyIndex < keyLength; keyIndex++) {
223 var key = keys[keyIndex];
224 try {
225 objectResult[key] = serializeConsoleArg(arg[key], seen, depth + 1);
226 } catch (error) {
227 objectResult[key] = '[Thrown: ' + String(error) + ']';
228 }
229 }
230 if (keys.length > MAX_OBJECT_KEYS) {
231 objectResult['...'] = '(' + (keys.length - MAX_OBJECT_KEYS) + ' more keys)';
232 }
233 seen.pop();
234 return objectResult;
235 }
236β
237 // Override global console methods
238 for (var j = 0; j < CONSOLE_LEVELS.length; j++) {
239 (function(level) {
240 var original = originalConsole[level];
241 console[level] = function() {
242 var args = Array.prototype.slice.call(arguments);
244 // Always call original first so logs appear normally
245 original.apply(console, args);
247 // Skip our own TSD Console Pipe logs to avoid recursion/noise
248 if (args.length > 0 && typeof args[0] === 'string' &&
249 (args[0].indexOf('[TSD Console Pipe]') !== -1 ||
250 args[0].indexOf('[@tanstack/devtools') !== -1)) {
251 return;
252 }
253β
254 var safeArgs = args.map(function(arg) {
255 try {
256 return serializeConsoleArg(arg, [], 0);
257 } catch (e) {
258 return String(arg);
259 }
260 });
261β
262 var entry = {
263 level: level,
264 args: safeArgs,
265 source: isServer ? 'server' : 'client',
266 timestamp: Date.now(),
267 };
269 addToBatch(entry);
270 };
271 })(CONSOLE_LEVELS[j]);
272 }
273β
274 // CLIENT ONLY: Listen for server console logs via SSE
275 if (!isServer) {
276 // Transform server log args - strip ANSI codes and convert source paths to clickable URLs
277 function transformServerLogArgs(args) {
278 var escChar = String.fromCharCode(27);
279 var transformed = [];
281 for (var k = 0; k < args.length; k++) {
282 var arg = args[k];
283 if (typeof arg === 'string') {
284 // Strip ANSI escape sequences (ESC[...m patterns)
285 var cleaned = arg;
286 // Remove ESC character followed by [...m] - need to build regex dynamically
287 while (cleaned.indexOf(escChar) !== -1) {
288 cleaned = cleaned.split(escChar).join('');
289 }
290 // Also remove any leftover bracket codes like [35m
291 cleaned = cleaned.replace(/\\[[0-9;]*m/g, '');
293 // Transform source paths to clickable URLs
294 // Match patterns like /src/components/Header.tsx:17:3
295 var sourceRegex = /(\\/[^\\s]+:\\d+:\\d+)/g;
296 cleaned = cleaned.replace(sourceRegex, function(match) {
297 return window.location.origin + '/__tsd/open-source?source=' + encodeURIComponent(match);
298 });
300 if (cleaned.trim()) {
301 transformed.push(cleaned);
302 }
303 } else {
304 transformed.push(arg);
305 }
306 }
308 return transformed;
309 }
310β
311 var eventSource = new EventSource('/__tsd/console-pipe/sse');
313 eventSource.onmessage = function(event) {
314 try {
315 var data = JSON.parse(event.data);
316 if (data.entries) {
317 for (var m = 0; m < data.entries.length; m++) {
318 var entry = data.entries[m];
319 var transformedArgs = transformServerLogArgs(entry.args);
320 var prefix = '%c[Server]%c';
321 var prefixStyle = 'color: #9333ea; font-weight: bold;';
322 var resetStyle = 'color: inherit;';
323 var logMethod = originalConsole[entry.level] || originalConsole.log;
324 logMethod.apply(console, [prefix, prefixStyle, resetStyle].concat(transformedArgs));
325 }
326 }
327 } catch (err) {
328 // Swallow errors
329 }
330 };
331β
332 eventSource.onerror = function() {
333 // Swallow errors
334 };
335β
336 // Flush on page unload
337 window.addEventListener('beforeunload', flushBatch);
338 }
339})();
340`
341}