mirror of https://git.lenooby09.tech/LeNooby09/social-app.git
1// Regex from the go implementation
2// https://github.com/bluesky-social/indigo/blob/main/atproto/syntax/handle.go#L10
3import {forceLTR} from 'lib/strings/bidi'
4
5const VALIDATE_REGEX =
6 /^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/
7
8export function makeValidHandle(str: string): string {
9 if (str.length > 20) {
10 str = str.slice(0, 20)
11 }
12 str = str.toLowerCase()
13 return str.replace(/^[^a-z0-9]+/g, '').replace(/[^a-z0-9-]/g, '')
14}
15
16export function createFullHandle(name: string, domain: string): string {
17 name = (name || '').replace(/[.]+$/, '')
18 domain = (domain || '').replace(/^[.]+/, '')
19 return `${name}.${domain}`
20}
21
22export function isInvalidHandle(handle: string): boolean {
23 return handle === 'handle.invalid'
24}
25
26export function sanitizeHandle(handle: string, prefix = ''): string {
27 return isInvalidHandle(handle)
28 ? '⚠Invalid Handle'
29 : forceLTR(`${prefix}${handle}`)
30}
31
32export interface IsValidHandle {
33 handleChars: boolean
34 hyphenStartOrEnd: boolean
35 frontLength: boolean
36 totalLength: boolean
37 overall: boolean
38}
39
40// More checks from https://github.com/bluesky-social/atproto/blob/main/packages/pds/src/handle/index.ts#L72
41export function validateHandle(str: string, userDomain: string): IsValidHandle {
42 const fullHandle = createFullHandle(str, userDomain)
43
44 const results = {
45 handleChars:
46 !str || (VALIDATE_REGEX.test(fullHandle) && !str.includes('.')),
47 hyphenStartOrEnd: !str.startsWith('-') && !str.endsWith('-'),
48 frontLength: str.length >= 3,
49 totalLength: fullHandle.length <= 253,
50 }
51
52 return {
53 ...results,
54 overall: !Object.values(results).includes(false),
55 }
56}