@application-kit/i18n 0.0.0-stage → 0.1.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.
Files changed (49) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/LICENSE +21 -0
  3. package/README.md +65 -2
  4. package/dist/cjs/define-locales.d.ts +10 -0
  5. package/dist/cjs/define-locales.js +15 -0
  6. package/dist/cjs/dictionary-provider.interface.d.ts +4 -0
  7. package/dist/cjs/dictionary-provider.interface.js +2 -0
  8. package/dist/cjs/dictionary.d.ts +4 -0
  9. package/dist/cjs/dictionary.js +13 -0
  10. package/dist/cjs/index.d.ts +4 -0
  11. package/dist/cjs/index.js +20 -0
  12. package/dist/cjs/package.json +3 -0
  13. package/dist/cjs/server/index.d.ts +1 -0
  14. package/dist/cjs/server/index.js +17 -0
  15. package/dist/cjs/server/resolve-locale.d.ts +13 -0
  16. package/dist/cjs/server/resolve-locale.js +48 -0
  17. package/dist/cjs/translate-function.d.ts +1 -0
  18. package/dist/cjs/translate-function.js +2 -0
  19. package/dist/cjs/vue/i18n-plugin.d.ts +20 -0
  20. package/dist/cjs/vue/i18n-plugin.js +40 -0
  21. package/dist/cjs/vue/index.d.ts +3 -0
  22. package/dist/cjs/vue/index.js +19 -0
  23. package/dist/cjs/vue/locale-cookie.d.ts +5 -0
  24. package/dist/cjs/vue/locale-cookie.js +14 -0
  25. package/dist/cjs/vue/module-dictionary.d.ts +5 -0
  26. package/dist/cjs/vue/module-dictionary.js +11 -0
  27. package/dist/esm/define-locales.d.ts +10 -0
  28. package/dist/esm/define-locales.js +11 -0
  29. package/dist/esm/dictionary-provider.interface.d.ts +4 -0
  30. package/dist/esm/dictionary-provider.interface.js +1 -0
  31. package/dist/esm/dictionary.d.ts +4 -0
  32. package/dist/esm/dictionary.js +9 -0
  33. package/dist/esm/index.d.ts +4 -0
  34. package/dist/esm/index.js +4 -0
  35. package/dist/esm/server/index.d.ts +1 -0
  36. package/dist/esm/server/index.js +1 -0
  37. package/dist/esm/server/resolve-locale.d.ts +13 -0
  38. package/dist/esm/server/resolve-locale.js +44 -0
  39. package/dist/esm/translate-function.d.ts +1 -0
  40. package/dist/esm/translate-function.js +1 -0
  41. package/dist/esm/vue/i18n-plugin.d.ts +20 -0
  42. package/dist/esm/vue/i18n-plugin.js +33 -0
  43. package/dist/esm/vue/index.d.ts +3 -0
  44. package/dist/esm/vue/index.js +3 -0
  45. package/dist/esm/vue/locale-cookie.d.ts +5 -0
  46. package/dist/esm/vue/locale-cookie.js +10 -0
  47. package/dist/esm/vue/module-dictionary.d.ts +5 -0
  48. package/dist/esm/vue/module-dictionary.js +7 -0
  49. package/package.json +87 -3
