From 85546853ee74d6c83691203f31c8853a195b3102 Mon Sep 17 00:00:00 2001 From: TBM Quality Pass Date: Sat, 21 Nov 2026 11:51:46 +0300 Subject: [PATCH 1/5] Strengthen Bot API drift detection - compare parameters of every method the tool calls, not only setWebhook - check WebhookInfo, BotCommand and MenuButton fields - flag used methods that have no parameter expectations - warn when the spec release date is stale - cover the new checks with synthetic-spec tests and update docs --- CLAUDE.md | 4 +- README.md | 4 +- scripts/check-bot-api.mjs | 100 +++++++++++++++++++++++++++++++---- tests/check-bot-api.test.mjs | 62 +++++++++++++++++----- 4 files changed, 142 insertions(+), 28 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 0995338..2605912 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -10,8 +10,8 @@ Static site (GitHub Pages) that calls the Telegram Bot API from the browser. No ## Updating to a new Bot API version -1. `node scripts/check-bot-api.mjs` — lists new update types, admin rights, getMe flags, command scopes, setWebhook params and bot-settings methods (spec: PaulSonOfLars/telegram-bot-api-spec; core.telegram.org may be unreachable). -2. Update `src/assets/js/data.js`: `UPDATE_GROUPS` (mark `optIn` if the spec says it must be requested explicitly), `ADMIN_RIGHTS` (with `target`), `ME_FLAGS`, `COMMAND_SCOPES`, `BOT_API_VERSION`. +1. `node scripts/check-bot-api.mjs` — lists new update types, admin rights, getMe flags, command scopes, BotCommand/MenuButton/WebhookInfo fields, parameters of every method the tool calls, and bot-settings methods (spec: PaulSonOfLars/telegram-bot-api-spec; core.telegram.org may be unreachable). It also warns when the spec release date is stale, so an outdated spec source is not mistaken for “no changes”. +2. Update `src/assets/js/data.js`: `UPDATE_GROUPS` (mark `optIn` if the spec says it must be requested explicitly), `ADMIN_RIGHTS` (with `target`), `ME_FLAGS`, `COMMAND_SCOPES`, `BOT_API_VERSION`. If a new parameter appears on a method the tool already calls, add it to `METHOD_PARAMS` in `scripts/check-bot-api.mjs` and expose it in the UI when it matters. 3. Add labels for every new key to all five locale files (`app.updates.*`, `app.rights.*`, `app.me.*`, `app.scopes.*`). `npm test` lists anything missing. 4. A new bot-settings method that needs its own UI (a new tab or form) is a design change: describe it in the PR instead of building it silently. 5. Update `CHANGELOG.md` and the version badge in `README.md`; bump `package.json` patch/minor version. diff --git a/README.md b/README.md index 27152f2..a19c377 100644 --- a/README.md +++ b/README.md @@ -88,12 +88,12 @@ npm run build && node scripts/screenshots.mjs # e2e smoke test (Playwright + C **Adding a language:** copy `src/i18n/en.json` to `.json`, translate it, and add the language to `LANGS` in `scripts/build.mjs`. The tests fail if any key is missing. -**New Bot API version:** update `src/assets/js/data.js` (update types, admin rights, `getMe` flags) and the translations; `npm test` lists every missing label. +**New Bot API version:** update `src/assets/js/data.js` (update types, admin rights, `getMe` flags) and the translations; `npm test` lists every missing label. If a new parameter appears on a method the tool calls, add it to `METHOD_PARAMS` in `scripts/check-bot-api.mjs` and expose it in the UI when it matters. ## Automation - **CI** (`.github/workflows/ci.yml`, on pull requests): unit tests, build, end-to-end test in Chromium against a mocked Bot API, and a Lighthouse audit (accessibility and best practices must stay ≥ 95/90; reports are attached to the run). -- **Bot API watch** (`.github/workflows/bot-api-watch.yml`, weekly): compares the latest Bot API spec with `src/assets/js/data.js` via `scripts/check-bot-api.mjs` and opens an issue labelled `bot-api-update` when something is missing. +- **Bot API watch** (`.github/workflows/bot-api-watch.yml`, weekly): compares the latest Bot API spec with `src/assets/js/data.js` via `scripts/check-bot-api.mjs` — update types, admin rights, `getMe` flags, scopes, `BotCommand`/`MenuButton`/`WebhookInfo` fields and the parameters of every method the tool calls — and opens an issue labelled `bot-api-update` when something is missing. A stale spec source is reported as a warning. - **Agent instructions** for updating the project are in [`CLAUDE.md`](CLAUDE.md). ## FAQ diff --git a/scripts/check-bot-api.mjs b/scripts/check-bot-api.mjs index e32c8a6..066f7b0 100644 --- a/scripts/check-bot-api.mjs +++ b/scripts/check-bot-api.mjs @@ -1,5 +1,5 @@ -// Compares the project's Bot API reference data (src/assets/js/data.js) with the latest -// machine-readable Bot API spec and reports what is missing or outdated. +// Compares the project's Bot API reference data with the latest machine-readable Bot API spec +// and reports what is missing or outdated. // Usage: node scripts/check-bot-api.mjs [--spec path/to/api.json] [--json] // Exit code: 0 = up to date, 1 = drift found, 2 = error. import { readFile, readdir } from 'node:fs/promises'; @@ -14,12 +14,52 @@ const JS_DIR = fileURLToPath(new URL('../src/assets/js/', import.meta.url)); const IGNORED_METHODS = new Set(['getMyStarBalance', 'logOut', 'close']); const BOT_SETTINGS_METHOD = /^(set|get|delete|remove)(My[A-Z]|Webhook|WebhookInfo|ChatMenuButton)/; +// Bot API parameters the project knows about for every method it calls. +// A parameter added by Telegram is reported even when the UI does not need it yet; +// when the UI starts using it, add it here. Keep this map in sync with src/assets/js. +export const METHOD_PARAMS = { + getMe: [], + getWebhookInfo: [], + setWebhook: ['url', 'certificate', 'ip_address', 'max_connections', 'allowed_updates', 'drop_pending_updates', 'secret_token'], + deleteWebhook: ['drop_pending_updates'], + getFile: ['file_id'], + getUserProfilePhotos: ['user_id', 'offset', 'limit'], + getMyStarBalance: [], + removeMyProfilePhoto: [], + setMyProfilePhoto: ['photo'], + getMyName: ['language_code'], + setMyName: ['name', 'language_code'], + getMyShortDescription: ['language_code'], + setMyShortDescription: ['short_description', 'language_code'], + getMyDescription: ['language_code'], + setMyDescription: ['description', 'language_code'], + getMyCommands: ['scope', 'language_code'], + setMyCommands: ['commands', 'scope', 'language_code'], + deleteMyCommands: ['scope', 'language_code'], + getChatMenuButton: ['chat_id'], + setChatMenuButton: ['chat_id', 'menu_button'], + getMyDefaultAdministratorRights: ['for_channels'], + setMyDefaultAdministratorRights: ['rights', 'for_channels'], +}; + +// Object fields rendered (or deliberately ignored) by the UI. +export const WEBHOOK_INFO_FIELDS = [ + 'url', 'has_custom_certificate', 'pending_update_count', 'ip_address', 'last_error_date', + 'last_error_message', 'last_synchronization_error_date', 'max_connections', 'allowed_updates', +]; +export const BOT_COMMAND_FIELDS = ['command', 'description', 'is_ephemeral']; +export const MENU_BUTTON_TYPES = ['MenuButtonCommands', 'MenuButtonWebApp', 'MenuButtonDefault']; + +// A stale spec source is a silent-drift risk: it can look "up to date" while Telegram has +// already shipped a newer API. The report warns when the spec release date is older than this. +export const MAX_SPEC_AGE_DAYS = 90; + const diff = (spec, ours) => ({ added: spec.filter((x) => !ours.includes(x)), removed: ours.filter((x) => !spec.includes(x)), }); -async function usedMethods() { +export async function usedMethods() { const files = []; const walk = async (dir) => { for (const entry of await readdir(dir, { withFileTypes: true })) { @@ -37,14 +77,38 @@ async function usedMethods() { return [...methods]; } -export async function checkBotApi(spec) { - const fields = (type) => spec.types[type].fields.map((f) => f.name); +function parseDate(value) { + if (!value) return null; + const date = new Date(value); + return Number.isNaN(date.getTime()) ? null : date; +} + +export async function checkBotApi(spec, { now = new Date(), maxSpecAgeDays = MAX_SPEC_AGE_DAYS } = {}) { + const fields = (type) => (spec.types[type]?.fields ?? []).map((f) => f.name); const version = spec.version.replace(/^Bot API\s*/, ''); const used = await usedMethods(); + // Parameters of every method the tool calls: a new optional parameter matters because + // the UI may need a control for it (as happened with is_ephemeral and secret_token). + const methodParams = { added: [], removed: [] }; + for (const [method, expected] of Object.entries(METHOD_PARAMS)) { + if (!spec.methods[method]) continue; // Method removal is reported by botSettingsMethods.removed. + const actual = (spec.methods[method].fields ?? []).map((f) => f.name); + for (const name of actual) if (!expected.includes(name)) methodParams.added.push(`${method}.${name}`); + for (const name of expected) if (!actual.includes(name)) methodParams.removed.push(`${method}.${name}`); + } + + // A new method in the source must also get a METHOD_PARAMS entry, otherwise its + // parameters are silently unchecked. + const uncheckedMethods = used.filter((method) => spec.methods[method] && !(method in METHOD_PARAMS)); + const releaseDate = parseDate(spec.release_date); + const specAgeDays = releaseDate ? Math.floor((now.getTime() - releaseDate.getTime()) / 86_400_000) : null; + const report = { specVersion: version, specReleaseDate: spec.release_date, + specAgeDays, + staleSpec: specAgeDays !== null && specAgeDays > maxSpecAgeDays, ourVersion: data.BOT_API_VERSION, changelog: spec.changelog, updateTypes: diff(fields('Update').filter((f) => f !== 'update_id'), data.UPDATE_TYPES), @@ -57,14 +121,21 @@ export async function checkBotApi(spec) { spec.types.BotCommandScope.subtypes.map((t) => spec.types[t].fields.find((f) => f.name === 'type').description.match(/must be (\w+)/)[1]), data.COMMAND_SCOPES.map((s) => s.type), ), - setWebhookParams: diff(spec.methods.setWebhook.fields.map((f) => f.name), - ['url', 'certificate', 'ip_address', 'max_connections', 'allowed_updates', 'drop_pending_updates', 'secret_token']), + botCommandFields: diff(fields('BotCommand'), BOT_COMMAND_FIELDS), + menuButtonTypes: diff(spec.types.MenuButton?.subtypes ?? [], MENU_BUTTON_TYPES), + webhookInfoFields: diff(fields('WebhookInfo'), WEBHOOK_INFO_FIELDS), + methodParams, + uncheckedMethods: { added: uncheckedMethods, removed: [] }, botSettingsMethods: { added: Object.keys(spec.methods).filter((m) => BOT_SETTINGS_METHOD.test(m) && !used.includes(m) && !IGNORED_METHODS.has(m)), removed: used.filter((m) => !spec.methods[m]), }, }; - const sections = Object.values(report).filter((v) => v && typeof v === 'object'); + const sections = [ + report.updateTypes, report.adminRights, report.meFlags, report.commandScopes, + report.botCommandFields, report.menuButtonTypes, report.webhookInfoFields, + report.methodParams, report.uncheckedMethods, report.botSettingsMethods, + ]; report.upToDate = report.specVersion === report.ourVersion && sections.every((s) => s.added.length === 0 && s.removed.length === 0); return report; @@ -81,7 +152,11 @@ export function toMarkdown(r) { adminRights: 'ChatAdministratorRights', meFlags: 'getMe flags', commandScopes: 'BotCommandScope types', - setWebhookParams: 'setWebhook parameters', + botCommandFields: 'BotCommand fields', + menuButtonTypes: 'MenuButton types', + webhookInfoFields: 'WebhookInfo fields', + methodParams: 'Method parameters', + uncheckedMethods: 'Used methods without a parameter check', botSettingsMethods: 'Bot settings methods not used by the tool', }; for (const [key, label] of Object.entries(labels)) { @@ -92,6 +167,10 @@ export function toMarkdown(r) { if (removed.length) lines.push(`- Removed from spec: ${removed.map((x) => `\`${x}\``).join(', ')}`); lines.push(''); } + if (r.staleSpec) { + lines.push(`⚠️ The spec was released ${r.specAgeDays} days ago; the source may be stale.`); + lines.push(''); + } if (r.upToDate) lines.push('✅ Up to date.'); return lines.join('\n'); } @@ -102,7 +181,8 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) { const spec = specIndex > -1 ? JSON.parse(await readFile(process.argv[specIndex + 1], 'utf8')) : await (await fetch(SPEC_URL)).json(); - const report = await checkBotApi(spec); + const maxSpecAgeDays = Number(process.env.SPEC_MAX_AGE_DAYS) || MAX_SPEC_AGE_DAYS; + const report = await checkBotApi(spec, { maxSpecAgeDays }); console.log(process.argv.includes('--json') ? JSON.stringify(report, null, 2) : toMarkdown(report)); process.exitCode = report.upToDate ? 0 : 1; } catch (error) { diff --git a/tests/check-bot-api.test.mjs b/tests/check-bot-api.test.mjs index ab0d414..3fcdb68 100644 --- a/tests/check-bot-api.test.mjs +++ b/tests/check-bot-api.test.mjs @@ -1,13 +1,16 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { readFile } from 'node:fs/promises'; -import { checkBotApi, toMarkdown } from '../scripts/check-bot-api.mjs'; +import { + checkBotApi, toMarkdown, usedMethods, METHOD_PARAMS, WEBHOOK_INFO_FIELDS, BOT_COMMAND_FIELDS, MENU_BUTTON_TYPES, +} from '../scripts/check-bot-api.mjs'; import { loadLocales, LANGS } from '../scripts/build.mjs'; import * as data from '../src/assets/js/data.js'; const field = (name, description = '') => ({ name, description }); +const NOW = new Date('2026-11-21T00:00:00Z'); -// Minimal spec that mirrors the project's data.js exactly. +// Minimal spec that mirrors the project's reference data exactly. function specFromProject() { const scopeTypes = data.COMMAND_SCOPES.map((s) => `Scope_${s.type}`); const types = { @@ -15,25 +18,24 @@ function specFromProject() { ChatAdministratorRights: { fields: data.ADMIN_RIGHTS.map((r) => field(r.key)) }, User: { fields: [field('id'), ...data.ME_FLAGS.map((f) => field(f, 'Optional. Returned only in getMe.'))] }, BotCommandScope: { subtypes: scopeTypes }, + BotCommand: { fields: BOT_COMMAND_FIELDS.map((n) => field(n)) }, + MenuButton: { subtypes: [...MENU_BUTTON_TYPES] }, + WebhookInfo: { fields: WEBHOOK_INFO_FIELDS.map((n) => field(n)) }, }; data.COMMAND_SCOPES.forEach((s, i) => { types[scopeTypes[i]] = { fields: [field('type', `Scope type, must be ${s.type}`)] }; }); - const methods = { - setWebhook: { fields: ['url', 'certificate', 'ip_address', 'max_connections', 'allowed_updates', 'drop_pending_updates', 'secret_token'].map((n) => field(n)) }, - }; - for (const m of ['getMe', 'getWebhookInfo', 'deleteWebhook', 'getUserProfilePhotos', 'getFile', 'getMyName', 'setMyName', - 'getMyDescription', 'setMyDescription', 'getMyShortDescription', 'setMyShortDescription', 'getMyCommands', 'setMyCommands', - 'deleteMyCommands', 'getChatMenuButton', 'setChatMenuButton', 'getMyDefaultAdministratorRights', - 'setMyDefaultAdministratorRights', 'setMyProfilePhoto', 'removeMyProfilePhoto', 'getMyStarBalance']) { - methods[m] ??= { fields: [] }; + const methods = {}; + for (const [method, params] of Object.entries(METHOD_PARAMS)) { + methods[method] = { fields: params.map((n) => field(n)) }; } - return { version: `Bot API ${data.BOT_API_VERSION}`, release_date: 'today', changelog: 'url', types, methods }; + return { version: `Bot API ${data.BOT_API_VERSION}`, release_date: 'November 9, 2026', changelog: 'url', types, methods }; } -test('reports up to date when spec matches data.js', async () => { - const report = await checkBotApi(specFromProject()); +test('reports up to date when spec matches the project', async () => { + const report = await checkBotApi(specFromProject(), { now: NOW }); assert.equal(report.upToDate, true, toMarkdown(report)); + assert.equal(report.staleSpec, false); }); test('detects a new version, update type, admin right and bot method', async () => { @@ -42,7 +44,7 @@ test('detects a new version, update type, admin right and bot method', async () spec.types.Update.fields.push(field('brand_new_update')); spec.types.ChatAdministratorRights.fields.push(field('can_do_magic')); spec.methods.setMyEmojiStatus = { fields: [] }; - const report = await checkBotApi(spec); + const report = await checkBotApi(spec, { now: NOW }); assert.equal(report.upToDate, false); assert.deepEqual(report.updateTypes.added, ['brand_new_update']); assert.deepEqual(report.adminRights.added, ['can_do_magic']); @@ -51,6 +53,38 @@ test('detects a new version, update type, admin right and bot method', async () assert.ok(md.includes('99.0') && md.includes('`brand_new_update`')); }); +test('detects new method parameters and object fields', async () => { + const spec = specFromProject(); + spec.methods.setMyCommands.fields.push(field('new_parameter')); + spec.methods.setWebhook.fields = spec.methods.setWebhook.fields.filter((f) => f.name !== 'secret_token'); + spec.types.WebhookInfo.fields.push(field('new_info_field')); + spec.types.BotCommand.fields.push(field('new_command_field')); + spec.types.MenuButton.subtypes.push('MenuButtonNew'); + const report = await checkBotApi(spec, { now: NOW }); + assert.equal(report.upToDate, false); + assert.deepEqual(report.methodParams.added, ['setMyCommands.new_parameter']); + assert.deepEqual(report.methodParams.removed, ['setWebhook.secret_token']); + assert.deepEqual(report.webhookInfoFields.added, ['new_info_field']); + assert.deepEqual(report.botCommandFields.added, ['new_command_field']); + assert.deepEqual(report.menuButtonTypes.added, ['MenuButtonNew']); + const md = toMarkdown(report); + assert.ok(md.includes('`setMyCommands.new_parameter`') && md.includes('### WebhookInfo fields')); +}); + +test('every method used by the source has a parameter expectation', async () => { + const used = await usedMethods(); + assert.ok(used.length > 15); + assert.deepEqual(used.filter((method) => !(method in METHOD_PARAMS)), []); +}); + +test('warns when the spec source is stale without treating it as drift', async () => { + const report = await checkBotApi(specFromProject(), { now: new Date('2027-03-01T00:00:00Z') }); + assert.equal(report.staleSpec, true); + assert.ok(report.specAgeDays > 90); + assert.equal(report.upToDate, true); + assert.match(toMarkdown(report), /source may be stale/); +}); + test('Bot API version is defined only in data.js', async () => { for (const lang of LANGS) { const raw = await readFile(new URL(`../src/i18n/${lang.code}.json`, import.meta.url), 'utf8'); From 3e216b1239c1d6130112d4d5414e41e7267cd642 Mon Sep 17 00:00:00 2001 From: TBM Quality Pass Date: Sat, 21 Nov 2026 11:52:51 +0300 Subject: [PATCH 2/5] Improve keyboard and screen-reader accessibility - move focus to the active tab after connecting - link validation errors to their field with aria-describedby - expose the theme toggle state with aria-pressed - give radio groups accessible names via visible headings - remove the nested toast live region (each toast has its own role) - assert focus, error linkage, theme state and group names in the e2e test --- scripts/screenshots.mjs | 12 ++++++++++++ src/assets/js/main.js | 14 +++++++++----- src/assets/js/ui.js | 32 ++++++++++++++++++++++++++------ src/templates/index.html | 18 +++++++++--------- 4 files changed, 56 insertions(+), 20 deletions(-) diff --git a/scripts/screenshots.mjs b/scripts/screenshots.mjs index c09b7b6..1a2b30a 100644 --- a/scripts/screenshots.mjs +++ b/scripts/screenshots.mjs @@ -152,6 +152,8 @@ async function connect(page) { await page.waitForSelector('#app:not([hidden])'); await page.waitForSelector('#webhook-status .stats'); await page.waitForSelector('#bot-avatar img'); + await page.waitForFunction(() => document.activeElement?.id === 'tab-webhook'); + assert(await page.evaluate(() => document.activeElement?.id) === 'tab-webhook', 'focus moves to the active tab'); } try { @@ -163,7 +165,12 @@ try { await page.fill('#token', 'bad'); await page.click('#connect-form button[type="submit"]'); assert(await page.locator('.field-error').isVisible(), 'token validation'); + const describedBy = await page.getAttribute('#token', 'aria-describedby'); + assert(describedBy && await page.locator(`#${describedBy}`).isVisible(), 'token error is linked to the field'); await shot(page, 'landing.png'); + const themePressed = await page.getAttribute('#theme-toggle', 'aria-pressed'); + await page.click('#theme-toggle'); + assert((await page.getAttribute('#theme-toggle', 'aria-pressed')) !== themePressed, 'theme toggle exposes its state'); await context.close(); } @@ -172,6 +179,11 @@ try { const { page, mock, context } = await openApp(); await connect(page); assert((await page.textContent('#bot-name')) === 'Demo Helper Bot', 'bot name'); + const unnamedGroups = await page.locator('[role="radiogroup"]').evaluateAll((groups) => groups.filter((group) => { + const labelledBy = group.getAttribute('aria-labelledby'); + return !group.getAttribute('aria-label') && !(labelledBy && document.getElementById(labelledBy)); + }).length); + assert(unnamedGroups === 0, 'radio groups have accessible names'); assert((await page.textContent('#webhook-status')).includes('502 Bad Gateway'), 'last error shown'); assert(await page.isChecked('input[name="wh-updates-mode"][value="custom"]'), 'custom updates mode'); assert(await page.isChecked('input[value="chat_member"]'), 'chat_member checked'); diff --git a/src/assets/js/main.js b/src/assets/js/main.js index 06aa6c6..06a0309 100644 --- a/src/assets/js/main.js +++ b/src/assets/js/main.js @@ -63,7 +63,7 @@ async function connect({ token, remember, apiBase }) { renderBot(); loadAvatar(); loadStars(); - activateTab(tabFromHash() ?? 'webhook'); + activateTab(tabFromHash() ?? 'webhook', { focus: true }); window.scrollTo(0, 0); } @@ -261,12 +261,16 @@ function initHeader() { } function initThemeToggle() { - $('#theme-toggle').addEventListener('click', () => { - const current = document.documentElement.dataset.theme - ?? (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'); - const next = current === 'dark' ? 'light' : 'dark'; + const button = $('#theme-toggle'); + const currentTheme = () => document.documentElement.dataset.theme + ?? (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'); + const sync = () => button.setAttribute('aria-pressed', String(currentTheme() === 'dark')); + sync(); + button.addEventListener('click', () => { + const next = currentTheme() === 'dark' ? 'light' : 'dark'; document.documentElement.dataset.theme = next; storage.set('theme', next); + sync(); }); } diff --git a/src/assets/js/ui.js b/src/assets/js/ui.js index 43de163..94ff4d2 100644 --- a/src/assets/js/ui.js +++ b/src/assets/js/ui.js @@ -69,20 +69,40 @@ export async function copyText(text) { } // Marks a field invalid and shows a message under it. Pass null to clear. +// The message is linked through aria-describedby, so screen readers announce it again +// when the user returns to the field (role="alert" covers the first insertion). +const fieldErrorIds = new WeakMap(); +let fieldErrorSeq = 0; + +function fieldErrorId(input) { + let id = fieldErrorIds.get(input); + if (!id) { + id = `${input.id || `field-${++fieldErrorSeq}`}-error`; + fieldErrorIds.set(input, id); + } + return id; +} + export function setFieldError(input, message) { const field = input.closest('.field') ?? input.parentElement; - let node = field.querySelector('.field-error'); + const errorId = fieldErrorId(input); + const describedBy = new Set((input.getAttribute('aria-describedby') ?? '').split(/\s+/).filter(Boolean)); + const node = field.querySelector('.field-error'); if (!message) { input.removeAttribute('aria-invalid'); + describedBy.delete(errorId); + if (describedBy.size) input.setAttribute('aria-describedby', [...describedBy].join(' ')); + else input.removeAttribute('aria-describedby'); node?.remove(); return; } input.setAttribute('aria-invalid', 'true'); - if (!node) { - node = el('p', { class: 'field-error', role: 'alert' }); - field.append(node); - } - node.textContent = message; + const error = node ?? el('p', { class: 'field-error', role: 'alert' }); + if (!node) field.append(error); + error.id = errorId; + error.textContent = message; + describedBy.add(errorId); + input.setAttribute('aria-describedby', [...describedBy].join(' ')); } // Runs validators ([input, errorCode|null, vars]) and focuses the first invalid input. diff --git a/src/templates/index.html b/src/templates/index.html index 323809c..8dedded 100644 --- a/src/templates/index.html +++ b/src/templates/index.html @@ -110,8 +110,8 @@

