@@ -6,31 +6,46 @@ import { stopSketch, expandConsole } from '../actions/ide';
6
6
export default function useHandleMessageEvent ( ) {
7
7
const dispatch = useDispatch ( ) ;
8
8
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
+ ) ;
19
31
} ;
20
32
21
33
const handleMessageEvent = ( data ) => {
22
34
if ( ! data || typeof data !== 'object' ) return ;
23
35
const { source, messages } = data ;
24
36
if ( source !== 'sketch' || ! Array . isArray ( messages ) ) return ;
37
+
25
38
const decodedMessages = messages . map ( ( message ) => {
26
39
try {
27
- return JSON . parse ( safeStringify ( Decode ( message . log ) ) ) ;
40
+ const decoded = Decode ( message . log ) ?? '[Unknown Message]' ; // Ensure decoding works
41
+ return safeStringify ( decoded ) ;
28
42
} catch ( error ) {
29
43
console . error ( 'Error decoding message:' , error ) ;
30
44
return { error : 'Failed to decode message' } ;
31
45
}
32
46
} ) ;
33
47
48
+ // Detect infinite loop warnings
34
49
const hasInfiniteLoop = decodedMessages . some (
35
50
( message ) =>
36
51
message ?. data &&
0 commit comments