@i18n-micro/types-generator 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,62 @@
1
+ # @i18n-micro/types-generator
2
+
3
+ Type generator for i18n-micro translation keys. Automatically generates TypeScript types from JSON translation files.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install -D @i18n-micro/types-generator
9
+ # or
10
+ pnpm add -D @i18n-micro/types-generator
11
+ # or
12
+ yarn add -D @i18n-micro/types-generator
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ### Nuxt
18
+
19
+ Add to `nuxt.config.ts`:
20
+
21
+ ```typescript
22
+ export default defineNuxtConfig({
23
+ modules: [
24
+ 'nuxt-i18n-micro',
25
+ '@i18n-micro/types-generator/nuxt',
26
+ ],
27
+ })
28
+ ```
29
+
30
+ ### Vite/Vue
31
+
32
+ Add to `vite.config.ts`:
33
+
34
+ ```typescript
35
+ import { I18nTypesPlugin } from '@i18n-micro/types-generator'
36
+
37
+ export default defineConfig({
38
+ plugins: [
39
+ I18nTypesPlugin({
40
+ srcDir: 'src',
41
+ translationDir: 'locales',
42
+ }),
43
+ ],
44
+ })
45
+ ```
46
+
47
+ ## Features
48
+
49
+ - 🔍 Automatic type generation from JSON files
50
+ - ✅ Full type safety for translation keys
51
+ - 🎯 IDE autocomplete support
52
+ - 🔄 Hot reload on file changes
53
+ - 🚀 Zero runtime overhead
54
+
55
+ ## Documentation
56
+
57
+ See [full documentation](../../docs/integrations/types-generator.md) for detailed usage and examples.
58
+
59
+ ## License
60
+
61
+ MIT
62
+
@@ -0,0 +1,22 @@
1
+ export interface GeneratorOptions {
2
+ srcDir: string;
3
+ translationDir: string;
4
+ outputFile?: string;
5
+ }
6
+ /**
7
+ * Генерирует строку с TypeScript типами для ключей переводов.
8
+ * Не записывает файл, только возвращает содержимое.
9
+ *
10
+ * @param options - Опции генератора
11
+ * @returns Строка с содержимым .d.ts файла
12
+ */
13
+ export declare function getTypesString(options: GeneratorOptions): Promise<string>;
14
+ /**
15
+ * Генерирует TypeScript типы для ключей переводов из JSON файлов.
16
+ * Записывает результат в файл.
17
+ *
18
+ * @param options - Опции генератора
19
+ * @returns Путь к сгенерированному файлу
20
+ */
21
+ export declare function generateTypes(options: GeneratorOptions): Promise<string>;
22
+ //# sourceMappingURL=generator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generator.d.ts","sourceRoot":"","sources":["../../src/core/generator.ts"],"names":[],"mappings":"AAKA,MAAM,WAAW,gBAAgB;IAC/B,MAAM,EAAE,MAAM,CAAA;IACd,cAAc,EAAE,MAAM,CAAA;IACtB,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB;AAED;;;;;;GAMG;AACH,wBAAsB,cAAc,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,MAAM,CAAC,CA8C/E;AAED;;;;;;GAMG;AACH,wBAAsB,aAAa,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,MAAM,CAAC,CAkB9E"}
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Рекурсивно обходит JSON объект и создает плоский список ключей через точку.
3
+ *
4
+ * @param obj - JSON объект с переводами
5
+ * @param prefix - Префикс для вложенных ключей (используется рекурсивно)
6
+ * @returns Массив строк с плоскими ключами (например, ['greeting', 'header.title', 'errors.404'])
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * const obj = {
11
+ * greeting: 'Hello',
12
+ * header: {
13
+ * title: 'Welcome',
14
+ * subtitle: 'Subtitle'
15
+ * }
16
+ * }
17
+ * flattenKeys(obj) // ['greeting', 'header.title', 'header.subtitle']
18
+ * ```
19
+ */
20
+ export declare function flattenKeys(obj: Record<string, unknown>, prefix?: string): string[];
21
+ //# sourceMappingURL=parser.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parser.d.ts","sourceRoot":"","sources":["../../src/core/parser.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,WAAW,CACzB,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,MAAM,SAAK,GACV,MAAM,EAAE,CAsBV"}
@@ -0,0 +1,15 @@
1
+ "use strict";const d=require("globby"),i=require("node:fs"),a=require("node:path");function y(e,s=""){const t=[];for(const n in e){if(!Object.hasOwn(e,n))continue;const o=e[n],r=s?`${s}.${n}`:n;typeof o=="object"&&o!==null&&!Array.isArray(o)?t.push(...y(o,r)):t.push(r)}return t}async function l(e){const s=a.resolve(e.srcDir,e.translationDir),t=await d.globby("**/*.json",{cwd:s,absolute:!0,ignore:["node_modules/**","dist/**",".nuxt/**"]}),n=new Set;for(const r of t)try{const c=JSON.parse(i.readFileSync(r,"utf-8")),u=y(c);for(const f of u)n.add(f)}catch(c){console.warn(`[i18n-types] Failed to parse ${r}:`,c)}return`/* eslint-disable */
2
+ /* prettier-ignore */
3
+ // @ts-nocheck
4
+ // Generated by @i18n-micro/types-generator
5
+ // DO NOT EDIT THIS FILE MANUALLY
6
+
7
+ import '@i18n-micro/types';
8
+
9
+ declare module '@i18n-micro/types' {
10
+ export interface DefineLocaleMessage {
11
+ ${Array.from(n).sort().map(r=>` '${r}': string;`).join(`
12
+ `)}
13
+ }
14
+ }
15
+ `}async function p(e){const s=await l(e),t=e.outputFile||a.resolve(e.srcDir,"i18n-micro.d.ts"),n=a.dirname(t);try{i.mkdirSync(n,{recursive:!0})}catch{}return i.writeFileSync(t,s,"utf-8"),t}exports.flattenKeys=y;exports.generateTypes=p;exports.getTypesString=l;
@@ -0,0 +1,55 @@
1
+ import { globby as u } from "globby";
2
+ import { mkdirSync as f, writeFileSync as p, readFileSync as m } from "node:fs";
3
+ import { resolve as c, dirname as d } from "node:path";
4
+ function a(e, o = "") {
5
+ const t = [];
6
+ for (const n in e) {
7
+ if (!Object.hasOwn(e, n)) continue;
8
+ const s = e[n], r = o ? `${o}.${n}` : n;
9
+ typeof s == "object" && s !== null && !Array.isArray(s) ? t.push(...a(s, r)) : t.push(r);
10
+ }
11
+ return t;
12
+ }
13
+ async function g(e) {
14
+ const o = c(e.srcDir, e.translationDir), t = await u("**/*.json", {
15
+ cwd: o,
16
+ absolute: !0,
17
+ ignore: ["node_modules/**", "dist/**", ".nuxt/**"]
18
+ }), n = /* @__PURE__ */ new Set();
19
+ for (const r of t)
20
+ try {
21
+ const i = JSON.parse(m(r, "utf-8")), l = a(i);
22
+ for (const y of l)
23
+ n.add(y);
24
+ } catch (i) {
25
+ console.warn(`[i18n-types] Failed to parse ${r}:`, i);
26
+ }
27
+ return `/* eslint-disable */
28
+ /* prettier-ignore */
29
+ // @ts-nocheck
30
+ // Generated by @i18n-micro/types-generator
31
+ // DO NOT EDIT THIS FILE MANUALLY
32
+
33
+ import '@i18n-micro/types';
34
+
35
+ declare module '@i18n-micro/types' {
36
+ export interface DefineLocaleMessage {
37
+ ${Array.from(n).sort().map((r) => ` '${r}': string;`).join(`
38
+ `)}
39
+ }
40
+ }
41
+ `;
42
+ }
43
+ async function h(e) {
44
+ const o = await g(e), t = e.outputFile || c(e.srcDir, "i18n-micro.d.ts"), n = d(t);
45
+ try {
46
+ f(n, { recursive: !0 });
47
+ } catch {
48
+ }
49
+ return p(t, o, "utf-8"), t;
50
+ }
51
+ export {
52
+ g as a,
53
+ a as f,
54
+ h as g
55
+ };
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("unplugin"),i=require("./generator-D2pTueXl.cjs"),c=require("chokidar"),u=require("node:path");let r=null,e=null;function y(t,n){return function(...o){const a=()=>{e&&clearTimeout(e),e=null,t(...o)};e&&clearTimeout(e),e=setTimeout(a,n)}}const g=s.createUnplugin(t=>({name:"i18n-micro-types-generator",async buildStart(){try{await i.generateTypes(t)}catch(n){console.warn("[i18n-types] Failed to generate types:",n)}if(process.env.NODE_ENV==="development"||process.env.NODE_ENV!=="production"){const n=u.resolve(t.srcDir,t.translationDir),l=y(async()=>{try{await i.generateTypes(t)}catch(o){console.warn("[i18n-types] Failed to regenerate types:",o)}},300);r=c.watch(n,{ignoreInitial:!0,ignored:["node_modules/**","dist/**",".nuxt/**"]}),r.on("all",async(o,a)=>{a.endsWith(".json")&&l()})}},buildEnd(){r&&(r.close(),r=null),e&&(clearTimeout(e),e=null)}}));exports.flattenKeys=i.flattenKeys;exports.generateTypes=i.generateTypes;exports.getTypesString=i.getTypesString;exports.I18nTypesPlugin=g;
@@ -0,0 +1,5 @@
1
+ export { I18nTypesPlugin } from './unplugin';
2
+ export { generateTypes, getTypesString } from './core/generator';
3
+ export type { GeneratorOptions } from './core/generator';
4
+ export { flattenKeys } from './core/parser';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AAC5C,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAA;AAChE,YAAY,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAA;AACxD,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAA"}
package/dist/index.mjs ADDED
@@ -0,0 +1,48 @@
1
+ import { createUnplugin as c } from "unplugin";
2
+ import { g as l } from "./generator-D56a37C-.js";
3
+ import { f as w, a as v } from "./generator-D56a37C-.js";
4
+ import s from "chokidar";
5
+ import { resolve as u } from "node:path";
6
+ let r = null, e = null;
7
+ function m(t, n) {
8
+ return function(...o) {
9
+ const i = () => {
10
+ e && clearTimeout(e), e = null, t(...o);
11
+ };
12
+ e && clearTimeout(e), e = setTimeout(i, n);
13
+ };
14
+ }
15
+ const g = c((t) => ({
16
+ name: "i18n-micro-types-generator",
17
+ async buildStart() {
18
+ try {
19
+ await l(t);
20
+ } catch (n) {
21
+ console.warn("[i18n-types] Failed to generate types:", n);
22
+ }
23
+ if (process.env.NODE_ENV === "development" || process.env.NODE_ENV !== "production") {
24
+ const n = u(t.srcDir, t.translationDir), a = m(async () => {
25
+ try {
26
+ await l(t);
27
+ } catch (o) {
28
+ console.warn("[i18n-types] Failed to regenerate types:", o);
29
+ }
30
+ }, 300);
31
+ r = s.watch(n, {
32
+ ignoreInitial: !0,
33
+ ignored: ["node_modules/**", "dist/**", ".nuxt/**"]
34
+ }), r.on("all", async (o, i) => {
35
+ i.endsWith(".json") && a();
36
+ });
37
+ }
38
+ },
39
+ buildEnd() {
40
+ r && (r.close(), r = null), e && (clearTimeout(e), e = null);
41
+ }
42
+ }));
43
+ export {
44
+ g as I18nTypesPlugin,
45
+ w as flattenKeys,
46
+ l as generateTypes,
47
+ v as getTypesString
48
+ };
package/dist/nuxt.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const s=require("@nuxt/kit"),p=require("./generator-D2pTueXl.cjs"),u=s.defineNuxtModule({meta:{name:"@i18n-micro/types-generator",configKey:"i18nTypes"},defaults:{translationDir:"locales"},async setup(l,t){var o;const n=(o=t.options.runtimeConfig)==null?void 0:o.public,r=n==null?void 0:n.i18nConfig,a=l.translationDir||(r==null?void 0:r.translationDir)||"locales";s.addTypeTemplate({filename:"types/i18n-micro.d.ts",getContents:async()=>{try{return await p.getTypesString({srcDir:t.options.rootDir,translationDir:a})}catch(e){return console.warn("[i18n-types] Failed to generate types:",e),`// Failed to generate types: ${e instanceof Error?e.message:String(e)}`}}}),t.hook("builder:watch",async(e,c)=>{const i=c.replace(/\\/g,"/"),d=a.replace(/\\/g,"/");i.includes(d)&&i.endsWith(".json")&&await t.callHook("builder:generateApp")})}});exports.default=u;
package/dist/nuxt.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ export interface I18nTypesGeneratorOptions {
2
+ translationDir?: string;
3
+ outputFile?: string;
4
+ }
5
+ declare const _default: import('@nuxt/schema').NuxtModule<I18nTypesGeneratorOptions, I18nTypesGeneratorOptions, false>;
6
+ export default _default;
7
+ //# sourceMappingURL=nuxt.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nuxt.d.ts","sourceRoot":"","sources":["../src/nuxt.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,yBAAyB;IACxC,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB;;AAED,wBAoDE"}
package/dist/nuxt.mjs ADDED
@@ -0,0 +1,34 @@
1
+ import { defineNuxtModule as p, addTypeTemplate as d } from "@nuxt/kit";
2
+ import { a as m } from "./generator-D56a37C-.js";
3
+ const u = p({
4
+ meta: {
5
+ name: "@i18n-micro/types-generator",
6
+ configKey: "i18nTypes"
7
+ },
8
+ defaults: {
9
+ translationDir: "locales"
10
+ },
11
+ async setup(s, t) {
12
+ var o;
13
+ const n = (o = t.options.runtimeConfig) == null ? void 0 : o.public, a = n == null ? void 0 : n.i18nConfig, r = s.translationDir || (a == null ? void 0 : a.translationDir) || "locales";
14
+ d({
15
+ filename: "types/i18n-micro.d.ts",
16
+ getContents: async () => {
17
+ try {
18
+ return await m({
19
+ srcDir: t.options.rootDir,
20
+ translationDir: r
21
+ });
22
+ } catch (e) {
23
+ return console.warn("[i18n-types] Failed to generate types:", e), `// Failed to generate types: ${e instanceof Error ? e.message : String(e)}`;
24
+ }
25
+ }
26
+ }), t.hook("builder:watch", async (e, l) => {
27
+ const i = l.replace(/\\/g, "/"), c = r.replace(/\\/g, "/");
28
+ i.includes(c) && i.endsWith(".json") && await t.callHook("builder:generateApp");
29
+ });
30
+ }
31
+ });
32
+ export {
33
+ u as default
34
+ };
@@ -0,0 +1,3 @@
1
+ import { GeneratorOptions } from './core/generator';
2
+ export declare const I18nTypesPlugin: import('unplugin').UnpluginInstance<GeneratorOptions, boolean>;
3
+ //# sourceMappingURL=unplugin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"unplugin.d.ts","sourceRoot":"","sources":["../src/unplugin.ts"],"names":[],"mappings":"AACA,OAAO,EAAiB,KAAK,gBAAgB,EAAE,MAAM,kBAAkB,CAAA;AAuBvE,eAAO,MAAM,eAAe,gEAkD1B,CAAA"}
package/package.json ADDED
@@ -0,0 +1,68 @@
1
+ {
2
+ "name": "@i18n-micro/types-generator",
3
+ "version": "1.0.0",
4
+ "description": "Type generator for i18n-micro translation keys",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.mjs",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.mjs",
13
+ "require": "./dist/index.cjs"
14
+ },
15
+ "./nuxt": {
16
+ "types": "./dist/nuxt.d.ts",
17
+ "import": "./dist/nuxt.mjs",
18
+ "require": "./dist/nuxt.cjs"
19
+ }
20
+ },
21
+ "files": [
22
+ "dist"
23
+ ],
24
+ "publishConfig": {
25
+ "access": "public"
26
+ },
27
+ "keywords": [
28
+ "i18n",
29
+ "typescript",
30
+ "type-generator",
31
+ "translation"
32
+ ],
33
+ "author": {
34
+ "name": "s00d",
35
+ "email": "Virus191288@gmail.com",
36
+ "url": "https://s00d.github.io/"
37
+ },
38
+ "license": "MIT",
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "https://github.com/s00d/nuxt-i18n-micro"
42
+ },
43
+ "dependencies": {
44
+ "globby": "^14.0.0",
45
+ "chokidar": "^3.6.0",
46
+ "unplugin": "^1.0.0"
47
+ },
48
+ "peerDependencies": {
49
+ "@nuxt/kit": "^3.0.0"
50
+ },
51
+ "engines": {
52
+ "node": ">=18.17.0"
53
+ },
54
+ "devDependencies": {
55
+ "@types/node": "^20.17.10",
56
+ "vite": "^5.0.0",
57
+ "vite-plugin-dts": "^4.3.0",
58
+ "typescript": "^5.0.0",
59
+ "jest": "^29.7.0",
60
+ "ts-jest": "^29.1.2",
61
+ "@types/jest": "^29.5.0"
62
+ },
63
+ "scripts": {
64
+ "build": "vite build",
65
+ "test": "jest",
66
+ "typecheck": "tsc --noEmit"
67
+ }
68
+ }