@@ -6,30 +6,64 @@ import { stopSketch, expandConsole } from '../actions/ide';
6
6
export default function useHandleMessageEvent ( ) {
7
7
const dispatch = useDispatch ( ) ;
8
8
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
+ ) ;
31
+ } ;
32
+
9
33
const handleMessageEvent = ( data ) => {
34
+ if ( ! data || typeof data !== 'object' ) return ;
10
35
const { source, messages } = data ;
11
- if ( source === 'sketch' && Array . isArray ( messages ) ) {
12
- const decodedMessages = messages . map ( ( message ) => Decode ( message . log ) ) ;
13
- decodedMessages . every ( ( message , index , arr ) => {
14
- const { data : args } = message ;
15
- let hasInfiniteLoop = false ;
16
- Object . keys ( args ) . forEach ( ( key ) => {
17
- if (
18
- typeof args [ key ] === 'string' &&
19
- args [ key ] . includes ( 'Exiting potential infinite loop' )
20
- ) {
21
- dispatch ( stopSketch ( ) ) ;
22
- dispatch ( expandConsole ( ) ) ;
23
- hasInfiniteLoop = true ;
24
- }
25
- } ) ;
26
- if ( hasInfiniteLoop ) {
27
- return false ;
28
- }
29
- return true ;
30
- } ) ;
31
- dispatch ( dispatchConsoleEvent ( decodedMessages ) ) ;
36
+ if ( source !== 'sketch' || ! Array . isArray ( messages ) ) return ;
37
+
38
+ const decodedMessages = messages . map ( ( message ) => {
39
+ try {
40
+ const decoded = Decode ( message . log ) ?? '[Unknown Message]' ; // Ensure decoding works
41
+ return safeStringify ( decoded ) ;
42
+ } catch ( error ) {
43
+ console . error ( 'Error decoding message:' , error ) ;
44
+ return { error : 'Failed to decode message' } ;
45
+ }
46
+ } ) ;
47
+
48
+ // Detect infinite loop warnings
49
+ const hasInfiniteLoop = decodedMessages . some (
50
+ ( message ) =>
51
+ message ?. data &&
52
+ Object . values ( message . data ) . some (
53
+ ( arg ) =>
54
+ typeof arg === 'string' &&
55
+ arg . includes ( 'Exiting potential infinite loop' )
56
+ )
57
+ ) ;
58
+
59
+ if ( hasInfiniteLoop ) {
60
+ dispatch ( stopSketch ( ) ) ;
61
+ dispatch ( expandConsole ( ) ) ;
62
+ return ;
32
63
}
64
+
65
+ dispatch ( dispatchConsoleEvent ( decodedMessages ) ) ;
33
66
} ;
67
+
34
68
return handleMessageEvent ;
35
69
}
0 commit comments