@sixbell-telco/sdk-tools 0.0.0-stage → 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 (58) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +277 -2
  3. package/data/security-floors.json +47 -0
  4. package/package.json +43 -4
  5. package/recipes/README.md +53 -0
  6. package/recipes/crud-list.md +21 -0
  7. package/recipes/custom-component.md +35 -0
  8. package/recipes/detail-page.md +19 -0
  9. package/recipes/form-dialog.md +17 -0
  10. package/recipes/parts/crud-list/i18n.json +83 -0
  11. package/recipes/parts/crud-list/src/app/features/__name__/__name__.routes.ts.tpl +30 -0
  12. package/recipes/parts/crud-list/src/app/features/__name__/pages/__name__-list/__name__-list.component.html.tpl +102 -0
  13. package/recipes/parts/crud-list/src/app/features/__name__/pages/__name__-list/__name__-list.component.spec.ts.tpl +101 -0
  14. package/recipes/parts/crud-list/src/app/features/__name__/pages/__name__-list/__name__-list.component.ts.tpl +143 -0
  15. package/recipes/parts/detail-page/i18n.json +32 -0
  16. package/recipes/parts/detail-page/src/app/features/__name__/pages/__name__-detail/__name__-detail.component.html.tpl +35 -0
  17. package/recipes/parts/detail-page/src/app/features/__name__/pages/__name__-detail/__name__-detail.component.spec.ts.tpl +58 -0
  18. package/recipes/parts/detail-page/src/app/features/__name__/pages/__name__-detail/__name__-detail.component.ts.tpl +68 -0
  19. package/recipes/parts/entity/i18n.json +5 -0
  20. package/recipes/parts/entity/src/app/features/__name__/__name__.model.ts.tpl +9 -0
  21. package/recipes/parts/entity/src/app/features/__name__/__name__.service.spec.ts.tpl +29 -0
  22. package/recipes/parts/entity/src/app/features/__name__/__name__.service.ts.tpl +33 -0
  23. package/recipes/parts/form-dialog/i18n.json +35 -0
  24. package/recipes/parts/form-dialog/src/app/features/__name__/components/__name__-form-dialog/__name__-form-dialog.component.html.tpl +33 -0
  25. package/recipes/parts/form-dialog/src/app/features/__name__/components/__name__-form-dialog/__name__-form-dialog.component.spec.ts.tpl +69 -0
  26. package/recipes/parts/form-dialog/src/app/features/__name__/components/__name__-form-dialog/__name__-form-dialog.component.ts.tpl +73 -0
  27. package/src/add/add.mjs +251 -0
  28. package/src/check/config.mjs +112 -0
  29. package/src/check/exceptions.mjs +103 -0
  30. package/src/check/federation.mjs +224 -0
  31. package/src/check/finding.mjs +23 -0
  32. package/src/check/harness.mjs +146 -0
  33. package/src/check/i18n.mjs +218 -0
  34. package/src/check/integration.mjs +566 -0
  35. package/src/check/security.mjs +165 -0
  36. package/src/check/steps.mjs +37 -0
  37. package/src/check/styles.mjs +347 -0
  38. package/src/check/wiring.mjs +198 -0
  39. package/src/check.mjs +333 -0
  40. package/src/cli.mjs +551 -0
  41. package/src/docs/docs.mjs +154 -0
  42. package/src/doctor/doctor.mjs +492 -0
  43. package/src/format.mjs +102 -0
  44. package/src/info/info.mjs +149 -0
  45. package/src/init/init.mjs +490 -0
  46. package/src/init/merge.mjs +191 -0
  47. package/src/init/template.mjs +292 -0
  48. package/src/mcp/catalog.mjs +248 -0
  49. package/src/mcp/glossary.mjs +75 -0
  50. package/src/mcp/manifest.mjs +53 -0
  51. package/src/mcp/recipes.mjs +198 -0
  52. package/src/mcp/server.mjs +249 -0
  53. package/src/mcp/upgrade-guide.mjs +116 -0
  54. package/src/mcp/usage.mjs +48 -0
  55. package/src/project/project.mjs +220 -0
  56. package/src/types.d.ts +448 -0
  57. package/src/upgrade/lockstep.mjs +153 -0
  58. package/src/upgrade/upgrade.mjs +623 -0
