Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
refactor(ts): type the frontend tests
spacesdrive6889daca6b3c
diff --git a/frontend/tests/docs/nav.test.ts b/frontend/tests/docs/nav.test.tsindex 390051c..7dc96a8 100644--- a/frontend/tests/docs/nav.test.ts+++ b/frontend/tests/docs/nav.test.ts@@ -16,8 +16,8 @@ test('page paths are unique', () => {test('neighbours link the first and last pages correctly', () => {assert.equal(neighbours('/docs').prev, null);- assert.equal(neighbours('/docs').next.path, '/docs/concepts');- assert.equal(neighbours(ALL_DOC_PAGES.at(-1).path).next, null);+ assert.equal(neighbours('/docs').next!.path, '/docs/concepts');+ assert.equal(neighbours(ALL_DOC_PAGES.at(-1)!.path).next, null);});test('tabForPath falls back to the first tab for unknown paths', () => {diff --git a/frontend/tests/docs/pages/selfHost/selfHostSql.test.ts b/frontend/tests/docs/pages/selfHost/selfHostSql.test.tsindex 3cd68f6..e6d36da 100644--- a/frontend/tests/docs/pages/selfHost/selfHostSql.test.ts+++ b/frontend/tests/docs/pages/selfHost/selfHostSql.test.ts@@ -2,8 +2,8 @@ import { test } from 'node:test';import assert from 'node:assert/strict';import { SCHEMA_SQL, RLS_SQL, UPGRADE_SQL } from '../../../../src/docs/pages/selfHost/selfHostSql.ts';-const tablesIn = sql => [...sql.matchAll(/create table (\w+)/g)].map(match => match[1]);-const secured = sql => [...sql.matchAll(/alter table (\w+) enable row level security;/g)].map(match => match[1]);+const tablesIn = (sql: string) => [...sql.matchAll(/create table (\w+)/g)].map(match => match[1]);+const secured = (sql: string) => [...sql.matchAll(/alter table (\w+) enable row level security;/g)].map(match => match[1]);test('every table in the schema turns on row level security', () => {const tables = tablesIn(SCHEMA_SQL);diff --git a/frontend/tests/features/accounts/accountManagerData.test.ts b/frontend/tests/features/accounts/accountManagerData.test.tsindex a6e42b2..2b9016c 100644--- a/frontend/tests/features/accounts/accountManagerData.test.ts+++ b/frontend/tests/features/accounts/accountManagerData.test.ts@@ -4,7 +4,7 @@ import {TESTER_HINT, instagramErrorMessage, readOAuthReturn, accountMetrics, accountCardHandle, visibleSections,} from '../../../src/features/accounts/accountManagerData.ts';-const params = query => new URLSearchParams(query);+const params = (query: string) => new URLSearchParams(query);test('known Instagram errors have their own message', () => {assert.equal(instagramErrorMessage('already_added'), 'This Instagram account is already connected.');@@ -29,7 +29,7 @@ test('connected values other than true are dropped silently', () => {});test('errors and the add flag are read together', () => {- const result = readOAuthReturn(params('ig_error=cancelled&add=1'));+ const result = readOAuthReturn(params('ig_error=cancelled&add=1'))!;assert.equal(result.connected, false);assert.equal(result.errorMessage, 'Instagram sign-in was cancelled. Try again when you are ready.');assert.equal(result.openAdd, true);diff --git a/frontend/tests/features/analytics/channel/channelChartData.test.ts b/frontend/tests/features/analytics/channel/channelChartData.test.tsindex 1d07710..b08ed0f 100644--- a/frontend/tests/features/analytics/channel/channelChartData.test.ts+++ b/frontend/tests/features/analytics/channel/channelChartData.test.ts@@ -5,17 +5,18 @@ import {topVideosChartOf, topVideoRowsOf, viewRangeDataOf, uploadsByMonthOf, rateOf, likesPerComment, peakHourLabel,bestVideosOf, likesLabel,} from '../../../../src/features/analytics/channel/channelChartData.ts';+import type { VideoAnalytics, YouTubeVideoSummary } from '../../../../../shared/types/youtube.ts';test('watch links point at YouTube', () => {assert.equal(watchUrl('abc'), 'https://www.youtube.com/watch?v=abc');});test('channel meta skips an unknown country and a missing handle', () => {- const meta = channelMeta({ country: 'Unknown', channelAgeYears: 3, publishedAt: '2023-01-05T12:00:00Z' });+ const meta = channelMeta({ country: 'Unknown', channelAgeYears: 3 as unknown as string, publishedAt: '2023-01-05T12:00:00Z' });assert.equal(meta.length, 2);assert.equal(meta[0], '3 years old');assert.ok(meta[1].startsWith('Since '));- assert.equal(channelMeta({ customUrl: '@dusk', country: 'IN', channelAgeYears: 1 })[1], 'IN');+ assert.equal(channelMeta({ customUrl: '@dusk', country: 'IN', channelAgeYears: 1 as unknown as string })[1], 'IN');});test('publish distributions become chart rows', () => {@@ -37,7 +38,7 @@ test('categories use their name or a numbered fallback', () => {});test('top video chart truncates titles and always adds an ellipsis', () => {- const rows = topVideosChartOf([{ title: 'Short', viewCount: 5 }, null]);+ const rows = topVideosChartOf([{ title: 'Short', viewCount: 5 }, null] as (YouTubeVideoSummary | null)[]);assert.deepEqual(rows[0], { name: 'Short…', views: 5, likes: 0 });assert.deepEqual(rows[1], { name: '…', views: 0, likes: 0 });assert.deepEqual(topVideosChartOf(undefined), []);@@ -47,7 +48,7 @@ test('top video rows merge both lists once each, by views', () => {const analytics = {top10ByViews: [{ videoId: 'a', viewCount: 10 }, { videoId: 'b', viewCount: 30 }],top10ByLikes: [{ videoId: 'b', viewCount: 30 }, null, { videoId: 'c', viewCount: 20 }],- };+ } as Pick<VideoAnalytics, 'top10ByViews' | 'top10ByLikes'>;assert.deepEqual(topVideoRowsOf(analytics).map(video => video.videoId), ['b', 'c', 'a']);assert.deepEqual(topVideoRowsOf({}), []);});@@ -73,7 +74,7 @@ test('peak hour treats only a missing hour as unavailable', () => {});test('best videos and like labels', () => {- const best = bestVideosOf({ bestByViews: { videoId: 'a' }, bestByEngagement: { videoId: 'b' } });+ const best = bestVideosOf({ bestByViews: { videoId: 'a' }, bestByEngagement: { videoId: 'b' } } as unknown as VideoAnalytics);assert.deepEqual(best.map(item => item.label), ['Most viewed', 'Best engagement']);assert.equal(likesLabel(undefined), 'likes hidden');assert.equal(likesLabel(null), 'likes hidden');diff --git a/frontend/tests/features/analytics/instagram/instagramAnalyticsData.test.ts b/frontend/tests/features/analytics/instagram/instagramAnalyticsData.test.tsindex 5be4de2..f45efc0 100644--- a/frontend/tests/features/analytics/instagram/instagramAnalyticsData.test.ts+++ b/frontend/tests/features/analytics/instagram/instagramAnalyticsData.test.ts@@ -4,6 +4,7 @@ import {typeRowsOf, contentMixOf, topPostsChartOf, dayOfWeekDataOf, timelineDataOf, instagramChartsOf, followerRatio,typeViewsSubtitle, reportedViews,} from '../../../../src/features/analytics/instagram/instagramAnalyticsData.ts';+import type { InstagramContentTypeStatsMap, InstagramDayStats, InstagramMonthStats } from '../../../../../shared/types/instagram.ts';const typeStats = {reel: { count: 3, avgLikes: 10, viewsReported: 3, totalViews: 4500, avgViews: 1500 },@@ -12,7 +13,7 @@ const typeStats = {};test('type rows keep content types with posts, in display order', () => {- const rows = typeRowsOf(typeStats);+ const rows = typeRowsOf(typeStats as Partial<InstagramContentTypeStatsMap>);assert.deepEqual(rows.map(row => row.type), ['reel', 'video']);assert.equal(rows[0].name, 'Reels');assert.equal(rows[0].color, 'var(--chart-1)');@@ -29,10 +30,10 @@ test('chart rows map the analytics fields', () => {assert.equal(top.length, 8);assert.deepEqual(top[1], { name: '#2', likes: 1, comments: 2 });assert.deepEqual(topPostsChartOf(undefined), []);- assert.deepEqual(dayOfWeekDataOf([{ shortDay: 'Mon', posts: 2, avgEngagement: 5, avgLikes: 4, extra: 1 }]), [+ assert.deepEqual(dayOfWeekDataOf([{ shortDay: 'Mon', posts: 2, avgEngagement: 5, avgLikes: 4, extra: 1 }] as Array<InstagramDayStats & { extra: number }>), [{ name: 'Mon', posts: 2, avgEngagement: 5, avgLikes: 4 },]);- assert.deepEqual(timelineDataOf([{ month: 'Jan', posts: 1, likes: 2, comments: 3, avgLikes: 2 }]), [+ assert.deepEqual(timelineDataOf([{ month: 'Jan', posts: 1, likes: 2, comments: 3, avgLikes: 2 }] as InstagramMonthStats[]), [{ name: 'Jan', posts: 1, likes: 2, comments: 3, avgLikes: 2 },]);});diff --git a/frontend/tests/features/analytics/overview/greeting.test.ts b/frontend/tests/features/analytics/overview/greeting.test.tsindex d438a12..5a0daf1 100644--- a/frontend/tests/features/analytics/overview/greeting.test.ts+++ b/frontend/tests/features/analytics/overview/greeting.test.ts@@ -2,7 +2,7 @@ import { test } from 'node:test';import assert from 'node:assert/strict';import { greeting, greetingName, greetingTitle } from '../../../../src/features/analytics/overview/greeting.ts';-const atHour = hour => new Date(2026, 0, 1, hour, 30);+const atHour = (hour: number) => new Date(2026, 0, 1, hour, 30);test('greeting follows the time of day', () => {assert.equal(greeting(atHour(6)), 'Good morning');diff --git a/frontend/tests/features/analytics/reddit/redditAnalyticsData.test.ts b/frontend/tests/features/analytics/reddit/redditAnalyticsData.test.tsindex 05a39ca..e323185 100644--- a/frontend/tests/features/analytics/reddit/redditAnalyticsData.test.ts+++ b/frontend/tests/features/analytics/reddit/redditAnalyticsData.test.ts@@ -3,11 +3,12 @@ import assert from 'node:assert/strict';import {mediaTypeDataOf, karmaSummaryOf, postingFrequencyRows, karmaBreakdownRows, performanceIndicators,} from '../../../../src/features/analytics/reddit/redditAnalyticsData.ts';+import type { RedditMediaType, RedditPost } from '../../../../../shared/types/reddit.ts';const labels = { text: 'Text', image: 'Image', video: 'Video', link: 'Link' };test('media types use their label and a fixed colour per type', () => {- assert.deepEqual(mediaTypeDataOf({ image: 4, gallery: 1 }, labels), [+ assert.deepEqual(mediaTypeDataOf({ image: 4, gallery: 1 } as Partial<Record<RedditMediaType, number>>, labels), [{ name: 'Image', value: 4, color: 'var(--chart-2)' },{ name: 'gallery', value: 1, color: 'var(--chart-1)' },]);@@ -23,14 +24,14 @@ test('karma summary leads with total karma', () => {test('stat lists fall back to zero', () => {assert.deepEqual(postingFrequencyRows({}).map(row => row.value), ['0 posts', '0 posts', '0 posts', 0, 0]);- const breakdown = karmaBreakdownRows({ avgScore: 12, topPosts: [{ score: 2400 }], avgUpvoteRatio: 93 });+ const breakdown = karmaBreakdownRows({ avgScore: 12, topPosts: [{ score: 2400 }] as RedditPost[], avgUpvoteRatio: 93 });assert.equal(breakdown[0].value, '12');assert.equal(breakdown[2].value, '2.4K');assert.equal(breakdown[3].value, '93%');});test('virality scale grows past ten', () => {- assert.equal(performanceIndicators({}).at(0).max, 10);- assert.equal(performanceIndicators({ viralityScore: 25 }).at(0).max, 25);- assert.equal(performanceIndicators({ consistencyScore: 80 }).at(1).value, 80);+ assert.equal(performanceIndicators({}).at(0)!.max, 10);+ assert.equal(performanceIndicators({ viralityScore: 25 }).at(0)!.max, 25);+ assert.equal(performanceIndicators({ consistencyScore: 80 }).at(1)!.value, 80);});diff --git a/frontend/tests/features/analytics/reels/reelsLibrary.test.ts b/frontend/tests/features/analytics/reels/reelsLibrary.test.tsindex 3aa5397..673a5ee 100644--- a/frontend/tests/features/analytics/reels/reelsLibrary.test.ts+++ b/frontend/tests/features/analytics/reels/reelsLibrary.test.ts@@ -3,15 +3,16 @@ import assert from 'node:assert/strict';import {mergeAccountMedia, typeTotalsOf, viewTotalsOf, filterAndSortMedia, typeViewsSubtitle, reelsDescription,} from '../../../../src/features/analytics/reels/reelsLibrary.ts';+import type { AccountMediaResult, LibraryMedia, MediaAccount, MediaQuery } from '../../../../src/features/analytics/reels/reelsLibrary.ts';-const accounts = [{ id: 'i1', title: 'Paper Fold' }, { id: 'i2', username: 'second' }, { id: 'i3' }];+const accounts: MediaAccount[] = [{ id: 'i1', title: 'Paper Fold' }, { id: 'i2', username: 'second' }, { id: 'i3' }];test('media from every fulfilled account is merged with its account', () => {const results = [{ status: 'fulfilled', value: { media: [{ id: 'm1', viewCount: 200, likeCount: 10, commentsCount: 10 }] } },{ status: 'rejected', reason: new Error('token expired') },{ status: 'fulfilled', value: { media: [{ id: 'm2', viewCount: 0 }] } },- ];+ ] as PromiseSettledResult<AccountMediaResult>[];const media = mergeAccountMedia(accounts, results);assert.deepEqual(media.map(item => [item.id, item.accountId, item.accountTitle]), [['m1', 'i1', 'Paper Fold'],@@ -26,7 +27,7 @@ const media = [{ id: 'r1', contentType: 'reel', viewCount: 1000, likeCount: 50, caption: 'Folding a crane', timestamp: '2026-03-01T00:00:00Z' },{ id: 'p1', contentType: 'post', likeCount: 5000, caption: 'Paper stack', timestamp: '2026-05-01T00:00:00Z' },{ id: 'x1', contentType: 'carousel', viewCount: 10, likeCount: 2, timestamp: 'not a date' },-];+] as LibraryMedia[];test('type totals count unknown types as posts and only reported views', () => {const totals = typeTotalsOf(media);@@ -37,14 +38,14 @@ test('type totals count unknown types as posts and only reported views', () => {});test('media filters by type, caption and like range', () => {- const base = { typeFilter: 'all', search: '', tier: 'all', sortField: 'viewCount' };+ const base: MediaQuery = { typeFilter: 'all', search: '', tier: 'all', sortField: 'viewCount' };assert.deepEqual(filterAndSortMedia(media, { ...base, typeFilter: 'reel' }).map(item => item.id), ['r1']);assert.deepEqual(filterAndSortMedia(media, { ...base, search: 'paper' }).map(item => item.id), ['p1']);assert.deepEqual(filterAndSortMedia(media, { ...base, tier: 'medium' }).map(item => item.id), ['p1']);});test('media sorts with missing values last', () => {- const base = { typeFilter: 'all', search: '', tier: 'all' };+ const base: Omit<MediaQuery, 'sortField'> = { typeFilter: 'all', search: '', tier: 'all' };assert.deepEqual(filterAndSortMedia(media, { ...base, sortField: 'viewCount' }).map(item => item.id), ['r1', 'x1', 'p1']);assert.deepEqual(filterAndSortMedia(media, { ...base, sortField: 'timestamp' }).map(item => item.id), ['p1', 'r1', 'x1']);});diff --git a/frontend/tests/features/analytics/shorts/shortsLibrary.test.ts b/frontend/tests/features/analytics/shorts/shortsLibrary.test.tsindex b2ac9ed..ff13eae 100644--- a/frontend/tests/features/analytics/shorts/shortsLibrary.test.ts+++ b/frontend/tests/features/analytics/shorts/shortsLibrary.test.ts@@ -1,6 +1,8 @@import { test } from 'node:test';import assert from 'node:assert/strict';import { shortsOf, filterAndSortShorts, shortsDescription } from '../../../../src/features/analytics/shorts/shortsLibrary.ts';+import type { ShortsQuery } from '../../../../src/features/analytics/shorts/shortsLibrary.ts';+import type { LibraryVideo } from '../../../../src/features/analytics/videos/videoLibrary.ts';const videos = [{ videoId: 's1', channelId: 'c1', title: 'Quick pasta', durationSeconds: 45, viewCount: 900, likeCount: 5, publishedAt: '2026-02-01T00:00:00Z' },@@ -8,9 +10,9 @@ const videos = [{ videoId: 's3', channelId: 'c1', title: 'Pasta tips', durationSeconds: 12, publishedAt: 'not a date' },{ videoId: 'l1', channelId: 'c1', title: 'Long pasta', durationSeconds: 61, viewCount: 1 },{ videoId: 'z1', channelId: 'c1', title: 'Unknown length', durationSeconds: 0, viewCount: 1 },-];+] as unknown as LibraryVideo[];-const all = { channelFilter: 'all', search: '', tier: 'all', sortField: 'viewCount' };+const all: ShortsQuery = { channelFilter: 'all', search: '', tier: 'all', sortField: 'viewCount' };test('shorts are videos of 1 to 60 seconds', () => {assert.deepEqual(shortsOf(videos).map(video => video.videoId), ['s1', 's2', 's3']);diff --git a/frontend/tests/features/analytics/tracked/trackedCategoryStats.test.ts b/frontend/tests/features/analytics/tracked/trackedCategoryStats.test.tsindex 6c1076c..17041f5 100644--- a/frontend/tests/features/analytics/tracked/trackedCategoryStats.test.ts+++ b/frontend/tests/features/analytics/tracked/trackedCategoryStats.test.ts@@ -4,15 +4,16 @@ import {youtubeStatsOf, redditStatsOf, sortedByViews, sortedByKarma, chartDataOf, platformSplit, categoryDescription,itemsSubtitle, viewsMetric, karmaMetric, commentsSubtitle, redditViewsMetric, upvoteRatioLabel,} from '../../../../src/features/analytics/tracked/trackedCategoryStats.ts';+import type { TrackedContentItem } from '../../../../../shared/types/domain.ts';const videos = [{ id: 'y1', contentType: 'youtube', title: 'A very long video title here', viewCount: 2000, likeCount: 100, commentCount: 7 },{ id: 'y2', contentType: 'youtube', url: 'https://youtu.be/x', viewCount: 1000, likeCount: 1 },-];+] as TrackedContentItem[];const posts = [{ id: 'r1', title: 'Post one', score: 40, numComments: 3, upvoteRatio: 0.9, manualViews: 500 },{ id: 'r2', title: 'Post two', score: 60, numComments: 1, upvoteRatio: 0.7 },-];+] as TrackedContentItem[];test('YouTube totals, averages and like ratio', () => {assert.deepEqual(youtubeStatsOf(videos), {@@ -39,7 +40,7 @@ test('chart data trims names and keeps the data key', () => {{ name: 'A very long vide', views: 2000 },{ name: 'https://youtu.be', views: 1000 },]);- assert.equal(chartDataOf(Array.from({ length: 20 }, () => ({ score: 1 })), 'karma', item => item.score).length, 12);+ assert.equal(chartDataOf(Array.from({ length: 20 }, () => ({ score: 1 })) as TrackedContentItem[], 'karma', item => item.score!).length, 12);});test('platform parts show only for platforms with items', () => {diff --git a/frontend/tests/features/analytics/tracked/trackedList.test.ts b/frontend/tests/features/analytics/tracked/trackedList.test.tsindex 0f97ae6..b01a3a9 100644--- a/frontend/tests/features/analytics/tracked/trackedList.test.ts+++ b/frontend/tests/features/analytics/tracked/trackedList.test.ts@@ -4,15 +4,17 @@ import {SORT_OPTIONS, filterAndSortTracked, categoriesOf, trackedStatsOf, typeChipsOf, pluralize, countLabel,bulkCategoryMessage, parseManualViews, imageFileError, MAX_IMAGE_BYTES,} from '../../../../src/features/analytics/tracked/trackedList.ts';+import type { TrackedFilterOptions } from '../../../../src/features/analytics/tracked/trackedList.ts';+import type { TrackedContentItem } from '../../../../../shared/types/domain.ts';const items = [{ id: 'r1', title: 'Cat post', subreddit: 'cats', score: 50, numComments: 4, manualViews: 900, category: 'Pets', createdAt: '2030-01-02' },{ id: 'y1', contentType: 'youtube', title: 'Dog video', channelTitle: 'Dogs', likeCount: 10, commentCount: 9, viewCount: 100, category: 'Pets', createdAt: '2030-01-03' },{ id: 'r2', contentType: 'reddit', title: 'Launch', score: 5, numComments: 1, category: 'Launch', createdAt: '2030-01-01' },{ id: 'y2', contentType: 'youtube', title: 'Teaser', label: 'Campaign', likeCount: 99, commentCount: 0, viewCount: 5 },-];-const allFilters = { typeFilter: 'all', categoryFilter: 'all', query: '', sort: 'date-desc' };-const ids = list => list.map(item => item.id);+] as unknown as TrackedContentItem[];+const allFilters: TrackedFilterOptions = { typeFilter: 'all', categoryFilter: 'all', query: '', sort: 'date-desc' };+const ids = (list: { id: string }[]) => list.map(item => item.id);test('sort options keep their order and labels', () => {assert.deepEqual(SORT_OPTIONS.map(option => option.value), ['date-desc', 'engagement-desc', 'comments-desc', 'views-desc']);diff --git a/frontend/tests/features/analytics/videos/videoLibrary.test.ts b/frontend/tests/features/analytics/videos/videoLibrary.test.tsindex ccd5eef..3805ece 100644--- a/frontend/tests/features/analytics/videos/videoLibrary.test.ts+++ b/frontend/tests/features/analytics/videos/videoLibrary.test.ts@@ -1,14 +1,15 @@import { test } from 'node:test';import assert from 'node:assert/strict';import { watchUrl, filterAndSortVideos, videoStatsOf, nextSort, ariaSortOf, videosDescription, mergeChannelVideos } from '../../../../src/features/analytics/videos/videoLibrary.ts';+import type { ChannelVideosResult, LibraryVideo, VideoChannelAccount, VideoQuery } from '../../../../src/features/analytics/videos/videoLibrary.ts';const videos = [{ videoId: 'a', title: 'Banana bread', channelId: 'c1', viewCount: 500, likeCount: 10, commentCount: 1, tags: ['baking'] },{ videoId: 'b', title: 'Apple pie', channelId: 'c2', viewCount: 50000, likeCount: 900, commentCount: 40 },{ videoId: 'c', title: 'Cherry tart', channelId: 'c1', viewCount: 2000000 },-];-const allFilters = { channelFilter: 'all', search: '', tier: 'all', sort: { field: 'viewCount', order: 'desc' } };-const ids = list => list.map(video => video.videoId);+] as LibraryVideo[];+const allFilters: VideoQuery = { channelFilter: 'all', search: '', tier: 'all', sort: { field: 'viewCount', order: 'desc' } };+const ids = (list: { videoId: string }[]) => list.map(video => video.videoId);test('videos sort by number in either direction', () => {assert.deepEqual(ids(filterAndSortVideos(videos, allFilters)), ['c', 'b', 'a']);@@ -52,12 +53,12 @@ test('description and watch links', () => {});test('channel videos merge with their channel and skip failed channels', () => {- const channelAccounts = [{ id: 'c1', title: 'Alpha' }, { id: 'c2', channelTitle: 'Beta' }, { id: 'c3' }];+ const channelAccounts: VideoChannelAccount[] = [{ id: 'c1', title: 'Alpha' }, { id: 'c2', channelTitle: 'Beta' }, { id: 'c3' }];const results = [{ status: 'fulfilled', value: { videos: [{ videoId: 'a', viewCount: 200, likeCount: 10, commentCount: 0, duration: 'PT1M5S', thumbnails: { high: 'h.jpg' } }] } },{ status: 'rejected', reason: new Error('quota') },{ status: 'fulfilled', value: { data: { videos: [{ videoId: 'b', thumbnail: 't.jpg', durationSeconds: 30 }] } } },- ];+ ] as PromiseSettledResult<ChannelVideosResult>[];const merged = mergeChannelVideos(channelAccounts, results);assert.deepEqual(merged.channels.map(channel => [channel.id, channel.title]), [['c1', 'Alpha'], ['c3', 'Unknown channel']]);assert.equal(merged.channels[0].account, channelAccounts[0]);diff --git a/frontend/tests/features/publishing/publishHelpers.test.ts b/frontend/tests/features/publishing/publishHelpers.test.tsindex 8431064..be3ab12 100644--- a/frontend/tests/features/publishing/publishHelpers.test.ts+++ b/frontend/tests/features/publishing/publishHelpers.test.ts@@ -4,14 +4,16 @@ import {parseUserTags, parseCollaborators, buildScheduledPostPayload, buildContainerPayload, bulkPostDetails,singleUploadMessage, singlePostError, bulkStartError, bulkBaseTime, editPostError, bulkScheduledTime,} from '../../../src/features/publishing/publishHelpers.ts';+import type { AccountPostDetails, BulkSettings, UploadFailure } from '../../../src/features/publishing/publishHelpers.ts';+import type { ScheduleFieldValues } from '../../../src/features/publishing/scheduleHelpers.ts';const scheduledAt = new Date('2030-05-01T08:00:00Z');-const fullPost = {+const fullPost: AccountPostDetails = {accountId: 'ig1', mediaType: 'REELS', mediaUrl: 'https://cdn/x.mp4', caption: 'Hello', coverUrl: 'https://cdn/c.jpg',shareToFeed: false, collaborators: 'one, two ,', audioName: 'Song', thumbOffset: '1500', locationId: '42',userTags: '@ann 0.2 0.3, bob', altText: 'Alt',};-const bulkSettings = {+const bulkSettings: BulkSettings = {account: 'ig2', contentType: 'REELS', shareToFeed: true, collaborators: 'pal', locationId: '', userTags: '',sharedCaption: '', scheduleMode: true, startDate: '2030-05-01', startTime: '08:00', interval: 1440,};@@ -73,20 +75,20 @@ test('bulk payloads match the shapes the bulk upload has always sent', () => {test('single post upload errors keep their own wording', () => {assert.equal(singleUploadMessage({ reason: 'network', message: 'x' }), 'The upload lost its network connection. Check your connection and try again.');assert.equal(singleUploadMessage({ reason: 'rejected', cloudinaryMessage: 'Bad preset', message: 'Upload failed' }), 'Bad preset');- assert.equal(singleUploadMessage({ reason: 'rejected', parseMessage: 'Unexpected token', message: 'Upload failed' }), 'Upload failed');+ assert.equal(singleUploadMessage({ reason: 'rejected', parseMessage: 'Unexpected token', message: 'Upload failed' } as UploadFailure), 'Upload failed');assert.equal(singleUploadMessage(new Error('Other')), 'Other');});test('single post checks run in order', () => {const now = new Date('2030-05-01T00:00:00');- const base = { selectedAccount: 'a', file: {}, contentType: 'IMAGE', hasCloudConfig: true, now };+ const base = { selectedAccount: 'a', file: {} as File, contentType: 'IMAGE', hasCloudConfig: true, now };const fields = { scheduleMode: true, scheduleDate: '2030-05-02', scheduleTime: '09:00' };assert.equal(singlePostError({ ...base, file: null, fields }), 'Choose an account, a content type and a file before publishing.');assert.equal(singlePostError({ ...base, hasCloudConfig: false, fields }), 'Cloudinary is not set up on the server. Check Settings.');assert.equal(singlePostError({ ...base, fields: { ...fields, scheduleTime: '' } }), 'Set a date and time for the scheduled post.');assert.equal(singlePostError({ ...base, fields: { ...fields, scheduleDate: '2030-04-30' } }), 'Pick a time in the future.');assert.equal(singlePostError({ ...base, fields }), '');- assert.equal(singlePostError({ ...base, fields: { scheduleMode: false } }), '');+ assert.equal(singlePostError({ ...base, fields: { scheduleMode: false } as ScheduleFieldValues }), '');});test('bulk start checks run in order', () => {@@ -102,7 +104,7 @@ test('bulk start checks run in order', () => {test('bulk base time only exists in schedule mode', () => {assert.equal(bulkBaseTime({ ...bulkSettings, scheduleMode: false }), null);- assert.equal(bulkBaseTime(bulkSettings).getTime(), new Date('2030-05-01T08:00').getTime());+ assert.equal(bulkBaseTime(bulkSettings)!.getTime(), new Date('2030-05-01T08:00').getTime());});test('editing a scheduled post needs a future date and time', () => {diff --git a/frontend/tests/features/publishing/queueHelpers.test.ts b/frontend/tests/features/publishing/queueHelpers.test.tsindex 3c38f6d..bc092c2 100644--- a/frontend/tests/features/publishing/queueHelpers.test.ts+++ b/frontend/tests/features/publishing/queueHelpers.test.ts@@ -4,6 +4,9 @@ import {intervalLabel, bulkStatsOf, bulkFilesTitle, bulkActionLabel, progressHeading, fileSizeMb, isVideoFile,patchQueueItem, applyCaptionToPending, removeQueueItem,} from '../../../src/features/publishing/queueHelpers.ts';+import type { QueueItem } from '../../../src/features/publishing/queueHelpers.ts';++type TestQueueItem = Pick<QueueItem, 'id' | 'status' | 'caption'> & { progress?: number };test('intervals read in days from a day upward and in hours below', () => {assert.equal(intervalLabel(720), '12 hours');@@ -13,7 +16,7 @@ test('intervals read in days from a day upward and in hours below', () => {});test('bulk stats count each status', () => {- const files = ['pending', 'pending', 'done', 'scheduled', 'error', 'uploading'].map(status => ({ status }));+ const files = ['pending', 'pending', 'done', 'scheduled', 'error', 'uploading'].map(status => ({ status })) as Pick<QueueItem, 'status'>[];assert.deepEqual(bulkStatsOf(files), { total: 6, pending: 2, done: 1, scheduled: 1, errors: 1 });});@@ -44,7 +47,7 @@ test('file helpers read size and type', () => {});test('queue updates return new arrays and leave other items alone', () => {- const items = [{ id: 1, status: 'pending', caption: '' }, { id: 2, status: 'done', caption: 'kept' }];+ const items: TestQueueItem[] = [{ id: 1, status: 'pending', caption: '' }, { id: 2, status: 'done', caption: 'kept' }];const patched = patchQueueItem(items, 1, { status: 'uploading', progress: 0 });assert.deepEqual(patched[0], { id: 1, status: 'uploading', caption: '', progress: 0 });assert.equal(patched[1], items[1]);diff --git a/frontend/tests/features/publishing/scheduleHelpers.test.ts b/frontend/tests/features/publishing/scheduleHelpers.test.tsindex 6567e24..723ca54 100644--- a/frontend/tests/features/publishing/scheduleHelpers.test.ts+++ b/frontend/tests/features/publishing/scheduleHelpers.test.ts@@ -4,8 +4,9 @@ import {OVERDUE_MS, scheduledStatusChips, filterScheduledPosts, overduePostsOf, isPastDue, overdueLead, deleteAllMessage,formatScheduleDate, toLocalDateInput, toLocalTimeInput, utcDateInput, defaultBulkStartDate, goesLiveLabel,} from '../../../src/features/publishing/scheduleHelpers.ts';+import type { ScheduleTiming } from '../../../src/features/publishing/scheduleHelpers.ts';-const posts = [+const posts: Array<ScheduleTiming & { id: number }> = [{ id: 1, status: 'pending', scheduledAt: '2030-05-01T08:00:00Z' },{ id: 2, status: 'published', scheduledAt: '2030-05-03T08:00:00Z' },{ id: 3, status: 'pending', scheduledAt: '2030-05-02T08:00:00Z' },diff --git a/frontend/tests/features/settings/schedulingProgress.test.ts b/frontend/tests/features/settings/schedulingProgress.test.tsindex 0ec4818..835c1e9 100644--- a/frontend/tests/features/settings/schedulingProgress.test.ts+++ b/frontend/tests/features/settings/schedulingProgress.test.ts@@ -2,12 +2,12 @@ import { test } from 'node:test';import assert from 'node:assert/strict';import { PROGRESS_KEY, readProgress, saveProgress, completedSteps, repoBaseUrl } from '../../../src/features/settings/schedulingProgress.ts';-function fakeStorage(initial = {}) {- const items = { ...initial };+function fakeStorage(initial: Record<string, string> = {}) {+ const items: Record<string, string> = { ...initial };return {items,- getItem: key => (key in items ? items[key] : null),- setItem: (key, value) => { items[key] = String(value); },+ getItem: (key: string) => (key in items ? items[key] : null),+ setItem: (key: string, value: string) => { items[key] = String(value); },};}diff --git a/frontend/tests/features/settings/settingsData.test.ts b/frontend/tests/features/settings/settingsData.test.tsindex 62a7125..504e6e2 100644--- a/frontend/tests/features/settings/settingsData.test.ts+++ b/frontend/tests/features/settings/settingsData.test.ts@@ -3,9 +3,16 @@ import assert from 'node:assert/strict';import {loadServerSettings, githubSettingsPayload, healthCheckResult, healthCheckFailure,} from '../../../src/features/settings/settingsData.ts';+import type { ServerSettingsClient } from '../../../src/features/settings/settingsData.ts';+import type { GitHubSettingsResponse, KeysStatusResponse } from '../../../../shared/types/domain.ts';-function fakeApi({ keys = [], github }) {- const calls = [];+interface FakeApiOptions {+ keys?: unknown[];+ github: unknown;+}++function fakeApi({ keys = [], github }: FakeApiOptions) {+ const calls: string[] = [];const queue = [...keys];return {calls,@@ -13,18 +20,24 @@ function fakeApi({ keys = [], github }) {calls.push('getKeys');const next = queue.shift();if (next instanceof Error) throw next;- return next;+ return next as KeysStatusResponse;},getGithubSettings: async () => {calls.push('getGithubSettings');if (github instanceof Error) throw github;- return github;+ return github as GitHubSettingsResponse;},};}-async function run(apiClient, { cancelled = false } = {}) {- const state = { keys: [], github: null, finished: false };+interface LoadState {+ keys: KeysStatusResponse[];+ github: { owner: string; name: string } | null;+ finished: boolean;+}++async function run(apiClient: ServerSettingsClient, { cancelled = false } = {}) {+ const state: LoadState = { keys: [], github: null, finished: false };await loadServerSettings(apiClient, {isCancelled: () => cancelled,applyKeys: keys => state.keys.push(keys),diff --git a/frontend/tests/lib/holdProgress.test.ts b/frontend/tests/lib/holdProgress.test.tsindex e1cd1a7..e147946 100644--- a/frontend/tests/lib/holdProgress.test.ts+++ b/frontend/tests/lib/holdProgress.test.ts@@ -5,8 +5,8 @@ import { createHoldController } from '../../src/lib/holdProgress.ts';// A manual clock and frame queue so timing can be stepped deterministicallyfunction harness(duration = 1000) {let now = 0;- let queue = [];- const progress = [];+ let queue: Array<() => void> = [];+ const progress: number[] = [];let completed = 0;const controller = createHoldController({duration,@@ -16,7 +16,7 @@ function harness(duration = 1000) {onProgress: p => progress.push(p),onComplete: () => { completed++; },});- const advance = ms => {+ const advance = (ms: number) => {now += ms;const pending = queue;queue = [];diff --git a/frontend/tests/lib/icons.test.ts b/frontend/tests/lib/icons.test.tsindex c169ffb..ae83639 100644--- a/frontend/tests/lib/icons.test.ts+++ b/frontend/tests/lib/icons.test.ts@@ -7,7 +7,7 @@ import * as lucide from 'lucide-react';const SRC = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'src');-function sourceFiles(dir) {+function sourceFiles(dir: string): string[] {return readdirSync(dir).flatMap(name => {const path = join(dir, name);if (statSync(path).isDirectory()) return sourceFiles(path);@@ -17,7 +17,7 @@ function sourceFiles(dir) {// A renamed or removed icon renders as an empty box at runtime, so every imported name must existtest('every Lucide icon imported in src exists in lucide-react', () => {- const missing = [];+ const missing: string[] = [];for (const file of sourceFiles(SRC)) {const text = readFileSync(file, 'utf8');for (const match of text.matchAll(/import\s*\{([^}]+)\}\s*from\s*['"]lucide-react['"]/g)) {diff --git a/frontend/tsconfig.node.json b/frontend/tsconfig.node.jsonindex e3271ce..aa22697 100644--- a/frontend/tsconfig.node.json+++ b/frontend/tsconfig.node.json@@ -7,8 +7,18 @@"DOM.Iterable"],"types": [- "node"- ]+ "node",+ "vite/client"+ ],+ "jsx": "react-jsx",+ "paths": {+ "@/*": [+ "./src/*"+ ],+ "@shared/*": [+ "../shared/*"+ ]+ }},"include": ["vite.config.ts",