@application-kit/i18n 0.1.0 → 0.3.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/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # @application-kit/i18n
2
2
 
3
+ ## 0.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 61cb664: `useTranslate()` во входе `@application-kit/i18n/vue` — перевод и локаль для компонента без импорта `vue-i18n`. Пресет `@application-kit/lint-config` запрещает импорт `vue-i18n` в `src/libs` и `src/modules`.
8
+
9
+ ## 0.2.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 6ddb211: Вход `/testing`: `createFakeTranslate(dictionary, defaultLocale)` — перевод для спек кода, принимающего `t` зависимостью:
14
+ ходит в настоящий словарь, подставляет именованные строки и числа, на отсутствующий ключ бросает `TypeError`; локаль —
15
+ обобщённый параметр, язык по умолчанию называет вызывающий. `vue-i18n` вход не тянет.
16
+
3
17
  ## 0.1.0
4
18
 
5
19
  ### Minor Changes
package/README.md CHANGED
@@ -19,6 +19,7 @@ Peer-зависимости: `vue`, `vue-i18n` — экземпляр у при
19
19
  | `@application-kit/i18n` | изоморфно: набор локалей, тип словаря, сборка словаря, тип перевода | ничего (типы `vue-i18n`) |
20
20
  | `@application-kit/i18n/vue` | клиент и SSR-рендер: плагин, доступ к локали и переводу, cookie выбора | `vue`, `vue-i18n` |
21
21
  | `@application-kit/i18n/server` | сервер: локаль запроса | ничего |
22
+ | `@application-kit/i18n/testing` | спеки потребителя: перевод по словарю без `vue-i18n` | ничего |
22
23
 
23
24
  Импорт любого входа не имеет побочных эффектов и не требует окружения: состояние плагина заводится на
24
25
  установке в приложение, а не на загрузке модуля.
