Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions packages/i18n/src/__tests__/build.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,11 @@ import { describe, it, expect, vi } from 'vitest';

import {
parseMessagesFile,
parseMessagesObject,
generateChromeMessages,
generateChromeMessagesFile,
generateTypeFile,
generateTypeText,
} from '../build';

vi.mock('node:fs/promises');
Expand Down Expand Up @@ -198,4 +201,38 @@ describe('Built Tools', () => {
'Messages file should not contain `null` (found at "invalidField")',
);
});

it('should keep each plural form on its own count when only 0 and n are defined', () => {
const messages = parseMessagesObject({
items: { 0: 'No items', n: '$1 items' },
});

expect(generateChromeMessages(messages).items).toEqual({
message: 'No items | $1 items | $1 items',
});
});

it('should treat numeric keys without an n form as nested messages', () => {
const messages = parseMessagesObject({
errors: { 404: 'Not found', 500: 'Server error' },
});

expect(generateChromeMessages(messages)).toMatchObject({
errors_404: { message: 'Not found' },
errors_500: { message: 'Server error' },
});
expect(generateTypeText(messages)).toContain(
'"errors.404": { substitutions: 0, plural: false };',
);
});

it('should throw an error for unsupported plural keys', () => {
expect(() =>
parseMessagesObject({
items: { 1: 'One item', 2: 'Two items', n: '$1 items' },
}),
).toThrowError(
'Plural message "items" has unsupported key(s) "2". Only 0, 1, and n are supported.',
);
});
});
74 changes: 74 additions & 0 deletions packages/i18n/src/__tests__/plural.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { browser } from '@wxt-dev/browser';
import { describe, it, expect, vi } from 'vitest';

import { generateChromeMessages, parseMessagesObject } from '../build';
import { createI18n } from '../index';

vi.mock('@wxt-dev/browser', async () => {
const { vi } = await import('vitest');
return {
browser: {
i18n: {
getMessage: vi.fn(),
},
},
};
});
const getMessageMock = vi.mocked(browser.i18n.getMessage);

/** Serve the generated messages.json like `browser.i18n.getMessage` does. */
function useMessages(object: Parameters<typeof parseMessagesObject>[0]) {
const messages = generateChromeMessages(parseMessagesObject(object));
getMessageMock.mockImplementation((key, substitutions) =>
(messages[key]?.message ?? '').replace(/\$(\d)/g, (_, index) =>
String([substitutions ?? []].flat()[Number(index) - 1] ?? ''),
),
);
}

describe('plural messages from build to runtime', () => {
it.each([
[0, 'No items'],
[1, '1 items'],
[2, '2 items'],
])(
'should use the right form for %i when only 0 and n are defined',
(count, expected) => {
useMessages({ items: { 0: 'No items', n: '$1 items' } });

expect(createI18n().t('items', count)).toBe(expected);
},
);

it.each([
[0, '0 items'],
[1, 'One item'],
[2, '2 items'],
])(
'should keep the existing behavior of 1 and n for %i',
(count, expected) => {
useMessages({ items: { 1: 'One item', n: '$1 items' } });

expect(createI18n().t('items', count)).toBe(expected);
},
);

it.each([
[0, 'No items'],
[1, 'One item'],
[5, '5 items'],
])(
'should keep the existing behavior of 0, 1 and n for %i',
(count, expected) => {
useMessages({ items: { 0: 'No items', 1: 'One item', n: '$1 items' } });

expect(createI18n().t('items', count)).toBe(expected);
},
);

it('should resolve numeric nested keys', () => {
useMessages({ errors: { 404: 'Not found', 500: 'Server error' } });

expect(createI18n().t('errors.404')).toBe('Not found');
});
});
43 changes: 40 additions & 3 deletions packages/i18n/src/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,7 @@ function _parseMessagesObject(
);

if (isPluralMessage(object)) {
assertSupportedPluralKeys(object, path);
const message = Object.values(object).join('|');
const substitutions = getSubstitutionCount(message);
const namedSubstitutions = getNamedSubstitutionNames(message);
Expand Down Expand Up @@ -236,11 +237,47 @@ function _parseMessagesObject(
}

function isPluralMessage(object: Message): object is PluralMessage {
return Object.keys(object).every(
(key) => key === 'n' || isFinite(Number(key)),
// A plural message always has an `n` form. Objects with only numeric keys
// and no `n` (e.g. `{ 404: ..., 500: ... }`) are regular nested messages.
const keys = Object.keys(object);
return (
keys.includes('n') &&
keys.every((key) => key === 'n' || isFinite(Number(key)))
);
}

const SUPPORTED_PLURAL_KEYS = new Set(['0', '1', 'n']);

function assertSupportedPluralKeys(
object: PluralMessage,
path: string[],
): void {
const unsupported = Object.keys(object).filter(
(key) => !SUPPORTED_PLURAL_KEYS.has(key),
);
if (unsupported.length > 0) {
throw Error(
`Plural message "${path.join('.')}" has unsupported key(s) ${unsupported
.map((key) => `"${key}"`)
.join(', ')}. Only 0, 1, and n are supported.`,
);
}
}

/**
* The runtime picks a plural form by position: "one | n" or "zero | one | n".
* Missing forms fall back to `n` so each count gets the right form regardless
* of which keys were defined.
*/
function serializePluralMessage(
plurals: ParsedPluralMessage['plurals'],
): string {
const { 0: zero, 1: one, n } = plurals;
if (zero != null) return [zero, one ?? n, n].join(' | ');
if (one != null) return [one, n].join(' | ');
return n;
}

function isChromeMessage(object: Message): object is ChromeMessage {
return Object.keys(object).every((key) =>
ALLOWED_CHROME_MESSAGE_KEYS.has(key),
Expand Down Expand Up @@ -302,7 +339,7 @@ export function generateChromeMessages(
break;
case 'plural':
acc[key] = {
message: Object.values(message.plurals).join(' | '),
message: serializePluralMessage(message.plurals),
};
break;
case 'simple':
Expand Down
Loading