export const now = () => Math.floor(Date.now() / 1000); export const DAY = 86400; const B36 = '0123456789abcdefghijklmnopqrstuvwxyz'; export function newId(len = 16): string { const bytes = crypto.getRandomValues(new Uint8Array(len)); let out = ''; for (const b of bytes) out += B36[b % 36]; return out; } export function b64url(bytes: Uint8Array): string { let s = ''; for (const b of bytes) s += String.fromCharCode(b); return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); } export function randomToken(bytes = 32): string { return b64url(crypto.getRandomValues(new Uint8Array(bytes))); } export function hex(buf: ArrayBuffer | Uint8Array): string { const a = buf instanceof Uint8Array ? buf : new Uint8Array(buf); let s = ''; for (const b of a) s += b.toString(16).padStart(2, '0'); return s; } export async function sha256Hex(data: string | Uint8Array | ArrayBuffer): Promise { const bytes = typeof data === 'string' ? new TextEncoder().encode(data) : data; return hex(await crypto.subtle.digest('SHA-256', bytes)); } export async function sha256B64url(data: string): Promise { return b64url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(data)))); } export async function hmacHex(secret: string, data: string): Promise { const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']); return hex(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(data))); } /** Constant-time string comparison. */ export function safeEqual(a: string, b: string): boolean { if (a.length !== b.length) return false; let diff = 0; for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i); return diff === 0; } export function slugify(input: string, max = 48): string { return input .normalize('NFKD') .replace(/[̀-ͯ]/g, '') .toLowerCase() .replace(/[^a-z0-9]+/g, '-') .replace(/^-+|-+$/g, '') .slice(0, max) .replace(/-+$/g, ''); } export function escapeHtml(s: string): string { return s.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, '''); } export function likeEscape(s: string): string { return s.replace(/[\\%_]/g, (m) => '\\' + m); } export function compactNumber(n: number): string { if (n < 1000) return String(n); if (n < 10000) return (n / 1000).toFixed(1).replace(/\.0$/, '') + 'k'; if (n < 1_000_000) return Math.round(n / 1000) + 'k'; return (n / 1_000_000).toFixed(1).replace(/\.0$/, '') + 'M'; } export function timeAgo(ts: number | null | undefined): string { if (!ts) return 'never'; const s = Math.max(0, now() - ts); if (s < 60) return 'just now'; if (s < 3600) return plural(Math.floor(s / 60), 'minute') + ' ago'; if (s < DAY) return plural(Math.floor(s / 3600), 'hour') + ' ago'; if (s < 30 * DAY) return plural(Math.floor(s / DAY), 'day') + ' ago'; if (s < 365 * DAY) return plural(Math.floor(s / (30 * DAY)), 'month') + ' ago'; return plural(Math.floor(s / (365 * DAY)), 'year') + ' ago'; } export function plural(n: number, word: string, pluralWord?: string): string { return `${n.toLocaleString('en-US')} ${n === 1 ? word : pluralWord ?? word + 's'}`; } export function dateLabel(ts: number): string { return new Date(ts * 1000).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric', timeZone: 'UTC' }); } export function clampInt(v: unknown, min: number, max: number, fallback: number): number { const n = typeof v === 'number' ? v : parseInt(String(v ?? ''), 10); if (!Number.isFinite(n)) return fallback; return Math.min(max, Math.max(min, Math.trunc(n))); } export function safeUrl(input: string | null | undefined): string | null { if (!input) return null; try { const u = new URL(input); return u.protocol === 'https:' || u.protocol === 'http:' ? u.toString() : null; } catch { return null; } } /** Only allow same-site relative redirect targets. */ export function safeNext(next: string | null | undefined, fallback = '/'): string { if (!next || !next.startsWith('/') || next.startsWith('//') || next.includes('\\')) return fallback; return next; } export class HttpError extends Error { constructor(public status: number, message: string, public code = 'error') { super(message); } }