/ opencodehub / src / lib / cross-repo-issues.ts
swadhinbiswas feat: OpenCodeHub v1.1.0 - Enterprise Features & Storage Adapters · 2/15/2026
719a1cb
278 lines · 7.9 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
/**
 * Cross-repo Issues Library
 * Track and manage issues across repositories
 */

import { pgTable, text, timestamp } from "drizzle-orm/pg-core";
import { getDatabase, schema } from "@/db";
import { eq, and, or, inArray } from "drizzle-orm";
import { logger } from "./logger";
import { issues } from "@/db/schema/issues";

/**
 * Cross-repo issue references
 */
export const crossRepoIssueLinks = pgTable("cross_repo_issue_links", {
    id: text("id").primaryKey(),
    sourceIssueId: text("source_issue_id")
        .notNull()
        .references(() => issues.id, { onDelete: "cascade" }),
    targetIssueId: text("target_issue_id")
        .notNull()
        .references(() => issues.id, { onDelete: "cascade" }),
    linkType: text("link_type").notNull(), // relates, blocks, blocked_by, duplicates
    createdById: text("created_by_id").notNull(),
    createdAt: timestamp("created_at").notNull().defaultNow(),
});

export type CrossRepoIssueLink = typeof crossRepoIssueLinks.$inferSelect;

/**
 * Parse cross-repo issue references
 * Format: owner/repo#number
 */
export function parseCrossRepoReferences(text: string): {
    owner: string;
    repo: string;
    number: number;
}[] {
    const references: { owner: string; repo: string; number: number }[] = [];

    // Pattern: owner/repo#number
    const regex = /([a-zA-Z0-9_-]+)\/([a-zA-Z0-9_-]+)#(\d+)/g;
    let match;

    while ((match = regex.exec(text)) !== null) {
        references.push({
            owner: match[1],
            repo: match[2],
            number: parseInt(match[3]),
        });
    }

    return references;
}

/**
 * Link issues across repos
 */
export async function linkCrossRepoIssues(options: {
    sourceIssueId: string;
    targetIssueId: string;
    linkType: "relates" | "blocks" | "blocked_by" | "duplicates";
    createdById: string;
}): Promise<CrossRepoIssueLink> {
    const db = getDatabase();

    // Check for existing link
    const existing = await db.query.crossRepoIssueLinks?.findFirst({
        where: and(
            eq(schema.crossRepoIssueLinks.sourceIssueId, options.sourceIssueId),
            eq(schema.crossRepoIssueLinks.targetIssueId, options.targetIssueId)
        ),
    });

    if (existing) {
        // @ts-expect-error - Drizzle multi-db union type issue
        await db.update(schema.crossRepoIssueLinks)
            .set({ linkType: options.linkType })
            .where(eq(schema.crossRepoIssueLinks.id, existing.id));

        return { ...existing, linkType: options.linkType };
    }

    const link = {
        id: crypto.randomUUID(),
        sourceIssueId: options.sourceIssueId,
        targetIssueId: options.targetIssueId,
        linkType: options.linkType,
        createdById: options.createdById,
        createdAt: new Date(),
    };

    // @ts-expect-error - Drizzle multi-db union type issue
    await db.insert(schema.crossRepoIssueLinks).values(link);

    // Create reverse link for bidirectional types
    if (options.linkType === "relates") {
        // @ts-expect-error - Drizzle multi-db union type issue
        await db.insert(schema.crossRepoIssueLinks).values({
            id: crypto.randomUUID(),
            sourceIssueId: options.targetIssueId,
            targetIssueId: options.sourceIssueId,
            linkType: "relates",
            createdById: options.createdById,
            createdAt: new Date(),
        });
    } else if (options.linkType === "blocks") {
        // @ts-expect-error - Drizzle multi-db union type issue
        await db.insert(schema.crossRepoIssueLinks).values({
            id: crypto.randomUUID(),
            sourceIssueId: options.targetIssueId,
            targetIssueId: options.sourceIssueId,
            linkType: "blocked_by",
            createdById: options.createdById,
            createdAt: new Date(),
        });
    }

    logger.info({
        sourceId: options.sourceIssueId,
        targetId: options.targetIssueId,
        type: options.linkType
    }, "Cross-repo issues linked");

    return link as CrossRepoIssueLink;
}

