1- const SIMPLEFLAKE_EPOCH = 946684800000n ; // Date.UTC(2000, 0, 1)
1+ export const SIMPLEFLAKE_EPOCH = 946684800000n ; // Date.UTC(2000, 0, 1)
22const UNSIGNED_23BIT_MAX = 8388607 ;
33const RANDOM_BUFFER_SIZE = 1024 ;
44
@@ -18,6 +18,8 @@ interface RandomSource {
1818 getRandomValues < T extends ArrayBufferView > ( array : T ) : T ;
1919}
2020
21+ type NodeCryptoRequire = ( moduleName : string ) => { webcrypto : RandomSource } ;
22+
2123declare const require : ( ( moduleName : string ) => unknown ) | undefined ;
2224
2325const randomBuffer = new Uint32Array ( RANDOM_BUFFER_SIZE ) ;
@@ -45,16 +47,12 @@ function assertInRange(
4547}
4648
4749function getRandomSource ( ) : RandomSource {
48- const globalCrypto = ( globalThis as typeof globalThis & {
49- crypto ?: RandomSource ;
50- } ) . crypto ;
50+ const globalCrypto = ( globalThis as { crypto ?: RandomSource } ) . crypto ;
5151
5252 if ( globalCrypto ) return globalCrypto ;
5353
5454 try {
55- return ( require as ( moduleName : string ) => { webcrypto : RandomSource } ) (
56- [ "node" , "crypto" ] . join ( ":" )
57- ) . webcrypto ;
55+ return ( require as NodeCryptoRequire ) ( "node:crypto" ) . webcrypto ;
5856 } catch {
5957 throw new Error (
6058 "Cryptographically secure random values are unavailable in this environment."
@@ -72,7 +70,6 @@ function random23(): bigint {
7270 refillRandomBuffer ( ) ;
7371 }
7472 const value = randomBuffer [ randomBufferIndex ] ! ;
75-
7673 randomBufferIndex += 1 ;
7774 return BigInt ( value & UNSIGNED_23BIT_MAX ) ;
7875}
@@ -95,16 +92,9 @@ export function simpleflake(
9592 const resolvedRandomBits =
9693 randomBits == null ? random23 ( ) : toBigInt ( randomBits , "randomBits" ) ;
9794
98- assertInRange (
99- timestampOffset ,
100- 0n ,
101- SIMPLEFLAKE_TIMESTAMP_MAX ,
102- "timestamp - epoch"
103- ) ;
95+ assertInRange ( timestampOffset , 0n , SIMPLEFLAKE_TIMESTAMP_MAX , "timestamp - epoch" ) ;
10496 assertInRange ( resolvedRandomBits , 0n , SIMPLEFLAKE_RANDOM_MAX , "randomBits" ) ;
10597
106- // Use bitwise OR instead of addition since bit ranges don't overlap
107-
10898 return (
10999 ( timestampOffset << SIMPLEFLAKE_TIMESTAMP_SHIFT ) |
110100 resolvedRandomBits
@@ -190,10 +180,6 @@ export function parseSimpleflake(
190180 ) ;
191181}
192182
193- // Export constants
194- export { SIMPLEFLAKE_EPOCH } ;
195-
196- // Default export for CommonJS compatibility
197183export default {
198184 binary,
199185 extractBits,
0 commit comments