Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/app/src/flow-schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export const runIdSchema = z.object({ runId: z.string().min(1) });
const webhookCommonSchema = z.object({ handlerCode: z.string().max(16_384).optional() });
export const webhookTriggerConfigSchema = z.discriminatedUnion("provider", [
webhookCommonSchema.extend({ provider: z.literal("linear"), projectId: z.string().min(1), matchRules: z.array(matchRuleSchema).min(1) }).strict(),
webhookCommonSchema.extend({ provider: z.literal("github"), installationId: z.number().int().positive(), repositoryId: z.number().int().positive(), event: z.string().min(1).default("pull_request"), action: z.string().min(1).default("dequeued") }).strict(),
webhookCommonSchema.extend({ provider: z.literal("github"), installationId: z.number().int().positive(), repositoryId: z.number().int().positive(), event: z.string().min(1).optional(), action: z.string().min(1).optional(), matchRules: z.array(matchRuleSchema).min(1).optional() }).strict().refine(value => Boolean(value.matchRules?.length || (value.event && value.action)), { message: "GitHub triggers require issue matching rules or an event and action" }),
webhookCommonSchema.extend({ provider: z.literal("cloudflareTail"), integrationId: z.string().min(1) }).strict(),
]);
export const triggerSchema = z.discriminatedUnion("kind", [
Expand Down
44 changes: 44 additions & 0 deletions packages/app/src/github-issue-matcher.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import type { MatchRule } from "./types";

type GitHubIssue = {
state?: string;
user?: { id?: number };
assignee?: { id?: number } | null;
assignees?: Array<{ id?: number }>;
labels?: Array<{ id?: number }>;
};

type GitHubIssueEvent = {
action?: string;
issue?: GitHubIssue;
label?: { id?: number };
assignee?: { id?: number };
};

const idMatches = (value: number | undefined, target: string) => value !== undefined && String(value) === target;

/** Returns true only when an issue currently matches every rule and this event made it enter that set. */
export function matchingGitHubIssue(event: GitHubIssueEvent, rules: MatchRule[]): boolean {
const issue = event.issue;
if (!issue || !rules.length) return false;

const matches = (rule: MatchRule): boolean => {
if (rule.type === "status") return issue.state === rule.targetId;
if (rule.type === "label") return issue.labels?.some(label => idMatches(label.id, rule.targetId)) === true;
if (rule.type === "creator") return idMatches(issue.user?.id, rule.targetId);
if (rule.type === "assignee" || rule.type === "owner") {
return issue.assignees?.some(assignee => idMatches(assignee.id, rule.targetId)) === true
|| idMatches(issue.assignee?.id, rule.targetId);
}
return false;
};
if (!rules.every(matches)) return false;

const action = event.action;
if (action === "opened" || action === "reopened") return true;
return rules.some(rule =>
(rule.type === "status" && action === "closed" && rule.targetId === "closed")
|| (rule.type === "label" && action === "labeled" && idMatches(event.label?.id, rule.targetId))
|| ((rule.type === "assignee" || rule.type === "owner") && action === "assigned" && idMatches(event.assignee?.id, rule.targetId)),
);
}
4 changes: 4 additions & 0 deletions packages/app/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,10 @@ app.get("/api/github/installations/:id/repositories", async (c) => {
const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401);
return tenant(c, session.tenantId).fetch(`https://tenant/github/installations/${encodeURIComponent(c.req.param("id"))}/repositories`);
});
app.get("/api/github/installations/:installationId/repositories/:repositoryId/issue-options", async (c) => {
const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401);
return tenant(c, session.tenantId).fetch(`https://tenant/github/installations/${encodeURIComponent(c.req.param("installationId"))}/repositories/${encodeURIComponent(c.req.param("repositoryId"))}/issue-options`);
});
app.delete("/api/github/installations/:id", async (c) => {
const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401);
const response = await tenant(c, session.tenantId).fetch(`https://tenant/github/installations/${encodeURIComponent(c.req.param("id"))}`, { method: "DELETE" });
Expand Down
23 changes: 23 additions & 0 deletions packages/app/src/tenant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,8 @@ export class TenantV2 extends DurableObject<Env> {
if (request.method === "POST" && url.pathname === "/github/setup-state/consume") return this.consumeSetupState(await request.json());
const repoMatch = url.pathname.match(/^\/github\/installations\/(\d+)\/repositories$/);
if (request.method === "GET" && repoMatch) return await this.githubRepositories(Number(repoMatch[1]));
const optionMatch = url.pathname.match(/^\/github\/installations\/(\d+)\/repositories\/(\d+)\/issue-options$/);
if (request.method === "GET" && optionMatch) return await this.githubIssueOptions(Number(optionMatch[1]), Number(optionMatch[2]));
const stateMatch = url.pathname.match(/^\/github\/installations\/(\d+)\/state$/);
if (request.method === "PATCH" && stateMatch) return this.updateGitHubInstallation(Number(stateMatch[1]), await request.json());
const installMatch = url.pathname.match(/^\/github\/installations\/(\d+)$/);
Expand Down Expand Up @@ -1536,6 +1538,27 @@ export class TenantV2 extends DurableObject<Env> {
return json(repositories.map(normalizeRepository));
}

private async githubIssueOptions(installationId: number, repositoryId: number): Promise<Response> {
const installation = this.one("SELECT state FROM github_installations WHERE installation_id=?", installationId) as Row | undefined;
if (installation?.state !== "active") return new Response("GitHub installation is unavailable", { status: 409 });
const token = await installationToken(this.env, installationId);
const repositoryResponse = await fetch(`https://api.github.com/repositories/${repositoryId}`, { headers: githubHeaders(token) });
if (!repositoryResponse.ok) return new Response("GitHub repository is unavailable", { status: repositoryResponse.status });
const repository = await repositoryResponse.json() as { full_name?: string };
if (!repository.full_name) return new Response("GitHub repository is unavailable", { status: 404 });
const load = async (path: string) => {
const response = await fetch(`https://api.github.com/repos/${repository.full_name}/${path}?per_page=100`, { headers: githubHeaders(token) });
if (!response.ok) throw new Error(`GitHub ${path} could not be loaded`);
return await response.json() as Array<{ id: number; name?: string; login?: string }>;
};
const [labels, assignees] = await Promise.all([load("labels"), load("assignees")]);
return json({
statuses: [{ id: "open", name: "Open" }, { id: "closed", name: "Closed" }],
labels: labels.map(label => ({ id: String(label.id), name: label.name ?? String(label.id) })),
users: assignees.map(user => ({ id: String(user.id), name: user.login ?? String(user.id) })),
});
}

private async validateSource(input: PipeInput): Promise<FlowSource> {
if (!input.source || input.source.kind === "linear") {
const projectId = input.source?.kind === "linear" ? input.source.projectId : input.projectId;
Expand Down
6 changes: 6 additions & 0 deletions packages/app/src/trigger-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,12 @@ export const triggerContextCatalog: Record<string, ContextPath[]> = {
],
github: [...commonWebhook,
{ path: "action", type: "string", description: "GitHub webhook action." },
{ path: "issue", type: "object", description: "Complete GitHub issue payload." },
{ path: "issue.number", type: "number", description: "Issue number.", example: 42 },
{ path: "issue.title", type: "string", description: "Issue title." },
{ path: "issue.body", type: "string", description: "Issue body, when present." },
{ path: "issue.html_url", type: "string", description: "Issue URL." },
{ path: "issue.state", type: "string", description: "Current issue state." },
{ path: "pull_request", type: "object", description: "Complete GitHub pull request payload." },
{ path: "pull_request.number", type: "number", description: "Pull request number.", example: 42 },
{ path: "pull_request.title", type: "string", description: "Pull request title." },
Expand Down
Loading