@@ -3,19 +3,30 @@ export function detectBadJsonStrings(jsonString: string): boolean {
33 let idx = jsonString . indexOf ( "\\u" ) ;
44 if ( idx === - 1 ) return false ;
55
6- // Only check the area around each \u
7- while ( idx !== - 1 && idx < jsonString . length - 5 ) {
6+ // Use a more efficient scanning strategy
7+ const length = jsonString . length ;
8+
9+ while ( idx !== - 1 && idx < length - 5 ) {
10+ // Only check if we have enough characters left
11+ if ( idx + 6 > length ) break ;
12+
813 if ( jsonString [ idx + 1 ] === "u" && jsonString [ idx + 2 ] === "d" ) {
914 const third = jsonString [ idx + 3 ] ;
10- // High surrogate
15+
16+ // High surrogate check
1117 if (
1218 / [ 8 9 a b ] / . test ( third ) &&
1319 / [ 0 - 9 a - f ] / . test ( jsonString [ idx + 4 ] ) &&
1420 / [ 0 - 9 a - f ] / . test ( jsonString [ idx + 5 ] )
1521 ) {
16- // Check for low surrogate after
22+ // Check for low surrogate after (need at least 6 more chars)
23+ if ( idx + 12 > length ) {
24+ return true ; // Incomplete high surrogate (not enough chars left)
25+ }
26+
1727 if (
18- jsonString . substr ( idx + 6 , 2 ) !== "\\u" ||
28+ jsonString [ idx + 6 ] !== "\\" ||
29+ jsonString [ idx + 7 ] !== "u" ||
1930 jsonString [ idx + 8 ] !== "d" ||
2031 ! / [ c d ] / . test ( jsonString [ idx + 9 ] ) ||
2132 ! / [ 0 - 9 a - f ] / . test ( jsonString [ idx + 10 ] ) ||
@@ -24,16 +35,21 @@ export function detectBadJsonStrings(jsonString: string): boolean {
2435 return true ; // Incomplete high surrogate
2536 }
2637 }
27- // Low surrogate
38+
39+ // Low surrogate check
2840 if (
2941 ( third === "c" || third === "d" ) &&
3042 / [ 0 - 9 a - f ] / . test ( jsonString [ idx + 4 ] ) &&
3143 / [ 0 - 9 a - f ] / . test ( jsonString [ idx + 5 ] )
3244 ) {
33- // Check for high surrogate before
45+ // Check for high surrogate before (need at least 6 chars before)
46+ if ( idx < 6 ) {
47+ return true ; // Incomplete low surrogate (not enough chars before)
48+ }
49+
3450 if (
35- idx < 6 ||
36- jsonString . substr ( idx - 6 , 2 ) !== "\\ u" ||
51+ jsonString [ idx - 6 ] !== "\\" ||
52+ jsonString [ idx - 5 ] !== "u" ||
3753 jsonString [ idx - 4 ] !== "d" ||
3854 ! / [ 8 9 a b ] / . test ( jsonString [ idx - 3 ] ) ||
3955 ! / [ 0 - 9 a - f ] / . test ( jsonString [ idx - 2 ] ) ||
@@ -43,7 +59,10 @@ export function detectBadJsonStrings(jsonString: string): boolean {
4359 }
4460 }
4561 }
46- idx = jsonString . indexOf ( "\\u" , idx + 1 ) ;
62+
63+ // More efficient next search - skip ahead by 2 to avoid overlapping matches
64+ idx = jsonString . indexOf ( "\\u" , idx + 2 ) ;
4765 }
66+
4867 return false ;
4968}
0 commit comments