package websource import ( "regexp" "slices" "strings" ) // Mentions finds the web sources in a person's own words (Research spec // ยง2 step 2): every http or https URL as typed, and every bare domain (an // optional path after it) as https:///, each made canonical by // Parse, in the order written and once each. Anything Parse refuses is // left out, and so are e-mail addresses, parts of other URLs, names whose // last label is a common file extension (README.md, main.go, Next.js) and // abbreviations (e.g., i.e.). func Mentions(text string) []URL { type found struct { at int raw string } var all []found // Full URLs first; their text is then blanked so no part of one is // read again as a bare domain. rest := []byte(text) for _, m := range fullURL.FindAllStringIndex(text, -1) { all = append(all, found{m[0], trimTrailing(text[m[0]:m[1]])}) for i := m[0]; i < m[1]; i++ { rest[i] = ' ' } } plain := string(rest) for _, m := range bareDomain.FindAllStringIndex(plain, -1) { if m[0] > 0 && strings.ContainsRune("@/_:.-", rune(plain[m[0]-1])) || m[1] < len(plain) && plain[m[1]] == '@' { continue } raw := trimTrailing(plain[m[0]:m[1]]) host, path, _ := strings.Cut(raw, "/") labels := strings.Split(strings.ToLower(strings.TrimSuffix(host, ".")), ".") last := labels[len(labels)-1] if len(last) < 2 || slices.Contains(fileExtensions, last) { continue } all = append(all, found{m[0], "https://" + host + "/" + path}) } slices.SortStableFunc(all, func(a, b found) int { return a.at - b.at }) var out []URL seen := map[string]bool{} for _, f := range all { u, err := Parse(f.raw) if err != nil || seen[u.String()] { continue } seen[u.String()] = true out = append(out, u) } return out } var ( fullURL = regexp.MustCompile(`(?i)\bhttps?://[^\s<>"'\x60]+`) bareDomain = regexp.MustCompile(`[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z][A-Za-z0-9-]*(?:/[^\s<>"'\x60]*)?`) ) // trimTrailing drops the punctuation that ends a sentence or a bracket // around a URL. func trimTrailing(s string) string { return strings.TrimRight(s, ".,;:!?)]}>'\"") } // fileExtensions are last labels that name a file far more often than a // site; a source with one is taken only when typed with its scheme. var fileExtensions = []string{"md", "mdx", "txt", "rst", "go", "mod", "sum", "sh", "py", "rs", "js", "jsx", "ts", "tsx", "mjs", "cjs", "json", "yaml", "yml", "toml", "ini", "cfg", "conf", "env", "lock", "html", "htm", "css", "scss", "rb", "php", "sql", "db", "sqlite", "png", "jpg", "jpeg", "gif", "svg", "webp", "ico", "pdf", "zip", "gz", "tar", "xml", "csv", "log", "swift", "kt", "java", "c", "h", "cpp", "hpp", "vue", "svelte", "lua", "pl", "ex", "exs", "hs", "ml", "dart", "plist", "tf", "hcl", "nix", "bak", "tmp", "so", "dll", "exe", "bin", "out", "ipynb", "gradle"}