@@ -0,0 +1,29 @@
1
+ import { TestBed } from '@angular/core/testing';
2
+ import { __Name__Service } from './__name__.service';
3
+
4
+ describe('__Name__Service', () => {
5
+ let service: __Name__Service;
6
+
7
+ beforeEach(() => {
8
+ service = TestBed.inject(__Name__Service);
9
+ });
10
+
11
+ it('creates, finds, updates and removes a record', () => {
12
+ const created = service.create({ name: 'First', description: 'One' });
13
+ expect(service.items()).toEqual([created]);
14
+ expect(service.find(created.id)).toEqual(created);
15
+
16
+ service.update(created.id, { name: 'Renamed', description: 'Two' });
17
+ expect(service.find(created.id)).toEqual({ id: created.id, name: 'Renamed', description: 'Two' });
18
+
19
+ service.remove(created.id);
20
+ expect(service.items()).toEqual([]);
21
+ expect(service.find(created.id)).toBeUndefined();
22
+ });
23
+
24
+ it('gives every record its own id', () => {
25
+ const first = service.create({ name: 'A', description: '' });
26
+ const second = service.create({ name: 'B', description: '' });
27
+ expect(first.id).not.toBe(second.id);
28
+ });
29
+ });
@@ -0,0 +1,33 @@
1
+ import { Injectable, signal } from '@angular/core';
2
+ import { __Name__, __Name__Draft } from './__name__.model';
3
+
4
+ /**
5
+ * In-memory store for __name__ records. Replace the method bodies with calls to your backend and
6
+ * keep the signal API, so the pages that use it do not change.
7
+ */
8
+ @Injectable({ providedIn: 'root' })
9
+ export class __Name__Service {
10
+ private readonly store = signal<__Name__[]>([]);
11
+ private sequence = 0;
12
+
13
+ /** Every record, newest last. */
14
+ readonly items = this.store.asReadonly();
15
+
16
+ find(id: string): __Name__ | undefined {
17
+ return this.store().find((item) => item.id === id);
18
+ }
19
+
20
+ create(draft: __Name__Draft): __Name__ {
21
+ const item: __Name__ = { id: `${Date.now().toString(36)}-${++this.sequence}`, ...draft };
22
+ this.store.update((items) => [...items, item]);
23
+ return item;
24
+ }
25
+
26
+ update(id: string, draft: __Name__Draft): void {
27
+ this.store.update((items) => items.map((item) => (item.id === id ? { ...item, ...draft } : item)));
28
+ }
29
+
30
+ remove(id: string): void {
31
+ this.store.update((items) => items.filter((item) => item.id !== id));
32
+ }
33
+ }
@@ -0,0 +1,35 @@
1
+ {
2
+ "en": {
3
+ "actions": { "cancel": "Cancel", "create": "Create", "save": "Save" },
4
+ "form": {
5
+ "create_title": "New record",
6
+ "edit_title": "Edit record",
7
+ "name_hint": "Up to 80 characters.",
8
+ "name_required": "Enter a name.",
9
+ "name_too_long": "Use 80 characters or fewer.",
10
+ "description_too_long": "Use 500 characters or fewer."
11
+ }
12
+ },
13
+ "es": {
14
+ "actions": { "cancel": "Cancelar", "create": "Crear", "save": "Guardar" },
15
+ "form": {
16
+ "create_title": "Nuevo registro",
17
+ "edit_title": "Editar registro",
18
+ "name_hint": "Hasta 80 caracteres.",
19
+ "name_required": "Ingrese un nombre.",
20
+ "name_too_long": "Use 80 caracteres o menos.",
21
+ "description_too_long": "Use 500 caracteres o menos."
22
+ }
23
+ },
24
+ "pt": {
25
+ "actions": { "cancel": "Cancelar", "create": "Criar", "save": "Salvar" },
26
+ "form": {
27
+ "create_title": "Novo registro",
28
+ "edit_title": "Editar registro",
29
+ "name_hint": "Até 80 caracteres.",
30
+ "name_required": "Informe um nome.",
31
+ "name_too_long": "Use 80 caracteres ou menos.",
32
+ "description_too_long": "Use 500 caracteres ou menos."
33
+ }
34
+ }
35
+ }
@@ -0,0 +1,33 @@
1
+ <st-dialog [(opened)]="opened" width="lg">
2
+ <st-dialog-title>{{ (isEdit() ? '__i18n__.form.edit_title' : '__i18n__.form.create_title') | translate }}</st-dialog-title>
3
+ <st-dialog-content>
4
+ <form #formRef id="__name__-form" class="flex flex-col gap-4" [formGroup]="form" (ngSubmit)="submit()">
5
+ <st-form-required-legend />
6
+ <st-form-item>
7
+ <st-input formControlName="name" [label]="'__i18n__.fields.name' | translate" [parentForm]="form" />
8
+ <st-form-hint>{{ '__i18n__.form.name_hint' | translate }}</st-form-hint>
9
+ <st-form-errors
10
+ formField="name"
11
+ [parentForm]="form"
12
+ [isRequired]="'__i18n__.form.name_required' | translate"
13
+ [isMaxLength]="'__i18n__.form.name_too_long' | translate"
14
+ />
15
+ </st-form-item>
16
+ <st-form-item>
17
+ <st-textarea
18
+ formControlName="description"
19
+ [label]="'__i18n__.fields.description' | translate"
20
+ [parentForm]="form"
21
+ [maxCharacters]="500"
22
+ />
23
+ <st-form-errors formField="description" [parentForm]="form" [isMaxLength]="'__i18n__.form.description_too_long' | translate" />
24
+ </st-form-item>
25
+ </form>
26
+ </st-dialog-content>
27
+ <st-dialog-actions>
28
+ <st-button variant="secondary" (clicked)="cancel()">{{ '__i18n__.actions.cancel' | translate }}</st-button>
29
+ <st-button variant="primary" [loader]="saving()" [disabled]="saving()" (clicked)="submit()">
30
+ {{ (isEdit() ? '__i18n__.actions.save' : '__i18n__.actions.create') | translate }}
31
+ </st-button>
32
+ </st-dialog-actions>
33
+ </st-dialog>
@@ -0,0 +1,69 @@
1
+ import { ComponentFixture, TestBed } from '@angular/core/testing';
2
+ import { TranslatePipe } from '@sixbell-telco/sdk/utils/translation';
3
+ import { MockPipe } from 'ng-mocks';
4
+ import { __Name__FormDialogComponent } from './__name__-form-dialog.component';
5
+
6
+ describe('__Name__FormDialogComponent', () => {
7
+ let fixture: ComponentFixture<__Name__FormDialogComponent>;
8
+ let component: __Name__FormDialogComponent;
9
+
10
+ beforeEach(async () => {
11
+ await TestBed.configureTestingModule({
12
+ imports: [__Name__FormDialogComponent, MockPipe(TranslatePipe, (key: string) => key)],
13
+ })
14
+ // The kit dialog renders in a CDK overlay; these tests drive the form, not the overlay.
15
+ .overrideComponent(__Name__FormDialogComponent, { set: { template: '' } })
16
+ .compileComponents();
17
+
18
+ fixture = TestBed.createComponent(__Name__FormDialogComponent);
19
+ component = fixture.componentInstance;
20
+ });
21
+
22
+ it('starts empty when it opens to create', () => {
23
+ component.form.setValue({ name: 'stale', description: 'stale' });
24
+ fixture.componentRef.setInput('opened', true);
25
+ fixture.detectChanges();
26
+
27
+ expect(component.isEdit()).toBe(false);
28
+ expect(component.form.getRawValue()).toEqual({ name: '', description: '' });
29
+ });
30
+
31
+ it('loads the record when it opens to edit', () => {
32
+ fixture.componentRef.setInput('value', { id: '1', name: 'Alpha', description: 'First' });
33
+ fixture.componentRef.setInput('opened', true);
34
+ fixture.detectChanges();
35
+
36
+ expect(component.isEdit()).toBe(true);
37
+ expect(component.form.getRawValue()).toEqual({ name: 'Alpha', description: 'First' });
38
+ });
39
+
40
+ it('does not emit an invalid form and marks the fields', () => {
41
+ const saved = jest.fn();
42
+ component.saved.subscribe(saved);
43
+ fixture.componentRef.setInput('opened', true);
44
+ fixture.detectChanges();
45
+
46
+ component.submit();
47
+
48
+ expect(saved).not.toHaveBeenCalled();
49
+ expect(component.form.controls.name.touched).toBe(true);
50
+ });
51
+
52
+ it('emits the value of a valid form', () => {
53
+ const saved = jest.fn();
54
+ component.saved.subscribe(saved);
55
+ fixture.componentRef.setInput('opened', true);
56
+ fixture.detectChanges();
57
+
58
+ component.form.setValue({ name: 'Beta', description: '' });
59
+ component.submit();
60
+
61
+ expect(saved).toHaveBeenCalledWith({ name: 'Beta', description: '' });
62
+ });
63
+
64
+ it('closes on cancel', () => {
65
+ fixture.componentRef.setInput('opened', true);
66
+ component.cancel();
67
+ expect(component.opened()).toBe(false);
68
+ });
69
+ });
@@ -0,0 +1,73 @@
1
+ import { ChangeDetectionStrategy, Component, computed, effect, ElementRef, input, model, output, viewChild } from '@angular/core';
2
+ import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
3
+ import { ButtonComponent } from '@sixbell-telco/sdk/components/button';
4
+ import { DialogActionsComponent, DialogComponent, DialogContentComponent, DialogTitleComponent } from '@sixbell-telco/sdk/components/dialog';
5
+ import { FormErrorsComponent } from '@sixbell-telco/sdk/components/forms/form-error';
6
+ import { FormHintComponent, FormRequiredLegendComponent } from '@sixbell-telco/sdk/components/forms/form-hint';
7
+ import { FormItemComponent } from '@sixbell-telco/sdk/components/forms/form-item';
8
+ import { InputComponent } from '@sixbell-telco/sdk/components/forms/input';
9
+ import { TextareaComponent } from '@sixbell-telco/sdk/components/forms/textarea';
10
+ import { TranslatePipe } from '@sixbell-telco/sdk/utils/translation';
11
+ import { __Name__, __Name__Draft } from '../../__name__.model';
12
+
13
+ /** Create or edit dialog for a __name__ record. The parent saves and closes it. */
14
+ @Component({
15
+ selector: 'app-__name__-form-dialog',
16
+ imports: [
17
+ ReactiveFormsModule,
18
+ ButtonComponent,
19
+ DialogComponent,
20
+ DialogTitleComponent,
21
+ DialogContentComponent,
22
+ DialogActionsComponent,
23
+ FormItemComponent,
24
+ FormErrorsComponent,
25
+ FormHintComponent,
26
+ FormRequiredLegendComponent,
27
+ InputComponent,
28
+ TextareaComponent,
29
+ TranslatePipe,
30
+ ],
31
+ templateUrl: './__name__-form-dialog.component.html',
32
+ changeDetection: ChangeDetectionStrategy.OnPush,
33
+ })
34
+ export class __Name__FormDialogComponent {
35
+ /** Open state; bind it two-way with `[(opened)]`. */
36
+ readonly opened = model(false);
37
+ /** The record to edit, or `null` to create one. */
38
+ readonly value = input<__Name__ | null>(null);
39
+ /** True while the parent saves: Save shows a loader and is disabled. */
40
+ readonly saving = input(false);
41
+ /** The valid form value, emitted on Save. */
42
+ readonly saved = output<__Name__Draft>();
43
+
44
+ readonly isEdit = computed(() => this.value() !== null);
45
+
46
+ readonly form = new FormGroup({
47
+ name: new FormControl('', { nonNullable: true, validators: [Validators.required, Validators.maxLength(80)] }),
48
+ description: new FormControl('', { nonNullable: true, validators: [Validators.maxLength(500)] }),
49
+ });
50
+
51
+ private readonly formRef = viewChild<ElementRef<HTMLFormElement>>('formRef');
52
+
53
+ /** Every time the dialog opens, the form starts from the record (or empty). */
54
+ private readonly resetOnOpen = effect(() => {
55
+ if (!this.opened()) return;
56
+ const value = this.value();
57
+ this.form.reset({ name: value?.name ?? '', description: value?.description ?? '' });
58
+ });
59
+
60
+ /** Validates on submit: marks every field and focuses the first invalid one. */
61
+ submit(): void {
62
+ if (this.form.invalid) {
63
+ this.form.markAllAsTouched();
64
+ this.formRef()?.nativeElement.querySelector<HTMLElement>('.ng-invalid input, .ng-invalid textarea')?.focus();
65
+ return;
66
+ }
67
+ this.saved.emit(this.form.getRawValue());
68
+ }
69
+
70
+ cancel(): void {
71
+ this.opened.set(false);
72
+ }
73
+ }
@@ -0,0 +1,251 @@
1
+ /**
2
+ * `sdk-tools add <recipe> [name]`: writes a composition recipe's template files into an app as
3
+ * local app-* code and merges its i18n keys. The recipes and their files are the ones the MCP
4
+ * get_recipe returns (src/mcp/recipes.mjs), so both describe the same thing.
5
+ *
6
+ * Nothing is overwritten: a target file that exists with other content is a conflict, and any
7
+ * conflict writes nothing (unless --force). Files a recipe shares with another one (the model,
8
+ * the store, the form dialog) keep an existing copy. Existing i18n values are never changed.
9
+ */
10
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
11
+ import { basename, dirname, join } from 'node:path';
12
+ import { NotFoundError } from '../mcp/catalog.mjs';
13
+ import { findRecipe, flattenKeys, loadRecipes, recipeI18n, recipePartFiles } from '../mcp/recipes.mjs';
14
+
15
+ /**
16
+ * @typedef {import('../types.js').Recipe} Recipe
17
+ * @typedef {import('../types.js').AddPlan} AddPlan
18
+ * @typedef {import('../types.js').AddFile} AddFile
19
+ * @typedef {import('../types.js').AddI18n} AddI18n
20
+ * @typedef {{ [key: string]: string | I18nTree }} I18nTree
21
+ */
22
+
23
+ export class AddUsageError extends Error {}
24
+
25
+ const NAME = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;
26
+ const DEFAULT_NAME = 'item';
27
+ const I18N_DIR = 'src/assets/i18n';
28
+ /** The route guard of the MFE templates; a feature routes file uses it when the app has it. */
29
+ const CONFIGURATION_GUARD = 'src/app/core/guards/configuration/configuration.guard.ts';
30
+
31
+ /** @param {string} kebab */
32
+ const pascal = (kebab) => kebab.replace(/(^|-)([a-z0-9])/g, (_, __, c) => c.toUpperCase());
33
+ /** @param {string} kebab */
34
+ const snake = (kebab) => kebab.replaceAll('-', '_');
35
+ /** @param {string} kebab */
36
+ const constant = (kebab) => snake(kebab).toUpperCase();
37
+
38
+ /**
39
+ * A routes file without the configurationGuard import and `canActivate` lines, for an app that has
40
+ * no such guard.
41
+ * @param {string} text
42
+ */
43
+ const withoutGuard = (text) =>
44
+ text
45
+ .split('\n')
46
+ .filter((line) => !line.includes('configurationGuard'))
47
+ .join('\n');
48
+
49
+ /**
50
+ * The recipes `add` can write (those with template parts), for `sdk-tools add` with no recipe.
51
+ * @param {string} [recipesDir]
52
+ */
53
+ export function listRecipes(recipesDir) {
54
+ return {
55
+ recipes: loadRecipes(recipesDir)
56
+ .filter((recipe) => recipe.files.length)
57
+ .map(({ id, title, summary, files }) => ({ id, title, summary, files: files.map((file) => file.path) })),
58
+ };
59
+ }
60
+
61
+ /**
62
+ * The i18n prefix of the app: its package name in snake case, as the templates derive it
63
+ * (`mfe-child-template` -> `mfe_child_template`).
64
+ * @param {string} root
65
+ */
66
+ function appNamespace(root) {
67
+ /** @type {{ name?: unknown }} */
68
+ let pkg = {};
69
+ try {
70
+ pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
71
+ } catch {
72
+ // handled below
73
+ }
74
+ if (typeof pkg.name !== 'string' || !pkg.name) throw new AddUsageError('package.json has no "name"; add derives the i18n prefix from it');
75
+ return snake(pkg.name.replace(/^@[^/]+\//, '')).replace(/[^A-Za-z0-9_]/g, '_');
76
+ }
77
+
78
+ /** Keys a JSON merge must never copy: they would reach the object prototype. */
79
+ const UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
80
+
81
+ /**
82
+ * Adds the keys of `from` that `into` lacks; returns how many were added and kept.
83
+ * @param {I18nTree} into
84
+ * @param {I18nTree} from
85
+ * @param {string} at
86
+ * @param {string[]} conflicts
87
+ */
88
+ function mergeMissing(into, from, at, conflicts) {
89
+ let added = 0;
90
+ let kept = 0;
91
+ for (const [key, value] of Object.entries(from)) {
92
+ if (UNSAFE_KEYS.has(key)) {
93
+ conflicts.push(`${at}${key}`);
94
+ continue;
95
+ }
96
+ const existing = Object.hasOwn(into, key) ? into[key] : undefined;
97
+ if (existing === undefined) {
98
+ into[key] = value;
99
+ added += typeof value === 'string' ? 1 : flattenKeys(value).length;
100
+ } else if (typeof value === 'string' || typeof existing === 'string') {
101
+ if (typeof value !== typeof existing) conflicts.push(`${at}${key}`);
102
+ else kept += 1;
103
+ } else {
104
+ const counts = mergeMissing(existing, value, `${at}${key}.`, conflicts);
105
+ added += counts.added;
106
+ kept += counts.kept;
107
+ }
108
+ }
109
+ return { added, kept };
110
+ }
111
+
112
+ /**
113
+ * Serializes like the file it replaces: same indentation, or one line when it was one line.
114
+ * @param {unknown} value
115
+ * @param {string} original
116
+ */
117
+ function stringifyLike(value, original) {
118
+ const indent = /\n([ \t]+)"/.exec(original)?.[1];
119
+ const text = indent ? JSON.stringify(value, null, indent) : JSON.stringify(value);
120
+ return original.endsWith('\n') ? `${text}\n` : text;
121
+ }
122
+
123
+ /**
124
+ * Plans (and unless dryRun or blocked, writes) one recipe into the app at `cwd`.
125
+ * @param {{ cwd: string, recipe: string, name?: string, dryRun?: boolean, force?: boolean, recipesDir?: string }} options
126
+ * @returns {AddPlan}
127
+ */
128
+ export function add({ cwd, recipe: recipeId, name = DEFAULT_NAME, dryRun = false, force = false, recipesDir }) {
129
+ const recipes = loadRecipes(recipesDir);
130
+ /** @type {Recipe} */
131
+ let recipe;
132
+ try {
133
+ recipe = findRecipe(recipes, recipeId);
134
+ } catch (error) {
135
+ if (error instanceof NotFoundError) throw new AddUsageError(error.message);
136
+ throw error;
137
+ }
138
+ if (!recipe.files.length) throw new AddUsageError(`recipe "${recipe.id}" has no files to add; read it with get_recipe and follow its steps`);
139
+ if (!NAME.test(name))
140
+ throw new AddUsageError(`name "${name}" must be kebab-case: lowercase letters and digits, words joined by "-" (for example price-list)`);
141
+ if (!existsSync(join(cwd, 'angular.json'))) throw new AddUsageError('run add in the app folder (the one with angular.json)');
142
+
143
+ const namespace = appNamespace(cwd);
144
+ const prefix = `${namespace}.${snake(name)}`;
145
+ /** @param {string} text */
146
+ const render = (text) =>
147
+ text.replaceAll('__NAME__', constant(name)).replaceAll('__Name__', pascal(name)).replaceAll('__name__', name).replaceAll('__i18n__', prefix);
148
+ const hasGuard = existsSync(join(cwd, CONFIGURATION_GUARD));
149
+
150
+ /** @type {AddFile[]} */
151
+ const files = [];
152
+ /** @type {Map<string, string>} */
153
+ const contents = new Map();
154
+ for (const file of recipePartFiles(recipe, recipesDir)) {
155
+ const path = render(file.target);
156
+ const rendered = render(readFileSync(file.template, 'utf8'));
157
+ const content = path.endsWith('.routes.ts') && !hasGuard ? withoutGuard(rendered) : rendered;
158
+ const absolute = join(cwd, path);
159
+ /** @type {AddFile['action']} */
160
+ let action = 'create';
161
+ if (existsSync(absolute)) {
162
+ const current = readFileSync(absolute, 'utf8');
163
+ action = current === content ? 'unchanged' : file.shared ? 'kept' : force ? 'overwrite' : 'conflict';
164
+ }
165
+ files.push({ path, action, shared: file.shared });
166
+ if (action === 'create' || action === 'overwrite') contents.set(path, content);
167
+ }
168
+
169
+ const bundles = recipeI18n(recipe, recipesDir);
170
+ /** @type {AddI18n[]} */
171
+ const i18n = [];
172
+ /** @type {Map<string, string>} */
173
+ const i18nWrites = new Map();
174
+ /** @type {string[]} */
175
+ const warnings = [];
176
+ const i18nDir = join(cwd, I18N_DIR);
177
+ const languageFiles = existsSync(i18nDir) ? readdirSync(i18nDir).filter((file) => /^[a-z]{2}(-[A-Z]{2})?\.json$/.test(file)) : [];
178
+ if (!languageFiles.length) warnings.push(`no ${I18N_DIR}/<lang>.json files: add the ${prefix}.* keys yourself`);
179
+ for (const file of languageFiles.sort()) {
180
+ const path = `${I18N_DIR}/${file}`;
181
+ const language = basename(file, '.json').split('-')[0];
182
+ const tree = bundles[language] ?? bundles.en;
183
+ if (!language || !tree) continue;
184
+ const original = readFileSync(join(cwd, path), 'utf8');
185
+ /** @type {I18nTree} */
186
+ let bundle;
187
+ try {
188
+ bundle = JSON.parse(original);
189
+ } catch {
190
+ i18n.push({ path, added: 0, kept: 0, conflicts: ['(the file is not valid JSON)'] });
191
+ continue;
192
+ }
193
+ if (!bundles[language]) warnings.push(`${path}: the recipe has no ${language} text; added the English values`);
194
+ /** @type {string[]} */
195
+ const conflicts = [];
196
+ const counts = mergeMissing(bundle, { [namespace]: { [snake(name)]: tree } }, '', conflicts);
197
+ i18n.push({ path, ...counts, conflicts });
198
+ if (counts.added) i18nWrites.set(path, stringifyLike(bundle, original));
199
+ }
200
+
201
+ const blocked = files.some((file) => file.action === 'conflict') || i18n.some((entry) => entry.conflicts.length > 0);
202
+ const written = !dryRun && !blocked;
203
+ if (written) {
204
+ for (const [path, content] of [...contents, ...i18nWrites]) {
205
+ mkdirSync(dirname(join(cwd, path)), { recursive: true });
206
+ writeFileSync(join(cwd, path), content);
207
+ }
208
+ }
209
+
210
+ const Name = pascal(name);
211
+ const routes = files.find((file) => file.path.endsWith('.routes.ts'));
212
+ if (routes && !hasGuard) warnings.push(`no ${CONFIGURATION_GUARD}: ${routes.path} has no canActivate guard`);
213
+ /** @type {string[]} */
214
+ const next = [];
215
+ if (routes) next.push(`spread ${constant(name)}_ROUTES from ${routes.path} into the app's feature routes`);
216
+ else if (recipe.parts.includes('detail-page'))
217
+ next.push(`register the detail page in the feature's ${name}.routes.ts: { path: '${name}/:id', component: ${Name}DetailComponent }`);
218
+ if (recipe.id === 'form-dialog') next.push(`open <app-${name}-form-dialog [(opened)]="…" [value]="…" (saved)="…" /> from a page`);
219
+ next.push(`rename "record" in the ${prefix}.* i18n values to your entity`);
220
+ next.push(`replace the in-memory store in ${name}.service.ts with your backend calls`);
221
+ next.push(`npx prettier --write src/app/features/${name} ${I18N_DIR}`);
222
+ next.push(`npx @sixbell-telco/sdk-tools check src/app/features/${name}`);
223
+
224
+ return { recipe: recipe.id, name, i18nPrefix: prefix, dryRun, force, written, blocked, files, i18n, warnings, next };
225
+ }
226
+
227
+ /**
228
+ * @param {AddPlan} plan
229
+ * @returns {string}
230
+ */
231
+ export function formatAdd(plan) {
232
+ const verb = { create: 'create', overwrite: 'overwrite', unchanged: 'same', kept: 'keep', conflict: 'EXISTS' };
233
+ const lines = [`sdk-tools add ${plan.recipe} ${plan.name}${plan.dryRun ? ' (dry run: nothing written)' : ''}`, ''];
234
+ for (const file of plan.files) lines.push(` ${verb[file.action].padEnd(9)} ${file.path}`);
235
+ for (const entry of plan.i18n) {
236
+ lines.push(` ${'i18n'.padEnd(9)} ${entry.path}: ${entry.added} added, ${entry.kept} kept (${plan.i18nPrefix}.*)`);
237
+ for (const key of entry.conflicts)
238
+ lines.push(` ${'EXISTS'.padEnd(9)} ${entry.path}: ${key} has another shape (a text where the recipe needs a group, or the reverse)`);
239
+ }
240
+ for (const warning of plan.warnings) lines.push(` warning ${warning}`);
241
+ lines.push('');
242
+ if (plan.blocked) {
243
+ lines.push(
244
+ 'Nothing written: the entries marked EXISTS are in the way. Move them or pick another name; --force overwrites files, never i18n keys.',
245
+ );
246
+ } else {
247
+ if (plan.written) lines.push('Done.');
248
+ lines.push('Next:', ...plan.next.map((step) => ` - ${step}`));
249
+ }
250
+ return lines.join('\n');
251
+ }
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Config step: package.json scripts against angular.json targets, the test target, and the JSON
3
+ * files the other steps read.
4
+ * Ids: MFE_PROJECT_SCRIPT_001, MFE_PROJECT_TEST_001, MFE_SHOWCASE_001, MFE_JSON_001.
5
+ */
6
+ import { existsSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+
9
+ import { readText, walk } from '../project/project.mjs';
10
+ import { finding } from './finding.mjs';
11
+
12
+ /**
13
+ * @typedef {import('../types.js').Finding} Finding
14
+ * @typedef {import('../types.js').ProjectInfo} ProjectInfo
15
+ */
16
+
17
+ /**
18
+ * @param {ProjectInfo} project
19
+ * @returns {Finding[]}
20
+ */
21
+ function scripts(project) {
22
+ const { root, angular, packageJson } = project;
23
+ /** @type {Finding[]} */
24
+ const findings = [];
25
+ const scriptsMap = packageJson?.scripts ?? {};
26
+ const projectName = angular?.defaultProject;
27
+ for (const [name, command] of Object.entries(scriptsMap)) {
28
+ if (typeof command !== 'string') continue;
29
+ for (const [, configuration] of command.matchAll(/--configuration[= ]+([\w:,-]+)/g)) {
30
+ const target = /\bng\s+serve\b/.test(command) ? 'serve' : 'build';
31
+ const targetConfig = projectName ? angular?.projects[projectName]?.targets[target] : undefined;
32
+ const known = configuration.split(',').every((part) => targetConfig?.configurations?.[part] || targetConfig?.defaultConfiguration === part);
33
+ if (!known)
34
+ findings.push(
35
+ finding(
36
+ 'MFE_PROJECT_SCRIPT_001',
37
+ 'package.json',
38
+ `Script "${name}" uses Angular ${target} configuration "${configuration}", which angular.json does not define.`,
39
+ ),
40
+ );
41
+ }
42
+ for (const [, file] of command.matchAll(/\bnode\s+([^\s;&|]+\.[cm]?js)\b/g)) {
43
+ const path = file.replace(/^['"]|['"]$/g, '').replace(/^\.\//, '');
44
+ // write-stylesheet-href.mjs is MFE_CHILD_005's.
45
+ if (!path.endsWith('write-stylesheet-href.mjs') && !existsSync(join(root, path)))
46
+ findings.push(finding('MFE_PROJECT_SCRIPT_001', 'package.json', `Script "${name}" runs ${path}, which does not exist.`));
47
+ }
48
+ }
49
+ if (Object.values(scriptsMap).filter((command) => typeof command === 'string' && command.includes('write-stylesheet-href')).length > 1)
50
+ findings.push(finding('MFE_PROJECT_SCRIPT_001', 'package.json', 'write-stylesheet-href.mjs must run exactly once across the npm scripts.'));
51
+ if (project.role) {
52
+ if (!scriptsMap['start:showcase'])
53
+ findings.push(
54
+ finding('MFE_SHOWCASE_001', 'package.json', 'Missing npm script "start:showcase" (the template serves the showcase configuration with it).'),
55
+ );
56
+ }
57
+ for (const [name, ngProject] of Object.entries(angular?.projects ?? {})) {
58
+ const test = ngProject.targets.test;
59
+ if (!test) continue;
60
+ const builderPackage = test.builder?.split(':')[0] ?? '';
61
+ const installed =
62
+ builderPackage &&
63
+ (existsSync(join(root, 'node_modules', builderPackage)) ||
64
+ Boolean(packageJson?.devDependencies?.[builderPackage] ?? packageJson?.dependencies?.[builderPackage]));
65
+ const configPath = test.options?.configPath ?? test.options?.jestConfig;
66
+ const configOk = typeof configPath !== 'string' || existsSync(join(root, configPath));
67
+ if (!installed || !configOk)
68
+ findings.push(
69
+ finding(
70
+ 'MFE_PROJECT_TEST_001',
71
+ 'angular.json',
72
+ `The test target of "${name}" uses ${!installed ? `builder ${test.builder ?? '(none)'}, which is not installed` : `config ${configPath}, which does not exist`}.`,
73
+ ),
74
+ );
75
+ }
76
+ return findings;
77
+ }
78
+
79
+ /**
80
+ * MFE_JSON_001: the JSON files the project steps read must parse.
81
+ * @param {ProjectInfo} project
82
+ * @returns {Finding[]}
83
+ */
84
+ function json(project) {
85
+ const { root } = project;
86
+ const files = [
87
+ 'package.json',
88
+ 'angular.json',
89
+ 'mfe-foundation.config.json',
90
+ ...walk(root, 'src/assets', (file) => file.endsWith('.json') && !file.startsWith('src/assets/themes/assets/')),
91
+ ];
92
+ /** @type {Finding[]} */
93
+ const findings = [];
94
+ for (const file of files) {
95
+ const text = readText(root, file);
96
+ if (text === null) continue;
97
+ try {
98
+ JSON.parse(text);
99
+ } catch (error) {
100
+ findings.push(finding('MFE_JSON_001', file, `Invalid JSON: ${/** @type {Error} */ (error).message}`));
101
+ }
102
+ }
103
+ return findings;
104
+ }
105
+
106
+ /**
107
+ * @param {ProjectInfo} project
108
+ * @returns {Finding[]}
109
+ */
110
+ export function configStep(project) {
111
+ return [...scripts(project), ...json(project)];
112
+ }