import { zValidator } from '@hono/zod-validator' import type { Context, ValidationTargets } from 'hono' import { HTTPException } from 'hono/http-exception' import type { ZodType } from 'zod' import type { SessionUser } from '../auth/sessions.ts' import type { Config } from '../config.ts' import type { Db } from '../db/client.ts' import type { Notifier } from '../notifications.ts' import type { FileStorage } from '../storage.ts' export interface AppEnv { Variables: { db: Db config: Config user: SessionUser | null notifier: Notifier storage: FileStorage } } /** Validates part of the request, answering 400 with field-level issues on failure. */ export function validate(target: Target, schema: Schema) { return zValidator(target, schema, (result, c) => { if (!result.success) { return c.json({ error: 'Invalid request', issues: result.error.issues.map((issue) => ({ path: issue.path.join('.'), message: issue.message })) }, 400) } }) } export const fail = (status: 400 | 401 | 403 | 404 | 409 | 413 | 429, message: string) => new HTTPException(status, { message }) /** The signed-in user; use after `requireAuth`. */ export function currentUser(c: Context): SessionUser { const user = c.get('user') if (!user) throw fail(401, 'Sign in required') return user }