import { randomFill } from "crypto";
import { urlAlphabet } from "../url-alphabet/index.js";
export var random = function random(bytes) {
    return new Promise(function(resolve, reject) {
        randomFill(Buffer.allocUnsafe(bytes), function(err, buf) {
            if (err) {
                reject(err);
            } else {
                resolve(buf);
            }
        });
    });
};
export var customAlphabet = function customAlphabet(alphabet) {
    var defaultSize = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 21;
    var mask = (2 << 31 - Math.clz32(alphabet.length - 1 | 1)) - 1;
    var step = Math.ceil(1.6 * mask * defaultSize / alphabet.length);
    var tick = function tick1(id) {
        var size = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : defaultSize;
        return random(step).then(function(bytes) {
            var i = step;
            while(i--){
                id += alphabet[bytes[i] & mask] || '';
                if (id.length === size) return id;
            }
            return tick(id, size);
        });
    };
    return function(size) {
        return tick('', size);
    };
};
export var nanoid = function nanoid() {
    var size = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : 21;
    return random(size).then(function(bytes) {
        var id = '';
        while(size--){
            id += urlAlphabet[bytes[size] & 63];
        }
        return id;
    });
};
