@@ -4,9 +4,6 @@ import { type InspectFn, defaultInspect } from './parser/utils';
44import { ByteUtils } from './utils/byte_utils' ;
55import { NumberUtils } from './utils/number_utils' ;
66
7- // Regular expression that checks for hex value
8- const checkForHexRegExp = new RegExp ( '^[0-9a-fA-F]{24}$' ) ;
9-
107// Unique sequence for the current process (initialized on first use)
118let PROCESS_UNIQUE : Uint8Array | null = null ;
129
@@ -112,7 +109,7 @@ export class ObjectId extends BSONValue {
112109 // If intstanceof matches we can escape calling ensure buffer in Node.js environments
113110 this . buffer = ByteUtils . toLocalBufferType ( workingId ) ;
114111 } else if ( typeof workingId === 'string' ) {
115- if ( workingId . length === 24 && checkForHexRegExp . test ( workingId ) ) {
112+ if ( ObjectId . validateHexString ( workingId ) ) {
116113 this . buffer = ByteUtils . fromHex ( workingId ) ;
117114 } else {
118115 throw new BSONError (
@@ -143,6 +140,29 @@ export class ObjectId extends BSONValue {
143140 }
144141 }
145142
143+ /**
144+ * @internal
145+ * Validates the input string is a valid hex representation of an ObjectId.
146+ */
147+ private static validateHexString ( string : string ) : boolean {
148+ if ( string ?. length !== 24 ) return false ;
149+ for ( let i = 0 ; i < 24 ; i ++ ) {
150+ const char = string . charCodeAt ( i ) ;
151+ if (
152+ // Check for ASCII 0-9
153+ ( char >= 48 && char <= 57 ) ||
154+ // Check for ASCII a-f
155+ ( char >= 97 && char <= 102 ) ||
156+ // Check for ASCII A-F
157+ ( char >= 65 && char <= 70 )
158+ ) {
159+ continue ;
160+ }
161+ return false ;
162+ }
163+ return true ;
164+ }
165+
146166 /** Returns the ObjectId id as a 24 lowercase character hex string representation */
147167 toHexString ( ) : string {
148168 if ( ObjectId . cacheHexString && this . __id ) {
@@ -329,6 +349,7 @@ export class ObjectId extends BSONValue {
329349 */
330350 static isValid ( id : string | number | ObjectId | ObjectIdLike | Uint8Array ) : boolean {
331351 if ( id == null ) return false ;
352+ if ( typeof id === 'string' ) return ObjectId . validateHexString ( id ) ;
332353
333354 try {
334355 new ObjectId ( id ) ;
0 commit comments