import { join, isAbsolute } from 'node:path'; import type { BodyParserConfig } from '#models/types'; import { createId } from '@paralleldrive/cuid2'; import { tmpdir } from 'node:os'; import config from '@adonisjs/core/services/config'; export function sum(a: number, b: number): number { return a + b; } export function getDomain(host: string): string { // $myhost = strtolower(trim($host)); let myHost: string = host.trim().toLocaleLowerCase(); // $count = substr_count($myhost, '.'); const count: number = myHost.split(',').length - 1; if (count == 2) { const words = myHost.split('.'); if (words[1].length > 3) { myHost = myHost.split('.', 2)[1]; } } else if (count > 2) { myHost = getDomain(myHost.split('.', 2)[1]); } myHost = myHost.replace(new RegExp(/^.*:\/\//i, 'g'), ''); return myHost; } export function preg_match(regex: RegExp, str: string) { const result: boolean = regex.test(str); return result; } /** * Returns the tmp path for storing the files temporarly */ export function getTmpPath(config: BodyParserConfig['multipart']): string { if (typeof config.tmpFileName === 'function') { const tmpPath = config.tmpFileName(); return isAbsolute(tmpPath) ? tmpPath : join(tmpdir(), tmpPath); } return join(tmpdir(), createId()); } /** * Returns config for a given type */ export function getConfigFor(type: K): BodyParserConfig[K] { const bodyParserConfig: BodyParserConfig = config.get('bodyparser'); const configType = bodyParserConfig[type]; return configType; } export function parseBytesSize(size: string): number { const units: Record = { kb: 1024, mb: 1024 * 1024, gb: 1024 * 1024 * 1024, tb: 1024 * 1024 * 1024 * 1024, }; const match = size.match(/^(\d+)(kb|mb|gb|tb)$/i); // Regex to match size format if (!match) { throw new Error('Invalid size format'); } const [, value, unit] = match; return parseInt(value) * units[unit.toLowerCase()]; } // Helper function to format bytes as human-readable text export function formatBytes(bytes: number): string { if (bytes === 0) return '0 Bytes'; const k = 1024; const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]; }