Skillfarm / website · skillfarm.ai / src / lib / util.ts
| 1 | export const now = () => Math.floor(Date.now() / 1000); |
| 2 | export const DAY = 86400; |
| 3 | |
| 4 | const B36 = '0123456789abcdefghijklmnopqrstuvwxyz'; |
| 5 | export function newId(len = 16): string { |
| 6 | const bytes = crypto.getRandomValues(new Uint8Array(len)); |
| 7 | let out = ''; |
| 8 | for (const b of bytes) out += B36[b % 36]; |
| 9 | return out; |
| 10 | } |
| 11 | |
| 12 | export function b64url(bytes: Uint8Array): string { |
| 13 | let s = ''; |
| 14 | for (const b of bytes) s += String.fromCharCode(b); |
| 15 | return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); |
| 16 | } |
| 17 | |
| 18 | export function randomToken(bytes = 32): string { |
| 19 | return b64url(crypto.getRandomValues(new Uint8Array(bytes))); |
| 20 | } |
| 21 | |
| 22 | export function hex(buf: ArrayBuffer | Uint8Array): string { |
| 23 | const a = buf instanceof Uint8Array ? buf : new Uint8Array(buf); |
| 24 | let s = ''; |
| 25 | for (const b of a) s += b.toString(16).padStart(2, '0'); |
| 26 | return s; |
| 27 | } |
| 28 | |
| 29 | export async function sha256Hex(data: string | Uint8Array | ArrayBuffer): Promise<string> { |
| 30 | const bytes = typeof data === 'string' ? new TextEncoder().encode(data) : data; |
| 31 | return hex(await crypto.subtle.digest('SHA-256', bytes)); |
| 32 | } |
| 33 | |
| 34 | export async function sha256B64url(data: string): Promise<string> { |
| 35 | return b64url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(data)))); |
| 36 | } |
| 37 | |
| 38 | export async function hmacHex(secret: string, data: string): Promise<string> { |
| 39 | const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']); |
| 40 | return hex(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(data))); |
| 41 | } |
| 42 | |
| 43 | /** Constant-time string comparison. */ |
| 44 | export function safeEqual(a: string, b: string): boolean { |
| 45 | if (a.length !== b.length) return false; |
| 46 | let diff = 0; |
| 47 | for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i); |
| 48 | return diff === 0; |
| 49 | } |
| 50 | |
| 51 | export function slugify(input: string, max = 48): string { |
| 52 | return input |
| 53 | .normalize('NFKD') |
| 54 | .replace(/[̀-ͯ]/g, '') |
| 55 | .toLowerCase() |
| 56 | .replace(/[^a-z0-9]+/g, '-') |
| 57 | .replace(/^-+|-+$/g, '') |
| 58 | .slice(0, max) |
| 59 | .replace(/-+$/g, ''); |
| 60 | } |
| 61 | |
| 62 | export function escapeHtml(s: string): string { |
| 63 | return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, '''); |
| 64 | } |
| 65 | |
| 66 | export function likeEscape(s: string): string { |
| 67 | return s.replace(/[\\%_]/g, (m) => '\\' + m); |
| 68 | } |
| 69 | |
| 70 | export function compactNumber(n: number): string { |
| 71 | if (n < 1000) return String(n); |
| 72 | if (n < 10000) return (n / 1000).toFixed(1).replace(/\.0$/, '') + 'k'; |
| 73 | if (n < 1_000_000) return Math.round(n / 1000) + 'k'; |
| 74 | return (n / 1_000_000).toFixed(1).replace(/\.0$/, '') + 'M'; |
| 75 | } |
| 76 | |
| 77 | export function timeAgo(ts: number | null | undefined): string { |
| 78 | if (!ts) return 'never'; |
| 79 | const s = Math.max(0, now() - ts); |
| 80 | if (s < 60) return 'just now'; |
| 81 | if (s < 3600) return plural(Math.floor(s / 60), 'minute') + ' ago'; |
| 82 | if (s < DAY) return plural(Math.floor(s / 3600), 'hour') + ' ago'; |
| 83 | if (s < 30 * DAY) return plural(Math.floor(s / DAY), 'day') + ' ago'; |
| 84 | if (s < 365 * DAY) return plural(Math.floor(s / (30 * DAY)), 'month') + ' ago'; |
| 85 | return plural(Math.floor(s / (365 * DAY)), 'year') + ' ago'; |
| 86 | } |
| 87 | |
| 88 | export function plural(n: number, word: string, pluralWord?: string): string { |
| 89 | return `${n.toLocaleString('en-US')} ${n === 1 ? word : pluralWord ?? word + 's'}`; |
| 90 | } |
| 91 | |
| 92 | export function dateLabel(ts: number): string { |
| 93 | return new Date(ts * 1000).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric', timeZone: 'UTC' }); |
| 94 | } |
| 95 | |
| 96 | export function clampInt(v: unknown, min: number, max: number, fallback: number): number { |
| 97 | const n = typeof v === 'number' ? v : parseInt(String(v ?? ''), 10); |
| 98 | if (!Number.isFinite(n)) return fallback; |
| 99 | return Math.min(max, Math.max(min, Math.trunc(n))); |
| 100 | } |
| 101 | |
| 102 | export function safeUrl(input: string | null | undefined): string | null { |
| 103 | if (!input) return null; |
| 104 | try { |
| 105 | const u = new URL(input); |
| 106 | return u.protocol === 'https:' || u.protocol === 'http:' ? u.toString() : null; |
| 107 | } catch { |
| 108 | return null; |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | /** Only allow same-site relative redirect targets. */ |
| 113 | export function safeNext(next: string | null | undefined, fallback = '/'): string { |
| 114 | if (!next || !next.startsWith('/') || next.startsWith('//') || next.includes('\\')) return fallback; |
| 115 | return next; |
| 116 | } |
| 117 | |
| 118 | export class HttpError extends Error { |
| 119 | constructor(public status: number, message: string, public code = 'error') { |
| 120 | super(message); |
| 121 | } |
| 122 | } |