@stats-organization/github-readme-stats-core 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -0
  3. package/build/api/gist.d.ts +19 -0
  4. package/build/api/gist.d.ts.map +1 -0
  5. package/build/api/gist.js +77 -0
  6. package/build/api/index.d.ts +37 -0
  7. package/build/api/index.d.ts.map +1 -0
  8. package/build/api/index.js +115 -0
  9. package/build/api/pin.d.ts +27 -0
  10. package/build/api/pin.d.ts.map +1 -0
  11. package/build/api/pin.js +104 -0
  12. package/build/api/top-langs.d.ts +31 -0
  13. package/build/api/top-langs.d.ts.map +1 -0
  14. package/build/api/top-langs.js +121 -0
  15. package/build/api/wakatime.d.ts +28 -0
  16. package/build/api/wakatime.d.ts.map +1 -0
  17. package/build/api/wakatime.js +85 -0
  18. package/build/calculateRank.d.ts +28 -0
  19. package/build/calculateRank.d.ts.map +1 -0
  20. package/build/calculateRank.js +63 -0
  21. package/build/cards/gist.d.ts +21 -0
  22. package/build/cards/gist.d.ts.map +1 -0
  23. package/build/cards/gist.js +124 -0
  24. package/build/cards/repo.d.ts +21 -0
  25. package/build/cards/repo.d.ts.map +1 -0
  26. package/build/cards/repo.js +264 -0
  27. package/build/cards/stats.d.ts +49 -0
  28. package/build/cards/stats.d.ts.map +1 -0
  29. package/build/cards/stats.js +527 -0
  30. package/build/cards/top-languages.d.ts +143 -0
  31. package/build/cards/top-languages.d.ts.map +1 -0
  32. package/build/cards/top-languages.js +795 -0
  33. package/build/cards/wakatime.d.ts +16 -0
  34. package/build/cards/wakatime.d.ts.map +1 -0
  35. package/build/cards/wakatime.js +387 -0
  36. package/build/common/Card.d.ts +109 -0
  37. package/build/common/Card.d.ts.map +1 -0
  38. package/build/common/Card.js +241 -0
  39. package/build/common/I18n.d.ts +26 -0
  40. package/build/common/I18n.d.ts.map +1 -0
  41. package/build/common/I18n.js +34 -0
  42. package/build/common/color.d.ts +53 -0
  43. package/build/common/color.d.ts.map +1 -0
  44. package/build/common/color.js +92 -0
  45. package/build/common/config.d.ts +3 -0
  46. package/build/common/config.d.ts.map +1 -0
  47. package/build/common/config.js +69 -0
  48. package/build/common/constants.d.ts +6 -0
  49. package/build/common/constants.d.ts.map +1 -0
  50. package/build/common/constants.js +7 -0
  51. package/build/common/error.d.ts +53 -0
  52. package/build/common/error.d.ts.map +1 -0
  53. package/build/common/error.js +72 -0
  54. package/build/common/fmt.d.ts +27 -0
  55. package/build/common/fmt.d.ts.map +1 -0
  56. package/build/common/fmt.js +66 -0
  57. package/build/common/html.d.ts +10 -0
  58. package/build/common/html.d.ts.map +1 -0
  59. package/build/common/html.js +18 -0
  60. package/build/common/http.d.ts +9 -0
  61. package/build/common/http.d.ts.map +1 -0
  62. package/build/common/http.js +18 -0
  63. package/build/common/icons.d.ts +26 -0
  64. package/build/common/icons.d.ts.map +1 -0
  65. package/build/common/icons.js +77 -0
  66. package/build/common/languageColors.json +667 -0
  67. package/build/common/log.d.ts +9 -0
  68. package/build/common/log.d.ts.map +1 -0
  69. package/build/common/log.js +8 -0
  70. package/build/common/ops.d.ts +65 -0
  71. package/build/common/ops.d.ts.map +1 -0
  72. package/build/common/ops.js +137 -0
  73. package/build/common/render.d.ts +155 -0
  74. package/build/common/render.d.ts.map +1 -0
  75. package/build/common/render.js +361 -0
  76. package/build/common/retryer.d.ts +22 -0
  77. package/build/common/retryer.d.ts.map +1 -0
  78. package/build/common/retryer.js +86 -0
  79. package/build/fetchers/gist.d.ts +26 -0
  80. package/build/fetchers/gist.d.ts.map +1 -0
  81. package/build/fetchers/gist.js +99 -0
  82. package/build/fetchers/repo.d.ts +16 -0
  83. package/build/fetchers/repo.d.ts.map +1 -0
  84. package/build/fetchers/repo.js +116 -0
  85. package/build/fetchers/stats.d.ts +22 -0
  86. package/build/fetchers/stats.d.ts.map +1 -0
  87. package/build/fetchers/stats.js +339 -0
  88. package/build/fetchers/top-languages.d.ts +20 -0
  89. package/build/fetchers/top-languages.d.ts.map +1 -0
  90. package/build/fetchers/top-languages.js +139 -0
  91. package/build/fetchers/wakatime.d.ts +11 -0
  92. package/build/fetchers/wakatime.d.ts.map +1 -0
  93. package/build/fetchers/wakatime.js +25 -0
  94. package/build/index.d.ts +20 -0
  95. package/build/index.d.ts.map +1 -0
  96. package/build/index.js +19 -0
  97. package/build/themes/index.d.ts +469 -0
  98. package/build/themes/index.d.ts.map +1 -0
  99. package/build/themes/index.js +468 -0
  100. package/build/translations.d.ts +533 -0
  101. package/build/translations.d.ts.map +1 -0
  102. package/build/translations.js +1140 -0
  103. package/package.json +94 -0
  104. package/src/api/gist.js +99 -0
  105. package/src/api/index.js +185 -0
  106. package/src/api/pin.js +146 -0
  107. package/src/api/top-langs.js +168 -0
  108. package/src/api/wakatime.js +113 -0
  109. package/src/calculateRank.js +86 -0
  110. package/src/cards/gist.js +187 -0
  111. package/src/cards/repo.js +365 -0
  112. package/src/cards/stats.js +673 -0
  113. package/src/cards/top-languages.js +1023 -0
  114. package/src/cards/types.d.ts +78 -0
  115. package/src/cards/wakatime.js +471 -0
  116. package/src/common/Card.js +275 -0
  117. package/src/common/I18n.js +42 -0
  118. package/src/common/color.js +145 -0
  119. package/src/common/config.js +78 -0
  120. package/src/common/constants.js +9 -0
  121. package/src/common/error.js +90 -0
  122. package/src/common/fmt.js +80 -0
  123. package/src/common/html.js +22 -0
  124. package/src/common/http.js +21 -0
  125. package/src/common/icons.js +81 -0
  126. package/src/common/languageColors.json +667 -0
  127. package/src/common/log.ts +12 -0
  128. package/src/common/ops.js +172 -0
  129. package/src/common/render.js +442 -0
  130. package/src/common/retryer.js +104 -0
  131. package/src/fetchers/gist.js +114 -0
  132. package/src/fetchers/repo.js +165 -0
  133. package/src/fetchers/stats.js +478 -0
  134. package/src/fetchers/top-languages.js +177 -0
  135. package/src/fetchers/types.d.ts +128 -0
  136. package/src/fetchers/wakatime.js +37 -0
  137. package/src/index.ts +25 -0
  138. package/src/themes/README.md +229 -0
  139. package/src/themes/index.ts +476 -0
  140. package/src/translations.js +1156 -0
