Skip to content
← Public packages

@kody/kody-factory

Forkable multi-project software factory: signals, priority queue, project UI, sweep job. Agent runners and Sentry reach it by events.

FollowFork

Files

owner-github-request.ts

124 lines · 4.7 KB · TypeScript
/**
 * GitHub REST helper for ./friction/push-branch. Always uses the factory's
 * `githubOwner` credential (the owner's account). Never falls back to the bot
 * `github` slot.
 */
import { credential } from 'kody:runtime'
import type { Request } from './push-branch-core.ts'

export const GITHUB_OWNER_CREDENTIAL_KEY = 'githubOwner'
export const GITHUB_API_HOST = 'api.github.com'

export const GITHUB_OWNER_UNMAPPED_MESSAGE =
	'push-branch: the factory credential "githubOwner" is not mapped. Map it to the owner\'s GitHub account (an org GitHub OAuth connection or a fine-grained PAT with provider github) on this package\'s Credentials tab. This export will not fall back to the bot "github" credential; do not push or open the PR another way until githubOwner is mapped.'

const SAFE_HTTP_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])

export class GithubOwnerSetupError extends Error {
	readonly code = 'github-owner-credential-missing'
	constructor(message = GITHUB_OWNER_UNMAPPED_MESSAGE) {
		super(message)
		this.name = 'GithubOwnerSetupError'
	}
}

type GithubOwnerClient = { fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response> }

/** Open credential("githubOwner"). Throws GithubOwnerSetupError when it is missing. Never opens "github". */
export async function openGithubOwnerCredential(): Promise<GithubOwnerClient> {
	let client: GithubOwnerClient | null = null
	try {
		client = (await credential(GITHUB_OWNER_CREDENTIAL_KEY)) as unknown as GithubOwnerClient
	} catch (err) {
		const detail = err instanceof Error ? err.message.replace(/\s+/g, ' ').trim().slice(0, 200) : ''
		throw new GithubOwnerSetupError(
			detail && !/githubOwner/i.test(detail)
				? `${GITHUB_OWNER_UNMAPPED_MESSAGE} (${detail})`
				: GITHUB_OWNER_UNMAPPED_MESSAGE,
		)
	}
	if (!client || typeof client.fetch !== 'function') {
		throw new GithubOwnerSetupError()
	}
	return client
}

function buildUrl(path: unknown, query: unknown): string {
	if (typeof path !== 'string' || path.length === 0) {
		throw new Error('push-branch: GitHub request requires a non-empty path')
	}
	const url = new URL(path.startsWith('http') ? path : `https://${GITHUB_API_HOST}${path.startsWith('/') ? path : `/${path}`}`)
	if (url.protocol !== 'https:' || url.host !== GITHUB_API_HOST) {
		throw new Error(`push-branch: refusing non-GitHub API host ${url.host}`)
	}
	if (query && typeof query === 'object') {
		for (const [key, value] of Object.entries(query as Record<string, unknown>)) {
			if (value === undefined || value === null) continue
			url.searchParams.set(key, String(value))
		}
	}
	return url.toString()
}

function parseBody(text: string, contentType: string | null): unknown {
	if (!text) return null
	if ((contentType ?? '').includes('json') || text.startsWith('{') || text.startsWith('[')) {
		try {
			return JSON.parse(text)
		} catch {
			return text
		}
	}
	return text
}

/**
 * Authenticated GitHub REST request as the owner. Mutations require
 * `dryRun: true` (no request is sent) or `confirm: true`.
 */
export const ownerGithubRequest: Request = async (params) => {
	if (params && typeof params === 'object') {
		for (const key of ['account', 'secretName', 'integrationName'] as const) {
			if (params[key] !== undefined && params[key] !== null) {
				throw new Error(
					`push-branch: the "${key}" option is not supported. This export always uses the "githubOwner" credential.`,
				)
			}
		}
	}
	const url = buildUrl(params.path, params.query)
	const method = String(params.method ?? (params.body === undefined ? 'GET' : 'POST')).toUpperCase()
	const mutating = !SAFE_HTTP_METHODS.has(method)
	if (mutating && params.dryRun !== true && params.confirm !== true) {
		throw new Error(`GitHub mutation "${method} ${params.path}" requires dryRun: true or confirm: true`)
	}
	if (mutating && params.dryRun === true) {
		return {
			ok: true,
			status: 0,
			data: { dryRun: true, method, path: params.path, wouldRequest: true },
			text: '',
		}
	}

	const headers = new Headers(params.headers as HeadersInit | undefined)
	headers.set('Accept', headers.get('Accept') ?? 'application/vnd.github+json')
	headers.set('X-GitHub-Api-Version', headers.get('X-GitHub-Api-Version') ?? '2022-11-28')
	headers.set('User-Agent', headers.get('User-Agent') ?? 'kody-factory-push-branch')

	const init: RequestInit = { method, headers }
	if (params.body !== undefined) {
		if (!headers.has('Content-Type')) headers.set('Content-Type', 'application/json')
		init.body = typeof params.body === 'string' ? params.body : JSON.stringify(params.body)
	}

	const client = await openGithubOwnerCredential()
	const response = await client.fetch(url, init)
	const text = await response.text()
	return {
		ok: response.ok,
		status: response.status,
		data: parseBody(text, response.headers.get('content-type')),
		text,
	}
}