-
-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
de10004
commit 2c92216
Showing
14 changed files
with
883 additions
and
67 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -27,4 +27,4 @@ logs | |
|
||
# misc | ||
# add other ignore file below | ||
lib | ||
**/**/makeQuery.ts |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
import { parse } from 'node-html-parser'; | ||
|
||
import type { Sponsorship } from '../types'; | ||
|
||
export interface GetPastSponsorsOptions { | ||
/** | ||
* @default false | ||
*/ | ||
includePrivate?: boolean; | ||
} | ||
|
||
function pickSponsorsInfo(html: string): Sponsorship[] { | ||
const root = parse(html); | ||
const baseDate = new Date('2000-1-1'); | ||
const sponsors = root.querySelectorAll('div').map((el) => { | ||
const isPublic = el.querySelector('img'); | ||
const name = isPublic ? isPublic?.getAttribute('alt')?.replace('@', '') : 'Private Sponsor'; | ||
const avatarUrl = isPublic ? isPublic?.getAttribute('src') : ''; | ||
const login = isPublic | ||
? el.querySelector('a')?.getAttribute('href')?.replace('/', '') | ||
: undefined; | ||
const type = el | ||
.querySelector('a') | ||
?.getAttribute('data-hovercard-type') | ||
?.replace(/^\S/, (s) => s.toUpperCase()); | ||
|
||
return { | ||
createdAt: baseDate.toUTCString(), | ||
isOneTime: undefined, | ||
monthlyDollars: -1, | ||
privacyLevel: isPublic ? 'PUBLIC' : 'PRIVATE', | ||
sponsor: { | ||
__typename: undefined, | ||
avatarUrl, | ||
linkUrl: `https://github.com/${name}`, | ||
login, | ||
name, | ||
type, | ||
}, | ||
tierName: undefined, | ||
} as Sponsorship; | ||
}); | ||
|
||
return sponsors; | ||
} | ||
|
||
export async function getPastSponsors(username: string): Promise<Sponsorship[]> { | ||
const allSponsors: Sponsorship[] = []; | ||
let newSponsors = []; | ||
let cursor = 1; | ||
|
||
do { | ||
const res = await fetch( | ||
`https://github.com/sponsors/${username}/sponsors_partial?filter=inactive&page=${cursor++}`, | ||
{ method: 'GET' }, | ||
); | ||
const content = await res.text(); | ||
newSponsors = pickSponsorsInfo(content); | ||
allSponsors.push(...newSponsors); | ||
} while (newSponsors.length); | ||
|
||
return allSponsors; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
import type { Provider, SponsorkitConfig, Sponsorship } from '../types'; | ||
import { getPastSponsors } from './get-past-sponsors'; | ||
import { makeQuery } from './makeQuery'; | ||
|
||
const API = 'https://api.github.com/graphql'; | ||
|
||
export async function fetchGitHubSponsors( | ||
token: string, | ||
login: string, | ||
type: string, | ||
config: SponsorkitConfig, | ||
): Promise<Sponsorship[]> { | ||
if (!token) throw new Error('GitHub token is required'); | ||
if (!login) throw new Error('GitHub login is required'); | ||
if (!['user', 'organization'].includes(type)) | ||
throw new Error('GitHub type must be either `user` or `organization`'); | ||
|
||
const sponsors: Sponsorship[] = []; | ||
let cursor; | ||
|
||
do { | ||
const query = makeQuery(login, type, cursor); | ||
const res = await fetch(API, { | ||
body: JSON.stringify({ query }), | ||
headers: { | ||
'Authorization': `bearer ${token}`, | ||
'Content-Type': 'application/json', | ||
}, | ||
method: 'POST', | ||
}); | ||
|
||
const data = await res.json(); | ||
|
||
if (!data) throw new Error(`Get no response on requesting ${API}`); | ||
else if (data.errors?.[0]?.type === 'INSUFFICIENT_SCOPES') | ||
throw new Error('Token is missing the `read:user` and/or `read:org` scopes'); | ||
else if (data.errors?.length) | ||
throw new Error(`GitHub API error:\n${JSON.stringify(data.errors, null, 2)}`); | ||
|
||
sponsors.push(...(data.data[type].sponsorshipsAsMaintainer.nodes || [])); | ||
if (data.data[type].sponsorshipsAsMaintainer.pageInfo.hasNextPage) | ||
cursor = data.data[type].sponsorshipsAsMaintainer.pageInfo.endCursor; | ||
else cursor = undefined; | ||
} while (cursor); | ||
|
||
const processed = sponsors.map( | ||
(raw: any): Sponsorship => ({ | ||
createdAt: raw.createdAt, | ||
isOneTime: raw.tier.isOneTime, | ||
monthlyDollars: raw.tier.monthlyPriceInDollars, | ||
privacyLevel: raw.privacyLevel, | ||
sponsor: { | ||
...raw.sponsorEntity, | ||
__typename: undefined, | ||
linkUrl: `https://github.com/${raw.sponsorEntity.login}`, | ||
type: raw.sponsorEntity.__typename, | ||
}, | ||
tierName: raw.tier.name, | ||
}), | ||
); | ||
|
||
if (config.includePastSponsors) { | ||
try { | ||
processed.push(...(await getPastSponsors(login))); | ||
} catch (error) { | ||
console.error('Failed to fetch past sponsors:', error); | ||
} | ||
} | ||
|
||
return processed; | ||
} | ||
|
||
export const GitHubProvider: Provider = { | ||
fetchSponsors(config) { | ||
return fetchGitHubSponsors( | ||
config.github?.token || config.token!, | ||
config.github?.login || config.login!, | ||
config.github?.type || 'user', | ||
config, | ||
); | ||
}, | ||
name: 'github', | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
const graphql = String.raw; | ||
|
||
export function makeQuery(login: string, type: string, cursor?: string) { | ||
return graphql`{ | ||
${type}(login: "${login}") { | ||
sponsorshipsAsMaintainer(first: 100${cursor ? ` after: "${cursor}"` : ''}) { | ||
totalCount | ||
pageInfo { | ||
endCursor | ||
hasNextPage | ||
} | ||
nodes { | ||
createdAt | ||
privacyLevel | ||
tier { | ||
name | ||
isOneTime | ||
monthlyPriceInCents | ||
monthlyPriceInDollars | ||
} | ||
sponsorEntity { | ||
__typename | ||
...on Organization { | ||
login | ||
name | ||
avatarUrl | ||
websiteUrl | ||
} | ||
...on User { | ||
login | ||
name | ||
avatarUrl | ||
websiteUrl | ||
} | ||
} | ||
} | ||
} | ||
} | ||
}`; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
import { GitHubProvider } from './github'; | ||
import { OpenCollectiveProvider } from './opencollective'; | ||
import type { Provider, ProviderName, SponsorkitConfig } from './types'; | ||
|
||
export * from './github'; | ||
|
||
export const ProvidersMap = { | ||
github: GitHubProvider, | ||
opencollective: OpenCollectiveProvider, | ||
}; | ||
|
||
export function guessProviders(config: SponsorkitConfig) { | ||
const items: ProviderName[] = []; | ||
if (config.github && config.github.login) items.push('github'); | ||
|
||
if (config.patreon && config.patreon.token) items.push('patreon'); | ||
|
||
if ( | ||
config.opencollective && | ||
(config.opencollective.id || config.opencollective.slug || config.opencollective.githubHandle) | ||
) | ||
items.push('opencollective'); | ||
|
||
if (config.afdian && config.afdian.userId && config.afdian.token) items.push('afdian'); | ||
|
||
// fallback | ||
if (!items.length) items.push('github'); | ||
|
||
return items; | ||
} | ||
|
||
export function resolveProviders(names: (ProviderName | Provider)[]) { | ||
return [...new Set(names)].map((i) => { | ||
if (typeof i === 'string') { | ||
// @ts-ignore | ||
const provider = ProvidersMap[i]; | ||
if (!provider) throw new Error(`Unknown provider: ${i}`); | ||
return provider; | ||
} | ||
return i; | ||
}); | ||
} | ||
|
||
export async function fetchSponsors(config: SponsorkitConfig) { | ||
const providers = resolveProviders(guessProviders(config)); | ||
const sponsorships = await Promise.all( | ||
providers.map((provider) => provider.fetchSponsors(config)), | ||
); | ||
|
||
return sponsorships.flat(1); | ||
} |
Oops, something went wrong.