@barcidev/ngx-autogen 0.1.28 → 0.1.30

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.28",
3
+ "version": "0.1.30",
4
4
  "description": "A collection of Angular schematics for essential functionalities.",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -1,6 +1,3 @@
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
- */
6
3
  export declare function transloco(options: TranslocoSchemaOptions): Rule;
@@ -12,138 +12,115 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.transloco = transloco;
13
13
  const schematics_1 = require("@angular-devkit/schematics");
14
14
  const workspace_1 = require("@schematics/angular/utility/workspace");
15
+ const jsonc_parser_1 = require("jsonc-parser");
15
16
  const path_1 = require("path");
17
+ // Utilidades locales
16
18
  const file_actions_1 = require("../common/file-actions");
17
19
  const pluralize_1 = require("../common/pluralize");
18
- /**
19
- * Schematic principal para configurar Transloco en un componente específico
20
- */
21
20
  function transloco(options) {
22
- return (tree, _context) => __awaiter(this, void 0, void 0, function* () {
23
- // --- 1. CONFIGURACIÓN INICIAL Y WORKSPACE ---
21
+ return (tree) => __awaiter(this, void 0, void 0, function* () {
24
22
  const workspace = yield (0, workspace_1.getWorkspace)(tree);
25
- if (!options.project) {
26
- options.project =
27
- workspace.extensions.defaultProject ||
28
- Array.from(workspace.projects.keys())[0];
29
- }
30
- const project = workspace.projects.get(options.project);
31
- if (!project) {
32
- throw new schematics_1.SchematicsException(`El proyecto "${options.project}" no existe.`);
33
- }
34
- // --- 2. DETERMINACIÓN DE RUTAS Y DETECCIÓN DE COMPONENTE ---
35
- // Resolvemos el path relativo (src/app/...) basado en el directorio de ejecución
36
- const fullPath = process.cwd();
37
- const srcIndex = fullPath.lastIndexOf("src");
38
- const relativePath = srcIndex !== -1
39
- ? fullPath.substring(srcIndex)
40
- : (0, path_1.join)((0, path_1.normalize)("src"), "app");
41
- options.path = (0, path_1.normalize)(relativePath);
42
- const directory = tree.getDir(options.path);
43
- // Buscamos el archivo .ts principal del directorio
44
- const componentFile = directory.subfiles.find((f) => f.endsWith(".component.ts")) ||
45
- directory.subfiles.find((f) => f.endsWith(".ts"));
46
- if (!componentFile && !options.name) {
47
- throw new schematics_1.SchematicsException("❌ No se encontró un archivo .ts en este directorio y no se proveyó un --name.");
48
- }
49
- // Normalizamos el nombre (ej. mi-componente.component -> mi-componente)
50
- options.name = componentFile
51
- ? componentFile.replace(".component.ts", "").replace(".ts", "")
52
- : options.name;
53
- const rules = [];
54
- // --- 3. CONFIGURACIÓN GLOBAL (IDEMPOTENTE) ---
55
- /*const appConfigPath = "src/app/app.config.ts";
56
- const appConfigContent = tree.read(appConfigPath)?.toString() || "";
57
-
58
- if (!appConfigContent.includes("provideTransloco")) {
59
- _context.logger.info(
60
- "📦 Transloco no detectado. Configurando globalmente...",
61
- );
62
- // Dependencias y tarea de instalación
63
- rules.push((host: Tree) => {
64
- addPackageJsonDependency(host, {
65
- type: NodeDependencyType.Default,
66
- name: "@jsverse/transloco",
67
- version: "^7.0.0",
68
- });
69
- _context.addTask(new NodePackageInstallTask());
70
- return host;
71
- });
72
- }*/
73
- // --- 4. GENERACIÓN DE ARCHIVOS I18N DEL COMPONENTE ---
74
- rules.push((0, schematics_1.mergeWith)((0, schematics_1.apply)((0, schematics_1.url)("./files/component"), [
75
- (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) })),
76
- (0, schematics_1.move)(options.path),
77
- ])));
78
- // --- 5. REGISTRO DEL SCOPE EN EL COMPONENTE ---
79
- if (componentFile) {
80
- const componentPath = (0, path_1.join)(options.path, componentFile);
81
- const i18nConstantName = `${schematics_1.strings.camelize(options.name)}I18n`;
82
- rules.push((0, file_actions_1.addProviderToStandaloneComponent)(componentPath, `provideTranslocoScopeWrapper(${i18nConstantName})`, [
83
- {
84
- symbol: `provideTranslocoScopeWrapper`,
85
- path: `@barcidev/typed-transloco`,
86
- },
87
- {
88
- symbol: i18nConstantName,
89
- path: `./${schematics_1.strings.dasherize(options.name)}.i18n`,
90
- },
91
- ]));
92
- }
23
+ // 1. Configuración de Proyecto y Roots
24
+ const projectName = options.project ||
25
+ workspace.extensions.defaultProject ||
26
+ Array.from(workspace.projects.keys())[0];
27
+ const project = workspace.projects.get(projectName);
28
+ if (!project)
29
+ throw new schematics_1.SchematicsException(`El proyecto "${projectName}" no existe.`);
30
+ const projectRoot = project.sourceRoot || "src";
31
+ // 2. Resolución de Contexto (Path y Componente)
32
+ const { path, componentFile, componentName } = resolveComponentContext(tree, options);
33
+ // Sincronizamos las opciones normalizadas
34
+ const finalOptions = Object.assign(Object.assign({}, options), { name: componentName, path: path, project: projectName, projectRoot: projectRoot });
93
35
  return (0, schematics_1.chain)([
94
- ...rules,
95
- (0, schematics_1.externalSchematic)("@barcidev/typed-transloco", "ng-add", {}),
36
+ generateI18nFiles(finalOptions),
37
+ updateAppI18nTypeRule(finalOptions),
38
+ registerProviderInComponent(finalOptions, componentFile),
96
39
  ]);
97
40
  });
