Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

9.6 KB
Raw Blame
// keeps node's experimental mock timer warning out of the captured console output
process.removeAllListeners('warning');

import { test, describe, before, after, beforeEach, afterEach, mock } from 'node:test';
import assert from 'node:assert/strict';
import accountsRouter from '../../routes/accountRoutes.ts';
import { assertGolden } from '../fixtures/golden.ts';
import { installFetch, reply } from '../fixtures/fakeFetch.ts';
import type { FetchMock, RecordedRequest } from '../fixtures/fakeFetch.ts';
import { fakeSupabase, accountRow } from '../fixtures/fakeSupabase.ts';
import type { SupabaseCall } from '../fixtures/fakeSupabase.ts';
import { mountWithContext, callRoute, fakeRedis } from '../fixtures/routeHarness.ts';
import { mockRowIds } from '../fixtures/rowIds.ts';
import type { RouteStep } from '../fixtures/routeHarness.ts';

// a byte order mark that pasted secrets sometimes start with
const BOM = String.fromCharCode(0xfeff);
const FIXED_NOW = Date.parse('2026-09-01T12:00:00Z');
const CHANNEL_A = 'UCaaaaaaaaaaaaaaaaaaaaaa';
const CHANNEL_NEW = 'UCnnnnnnnnnnnnnnnnnnnnnn';
const ENV = { YOUTUBE_API_KEY: `${BOM} YTKEY \n`, INSTAGRAM_APP_SECRET: 'IGSECRET' };

const storedAccounts = [
    accountRow({ id: 'yt1', platform: 'youtube', channelId: CHANNEL_A, title: 'Old title', subscriberCount: 1 }),
    accountRow({ id: 'ig1', platform: 'instagram', igUserId: '1789', username: 'ribbon', accessToken: 'IGTOKEN', tokenExpiresAt: '2026-09-05T00:00:00.000Z', followersCount: 1 }),
    accountRow({ id: 'ig2', platform: 'instagram', igUserId: '2000', username: 'notoken' }),
    // a platform Twiligent no longer supports; the app never reads its rows
    accountRow({ id: 'old1', platform: 'retired', username: 'old_profile' }),
    accountRow({ id: 'yt2', platform: 'youtube', channelId: 'UCmissingmissingmissing0' }),
    accountRow({ id: 'other', platform: 'youtube', channelId: CHANNEL_NEW }, 'user-2'),
];

function channelBody(channelId: string) {
    if (channelId.startsWith('UCmissing')) return { items: [] };
    return {
        items: [{
            id: channelId,
            snippet: { title: `Channel ${channelId.slice(0, 4)}`, description: 'Desc', customUrl: '@chan', publishedAt: '2020-01-01T00:00:00Z', country: 'GB', thumbnails: { default: { url: 'd' }, medium: { url: 'm' }, high: { url: 'h' } } },
            statistics: { subscriberCount: '500', viewCount: '9000', videoCount: '12' },
            contentDetails: { relatedPlaylists: { uploads: `UU${channelId.slice(2)}` } },
            brandingSettings: { channel: { keywords: 'k' } },
            status: { madeForKids: false },
            topicDetails: { topicCategories: ['t'] },
        }],
    };
}

const instagramProfiles = {
    IGTOKEN: { user_id: '1789', username: 'ribbon', name: 'Ribbon', followers_count: 2500, follows_count: 10, media_count: 140, biography: 'Bio', website: 'https://r.example', profile_picture_url: 'https://p' },
    LONGTOKEN: { user_id: '3000', username: 'fresh', name: '', followers_count: 5, media_count: 1 },
    SHORTONLY: { user_id: '3001', username: 'shorty', name: 'Shorty' },
    NOID: { username: 'ghost' },
};

function instagramReply(url: URL) {
    const params = url.searchParams;
    const token = params.get('access_token');
    if (url.pathname === '/access_token') {
        if (token === 'SHORT') return reply({ access_token: 'LONGTOKEN', expires_in: 5000 });
        return reply({ error: { message: 'Invalid platform app' } });
    }
    if (url.pathname === '/refresh_access_token') {
        if (token === 'IGTOKEN') return reply({ access_token: 'IGTOKEN2', expires_in: 86400 });
        return reply({ error: { message: 'Token cannot be refreshed' } });
    }
    const profile = instagramProfiles[token as keyof typeof instagramProfiles];
    return profile ? reply(profile) : reply({ error: { message: 'Invalid OAuth access token' } });
}

function platformServer(request: RecordedRequest) {
    const url = new URL(request.url);
    if (url.hostname === 'graph.instagram.com') return instagramReply(url);
    const params = url.searchParams;
    if (params.get('forHandle')) return reply({ items: [{ id: params.get('forHandle') === 'existing' ? CHANNEL_A : CHANNEL_NEW }] });
    if (params.get('forUsername') || params.get('q')) return reply({ items: [] });
    return reply(channelBody(params.get('id')!));
}

let fetchMock: FetchMock | null = null;
let logLines: unknown[][] = [];

