forked from
tangled.org/core
Monorepo for Tangled — https://tangled.org
1package userutil
2
3import (
4 "regexp"
5 "strings"
6)
7
8func IsHandleNoAt(s string) bool {
9 // ref: https://atproto.com/specs/handle
10 re := regexp.MustCompile(`^([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])?$`)
11 return re.MatchString(s)
12}
13
14func UnflattenDid(s string) string {
15 if !IsFlattenedDid(s) {
16 return s
17 }
18
19 return strings.Replace(s, "-", ":", 2)
20}
21
22// IsFlattenedDid checks if the given string is a flattened DID.
23func IsFlattenedDid(s string) bool {
24 // Check if the string starts with "did-"
25 if !strings.HasPrefix(s, "did-") {
26 return false
27 }
28
29 // Reconstruct as a standard DID format using Replace
30 // Example: "did-plc-xyz-abc" becomes "did:plc:xyz-abc"
31 reconstructed := strings.Replace(s, "-", ":", 2)
32 re := regexp.MustCompile(`^did:[a-z]+:[a-zA-Z0-9._:%-]*[a-zA-Z0-9._-]$`)
33
34 return re.MatchString(reconstructed)
35}
36
37// FlattenDid converts a DID to a flattened format.
38// A flattened DID is a DID with the :s swapped to -s to satisfy certain
39// application requirements, such as Go module naming conventions.
40func FlattenDid(s string) string {
41 if IsDid(s) {
42 return strings.Replace(s, ":", "-", 2)
43 }
44 return s
45}
46
47// IsDid checks if the given string is a standard DID.
48func IsDid(s string) bool {
49 re := regexp.MustCompile(`^did:[a-z]+:[a-zA-Z0-9._:%-]*[a-zA-Z0-9._-]$`)
50 return re.MatchString(s)
51}