From 7d2340ab24b10e3baccd7f82045a67bf5ac0da9c Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Tue, 10 Nov 2026 16:34:24 -0500 Subject: [PATCH] test(merge): migrate community API tests to the lex clients --- src/lib/api/__tests__/community-feed.test.ts | 47 ++-- .../__tests__/community-notifications.test.ts | 201 +++++++----------- src/lib/api/__tests__/community.test.ts | 19 +- src/lib/api/__tests__/group-invites.test.ts | 10 +- src/lib/api/__tests__/space-post-poll.test.ts | 5 +- src/lib/api/__tests__/space-post.test.ts | 23 +- src/lib/api/__tests__/space-write.test.ts | 39 ++-- src/lib/api/community-notifications.ts | 15 +- src/lib/media/video/__tests__/upload.test.ts | 7 +- 9 files changed, 177 insertions(+), 189 deletions(-) diff --git a/src/lib/api/__tests__/community-feed.test.ts b/src/lib/api/__tests__/community-feed.test.ts index 2e6afbfb9..a58837010 100644 --- a/src/lib/api/__tests__/community-feed.test.ts +++ b/src/lib/api/__tests__/community-feed.test.ts @@ -1,5 +1,7 @@ -import {type Client} from '@atproto/lex' +import {type Client, XrpcResponseError} from '@atproto/lex' + +import {com} from '#/lexicons' import { ADMIT_FEED_POST, admitFeedPost, @@ -27,21 +29,28 @@ const config = { createdAt: '2026-08-06T12:00:00.000Z', } as const -function mockAgent() { +function xrpcError(status: number, error: string) { + return new XrpcResponseError( + com.atproto.repo.getRecord.main, + new Response(null, {status}), + {encoding: 'application/json', body: {error, message: error}}, + ) +} + +function mockClient() { const getRecord = jest.fn(({collection}: {collection: string}) => { if (collection === 'community.blacksky.feed.config') { - return Promise.resolve({data: {value: config}}) + return Promise.resolve({value: config}) } - return Promise.resolve({ - data: {value: {$type: collection, did: serviceDid}}, - }) + return Promise.resolve({value: {$type: collection, did: serviceDid}}) }) const fetchHandler = jest.fn, [string, RequestInit?]>() return { - agent: { - com: {atproto: {repo: {getRecord}}}, - fetchHandler, - } as unknown as AtpAgent, + client: { + call: (_method: unknown, params: {collection: string}) => + getRecord(params), + agent: {fetchHandler}, + } as unknown as Client, fetchHandler, getRecord, } @@ -54,7 +63,7 @@ describe('community feed API', () => { }) it('loads config and generator records from the feed owner at the same rkey', async () => { - const {client, getRecord} = mockAgent() + const {client, getRecord} = mockClient() await expect(fetchCommunityFeedConfig(client, feed)).resolves.toEqual(config) await expect(fetchFeedServiceDid(client, feed)).resolves.toBe(serviceDid) @@ -72,21 +81,21 @@ describe('community feed API', () => { }) it('distinguishes an absent config from a failed config read', async () => { - const {client, getRecord} = mockAgent() - getRecord.mockRejectedValueOnce(new XRPCError(400, 'RecordNotFound')) + const {client, getRecord} = mockClient() + getRecord.mockRejectedValueOnce(xrpcError(400, 'RecordNotFound')) await expect( fetchCommunityFeedConfigStrict(client, feed), ).resolves.toBeNull() - getRecord.mockRejectedValueOnce(new XRPCError(503, 'UpstreamFailure')) + getRecord.mockRejectedValueOnce(xrpcError(503, 'UpstreamFailure')) await expect(fetchCommunityFeedConfigStrict(client, feed)).rejects.toThrow( 'UpstreamFailure', ) }) it('checks self-scoped permissions with exact service auth and filters unknown values', async () => { - const {client, fetchHandler} = mockAgent() + const {client, fetchHandler} = mockClient() fetchHandler.mockResolvedValue( new Response( JSON.stringify({ @@ -118,14 +127,14 @@ describe('community feed API', () => { }) it('fails closed when the permission service rejects the request', async () => { - const {client, fetchHandler} = mockAgent() + const {client, fetchHandler} = mockClient() fetchHandler.mockResolvedValue(new Response('{}', {status: 403})) await expect(fetchFeedPermissions(client, feed)).resolves.toEqual([]) }) it('resolves a post target only when the user can post', async () => { - const {client, fetchHandler} = mockAgent() + const {client, fetchHandler} = mockClient() fetchHandler.mockResolvedValue( new Response(JSON.stringify({permissions: ['canView', 'canPost']})), ) @@ -139,7 +148,7 @@ describe('community feed API', () => { }) it('fails closed when resolving a post target without canPost', async () => { - const {client, fetchHandler} = mockAgent() + const {client, fetchHandler} = mockClient() fetchHandler.mockResolvedValue( new Response(JSON.stringify({permissions: ['canView']})), ) @@ -148,7 +157,7 @@ describe('community feed API', () => { }) it('admits a canonical record through the feed generator service', async () => { - const {client, fetchHandler} = mockAgent() + const {client, fetchHandler} = mockClient() fetchHandler.mockResolvedValue(new Response('{}')) const post = 'at://did:plc:author/app.bsky.feed.post/3m2post' diff --git a/src/lib/api/__tests__/community-notifications.test.ts b/src/lib/api/__tests__/community-notifications.test.ts index da224503d..c2c4a5812 100644 --- a/src/lib/api/__tests__/community-notifications.test.ts +++ b/src/lib/api/__tests__/community-notifications.test.ts @@ -1,23 +1,10 @@ +// The repo-wide stub of this module rejects every CID the client validates. +jest.unmock('multiformats/cid') -jest.mock('@atproto/api', () => ({ - ...jest.requireActual('@atproto/api'), - jsonToLex: (value: unknown) => value, -})) -jest.mock('multiformats/cid', () => ({ - CID: { - asCID: () => null, - parse: (value: string) => { - if (!value.startsWith('bafy')) throw new Error('invalid cid') - return {toString: () => value} - }, - }, -})) - -import {type Client} from '@atproto/lex' -import {type app} from '#/lexicons' -import {HOME_APPVIEW_PINNED_OPTS} from '#/lib/constants' +import {HOME_PROXY_HEADER} from '#/lib/constants' +import {createLexClient} from '#/lib/lexClient' +import {getErrorName, getErrorStatus} from '#/lib/xrpc-error' import { - type CommunityNotificationXrpcError, GET_UNREAD_COUNT_METHOD, getUnreadCount, LIST_NOTIFICATIONS_METHOD, @@ -27,7 +14,9 @@ import { const SPACE = 'at://did:plc:tenant/space/community.blacksky.feed/private' const PRIVATE_URI = `${SPACE}/did:plc:alice/app.bsky.feed.post/3kprivate` const PUBLIC_URI = 'at://did:plc:alice/app.bsky.feed.post/3kpublic' -const CID = 'bafyreihhl5mpvjkrhnnagen2fomozzhnhhdq2jr6cego2nzbvmwewv5rd4' +const CID = 'bafyreiacsg6vsw7ppwbnowzsdgstulhrwftirtcnvkcbnfgvhwjrnzfmsu' +const STANDARD_LIST = 'app.bsky.notification.listNotifications' +const STANDARD_COUNT = 'app.bsky.notification.getUnreadCount' function notification(uri: string) { return { @@ -55,91 +44,63 @@ function listBody(uri = PRIVATE_URI) { } } -function mockAgent() { +function json(body: unknown, status = 200) { + return new Response(JSON.stringify(body), { + status, + headers: {'content-type': 'application/json'}, + }) +} + +function unsupported() { + return json({error: 'MethodNotImplemented', message: 'not here'}, 501) +} + +function mockClient() { const fetchHandler = jest.fn, [string, RequestInit]>() - const standardList = jest.fn< - Promise<{data: app.bsky.notification.listNotifications.$OutputBody}>, - [app.bsky.notification.listNotifications.$Params, unknown] - >() - const standardCount = jest.fn< - Promise<{data: app.bsky.notification.getUnreadCount.$OutputBody}>, - [app.bsky.notification.getUnreadCount.$Params, unknown] - >() - const client = { - fetchHandler, - app: { - bsky: { - notification: { - listNotifications: standardList, - getUnreadCount: standardCount, - }, - }, - }, - } as unknown as AtpAgent - return {client, fetchHandler, standardList, standardCount} + const client = createLexClient({fetchHandler}) + const request = (call: number) => { + const [path, init] = fetchHandler.mock.calls[call] + return { + method: path.slice('/xrpc/'.length).split('?')[0], + query: new URLSearchParams(path.split('?')[1] ?? ''), + proxy: new Headers(init.headers).get('atproto-proxy'), + } + } + return {client, fetchHandler, request} } describe('community notification API', () => { - it('accepts private notification output rejected by the standard catalog', async () => { - const {client, fetchHandler} = mockAgent() + it('reads notifications on space records from the home appview', async () => { + const {client, fetchHandler, request} = mockClient() const body = listBody() - fetchHandler.mockResolvedValue(new Response(JSON.stringify(body))) - - expect(() => - lexicons.assertValidXrpcOutput( - 'app.bsky.notification.listNotifications', - body, - ), - ).toThrow() + fetchHandler.mockResolvedValue(json(body)) + await expect( listNotifications(client, {limit: 30, reasons: ['mention']}), ).resolves.toEqual(body) - expect(fetchHandler).toHaveBeenCalledWith( - expect.stringContaining(`/xrpc/${LIST_NOTIFICATIONS_METHOD}?`), - expect.objectContaining({method: 'GET'}), - ) - }) - it('keeps public notification output compatible', async () => { - const {client, fetchHandler} = mockAgent() - const body = listBody(PUBLIC_URI) - fetchHandler.mockResolvedValue(new Response(JSON.stringify(body))) - - expect(() => - lexicons.assertValidXrpcOutput( - 'app.bsky.notification.listNotifications', - body, - ), - ).not.toThrow() - await expect(listNotifications(client, {})).resolves.toEqual(body) + expect(fetchHandler).toHaveBeenCalledTimes(1) + expect(request(0).method).toBe(LIST_NOTIFICATIONS_METHOD) + expect(request(0).query.get('limit')).toBe('30') + expect(request(0).query.getAll('reasons')).toEqual(['mention']) + expect(request(0).proxy).toBe(HOME_PROXY_HEADER) }) - it('rejects malformed successful output before returning it', async () => { - const {client, fetchHandler} = mockAgent() - fetchHandler.mockResolvedValue( - new Response(JSON.stringify({notifications: [{uri: PRIVATE_URI}]})), - ) + it('returns public notifications unchanged', async () => { + const {client, fetchHandler} = mockClient() + const body = listBody(PUBLIC_URI) + fetchHandler.mockResolvedValue(json(body)) - await expect(listNotifications(client, {})).rejects.toThrow() + await expect(listNotifications(client, {})).resolves.toEqual(body) }) it('falls back only for a 501 MethodNotImplemented response', async () => { - const {client, fetchHandler, standardList, standardCount} = mockAgent() + const {client, fetchHandler, request} = mockClient() fetchHandler - .mockResolvedValueOnce( - new Response(JSON.stringify({error: 'MethodNotImplemented'}), { - status: 501, - }), - ) - .mockResolvedValueOnce( - new Response(JSON.stringify({error: 'MethodNotImplemented'}), { - status: 501, - }), - ) - standardList.mockResolvedValue({ - data: listBody(PUBLIC_URI), - }) - standardCount.mockResolvedValue({data: {count: 4}}) + .mockResolvedValueOnce(unsupported()) + .mockResolvedValueOnce(json(listBody(PUBLIC_URI))) + .mockResolvedValueOnce(unsupported()) + .mockResolvedValueOnce(json({count: 4})) await expect(listNotifications(client, {limit: 20})).resolves.toEqual( listBody(PUBLIC_URI), @@ -147,54 +108,56 @@ describe('community notification API', () => { await expect(getUnreadCount(client, {priority: true})).resolves.toEqual({ count: 4, }) - expect(standardList).toHaveBeenCalledWith( - {limit: 20}, - HOME_APPVIEW_PINNED_OPTS, - ) - expect(standardCount).toHaveBeenCalledWith( - {priority: true}, - HOME_APPVIEW_PINNED_OPTS, - ) + + expect(fetchHandler).toHaveBeenCalledTimes(4) + expect(request(1).method).toBe(STANDARD_LIST) + expect(request(1).query.get('limit')).toBe('20') + expect(request(1).proxy).toBe(HOME_PROXY_HEADER) + expect(request(3).method).toBe(STANDARD_COUNT) + expect(request(3).query.get('priority')).toBe('true') + expect(request(3).proxy).toBe(HOME_PROXY_HEADER) }) it.each([ [404, 'MethodNotImplemented'], [501, 'UnknownMethod'], - [501, undefined], [403, 'Forbidden'], [503, 'UpstreamFailure'], ])('does not fall back for status %s and error %s', async (status, error) => { - const {client, fetchHandler, standardList} = mockAgent() - fetchHandler.mockResolvedValue( - new Response(JSON.stringify(error ? {error} : {}), {status}), - ) + const {client, fetchHandler} = mockClient() + fetchHandler.mockResolvedValue(json({error, message: error}, status)) - await expect(listNotifications(client, {})).rejects.toEqual( - expect.objectContaining>({ - status, - error, - }), + const failure: unknown = await listNotifications(client, {}).catch( + (e: unknown) => e, ) - expect(standardList).not.toHaveBeenCalled() + + expect(getErrorStatus(failure)).toBe(status) + expect(getErrorName(failure)).toBe(error) + expect(fetchHandler).toHaveBeenCalledTimes(1) + }) + + it('does not fall back for a 501 that names no error', async () => { + const {client, fetchHandler} = mockClient() + fetchHandler.mockResolvedValue(json({}, 501)) + + await expect(listNotifications(client, {})).rejects.toBeDefined() + expect(fetchHandler).toHaveBeenCalledTimes(1) }) it('surfaces transport failures without fallback', async () => { - const {client, fetchHandler, standardList} = mockAgent() - const error = new Error('offline') - fetchHandler.mockRejectedValue(error) + const {client, fetchHandler} = mockClient() + fetchHandler.mockRejectedValue(new Error('offline')) - await expect(listNotifications(client, {})).rejects.toBe(error) - expect(standardList).not.toHaveBeenCalled() + await expect(listNotifications(client, {})).rejects.toBeDefined() + expect(fetchHandler).toHaveBeenCalledTimes(1) }) - it('validates and returns the custom unread count', async () => { - const {client, fetchHandler} = mockAgent() - fetchHandler.mockResolvedValue(new Response(JSON.stringify({count: 8}))) + it('returns the community unread count', async () => { + const {client, fetchHandler, request} = mockClient() + fetchHandler.mockResolvedValue(json({count: 8})) await expect(getUnreadCount(client)).resolves.toEqual({count: 8}) - expect(fetchHandler).toHaveBeenCalledWith( - `/xrpc/${GET_UNREAD_COUNT_METHOD}`, - expect.objectContaining({method: 'GET'}), - ) + expect(request(0).method).toBe(GET_UNREAD_COUNT_METHOD) + expect(request(0).proxy).toBe(HOME_PROXY_HEADER) }) }) diff --git a/src/lib/api/__tests__/community.test.ts b/src/lib/api/__tests__/community.test.ts index c33d579b9..d010c16ac 100644 --- a/src/lib/api/__tests__/community.test.ts +++ b/src/lib/api/__tests__/community.test.ts @@ -1,9 +1,4 @@ -jest.mock('@atproto/api', () => ({ - ...jest.requireActual('@atproto/api'), - jsonToLex: (value: unknown) => value, -})) - import {type Client} from '@atproto/lex' import { BLUESKY_FALLBACK_PROXY_HEADER, @@ -26,15 +21,15 @@ describe('communityXrpc', () => { BLUESKY_PROXY_HEADER.set(originalHeader) }) - function mockAgent() { + function mockClient() { const fetchHandler = jest.fn, [string, RequestInit]>() fetchHandler.mockResolvedValue(new Response('{}')) - return {agent: {fetchHandler} as unknown as BskyAgent, fetchHandler} + return {client: {agent: {fetchHandler}} as unknown as Client, fetchHandler} } it('always targets the home appview, even when the global proxy header is flipped', async () => { BLUESKY_PROXY_HEADER.set(BLUESKY_FALLBACK_PROXY_HEADER) - const {client, fetchHandler} = mockAgent() + const {client, fetchHandler} = mockClient() await communityXrpc(client, 'community.blacksky.feed.getCommunityTimeline') @@ -48,7 +43,7 @@ describe('communityXrpc', () => { }) it('can target a configured content store', async () => { - const {client, fetchHandler} = mockAgent() + const {client, fetchHandler} = mockClient() await communityXrpc(client, 'community.blacksky.feed.submitPost', { body: {text: 'hello'}, @@ -64,7 +59,7 @@ describe('communityXrpc', () => { }) it('serializes repeated primitive parameters and omits empty values', async () => { - const {client, fetchHandler} = mockAgent() + const {client, fetchHandler} = mockClient() await communityXrpc( client, @@ -91,7 +86,7 @@ describe('communityXrpc', () => { }) it('fetches space likes through the permission-aware endpoint', async () => { - const {client, fetchHandler} = mockAgent() + const {client, fetchHandler} = mockClient() fetchHandler.mockResolvedValue( new Response( JSON.stringify({ @@ -131,7 +126,7 @@ describe('communityXrpc', () => { }) it('converts custom space quote views into standard renderer views', async () => { - const {client, fetchHandler} = mockAgent() + const {client, fetchHandler} = mockClient() fetchHandler.mockResolvedValue( new Response( JSON.stringify({ diff --git a/src/lib/api/__tests__/group-invites.test.ts b/src/lib/api/__tests__/group-invites.test.ts index 6e9ebfcde..3c5ce35e0 100644 --- a/src/lib/api/__tests__/group-invites.test.ts +++ b/src/lib/api/__tests__/group-invites.test.ts @@ -83,14 +83,14 @@ describe('group invite client API', () => { }, }), ) - const agent = {} as Parameters[0]['agent'] + const client = {} as Parameters[0]['client'] await expect( - acceptGroupInvite({code: CODE, communityDid: COMMUNITY_DID, agent}), + acceptGroupInvite({code: CODE, communityDid: COMMUNITY_DID, client}), ).resolves.toMatchObject({membership: 'joined'}) expect(mockGetServiceAuthToken).toHaveBeenCalledWith( expect.objectContaining({ - agent, + client, aud: COMMUNITY_DID, lxm: 'community.blacksky.group.acceptInvite', }), @@ -112,7 +112,7 @@ describe('group invite client API', () => { acceptGroupInvite({ code: CODE, communityDid: COMMUNITY_DID, - agent: {} as Parameters[0]['agent'], + client: {} as Parameters[0]['client'], }), ).rejects.toMatchObject({code: GroupInviteError.AuthenticationRequired}) expect(fetchMock).not.toHaveBeenCalled() @@ -176,7 +176,7 @@ describe('group invite client API', () => { acceptGroupInvite({ code: CODE, communityDid: COMMUNITY_DID, - agent: {} as Parameters[0]['agent'], + client: {} as Parameters[0]['client'], }), ).rejects.toMatchObject({code: GroupInviteError.AuthorizationUnavailable}) }) diff --git a/src/lib/api/__tests__/space-post-poll.test.ts b/src/lib/api/__tests__/space-post-poll.test.ts index b7d94ead1..db68638b7 100644 --- a/src/lib/api/__tests__/space-post-poll.test.ts +++ b/src/lib/api/__tests__/space-post-poll.test.ts @@ -28,7 +28,10 @@ const draft = (embed: Record) => ({ describe('posting a thread into a space', () => { it('refuses the whole thread before the first write when any post has a poll', async () => { await expect( - postToSpace({} as AtpAgent, {} as QueryClient, SPACE, { + postToSpace({} as QueryClient, SPACE, { + appviewClient: {} as Client, + chatClient: {} as Client, + pdsClient: {} as Client, thread: { posts: [draft({}), draft({poll: {statements: ['A']}})], postgate: {}, diff --git a/src/lib/api/__tests__/space-post.test.ts b/src/lib/api/__tests__/space-post.test.ts index 8103b05b6..79b801589 100644 --- a/src/lib/api/__tests__/space-post.test.ts +++ b/src/lib/api/__tests__/space-post.test.ts @@ -26,7 +26,12 @@ jest.mock('../space-write', () => ({ const SPACE = 'at://did:plc:space/space/community.blacksky.feed/private' const OTHER = 'at://did:plc:other/space/community.blacksky.feed/private' -const client = {} as AtpAgent +const client = {} as Client +const clients = { + appviewClient: client, + chatClient: client, + pdsClient: client, +} const queryClient = {} as QueryClient const thread = (embed: object = {}, id = 'draft-operation-1') => @@ -51,7 +56,8 @@ describe(postToSpace, () => { it('refuses a quote from another space before embed resolution', async () => { await expect( - postToSpace(client, queryClient, SPACE, { + postToSpace(queryClient, SPACE, { + ...clients, thread: thread({ quote: { uri: `${OTHER}/did:plc:author/app.bsky.feed.post/3kquote`, @@ -65,7 +71,7 @@ describe(postToSpace, () => { }) it('uses the stable protocol-valid draft id as the record key', async () => { - await postToSpace(client, queryClient, SPACE, {thread: thread()}) + await postToSpace(queryClient, SPACE, {...clients, thread: thread()}) expect(spaceCreateRecord).toHaveBeenCalledWith( client, @@ -77,10 +83,10 @@ describe(postToSpace, () => { }) it('derives a stable record key from a saved draft id and post index', async () => { - const opts = {thread: thread(), draftId: '3mabcde234567'} + const opts = {...clients, thread: thread(), draftId: '3mabcde234567'} - await postToSpace(client, queryClient, SPACE, opts) - await postToSpace(client, queryClient, SPACE, opts) + await postToSpace(queryClient, SPACE, opts) + await postToSpace(queryClient, SPACE, opts) expect(spaceCreateRecord).toHaveBeenNthCalledWith( 1, @@ -102,7 +108,10 @@ describe(postToSpace, () => { it('rejects an invalid draft id before writing', async () => { await expect( - postToSpace(client, queryClient, SPACE, {thread: thread({}, 'bad/id')}), + postToSpace(queryClient, SPACE, { + ...clients, + thread: thread({}, 'bad/id'), + }), ).rejects.toThrow(/record key/i) expect(spaceCreateRecord).not.toHaveBeenCalled() diff --git a/src/lib/api/__tests__/space-write.test.ts b/src/lib/api/__tests__/space-write.test.ts index 3c5fabb69..0a914e007 100644 --- a/src/lib/api/__tests__/space-write.test.ts +++ b/src/lib/api/__tests__/space-write.test.ts @@ -29,7 +29,7 @@ type Call = { } type MockResponse = {status?: number; body?: unknown} -function agentWith( +function clientWith( response: MockResponse | MockResponse[] = {}, signedIn = true, ) { @@ -37,8 +37,10 @@ function agentWith( const responses = Array.isArray(response) ? response : [response] let responseIndex = 0 const client = { - ...(signedIn ? {session: {did: 'did:plc:me'}} : {}), - fetchHandler(path: string, init: RequestInit) { + ...(signedIn ? {did: 'did:plc:me'} : {}), + agent: {fetchHandler}, + } as unknown as Client + function fetchHandler(path: string, init: RequestInit) { const current = responses[Math.min(responseIndex++, responses.length - 1)] const status = current.status ?? 200 calls.push({ @@ -54,9 +56,8 @@ function agentWith( Promise.resolve( current.body ?? {uri: 'at://space/record', cid: 'bafyreinew'}, ), - } as unknown as Response) - }, - } as unknown as BskyAgent + } as unknown as Response) + } return {client, calls} } @@ -65,7 +66,7 @@ const bodyOf = (call: Call): Record => describe('space writes', () => { it('posts to the account’s own pds without a proxy header', async () => { - const {client, calls} = agentWith() + const {client, calls} = clientWith() await spaceCreateRecord(client, SPACE, POST_COLLECTION, { $type: POST_COLLECTION, text: 'hello', @@ -86,7 +87,7 @@ describe('space writes', () => { }) it('uses an explicit stable rkey or generates a protocol key', async () => { - const {client, calls} = agentWith() + const {client, calls} = clientWith() await spaceCreateRecord(client, SPACE, POST_COLLECTION, {}, '3kxyz') expect(bodyOf(calls[0]).rkey).toBe('3kxyz') @@ -101,7 +102,7 @@ describe('space writes', () => { createdAt: '2026-08-26T12:00:00.000Z', } const original = {uri: 'at://space/original', cid: 'bafyreioriginal'} - const {client, calls} = agentWith([ + const {client, calls} = clientWith([ {body: original}, {status: 400, body: {error: 'RecordExists'}}, {body: {...original, value: record}}, @@ -137,7 +138,7 @@ describe('space writes', () => { }) it('writes a like into the permissioned repo, never the public one', async () => { - const {client, calls} = agentWith() + const {client, calls} = clientWith() await spaceLike(client, SPACE, SUBJECT) // The one thing that must never happen: com.atproto.repo.createRecord with @@ -152,7 +153,7 @@ describe('space writes', () => { }) it('unlikes by the rkey of the like record', async () => { - const {client, calls} = agentWith({body: {}}) + const {client, calls} = clientWith({body: {}}) await spaceUnlike( client, SPACE, @@ -169,14 +170,14 @@ describe('space writes', () => { }) it('deletes one of the caller’s own records', async () => { - const {client, calls} = agentWith({body: {}}) + const {client, calls} = clientWith({body: {}}) await spaceDeleteRecord(client, SPACE, POST_COLLECTION, '3kpost') expect(bodyOf(calls[0]).rkey).toBe('3kpost') expect(bodyOf(calls[0]).repo).toBe('did:plc:me') }) it('fails before issuing a request when the client is signed out', async () => { - const {client, calls} = agentWith({}, false) + const {client, calls} = clientWith({}, false) await expect( spaceCreateRecord(client, SPACE, POST_COLLECTION, {}), @@ -188,7 +189,7 @@ describe('space writes', () => { }) it('reads a 404 as “this pds has no space support”', async () => { - const {client} = agentWith({status: 404}) + const {client} = clientWith({status: 404}) // A PDS that never heard of the method answers 404 rather than an XRPC // error; that is how a foreign-PDS account is recognised so the UI can // offer migration instead of a generic failure. @@ -198,7 +199,7 @@ describe('space writes', () => { }) it('surfaces the host’s own message on other failures', async () => { - const {client} = agentWith({ + const {client} = clientWith({ status: 429, body: {error: 'RateLimitExceeded', message: 'records quota exceeded'}, }) @@ -208,7 +209,7 @@ describe('space writes', () => { }) it('refuses a response that names no record', async () => { - const {client} = agentWith({body: {cid: 'bafyreinew'}}) + const {client} = clientWith({body: {cid: 'bafyreinew'}}) await expect( spaceCreateRecord(client, SPACE, POST_COLLECTION, {}), ).rejects.toThrow(/no record reference/) @@ -220,7 +221,7 @@ const PUBLIC_LIKE = 'at://did:plc:alice/app.bsky.feed.like/3klike' describe('interaction routing', () => { it('likes a space post into its own space', async () => { - const {client, calls} = agentWith() + const {client, calls} = clientWith() await spaceLikeIfSpace(client, SUBJECT.uri, SUBJECT.cid) @@ -234,7 +235,7 @@ describe('interaction routing', () => { }) it('unlikes and deletes within the space the record belongs to', async () => { - const {client, calls} = agentWith({body: {}}) + const {client, calls} = clientWith({body: {}}) await spaceUnlikeIfSpace( client, @@ -266,7 +267,7 @@ describe('interaction routing', () => { ['unlike', (a: Client) => spaceUnlikeIfSpace(a, PUBLIC_LIKE)], ['delete', (a: Client) => spaceDeleteIfSpace(a, PUBLIC_POST)], ])('leaves a public %s to the public repo', (_name, run) => { - const {client, calls} = agentWith() + const {client, calls} = clientWith() // null means "not mine" — the caller falls back to the ordinary client call. expect(run(client)).toBeNull() diff --git a/src/lib/api/community-notifications.ts b/src/lib/api/community-notifications.ts index d2171dff2..1af8b5741 100644 --- a/src/lib/api/community-notifications.ts +++ b/src/lib/api/community-notifications.ts @@ -1,7 +1,6 @@ -import {type Client} from '@atproto/lex' +import {type Client, XrpcResponseError} from '@atproto/lex' import {HOME_APPVIEW_PINNED_OPTS} from '#/lib/constants' -import {getErrorName, getErrorStatus} from '#/lib/xrpc-error' import {app, community} from '#/lexicons' export const LIST_NOTIFICATIONS_METHOD = @@ -13,9 +12,19 @@ export const GET_UNREAD_COUNT_METHOD = * An appview that predates these methods answers 501 MethodNotImplemented. The * standard methods then return the public notifications, which is everything * such an appview knows about. + * + * The name is read from the response body: the client also derives it from a + * bare 501, which any intermediary can answer. */ function isUnsupportedMethod(e: unknown): boolean { - return getErrorStatus(e) === 501 && getErrorName(e) === 'MethodNotImplemented' + if (!(e instanceof XrpcResponseError) || e.status !== 501) return false + const body = e.body + return ( + typeof body === 'object' && + body !== null && + 'error' in body && + body.error === 'MethodNotImplemented' + ) } export async function listNotifications( diff --git a/src/lib/media/video/__tests__/upload.test.ts b/src/lib/media/video/__tests__/upload.test.ts index 1381e2617..51b1bb42a 100644 --- a/src/lib/media/video/__tests__/upload.test.ts +++ b/src/lib/media/video/__tests__/upload.test.ts @@ -6,10 +6,8 @@ jest.mock('expo-file-system/legacy', () => ({ FileSystemUploadType: {BINARY_CONTENT: 0}, createUploadTask: mockCreateUploadTask, })) -jest.mock('#/lib/api/service-auth', () => ({ - getServiceAuthToken: jest.fn().mockResolvedValue('token'), -})) jest.mock('../upload.shared', () => ({ + getServiceAuthToken: jest.fn().mockResolvedValue('token'), getVideoUploadLimits: jest.fn().mockResolvedValue(undefined), })) @@ -29,7 +27,8 @@ describe('uploadVideo', () => { async (isPrivate, expected) => { await uploadVideo({ video: {uri: 'file:///video.mp4', mimeType: 'video/mp4'} as never, - agent: {} as never, + client: {} as never, + dispatchUrl: 'https://pds.test', did: 'did:plc:test', setProgress: jest.fn(), signal: new AbortController().signal, -- knotmirror 0.0.1