@@ -0,0 +1,116 @@
1
+ // @ts-check
2
+ import { MissingParamError } from "../common/error.js";
3
+ import { request } from "../common/http.js";
4
+ import { retryer } from "../common/retryer.js";
5
+ import { fetchRepoUserStats } from "./stats.js";
6
+ /**
7
+ * Repo data fetcher.
8
+ *
9
+ * @param {object} variables Fetcher variables.
10
+ * @param {string} token GitHub token.
11
+ * @returns {Promise<import('axios').AxiosResponse>} The response.
12
+ */
13
+ const fetcher = (variables, token) => {
14
+ return request({
15
+ query: `
16
+ fragment RepoInfo on Repository {
17
+ name
18
+ nameWithOwner
19
+ isPrivate
20
+ isArchived
21
+ isTemplate
22
+ stargazers {
23
+ totalCount
24
+ }
25
+ description
26
+ primaryLanguage {
27
+ color
28
+ id
29
+ name
30
+ }
31
+ forkCount
32
+ }
33
+ query getRepo($login: String!, $repo: String!) {
34
+ user(login: $login) {
35
+ repository(name: $repo) {
36
+ ...RepoInfo
37
+ }
38
+ }
39
+ organization(login: $login) {
40
+ repository(name: $repo) {
41
+ ...RepoInfo
42
+ }
43
+ }
44
+ }
45
+ `,
46
+ variables,
47
+ }, {
48
+ Authorization: `token ${token}`,
49
+ });
50
+ };
51
+ const urlExample = "/api/pin?username=USERNAME&amp;repo=REPO_NAME";
52
+ /**
53
+ * @typedef {import("./types").RepositoryData} RepositoryData Repository data.
54
+ */
55
+ /**
56
+ * Fetch repository data.
57
+ *
58
+ * @param {string} username GitHub username.
59
+ * @param {string} reponame GitHub repository name.
60
+ * @returns {Promise<RepositoryData>} Repository data.
61
+ */
62
+ const fetchRepo = async (username, reponame, include_prs_authored = false, include_prs_commented = false, include_prs_reviewed = false, include_issues_authored = false, include_issues_commented = false, pat = null) => {
63
+ let owner = username;
64
+ if (reponame && reponame.includes("/")) {
65
+ const [parsed_owner, parsed_repo] = reponame.split("/");
66
+ owner = parsed_owner;
67
+ reponame = parsed_repo;
68
+ }
69
+ if (owner && !username) {
70
+ username = owner;
71
+ }
72
+ if (username && !owner) {
73
+ owner = username;
74
+ }
75
+ if (!username && !reponame) {
76
+ throw new MissingParamError(["username", "repo"], urlExample);
77
+ }
78
+ if (!username) {
79
+ throw new MissingParamError(["username"], urlExample);
80
+ }
81
+ if (!reponame) {
82
+ throw new MissingParamError(["repo"], urlExample);
83
+ }
84
+ let res = await retryer(fetcher, { login: owner, repo: reponame }, pat);
85
+ const data = res.data.data;
86
+ if (!data.user && !data.organization) {
87
+ throw new Error("Not found");
88
+ }
89
+ const isUser = data.organization === null && data.user;
90
+ const isOrg = data.user === null && data.organization;
91
+ if (isUser) {
92
+ if (!data.user.repository || data.user.repository.isPrivate) {
93
+ throw new Error("User Repository Not found");
94
+ }
95
+ let repoUserStats = await fetchRepoUserStats(username, [owner + "/" + reponame], [], include_prs_authored, include_prs_commented, include_prs_reviewed, include_issues_authored, include_issues_commented, pat);
96
+ return {
97
+ ...repoUserStats,
98
+ ...data.user.repository,
99
+ starCount: data.user.repository.stargazers.totalCount,
100
+ };
101
+ }
102
+ if (isOrg) {
103
+ if (!data.organization.repository ||
104
+ data.organization.repository.isPrivate) {
105
+ throw new Error("Organization Repository Not found");
106
+ }
107
+ let repoUserStats = await fetchRepoUserStats(username, [owner + "/" + reponame], [], include_prs_authored, include_prs_commented, include_prs_reviewed, include_issues_authored, include_issues_commented, pat);
108
+ return {
109
+ ...repoUserStats,
110
+ ...data.organization.repository,
111
+ starCount: data.organization.repository.stargazers.totalCount,
112
+ };
113
+ }
114
+ throw new Error("Unexpected behavior");
115
+ };
116
+ export { fetchRepo };
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Fetch stats for a given username.
3
+ *
4
+ * @param {string} username GitHub username.
5
+ * @param {boolean} include_all_commits Include all commits.
6
+ * @param {string[]} exclude_repo Repositories to exclude.
7
+ * @param {boolean} include_merged_pull_requests Include merged pull requests.
8
+ * @param {boolean} include_discussions Include discussions.
9
+ * @param {boolean} include_discussions_answers Include discussions answers.
10
+ * @param {number|undefined} commits_year Year to count total commits
11
+ * @param {string[]} ownerAffiliations Owner affiliations. Default: OWNER.
12
+ * @returns {Promise<import("./types").StatsData>} Stats data.
13
+ */
14
+ export function fetchStats(username: string, include_all_commits: boolean | undefined, exclude_repo: string[] | undefined, include_merged_pull_requests: boolean | undefined, include_discussions: boolean | undefined, include_discussions_answers: boolean | undefined, commits_year: number | undefined, repo?: any[], owner?: any[], include_prs_authored?: boolean, include_prs_commented?: boolean, include_prs_reviewed?: boolean, include_issues_authored?: boolean, include_issues_commented?: boolean, ownerAffiliations?: string[], pat?: null): Promise<any>;
15
+ export function fetchRepoUserStats(username: any, repo: any, owner: any, include_prs_authored: any, include_prs_commented: any, include_prs_reviewed: any, include_issues_authored: any, include_issues_commented: any, pat: any): Promise<{
16
+ totalPRsAuthored: number;
17
+ totalPRsCommented: number;
18
+ totalPRsReviewed: number;
19
+ totalIssuesAuthored: number;
20
+ totalIssuesCommented: number;
21
+ }>;
22
+ //# sourceMappingURL=stats.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stats.d.ts","sourceRoot":"","sources":["../../src/fetchers/stats.js"],"names":[],"mappings":"AAuTA;;;;;;;;;;;;GAYG;AACH,qCAVW,MAAM,uBACN,OAAO,4BACP,MAAM,EAAE,4CACR,OAAO,mCACP,OAAO,2CACP,OAAO,4BACP,MAAM,GAAC,SAAS,2NAChB,MAAM,EAAE,eACN,OAAO,CAAC,GAA2B,CAAC,CAyJhD;AArOD;;;;;;GA+DC"}
@@ -0,0 +1,339 @@
1
+ // @ts-check
2
+ import axios from "axios";
3
+ import githubUsernameRegex from "github-username-regex";
4
+ import { calculateRank } from "../calculateRank.js";
5
+ import { getConfig } from "../common/config.js";
6
+ import { CustomError, MissingParamError } from "../common/error.js";
7
+ import { wrapTextMultiline } from "../common/fmt.js";
8
+ import { request } from "../common/http.js";
9
+ import { logger } from "../common/log.js";
10
+ import { buildSearchFilter, parseOwnerAffiliations } from "../common/ops.js";
11
+ import { retryer } from "../common/retryer.js";
12
+ // GraphQL queries.
13
+ const GRAPHQL_REPOS_FIELD = `
14
+ repositories(first: 100, after: $after, ownerAffiliations: $ownerAffiliations, orderBy: {direction: DESC, field: STARGAZERS}) {
15
+ totalCount
16
+ nodes {
17
+ name
18
+ stargazers {
19
+ totalCount
20
+ }
21
+ }
22
+ pageInfo {
23
+ hasNextPage
24
+ endCursor
25
+ }
26
+ }
27
+ `;
28
+ const GRAPHQL_REPOS_QUERY = `
29
+ query userInfo($login: String!, $after: String, $ownerAffiliations: [RepositoryAffiliation]) {
30
+ user(login: $login) {
31
+ ${GRAPHQL_REPOS_FIELD}
32
+ }
33
+ }
34
+ `;
35
+ const GRAPHQL_STATS_QUERY = `
36
+ query userInfo($login: String!, $after: String, $includeMergedPullRequests: Boolean!, $includeDiscussions: Boolean!, $includeDiscussionsAnswers: Boolean!, $startTime: DateTime = null, $ownerAffiliations: [RepositoryAffiliation]) {
37
+ user(login: $login) {
38
+ name
39
+ login
40
+ commits: contributionsCollection (from: $startTime) {
41
+ totalCommitContributions,
42
+ }
43
+ reviews: contributionsCollection {
44
+ totalPullRequestReviewContributions
45
+ }
46
+ repositoriesContributedTo(first: 1, contributionTypes: [COMMIT, ISSUE, PULL_REQUEST, REPOSITORY]) {
47
+ totalCount
48
+ }
49
+ pullRequests(first: 1) {
50
+ totalCount
51
+ }
52
+ mergedPullRequests: pullRequests(states: MERGED) @include(if: $includeMergedPullRequests) {
53
+ totalCount
54
+ }
55
+ openIssues: issues(states: OPEN) {
56
+ totalCount
57
+ }
58
+ closedIssues: issues(states: CLOSED) {
59
+ totalCount
60
+ }
61
+ followers {
62
+ totalCount
63
+ }
64
+ repositoryDiscussions @include(if: $includeDiscussions) {
65
+ totalCount
66
+ }
67
+ repositoryDiscussionComments(onlyAnswers: true) @include(if: $includeDiscussionsAnswers) {
68
+ totalCount
69
+ }
70
+ ${GRAPHQL_REPOS_FIELD}
71
+ }
72
+ }
73
+ `;
74
+ /**
75
+ * Stats fetcher object.
76
+ *
77
+ * @param {object & { after: string | null }} variables Fetcher variables.
78
+ * @param {string} token GitHub token.
79
+ * @returns {Promise<import('axios').AxiosResponse>} Axios response.
80
+ */
81
+ const fetcher = (variables, token) => {
82
+ const query = variables.after ? GRAPHQL_REPOS_QUERY : GRAPHQL_STATS_QUERY;
83
+ return request({
84
+ query,
85
+ variables,
86
+ }, {
87
+ Authorization: `bearer ${token}`,
88
+ });
89
+ };
90
+ /**
91
+ * Fetch stats information for a given username.
92
+ *
93
+ * @param {object} variables Fetcher variables.
94
+ * @param {string} variables.username GitHub username.
95
+ * @param {boolean} variables.includeMergedPullRequests Include merged pull requests.
96
+ * @param {boolean} variables.includeDiscussions Include discussions.
97
+ * @param {boolean} variables.includeDiscussionsAnswers Include discussions answers.
98
+ * @param {string|undefined} variables.startTime Time to start the count of total commits.
99
+ * @param {string[]} variables.ownerAffiliations The owner affiliations to filter by. Default: OWNER.
100
+ * @param {string | null} variables.pat PAT override or null.
101
+ * @returns {Promise<import('axios').AxiosResponse>} Axios response.
102
+ *
103
+ * @description This function supports multi-page fetching if the 'FETCH_MULTI_PAGE_STARS' environment variable is set to true or a limit of fetches.
104
+ */
105
+ const statsFetcher = async ({ username, includeMergedPullRequests, includeDiscussions, includeDiscussionsAnswers, startTime, ownerAffiliations, pat, }) => {
106
+ let stats;
107
+ let hasNextPage = true;
108
+ let endCursor = null;
109
+ let fetchedPages = 0;
110
+ while (hasNextPage) {
111
+ const variables = {
112
+ login: username,
113
+ first: 100,
114
+ after: endCursor,
115
+ includeMergedPullRequests,
116
+ includeDiscussions,
117
+ includeDiscussionsAnswers,
118
+ startTime,
119
+ ownerAffiliations,
120
+ };
121
+ let res = await retryer(fetcher, variables, pat);
122
+ if (res.data.errors) {
123
+ return res;
124
+ }
125
+ // Store stats data.
126
+ const repoNodes = res.data.data.user.repositories.nodes;
127
+ if (stats) {
128
+ if (fetchedPages === 1) {
129
+ // make deep copy of relevant stats fields to avoid altering the cached response object in frontend
130
+ stats = structuredClone({
131
+ data: stats.data,
132
+ statusText: stats.statusText,
133
+ });
134
+ }
135
+ stats.data.data.user.repositories.nodes.push(...repoNodes);
136
+ }
137
+ else {
138
+ stats = res;
139
+ }
140
+ // Disable multi page fetching on public Vercel instance due to rate limits.
141
+ fetchedPages++;
142
+ const repoNodesWithStars = repoNodes.filter((node) => node.stargazers.totalCount !== 0);
143
+ hasNextPage =
144
+ (getConfig().fetchMultiPageStars === "true" ||
145
+ getConfig().fetchMultiPageStars > fetchedPages) &&
146
+ repoNodes.length === repoNodesWithStars.length &&
147
+ res.data.data.user.repositories.pageInfo.hasNextPage;
148
+ endCursor = res.data.data.user.repositories.pageInfo.endCursor;
149
+ }
150
+ return stats;
151
+ };
152
+ /**
153
+ * Fetch total commits using the REST API.
154
+ *
155
+ * @param {object} variables Fetcher variables.
156
+ * @param {string} token GitHub token.
157
+ * @returns {Promise<import('axios').AxiosResponse>} Axios response.
158
+ *
159
+ * @see https://developer.github.com/v3/search/#search-commits
160
+ */
161
+ const fetchTotalItems = (variables, token) => {
162
+ return axios({
163
+ method: "get",
164
+ url: `https://api.github.com/search/` +
165
+ variables.type +
166
+ `?per_page=1&q=` +
167
+ buildSearchFilter(variables.repo, variables.owner).replaceAll(" ", "+") +
168
+ variables.filter,
169
+ headers: {
170
+ "Content-Type": "application/json",
171
+ Accept: "application/vnd.github.cloak-preview",
172
+ Authorization: `token ${token}`,
173
+ },
174
+ });
175
+ };
176
+ /**
177
+ * Fetch all the commits for all the repositories of a given username.
178
+ *
179
+ * @param {string} username GitHub username.
180
+ * @returns {Promise<number>} Total commits.
181
+ *
182
+ * @description Done like this because the GitHub API does not provide a way to fetch all the commits. See
183
+ * #92#issuecomment-661026467 and #211 for more information.
184
+ */
185
+ const totalItemsFetcher = async (username, repo, owner, type, filter, pat) => {
186
+ if (!githubUsernameRegex.test(username)) {
187
+ logger.log("Invalid username provided.");
188
+ throw new Error("Invalid username provided.");
189
+ }
190
+ let res;
191
+ try {
192
+ res = await retryer(fetchTotalItems, {
193
+ login: username,
194
+ repo,
195
+ owner,
196
+ type,
197
+ filter,
198
+ }, pat);
199
+ }
200
+ catch (err) {
201
+ logger.log(err);
202
+ throw err;
203
+ }
204
+ const totalCount = res.data.total_count;
205
+ if (isNaN(totalCount)) {
206
+ logger.error("GitHub error: " + JSON.stringify(res.data));
207
+ throw new CustomError("Could not fetch data from GitHub REST API.", CustomError.GITHUB_REST_API_ERROR);
208
+ }
209
+ return totalCount;
210
+ };
211
+ const fetchRepoUserStats = async (username, repo, owner, include_prs_authored, include_prs_commented, include_prs_reviewed, include_issues_authored, include_issues_commented, pat) => {
212
+ let stats = {};
213
+ if (include_prs_authored) {
214
+ stats.totalPRsAuthored = await totalItemsFetcher(username, repo, owner, "issues", `author:${username}+type:pr`, pat);
215
+ }
216
+ if (include_prs_commented) {
217
+ stats.totalPRsCommented = await totalItemsFetcher(username, repo, owner, "issues", `commenter:${username}+-author:${username}+type:pr`, pat);
218
+ }
219
+ if (include_prs_reviewed) {
220
+ stats.totalPRsReviewed = await totalItemsFetcher(username, repo, owner, "issues", `reviewed-by:${username}+-author:${username}+type:pr`, pat);
221
+ }
222
+ if (include_issues_authored) {
223
+ stats.totalIssuesAuthored = await totalItemsFetcher(username, repo, owner, "issues", `author:${username}+type:issue`, pat);
224
+ }
225
+ if (include_issues_commented) {
226
+ stats.totalIssuesCommented = await totalItemsFetcher(username, repo, owner, "issues", `commenter:${username}+-author:${username}+type:issue`, pat);
227
+ }
228
+ return stats;
229
+ };
230
+ /**
231
+ * Fetch stats for a given username.
232
+ *
233
+ * @param {string} username GitHub username.
234
+ * @param {boolean} include_all_commits Include all commits.
235
+ * @param {string[]} exclude_repo Repositories to exclude.
236
+ * @param {boolean} include_merged_pull_requests Include merged pull requests.
237
+ * @param {boolean} include_discussions Include discussions.
238
+ * @param {boolean} include_discussions_answers Include discussions answers.
239
+ * @param {number|undefined} commits_year Year to count total commits
240
+ * @param {string[]} ownerAffiliations Owner affiliations. Default: OWNER.
241
+ * @returns {Promise<import("./types").StatsData>} Stats data.
242
+ */
243
+ const fetchStats = async (username, include_all_commits = false, exclude_repo = [], include_merged_pull_requests = false, include_discussions = false, include_discussions_answers = false, commits_year, repo = [], owner = [], include_prs_authored = false, include_prs_commented = false, include_prs_reviewed = false, include_issues_authored = false, include_issues_commented = false, ownerAffiliations = [], pat = null) => {
244
+ if (!username) {
245
+ throw new MissingParamError(["username"]);
246
+ }
247
+ const stats = {
248
+ name: "",
249
+ totalPRs: 0,
250
+ totalPRsMerged: 0,
251
+ mergedPRsPercentage: 0,
252
+ totalReviews: 0,
253
+ totalCommits: 0,
254
+ totalIssues: 0,
255
+ totalStars: 0,
256
+ totalDiscussionsStarted: 0,
257
+ totalDiscussionsAnswered: 0,
258
+ contributedTo: 0,
259
+ totalPRsAuthored: 0,
260
+ totalPRsCommented: 0,
261
+ totalPRsReviewed: 0,
262
+ totalIssuesAuthored: 0,
263
+ totalIssuesCommented: 0,
264
+ rank: { level: "C", percentile: 100 },
265
+ };
266
+ ownerAffiliations = parseOwnerAffiliations(ownerAffiliations);
267
+ let res = await statsFetcher({
268
+ username,
269
+ includeMergedPullRequests: include_merged_pull_requests,
270
+ includeDiscussions: include_discussions,
271
+ includeDiscussionsAnswers: include_discussions_answers,
272
+ startTime: commits_year ? `${commits_year}-01-01T00:00:00Z` : undefined,
273
+ ownerAffiliations,
274
+ }, pat);
275
+ // Catch GraphQL errors.
276
+ if (res.data.errors) {
277
+ logger.error(res.data.errors);
278
+ if (res.data.errors[0].type === "NOT_FOUND") {
279
+ throw new CustomError(res.data.errors[0].message || "Could not fetch user.", CustomError.USER_NOT_FOUND);
280
+ }
281
+ if (res.data.errors[0].message) {
282
+ throw new CustomError(wrapTextMultiline(res.data.errors[0].message, 525, 12)[0], res.statusText);
283
+ }
284
+ throw new CustomError("Something went wrong while trying to retrieve the stats data using the GraphQL API.", CustomError.GRAPHQL_ERROR);
285
+ }
286
+ const user = res.data.data.user;
287
+ stats.name = user.name || user.login;
288
+ // if include_all_commits, fetch all commits using the REST API.
289
+ if (include_all_commits) {
290
+ stats.totalCommits = await totalItemsFetcher(username, repo, owner, "commits", `author:${username}`, pat);
291
+ }
292
+ else {
293
+ stats.totalCommits = user.commits.totalCommitContributions;
294
+ }
295
+ let repoUserStats = await fetchRepoUserStats(username, repo, owner, include_prs_authored, include_prs_commented, include_prs_reviewed, include_issues_authored, include_issues_commented, pat);
296
+ Object.assign(stats, repoUserStats);
297
+ stats.totalPRs = user.pullRequests.totalCount;
298
+ if (include_merged_pull_requests) {
299
+ stats.totalPRsMerged = user.mergedPullRequests.totalCount;
300
+ stats.mergedPRsPercentage =
301
+ (user.mergedPullRequests.totalCount / user.pullRequests.totalCount) *
302
+ 100 || 0;
303
+ }
304
+ stats.totalReviews = user.reviews.totalPullRequestReviewContributions;
305
+ stats.totalIssues = user.openIssues.totalCount + user.closedIssues.totalCount;
306
+ if (include_discussions) {
307
+ stats.totalDiscussionsStarted = user.repositoryDiscussions.totalCount;
308
+ }
309
+ if (include_discussions_answers) {
310
+ stats.totalDiscussionsAnswered =
311
+ user.repositoryDiscussionComments.totalCount;
312
+ }
313
+ stats.contributedTo = user.repositoriesContributedTo.totalCount;
314
+ // Retrieve stars while filtering out repositories to be hidden.
315
+ const allExcludedRepos = [
316
+ ...exclude_repo,
317
+ ...getConfig().excludeRepositories,
318
+ ];
319
+ let repoToHide = new Set(allExcludedRepos);
320
+ stats.totalStars = user.repositories.nodes
321
+ .filter((data) => {
322
+ return !repoToHide.has(data.name);
323
+ })
324
+ .reduce((prev, curr) => {
325
+ return prev + curr.stargazers.totalCount;
326
+ }, 0);
327
+ stats.rank = calculateRank({
328
+ all_commits: include_all_commits,
329
+ commits: stats.totalCommits,
330
+ prs: stats.totalPRs,
331
+ reviews: stats.totalReviews,
332
+ issues: stats.totalIssues,
333
+ repos: user.repositories.totalCount,
334
+ stars: stats.totalStars,
335
+ followers: user.followers.totalCount,
336
+ });
337
+ return stats;
338
+ };
339
+ export { fetchStats, fetchRepoUserStats };
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Top languages data.
3
+ */
4
+ export type TopLangData = any;
5
+ /**
6
+ * @typedef {import("./types").TopLangData} TopLangData Top languages data.
7
+ */
8
+ /**
9
+ * Fetch top languages for a given username.
10
+ *
11
+ * @param {string} username GitHub username.
12
+ * @param {string[]} exclude_repo List of repositories to exclude. Default: [].
13
+ * @param {number} size_weight Weightage to be given to size.
14
+ * @param {number} count_weight Weightage to be given to count.
15
+ * @param {string[]} ownerAffiliations The owner affiliations to filter by. Default: OWNER.
16
+ * @param {string|null} pat Optional PAT override.
17
+ * @returns {Promise<TopLangData>} Top languages data.
18
+ */
19
+ export function fetchTopLanguages(username: string, exclude_repo?: string[], size_weight?: number, count_weight?: number, ownerAffiliations?: string[], pat?: string | null): Promise<TopLangData>;
20
+ //# sourceMappingURL=top-languages.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"top-languages.d.ts","sourceRoot":"","sources":["../../src/fetchers/top-languages.js"],"names":[],"mappings":";;;;AAiDA;;GAEG;AAEH;;;;;;;;;;GAUG;AACH,4CARW,MAAM,iBACN,MAAM,EAAE,gBACR,MAAM,iBACN,MAAM,sBACN,MAAM,EAAE,QACR,MAAM,GAAC,IAAI,GACT,OAAO,CAAC,WAAW,CAAC,CAgHhC"}
@@ -0,0 +1,139 @@
1
+ // @ts-check
2
+ import { getConfig } from "../common/config.js";
3
+ import { CustomError, MissingParamError } from "../common/error.js";
4
+ import { wrapTextMultiline } from "../common/fmt.js";
5
+ import { request } from "../common/http.js";
6
+ import { logger } from "../common/log.js";
7
+ import { parseOwnerAffiliations } from "../common/ops.js";
8
+ import { retryer } from "../common/retryer.js";
9
+ /**
10
+ * Top languages fetcher object.
11
+ *
12
+ * @param {any} variables Fetcher variables.
13
+ * @param {string} token GitHub token.
14
+ * @returns {Promise<import("axios").AxiosResponse>} Languages fetcher response.
15
+ */
16
+ const fetcher = (variables, token) => {
17
+ return request({
18
+ query: `
19
+ query userInfo($login: String!, $ownerAffiliations: [RepositoryAffiliation]) {
20
+ user(login: $login) {
21
+ # do not fetch forks
22
+ repositories(ownerAffiliations: $ownerAffiliations, isFork: false, first: 100) {
23
+ nodes {
24
+ name
25
+ languages(first: 10, orderBy: {field: SIZE, direction: DESC}) {
26
+ edges {
27
+ size
28
+ node {
29
+ color
30
+ name
31
+ }
32
+ }
33
+ }
34
+ }
35
+ }
36
+ }
37
+ }
38
+ `,
39
+ variables,
40
+ }, {
41
+ Authorization: `token ${token}`,
42
+ });
43
+ };
44
+ /**
45
+ * @typedef {import("./types").TopLangData} TopLangData Top languages data.
46
+ */
47
+ /**
48
+ * Fetch top languages for a given username.
49
+ *
50
+ * @param {string} username GitHub username.
51
+ * @param {string[]} exclude_repo List of repositories to exclude. Default: [].
52
+ * @param {number} size_weight Weightage to be given to size.
53
+ * @param {number} count_weight Weightage to be given to count.
54
+ * @param {string[]} ownerAffiliations The owner affiliations to filter by. Default: OWNER.
55
+ * @param {string|null} pat Optional PAT override.
56
+ * @returns {Promise<TopLangData>} Top languages data.
57
+ */
58
+ const fetchTopLanguages = async (username, exclude_repo = [], size_weight = 1, count_weight = 0, ownerAffiliations = [], pat = null) => {
59
+ if (!username) {
60
+ throw new MissingParamError(["username"]);
61
+ }
62
+ ownerAffiliations = parseOwnerAffiliations(ownerAffiliations);
63
+ const res = await retryer(fetcher, {
64
+ login: username,
65
+ ownerAffiliations,
66
+ }, pat);
67
+ if (res.data.errors) {
68
+ logger.error(res.data.errors);
69
+ if (res.data.errors[0].type === "NOT_FOUND") {
70
+ throw new CustomError(res.data.errors[0].message || "Could not fetch user.", CustomError.USER_NOT_FOUND);
71
+ }
72
+ if (res.data.errors[0].message) {
73
+ throw new CustomError(wrapTextMultiline(res.data.errors[0].message, 525, 12)[0], res.statusText);
74
+ }
75
+ throw new CustomError("Something went wrong while trying to retrieve the language data using the GraphQL API.", CustomError.GRAPHQL_ERROR);
76
+ }
77
+ let repoNodes = res.data.data.user.repositories.nodes;
78
+ /** @type {Record<string, boolean>} */
79
+ let repoToHide = {};
80
+ const allExcludedRepos = [
81
+ ...exclude_repo,
82
+ ...getConfig().excludeRepositories,
83
+ ];
84
+ // populate repoToHide map for quick lookup
85
+ // while filtering out
86
+ if (allExcludedRepos) {
87
+ allExcludedRepos.forEach((repoName) => {
88
+ repoToHide[repoName] = true;
89
+ });
90
+ }
91
+ // filter out repositories to be hidden
92
+ repoNodes = repoNodes
93
+ .sort((a, b) => b.size - a.size)
94
+ .filter((name) => !repoToHide[name.name]);
95
+ let repoCount = 0;
96
+ repoNodes = repoNodes
97
+ .filter((node) => node.languages.edges.length > 0)
98
+ // flatten the list of language nodes
99
+ .reduce((acc, curr) => curr.languages.edges.concat(acc), [])
100
+ .reduce((acc, prev) => {
101
+ // get the size of the language (bytes)
102
+ let langSize = prev.size;
103
+ // if we already have the language in the accumulator
104
+ // & the current language name is same as previous name
105
+ // add the size to the language size and increase repoCount.
106
+ if (acc[prev.node.name] && prev.node.name === acc[prev.node.name].name) {
107
+ langSize = prev.size + acc[prev.node.name].size;
108
+ repoCount += 1;
109
+ }
110
+ else {
111
+ // reset repoCount to 1
112
+ // language must exist in at least one repo to be detected
113
+ repoCount = 1;
114
+ }
115
+ return {
116
+ ...acc,
117
+ [prev.node.name]: {
118
+ name: prev.node.name,
119
+ color: prev.node.color,
120
+ size: langSize,
121
+ count: repoCount,
122
+ },
123
+ };
124
+ }, {});
125
+ Object.keys(repoNodes).forEach((name) => {
126
+ // comparison index calculation
127
+ repoNodes[name].size =
128
+ Math.pow(repoNodes[name].size, size_weight) *
129
+ Math.pow(repoNodes[name].count, count_weight);
130
+ });
131
+ const topLangs = Object.keys(repoNodes)
132
+ .sort((a, b) => repoNodes[b].size - repoNodes[a].size)
133
+ .reduce((result, key) => {
134
+ result[key] = repoNodes[key];
135
+ return result;
136
+ }, {});
137
+ return topLangs;
138
+ };
139
+ export { fetchTopLanguages };
@@ -0,0 +1,11 @@
1
+ /**
2
+ * WakaTime data fetcher.
3
+ *
4
+ * @param {{username: string, api_domain: string }} props Fetcher props.
5
+ * @returns {Promise<import("./types").WakaTimeData>} WakaTime data response.
6
+ */
7
+ export function fetchWakatimeStats({ username, api_domain }: {
8
+ username: string;
9
+ api_domain: string;
10
+ }): Promise<any>;
11
+ //# sourceMappingURL=wakatime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wakatime.d.ts","sourceRoot":"","sources":["../../src/fetchers/wakatime.js"],"names":[],"mappings":"AAMA;;;;;GAKG;AACH,6DAHW;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,GACrC,OAAO,CAAC,GAA8B,CAAC,CAwBnD"}
@@ -0,0 +1,25 @@
1
+ // @ts-check
2
+ import axios from "axios";
3
+ import { CustomError, MissingParamError } from "../common/error.js";
4
+ /**
5
+ * WakaTime data fetcher.
6
+ *
7
+ * @param {{username: string, api_domain: string }} props Fetcher props.
8
+ * @returns {Promise<import("./types").WakaTimeData>} WakaTime data response.
9
+ */
10
+ const fetchWakatimeStats = async ({ username, api_domain }) => {
11
+ if (!username) {
12
+ throw new MissingParamError(["username"]);
13
+ }
14
+ try {
15
+ const { data } = await axios.get(`https://${api_domain ? api_domain.replace(/\/$/gi, "") : "wakatime.com"}/api/v1/users/${username}/stats?is_including_today=true`);
16
+ return data.data;
17
+ }
18
+ catch (err) {
19
+ if (err.response.status < 200 || err.response.status > 299) {
20
+ throw new CustomError(`Could not resolve to a User with the login of '${username}'`, "WAKATIME_USER_NOT_FOUND");
21
+ }
22
+ throw err;
23
+ }
24
+ };
25
+ export { fetchWakatimeStats };