-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
357 lines (324 loc) · 11 KB
/
index.ts
File metadata and controls
357 lines (324 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
import { createApiBuilder, defineResource, type TModule } from "../core";
const GITHUB_API_BASE = "https://api.github.com";
const userResource = defineResource({
name: "users",
basePath: "/users",
methods: {
getUser: { path: "/{username}" },
getUserRepos: { path: "/{username}/repos" },
getUserGists: { path: "/{username}/gists" },
getUserFollowers: { path: "/{username}/followers" },
getUserFollowing: { path: "/{username}/following" },
getUserStarred: { path: "/{username}/starred" },
getUserOrgs: { path: "/{username}/orgs" },
getUserEvents: { path: "/{username}/events" },
getUserReceivedEvents: { path: "/{username}/received_events" },
checkUserFollowing: { path: "/{username}/following/{target}" },
},
});
const repoResource = defineResource({
name: "repos",
basePath: "/repos",
methods: {
getRepo: { path: "/{owner}/{repo}" },
getRepoCommits: { path: "/{owner}/{repo}/commits" },
getRepoCommit: { path: "/{owner}/{repo}/commits/{sha}" },
getRepoBranches: { path: "/{owner}/{repo}/branches" },
getRepoTags: { path: "/{owner}/{repo}/tags" },
getRepoReleases: { path: "/{owner}/{repo}/releases" },
getRepoLatestRelease: { path: "/{owner}/{repo}/releases/latest" },
getRepoContributors: { path: "/{owner}/{repo}/contributors" },
getRepoLanguages: { path: "/{owner}/{repo}/languages" },
getRepoTopics: { path: "/{owner}/{repo}/topics" },
getRepoStargazers: { path: "/{owner}/{repo}/stargazers" },
getRepoForks: { path: "/{owner}/{repo}/forks" },
getRepoIssues: { path: "/{owner}/{repo}/issues" },
getRepoIssue: { path: "/{owner}/{repo}/issues/{issue_number}" },
getRepoPulls: { path: "/{owner}/{repo}/pulls" },
getRepoPull: { path: "/{owner}/{repo}/pulls/{pull_number}" },
getRepoContents: { path: "/{owner}/{repo}/contents/{path}" },
getRepoReadme: { path: "/{owner}/{repo}/readme" },
createRepoIssue: {
path: "/{owner}/{repo}/issues",
method: "POST",
},
updateRepoIssue: {
path: "/{owner}/{repo}/issues/{issue_number}",
method: "PATCH",
},
createRepoPull: {
path: "/{owner}/{repo}/pulls",
method: "POST",
},
},
});
const searchResource = defineResource({
name: "search",
basePath: "/search",
methods: {
searchRepos: { path: "/repositories" },
searchCode: { path: "/code" },
searchIssues: { path: "/issues" },
searchUsers: { path: "/users" },
searchTopics: { path: "/topics" },
searchLabels: { path: "/labels" },
searchCommits: { path: "/commits" },
},
});
const gistResource = defineResource({
name: "gists",
basePath: "/gists",
methods: {
getPublicGists: { path: "" },
getUserGists: { path: "/users/{username}/gists" },
getGist: { path: "/{gist_id}" },
createGist: { path: "", method: "POST" },
updateGist: { path: "/{gist_id}", method: "PATCH" },
deleteGist: { path: "/{gist_id}", method: "DELETE" },
getGistComments: { path: "/{gist_id}/comments" },
createGistComment: { path: "/{gist_id}/comments", method: "POST" },
},
});
const orgResource = defineResource({
name: "orgs",
basePath: "/orgs",
methods: {
getOrg: { path: "/{org}" },
getOrgRepos: { path: "/{org}/repos" },
getOrgMembers: { path: "/{org}/members" },
getOrgTeams: { path: "/{org}/teams" },
getOrgProjects: { path: "/{org}/projects" },
getOrgEvents: { path: "/{org}/events" },
checkOrgMembership: { path: "/{org}/members/{username}" },
},
});
const activityResource = defineResource({
name: "activity",
basePath: "",
methods: {
getPublicEvents: { path: "/events" },
getNotifications: { path: "/notifications" },
markNotificationAsRead: {
path: "/notifications/{notification_id}",
method: "PATCH",
},
getStarred: { path: "/user/starred" },
starRepo: {
path: "/user/starred/{owner}/{repo}",
method: "PUT",
},
unstarRepo: {
path: "/user/starred/{owner}/{repo}",
method: "DELETE",
},
getWatching: { path: "/user/subscriptions" },
watchRepo: {
path: "/user/subscriptions/{owner}/{repo}",
method: "PUT",
},
unwatchRepo: {
path: "/user/subscriptions/{owner}/{repo}",
method: "DELETE",
},
},
});
const authUserResource = defineResource({
name: "me",
basePath: "/user",
methods: {
getAuthenticatedUser: { path: "" },
updateAuthenticatedUser: { path: "", method: "PATCH" },
getMyRepos: { path: "/repos" },
getMyOrgs: { path: "/orgs" },
getMyGists: { path: "/gists" },
getMyFollowers: { path: "/followers" },
getMyFollowing: { path: "/following" },
followUser: { path: "/following/{username}", method: "PUT" },
unfollowUser: { path: "/following/{username}", method: "DELETE" },
getMyEmails: { path: "/emails" },
getMySSHKeys: { path: "/keys" },
addSSHKey: { path: "/keys", method: "POST" },
deleteSSHKey: { path: "/keys/{key_id}", method: "DELETE" },
},
});
const statsResource = defineResource({
name: "stats",
basePath: "/repos/{owner}/{repo}/stats",
methods: {
getContributorStats: { path: "/contributors" },
getCommitActivity: { path: "/commit_activity" },
getCodeFrequency: { path: "/code_frequency" },
getParticipation: { path: "/participation" },
getPunchCard: { path: "/punch_card" },
},
});
const gitDataResource = defineResource({
name: "git",
basePath: "/repos/{owner}/{repo}/git",
methods: {
getRef: { path: "/ref/{ref}" },
getRefs: { path: "/refs" },
createRef: { path: "/refs", method: "POST" },
updateRef: { path: "/refs/{ref}", method: "PATCH" },
deleteRef: { path: "/refs/{ref}", method: "DELETE" },
getCommit: { path: "/commits/{commit_sha}" },
createCommit: { path: "/commits", method: "POST" },
getTree: { path: "/trees/{tree_sha}" },
createTree: { path: "/trees", method: "POST" },
getBlob: { path: "/blobs/{file_sha}" },
createBlob: { path: "/blobs", method: "POST" },
getTag: { path: "/tags/{tag_sha}" },
createTag: { path: "/tags", method: "POST" },
},
});
const resources = {
users: userResource,
repos: repoResource,
search: searchResource,
gists: gistResource,
orgs: orgResource,
activity: activityResource,
me: authUserResource,
stats: statsResource,
git: gitDataResource,
};
const buildGitHub = createApiBuilder({
baseUrl: GITHUB_API_BASE,
auth: { type: "bearer" as const },
headers: {
Accept: "application/vnd.github.v3+json",
"X-GitHub-Api-Version": "2022-11-28",
},
});
type TGitHubModule = TModule<typeof resources> & {
getUser: (username: string) => Promise<any>;
getRepository: (owner: string, repo: string) => Promise<any>;
getRepositoryFromUrl: (url: string) => Promise<any>;
getUserCommits: (username: string, options?: any) => Promise<any>;
getUserLatestCommit: (username: string) => Promise<any>;
getUserCommitsInTimeframe: (
username: string,
timeframe: string,
) => Promise<any>;
getRepositoryStars: (owner: string, repo: string) => Promise<number>;
getUserStarredCount: (username: string) => Promise<number>;
getUserStats: (username: string) => Promise<any>;
searchRepositories: (query: string, options?: any) => Promise<any>;
getUserActivity: (username: string, options?: any) => Promise<any>;
};
/**
* Create a configured GitHub API client module.
*
* Returns a GitHub API wrapper built from the shared resource definitions and the provided personal access token. The returned module exposes the underlying resource methods plus convenience helpers such as:
* - getUser, getRepository, getRepositoryFromUrl
* - getUserCommits, getUserLatestCommit, getUserCommitsInTimeframe
* - getRepositoryStars, getUserStarredCount, getUserStats
* - searchRepositories, getUserActivity
*
* @param config - Configuration object containing authentication credentials.
* - token: A GitHub personal access token used for bearer authentication.
* @returns A fully configured TGitHubModule instance with the standard resource methods and additional convenience helpers.
*/
export function GitHub(config: { token: string }): TGitHubModule {
const base = buildGitHub(config, resources);
function parseGitHubUrl(url: string): { owner: string; repo: string } | null {
const match = url.match(/github\.com\/([^/]+)\/([^/]+)/);
if (match) {
return { owner: match[1], repo: match[2].replace(/\.git$/, "") };
}
return null;
}
function calculateTimeframeDate(timeframe: string): string {
const now = new Date();
const match = timeframe.match(/(\d+)([DWMY])/i);
if (!match) return now.toISOString();
const [, amount, unit] = match;
const num = parseInt(amount, 10);
switch (unit.toUpperCase()) {
case "D":
now.setDate(now.getDate() - num);
break;
case "W":
now.setDate(now.getDate() - num * 7);
break;
case "M":
now.setMonth(now.getMonth() - num);
break;
case "Y":
now.setFullYear(now.getFullYear() - num);
break;
}
return now.toISOString();
}
const github = base as unknown as TGitHubModule;
github.getUser = function (username: string) {
return base.users.getUser({ username });
};
github.getRepository = function (owner: string, repo: string) {
return base.repos.getRepo({ owner, repo });
};
github.getRepositoryFromUrl = function (url: string) {
const parsed = parseGitHubUrl(url);
if (!parsed) throw new Error("Invalid GitHub URL");
return base.repos.getRepo(parsed);
};
github.getUserCommits = async function (username: string, options?: any) {
const events = await base.users.getUserEvents({
username,
per_page: options?.limit || 100,
});
return events.filter((e: any) => e.type === "PushEvent");
};
github.getUserLatestCommit = async function (username: string) {
const commits = await github.getUserCommits(username, { limit: 1 });
return commits[0] || null;
};
github.getUserCommitsInTimeframe = async function (
username: string,
timeframe: string,
) {
const since = calculateTimeframeDate(timeframe);
const events = await base.users.getUserEvents({ username });
return events.filter(
(e: any) =>
e.type === "PushEvent" && new Date(e.created_at) >= new Date(since),
);
};
github.getRepositoryStars = async function (owner: string, repo: string) {
const repository = await base.repos.getRepo({ owner, repo });
return repository.stargazers_count || 0;
};
github.getUserStarredCount = async function (username: string) {
const starred = await base.users.getUserStarred({ username });
return Array.isArray(starred) ? starred.length : 0;
};
github.getUserStats = async function (username: string) {
const [user, repos, events] = await Promise.all([
base.users.getUser({ username }),
base.users.getUserRepos({ username }),
base.users.getUserEvents({ username, per_page: 100 }),
]);
const pushEvents = events.filter((e: any) => e.type === "PushEvent");
const totalStars = repos.reduce(
(sum: number, repo: any) => sum + (repo.stargazers_count || 0),
0,
);
return {
user,
totalRepos: repos.length,
totalStars,
recentCommits: pushEvents.length,
publicRepos: user.public_repos,
publicGists: user.public_gists,
followers: user.followers,
following: user.following,
};
};
github.searchRepositories = function (query: string, options?: any) {
return base.search.searchRepos({ q: query, ...options });
};
github.getUserActivity = function (username: string, options?: any) {
return base.users.getUserEvents({ username, ...options });
};
return github;
}