@@ -18,21 +18,43 @@ import { NonRecordingSpan } from './NonRecordingSpan';
1818import { Span } from './span' ;
1919import { SpanContext } from './span_context' ;
2020
21- const VALID_TRACEID_REGEX = / ^ ( [ 0 - 9 a - f ] { 32 } ) $ / i;
22- const VALID_SPANID_REGEX = / ^ [ 0 - 9 a - f ] { 16 } $ / i;
21+ // Valid characters (0-9, a-f, A-F) are marked as 1.
22+ const isHex = new Uint8Array ( [
23+ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
24+ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 ,
25+ 1 , 1 , 1 , 1 , 1 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 1 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
26+ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 1 , 1 ,
27+ ] ) ;
28+
29+ function isValidHex ( id : string , length : number ) : boolean {
30+ // As of 1.9.0 the id was allowed to be a non-string value,
31+ // even though it was not possible in the types.
32+ if ( typeof id !== 'string' || id . length !== length ) return false ;
33+
34+ let r = 0 ;
35+ for ( let i = 0 ; i < id . length ; i += 4 ) {
36+ r +=
37+ ( isHex [ id . charCodeAt ( i ) ] | 0 ) +
38+ ( isHex [ id . charCodeAt ( i + 1 ) ] | 0 ) +
39+ ( isHex [ id . charCodeAt ( i + 2 ) ] | 0 ) +
40+ ( isHex [ id . charCodeAt ( i + 3 ) ] | 0 ) ;
41+ }
42+
43+ return r === length ;
44+ }
2345
2446/**
2547 * @since 1.0.0
2648 */
2749export function isValidTraceId ( traceId : string ) : boolean {
28- return VALID_TRACEID_REGEX . test ( traceId ) && traceId !== INVALID_TRACEID ;
50+ return isValidHex ( traceId , 32 ) && traceId !== INVALID_TRACEID ;
2951}
3052
3153/**
3254 * @since 1.0.0
3355 */
3456export function isValidSpanId ( spanId : string ) : boolean {
35- return VALID_SPANID_REGEX . test ( spanId ) && spanId !== INVALID_SPANID ;
57+ return isValidHex ( spanId , 16 ) && spanId !== INVALID_SPANID ;
3658}
3759
3860/**
0 commit comments