@@ -8,43 +8,67 @@ function _isValidQuery(query: string): boolean {
88 }
99}
1010
11+ // Add _id: ObjectId("<id>") when a user pastes only an object id.
12+ function _fixObjectIdInQuery ( query : string ) : string | undefined {
13+ const objectIdRegex = / ^ { ( [ 0 - 9 a - f A - F ] { 24 } ) } $ / ;
14+
15+ const match = query . match ( objectIdRegex ) ;
16+ if ( match ) {
17+ return `{ _id: ObjectId("${ match [ 1 ] } ") }` ;
18+ }
19+ }
20+
21+ function _fixBraceEscapingInQuery ( query : string ) : string | undefined {
22+ const isValid = _isValidQuery ( query ) ;
23+
24+ if ( isValid ) {
25+ return ;
26+ }
27+
28+ if ( query . startsWith ( '{' ) && query . endsWith ( '}' ) ) {
29+ const queryWithoutWrappingBraces = query . substring ( 1 , query . length - 1 ) ;
30+ const isInnerQueryValid = _isValidQuery ( queryWithoutWrappingBraces ) ;
31+ if ( isInnerQueryValid ) {
32+ return queryWithoutWrappingBraces ;
33+ }
34+ } else {
35+ const wrappedQuery = `{${ query } }` ;
36+ if ( _isValidQuery ( wrappedQuery ) ) {
37+ return wrappedQuery ;
38+ }
39+ }
40+ }
41+
1142export function lenientlyFixQuery ( query : string ) : string | false {
1243 query = query . trim ( ) ;
13- let modified = false ;
1444
1545 if ( query === '' ) {
1646 return '\\{${}}' ;
1747 }
1848
19- const isValid = _isValidQuery ( query ) ;
49+ let modified = false ;
2050
21- if ( ! isValid ) {
22- if ( query . startsWith ( '{' ) && query . endsWith ( '}' ) ) {
23- const queryWithoutWrappingBraces = query . substring ( 1 , query . length - 1 ) ;
24- const isInnerQueryValid = _isValidQuery ( queryWithoutWrappingBraces ) ;
25- if ( isInnerQueryValid ) {
26- modified = true ;
27- query = queryWithoutWrappingBraces ;
28- }
29- } else {
30- const wrappedQuery = `{${ query } }` ;
31- if ( _isValidQuery ( wrappedQuery ) ) {
32- modified = true ;
33- query = wrappedQuery ;
34- }
35- }
51+ const fixedObjectId = _fixObjectIdInQuery ( query ) ;
52+ if ( fixedObjectId ) {
53+ modified = true ;
54+ query = fixedObjectId ;
3655 }
3756
38- if ( modified ) {
39- query = query . replaceAll ( '{' , '\\{' ) ;
40- const caretPosition = query . lastIndexOf ( '}' ) ;
57+ const fixedBraceEscaping = _fixBraceEscapingInQuery ( query ) ;
58+ if ( fixedBraceEscaping ) {
59+ modified = true ;
60+ query = fixedBraceEscaping ;
61+ }
4162
42- query =
43- query . substring ( 0 , caretPosition ) +
44- '${}' +
45- query . substring ( caretPosition ) ;
46- return query ;
63+ if ( ! modified ) {
64+ return false ;
4765 }
4866
49- return false ;
67+ // Add template formatting to put the cursor position before the last closing brace.
68+ query = query . replaceAll ( '{' , '\\{' ) ;
69+ const caretPosition = query . lastIndexOf ( '}' ) ;
70+
71+ query =
72+ query . substring ( 0 , caretPosition ) + '${}' + query . substring ( caretPosition ) ;
73+ return query ;
5074}
0 commit comments