@zairakai/js-i18n 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +228 -0
- package/dist/index.cjs +183 -0
- package/dist/index.d.cts +88 -0
- package/dist/index.d.ts +88 -0
- package/dist/index.js +153 -0
- package/package.json +96 -0
- package/src/index.ts +27 -0
- package/src/pluralization.ts +87 -0
- package/src/schemas.ts +40 -0
- package/src/translator.ts +180 -0
- package/src/types.ts +42 -0
package/README.md
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
# @zairakai/js-i18n
|
|
2
|
+
|
|
3
|
+
[![Main][pipeline-main-badge]][pipeline-main-link]
|
|
4
|
+
[![Develop][pipeline-develop-badge]][pipeline-develop-link]
|
|
5
|
+
[![Coverage][coverage-badge]][coverage-link]
|
|
6
|
+
|
|
7
|
+
[![npm][npm-badge]][npm-link]
|
|
8
|
+
[![GitLab Release][gitlab-release-badge]][gitlab-release]
|
|
9
|
+
[![License][license-badge]][license]
|
|
10
|
+
|
|
11
|
+
[![Node.js][node-badge]][node]
|
|
12
|
+
[![ESLint][eslint-badge]][eslint]
|
|
13
|
+
[![Prettier][prettier-badge]][prettier]
|
|
14
|
+
|
|
15
|
+
Lightweight internationalization library with Laravel-style translation, pluralization, dot-notation keys, and multi-locale support.
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
## Features
|
|
20
|
+
|
|
21
|
+
- **Laravel-style `__()`** — familiar `:attribute` replacement and `{0} | {1} | [2,*] :count` pluralization
|
|
22
|
+
- **Dot notation keys** — navigate nested translation objects with `auth.login.title`
|
|
23
|
+
- **Multi-locale** — manage any number of locales, switch at runtime
|
|
24
|
+
- **Runtime validation** — translation data validated at runtime, invalid structures throw with a descriptive error message
|
|
25
|
+
- **Type-safe** — full TypeScript types for IDE support and static analysis
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## Install
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
npm install @zairakai/js-i18n
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
---
|
|
36
|
+
|
|
37
|
+
## Usage
|
|
38
|
+
|
|
39
|
+
### Basic translation
|
|
40
|
+
|
|
41
|
+
```typescript
|
|
42
|
+
import { createI18n } from '@zairakai/js-i18n'
|
|
43
|
+
|
|
44
|
+
const i18n = createI18n(
|
|
45
|
+
{
|
|
46
|
+
en: {
|
|
47
|
+
welcome: 'Welcome, :name!',
|
|
48
|
+
auth: {
|
|
49
|
+
login: 'Sign in',
|
|
50
|
+
logout: 'Sign out',
|
|
51
|
+
},
|
|
52
|
+
},
|
|
53
|
+
fr: {
|
|
54
|
+
welcome: 'Bienvenue, :name !',
|
|
55
|
+
auth: {
|
|
56
|
+
login: 'Se connecter',
|
|
57
|
+
logout: 'Se déconnecter',
|
|
58
|
+
},
|
|
59
|
+
},
|
|
60
|
+
},
|
|
61
|
+
'en'
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
i18n.__('welcome', { name: 'Stan' }) // "Welcome, Stan!"
|
|
65
|
+
i18n.__('auth.login') // "Sign in"
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### Pluralization
|
|
69
|
+
|
|
70
|
+
```typescript
|
|
71
|
+
import { createI18n } from '@zairakai/js-i18n'
|
|
72
|
+
|
|
73
|
+
const i18n = createI18n({
|
|
74
|
+
en: {
|
|
75
|
+
apples: '{0} No apples|{1} One apple|[2,*] :count apples',
|
|
76
|
+
files: '[0,1] :count file|[2,*] :count files',
|
|
77
|
+
},
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
i18n.__('apples', 0) // "No apples"
|
|
81
|
+
i18n.__('apples', 1) // "One apple"
|
|
82
|
+
i18n.__('apples', 5) // "5 apples"
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
### Count + replacements (case 3)
|
|
86
|
+
|
|
87
|
+
```typescript
|
|
88
|
+
i18n.__('files', 3, { extra: 'info' }) // "3 files"
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
### Managing locales at runtime
|
|
92
|
+
|
|
93
|
+
```typescript
|
|
94
|
+
i18n.setLocale('fr')
|
|
95
|
+
i18n.getLocale() // "fr"
|
|
96
|
+
i18n.getAvailableLocales() // ["en", "fr"]
|
|
97
|
+
|
|
98
|
+
i18n.setTranslations('de', { welcome: 'Willkommen, :name!' })
|
|
99
|
+
i18n.addTranslations('de', { auth: { login: 'Anmelden' } })
|
|
100
|
+
|
|
101
|
+
i18n.hasTranslation('auth.login', 'de') // true
|
|
102
|
+
i18n.hasTranslation('auth.logout', 'de') // false
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
### Error handling
|
|
106
|
+
|
|
107
|
+
Translation data is validated at runtime. Invalid structures (e.g. loading from an API or external JSON) throw an `Error` with a descriptive message indicating exactly what is wrong.
|
|
108
|
+
|
|
109
|
+
```typescript
|
|
110
|
+
import { createI18n } from '@zairakai/js-i18n'
|
|
111
|
+
|
|
112
|
+
try {
|
|
113
|
+
const data = await fetchTranslations() // unknown external data
|
|
114
|
+
const i18n = createI18n(data, 'en')
|
|
115
|
+
} catch (e) {
|
|
116
|
+
// e.message describes the invalid field and its path
|
|
117
|
+
console.error('Invalid translation data:', (e as Error).message)
|
|
118
|
+
}
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
The same applies to `setTranslations()`, `addTranslations()`, and `translate()` when replacements are malformed.
|
|
122
|
+
|
|
123
|
+
---
|
|
124
|
+
|
|
125
|
+
## Pluralization syntax
|
|
126
|
+
|
|
127
|
+
The pluralization format follows Laravel's `trans_choice` pattern exactly.
|
|
128
|
+
|
|
129
|
+
| Pattern | Matches | Example |
|
|
130
|
+
| --------------- | ---------------------------- | ------------------------------------ |
|
|
131
|
+
| `{0}` | Exactly 0 | `{0} No items` |
|
|
132
|
+
| `{1}` | Exactly 1 | `{1} One item` |
|
|
133
|
+
| `{n}` | Exactly n | `{5} Exactly five` |
|
|
134
|
+
| `[2,*]` | 2 and above | `[2,*] :count items` |
|
|
135
|
+
| `[0,1]` | 0 or 1 | `[0,1] :count file` |
|
|
136
|
+
| `[1,10]` | Between 1 and 10 (inclusive) | `[1,10] a few items` |
|
|
137
|
+
|
|
138
|
+
Forms are separated by `|`. The `:count` placeholder is automatically replaced by the count value.
|
|
139
|
+
|
|
140
|
+
```typescript
|
|
141
|
+
// Full example
|
|
142
|
+
'{0} No apples|{1} One apple|[2,*] :count apples'
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
---
|
|
146
|
+
|
|
147
|
+
## API Reference
|
|
148
|
+
|
|
149
|
+
### Factory functions
|
|
150
|
+
|
|
151
|
+
| Function | Description |
|
|
152
|
+
| --- | --- |
|
|
153
|
+
| `createI18n(translations?, locale?)` | Creates a translator instance (alias, preferred). |
|
|
154
|
+
| `createTranslator(translations?, locale?)` | Creates a translator instance (explicit name). |
|
|
155
|
+
|
|
156
|
+
Both return a `Translator` instance. Default locale is `'en'`.
|
|
157
|
+
|
|
158
|
+
### Translator methods
|
|
159
|
+
|
|
160
|
+
| Method | Description |
|
|
161
|
+
| --------------------------------------- | ------------------------------------------------------- |
|
|
162
|
+
| `__(path, replacements?)` | Translate a key with optional replacements. |
|
|
163
|
+
| `__(path, count, replacements?)` | Translate with pluralization count. |
|
|
164
|
+
| `translate(path, replacements?)` | Alias for `__`. |
|
|
165
|
+
| `translate(path, count, replacements?)` | Alias for `__` with count. |
|
|
166
|
+
| `setLocale(locale)` | Set the active locale. |
|
|
167
|
+
| `getLocale()` | Get the active locale. |
|
|
168
|
+
| `setTranslations(locale, translations)` | Replace all translations for a locale. |
|
|
169
|
+
| `addTranslations(locale, translations)` | Merge translations into an existing locale. |
|
|
170
|
+
| `hasTranslation(path, locale?)` | Check if a translation key exists (uses active locale). |
|
|
171
|
+
| `getAvailableLocales()` | Return all registered locale codes. |
|
|
172
|
+
|
|
173
|
+
### Pluralization utilities
|
|
174
|
+
|
|
175
|
+
| Function | Description |
|
|
176
|
+
| ---------------------------------- | ----------------------------------------------- |
|
|
177
|
+
| `applyPluralization(value, count)` | Apply pluralization to a raw string with count. |
|
|
178
|
+
| `selectPluralForm(forms, count)` | Select the correct form from a pre-split array. |
|
|
179
|
+
|
|
180
|
+
---
|
|
181
|
+
|
|
182
|
+
## Development
|
|
183
|
+
|
|
184
|
+
```bash
|
|
185
|
+
npm install # install dependencies
|
|
186
|
+
make quality # full quality gate (lint, format, typecheck, tests)
|
|
187
|
+
make test # run vitest
|
|
188
|
+
make test-coverage # run vitest with coverage
|
|
189
|
+
make ci # run CI validation locally
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
See [CONTRIBUTING.md](./CONTRIBUTING.md) for the full development workflow.
|
|
193
|
+
|
|
194
|
+
---
|
|
195
|
+
|
|
196
|
+
## Getting Help
|
|
197
|
+
|
|
198
|
+
[![License][license-badge]][license]
|
|
199
|
+
[![Security Policy][security-badge]][security]
|
|
200
|
+
[![Issues][issues-badge]][issues]
|
|
201
|
+
|
|
202
|
+
**Made with ❤️ by [Zairakai][ecosystem]**
|
|
203
|
+
|
|
204
|
+
<!-- Reference Links -->
|
|
205
|
+
|
|
206
|
+
[pipeline-main-badge]: https://gitlab.com/zairakai/npm-packages/js-i18n/badges/main/pipeline.svg?ignore_skipped=true&key_text=Main
|
|
207
|
+
[pipeline-main-link]: https://gitlab.com/zairakai/npm-packages/js-i18n/-/commits/main
|
|
208
|
+
[pipeline-develop-badge]: https://gitlab.com/zairakai/npm-packages/js-i18n/badges/develop/pipeline.svg?ignore_skipped=true&key_text=Develop
|
|
209
|
+
[pipeline-develop-link]: https://gitlab.com/zairakai/npm-packages/js-i18n/-/commits/develop
|
|
210
|
+
[npm-badge]: https://img.shields.io/npm/v/@zairakai/js-i18n
|
|
211
|
+
[npm-link]: https://www.npmjs.com/package/@zairakai/js-i18n
|
|
212
|
+
[gitlab-release-badge]: https://img.shields.io/gitlab/v/release/zairakai/npm-packages/js-i18n?logo=gitlab
|
|
213
|
+
[gitlab-release]: https://gitlab.com/zairakai/npm-packages/js-i18n/-/releases
|
|
214
|
+
[coverage-badge]: https://gitlab.com/zairakai/npm-packages/js-i18n/badges/main/coverage.svg
|
|
215
|
+
[coverage-link]: https://gitlab.com/zairakai/npm-packages/js-i18n/-/pipelines?ref=main
|
|
216
|
+
[license-badge]: https://img.shields.io/badge/license-MIT-blue.svg
|
|
217
|
+
[license]: ./LICENSE
|
|
218
|
+
[security-badge]: https://img.shields.io/badge/security-scanned-green.svg
|
|
219
|
+
[security]: ./SECURITY.md
|
|
220
|
+
[issues-badge]: https://img.shields.io/gitlab/issues/open-raw/zairakai%2Fnpm-packages%2Fi18n?logo=gitlab&label=Issues
|
|
221
|
+
[issues]: https://gitlab.com/zairakai/npm-packages/js-i18n/-/issues
|
|
222
|
+
[node-badge]: https://img.shields.io/badge/node.js-%3E%3D22-green.svg?logo=node.js
|
|
223
|
+
[node]: https://nodejs.org
|
|
224
|
+
[eslint-badge]: https://img.shields.io/badge/code%20style-eslint-4B32C3.svg?logo=eslint
|
|
225
|
+
[eslint]: https://eslint.org
|
|
226
|
+
[prettier-badge]: https://img.shields.io/badge/formatter-prettier-F7B93E.svg?logo=prettier
|
|
227
|
+
[prettier]: https://prettier.io
|
|
228
|
+
[ecosystem]: https://gitlab.com/zairakai
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var src_exports = {};
|
|
22
|
+
__export(src_exports, {
|
|
23
|
+
applyPluralization: () => applyPluralization,
|
|
24
|
+
createI18n: () => createI18n,
|
|
25
|
+
createTranslator: () => createTranslator,
|
|
26
|
+
selectPluralForm: () => selectPluralForm
|
|
27
|
+
});
|
|
28
|
+
module.exports = __toCommonJS(src_exports);
|
|
29
|
+
|
|
30
|
+
// src/pluralization.ts
|
|
31
|
+
var selectPluralForm = (message, count) => {
|
|
32
|
+
const parts = message.split("|");
|
|
33
|
+
for (const part of parts) {
|
|
34
|
+
const trimmedPart = part.trim();
|
|
35
|
+
const exactMatch2 = trimmedPart.match(/^{\s*(\d+)\s*}\s*(.*)$/);
|
|
36
|
+
const rangeMatch2 = trimmedPart.match(/^\[\s*(\d+|\*)\s*,\s*(\d+|\*)\s*\]\s*(.*)$/);
|
|
37
|
+
if (exactMatch2) {
|
|
38
|
+
const exactNumber = parseInt(exactMatch2[1], 10);
|
|
39
|
+
if (count === exactNumber) {
|
|
40
|
+
return exactMatch2[2].trim();
|
|
41
|
+
}
|
|
42
|
+
} else if (rangeMatch2) {
|
|
43
|
+
const min = "*" === rangeMatch2[1] ? -Infinity : parseInt(rangeMatch2[1], 10);
|
|
44
|
+
const max = "*" === rangeMatch2[2] ? Infinity : parseInt(rangeMatch2[2], 10);
|
|
45
|
+
if (count >= min && count <= max) {
|
|
46
|
+
return rangeMatch2[3].trim();
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
const simpleParts = parts.filter((part) => {
|
|
51
|
+
const trimmed = part.trim();
|
|
52
|
+
return !trimmed.match(/^[{\[]/);
|
|
53
|
+
});
|
|
54
|
+
if (2 <= simpleParts.length) {
|
|
55
|
+
return 1 === count ? simpleParts[0].trim() : simpleParts[1].trim();
|
|
56
|
+
} else if (1 === simpleParts.length) {
|
|
57
|
+
return simpleParts[0].trim();
|
|
58
|
+
}
|
|
59
|
+
const firstPart = parts[0].trim();
|
|
60
|
+
const exactMatch = firstPart.match(/^{\s*(\d+)\s*}\s*(.*)$/);
|
|
61
|
+
const rangeMatch = firstPart.match(/^\[\s*(\d+|\*)\s*,\s*(\d+|\*)\s*\]\s*(.*)$/);
|
|
62
|
+
if (exactMatch) {
|
|
63
|
+
return exactMatch[2].trim();
|
|
64
|
+
} else if (rangeMatch) {
|
|
65
|
+
return rangeMatch[3].trim();
|
|
66
|
+
}
|
|
67
|
+
return firstPart;
|
|
68
|
+
};
|
|
69
|
+
var applyPluralization = (translation, count) => {
|
|
70
|
+
if ("string" === typeof translation && translation.includes("|") && null !== count) {
|
|
71
|
+
return selectPluralForm(translation, count);
|
|
72
|
+
}
|
|
73
|
+
return translation;
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
// src/schemas.ts
|
|
77
|
+
var import_zod = require("zod");
|
|
78
|
+
var TranslationValueSchema = import_zod.z.lazy(
|
|
79
|
+
() => import_zod.z.union([import_zod.z.string(), import_zod.z.record(import_zod.z.string(), TranslationValueSchema)])
|
|
80
|
+
);
|
|
81
|
+
var TranslationObjectSchema = import_zod.z.record(
|
|
82
|
+
import_zod.z.string(),
|
|
83
|
+
TranslationValueSchema
|
|
84
|
+
);
|
|
85
|
+
var TranslationDataSchema = import_zod.z.record(import_zod.z.string(), TranslationObjectSchema);
|
|
86
|
+
var ReplacementParametersSchema = import_zod.z.record(
|
|
87
|
+
import_zod.z.string(),
|
|
88
|
+
import_zod.z.union([import_zod.z.string(), import_zod.z.number()])
|
|
89
|
+
);
|
|
90
|
+
var CountOrReplacementsSchema = import_zod.z.union([import_zod.z.number(), ReplacementParametersSchema]);
|
|
91
|
+
|
|
92
|
+
// src/translator.ts
|
|
93
|
+
var createTranslator = (translations = {}, locale = "en") => {
|
|
94
|
+
const currentTranslations = TranslationDataSchema.parse(translations);
|
|
95
|
+
let currentLocale = locale;
|
|
96
|
+
const translate = (path, countOrReplacements = {}, replacements = {}) => {
|
|
97
|
+
CountOrReplacementsSchema.parse(countOrReplacements);
|
|
98
|
+
ReplacementParametersSchema.parse(replacements);
|
|
99
|
+
let count = null;
|
|
100
|
+
let actualReplacements = replacements;
|
|
101
|
+
if ("number" === typeof countOrReplacements) {
|
|
102
|
+
count = countOrReplacements;
|
|
103
|
+
actualReplacements = { count: countOrReplacements, ...replacements };
|
|
104
|
+
} else {
|
|
105
|
+
actualReplacements = { ...countOrReplacements, ...replacements };
|
|
106
|
+
}
|
|
107
|
+
if (!currentTranslations[currentLocale]) {
|
|
108
|
+
return path;
|
|
109
|
+
}
|
|
110
|
+
const segments = path.split(".");
|
|
111
|
+
let translation = currentTranslations[currentLocale];
|
|
112
|
+
for (const segment of segments) {
|
|
113
|
+
if (translation && "object" === typeof translation && Object.prototype.hasOwnProperty.call(translation, segment)) {
|
|
114
|
+
translation = translation[segment];
|
|
115
|
+
} else {
|
|
116
|
+
return path;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
if ("string" === typeof translation) {
|
|
120
|
+
const pluralizedTranslation = applyPluralization(translation, count);
|
|
121
|
+
const result = pluralizedTranslation.replace(/:(\w+)/g, (match, key) => {
|
|
122
|
+
return Object.prototype.hasOwnProperty.call(actualReplacements, key) ? String(actualReplacements[key]) : match;
|
|
123
|
+
}).replace(/{(\w+)}/g, (match, key) => {
|
|
124
|
+
return Object.prototype.hasOwnProperty.call(actualReplacements, key) ? String(actualReplacements[key]) : match;
|
|
125
|
+
});
|
|
126
|
+
return result;
|
|
127
|
+
}
|
|
128
|
+
return path;
|
|
129
|
+
};
|
|
130
|
+
const setLocale = (newLocale) => {
|
|
131
|
+
currentLocale = newLocale;
|
|
132
|
+
};
|
|
133
|
+
const getLocale = () => currentLocale;
|
|
134
|
+
const setTranslations = (locale2, translations2) => {
|
|
135
|
+
currentTranslations[locale2] = TranslationObjectSchema.parse(translations2);
|
|
136
|
+
};
|
|
137
|
+
const addTranslations = (locale2, translations2) => {
|
|
138
|
+
const validated = TranslationObjectSchema.parse(translations2);
|
|
139
|
+
if (!currentTranslations[locale2]) {
|
|
140
|
+
currentTranslations[locale2] = {};
|
|
141
|
+
}
|
|
142
|
+
currentTranslations[locale2] = { ...currentTranslations[locale2], ...validated };
|
|
143
|
+
};
|
|
144
|
+
const hasTranslation = (path, locale2 = null) => {
|
|
145
|
+
const checkLocale = locale2 ?? currentLocale;
|
|
146
|
+
if (!currentTranslations[checkLocale]) {
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
const segments = path.split(".");
|
|
150
|
+
let current = currentTranslations[checkLocale];
|
|
151
|
+
for (const segment of segments) {
|
|
152
|
+
if (current && "object" === typeof current && segment in current) {
|
|
153
|
+
current = current[segment];
|
|
154
|
+
} else {
|
|
155
|
+
return false;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return "string" === typeof current;
|
|
159
|
+
};
|
|
160
|
+
const getAvailableLocales = () => Object.keys(currentTranslations);
|
|
161
|
+
return {
|
|
162
|
+
__: translate,
|
|
163
|
+
translate,
|
|
164
|
+
setLocale,
|
|
165
|
+
getLocale,
|
|
166
|
+
setTranslations,
|
|
167
|
+
addTranslations,
|
|
168
|
+
hasTranslation,
|
|
169
|
+
getAvailableLocales
|
|
170
|
+
};
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
// src/index.ts
|
|
174
|
+
var createI18n = (translations = {}, locale = "en") => {
|
|
175
|
+
return createTranslator(translations, locale);
|
|
176
|
+
};
|
|
177
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
178
|
+
0 && (module.exports = {
|
|
179
|
+
applyPluralization,
|
|
180
|
+
createI18n,
|
|
181
|
+
createTranslator,
|
|
182
|
+
selectPluralForm
|
|
183
|
+
});
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pluralization utilities for Laravel-style translation strings
|
|
3
|
+
* Handles complex pluralization rules with conditions and ranges
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* Selects the appropriate plural form based on count
|
|
7
|
+
* Supports Laravel formats:
|
|
8
|
+
* - Simple: "item|items"
|
|
9
|
+
* - With conditions: "{0} none|{1} one|[2,*] many"
|
|
10
|
+
* - With ranges: "[1,19] some|[20,*] many"
|
|
11
|
+
*
|
|
12
|
+
* @param message - Translation string with plural forms
|
|
13
|
+
* @param count - Count to determine plural form
|
|
14
|
+
* @returns Selected plural form
|
|
15
|
+
*/
|
|
16
|
+
declare const selectPluralForm: (message: string, count: number) => string;
|
|
17
|
+
/**
|
|
18
|
+
* Apply pluralization rules to a translation
|
|
19
|
+
* @param translation - Translation string
|
|
20
|
+
* @param count - Count for pluralization
|
|
21
|
+
* @returns Pluralized translation
|
|
22
|
+
*/
|
|
23
|
+
declare const applyPluralization: (translation: string, count: number | null) => string;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Type definitions for the i18n library
|
|
27
|
+
*/
|
|
28
|
+
/** Object containing nested translation values */
|
|
29
|
+
interface TranslationObject {
|
|
30
|
+
[key: string]: string | TranslationObject;
|
|
31
|
+
}
|
|
32
|
+
/** Translation data for multiple locales */
|
|
33
|
+
type TranslationData = Record<string, TranslationObject>;
|
|
34
|
+
/** Parameters that can be used to replace placeholders in translations */
|
|
35
|
+
type ReplacementParameters = Record<string, string | number>;
|
|
36
|
+
/** Translator instance interface */
|
|
37
|
+
interface Translator {
|
|
38
|
+
/** Main translation function (alias for translate) */
|
|
39
|
+
__: TranslateFunction;
|
|
40
|
+
/** Main translation function */
|
|
41
|
+
translate: TranslateFunction;
|
|
42
|
+
/** Set the current locale */
|
|
43
|
+
setLocale: (locale: string) => void;
|
|
44
|
+
/** Get the current locale */
|
|
45
|
+
getLocale: () => string;
|
|
46
|
+
/** Set translations for a specific locale */
|
|
47
|
+
setTranslations: (locale: string, translations: TranslationObject) => void;
|
|
48
|
+
/** Add translations to an existing locale */
|
|
49
|
+
addTranslations: (locale: string, translations: TranslationObject) => void;
|
|
50
|
+
/** Check if a translation key exists */
|
|
51
|
+
hasTranslation: (path: string, locale?: string | null) => boolean;
|
|
52
|
+
/** Get all available locales */
|
|
53
|
+
getAvailableLocales: () => string[];
|
|
54
|
+
}
|
|
55
|
+
/** Translation function signature with overloads */
|
|
56
|
+
interface TranslateFunction {
|
|
57
|
+
/** Translate with replacements only */
|
|
58
|
+
(path: string, replacements?: ReplacementParameters): string;
|
|
59
|
+
/** Translate with count for pluralization */
|
|
60
|
+
(path: string, count: number, replacements?: ReplacementParameters): string;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Core translation functionality
|
|
65
|
+
*/
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Creates a translator instance
|
|
69
|
+
* @param translations - Translation object
|
|
70
|
+
* @param locale - Current locale
|
|
71
|
+
* @returns Translator instance
|
|
72
|
+
*/
|
|
73
|
+
declare const createTranslator: (translations?: TranslationData, locale?: string) => Translator;
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* @zairakai/npm-i18n
|
|
77
|
+
* Lightweight internationalization library with Laravel-style features
|
|
78
|
+
*/
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Create a quick translator instance
|
|
82
|
+
* @param translations - Translation object
|
|
83
|
+
* @param locale - Default locale
|
|
84
|
+
* @returns Translator instance with __ function
|
|
85
|
+
*/
|
|
86
|
+
declare const createI18n: (translations?: TranslationData, locale?: string) => Translator;
|
|
87
|
+
|
|
88
|
+
export { type ReplacementParameters, type TranslateFunction, type TranslationData, type TranslationObject, type Translator, applyPluralization, createI18n, createTranslator, selectPluralForm };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pluralization utilities for Laravel-style translation strings
|
|
3
|
+
* Handles complex pluralization rules with conditions and ranges
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* Selects the appropriate plural form based on count
|
|
7
|
+
* Supports Laravel formats:
|
|
8
|
+
* - Simple: "item|items"
|
|
9
|
+
* - With conditions: "{0} none|{1} one|[2,*] many"
|
|
10
|
+
* - With ranges: "[1,19] some|[20,*] many"
|
|
11
|
+
*
|
|
12
|
+
* @param message - Translation string with plural forms
|
|
13
|
+
* @param count - Count to determine plural form
|
|
14
|
+
* @returns Selected plural form
|
|
15
|
+
*/
|
|
16
|
+
declare const selectPluralForm: (message: string, count: number) => string;
|
|
17
|
+
/**
|
|
18
|
+
* Apply pluralization rules to a translation
|
|
19
|
+
* @param translation - Translation string
|
|
20
|
+
* @param count - Count for pluralization
|
|
21
|
+
* @returns Pluralized translation
|
|
22
|
+
*/
|
|
23
|
+
declare const applyPluralization: (translation: string, count: number | null) => string;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Type definitions for the i18n library
|
|
27
|
+
*/
|
|
28
|
+
/** Object containing nested translation values */
|
|
29
|
+
interface TranslationObject {
|
|
30
|
+
[key: string]: string | TranslationObject;
|
|
31
|
+
}
|
|
32
|
+
/** Translation data for multiple locales */
|
|
33
|
+
type TranslationData = Record<string, TranslationObject>;
|
|
34
|
+
/** Parameters that can be used to replace placeholders in translations */
|
|
35
|
+
type ReplacementParameters = Record<string, string | number>;
|
|
36
|
+
/** Translator instance interface */
|
|
37
|
+
interface Translator {
|
|
38
|
+
/** Main translation function (alias for translate) */
|
|
39
|
+
__: TranslateFunction;
|
|
40
|
+
/** Main translation function */
|
|
41
|
+
translate: TranslateFunction;
|
|
42
|
+
/** Set the current locale */
|
|
43
|
+
setLocale: (locale: string) => void;
|
|
44
|
+
/** Get the current locale */
|
|
45
|
+
getLocale: () => string;
|
|
46
|
+
/** Set translations for a specific locale */
|
|
47
|
+
setTranslations: (locale: string, translations: TranslationObject) => void;
|
|
48
|
+
/** Add translations to an existing locale */
|
|
49
|
+
addTranslations: (locale: string, translations: TranslationObject) => void;
|
|
50
|
+
/** Check if a translation key exists */
|
|
51
|
+
hasTranslation: (path: string, locale?: string | null) => boolean;
|
|
52
|
+
/** Get all available locales */
|
|
53
|
+
getAvailableLocales: () => string[];
|
|
54
|
+
}
|
|
55
|
+
/** Translation function signature with overloads */
|
|
56
|
+
interface TranslateFunction {
|
|
57
|
+
/** Translate with replacements only */
|
|
58
|
+
(path: string, replacements?: ReplacementParameters): string;
|
|
59
|
+
/** Translate with count for pluralization */
|
|
60
|
+
(path: string, count: number, replacements?: ReplacementParameters): string;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Core translation functionality
|
|
65
|
+
*/
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Creates a translator instance
|
|
69
|
+
* @param translations - Translation object
|
|
70
|
+
* @param locale - Current locale
|
|
71
|
+
* @returns Translator instance
|
|
72
|
+
*/
|
|
73
|
+
declare const createTranslator: (translations?: TranslationData, locale?: string) => Translator;
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* @zairakai/npm-i18n
|
|
77
|
+
* Lightweight internationalization library with Laravel-style features
|
|
78
|
+
*/
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Create a quick translator instance
|
|
82
|
+
* @param translations - Translation object
|
|
83
|
+
* @param locale - Default locale
|
|
84
|
+
* @returns Translator instance with __ function
|
|
85
|
+
*/
|
|
86
|
+
declare const createI18n: (translations?: TranslationData, locale?: string) => Translator;
|
|
87
|
+
|
|
88
|
+
export { type ReplacementParameters, type TranslateFunction, type TranslationData, type TranslationObject, type Translator, applyPluralization, createI18n, createTranslator, selectPluralForm };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// src/pluralization.ts
|
|
2
|
+
var selectPluralForm = (message, count) => {
|
|
3
|
+
const parts = message.split("|");
|
|
4
|
+
for (const part of parts) {
|
|
5
|
+
const trimmedPart = part.trim();
|
|
6
|
+
const exactMatch2 = trimmedPart.match(/^{\s*(\d+)\s*}\s*(.*)$/);
|
|
7
|
+
const rangeMatch2 = trimmedPart.match(/^\[\s*(\d+|\*)\s*,\s*(\d+|\*)\s*\]\s*(.*)$/);
|
|
8
|
+
if (exactMatch2) {
|
|
9
|
+
const exactNumber = parseInt(exactMatch2[1], 10);
|
|
10
|
+
if (count === exactNumber) {
|
|
11
|
+
return exactMatch2[2].trim();
|
|
12
|
+
}
|
|
13
|
+
} else if (rangeMatch2) {
|
|
14
|
+
const min = "*" === rangeMatch2[1] ? -Infinity : parseInt(rangeMatch2[1], 10);
|
|
15
|
+
const max = "*" === rangeMatch2[2] ? Infinity : parseInt(rangeMatch2[2], 10);
|
|
16
|
+
if (count >= min && count <= max) {
|
|
17
|
+
return rangeMatch2[3].trim();
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
const simpleParts = parts.filter((part) => {
|
|
22
|
+
const trimmed = part.trim();
|
|
23
|
+
return !trimmed.match(/^[{\[]/);
|
|
24
|
+
});
|
|
25
|
+
if (2 <= simpleParts.length) {
|
|
26
|
+
return 1 === count ? simpleParts[0].trim() : simpleParts[1].trim();
|
|
27
|
+
} else if (1 === simpleParts.length) {
|
|
28
|
+
return simpleParts[0].trim();
|
|
29
|
+
}
|
|
30
|
+
const firstPart = parts[0].trim();
|
|
31
|
+
const exactMatch = firstPart.match(/^{\s*(\d+)\s*}\s*(.*)$/);
|
|
32
|
+
const rangeMatch = firstPart.match(/^\[\s*(\d+|\*)\s*,\s*(\d+|\*)\s*\]\s*(.*)$/);
|
|
33
|
+
if (exactMatch) {
|
|
34
|
+
return exactMatch[2].trim();
|
|
35
|
+
} else if (rangeMatch) {
|
|
36
|
+
return rangeMatch[3].trim();
|
|
37
|
+
}
|
|
38
|
+
return firstPart;
|
|
39
|
+
};
|
|
40
|
+
var applyPluralization = (translation, count) => {
|
|
41
|
+
if ("string" === typeof translation && translation.includes("|") && null !== count) {
|
|
42
|
+
return selectPluralForm(translation, count);
|
|
43
|
+
}
|
|
44
|
+
return translation;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
// src/schemas.ts
|
|
48
|
+
import { z } from "zod";
|
|
49
|
+
var TranslationValueSchema = z.lazy(
|
|
50
|
+
() => z.union([z.string(), z.record(z.string(), TranslationValueSchema)])
|
|
51
|
+
);
|
|
52
|
+
var TranslationObjectSchema = z.record(
|
|
53
|
+
z.string(),
|
|
54
|
+
TranslationValueSchema
|
|
55
|
+
);
|
|
56
|
+
var TranslationDataSchema = z.record(z.string(), TranslationObjectSchema);
|
|
57
|
+
var ReplacementParametersSchema = z.record(
|
|
58
|
+
z.string(),
|
|
59
|
+
z.union([z.string(), z.number()])
|
|
60
|
+
);
|
|
61
|
+
var CountOrReplacementsSchema = z.union([z.number(), ReplacementParametersSchema]);
|
|
62
|
+
|
|
63
|
+
// src/translator.ts
|
|
64
|
+
var createTranslator = (translations = {}, locale = "en") => {
|
|
65
|
+
const currentTranslations = TranslationDataSchema.parse(translations);
|
|
66
|
+
let currentLocale = locale;
|
|
67
|
+
const translate = (path, countOrReplacements = {}, replacements = {}) => {
|
|
68
|
+
CountOrReplacementsSchema.parse(countOrReplacements);
|
|
69
|
+
ReplacementParametersSchema.parse(replacements);
|
|
70
|
+
let count = null;
|
|
71
|
+
let actualReplacements = replacements;
|
|
72
|
+
if ("number" === typeof countOrReplacements) {
|
|
73
|
+
count = countOrReplacements;
|
|
74
|
+
actualReplacements = { count: countOrReplacements, ...replacements };
|
|
75
|
+
} else {
|
|
76
|
+
actualReplacements = { ...countOrReplacements, ...replacements };
|
|
77
|
+
}
|
|
78
|
+
if (!currentTranslations[currentLocale]) {
|
|
79
|
+
return path;
|
|
80
|
+
}
|
|
81
|
+
const segments = path.split(".");
|
|
82
|
+
let translation = currentTranslations[currentLocale];
|
|
83
|
+
for (const segment of segments) {
|
|
84
|
+
if (translation && "object" === typeof translation && Object.prototype.hasOwnProperty.call(translation, segment)) {
|
|
85
|
+
translation = translation[segment];
|
|
86
|
+
} else {
|
|
87
|
+
return path;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if ("string" === typeof translation) {
|
|
91
|
+
const pluralizedTranslation = applyPluralization(translation, count);
|
|
92
|
+
const result = pluralizedTranslation.replace(/:(\w+)/g, (match, key) => {
|
|
93
|
+
return Object.prototype.hasOwnProperty.call(actualReplacements, key) ? String(actualReplacements[key]) : match;
|
|
94
|
+
}).replace(/{(\w+)}/g, (match, key) => {
|
|
95
|
+
return Object.prototype.hasOwnProperty.call(actualReplacements, key) ? String(actualReplacements[key]) : match;
|
|
96
|
+
});
|
|
97
|
+
return result;
|
|
98
|
+
}
|
|
99
|
+
return path;
|
|
100
|
+
};
|
|
101
|
+
const setLocale = (newLocale) => {
|
|
102
|
+
currentLocale = newLocale;
|
|
103
|
+
};
|
|
104
|
+
const getLocale = () => currentLocale;
|
|
105
|
+
const setTranslations = (locale2, translations2) => {
|
|
106
|
+
currentTranslations[locale2] = TranslationObjectSchema.parse(translations2);
|
|
107
|
+
};
|
|
108
|
+
const addTranslations = (locale2, translations2) => {
|
|
109
|
+
const validated = TranslationObjectSchema.parse(translations2);
|
|
110
|
+
if (!currentTranslations[locale2]) {
|
|
111
|
+
currentTranslations[locale2] = {};
|
|
112
|
+
}
|
|
113
|
+
currentTranslations[locale2] = { ...currentTranslations[locale2], ...validated };
|
|
114
|
+
};
|
|
115
|
+
const hasTranslation = (path, locale2 = null) => {
|
|
116
|
+
const checkLocale = locale2 ?? currentLocale;
|
|
117
|
+
if (!currentTranslations[checkLocale]) {
|
|
118
|
+
return false;
|
|
119
|
+
}
|
|
120
|
+
const segments = path.split(".");
|
|
121
|
+
let current = currentTranslations[checkLocale];
|
|
122
|
+
for (const segment of segments) {
|
|
123
|
+
if (current && "object" === typeof current && segment in current) {
|
|
124
|
+
current = current[segment];
|
|
125
|
+
} else {
|
|
126
|
+
return false;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return "string" === typeof current;
|
|
130
|
+
};
|
|
131
|
+
const getAvailableLocales = () => Object.keys(currentTranslations);
|
|
132
|
+
return {
|
|
133
|
+
__: translate,
|
|
134
|
+
translate,
|
|
135
|
+
setLocale,
|
|
136
|
+
getLocale,
|
|
137
|
+
setTranslations,
|
|
138
|
+
addTranslations,
|
|
139
|
+
hasTranslation,
|
|
140
|
+
getAvailableLocales
|
|
141
|
+
};
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
// src/index.ts
|
|
145
|
+
var createI18n = (translations = {}, locale = "en") => {
|
|
146
|
+
return createTranslator(translations, locale);
|
|
147
|
+
};
|
|
148
|
+
export {
|
|
149
|
+
applyPluralization,
|
|
150
|
+
createI18n,
|
|
151
|
+
createTranslator,
|
|
152
|
+
selectPluralForm
|
|
153
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@zairakai/js-i18n",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Lightweight internationalization library with Laravel-style translation, pluralization, dot-notation keys, and multi-locale support",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"i18n",
|
|
7
|
+
"internationalization",
|
|
8
|
+
"localization",
|
|
9
|
+
"pluralization",
|
|
10
|
+
"translations",
|
|
11
|
+
"laravel-like",
|
|
12
|
+
"fluent",
|
|
13
|
+
"typescript"
|
|
14
|
+
],
|
|
15
|
+
"homepage": "https://gitlab.com/zairakai/npm-packages/js-i18n",
|
|
16
|
+
"bugs": {
|
|
17
|
+
"url": "https://gitlab.com/zairakai/npm-packages/js-i18n/-/issues",
|
|
18
|
+
"email": "contact-project+zairakai-npm-packages-js-i18n-80190292-issue-@incoming.gitlab.com"
|
|
19
|
+
},
|
|
20
|
+
"repository": {
|
|
21
|
+
"type": "git",
|
|
22
|
+
"url": "git+https://gitlab.com/zairakai/npm-packages/js-i18n.git"
|
|
23
|
+
},
|
|
24
|
+
"funding": [
|
|
25
|
+
{
|
|
26
|
+
"type": "patreon",
|
|
27
|
+
"url": "https://www.patreon.com/c/zairakai"
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
"type": "twitch",
|
|
31
|
+
"url": "https://www.twitch.tv/zairakai"
|
|
32
|
+
}
|
|
33
|
+
],
|
|
34
|
+
"license": "MIT",
|
|
35
|
+
"author": "Stanislas Poisson <stanislas.p@the-white-rabbits.fr> (https://the-white-rabbits.fr)",
|
|
36
|
+
"contributors": [
|
|
37
|
+
{
|
|
38
|
+
"name": "Stanislas Poisson",
|
|
39
|
+
"url": "https://gitlab.com/zairakai",
|
|
40
|
+
"role": "Maintainer"
|
|
41
|
+
}
|
|
42
|
+
],
|
|
43
|
+
"type": "module",
|
|
44
|
+
"exports": {
|
|
45
|
+
".": {
|
|
46
|
+
"types": "./dist/index.d.ts",
|
|
47
|
+
"import": "./dist/index.js",
|
|
48
|
+
"require": "./dist/index.cjs"
|
|
49
|
+
}
|
|
50
|
+
},
|
|
51
|
+
"main": "./dist/index.cjs",
|
|
52
|
+
"types": "./dist/index.d.ts",
|
|
53
|
+
"files": [
|
|
54
|
+
"dist",
|
|
55
|
+
"src",
|
|
56
|
+
"LICENSE",
|
|
57
|
+
"README.md"
|
|
58
|
+
],
|
|
59
|
+
"scripts": {
|
|
60
|
+
"build": "bash node_modules/@zairakai/js-dev-tools/scripts/build.sh",
|
|
61
|
+
"eslint": "bash node_modules/@zairakai/js-dev-tools/scripts/eslint.sh",
|
|
62
|
+
"eslint:fix": "bash node_modules/@zairakai/js-dev-tools/scripts/eslint-fix.sh",
|
|
63
|
+
"markdownlint": "bash node_modules/@zairakai/js-dev-tools/scripts/markdownlint.sh",
|
|
64
|
+
"markdownlint:fix": "bash node_modules/@zairakai/js-dev-tools/scripts/markdownlint-fix.sh",
|
|
65
|
+
"normalize": "make package-normalize",
|
|
66
|
+
"package:validate": "make package-validate",
|
|
67
|
+
"postinstall": "bash node_modules/@zairakai/js-dev-tools/scripts/setup-project.sh --silent || true",
|
|
68
|
+
"prettier": "bash node_modules/@zairakai/js-dev-tools/scripts/prettier.sh",
|
|
69
|
+
"prettier:fix": "bash node_modules/@zairakai/js-dev-tools/scripts/prettier-fix.sh",
|
|
70
|
+
"setup": "bash node_modules/@zairakai/js-dev-tools/scripts/setup-project.sh",
|
|
71
|
+
"stylelint": "bash node_modules/@zairakai/js-dev-tools/scripts/stylelint.sh",
|
|
72
|
+
"stylelint:fix": "bash node_modules/@zairakai/js-dev-tools/scripts/stylelint-fix.sh",
|
|
73
|
+
"test": "make test-all",
|
|
74
|
+
"validate": "make quality"
|
|
75
|
+
},
|
|
76
|
+
"dependencies": {
|
|
77
|
+
"zod": "^4.0.0"
|
|
78
|
+
},
|
|
79
|
+
"devDependencies": {
|
|
80
|
+
"@types/node": "^25.0.0",
|
|
81
|
+
"@vitest/coverage-v8": "^4.0.0",
|
|
82
|
+
"@zairakai/js-dev-tools": "^1.0.0",
|
|
83
|
+
"knip": "^5.86.0",
|
|
84
|
+
"sort-package-json": "^3.6.1",
|
|
85
|
+
"tsup": "^8.0.0",
|
|
86
|
+
"typedoc": "^0.28.0",
|
|
87
|
+
"typescript": "^5.7.2",
|
|
88
|
+
"vitest": "^4.0.0"
|
|
89
|
+
},
|
|
90
|
+
"engines": {
|
|
91
|
+
"node": ">=22.0.0"
|
|
92
|
+
},
|
|
93
|
+
"publishConfig": {
|
|
94
|
+
"access": "public"
|
|
95
|
+
}
|
|
96
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @zairakai/npm-i18n
|
|
3
|
+
* Lightweight internationalization library with Laravel-style features
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export { applyPluralization, selectPluralForm } from './pluralization.js'
|
|
7
|
+
export { createTranslator } from './translator.js'
|
|
8
|
+
export type {
|
|
9
|
+
ReplacementParameters,
|
|
10
|
+
TranslateFunction,
|
|
11
|
+
TranslationData,
|
|
12
|
+
TranslationObject,
|
|
13
|
+
Translator,
|
|
14
|
+
} from './types.js'
|
|
15
|
+
|
|
16
|
+
import { createTranslator } from './translator.js'
|
|
17
|
+
import type { TranslationData, Translator } from './types.js'
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Create a quick translator instance
|
|
21
|
+
* @param translations - Translation object
|
|
22
|
+
* @param locale - Default locale
|
|
23
|
+
* @returns Translator instance with __ function
|
|
24
|
+
*/
|
|
25
|
+
export const createI18n = (translations: TranslationData = {}, locale = 'en'): Translator => {
|
|
26
|
+
return createTranslator(translations, locale)
|
|
27
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pluralization utilities for Laravel-style translation strings
|
|
3
|
+
* Handles complex pluralization rules with conditions and ranges
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Selects the appropriate plural form based on count
|
|
8
|
+
* Supports Laravel formats:
|
|
9
|
+
* - Simple: "item|items"
|
|
10
|
+
* - With conditions: "{0} none|{1} one|[2,*] many"
|
|
11
|
+
* - With ranges: "[1,19] some|[20,*] many"
|
|
12
|
+
*
|
|
13
|
+
* @param message - Translation string with plural forms
|
|
14
|
+
* @param count - Count to determine plural form
|
|
15
|
+
* @returns Selected plural form
|
|
16
|
+
*/
|
|
17
|
+
export const selectPluralForm = (message: string, count: number): string => {
|
|
18
|
+
const parts = message.split('|')
|
|
19
|
+
|
|
20
|
+
// Check each part for conditions
|
|
21
|
+
for (const part of parts) {
|
|
22
|
+
const trimmedPart = part.trim()
|
|
23
|
+
|
|
24
|
+
// Look for exact match conditions {n}
|
|
25
|
+
const exactMatch = trimmedPart.match(/^{\s*(\d+)\s*}\s*(.*)$/)
|
|
26
|
+
// Look for range conditions [n,m]
|
|
27
|
+
const rangeMatch = trimmedPart.match(/^\[\s*(\d+|\*)\s*,\s*(\d+|\*)\s*\]\s*(.*)$/)
|
|
28
|
+
|
|
29
|
+
if (exactMatch) {
|
|
30
|
+
// Exact number match {5}
|
|
31
|
+
const exactNumber = parseInt(exactMatch[1], 10)
|
|
32
|
+
if (count === exactNumber) {
|
|
33
|
+
return exactMatch[2].trim()
|
|
34
|
+
}
|
|
35
|
+
} else if (rangeMatch) {
|
|
36
|
+
// Range match [1,5] or [20,*]
|
|
37
|
+
const min = '*' === rangeMatch[1] ? -Infinity : parseInt(rangeMatch[1], 10)
|
|
38
|
+
const max = '*' === rangeMatch[2] ? Infinity : parseInt(rangeMatch[2], 10)
|
|
39
|
+
|
|
40
|
+
if (count >= min && count <= max) {
|
|
41
|
+
return rangeMatch[3].trim()
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Fallback to simple plural logic (no special conditions)
|
|
47
|
+
const simpleParts = parts.filter((part) => {
|
|
48
|
+
const trimmed = part.trim()
|
|
49
|
+
// eslint-disable-next-line no-useless-escape
|
|
50
|
+
return !trimmed.match(/^[{\[]/) // No special condition markers
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
if (2 <= simpleParts.length) {
|
|
54
|
+
// English pluralization: only 1 = singular, others (including 0) = plural
|
|
55
|
+
return 1 === count ? simpleParts[0].trim() : simpleParts[1].trim()
|
|
56
|
+
} else if (1 === simpleParts.length) {
|
|
57
|
+
return simpleParts[0].trim()
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Last resort: return first part, extracting content from patterns
|
|
61
|
+
const firstPart = parts[0].trim()
|
|
62
|
+
|
|
63
|
+
// Try to extract content from patterns
|
|
64
|
+
const exactMatch = firstPart.match(/^{\s*(\d+)\s*}\s*(.*)$/)
|
|
65
|
+
const rangeMatch = firstPart.match(/^\[\s*(\d+|\*)\s*,\s*(\d+|\*)\s*\]\s*(.*)$/)
|
|
66
|
+
|
|
67
|
+
if (exactMatch) {
|
|
68
|
+
return exactMatch[2].trim()
|
|
69
|
+
} else if (rangeMatch) {
|
|
70
|
+
return rangeMatch[3].trim()
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
return firstPart
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Apply pluralization rules to a translation
|
|
78
|
+
* @param translation - Translation string
|
|
79
|
+
* @param count - Count for pluralization
|
|
80
|
+
* @returns Pluralized translation
|
|
81
|
+
*/
|
|
82
|
+
export const applyPluralization = (translation: string, count: number | null): string => {
|
|
83
|
+
if ('string' === typeof translation && translation.includes('|') && null !== count) {
|
|
84
|
+
return selectPluralForm(translation, count)
|
|
85
|
+
}
|
|
86
|
+
return translation
|
|
87
|
+
}
|
package/src/schemas.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Zod schemas for runtime validation of translation data structures
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { z } from 'zod'
|
|
6
|
+
import type { ReplacementParameters, TranslationData, TranslationObject } from './types.js'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Recursive schema for a translation value (string or nested TranslationObject)
|
|
10
|
+
*/
|
|
11
|
+
const TranslationValueSchema: z.ZodType<string | TranslationObject> = z.lazy(() =>
|
|
12
|
+
z.union([z.string(), z.record(z.string(), TranslationValueSchema)])
|
|
13
|
+
) as z.ZodType<string | TranslationObject>
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Schema for a locale's translation object (flat or nested key/value pairs)
|
|
17
|
+
*/
|
|
18
|
+
export const TranslationObjectSchema: z.ZodType<TranslationObject> = z.record(
|
|
19
|
+
z.string(),
|
|
20
|
+
TranslationValueSchema
|
|
21
|
+
) as z.ZodType<TranslationObject>
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Schema for the full translation data map (locale → TranslationObject)
|
|
25
|
+
*/
|
|
26
|
+
export const TranslationDataSchema: z.ZodType<TranslationData> = z.record(z.string(), TranslationObjectSchema)
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Schema for placeholder replacement parameters
|
|
30
|
+
*/
|
|
31
|
+
export const ReplacementParametersSchema: z.ZodType<ReplacementParameters> = z.record(
|
|
32
|
+
z.string(),
|
|
33
|
+
z.union([z.string(), z.number()])
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Schema for the second parameter of translate():
|
|
38
|
+
* either a count (number) for pluralization or a replacements object
|
|
39
|
+
*/
|
|
40
|
+
export const CountOrReplacementsSchema = z.union([z.number(), ReplacementParametersSchema])
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Core translation functionality
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { applyPluralization } from './pluralization.js'
|
|
6
|
+
import {
|
|
7
|
+
CountOrReplacementsSchema,
|
|
8
|
+
ReplacementParametersSchema,
|
|
9
|
+
TranslationDataSchema,
|
|
10
|
+
TranslationObjectSchema,
|
|
11
|
+
} from './schemas.js'
|
|
12
|
+
import type {
|
|
13
|
+
ReplacementParameters,
|
|
14
|
+
TranslateFunction,
|
|
15
|
+
TranslationData,
|
|
16
|
+
TranslationObject,
|
|
17
|
+
Translator,
|
|
18
|
+
} from './types.js'
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Creates a translator instance
|
|
22
|
+
* @param translations - Translation object
|
|
23
|
+
* @param locale - Current locale
|
|
24
|
+
* @returns Translator instance
|
|
25
|
+
*/
|
|
26
|
+
export const createTranslator = (translations: TranslationData = {}, locale = 'en'): Translator => {
|
|
27
|
+
const currentTranslations = TranslationDataSchema.parse(translations)
|
|
28
|
+
let currentLocale = locale
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Translate a key with optional pluralization and replacements
|
|
32
|
+
* @param path - Translation key (dot notation)
|
|
33
|
+
* @param countOrReplacements - Count for pluralization or replacements object
|
|
34
|
+
* @param replacements - Replacement values for placeholders
|
|
35
|
+
* @returns Translated string
|
|
36
|
+
*/
|
|
37
|
+
const translate: TranslateFunction = (
|
|
38
|
+
path: string,
|
|
39
|
+
countOrReplacements: number | ReplacementParameters = {},
|
|
40
|
+
replacements: ReplacementParameters = {}
|
|
41
|
+
): string => {
|
|
42
|
+
CountOrReplacementsSchema.parse(countOrReplacements)
|
|
43
|
+
ReplacementParametersSchema.parse(replacements)
|
|
44
|
+
|
|
45
|
+
let count: number | null = null
|
|
46
|
+
let actualReplacements = replacements
|
|
47
|
+
|
|
48
|
+
// Handle parameter overloading
|
|
49
|
+
if ('number' === typeof countOrReplacements) {
|
|
50
|
+
count = countOrReplacements
|
|
51
|
+
// Automatically add count to replacements
|
|
52
|
+
actualReplacements = { count: countOrReplacements, ...replacements }
|
|
53
|
+
} else {
|
|
54
|
+
actualReplacements = { ...countOrReplacements, ...replacements }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Check if locale exists
|
|
58
|
+
if (!currentTranslations[currentLocale]) {
|
|
59
|
+
return path
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Navigate through translation object using dot notation
|
|
63
|
+
const segments = path.split('.')
|
|
64
|
+
let translation: string | TranslationObject = currentTranslations[currentLocale]
|
|
65
|
+
|
|
66
|
+
for (const segment of segments) {
|
|
67
|
+
if (
|
|
68
|
+
translation &&
|
|
69
|
+
'object' === typeof translation &&
|
|
70
|
+
Object.prototype.hasOwnProperty.call(translation, segment)
|
|
71
|
+
) {
|
|
72
|
+
translation = translation[segment]
|
|
73
|
+
} else {
|
|
74
|
+
return path // Return key if not found
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
if ('string' === typeof translation) {
|
|
79
|
+
// Apply pluralization if count provided
|
|
80
|
+
const pluralizedTranslation = applyPluralization(translation, count)
|
|
81
|
+
|
|
82
|
+
// Replace placeholders (:key and {key} formats)
|
|
83
|
+
const result = pluralizedTranslation
|
|
84
|
+
.replace(/:(\w+)/g, (match, key) => {
|
|
85
|
+
return Object.prototype.hasOwnProperty.call(actualReplacements, key) ? String(actualReplacements[key]) : match
|
|
86
|
+
})
|
|
87
|
+
.replace(/{(\w+)}/g, (match, key) => {
|
|
88
|
+
return Object.prototype.hasOwnProperty.call(actualReplacements, key) ? String(actualReplacements[key]) : match
|
|
89
|
+
})
|
|
90
|
+
|
|
91
|
+
return result
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Return path if translation is not a string
|
|
95
|
+
return path
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Set current locale
|
|
100
|
+
* @param newLocale - New locale
|
|
101
|
+
*/
|
|
102
|
+
const setLocale = (newLocale: string): void => {
|
|
103
|
+
currentLocale = newLocale
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Get current locale
|
|
108
|
+
* @returns Current locale
|
|
109
|
+
*/
|
|
110
|
+
const getLocale = (): string => currentLocale
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Set translations for a locale
|
|
114
|
+
* @param locale - Locale code
|
|
115
|
+
* @param translations - Translation object
|
|
116
|
+
*/
|
|
117
|
+
const setTranslations = (locale: string, translations: TranslationObject): void => {
|
|
118
|
+
currentTranslations[locale] = TranslationObjectSchema.parse(translations)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Add translations to existing locale
|
|
123
|
+
* @param locale - Locale code
|
|
124
|
+
* @param translations - Translation object to merge
|
|
125
|
+
*/
|
|
126
|
+
const addTranslations = (locale: string, translations: TranslationObject): void => {
|
|
127
|
+
const validated = TranslationObjectSchema.parse(translations)
|
|
128
|
+
if (!currentTranslations[locale]) {
|
|
129
|
+
currentTranslations[locale] = {}
|
|
130
|
+
}
|
|
131
|
+
currentTranslations[locale] = { ...currentTranslations[locale], ...validated }
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Check if a translation key exists
|
|
136
|
+
* @param path - Translation key
|
|
137
|
+
* @param locale - Locale to check (optional, uses current if not provided)
|
|
138
|
+
* @returns True if key exists
|
|
139
|
+
*/
|
|
140
|
+
const hasTranslation = (path: string, locale: string | null = null): boolean => {
|
|
141
|
+
const checkLocale = locale ?? currentLocale
|
|
142
|
+
|
|
143
|
+
// Check if locale exists
|
|
144
|
+
if (!currentTranslations[checkLocale]) {
|
|
145
|
+
return false
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const segments = path.split('.')
|
|
149
|
+
let current: Record<string, unknown> | string = currentTranslations[checkLocale]
|
|
150
|
+
|
|
151
|
+
// Navigate through the path
|
|
152
|
+
for (const segment of segments) {
|
|
153
|
+
if (current && 'object' === typeof current && segment in current) {
|
|
154
|
+
current = current[segment] as Record<string, unknown> | string
|
|
155
|
+
} else {
|
|
156
|
+
return false
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// Check if final value is a string
|
|
161
|
+
return 'string' === typeof current
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Get available locales
|
|
166
|
+
* @returns Array of available locale codes
|
|
167
|
+
*/
|
|
168
|
+
const getAvailableLocales = (): string[] => Object.keys(currentTranslations)
|
|
169
|
+
|
|
170
|
+
return {
|
|
171
|
+
__: translate,
|
|
172
|
+
translate,
|
|
173
|
+
setLocale,
|
|
174
|
+
getLocale,
|
|
175
|
+
setTranslations,
|
|
176
|
+
addTranslations,
|
|
177
|
+
hasTranslation,
|
|
178
|
+
getAvailableLocales,
|
|
179
|
+
}
|
|
180
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Type definitions for the i18n library
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
/** Object containing nested translation values */
|
|
6
|
+
export interface TranslationObject {
|
|
7
|
+
[key: string]: string | TranslationObject
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Translation data for multiple locales */
|
|
11
|
+
export type TranslationData = Record<string, TranslationObject>
|
|
12
|
+
|
|
13
|
+
/** Parameters that can be used to replace placeholders in translations */
|
|
14
|
+
export type ReplacementParameters = Record<string, string | number>
|
|
15
|
+
|
|
16
|
+
/** Translator instance interface */
|
|
17
|
+
export interface Translator {
|
|
18
|
+
/** Main translation function (alias for translate) */
|
|
19
|
+
__: TranslateFunction
|
|
20
|
+
/** Main translation function */
|
|
21
|
+
translate: TranslateFunction
|
|
22
|
+
/** Set the current locale */
|
|
23
|
+
setLocale: (locale: string) => void
|
|
24
|
+
/** Get the current locale */
|
|
25
|
+
getLocale: () => string
|
|
26
|
+
/** Set translations for a specific locale */
|
|
27
|
+
setTranslations: (locale: string, translations: TranslationObject) => void
|
|
28
|
+
/** Add translations to an existing locale */
|
|
29
|
+
addTranslations: (locale: string, translations: TranslationObject) => void
|
|
30
|
+
/** Check if a translation key exists */
|
|
31
|
+
hasTranslation: (path: string, locale?: string | null) => boolean
|
|
32
|
+
/** Get all available locales */
|
|
33
|
+
getAvailableLocales: () => string[]
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Translation function signature with overloads */
|
|
37
|
+
export interface TranslateFunction {
|
|
38
|
+
/** Translate with replacements only */
|
|
39
|
+
(path: string, replacements?: ReplacementParameters): string
|
|
40
|
+
/** Translate with count for pluralization */
|
|
41
|
+
(path: string, count: number, replacements?: ReplacementParameters): string
|
|
42
|
+
}
|