CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
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 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 | /**
* Block L — GitHub importer.
*
* Pure helpers + orchestrator to copy a GitHub repo's metadata (labels,
* issues, PRs, comments, releases, stargazers) into Gluecron's own tables.
* The git content itself is handled separately via `git clone --mirror`.
*
* Contract:
* - Never throws. All helpers return `{ ok, data? } | { ok: false, error }`.
* - Paginated walkers honour a per-endpoint cap so a single sync request
* terminates in bounded time (no background worker needed for v1).
* - Auth is a GitHub PAT passed per call; we never log it.
* - Every insert uses the importing user as the authorId fallback so schema
* NOT NULL constraints are preserved even when we can't resolve the
* original GitHub author to a Gluecron user.
*/
import { and, eq } from "drizzle-orm";
import { db } from "../db";
import {
issueComments,
issueLabels,
issues,
labels as labelsTable,
prComments,
pullRequests,
releases,
repositories,
stars,
githubImports,
} from "../db/schema";
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export type Result<T> = { ok: true; data: T } | { ok: false; error: string };
export interface GhRepo {
default_branch?: string;
private?: boolean;
description?: string | null;
}
export interface GhLabel {
name: string;
color: string;
description: string | null;
}
export interface GhIssue {
number: number;
title: string;
body: string | null;
state: "open" | "closed";
created_at: string;
updated_at: string;
closed_at: string | null;
labels: GhLabel[] | Array<{ name: string }>;
pull_request?: { url: string } | null;
}
export interface GhPull {
number: number;
title: string;
body: string | null;
state: "open" | "closed";
merged_at: string | null;
closed_at: string | null;
created_at: string;
updated_at: string;
draft: boolean;
base: { ref: string };
head: { ref: string };
}
export interface GhComment {
body: string;
created_at: string;
updated_at: string;
}
export interface GhRelease {
tag_name: string;
name: string | null;
body: string | null;
target_commitish: string;
prerelease: boolean;
draft: boolean;
created_at: string;
published_at: string | null;
}
export interface ImportCaps {
labels: number;
issues: number;
pulls: number;
issueComments: number;
prComments: number;
releases: number;
stargazers: number;
}
export const DEFAULT_CAPS: ImportCaps = {
labels: 200,
issues: 200,
pulls: 100,
issueComments: 500,
prComments: 500,
releases: 50,
stargazers: 200,
};
export interface ImportStats {
labels: number;
issues: number;
pulls: number;
issueComments: number;
prComments: number;
releases: number;
stargazers: number;
}
export interface RunImportArgs {
token: string;
sourceOwner: string;
sourceRepo: string;
targetRepoId: string;
importerUserId: string;
caps?: Partial<ImportCaps>;
fetchImpl?: typeof fetch; // injectable for tests
}
export interface RunImportResult {
ok: boolean;
stats: ImportStats;
error?: string;
}
// ---------------------------------------------------------------------------
// URL construction
// ---------------------------------------------------------------------------
/**
* Build an authed clone URL. The token is URL-encoded and injected as
* username. We reject CR/LF so a malicious token can't inject a header.
*/
export function buildAuthedCloneUrl(
token: string,
owner: string,
repo: string
): Result<string> {
if (!token || /[\r\n\s]/.test(token)) {
return { ok: false, error: "invalid token" };
}
if (!/^[A-Za-z0-9_.-]+$/.test(owner) || !/^[A-Za-z0-9_.-]+$/.test(repo)) {
return { ok: false, error: "invalid owner/repo" };
}
const encoded = encodeURIComponent(token);
return {
ok: true,
data: `https://x-access-token:${encoded}@github.com/${owner}/${repo}.git`,
};
}
/** Redact authed URL for logging. */
export function redactCloneUrl(url: string): string {
return url.replace(/https:\/\/[^@]+@/, "https://***@");
}
// ---------------------------------------------------------------------------
// Pagination
// ---------------------------------------------------------------------------
export interface GhFetchResponse {
ok: boolean;
status: number;
body: unknown;
linkNext?: string;
}
export async function ghFetch(
token: string,
url: string,
fetchImpl: typeof fetch = fetch
): Promise<GhFetchResponse> {
try {
const res = await fetchImpl(url, {
headers: {
Accept: "application/vnd.github+json",
Authorization: `token ${token}`,
"User-Agent": "gluecron-importer",
},
});
let body: unknown = null;
try {
body = await res.json();
} catch {
body = null;
}
const link = res.headers.get("link") || res.headers.get("Link");
const linkNext = parseNextLink(link);
return { ok: res.ok, status: res.status, body, linkNext };
} catch (err) {
return {
ok: false,
status: 0,
body: null,
linkNext: undefined,
};
}
}
export function parseNextLink(link: string | null): string | undefined {
if (!link) return undefined;
for (const part of link.split(",")) {
const m = part.match(/<([^>]+)>\s*;\s*rel="next"/);
if (m) return m[1];
}
return undefined;
}
/**
* Walk a paginated endpoint accumulating items up to `cap`. Stops on first
* error response or when `linkNext` is absent.
*/
export async function paginate<T>(
token: string,
firstUrl: string,
cap: number,
fetchImpl: typeof fetch = fetch
): Promise<Result<T[]>> {
const out: T[] = [];
let url: string | undefined = firstUrl;
let safety = 20; // hard ceiling on page walks
while (url && out.length < cap && safety-- > 0) {
const r = await ghFetch(token, url, fetchImpl);
if (!r.ok) return { ok: false, error: `github ${r.status}` };
if (!Array.isArray(r.body)) {
return { ok: false, error: "expected array" };
}
for (const item of r.body as T[]) {
out.push(item);
if (out.length >= cap) break;
}
url = r.linkNext;
}
return { ok: true, data: out };
}
// ---------------------------------------------------------------------------
// Endpoint walkers
// ---------------------------------------------------------------------------
const API = "https://api.github.com";
export function fetchRepo(
token: string,
owner: string,
repo: string,
fetchImpl: typeof fetch = fetch
): Promise<GhFetchResponse> {
return ghFetch(token, `${API}/repos/${owner}/${repo}`, fetchImpl);
}
export function fetchLabels(
token: string,
owner: string,
repo: string,
cap: number,
fetchImpl: typeof fetch = fetch
): Promise<Result<GhLabel[]>> {
return paginate<GhLabel>(
token,
`${API}/repos/${owner}/${repo}/labels?per_page=100`,
cap,
fetchImpl
);
}
export function fetchIssuesAndPulls(
token: string,
owner: string,
repo: string,
cap: number,
fetchImpl: typeof fetch = fetch
): Promise<Result<GhIssue[]>> {
return paginate<GhIssue>(
token,
`${API}/repos/${owner}/${repo}/issues?state=all&per_page=100`,
cap,
fetchImpl
);
}
/** Filter a mixed issues+pulls list down to issues only. */
export function filterIssuesOnly(items: GhIssue[]): GhIssue[] {
return items.filter((i) => !i.pull_request);
}
export function fetchPullRequests(
token: string,
owner: string,
repo: string,
cap: number,
fetchImpl: typeof fetch = fetch
): Promise<Result<GhPull[]>> {
return paginate<GhPull>(
token,
`${API}/repos/${owner}/${repo}/pulls?state=all&per_page=100`,
cap,
fetchImpl
);
}
export function fetchIssueComments(
token: string,
owner: string,
repo: string,
issueNumber: number,
cap: number,
fetchImpl: typeof fetch = fetch
): Promise<Result<GhComment[]>> {
return paginate<GhComment>(
token,
`${API}/repos/${owner}/${repo}/issues/${issueNumber}/comments?per_page=100`,
cap,
fetchImpl
);
}
export function fetchReleases(
token: string,
owner: string,
repo: string,
cap: number,
fetchImpl: typeof fetch = fetch
): Promise<Result<GhRelease[]>> {
return paginate<GhRelease>(
token,
`${API}/repos/${owner}/${repo}/releases?per_page=100`,
cap,
fetchImpl
);
}
// ---------------------------------------------------------------------------
// Mappers — pure transforms from GitHub shapes to Gluecron insert rows
// ---------------------------------------------------------------------------
/** Normalise GitHub's 6-hex color (no #) into Gluecron's `#RRGGBB`. */
export function normaliseColor(hex: string | null | undefined): string {
if (!hex) return "#8b949e";
const s = hex.replace(/^#/, "").toLowerCase();
if (!/^[0-9a-f]{6}$/.test(s)) return "#8b949e";
return `#${s}`;
}
export function mapLabel(
gh: GhLabel,
repoId: string
): {
repositoryId: string;
name: string;
color: string;
description: string | null;
} {
return {
repositoryId: repoId,
name: gh.name.slice(0, 50),
color: normaliseColor(gh.color),
description: gh.description ? gh.description.slice(0, 200) : null,
};
}
export function mapIssue(
gh: GhIssue,
repoId: string,
authorId: string
): {
repositoryId: string;
authorId: string;
title: string;
body: string | null;
state: string;
closedAt: Date | null;
} {
return {
repositoryId: repoId,
authorId,
title: gh.title.slice(0, 500),
body: gh.body,
state: gh.state === "closed" ? "closed" : "open",
closedAt: gh.closed_at ? new Date(gh.closed_at) : null,
};
}
export function mapPull(
gh: GhPull,
repoId: string,
authorId: string
): {
repositoryId: string;
authorId: string;
title: string;
body: string | null;
state: string;
baseBranch: string;
headBranch: string;
isDraft: boolean;
mergedAt: Date | null;
closedAt: Date | null;
} {
let state: "open" | "closed" | "merged" = "open";
if (gh.merged_at) state = "merged";
else if (gh.state === "closed") state = "closed";
return {
repositoryId: repoId,
authorId,
title: gh.title.slice(0, 500),
body: gh.body,
state,
baseBranch: gh.base.ref.slice(0, 200),
headBranch: gh.head.ref.slice(0, 200),
isDraft: !!gh.draft,
mergedAt: gh.merged_at ? new Date(gh.merged_at) : null,
closedAt: gh.closed_at ? new Date(gh.closed_at) : null,
};
}
export function mapRelease(
gh: GhRelease,
repoId: string,
authorId: string
): {
repositoryId: string;
authorId: string;
tag: string;
name: string;
body: string | null;
targetCommit: string;
isDraft: boolean;
isPrerelease: boolean;
publishedAt: Date | null;
} {
return {
repositoryId: repoId,
authorId,
tag: gh.tag_name.slice(0, 100),
name: (gh.name ?? gh.tag_name).slice(0, 200),
body: gh.body,
targetCommit: gh.target_commitish.slice(0, 100),
isDraft: !!gh.draft,
isPrerelease: !!gh.prerelease,
publishedAt: gh.published_at ? new Date(gh.published_at) : null,
};
}
// ---------------------------------------------------------------------------
// Orchestrator
// ---------------------------------------------------------------------------
function emptyStats(): ImportStats {
return {
labels: 0,
issues: 0,
pulls: 0,
issueComments: 0,
prComments: 0,
releases: 0,
stargazers: 0,
};
}
/**
* Walk GitHub endpoints for a single repo and mirror metadata into Gluecron.
* Each endpoint is capped; failures are recorded on the run but do not halt
* the overall import (best-effort, never throws).
*/
export async function runImport(args: RunImportArgs): Promise<RunImportResult> {
const caps: ImportCaps = { ...DEFAULT_CAPS, ...(args.caps ?? {}) };
const stats = emptyStats();
const fetchImpl = args.fetchImpl ?? fetch;
const errors: string[] = [];
try {
// Labels — build a name → id map so we can attach issueLabels.
const labelMap = new Map<string, string>();
const labelsRes = await fetchLabels(
args.token,
args.sourceOwner,
args.sourceRepo,
caps.labels,
fetchImpl
);
if (labelsRes.ok) {
for (const ghLabel of labelsRes.data) {
try {
const row = mapLabel(ghLabel, args.targetRepoId);
const [inserted] = await db
.insert(labelsTable)
.values(row)
.onConflictDoNothing()
.returning();
let labelId = inserted?.id;
if (!labelId) {
const [existing] = await db
.select()
.from(labelsTable)
.where(
and(
eq(labelsTable.repositoryId, args.targetRepoId),
eq(labelsTable.name, row.name)
)
)
.limit(1);
labelId = existing?.id;
}
if (labelId) {
labelMap.set(row.name, labelId);
stats.labels += 1;
}
} catch {
// skip individual label on failure
}
}
} else {
errors.push(`labels: ${labelsRes.error}`);
}
// Issues + PRs come together from /issues?state=all; split them here.
const mixedRes = await fetchIssuesAndPulls(
args.token,
args.sourceOwner,
args.sourceRepo,
caps.issues + caps.pulls,
fetchImpl
);
const issuesOnly = mixedRes.ok ? filterIssuesOnly(mixedRes.data) : [];
const issuesToInsert = issuesOnly.slice(0, caps.issues);
if (!mixedRes.ok) errors.push(`issues: ${mixedRes.error}`);
for (const ghIssue of issuesToInsert) {
try {
const [row] = await db
.insert(issues)
.values(mapIssue(ghIssue, args.targetRepoId, args.importerUserId))
.returning();
if (!row) continue;
stats.issues += 1;
// Attach labels
for (const raw of ghIssue.labels ?? []) {
const name =
typeof raw === "string"
? raw
: (raw as { name?: string } | null)?.name;
if (!name) continue;
const labelId = labelMap.get(name.slice(0, 50));
if (!labelId) continue;
try {
await db
.insert(issueLabels)
.values({ issueId: row.id, labelId })
.onConflictDoNothing();
} catch {
// ignore per-label
}
}
// Walk comments for this issue (only while under the global cap)
if (stats.issueComments < caps.issueComments) {
const commentsRes = await fetchIssueComments(
args.token,
args.sourceOwner,
args.sourceRepo,
ghIssue.number,
Math.min(50, caps.issueComments - stats.issueComments),
fetchImpl
);
if (commentsRes.ok) {
for (const ghComment of commentsRes.data) {
try {
await db.insert(issueComments).values({
issueId: row.id,
authorId: args.importerUserId,
body: ghComment.body,
});
stats.issueComments += 1;
if (stats.issueComments >= caps.issueComments) break;
} catch {
// skip one comment
}
}
}
}
} catch {
// skip one issue
}
}
// Pull requests — separate endpoint has base/head/merged_at we need.
const pullsRes = await fetchPullRequests(
args.token,
args.sourceOwner,
args.sourceRepo,
caps.pulls,
fetchImpl
);
if (!pullsRes.ok) errors.push(`pulls: ${pullsRes.error}`);
if (pullsRes.ok) {
for (const ghPull of pullsRes.data) {
try {
const [row] = await db
.insert(pullRequests)
.values(mapPull(ghPull, args.targetRepoId, args.importerUserId))
.returning();
if (!row) continue;
stats.pulls += 1;
if (stats.prComments < caps.prComments) {
const commentsRes = await fetchIssueComments(
args.token,
args.sourceOwner,
args.sourceRepo,
ghPull.number,
Math.min(50, caps.prComments - stats.prComments),
fetchImpl
);
if (commentsRes.ok) {
for (const ghComment of commentsRes.data) {
try {
await db.insert(prComments).values({
pullRequestId: row.id,
authorId: args.importerUserId,
body: ghComment.body,
isAiReview: false,
});
stats.prComments += 1;
if (stats.prComments >= caps.prComments) break;
} catch {
// skip one comment
}
}
}
}
} catch {
// skip one PR
}
}
}
// Releases
const releasesRes = await fetchReleases(
args.token,
args.sourceOwner,
args.sourceRepo,
caps.releases,
fetchImpl
);
if (!releasesRes.ok) errors.push(`releases: ${releasesRes.error}`);
if (releasesRes.ok) {
for (const ghRelease of releasesRes.data) {
try {
await db
.insert(releases)
.values(
mapRelease(ghRelease, args.targetRepoId, args.importerUserId)
)
.onConflictDoNothing();
stats.releases += 1;
} catch {
// skip
}
}
}
// Stargazers — just a count bump; we don't create fake user rows.
const stargazersRes = await paginate<unknown>(
args.token,
`${API}/repos/${args.sourceOwner}/${args.sourceRepo}/stargazers?per_page=100`,
caps.stargazers,
fetchImpl
);
if (stargazersRes.ok) {
stats.stargazers = stargazersRes.data.length;
try {
await db
.update(repositories)
.set({ starCount: stats.stargazers })
.where(eq(repositories.id, args.targetRepoId));
// Self-star from the importer so the "Stars" list isn't empty.
await db
.insert(stars)
.values({
userId: args.importerUserId,
repositoryId: args.targetRepoId,
})
.onConflictDoNothing();
} catch {
// ignore
}
} else {
errors.push(`stargazers: ${stargazersRes.error}`);
}
return {
ok: errors.length === 0,
stats,
error: errors.length > 0 ? errors.join("; ") : undefined,
};
} catch (err) {
return {
ok: false,
stats,
error: err instanceof Error ? err.message : "unknown error",
};
}
}
// ---------------------------------------------------------------------------
// Ledger helpers
// ---------------------------------------------------------------------------
export async function createImportRow(args: {
userId: string;
sourceOwner: string;
sourceRepo: string;
}): Promise<string | null> {
try {
const [row] = await db
.insert(githubImports)
.values({
userId: args.userId,
sourceOwner: args.sourceOwner,
sourceRepo: args.sourceRepo,
status: "pending",
})
.returning();
return row?.id ?? null;
} catch {
return null;
}
}
export async function finaliseImportRow(
importId: string,
patch: {
repositoryId?: string;
status: "cloning" | "walking" | "ok" | "error";
stats?: ImportStats;
error?: string;
}
): Promise<void> {
try {
await db
.update(githubImports)
.set({
repositoryId: patch.repositoryId,
status: patch.status,
stats: patch.stats ? JSON.stringify(patch.stats) : undefined,
error: patch.error,
finishedAt:
patch.status === "ok" || patch.status === "error"
? new Date()
: undefined,
})
.where(eq(githubImports.id, importId));
} catch {
// best effort
}
}
|