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 backend services and the scheduler
spacesdrive57fe284fe1bc
diff --git a/backend/services/accountConnect.ts b/backend/services/accountConnect.tsindex e336a39..d896aeb 100644--- a/backend/services/accountConnect.ts+++ b/backend/services/accountConnect.ts@@ -4,11 +4,25 @@ import { fetchRedditProfile } from './reddit.ts';import { fetchInstagramProfile } from './instagramApi.ts';import { exchangeForLongLivedToken, refreshLongLivedToken } from './instagramTokens.ts';import { buildYouTubeAccount, buildRedditAccount, buildInstagramAccount } from './accountFactory.ts';+import type { SupabaseClient } from '../types/app.ts';+import type { Account, NewAccount } from '../../shared/types/domain.ts';++export interface ServiceFailure {+ status: 400 | 404;+ message: string;+}++export type TokenRefreshOutcome = { failure: ServiceFailure; expiresAt?: undefined } | { expiresAt: string; failure?: undefined };++interface PastedToken {+ token: string;+ expiresIn: number;+}const DEFAULT_TOKEN_LIFETIME_S = 5184000;// duplicates throw like other failures; the route answers all with a 400-export async function addYouTubeAccount(supabase, userId, input, apiKey) {+export async function addYouTubeAccount(supabase: SupabaseClient, userId: string, input: string, apiKey: string): Promise<NewAccount> {const channelId = await resolveChannelId(input, apiKey);const [channelData, accounts] = await Promise.all([fetchChannelData(channelId, apiKey),@@ -24,7 +38,7 @@ export async function addYouTubeAccount(supabase, userId, input, apiKey) {return newAccount;}-export async function addRedditAccount(supabase, userId, username, cookie) {+export async function addRedditAccount(supabase: SupabaseClient, userId: string, username: string, cookie: string): Promise<Account> {const cleanUsername = username.replace(/^u\//i, '').trim();const profile = await fetchRedditProfile(cleanUsername, cookie);@@ -39,18 +53,18 @@ export async function addRedditAccount(supabase, userId, username, cookie) {}// a pasted token may already be long-lived, so a failed exchange keeps it as is-async function exchangePastedToken(accessToken, appSecret) {+async function exchangePastedToken(accessToken: string, appSecret: string | undefined): Promise<PastedToken> {if (!appSecret) return { token: accessToken, expiresIn: 0 };try {const longToken = await exchangeForLongLivedToken(accessToken, appSecret);return { token: longToken.accessToken, expiresIn: longToken.expiresIn };} catch (err) {- console.log('Token exchange skipped (token may already be long-lived):', err.message);+ console.log('Token exchange skipped (token may already be long-lived):', (err as Error).message);return { token: accessToken, expiresIn: 0 };}}-export async function addInstagramAccount(supabase, userId, accessToken, appSecret) {+export async function addInstagramAccount(supabase: SupabaseClient, userId: string, accessToken: string, appSecret: string | undefined): Promise<Account> {const { token, expiresIn } = await exchangePastedToken(accessToken, appSecret);const profile = await fetchInstagramProfile(null, token);@@ -68,7 +82,7 @@ export async function addInstagramAccount(supabase, userId, accessToken, appSecrreturn newAccount;}-export async function refreshInstagramToken(supabase, userId, accountId) {+export async function refreshInstagramToken(supabase: SupabaseClient, userId: string, accountId: string): Promise<TokenRefreshOutcome> {const account = await getAccountById(supabase, accountId, userId);if (!account || account.platform !== 'instagram') {return { failure: { status: 404, message: 'Instagram account not found' } };diff --git a/backend/services/accountFactory.ts b/backend/services/accountFactory.tsindex bdc4cc6..22cfdbc 100644--- a/backend/services/accountFactory.ts+++ b/backend/services/accountFactory.ts@@ -1,15 +1,20 @@-export function newAccountId() {+import type { Account, NewAccount } from '../../shared/types/domain.ts';+import type { YouTubeChannelData } from '../../shared/types/youtube.ts';+import type { RedditProfile } from '../../shared/types/reddit.ts';+import type { InstagramProfile } from '../../shared/types/instagram.ts';++export function newAccountId(): string {return Date.now().toString() + Math.random().toString(36).substring(2, 6);}// a token without a known lifetime is stored with no expiry-export function tokenExpiryIso(expiresIn) {+export function tokenExpiryIso(expiresIn: number): string | null {return expiresIn > 0? new Date(Date.now() + expiresIn * 1000).toISOString(): null;}-export function buildYouTubeAccount(channelData) {+export function buildYouTubeAccount(channelData: YouTubeChannelData): NewAccount {return {id: newAccountId(),channelId: channelData.channelId,@@ -32,7 +37,7 @@ export function buildYouTubeAccount(channelData) {};}-export function buildRedditAccount(profile, cookie) {+export function buildRedditAccount(profile: RedditProfile, cookie: string): Account {return {id: newAccountId(),platform: 'reddit',@@ -49,7 +54,7 @@ export function buildRedditAccount(profile, cookie) {};}-export function buildInstagramAccount(profile, accessToken, expiresIn) {+export function buildInstagramAccount(profile: InstagramProfile, accessToken: string, expiresIn: number): Account {return {id: newAccountId(),platform: 'instagram',diff --git a/backend/services/accountRefresh.ts b/backend/services/accountRefresh.tsindex e887608..8c3029f 100644--- a/backend/services/accountRefresh.ts+++ b/backend/services/accountRefresh.ts@@ -2,21 +2,36 @@ import { getAccounts, getAccountById, updateAccount } from '../lib/db.ts';import { fetchChannelData } from './youtubeChannels.ts';import { fetchRedditProfile } from './reddit.ts';import { fetchInstagramProfile } from './instagramApi.ts';+import type { SupabaseClient } from '../types/app.ts';+import type { ServiceFailure } from './accountConnect.ts';+import type { Account, AccountRefreshResult } from '../../shared/types/domain.ts';+import type { YouTubeChannelData } from '../../shared/types/youtube.ts';+import type { RedditProfile } from '../../shared/types/reddit.ts';+import type { InstagramProfile } from '../../shared/types/instagram.ts';++type Credential = 'accessToken' | 'cookie' | 'apiKey';++export type AccountRefreshOutcome = { failure: ServiceFailure; account?: undefined } | { account: Account; failure?: undefined };++export interface RefreshAllOutcome {+ accounts: Account[];+ results: AccountRefreshResult[];+}const NO_COOKIE_MESSAGE = 'No session cookie stored - re-add this account with a session cookie from reddit.com DevTools';// known issue: the two refresh paths word a missing YouTube key differently-const SINGLE_REFRESH_MESSAGES = { accessToken: 'No access token', cookie: NO_COOKIE_MESSAGE, apiKey: 'No API key' };-const REFRESH_ALL_MESSAGES = { accessToken: 'No access token', cookie: NO_COOKIE_MESSAGE, apiKey: 'No YouTube API key' };+const SINGLE_REFRESH_MESSAGES: Record<Credential, string> = { accessToken: 'No access token', cookie: NO_COOKIE_MESSAGE, apiKey: 'No API key' };+const REFRESH_ALL_MESSAGES: Record<Credential, string> = { accessToken: 'No access token', cookie: NO_COOKIE_MESSAGE, apiKey: 'No YouTube API key' };-function findMissingCredential(account, apiKey) {+function findMissingCredential(account: Account, apiKey: string | undefined): Credential | null {if (account.platform === 'instagram') return account.accessToken ? null : 'accessToken';if (account.platform === 'reddit') return account.cookie ? null : 'cookie';return apiKey ? null : 'apiKey';}// full adds the fields only a single account refresh updates-function instagramUpdates(profile, full) {+function instagramUpdates(profile: InstagramProfile, full: boolean): Partial<Account> {const updates = {followersCount: profile.followersCount,followsCount: profile.followsCount,@@ -29,7 +44,7 @@ function instagramUpdates(profile, full) {return { ...updates, biography: profile.biography, website: profile.website };}-function redditUpdates(profile) {+function redditUpdates(profile: RedditProfile): Partial<Account> {return {totalKarma: profile.totalKarma,postKarma: profile.postKarma,@@ -38,7 +53,7 @@ function redditUpdates(profile) {};}-function youtubeUpdates(channelData, full) {+function youtubeUpdates(channelData: YouTubeChannelData, full: boolean): Partial<Account> {const { subscriberCount, viewCount, videoCount, title, thumbnails } = channelData;if (!full) return { subscriberCount, viewCount, videoCount, title, thumbnails };return {@@ -53,9 +68,9 @@ function youtubeUpdates(channelData, full) {}// fills creation dates on older accounts once; a failure only skips the extras-export async function backfillChannelData(supabase, account, apiKey, userId) {+export async function backfillChannelData(supabase: SupabaseClient, account: Account, apiKey: string, userId: string): Promise<void> {try {- const channelData = await fetchChannelData(account.channelId, apiKey);+ const channelData = await fetchChannelData(account.channelId!, apiKey);await updateAccount(supabase, account.id, {publishedAt: channelData.publishedAt,subscriberCount: channelData.subscriberCount,@@ -69,24 +84,24 @@ export async function backfillChannelData(supabase, account, apiKey, userId) {}, userId);Object.assign(account, channelData);} catch (err) {- console.error('Failed to backfill channel data:', err.message);+ console.error('Failed to backfill channel data:', (err as Error).message);}}-export async function fetchAccountUpdates(account, apiKey, full) {+export async function fetchAccountUpdates(account: Account, apiKey: string | undefined, full: boolean): Promise<Partial<Account>> {if (account.platform === 'instagram') {- const profile = await fetchInstagramProfile(account.igUserId, account.accessToken);+ const profile = await fetchInstagramProfile(account.igUserId, account.accessToken!);return instagramUpdates(profile, full);}if (account.platform === 'reddit') {- const profile = await fetchRedditProfile(account.username, account.cookie);+ const profile = await fetchRedditProfile(account.username!, account.cookie);return redditUpdates(profile);}- const channelData = await fetchChannelData(account.channelId, apiKey);+ const channelData = await fetchChannelData(account.channelId!, apiKey!);return youtubeUpdates(channelData, full);}-export async function refreshAccount(supabase, userId, accountId, apiKey) {+export async function refreshAccount(supabase: SupabaseClient, userId: string, accountId: string, apiKey: string | undefined): Promise<AccountRefreshOutcome> {const account = await getAccountById(supabase, accountId, userId);if (!account) return { failure: { status: 404, message: 'Not found' } };@@ -99,7 +114,7 @@ export async function refreshAccount(supabase, userId, accountId, apiKey) {return { account: { ...account, ...updates } };}-async function refreshListedAccount(supabase, userId, account, apiKey) {+async function refreshListedAccount(supabase: SupabaseClient, userId: string, account: Account, apiKey: string | undefined): Promise<string> {const lastUpdated = new Date().toISOString();const missing = findMissingCredential(account, apiKey);if (missing) throw new Error(REFRESH_ALL_MESSAGES[missing]);@@ -110,11 +125,11 @@ async function refreshListedAccount(supabase, userId, account, apiKey) {}// one failure must not stop the rest; results align with the accounts by index-export async function refreshAllAccounts(supabase, userId, apiKey) {+export async function refreshAllAccounts(supabase: SupabaseClient, userId: string, apiKey: string | undefined): Promise<RefreshAllOutcome> {const accounts = await getAccounts(supabase, userId);const settled = await Promise.allSettled(accounts.map(account => refreshListedAccount(supabase, userId, account, apiKey)));- const results = settled.map((outcome, i) => (outcome.status === 'fulfilled'+ const results: AccountRefreshResult[] = settled.map((outcome, i) => (outcome.status === 'fulfilled'? { id: accounts[i].id, success: true }: { id: accounts[i].id, success: false, error: outcome.reason?.message }));diff --git a/backend/services/analyticsMath.ts b/backend/services/analyticsMath.tsindex 1ef9846..089f0c1 100644--- a/backend/services/analyticsMath.ts+++ b/backend/services/analyticsMath.ts@@ -1,26 +1,28 @@+import type { PostFrequency } from '../../shared/types/reddit.ts';+export const DAY_NAMES = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];export const DAY_MS = 86400000;-export function sumOf(items, pickValue) {+export function sumOf<T>(items: T[], pickValue: (item: T) => number): number {return items.reduce((total, item) => total + pickValue(item), 0);}-export function roundedAverage(total, count) {+export function roundedAverage(total: number, count: number): number {return count > 0 ? Math.round(total / count) : 0;}-export function medianOf(values) {+export function medianOf(values: number[]): number {const sorted = [...values].sort((first, second) => first - second);const middle = Math.floor(sorted.length / 2);if (sorted.length % 2) return sorted[middle];return Math.round((sorted[middle - 1] + sorted[middle]) / 2);}-export function countWithinDays(dates, now, days) {+export function countWithinDays(dates: Date[], now: number, days: number): number {return dates.filter(date => (now - date.getTime()) <= days * DAY_MS).length;}-export function postFrequency(dates, postCount) {+export function postFrequency(dates: Date[], postCount: number): PostFrequency {if (dates.length < 2) return { perWeek: 0, perMonth: 0 };const times = dates.map(date => date.getTime());const spanDays = Math.max(1, (Math.max(...times) - Math.min(...times)) / DAY_MS);@@ -30,13 +32,13 @@ export function postFrequency(dates, postCount) {};}-function coefficientOfVariation(mean, stdDev) {+function coefficientOfVariation(mean: number, stdDev: number): number {if (mean > 0) return stdDev / mean;return stdDev > 0 ? 10 : 0;}// 100 when all values are equal, lower as they spread out from their mean-export function consistencyScore(values) {+export function consistencyScore(values: number[]): number {if (values.length < 3) return 0;const mean = values.reduce((total, value) => total + value, 0) / values.length;const variance = values.reduce((total, value) => total + Math.pow(value - mean, 2), 0) / values.length;@@ -44,14 +46,15 @@ export function consistencyScore(values) {return Math.max(0, Math.min(100, Math.round(100 / (1 + variation))));}-export function bestToAverageRatio(best, average) {+export function bestToAverageRatio(best: number, average: number): number {return average > 0 ? parseFloat((best / average).toFixed(1)) : 0;}-export function pickHighest(items, field) {+// undefined for an empty array+export function pickHighest<T extends Record<K, number>, K extends keyof T>(items: T[], field: K): T {return items.reduce((best, item) => item[field] > best[field] ? item : best, items[0]);}-export function monthKey(date) {+export function monthKey(date: Date): string {return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;}diff --git a/backend/services/instagram.ts b/backend/services/instagram.tsindex c1a977e..ddb1af3 100644--- a/backend/services/instagram.ts+++ b/backend/services/instagram.ts@@ -6,3 +6,9 @@ export {export { CONTENT_TYPES, summarizeContentTypes } from './instagramContentTypes.ts';export { computeInstagramAnalytics } from './instagramAnalytics.ts';export { buildMediaParams } from './instagramPublishing.ts';+export type {+ GraphParams, InstagramApiError, InstagramApiErrorBody, InstagramApiIdResponse, InstagramApiContainerStatus,+} from './instagramApi.ts';+export type { InstagramApiToken, InstagramTokenResult } from './instagramTokens.ts';+export type { InstagramApiMedia, InstagramApiInsight } from './instagramMedia.ts';+export type { InstagramMediaParams } from './instagramPublishing.ts';diff --git a/backend/services/instagramAnalytics.ts b/backend/services/instagramAnalytics.tsindex 6c7d6bc..62bd8ff 100644--- a/backend/services/instagramAnalytics.ts+++ b/backend/services/instagramAnalytics.ts@@ -5,8 +5,23 @@ import {import { CONTENT_TYPES, buildContentTypeStats } from './instagramContentTypes.ts';import { summarizeTiming } from './instagramTiming.ts';import { buildHashtagAnalysis, buildCaptionLengthCorrelation } from './instagramCaptions.ts';+import type {+ InstagramAnalytics, InstagramContentTypeStatsMap, InstagramMedia, InstagramProfile, InstagramTopPost,+} from '../../shared/types/instagram.ts';-function emptyInstagramAnalytics(profile) {+export type AnalyticsProfile = Pick<InstagramProfile, 'mediaCount' | 'followersCount'>;++type EngagementSummary = Pick<InstagramAnalytics,+ 'totalLikes' | 'totalComments' | 'totalEngagement' | 'avgLikes' | 'avgComments' | 'avgEngagement' |+ 'medianLikes' | 'medianComments' | 'engagementRate' | 'likesPerFollower' | 'commentsPerFollower' | 'likesToCommentsRatio'>;++type ViewsSummary = Pick<InstagramAnalytics, 'totalViews' | 'avgViews' | 'mediaWithViews'>;++type LikesAndCommentsRanking = Pick<InstagramAnalytics, 'bestByLikes' | 'bestByComments' | 'worstByLikes'>;++type RecentPostCounts = Pick<InstagramAnalytics, 'postsLast7Days' | 'postsLast30Days' | 'postsLast90Days'>;++function emptyInstagramAnalytics(profile: AnalyticsProfile): InstagramAnalytics {return {totalPosts: profile.mediaCount || 0, fetchedPosts: 0,totalLikes: 0, totalComments: 0, totalEngagement: 0,@@ -28,11 +43,11 @@ function emptyInstagramAnalytics(profile) {};}-function perFollowerRate(total, postCount, followersCount) {+function perFollowerRate(total: number, postCount: number, followersCount: number): number {return followersCount > 0 ? parseFloat((total / postCount / followersCount * 100).toFixed(2)) : 0;}-function summarizeEngagement(profile, media) {+function summarizeEngagement(profile: AnalyticsProfile, media: InstagramMedia[]): EngagementSummary {const totalLikes = sumOf(media, item => item.likeCount);const totalComments = sumOf(media, item => item.commentsCount);const totalEngagement = totalLikes + totalComments;@@ -50,13 +65,13 @@ function summarizeEngagement(profile, media) {};}-function summarizeViews(contentTypeStats) {+function summarizeViews(contentTypeStats: InstagramContentTypeStatsMap): ViewsSummary {const mediaWithViews = CONTENT_TYPES.reduce((total, type) => total + contentTypeStats[type].viewsReported, 0);const totalViews = CONTENT_TYPES.reduce((total, type) => total + contentTypeStats[type].totalViews, 0);return { totalViews, avgViews: roundedAverage(totalViews, mediaWithViews), mediaWithViews };}-function rankByLikesAndComments(media) {+function rankByLikesAndComments(media: InstagramMedia[]): LikesAndCommentsRanking {const byLikes = [...media].sort((first, second) => second.likeCount - first.likeCount);const byComments = [...media].sort((first, second) => second.commentsCount - first.commentsCount);return {@@ -66,14 +81,14 @@ function rankByLikesAndComments(media) {};}-function rankTopPosts(media) {+function rankTopPosts(media: InstagramMedia[]): InstagramTopPost[] {return [...media].map(item => ({ ...item, engagement: item.likeCount + item.commentsCount })).sort((first, second) => second.engagement - first.engagement).slice(0, 10);}-function countRecentPosts(dates) {+function countRecentPosts(dates: Date[]): RecentPostCounts {const now = Date.now();return {postsLast7Days: countWithinDays(dates, now, 7),@@ -82,12 +97,12 @@ function countRecentPosts(dates) {};}-export function computeInstagramAnalytics(profile, media) {+export function computeInstagramAnalytics(profile: AnalyticsProfile, media: InstagramMedia[] | null | undefined): InstagramAnalytics {if (!media || media.length === 0) return emptyInstagramAnalytics(profile);const engagement = summarizeEngagement(profile, media);const contentTypeStats = buildContentTypeStats(media);- const dates = media.map(item => new Date(item.timestamp)).filter(date => !isNaN(date));+ const dates = media.map(item => new Date(item.timestamp)).filter(date => !isNaN(date as unknown as number));const topPosts = rankTopPosts(media);const bestEngagement = topPosts[0] ? topPosts[0].engagement : 0;diff --git a/backend/services/instagramApi.ts b/backend/services/instagramApi.tsindex dca1cc5..6d8e55a 100644--- a/backend/services/instagramApi.ts+++ b/backend/services/instagramApi.ts@@ -1,10 +1,53 @@+import type { InstagramContainerStatusCode, InstagramProfile } from '../../shared/types/instagram.ts';+const IG_GRAPH_URL = 'https://graph.instagram.com';const IG_API_VERSION = 'v25.0';const REQUEST_TIMEOUT_MS = 15000;const RETRY_DELAY_MS = 1000;const UNVERSIONED_PREFIXES = ['/oauth', '/access_token', '/refresh_access_token'];-function buildGraphUrl(endpoint, params) {+export type GraphParams = Record<string, string>;++export interface InstagramApiError {+ message?: string;+ error_message?: string;+ type?: string;+ code?: number;+ error_subcode?: number;+ fbtrace_id?: string;+}++// every Graph API failure carries one of these two fields+export interface InstagramApiErrorBody {+ error?: InstagramApiError;+ error_message?: string;+}++// container creation and media_publish both answer with the new object id+export interface InstagramApiIdResponse extends InstagramApiErrorBody {+ id: string;+}++export interface InstagramApiContainerStatus extends InstagramApiErrorBody {+ id?: string;+ status_code?: InstagramContainerStatusCode;+ status?: string;+}++interface InstagramApiProfile {+ id?: string;+ user_id?: string;+ username?: string;+ name?: string;+ profile_picture_url?: string;+ followers_count?: number;+ follows_count?: number;+ media_count?: number;+ biography?: string;+ website?: string;+}++function buildGraphUrl(endpoint: string, params: GraphParams): URL {const needsVersion = !UNVERSIONED_PREFIXES.some(prefix => endpoint.startsWith(prefix));const base = needsVersion ? `${IG_GRAPH_URL}/${IG_API_VERSION}` : IG_GRAPH_URL;const url = new URL(`${base}${endpoint}`);@@ -12,43 +55,43 @@ function buildGraphUrl(endpoint, params) {return url;}-function isTransientError(err) {+function isTransientError(err: Error): boolean | undefined {return err.name === 'AbortError' ||err.message?.includes('EAI_AGAIN') ||err.message?.includes('ECONNRESET');}-function readGraphResponse(data) {+function readGraphResponse<T>(data: T & InstagramApiErrorBody): T {if (data.error) throw new Error(data.error.message || data.error.error_message || JSON.stringify(data.error));if (data.error_message) throw new Error(data.error_message);return data;}-export async function igFetch(endpoint, params = {}, retries = 1) {+export async function igFetch<T = unknown>(endpoint: string, params: GraphParams = {}, retries = 1): Promise<T> {const url = buildGraphUrl(endpoint, params);const controller = new AbortController();const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);- let response;+ let response: Response;try {response = await fetch(url.toString(), { signal: controller.signal });} catch (err) {clearTimeout(timer);- if (isTransientError(err) && retries > 0) {+ if (isTransientError(err as Error) && retries > 0) {await new Promise(resolve => setTimeout(resolve, RETRY_DELAY_MS));- return igFetch(endpoint, params, retries - 1);+ return igFetch<T>(endpoint, params, retries - 1);}- if (err.name === 'AbortError') throw new Error('Instagram API request timed out');- throw new Error(`Instagram API unreachable (${err.message})`);+ if ((err as Error).name === 'AbortError') throw new Error('Instagram API request timed out');+ throw new Error(`Instagram API unreachable (${(err as Error).message})`);}clearTimeout(timer);- return readGraphResponse(await response.json());+ return readGraphResponse(await response.json() as T & InstagramApiErrorBody);}-export async function fetchInstagramProfile(igUserId, accessToken) {+export async function fetchInstagramProfile(igUserId: string | null | undefined, accessToken: string): Promise<InstagramProfile> {const endpoint = igUserId ? `/${igUserId}` : '/me';- const data = await igFetch(endpoint, {+ const data = await igFetch<InstagramApiProfile>(endpoint, {access_token: accessToken,fields: 'user_id,username,name,profile_picture_url,followers_count,follows_count,media_count,biography,website',});diff --git a/backend/services/instagramCaptions.ts b/backend/services/instagramCaptions.tsindex 8957bdd..a817fe6 100644--- a/backend/services/instagramCaptions.ts+++ b/backend/services/instagramCaptions.ts@@ -1,9 +1,18 @@import { sumOf, roundedAverage } from './analyticsMath.ts';+import type {+ InstagramCaptionLengthStats, InstagramHashtagStats, InstagramMedia,+} from '../../shared/types/instagram.ts';++interface CaptionBucket {+ label: string;+ min: number;+ max: number;+}const HASHTAG_PATTERN = /#[\wÀ-ɏ]+/g;const MAX_HASHTAGS = 20;-const CAPTION_BUCKETS = [+const CAPTION_BUCKETS: CaptionBucket[] = [{ label: 'No caption', min: 0, max: 0 },{ label: 'Short (1-50)', min: 1, max: 50 },{ label: 'Medium (51-150)', min: 51, max: 150 },@@ -11,8 +20,8 @@ const CAPTION_BUCKETS = [{ label: 'Very Long (300+)', min: 301, max: Infinity },];-export function buildHashtagAnalysis(media) {- const hashtags = {};+export function buildHashtagAnalysis(media: InstagramMedia[]): InstagramHashtagStats[] {+ const hashtags: Record<string, Omit<InstagramHashtagStats, 'avgEngagement'>> = {};media.forEach(item => {const found = (item.caption || '').match(HASHTAG_PATTERN) || [];found.forEach(rawTag => {@@ -29,7 +38,7 @@ export function buildHashtagAnalysis(media) {.slice(0, MAX_HASHTAGS);}-function summarizeCaptionBucket(bucket, media) {+function summarizeCaptionBucket(bucket: CaptionBucket, media: InstagramMedia[]): InstagramCaptionLengthStats {const posts = media.filter(item => {const length = (item.caption || '').length;return length >= bucket.min && length <= bucket.max;@@ -43,7 +52,7 @@ function summarizeCaptionBucket(bucket, media) {};}-export function buildCaptionLengthCorrelation(media) {+export function buildCaptionLengthCorrelation(media: InstagramMedia[]): InstagramCaptionLengthStats[] {return CAPTION_BUCKETS.map(bucket => summarizeCaptionBucket(bucket, media)).filter(bucket => bucket.count > 0);diff --git a/backend/services/instagramContentTypes.ts b/backend/services/instagramContentTypes.tsindex 79b7165..e0fdea8 100644--- a/backend/services/instagramContentTypes.ts+++ b/backend/services/instagramContentTypes.ts@@ -1,9 +1,12 @@import { roundedAverage } from './analyticsMath.ts';+import type {+ InstagramContentType, InstagramContentTypeStatsMap, InstagramContentTypeSummary, InstagramMedia,+} from '../../shared/types/instagram.ts';-export const CONTENT_TYPES = ['reel', 'post', 'video'];+export const CONTENT_TYPES: InstagramContentType[] = ['reel', 'post', 'video'];-export function summarizeContentTypes(media) {- const summary = {};+export function summarizeContentTypes(media: InstagramMedia[] | null | undefined): InstagramContentTypeSummary {+ const summary = {} as InstagramContentTypeSummary;CONTENT_TYPES.forEach(type => {summary[type] = { count: 0, likes: 0, comments: 0, views: 0, viewsReported: 0 };});@@ -20,9 +23,9 @@ export function summarizeContentTypes(media) {return summary;}-export function buildContentTypeStats(media) {+export function buildContentTypeStats(media: InstagramMedia[]): InstagramContentTypeStatsMap {const summary = summarizeContentTypes(media);- const stats = {};+ const stats = {} as InstagramContentTypeStatsMap;CONTENT_TYPES.forEach(type => {const totals = summary[type];stats[type] = {diff --git a/backend/services/instagramMedia.ts b/backend/services/instagramMedia.tsindex ca9d5c8..08935a7 100644--- a/backend/services/instagramMedia.ts+++ b/backend/services/instagramMedia.ts@@ -1,4 +1,6 @@import { igFetch } from './instagramApi.ts';+import type { GraphParams } from './instagramApi.ts';+import type { InstagramContentType, InstagramMedia } from '../../shared/types/instagram.ts';const MEDIA_FIELDS = 'id,caption,media_type,media_product_type,media_url,thumbnail_url,cover_url,permalink,timestamp,like_count,comments_count';const VIEWS_FIELD = 'insights.metric(views)';@@ -6,8 +8,38 @@ const MEDIA_PAGE_SIZE = 50;const MAX_MEDIA_PAGES = 10;const REEL_PERMALINK = /instagram\.com\/reels?\//i;+export interface InstagramApiInsight {+ name: string;+ values?: { value?: number }[];+ total_value?: { value?: number };+}++// one item of the /{ig-user-id}/media edge with MEDIA_FIELDS and, when allowed, the views insight+export interface InstagramApiMedia {+ id: string;+ caption?: string;+ media_type?: string;+ media_product_type?: string;+ media_url?: string;+ thumbnail_url?: string;+ cover_url?: string;+ permalink?: string;+ timestamp?: string;+ like_count?: number;+ comments_count?: number;+ insights?: { data?: InstagramApiInsight[] };+}++interface InstagramApiMediaPage {+ data?: InstagramApiMedia[];+ paging?: {+ next?: string;+ cursors?: { before?: string; after?: string };+ };+}+// media_type never says REELS; only media_product_type tells a reel from a video-export function classifyInstagramMedia(raw) {+export function classifyInstagramMedia(raw: Partial<InstagramApiMedia> | null | undefined): InstagramContentType {const productType = String(raw?.media_product_type || '').toUpperCase();const mediaType = String(raw?.media_type || '').toUpperCase();@@ -18,14 +50,14 @@ export function classifyInstagramMedia(raw) {return 'post';}-export function extractInstagramViews(raw) {+export function extractInstagramViews(raw: Partial<InstagramApiMedia> | null | undefined): number | null {const metric = raw?.insights?.data?.find(insight => insight.name === 'views');const value = metric?.values?.[0]?.value ?? metric?.total_value?.value;const views = Number(value);return value !== undefined && value !== null && Number.isFinite(views) ? views : null;}-export function normalizeInstagramMedia(raw) {+export function normalizeInstagramMedia(raw: InstagramApiMedia): InstagramMedia {const contentType = classifyInstagramMedia(raw);const mediaType = String(raw.media_type || 'IMAGE').toUpperCase();return {@@ -43,28 +75,28 @@ export function normalizeInstagramMedia(raw) {};}-async function fetchMediaPage(igUserId, accessToken, after) {- const params = { access_token: accessToken, limit: String(MEDIA_PAGE_SIZE) };+async function fetchMediaPage(igUserId: string, accessToken: string, after: string | null | undefined): Promise<InstagramApiMediaPage> {+ const params: GraphParams = { access_token: accessToken, limit: String(MEDIA_PAGE_SIZE) };if (after) params.after = after;try {- return await igFetch(`/${igUserId}/media`, { ...params, fields: `${MEDIA_FIELDS},${VIEWS_FIELD}` });+ return await igFetch<InstagramApiMediaPage>(`/${igUserId}/media`, { ...params, fields: `${MEDIA_FIELDS},${VIEWS_FIELD}` });} catch {// one item without insights (e.g. pre-professional posts) fails the whole page- return igFetch(`/${igUserId}/media`, { ...params, fields: MEDIA_FIELDS });+ return igFetch<InstagramApiMediaPage>(`/${igUserId}/media`, { ...params, fields: MEDIA_FIELDS });}}-function uniqueById(items) {- const unique = new Map();+function uniqueById(items: InstagramApiMedia[]): InstagramApiMedia[] {+ const unique = new Map<string, InstagramApiMedia>();items.forEach(item => {if (item?.id && !unique.has(item.id)) unique.set(item.id, item);});return [...unique.values()];}-export async function fetchInstagramMedia(igUserId, accessToken, limit = 500) {- const allMedia = [];- let after = null;+export async function fetchInstagramMedia(igUserId: string, accessToken: string, limit = 500): Promise<InstagramMedia[]> {+ const allMedia: InstagramApiMedia[] = [];+ let after: string | null | undefined = null;for (let page = 0; page < MAX_MEDIA_PAGES && allMedia.length < limit; page++) {const data = await fetchMediaPage(igUserId, accessToken, after);diff --git a/backend/services/instagramOAuth.ts b/backend/services/instagramOAuth.tsindex d8e9d47..0f94c3b 100644--- a/backend/services/instagramOAuth.ts+++ b/backend/services/instagramOAuth.ts@@ -2,6 +2,9 @@ import { createOAuthState } from '../lib/oauthState.ts';import { createAccount, getAccounts } from '../lib/db.ts';import { fetchInstagramProfile } from './instagramApi.ts';import { buildInstagramAccount } from './accountFactory.ts';+import type { InstagramApiToken } from './instagramTokens.ts';+import type { Env } from '../types/env.ts';+import type { SupabaseClient } from '../types/app.ts';const DEFAULT_BACKEND_URL = 'http://localhost:8787';const DEFAULT_FRONTEND_URL = 'http://localhost:5173';@@ -11,16 +14,38 @@ const TOKEN_URL = 'https://api.instagram.com/oauth/access_token';const LONG_LIVED_TOKEN_URL = 'https://graph.instagram.com/access_token';const OAUTH_SCOPES = 'instagram_business_basic,instagram_business_manage_messages,instagram_business_manage_comments,instagram_business_content_publish,instagram_business_manage_insights';+export type InstagramOAuthEnv = Pick<Env, 'FRONTEND_URL' | 'BACKEND_URL' | 'INSTAGRAM_APP_ID' | 'INSTAGRAM_APP_SECRET'>;++// appId and appSecret are undefined when the Worker secrets are not set+export interface InstagramOAuthConfig {+ frontendUrl: string;+ redirectUri: string;+ appId: string | undefined;+ appSecret: string | undefined;+}++export type InstagramOAuthOutcome = 'already_added' | 'connected';++// answer of the short-lived code exchange at api.instagram.com+interface InstagramApiCodeToken {+ access_token?: string;+ user_id?: string | number;+ permissions?: string[];+ error_type?: string;+ error_message?: string;+ code?: number;+}+// pasted secrets can carry a byte order mark or stray whitespace-function cleanSecret(value) {+function cleanSecret(value: string | undefined): string | undefined {return value?.replace(/^\uFEFF/, '').trim();}-function cleanUrl(value, fallback) {+function cleanUrl(value: string | undefined, fallback: string): string {return (value || fallback).replace(/^\uFEFF/, '').trim();}-export function readInstagramOAuthConfig(env) {+export function readInstagramOAuthConfig(env: InstagramOAuthEnv): InstagramOAuthConfig {const frontendUrl = cleanUrl(env.FRONTEND_URL, DEFAULT_FRONTEND_URL);const backendUrl = cleanUrl(env.BACKEND_URL, DEFAULT_BACKEND_URL).replace(/\/$/, '');return {@@ -32,11 +57,11 @@ export function readInstagramOAuthConfig(env) {}// the hmac-signed state carries the userId and a timestamp, so no redis is needed-export async function buildAuthorizationUrl(config, userId) {- const state = await createOAuthState(userId, config.appSecret);+export async function buildAuthorizationUrl(config: InstagramOAuthConfig, userId: string): Promise<string> {+ const state = await createOAuthState(userId, config.appSecret as string);const params = new URLSearchParams({force_reauth: 'true',- client_id: config.appId,+ client_id: config.appId as string,redirect_uri: config.redirectUri,response_type: 'code',scope: OAUTH_SCOPES,@@ -45,20 +70,20 @@ export async function buildAuthorizationUrl(config, userId) {return `${AUTHORIZE_URL}?${params}`;}-async function exchangeCodeForToken(config, code) {+async function exchangeCodeForToken(config: InstagramOAuthConfig, code: string): Promise<string> {const tokenRes = await fetch(TOKEN_URL, {method: 'POST',headers: { 'Content-Type': 'application/x-www-form-urlencoded' },body: new URLSearchParams({- client_id: config.appId,- client_secret: config.appSecret,+ client_id: config.appId as string,+ client_secret: config.appSecret as string,grant_type: 'authorization_code',redirect_uri: config.redirectUri,// instagram sometimes appends #_ to the codecode: code.replace(/#.*$/, ''),}),});- const tokenData = await tokenRes.json();+ const tokenData = await tokenRes.json() as InstagramApiCodeToken;if (!tokenData.access_token) {throw new Error(tokenData.error_message || JSON.stringify(tokenData));}@@ -66,19 +91,21 @@ async function exchangeCodeForToken(config, code) {}// keeps the short-lived token (no expiry) when instagram declines the upgrade-async function upgradeToLongLivedToken(config, shortToken) {+async function upgradeToLongLivedToken(config: InstagramOAuthConfig, shortToken: string): Promise<{ token: string; expiresIn: number }> {const longParams = new URLSearchParams({grant_type: 'ig_exchange_token',- client_id: config.appId,- client_secret: config.appSecret,+ client_id: config.appId as string,+ client_secret: config.appSecret as string,access_token: shortToken,});const longRes = await fetch(`${LONG_LIVED_TOKEN_URL}?${longParams}`);- const longData = await longRes.json();+ const longData = await longRes.json() as InstagramApiToken;return { token: longData.access_token || shortToken, expiresIn: longData.expires_in || 0 };}-export async function connectInstagramFromOAuth(supabase, userId, config, code) {+export async function connectInstagramFromOAuth(+ supabase: SupabaseClient, userId: string, config: InstagramOAuthConfig, code: string,+): Promise<InstagramOAuthOutcome> {const shortToken = await exchangeCodeForToken(config, code);const { token, expiresIn } = await upgradeToLongLivedToken(config, shortToken);diff --git a/backend/services/instagramPublishing.ts b/backend/services/instagramPublishing.tsindex 7cb2aa5..033425f 100644--- a/backend/services/instagramPublishing.ts+++ b/backend/services/instagramPublishing.ts@@ -1,4 +1,25 @@-function addCarouselParams(params, post) {+import type { InstagramPublishRequest } from '../../shared/types/instagram.ts';++// query parameters of POST /{ig-user-id}/media; URLSearchParams turns the booleans and numbers into strings+export interface InstagramMediaParams {+ access_token: string;+ media_type?: 'CAROUSEL' | 'VIDEO' | 'REELS' | 'STORIES';+ image_url?: string;+ video_url?: string;+ is_carousel_item?: boolean;+ caption?: string;+ children?: string;+ collaborators?: string;+ location_id?: string;+ share_to_feed?: boolean;+ cover_url?: string;+ audio_name?: string;+ thumb_offset?: number;+ user_tags?: string;+ alt_text?: string;+}++function addCarouselParams(params: InstagramMediaParams, post: InstagramPublishRequest): InstagramMediaParams {const { caption, children, collaborators, locationId } = post;params.media_type = 'CAROUSEL';if (caption) params.caption = caption;@@ -8,20 +29,20 @@ function addCarouselParams(params, post) {return params;}-function addCarouselImageParams(params, post) {+function addCarouselImageParams(params: InstagramMediaParams, post: InstagramPublishRequest): InstagramMediaParams {params.image_url = post.mediaUrl;params.is_carousel_item = true;return params;}-function addCarouselVideoParams(params, post) {+function addCarouselVideoParams(params: InstagramMediaParams, post: InstagramPublishRequest): InstagramMediaParams {params.media_type = 'VIDEO';params.video_url = post.mediaUrl;params.is_carousel_item = true;return params;}-function addReelParams(params, post) {+function addReelParams(params: InstagramMediaParams, post: InstagramPublishRequest): InstagramMediaParams {const { mediaUrl, caption, shareToFeed, coverUrl, collaborators, audioName, thumbOffset, locationId, userTags } = post;params.media_type = 'REELS';params.video_url = mediaUrl;@@ -36,7 +57,7 @@ function addReelParams(params, post) {return params;}-function addStoryParams(params, post) {+function addStoryParams(params: InstagramMediaParams, post: InstagramPublishRequest): InstagramMediaParams {const { mediaUrl, userTags } = post;params.media_type = 'STORIES';if (mediaUrl?.match(/\.(mp4|mov|avi|webm)/i)) {@@ -48,7 +69,7 @@ function addStoryParams(params, post) {return params;}-function addPhotoParams(params, post) {+function addPhotoParams(params: InstagramMediaParams, post: InstagramPublishRequest): InstagramMediaParams {const { mediaUrl, caption, locationId, userTags, altText } = post;params.image_url = mediaUrl;if (caption) params.caption = caption;@@ -59,8 +80,8 @@ function addPhotoParams(params, post) {}// scripts/publish-scheduled.js keeps its own copy because it must stay dependency-free-export function buildMediaParams(post, accessToken) {- const params = { access_token: accessToken };+export function buildMediaParams(post: InstagramPublishRequest, accessToken: string): InstagramMediaParams {+ const params: InstagramMediaParams = { access_token: accessToken };const { mediaType } = post;if (mediaType === 'CAROUSEL') return addCarouselParams(params, post);if (mediaType === 'CAROUSEL_ITEM_IMAGE') return addCarouselImageParams(params, post);diff --git a/backend/services/instagramTiming.ts b/backend/services/instagramTiming.tsindex 2c33ec4..4c10986 100644--- a/backend/services/instagramTiming.ts+++ b/backend/services/instagramTiming.ts@@ -1,11 +1,28 @@import { DAY_NAMES, roundedAverage, pickHighest, monthKey } from './analyticsMath.ts';+import type {+ InstagramDayStats, InstagramHourStats, InstagramMedia, InstagramMonthStats, InstagramTiming,+} from '../../shared/types/instagram.ts';-function emptyBuckets(size) {+interface EngagementBucket {+ count: number;+ likes: number;+ comments: number;+}++interface MonthTotals {+ posts: number;+ likes: number;+ comments: number;+}++function emptyBuckets(size: number): EngagementBucket[] {return Array(size).fill(null).map(() => ({ count: 0, likes: 0, comments: 0 }));}// dates drops bad timestamps yet is indexed by media, matching stored analytics-function fillBuckets(buckets, dates, media, bucketIndexOf) {+function fillBuckets(+ buckets: EngagementBucket[], dates: Date[], media: InstagramMedia[], bucketIndexOf: (date: Date) => number,+): EngagementBucket[] {dates.forEach((date, i) => {const bucket = buckets[bucketIndexOf(date)];bucket.count++;@@ -15,7 +32,7 @@ function fillBuckets(buckets, dates, media, bucketIndexOf) {return buckets;}-function buildPostsByDayOfWeek(dates, media) {+function buildPostsByDayOfWeek(dates: Date[], media: InstagramMedia[]): InstagramDayStats[] {const buckets = fillBuckets(emptyBuckets(7), dates, media, date => date.getDay());return buckets.map((bucket, i) => ({day: DAY_NAMES[i], shortDay: DAY_NAMES[i].slice(0, 3),@@ -26,7 +43,7 @@ function buildPostsByDayOfWeek(dates, media) {}));}-function buildPostsByHour(dates, media) {+function buildPostsByHour(dates: Date[], media: InstagramMedia[]): InstagramHourStats[] {const buckets = fillBuckets(emptyBuckets(24), dates, media, date => date.getHours());return buckets.map((bucket, i) => ({hour: i, label: `${i}:00`,@@ -35,11 +52,11 @@ function buildPostsByHour(dates, media) {}));}-function buildMonthlyBreakdown(media) {- const months = {};+function buildMonthlyBreakdown(media: InstagramMedia[]): InstagramMonthStats[] {+ const months: Record<string, MonthTotals> = {};media.forEach(item => {const date = new Date(item.timestamp);- if (isNaN(date)) return;+ if (isNaN(date as unknown as number)) return;const key = monthKey(date);if (!months[key]) months[key] = { posts: 0, likes: 0, comments: 0 };months[key].posts++;@@ -57,7 +74,7 @@ function buildMonthlyBreakdown(media) {}));}-export function summarizeTiming(dates, media) {+export function summarizeTiming(dates: Date[], media: InstagramMedia[]): InstagramTiming {const postsByDayOfWeek = buildPostsByDayOfWeek(dates, media);const postsByHour = buildPostsByHour(dates, media);const monthlyBreakdown = buildMonthlyBreakdown(media);diff --git a/backend/services/instagramTokens.ts b/backend/services/instagramTokens.tsindex 7a8a54e..7930d28 100644--- a/backend/services/instagramTokens.ts+++ b/backend/services/instagramTokens.ts@@ -1,10 +1,27 @@import { getAccounts, updateAccount } from '../lib/db.ts';import { igFetch } from './instagramApi.ts';+import type { Account } from '../../shared/types/domain.ts';+import type { SupabaseClient } from '../types/app.ts';const DEFAULT_TOKEN_LIFETIME_S = 5184000;const REFRESH_WINDOW_MS = 15 * 24 * 60 * 60 * 1000;-function toTokenResult(data) {+// answer of /access_token and /refresh_access_token+export interface InstagramApiToken {+ access_token?: string;+ token_type?: string;+ expires_in?: number;+}++type IssuedToken = InstagramApiToken & { access_token: string };++export interface InstagramTokenResult {+ accessToken: string;+ tokenType: string;+ expiresIn: number;+}++function toTokenResult(data: IssuedToken): InstagramTokenResult {return {accessToken: data.access_token,tokenType: data.token_type || 'bearer',@@ -12,55 +29,55 @@ function toTokenResult(data) {};}-export async function exchangeForLongLivedToken(shortToken, appSecret) {- const data = await igFetch('/access_token', {+export async function exchangeForLongLivedToken(shortToken: string, appSecret: string): Promise<InstagramTokenResult> {+ const data = await igFetch<InstagramApiToken>('/access_token', {grant_type: 'ig_exchange_token',client_secret: appSecret,access_token: shortToken,});if (!data.access_token) throw new Error('Failed to exchange token - check Instagram App Secret');- return toTokenResult(data);+ return toTokenResult(data as IssuedToken);}-export async function refreshLongLivedToken(longToken) {- const data = await igFetch('/refresh_access_token', {+export async function refreshLongLivedToken(longToken: string): Promise<InstagramTokenResult> {+ const data = await igFetch<InstagramApiToken>('/refresh_access_token', {grant_type: 'ig_refresh_token',access_token: longToken,});if (!data.access_token) throw new Error('Failed to refresh token');- return toTokenResult(data);+ return toTokenResult(data as IssuedToken);}-function isInstagramWithToken(account) {+function isInstagramWithToken(account: Account): string | false | null | undefined {return account.platform === 'instagram' && account.accessToken && account.tokenExpiresAt;}-async function refreshStoredToken(supabase, account) {+async function refreshStoredToken(supabase: SupabaseClient, account: Account): Promise<void> {try {- const refreshed = await refreshLongLivedToken(account.accessToken);+ const refreshed = await refreshLongLivedToken(account.accessToken!);const tokenExpiresAt = new Date(Date.now() + (refreshed.expiresIn || DEFAULT_TOKEN_LIFETIME_S) * 1000).toISOString();await updateAccount(supabase, account.id, { accessToken: refreshed.accessToken, tokenExpiresAt });console.log(`Token refreshed for @${account.username} - expires ${tokenExpiresAt}`);} catch (err) {- console.error(`Failed to refresh token for @${account.username}: ${err.message}`);+ console.error(`Failed to refresh token for @${account.username}: ${(err as Error).message}`);}}// takes supabase directly because cron handlers have no hono request context-export async function autoRefreshInstagramTokens(supabase) {+export async function autoRefreshInstagramTokens(supabase: SupabaseClient): Promise<void> {try {const accounts = await getAccounts(supabase);const igAccounts = accounts.filter(isInstagramWithToken);if (igAccounts.length === 0) return;const soon = new Date(Date.now() + REFRESH_WINDOW_MS);- const toRefresh = igAccounts.filter(account => new Date(account.tokenExpiresAt) <= soon);+ const toRefresh = igAccounts.filter(account => new Date(account.tokenExpiresAt!) <= soon);if (toRefresh.length === 0) return;for (const account of toRefresh) {await refreshStoredToken(supabase, account);}} catch (err) {- console.error('autoRefreshInstagramTokens error:', err.message);+ console.error('autoRefreshInstagramTokens error:', (err as Error).message);}}diff --git a/backend/services/overviewSummary.ts b/backend/services/overviewSummary.tsindex 5cc14b7..b39f1aa 100644--- a/backend/services/overviewSummary.ts+++ b/backend/services/overviewSummary.ts@@ -2,47 +2,69 @@ import { getVideosCache, setVideosCache, getIGCache, setIGCache, getRedditCache,import { fetchAllVideos } from './youtube.ts';import { fetchInstagramMedia, summarizeContentTypes } from './instagram.ts';import { fetchRedditProfile, fetchRedditPosts, computeRedditAnalytics } from './reddit.ts';+import type { Redis } from '../types/app.ts';+import type {+ Account, AccountSummary, PendingAccountSummary, RedditAccountSummary, InstagramAccountSummary,+ YouTubeAccountSummary, OverviewAnalyticsCache,+} from '../../shared/types/domain.ts';-function sumBy(items, pick) {+type WarmTask = () => Promise<void>;++export interface OverviewSummaryOptions {+ redis: Redis | null;+ userId: string;+ apiKey: string | undefined;+}++interface SummaryContext extends OverviewSummaryOptions {+ warmTasks: Promise<void>[];+}++export interface OverviewSummaries {+ analyticsCache: OverviewAnalyticsCache;+ warmTasks: Promise<void>[];+}++function sumBy<T>(items: T[], pick: (item: T) => number): number {return items.reduce((total, item) => total + pick(item), 0);}// syncing only when a fetch started, so the client never waits for nothing-function startWarm(context, accountId, task) {+function startWarm(context: SummaryContext, accountId: string, task: WarmTask | null): PendingAccountSummary {if (!context.redis || !task) return { id: accountId, cacheWarmed: false, syncing: false };// a failed warm leaves the cache empty, so the next load starts it againcontext.warmTasks.push(task().catch(() => undefined));return { id: accountId, cacheWarmed: false, syncing: true };}-function redditWarmTask(context, account) {+function redditWarmTask(context: SummaryContext, account: Account): WarmTask | null {if (!account.username || !account.cookie) return null;return async () => {const [profile, posts] = await Promise.all([- fetchRedditProfile(account.username, account.cookie),- fetchRedditPosts(account.username, account.cookie, 100),+ fetchRedditProfile(account.username!, account.cookie),+ fetchRedditPosts(account.username!, account.cookie, 100),]);await setRedditCache(context.redis, context.userId, account.id, { profile, analytics: computeRedditAnalytics(profile, posts), posts });};}-function instagramWarmTask(context, account) {+function instagramWarmTask(context: SummaryContext, account: Account): WarmTask | null {if (!account.igUserId || !account.accessToken) return null;return async () => {- const media = await fetchInstagramMedia(account.igUserId, account.accessToken, 500);+ const media = await fetchInstagramMedia(account.igUserId!, account.accessToken!, 500);await setIGCache(context.redis, context.userId, account.id, { media, fetchedAt: new Date().toISOString() });};}-function youtubeWarmTask(context, account) {+function youtubeWarmTask(context: SummaryContext, account: Account): WarmTask | null {if (!context.apiKey || !account.uploadsPlaylistId) return null;return async () => {- const videos = await fetchAllVideos(account.uploadsPlaylistId, context.apiKey, 10);+ const videos = await fetchAllVideos(account.uploadsPlaylistId!, context.apiKey!, 10);await setVideosCache(context.redis, context.userId, account.id, { videos, fetchedAt: new Date().toISOString() });};}-async function summarizeReddit(context, account) {+async function summarizeReddit(context: SummaryContext, account: Account): Promise<RedditAccountSummary | PendingAccountSummary> {const cached = await getRedditCache(context.redis, context.userId, account.id);if (!cached?.analytics) return startWarm(context, account.id, redditWarmTask(context, account));return {@@ -54,7 +76,7 @@ async function summarizeReddit(context, account) {};}-async function summarizeInstagram(context, account) {+async function summarizeInstagram(context: SummaryContext, account: Account): Promise<InstagramAccountSummary | PendingAccountSummary> {const cached = await getIGCache(context.redis, context.userId, account.id);if (!cached?.media) return startWarm(context, account.id, instagramWarmTask(context, account));const contentTypes = summarizeContentTypes(cached.media);@@ -69,7 +91,7 @@ async function summarizeInstagram(context, account) {};}-async function summarizeYouTube(context, account) {+async function summarizeYouTube(context: SummaryContext, account: Account): Promise<YouTubeAccountSummary | PendingAccountSummary> {const cached = await getVideosCache(context.redis, context.userId, account.id);if (!cached?.videos) return startWarm(context, account.id, youtubeWarmTask(context, account));return {@@ -80,15 +102,15 @@ async function summarizeYouTube(context, account) {};}-async function summarizeAccount(context, account) {+async function summarizeAccount(context: SummaryContext, account: Account): Promise<AccountSummary> {if (account.platform === 'reddit') return summarizeReddit(context, account);if (account.platform === 'instagram') return summarizeInstagram(context, account);return summarizeYouTube(context, account);}// a failed cache read leaves the account out instead of failing the overview-function collectSummaries(results) {- const analyticsCache = {};+function collectSummaries(results: PromiseSettledResult<AccountSummary>[]): OverviewAnalyticsCache {+ const analyticsCache: OverviewAnalyticsCache = {};results.forEach(result => {if (result.status === 'fulfilled' && result.value?.id) {analyticsCache[result.value.id] = result.value;@@ -98,8 +120,8 @@ function collectSummaries(results) {}// the warm tasks already run; the caller decides how long they are kept alive-export async function summarizeAccountCaches(accounts, { redis, userId, apiKey }) {- const context = { redis, userId, apiKey, warmTasks: [] };+export async function summarizeAccountCaches(accounts: Account[], { redis, userId, apiKey }: OverviewSummaryOptions): Promise<OverviewSummaries> {+ const context: SummaryContext = { redis, userId, apiKey, warmTasks: [] };const results = await Promise.allSettled(accounts.map(account => summarizeAccount(context, account)));return { analyticsCache: collectSummaries(results), warmTasks: context.warmTasks };}diff --git a/backend/services/reddit.ts b/backend/services/reddit.tsindex 132e640..005c7e5 100644--- a/backend/services/reddit.ts+++ b/backend/services/reddit.ts@@ -1,3 +1,5 @@+import type { RedditMediaType, RedditPost, RedditProfile, RedditTrackedPostData } from '../../shared/types/reddit.ts';+export { computeRedditAnalytics } from './redditAnalytics.ts';// fetch is a worker global; requests send the stored reddit_session cookie@@ -5,8 +7,63 @@ const REDDIT_BASE = 'https://www.reddit.com';// reddit requires <platform>:<appid>:<version> (by /u/<username>)const USER_AGENT = 'script:twiligent:v1.0 (by /u/spacesdrive)';-async function redditFetch(path, cookie) {- const headers = { 'User-Agent': USER_AGENT, 'Accept': 'application/json' };+interface RedditApiError {+ error?: number | string;+ message?: string;+}++interface RedditApiUser {+ name: string;+ total_karma?: number;+ link_karma: number;+ comment_karma: number;+ awardee_karma?: number;+ awarder_karma?: number;+ icon_img?: string;+ snoovatar_img?: string;+ created_utc?: number;+ is_gold?: boolean;+ is_mod?: boolean;+ verified?: boolean;+}++interface RedditApiPost {+ id: string;+ title: string;+ subreddit: string;+ subreddit_name_prefixed?: string;+ author?: string;+ score?: number;+ upvote_ratio?: number;+ num_comments?: number;+ url?: string;+ permalink: string;+ thumbnail?: string;+ post_hint?: string;+ is_self?: boolean;+ is_video?: boolean;+ over_18?: boolean;+ created_utc?: number;+ link_flair_text?: string | null;+ total_awards_received?: number;+}++interface RedditThing<T> {+ kind?: string;+ data: T;+}++interface RedditListing<T> {+ data?: {+ children?: RedditThing<T>[];+ after?: string | null;+ };+}++type RedditCookie = string | null | undefined;++async function redditFetch<T>(path: string, cookie: RedditCookie): Promise<T> {+ const headers: Record<string, string> = { 'User-Agent': USER_AGENT, 'Accept': 'application/json' };if (cookie) headers['Cookie'] = `reddit_session=${cookie}`;const res = await fetch(`${REDDIT_BASE}${path}`, { headers });@@ -15,13 +72,13 @@ async function redditFetch(path, cookie) {if (res.status === 429) throw new Error('Reddit rate limit hit - try again in a moment');if (!res.ok) throw new Error(`Reddit API ${res.status}: ${res.statusText}`);- const data = await res.json();+ const data = await res.json() as T & RedditApiError;if (data.error) throw new Error(data.message || 'Reddit API error');return data;}-export async function fetchRedditProfile(username, cookie) {- const data = await redditFetch(`/user/${username}/about.json`, cookie);+export async function fetchRedditProfile(username: string, cookie: RedditCookie): Promise<RedditProfile> {+ const data = await redditFetch<RedditThing<RedditApiUser>>(`/user/${username}/about.json`, cookie);const user = data.data;return {username: user.name,@@ -38,14 +95,14 @@ export async function fetchRedditProfile(username, cookie) {};}-function redditMediaType(post) {+function redditMediaType(post: RedditApiPost): RedditMediaType {if (post.is_video) return 'video';if (post.post_hint === 'image') return 'image';if (post.is_self) return 'text';return 'link';}-function normalizeRedditPost(post) {+function normalizeRedditPost(post: RedditApiPost): RedditPost {return {id: post.id,title: post.title,@@ -67,9 +124,9 @@ function normalizeRedditPost(post) {};}-export async function fetchRedditPosts(username, cookie, limit = 100) {- const allPosts = [];- let after = null;+export async function fetchRedditPosts(username: string, cookie: RedditCookie, limit = 100): Promise<RedditPost[]> {+ const allPosts: RedditApiPost[] = [];+ let after: string | null = null;let pages = 0;while (pages < 10 && allPosts.length < limit) {@@ -79,7 +136,7 @@ export async function fetchRedditPosts(username, cookie, limit = 100) {});if (after) query.set('after', after);- const data = await redditFetch(`/user/${username}/submitted.json?${query}`, cookie);+ const data: RedditListing<RedditApiPost> = await redditFetch<RedditListing<RedditApiPost>>(`/user/${username}/submitted.json?${query}`, cookie);const children = data.data?.children ?? [];if (children.length === 0) break;@@ -93,10 +150,10 @@ export async function fetchRedditPosts(username, cookie, limit = 100) {}// no-op kept because the server.js cron handler still calls it-export async function autoRefreshRedditSessions() {}+export async function autoRefreshRedditSessions(): Promise<void> {}-function parseRedditPostUrl(rawUrl) {- let parsedUrl;+function parseRedditPostUrl(rawUrl: string): string {+ let parsedUrl: URL;try {parsedUrl = new URL(rawUrl);} catch {@@ -108,9 +165,9 @@ function parseRedditPostUrl(rawUrl) {return match[1];}-export async function fetchTrackedPostData(postUrl, cookie) {+export async function fetchTrackedPostData(postUrl: string, cookie: RedditCookie): Promise<RedditTrackedPostData> {const path = parseRedditPostUrl(postUrl);- const data = await redditFetch(`${path}.json`, cookie);+ const data = await redditFetch<RedditListing<RedditApiPost>[]>(`${path}.json`, cookie);if (!Array.isArray(data) || !data[0]) throw new Error('Unexpected Reddit response - post may be deleted or private');const post = data[0]?.data?.children?.[0]?.data;if (!post) throw new Error('Post not found or has been deleted');diff --git a/backend/services/redditAnalytics.ts b/backend/services/redditAnalytics.tsindex 66e0125..74e25b2 100644--- a/backend/services/redditAnalytics.ts+++ b/backend/services/redditAnalytics.ts@@ -2,10 +2,13 @@ import {DAY_NAMES, sumOf, roundedAverage, medianOf, countWithinDays, postFrequency,consistencyScore, bestToAverageRatio, pickHighest, monthKey,} from './analyticsMath.ts';+import type {+ RedditAnalytics, RedditPost, RedditProfile, RedditSubredditStats, RedditMediaType, RedditMonthStats,+} from '../../shared/types/reddit.ts';const MAX_SUBREDDITS = 20;-function emptyRedditAnalytics() {+function emptyRedditAnalytics(): RedditAnalytics {return {fetchedPosts: 0, totalScore: 0, avgScore: 0, medianScore: 0,totalComments: 0, avgComments: 0, avgUpvoteRatio: 0,@@ -20,7 +23,10 @@ function emptyRedditAnalytics() {};}-function summarizeScores(posts) {+type ScoreSummary = Pick<RedditAnalytics,+ 'totalScore' | 'avgScore' | 'medianScore' | 'totalComments' | 'avgComments' | 'avgUpvoteRatio' | 'totalAwards' | 'avgAwards'>;++function summarizeScores(posts: RedditPost[]): ScoreSummary {const totalScore = sumOf(posts, post => post.score);const totalComments = sumOf(posts, post => post.numComments);const totalAwards = sumOf(posts, post => post.awardsCount ?? 0);@@ -37,8 +43,10 @@ function summarizeScores(posts) {};}-function buildSubredditBreakdown(posts) {- const subreddits = {};+type SubredditTotals = Omit<RedditSubredditStats, 'avgScore' | 'avgComments'>;++function buildSubredditBreakdown(posts: RedditPost[]): RedditSubredditStats[] {+ const subreddits: Record<string, SubredditTotals> = {};posts.forEach(post => {const name = post.subreddit;if (!subreddits[name]) subreddits[name] = { subreddit: name, posts: 0, totalScore: 0, totalComments: 0 };@@ -56,14 +64,14 @@ function buildSubredditBreakdown(posts) {.slice(0, MAX_SUBREDDITS);}-function buildMediaTypeDistribution(posts) {- const distribution = {};+function buildMediaTypeDistribution(posts: RedditPost[]): Partial<Record<RedditMediaType, number>> {+ const distribution: Partial<Record<RedditMediaType, number>> = {};posts.forEach(post => { distribution[post.mediaType] = (distribution[post.mediaType] ?? 0) + 1; });return distribution;}// dates skips undated posts yet is indexed by posts, matching stored analytics-function fillTimeBuckets(dates, posts) {+function fillTimeBuckets(dates: Date[], posts: RedditPost[]) {const dayBuckets = Array(7).fill(null).map(() => ({ count: 0, score: 0, comments: 0 }));const hourBuckets = Array(24).fill(null).map(() => ({ count: 0, score: 0 }));dates.forEach((date, i) => {@@ -78,7 +86,9 @@ function fillTimeBuckets(dates, posts) {return { dayBuckets, hourBuckets };}-function summarizeTiming(dates, posts) {+type TimingSummary = Pick<RedditAnalytics, 'postsByDayOfWeek' | 'bestPostingDay' | 'postsByHour' | 'bestPostingHour'>;++function summarizeTiming(dates: Date[], posts: RedditPost[]): TimingSummary {const { dayBuckets, hourBuckets } = fillTimeBuckets(dates, posts);const postsByDayOfWeek = dayBuckets.map((bucket, i) => ({day: DAY_NAMES[i], shortDay: DAY_NAMES[i].slice(0, 3),@@ -99,12 +109,18 @@ function summarizeTiming(dates, posts) {};}-function buildMonthlyBreakdown(posts) {- const months = {};+interface MonthTotals {+ posts: number;+ score: number;+ comments: number;+}++function buildMonthlyBreakdown(posts: RedditPost[]): RedditMonthStats[] {+ const months: Record<string, MonthTotals> = {};posts.forEach(post => {if (!post.createdAt) return;const date = new Date(post.createdAt);- if (isNaN(date)) return;+ if (isNaN(date as unknown as number)) return;const key = monthKey(date);if (!months[key]) months[key] = { posts: 0, score: 0, comments: 0 };months[key].posts++;@@ -119,7 +135,7 @@ function buildMonthlyBreakdown(posts) {}));}-function countRecentPosts(dates) {+function countRecentPosts(dates: Date[]): Pick<RedditAnalytics, 'postsLast7Days' | 'postsLast30Days' | 'postsLast90Days'> {const now = Date.now();return {postsLast7Days: countWithinDays(dates, now, 7),@@ -128,12 +144,12 @@ function countRecentPosts(dates) {};}-export function computeRedditAnalytics(_profile, posts) {+export function computeRedditAnalytics(_profile: RedditProfile, posts: RedditPost[] | null | undefined): RedditAnalytics {if (!posts || posts.length === 0) return emptyRedditAnalytics();const scores = summarizeScores(posts);const byScore = [...posts].sort((first, second) => second.score - first.score);- const dates = posts.map(post => (post.createdAt ? new Date(post.createdAt) : null)).filter(Boolean);+ const dates = posts.map(post => (post.createdAt ? new Date(post.createdAt) : null)).filter(Boolean) as Date[];const monthlyBreakdown = buildMonthlyBreakdown(posts);return {diff --git a/backend/services/trackedContent.ts b/backend/services/trackedContent.tsindex f1c5c38..8a6df14 100644--- a/backend/services/trackedContent.ts+++ b/backend/services/trackedContent.ts@@ -1,4 +1,9 @@-export function detectContentType(url) {+export type TrackedContentType = 'reddit' | 'youtube';++// either a validation error to send back or the fields to merge into the tracked post's data+export type PatchResult<P> = { error: string; patch?: undefined } | { patch: P; error?: undefined };++export function detectContentType(url: string | null | undefined): TrackedContentType | null {const lower = (url || '').toLowerCase();if (lower.includes('reddit.com') || lower.includes('redd.it')) return 'reddit';if (lower.includes('youtube.com') || lower.includes('youtu.be')) return 'youtube';@@ -6,7 +11,7 @@ export function detectContentType(url) {}// reddit dropped view_count in 2018 so views are typed in; youtube keeps its own-export function manualViewsPatch(manualViews, isYouTube) {+export function manualViewsPatch(manualViews: unknown, isYouTube: boolean): PatchResult<{ manualViews: number | null }> {if (isYouTube) return { error: 'YouTube view counts are fetched automatically and cannot be set by hand' };if (manualViews === null || manualViews === '') return { patch: { manualViews: null } };@@ -15,7 +20,7 @@ export function manualViewsPatch(manualViews, isYouTube) {return { patch: { manualViews: views } };}-function parseUrl(value) {+function parseUrl(value: unknown): URL | null {try {return new URL(String(value));} catch {@@ -25,7 +30,7 @@ function parseUrl(value) {}// reddit has no thumbnail, so the browser uploads one; youtube keeps its own-export function imageUrlPatch(imageUrl, isYouTube) {+export function imageUrlPatch(imageUrl: unknown, isYouTube: boolean): PatchResult<{ imageUrl: string | null }> {if (isYouTube) return { error: 'Images can only be attached to Reddit posts' };if (imageUrl === null || imageUrl === '') return { patch: { imageUrl: null } };diff --git a/backend/services/youtubeAnalytics.ts b/backend/services/youtubeAnalytics.tsindex cf9df1e..83c0484 100644--- a/backend/services/youtubeAnalytics.ts+++ b/backend/services/youtubeAnalytics.ts@@ -4,11 +4,57 @@ import {buildPublishTiming, buildCategoryDistribution, buildTagFrequency, countRecentUploads,buildUploadFrequency, weeklyConsistencyScore, buildViewsDistribution, buildMonthlyTrends,} from './youtubeTrends.ts';+import type { VideoAnalytics, YouTubeVideo, YouTubeDurationDistribution } from '../../shared/types/youtube.ts';++// a stored video with the per-video rates the analytics are built from+export interface EnrichedVideo extends YouTubeVideo {+ engagementRate: number;+ likeRate: number;+ commentRate: number;+ durationSeconds: number;+ daysSinceUpload: number;+}++interface SortedVideos {+ byViews: EnrichedVideo[];+ byLikes: EnrichedVideo[];+ byComments: EnrichedVideo[];+ byDate: EnrichedVideo[];+ byEngagement: EnrichedVideo[];+}++type VideoTotals = Pick<VideoAnalytics,+ 'totalViews' | 'totalLikes' | 'totalComments' | 'avgViews' | 'avgLikes' | 'avgComments'+ | 'medianViews' | 'totalEngagement' | 'overallEngagementRate'>;++type DurationSummary = Required<Pick<VideoAnalytics,+ 'avgDurationSeconds' | 'avgDurationFormatted' | 'totalDurationSeconds' | 'totalDurationFormatted'+ | 'estimatedTotalWatchTimeHours'>>;++type RankingSummary = Pick<VideoAnalytics,+ 'bestByViews' | 'bestByLikes' | 'bestByComments' | 'bestByEngagement' | 'worstByViews' | 'mostRecent' | 'oldest'+ | 'top10ByViews' | 'top10ByLikes' | 'top10ByComments' | 'top10ByEngagement'>;++type ShortsSummary = Required<Pick<VideoAnalytics,+ 'shortsCount' | 'regularCount' | 'avgShortViews' | 'avgRegularViews' | 'avgShortLikes' | 'avgRegularLikes'>>;++interface FlagSummary {+ hdCount: number;+ sdCount: number;+ hdPercentage: string;+ captionCount: number;+ captionPercentage: string;+ licensedCount: number;+ licensedPercentage: string;+ madeForKidsCount: number;+ embeddableCount: number;+ embeddablePercentage: string;+}// shorts are judged by duration alone: any video up to 60 seconds countsconst SHORT_MAX_SECONDS = 60;-function emptyVideoAnalytics() {+function emptyVideoAnalytics(): VideoAnalytics {return {totalVideos: 0, totalViews: 0, totalLikes: 0, totalComments: 0,avgViews: 0, avgLikes: 0, avgComments: 0, medianViews: 0,@@ -38,35 +84,36 @@ function emptyVideoAnalytics() {};}-function rateOfViews(count, video) {+function rateOfViews(count: number, video: YouTubeVideo): number {return video.viewCount > 0 ? (count / video.viewCount) * 100 : 0;}-function withEngagementRates(video, now) {+// hidden counts are null, which adds, subtracts and divides as zero+function withEngagementRates(video: YouTubeVideo, now: Date): EnrichedVideo {return {...video,- engagementRate: rateOfViews(video.likeCount + video.commentCount, video),- likeRate: rateOfViews(video.likeCount, video),- commentRate: rateOfViews(video.commentCount, video),+ engagementRate: rateOfViews((video.likeCount as number) + (video.commentCount as number), video),+ likeRate: rateOfViews(video.likeCount as number, video),+ commentRate: rateOfViews(video.commentCount as number, video),durationSeconds: parseDuration(video.duration),- daysSinceUpload: Math.max(1, Math.floor((now - new Date(video.publishedAt)) / DAY_MS)),+ daysSinceUpload: Math.max(1, Math.floor(((now as unknown as number) - (new Date(video.publishedAt) as unknown as number)) / DAY_MS)),};}-function sortVideos(videos) {+function sortVideos(videos: EnrichedVideo[]): SortedVideos {return {byViews: [...videos].sort((first, second) => second.viewCount - first.viewCount),- byLikes: [...videos].sort((first, second) => second.likeCount - first.likeCount),- byComments: [...videos].sort((first, second) => second.commentCount - first.commentCount),- byDate: [...videos].sort((first, second) => new Date(second.publishedAt) - new Date(first.publishedAt)),+ byLikes: [...videos].sort((first, second) => (second.likeCount as number) - (first.likeCount as number)),+ byComments: [...videos].sort((first, second) => (second.commentCount as number) - (first.commentCount as number)),+ byDate: [...videos].sort((first, second) => (new Date(second.publishedAt) as unknown as number) - (new Date(first.publishedAt) as unknown as number)),byEngagement: [...videos].sort((first, second) => second.engagementRate - first.engagementRate),};}-function summarizeTotals(videos) {+function summarizeTotals(videos: YouTubeVideo[]): VideoTotals {const totalViews = sumOf(videos, video => video.viewCount);- const totalLikes = sumOf(videos, video => video.likeCount);- const totalComments = sumOf(videos, video => video.commentCount);+ const totalLikes = sumOf(videos, video => video.likeCount as number);+ const totalComments = sumOf(videos, video => video.commentCount as number);return {totalViews, totalLikes, totalComments,avgViews: Math.round(totalViews / videos.length),@@ -78,7 +125,7 @@ function summarizeTotals(videos) {};}-function summarizeDurations(totalDuration, totalViews, videoCount) {+function summarizeDurations(totalDuration: number, totalViews: number, videoCount: number): DurationSummary {return {avgDurationSeconds: Math.round(totalDuration / videoCount),avgDurationFormatted: formatDuration(Math.round(totalDuration / videoCount)),@@ -89,7 +136,7 @@ function summarizeDurations(totalDuration, totalViews, videoCount) {};}-function summarizeRankings(sorted) {+function summarizeRankings(sorted: SortedVideos): RankingSummary {const { byViews, byLikes, byComments, byDate, byEngagement } = sorted;return {bestByViews: formatVideoSummary(byViews[0]),@@ -106,7 +153,7 @@ function summarizeRankings(sorted) {};}-function summarizeShorts(videos) {+function summarizeShorts(videos: EnrichedVideo[]): ShortsSummary {const shorts = videos.filter(video => video.durationSeconds <= SHORT_MAX_SECONDS);const regular = videos.filter(video => video.durationSeconds > SHORT_MAX_SECONDS);return {@@ -114,16 +161,16 @@ function summarizeShorts(videos) {regularCount: regular.length,avgShortViews: roundedAverage(sumOf(shorts, video => video.viewCount), shorts.length),avgRegularViews: roundedAverage(sumOf(regular, video => video.viewCount), regular.length),- avgShortLikes: roundedAverage(sumOf(shorts, video => video.likeCount), shorts.length),- avgRegularLikes: roundedAverage(sumOf(regular, video => video.likeCount), regular.length),+ avgShortLikes: roundedAverage(sumOf(shorts, video => video.likeCount as number), shorts.length),+ avgRegularLikes: roundedAverage(sumOf(regular, video => video.likeCount as number), regular.length),};}-function percentOf(count, total) {+function percentOf(count: number, total: number): string {return ((count / total) * 100).toFixed(1);}-function summarizeFlags(videos) {+function summarizeFlags(videos: YouTubeVideo[]): FlagSummary {const hdCount = videos.filter(video => video.definition === 'hd').length;const captionCount = videos.filter(video => video.caption).length;const licensedCount = videos.filter(video => video.licensedContent).length;@@ -138,8 +185,8 @@ function summarizeFlags(videos) {};}-function buildDurationDistribution(videos) {- const distribution = { short: 0, medium: 0, long: 0, veryLong: 0 };+function buildDurationDistribution(videos: EnrichedVideo[]): YouTubeDurationDistribution {+ const distribution: YouTubeDurationDistribution = { short: 0, medium: 0, long: 0, veryLong: 0 };videos.forEach(video => {if (video.durationSeconds <= SHORT_MAX_SECONDS) distribution.short++;else if (video.durationSeconds <= 600) distribution.medium++;@@ -149,11 +196,11 @@ function buildDurationDistribution(videos) {return distribution;}-function viralityScore(topViews, avgViews) {+function viralityScore(topViews: number, avgViews: number): number {return avgViews > 0 ? Math.round(topViews / avgViews * 10) / 10 : 0;}-export function computeVideoAnalytics(videos) {+export function computeVideoAnalytics(videos: YouTubeVideo[] | null | undefined): VideoAnalytics {if (!videos || videos.length === 0) return emptyVideoAnalytics();const now = new Date();diff --git a/backend/services/youtubeApi.ts b/backend/services/youtubeApi.tsindex 9a9fb1b..d0e1862 100644--- a/backend/services/youtubeApi.ts+++ b/backend/services/youtubeApi.ts@@ -1,12 +1,104 @@+export type YouTubeApiParams = Record<string, string>;++export interface YouTubeApiThumbnail {+ url: string;+ width?: number;+ height?: number;+}++export type YouTubeApiThumbnails = Partial<Record<'default' | 'medium' | 'high' | 'standard' | 'maxres', YouTubeApiThumbnail>>;++export interface YouTubeApiListResponse<TItem> {+ items?: TItem[];+ nextPageToken?: string;+ pageInfo?: { totalResults: number; resultsPerPage: number };+}++export interface YouTubeApiErrorBody {+ error?: {+ code: number;+ message: string;+ errors?: { reason?: string; message?: string; domain?: string }[];+ };+}++export interface YouTubeApiError extends Error {+ reason?: string;+ status?: number;+}++export interface YouTubeApiChannel {+ id: string;+ snippet: {+ title: string;+ description: string;+ customUrl?: string;+ publishedAt: string;+ country?: string;+ thumbnails?: YouTubeApiThumbnails;+ };+ statistics: {+ subscriberCount: string;+ viewCount: string;+ videoCount: string;+ hiddenSubscriberCount?: boolean;+ };+ contentDetails?: { relatedPlaylists?: { uploads?: string } };+ brandingSettings?: { channel?: { keywords?: string }; image?: { bannerExternalUrl?: string } };+ status?: { madeForKids?: boolean; isLinked?: boolean };+ topicDetails?: { topicCategories?: string[] };+}++export interface YouTubeApiSearchResult {+ id: { kind: string; channelId?: string; videoId?: string };+ snippet: { channelId: string; title?: string };+}++export interface YouTubeApiPlaylistItem {+ snippet: { resourceId: { videoId: string } };+ contentDetails?: { videoId: string; videoPublishedAt?: string };+}++export interface YouTubeApiVideo {+ id: string;+ snippet: {+ title: string;+ description?: string;+ publishedAt: string;+ channelId: string;+ channelTitle: string;+ thumbnails?: YouTubeApiThumbnails;+ tags?: string[];+ categoryId?: string;+ liveBroadcastContent?: string;+ defaultAudioLanguage?: string;+ };+ contentDetails: {+ duration: string;+ dimension?: string;+ definition?: string;+ caption?: string;+ licensedContent?: boolean;+ projection?: string;+ };+ // youtube leaves likeCount and commentCount out when they are hidden or turned off+ statistics: {+ viewCount: string;+ likeCount?: string;+ commentCount?: string;+ };+ status?: { privacyStatus?: string; embeddable?: boolean; madeForKids?: boolean };+}+// adds the key to the caller's params object, as callers always pass a fresh one-export async function ytFetch(endpoint, params, apiKey) {+export async function ytFetch<T>(endpoint: string, params: YouTubeApiParams, apiKey: string): Promise<T> {const url = new URL(`https://www.googleapis.com/youtube/v3/${endpoint}`);params.key = apiKey;Object.entries(params).forEach(([key, value]) => url.searchParams.set(key, value));const response = await fetch(url.toString());- const data = await response.json();+ const data = await response.json() as T & YouTubeApiErrorBody;if (data.error) {- const err = new Error(data.error.message);+ const err: YouTubeApiError = new Error(data.error.message);err.reason = data.error.errors?.[0]?.reason || '';err.status = data.error.code;throw err;@@ -14,7 +106,7 @@ export async function ytFetch(endpoint, params, apiKey) {return data;}-export function optionalCount(value) {+export function optionalCount(value: string | null | undefined): number | null {if (value == null) return null;const count = parseInt(value, 10);return Number.isFinite(count) ? count : null;diff --git a/backend/services/youtubeChannels.ts b/backend/services/youtubeChannels.tsindex f53afb9..056c468 100644--- a/backend/services/youtubeChannels.ts+++ b/backend/services/youtubeChannels.ts@@ -1,4 +1,6 @@import { ytFetch } from './youtubeApi.ts';+import type { YouTubeApiParams, YouTubeApiListResponse, YouTubeApiChannel, YouTubeApiSearchResult } from './youtubeApi.ts';+import type { YouTubeChannelData } from '../../shared/types/youtube.ts';const CHANNEL_ID_PATTERN = /^UC[\w-]{22}$/;const CHANNEL_URL_PATTERNS = [@@ -9,7 +11,7 @@ const CHANNEL_URL_PATTERNS = [/youtube\.com\/([\w.-]+)/,];-function extractChannelId(input) {+function extractChannelId(input: string | null | undefined): string | null {if (!input) return null;const trimmed = input.trim();if (CHANNEL_ID_PATTERN.test(trimmed)) return trimmed;@@ -21,9 +23,11 @@ function extractChannelId(input) {}// null when the lookup finds nothing or fails, so the next strategy runs-async function lookupChannelId(endpoint, params, pickId, apiKey) {+async function lookupChannelId<TItem>(+ endpoint: string, params: YouTubeApiParams, pickId: (item: TItem) => string, apiKey: string,+): Promise<string | null> {try {- const data = await ytFetch(endpoint, params, apiKey);+ const data = await ytFetch<YouTubeApiListResponse<TItem>>(endpoint, params, apiKey);if (data.items && data.items.length > 0) return pickId(data.items[0]);return null;} catch {@@ -31,27 +35,27 @@ async function lookupChannelId(endpoint, params, pickId, apiKey) {}}-export async function resolveChannelId(input, apiKey) {+export async function resolveChannelId(input: string | null | undefined, apiKey: string): Promise<string> {const extracted = extractChannelId(input);if (!extracted) throw new Error('Invalid input');if (CHANNEL_ID_PATTERN.test(extracted)) return extracted;// sequential on purpose: a search costs 100 quota units- const byHandle = await lookupChannelId('channels', { part: 'id', forHandle: extracted }, (item) => item.id, apiKey);+ const byHandle = await lookupChannelId<YouTubeApiChannel>('channels', { part: 'id', forHandle: extracted }, (item) => item.id, apiKey);if (byHandle !== null) return byHandle;- const byUsername = await lookupChannelId('channels', { part: 'id', forUsername: extracted }, (item) => item.id, apiKey);+ const byUsername = await lookupChannelId<YouTubeApiChannel>('channels', { part: 'id', forUsername: extracted }, (item) => item.id, apiKey);if (byUsername !== null) return byUsername;const searchParams = { part: 'snippet', q: extracted, type: 'channel', maxResults: '1' };- const bySearch = await lookupChannelId('search', searchParams, (item) => item.snippet.channelId, apiKey);+ const bySearch = await lookupChannelId<YouTubeApiSearchResult>('search', searchParams, (item) => item.snippet.channelId, apiKey);if (bySearch !== null) return bySearch;throw new Error('Could not resolve channel. Please provide a valid Channel ID (starts with UC).');}-export async function fetchChannelData(channelId, apiKey) {- const data = await ytFetch('channels', {+export async function fetchChannelData(channelId: string, apiKey: string): Promise<YouTubeChannelData> {+ const data = await ytFetch<YouTubeApiListResponse<YouTubeApiChannel>>('channels', {part: 'snippet,statistics,contentDetails,brandingSettings,status,topicDetails',id: channelId,}, apiKey);diff --git a/backend/services/youtubeFormat.ts b/backend/services/youtubeFormat.tsindex d0c438f..04f70e2 100644--- a/backend/services/youtubeFormat.ts+++ b/backend/services/youtubeFormat.ts@@ -1,24 +1,31 @@+import type { YouTubeVideo, YouTubeVideoSummary } from '../../shared/types/youtube.ts';++// a stored video, optionally carrying the rates computeVideoAnalytics() adds+export type VideoSummarySource = YouTubeVideo & { engagementRate?: number; durationSeconds?: number };+// ignores the day part, so durations such as P1DT2H parse as zero seconds-export function parseDuration(iso) {+export function parseDuration(iso: string): number {const match = iso.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/);if (!match) return 0;- return (parseInt(match[1] || 0) * 3600) + (parseInt(match[2] || 0) * 60) + parseInt(match[3] || 0);+ return (parseInt((match[1] || 0) as string) * 3600) + (parseInt((match[2] || 0) as string) * 60) + parseInt((match[3] || 0) as string);}-export function formatCompact(value) {+export function formatCompact(value: number): string {if (value >= 1e6) return (value / 1e6).toFixed(1) + 'M';if (value >= 1e3) return (value / 1e3).toFixed(1) + 'K';return value.toString();}-export function formatDuration(totalSeconds) {+export function formatDuration(totalSeconds: number): string {const hours = Math.floor(totalSeconds / 3600);const minutes = Math.floor((totalSeconds % 3600) / 60);const seconds = totalSeconds % 60;return hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m ${seconds}s`;}-export function formatVideoSummary(video) {+export function formatVideoSummary(video: VideoSummarySource): YouTubeVideoSummary;+export function formatVideoSummary(video: VideoSummarySource | undefined): YouTubeVideoSummary | null;+export function formatVideoSummary(video: VideoSummarySource | undefined): YouTubeVideoSummary | null {if (!video) return null;return {videoId: video.videoId, title: video.title, viewCount: video.viewCount,diff --git a/backend/services/youtubeLibrary.ts b/backend/services/youtubeLibrary.tsindex aefdf4c..b6bc185 100644--- a/backend/services/youtubeLibrary.ts+++ b/backend/services/youtubeLibrary.ts@@ -1,21 +1,34 @@import { DAY_MS } from './analyticsMath.ts';+import type { Account } from '../../shared/types/domain.ts';+import type { YouTubeAccountComparison, YouTubeChannelMetrics, YouTubeVideo } from '../../shared/types/youtube.ts';-// a channel without a creation date is treated as a year old-export function channelMetrics(account) {+// query string values from GET /api/videos/all+export interface VideoLibraryFilters {+ search?: string;+ minViews?: string;+ maxViews?: string;+ sort?: string;+ order?: string;+}++type ComparableAccount = Pick<Account, 'subscriberCount' | 'viewCount' | 'videoCount'>;++// a channel without a creation date is treated as a year old; youtube accounts always store their counts+export function channelMetrics(account: Account): YouTubeChannelMetrics {const channelAge = account.publishedAt? Math.floor((Date.now() - new Date(account.publishedAt).getTime()) / DAY_MS): 365;- const viewsPerSub = account.subscriberCount > 0 ? (account.viewCount / account.subscriberCount).toFixed(1) : 0;- const subsPerView = account.viewCount > 0 ? (account.subscriberCount / account.viewCount * 100).toFixed(4) : 0;- const avgViewsPerVideo = account.videoCount > 0 ? Math.round(account.viewCount / account.videoCount) : 0;- const avgSubGainPerDay = channelAge > 0 ? Math.round(account.subscriberCount / channelAge) : 0;- const avgViewsPerDay = channelAge > 0 ? Math.round(account.viewCount / channelAge) : 0;+ const viewsPerSub = account.subscriberCount! > 0 ? (account.viewCount! / account.subscriberCount!).toFixed(1) : 0;+ const subsPerView = account.viewCount! > 0 ? (account.subscriberCount! / account.viewCount! * 100).toFixed(4) : 0;+ const avgViewsPerVideo = account.videoCount! > 0 ? Math.round(account.viewCount! / account.videoCount!) : 0;+ const avgSubGainPerDay = channelAge > 0 ? Math.round(account.subscriberCount! / channelAge) : 0;+ const avgViewsPerDay = channelAge > 0 ? Math.round(account.viewCount! / channelAge) : 0;return {channelAge,channelAgeYears: (channelAge / 365).toFixed(1),- viewsPerSubscriber: parseFloat(viewsPerSub),- subscriberToViewRatio: parseFloat(subsPerView),+ viewsPerSubscriber: parseFloat(viewsPerSub as string),+ subscriberToViewRatio: parseFloat(subsPerView as string),avgViewsPerVideo,avgSubGainPerDay,avgViewsPerDay,@@ -26,11 +39,11 @@ export function channelMetrics(account) {};}-export function accountComparison(accounts) {+export function accountComparison<TAccount extends ComparableAccount>(accounts: TAccount[]): YouTubeAccountComparison<TAccount> {const sorted = {- bySubscribers: [...accounts].sort((first, second) => second.subscriberCount - first.subscriberCount),- byViews: [...accounts].sort((first, second) => second.viewCount - first.viewCount),- byVideos: [...accounts].sort((first, second) => second.videoCount - first.videoCount),+ bySubscribers: [...accounts].sort((first, second) => second.subscriberCount! - first.subscriberCount!),+ byViews: [...accounts].sort((first, second) => second.viewCount! - first.viewCount!),+ byVideos: [...accounts].sort((first, second) => second.videoCount! - first.videoCount!),};const totals = accounts.reduce((acc, account) => ({@@ -49,11 +62,13 @@ export function accountComparison(accounts) {};}-function matchesSearch(video, term) {+function matchesSearch(video: YouTubeVideo, term: string): boolean {return video.title?.toLowerCase().includes(term) || (video.tags || []).some(tag => tag.toLowerCase().includes(term));}-export function filterAndSortVideos(videos, { search, minViews, maxViews, sort, order }) {+export function filterAndSortVideos<TVideo extends YouTubeVideo>(+ videos: TVideo[], { search, minViews, maxViews, sort, order }: VideoLibraryFilters,+): TVideo[] {let result = videos;if (search) {const term = search.toLowerCase();@@ -65,10 +80,10 @@ export function filterAndSortVideos(videos, { search, minViews, maxViews, sort,const sortField = sort || 'viewCount';const sortOrder = order === 'asc' ? 1 : -1;result.sort((first, second) => {- const firstValue = first[sortField] ?? 0;- const secondValue = second[sortField] ?? 0;- if (typeof firstValue === 'string') return sortOrder * firstValue.localeCompare(secondValue);- return sortOrder * (secondValue - firstValue);+ const firstValue = first[sortField as keyof YouTubeVideo] ?? 0;+ const secondValue = second[sortField as keyof YouTubeVideo] ?? 0;+ if (typeof firstValue === 'string') return sortOrder * firstValue.localeCompare(secondValue as string);+ return sortOrder * ((secondValue as number) - (firstValue as number));});return result;}diff --git a/backend/services/youtubeTracked.ts b/backend/services/youtubeTracked.tsindex 9c1f649..c002991 100644--- a/backend/services/youtubeTracked.ts+++ b/backend/services/youtubeTracked.ts@@ -1,7 +1,12 @@import { ytFetch, optionalCount } from './youtubeApi.ts';+import type { YouTubeApiListResponse, YouTubeApiVideo } from './youtubeApi.ts';+import type { YouTubeTrackedVideoData } from '../../shared/types/youtube.ts';-export function extractYouTubeVideoId(url) {- let parsedUrl;+// requested with part=snippet,statistics only+type TrackedApiVideo = Pick<YouTubeApiVideo, 'id' | 'snippet' | 'statistics'>;++export function extractYouTubeVideoId(url: string): string | null {+ let parsedUrl: URL;try {parsedUrl = new URL(url.trim());} catch {@@ -16,11 +21,11 @@ export function extractYouTubeVideoId(url) {return searchParams.get('v');}-export async function fetchTrackedYouTubeData(videoUrl, apiKey) {+export async function fetchTrackedYouTubeData(videoUrl: string, apiKey: string): Promise<YouTubeTrackedVideoData> {const videoId = extractYouTubeVideoId(videoUrl);if (!videoId) throw new Error('Invalid YouTube URL - could not extract video ID');- const data = await ytFetch('videos', {+ const data = await ytFetch<YouTubeApiListResponse<TrackedApiVideo>>('videos', {part: 'snippet,statistics',id: videoId,}, apiKey);diff --git a/backend/services/youtubeTrends.ts b/backend/services/youtubeTrends.tsindex 4f73b94..52476da 100644--- a/backend/services/youtubeTrends.ts+++ b/backend/services/youtubeTrends.ts@@ -1,17 +1,35 @@import { DAY_NAMES, DAY_MS, monthKey } from './analyticsMath.ts';import { formatCompact } from './youtubeFormat.ts';+import type {+ VideoAnalytics, YouTubeVideo, YouTubeTagCount, YouTubeViewsDistribution, YouTubeMonthlyTrends, FormattedRate,+} from '../../shared/types/youtube.ts';++export type YouTubePublishTiming = Pick<VideoAnalytics, 'publishDayDistribution' | 'publishHourDistribution' | 'peakPublishDay' | 'peakPublishHour'>;+export type YouTubeRecentUploads = Pick<VideoAnalytics, 'videosLast7Days' | 'videosLast30Days' | 'videosLast90Days' | 'videosLast365Days'>;++export interface YouTubeUploadFrequency {+ uploadFrequencyPerWeek: string;+ uploadFrequencyPerMonth: string;+}++interface MonthTotals {+ views: number;+ likes: number;+ comments: number;+ count: number;+}const WEEK_MS = 7 * DAY_MS;const HISTOGRAM_BUCKETS = 10;const MAX_TAGS = 30;-function byCountDescending(first, second) {+function byCountDescending(first: [string, number], second: [string, number]): number {return second[1] - first[1];}-export function buildPublishTiming(videos) {- const dayDistribution = {};- const hourDistribution = {};+export function buildPublishTiming(videos: YouTubeVideo[]): YouTubePublishTiming {+ const dayDistribution: Record<string, number> = {};+ const hourDistribution: Record<number, number> = {};videos.forEach(video => {const date = new Date(video.publishedAt);const day = DAY_NAMES[date.getUTCDay()];@@ -29,8 +47,8 @@ export function buildPublishTiming(videos) {};}-export function buildCategoryDistribution(videos) {- const distribution = {};+export function buildCategoryDistribution(videos: YouTubeVideo[]): Record<string, number> {+ const distribution: Record<string, number> = {};videos.forEach(video => {const category = video.categoryId || 'Unknown';distribution[category] = (distribution[category] || 0) + 1;@@ -38,8 +56,8 @@ export function buildCategoryDistribution(videos) {return distribution;}-export function buildTagFrequency(videos) {- const tagCounts = {};+export function buildTagFrequency(videos: YouTubeVideo[]): YouTubeTagCount[] {+ const tagCounts: Record<string, number> = {};videos.forEach(video => {(video.tags || []).forEach(tag => {const lower = tag.toLowerCase();@@ -53,8 +71,8 @@ export function buildTagFrequency(videos) {}// strict < unlike instagram and reddit (inclusive), to match stored analytics-export function countRecentUploads(videos, now) {- const uploadedWithin = (days) => videos.filter(video => (now - new Date(video.publishedAt)) < days * DAY_MS).length;+export function countRecentUploads(videos: YouTubeVideo[], now: Date): YouTubeRecentUploads {+ const uploadedWithin = (days: number) => videos.filter(video => ((now as unknown as number) - (new Date(video.publishedAt) as unknown as number)) < days * DAY_MS).length;return {videosLast7Days: uploadedWithin(7),videosLast30Days: uploadedWithin(30),@@ -63,9 +81,9 @@ export function countRecentUploads(videos, now) {};}-export function buildUploadFrequency(videoCount, oldestVideo, now) {+export function buildUploadFrequency(videoCount: number, oldestVideo: YouTubeVideo | undefined, now: Date): YouTubeUploadFrequency {const oldestDate = new Date(oldestVideo?.publishedAt || now);- const totalWeeks = Math.max(1, (now - oldestDate) / WEEK_MS);+ const totalWeeks = Math.max(1, ((now as unknown as number) - (oldestDate as unknown as number)) / WEEK_MS);const totalMonths = Math.max(1, totalWeeks / 4.33);return {uploadFrequencyPerWeek: (videoCount / totalWeeks).toFixed(1),@@ -74,9 +92,9 @@ export function buildUploadFrequency(videoCount, oldestVideo, now) {}// scores how evenly uploads spread across the weeks that have any-export function weeklyConsistencyScore(videos, now) {- const weeklyUploads = videos.reduce((weeks, video) => {- const weekNumber = Math.floor((now - new Date(video.publishedAt)) / WEEK_MS);+export function weeklyConsistencyScore(videos: YouTubeVideo[], now: Date): number {+ const weeklyUploads = videos.reduce<Record<number, number>>((weeks, video) => {+ const weekNumber = Math.floor(((now as unknown as number) - (new Date(video.publishedAt) as unknown as number)) / WEEK_MS);weeks[weekNumber] = (weeks[weekNumber] || 0) + 1;return weeks;}, {});@@ -89,10 +107,10 @@ export function weeklyConsistencyScore(videos, now) {}// known issue: < high drops the top video when ten buckets divide views evenly-export function buildViewsDistribution(videos, maxViews) {+export function buildViewsDistribution(videos: YouTubeVideo[], maxViews: number): YouTubeViewsDistribution {const step = Math.max(1, Math.ceil(maxViews / HISTOGRAM_BUCKETS));- const ranges = [];- const counts = [];+ const ranges: string[] = [];+ const counts: number[] = [];for (let i = 0; i < HISTOGRAM_BUCKETS; i++) {const low = i * step;const high = (i + 1) * step;@@ -102,18 +120,18 @@ export function buildViewsDistribution(videos, maxViews) {return { ranges, counts };}-function percentOfViews(count, views) {+function percentOfViews(count: number, views: number): FormattedRate {return views > 0 ? ((count / views) * 100).toFixed(2) : 0;}-export function buildMonthlyTrends(videos) {- const months = {};+export function buildMonthlyTrends(videos: YouTubeVideo[]): YouTubeMonthlyTrends {+ const months: Record<string, MonthTotals> = {};videos.forEach(video => {const key = monthKey(new Date(video.publishedAt));if (!months[key]) months[key] = { views: 0, likes: 0, comments: 0, count: 0 };months[key].views += video.viewCount;- months[key].likes += video.likeCount;- months[key].comments += video.commentCount;+ months[key].likes += video.likeCount as number;+ months[key].comments += video.commentCount as number;months[key].count++;});const sortedMonths = Object.keys(months).sort();diff --git a/backend/services/youtubeVideos.ts b/backend/services/youtubeVideos.tsindex 76ec263..e3edc30 100644--- a/backend/services/youtubeVideos.ts+++ b/backend/services/youtubeVideos.ts@@ -1,6 +1,8 @@import { ytFetch, optionalCount } from './youtubeApi.ts';+import type { YouTubeApiError, YouTubeApiListResponse, YouTubeApiParams, YouTubeApiPlaylistItem, YouTubeApiVideo } from './youtubeApi.ts';+import type { YouTubeVideo } from '../../shared/types/youtube.ts';-export function normalizeYouTubeVideo(video) {+export function normalizeYouTubeVideo(video: YouTubeApiVideo): YouTubeVideo {const { snippet, contentDetails, statistics, status } = video;return {videoId: video.id,@@ -33,29 +35,31 @@ export function normalizeYouTubeVideo(video) {};}-async function fetchPlaylistPage(playlistId, pageToken, apiKey) {- const params = { part: 'snippet,contentDetails', playlistId, maxResults: '50' };+async function fetchPlaylistPage(+ playlistId: string, pageToken: string, apiKey: string,+): Promise<YouTubeApiListResponse<YouTubeApiPlaylistItem> | null> {+ const params: YouTubeApiParams = { part: 'snippet,contentDetails', playlistId, maxResults: '50' };if (pageToken) params.pageToken = pageToken;try {- return await ytFetch('playlistItems', params, apiKey);+ return await ytFetch<YouTubeApiListResponse<YouTubeApiPlaylistItem>>('playlistItems', params, apiKey);} catch (err) {// youtube reports the uploads playlist missing until the first public video- if (err.reason === 'playlistNotFound') return null;+ if ((err as YouTubeApiError).reason === 'playlistNotFound') return null;throw err;}}-async function fetchVideoDetails(playlistItems, apiKey) {+async function fetchVideoDetails(playlistItems: YouTubeApiPlaylistItem[], apiKey: string): Promise<YouTubeVideo[]> {const videoIds = playlistItems.map(item => item.snippet.resourceId.videoId).join(',');- const statsData = await ytFetch('videos', {+ const statsData = await ytFetch<YouTubeApiListResponse<YouTubeApiVideo>>('videos', {part: 'statistics,contentDetails,snippet,status',id: videoIds,}, apiKey);return statsData.items ? statsData.items.map(normalizeYouTubeVideo) : [];}-export async function fetchAllVideos(playlistId, apiKey, maxPages = 10) {- const allVideos = [];+export async function fetchAllVideos(playlistId: string, apiKey: string, maxPages = 10): Promise<YouTubeVideo[]> {+ const allVideos: YouTubeVideo[] = [];let pageToken = '';let page = 0;diff --git a/backend/utils/scheduler.ts b/backend/utils/scheduler.tsindex 61791df..6467f97 100644--- a/backend/utils/scheduler.ts+++ b/backend/utils/scheduler.ts@@ -1,27 +1,33 @@// fetch is a global in Cloudflare Workers.import { getDuePosts, updatePost, getAccountById, claimPost } from '../lib/db.ts';import { buildMediaParams } from '../services/instagram.ts';+import type { InstagramMediaParams } from '../services/instagramPublishing.ts';+import type { InstagramApiContainerStatus, InstagramApiIdResponse } from '../services/instagramApi.ts';+import type { ScheduledPost, ScheduledPublishFailure, ScheduledPublishRun } from '../../shared/types/domain.ts';+import type { InstagramPublishMediaType } from '../../shared/types/instagram.ts';+import type { SupabaseClient } from '../types/app.ts';const GRAPH_API = 'https://graph.instagram.com/v25.0';-export function generateId() {+export function generateId(): string {return Date.now().toString(36) + Math.random().toString(36).substring(2, 8);}-function wait(ms) {- return new Promise(resolve => setTimeout(resolve, ms));+function wait(ms: number): Promise<void> {+ return new Promise<void>(resolve => setTimeout(resolve, ms));}-async function createContainer(igId, params) {- const query = new URLSearchParams(params).toString();+async function createContainer(igId: string, params: InstagramMediaParams): Promise<string> {+ // URLSearchParams stringifies the boolean and number values+ const query = new URLSearchParams(params as unknown as Record<string, string>).toString();const createRes = await fetch(`${GRAPH_API}/${igId}/media?${query}`, { method: 'POST' });- const createData = await createRes.json();+ const createData = await createRes.json() as InstagramApiIdResponse;if (createData.error) throw new Error(createData.error.message);return createData.id;}// reels and stories need processing; other media only need a short pause-async function waitForContainer(mediaType, containerId, token) {+async function waitForContainer(mediaType: InstagramPublishMediaType | undefined, containerId: string, token: string): Promise<void> {if (mediaType !== 'REELS' && mediaType !== 'STORIES') {await wait(2000);return;@@ -29,29 +35,29 @@ async function waitForContainer(mediaType, containerId, token) {for (let i = 0; i < 60; i++) {await wait(3000);const statusRes = await fetch(`${GRAPH_API}/${containerId}?fields=status_code,status&access_token=${token}`);- const statusData = await statusRes.json();+ const statusData = await statusRes.json() as InstagramApiContainerStatus;if (statusData.status_code === 'FINISHED' || statusData.status_code === 'PUBLISHED') return;if (statusData.status_code === 'ERROR') throw new Error('Processing failed: ' + (statusData.status || ''));if (statusData.status_code === 'EXPIRED') throw new Error('Container expired');}}-async function publishContainer(igId, containerId, token) {+async function publishContainer(igId: string, containerId: string, token: string): Promise<string> {const pubRes = await fetch(`${GRAPH_API}/${igId}/media_publish?creation_id=${containerId}&access_token=${token}`,{ method: 'POST' });- const pubData = await pubRes.json();+ const pubData = await pubRes.json() as InstagramApiIdResponse;if (pubData.error) throw new Error(pubData.error.message);return pubData.id;}-async function publishPost(supabase, post) {+async function publishPost(supabase: SupabaseClient, post: ScheduledPost): Promise<string> {const acct = await getAccountById(supabase, post.accountId);if (!acct) throw new Error('Account not found: ' + post.accountId);- const igId = acct.igUserId;- const token = acct.accessToken;+ const igId = acct.igUserId!;+ const token = acct.accessToken!;const params = buildMediaParams(post, token);const containerId = await createContainer(igId, params);@@ -60,9 +66,9 @@ async function publishPost(supabase, post) {}// cron entry: there is no request context, so supabase is passed in directly-export async function processScheduledPosts(supabase) {+export async function processScheduledPosts(supabase: SupabaseClient): Promise<ScheduledPublishRun> {let processed = 0;- const errors = [];+ const errors: ScheduledPublishFailure[] = [];try {const duePosts = await getDuePosts(supabase);@@ -80,9 +86,9 @@ export async function processScheduledPosts(supabase) {processed++;console.log(`Published scheduled post ${post.id} → media ${mediaId}`);} catch (err) {- await updatePost(supabase, post.id, { status: 'failed', error: err.message });- errors.push({ id: post.id, error: err.message });- console.error(`Failed to publish scheduled post ${post.id}: ${err.message}`);+ await updatePost(supabase, post.id, { status: 'failed', error: (err as Error).message });+ errors.push({ id: post.id, error: (err as Error).message });+ console.error(`Failed to publish scheduled post ${post.id}: ${(err as Error).message}`);}}} catch (err) {diff --git a/shared/types/domain.ts b/shared/types/domain.tsindex 67099d6..780a9df 100644--- a/shared/types/domain.ts+++ b/shared/types/domain.ts@@ -1,3 +1,5 @@+import type { InstagramContentTypeSummary } from './instagram.ts';+export type Platform = 'youtube' | 'instagram' | 'reddit';export interface YouTubeThumbnail {@@ -8,6 +10,13 @@ export interface YouTubeThumbnail {export type YouTubeThumbnails = Partial<Record<'default' | 'medium' | 'high' | 'standard' | 'maxres', YouTubeThumbnail>>;+// fetchChannelData() flattens each size to its url, and accounts store that shape+export interface ChannelThumbnails {+ default: string;+ medium: string;+ high: string;+}+// one row of `accounts`: id and platform are columns, every other field lives in the data jsonbexport interface Account {id: string;@@ -22,7 +31,7 @@ export interface Account {customUrl?: string;publishedAt?: string;country?: string;- thumbnails?: YouTubeThumbnails;+ thumbnails?: ChannelThumbnails;subscriberCount?: number;viewCount?: number;videoCount?: number;@@ -36,7 +45,8 @@ export interface Account {username?: string;- igUserId?: string;+ // null when neither the profile nor the request had an id+ igUserId?: string | null;biography?: string;website?: string;profilePictureUrl?: string;@@ -108,6 +118,17 @@ export interface ScheduledPost {error?: string | null;}+export interface ScheduledPublishFailure {+ id: string;+ error: string;+}++// processScheduledPosts() output; the process-scheduled routes add success and timestamp+export interface ScheduledPublishRun {+ processed: number;+ errors: ScheduledPublishFailure[];+}+// one row of `tracked_posts`; fields refreshed from the platform live in the data jsonbexport interface TrackedPost {id: string;@@ -121,3 +142,46 @@ export interface TrackedPost {updatedAt: string;[field: string]: unknown;}++// one entry of the refresh-all response, in the same order as the accounts+export interface AccountRefreshResult {+ id: string;+ success: boolean;+ error?: string;+}++// an account whose analytics cache is empty; syncing is true once a background fetch started+export interface PendingAccountSummary {+ id: string;+ cacheWarmed: false;+ syncing: boolean;+}++export interface RedditAccountSummary {+ id: string;+ cacheWarmed: true;+ fetchedPosts: number;+ totalScore: number;+ totalComments: number;+}++export interface InstagramAccountSummary {+ id: string;+ cacheWarmed: true;+ totalLikes: number;+ totalComments: number;+ totalViews: number;+ contentTypes: InstagramContentTypeSummary;+}++export interface YouTubeAccountSummary {+ id: string;+ cacheWarmed: true;+ totalLikes: number;+ totalComments: number;+}++export type AccountSummary = PendingAccountSummary | RedditAccountSummary | InstagramAccountSummary | YouTubeAccountSummary;++// the overview's analyticsCache, keyed by account id; accounts whose cache read failed are left out+export type OverviewAnalyticsCache = Record<string, AccountSummary>;diff --git a/shared/types/instagram.ts b/shared/types/instagram.tsindex 56b2e97..987d6e6 100644--- a/shared/types/instagram.ts+++ b/shared/types/instagram.ts@@ -1,3 +1,6 @@+import type { MediaType, UserTag } from './domain.ts';+import type { PostFrequency } from './reddit.ts';+export type InstagramContentType = 'reel' | 'post' | 'video';// a media item as normalizeInstagramMedia() stores it in the ig: cache@@ -19,3 +22,193 @@ export interface IGCacheData {media: InstagramMedia[];fetchedAt: string;}++// fetchInstagramProfile() output; igUserId falls back to the id that was asked for+export interface InstagramProfile {+ igUserId?: string | null;+ name: string;+ username: string;+ profilePictureUrl: string;+ followersCount: number;+ followsCount: number;+ mediaCount: number;+ biography: string;+ website: string;+}++// running totals per content type, from summarizeContentTypes()+export interface InstagramContentTypeTotals {+ count: number;+ likes: number;+ comments: number;+ views: number;+ viewsReported: number;+}++export type InstagramContentTypeSummary = Record<InstagramContentType, InstagramContentTypeTotals>;++export interface InstagramContentTypeStats {+ count: number;+ totalLikes: number;+ totalComments: number;+ totalViews: number;+ viewsReported: number;+ avgLikes: number;+ avgComments: number;+ avgEngagement: number;+ avgViews: number;+}++export type InstagramContentTypeStatsMap = Record<InstagramContentType, InstagramContentTypeStats>;++export interface InstagramDayStats {+ day: string;+ shortDay: string;+ posts: number;+ avgLikes: number;+ avgComments: number;+ avgEngagement: number;+}++export interface InstagramHourStats {+ hour: number;+ label: string;+ posts: number;+ avgEngagement: number;+}++export interface InstagramMonthStats {+ month: string;+ posts: number;+ likes: number;+ comments: number;+ avgLikes: number;+ avgComments: number;+ engagement: number;+}++// summarizeTiming() output; engagementTimeline and monthlyBreakdown are the same array+export interface InstagramTiming {+ postsByDayOfWeek: InstagramDayStats[];+ bestPostingDay: string;+ postsByHour: InstagramHourStats[];+ bestPostingHour: string;+ engagementTimeline: InstagramMonthStats[];+ monthlyBreakdown: InstagramMonthStats[];+}++export interface InstagramHashtagStats {+ tag: string;+ count: number;+ likes: number;+ comments: number;+ avgEngagement: number;+}++export interface InstagramCaptionLengthStats {+ label: string;+ count: number;+ avgLikes: number;+ avgComments: number;+ avgEngagement: number;+}++export interface InstagramTopPost extends InstagramMedia {+ engagement: number;+}++// computeInstagramAnalytics() output, returned by GET /api/accounts/:id/ig-analytics+export interface InstagramAnalytics extends InstagramTiming {+ totalPosts: number;+ fetchedPosts: number;+ totalLikes: number;+ totalComments: number;+ totalEngagement: number;+ avgLikes: number;+ avgComments: number;+ avgEngagement: number;+ medianLikes: number;+ medianComments: number;+ engagementRate: number;+ likesPerFollower: number;+ commentsPerFollower: number;+ likesToCommentsRatio: number;+ totalViews: number;+ avgViews: number;+ mediaWithViews: number;+ bestByLikes: InstagramMedia | null;+ bestByComments: InstagramMedia | null;+ worstByLikes: InstagramMedia | null;+ recentMedia: InstagramMedia[];+ contentTypeStats: InstagramContentTypeStatsMap;+ postFrequency: PostFrequency;+ topPosts: InstagramTopPost[];+ hashtagAnalysis: InstagramHashtagStats[];+ captionLengthCorrelation: InstagramCaptionLengthStats[];+ postsLast7Days: number;+ postsLast30Days: number;+ postsLast90Days: number;+ viralityScore: number;+ consistencyScore: number;+}++// carousel children are created with their own container before the carousel itself+export type InstagramPublishMediaType = MediaType | 'CAROUSEL_ITEM_IMAGE' | 'CAROUSEL_ITEM_VIDEO';++// body of POST /api/accounts/:id/ig-publish; a ScheduledPost is also accepted as is+export interface InstagramPublishRequest {+ mediaType?: InstagramPublishMediaType;+ mediaUrl?: string;+ caption?: string;+ coverUrl?: string | null;+ shareToFeed?: boolean;+ collaborators?: string[];+ audioName?: string;+ thumbOffset?: number | null;+ locationId?: string;+ userTags?: UserTag[];+ altText?: string;+ children?: string[];+}++export interface InstagramPublishResponse {+ success: true;+ containerId: string;+}++export type InstagramContainerStatusCode = 'EXPIRED' | 'ERROR' | 'FINISHED' | 'IN_PROGRESS' | 'PUBLISHED';++export interface InstagramContainerStatusResponse {+ success: true;+ statusCode: InstagramContainerStatusCode;+ status: string;+}++export interface InstagramMediaPublishRequest {+ containerId: string;+}++export interface InstagramMediaPublishResponse {+ success: true;+ mediaId: string;+}++// one entry of the Graph API content_publishing_limit edge, passed through unchanged+export interface InstagramPublishingLimit {+ quota_usage: number;+ config?: {+ quota_total: number;+ quota_duration: number;+ };+}++export interface InstagramPublishingLimitResponse {+ success: true;+ data: InstagramPublishingLimit[];+}++export interface CloudinaryConfigResponse {+ success: true;+ cloudName: string;+ uploadPreset: string;+}diff --git a/shared/types/reddit.ts b/shared/types/reddit.tsindex a8fa782..a8a04f6 100644--- a/shared/types/reddit.ts+++ b/shared/types/reddit.ts@@ -105,3 +105,19 @@ export interface RedditCacheData {analytics: RedditAnalytics;posts: RedditPost[];}++// fetchTrackedPostData() output, patched into a reddit tracked post's data on add and refresh+export interface RedditTrackedPostData {+ postId: string;+ title: string;+ subreddit: string;+ subredditPrefixed: string;+ author: string;+ score: number;+ upvoteRatio: number;+ numComments: number;+ permalink: string;+ isNsfw: boolean;+ createdAt: string;+ lastFetchedAt: string;+}diff --git a/shared/types/youtube.ts b/shared/types/youtube.tsindex 3e975a2..b6965f3 100644--- a/shared/types/youtube.ts+++ b/shared/types/youtube.ts@@ -1,3 +1,5 @@+import type { Account, ChannelThumbnails } from './domain.ts';+// a video as normalizeYouTubeVideo() stores it in the videos: cacheexport interface YouTubeVideo {videoId: string;@@ -29,3 +31,198 @@ export interface VideosCacheData {videos: YouTubeVideo[];fetchedAt: string;}++// a channel as fetchChannelData() returns it; new accounts copy most of these fields+export interface YouTubeChannelData {+ channelId: string;+ title: string;+ description: string;+ customUrl: string;+ publishedAt: string;+ country: string;+ thumbnails: ChannelThumbnails;+ subscriberCount: number;+ viewCount: number;+ videoCount: number;+ hiddenSubscriberCount: boolean;+ uploadsPlaylistId: string;+ keywords: string;+ bannerUrl: string;+ madeForKids: boolean;+ topicCategories: string[];+ isLinked: boolean;+}++// a tracked YouTube video as fetchTrackedYouTubeData() returns it+export interface YouTubeTrackedVideoData {+ contentType: 'youtube';+ title: string;+ channelTitle: string;+ channelId: string;+ thumbnail: string;+ publishedAt: string;+ viewCount: number;+ likeCount: number | null;+ commentCount: number | null;+ isShort: boolean;+ permalink: string;+ lastFetchedAt: string;+}++// rates and percentages come from toFixed(), so they are strings, or the number 0 when there is nothing to divide by+export type FormattedRate = string | number;++export interface YouTubeVideoSummary {+ videoId: string;+ title: string;+ viewCount: number;+ likeCount: number | null;+ commentCount: number | null;+ publishedAt: string;+ thumbnail: string;+ engagementRate: FormattedRate;+ durationSeconds: number;+}++export interface YouTubeDurationDistribution {+ short: number;+ medium: number;+ long: number;+ veryLong: number;+}++export interface YouTubeTagCount {+ tag: string;+ count: number;+}++export interface YouTubeViewsDistribution {+ ranges: string[];+ counts: number[];+}++export interface YouTubeMonthlyViews {+ month: string;+ value: number;+ count: number;+}++export interface YouTubeMonthlyRate {+ month: string;+ value: FormattedRate;+}++export interface YouTubeMonthlyTrends {+ viewsTrend: YouTubeMonthlyViews[];+ engagementTrend: YouTubeMonthlyRate[];+ likeRateTrend: YouTubeMonthlyRate[];+}++// computeVideoAnalytics() output; the optional fields are missing when the channel has no videos+export interface VideoAnalytics extends YouTubeMonthlyTrends {+ totalVideos: number;+ totalViews: number;+ totalLikes: number;+ totalComments: number;+ avgViews: number;+ avgLikes: number;+ avgComments: number;+ medianViews: number;+ totalEngagement: number;+ overallEngagementRate: FormattedRate;+ avgDurationSeconds: number;+ avgDurationFormatted: string;+ totalDurationSeconds: number;+ totalDurationFormatted: string;+ estimatedTotalWatchTimeHours?: number;+ bestByViews: YouTubeVideoSummary | null;+ bestByLikes: YouTubeVideoSummary | null;+ bestByComments: YouTubeVideoSummary | null;+ bestByEngagement: YouTubeVideoSummary | null;+ worstByViews: YouTubeVideoSummary | null;+ mostRecent: YouTubeVideoSummary | null;+ oldest: YouTubeVideoSummary | null;+ top10ByViews: YouTubeVideoSummary[];+ top10ByLikes: YouTubeVideoSummary[];+ top10ByComments: YouTubeVideoSummary[];+ top10ByEngagement: YouTubeVideoSummary[];+ shortsCount: number;+ regularCount: number;+ avgShortViews: number;+ avgRegularViews: number;+ avgShortLikes?: number;+ avgRegularLikes?: number;+ hdCount: number;+ sdCount: number;+ hdPercentage: FormattedRate;+ captionCount: number;+ captionPercentage: FormattedRate;+ licensedCount: number;+ licensedPercentage: FormattedRate;+ madeForKidsCount: number;+ embeddableCount: number;+ embeddablePercentage?: string;+ // keyed by day name and by UTC hour+ publishDayDistribution: Record<string, number>;+ publishHourDistribution: Record<string, number>;+ peakPublishDay: string;+ peakPublishHour: number;+ durationDistribution: YouTubeDurationDistribution;+ // keyed by YouTube category id, 'Unknown' when a video has none+ categoryDistribution: Record<string, number>;+ tagFrequency: YouTubeTagCount[];+ videosLast7Days: number;+ videosLast30Days: number;+ videosLast90Days: number;+ videosLast365Days: number;+ uploadFrequencyPerWeek: FormattedRate;+ uploadFrequencyPerMonth: FormattedRate;+ consistencyScore: number;+ viralityScore: number;+ viewsDistribution: YouTubeViewsDistribution;+}++// derived from the stored account by channelMetrics()+export interface YouTubeChannelMetrics {+ channelAge: number;+ channelAgeYears: string;+ viewsPerSubscriber: number;+ subscriberToViewRatio: number;+ avgViewsPerVideo: number;+ avgSubGainPerDay: number;+ avgViewsPerDay: number;+ estimatedMonthlyViews: number;+ estimatedMonthlySubGain: number;+ estimatedYearlyViews: number;+ estimatedYearlySubGain: number;+}++// GET /api/accounts/:id/analytics+export interface YouTubeAnalyticsPayload {+ success: true;+ channel: Account & YouTubeChannelMetrics;+ analytics: VideoAnalytics;+ videoCount: number;+}++export interface YouTubeAccountRankings<TAccount = Account> {+ bySubscribers: TAccount[];+ byViews: TAccount[];+ byVideos: TAccount[];+}++// accountComparison() output, sent by GET /api/comparison+export interface YouTubeAccountComparison<TAccount = Account> {+ rankings: YouTubeAccountRankings<TAccount>;+ totals: { subscribers: number; views: number; videos: number };+ accountCount: number;+ bestBySubscribers: TAccount | null;+ bestByViews: TAccount | null;+ bestByVideos: TAccount | null;+}++// a cached video tagged with its channel, as GET /api/videos/all lists it+export interface YouTubeLibraryVideo extends YouTubeVideo {+ channelId: string;+ channelThumbnail: string;+}