1+ /* @flow */
2+
13import { randomBytes } from 'crypto' ;
24
35// Returns a new random hex string of the given even size.
4- export function randomHexString ( size ) {
6+ export function randomHexString ( size : number ) : string {
57 if ( size === 0 ) {
68 throw new Error ( 'Zero-length randomHexString is useless.' ) ;
79 }
@@ -17,28 +19,28 @@ export function randomHexString(size) {
1719// because chars length of 62 doesn't divide the number of all bytes
1820// (256) evenly. Such bias is acceptable for most cases when the output
1921// length is long enough and doesn't need to be uniform.
20- export function randomString ( size ) {
22+ export function randomString ( size : number ) : string {
2123 if ( size === 0 ) {
2224 throw new Error ( 'Zero-length randomString is useless.' ) ;
2325 }
24- var chars = ( 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
26+ let chars = ( 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
2527 'abcdefghijklmnopqrstuvwxyz' +
2628 '0123456789' ) ;
27- var objectId = '' ;
28- var bytes = randomBytes ( size ) ;
29- for ( var i = 0 ; i < bytes . length ; ++ i ) {
29+ let objectId = '' ;
30+ let bytes = randomBytes ( size ) ;
31+ for ( let i = 0 ; i < bytes . length ; ++ i ) {
3032 objectId += chars [ bytes . readUInt8 ( i ) % chars . length ] ;
3133 }
3234 return objectId ;
3335}
3436
3537// Returns a new random alphanumeric string suitable for object ID.
36- export function newObjectId ( ) {
38+ export function newObjectId ( ) : string {
3739 //TODO: increase length to better protect against collisions.
3840 return randomString ( 10 ) ;
3941}
4042
4143// Returns a new random hex string suitable for secure tokens.
42- export function newToken ( ) {
44+ export function newToken ( ) : string {
4345 return randomHexString ( 32 ) ;
4446}
0 commit comments