/**
 * Get all linked issues for an issue
 */
export async function getLinkedCrossRepoIssues(issueId: string): Promise<{
    link: CrossRepoIssueLink;
    issue: typeof schema.issues.$inferSelect;
    repository: typeof schema.repositories.$inferSelect;
}[]> {
    const db = getDatabase();

    try {
        const links = await db.query.crossRepoIssueLinks?.findMany({
            where: or(
                eq(schema.crossRepoIssueLinks.sourceIssueId, issueId),
                eq(schema.crossRepoIssueLinks.targetIssueId, issueId)
            ),
        }) || [];

        const results = [];

        for (const link of links) {
            const targetId = link.sourceIssueId === issueId
                ? link.targetIssueId
                : link.sourceIssueId;

            const issue = await db.query.issues.findFirst({
                where: eq(schema.issues.id, targetId),
            });

            if (!issue) continue;

            const repository = await db.query.repositories.findFirst({
                where: eq(schema.repositories.id, issue.repositoryId),
            });

            if (repository) {
                results.push({ link, issue, repository });
            }
        }

        return results;
    } catch {
        return [];
    }
}

/**
 * Auto-link cross-repo issues from text
 */
export async function autoLinkCrossRepoIssues(
    issueId: string,
    text: string,
    createdById: string
): Promise<CrossRepoIssueLink[]> {
    const db = getDatabase();
    const references = parseCrossRepoReferences(text);
    const links: CrossRepoIssueLink[] = [];

    for (const ref of references) {
        // Find repository
        const ownerUser = await db.query.users.findFirst({
            where: eq(schema.users.username, ref.owner),
        });

        if (!ownerUser) continue;

        const repo = await db.query.repositories.findFirst({
            where: and(
                eq(schema.repositories.ownerId, ownerUser.id),
                eq(schema.repositories.name, ref.repo)
            ),
        });

        if (!repo) continue;

        // Find issue
        const targetIssue = await db.query.issues.findFirst({
            where: and(
                eq(schema.issues.repositoryId, repo.id),
                eq(schema.issues.number, ref.number)
            ),
        });

        if (!targetIssue) continue;

        const link = await linkCrossRepoIssues({
            sourceIssueId: issueId,
            targetIssueId: targetIssue.id,
            linkType: "relates",
            createdById,
        });

        links.push(link);
    }

    return links;
}

/**
 * Get blocking issues (issues that block this one)
 */
export async function getBlockingIssues(issueId: string): Promise<typeof schema.issues.$inferSelect[]> {
    const db = getDatabase();

    try {
        const links = await db.query.crossRepoIssueLinks?.findMany({
            where: and(
                eq(schema.crossRepoIssueLinks.sourceIssueId, issueId),
                eq(schema.crossRepoIssueLinks.linkType, "blocked_by")
            ),
        }) || [];

        const issues = [];

        for (const link of links) {
            const issue = await db.query.issues.findFirst({
                where: eq(schema.issues.id, link.targetIssueId),
            });
            if (issue) issues.push(issue);
        }

        return issues;
    } catch {
        return [];
    }
}

/**
 * Check if issue is blocked
 */
export async function isIssueBlocked(issueId: string): Promise<boolean> {
    const blockers = await getBlockingIssues(issueId);
    return blockers.some(b => b.state === "open");
}

/**
 * Unlink cross-repo issues
 */
export async function unlinkCrossRepoIssues(linkId: string): Promise<boolean> {
    const db = getDatabase();

    try {
        // @ts-expect-error - Drizzle multi-db union type issue
        await db.delete(schema.crossRepoIssueLinks)
            .where(eq(schema.crossRepoIssueLinks.id, linkId));
        return true;
    } catch {
        return false;
    }
}