package/CHANGELOG.md ADDED
@@ -0,0 +1,10 @@
1
+ # @application-kit/i18n
2
+
3
+ ## 0.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - bea5e4a: Первый выпуск: набор локалей `defineLocales`, словари `LocaleDictionary`/`composeMessages` и тип `TranslateFunction` (корень,
8
+ изоморфно); `I18nPlugin` с доступом к локали и переводу приложения (`getLocaleReference`, `getTranslate`, `setLocale`),
9
+ `collectModuleDictionaries` и `writeLocaleCookie` (вход `/vue`); `resolveLocale` — локаль запроса по профилю, cookie и
10
+ `Accept-Language` (вход `/server`).
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 application-kit
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 all
13
+ 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 THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,66 @@
1
- # Temporary Holding Version
1
+ # @application-kit/i18n
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Локали, словари и плагин `vue-i18n` для SSR-приложений на Vue.js и серверный резолв локали запроса. Пакет не знает
4
+ языков продукта, его словарей и реестра модулей: набор локалей, каркасный словарь и словари модулей приходят
5
+ параметрами.
6
+
7
+ ## Установка
8
+
9
+ ```sh
10
+ yarn add @application-kit/i18n
11
+ ```
12
+
13
+ Peer-зависимости: `vue`, `vue-i18n` — экземпляр у приложения один.
14
+
15
+ ## Входы
16
+
17
+ | Вход | Для чего | Тянет |
18
+ |------|----------|-------|
19
+ | `@application-kit/i18n` | изоморфно: набор локалей, тип словаря, сборка словаря, тип перевода | ничего (типы `vue-i18n`) |
20
+ | `@application-kit/i18n/vue` | клиент и SSR-рендер: плагин, доступ к локали и переводу, cookie выбора | `vue`, `vue-i18n` |
21
+ | `@application-kit/i18n/server` | сервер: локаль запроса | ничего |
22
+
23
+ Импорт любого входа не имеет побочных эффектов и не требует окружения: состояние плагина заводится на
24
+ установке в приложение, а не на загрузке модуля.
25
+
26
+ ## Корень
27
+
28
+ - `defineLocales(locales, fallback)` — набор `{ locales, fallback, isSupported }`; тип локали выводится из
29
+ литерального кортежа, запасная локаль вне списка не компилируется. `isSupported(value: unknown)` — проверка
30
+ значения, пришедшего снаружи (cookie, заголовок, профиль).
31
+ - `LocaleDictionary<L>` — половины словаря одного поставщика по локалям; `LocaleMessages` — одна половина.
32
+ - `composeMessages(dictionaries, locales)` — словарь приложения: каркас первым, модули за ним, поздний перекрывает ранний.
33
+ - `TranslateFunction` — `(key, named?) => string`, форма `t` из `useI18n()`: перевод для кода вне компонентов.
34
+ - `DictionaryProviderInterface<L>` — контракт модуля, несущего свой словарь (`getDictionary()`).
35
+
36
+ ```ts
37
+ export const localeSet = defineLocales(['ru', 'en'], 'ru')
38
+ export type AppLocale = (typeof localeSet.locales)[number]
39
+ ```
40
+
41
+ ## Vue.js
42
+
43
+ ```ts
44
+ app.use(new I18nPlugin({
45
+ localeSet,
46
+ messages: frameworkMessages,
47
+ // Вызывается в контексте приложения: `inject` доступен, реестр модулей приложение достаёт само.
48
+ moduleDictionaries: () => collectModuleDictionaries(inject(MODULE_REGISTRY, undefined)),
49
+ }))
50
+ ```
51
+
52
+ - `I18nPlugin` — ставит `vue-i18n` (Composition API), стартовая и запасная локаль — `localeSet.fallback`.
53
+ - `collectModuleDictionaries(registry)` — словари модулей реестра в порядке регистрации. Реестр структурный:
54
+ достаточно `getModules()`; словарь берётся у модуля с методом `getDictionary`.
55
+ - `setLocale(app, locale)`, `getLocaleReference(app)`, `getTranslate(app)` — локаль и перевод конкретного
56
+ экземпляра приложения для кода вне компонентов. Состояние хранится по `App` (`WeakMap`), а не в модуле:
57
+ на сервере модуль живёт между запросами, и язык одного пользователя не доезжает до другого.
58
+ - `writeLocaleCookie(locale, { name, maxAgeSeconds? })` — запоминает выбор языка для следующего запроса:
59
+ `Path=/`, `SameSite=Lax`, год по умолчанию, без `HttpOnly` (cookie пишет браузер, значение не секрет).
60
+
61
+ ## Сервер
62
+
63
+ - `resolveLocale(request, { localeSet, cookieName })` — локаль запроса: профиль (`request.user.locale`) → cookie →
64
+ `Accept-Language` с весами `q` (`q=0` отклоняет язык, `ru-RU` — это `ru`) → `localeSet.fallback`. Испорченное
65
+ значение любого источника читается как «предпочтения нет». Запрос описан структурно (`LocaleRequestInterface`) —
66
+ подходит запрос Fastify с `@fastify/cookie` и без привязки к фреймворку.
@@ -0,0 +1,10 @@
1
+ export interface LocaleSetInterface<L extends string> {
2
+ readonly fallback: L;
3
+ readonly isSupported: LocaleGuard<L>;
4
+ readonly locales: readonly L[];
5
+ }
6
+ type LocaleGuard<L extends string> = (value: unknown) => value is L;
7
+ export declare const defineLocales: <const T extends readonly [string, ...string[]]>(locales: T, fallback: NoInfer<T[number]>) => {
8
+ readonly locales: T;
9
+ } & LocaleSetInterface<T[number]>;
10
+ export {};
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.defineLocales = void 0;
4
+ const defineLocales = (locales, fallback) => {
5
+ const values = locales;
6
+ if (!values.includes(fallback)) {
7
+ throw new RangeError(`Запасная локаль «${fallback}» не входит в набор: ${locales.join(', ')}`);
8
+ }
9
+ return {
10
+ fallback,
11
+ isSupported: (value) => values.includes(value),
12
+ locales,
13
+ };
14
+ };
15
+ exports.defineLocales = defineLocales;
@@ -0,0 +1,4 @@
1
+ import type { LocaleDictionary } from './dictionary.js';
2
+ export interface DictionaryProviderInterface<L extends string> {
3
+ getDictionary(): LocaleDictionary<L>;
4
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,4 @@
1
+ import type { LocaleMessageValue, VueMessageType } from 'vue-i18n';
2
+ export type LocaleDictionary<L extends string> = Record<L, LocaleMessages>;
3
+ export type LocaleMessages = Record<string, LocaleMessageValue<VueMessageType>>;
4
+ export declare const composeMessages: <L extends string>(dictionaries: readonly LocaleDictionary<L>[], locales: readonly L[]) => LocaleDictionary<L>;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.composeMessages = void 0;
4
+ const composeMessages = (dictionaries, locales) => {
5
+ const merged = new Map(locales.map((locale) => [locale, {}]));
6
+ for (const [locale, messages] of merged) {
7
+ for (const dictionary of dictionaries) {
8
+ Object.assign(messages, dictionary[locale]);
9
+ }
10
+ }
11
+ return Object.fromEntries(merged);
12
+ };
13
+ exports.composeMessages = composeMessages;
@@ -0,0 +1,4 @@
1
+ export * from './define-locales.js';
2
+ export * from './dictionary.js';
3
+ export * from './dictionary-provider.interface.js';
4
+ export * from './translate-function.js';
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./define-locales.js"), exports);
18
+ __exportStar(require("./dictionary.js"), exports);
19
+ __exportStar(require("./dictionary-provider.interface.js"), exports);
20
+ __exportStar(require("./translate-function.js"), exports);
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }
@@ -0,0 +1 @@
1
+ export * from './resolve-locale.js';
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./resolve-locale.js"), exports);
@@ -0,0 +1,13 @@
1
+ import type { LocaleSetInterface } from '../define-locales.js';
2
+ export interface LocaleRequestInterface {
3
+ cookies?: Partial<Record<string, string>> | undefined;
4
+ headers: Partial<Record<string, string | string[]>>;
5
+ user?: {
6
+ locale?: null | string;
7
+ } | undefined;
8
+ }
9
+ export interface ResolveLocaleOptionsInterface<L extends string> {
10
+ cookieName: string;
11
+ localeSet: LocaleSetInterface<L>;
12
+ }
13
+ export declare const resolveLocale: <L extends string>(request: LocaleRequestInterface, options: ResolveLocaleOptionsInterface<L>) => L;
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveLocale = void 0;
4
+ const DEFAULT_QUALITY = 1;
5
+ const REJECTED_QUALITY = 0;
6
+ const QUALITY_PATTERN = /(?<=;\s*q=)[^;]*/u;
7
+ const SUBTAGS_AND_PARAMETERS_PATTERN = /[-;].*/u;
8
+ const parseQuality = (range) => {
9
+ const value = QUALITY_PATTERN.exec(range)?.[0];
10
+ if (value === undefined) {
11
+ return DEFAULT_QUALITY;
12
+ }
13
+ const quality = Number(value);
14
+ return Number.isNaN(quality) ? REJECTED_QUALITY : quality;
15
+ };
16
+ const parseLanguageRange = (range) => ({
17
+ primaryTag: range.replace(SUBTAGS_AND_PARAMETERS_PATTERN, '').trim()
18
+ .toLowerCase(),
19
+ quality: parseQuality(range),
20
+ });
21
+ const resolveFromAcceptLanguage = (header, localeSet) => {
22
+ const ranges = header
23
+ .split(',')
24
+ .map((range) => parseLanguageRange(range))
25
+ .filter((range) => range.quality > REJECTED_QUALITY)
26
+ .toSorted((left, right) => right.quality - left.quality);
27
+ for (const range of ranges) {
28
+ if (localeSet.isSupported(range.primaryTag)) {
29
+ return range.primaryTag;
30
+ }
31
+ }
32
+ return undefined;
33
+ };
34
+ const requestedLocaleOf = (request, localeSet) => {
35
+ const header = request.headers['accept-language'];
36
+ return typeof header === 'string' ? resolveFromAcceptLanguage(header, localeSet) : undefined;
37
+ };
38
+ const chosenLocalesOf = (request, cookieName) => [
39
+ request.user?.locale,
40
+ request.cookies?.[cookieName],
41
+ ];
42
+ const resolveLocale = (request, options) => {
43
+ const { cookieName, localeSet } = options;
44
+ return chosenLocalesOf(request, cookieName).find((value) => localeSet.isSupported(value))
45
+ ?? requestedLocaleOf(request, localeSet)
46
+ ?? localeSet.fallback;
47
+ };
48
+ exports.resolveLocale = resolveLocale;
@@ -0,0 +1 @@
1
+ export type TranslateFunction = (key: string, named?: Record<string, unknown>) => string;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,20 @@
1
+ import type { App, WritableComputedRef } from 'vue';
2
+ import type { LocaleSetInterface } from '../define-locales.js';
3
+ import type { LocaleDictionary } from '../dictionary.js';
4
+ import type { TranslateFunction } from '../translate-function.js';
5
+ export interface I18nPluginOptionsInterface<L extends string> {
6
+ localeSet: LocaleSetInterface<L>;
7
+ messages: LocaleDictionary<L>;
8
+ moduleDictionaries?: ModuleDictionariesResolver<L>;
9
+ }
10
+ type LocaleReference = WritableComputedRef<string>;
11
+ type ModuleDictionariesResolver<L extends string> = (app: App) => readonly LocaleDictionary<L>[];
12
+ export declare class I18nPlugin<L extends string> {
13
+ private readonly options;
14
+ constructor(options: I18nPluginOptionsInterface<L>);
15
+ install(app: App): void;
16
+ }
17
+ export declare const setLocale: (app: App, locale: string) => void;
18
+ export declare const getLocaleReference: (app: App) => LocaleReference | undefined;
19
+ export declare const getTranslate: (app: App) => TranslateFunction | undefined;
20
+ export {};
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getTranslate = exports.getLocaleReference = exports.setLocale = exports.I18nPlugin = void 0;
4
+ const vue_i18n_1 = require("vue-i18n");
5
+ const dictionary_js_1 = require("../dictionary.js");
6
+ const localeReferences = new WeakMap();
7
+ const translators = new WeakMap();
8
+ class I18nPlugin {
9
+ options;
10
+ constructor(options) {
11
+ this.options = options;
12
+ }
13
+ install(app) {
14
+ const { localeSet, messages, moduleDictionaries } = this.options;
15
+ const dictionaries = moduleDictionaries === undefined
16
+ ? [messages]
17
+ : [messages, ...app.runWithContext(() => moduleDictionaries(app))];
18
+ const i18n = (0, vue_i18n_1.createI18n)({
19
+ fallbackLocale: localeSet.fallback,
20
+ legacy: false,
21
+ locale: localeSet.fallback,
22
+ messages: (0, dictionary_js_1.composeMessages)(dictionaries, localeSet.locales),
23
+ });
24
+ localeReferences.set(app, i18n.global.locale);
25
+ translators.set(app, (key, named) => i18n.global.t(key, named ?? {}));
26
+ app.use(i18n);
27
+ }
28
+ }
29
+ exports.I18nPlugin = I18nPlugin;
30
+ const setLocale = (app, locale) => {
31
+ const localeReference = localeReferences.get(app);
32
+ if (localeReference) {
33
+ localeReference.value = locale;
34
+ }
35
+ };
36
+ exports.setLocale = setLocale;
37
+ const getLocaleReference = (app) => localeReferences.get(app);
38
+ exports.getLocaleReference = getLocaleReference;
39
+ const getTranslate = (app) => translators.get(app);
40
+ exports.getTranslate = getTranslate;
@@ -0,0 +1,3 @@
1
+ export * from './i18n-plugin.js';
2
+ export * from './locale-cookie.js';
3
+ export * from './module-dictionary.js';
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./i18n-plugin.js"), exports);
18
+ __exportStar(require("./locale-cookie.js"), exports);
19
+ __exportStar(require("./module-dictionary.js"), exports);
@@ -0,0 +1,5 @@
1
+ export interface LocaleCookieOptionsInterface {
2
+ maxAgeSeconds?: number;
3
+ name: string;
4
+ }
5
+ export declare const writeLocaleCookie: (locale: string, options: LocaleCookieOptionsInterface) => void;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.writeLocaleCookie = void 0;
4
+ const DEFAULT_MAX_AGE_SECONDS = 31_536_000;
5
+ const writeLocaleCookie = (locale, options) => {
6
+ const { maxAgeSeconds = DEFAULT_MAX_AGE_SECONDS, name } = options;
7
+ globalThis.document.cookie = [
8
+ `${name}=${locale}`,
9
+ 'Path=/',
10
+ `Max-Age=${maxAgeSeconds}`,
11
+ 'SameSite=Lax',
12
+ ].join('; ');
13
+ };
14
+ exports.writeLocaleCookie = writeLocaleCookie;
@@ -0,0 +1,5 @@
1
+ import type { LocaleDictionary } from '../dictionary.js';
2
+ export interface ModuleRegistryInterface {
3
+ getModules(): Iterable<unknown>;
4
+ }
5
+ export declare const collectModuleDictionaries: <L extends string>(registry: ModuleRegistryInterface | undefined) => LocaleDictionary<L>[];
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.collectModuleDictionaries = void 0;
4
+ const isObject = (value) => typeof value === 'object' && value !== null;
5
+ const hasDictionary = (module) => isObject(module) && 'getDictionary' in module;
6
+ const collectModuleDictionaries = (registry) => (registry === undefined
7
+ ? []
8
+ : [...registry.getModules()]
9
+ .filter((module) => hasDictionary(module))
10
+ .map((module) => module.getDictionary()));
11
+ exports.collectModuleDictionaries = collectModuleDictionaries;
@@ -0,0 +1,10 @@
1
+ export interface LocaleSetInterface<L extends string> {
2
+ readonly fallback: L;
3
+ readonly isSupported: LocaleGuard<L>;
4
+ readonly locales: readonly L[];
5
+ }
6
+ type LocaleGuard<L extends string> = (value: unknown) => value is L;
7
+ export declare const defineLocales: <const T extends readonly [string, ...string[]]>(locales: T, fallback: NoInfer<T[number]>) => {
8
+ readonly locales: T;
9
+ } & LocaleSetInterface<T[number]>;
10
+ export {};
@@ -0,0 +1,11 @@
1
+ export const defineLocales = (locales, fallback) => {
2
+ const values = locales;
3
+ if (!values.includes(fallback)) {
4
+ throw new RangeError(`Запасная локаль «${fallback}» не входит в набор: ${locales.join(', ')}`);
5
+ }
6
+ return {
7
+ fallback,
8
+ isSupported: (value) => values.includes(value),
9
+ locales,
10
+ };
11
+ };
@@ -0,0 +1,4 @@
1
+ import type { LocaleDictionary } from './dictionary.js';
2
+ export interface DictionaryProviderInterface<L extends string> {
3
+ getDictionary(): LocaleDictionary<L>;
4
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,4 @@
1
+ import type { LocaleMessageValue, VueMessageType } from 'vue-i18n';
2
+ export type LocaleDictionary<L extends string> = Record<L, LocaleMessages>;
3
+ export type LocaleMessages = Record<string, LocaleMessageValue<VueMessageType>>;
4
+ export declare const composeMessages: <L extends string>(dictionaries: readonly LocaleDictionary<L>[], locales: readonly L[]) => LocaleDictionary<L>;
@@ -0,0 +1,9 @@
1
+ export const composeMessages = (dictionaries, locales) => {
2
+ const merged = new Map(locales.map((locale) => [locale, {}]));
3
+ for (const [locale, messages] of merged) {
4
+ for (const dictionary of dictionaries) {
5
+ Object.assign(messages, dictionary[locale]);
6
+ }
7
+ }
8
+ return Object.fromEntries(merged);
9
+ };
@@ -0,0 +1,4 @@
1
+ export * from './define-locales.js';
2
+ export * from './dictionary.js';
3
+ export * from './dictionary-provider.interface.js';
4
+ export * from './translate-function.js';
@@ -0,0 +1,4 @@
1
+ export * from './define-locales.js';
2
+ export * from './dictionary.js';
3
+ export * from './dictionary-provider.interface.js';
4
+ export * from './translate-function.js';
@@ -0,0 +1 @@
1
+ export * from './resolve-locale.js';
@@ -0,0 +1 @@
1
+ export * from './resolve-locale.js';
@@ -0,0 +1,13 @@
1
+ import type { LocaleSetInterface } from '../define-locales.js';
2
+ export interface LocaleRequestInterface {
3
+ cookies?: Partial<Record<string, string>> | undefined;
4
+ headers: Partial<Record<string, string | string[]>>;
5
+ user?: {
6
+ locale?: null | string;
7
+ } | undefined;
8
+ }
9
+ export interface ResolveLocaleOptionsInterface<L extends string> {
10
+ cookieName: string;
11
+ localeSet: LocaleSetInterface<L>;
12
+ }
13
+ export declare const resolveLocale: <L extends string>(request: LocaleRequestInterface, options: ResolveLocaleOptionsInterface<L>) => L;
@@ -0,0 +1,44 @@
1
+ const DEFAULT_QUALITY = 1;
2
+ const REJECTED_QUALITY = 0;
3
+ const QUALITY_PATTERN = /(?<=;\s*q=)[^;]*/u;
4
+ const SUBTAGS_AND_PARAMETERS_PATTERN = /[-;].*/u;
5
+ const parseQuality = (range) => {
6
+ const value = QUALITY_PATTERN.exec(range)?.[0];
7
+ if (value === undefined) {
8
+ return DEFAULT_QUALITY;
9
+ }
10
+ const quality = Number(value);
11
+ return Number.isNaN(quality) ? REJECTED_QUALITY : quality;
12
+ };
13
+ const parseLanguageRange = (range) => ({
14
+ primaryTag: range.replace(SUBTAGS_AND_PARAMETERS_PATTERN, '').trim()
15
+ .toLowerCase(),
16
+ quality: parseQuality(range),
17
+ });
18
+ const resolveFromAcceptLanguage = (header, localeSet) => {
19
+ const ranges = header
20
+ .split(',')
21
+ .map((range) => parseLanguageRange(range))
22
+ .filter((range) => range.quality > REJECTED_QUALITY)
23
+ .toSorted((left, right) => right.quality - left.quality);
24
+ for (const range of ranges) {
25
+ if (localeSet.isSupported(range.primaryTag)) {
26
+ return range.primaryTag;
27
+ }
28
+ }
29
+ return undefined;
30
+ };
31
+ const requestedLocaleOf = (request, localeSet) => {
32
+ const header = request.headers['accept-language'];
33
+ return typeof header === 'string' ? resolveFromAcceptLanguage(header, localeSet) : undefined;
34
+ };
35
+ const chosenLocalesOf = (request, cookieName) => [
36
+ request.user?.locale,
37
+ request.cookies?.[cookieName],
38
+ ];
39
+ export const resolveLocale = (request, options) => {
40
+ const { cookieName, localeSet } = options;
41
+ return chosenLocalesOf(request, cookieName).find((value) => localeSet.isSupported(value))
42
+ ?? requestedLocaleOf(request, localeSet)
43
+ ?? localeSet.fallback;
44
+ };
@@ -0,0 +1 @@
1
+ export type TranslateFunction = (key: string, named?: Record<string, unknown>) => string;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,20 @@
1
+ import type { App, WritableComputedRef } from 'vue';
2
+ import type { LocaleSetInterface } from '../define-locales.js';
3
+ import type { LocaleDictionary } from '../dictionary.js';
4
+ import type { TranslateFunction } from '../translate-function.js';
5
+ export interface I18nPluginOptionsInterface<L extends string> {
6
+ localeSet: LocaleSetInterface<L>;
7
+ messages: LocaleDictionary<L>;
8
+ moduleDictionaries?: ModuleDictionariesResolver<L>;
9
+ }
10
+ type LocaleReference = WritableComputedRef<string>;
11
+ type ModuleDictionariesResolver<L extends string> = (app: App) => readonly LocaleDictionary<L>[];
12
+ export declare class I18nPlugin<L extends string> {
13
+ private readonly options;
14
+ constructor(options: I18nPluginOptionsInterface<L>);
15
+ install(app: App): void;
16
+ }
17
+ export declare const setLocale: (app: App, locale: string) => void;
18
+ export declare const getLocaleReference: (app: App) => LocaleReference | undefined;
19
+ export declare const getTranslate: (app: App) => TranslateFunction | undefined;
20
+ export {};
@@ -0,0 +1,33 @@
1
+ import { createI18n } from 'vue-i18n';
2
+ import { composeMessages } from '../dictionary.js';
3
+ const localeReferences = new WeakMap();
4
+ const translators = new WeakMap();
5
+ export class I18nPlugin {
6
+ options;
7
+ constructor(options) {
8
+ this.options = options;
9
+ }
10
+ install(app) {
11
+ const { localeSet, messages, moduleDictionaries } = this.options;
12
+ const dictionaries = moduleDictionaries === undefined
13
+ ? [messages]
14
+ : [messages, ...app.runWithContext(() => moduleDictionaries(app))];
15
+ const i18n = createI18n({
16
+ fallbackLocale: localeSet.fallback,
17
+ legacy: false,
18
+ locale: localeSet.fallback,
19
+ messages: composeMessages(dictionaries, localeSet.locales),
20
+ });
21
+ localeReferences.set(app, i18n.global.locale);
22
+ translators.set(app, (key, named) => i18n.global.t(key, named ?? {}));
23
+ app.use(i18n);
24
+ }
25
+ }
26
+ export const setLocale = (app, locale) => {
27
+ const localeReference = localeReferences.get(app);
28
+ if (localeReference) {
29
+ localeReference.value = locale;
30
+ }
31
+ };
32
+ export const getLocaleReference = (app) => localeReferences.get(app);
33
+ export const getTranslate = (app) => translators.get(app);
@@ -0,0 +1,3 @@
1
+ export * from './i18n-plugin.js';
2
+ export * from './locale-cookie.js';
3
+ export * from './module-dictionary.js';
@@ -0,0 +1,3 @@
1
+ export * from './i18n-plugin.js';
2
+ export * from './locale-cookie.js';
3
+ export * from './module-dictionary.js';
@@ -0,0 +1,5 @@
1
+ export interface LocaleCookieOptionsInterface {
2
+ maxAgeSeconds?: number;
3
+ name: string;
4
+ }
5
+ export declare const writeLocaleCookie: (locale: string, options: LocaleCookieOptionsInterface) => void;
@@ -0,0 +1,10 @@
1
+ const DEFAULT_MAX_AGE_SECONDS = 31_536_000;
2
+ export const writeLocaleCookie = (locale, options) => {
3
+ const { maxAgeSeconds = DEFAULT_MAX_AGE_SECONDS, name } = options;
4
+ globalThis.document.cookie = [
5
+ `${name}=${locale}`,
6
+ 'Path=/',
7
+ `Max-Age=${maxAgeSeconds}`,
8
+ 'SameSite=Lax',
9
+ ].join('; ');
10
+ };
@@ -0,0 +1,5 @@
1
+ import type { LocaleDictionary } from '../dictionary.js';
2
+ export interface ModuleRegistryInterface {
3
+ getModules(): Iterable<unknown>;
4
+ }
5
+ export declare const collectModuleDictionaries: <L extends string>(registry: ModuleRegistryInterface | undefined) => LocaleDictionary<L>[];
@@ -0,0 +1,7 @@
1
+ const isObject = (value) => typeof value === 'object' && value !== null;
2
+ const hasDictionary = (module) => isObject(module) && 'getDictionary' in module;
3
+ export const collectModuleDictionaries = (registry) => (registry === undefined
4
+ ? []
5
+ : [...registry.getModules()]
6
+ .filter((module) => hasDictionary(module))
7
+ .map((module) => module.getDictionary()));
package/package.json CHANGED
@@ -1,6 +1,90 @@
1
1
  {
2
2
  "name": "@application-kit/i18n",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Локали, словари и плагин vue-i18n для SSR-приложений на Vue и серверный резолв локали запроса",
5
+ "keywords": [
6
+ "i18n",
7
+ "locale",
8
+ "ssr",
9
+ "vue",
10
+ "vue-i18n"
11
+ ],
12
+ "homepage": "https://gitlab.com/application-kit/application-kit/-/tree/main/packages/i18n",
13
+ "bugs": "https://gitlab.com/application-kit/application-kit/-/issues",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "https://gitlab.com/application-kit/application-kit.git",
17
+ "directory": "packages/i18n"
18
+ },
19
+ "license": "MIT",
20
+ "author": {
21
+ "name": "application-kit"
22
+ },
23
+ "sideEffects": false,
24
+ "type": "module",
25
+ "exports": {
26
+ ".": {
27
+ "import": {
28
+ "types": "./dist/esm/index.d.ts",
29
+ "default": "./dist/esm/index.js"
30
+ },
31
+ "require": {
32
+ "types": "./dist/cjs/index.d.ts",
33
+ "default": "./dist/cjs/index.js"
34
+ }
35
+ },
36
+ "./package.json": "./package.json",
37
+ "./server": {
38
+ "import": {
39
+ "types": "./dist/esm/server/index.d.ts",
40
+ "default": "./dist/esm/server/index.js"
41
+ },
42
+ "require": {
43
+ "types": "./dist/cjs/server/index.d.ts",
44
+ "default": "./dist/cjs/server/index.js"
45
+ }
46
+ },
47
+ "./vue": {
48
+ "import": {
49
+ "types": "./dist/esm/vue/index.d.ts",
50
+ "default": "./dist/esm/vue/index.js"
51
+ },
52
+ "require": {
53
+ "types": "./dist/cjs/vue/index.d.ts",
54
+ "default": "./dist/cjs/vue/index.js"
55
+ }
56
+ }
57
+ },
58
+ "main": "./dist/cjs/index.js",
59
+ "module": "./dist/esm/index.js",
60
+ "types": "./dist/cjs/index.d.ts",
61
+ "files": [
62
+ "dist"
63
+ ],
64
+ "scripts": {
65
+ "build": "rm -rf ./dist && node ../../scripts/barrels.mjs create ./src --entry-only=server,vue && tsc --project tsconfig.build.json && tsc --project tsconfig.build.cjs.json && node ../../scripts/barrels.mjs clean ./src && node ../../scripts/mark-cjs.mjs ./dist/cjs",
66
+ "lint:tsc": "tsc --noEmit --pretty --project .",
67
+ "test:mutation": "stryker run",
68
+ "test:unit": "vitest run"
69
+ },
70
+ "devDependencies": {
71
+ "@stryker-mutator/core": "^10.0.0",
72
+ "@stryker-mutator/vitest-runner": "^10.0.0",
73
+ "@types/node": "^26.2.0",
74
+ "jsdom": "^30.0.1",
75
+ "typescript": "^6.0.3",
76
+ "vitest": "^4.1.11",
77
+ "vue": "^3.5.41",
78
+ "vue-i18n": "^11.4.10"
79
+ },
80
+ "peerDependencies": {
81
+ "vue": "^3.5.0",
82
+ "vue-i18n": "^11.0.0"
83
+ },
84
+ "engines": {
85
+ "node": ">=24"
86
+ },
87
+ "publishConfig": {
88
+ "access": "public"
89
+ }
6
90
  }