@@ -376,17 +376,25 @@ <h3>生成结果</h3>
376376 return v . toString ( 16 ) ;
377377 } ) ;
378378 } else if ( version === '1' ) {
379- // UUID v1 simulation (timestamp-based)
380- const timestamp = Date . now ( ) ;
381- const timeHex = timestamp . toString ( 16 ) . padStart ( 12 , '0' ) ;
382- const clockSeq = Math . floor ( Math . random ( ) * 16384 ) . toString ( 16 ) . padStart ( 4 , '0' ) ;
383- const node = Math . floor ( Math . random ( ) * 281474976710656 ) . toString ( 16 ) . padStart ( 12 , '0' ) ;
384-
385- return timeHex . substring ( 0 , 8 ) + '-' +
386- timeHex . substring ( 8 , 12 ) + '-1' +
387- timeHex . substring ( 12 , 15 ) + '-' +
388- clockSeq . substring ( 0 , 1 ) + '0' + clockSeq . substring ( 1 ) + '-' +
389- node ;
379+ // UUID v1(RFC 4122 正确实现)
380+ const UUID_EPOCH = 12219292800000n ; // ms between 1582-10-15 and 1970-01-01
381+ const now = BigInt ( Date . now ( ) ) ;
382+ const time100ns = ( now + UUID_EPOCH ) * 10000n ;
383+ const timeLow = Number ( time100ns & 0xffffffffn ) ;
384+ const timeMid = Number ( ( time100ns >> 32n ) & 0xffffn ) ;
385+ const timeHi = Number ( ( time100ns >> 48n ) & 0x0fffn ) | 0x1000 ; // version = 1
386+ const clockSeq = Math . floor ( Math . random ( ) * 0x3fff ) ;
387+ const clockSeqHi = ( clockSeq >> 8 ) | 0x80 ; // variant = 10xx
388+ const clockSeqLow = clockSeq & 0xff ;
389+ const node = crypto . getRandomValues ( new Uint8Array ( 6 ) ) ;
390+ return (
391+ timeLow . toString ( 16 ) . padStart ( 8 , '0' ) + '-' +
392+ timeMid . toString ( 16 ) . padStart ( 4 , '0' ) + '-' +
393+ timeHi . toString ( 16 ) . padStart ( 4 , '0' ) + '-' +
394+ clockSeqHi . toString ( 16 ) . padStart ( 2 , '0' ) +
395+ clockSeqLow . toString ( 16 ) . padStart ( 2 , '0' ) + '-' +
396+ [ ...node ] . map ( b => b . toString ( 16 ) . padStart ( 2 , '0' ) ) . join ( '' )
397+ ) ;
390398 }
391399 return generateUUID ( '4' ) ;
392400 }
0 commit comments