98
41
  }
99
- /*function updateAppI18nType(
100
- root: string,
101
- name: string,
102
- importPath: string,
103
- ): Rule {
104
- return (tree: Tree, context: SchematicContext) => {
105
- const path = `${root}/app/i18n/app.i18n.ts`;
106
- const buffer = tree.read(path);
107
-
108
- if (!buffer) {
109
- context.logger.warn(`⚠️ No se encontró el archivo ${path}`);
110
- return tree;
111
- }
112
-
113
- let content = buffer.toString();
114
- const importStatement = `import { ${name} } from '${importPath}';\n`;
115
-
116
- // 1. AGREGAR EL IMPORT (si no existe ya)
117
- if (!content.includes(importPath)) {
118
- content = importStatement + content;
119
- }
120
-
121
- // 2. ACTUALIZAR EL OBJETO appI18n
122
- const options: ModificationOptions = {
123
- formattingOptions: { insertSpaces: true, tabSize: 2 },
42
+ /**
43
+ * --- REGLAS FUNCIONALES ---
44
+ */
45
+ // Regla 1: Generación de archivos desde plantillas
46
+ function generateI18nFiles(options) {
47
+ return (0, schematics_1.mergeWith)((0, schematics_1.apply)((0, schematics_1.url)("./files/component"), [
48
+ (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) })),
49
+ (0, schematics_1.move)(options.path),
50
+ ]));
51
+ }
52
+ // Regla 2: Actualización del archivo de tipos global
53
+ function updateAppI18nTypeRule(options) {
54
+ return (tree, context) => {
55
+ const i18nFilePath = `${options.projectRoot}/app/i18n/app.i18n.ts`;
56
+ const buffer = tree.read(i18nFilePath);
57
+ if (!buffer) {
58
+ context.logger.warn(`⚠️ No se encontró app.i18n.ts en ${i18nFilePath}. Salteando actualización de tipos.`);
59
+ return tree;
60
+ }
61
+ let content = buffer.toString();
62
+ const camelName = schematics_1.strings.camelize(options.name);
63
+ const i18nConstantName = `${camelName}I18n`;
64
+ // Inyección de Import
65
+ const importStatement = `import { ${i18nConstantName} } from '${options.path.replace("src/app/", "./")}/${schematics_1.strings.dasherize(options.name)}.i18n';\n`;
66
+ if (!content.includes(i18nConstantName)) {
67
+ content = importStatement + content;
68
+ }
69
+ // Modificación del objeto appI18n
70
+ const jsonOptions = {
71
+ formattingOptions: { insertSpaces: true, tabSize: 2 },
72
+ };
73
+ const regex = /const\s+appI18n\s*=\s*(\{[\s\S]*?\});/;
74
+ const match = content.match(regex);
75
+ if (match) {
76
+ const oldObjectStr = match[1];
77
+ const propertyKey = camelName;
78
+ const propertyValue = `${i18nConstantName}.translations['en-US']`;
79
+ // Placeholder para evitar comillas de JSON
80
+ const placeholder = `__REF__${i18nConstantName}`;
81
+ const edits = (0, jsonc_parser_1.modify)(oldObjectStr, [propertyKey], placeholder, jsonOptions);
82
+ let newObjectStr = (0, jsonc_parser_1.applyEdits)(oldObjectStr, edits);
83
+ newObjectStr = newObjectStr.replace(`"${placeholder}"`, propertyValue);
84
+ tree.overwrite(i18nFilePath, content.replace(oldObjectStr, newObjectStr));
85
+ context.logger.info(`✅ Tipos actualizados para el scope: ${propertyKey}`);
86
+ }
87
+ return tree;
124
88
  };
125
-
126
- // Buscamos el bloque del objeto appI18n
127
- const regex = /const\s+appI18n\s*=\s*(\{[\s\S]*?\});/;
128
- const match = content.match(regex);
129
-
130
- if (match) {
131
- const oldObjectStr = match[1];
132
-
133
-
134
- const edits = modify(
135
- oldObjectStr,
136
- [name],
137
- [name + ".translations[en-US]"],
138
- options,
139
- );
140
- let newObjectStr = applyEdits(oldObjectStr, edits);
141
-
142
- const newContent = content.replace(oldObjectStr, newObjectStr);
143
- tree.overwrite(path, newContent);
144
-
145
- context.logger.info(`✅ Importado ${name}"`);
146
- }
147
- };
148
- }*/
89
+ }
90
+ // Regla 3: Registro de Provider en el componente
91
+ function registerProviderInComponent(options, componentFile) {
92
+ if (!componentFile)
93
+ return (tree) => tree;
94
+ const componentPath = (0, path_1.join)(options.path, componentFile);
95
+ const i18nConstantName = `${schematics_1.strings.camelize(options.name)}I18n`;
96
+ return (0, file_actions_1.addProviderToStandaloneComponent)(componentPath, `provideTranslocoScopeWrapper(${i18nConstantName})`, [
97
+ {
98
+ symbol: "provideTranslocoScopeWrapper",
99
+ path: "@barcidev/typed-transloco",
100
+ },
101
+ {
102
+ symbol: i18nConstantName,
103
+ path: `./${schematics_1.strings.dasherize(options.name)}.i18n`,
104
+ },
105
+ ]);
106
+ }
107
+ /**
108
+ * --- HELPERS ---
109
+ */
110
+ function resolveComponentContext(tree, options) {
111
+ const fullPath = process.cwd();
112
+ const srcIndex = fullPath.lastIndexOf("src");
113
+ const path = (0, path_1.normalize)(srcIndex !== -1
114
+ ? fullPath.substring(srcIndex)
115
+ : (0, path_1.join)((0, path_1.normalize)("src"), "app"));
116
+ const directory = tree.getDir(path);
117
+ const componentFile = directory.subfiles.find((f) => f.endsWith(".component.ts")) ||
118
+ directory.subfiles.find((f) => f.endsWith(".ts"));
119
+ const componentName = componentFile
120
+ ? componentFile.replace(".component.ts", "").replace(".ts", "")
121
+ : options.name;
122
+ if (!componentName)
123
+ throw new schematics_1.SchematicsException("❌ No se pudo determinar el nombre del componente.");
124
+ return { path, componentFile, componentName };
125
+ }
149
126
  //# sourceMappingURL=index.js.map