Line data Source code
1 : import { uniq } from 'es-toolkit'
2 :
3 2355 : const GITHUB_REPO_URL =
4 : /^(?:git@github\.com:|(?:https?:\/\/)?(?:www\.)?github\.com\/)[a-z0-9-]+\/([\w.-]+?)(?:\.git)?(?:[/?#].*)?$/i
5 :
6 2355 : const BARE_REPO_SLUG = /^[A-Za-z0-9-]+\/([\w.-]+)$/
7 :
8 2355 : const COMPOUND_WORD_JOIN = /[A-Za-z0-9][-_][A-Za-z0-9]/
9 :
10 2355 : const SLASH_OR_SPACE = /[\s/]/
11 :
12 2355 : const GIT_SUFFIX = '.git'
13 :
14 2355 : const WORD_SEPARATORS = /[\s_-]+/
15 :
16 2355 : const WHITESPACE_RUN = /\s+/g
17 :
18 2 : function endsWithGitSuffix(input: string, end: number): boolean {
19 2 : const start = end - GIT_SUFFIX.length
20 2 : return start >= 0 && input.slice(start, end).toLowerCase() === GIT_SUFFIX
21 : }
22 :
23 18 : function stripTrailingRun(
24 : input: string,
25 : { stripGit }: { stripGit: boolean }
26 : ): string {
27 18 : let end = input.length
28 18 : while (end > 0) {
29 2 : if (SLASH_OR_SPACE.test(input[end - 1])) {
30 0 : end -= 1
31 2 : } else if (stripGit && endsWithGitSuffix(input, end)) {
32 0 : end -= GIT_SUFFIX.length
33 : } else {
34 2 : break
35 : }
36 : }
37 18 : return input.slice(0, end)
38 : }
39 :
40 18 : function bareCompoundRepoName(query: string): string | undefined {
41 18 : const repoName = BARE_REPO_SLUG.exec(query)?.[1]
42 18 : return repoName && COMPOUND_WORD_JOIN.test(repoName) ? repoName : undefined
43 : }
44 :
45 18 : function stripRepoOwner(query: string): string {
46 18 : return (
47 : GITHUB_REPO_URL.exec(query)?.[1] ?? bareCompoundRepoName(query) ?? query
48 : )
49 : }
50 :
51 18 : export function toRepoName(query: string): string {
52 18 : return stripRepoOwner(stripTrailingRun(query.trim(), { stripGit: true }))
53 : }
54 :
55 18 : export function splitOnSeparators(input: string): string {
56 18 : return input.split(WORD_SEPARATORS).filter(Boolean).join(' ')
57 : }
58 :
59 0 : function toComparableQuery(input: string): string {
60 0 : return stripTrailingRun(input.trim(), { stripGit: false }).replace(
61 : WHITESPACE_RUN,
62 : ' '
63 : )
64 : }
65 :
66 0 : export function buildPackSearchFallbacks(query: string): string[] {
67 0 : const comparableQuery = toComparableQuery(query)
68 0 : const repoName = toRepoName(query)
69 0 : return uniq([repoName, splitOnSeparators(repoName)]).filter(
70 : (candidate) =>
71 : candidate.length > 0 && toComparableQuery(candidate) !== comparableQuery
72 : )
73 : }
|