Branchwell

Skillfarm / website · skillfarm.ai / src / lib / util.ts

Raw 4.3 KB on c724bfa127f7a93b48788385cedf1e60cb4e7943
1export const now = () => Math.floor(Date.now() / 1000);
2export const DAY = 86400;
3
4const B36 = '0123456789abcdefghijklmnopqrstuvwxyz';
5export 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
12export 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
18export function randomToken(bytes = 32): string {
19 return b64url(crypto.getRandomValues(new Uint8Array(bytes)));
20}
21
22export 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
29export 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
34export async function sha256B64url(data: string): Promise<string> {
35 return b64url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(data))));
36}
37
38export 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. */
44export 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
51export 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
62export function escapeHtml(s: string): string {
63 return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
64}
65
66export function likeEscape(s: string): string {
67 return s.replace(/[\\%_]/g, (m) => '\\' + m);
68}
69
70export 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
77export 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
88export function plural(n: number, word: string, pluralWord?: string): string {
89 return `${n.toLocaleString('en-US')} ${n === 1 ? word : pluralWord ?? word + 's'}`;
90}
91
92export function dateLabel(ts: number): string {
93 return new Date(ts * 1000).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric', timeZone: 'UTC' });
94}
95
96export 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
102export 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. */
113export function safeNext(next: string | null | undefined, fallback = '/'): string {
114 if (!next || !next.startsWith('/') || next.startsWith('//') || next.includes('\\')) return fallback;
115 return next;
116}
117
118export class HttpError extends Error {
119 constructor(public status: number, message: string, public code = 'error') {
120 super(message);
121 }
122}