All files / src/event context.ts

95.65% Statements 22/23
87.5% Branches 7/8
100% Functions 4/4
95.45% Lines 21/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                      2x       2x             2x                             2x               2x 2x                   42x 42x 2x     40x   40x                 40x 39x     39x             39x                         40x                   40x 40x       40x                 39x             42x                
import type { Octokit } from '@octokit/rest';
import { z } from 'zod';
import {
  EventContextSchema,
  type EventContext,
  type FileChange,
  type PullRequestContext,
  type RepositoryContext,
} from '../types/index.js';
 
// GitHub Action event payload schemas
const GitHubUserSchema = z.object({
  login: z.string(),
});
 
const GitHubRepoSchema = z.object({
  name: z.string(),
  full_name: z.string(),
  default_branch: z.string(),
  owner: GitHubUserSchema,
});
 
const GitHubPullRequestSchema = z.object({
  number: z.number(),
  title: z.string(),
  body: z.string().nullable(),
  user: GitHubUserSchema,
  base: z.object({
    ref: z.string(),
    sha: z.string(),
  }),
  head: z.object({
    ref: z.string(),
    sha: z.string(),
  }),
});
 
const GitHubEventPayloadSchema = z.object({
  action: z.string(),
  repository: GitHubRepoSchema,
  pull_request: GitHubPullRequestSchema.optional(),
});
 
export class EventContextError extends Error {
  constructor(message: string, options?: { cause?: unknown }) {
    super(message, options);
    this.name = 'EventContextError';
  }
}
 
export async function buildEventContext(
  eventName: string,
  eventPayload: unknown,
  repoPath: string,
  octokit: Octokit
): Promise<EventContext> {
  const payloadResult = GitHubEventPayloadSchema.safeParse(eventPayload);
  if (!payloadResult.success) {
    throw new EventContextError('Invalid event payload', { cause: payloadResult.error });
  }
 
  const payload = payloadResult.data;
 
  const repository: RepositoryContext = {
    owner: payload.repository.owner.login,
    name: payload.repository.name,
    fullName: payload.repository.full_name,
    defaultBranch: payload.repository.default_branch,
  };
 
  let pullRequest: PullRequestContext | undefined;
 
  if (eventName === 'pull_request' && payload.pull_request) {
    const pr = payload.pull_request;
 
    // Fetch files changed in the PR
    const files = await fetchPullRequestFiles(
      octokit,
      repository.owner,
      repository.name,
      pr.number
    );
 
    pullRequest = {
      number: pr.number,
      title: pr.title,
      body: pr.body,
      author: pr.user.login,
      baseBranch: pr.base.ref,
      headBranch: pr.head.ref,
      headSha: pr.head.sha,
      baseSha: pr.base.sha,
      files,
    };
  }
 
  const context: EventContext = {
    eventType: eventName as EventContext['eventType'],
    action: payload.action,
    repository,
    pullRequest,
    diffContextSource: { type: 'working-tree' },
    repoPath,
  };
 
  // Validate the final context
  const result = EventContextSchema.safeParse(context);
  Iif (!result.success) {
    throw new EventContextError('Failed to build valid event context', { cause: result.error });
  }
 
  return result.data;
}
 
async function fetchPullRequestFiles(
  octokit: Octokit,
  owner: string,
  repo: string,
  pullNumber: number
): Promise<FileChange[]> {
  const files = await octokit.paginate(octokit.pulls.listFiles, {
    owner,
    repo,
    pull_number: pullNumber,
    per_page: 100,
  });
 
  return files.map((file) => ({
    filename: file.filename,
    status: file.status as FileChange['status'],
    additions: file.additions,
    deletions: file.deletions,
    patch: file.patch,
  }));
}