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

bridge.ts

39 lines · 2.1 KB · TypeScript
/**
 * Bridge: while a GitHub hook still points at one of the factory's own
 * webhooks, forward each verified delivery to `@kody/github`, which publishes
 * it as `@kody/github.*` events. Kody emits as @kody/github no matter who
 * calls. Never throws; the factory's webhook result never depends on it.
 */
import ingestGithubDelivery from 'kody:@kody/github/events/ingest'

export type BridgeResult = { forwarded: boolean; emitted: number; topics: string[]; ignored?: string; error?: string }

type Ingest = (input: { event: string; deliveryId: string; json: unknown; dryRun?: boolean }) => Promise<{ ok?: boolean; ignored?: string; emitted?: Array<{ topic: string }>; errors?: Array<{ error: string }> }>

let ingestOverride: Ingest | null = null
/** Test seam. */
export function setIngestForTests(fn: Ingest | null) {
	ingestOverride = fn
}

export function githubHeader(headers: Record<string, string> | undefined, name: string): string {
	if (!headers) return ''
	const want = name.toLowerCase()
	for (const [k, v] of Object.entries(headers)) if (k.toLowerCase() === want) return String(v ?? '')
	return ''
}

export async function bridgeDelivery(headers: Record<string, string> | undefined, json: unknown): Promise<BridgeResult> {
	const event = githubHeader(headers, 'x-github-event')
	const deliveryId = githubHeader(headers, 'x-github-delivery')
	if (!event || !deliveryId) return { forwarded: false, emitted: 0, topics: [], error: 'missing X-GitHub-Event or X-GitHub-Delivery header' }
	try {
		const ingest = ingestOverride ?? (ingestGithubDelivery as unknown as Ingest)
		const res = await ingest({ event, deliveryId, json })
		const topics = (res.emitted ?? []).map((e) => e.topic)
		const error = res.ok === false ? (res.errors ?? []).map((e) => e.error).join('; ').slice(0, 300) || 'ingest failed' : undefined
		return { forwarded: true, emitted: topics.length, topics, ...(res.ignored ? { ignored: res.ignored } : {}), ...(error ? { error } : {}) }
	} catch (error) {
		return { forwarded: false, emitted: 0, topics: [], error: error instanceof Error ? error.message.slice(0, 300) : 'bridge failed' }
	}
}