@i18n-micro/node 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2016
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 ADDED
@@ -0,0 +1,43 @@
1
+ # @i18n-micro/node
2
+
3
+ Node.js runtime for nuxt-i18n-micro - use i18n translations in any Node.js application, CLI tool, or backend service.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pnpm add @i18n-micro/node
9
+ # or
10
+ npm install @i18n-micro/node
11
+ # or
12
+ yarn add @i18n-micro/node
13
+ ```
14
+
15
+ ## Quick Start
16
+
17
+ ```typescript
18
+ import { createI18n } from '@i18n-micro/node'
19
+
20
+ // 1. Create I18n instance
21
+ const i18n = createI18n({
22
+ locale: 'en',
23
+ fallbackLocale: 'en',
24
+ translationDir: './locales', // Path to your locales directory
25
+ disablePageLocales: false, // If true, ignores pages/ folder and treats all files as global translations
26
+ })
27
+
28
+ // 2. Load translations from directory (recursive, supports pages structure)
29
+ await i18n.loadTranslations()
30
+
31
+ // 3. Use translations
32
+ console.log(i18n.t('greeting', { name: 'John' })) // "Hello, John!"
33
+ console.log(i18n.tc('apples', 5)) // "5 apples"
34
+ ```
35
+
36
+ ## Resources
37
+
38
+ - **Repository**: [https://github.com/s00d/nuxt-i18n-micro](https://github.com/s00d/nuxt-i18n-micro)
39
+ - **Documentation**: [https://s00d.github.io/nuxt-i18n-micro/](https://s00d.github.io/nuxt-i18n-micro/)
40
+
41
+ ## License
42
+
43
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const b=require("node:fs/promises"),f=require("node:path"),c=require("@i18n-micro/core");async function g(l,e=!1){const t={global:{},routes:{}};try{const r=await b.readdir(l,{recursive:!0,withFileTypes:!0});for(const a of r){if(!a.isFile()||!a.name.endsWith(".json"))continue;const s=f.join(a.path,a.name),o=f.relative(l,s).split(f.sep),i=f.basename(a.name,".json");try{const h=await b.readFile(s,"utf-8"),u=JSON.parse(h);if(!e&&o[0]==="pages"&&o.length>=2){const m=o.slice(1,-1);if(m.length>0){const d=m.join("-");t.routes[d]||(t.routes[d]={}),t.routes[d][i]=u}}else t.global[i]=u}catch(h){console.error(`Failed to load translation file ${s}:`,h)}}}catch(r){r&&typeof r=="object"&&"code"in r&&r.code!=="ENOENT"&&console.error(`Failed to read directory ${l}:`,r)}return t}async function T(l,e=!1){const{global:t}=await g(l,e);return t}class p{constructor(e){this.currentRoute="general",this.cache={generalLocaleCache:{},routeLocaleCache:{},dynamicTranslationsCaches:[],serverTranslationCache:{}},this.helper=c.useTranslationHelper(this.cache),this.formatter=new c.FormatService,this.locale=e.locale,this.fallbackLocale=e.fallbackLocale||e.locale,this.translationDir=e.translationDir,this.disablePageLocales=e.disablePageLocales??!1,this.pluralFunc=e.plural||c.defaultPlural,this.missingWarn=e.missingWarn??!1,this.missingHandler=e.missingHandler}setRoute(e){this.currentRoute=e}getRoute(){return this.currentRoute}t(e,t,r,a){if(!e)return"";const s=a||this.currentRoute;let n=this.helper.getTranslation(this.locale,s,e);return!n&&this.locale!==this.fallbackLocale&&(n=this.helper.getTranslation(this.fallbackLocale,s,e)),n||(this.missingHandler?this.missingHandler(this.locale,e,s):this.missingWarn&&console.warn(`[i18n] Translation key '${e}' not found for locale '${this.locale}' (route: '${s}').`),n=r===void 0?e:r||e),typeof n=="string"&&t?c.interpolate(n,t):n||e}ts(e,t,r,a){return this.t(e,t,r,a)?.toString()??r??e}tc(e,t,r){const{count:a,...s}=typeof t=="number"?{count:t}:t;if(a===void 0)return r??e;const n=(i,h,u)=>this.t(i,h,u);return this.pluralFunc(e,Number.parseInt(a.toString()),s,this.locale,n)??r??e}tn(e,t){return this.formatter.formatNumber(e,this.locale,t)}td(e,t){return this.formatter.formatDate(e,this.locale,t)}tdr(e,t){return this.formatter.formatRelativeTime(e,this.locale,t)}async loadTranslations(e){const t=e||this.translationDir;if(!t){console.warn("[i18n-node] No translation directory specified");return}const{global:r,routes:a}=await g(t,this.disablePageLocales);for(const[s,n]of Object.entries(r))this.helper.mergeGlobalTranslation(s,n,!0);for(const[s,n]of Object.entries(a))for(const[o,i]of Object.entries(n))await this.helper.loadPageTranslations(o,s,i)}async reload(){this.helper.clearCache(),await this.loadTranslations(),console.log("[i18n-node] Cache cleared and translations reloaded.")}addTranslations(e,t,r=!0){r?this.helper.mergeGlobalTranslation(e,t,!0):this.helper.loadTranslations(e,t)}addRouteTranslations(e,t,r,a=!0){a?this.helper.mergeTranslation(e,t,r,!0):this.helper.loadPageTranslations(e,t,r)}hasTranslation(e){return this.helper.hasTranslation(this.locale,e)}clear(){this.helper.clearCache()}}function v(l){return new p(l)}Object.defineProperty(exports,"FormatService",{enumerable:!0,get:()=>c.FormatService});Object.defineProperty(exports,"interpolate",{enumerable:!0,get:()=>c.interpolate});exports.I18n=p;exports.createI18n=v;exports.loadGlobalTranslations=T;exports.loadTranslations=g;
@@ -0,0 +1,144 @@
1
+ import { CleanTranslation } from '@i18n-micro/types';
2
+ import { FormatService } from '@i18n-micro/core';
3
+ import { Getter } from '@i18n-micro/types';
4
+ import { interpolate } from '@i18n-micro/core';
5
+ import { Locale } from '@i18n-micro/types';
6
+ import { LocaleCode } from '@i18n-micro/types';
7
+ import { Params } from '@i18n-micro/types';
8
+ import { PluralFunc } from '@i18n-micro/types';
9
+ import { TranslationKey } from '@i18n-micro/types';
10
+ import { Translations } from '@i18n-micro/types';
11
+
12
+ export { CleanTranslation }
13
+
14
+ /**
15
+ * Create a new I18n instance
16
+ */
17
+ export declare function createI18n(options: I18nOptions): I18n;
18
+
19
+ export { FormatService }
20
+
21
+ export { Getter }
22
+
23
+ /**
24
+ * Node.js I18n Adapter
25
+ *
26
+ * Provides a standalone i18n instance that uses the shared core logic from nuxt-i18n-micro.
27
+ * Fully compatible with the file structure and caching mechanisms of the Nuxt module.
28
+ */
29
+ export declare class I18n {
30
+ locale: string;
31
+ fallbackLocale: string;
32
+ translationDir?: string;
33
+ private disablePageLocales;
34
+ /**
35
+ * Current active route name for translations.
36
+ * Defaults to 'general' (global translations only).
37
+ * Change this using setRoute() to access page-specific translations.
38
+ */
39
+ currentRoute: string;
40
+ private cache;
41
+ readonly helper: {
42
+ hasCache(locale: string, page: string): boolean;
43
+ getCache(locale: string, routeName: string): Map<string, unknown> | undefined;
44
+ setCache(locale: string, routeName: string, cache: Map<string, Translations | unknown>): void;
45
+ mergeTranslation(locale: string, routeName: string, newTranslations: Translations, force?: boolean): void;
46
+ mergeGlobalTranslation(locale: string, newTranslations: Translations, force?: boolean): void;
47
+ hasGeneralTranslation(locale: string): boolean;
48
+ hasPageTranslation(locale: string, routeName: string): boolean;
49
+ hasTranslation: (locale: string, key: TranslationKey) => boolean;
50
+ getTranslation: <T = unknown>(locale: string, routeName: string, key: TranslationKey) => T | null;
51
+ loadPageTranslations(locale: string, routeName: string, translations: Translations): Promise<void>;
52
+ loadTranslations(locale: string, translations: Translations): Promise<void>;
53
+ clearCache(): void;
54
+ };
55
+ private formatter;
56
+ private pluralFunc;
57
+ private missingWarn;
58
+ private missingHandler?;
59
+ constructor(options: I18nOptions);
60
+ /**
61
+ * Set the current route name context.
62
+ * Useful when processing a specific page request in Node.
63
+ */
64
+ setRoute(routeName: string): void;
65
+ getRoute(): string;
66
+ /**
67
+ * Get translation for a key
68
+ *
69
+ * Search order:
70
+ * 1. Current Locale + Current Route (Specific)
71
+ * 2. Current Locale + General (Global)
72
+ * 3. Fallback Locale + Current Route
73
+ * 4. Fallback Locale + General
74
+ */
75
+ t(key: TranslationKey, params?: Params, defaultValue?: string | null, routeName?: string): string;
76
+ /**
77
+ * Get translation as string
78
+ */
79
+ ts(key: TranslationKey, params?: Params, defaultValue?: string, routeName?: string): string;
80
+ /**
81
+ * Plural translation
82
+ */
83
+ tc(key: TranslationKey, count: number | Params, defaultValue?: string): string;
84
+ tn(value: number, options?: Intl.NumberFormatOptions): string;
85
+ td(value: Date | number | string, options?: Intl.DateTimeFormatOptions): string;
86
+ tdr(value: Date | number | string, options?: Intl.RelativeTimeFormatOptions): string;
87
+ /**
88
+ * Load translations from directory.
89
+ */
90
+ loadTranslations(dir?: string): Promise<void>;
91
+ /**
92
+ * Clear cache and reload translations from disk
93
+ */
94
+ reload(): Promise<void>;
95
+ addTranslations(locale: string, translations: Translations, merge?: boolean): void;
96
+ addRouteTranslations(locale: string, routeName: string, translations: Translations, merge?: boolean): void;
97
+ hasTranslation(key: TranslationKey): boolean;
98
+ clear(): void;
99
+ }
100
+
101
+ export declare interface I18nOptions {
102
+ locale: string;
103
+ fallbackLocale?: string;
104
+ translationDir?: string;
105
+ plural?: PluralFunc;
106
+ missingWarn?: boolean;
107
+ missingHandler?: (locale: string, key: string, routeName: string) => void;
108
+ disablePageLocales?: boolean;
109
+ }
110
+
111
+ export { interpolate }
112
+
113
+ export declare interface LoadedTranslations {
114
+ global: Record<string, Translations>;
115
+ routes: Record<string, Record<string, Translations>>;
116
+ }
117
+
118
+ /**
119
+ * Load only global translations from a directory
120
+ * @param dir - Directory path containing translation files
121
+ * @param disablePageLocales - If true, ignores pages/ folder and treats all files as global translations
122
+ */
123
+ export declare function loadGlobalTranslations(dir: string, disablePageLocales?: boolean): Promise<Record<string, Translations>>;
124
+
125
+ /**
126
+ * Load translations from a directory
127
+ * Supports both flat structure (locales/{lang}.json) and nested structure (locales/pages/{page}/{lang}.json)
128
+ * @param dir - Directory path containing translation files
129
+ * @param disablePageLocales - If true, ignores pages/ folder and treats all files as global translations
130
+ * @returns Object with global and route-specific translations
131
+ */
132
+ export declare function loadTranslations(dir: string, disablePageLocales?: boolean): Promise<LoadedTranslations>;
133
+
134
+ export { Locale }
135
+
136
+ export { LocaleCode }
137
+
138
+ export { Params }
139
+
140
+ export { PluralFunc }
141
+
142
+ export { Translations }
143
+
144
+ export { }
package/dist/index.mjs ADDED
@@ -0,0 +1,154 @@
1
+ import { readdir as m, readFile as g } from "node:fs/promises";
2
+ import { join as p, relative as T, sep as b, basename as v } from "node:path";
3
+ import { useTranslationHelper as w, FormatService as L, defaultPlural as P, interpolate as F } from "@i18n-micro/core";
4
+ import { FormatService as $, interpolate as y } from "@i18n-micro/core";
5
+ async function d(o, e = !1) {
6
+ const t = {
7
+ global: {},
8
+ routes: {}
9
+ };
10
+ try {
11
+ const r = await m(o, { recursive: !0, withFileTypes: !0 });
12
+ for (const a of r) {
13
+ if (!a.isFile() || !a.name.endsWith(".json"))
14
+ continue;
15
+ const s = p(a.path, a.name), n = T(o, s).split(b), i = v(a.name, ".json");
16
+ try {
17
+ const c = await g(s, "utf-8"), h = JSON.parse(c);
18
+ if (!e && n[0] === "pages" && n.length >= 2) {
19
+ const f = n.slice(1, -1);
20
+ if (f.length > 0) {
21
+ const u = f.join("-");
22
+ t.routes[u] || (t.routes[u] = {}), t.routes[u][i] = h;
23
+ }
24
+ } else
25
+ t.global[i] = h;
26
+ } catch (c) {
27
+ console.error(`Failed to load translation file ${s}:`, c);
28
+ }
29
+ }
30
+ } catch (r) {
31
+ r && typeof r == "object" && "code" in r && r.code !== "ENOENT" && console.error(`Failed to read directory ${o}:`, r);
32
+ }
33
+ return t;
34
+ }
35
+ async function D(o, e = !1) {
36
+ const { global: t } = await d(o, e);
37
+ return t;
38
+ }
39
+ class j {
40
+ constructor(e) {
41
+ this.currentRoute = "general", this.cache = {
42
+ generalLocaleCache: {},
43
+ routeLocaleCache: {},
44
+ dynamicTranslationsCaches: [],
45
+ serverTranslationCache: {}
46
+ }, this.helper = w(this.cache), this.formatter = new L(), this.locale = e.locale, this.fallbackLocale = e.fallbackLocale || e.locale, this.translationDir = e.translationDir, this.disablePageLocales = e.disablePageLocales ?? !1, this.pluralFunc = e.plural || P, this.missingWarn = e.missingWarn ?? !1, this.missingHandler = e.missingHandler;
47
+ }
48
+ /**
49
+ * Set the current route name context.
50
+ * Useful when processing a specific page request in Node.
51
+ */
52
+ setRoute(e) {
53
+ this.currentRoute = e;
54
+ }
55
+ getRoute() {
56
+ return this.currentRoute;
57
+ }
58
+ /**
59
+ * Get translation for a key
60
+ *
61
+ * Search order:
62
+ * 1. Current Locale + Current Route (Specific)
63
+ * 2. Current Locale + General (Global)
64
+ * 3. Fallback Locale + Current Route
65
+ * 4. Fallback Locale + General
66
+ */
67
+ t(e, t, r, a) {
68
+ if (!e) return "";
69
+ const s = a || this.currentRoute;
70
+ let l = this.helper.getTranslation(this.locale, s, e);
71
+ return !l && this.locale !== this.fallbackLocale && (l = this.helper.getTranslation(this.fallbackLocale, s, e)), l || (this.missingHandler ? this.missingHandler(this.locale, e, s) : this.missingWarn && console.warn(
72
+ `[i18n] Translation key '${e}' not found for locale '${this.locale}' (route: '${s}').`
73
+ ), l = r === void 0 ? e : r || e), typeof l == "string" && t ? F(l, t) : l || e;
74
+ }
75
+ /**
76
+ * Get translation as string
77
+ */
78
+ ts(e, t, r, a) {
79
+ return this.t(e, t, r, a)?.toString() ?? r ?? e;
80
+ }
81
+ /**
82
+ * Plural translation
83
+ */
84
+ tc(e, t, r) {
85
+ const { count: a, ...s } = typeof t == "number" ? { count: t } : t;
86
+ if (a === void 0)
87
+ return r ?? e;
88
+ const l = (i, c, h) => this.t(i, c, h);
89
+ return this.pluralFunc(
90
+ e,
91
+ Number.parseInt(a.toString()),
92
+ s,
93
+ this.locale,
94
+ l
95
+ ) ?? r ?? e;
96
+ }
97
+ // --- Formatters ---
98
+ tn(e, t) {
99
+ return this.formatter.formatNumber(e, this.locale, t);
100
+ }
101
+ td(e, t) {
102
+ return this.formatter.formatDate(e, this.locale, t);
103
+ }
104
+ tdr(e, t) {
105
+ return this.formatter.formatRelativeTime(e, this.locale, t);
106
+ }
107
+ // --- Loader & Cache Management ---
108
+ /**
109
+ * Load translations from directory.
110
+ */
111
+ async loadTranslations(e) {
112
+ const t = e || this.translationDir;
113
+ if (!t) {
114
+ console.warn("[i18n-node] No translation directory specified");
115
+ return;
116
+ }
117
+ const { global: r, routes: a } = await d(t, this.disablePageLocales);
118
+ for (const [s, l] of Object.entries(r))
119
+ this.helper.mergeGlobalTranslation(s, l, !0);
120
+ for (const [s, l] of Object.entries(a))
121
+ for (const [n, i] of Object.entries(l))
122
+ await this.helper.loadPageTranslations(n, s, i);
123
+ }
124
+ /**
125
+ * Clear cache and reload translations from disk
126
+ */
127
+ async reload() {
128
+ this.helper.clearCache(), await this.loadTranslations(), console.log("[i18n-node] Cache cleared and translations reloaded.");
129
+ }
130
+ // --- Manual Manipulation ---
131
+ addTranslations(e, t, r = !0) {
132
+ r ? this.helper.mergeGlobalTranslation(e, t, !0) : this.helper.loadTranslations(e, t);
133
+ }
134
+ addRouteTranslations(e, t, r, a = !0) {
135
+ a ? this.helper.mergeTranslation(e, t, r, !0) : this.helper.loadPageTranslations(e, t, r);
136
+ }
137
+ hasTranslation(e) {
138
+ return this.helper.hasTranslation(this.locale, e);
139
+ }
140
+ clear() {
141
+ this.helper.clearCache();
142
+ }
143
+ }
144
+ function H(o) {
145
+ return new j(o);
146
+ }
147
+ export {
148
+ $ as FormatService,
149
+ j as I18n,
150
+ H as createI18n,
151
+ y as interpolate,
152
+ D as loadGlobalTranslations,
153
+ d as loadTranslations
154
+ };
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@i18n-micro/node",
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "main": "./dist/index.cjs",
6
+ "module": "./dist/index.mjs",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.mjs",
12
+ "require": "./dist/index.cjs"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "engines": {
19
+ "node": ">=20.0.0"
20
+ },
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "dependencies": {
25
+ "@i18n-micro/core": "1.0.27",
26
+ "@i18n-micro/types": "1.0.15"
27
+ },
28
+ "devDependencies": {
29
+ "@types/node": "^20.17.10",
30
+ "vite": "^5.0.0",
31
+ "vite-plugin-dts": "^4.3.0",
32
+ "jest": "^29.7.0",
33
+ "ts-jest": "^29.1.2",
34
+ "@types/jest": "^29.5.0"
35
+ },
36
+ "scripts": {
37
+ "build": "vite build",
38
+ "dev": "cd playground && npm run dev",
39
+ "test": "jest",
40
+ "typecheck": "tsc --noEmit"
41
+ }
42
+ }