@barcidev/ngx-autogen 0.1.20 → 0.1.22

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.20",
3
+ "version": "0.1.22",
4
4
  "description": "A collection of Angular schematics for essential functionalities.",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -50,6 +50,7 @@
50
50
  "dependencies": {
51
51
  "@angular-devkit/core": "^21.2.0",
52
52
  "@angular-devkit/schematics": "^21.2.0",
53
+ "@barcidev/typed-transloco": "^0.0.8",
53
54
  "@schematics/angular": "^21.2.0",
54
55
  "typescript": "~5.9.2"
55
56
  },
@@ -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;
@@ -11,11 +11,19 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.transloco = transloco;
13
13
  const schematics_1 = require("@angular-devkit/schematics");
14
- const utility_1 = require("@schematics/angular/utility");
14
+ const tasks_1 = require("@angular-devkit/schematics/tasks");
15
+ const dependencies_1 = require("@schematics/angular/utility/dependencies");
15
16
  const workspace_1 = require("@schematics/angular/utility/workspace");
16
- const jsonc_parser_1 = require("jsonc-parser");
17
+ const path_1 = require("path");
18
+ const file_actions_1 = require("../common/file-actions");
19
+ const pluralize_1 = require("../common/pluralize");
20
+ /**
21
+ * Schematic principal para configurar Transloco en un componente específico
22
+ */
17
23
  function transloco(options) {
18
24
  return (tree, _context) => __awaiter(this, void 0, void 0, function* () {
25
+ var _a;
26
+ // --- 1. CONFIGURACIÓN INICIAL Y WORKSPACE ---
19
27
  const workspace = yield (0, workspace_1.getWorkspace)(tree);
20
28
  if (!options.project) {
21
29
  options.project =
@@ -24,131 +32,67 @@ function transloco(options) {
24
32
  }
25
33
  const project = workspace.projects.get(options.project);
26
34
  if (!project) {
27
- _context.logger.error(`❌ El proyecto "${options.project}" no existe en el workspace.`);
28
- return;
35
+ throw new schematics_1.SchematicsException(`El proyecto "${options.project}" no existe.`);
29
36
  }
30
- const projectRoot = project.sourceRoot || "src";
31
- return (0, schematics_1.chain)([
37
+ // --- 2. DETERMINACIÓN DE RUTAS Y DETECCIÓN DE COMPONENTE ---
38
+ // Resolvemos el path relativo (src/app/...) basado en el directorio de ejecución
39
+ const fullPath = process.cwd();
40
+ const srcIndex = fullPath.lastIndexOf("src");
41
+ const relativePath = srcIndex !== -1
42
+ ? fullPath.substring(srcIndex)
43
+ : (0, path_1.join)((0, path_1.normalize)("src"), "app");
44
+ options.path = (0, path_1.normalize)(relativePath);
45
+ const directory = tree.getDir(options.path);
46
+ // Buscamos el archivo .ts principal del directorio
47
+ const componentFile = directory.subfiles.find((f) => f.endsWith(".component.ts")) ||
48
+ directory.subfiles.find((f) => f.endsWith(".ts"));
49
+ if (!componentFile && !options.name) {
50
+ throw new schematics_1.SchematicsException("❌ No se encontró un archivo .ts en este directorio y no se proveyó un --name.");
51
+ }
52
+ // Normalizamos el nombre (ej. mi-componente.component -> mi-componente)
53
+ options.name = componentFile
54
+ ? componentFile.replace(".component.ts", "").replace(".ts", "")
55
+ : options.name;
56
+ const rules = [
32
57
  (0, schematics_1.externalSchematic)("@barcidev/typed-transloco", "ng-add", {}),
33
- setupGlobalConfig(options.project, projectRoot),
34
- createI18nFiles(projectRoot),
35
- updateTsConfigRule(projectRoot),
36
- ]);
37
- });
38
- }
39
- // --- 1. CONFIGURACIÓN DEL PROVIDER ---
40
- function setupGlobalConfig(project, root) {
41
- return (tree) => {
42
- const appConfigPath = `${root}/app/app.config.ts`;
43
- if (!tree.exists(appConfigPath))
44
- return tree;
45
- const content = tree.read(appConfigPath).toString();
46
- if (content.includes("provideTransloco"))
47
- return tree;
48
- return (0, utility_1.addRootProvider)(project, ({ code, external }) => code `
49
- ${external("provideTransloco", "@jsverse/transloco")}({
50
- config: {
51
- availableLangs: ['en-US', 'es-CO'],
52
- defaultLang: 'en-US',
53
- prodMode: !${external("isDevMode", "@angular/core")}(),
54
- reRenderOnLangChange: true
55
- },
56
- loader: ${external("TranslocoHttpLoader", "@barcidev/typed-transloco")}
57
- })
58
- `);
59
- };
60
- }
61
- // --- 2. CREACIÓN DE ARCHIVOS (MODO STANDALONE) ---
62
- function createI18nFiles(root) {
63
- return (tree) => {
64
- const i18nPath = `${root}/app/i18n`;
65
- const files = [
66
- {
67
- path: `${i18nPath}/app-typed-transloco.directive.ts`,
68
- content: `import { Directive } from '@angular/core';
69
- import { TypedTranslocoDirective, TypedViewContext } from '@barcidev/typed-transloco';
70
- import { AppI18nType } from './app.i18n';
71
-
72
- @Directive({
73
- selector: '[typedTransloco]',
74
- standalone: true,
75
- })
76
- export class AppTypedTranslocoDirective<
77
- T extends keyof AppI18nType = keyof AppI18nType,
78
- > extends TypedTranslocoDirective<T> {
79
- static override ngTemplateContextGuard<T extends keyof AppI18nType>(
80
- dir: TypedTranslocoDirective<T>,
81
- ctx: any,
82
- ): ctx is TypedViewContext<T extends keyof AppI18nType ? AppI18nType[T] : AppI18nType> {
83
- return true;
84
- }
85
- }`,
86
- },
87
- {
88
- path: `${i18nPath}/app-typed-transloco.pipe.ts`,
89
- content: `import { Pipe } from '@angular/core';
90
- import { TypedTranslocoPipe } from '@barcidev/typed-transloco';
91
- import { AppI18nType } from './app.i18n';
92
-
93
- @Pipe({
94
- name: 'typedTransloco',
95
- standalone: true,
96
- pure: false,
97
- })
98
- export class AppTypedTranslocoPipe extends TypedTranslocoPipe<AppI18nType> {}`,
99
- },
100
- {
101
- path: `${i18nPath}/app.i18n.ts`,
102
- content: `export const appI18n = {};
103
- export type AppI18nType = typeof appI18n;
104
- export type AppLanguageCode = 'en-US' | 'es-CO';`,
105
- },
106
58
  ];
107
- files.forEach((f) => {
108
- if (!tree.exists(f.path)) {
109
- tree.create(f.path, f.content);
110
- }
111
- else {
112
- tree.overwrite(f.path, f.content);
113
- }
114
- });
115
- };
116
- }
117
- // --- 3. ACTUALIZACIÓN SEGURA DE TSCONFIG ---
118
- function updateTsConfigRule(root) {
119
- return (tree, context) => {
120
- var _a, _b;
121
- const tsConfigPath = tree.exists("/tsconfig.app.json")
122
- ? "/tsconfig.app.json"
123
- : "/tsconfig.json";
124
- const buffer = tree.read(tsConfigPath);
125
- if (!buffer)
126
- return;
127
- const content = buffer.toString();
128
- const tsconfig = (0, jsonc_parser_1.parse)(content);
129
- const baseUrl = ((_a = tsconfig.compilerOptions) === null || _a === void 0 ? void 0 : _a.baseUrl) || "./";
130
- let i18nPath = `${root}/app/i18n/*`;
131
- // Lógica de normalización de path
132
- if (baseUrl !== "./" && baseUrl !== ".") {
133
- const normalizedBase = baseUrl.replace(/^\.\/|\/$/g, "");
134
- if (i18nPath.startsWith(normalizedBase)) {
135
- i18nPath = i18nPath.replace(normalizedBase, "").replace(/^\//, "");
136
- }
59
+ // --- 3. CONFIGURACIÓN GLOBAL (IDEMPOTENTE) ---
60
+ const appConfigPath = "src/app/app.config.ts";
61
+ const appConfigContent = ((_a = tree.read(appConfigPath)) === null || _a === void 0 ? void 0 : _a.toString()) || "";
62
+ if (!appConfigContent.includes("provideTransloco")) {
63
+ _context.logger.info("📦 Transloco no detectado. Configurando globalmente...");
64
+ // Dependencias y tarea de instalación
65
+ rules.push((host) => {
66
+ (0, dependencies_1.addPackageJsonDependency)(host, {
67
+ type: dependencies_1.NodeDependencyType.Default,
68
+ name: "@jsverse/transloco",
69
+ version: "^7.0.0",
70
+ });
71
+ _context.addTask(new tasks_1.NodePackageInstallTask());
72
+ return host;
73
+ });
137
74
  }
138
- const alias = "@i18n/*";
139
- const modificationOptions = {
140
- formattingOptions: { insertSpaces: true, tabSize: 2 },
141
- };
142
- // Usamos jsonc-parser para modificar manteniendo comentarios
143
- let edits = (0, jsonc_parser_1.modify)(content, ["compilerOptions", "paths", alias], [i18nPath], modificationOptions);
144
- // Si no existe baseUrl, la añadimos para asegurar consistencia
145
- if (!((_b = tsconfig.compilerOptions) === null || _b === void 0 ? void 0 : _b.baseUrl)) {
146
- const baseUrlEdits = (0, jsonc_parser_1.modify)(content, ["compilerOptions", "baseUrl"], "./", modificationOptions);
147
- edits = [...edits, ...baseUrlEdits];
75
+ // --- 4. GENERACIÓN DE ARCHIVOS I18N DEL COMPONENTE ---
76
+ rules.push((0, schematics_1.mergeWith)((0, schematics_1.apply)((0, schematics_1.url)("./files/component"), [
77
+ (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) })),
78
+ (0, schematics_1.move)(options.path),
79
+ ])));
80
+ // --- 5. REGISTRO DEL SCOPE EN EL COMPONENTE ---
81
+ if (componentFile) {
82
+ const componentPath = (0, path_1.join)(options.path, componentFile);
83
+ const i18nConstantName = `${schematics_1.strings.camelize(options.name)}I18n`;
84
+ rules.push((0, file_actions_1.addProviderToStandaloneComponent)(componentPath, `provideTranslocoScopeWrapper(${i18nConstantName})`, [
85
+ {
86
+ symbol: `provideTranslocoScopeWrapper`,
87
+ path: `@i18n/transloco-wrapper`,
88
+ },
89
+ {
90
+ symbol: i18nConstantName,
91
+ path: `./${schematics_1.strings.dasherize(options.name)}.i18n`,
92
+ },
93
+ ]));
148
94
  }
149
- const updatedContent = (0, jsonc_parser_1.applyEdits)(content, edits);
150
- tree.overwrite(tsConfigPath, updatedContent);
151
- context.logger.info(`✅ Alias @i18n configurado en ${tsConfigPath}`);
152
- };
95
+ return (0, schematics_1.chain)(rules);
96
+ });
153
97
  }
154
98
  //# sourceMappingURL=index.js.map