import { describe, it, expect, vi, beforeEach } from 'vitest'; // Mock API client and DB queries before importing the engine vi.mock('../api/client', () => ({ fetchEntries: vi.fn(), patchEntry: vi.fn(), deleteEntryApi: vi.fn(), addEntry: vi.fn(), searchEntries: vi.fn() })); vi.mock('../db/queries', () => ({ upsertEntries: vi.fn(), deleteEntry: vi.fn(), saveSettings: vi.fn(), getSettings: vi.fn(), getPendingMutations: vi.fn(), removeMutation: vi.fn(), incrementMutationAttempt: vi.fn(), getAllEntryIds: vi.fn(), enqueueMutation: vi.fn(), getEntries: vi.fn() })); vi.mock('dompurify', () => ({ default: { sanitize: (html: string) => html } })); import { syncIncremental, syncFull, drainMutationQueue, addArticleByUrl, searchArticles, extractImageUrls, prefetchImageUrls, prefetchUnreadForOffline } from './engine'; import { fetchEntries, patchEntry, deleteEntryApi, addEntry, searchEntries } from '../api/client'; import { upsertEntries, deleteEntry, saveSettings, getSettings, getPendingMutations, removeMutation, incrementMutationAttempt, getAllEntryIds, enqueueMutation, getEntries } from '../db/queries'; const mockFetchEntries = vi.mocked(fetchEntries); const mockPatchEntry = vi.mocked(patchEntry); const mockDeleteEntryApi = vi.mocked(deleteEntryApi); const mockAddEntry = vi.mocked(addEntry); const mockSearchEntries = vi.mocked(searchEntries); const mockGetEntries = vi.mocked(getEntries); const mockUpsertEntries = vi.mocked(upsertEntries); const mockDeleteEntry = vi.mocked(deleteEntry); const mockSaveSettings = vi.mocked(saveSettings); const mockGetSettings = vi.mocked(getSettings); const mockGetPendingMutations = vi.mocked(getPendingMutations); const mockRemoveMutation = vi.mocked(removeMutation); const mockIncrementMutationAttempt = vi.mocked(incrementMutationAttempt); const mockGetAllEntryIds = vi.mocked(getAllEntryIds); const mockEnqueueMutation = vi.mocked(enqueueMutation); function makeRawEntry(id: number) { return { id, title: `Article ${id}`, url: `https://example.com/${id}`, origin_url: null, content: `
content ${id}
`, preview_picture: null, domain_name: 'example.com', reading_time: 3, language: 'en', is_archived: 0 as 0 | 1, is_starred: 0 as 0 | 1, created_at: '2024-01-01T00:00:00Z', updated_at: '2024-01-01T00:00:00Z', published_at: null, tags: [] }; } function makeMutation( overrides: Partial<{ id: number; entry_id: number; type: 'archive' | 'unarchive' | 'star' | 'unstar' | 'delete' | 'add'; attempts: number; created_at: number; payload: Recordcontent 1
'); }); }); describe('syncFull', () => { it('deletes local entries that no longer exist on the server', async () => { // First call: incremental (since=0), returns entries 1 and 2 // Second call: full (since=0 again), returns only entry 1 mockFetchEntries .mockResolvedValueOnce({ entries: [makeRawEntry(1), makeRawEntry(2)], pages: 1 }) .mockResolvedValueOnce({ entries: [makeRawEntry(1)], pages: 1 }); mockGetAllEntryIds.mockResolvedValue([1, 2]); mockDeleteEntry.mockResolvedValue(undefined); const { deleted } = await syncFull(); expect(mockDeleteEntry).toHaveBeenCalledWith(2); expect(deleted).toBe(1); }); }); describe('drainMutationQueue', () => { it('calls patchEntry with archive:1 for archive mutations', async () => { mockGetPendingMutations.mockResolvedValue([makeMutation({ type: 'archive' })]); mockPatchEntry.mockResolvedValue({} as never); await drainMutationQueue(); expect(mockPatchEntry).toHaveBeenCalledWith(1, { archive: 1 }); expect(mockRemoveMutation).toHaveBeenCalledWith(1); }); it('calls patchEntry with archive:0 for unarchive mutations', async () => { mockGetPendingMutations.mockResolvedValue([makeMutation({ type: 'unarchive' })]); mockPatchEntry.mockResolvedValue({} as never); await drainMutationQueue(); expect(mockPatchEntry).toHaveBeenCalledWith(1, { archive: 0 }); }); it('calls patchEntry with starred:1/0 for star/unstar mutations', async () => { mockGetPendingMutations.mockResolvedValue([ makeMutation({ id: 1, type: 'star' }), makeMutation({ id: 2, type: 'unstar' }) ]); mockPatchEntry.mockResolvedValue({} as never); await drainMutationQueue(); expect(mockPatchEntry).toHaveBeenCalledWith(1, { starred: 1 }); expect(mockPatchEntry).toHaveBeenCalledWith(1, { starred: 0 }); }); it('calls deleteEntryApi for delete mutations', async () => { mockGetPendingMutations.mockResolvedValue([makeMutation({ type: 'delete' })]); mockDeleteEntryApi.mockResolvedValue(undefined); await drainMutationQueue(); expect(mockDeleteEntryApi).toHaveBeenCalledWith(1); expect(mockRemoveMutation).toHaveBeenCalledWith(1); }); it('calls addEntry and upserts the result for add mutations', async () => { mockGetPendingMutations.mockResolvedValue([ makeMutation({ type: 'add', payload: { url: 'https://new.example.com' } }) ]); mockAddEntry.mockResolvedValue(makeRawEntry(42)); await drainMutationQueue(); expect(mockAddEntry).toHaveBeenCalledWith('https://new.example.com'); expect(mockUpsertEntries).toHaveBeenCalledWith([ expect.objectContaining({ id: 42, cached_at: expect.any(Number) }) ]); expect(mockRemoveMutation).toHaveBeenCalledWith(1); }); it('increments attempts and stores error on failure', async () => { mockGetPendingMutations.mockResolvedValue([makeMutation({ type: 'archive' })]); mockPatchEntry.mockRejectedValue(new Error('Network error')); await drainMutationQueue(); expect(mockRemoveMutation).not.toHaveBeenCalled(); expect(mockIncrementMutationAttempt).toHaveBeenCalledWith(1, 'Network error'); }); it('silently drops a delete mutation when server returns 404', async () => { mockGetPendingMutations.mockResolvedValue([makeMutation({ type: 'delete' })]); mockDeleteEntryApi.mockRejectedValue(new Error('API error: 404 Not Found')); await drainMutationQueue(); expect(mockRemoveMutation).toHaveBeenCalledWith(1); expect(mockIncrementMutationAttempt).not.toHaveBeenCalled(); }); it('skips mutations whose backoff period has not elapsed', async () => { // attempts=1 → backoff is 5000ms; created_at is only 1000ms ago → skip mockGetPendingMutations.mockResolvedValue([ makeMutation({ attempts: 1, created_at: Date.now() - 1000 }) ]); await drainMutationQueue(); expect(mockPatchEntry).not.toHaveBeenCalled(); }); }); describe('addArticleByUrl', () => { it('returns the upserted entry on a successful add', async () => { mockAddEntry.mockResolvedValue(makeRawEntry(7)); const result = await addArticleByUrl('https://example.com/x'); expect(mockAddEntry).toHaveBeenCalledWith('https://example.com/x'); expect(mockUpsertEntries).toHaveBeenCalledWith([expect.objectContaining({ id: 7 })]); expect(mockEnqueueMutation).not.toHaveBeenCalled(); expect(result).toEqual({ status: 'added', entry: expect.objectContaining({ id: 7 }) }); }); it('queues a pending mutation when addEntry throws', async () => { mockAddEntry.mockRejectedValue(new Error('Network down')); const result = await addArticleByUrl('https://example.com/x'); expect(mockEnqueueMutation).toHaveBeenCalledWith({ entry_id: 0, type: 'add', payload: { url: 'https://example.com/x' } }); expect(mockUpsertEntries).not.toHaveBeenCalled(); expect(result).toEqual({ status: 'queued' }); }); }); describe('extractImageUrls', () => { it('returns the preview picture and anyHello

',
cached_at: 0
}
];
const urls = extractImageUrls(entries as never);
expect(urls).toEqual(
expect.arrayContaining([
'https://cdn.example.com/cover.jpg',
'https://cdn.example.com/inline.jpg',
'https://cdn.example.com/two.png'
])
);
expect(urls).toHaveLength(3);
});
it('deduplicates URLs across entries', () => {
const entries = [
{
...makeRawEntry(1),
preview_picture: 'https://cdn.example.com/x.jpg',
content: '
',
cached_at: 0
},
{
...makeRawEntry(2),
preview_picture: 'https://cdn.example.com/x.jpg',
content: '',
cached_at: 0
}
];
expect(extractImageUrls(entries as never)).toEqual(['https://cdn.example.com/x.jpg']);
});
it('skips non-http schemes (data:, file:, javascript:)', () => {
const entries = [
{
...makeRawEntry(1),
preview_picture: 'data:image/png;base64,AAA',
content:
'
',
cached_at: 0
}
];
expect(extractImageUrls(entries as never)).toEqual(['https://ok.example/yes.jpg']);
});
it('handles entries with no images at all', () => {
const entries = [
{
...makeRawEntry(1),
preview_picture: null,
content: 'Pure text
', cached_at: 0 } ]; expect(extractImageUrls(entries as never)).toEqual([]); }); it('tolerates missing content field', () => { const entries = [ { ...makeRawEntry(1), preview_picture: null, content: '', cached_at: 0 } ]; expect(extractImageUrls(entries as never)).toEqual([]); }); }); describe('prefetchImageUrls', () => { beforeEach(() => { // Stub a minimal Image constructor that resolves immediately on src set. class FakeImage { onload: (() => void) | null = null; onerror: (() => void) | null = null; set src(_value: string) { queueMicrotask(() => this.onload?.()); } } vi.stubGlobal('Image', FakeImage); }); it('reports progress for every URL and finishes once all settle', async () => { const calls: Array<[number, number]> = []; await prefetchImageUrls(['https://a.example/1.jpg', 'https://a.example/2.jpg'], (done, total) => calls.push([done, total]) ); // Initial 0/total + one update per URL completion expect(calls[0]).toEqual([0, 2]); expect(calls.at(-1)).toEqual([2, 2]); }); it('is a no-op for an empty list', async () => { const onProgress = vi.fn(); await prefetchImageUrls([], onProgress); expect(onProgress).toHaveBeenCalledWith(0, 0); }); }); describe('prefetchUnreadForOffline', () => { beforeEach(() => { class FakeImage { onload: (() => void) | null = null; onerror: (() => void) | null = null; set src(_value: string) { queueMicrotask(() => this.onload?.()); } } vi.stubGlobal('Image', FakeImage); }); it('returns counts of entries scanned and unique images prefetched', async () => { mockGetEntries.mockResolvedValue([ { ...makeRawEntry(1), preview_picture: 'https://cdn.example.com/a.jpg', content: '
',
cached_at: 0
},
{
...makeRawEntry(2),
preview_picture: 'https://cdn.example.com/a.jpg',
content: '',
cached_at: 0
}
] as never);
const result = await prefetchUnreadForOffline();
expect(mockGetEntries).toHaveBeenCalledWith('unread');
expect(result).toEqual({ entries: 2, images: 2 });
});
it('handles the empty-unread case without errors', async () => {
mockGetEntries.mockResolvedValue([]);
const result = await prefetchUnreadForOffline();
expect(result).toEqual({ entries: 0, images: 0 });
});
});
describe('searchArticles', () => {
it('returns sanitized entries and caches them locally', async () => {
mockSearchEntries.mockResolvedValue({
entries: [makeRawEntry(1), makeRawEntry(2)],
pages: 1
});
const results = await searchArticles('test');
expect(mockSearchEntries).toHaveBeenCalledWith('test');
expect(results).toHaveLength(2);
expect(results[0]).toHaveProperty('cached_at');
expect(mockUpsertEntries).toHaveBeenCalledWith(results);
});
it('does not call upsertEntries when results are empty', async () => {
mockSearchEntries.mockResolvedValue({ entries: [], pages: 1 });
const results = await searchArticles('empty');
expect(results).toEqual([]);
expect(mockUpsertEntries).not.toHaveBeenCalled();
});
it('propagates API errors', async () => {
mockSearchEntries.mockRejectedValue(new Error('API error: 500'));
await expect(searchArticles('bad')).rejects.toThrow('API error: 500');
});
});