before(() => mock.timers.enable({ apis: ['Date'], now: FIXED_NOW }));
after(() => mock.timers.reset());
beforeEach(() => {
    mock.method(Math, 'random', () => 0.123456789);
    mockRowIds();
    logLines = [];
    mock.method(console, 'log', (...args: unknown[]) => logLines.push(['log', ...args]));
    mock.method(console, 'error', (...args: unknown[]) => logLines.push(['error', ...args]));
    fetchMock = installFetch(platformServer);
});
afterEach(() => {
    fetchMock!.restore();
    mock.restoreAll();
});

async function runScenario(steps: RouteStep[], options: { supabase?: { calls: SupabaseCall[] } } = {}) {
    const supabase = options.supabase ?? fakeSupabase(storedAccounts);
    const redis = fakeRedis();
    const app = mountWithContext(app => app.route('/', accountsRouter), { supabase, redis, userId: 'user-1' });
    const responses = [];
    for (const [method, path, json, env] of steps) {
        responses.push(await callRoute(app, method, path, { json, env: env ?? ENV }));
    }
    return { responses, requests: fetchMock!.requests, calls: supabase.calls, redis: redis.deleted, logs: logLines };
}

const brokenSupabase = { calls: [], from() { throw new Error('database unavailable'); } };

describe('accounts routes golden output', () => {
    test('lists accounts and resolves channels', async () => {
        assertGolden(await runScenario([
            ['GET', '/accounts'],
            ['POST', '/resolve-channel', { input: 'https://youtube.com/@creator' }],
            ['POST', '/resolve-channel', { input: 'UCmissingmissingmissing0' }],
            ['POST', '/resolve-channel', { input: 'x' }, {}],
            ['POST', '/resolve-channel', '{not json'],
        ]), 'accountsRoutes.listResolve');
    });

    test('adds YouTube channels and rejects duplicates', async () => {
        assertGolden(await runScenario([
            ['POST', '/accounts', { input: 'https://youtube.com/@creator' }],
            ['POST', '/accounts', { input: '@existing' }],
            ['POST', '/accounts', { input: 'https://youtube.com/@existing' }],
            ['POST', '/accounts', { input: '' }],
            ['POST', '/accounts', { input: 'x' }, { YOUTUBE_API_KEY: `${BOM}   ` }],
        ]), 'accountsRoutes.addYouTube');
    });

    test('refreshes every account and reports each result', async () => {
        assertGolden(await runScenario([
            ['POST', '/accounts/refresh-all'],
            ['POST', '/accounts/refresh-all', undefined, {}],
            ['POST', '/accounts/refresh-all', undefined, { YOUTUBE_API_KEY: 'PLAINKEY' }],
        ]), 'accountsRoutes.refreshAll');
    });

    test('refreshes one account', async () => {
        assertGolden(await runScenario([
            ['POST', '/accounts/nope/refresh'],
            ['POST', '/accounts/ig1/refresh'],
            ['POST', '/accounts/ig2/refresh'],
            ['POST', '/accounts/old1/refresh'],
            ['POST', '/accounts/yt1/refresh'],
            ['POST', '/accounts/yt1/refresh', undefined, {}],
            ['POST', '/accounts/yt2/refresh'],
            ['POST', '/accounts/other/refresh'],
        ]), 'accountsRoutes.refreshOne');
    });

    test('deletes accounts and clears their caches', async () => {
        assertGolden(await runScenario([
            ['DELETE', '/accounts/nope'],
            ['DELETE', '/accounts/other'],
            ['DELETE', '/accounts/old1'],
            ['DELETE', '/accounts/yt2'],
            ['GET', '/accounts'],
        ]), 'accountsRoutes.delete');
    });

    test('database failures surface as errors', async () => {
        assertGolden(await runScenario([
            ['GET', '/accounts'],
            ['POST', '/accounts', { input: '@creator' }],
            ['POST', '/accounts/refresh-all'],
            ['POST', '/accounts/ig1/refresh'],
            ['DELETE', '/accounts/ig1'],
        ], { supabase: brokenSupabase }), 'accountsRoutes.dbFailure');
    });

    test('refreshing an account without a channel id or token fails before calling the platform', async () => {
        const supabase = fakeSupabase([
            accountRow({ id: 'ytOld', platform: 'youtube', title: 'No id' }),
            accountRow({ id: 'igOld', platform: 'instagram', igUserId: '1' }),
        ]);
        const app = mountWithContext(app => app.route('/', accountsRouter), { supabase, redis: fakeRedis(), userId: 'user-1' });
        const single = async (id: string) => JSON.parse((await callRoute(app, 'POST', `/accounts/${id}/refresh`, { env: ENV })).body) as unknown;
        const failure = (message: string) => ({ success: false, code: 'VALIDATION_ERROR', message, requestId: 'req-test' });
        assert.deepEqual(await single('ytOld'), failure('No YouTube channel ID stored - delete this channel and add it again'));
        assert.deepEqual(await single('igOld'), failure('No access token stored - reconnect this Instagram account'));

        const all = JSON.parse((await callRoute(app, 'POST', '/accounts/refresh-all', { env: ENV })).body) as { results: unknown[] };
        assert.deepEqual(all.results, [
            { id: 'ytOld', success: false, error: 'No YouTube channel ID stored - delete this channel and add it again' },
            { id: 'igOld', success: false, error: 'No access token stored - reconnect this Instagram account' },
        ]);
        assert.deepEqual(fetchMock!.requests, []);
    });
});