@barcidev/ngx-autogen 0.1.13 → 0.1.15

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@barcidev/ngx-autogen",
3
- "version": "0.1.13",
3
+ "version": "0.1.15",
4
4
  "description": "A collection of Angular schematics for essential functionalities.",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -1,4 +1,4 @@
1
- import { TranslationScopeConfig } from 'app/i18n/transloco.model';
1
+ import { TranslationScopeConfig } from '@i18n/transloco.model';
2
2
 
3
3
  const esCO = {
4
4
  title: 'Titulo'
@@ -1,3 +1,6 @@
1
1
  import { Rule } from "@angular-devkit/schematics";
2
2
  import { TranslocoSchemaOptions } from "./scheme";
3
+ /**
4
+ * Schematic principal para configurar Transloco en un componente específico
5
+ */
3
6
  export declare function transloco(options: TranslocoSchemaOptions): Rule;
@@ -18,10 +18,13 @@ const workspace_1 = require("@schematics/angular/utility/workspace");
18
18
  const path_1 = require("path");
19
19
  const file_actions_1 = require("../common/file-actions");
20
20
  const pluralize_1 = require("../common/pluralize");
21
+ /**
22
+ * Schematic principal para configurar Transloco en un componente específico
23
+ */
21
24
  function transloco(options) {
22
25
  return (tree, _context) => __awaiter(this, void 0, void 0, function* () {
23
26
  var _a;
24
- // 1. Configuración del Workspace y Proyecto
27
+ // --- 1. CONFIGURACIÓN INICIAL Y WORKSPACE ---
25
28
  const workspace = yield (0, workspace_1.getWorkspace)(tree);
26
29
  if (!options.project) {
27
30
  options.project =
@@ -32,39 +35,32 @@ function transloco(options) {
32
35
  if (!project) {
33
36
  throw new schematics_1.SchematicsException(`El proyecto "${options.project}" no existe.`);
34
37
  }
35
- // 2. Detección automática del componente en la ruta actual
38
+ // --- 2. DETERMINACIÓN DE RUTAS Y DETECCIÓN DE COMPONENTE ---
39
+ // Resolvemos el path relativo (src/app/...) basado en el directorio de ejecución
36
40
  const fullPath = process.cwd();
37
- const relativeExecutionPath = fullPath
38
- .replace(process.cwd(), "")
39
- .replace(/\\/g, "/");
40
- const directory = tree.getDir((0, path_1.normalize)(relativeExecutionPath));
41
- console.log(`🔍 Buscando componente en: ${relativeExecutionPath}`);
42
- const componentFile = directory.subfiles.find((file) => file.endsWith(".component.ts"));
43
- console.log(`📄 Componente detectado: ${componentFile || "Ninguno"}`);
44
- if (!componentFile && !options.name) {
45
- throw new schematics_1.SchematicsException("❌ No se encontró un archivo *.component.ts en este directorio.");
46
- }
47
- const componentFileName = componentFile
48
- ? componentFile.replace(".component.ts", "")
49
- : options.name;
50
- options.name = componentFileName;
51
- console.log(`✅ Nombre del componente para i18n: ${options.name}`);
52
- // 3. Determinación de rutas para generación de archivos
53
41
  const srcIndex = fullPath.lastIndexOf("src");
54
42
  const relativePath = srcIndex !== -1
55
43
  ? fullPath.substring(srcIndex)
56
44
  : (0, path_1.join)((0, path_1.normalize)("src"), "app");
57
45
  options.path = (0, path_1.normalize)(relativePath);
58
- console.log(`📂 Ruta de generación de archivos i18n: ${options.path}`);
59
- const namePath = options.path; // Generamos archivos en la misma carpeta del componente detectado
46
+ const directory = tree.getDir(options.path);
47
+ // Buscamos el archivo .ts principal del directorio
48
+ const componentFile = directory.subfiles.find((f) => f.endsWith(".component.ts")) ||
49
+ directory.subfiles.find((f) => f.endsWith(".ts"));
50
+ if (!componentFile && !options.name) {
51
+ throw new schematics_1.SchematicsException("❌ No se encontró un archivo .ts en este directorio y no se proveyó un --name.");
52
+ }
53
+ // Normalizamos el nombre (ej. mi-componente.component -> mi-componente)
54
+ options.name = componentFile
55
+ ? componentFile.replace(".component.ts", "").replace(".ts", "")
56
+ : options.name;
60
57
  const rules = [];
61
- // 4. Verificación de instalación de Transloco (Idempotencia)
58
+ // --- 3. CONFIGURACIÓN GLOBAL (IDEMPOTENTE) ---
62
59
  const appConfigPath = "src/app/app.config.ts";
63
60
  const appConfigContent = ((_a = tree.read(appConfigPath)) === null || _a === void 0 ? void 0 : _a.toString()) || "";
64
- const isTranslocoInstalled = appConfigContent.includes("provideTransloco");
65
- if (!isTranslocoInstalled) {
66
- _context.logger.info("📦 Transloco no detectado. Iniciando configuración global...");
67
- // A. Añadir dependencia a package.json
61
+ if (!appConfigContent.includes("provideTransloco")) {
62
+ _context.logger.info("📦 Transloco no detectado. Configurando globalmente...");
63
+ // Dependencias y tarea de instalación
68
64
  rules.push((host) => {
69
65
  (0, dependencies_1.addPackageJsonDependency)(host, {
70
66
  type: dependencies_1.NodeDependencyType.Default,
@@ -74,35 +70,32 @@ function transloco(options) {
74
70
  _context.addTask(new tasks_1.NodePackageInstallTask());
75
71
  return host;
76
72
  });
77
- // B. Inyectar provider global en app.config.ts
78
- rules.push((0, rules_1.addRootProvider)(options.project, ({ code, external }) => {
79
- return code `
80
- ${external("provideTransloco", "@jsverse/transloco")}({
81
- config: {
82
- availableLangs: ['en', 'es'],
83
- defaultLang: 'en',
84
- prodMode: !${external("isDevMode", "@angular/core")}(),
85
- reRenderOnLangChange: true
86
- },
87
- loader: ${external("TranslocoHttpLoader", "./i18n/transloco-loader")}
88
- })
89
- `;
90
- }));
73
+ // Provider global en app.config.ts
74
+ rules.push((0, rules_1.addRootProvider)(options.project, ({ code, external }) => code `
75
+ ${external("provideTransloco", "@jsverse/transloco")}({
76
+ config: {
77
+ availableLangs: ['en', 'es'],
78
+ defaultLang: 'en',
79
+ prodMode: !${external("isDevMode", "@angular/core")}(),
80
+ reRenderOnLangChange: true
81
+ },
82
+ loader: ${external("TranslocoHttpLoader", "@i18n/transloco-loader")}
83
+ })
84
+ `));
91
85
  }
92
- // 5. Generación de archivos i18n del componente
86
+ // --- 4. GENERACIÓN DE ARCHIVOS I18N DEL COMPONENTE ---
93
87
  rules.push((0, schematics_1.mergeWith)((0, schematics_1.apply)((0, schematics_1.url)("./files/component"), [
94
88
  (0, schematics_1.applyTemplates)(Object.assign(Object.assign(Object.assign({}, schematics_1.strings), options), { pluralize: (word) => options.lang === "es" ? (0, pluralize_1.pluralizeEs)(word) : (0, pluralize_1.pluralizeEn)(word) })),
95
- (0, schematics_1.move)(namePath),
89
+ (0, schematics_1.move)(options.path),
96
90
  ])));
97
- // 6. Registro del Scope en el Componente Standalone
91
+ // --- 5. REGISTRO DEL SCOPE EN EL COMPONENTE ---
98
92
  if (componentFile) {
99
- const componentPath = (0, path_1.join)(namePath, componentFile);
93
+ const componentPath = (0, path_1.join)(options.path, componentFile);
100
94
  const i18nConstantName = `${schematics_1.strings.camelize(options.name)}I18n`;
101
- console.log(`🔗 Registrando scope de Transloco en ${componentFile} con constante ${i18nConstantName}, este es el path: ${componentPath}`);
102
95
  rules.push((0, file_actions_1.addProviderToStandaloneComponent)(componentPath, `provideTranslocoScopeWrapper(${i18nConstantName})`, [
103
96
  {
104
97
  symbol: `provideTranslocoScopeWrapper`,
105
- path: `src/app/i18n/transloco-loader`, // Ajusta a tu path real de utilidades
98
+ path: `@i18n/transloco-loader`,
106
99
  },
107
100
  {
108
101
  symbol: i18nConstantName,
@@ -110,44 +103,64 @@ function transloco(options) {
110
103
  },
111
104
  ]));
112
105
  }
113
- // 7. Sincronización de archivos i18n comunes
106
+ // --- 6. SINCRONIZACIÓN DE ARCHIVOS COMUNES Y TSCONFIG ---
114
107
  rules.push((0, file_actions_1.mergeFilesSmart)("./files/i18n", "src/app/i18n", options, tree));
108
+ // Ejecutar actualización de tsconfig
115
109
  updateTsConfig(tree);
116
110
  return (0, schematics_1.chain)(rules);
117
111
  });
118
- function updateTsConfig(tree) {
119
- const tsConfigPath = "/tsconfig.json";
120
- const path = tree.exists(tsConfigPath)
121
- ? tsConfigPath
122
- : "/tsconfig.app.json";
123
- const buffer = tree.read(path);
124
- if (!buffer)
125
- return;
126
- let contentText = buffer.toString();
127
- // Limpieza manual de comentarios para evitar que JSON.parse falle
128
- const cleanJson = contentText.replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm, "$1");
129
- let tsconfig;
130
- try {
131
- tsconfig = JSON.parse(cleanJson);
112
+ }
113
+ /**
114
+ * Actualiza los paths en tsconfig para soportar el alias @i18n.
115
+ * Detecta la baseUrl existente para calcular la ruta relativa correcta.
116
+ */
117
+ function updateTsConfig(tree) {
118
+ const tsConfigPath = tree.exists("/tsconfig.json")
119
+ ? "/tsconfig.json"
120
+ : "/tsconfig.app.json";
121
+ const buffer = tree.read(tsConfigPath);
122
+ if (!buffer)
123
+ return;
124
+ // Limpieza de comentarios para evitar errores en JSON.parse
125
+ const content = buffer
126
+ .toString()
127
+ .replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm, "$1");
128
+ try {
129
+ const tsconfig = JSON.parse(content);
130
+ // Asegurar que exista compilerOptions
131
+ tsconfig.compilerOptions = tsconfig.compilerOptions || {};
132
+ // 1. Detectar o establecer baseUrl
133
+ // Si no existe, la inicializamos en "./"
134
+ const baseUrl = tsconfig.compilerOptions.baseUrl || "./";
135
+ if (!tsconfig.compilerOptions.baseUrl) {
136
+ tsconfig.compilerOptions.baseUrl = baseUrl;
132
137
  }
133
- catch (e) {
134
- // Si falla, intentamos parsearlo tal cual por si no tiene comentarios
135
- try {
136
- tsconfig = JSON.parse(contentText);
137
- }
138
- catch (innerError) {
139
- throw new schematics_1.SchematicsException(`No se pudo parsear ${path}. Asegúrate de que es un JSON válido.`);
138
+ // 2. Calcular el path del alias basado en la baseUrl
139
+ // Si baseUrl es "./", el path debe ser "src/app/i18n/*"
140
+ // Si baseUrl es "src", el path debe ser "app/i18n/*"
141
+ let i18nPath = "src/app/i18n/*";
142
+ if (baseUrl !== "./" && baseUrl !== ".") {
143
+ // Normalizamos la baseUrl eliminando barras iniciales/finales (ej. "src/" -> "src")
144
+ const normalizedBase = baseUrl.replace(/^\.\/|\/$/g, "");
145
+ // Si la baseUrl ya incluye 'src', la recortamos del path del alias
146
+ if (i18nPath.startsWith(normalizedBase)) {
147
+ i18nPath = i18nPath.replace(normalizedBase, "").replace(/^\//, "");
140
148
  }
141
149
  }
142
- // Configurar los paths
143
- tsconfig.compilerOptions = tsconfig.compilerOptions || {};
150
+ // 3. Configurar los paths
144
151
  tsconfig.compilerOptions.paths = tsconfig.compilerOptions.paths || {};
145
- const sharedAlias = "@i18n/*";
146
- const sharedPath = ["src/app/i18n/*"];
147
- if (!tsconfig.compilerOptions.paths[sharedAlias]) {
148
- tsconfig.compilerOptions.paths[sharedAlias] = sharedPath;
149
- tree.overwrite(path, JSON.stringify(tsconfig, null, 2));
152
+ const alias = "@i18n/*";
153
+ const pathValue = [i18nPath];
154
+ // Solo actualizamos si el alias no existe o el valor ha cambiado
155
+ if (!tsconfig.compilerOptions.paths[alias] ||
156
+ tsconfig.compilerOptions.paths[alias][0] !== i18nPath) {
157
+ tsconfig.compilerOptions.paths[alias] = pathValue;
158
+ tree.overwrite(tsConfigPath, JSON.stringify(tsconfig, null, 2));
159
+ console.log(`✅ TsConfig actualizado: @i18n -> ${i18nPath} (baseUrl: ${baseUrl})`);
150
160
  }
151
161
  }
162
+ catch (e) {
163
+ console.warn(`⚠️ No se pudo procesar ${tsConfigPath}. Revisa que sea un JSON válido.`);
164
+ }
152
165
  }
153
166
  //# sourceMappingURL=index.js.map