{{t.ui.webhook.setTitle}}

- {{t.ui.webhook.allowedUpdates}} -
+ {{t.ui.webhook.allowedUpdates}} +
@@ -188,9 +188,9 @@

{{t.ui.profile.title}}


-

{{t.ui.photo.title}}

+

{{t.ui.photo.title}}

{{t.ui.photo.intro}}

-
+
@@ -258,7 +258,7 @@

{{t.ui.commands.title}}

-
+
@@ -298,10 +298,10 @@

{{t.ui.menu.title}}

-
+
From 9387f42eac848d3b69c3d702a049a075929e3c93 Mon Sep 17 00:00:00 2001 From: TBM Quality Pass Date: Sat, 21 Nov 2026 11:55:05 +0300 Subject: [PATCH 3/5] Improve internationalisation and language discovery - add tp() with Intl.PluralRules and plural forms for pending updates and saved commands - suggest a localized version on the English root page (banner, no redirect) - test plural completeness and flag untranslated long strings - cover the language suggestion and its persistence in the e2e test --- scripts/screenshots.mjs | 19 +++++++++++-- src/assets/css/app.css | 3 +++ src/assets/js/i18n.js | 22 +++++++++++++-- src/assets/js/main.js | 36 +++++++++++++++++++++++++ src/assets/js/tabs/commands.js | 4 +-- src/assets/js/tabs/webhook.js | 4 +-- src/i18n/en.json | 19 +++++++++++-- src/i18n/es.json | 19 +++++++++++-- src/i18n/pt.json | 19 +++++++++++-- src/i18n/ru.json | 19 +++++++++++-- src/i18n/zh.json | 19 +++++++++++-- src/templates/index.html | 8 ++++++ tests/i18n.test.mjs | 49 +++++++++++++++++++++++++++++++++- 13 files changed, 221 insertions(+), 19 deletions(-) diff --git a/scripts/screenshots.mjs b/scripts/screenshots.mjs index 1a2b30a..3dbe1c9 100644 --- a/scripts/screenshots.mjs +++ b/scripts/screenshots.mjs @@ -113,9 +113,11 @@ const { chromium } = await loadPlaywright(); const browser = await chromium.launch(); const errors = []; -async function openApp({ theme = 'dark', lang = '', width = 1280, height = 900 } = {}) { +async function openApp({ theme = 'dark', lang = '', width = 1280, height = 900, locale } = {}) { const mock = createMock(); - const context = await browser.newContext({ viewport: { width, height }, colorScheme: theme, deviceScaleFactor: 1 }); + const context = await browser.newContext({ + viewport: { width, height }, colorScheme: theme, deviceScaleFactor: 1, ...(locale ? { locale } : {}), + }); const page = await context.newPage(); page.on('pageerror', (e) => errors.push(`pageerror: ${e.message}`)); page.on('console', (m) => { @@ -174,6 +176,19 @@ try { await context.close(); } + // Browser-language suggestion (a banner, not a redirect) + { + const { page, context } = await openApp({ theme: 'light', locale: 'ru-RU' }); + await page.waitForSelector('#lang-suggest:not([hidden])'); + assert((await page.textContent('#lang-suggest-link')) === 'Русский', 'language suggestion'); + assert((await page.getAttribute('#lang-suggest-link', 'href')) === 'ru/', 'language suggestion link'); + await page.click('#lang-suggest-dismiss'); + assert(await page.locator('#lang-suggest').isHidden(), 'language suggestion dismissed'); + await page.reload(); + assert(await page.locator('#lang-suggest').isHidden(), 'language suggestion stays dismissed'); + await context.close(); + } + // Webhook tab { const { page, mock, context } = await openApp(); diff --git a/src/assets/css/app.css b/src/assets/css/app.css index 1aa6430..a10ace8 100644 --- a/src/assets/css/app.css +++ b/src/assets/css/app.css @@ -387,6 +387,9 @@ input[type="checkbox"], input[type="radio"] { accent-color: var(--accent); width @keyframes toast-in { from { transform: translateY(8px); opacity: 0; } } /* ---------- Landing & guides ---------- */ +.lang-suggest { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; margin-top: 16px; } +.lang-suggest p { margin: 0; flex: 1 1 240px; } + .section { padding: 44px 16px; } .section > h2 { font-size: 1.7rem; margin-bottom: 20px; } .feature-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 14px; } diff --git a/src/assets/js/i18n.js b/src/assets/js/i18n.js index f4cf90c..3667c20 100644 --- a/src/assets/js/i18n.js +++ b/src/assets/js/i18n.js @@ -13,18 +13,36 @@ export function initI18n() { } export function hasKey(key) { - return typeof lookup(key) === 'string'; + const value = lookup(key); + return typeof value === 'string' || (value !== null && typeof value === 'object'); } function lookup(key) { return key.split('.').reduce((node, part) => (node == null ? undefined : node[part]), dict); } +function interpolate(value, vars) { + return value.replace(/\{(\w+)\}/g, (match, name) => (name in vars ? String(vars[name]) : match)); +} + export function t(key, vars) { const value = lookup(key); if (typeof value !== 'string') return key; if (!vars) return value; - return value.replace(/\{(\w+)\}/g, (match, name) => (name in vars ? String(vars[name]) : match)); + return interpolate(value, vars); +} + +// Selects a plural form with Intl.PluralRules. Locale files store +// { one, few, many, other } objects; `{n}` and `{count}` are filled automatically. +export function tp(key, count, vars) { + const value = lookup(key); + if (value == null) return key; + const args = { ...vars, n: count, count }; + if (typeof value === 'string') return interpolate(value, args); + if (typeof value !== 'object') return key; + const category = new Intl.PluralRules(locale).select(count); + const template = value[category] ?? value.other ?? value.one; + return typeof template === 'string' ? interpolate(template, args) : key; } export function getLocale() { diff --git a/src/assets/js/main.js b/src/assets/js/main.js index 06a0309..e7c6707 100644 --- a/src/assets/js/main.js +++ b/src/assets/js/main.js @@ -13,6 +13,12 @@ import devTab from './tabs/dev.js'; const TABS = [webhookTab, profileTab, commandsTab, menuTab, rightsTab, devTab]; const LOG_LIMIT = 100; +const LANGUAGE_SUGGESTIONS = [ + { code: 'ru', prefix: 'ru/', name: 'Русский' }, + { code: 'es', prefix: 'es/', name: 'Español' }, + { code: 'pt', prefix: 'pt/', name: 'Português' }, + { code: 'zh', prefix: 'zh/', name: '简体中文' }, +]; const bus = new EventTarget(); @@ -250,6 +256,35 @@ function initLanguageSelects() { } } +// The root page is English. Suggest a localized version instead of redirecting, +// so search engines still see one canonical page per language. +function initLanguageSuggestion() { + const box = $('#lang-suggest'); + if (!box || document.documentElement.lang !== 'en') return; + if (storage.get('langSuggestionDismissed')) return; + const preferred = (navigator.languages?.length ? navigator.languages : [navigator.language]) + .map((code) => String(code).toLowerCase().split('-')[0]); + const suggestion = LANGUAGE_SUGGESTIONS.find((lang) => preferred.includes(lang.code)); + if (!suggestion) return; + + $('#lang-suggest-text').textContent = t('langSuggest.text'); + const link = $('#lang-suggest-link'); + link.textContent = suggestion.name; + link.href = suggestion.prefix; + link.hreflang = suggestion.code; + link.lang = suggestion.code; + link.setAttribute('aria-label', t('langSuggest.open', { language: suggestion.name })); + + const dismiss = $('#lang-suggest-dismiss'); + dismiss.textContent = t('langSuggest.dismiss'); + dismiss.addEventListener('click', () => { + box.hidden = true; + storage.set('langSuggestionDismissed', '1'); + }); + link.addEventListener('click', () => storage.set('langSuggestionDismissed', '1')); + box.hidden = false; +} + function initHeader() { // Close header dropdowns when clicking elsewhere. document.addEventListener('click', (event) => { @@ -308,6 +343,7 @@ function init() { if (!$('#app')) return; // Guide pages have no app. initGlobalButtons(); initLanguageSelects(); + initLanguageSuggestion(); bindCounters(); initTabs(); initConnectForm(); diff --git a/src/assets/js/tabs/commands.js b/src/assets/js/tabs/commands.js index 1615ad4..c8e93f4 100644 --- a/src/assets/js/tabs/commands.js +++ b/src/assets/js/tabs/commands.js @@ -1,4 +1,4 @@ -import { t } from '../i18n.js'; +import { t, tp } from '../i18n.js'; import { COMMAND_SCOPES, LIMITS } from '../data.js'; import { parseCommands, formatCommands } from '../commands.js'; import { validateChatId, validateUserId, parseChatId } from '../validators.js'; @@ -87,7 +87,7 @@ export default { await withBusy(event.submitter, async () => { try { await app.api.call(request.method, request.params); - toast(t('commands.saved', { n: request.params.commands.length })); + toast(tp('commands.saved', request.params.commands.length)); } catch (error) { showError(error); } diff --git a/src/assets/js/tabs/webhook.js b/src/assets/js/tabs/webhook.js index dee1731..2336945 100644 --- a/src/assets/js/tabs/webhook.js +++ b/src/assets/js/tabs/webhook.js @@ -1,4 +1,4 @@ -import { t, formatDateTime, formatRelative } from '../i18n.js'; +import { t, tp, formatDateTime, formatRelative } from '../i18n.js'; import { UPDATE_GROUPS } from '../data.js'; import { validateWebhookUrl, validateSecretToken, validateMaxConnections, validateIpAddress, generateSecretToken, @@ -189,7 +189,7 @@ function initForms() { } const secret = $('#drop-secret'); if (!applyValidation([[secret, validateSecretToken(secret.value.trim())]])) return; - if (!confirmAction(t('webhook.dropConfirm', { count: info.pending_update_count ?? 0 }))) return; + if (!confirmAction(tp('webhook.dropConfirm', info.pending_update_count ?? 0))) return; await withBusy(event.submitter, async () => { try { // allowed_updates is omitted on purpose: Telegram keeps the previous value. diff --git a/src/i18n/en.json b/src/i18n/en.json index 20bfcfb..0b0bdd4 100644 --- a/src/i18n/en.json +++ b/src/i18n/en.json @@ -301,6 +301,11 @@ } }, "app": { + "langSuggest": { + "text": "This site is also available in other languages.", + "open": "Open the {language} version", + "dismiss": "Dismiss" + }, "common": { "copied": "Copied to clipboard", "copyFailed": "Could not copy — select the text manually", @@ -379,7 +384,12 @@ "secretGenerated": "Secret generated. Save it in your server config before setting the webhook.", "saved": "Webhook saved.", "noWebhook": "The webhook is not set.", - "dropConfirm": "Drop {count} pending update(s)? They will be lost.", + "dropConfirm": { + "one": "Drop {count} pending update? It will be lost.", + "few": "Drop {count} pending updates? They will be lost.", + "many": "Drop {count} pending updates? They will be lost.", + "other": "Drop {count} pending updates? They will be lost." + }, "dropped": "Pending updates dropped.", "deleteConfirm": "Delete the webhook? The bot will stop receiving updates on this URL.", "deleted": "Webhook deleted. The bot can use getUpdates now.", @@ -448,7 +458,12 @@ }, "commands": { "line": "Line {n}", - "saved": "Saved {n} command(s).", + "saved": { + "one": "Saved {n} command.", + "few": "Saved {n} commands.", + "many": "Saved {n} commands.", + "other": "Saved {n} commands." + }, "deleteConfirm": "Delete the command list for this scope and language?", "deleted": "Commands deleted." }, diff --git a/src/i18n/es.json b/src/i18n/es.json index d76e9d6..1ed5fcb 100644 --- a/src/i18n/es.json +++ b/src/i18n/es.json @@ -301,6 +301,11 @@ } }, "app": { + "langSuggest": { + "text": "Este sitio también está disponible en otros idiomas.", + "open": "Abrir la versión en {language}", + "dismiss": "Descartar" + }, "common": { "copied": "Copiado al portapapeles", "copyFailed": "No se pudo copiar: selecciona el texto manualmente", @@ -379,7 +384,12 @@ "secretGenerated": "Secreto generado. Guárdalo en la configuración del servidor antes de configurar el webhook.", "saved": "Webhook guardado.", "noWebhook": "El webhook no está configurado.", - "dropConfirm": "¿Descartar {count} actualización(es) pendiente(s)? Se perderán.", + "dropConfirm": { + "one": "¿Descartar {count} actualización pendiente? Se perderá.", + "few": "¿Descartar {count} actualizaciones pendientes? Se perderán.", + "many": "¿Descartar {count} actualizaciones pendientes? Se perderán.", + "other": "¿Descartar {count} actualizaciones pendientes? Se perderán." + }, "dropped": "Actualizaciones pendientes descartadas.", "deleteConfirm": "¿Eliminar el webhook? El bot dejará de recibir actualizaciones en esta URL.", "deleted": "Webhook eliminado. Ahora el bot puede usar getUpdates.", @@ -448,7 +458,12 @@ }, "commands": { "line": "Línea {n}", - "saved": "{n} comando(s) guardado(s).", + "saved": { + "one": "Se guardó {n} comando.", + "few": "Se guardaron {n} comandos.", + "many": "Se guardaron {n} comandos.", + "other": "Se guardaron {n} comandos." + }, "deleteConfirm": "¿Eliminar la lista de comandos para este ámbito e idioma?", "deleted": "Comandos eliminados." }, diff --git a/src/i18n/pt.json b/src/i18n/pt.json index bd98229..bfe28c8 100644 --- a/src/i18n/pt.json +++ b/src/i18n/pt.json @@ -301,6 +301,11 @@ } }, "app": { + "langSuggest": { + "text": "Este site também está disponível em outros idiomas.", + "open": "Abrir a versão em {language}", + "dismiss": "Dispensar" + }, "common": { "copied": "Copiado para a área de transferência", "copyFailed": "Não foi possível copiar — selecione o texto manualmente", @@ -379,7 +384,12 @@ "secretGenerated": "Segredo gerado. Salve-o na configuração do servidor antes de configurar o webhook.", "saved": "Webhook salvo.", "noWebhook": "O webhook não está configurado.", - "dropConfirm": "Descartar {count} atualização(ões) pendente(s)? Elas serão perdidas.", + "dropConfirm": { + "one": "Descartar {count} atualização pendente? Ela será perdida.", + "few": "Descartar {count} atualizações pendentes? Elas serão perdidas.", + "many": "Descartar {count} atualizações pendentes? Elas serão perdidas.", + "other": "Descartar {count} atualizações pendentes? Elas serão perdidas." + }, "dropped": "Atualizações pendentes descartadas.", "deleteConfirm": "Excluir o webhook? O bot deixará de receber atualizações nesta URL.", "deleted": "Webhook excluído. Agora o bot pode usar getUpdates.", @@ -448,7 +458,12 @@ }, "commands": { "line": "Linha {n}", - "saved": "{n} comando(s) salvo(s).", + "saved": { + "one": "Foi salvo {n} comando.", + "few": "Foram salvos {n} comandos.", + "many": "Foram salvos {n} comandos.", + "other": "Foram salvos {n} comandos." + }, "deleteConfirm": "Excluir a lista de comandos para este escopo e idioma?", "deleted": "Comandos excluídos." }, diff --git a/src/i18n/ru.json b/src/i18n/ru.json index f532fe3..bb6dc0f 100644 --- a/src/i18n/ru.json +++ b/src/i18n/ru.json @@ -301,6 +301,11 @@ } }, "app": { + "langSuggest": { + "text": "Сайт также доступен на других языках.", + "open": "Открыть версию на языке {language}", + "dismiss": "Скрыть" + }, "common": { "copied": "Скопировано в буфер обмена", "copyFailed": "Не удалось скопировать — выделите текст вручную", @@ -379,7 +384,12 @@ "secretGenerated": "Секрет создан. Сохраните его в конфиге сервера до установки вебхука.", "saved": "Вебхук сохранён.", "noWebhook": "Вебхук не установлен.", - "dropConfirm": "Удалить ожидающие обновления ({count})? Они будут потеряны.", + "dropConfirm": { + "one": "Удалить {count} ожидающее обновление? Оно будет потеряно.", + "few": "Удалить {count} ожидающих обновления? Они будут потеряны.", + "many": "Удалить {count} ожидающих обновлений? Они будут потеряны.", + "other": "Удалить {count} ожидающих обновлений? Они будут потеряны." + }, "dropped": "Очередь обновлений очищена.", "deleteConfirm": "Удалить вебхук? Бот перестанет получать обновления на этот URL.", "deleted": "Вебхук удалён. Теперь бот может использовать getUpdates.", @@ -448,7 +458,12 @@ }, "commands": { "line": "Строка {n}", - "saved": "Сохранено команд: {n}.", + "saved": { + "one": "Сохранена {n} команда.", + "few": "Сохранено {n} команды.", + "many": "Сохранено {n} команд.", + "other": "Сохранено {n} команд." + }, "deleteConfirm": "Удалить список команд для этой области и языка?", "deleted": "Команды удалены." }, diff --git a/src/i18n/zh.json b/src/i18n/zh.json index f66d0ab..bac7c29 100644 --- a/src/i18n/zh.json +++ b/src/i18n/zh.json @@ -301,6 +301,11 @@ } }, "app": { + "langSuggest": { + "text": "本站还提供其他语言版本。", + "open": "打开{language}版本", + "dismiss": "关闭" + }, "common": { "copied": "已复制到剪贴板", "copyFailed": "复制失败——请手动选择文本", @@ -379,7 +384,12 @@ "secretGenerated": "已生成密钥。请在设置 Webhook 之前将其保存到服务器配置中。", "saved": "Webhook 已保存。", "noWebhook": "未设置 Webhook。", - "dropConfirm": "丢弃 {count} 条待处理更新?它们将无法恢复。", + "dropConfirm": { + "one": "丢弃 {count} 条待处理更新?此操作无法撤销。", + "few": "丢弃 {count} 条待处理更新?此操作无法撤销。", + "many": "丢弃 {count} 条待处理更新?此操作无法撤销。", + "other": "丢弃 {count} 条待处理更新?此操作无法撤销。" + }, "dropped": "已丢弃待处理更新。", "deleteConfirm": "删除 Webhook?机器人将不再通过该 URL 接收更新。", "deleted": "Webhook 已删除。机器人现在可以使用 getUpdates。", @@ -448,7 +458,12 @@ }, "commands": { "line": "第 {n} 行", - "saved": "已保存 {n} 个命令。", + "saved": { + "one": "已保存 {n} 个命令。", + "few": "已保存 {n} 个命令。", + "many": "已保存 {n} 个命令。", + "other": "已保存 {n} 个命令。" + }, "deleteConfirm": "删除此范围和语言的命令列表?", "deleted": "命令已删除。" }, diff --git a/src/templates/index.html b/src/templates/index.html index 8dedded..abd52cb 100644 --- a/src/templates/index.html +++ b/src/templates/index.html @@ -337,6 +337,14 @@

{{t.ui.dev.log}}

+
+ +
+

{{t.home.featuresTitle}}

{{{home.features}}}
diff --git a/tests/i18n.test.mjs b/tests/i18n.test.mjs index 583e020..ed37252 100644 --- a/tests/i18n.test.mjs +++ b/tests/i18n.test.mjs @@ -4,7 +4,7 @@ import { readFile, readdir } from 'node:fs/promises'; import { join } from 'node:path'; import { loadLocales, LANGS } from '../scripts/build.mjs'; import { UPDATE_TYPES, ADMIN_RIGHTS, ME_FLAGS, COMMAND_SCOPES, UPDATE_GROUPS } from '../src/assets/js/data.js'; -import { setDictionary, hasKey, t } from '../src/assets/js/i18n.js'; +import { setDictionary, hasKey, t, tp } from '../src/assets/js/i18n.js'; const JS_DIR = new URL('../src/assets/js/', import.meta.url).pathname; @@ -57,6 +57,53 @@ test('t() interpolates variables', () => { assert.equal(t('a.unknown'), 'a.unknown'); }); +test('tp() selects the plural form for the locale', () => { + setDictionary({ + a: { b: { one: 'one {count}', few: 'few {count}', many: 'many {count}', other: 'other {count}' } }, + }, 'ru'); + assert.equal(hasKey('a.b'), true); + assert.equal(tp('a.b', 1), 'one 1'); + assert.equal(tp('a.b', 2), 'few 2'); + assert.equal(tp('a.b', 5), 'many 5'); + assert.equal(tp('a.b', 1.5), 'other 1.5'); + assert.equal(tp('a.missing', 1), 'a.missing'); +}); + +test('plural messages are complete in every locale', async () => { + const locales = await loadLocales(); + for (const lang of LANGS) { + const app = locales[lang.code].app; + for (const path of ['webhook.dropConfirm', 'commands.saved']) { + const value = path.split('.').reduce((node, key) => node[key], app); + assert.equal(typeof value, 'object', `${lang.code}.${path} must be a plural object`); + for (const form of ['one', 'few', 'many', 'other']) { + assert.equal(typeof value[form], 'string', `${lang.code}.${path}.${form} is missing`); + } + assert.ok(!/\((s|es|ões)\)/.test(JSON.stringify(value)), `${lang.code}.${path} still uses the "(s)" workaround`); + } + } +}); + +test('non-English locales have no untranslated long strings', async () => { + const locales = await loadLocales(); + // Product names and API field names are intentionally identical. + const allowed = new Set(['allowed_updates', 'Telegram Business']); + const problems = []; + const walk = (base, other, path = '') => { + for (const key of Object.keys(base)) { + const source = base[key]; + const translated = other?.[key]; + if (typeof source === 'string' && typeof translated === 'string') { + if (source.length > 12 && source === translated && !allowed.has(source)) problems.push(`${path}${key}: ${source}`); + } else if (source && typeof source === 'object') { + walk(source, translated, `${path}${key}.`); + } + } + }; + for (const lang of LANGS.filter((l) => l.code !== 'en')) walk(locales.en, locales[lang.code]); + assert.deepEqual(problems, [], `untranslated strings:\n ${problems.join('\n ')}`); +}); + test('SEO titles and descriptions fit search snippets', async () => { const locales = await loadLocales(); for (const lang of LANGS) { From 075c742aa3bb0e0ea3973d575647f770d6527a0a Mon Sep 17 00:00:00 2001 From: TBM Quality Pass Date: Sat, 21 Nov 2026 11:57:02 +0300 Subject: [PATCH 4/5] Update the CI toolchain and prepare 3.3.0 - Playwright 1.65.1 with a browser cache; e2e is back on ubuntu-latest - Lighthouse performance and SEO thresholds are now errors - document METHOD_PARAMS in the Bot API watch issue text - CHANGELOG and package version 3.3.0 --- .github/workflows/bot-api-watch.yml | 2 +- .github/workflows/ci.yml | 10 +++++++--- CHANGELOG.md | 11 +++++++++++ README.md | 2 +- lighthouserc.json | 4 ++-- package.json | 2 +- 6 files changed, 23 insertions(+), 8 deletions(-) diff --git a/.github/workflows/bot-api-watch.yml b/.github/workflows/bot-api-watch.yml index e9718d3..cd618b0 100644 --- a/.github/workflows/bot-api-watch.yml +++ b/.github/workflows/bot-api-watch.yml @@ -40,7 +40,7 @@ jobs: echo cat report.md echo - echo "To update: edit \`src/assets/js/data.js\` (lists and \`BOT_API_VERSION\`), add labels to all \`src/i18n/*.json\`, then run \`npm test\` and \`node scripts/check-bot-api.mjs\`." + echo "To update: edit \`src/assets/js/data.js\` (lists and \`BOT_API_VERSION\`), add labels to all \`src/i18n/*.json\`, add new method parameters to \`METHOD_PARAMS\` in \`scripts/check-bot-api.mjs\`, then run \`npm test\` and \`node scripts/check-bot-api.mjs\`." } > body.md existing=$(gh issue list --label bot-api-update --state open --json number --jq '.[0].number') if [ -n "$existing" ]; then diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 11c3ed8..4d54668 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,8 +31,7 @@ jobs: e2e: needs: test - # Pinned: Playwright 1.56 has no browser builds for ubuntu-latest (26.04) yet. - runs-on: ubuntu-24.04 + runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 - uses: actions/setup-node@v5 @@ -42,9 +41,14 @@ jobs: with: name: dist path: dist + - name: Cache Playwright browsers + uses: actions/cache@v4 + with: + path: ~/.cache/ms-playwright + key: playwright-${{ runner.os }}-${{ runner.arch }}-1.65.1 - name: Install Playwright run: | - npm install --no-save playwright@1.56.1 + npm install --no-save playwright@1.65.1 npx playwright install --with-deps chromium # Mocked Bot API flows; fails on any console error or CSP violation. - run: node scripts/screenshots.mjs --no-shots diff --git a/CHANGELOG.md b/CHANGELOG.md index e5080d3..665b32b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## 3.3.0 — 2026-11-21 + +### Added +- Bot API drift check now compares the parameters of every method the tool calls, plus `WebhookInfo`, `BotCommand` and `MenuButton` fields; it also warns when the spec source is stale. +- The English root page suggests a localized version based on the browser language (a dismissible banner, not a redirect). +- Plural forms for pending-update and saved-command messages via `Intl.PluralRules`. + +### Changed +- Accessibility: focus moves to the active tab after connecting; validation errors are linked to their field with `aria-describedby`; the theme toggle exposes `aria-pressed`; radio groups have accessible names; the toast live region is no longer nested. +- CI: Playwright 1.65.1 with a browser cache; Lighthouse performance and SEO thresholds are now errors (≥ 90 and ≥ 95). + ## 3.2.0 — 2026-11-11 ### Changed diff --git a/README.md b/README.md index a19c377..efbdbd6 100644 --- a/README.md +++ b/README.md @@ -92,7 +92,7 @@ npm run build && node scripts/screenshots.mjs # e2e smoke test (Playwright + C ## Automation -- **CI** (`.github/workflows/ci.yml`, on pull requests): unit tests, build, end-to-end test in Chromium against a mocked Bot API, and a Lighthouse audit (accessibility and best practices must stay ≥ 95/90; reports are attached to the run). +- **CI** (`.github/workflows/ci.yml`, on pull requests): unit tests, build, end-to-end test in Chromium against a mocked Bot API, and a Lighthouse audit (accessibility ≥ 95, best practices ≥ 90, SEO ≥ 95 and performance ≥ 90 are errors; reports are attached to the run). - **Bot API watch** (`.github/workflows/bot-api-watch.yml`, weekly): compares the latest Bot API spec with `src/assets/js/data.js` via `scripts/check-bot-api.mjs` — update types, admin rights, `getMe` flags, scopes, `BotCommand`/`MenuButton`/`WebhookInfo` fields and the parameters of every method the tool calls — and opens an issue labelled `bot-api-update` when something is missing. A stale spec source is reported as a warning. - **Agent instructions** for updating the project are in [`CLAUDE.md`](CLAUDE.md). diff --git a/lighthouserc.json b/lighthouserc.json index 152445e..5af74c3 100644 --- a/lighthouserc.json +++ b/lighthouserc.json @@ -14,8 +14,8 @@ "assertions": { "categories:accessibility": ["error", { "minScore": 0.95 }], "categories:best-practices": ["error", { "minScore": 0.9 }], - "categories:seo": ["warn", { "minScore": 0.9 }], - "categories:performance": ["warn", { "minScore": 0.85 }] + "categories:seo": ["error", { "minScore": 0.95 }], + "categories:performance": ["error", { "minScore": 0.9 }] } }, "upload": { "target": "filesystem", "outputDir": ".lighthouseci" } diff --git a/package.json b/package.json index 827d026..819edb1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "telegram-bot-manager", - "version": "3.2.0", + "version": "3.3.0", "private": true, "description": "Free online Telegram Bot Manager: set, check and delete webhooks, edit commands, profile, menu button and admin rights right in your browser.", "type": "module", From 7ba9524b7481eb69b8062bcf1ffdb978cc6779b4 Mon Sep 17 00:00:00 2001 From: f1devbin <280303226+f1devbin@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:56:42 +0300 Subject: [PATCH 5/5] ci: keep Lighthouse performance a warning The first PR run scored 0.83 on a shared runner while local runs are 100. Performance is noisy on GitHub runners, so keep it a warning at 0.85 and leave SEO as an error at 0.95. --- CHANGELOG.md | 2 +- README.md | 2 +- lighthouserc.json | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 665b32b..26b5427 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ ### Changed - Accessibility: focus moves to the active tab after connecting; validation errors are linked to their field with `aria-describedby`; the theme toggle exposes `aria-pressed`; radio groups have accessible names; the toast live region is no longer nested. -- CI: Playwright 1.65.1 with a browser cache; Lighthouse performance and SEO thresholds are now errors (≥ 90 and ≥ 95). +- CI: Playwright 1.65.1 with a browser cache; the Lighthouse SEO threshold is now an error (≥ 95), while performance stays a warning (≥ 85) because GitHub runners vary. ## 3.2.0 — 2026-11-11 diff --git a/README.md b/README.md index efbdbd6..eb52e65 100644 --- a/README.md +++ b/README.md @@ -92,7 +92,7 @@ npm run build && node scripts/screenshots.mjs # e2e smoke test (Playwright + C ## Automation -- **CI** (`.github/workflows/ci.yml`, on pull requests): unit tests, build, end-to-end test in Chromium against a mocked Bot API, and a Lighthouse audit (accessibility ≥ 95, best practices ≥ 90, SEO ≥ 95 and performance ≥ 90 are errors; reports are attached to the run). +- **CI** (`.github/workflows/ci.yml`, on pull requests): unit tests, build, end-to-end test in Chromium against a mocked Bot API, and a Lighthouse audit (accessibility ≥ 95, best practices ≥ 90 and SEO ≥ 95 are errors; performance ≥ 85 is a warning; reports are attached to the run). - **Bot API watch** (`.github/workflows/bot-api-watch.yml`, weekly): compares the latest Bot API spec with `src/assets/js/data.js` via `scripts/check-bot-api.mjs` — update types, admin rights, `getMe` flags, scopes, `BotCommand`/`MenuButton`/`WebhookInfo` fields and the parameters of every method the tool calls — and opens an issue labelled `bot-api-update` when something is missing. A stale spec source is reported as a warning. - **Agent instructions** for updating the project are in [`CLAUDE.md`](CLAUDE.md). diff --git a/lighthouserc.json b/lighthouserc.json index 5af74c3..bc10fd5 100644 --- a/lighthouserc.json +++ b/lighthouserc.json @@ -15,7 +15,7 @@ "categories:accessibility": ["error", { "minScore": 0.95 }], "categories:best-practices": ["error", { "minScore": 0.9 }], "categories:seo": ["error", { "minScore": 0.95 }], - "categories:performance": ["error", { "minScore": 0.9 }] + "categories:performance": ["warn", { "minScore": 0.85 }] } }, "upload": { "target": "filesystem", "outputDir": ".lighthouseci" }