const LIMIT = /^\s*(?\d+(?:\.\d+)?)\s*(?b|kb|mb|gb|tb|pb)?\s*$/iu; const BYTES_PER_KIB = 1024; const BYTES_PER_MIB = BYTES_PER_KIB * BYTES_PER_KIB; const BYTES_PER_GIB = BYTES_PER_MIB * BYTES_PER_KIB; const BYTES_PER_TIB = BYTES_PER_GIB * BYTES_PER_KIB; const BYTES_PER_PIB = BYTES_PER_TIB * BYTES_PER_KIB; const UNITS = new Map([ ['b', 1], ['gb', BYTES_PER_GIB], ['kb', BYTES_PER_KIB], ['mb', BYTES_PER_MIB], ['pb', BYTES_PER_PIB], ['tb', BYTES_PER_TIB], ]); const toByteLimit = (limit: number | string): number => { if (typeof limit === 'number') return limit; const match = LIMIT.exec(limit); if (match === null) { throw new TypeError(`The body limit "${limit}" is not a size such as "100kb" or "1mb".`); } const { amount, unit } = match.groups ?? {}; const bytes = Number(amount ?? ''); const suffix = (unit ?? 'b').toLowerCase(); return Math.floor(bytes * (UNITS.get(suffix) ?? 1)); }; export { toByteLimit };