import { z } from 'zod' import type { FaunosteoClient } from './client' import type { Enums, Tables } from './database.types' /** * Browser side of the files foundation (docs/development/STORAGE.md §2.1, * §4): the three avatar RPCs, the quarantine upload under the INSERT policy, * the own-row read for polling and the download under the SELECT policy. * Every failure is folded into a closed kind the UI knows how to phrase. */ export type AssetStatus = Enums<'asset_status'> /** Columns the owner may read (column grant); the lease columns stay server-side. */ export const ASSET_OWNER_COLUMNS = 'id, owner_id, kind, bucket_id, object_key, status, declared_mime, declared_size, byte_size, sha256, rejection_reason, created_at, updated_at' export type AssetRow = Pick< Tables<'assets'>, | 'id' | 'owner_id' | 'kind' | 'bucket_id' | 'object_key' | 'status' | 'declared_mime' | 'declared_size' | 'byte_size' | 'sha256' | 'rejection_reason' | 'created_at' | 'updated_at' > export const AVATAR_REJECTION_CODES = [ 'unsupported_type', 'decode_failed', 'dimensions', 'processing_error', ] as const export type AvatarRejectionCode = (typeof AVATAR_REJECTION_CODES)[number] export function isAvatarRejectionCode( value: string | null | undefined, ): value is AvatarRejectionCode { return (AVATAR_REJECTION_CODES as readonly string[]).includes(value ?? '') } export const ASSET_FAILURE_KINDS = [ 'too_large', 'unsupported_type', 'rate_limited', 'storage_full', 'upload_missing', 'invalid_state', 'not_found', 'network', 'unknown', ] as const export type AssetFailureKind = (typeof ASSET_FAILURE_KINDS)[number] export class AssetFailure extends Error { readonly kind: AssetFailureKind constructor(kind: AssetFailureKind, cause?: unknown) { super(`asset: ${kind}`, { cause }) this.name = 'AssetFailure' this.kind = kind } } /** Codes the RPCs raise as SQLSTATE P0001 messages (STORAGE.md §2). */ const RPC_MESSAGE_KINDS: ReadonlySet = new Set([ 'too_large', 'unsupported_type', 'rate_limited', 'storage_full', 'upload_missing', 'invalid_state', 'not_found', ]) interface PostgrestLikeError { code?: string | null message?: string status?: number } /** * Folds a PostgREST / storage / fetch error into a closed kind. `42501` * (authorisation) becomes `unknown` on purpose: the UI never reaches an RPC * without a session, so it is a bug, not a state to phrase. */ export function classifyAssetError(error: unknown): AssetFailureKind { if (error instanceof AssetFailure) return error.kind if (error instanceof TypeError) return 'network' const e = (error ?? {}) as PostgrestLikeError if (e.code === 'P0001' && e.message && RPC_MESSAGE_KINDS.has(e.message)) { return e.message as AssetFailureKind } if (e.status === undefined || e.status === 0) { return e.code ? 'unknown' : 'network' } return 'unknown' } function fail(error: unknown): never { throw new AssetFailure(classifyAssetError(error), error) } const BeginResultSchema = z.object({ asset_id: z.string().uuid(), bucket_id: z.literal('avatars'), quarantine_key: z.string().min(1), }) export interface BeginAvatarUploadInput { declaredMime: 'image/jpeg' | 'image/png' | 'image/webp' declaredSize: number } export interface AvatarUploadTicket { assetId: string bucketId: 'avatars' quarantineKey: string } export async function beginAvatarUpload( client: FaunosteoClient, input: BeginAvatarUploadInput, ): Promise { const { data, error } = await client.rpc('begin_avatar_upload', { declared_mime: input.declaredMime, declared_size: input.declaredSize, }) if (error) fail(error) const parsed = BeginResultSchema.safeParse(data) if (!parsed.success) throw new AssetFailure('unknown', parsed.error) return { assetId: parsed.data.asset_id, bucketId: parsed.data.bucket_id, quarantineKey: parsed.data.quarantine_key, } } export interface QuarantineUploadInput { bucketId: string quarantineKey: string blob: Blob } /** Direct upload with the user JWT; only the caller's pending quarantine key passes the INSERT policy. */ export async function uploadToQuarantine( client: FaunosteoClient, input: QuarantineUploadInput, ): Promise { const { error } = await client.storage .from(input.bucketId) .upload(input.quarantineKey, input.blob, { upsert: false, contentType: 'image/jpeg', }) if (error) throw new AssetFailure(classifyStorageUploadError(error), error) } /** * storage-js answers with a StorageApiError (status + statusCode) for a * refused upload; a policy refusal (the row is no longer pending, or the key * is not ours) is a state problem, not a network one. */ function classifyStorageUploadError(error: { message: string status?: number statusCode?: string }): AssetFailureKind { if (/already exists|duplicate/i.test(error.message)) return 'invalid_state' if (error.status === 413 || error.statusCode === '413') return 'too_large' if (error.status === undefined) return 'network' return 'invalid_state' } export async function confirmAssetUpload( client: FaunosteoClient, assetId: string, ): Promise { const { error } = await client.rpc('confirm_asset_upload', { asset_id: assetId, }) if (error) fail(error) } /** Every avatar row of the caller still alive → deleted; returns the count. */ export async function removeAvatar(client: FaunosteoClient): Promise { const { data, error } = await client.rpc('remove_avatar') if (error) fail(error) return typeof data === 'number' ? data : 0 } export interface AvatarState { /** The single clean avatar, if any. */ clean: AssetRow | null /** Newest pending / uploaded row newer than the clean one. */ inFlight: AssetRow | null /** Newest rejected row newer than the clean one (shown once). */ lastRejected: AssetRow | null } const IN_FLIGHT: ReadonlySet = new Set(['pending_upload', 'uploaded']) /** Reduces the newest-first rows of an owner to the three states the UI shows. */ export function reduceAvatarRows(rows: readonly AssetRow[]): AvatarState { const clean = rows.find((r) => r.status === 'clean') ?? null const newerThanClean = (r: AssetRow) => clean === null || r.created_at > clean.created_at const inFlight = rows.find((r) => IN_FLIGHT.has(r.status) && newerThanClean(r)) ?? null const lastRejected = rows.find((r) => r.status === 'rejected' && newerThanClean(r)) ?? null return { clean, inFlight, lastRejected } } export async function fetchOwnAvatarState( client: FaunosteoClient, userId: string, ): Promise { const { data, error } = await client .from('assets') .select(ASSET_OWNER_COLUMNS) .eq('owner_id', userId) .eq('kind', 'profile_avatar') .in('status', ['clean', 'pending_upload', 'uploaded', 'rejected']) .order('created_at', { ascending: false }) .limit(5) if (error) fail(error) return reduceAvatarRows((data ?? []) as AssetRow[]) } /** Download under the SELECT policy: only the owner's clean object answers. */ export async function downloadAvatar( client: FaunosteoClient, objectKey: string, ): Promise { const { data, error } = await client.storage .from('avatars') .download(objectKey) if (error || !data) fail(error ?? new Error('empty download')) return data }