import { AssetFailure, beginAvatarUpload, classifyAssetError, confirmAssetUpload, downloadAvatar, fetchOwnAvatarState, reduceAvatarRows, removeAvatar, uploadToQuarantine, type AssetRow, } from '../src' import type { FaunosteoClient } from '../src' /** * Stub of the client surface the assets module touches: rpc, the assets * select chain, storage upload / download. The RPC bodies are covered by * supabase/tests/010_files_foundation.sql; here the point is the call shape * and the closed failure kinds. */ function stubClient(options: { rpc?: Record rows?: AssetRow[] selectError?: unknown upload?: { error?: { message: string; status?: number; statusCode?: string } | null } download?: { data?: Blob | null; error?: unknown } } = {}) { const calls: Array<[string, unknown]> = [] const query: Record = {} const chain = { select: (cols: string) => { query.select = cols return chain }, eq: (col: string, value: unknown) => { query[`eq:${col}`] = value return chain }, in: (col: string, values: unknown) => { query[`in:${col}`] = values return chain }, order: (col: string, opts: unknown) => { query.order = [col, opts] return chain }, limit: async (n: number) => { query.limit = n return options.selectError ? { data: null, error: options.selectError } : { data: options.rows ?? [], error: null } }, } const storageCalls: Array<[string, unknown[]]> = [] const client = { rpc: async (name: string, args?: unknown) => { calls.push([name, args]) const r = options.rpc?.[name] ?? {} return { data: r.data ?? null, error: r.error ?? null } }, from: () => chain, storage: { from: (bucket: string) => ({ upload: async (...args: unknown[]) => { storageCalls.push([`upload:${bucket}`, args]) return { data: null, error: options.upload?.error ?? null } }, download: async (...args: unknown[]) => { storageCalls.push([`download:${bucket}`, args]) return { data: options.download?.data ?? null, error: options.download?.error ?? null, } }, }), }, } return { client: client as unknown as FaunosteoClient, calls, query, storageCalls } } function row(patch: Partial): AssetRow { return { id: 'a1', owner_id: 'u1', kind: 'profile_avatar', bucket_id: 'avatars', object_key: 'profiles/u1/a1/avatar.webp', status: 'clean', declared_mime: 'image/jpeg', declared_size: 1000, byte_size: null, sha256: null, rejection_reason: null, created_at: '2026-10-13T10:00:00Z', updated_at: '2026-10-13T10:00:00Z', ...patch, } } const TICKET = { asset_id: '11111111-1111-4111-8111-111111111111', bucket_id: 'avatars', quarantine_key: 'quarantine/u1/11111111-1111-4111-8111-111111111111/upload', } async function kindOf(p: Promise) { try { await p return null } catch (e) { return e instanceof AssetFailure ? e.kind : 'not-an-asset-failure' } } describe('classifyAssetError', () => { it('maps P0001 closed messages to their kind', () => { for (const m of ['too_large', 'unsupported_type', 'rate_limited', 'storage_full', 'upload_missing', 'invalid_state', 'not_found']) { expect(classifyAssetError({ code: 'P0001', message: m, status: 400 })).toBe(m) } }) it('never trusts an unknown message, authorisation is unknown, fetch failures are network', () => { expect(classifyAssetError({ code: 'P0001', message: 'drop table', status: 400 })).toBe('unknown') expect(classifyAssetError({ code: '42501', message: 'permission denied', status: 403 })).toBe('unknown') expect(classifyAssetError(new TypeError('Failed to fetch'))).toBe('network') expect(classifyAssetError({ message: 'offline' })).toBe('network') expect(classifyAssetError(new AssetFailure('too_large'))).toBe('too_large') }) }) describe('beginAvatarUpload', () => { it('calls the RPC with the declared transport and validates the ticket', async () => { const stub = stubClient({ rpc: { begin_avatar_upload: { data: TICKET } } }) const ticket = await beginAvatarUpload(stub.client, { declaredMime: 'image/jpeg', declaredSize: 1234 }) expect(stub.calls).toEqual([['begin_avatar_upload', { declared_mime: 'image/jpeg', declared_size: 1234 }]]) expect(ticket).toEqual({ assetId: TICKET.asset_id, bucketId: 'avatars', quarantineKey: TICKET.quarantine_key }) }) it('refuses a malformed ticket and folds RPC errors', async () => { const bad = stubClient({ rpc: { begin_avatar_upload: { data: { asset_id: 'x' } } } }) expect(await kindOf(beginAvatarUpload(bad.client, { declaredMime: 'image/jpeg', declaredSize: 1 }))).toBe('unknown') const limited = stubClient({ rpc: { begin_avatar_upload: { error: { code: 'P0001', message: 'rate_limited', status: 400 } } } }) expect(await kindOf(beginAvatarUpload(limited.client, { declaredMime: 'image/jpeg', declaredSize: 1 }))).toBe('rate_limited') }) }) describe('uploadToQuarantine / confirm / remove', () => { it('uploads with upsert off and the JPEG content type', async () => { const stub = stubClient() const blob = new Blob([new Uint8Array([1, 2, 3])], { type: 'image/jpeg' }) await uploadToQuarantine(stub.client, { bucketId: 'avatars', quarantineKey: TICKET.quarantine_key, blob }) expect(stub.storageCalls).toEqual([ ['upload:avatars', [TICKET.quarantine_key, blob, { upsert: false, contentType: 'image/jpeg' }]], ]) }) it('maps a duplicate or a policy refusal to invalid_state, a transport failure to network', async () => { const blob = new Blob([]) const dup = stubClient({ upload: { error: { message: 'The resource already exists' } } }) expect(await kindOf(uploadToQuarantine(dup.client, { bucketId: 'avatars', quarantineKey: 'k', blob }))).toBe('invalid_state') const refused = stubClient({ upload: { error: { message: 'new row violates row-level security policy', status: 400, statusCode: '42501' } }, }) expect(await kindOf(uploadToQuarantine(refused.client, { bucketId: 'avatars', quarantineKey: 'k', blob }))).toBe('invalid_state') const big = stubClient({ upload: { error: { message: 'Payload too large', status: 413, statusCode: '413' } } }) expect(await kindOf(uploadToQuarantine(big.client, { bucketId: 'avatars', quarantineKey: 'k', blob }))).toBe('too_large') const down = stubClient({ upload: { error: { message: 'fetch failed' } } }) expect(await kindOf(uploadToQuarantine(down.client, { bucketId: 'avatars', quarantineKey: 'k', blob }))).toBe('network') }) it('confirm and remove call their RPCs', async () => { const stub = stubClient({ rpc: { remove_avatar: { data: 2 } } }) await confirmAssetUpload(stub.client, TICKET.asset_id) expect(await removeAvatar(stub.client)).toBe(2) expect(stub.calls.map((c) => c[0])).toEqual(['confirm_asset_upload', 'remove_avatar']) expect(stub.calls[0][1]).toEqual({ asset_id: TICKET.asset_id }) const missing = stubClient({ rpc: { confirm_asset_upload: { error: { code: 'P0001', message: 'upload_missing', status: 400 } } } }) expect(await kindOf(confirmAssetUpload(missing.client, TICKET.asset_id))).toBe('upload_missing') }) }) describe('fetchOwnAvatarState', () => { it('reads the explicit column list, never *, for the owner', async () => { const stub = stubClient({ rows: [row({})] }) const state = await fetchOwnAvatarState(stub.client, 'u1') expect(stub.query.select).not.toContain('*') expect(stub.query.select).toContain('object_key') expect(stub.query.select).not.toContain('lock_token') expect(stub.query['eq:owner_id']).toBe('u1') expect(stub.query['eq:kind']).toBe('profile_avatar') expect(stub.query['in:status']).toEqual(['clean', 'pending_upload', 'uploaded', 'rejected']) expect(stub.query.limit).toBe(5) expect(state.clean?.id).toBe('a1') expect(state.inFlight).toBeNull() }) it('folds a select error', async () => { const stub = stubClient({ selectError: { code: '42501', message: 'denied', status: 403 } }) expect(await kindOf(fetchOwnAvatarState(stub.client, 'u1'))).toBe('unknown') }) }) describe('reduceAvatarRows', () => { const clean = row({ id: 'c', status: 'clean', created_at: '2026-10-13T10:00:00Z' }) it('only rows newer than the clean one count as in flight or rejected', () => { const older = row({ id: 'o', status: 'rejected', rejection_reason: 'dimensions', created_at: '2026-10-13T09:00:00Z' }) const newer = row({ id: 'n', status: 'uploaded', created_at: '2026-10-13T11:00:00Z' }) const rejected = row({ id: 'r', status: 'rejected', rejection_reason: 'decode_failed', created_at: '2026-10-13T12:00:00Z' }) const state = reduceAvatarRows([rejected, newer, clean, older]) expect(state.clean?.id).toBe('c') expect(state.inFlight?.id).toBe('n') expect(state.lastRejected?.id).toBe('r') }) it('without a clean row every newer row counts', () => { const state = reduceAvatarRows([row({ id: 'p', status: 'pending_upload' })]) expect(state).toEqual({ clean: null, inFlight: expect.objectContaining({ id: 'p' }), lastRejected: null }) expect(reduceAvatarRows([])).toEqual({ clean: null, inFlight: null, lastRejected: null }) }) }) describe('downloadAvatar', () => { it('downloads from the avatars bucket and folds a refusal', async () => { const blob = new Blob([new Uint8Array([82, 73, 70, 70])]) const ok = stubClient({ download: { data: blob } }) expect(await downloadAvatar(ok.client, 'profiles/u1/a1/avatar.webp')).toBe(blob) expect(ok.storageCalls[0]).toEqual(['download:avatars', ['profiles/u1/a1/avatar.webp']]) const denied = stubClient({ download: { error: { message: 'Object not found', status: 400 } } }) expect(await kindOf(downloadAvatar(denied.client, 'k'))).toBe('unknown') }) })