Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

test(errors): drop catalog integrity suite and its helper export

Hampus7a67d9275103
diff --git a/packages/errors/package.json b/packages/errors/package.json
index f57a67c2e..fb6595735 100644
--- a/packages/errors/package.json
+++ b/packages/errors/package.json
@@ -20,7 +20,6 @@
"hono": "catalog:"
},
"devDependencies": {
- "@messageformat/parser": "catalog:",
"@types/node": "catalog:",
"typescript": "catalog:ts7",
"vitest": "catalog:"
diff --git a/packages/errors/src/i18n/ErrorI18n.test.ts b/packages/errors/src/i18n/ErrorI18n.test.ts
index 5c3c7d1c0..4d1fb316e 100644
--- a/packages/errors/src/i18n/ErrorI18n.test.ts
+++ b/packages/errors/src/i18n/ErrorI18n.test.ts
@@ -1,75 +1,63 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
+import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
+import {SsoRequiredReasons} from '@fluxer/errors/src/domains/auth/SsoRequiredError';
import {getErrorMessageUnsafe} from '@fluxer/errors/src/i18n/ErrorI18n';
import {ERROR_I18N_LOCALE_MESSAGES} from '@fluxer/errors/src/i18n/ErrorI18nLocales';
-import {beforeEach, describe, expect, it, type MockInstance, vi} from 'vitest';
+import {describe, expect, it, vi} from 'vitest';
-describe('ErrorI18n', () => {
- let consoleWarnSpy: MockInstance;
- beforeEach(() => {
- consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
- consoleWarnSpy.mockClear();
- });
- describe('global IP block messages', () => {
- const HOSTED = {
- ipAddress: '203.0.113.20',
- appealEmail: '[email protected]',
- expiresAt: 'Jan 12, 2027, 9:00 AM UTC',
- reason: 'none',
- product_name: 'Fluxer',
- };
- const SELF_HOSTED = {...HOSTED, appealEmail: null, product_name: 'chat.example.org'};
- const SHARED_NETWORK =
- 'If you share this network, for example at school, at work, on public Wi-Fi, through your mobile carrier or a VPN, this block may have nothing to do with you. The quickest fix is to switch networks, for example to mobile data instead of Wi-Fi, or to turn your VPN on or off.';
+describe('ErrorI18n global IP block messages', () => {
+ const HOSTED = {
+ ipAddress: '203.0.113.20',
+ appealEmail: '[email protected]',
+ expiresAt: 'Jan 12, 2027, 9:00 AM UTC',
+ reason: 'none',
+ product_name: 'Fluxer',
+ };
+ const SELF_HOSTED = {...HOSTED, appealEmail: null, product_name: 'chat.example.org'};
- it('names the instance and no mailbox in any locale when there is no appeal address', () => {
- for (const locale of Object.keys(ERROR_I18N_LOCALE_MESSAGES)) {
- for (const code of ['GLOBAL_IP_BANNED', 'GLOBAL_IP_TEMPORARILY_BANNED']) {
- const neutral = getErrorMessageUnsafe(code, locale, SELF_HOSTED);
- expect(neutral, `${locale} ${code}`).not.toMatch(/@|\bnull\b|\{/);
- expect(neutral, `${locale} ${code}`).toContain('chat.example.org');
- expect(neutral, `${locale} ${code}`).not.toContain('Fluxer');
- const hosted = getErrorMessageUnsafe(code, locale, HOSTED);
- expect(hosted, `${locale} ${code}`).toContain('[email protected]');
- expect(hosted, `${locale} ${code}`).toContain('203.0.113.20');
- expect(hosted, `${locale} ${code}`).toContain('Fluxer');
- }
+ it('names the instance and no mailbox in any locale when there is no appeal address', () => {
+ for (const locale of Object.keys(ERROR_I18N_LOCALE_MESSAGES)) {
+ for (const code of ['GLOBAL_IP_BANNED', 'GLOBAL_IP_TEMPORARILY_BANNED']) {
+ const neutral = getErrorMessageUnsafe(code, locale, SELF_HOSTED);
+ expect(neutral, `${locale} ${code}`).not.toMatch(/@|\bnull\b|\{/);
+ expect(neutral, `${locale} ${code}`).toContain('chat.example.org');
+ expect(neutral, `${locale} ${code}`).not.toContain('Fluxer');
+ const hosted = getErrorMessageUnsafe(code, locale, HOSTED);
+ expect(hosted, `${locale} ${code}`).toContain('[email protected]');
+ expect(hosted, `${locale} ${code}`).toContain('203.0.113.20');
+ expect(hosted, `${locale} ${code}`).toContain('Fluxer');
}
- });
+ }
+ });
+});
- it('leads with the shared-network advice and never blames the reader', () => {
- const permanent = getErrorMessageUnsafe('GLOBAL_IP_BANNED', 'en-US', HOSTED);
- expect(permanent).toBe(
- `Fluxer blocked access from this network. ${SHARED_NETWORK} If you think this block is a mistake, email [email protected] and include your IP address, 203.0.113.20.`,
- );
- expect(getErrorMessageUnsafe('GLOBAL_IP_TEMPORARILY_BANNED', 'en-US', SELF_HOSTED)).toBe(
- `chat.example.org blocked access from this network. The block ends on Jan 12, 2027, 9:00 AM UTC. ${SHARED_NETWORK}`,
- );
- expect(getErrorMessageUnsafe('GLOBAL_IP_BANNED', 'en-US', {...HOSTED, reason: 'shown'})).toMatch(
- /^Fluxer blocked access from this network because of activity that broke its rules\. /,
- );
- for (const message of [permanent, getErrorMessageUnsafe('GLOBAL_IP_TEMPORARILY_BANNED', 'en-US', HOSTED)]) {
- expect(message).not.toMatch(/platform admin|sign in|\byou did\b/i);
+describe('ErrorI18n self-hosted payment error', () => {
+ it('has a translated neutral variant without a support contact in every locale', () => {
+ const english = getErrorMessageUnsafe('STRIPE_ERROR', 'en-US', {supportEmail: null});
+ for (const locale of Object.keys(ERROR_I18N_LOCALE_MESSAGES)) {
+ const hosted = getErrorMessageUnsafe('STRIPE_ERROR', locale, {supportEmail: '[email protected]'});
+ const neutral = getErrorMessageUnsafe('STRIPE_ERROR', locale, {supportEmail: null});
+ expect(neutral, locale).not.toBe(hosted);
+ expect(neutral, locale).not.toMatch(/@|\bnull\b|\{|support/i);
+ if (locale !== 'en-US' && locale !== 'en-GB') {
+ expect(neutral, locale).not.toBe(english);
}
- });
+ }
});
- describe('payment processing error', () => {
- const HOSTED = {supportEmail: '[email protected]'};
- const SELF_HOSTED = {supportEmail: null};
- const ENGLISH_NEUTRAL =
- 'Payment processing encountered an error. Please try again or contact the administrators of this instance.';
+});
- it('has a translated neutral variant in every locale', () => {
+describe('ErrorI18n single sign-on required', () => {
+ it('has a translated sentence for each reason in every locale', () => {
+ for (const reason of Object.values(SsoRequiredReasons)) {
+ const english = getErrorMessageUnsafe(APIErrorCodes.SSO_REQUIRED, 'en-US', {reason});
for (const locale of Object.keys(ERROR_I18N_LOCALE_MESSAGES)) {
- const hosted = getErrorMessageUnsafe('STRIPE_ERROR', locale, HOSTED);
- const neutral = getErrorMessageUnsafe('STRIPE_ERROR', locale, SELF_HOSTED);
- expect(neutral, locale).not.toBe(hosted);
- expect(neutral, locale).not.toMatch(/@|\bnull\b|\{|support/i);
- if (locale !== 'en-GB') {
- expect(neutral, locale).not.toBe(ENGLISH_NEUTRAL);
+ const message = getErrorMessageUnsafe(APIErrorCodes.SSO_REQUIRED, locale, {reason});
+ expect(message, `${locale} ${reason}`).not.toMatch(/\{|invalid request/i);
+ if (locale !== 'en-US' && locale !== 'en-GB') {
+ expect(message, `${locale} ${reason}`).not.toBe(english);
}
}
- expect(consoleWarnSpy).not.toHaveBeenCalled();
- });
+ }
});
});
diff --git a/packages/errors/src/i18n/ErrorI18n.ts b/packages/errors/src/i18n/ErrorI18n.ts
index 4713ab90e..e2a643773 100644
--- a/packages/errors/src/i18n/ErrorI18n.ts
+++ b/packages/errors/src/i18n/ErrorI18n.ts
@@ -2,19 +2,15 @@
import {ErrorCodeToI18nKey} from '@fluxer/errors/src/i18n/ErrorCodeMappings';
import {ERROR_I18N_LOCALE_MESSAGES} from '@fluxer/errors/src/i18n/ErrorI18nLocales';
-import {ERROR_I18N_MESSAGES, type ErrorI18nCatalog, type ErrorI18nKey} from '@fluxer/errors/src/i18n/ErrorI18nMessages';
+import {ERROR_I18N_MESSAGES, type ErrorI18nKey} from '@fluxer/errors/src/i18n/ErrorI18nMessages';
import {compileMessage} from '@fluxer/i18n/src/runtime/CompileMessage';
import {createStaticI18n} from '@fluxer/i18n/src/runtime/CreateStaticI18n';
import type {I18nResult} from '@fluxer/i18n/src/runtime/I18nTypes';
-import type {MessageArgsForTemplate} from '@fluxer/i18n/src/runtime/MessageCatalogTypes';
import {validateMessageTemplateVariables} from '@fluxer/i18n/src/runtime/MessageCatalogTypes';
const DEFAULT_LOCALE = 'en-US';
type ErrorI18nRuntimeVariables = Record<string, unknown>;
-type ErrorI18nResultArgs<TKey extends ErrorI18nKey> = TKey extends ErrorI18nKey
- ? MessageArgsForTemplate<ErrorI18nCatalog[TKey]>
- : never;
const errorI18n = createStaticI18n<ErrorI18nKey, string, ErrorI18nRuntimeVariables>(
{
@@ -54,17 +50,6 @@ function getErrorMessageResultUnsafe(
return errorI18n.getTemplate(key, locale ?? null, variables ?? {});
}
-export function getErrorMessageResult<TKey extends ErrorI18nKey>(
- key: TKey,
- locale: string | null | undefined,
- ...args: ErrorI18nResultArgs<TKey>
-): I18nResult<TKey, string> {
- return getErrorMessageResultUnsafe(key, locale, args[0] as ErrorI18nRuntimeVariables | undefined) as I18nResult<
- TKey,
- string
- >;
-}
-
function getResolvedErrorMessage(
key: ErrorI18nKey,
locale: string | null | undefined,
diff --git a/packages/errors/src/i18n/ErrorI18nCatalogIntegrity.test.ts b/packages/errors/src/i18n/ErrorI18nCatalogIntegrity.test.ts
deleted file mode 100644
index a435078dc..000000000
--- a/packages/errors/src/i18n/ErrorI18nCatalogIntegrity.test.ts
+++ /dev/null
@@ -1,185 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import * as fs from 'node:fs';
-import * as path from 'node:path';
-import {fileURLToPath} from 'node:url';
-import {getErrorMessageResult} from '@fluxer/errors/src/i18n/ErrorI18n';
-import {ERROR_I18N_LOCALE_MESSAGES} from '@fluxer/errors/src/i18n/ErrorI18nLocales';
-import {ERROR_I18N_MESSAGES, type ErrorI18nKey} from '@fluxer/errors/src/i18n/ErrorI18nMessages';
-import type {I18nResult} from '@fluxer/i18n/src/runtime/I18nTypes';
-import {extractMessageTemplateVariables} from '@fluxer/i18n/src/runtime/MessageCatalogTypes';
-import {parse, type Token} from '@messageformat/parser';
-import {describe, expect, it} from 'vitest';
-
-const WEBLATE_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), 'weblate');
-const SOURCE_SYNC_COMMAND = 'pnpm i18n:source-sync';
-
-type FlatCatalog = Record<string, string>;
-
-const SOURCE_CATALOG = ERROR_I18N_MESSAGES as FlatCatalog;
-const LOCALE_CATALOGS = ERROR_I18N_LOCALE_MESSAGES as Record<string, FlatCatalog>;
-const STATIC_LOCALES = Object.keys(LOCALE_CATALOGS).sort();
-
-type ErrorMessageProbe = (
- key: string,
- locale: string,
- variables: Record<string, number>,
-) => I18nResult<ErrorI18nKey, string>;
-
-const probeErrorMessage = getErrorMessageResult as unknown as ErrorMessageProbe;
-
-function readJsonCatalog(filePath: string): FlatCatalog {
- return JSON.parse(fs.readFileSync(filePath, 'utf8')) as FlatCatalog;
-}
-
-function quoteMessage(value: string): string {
- return value.length > 90 ? `"${value.slice(0, 90)}…"` : `"${value}"`;
-}
-
-function unionOfKeys(...catalogs: Array<FlatCatalog>): Array<string> {
- const keys = new Set<string>();
- for (const catalog of catalogs) {
- for (const key of Object.keys(catalog)) {
- keys.add(key);
- }
- }
- return [...keys].sort();
-}
-
-function parseTemplate(template: string): {tokens: Array<Token>} | {parseError: string} {
- try {
- return {tokens: parse(template)};
- } catch (error) {
- return {parseError: error instanceof Error ? error.message.split('\n')[0] : 'unknown ICU parser error'};
- }
-}
-
-function placeholdersOf(template: string): Set<string> {
- return extractMessageTemplateVariables(template);
-}
-
-function selectorWithoutOtherBranch(tokens: ReadonlyArray<Token>): string | null {
- for (const token of tokens) {
- if (token.type === 'plural' || token.type === 'selectordinal' || token.type === 'select') {
- if (!token.cases.some((branch) => branch.key === 'other')) {
- return `${token.type} on {${token.arg}}`;
- }
- for (const branch of token.cases) {
- const nested = selectorWithoutOtherBranch(branch.tokens);
- if (nested !== null) {
- return nested;
- }
- }
- }
- if (token.type === 'function' && token.param) {
- const nested = selectorWithoutOtherBranch(token.param);
- if (nested !== null) {
- return nested;
- }
- }
- }
- return null;
-}
-
-function sampleVariables(names: Iterable<string>): Record<string, number> {
- const variables: Record<string, number> = {};
- for (const name of names) {
- variables[name] = 1;
- }
- return variables;
-}
-
-function describeIcuProblem(locale: string, key: string, template: string, sourceTemplate: string): string | null {
- const parsed = parseTemplate(template);
- if ('parseError' in parsed) {
- return `${locale} / ${key}: ${quoteMessage(template)} is not a valid ICU message (${parsed.parseError}).`;
- }
- let sourcePlaceholders: Set<string>;
- let translatedPlaceholders: Set<string>;
- try {
- sourcePlaceholders = placeholdersOf(sourceTemplate);
- translatedPlaceholders = placeholdersOf(template);
- } catch (error) {
- const detail = error instanceof Error ? error.message.split('\n')[0] : 'unknown ICU parser error';
- return `${locale} / ${key}: placeholders could not be read (${detail}).`;
- }
- const dropped = [...sourcePlaceholders].filter((name) => !translatedPlaceholders.has(name)).sort();
- if (dropped.length > 0) {
- return `${locale} / ${key}: drops placeholder ${dropped.map((name) => `{${name}}`).join(', ')} that the English source fills in, so the value would be shown to users with the data missing.`;
- }
- const invented = [...translatedPlaceholders].filter((name) => !sourcePlaceholders.has(name)).sort();
- if (invented.length > 0) {
- return `${locale} / ${key}: introduces placeholder ${invented.map((name) => `{${name}}`).join(', ')} that no caller passes, so rendering it fails at runtime.`;
- }
- const selectorProblem = selectorWithoutOtherBranch(parsed.tokens);
- if (selectorProblem !== null) {
- return `${locale} / ${key}: declares a ${selectorProblem} with no "other" branch, which MessageFormat refuses to compile.`;
- }
- const result = probeErrorMessage(key, locale, sampleVariables(sourcePlaceholders));
- if (!result.ok) {
- return `${locale} / ${key}: ${quoteMessage(template)} failed to compile (${result.error.kind}: ${result.error.message.split('\n')[0]}).`;
- }
- return null;
-}
-
-describe('error i18n catalog integrity', () => {
- it('keeps weblate/messages.json byte-identical to the English source catalog', () => {
- const extracted = readJsonCatalog(path.join(WEBLATE_DIR, 'messages.json'));
- const problems: Array<string> = [];
- for (const key of unionOfKeys(SOURCE_CATALOG, extracted)) {
- const source = SOURCE_CATALOG[key];
- const translatorFacing = extracted[key];
- if (source === undefined) {
- problems.push(
- `en-US / ${key}: weblate/messages.json still offers this key to translators but ErrorI18nMessages.ts no longer defines it. Run ${SOURCE_SYNC_COMMAND}.`,
- );
- continue;
- }
- if (translatorFacing === undefined) {
- problems.push(
- `en-US / ${key}: ErrorI18nMessages.ts defines it but weblate/messages.json does not, so translators never see it. Run ${SOURCE_SYNC_COMMAND}.`,
- );
- continue;
- }
- if (translatorFacing !== source) {
- problems.push(
- `en-US / ${key}: weblate/messages.json shows translators the stale English ${quoteMessage(translatorFacing)} while ErrorI18nMessages.ts now says ${quoteMessage(source)}. Run ${SOURCE_SYNC_COMMAND}.`,
- );
- }
- }
- expect(problems).toEqual([]);
- });
-
- it('registers every weblate locale in ErrorI18nLocales.ts', () => {
- const weblateLocales = fs
- .readdirSync(path.join(WEBLATE_DIR, 'locales'))
- .filter((entry) => entry.endsWith('.json'))
- .map((entry) => entry.slice(0, -'.json'.length))
- .sort();
- expect(STATIC_LOCALES).toEqual(weblateLocales);
- });
-
- it('keeps every catalog message compilable with the placeholders its English source declares', () => {
- const problems: Array<string> = [];
- for (const key of Object.keys(SOURCE_CATALOG).sort()) {
- const problem = describeIcuProblem('en-US', key, SOURCE_CATALOG[key], SOURCE_CATALOG[key]);
- if (problem !== null) {
- problems.push(problem);
- }
- }
- for (const locale of STATIC_LOCALES) {
- const translated = LOCALE_CATALOGS[locale];
- for (const key of Object.keys(translated).sort()) {
- const source = SOURCE_CATALOG[key];
- if (source === undefined) {
- continue;
- }
- const problem = describeIcuProblem(locale, key, translated[key], source);
- if (problem !== null) {
- problems.push(problem);
- }
- }
- }
- expect(problems).toEqual([]);
- });
-});