Files
iishko-public/tests/test_rankings_frontend.mjs
T
reformandClaude Opus 5.5 0ee6fb843b
checks / pytest (push) Has been cancelled
checks / moderation (push) Has been cancelled
checks / node (push) Has been cancelled
IISHKO: Telegram bot, Mini App and gateway
Initial public release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 21:51:30 +03:00

577 lines
32 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import vm from 'node:vm';
const html = readFileSync(new URL('../bot/webapp/static/index.html', import.meta.url), 'utf8');
const lines = html.split(/\r?\n/);
function declaration(prefix) {
const line = lines.find(value => value.startsWith(prefix));
assert.ok(line, `Missing application declaration: ${prefix}`);
return line;
}
function between(start, end) {
const first = html.indexOf(start);
const last = html.indexOf(end, first + start.length);
assert.ok(first >= 0 && last > first, `Missing source block: ${start}`);
return html.slice(first, last);
}
const dailySource = between('/* ---------- Ежедневный кубик:', '/* ---------- Квесты и монеты сообщества');
const rankingSource = between('/* ---------- Рейтинги:', '/* ---------- Нейролаб:');
const questSource = between('function questsView(', 'let questBusy=') + declaration('let questBusy=');
const helpers = [
'const esc=', 'const num=', 'const fmt=', 'const usd=', 'const refreshBtn=',
'const intro=', 'const ECON_PERIODS=', 'const ECON_PERIOD_DETAILS=',
'const usageCount=', 'const usageGrouped=',
].map(declaration).join('\n');
function element(dataset = {}) {
return {
dataset, innerHTML: '', attributes: {}, hidden: false,
setAttribute(name, value) { this.attributes[name] = value; },
querySelector() { return null; },
};
}
function deferred() {
let resolve, reject;
const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
return { promise, resolve, reject };
}
function envelope(kind, rows = [], period = kind === 'referrals' ? 'all' : 'day') {
return {
kind, period, top: rows,
source: kind === 'referrals' ? 'bot.users.ref_awarded' : kind === 'models' ? 'gateway.logs(type=2).model_name' : 'gateway.logs(type=2)',
from_ts: kind === 'referrals' ? null : 1700000000,
to_ts: 1700086400, as_of: 1700086400, generated_at: 1700086400,
timezone: 'Europe/Moscow',
};
}
function dailyStatus(overrides = {}) {
return {
ok: true, claimed: false, paid: false, pending: false,
face: null, value: null, units: null, usd: null,
eligible: true, wallet: true, rank: 1, multiplier: 1,
streak: 2, day: '2026-10-28', already: false, resumed: false,
legacy: false, error: null, ...overrides,
};
}
function harness(overrides = {}) {
const roots = {
'#top-results': element(), '#top-periods': element(), '#econ-daily': element(),
};
const kinds = ['referrals', 'requests', 'tokens', 'models'].map(topKind => element({ topKind }));
const periods = ['day', 'week', 'month'].map(topPeriod => element({ topPeriod }));
const reads = [], writes = [], haptics = [];
const context = vm.createContext({
current: 'top', version: 1, resolvedUid: 'test-account', cache: new Map(),
$: selector => roots[selector] || null,
icon: () => '<svg aria-hidden="true"></svg>',
haptic: value => haptics.push(value),
document: { querySelectorAll: selector => selector === '[data-top-kind]' ? kinds : selector === '[data-top-period]' ? periods : [] },
apiFresh: async path => {
reads.push(path);
if (path === 'bonus') return dailyStatus();
const url = new URL(path, 'https://miniapp.test/');
return envelope(url.searchParams.get('kind'), [], url.searchParams.get('period'));
},
post: async (path, body) => { writes.push({ path, body }); throw new Error('Unexpected mutation'); },
...overrides,
});
vm.runInContext(`${helpers}\n${dailySource}\n${rankingSource}\n${questSource}\n` + `
globalThis.frontend = {
topView, topResults, topMeta, topMetric, topPath, topSelect, topLoad,
dailyView, dailyReceive, dailyClaim, dailyRefresh, dailyStatusValid, questsView,
getDaily: () => dailyState,
setSelection: (kind, period) => { topKind = kind; topPeriod = period; },
getSelection: () => ({ kind: topKind, period: topPeriod }),
};
`, context);
return { context, frontend: context.frontend, roots, kinds, periods, reads, writes, haptics };
}
function claimButton(markup) {
return markup.match(/<button\b[^>]*data-daily-claim[^>]*>/)?.[0] || '';
}
test('all inline JavaScript parses without executing the application', () => {
const scripts = [...html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/g)];
assert.ok(scripts.length >= 2);
for (const [, attributes, source] of scripts) {
if (/\bsrc=/.test(attributes)) continue;
assert.doesNotThrow(() => new vm.Script(source));
}
});
test('four named ranking controls expose selected state and a results relationship', () => {
const { frontend } = harness();
const markup = frontend.topView(envelope('referrals'), { rich: [], casino: [] });
assert.equal((markup.match(/data-top-kind=/g) || []).length, 4);
for (const [kind, label] of [['referrals', 'Рефералы'], ['requests', 'Запросы'], ['tokens', 'Токены'], ['models', 'Модели']]) {
assert.match(markup, new RegExp(`data-top-kind="${kind}"[^>]*aria-controls="top-results"[^>]*aria-pressed="${kind === 'referrals'}"[^>]*>${label}<`));
}
assert.match(markup, /aria-label="Вид рейтинга"/);
assert.match(markup, /id="top-results"[^>]*aria-live="polite"/);
assert.match(markup, /id="top-periods"[^>]* hidden/);
assert.match(markup, /За всё время/);
});
test('usage periods are explicit, while referrals always request the lifetime board', () => {
const { frontend } = harness();
assert.equal(frontend.topPath('referrals', 'month'), 'top?kind=referrals&period=all');
assert.equal(frontend.topPath('requests', 'day'), 'top?kind=requests&period=day');
assert.equal(frontend.topPath('tokens', 'week'), 'top?kind=tokens&period=week');
assert.equal(frontend.topPath('models', 'month'), 'top?kind=models&period=month');
frontend.setSelection('requests', 'week');
const markup = frontend.topView(envelope('requests', [], 'week'), null);
assert.doesNotMatch(markup, /id="top-periods"[^>]* hidden/);
assert.match(markup, /data-top-period="day"[^>]*>Сегодня</);
assert.match(markup, /data-top-period="week"[^>]*aria-pressed="true"[^>]*>7 дней</);
assert.match(markup, /data-top-period="month"[^>]*>30 дней</);
assert.match(markup, /Последние 7 дней/);
});
test('each ranking renders its actual metric instead of referral fields or money', () => {
const { frontend } = harness();
const row = { pos: 1, user: '@member', refs: 2.5, count: 9, requests: 1234, value: 1234, known_tokens: 98765, tokens: 98765, unknown_token_requests: 0, tokens_complete: true };
assert.equal(frontend.topMetric(row, 'referrals').value, '2,5');
assert.equal(frontend.topMetric(row, 'referrals').detail, '9 приглашено');
assert.equal(frontend.topMetric(row, 'requests').value, '1 234');
assert.equal(frontend.topMetric(row, 'requests').unit, 'запросов');
assert.equal(frontend.topMetric(row, 'tokens').value, '98 765');
assert.equal(frontend.topMetric(row, 'tokens').unit, 'токенов');
const modelMarkup = frontend.topResults(envelope('models', [{ ...row, model: 'gpt-model', user: '@must-not-be-used' }]), 'models', 'day');
assert.match(modelMarkup, />gpt-model</);
assert.match(modelMarkup, /1 234<small>запросов</);
assert.doesNotMatch(modelMarkup, /@must-not-be-used|2,5<small>|\$|реф\. вес/);
const unnamed = frontend.topResults(envelope('models', [{ pos: 1, model: null, requests: 4 }]), 'models', 'day');
assert.match(unnamed, /Модель не указана/);
});
test('token rows distinguish lower bounds, entirely unknown counters and exact zero', () => {
const { frontend } = harness();
const lower = { pos: 1, user: '@lower', known_tokens: 4500, tokens: null, unknown_token_requests: 3, tokens_complete: false };
const metric = frontend.topMetric(lower, 'tokens');
assert.equal(metric.value, '≥ 4 500');
assert.match(metric.unit, /нижняя граница/);
assert.match(metric.detail, /3$/);
const unknown = frontend.topMetric({ known_tokens: 0, tokens: null, unknown_token_requests: 7, tokens_complete: false }, 'tokens');
assert.equal(unknown.value, 'Неизвестно');
assert.notEqual(unknown.value, '0');
assert.equal(frontend.topMetric({ known_tokens: 0, tokens: 0, unknown_token_requests: 0, tokens_complete: true }, 'tokens').value, '0');
const markup = frontend.topResults(envelope('tokens', [lower]), 'tokens', 'day');
assert.match(markup, /Входные \+ выходные токены/);
assert.match(markup, /Запросов без полного счётчика: 3/);
assert.match(markup, /без пересчёта по цене модели/);
});
test('missing or invalid metrics are never fabricated as zero', () => {
const { frontend } = harness();
assert.equal(frontend.topMetric({}, 'requests').value, '—');
assert.equal(frontend.topMetric({ requests: -1 }, 'models').value, '—');
assert.equal(frontend.topMetric({ tokens: '0', known_tokens: null }, 'tokens').value, 'Неизвестно');
assert.equal(frontend.topMetric({ refs: null, count: undefined }, 'referrals').value, '—');
});
test('source and Moscow boundaries are visible, and missing boundaries are acknowledged', () => {
const { frontend } = harness();
const markup = frontend.topMeta(envelope('requests'), 'requests', 'day');
assert.match(markup, /Сегодня с 00:00 МСК/);
assert.match(markup, /Источник: сохранённая история запросов шлюза/);
assert.match(markup, /срез .* МСК/);
assert.match(markup, / — .* МСК/);
assert.match(frontend.topMeta({ source: 'gateway.logs(type=2)' }, 'requests', 'month'), /точные границы не переданы/);
assert.match(frontend.topMeta(envelope('referrals'), 'referrals', 'day'), /зачтённые приглашения в боте/);
});
test('valid empty, malformed and unavailable ranking states are distinct and retryable', () => {
const { frontend } = harness();
assert.match(frontend.topResults(envelope('requests'), 'requests', 'day'), /За этот период пока нет участников/);
for (const invalid of [{}, { top: null }, { top: [null] }, envelope('tokens', [], 'week')]) {
const markup = frontend.topResults(invalid, 'requests', 'day');
assert.match(markup, /Рейтинг временно недоступен/);
assert.match(markup, /data-top-retry/);
assert.doesNotMatch(markup, /За этот период пока нет участников/);
}
const failed = frontend.topResults(null, 'tokens', 'day', { status: 503 });
assert.match(failed, /HTTP 503/);
assert.match(failed, /не означает нулевую активность/);
assert.doesNotMatch(failed, /пока нет участников/);
});
test('legacy balance and weekly boards remain, with honest source failure instead of disappearance', () => {
const { frontend } = harness();
const boards = { rich: [{ pos: 1, user: '@rich', usd: 12 }], casino: [{ pos: 1, user: '@oldboard', n: 2 }] };
const markup = frontend.topView(envelope('referrals'), boards);
assert.match(markup, /Топ балансов/);
assert.match(markup, /@rich/);
assert.match(markup, /Рискующие недели/);
assert.match(markup, /@oldboard/);
const failed = frontend.topView(envelope('referrals'), null, null, { status: 503 });
assert.match(failed, /Другие рейтинги временно недоступны/);
assert.doesNotMatch(failed, /Пока пусто/);
});
test('ranking names, model IDs, sources and legacy board names are HTML-escaped', () => {
const { frontend } = harness();
const attack = '<img src=x onerror="alert(1)">';
const payload = envelope('requests', [{ pos: 1, user: attack, requests: 1 }]);
payload.source = '<script>alert(1)</script>';
const markup = frontend.topResults(payload, 'requests', 'day');
assert.doesNotMatch(markup, /<img|<script>/);
assert.match(markup, /&lt;img src=x onerror=&quot;alert\(1\)&quot;&gt;/);
assert.match(markup, /&lt;script&gt;/);
const model = frontend.topResults(envelope('models', [{ pos: 1, model: attack, requests: 1 }]), 'models', 'day');
assert.doesNotMatch(model, /<img/);
const board = frontend.topView(envelope('referrals'), { rich: [{ pos: 1, user: attack, usd: 1 }] });
assert.doesNotMatch(board, /<img/);
});
test('switching updates accessible controls, rejects invalid selections and preserves the chosen period', async () => {
const { frontend, roots, kinds, periods, reads } = harness();
assert.equal(frontend.topSelect('requests', 'month'), true);
assert.equal(roots['#top-periods'].hidden, false);
assert.equal(kinds.find(button => button.dataset.topKind === 'requests').attributes['aria-pressed'], 'true');
assert.equal(periods.find(button => button.dataset.topPeriod === 'month').attributes['aria-pressed'], 'true');
assert.equal(frontend.topSelect('requests', 'month'), false);
assert.equal(frontend.topSelect('unknown', 'month'), false);
assert.equal(frontend.topSelect('tokens', 'year'), false);
await Promise.resolve();
assert.deepEqual(reads, ['top?kind=requests&period=month']);
assert.equal(frontend.topSelect('referrals', 'month'), true);
assert.equal(roots['#top-periods'].hidden, true);
await Promise.resolve();
assert.equal(reads.at(-1), 'top?kind=referrals&period=all');
assert.equal(frontend.getSelection().period, 'month');
});
test('an older request cannot clear a newer loading state or populate another ranking', async () => {
const first = deferred(), second = deferred(), calls = [];
const { frontend, roots } = harness({ apiFresh: path => { calls.push(path); return calls.length === 1 ? first.promise : second.promise; } });
frontend.setSelection('requests', 'day');
const oldLoad = frontend.topLoad();
frontend.setSelection('tokens', 'week');
const newLoad = frontend.topLoad();
first.resolve(envelope('requests', [{ pos: 1, user: '@old', requests: 100 }]));
await oldLoad;
assert.equal(roots['#top-results'].attributes['aria-busy'], 'true');
assert.match(roots['#top-results'].innerHTML, /Загружаю рейтинг/);
second.resolve(envelope('tokens', [{ pos: 1, user: '@new', known_tokens: 8, tokens: 8, unknown_token_requests: 0, tokens_complete: true }], 'week'));
await newLoad;
assert.equal(roots['#top-results'].attributes['aria-busy'], 'false');
assert.match(roots['#top-results'].innerHTML, /@new/);
assert.doesNotMatch(roots['#top-results'].innerHTML, /@old/);
assert.deepEqual(calls, ['top?kind=requests&period=day', 'top?kind=tokens&period=week']);
});
test('late ranking failures cannot overwrite a newer result', async () => {
const first = deferred(), second = deferred();
let count = 0;
const { frontend, roots } = harness({ apiFresh: () => ++count === 1 ? first.promise : second.promise });
frontend.setSelection('requests', 'day');
const a = frontend.topLoad();
frontend.setSelection('models', 'month');
const b = frontend.topLoad();
second.resolve(envelope('models', [{ pos: 1, model: 'latest-model', requests: 12 }], 'month'));
await b;
first.reject({ status: 503 });
await a;
assert.match(roots['#top-results'].innerHTML, /latest-model/);
assert.doesNotMatch(roots['#top-results'].innerHTML, /временно недоступен/);
});
test('ranking failures are shown and a fresh retry can recover without showing zeros', async () => {
let count = 0;
const { frontend, roots } = harness({ apiFresh: async () => {
if (++count === 1) throw { status: 503 };
return envelope('requests', [{ pos: 1, user: '@recovered', requests: 17 }]);
} });
frontend.setSelection('requests', 'day');
await frontend.topLoad();
assert.match(roots['#top-results'].innerHTML, /HTTP 503/);
assert.match(roots['#top-results'].innerHTML, /data-top-retry/);
assert.equal(roots['#top-results'].attributes['aria-busy'], 'false');
await frontend.topLoad();
assert.match(roots['#top-results'].innerHTML, /@recovered/);
assert.doesNotMatch(roots['#top-results'].innerHTML, /временно недоступен/);
assert.equal(count, 2);
});
test('in-flight ranking data does not cross an account or screen-version boundary', async () => {
for (const changed of ['account', 'version']) {
const request = deferred();
const { frontend, roots, context } = harness({ apiFresh: () => request.promise });
frontend.setSelection('requests', 'day');
const load = frontend.topLoad();
if (changed === 'account') context.resolvedUid = 'other-account';
else context.version++;
roots['#top-results'].innerHTML = 'new screen';
request.resolve(envelope('requests', [{ pos: 1, user: '@old-account', requests: 100 }]));
await load;
assert.equal(roots['#top-results'].innerHTML, 'new screen');
}
});
test('daily ready, busy and paid states have explicit actionable controls', () => {
const { frontend } = harness();
const ready = frontend.dailyView({ data: dailyStatus() });
assert.match(ready, /Ежедневный кубик и чек-ин/);
assert.match(ready, /Бросить кубик и отметить день/);
assert.doesNotMatch(claimButton(ready), /disabled/);
assert.match(ready, /00:00 МСК/);
assert.match(ready, /не деньги к выводу/);
assert.doesNotMatch(ready, /Результат кубика: [1-6]/);
const busy = frontend.dailyView({ data: dailyStatus(), busy: true });
assert.match(busy, /aria-busy="true"/);
assert.match(claimButton(busy), /disabled aria-disabled="true"/);
assert.match(busy, /data-daily-refresh[^>]*disabled/);
const paid = frontend.dailyView({ data: dailyStatus({ claimed: true, paid: true, face: 6, value: 6, units: 20000000, usd: 40, already: true }) });
assert.match(paid, /Результат кубика: 6 из 6/);
assert.equal((paid.match(/daily-pip on/g) || []).length, 6);
assert.match(paid, /40 \$ API-кредита/);
assert.match(paid, /Сегодня уже отмечено/);
assert.match(paid, /Начисление подтверждено/);
assert.match(claimButton(paid), /disabled/);
});
test('daily face is not inferred from units or value, and legacy rewards never become fictional zero', () => {
const { frontend } = harness();
const legacy = frontend.dailyView({ data: dailyStatus({ claimed: true, paid: true, already: true, legacy: true, face: null, value: 6, units: null, usd: null }) });
assert.doesNotMatch(legacy, /Результат кубика: 6|0 \$ API-кредита/);
assert.match(legacy, /Размер награды не передан сервером/);
assert.match(claimButton(legacy), /disabled/);
});
test('legacy check-in marker is not a paid reward or a recoverable roll', async () => {
const { frontend, context, writes } = harness();
context.current = 'econ';
const data = dailyStatus({ legacy: true, claimed: true, paid: false, pending: false, already: true, face: null, units: null, usd: null });
const state = frontend.dailyReceive(data);
for (const uncertain of [false, true]) {
state.uncertain = uncertain;
const markup = frontend.dailyView(state);
assert.match(markup, /Сегодняшний чек-ин уже отмечен в прежней версии\. Новый кубик — завтра\./);
assert.match(claimButton(markup), /disabled aria-disabled="true"/);
assert.doesNotMatch(markup, /Начисление подтверждено|Награда за сегодня:|Награда по сохранённому результату:|Проверить начисление|Результат кубика: [1-6]/);
await frontend.dailyClaim();
}
assert.equal(writes.length, 0);
assert.equal(frontend.getDaily().data.paid, false);
});
test('legacy result discovered by POST is closed without claiming payout or permitting another roll', async () => {
let calls = 0;
const { frontend, context, roots } = harness({ post: async () => {
calls++;
return dailyStatus({ legacy: true, claimed: true, paid: false, pending: false, already: true });
} });
context.current = 'econ';
frontend.dailyReceive(dailyStatus());
await frontend.dailyClaim();
assert.equal(frontend.getDaily().data.paid, false);
assert.equal(frontend.getDaily().uncertain, false);
assert.match(roots['#econ-daily'].innerHTML, /Новый кубик — завтра/);
assert.doesNotMatch(roots['#econ-daily'].innerHTML, /Начисление подтверждено|Начисление не подтверждено/);
await frontend.dailyClaim();
assert.equal(calls, 1);
});
test('pending daily recovery keeps the real face and reward but does not claim credit was paid', () => {
const { frontend } = harness();
const markup = frontend.dailyView({ data: dailyStatus({ claimed: true, paid: false, pending: true, face: 5, value: 5, usd: 30 }) });
assert.match(markup, /Результат кубика: 5 из 6/);
assert.match(markup, /30 \$ API-кредита/);
assert.match(markup, /Начисление не подтверждено/);
assert.match(markup, /Проверить начисление/);
assert.doesNotMatch(claimButton(markup), /disabled/);
assert.doesNotMatch(markup, /Начисление подтверждено|Награда за сегодня:/);
});
test('failed status payload can still expose an idempotent pending recovery', () => {
const { frontend, context } = harness();
context.current = 'econ';
const data = dailyStatus({ ok: false, claimed: true, pending: true, paid: false, face: 2, usd: 16, error: 'daily_failed' });
const state = frontend.dailyReceive(undefined, { status: 503, data });
const markup = frontend.dailyView(state);
assert.equal(state.uncertain, true);
assert.match(markup, /Результат кубика: 2 из 6/);
assert.match(markup, /HTTP 503/);
assert.doesNotMatch(claimButton(markup), /disabled/);
assert.doesNotMatch(markup, /Начисление подтверждено/);
});
test('daily double-click sends one POST {}, and paid or already responses prevent another request', async () => {
const request = deferred(), writes = [];
const { frontend, context, roots } = harness({ post: (path, body) => { writes.push({ path, body }); return request.promise; } });
context.current = 'econ';
frontend.dailyReceive(dailyStatus());
const first = frontend.dailyClaim();
await frontend.dailyClaim();
assert.equal(writes.length, 1);
assert.equal(writes[0].path, 'daily');
assert.equal(JSON.stringify(writes[0].body), '{}');
assert.equal(frontend.getDaily().busy, true);
assert.match(claimButton(roots['#econ-daily'].innerHTML), /disabled/);
request.resolve(dailyStatus({ claimed: true, paid: true, face: 3, value: 3, units: 10000000, usd: 20, credited_units: 0, already: true }));
await first;
assert.equal(frontend.getDaily().busy, false);
assert.equal(frontend.getDaily().data.paid, true);
assert.match(roots['#econ-daily'].innerHTML, /20 \$ API-кредита/);
await frontend.dailyClaim();
assert.equal(writes.length, 1);
});
test('503 daily response preserves pending face; retry uses the same endpoint and never rerolls locally', async () => {
const writes = [];
const pending = dailyStatus({ ok: false, claimed: true, paid: false, pending: true, face: 4, usd: 24, units: 12000000, error: 'daily_failed' });
const { frontend, context, roots } = harness({ post: async (path, body) => {
writes.push({ path, body });
if (writes.length === 1) throw { status: 503, requestSent: true, data: pending };
return { ...pending, ok: true, paid: true, pending: false, already: true, resumed: true, credited_units: 0, error: null };
} });
context.current = 'econ';
frontend.dailyReceive(dailyStatus());
await frontend.dailyClaim();
assert.equal(frontend.getDaily().uncertain, true);
assert.match(roots['#econ-daily'].innerHTML, /Результат кубика: 4 из 6/);
assert.match(roots['#econ-daily'].innerHTML, /24 \$ API-кредита/);
assert.doesNotMatch(roots['#econ-daily'].innerHTML, /Начисление подтверждено/);
await frontend.dailyClaim();
assert.equal(writes.length, 2);
assert.equal(writes[1].path, 'daily');
assert.equal(JSON.stringify(writes[1].body), '{}');
assert.equal(frontend.getDaily().data.face, 4);
assert.equal(frontend.getDaily().data.usd, 24);
assert.equal(frontend.getDaily().data.paid, true);
assert.doesNotMatch(dailySource, /Math\.random|post\(['"](?:spin|task)/);
});
test('network failure or incomplete success never becomes a paid daily claim and remains retryable', async () => {
for (const result of ['network', 'incomplete']) {
const { frontend, context, roots } = harness({ post: async () => {
if (result === 'network') throw new Error('connection lost');
return { ok: true, face: 6, usd: 40 };
} });
context.current = 'econ';
frontend.dailyReceive(dailyStatus());
await frontend.dailyClaim();
assert.equal(frontend.getDaily().data.paid, false);
assert.equal(frontend.getDaily().uncertain, true);
assert.doesNotMatch(roots['#econ-daily'].innerHTML, /Начисление подтверждено/);
assert.doesNotMatch(claimButton(roots['#econ-daily'].innerHTML), /disabled/);
assert.match(roots['#econ-daily'].innerHTML, /Проверить начисление/);
}
});
test('wallet rejection explains API-key recovery; a fresh status makes the action usable again', async () => {
const { frontend, context, roots, reads } = harness({ post: async () => {
throw { status: 409, data: dailyStatus({ ok: false, wallet: false, error: 'daily_wallet' }) };
} });
context.current = 'econ';
frontend.dailyReceive(dailyStatus());
await frontend.dailyClaim();
assert.equal(frontend.getDaily().uncertain, false);
assert.match(roots['#econ-daily'].innerHTML, /Основной API-ключ недоступен/);
assert.match(roots['#econ-daily'].innerHTML, /data-tab="keys"/);
assert.match(claimButton(roots['#econ-daily'].innerHTML), /disabled/);
await frontend.dailyRefresh();
assert.equal(reads.at(-1), 'bonus');
assert.doesNotMatch(claimButton(roots['#econ-daily'].innerHTML), /disabled/);
});
test('late daily response cannot cross an account boundary', async () => {
const request = deferred();
const { frontend, context } = harness({ post: () => request.promise });
context.current = 'econ';
frontend.dailyReceive(dailyStatus());
const claim = frontend.dailyClaim();
context.resolvedUid = 'another-account';
frontend.dailyReceive(dailyStatus({ streak: 0 }));
request.resolve(dailyStatus({ claimed: true, paid: true, face: 6, usd: 40 }));
await claim;
assert.equal(frontend.getDaily().uid, 'another-account');
assert.equal(frontend.getDaily().data.paid, false);
assert.equal(frontend.getDaily().data.face, null);
});
test('daily error and untrusted scalar fields cannot insert HTML', () => {
const { frontend } = harness();
const attack = '<img src=x onerror="alert(1)">';
const markup = frontend.dailyView({ data: dailyStatus({ face: attack, usd: attack, streak: attack, day: attack }), error: { status: attack } });
assert.doesNotMatch(markup, /<img/);
assert.match(markup, /&lt;img/);
assert.doesNotMatch(markup, /Результат кубика: <|Награда за сегодня:/);
});
test('quest check-in remains callable and pending recovery is not disabled', () => {
const { frontend } = harness();
const base = { rank_name: 'Новичок', budget_left_usd: 2, budget_usd: 3, quests: [{ id: 'checkin', title: 'Дневной чек-ин', target: 1, progress: 0, reward_usd: 1, claimable: true, done: false }] };
const markup = frontend.questsView(base, false);
assert.match(markup, /data-quest="checkin"[^>]*>Чек-ин и получить/);
assert.match(markup, /API-кредита/);
assert.match(markup, /Чек-ин доступен здесь/);
const pending = frontend.questsView({ ...base, quests: [{ ...base.quests[0], claimable: false, pending: true }] }, false);
assert.match(pending, /data-quest="checkin"[^>]*>Проверить начисление/);
assert.doesNotMatch(pending.match(/<button\b[^>]*data-quest="checkin"[^>]*>/)?.[0] || '', /disabled/);
});
test('rankings and daily are wired to route rendering and delegated click actions', () => {
assert.match(html, /settled\(topPath\(\)\)/);
assert.match(html, /settled\('bonus'\)/);
assert.match(html, /id="econ-daily"/);
assert.match(html, /\[data-top-kind\][\s\S]*topSelect\(topKindButton\.dataset\.topKind\)/);
assert.match(html, /\[data-top-retry\][\s\S]*topLoad\(\)/);
assert.match(html, /\[data-daily-claim\][\s\S]*dailyClaim\(\)/);
assert.match(html, /\[data-daily-refresh\][\s\S]*dailyRefresh\(\)/);
});
test('new compact controls compose existing tokens, minimum tap targets and focus styles', () => {
const styles = html.match(/<style>([\s\S]*?)<\/style>/)?.[1] || '';
assert.match(styles, /\.top-kinds\{display:grid;grid-template-columns:repeat\(2,minmax\(0,1fr\)\);gap:var\(--space-2\)/);
assert.match(styles, /\.econ-periods\[hidden\]\{display:none\}/);
assert.match(styles, /\.chipbtn\{min-height:var\(--tap\)/);
assert.match(styles, /:focus-visible\{outline:var\(--stroke-strong\) solid var\(--accent\)/);
for (const rule of styles.matchAll(/\.(?:top-kinds|top-meta|top-results|daily-card|daily-outcome|daily-face|daily-pip)[^{]*\{([^}]*)\}/g)) {
assert.doesNotMatch(rule[1], /#[0-9a-fA-F]{3,8}\b|\b\d+px\b/);
}
});
test('confirmed receipt survives failed status reads and incomplete refresh responses', async () => {
for (const mode of ['receive', 'refresh']) {
const { frontend, context } = harness({ apiFresh: async () => { throw { status: 503 }; } });
context.current = 'econ';
frontend.dailyReceive(dailyStatus({ claimed: true, paid: true, face: 6, usd: 40 }));
if (mode === 'receive') frontend.dailyReceive(undefined, { status: 503 });
else await frontend.dailyRefresh();
const state = frontend.getDaily();
assert.equal(state.data.paid, true);
assert.equal(state.data.face, 6);
assert.equal(state.uncertain, false);
const markup = frontend.dailyView(state);
assert.match(markup, /Начисление подтверждено/);
assert.match(claimButton(markup), /disabled/);
assert.doesNotMatch(markup, /Начисление не подтверждено|начисление не подтверждено/);
}
});
test('authoritative paid receipt in an error body closes claim without a recovery loop', async () => {
const receipt = dailyStatus({ claimed: true, paid: true, already: true, face: 4, usd: 24 });
for (const mode of ['receive', 'refresh', 'claim']) {
let calls = 0;
const failure = { status: 409, data: receipt };
const { frontend, context } = harness({
apiFresh: async () => { throw failure; },
post: async () => { calls++; throw failure; },
});
context.current = 'econ';
frontend.dailyReceive(dailyStatus());
if (mode === 'receive') frontend.dailyReceive(undefined, failure);
else if (mode === 'refresh') await frontend.dailyRefresh();
else await frontend.dailyClaim();
const state = frontend.getDaily();
assert.equal(state.data.paid, true);
assert.equal(state.uncertain, false);
assert.match(claimButton(frontend.dailyView(state)), /disabled/);
await frontend.dailyClaim();
assert.equal(calls, mode === 'claim' ? 1 : 0);
}
});