@@ -52,6 +53,8 @@ app.use(new I18nPlugin({
52
53
  - `I18nPlugin` — ставит `vue-i18n` (Composition API), стартовая и запасная локаль — `localeSet.fallback`.
53
54
  - `collectModuleDictionaries(registry)` — словари модулей реестра в порядке регистрации. Реестр структурный:
54
55
  достаточно `getModules()`; словарь берётся у модуля с методом `getDictionary`.
56
+ - `useTranslate()` — перевод и локаль в `setup` компонента: `{ locale, t }`, область всегда глобальная, запись в
57
+ `locale` меняет язык всего приложения. Приложение импортирует его, а не `vue-i18n`: механизм словаря меняется в пакете.
55
58
  - `setLocale(app, locale)`, `getLocaleReference(app)`, `getTranslate(app)` — локаль и перевод конкретного
56
59
  экземпляра приложения для кода вне компонентов. Состояние хранится по `App` (`WeakMap`), а не в модуле:
57
60
  на сервере модуль живёт между запросами, и язык одного пользователя не доезжает до другого.
@@ -64,3 +67,16 @@ app.use(new I18nPlugin({
64
67
  `Accept-Language` с весами `q` (`q=0` отклоняет язык, `ru-RU` — это `ru`) → `localeSet.fallback`. Испорченное
65
68
  значение любого источника читается как «предпочтения нет». Запрос описан структурно (`LocaleRequestInterface`) —
66
69
  подходит запрос Fastify с `@fastify/cookie` и без привязки к фреймворку.
70
+
71
+ ## Тесты потребителя
72
+
73
+ - `createFakeTranslate(dictionary, defaultLocale)` — фабрика `(locale = defaultLocale) => TranslateFunction` для спек кода,
74
+ который принимает `t` зависимостью. Фейк, а не заглушка: ходит в настоящий словарь, подставляет именованные строки и
75
+ числа (`{name}`), на отсутствующий ключ бросает `TypeError` — опечатка в ключе валит спеку, а не проходит как «какой-то
76
+ текст вернулся».
77
+
78
+ ```ts
79
+ export const fakeTranslate = createFakeTranslate(messages, localeSet.fallback)
80
+
81
+ useUserListActions({ translate: fakeTranslate() })
82
+ ```
@@ -0,0 +1,3 @@
1
+ import type { LocaleDictionary } from '../dictionary.js';
2
+ import type { TranslateFunction } from '../translate-function.js';
3
+ export declare const createFakeTranslate: <L extends string>(dictionary: LocaleDictionary<L>, defaultLocale: L) => (locale?: L) => TranslateFunction;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createFakeTranslate = void 0;
4
+ const resolveTemplate = (dictionary, locale, key) => {
5
+ let node = dictionary[locale];
6
+ for (const part of key.split('.')) {
7
+ node = node instanceof Object ? Reflect.get(node, part) : undefined;
8
+ }
9
+ return node;
10
+ };
11
+ const createFakeTranslate = (dictionary, defaultLocale) => (locale = defaultLocale) => (key, named) => {
12
+ const template = resolveTemplate(dictionary, locale, key);
13
+ if (typeof template !== 'string') {
14
+ throw new TypeError(`Ключа нет в словаре: ${key}`);
15
+ }
16
+ return template.replaceAll(/\{(?<name>\w+)\}/gu, (_match, name) => {
17
+ const value = named?.[name];
18
+ return typeof value === 'string' || typeof value === 'number' ? String(value) : '';
19
+ });
20
+ };
21
+ exports.createFakeTranslate = createFakeTranslate;
@@ -0,0 +1 @@
1
+ export * from './fake-translate.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("./fake-translate.js"), exports);
@@ -1,3 +1,4 @@
1
1
  export * from './i18n-plugin.js';
2
2
  export * from './locale-cookie.js';
3
3
  export * from './module-dictionary.js';
4
+ export * from './use-translate.js';
@@ -17,3 +17,4 @@ Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./i18n-plugin.js"), exports);
18
18
  __exportStar(require("./locale-cookie.js"), exports);
19
19
  __exportStar(require("./module-dictionary.js"), exports);
20
+ __exportStar(require("./use-translate.js"), exports);
@@ -0,0 +1,7 @@
1
+ import type { WritableComputedRef } from 'vue';
2
+ import type { TranslateFunction } from '../translate-function.js';
3
+ export interface TranslateComposableInterface {
4
+ locale: WritableComputedRef<string>;
5
+ t: TranslateFunction;
6
+ }
7
+ export declare const useTranslate: () => TranslateComposableInterface;
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useTranslate = void 0;
4
+ const vue_i18n_1 = require("vue-i18n");
5
+ const useTranslate = () => {
6
+ const { locale, t } = (0, vue_i18n_1.useI18n)({ useScope: 'global' });
7
+ return { locale, t: (key, named) => t(key, named ?? {}) };
8
+ };
9
+ exports.useTranslate = useTranslate;
@@ -0,0 +1,3 @@
1
+ import type { LocaleDictionary } from '../dictionary.js';
2
+ import type { TranslateFunction } from '../translate-function.js';
3
+ export declare const createFakeTranslate: <L extends string>(dictionary: LocaleDictionary<L>, defaultLocale: L) => (locale?: L) => TranslateFunction;
@@ -0,0 +1,17 @@
1
+ const resolveTemplate = (dictionary, locale, key) => {
2
+ let node = dictionary[locale];
3
+ for (const part of key.split('.')) {
4
+ node = node instanceof Object ? Reflect.get(node, part) : undefined;
5
+ }
6
+ return node;
7
+ };
8
+ export const createFakeTranslate = (dictionary, defaultLocale) => (locale = defaultLocale) => (key, named) => {
9
+ const template = resolveTemplate(dictionary, locale, key);
10
+ if (typeof template !== 'string') {
11
+ throw new TypeError(`Ключа нет в словаре: ${key}`);
12
+ }
13
+ return template.replaceAll(/\{(?<name>\w+)\}/gu, (_match, name) => {
14
+ const value = named?.[name];
15
+ return typeof value === 'string' || typeof value === 'number' ? String(value) : '';
16
+ });
17
+ };
@@ -0,0 +1 @@
1
+ export * from './fake-translate.js';
@@ -0,0 +1 @@
1
+ export * from './fake-translate.js';
@@ -1,3 +1,4 @@
1
1
  export * from './i18n-plugin.js';
2
2
  export * from './locale-cookie.js';
3
3
  export * from './module-dictionary.js';
4
+ export * from './use-translate.js';
@@ -1,3 +1,4 @@
1
1
  export * from './i18n-plugin.js';
2
2
  export * from './locale-cookie.js';
3
3
  export * from './module-dictionary.js';
4
+ export * from './use-translate.js';
@@ -0,0 +1,7 @@
1
+ import type { WritableComputedRef } from 'vue';
2
+ import type { TranslateFunction } from '../translate-function.js';
3
+ export interface TranslateComposableInterface {
4
+ locale: WritableComputedRef<string>;
5
+ t: TranslateFunction;
6
+ }
7
+ export declare const useTranslate: () => TranslateComposableInterface;
@@ -0,0 +1,5 @@
1
+ import { useI18n } from 'vue-i18n';
2
+ export const useTranslate = () => {
3
+ const { locale, t } = useI18n({ useScope: 'global' });
4
+ return { locale, t: (key, named) => t(key, named ?? {}) };
5
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@application-kit/i18n",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Локали, словари и плагин vue-i18n для SSR-приложений на Vue и серверный резолв локали запроса",
5
5
  "keywords": [
6
6
  "i18n",
@@ -44,6 +44,16 @@
44
44
  "default": "./dist/cjs/server/index.js"
45
45
  }
46
46
  },
47
+ "./testing": {
48
+ "import": {
49
+ "types": "./dist/esm/testing/index.d.ts",
50
+ "default": "./dist/esm/testing/index.js"
51
+ },
52
+ "require": {
53
+ "types": "./dist/cjs/testing/index.d.ts",
54
+ "default": "./dist/cjs/testing/index.js"
55
+ }
56
+ },
47
57
  "./vue": {
48
58
  "import": {
49
59
  "types": "./dist/esm/vue/index.d.ts",
@@ -62,7 +72,7 @@
62
72
  "dist"
63
73
  ],
64
74
  "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",
75
+ "build": "rm -rf ./dist && node ../../scripts/barrels.mjs create ./src --entry-only=server,testing,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
76
  "lint:tsc": "tsc --noEmit --pretty --project .",
67
77
  "test:mutation": "stryker run",
68
78
  "test:unit": "vitest run"