@to-kn/koa-locales 2.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/LICENSE +21 -0
- package/README.md +201 -0
- package/dist/esm/index.js +271 -0
- package/dist/esm/src/index.js +320 -0
- package/dist/esm/test/index.test.js +580 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.js +250 -0
- package/dist/types/index.d.ts +28 -0
- package/dist/types/src/index.d.ts +27 -0
- package/dist/types/test/index.test.d.ts +1 -0
- package/package.json +79 -0
package/LICENSE
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
This software is licensed under the MIT License.
|
2
|
+
|
3
|
+
Copyright (c) 2015 - 2017 koajs and other contributors
|
4
|
+
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
7
|
+
in the Software without restriction, including without limitation the rights
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
10
|
+
furnished to do so, subject to the following conditions:
|
11
|
+
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
13
|
+
all copies or substantial portions of the Software.
|
14
|
+
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
21
|
+
THE SOFTWARE.
|
package/README.md
ADDED
@@ -0,0 +1,201 @@
|
|
1
|
+
# koa-locales
|
2
|
+
|
3
|
+
A modern i18n solution for Koa: [@to-kn/koa-locales](https://github.com/to-kn/koa-locales)
|
4
|
+
|
5
|
+
**Now TypeScript-first, ESM, and Node.js 18+!**
|
6
|
+
- Uses ESM (`import`/`export`), outputs to `dist/esm/`, and is CI-tested on GitHub Actions.
|
7
|
+
- Use the built output (`dist/esm/index.js`) as the main entry point for consumers, but tests and development use the source (`src/`).
|
8
|
+
- Modern test suite with [Vitest](https://vitest.dev/).
|
9
|
+
|
10
|
+
[![NPM version][npm-image]][npm-url]
|
11
|
+
|
12
|
+
koa locales, i18n solution for koa:
|
13
|
+
|
14
|
+
1. All locales resources location on `options.dirs`.
|
15
|
+
2. resources file supports: `*.js`, `*.json`, `*.yml`, `*.yaml` and `*.properties`, see [examples](test/locales/).
|
16
|
+
3. One api: `__(key[, value, ...])`.
|
17
|
+
4. Auto detect request locale from `query`, `cookie` and `header: Accept-Language`.
|
18
|
+
|
19
|
+
## Requirements
|
20
|
+
|
21
|
+
- Node.js >= 18
|
22
|
+
- ESM ("type": "module" in package.json)
|
23
|
+
- TypeScript (for development)
|
24
|
+
|
25
|
+
## Installation
|
26
|
+
|
27
|
+
```sh
|
28
|
+
npm install @to-kn/koa-locales
|
29
|
+
```
|
30
|
+
|
31
|
+
## Quick start (ESM/TypeScript)
|
32
|
+
|
33
|
+
```js
|
34
|
+
import locales from '@to-kn/koa-locales';
|
35
|
+
import Koa from 'koa';
|
36
|
+
|
37
|
+
const app = new Koa();
|
38
|
+
const options = {
|
39
|
+
dirs: [__dirname + '/locales', __dirname + '/foo/locales'],
|
40
|
+
};
|
41
|
+
locales(app, options);
|
42
|
+
```
|
43
|
+
|
44
|
+
## Development & Testing
|
45
|
+
|
46
|
+
- Run tests with [Vitest](https://vitest.dev/):
|
47
|
+
```sh
|
48
|
+
npm run test
|
49
|
+
```
|
50
|
+
- Lint and format with [Biome](https://biomejs.dev/):
|
51
|
+
```sh
|
52
|
+
npm run lint
|
53
|
+
```
|
54
|
+
- Build TypeScript to ESM:
|
55
|
+
```sh
|
56
|
+
npm run build
|
57
|
+
```
|
58
|
+
- CI runs on GitHub Actions (see `.github/workflows/`)
|
59
|
+
|
60
|
+
## API Reference
|
61
|
+
|
62
|
+
### `locales(app, options)`
|
63
|
+
|
64
|
+
Patch locales functions to koa app.
|
65
|
+
|
66
|
+
- {Application} app: koa app instance.
|
67
|
+
- {Object} options: optional params.
|
68
|
+
- {String} functionName: locale function name patch on koa context. Optional, default is `__`.
|
69
|
+
- {String} dirs: locales resources store directories. Optional, default is `['$PWD/locales']`.
|
70
|
+
- {String} defaultLocale: default locale. Optional, default is `en-US`.
|
71
|
+
- {String} queryField: locale field name on query. Optional, default is `locale`.
|
72
|
+
- {String} cookieField: locale field name on cookie. Optional, default is `locale`.
|
73
|
+
- {String} cookieDomain: domain on cookie. Optional, default is `''`.
|
74
|
+
- {Object} localeAlias: locale value map. Optional, default is `{}`.
|
75
|
+
- {Boolean} writeCookie: set cookie if header not sent. Optional, default is `true`.
|
76
|
+
- {String|Number} cookieMaxAge: set locale cookie value max age. Optional, default is `1y`, expired after one year.
|
77
|
+
|
78
|
+
```js
|
79
|
+
locales({
|
80
|
+
app: app,
|
81
|
+
dirs: [__dirname + '/app/locales'],
|
82
|
+
defaultLocale: 'zh-CN',
|
83
|
+
});
|
84
|
+
```
|
85
|
+
|
86
|
+
#### Aliases
|
87
|
+
|
88
|
+
The key `options.localeAlias` allows to not repeat dictionary files, as you can configure to use the same file for *es_ES* for *es*, or *en_UK* for *en*.
|
89
|
+
|
90
|
+
```js
|
91
|
+
locales({
|
92
|
+
localeAlias: {
|
93
|
+
es: es_ES,
|
94
|
+
en: en_UK,
|
95
|
+
},
|
96
|
+
});
|
97
|
+
```
|
98
|
+
|
99
|
+
### `context.__(key[, value1[, value2, ...]])`
|
100
|
+
|
101
|
+
Get current request locale text.
|
102
|
+
|
103
|
+
```js
|
104
|
+
async function home(ctx) {
|
105
|
+
ctx.body = {
|
106
|
+
message: ctx.__('Hello, %s', 'fengmk2'),
|
107
|
+
};
|
108
|
+
}
|
109
|
+
```
|
110
|
+
|
111
|
+
Examples:
|
112
|
+
|
113
|
+
```js
|
114
|
+
__('Hello, %s. %s', 'fengmk2', 'koa rock!')
|
115
|
+
=>
|
116
|
+
'Hello fengmk2. koa rock!'
|
117
|
+
|
118
|
+
__('{0} {0} {1} {1} {1}', ['foo', 'bar'])
|
119
|
+
=>
|
120
|
+
'foo foo bar bar bar'
|
121
|
+
|
122
|
+
__('{a} {a} {b} {b} {b}', {a: 'foo', b: 'bar'})
|
123
|
+
=>
|
124
|
+
'foo foo bar bar bar'
|
125
|
+
```
|
126
|
+
|
127
|
+
### `context.__getLocale()`
|
128
|
+
|
129
|
+
Get locale from query / cookie and header.
|
130
|
+
|
131
|
+
### `context.__setLocale()`
|
132
|
+
|
133
|
+
Set locale and cookie.
|
134
|
+
|
135
|
+
### `context.__getLocaleOrigin()`
|
136
|
+
|
137
|
+
Where does locale come from, could be `query`, `cookie`, `header` and `default`.
|
138
|
+
|
139
|
+
### `app.__(locale, key[, value1[, value2, ...]])`
|
140
|
+
|
141
|
+
Get the given locale text on application level.
|
142
|
+
|
143
|
+
```js
|
144
|
+
console.log(app.__('zh', 'Hello'));
|
145
|
+
// stdout '你好' for Chinese
|
146
|
+
```
|
147
|
+
|
148
|
+
## Usage on template
|
149
|
+
|
150
|
+
```js
|
151
|
+
this.state.__ = this.__.bind(this);
|
152
|
+
```
|
153
|
+
|
154
|
+
[Nunjucks] example:
|
155
|
+
|
156
|
+
```html
|
157
|
+
{{ __('Hello, %s', user.name) }}
|
158
|
+
```
|
159
|
+
|
160
|
+
[Pug] example:
|
161
|
+
|
162
|
+
```pug
|
163
|
+
p= __('Hello, %s', user.name)
|
164
|
+
```
|
165
|
+
|
166
|
+
[Koa-pug] integration:
|
167
|
+
|
168
|
+
You can set the property *locals* on the KoaPug instance, where the default locals are stored.
|
169
|
+
|
170
|
+
```js
|
171
|
+
app.use(async (ctx, next) => {
|
172
|
+
koaPug.locals.__ = ctx.__.bind(ctx);
|
173
|
+
await next();
|
174
|
+
});
|
175
|
+
```
|
176
|
+
|
177
|
+
## Debugging
|
178
|
+
|
179
|
+
If you are interested on knowing what locale was chosen and why you can enable the debug messages from [debug].
|
180
|
+
|
181
|
+
There is two level of verbosity:
|
182
|
+
|
183
|
+
```sh
|
184
|
+
$ DEBUG=koa-locales node .
|
185
|
+
```
|
186
|
+
With this line it only will show one line per request, with the chosen language and the origin where the locale come from (queryString, header or cookie).
|
187
|
+
|
188
|
+
```sh
|
189
|
+
$ DEBUG=koa-locales:silly node .
|
190
|
+
```
|
191
|
+
|
192
|
+
## Locale File Formats
|
193
|
+
|
194
|
+
You can provide locale files in the following formats:
|
195
|
+
|
196
|
+
- `.json` (recommended for most use cases)
|
197
|
+
- `.yml` or `.yaml`
|
198
|
+
- `.properties`
|
199
|
+
- `.cjs` (CommonJS JavaScript, e.g. `module.exports = { ... }`)
|
200
|
+
|
201
|
+
> **Note:** `.js` ESM modules are not supported for synchronous loading. Use `.cjs` for JavaScript locale files if you need sync loading.
|
@@ -0,0 +1,271 @@
|
|
1
|
+
import fs from "node:fs";
|
2
|
+
import { createRequire } from "node:module";
|
3
|
+
import path from "node:path";
|
4
|
+
import util from "node:util";
|
5
|
+
import Debug from "debug";
|
6
|
+
import { ms } from "humanize-ms";
|
7
|
+
import ini from "ini";
|
8
|
+
import yaml from "js-yaml";
|
9
|
+
const DEFAULT_OPTIONS = {
|
10
|
+
defaultLocale: "en-US",
|
11
|
+
queryField: "locale",
|
12
|
+
cookieField: "locale",
|
13
|
+
localeAlias: {},
|
14
|
+
writeCookie: true,
|
15
|
+
cookieMaxAge: "1y",
|
16
|
+
dir: undefined,
|
17
|
+
dirs: [path.join(process.cwd(), "locales")],
|
18
|
+
functionName: "__",
|
19
|
+
};
|
20
|
+
function locales(app, options = {}) {
|
21
|
+
options = Object.assign({}, DEFAULT_OPTIONS, options);
|
22
|
+
const defaultLocale = formatLocale(options.defaultLocale || "en-US");
|
23
|
+
const queryField = options.queryField || "locale";
|
24
|
+
const cookieField = options.cookieField || "locale";
|
25
|
+
const cookieDomain = options.cookieDomain;
|
26
|
+
const localeAlias = options.localeAlias || {};
|
27
|
+
const writeCookie = options.writeCookie !== false;
|
28
|
+
const cookieMaxAge = ms(options.cookieMaxAge || "1y");
|
29
|
+
const localeDir = options.dir;
|
30
|
+
const localeDirs = options.dirs || [path.join(process.cwd(), "locales")];
|
31
|
+
const functionName = options.functionName || "__";
|
32
|
+
const resources = {};
|
33
|
+
/**
|
34
|
+
* @Deprecated Use options.dirs instead.
|
35
|
+
*/
|
36
|
+
if (localeDir && !localeDirs.includes(localeDir)) {
|
37
|
+
localeDirs.push(localeDir);
|
38
|
+
}
|
39
|
+
appendDebugLog("Starting resource loading");
|
40
|
+
// Loop through all directories, merging resources for the same locale
|
41
|
+
// Later directories override earlier ones
|
42
|
+
for (let i = 0; i < localeDirs.length; i++) {
|
43
|
+
const dir = localeDirs[i];
|
44
|
+
if (!fs.existsSync(dir)) {
|
45
|
+
continue;
|
46
|
+
}
|
47
|
+
const names = fs.readdirSync(dir);
|
48
|
+
for (let j = 0; j < names.length; j++) {
|
49
|
+
const name = names[j];
|
50
|
+
const filepath = path.join(dir, name);
|
51
|
+
// support en_US.js => en-US.js
|
52
|
+
const locale = formatLocale(name.split(".")[0]);
|
53
|
+
let resource = {};
|
54
|
+
if (name.endsWith(".js")) {
|
55
|
+
const require = createRequire(import.meta.url);
|
56
|
+
const mod = require(filepath);
|
57
|
+
resource = flattening((mod.default || mod));
|
58
|
+
appendDebugLog(`Loaded JS resource for locale '${locale}' from: ${filepath}`, resource);
|
59
|
+
}
|
60
|
+
else if (name.endsWith(".json")) {
|
61
|
+
// @ts-ignore
|
62
|
+
resource = flattening(require(filepath));
|
63
|
+
appendDebugLog(`Loaded JSON resource for locale '${locale}' from: ${filepath}`, resource);
|
64
|
+
}
|
65
|
+
else if (name.endsWith(".properties")) {
|
66
|
+
resource = ini.parse(fs.readFileSync(filepath, "utf8"));
|
67
|
+
appendDebugLog(`Loaded PROPERTIES resource for locale '${locale}' from: ${filepath}`, resource);
|
68
|
+
}
|
69
|
+
else if (name.endsWith(".yml") || name.endsWith(".yaml")) {
|
70
|
+
resource = flattening(yaml.load(fs.readFileSync(filepath, "utf8")));
|
71
|
+
appendDebugLog(`Loaded YAML resource for locale '${locale}' from: ${filepath}`, resource);
|
72
|
+
}
|
73
|
+
// Always merge, but let later dirs override earlier ones
|
74
|
+
resources[locale] = { ...resources[locale], ...resource };
|
75
|
+
appendDebugLog(`Merged resource for locale '${locale}'`, resources[locale]);
|
76
|
+
}
|
77
|
+
}
|
78
|
+
appendDebugLog("Finished resource loading");
|
79
|
+
const debug = Debug("koa-locales");
|
80
|
+
const debugSilly = Debug("koa-locales:silly");
|
81
|
+
debug("Init locales with %j, got %j resources", options, Object.keys(resources));
|
82
|
+
if (typeof app[functionName] !==
|
83
|
+
"undefined") {
|
84
|
+
console.warn('[koa-locales] will override exists "%s" function on app', functionName);
|
85
|
+
}
|
86
|
+
function gettext(locale, key, ...args) {
|
87
|
+
if (!key || key === "")
|
88
|
+
return "";
|
89
|
+
const resource = resources[locale] || {};
|
90
|
+
let text = resource[key];
|
91
|
+
if (typeof text !== "string") {
|
92
|
+
text = key;
|
93
|
+
}
|
94
|
+
debugSilly("%s: %j => %j", locale, key, text);
|
95
|
+
if (args.length === 0) {
|
96
|
+
// __(locale, key)
|
97
|
+
return text;
|
98
|
+
}
|
99
|
+
if (args.length === 1) {
|
100
|
+
const value = args[0];
|
101
|
+
if (isObject(value)) {
|
102
|
+
return formatWithObject(text, value);
|
103
|
+
}
|
104
|
+
if (Array.isArray(value)) {
|
105
|
+
return formatWithArray(text, value);
|
106
|
+
}
|
107
|
+
return util.format(text, value);
|
108
|
+
}
|
109
|
+
// __(locale, key, value1, ...)
|
110
|
+
return util.format(text, ...args);
|
111
|
+
}
|
112
|
+
// Attach to app and context using proper Koa extension
|
113
|
+
app[functionName] = gettext;
|
114
|
+
app.context[functionName] =
|
115
|
+
function (key, ...args) {
|
116
|
+
const ctx = this;
|
117
|
+
const locale = ctx.__getLocale ? ctx.__getLocale() : "";
|
118
|
+
return gettext(locale, key, ...args);
|
119
|
+
};
|
120
|
+
app.context.__getLocale =
|
121
|
+
function () {
|
122
|
+
const ctx = this;
|
123
|
+
if (typeof ctx.__locale === "string" && ctx.__locale) {
|
124
|
+
return ctx.__locale;
|
125
|
+
}
|
126
|
+
const cookieLocale = ctx.cookies.get(cookieField, { signed: false });
|
127
|
+
let locale = ctx.query[queryField];
|
128
|
+
let localeOrigin = "query";
|
129
|
+
if (!locale) {
|
130
|
+
locale = cookieLocale;
|
131
|
+
localeOrigin = "cookie";
|
132
|
+
}
|
133
|
+
if (!locale) {
|
134
|
+
let languages = ctx.acceptsLanguages();
|
135
|
+
if (languages) {
|
136
|
+
if (Array.isArray(languages)) {
|
137
|
+
if (languages[0] === "*") {
|
138
|
+
languages = languages.slice(1);
|
139
|
+
}
|
140
|
+
if (languages.length > 0) {
|
141
|
+
for (let i = 0; i < languages.length; i++) {
|
142
|
+
const lang = formatLocale(String(languages[i]));
|
143
|
+
if (resources[lang] || localeAlias[lang]) {
|
144
|
+
locale = lang;
|
145
|
+
localeOrigin = "header";
|
146
|
+
break;
|
147
|
+
}
|
148
|
+
}
|
149
|
+
}
|
150
|
+
}
|
151
|
+
else if (typeof languages === "string") {
|
152
|
+
locale = languages;
|
153
|
+
localeOrigin = "header";
|
154
|
+
}
|
155
|
+
}
|
156
|
+
if (!locale) {
|
157
|
+
locale = defaultLocale;
|
158
|
+
localeOrigin = "default";
|
159
|
+
}
|
160
|
+
}
|
161
|
+
if (locale && typeof locale !== "string") {
|
162
|
+
locale = String(locale);
|
163
|
+
}
|
164
|
+
if (locale && locale in localeAlias) {
|
165
|
+
const originalLocale = locale;
|
166
|
+
locale = localeAlias[locale];
|
167
|
+
debugSilly("Used alias, received %s but using %s", originalLocale, locale);
|
168
|
+
}
|
169
|
+
locale = formatLocale(locale || defaultLocale);
|
170
|
+
if (!resources[locale]) {
|
171
|
+
debugSilly("Locale %s is not supported. Using default (%s)", locale, defaultLocale);
|
172
|
+
locale = defaultLocale;
|
173
|
+
}
|
174
|
+
if (writeCookie && cookieLocale !== locale && !ctx.headerSent) {
|
175
|
+
updateCookie(ctx, locale);
|
176
|
+
}
|
177
|
+
debug("Locale: %s from %s", locale, localeOrigin);
|
178
|
+
debugSilly("Locale: %s from %s", locale, localeOrigin);
|
179
|
+
ctx.__locale = locale;
|
180
|
+
ctx.__localeOrigin = localeOrigin;
|
181
|
+
return String(locale);
|
182
|
+
};
|
183
|
+
app.context.__getLocaleOrigin =
|
184
|
+
function () {
|
185
|
+
const ctx = this;
|
186
|
+
if (typeof ctx.__localeOrigin === "string" && ctx.__localeOrigin)
|
187
|
+
return ctx.__localeOrigin;
|
188
|
+
ctx.__getLocale?.();
|
189
|
+
return String(ctx.__localeOrigin ?? "");
|
190
|
+
};
|
191
|
+
app.context.__setLocale =
|
192
|
+
function (locale) {
|
193
|
+
const ctx = this;
|
194
|
+
ctx.__locale = locale;
|
195
|
+
ctx.__localeOrigin = "set";
|
196
|
+
updateCookie(ctx, locale);
|
197
|
+
};
|
198
|
+
function updateCookie(ctx, locale) {
|
199
|
+
const cookieOptions = {
|
200
|
+
httpOnly: false,
|
201
|
+
maxAge: cookieMaxAge,
|
202
|
+
signed: false,
|
203
|
+
domain: cookieDomain,
|
204
|
+
overwrite: true,
|
205
|
+
};
|
206
|
+
ctx.cookies.set(cookieField, locale, cookieOptions);
|
207
|
+
debugSilly("Saved cookie with locale %s", locale);
|
208
|
+
}
|
209
|
+
}
|
210
|
+
function isObject(obj) {
|
211
|
+
return Object.prototype.toString.call(obj) === "[object Object]";
|
212
|
+
}
|
213
|
+
const ARRAY_INDEX_RE = /\{(\d+)\}/g;
|
214
|
+
function formatWithArray(text, values) {
|
215
|
+
return text.replace(ARRAY_INDEX_RE, (orignal, matched) => {
|
216
|
+
const index = parseInt(matched);
|
217
|
+
if (index < values.length) {
|
218
|
+
return String(values[index]);
|
219
|
+
}
|
220
|
+
// not match index, return orignal text
|
221
|
+
return orignal;
|
222
|
+
});
|
223
|
+
}
|
224
|
+
const Object_INDEX_RE = /\{(.+?)\}/g;
|
225
|
+
function formatWithObject(text, values) {
|
226
|
+
return text.replace(Object_INDEX_RE, (orignal, matched) => {
|
227
|
+
const value = values[matched];
|
228
|
+
if (value !== undefined && value !== null) {
|
229
|
+
return String(value);
|
230
|
+
}
|
231
|
+
// not match index, return orignal text
|
232
|
+
return orignal;
|
233
|
+
});
|
234
|
+
}
|
235
|
+
function formatLocale(locale) {
|
236
|
+
if (!locale)
|
237
|
+
return "";
|
238
|
+
return locale.replace(/_/g, "-").toLowerCase();
|
239
|
+
}
|
240
|
+
function flattening(data) {
|
241
|
+
const result = {};
|
242
|
+
function deepFlat(data, keys) {
|
243
|
+
Object.keys(data).forEach((key) => {
|
244
|
+
const value = data[key];
|
245
|
+
const k = keys ? `${keys}.${key}` : key;
|
246
|
+
if (isObject(value)) {
|
247
|
+
deepFlat(value, k);
|
248
|
+
}
|
249
|
+
else {
|
250
|
+
result[k] = String(value);
|
251
|
+
}
|
252
|
+
});
|
253
|
+
}
|
254
|
+
deepFlat(data, "");
|
255
|
+
return result;
|
256
|
+
}
|
257
|
+
function appendDebugLog(message, obj) {
|
258
|
+
const logPath = path.resolve(process.cwd(), "resource-debug.log");
|
259
|
+
let line = `[DEBUG] ${message}`;
|
260
|
+
if (obj !== undefined) {
|
261
|
+
try {
|
262
|
+
line += ` ${JSON.stringify(obj)}`;
|
263
|
+
}
|
264
|
+
catch {
|
265
|
+
line += ` ${String(obj)}`;
|
266
|
+
}
|
267
|
+
}
|
268
|
+
fs.appendFileSync(logPath, `${line}
|
269
|
+
`);
|
270
|
+
}
|
271
|
+
export default locales;
|