@solercia/ui 0.1.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.
Files changed (33) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +2 -0
  4. package/README.md +110 -0
  5. package/fesm2022/solercia-ui.mjs +7213 -0
  6. package/fesm2022/solercia-ui.mjs.map +1 -0
  7. package/package.json +43 -0
  8. package/schematics/collection.json +34 -0
  9. package/schematics/entity/files/api/__name__-api.service.ts.template +51 -0
  10. package/schematics/entity/files/index.ts.template +2 -0
  11. package/schematics/entity/files/model/__name__.model.ts.template +16 -0
  12. package/schematics/entity/index.js +40 -0
  13. package/schematics/entity/schema.json +19 -0
  14. package/schematics/feature/files/index.ts.template +1 -0
  15. package/schematics/feature/files/ui/__name__.component.ts.template +41 -0
  16. package/schematics/feature/index.js +40 -0
  17. package/schematics/feature/schema.json +19 -0
  18. package/schematics/migrations/1-noop/index.js +19 -0
  19. package/schematics/migrations.json +10 -0
  20. package/schematics/ng-add/index.js +254 -0
  21. package/schematics/ng-add/schema.json +18 -0
  22. package/schematics/package.json +3 -0
  23. package/schematics/page/files/__name__.routes.ts.template +6 -0
  24. package/schematics/page/files/index.ts.template +2 -0
  25. package/schematics/page/files/ui/__name__-page.component.ts.template +31 -0
  26. package/schematics/page/index.js +38 -0
  27. package/schematics/page/schema.json +19 -0
  28. package/schematics/utils.js +127 -0
  29. package/schematics/widget/files/index.ts.template +1 -0
  30. package/schematics/widget/files/ui/__name__.component.ts.template +54 -0
  31. package/schematics/widget/index.js +40 -0
  32. package/schematics/widget/schema.json +19 -0
  33. package/types/solercia-ui.d.ts +1863 -0
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@solercia/ui",
3
+ "version": "0.1.0",
4
+ "description": "Design system Solercia (componentes sol-*, theming agnóstico por puertos, contrato i18n y schematics ng add/ng generate) para proyectos Angular del ecosistema Solercia.",
5
+ "license": "Apache-2.0",
6
+ "author": "Solercia Solutions SAS",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/camilocalderont/boki-front.git",
10
+ "directory": "projects/solercia/ui"
11
+ },
12
+ "publishConfig": {
13
+ "access": "public",
14
+ "registry": "https://registry.npmjs.org"
15
+ },
16
+ "schematics": "./schematics/collection.json",
17
+ "ng-update": {
18
+ "migrations": "./schematics/migrations.json"
19
+ },
20
+ "peerDependencies": {
21
+ "@angular/common": "^22.0.0",
22
+ "@angular/core": "^22.0.0",
23
+ "@angular/forms": "^22.0.0",
24
+ "rxjs": "^7.8.0",
25
+ "chart.js": "^4.5.1"
26
+ },
27
+ "dependencies": {
28
+ "tslib": "^2.3.0"
29
+ },
30
+ "sideEffects": false,
31
+ "module": "fesm2022/solercia-ui.mjs",
32
+ "typings": "types/solercia-ui.d.ts",
33
+ "exports": {
34
+ "./package.json": {
35
+ "default": "./package.json"
36
+ },
37
+ ".": {
38
+ "types": "./types/solercia-ui.d.ts",
39
+ "default": "./fesm2022/solercia-ui.mjs"
40
+ }
41
+ },
42
+ "type": "module"
43
+ }
@@ -0,0 +1,34 @@
1
+ {
2
+ "$schema": "../../../../node_modules/@angular-devkit/schematics/collection-schema.json",
3
+ "schematics": {
4
+ "ng-add": {
5
+ "description": "Scaffoldea el andamiaje FSD (carpetas + index.ts, path aliases, tokens + estilos, providers de los puertos de theming/i18n, @solercia/eslint-config y Husky) en un proyecto Angular consumidor.",
6
+ "factory": "./ng-add/index#ngAdd",
7
+ "schema": "./ng-add/schema.json"
8
+ },
9
+ "page": {
10
+ "aliases": ["p"],
11
+ "description": "Genera una page FSD (standalone, OnPush, claves i18n) en <sourceRoot>/pages/.",
12
+ "factory": "./page/index#page",
13
+ "schema": "./page/schema.json"
14
+ },
15
+ "feature": {
16
+ "aliases": ["f"],
17
+ "description": "Genera una feature FSD (standalone, OnPush, signals input()/output(), claves i18n) en <sourceRoot>/features/.",
18
+ "factory": "./feature/index#feature",
19
+ "schema": "./feature/schema.json"
20
+ },
21
+ "entity": {
22
+ "aliases": ["e"],
23
+ "description": "Genera una entity FSD (model + api) en <sourceRoot>/entities/.",
24
+ "factory": "./entity/index#entity",
25
+ "schema": "./entity/schema.json"
26
+ },
27
+ "widget": {
28
+ "aliases": ["w"],
29
+ "description": "Genera un widget FSD (standalone, OnPush, signals, claves i18n) en <sourceRoot>/widgets/.",
30
+ "factory": "./widget/index#widget",
31
+ "schema": "./widget/schema.json"
32
+ }
33
+ }
34
+ }
@@ -0,0 +1,51 @@
1
+ import { Injectable, inject } from '@angular/core';
2
+ import { HttpClient, HttpErrorResponse } from '@angular/common/http';
3
+ import { Observable, throwError } from 'rxjs';
4
+ import { catchError } from 'rxjs/operators';
5
+ import { APP_CONSTANTS } from '@shared/config';
6
+ import { ApiSuccessResponse, CustomError } from '@shared/api';
7
+ import { <%= className %>, Create<%= className %>Request } from '../model/<%= name %>.model';
8
+
9
+ /**
10
+ * Cliente REST de <%= className %>, generado por
11
+ * `ng g @solercia/ui:entity <%= name %>`. CRUD mínimo contra
12
+ * `${APP_CONSTANTS.apiBaseUrl}/<%= pluralName %>` — calcado del molde real
13
+ * (`src/entities/tag/api/tag-api.service.ts`).
14
+ */
15
+ @Injectable({ providedIn: 'root' })
16
+ export class <%= className %>ApiService {
17
+ private http = inject(HttpClient);
18
+ private baseUrl = `${APP_CONSTANTS.apiBaseUrl}/<%= pluralName %>`;
19
+
20
+ getAll(): Observable<ApiSuccessResponse<<%= className %>[]>> {
21
+ return this.http
22
+ .get<ApiSuccessResponse<<%= className %>[]>>(this.baseUrl)
23
+ .pipe(catchError(this.handleError));
24
+ }
25
+
26
+ create(data: Create<%= className %>Request): Observable<ApiSuccessResponse<<%= className %>>> {
27
+ return this.http
28
+ .post<ApiSuccessResponse<<%= className %>>>(this.baseUrl, data)
29
+ .pipe(catchError(this.handleError));
30
+ }
31
+
32
+ update(id: number, data: Partial<Create<%= className %>Request>): Observable<ApiSuccessResponse<<%= className %>>> {
33
+ return this.http
34
+ .put<ApiSuccessResponse<<%= className %>>>(`${this.baseUrl}/${id}`, data)
35
+ .pipe(catchError(this.handleError));
36
+ }
37
+
38
+ delete(id: number): Observable<ApiSuccessResponse<void>> {
39
+ return this.http
40
+ .delete<ApiSuccessResponse<void>>(`${this.baseUrl}/${id}`)
41
+ .pipe(catchError(this.handleError));
42
+ }
43
+
44
+ private handleError(error: HttpErrorResponse): Observable<never> {
45
+ const customError: CustomError = new Error(error.error?.message ?? 'Error desconocido') as CustomError;
46
+ customError.code = error.error?.errors?.[0]?.code ?? 'UNKNOWN';
47
+ customError.status = error.status;
48
+ customError.originalError = error;
49
+ return throwError(() => customError);
50
+ }
51
+ }
@@ -0,0 +1,2 @@
1
+ export type { <%= className %>, Create<%= className %>Request } from './model/<%= name %>.model';
2
+ export { <%= className %>ApiService } from './api/<%= name %>-api.service';
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Modelo de dominio de <%= className %>, generado por
3
+ * `ng g @solercia/ui:entity <%= name %>`.
4
+ *
5
+ * Los nombres de campo siguen el contrato PascalCase que expone el backend
6
+ * (.NET) — ajusta a la forma real del DTO (ver `src/entities/tag/model/` en
7
+ * boki-front para un ejemplo completo con validators).
8
+ */
9
+ export interface <%= className %> {
10
+ Id: number;
11
+ VcName: string;
12
+ }
13
+
14
+ export interface Create<%= className %>Request {
15
+ VcName: string;
16
+ }
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.entity = entity;
4
+ const schematics_1 = require("@angular-devkit/schematics");
5
+ const utils_1 = require("../utils");
6
+ /**
7
+ * `ng g @solercia/ui:entity <name>` — crea `<sourceRoot>/entities/<name>/`
8
+ * con `model/<name>.model.ts` (interfaz de dominio) y `api/<name>-api.service.ts`
9
+ * (CRUD REST sobre `APP_CONSTANTS.apiBaseUrl`), calcado del molde real
10
+ * (`src/entities/tag/`). Las entities NO tienen componentes: la capa `entities`
11
+ * solo modela dominio + acceso a datos (CONVENCIONES-FRONT-SOLERCIA §4).
12
+ *
13
+ * Actualiza (idempotente) el barrel agregador `<sourceRoot>/entities/index.ts`
14
+ * además del `index.ts` propio de la carpeta nueva.
15
+ */
16
+ function entity(options) {
17
+ return async (tree, context) => {
18
+ if (!options.name?.trim()) {
19
+ throw new Error('El schematic "entity" requiere un nombre, ej. `ng g @solercia/ui:entity tag`.');
20
+ }
21
+ const sourceRoot = await (0, utils_1.resolveSourceRoot)(tree, options.project);
22
+ const name = (0, utils_1.toDasherized)(options.name);
23
+ const className = (0, utils_1.toClassName)(options.name);
24
+ const pluralName = (0, utils_1.toPluralKebab)(options.name);
25
+ const targetDir = `${sourceRoot}/entities/${name}`;
26
+ const templateSource = (0, schematics_1.apply)((0, schematics_1.url)('./files'), [
27
+ (0, schematics_1.applyTemplates)({ name, className, pluralName }),
28
+ (0, schematics_1.move)(targetDir),
29
+ ]);
30
+ context.logger.info(`[@solercia/ui] Entity "${name}" creada en ${targetDir}/ (recurso REST /${pluralName}). ` +
31
+ `Ajusta los campos del modelo al contrato real del backend.`);
32
+ return (0, schematics_1.chain)([
33
+ (0, schematics_1.mergeWith)(templateSource),
34
+ (host) => {
35
+ (0, utils_1.appendToLayerBarrel)(host, `${sourceRoot}/entities/index.ts`, `export type { ${className}, Create${className}Request } from './${name}';\nexport { ${className}ApiService } from './${name}';`);
36
+ return host;
37
+ },
38
+ ]);
39
+ };
40
+ }
@@ -0,0 +1,19 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema",
3
+ "$id": "SolerciaUiEntity",
4
+ "title": "Solercia UI entity schematic",
5
+ "type": "object",
6
+ "properties": {
7
+ "name": {
8
+ "type": "string",
9
+ "description": "Nombre de la entity (kebab-case recomendado, ej. \"tag\").",
10
+ "$default": { "$source": "argv", "index": 0 }
11
+ },
12
+ "project": {
13
+ "type": "string",
14
+ "description": "Proyecto Angular objetivo. Por defecto, el proyecto de tipo application del workspace.",
15
+ "$default": { "$source": "projectName" }
16
+ }
17
+ },
18
+ "required": ["name"]
19
+ }
@@ -0,0 +1 @@
1
+ export { <%= className %>Component } from './ui/<%= name %>.component';
@@ -0,0 +1,41 @@
1
+ import { Component, ChangeDetectionStrategy, input, output, inject } from '@angular/core';
2
+ import { I18nService } from '@shared/i18n';
3
+
4
+ /**
5
+ * Feature generada por `ng g @solercia/ui:feature <%= name %>`.
6
+ *
7
+ * Standalone + `OnPush` + signals (`input()`/`output()`) + textos por clave
8
+ * i18n (`features.<%= camelName %>.*`), calcado del molde de `@solercia/ui`
9
+ * (ver `src/features/auth/ui/login-form.component.ts` en boki-front).
10
+ */
11
+ @Component({
12
+ standalone: true,
13
+ selector: '<%= selector %>',
14
+ changeDetection: ChangeDetectionStrategy.OnPush,
15
+ template: `
16
+ <div class="<%= name %>">
17
+ <span>{{ titleLabel() }}</span>
18
+ @if (value()) {
19
+ <span class="<%= name %>__value">{{ value() }}</span>
20
+ }
21
+ </div>
22
+ `,
23
+ styles: [`
24
+ .<%= name %> {
25
+ display: flex;
26
+ align-items: center;
27
+ gap: var(--sol-space-sm, 8px);
28
+ font-family: var(--sol-font-family);
29
+ color: var(--sol-color-text-primary);
30
+ }
31
+ `],
32
+ })
33
+ export class <%= className %>Component {
34
+ private readonly i18n = inject(I18nService);
35
+
36
+ /** Ajusta el tipo/valor por defecto al contrato real de la feature. */
37
+ readonly value = input<string>('');
38
+ readonly changed = output<string>();
39
+
40
+ readonly titleLabel = this.i18n.t('features.<%= camelName %>.title');
41
+ }
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.feature = feature;
4
+ const schematics_1 = require("@angular-devkit/schematics");
5
+ const utils_1 = require("../utils");
6
+ /**
7
+ * `ng g @solercia/ui:feature <name>` — crea `<sourceRoot>/features/<name>/`
8
+ * con un componente standalone `OnPush` con signals (`input()`/`output()`),
9
+ * calcado del molde real (`src/features/auth/ui/login-form.component.ts`):
10
+ * selector `sol-<name>`, clase `<Name>Component`, textos por
11
+ * `I18nService.t('features.<camelName>.*')`.
12
+ *
13
+ * Actualiza (idempotente) el barrel agregador `<sourceRoot>/features/index.ts`
14
+ * además del `index.ts` propio de la carpeta nueva.
15
+ */
16
+ function feature(options) {
17
+ return async (tree, context) => {
18
+ if (!options.name?.trim()) {
19
+ throw new Error('El schematic "feature" requiere un nombre, ej. `ng g @solercia/ui:feature manage-tags`.');
20
+ }
21
+ const sourceRoot = await (0, utils_1.resolveSourceRoot)(tree, options.project);
22
+ const name = (0, utils_1.toDasherized)(options.name);
23
+ const className = (0, utils_1.toClassName)(options.name);
24
+ const camelName = (0, utils_1.toCamelCase)(options.name);
25
+ const selector = `sol-${name}`;
26
+ const targetDir = `${sourceRoot}/features/${name}`;
27
+ (0, utils_1.upsertI18nKey)(tree, context, 'features', camelName, 'title', className, `${sourceRoot}/assets/i18n/es-CO.json`);
28
+ const templateSource = (0, schematics_1.apply)((0, schematics_1.url)('./files'), [
29
+ (0, schematics_1.applyTemplates)({ name, className, camelName, selector }),
30
+ (0, schematics_1.move)(targetDir),
31
+ ]);
32
+ return (0, schematics_1.chain)([
33
+ (0, schematics_1.mergeWith)(templateSource),
34
+ (host) => {
35
+ (0, utils_1.appendToLayerBarrel)(host, `${sourceRoot}/features/index.ts`, `export { ${className}Component } from './${name}';`);
36
+ return host;
37
+ },
38
+ ]);
39
+ };
40
+ }
@@ -0,0 +1,19 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema",
3
+ "$id": "SolerciaUiFeature",
4
+ "title": "Solercia UI feature schematic",
5
+ "type": "object",
6
+ "properties": {
7
+ "name": {
8
+ "type": "string",
9
+ "description": "Nombre de la feature (kebab-case recomendado, ej. \"manage-tags\").",
10
+ "$default": { "$source": "argv", "index": 0 }
11
+ },
12
+ "project": {
13
+ "type": "string",
14
+ "description": "Proyecto Angular objetivo. Por defecto, el proyecto de tipo application del workspace.",
15
+ "$default": { "$source": "projectName" }
16
+ }
17
+ },
18
+ "required": ["name"]
19
+ }
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.migrate = migrate;
4
+ /**
5
+ * Migración no-op de ejemplo (`ng update @solercia/ui` a 0.1.0). Sienta el
6
+ * andamiaje/convención para futuras migraciones reales — p. ej. cuando un
7
+ * `ng update` mayor renombre un token `--sol-*` o un `input()` de un
8
+ * componente `sol-*`, esta carpeta es el molde: cada versión con migración
9
+ * agrega su propia entrada a `migrations.json` con un factory dedicado.
10
+ *
11
+ * Ver diseño (Decisión B): lo que evoluciona en la librería se propaga por
12
+ * `ng update`, no por re-clonado (anti-patrón `modbase`).
13
+ */
14
+ function migrate() {
15
+ return (tree) => {
16
+ // Intencionalmente no-op: no hay cambios que migrar en 0.1.0.
17
+ return tree;
18
+ };
19
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "$schema": "../../../../node_modules/@angular-devkit/schematics/collection-schema.json",
3
+ "schematics": {
4
+ "migration-0-1-0-noop": {
5
+ "version": "0.1.0",
6
+ "description": "Andamiaje de migraciones para `ng update @solercia/ui`. No-op: sienta la convención para futuros renombres de tokens/inputs propagables (ver design.md, Decisión B — herencia por dependencia).",
7
+ "factory": "./migrations/1-noop/index#migrate"
8
+ }
9
+ }
10
+ }
@@ -0,0 +1,254 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ngAdd = ngAdd;
4
+ const schematics_1 = require("@angular-devkit/schematics");
5
+ const utility_1 = require("@schematics/angular/utility");
6
+ const json_file_1 = require("@schematics/angular/utility/json-file");
7
+ const utils_1 = require("../utils");
8
+ /** Alias FSD fijos del ecosistema Solercia (CONVENCIONES-FRONT-SOLERCIA.md). */
9
+ function fsdPathAliases(sourceRoot) {
10
+ return {
11
+ '@app/*': [`${sourceRoot}/app/*`],
12
+ '@pages/*': [`${sourceRoot}/pages/*`],
13
+ '@widgets/*': [`${sourceRoot}/widgets/*`],
14
+ '@features/*': [`${sourceRoot}/features/*`],
15
+ '@entities/*': [`${sourceRoot}/entities/*`],
16
+ '@shared/*': [`${sourceRoot}/shared/*`],
17
+ };
18
+ }
19
+ /**
20
+ * `ng add @solercia/ui` — scaffoldea el andamiaje FSD en un proyecto Angular
21
+ * standalone recién creado (`ng new`): carpetas `pages/widgets/features/entities`
22
+ * (con sus `index.ts` agregadores) + `shared/tokens` (adaptadores de los
23
+ * puertos de `@solercia/ui`), path aliases en `tsconfig.json`, `provideTheme()`
24
+ * cableado real en `app.config.ts`, `@solercia/eslint-config` referenciado y
25
+ * Husky + lint-staged + commitlint.
26
+ *
27
+ * Alcance deliberado (ver `openspec/07-e9-extraccion-solercia-ui/design.md`,
28
+ * Decisión A): `@solercia/ui` expone puertos (`THEME_SOURCE`, `SOL_TENANT_RESOLVER`,
29
+ * `SOL_I18N`) con defaults null-object `providedIn: 'root'` — un proyecto recién
30
+ * scaffoldeado YA renderiza con el tema por defecto de la librería sin wiring
31
+ * adicional. `ng-add` deja los ADAPTADORES listos en `shared/tokens/` (con TODO)
32
+ * para cuando el consumidor tenga backend/tenant real, en vez de inventar una
33
+ * llamada HTTP falsa que rompería un `ng new` limpio.
34
+ */
35
+ function ngAdd(options) {
36
+ return async (tree, context) => {
37
+ const projectName = await (0, utils_1.resolveProjectName)(tree, options.project);
38
+ const sourceRoot = await (0, utils_1.resolveSourceRoot)(tree, options.project);
39
+ const rules = [
40
+ scaffoldFsdLayers(sourceRoot),
41
+ scaffoldThemeAdapters(sourceRoot),
42
+ wireTsconfigPaths(sourceRoot),
43
+ appendGlobalStyles(sourceRoot, context),
44
+ scaffoldEslintConfig(context),
45
+ scaffoldHusky(context),
46
+ ];
47
+ // provideTheme() es la ÚNICA pieza que se puede cablear con seguridad vía
48
+ // AST en CUALQUIER `ng new` estándar (import de paquete, sin rutas
49
+ // relativas frágiles): activa el runtime de theming de @solercia/ui
50
+ // (aplica SOL_DEFAULT_THEME de inmediato).
51
+ if (projectName) {
52
+ rules.push((0, utility_1.addRootProvider)(projectName, ({ code, external }) => {
53
+ return code `${external('provideTheme', '@solercia/ui')}()`;
54
+ }));
55
+ }
56
+ else {
57
+ context.logger.warn('[@solercia/ui] No se encontró angular.json — se omite el cableado automático de ' +
58
+ 'provideTheme() en app.config.ts. Agrégalo a mano: providers: [provideTheme(), ...].');
59
+ }
60
+ // Solo devDependencies que SÍ existen en un registry público — nunca
61
+ // fuerces `npm install` contra un paquete inexistente (@solercia/eslint-config
62
+ // no está publicado todavía, PR4). `addDependency` ya agenda su propia
63
+ // NodePackageInstallTask (una sola, deduplicada) salvo `skipInstall`.
64
+ const installBehavior = options.skipInstall ? utility_1.InstallBehavior.None : utility_1.InstallBehavior.Auto;
65
+ return (0, schematics_1.chain)([
66
+ ...rules,
67
+ (0, utility_1.addDependency)('husky', '^9.1.7', { type: utility_1.DependencyType.Dev, install: installBehavior }),
68
+ (0, utility_1.addDependency)('lint-staged', '^17.0.8', { type: utility_1.DependencyType.Dev, install: installBehavior }),
69
+ (0, utility_1.addDependency)('@commitlint/cli', '^21.2.1', { type: utility_1.DependencyType.Dev, install: installBehavior }),
70
+ (0, utility_1.addDependency)('@commitlint/config-conventional', '^21.2.0', {
71
+ type: utility_1.DependencyType.Dev,
72
+ install: installBehavior,
73
+ }),
74
+ // @solercia/eslint-config aún no está publicado (07-e9 PR4, bloqueado por
75
+ // D1 del openspec madre): se documenta como pendiente en vez de forzar un
76
+ // `npm install` que fallaría contra un paquete inexistente en el registry.
77
+ (host, ctx) => {
78
+ ctx.logger.info('[@solercia/ui] @solercia/eslint-config todavía no está publicado (PR4 pendiente). ' +
79
+ 'eslint.config.js quedó listo esperándolo — mientras tanto, referencia el preset por ' +
80
+ 'ruta relativa si tienes el monorepo clonado (ver packages/eslint-config/README.md).');
81
+ return host;
82
+ },
83
+ ]);
84
+ };
85
+ }
86
+ /** Carpetas FSD con su `index.ts` agregador (vacío salvo el comentario de capa,
87
+ * calcado de `src/{pages,widgets,features,entities}/index.ts` reales). `pages/`
88
+ * NUNCA reexporta slices (lazy-loading por ruta) — las otras 3 capas sí. */
89
+ function scaffoldFsdLayers(sourceRoot) {
90
+ const layers = [
91
+ { name: 'pages', comment: 'Pages layer — lazy-loaded route views' },
92
+ { name: 'widgets', comment: 'Widgets layer — autonomous composed UI blocks' },
93
+ { name: 'features', comment: 'Features layer — user actions with business value' },
94
+ { name: 'entities', comment: 'Entities layer — domain models' },
95
+ ];
96
+ return (tree) => {
97
+ for (const layer of layers) {
98
+ const indexPath = `/${sourceRoot}/${layer.name}/index.ts`;
99
+ if (!tree.exists(indexPath)) {
100
+ tree.create(indexPath, `// ${layer.comment}\n`);
101
+ }
102
+ }
103
+ return tree;
104
+ };
105
+ }
106
+ /** Adaptadores mínimos de los puertos de `@solercia/ui` en `shared/tokens/`,
107
+ * listos para activarse cuando exista backend/tenant real. */
108
+ function scaffoldThemeAdapters(sourceRoot) {
109
+ return (tree) => {
110
+ const dir = `/${sourceRoot}/shared/tokens`;
111
+ const themeSourcePath = `${dir}/app-theme-source.ts`;
112
+ if (!tree.exists(themeSourcePath)) {
113
+ tree.create(themeSourcePath, `import { Injectable } from '@angular/core';\n` +
114
+ `import type { ThemeFile, ThemeSource } from '@solercia/ui';\n\n` +
115
+ `/**\n` +
116
+ ` * Adaptador de THEME_SOURCE (puerto de @solercia/ui). Por defecto no resuelve\n` +
117
+ ` * tema por tenant (retorna null → se aplica SOL_DEFAULT_THEME). Reemplaza el\n` +
118
+ ` * cuerpo de loadTheme() por tu llamada real (HTTP, storage, etc.) cuando exista\n` +
119
+ ` * backend multi-tenant. Cablea en app.config.ts:\n` +
120
+ ` * { provide: THEME_SOURCE, useExisting: AppThemeSource }\n` +
121
+ ` */\n` +
122
+ `@Injectable({ providedIn: 'root' })\n` +
123
+ `export class AppThemeSource implements ThemeSource {\n` +
124
+ ` async loadTheme(_tenantId: number | string): Promise<ThemeFile | null> {\n` +
125
+ ` return null;\n` +
126
+ ` }\n` +
127
+ `}\n`);
128
+ }
129
+ const tenantResolverPath = `${dir}/app-tenant-resolver.ts`;
130
+ if (!tree.exists(tenantResolverPath)) {
131
+ tree.create(tenantResolverPath, `import { Injectable } from '@angular/core';\n` +
132
+ `import type { SolTenantResolver } from '@solercia/ui';\n\n` +
133
+ `/**\n` +
134
+ ` * Adaptador de SOL_TENANT_RESOLVER (puerto de @solercia/ui). Por defecto no hay\n` +
135
+ ` * tenant activo (tema único). Implementa tu resolución real (sesión, dominio,\n` +
136
+ ` * slug) cuando exista multi-tenant. Cablea en app.config.ts:\n` +
137
+ ` * { provide: SOL_TENANT_RESOLVER, useExisting: AppTenantResolver }\n` +
138
+ ` */\n` +
139
+ `@Injectable({ providedIn: 'root' })\n` +
140
+ `export class AppTenantResolver implements SolTenantResolver {\n` +
141
+ ` activeTenantId(): number | null {\n` +
142
+ ` return null;\n` +
143
+ ` }\n` +
144
+ `}\n`);
145
+ }
146
+ const indexPath = `${dir}/index.ts`;
147
+ if (!tree.exists(indexPath)) {
148
+ tree.create(indexPath, `export { AppThemeSource } from './app-theme-source';\n` +
149
+ `export { AppTenantResolver } from './app-tenant-resolver';\n`);
150
+ }
151
+ return tree;
152
+ };
153
+ }
154
+ /** Path aliases FSD en `tsconfig.json` (edición segura vía JSONC AST — tolera
155
+ * comentarios/trailing commas, igual que el resto del tooling oficial Angular). */
156
+ function wireTsconfigPaths(sourceRoot) {
157
+ return (tree) => {
158
+ const tsconfigPath = '/tsconfig.json';
159
+ if (!tree.exists(tsconfigPath)) {
160
+ return tree;
161
+ }
162
+ const json = new json_file_1.JSONFile(tree, tsconfigPath);
163
+ for (const [alias, paths] of Object.entries(fsdPathAliases(sourceRoot))) {
164
+ json.modify(['compilerOptions', 'paths', alias], paths);
165
+ }
166
+ return tree;
167
+ };
168
+ }
169
+ /** Snippet de estilos globales que demuestra el consumo de los tokens `--sol-*`
170
+ * (el resto de las 95 variables las emite ThemeService en runtime — ver
171
+ * projects/solercia/ui/docs/THEMING.md). No falla si el proyecto no tiene
172
+ * `styles.css` (p. ej. usa SCSS): solo avisa. */
173
+ function appendGlobalStyles(sourceRoot, context) {
174
+ return (tree) => {
175
+ const stylesPath = `/${sourceRoot}/styles.css`;
176
+ if (!tree.exists(stylesPath)) {
177
+ context.logger.warn(`[@solercia/ui] No se encontró "${stylesPath}" — agrega manualmente el snippet de ` +
178
+ 'tokens --sol-* a tu hoja de estilos global (ver projects/solercia/ui/docs/THEMING.md).');
179
+ return tree;
180
+ }
181
+ const marker = '/* @solercia/ui — tokens base */';
182
+ const current = tree.read(stylesPath)?.toString('utf-8') ?? '';
183
+ if (current.includes(marker)) {
184
+ return tree;
185
+ }
186
+ const snippet = `\n${marker}\n` +
187
+ `body {\n` +
188
+ ` background: var(--sol-bg-page);\n` +
189
+ ` color: var(--sol-color-text-primary);\n` +
190
+ ` font-family: var(--sol-font-family);\n` +
191
+ `}\n`;
192
+ tree.overwrite(stylesPath, `${current}${snippet}`);
193
+ return tree;
194
+ };
195
+ }
196
+ /** `eslint.config.js` del consumidor, referenciando `@solercia/eslint-config`
197
+ * (preset compartido — fronteras FSD, smart/dumb, Chart.js, naming-convention).
198
+ * El `srcDir` por defecto del preset (`'src'`) ya coincide con el scaffold FSD
199
+ * de este schematic. No sobrescribe uno existente (proyecto que ya trae su
200
+ * propio lint). */
201
+ function scaffoldEslintConfig(context) {
202
+ return (tree) => {
203
+ const path = '/eslint.config.js';
204
+ if (tree.exists(path)) {
205
+ context.logger.info('[@solercia/ui] Ya existe "eslint.config.js" — se deja intacto.');
206
+ return tree;
207
+ }
208
+ tree.create(path, `// @ts-check\n` +
209
+ `// Generado por \`ng add @solercia/ui\`. @solercia/eslint-config trae las fronteras FSD\n` +
210
+ `// (app → pages → widgets → features → entities → shared), la regla smart/dumb de\n` +
211
+ `// shared/ui, la restricción de Chart.js y naming-convention/filename-case.\n` +
212
+ `import solerciaConfig from '@solercia/eslint-config';\n\n` +
213
+ `export default [\n` +
214
+ ` { ignores: ['.angular/', 'dist/', 'coverage/', 'node_modules/'] },\n` +
215
+ ` ...solerciaConfig,\n` +
216
+ `];\n`);
217
+ return tree;
218
+ };
219
+ }
220
+ /** Husky + lint-staged + commitlint, calcados 1:1 del cableado real de
221
+ * `boki-front` (07-e9 PR2, T21): `pre-commit` → lint-staged (eslint --fix +
222
+ * tsc --noEmit sobre staged); `commit-msg` → commitlint (conventional commits). */
223
+ function scaffoldHusky(context) {
224
+ return (tree) => {
225
+ if (!tree.exists('/.husky/pre-commit')) {
226
+ tree.create('/.husky/pre-commit', 'npx lint-staged\n');
227
+ }
228
+ if (!tree.exists('/.husky/commit-msg')) {
229
+ tree.create('/.husky/commit-msg', 'npx --no -- commitlint --edit "$1"\n');
230
+ }
231
+ if (!tree.exists('/commitlint.config.js')) {
232
+ tree.create('/commitlint.config.js', `module.exports = {\n extends: ['@commitlint/config-conventional'],\n};\n`);
233
+ }
234
+ if (!tree.exists('/lint-staged.config.js')) {
235
+ tree.create('/lint-staged.config.js', `// tsc --noEmit corre UNA vez contra todo el proyecto (no archivo por archivo):\n` +
236
+ `// TypeScript necesita el grafo completo para chequear tipos correctamente.\n` +
237
+ `module.exports = {\n` +
238
+ ` '*.ts': [\n` +
239
+ ` 'eslint --fix',\n` +
240
+ ` () => 'tsc -p tsconfig.app.json --noEmit',\n` +
241
+ ` ],\n` +
242
+ `};\n`);
243
+ }
244
+ if (tree.exists('/package.json')) {
245
+ const pkg = new json_file_1.JSONFile(tree, '/package.json');
246
+ if (pkg.get(['scripts', 'prepare']) === undefined) {
247
+ pkg.modify(['scripts', 'prepare'], 'husky');
248
+ }
249
+ }
250
+ context.logger.info('[@solercia/ui] Husky scaffoldeado. Ejecuta `npm run prepare` (o `npx husky`) una vez ' +
251
+ 'instaladas las dependencias para activar los hooks de git.');
252
+ return tree;
253
+ };
254
+ }
@@ -0,0 +1,18 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema",
3
+ "$id": "SolerciaUiNgAdd",
4
+ "title": "Solercia UI ng-add schema",
5
+ "type": "object",
6
+ "properties": {
7
+ "project": {
8
+ "type": "string",
9
+ "description": "Proyecto Angular a configurar. Por defecto, el proyecto de tipo application del workspace.",
10
+ "$default": { "$source": "projectName" }
11
+ },
12
+ "skipInstall": {
13
+ "type": "boolean",
14
+ "default": false,
15
+ "description": "Omite la instalación automática de dependencias tras el scaffolding."
16
+ }
17
+ }
18
+ }
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }
@@ -0,0 +1,6 @@
1
+ import { Routes } from '@angular/router';
2
+ import { <%= className %>PageComponent } from './ui/<%= name %>-page.component';
3
+
4
+ export const <%= camelName %>Routes: Routes = [
5
+ { path: '', component: <%= className %>PageComponent },
6
+ ];
@@ -0,0 +1,2 @@
1
+ export { <%= className %>PageComponent } from './ui/<%= name %>-page.component';
2
+ export { <%= camelName %>Routes } from './<%= name %>.routes';