@@ -6,31 +6,46 @@ import { stopSketch, expandConsole } from '../actions/ide';
66export default function useHandleMessageEvent ( ) {
77 const dispatch = useDispatch ( ) ;
88
9- // Function to safely convert objects to strings (handles circular references)
10- const safeStringify = ( obj ) => {
11- const seen = new WeakSet ( ) ;
12- return JSON . stringify ( obj , ( key , value ) => {
13- if ( typeof value === 'object' && value !== null ) {
14- if ( seen . has ( value ) ) return '[Circular Reference]' ;
15- seen . add ( value ) ;
16- }
17- return value ;
18- } ) ;
9+ const safeStringify = (
10+ obj ,
11+ depth = 0 ,
12+ maxDepth = 10 ,
13+ seen = new WeakMap ( )
14+ ) => {
15+ if ( typeof obj !== 'object' || obj === null ) return obj ;
16+
17+ if ( depth >= maxDepth ) {
18+ if ( seen . has ( obj ) ) return '[Circular Reference]' ;
19+ }
20+
21+ seen . set ( obj , true ) ;
22+
23+ return Array . isArray ( obj )
24+ ? obj . map ( ( item ) => safeStringify ( item , depth + 1 , maxDepth , seen ) )
25+ : Object . fromEntries (
26+ Object . entries ( obj ) . map ( ( [ key , value ] ) => [
27+ key ,
28+ safeStringify ( value , depth + 1 , maxDepth , seen )
29+ ] )
30+ ) ;
1931 } ;
2032
2133 const handleMessageEvent = ( data ) => {
2234 if ( ! data || typeof data !== 'object' ) return ;
2335 const { source, messages } = data ;
2436 if ( source !== 'sketch' || ! Array . isArray ( messages ) ) return ;
37+
2538 const decodedMessages = messages . map ( ( message ) => {
2639 try {
27- return JSON . parse ( safeStringify ( Decode ( message . log ) ) ) ;
40+ const decoded = Decode ( message . log ) ?? '[Unknown Message]' ; // Ensure decoding works
41+ return safeStringify ( decoded ) ;
2842 } catch ( error ) {
2943 console . error ( 'Error decoding message:' , error ) ;
3044 return { error : 'Failed to decode message' } ;
3145 }
3246 } ) ;
3347
48+ // Detect infinite loop warnings
3449 const hasInfiniteLoop = decodedMessages . some (
3550 ( message ) =>
3651 message ?. data &&
0 commit comments