semmet-angular 0.27.0 → 0.29.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.
@@ -0,0 +1,267 @@
1
+ # semmet-angular
2
+
3
+ **Kit de entrega de UI acessível para Angular.**
4
+
5
+ `semmet-angular` é uma coleção de schematics focada em entrega para times Angular que querem publicar interfaces acessíveis mais rápido: componentes com comportamento ARIA real, identidade visual consistente e arquivos de teste gerados desde o primeiro comando.
6
+
7
+ Semmet Angular ajuda times a gerar, testar, verificar e empacotar UI acessível usando o ecossistema do Angular CLI.
8
+
9
+ **Gerar. Testar. Verificar. Empacotar.**
10
+
11
+ Leia a direção geral do produto em [PRODUCT_VISION.md](./PRODUCT_VISION.md).
12
+
13
+ `ng generate semmet-angular:accordion minha-faq` cria um componente Angular standalone baseado em signals — `.ts`/`.html`/`.css` — junto com testes `.spec.ts` e `.e2e-spec.ts`. O componente gerado implementa de verdade um padrão do W3C ARIA Authoring Practices Guide: roles corretos, ligação de atributos `aria-*`, comportamento de teclado/foco exigido pelo padrão (navegação por setas, focus trap, restauração de foco...) e uma identidade visual consistente logo de saída.
14
+
15
+ ## Uso
16
+
17
+ ```bash
18
+ ng add semmet-angular
19
+ ng generate semmet-angular:accordion minha-faq
20
+ ng generate semmet-angular:ci
21
+ ```
22
+
23
+ `ng add semmet-angular` instala o pacote e configura uma vez o fluxo de entrega da aplicação alvo, incluindo suporte a e2e com Playwright e scripts npm. Cada componente gerado entra no seu projeto do mesmo jeito que entraria com `ng generate component` (respeitando `angular.json`, `sourceRoot` e prefixo de seletor), e tem **zero dependência em tempo de execução** deste pacote — `semmet-angular` só é necessário na geração.
24
+
25
+ ## Fluxo de Entrega
26
+
27
+ Depois de rodar `ng add semmet-angular`, use:
28
+
29
+ ```bash
30
+ npm test
31
+ npm run e2e
32
+ npm run e2e:ui
33
+ npm run verify
34
+ ```
35
+
36
+ `npm run e2e` executa o Playwright contra o servidor de desenvolvimento Angular configurado por `playwright.config.ts`; `npm run e2e:ui` abre a interface interativa do Playwright.
37
+
38
+ O script `npm run verify` é criado sem sobrescrever um script `verify` existente. Quando os scripts estão disponíveis no `package.json` da aplicação, ele compõe um fluxo simples com:
39
+
40
+ ```bash
41
+ npm test -- --watch=false
42
+ npm run e2e
43
+ npm run build
44
+ npm run lint
45
+ ```
46
+
47
+ `lint` só entra quando a aplicação já tem um script `lint`; `build` e `test` seguem a mesma lógica. O `e2e` entra depois da configuração do Playwright feita pelo `ng add`.
48
+
49
+ ## CI com GitHub Actions
50
+
51
+ ```bash
52
+ ng generate semmet-angular:ci
53
+ ```
54
+
55
+ Esse comando gera `.github/workflows/ci.yml` usando os scripts já existentes no `package.json`. O workflow detecta o gerenciador de pacotes por lockfile (`package-lock.json`, `pnpm-lock.yaml` ou `yarn.lock`), instala dependências e executa `verify` quando disponível. Se `verify` ainda não existir, ele roda `build`, `test` e `e2e` conforme esses scripts existirem.
56
+
57
+ Por padrão, o schematic não sobrescreve um workflow existente. Use `--force` quando quiser substituir `.github/workflows/ci.yml`.
58
+
59
+ ## Testes Gerados
60
+
61
+ Todo schematic de componente gera arquivos de teste ao lado do componente:
62
+
63
+ ```text
64
+ minha-faq.ts
65
+ minha-faq.html
66
+ minha-faq.css
67
+ minha-faq.spec.ts
68
+ minha-faq.e2e-spec.ts
69
+ ```
70
+
71
+ O teste unitário usa o `TestBed` do Angular para verificar o componente pelo seletor público. Componentes interativos também geram testes focados em comportamento: estado ARIA, fluxo de teclado, mudanças de valor, gerenciamento de foco e abertura/fechamento. O teste e2e usa Playwright e passa a valer assim que o componente estiver montado em uma rota ou componente host. Se o componente ainda não estiver em nenhuma página renderizada, o smoke test e2e gerado é pulado com uma mensagem clara, sem quebrar a suíte inteira.
72
+
73
+ ## Containers com Conteúdo Projetado
74
+
75
+ Alguns componentes gerados são containers: eles cuidam da ligação ARIA, comportamento de teclado, gerenciamento de foco e casca visual, enquanto a sua aplicação controla o conteúdo renderizado dentro deles.
76
+
77
+ `accordion`, `tabs`, `carousel`, `disclosure`, `card`, `button`, `badge`, `navbar`, `table` e `button-group` usam o padrão moderno de projeção do Angular com `ng-template`, signal queries e `NgTemplateOutlet`. Isso permite colocar componentes reais da aplicação dentro dos componentes gerados sem factories de componente dinâmico.
78
+
79
+ Exemplo depois de gerar `faq`:
80
+
81
+ ```ts
82
+ import { Component, signal } from '@angular/core';
83
+ import { Faq, FaqItem } from './faq/faq';
84
+ import { ProfilePanel } from './profile-panel/profile-panel';
85
+ import { SettingsPanel } from './settings-panel/settings-panel';
86
+
87
+ @Component({
88
+ selector: 'app-root',
89
+ imports: [Faq, FaqItem, ProfilePanel, SettingsPanel],
90
+ templateUrl: './app.html',
91
+ })
92
+ export class App {
93
+ readonly userId = signal(123);
94
+
95
+ reload(): void {}
96
+ }
97
+ ```
98
+
99
+ ```html
100
+ <app-faq>
101
+ <ng-template faqItem id="profile" title="Perfil" [expanded]="true">
102
+ <app-profile-panel />
103
+ </ng-template>
104
+
105
+ <ng-template faqItem id="settings" title="Configurações">
106
+ <app-settings-panel [userId]="userId()" (saved)="reload()" />
107
+ </ng-template>
108
+ </app-faq>
109
+ ```
110
+
111
+ O mesmo padrão vale para `tabs`, `carousel` e `disclosure`:
112
+
113
+ ```html
114
+ <app-settings-tabs>
115
+ <ng-template settingsTabsItem id="profile" label="Perfil" [selected]="true">
116
+ <app-profile-panel />
117
+ </ng-template>
118
+ </app-settings-tabs>
119
+
120
+ <app-featured-carousel>
121
+ <ng-template featuredCarouselSlide id="intro" label="Introdução">
122
+ <app-intro-slide />
123
+ </ng-template>
124
+ </app-featured-carousel>
125
+
126
+ <app-details label="Mostrar detalhes do perfil" [(expanded)]="profileDetailsOpen">
127
+ <ng-template detailsContent>
128
+ <app-profile-details [userId]="userId()" />
129
+ </ng-template>
130
+ </app-details>
131
+ ```
132
+
133
+ Por padrão, o conteúdo projetado de painel/slide é preservado depois da primeira renderização. Use `[preserveContent]="false"` no container gerado para destruir conteúdo inativo quando ele fechar ou ficar inativo.
134
+
135
+ Os schematics estruturais menores mantêm APIs simples por input e adicionam slots seguros onde o componente gerado continua dono da estrutura acessível:
136
+
137
+ ```html
138
+ <app-product-card title="Componentes acessíveis">
139
+ <ng-template productCardMedia>
140
+ <img src="/assets/card.png" alt="Prévia de componente Angular gerado" />
141
+ </ng-template>
142
+
143
+ <ng-template productCardDescription>
144
+ Gere componentes Angular com ARIA, comportamento de teclado e signals.
145
+ </ng-template>
146
+
147
+ <ng-template productCardActions>
148
+ <a href="/docs">Ler docs</a>
149
+ </ng-template>
150
+ </app-product-card>
151
+
152
+ <app-save-button label="Salvar">
153
+ <ng-template saveButtonLeading>
154
+ <app-save-icon aria-hidden="true" />
155
+ </ng-template>
156
+ </app-save-button>
157
+
158
+ <app-status-badge accessibleLabel="Build passou">
159
+ <ng-template statusBadgeLabel>Passou</ng-template>
160
+ </app-status-badge>
161
+
162
+ <app-main-navbar brand="Acme">
163
+ <ng-template mainNavbarActions>
164
+ <a href="/conta">Conta</a>
165
+ </ng-template>
166
+ </app-main-navbar>
167
+
168
+ <app-results-table caption="Receita trimestral" [rows]="results">
169
+ <ng-template resultsTableEmpty>Nenhum resultado de receita ainda.</ng-template>
170
+ </app-results-table>
171
+
172
+ <app-view-switcher [items]="views">
173
+ <ng-template viewSwitcherItem let-item>
174
+ {{ item.label }}
175
+ </ng-template>
176
+ </app-view-switcher>
177
+ ```
178
+
179
+ ## Schematics (43)
180
+
181
+ **Overlays e disclosure**
182
+
183
+ | Comando | Gera | Comportamento de teclado/foco implementado |
184
+ |---|---|---|
185
+ | `ng generate semmet-angular:accordion <nome>` | [Accordion](https://www.w3.org/WAI/ARIA/apg/patterns/accordion/) | Clique/Enter/Espaço alterna; Cima/Baixo/Home/End move foco entre cabeçalhos |
186
+ | `ng generate semmet-angular:disclosure <nome>` | [Disclosure](https://www.w3.org/WAI/ARIA/apg/patterns/disclosure/) | Clique/Enter/Espaço alterna |
187
+ | `ng generate semmet-angular:dialog <nome>` | [Dialog (Modal)](https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/) | Foco entra ao abrir; Tab/Shift+Tab prende o foco; Escape fecha; foco volta para o acionador |
188
+ | `ng generate semmet-angular:alert-dialog <nome>` | [Alert Dialog](https://www.w3.org/WAI/ARIA/apg/patterns/alertdialog/) | Mesmo focus trap do Dialog; foco inicial na ação menos destrutiva (Cancelar) |
189
+ | `ng generate semmet-angular:offcanvas <nome>` | Offcanvas / Drawer | Semântica de dialog modal; foco entra; Tab/Shift+Tab prende o foco; Escape/backdrop fecha; foco volta para o acionador |
190
+ | `ng generate semmet-angular:popover <nome>` | Popover | Acionador disclosure com `aria-haspopup="dialog"`; Escape fecha; clique externo dispensa |
191
+ | `ng generate semmet-angular:tooltip <nome>` | [Tooltip](https://www.w3.org/WAI/ARIA/apg/patterns/tooltip/) | Aparece no hover **e** no foco; esconde no blur/mouseleave/Escape |
192
+ | `ng generate semmet-angular:menu-button <nome>` | [Menu Button](https://www.w3.org/WAI/ARIA/apg/patterns/menu-button/) | Cima/Baixo/Home/End/Escape dentro do menu; fecha em clique externo; foco volta para o acionador |
193
+ | `ng generate semmet-angular:button <nome>` | Button | `<button>` nativo com variante, tamanho, desabilitado, ocupado, estado pressionado opcional e slots seguros de rótulo/ícone |
194
+ | `ng generate semmet-angular:button-group <nome>` | Button Group | Botões nativos agrupados com `role="group"`, estado toggle opcional com `aria-pressed` e projeção segura de rótulo por item |
195
+ | `ng generate semmet-angular:close-button <nome>` | Close Button | Botão de ícone nativo com rótulo acessível obrigatório |
196
+
197
+ **Navegação e estrutura**
198
+
199
+ | Comando | Gera | Comportamento de teclado/foco implementado |
200
+ |---|---|---|
201
+ | `ng generate semmet-angular:tabs <nome>` | [Tabs](https://www.w3.org/WAI/ARIA/apg/patterns/tabs/) | Ativação automática; Esquerda/Direita/Home/End com `tabindex` roving |
202
+ | `ng generate semmet-angular:breadcrumb <nome>` | [Breadcrumb](https://www.w3.org/WAI/ARIA/apg/patterns/breadcrumb/) | Estático — links simples + `aria-current="page"` |
203
+ | `ng generate semmet-angular:navigation-menu <nome>` | [Navigation Menu (Disclosure)](https://www.w3.org/WAI/ARIA/apg/patterns/disclosure/examples/disclosure-navigation/) | Clique/Enter/Espaço alterna submenu; evita `role="menu"` de propósito, reservado para menus de aplicação |
204
+ | `ng generate semmet-angular:navbar <nome>` | Navbar | Estrutura semântica `nav`/lista/link com toggle responsivo, `aria-current` e slots seguros de marca/ações |
205
+ | `ng generate semmet-angular:pagination <nome>` | Pagination | Estado de página funcional; Anterior/Próximo desabilitam nos limites |
206
+ | `ng generate semmet-angular:skip-link <nome>` | [Skip Link](https://www.w3.org/WAI/WCAG21/Techniques/general/G1) | Escondido até receber foco, conforme o padrão de skip link |
207
+ | `ng generate semmet-angular:landmarks <nome>` | [Landmarks (Page Skeleton)](https://www.w3.org/WAI/ARIA/apg/practices/landmark-regions/) | Wrapper de layout com projeção de conteúdo (`header`/`nav`/`main`/`aside`/`footer`) |
208
+ | `ng generate semmet-angular:tree-view <nome>` | [Tree View](https://www.w3.org/WAI/ARIA/apg/patterns/treeview/) | Cima/Baixo/Esquerda/Direita/Home/End/Enter com `tabindex` roving nos nós visíveis |
209
+ | `ng generate semmet-angular:toolbar <nome>` | [Toolbar](https://www.w3.org/WAI/ARIA/apg/patterns/toolbar/) | Esquerda/Direita/Home/End com `tabindex` roving |
210
+ | `ng generate semmet-angular:card <nome>` | Card | `<article>` semântico com heading/descrição/ações/mídia e slots seguros |
211
+ | `ng generate semmet-angular:list-group <nome>` | List Group | Estrutura semântica de lista com itens de ação, estado ativo, badges opcionais e estados desabilitados |
212
+ | `ng generate semmet-angular:table <nome>` | [Table](https://www.w3.org/WAI/ARIA/apg/patterns/table/) | Caption + cabeçalhos escopados, linhas por input e slots seguros de caption/estado vazio |
213
+
214
+ **Formulários e inputs**
215
+
216
+ | Comando | Gera | Comportamento de teclado/foco implementado |
217
+ |---|---|---|
218
+ | `ng generate semmet-angular:form <nome>` | Form | `<form>` nativo com controles rotulados, validação inline e mensagens de status |
219
+ | `ng generate semmet-angular:input <nome>` | Input | `<input>` nativo com label, dica, mensagem de validação e valor com signal |
220
+ | `ng generate semmet-angular:select <nome>` | Select | `<select>` nativo com label, dica, mensagem de validação e valor com signal |
221
+ | `ng generate semmet-angular:input-group <nome>` | Input Group | `<input>` nativo com prefixo/sufixo anunciados por `aria-describedby` e botão de ação opcional |
222
+ | `ng generate semmet-angular:textarea <nome>` | Textarea | `<textarea>` nativo com label, dica, contador, mensagem de validação e valor com signal |
223
+ | `ng generate semmet-angular:checkbox <nome>` | [Checkbox](https://www.w3.org/WAI/ARIA/apg/patterns/checkbox/) | Clique/Enter/Espaço alterna |
224
+ | `ng generate semmet-angular:radio-group <nome>` | [Radio Group](https://www.w3.org/WAI/ARIA/apg/patterns/radio/) | Cima/Baixo/Esquerda/Direita/Home/End movem foco e seleção juntos |
225
+ | `ng generate semmet-angular:switch <nome>` | [Switch](https://www.w3.org/WAI/ARIA/apg/patterns/switch/) | `<button>` nativo — Clique/Enter/Espaço alterna |
226
+ | `ng generate semmet-angular:combobox <nome>` | [Combobox](https://www.w3.org/WAI/ARIA/apg/patterns/combobox/) | Filtro em tempo real; Cima/Baixo/Home/End/Enter/Escape via `aria-activedescendant` |
227
+ | `ng generate semmet-angular:listbox <nome>` | [Listbox](https://www.w3.org/WAI/ARIA/apg/patterns/listbox/) | Cima/Baixo/Home/End via `aria-activedescendant` |
228
+ | `ng generate semmet-angular:slider <nome>` | [Slider](https://www.w3.org/WAI/ARIA/apg/patterns/slider/) | Setas/PageUp/PageDown/Home/End, além de arraste por ponteiro |
229
+ | `ng generate semmet-angular:spinbutton <nome>` | [Spinbutton](https://www.w3.org/WAI/ARIA/apg/patterns/spinbutton/) | Cima/Baixo/Home/End, além de botões incrementar/decrementar |
230
+ | `ng generate semmet-angular:meter <nome>` | [Meter](https://www.w3.org/TR/wai-aria-1.2/#meter) | Estático — `<meter>` nativo ligado a um signal |
231
+ | `ng generate semmet-angular:progress-bar <nome>` | [Progress Bar](https://www.w3.org/TR/wai-aria-1.2/#progressbar) | `<progress>` nativo ligado a um signal |
232
+
233
+ **Feedback e mídia**
234
+
235
+ | Comando | Gera | Comportamento de teclado/foco implementado |
236
+ |---|---|---|
237
+ | `ng generate semmet-angular:alert <nome>` | [Alert](https://www.w3.org/WAI/ARIA/apg/patterns/alert/) | Região live assertiva e dispensável |
238
+ | `ng generate semmet-angular:toast <nome>` | Toast / Notification | Auto-dismiss após 5s (limpo via `DestroyRef`); pode ser dispensado antes |
239
+ | `ng generate semmet-angular:skeleton <nome>` | Skeleton Loading | Placeholder de carregamento composível para texto, mídia, círculos, cards e blocos customizados |
240
+ | `ng generate semmet-angular:badge <nome>` | Badge | Rótulo/contador compacto com modo decorativo, rótulo acessível opcional e projeção segura de label |
241
+ | `ng generate semmet-angular:spinner <nome>` | Spinner | Status de carregamento com `role="status"`, rótulo visualmente escondido por padrão e suporte a reduced motion |
242
+ | `ng generate semmet-angular:carousel <nome>` | [Carousel](https://www.w3.org/WAI/ARIA/apg/patterns/carousel/) | Controles Anterior/Próximo; região de slide com `aria-live="polite"` |
243
+
244
+ ## Como Cada Componente Gerado É
245
+
246
+ - Standalone (implícito — sem `standalone: true`, alinhado ao padrão atual do Angular).
247
+ - Estado via `signal()`/`computed()`, não campos simples de classe.
248
+ - Templates usam o control flow embutido (`@for`, `@if`), não `*ngFor`/`*ngIf`.
249
+ - Sem sufixo `.component` nos nomes de arquivos ou classes (`accordion.ts`, `export class Accordion`), seguindo a convenção atual de `ng generate component`.
250
+ - Id único por instância (`<nome>-0`, `<nome>-1`, ...) para múltiplas instâncias do mesmo componente nunca colidirem em `id`/`aria-controls`/`aria-labelledby`.
251
+ - Teste unitário (`.spec.ts`) e smoke test e2e Playwright (`.e2e-spec.ts`) gerados para o componente já nascer com uma superfície de teste.
252
+
253
+ ## Identidade Visual
254
+
255
+ Todo componente gerado compartilha um visual inspirado em Material Design — superfícies limpas, elevação sutil e escala consistente de raio/movimento — usando sua própria paleta de cores (não as cores do Material, para evitar qualquer risco de cópia visual). Os tokens são CSS custom properties declaradas no `:host` de cada componente (por exemplo, `--semmet-color-primary`, `--semmet-radius-md`, `--semmet-elevation-1`), então você pode usar os defaults como estão ou sobrescrever a família inteira em uma stylesheet global sem tocar nos arquivos gerados.
256
+
257
+ ## Opções
258
+
259
+ Todo schematic aceita as mesmas três opções de `ng generate component`:
260
+
261
+ - `name` (obrigatório, posicional) — nome do componente.
262
+ - `project` — projeto alvo; por padrão, usa o projeto atual/default.
263
+ - `path` — diretório alvo; por padrão, usa `src/app` do projeto.
264
+
265
+ ## Licença
266
+
267
+ MIT
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "semmet-angular",
3
- "version": "0.27.0",
3
+ "version": "0.29.0",
4
4
  "description": "Accessible UI Delivery Kit for Angular: schematics that generate ARIA-conformant standalone components with styling, keyboard behavior, unit tests, and Playwright e2e smoke tests.",
5
5
  "publisher": "danilodevsilva",
6
6
  "license": "MIT",
@@ -25,6 +25,8 @@
25
25
  },
26
26
  "schematics": "./src/collection.json",
27
27
  "files": [
28
+ "README.en.md",
29
+ "README.pt-BR.md",
28
30
  "src",
29
31
  "!src/**/*_spec.ts",
30
32
  "!src/**/*_spec.js",
@@ -0,0 +1,3 @@
1
+ import { Rule } from '@angular-devkit/schematics';
2
+ import { Schema } from './schema';
3
+ export declare function ci(options: Schema): Rule;
@@ -0,0 +1,117 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ci = ci;
4
+ const schematics_1 = require("@angular-devkit/schematics");
5
+ function ci(options) {
6
+ return (tree) => {
7
+ const workflowPath = buildWorkflowPath(options.name);
8
+ if (tree.exists(workflowPath) && !options.force) {
9
+ throw new schematics_1.SchematicsException(`${workflowPath} already exists. Re-run with --force to overwrite it.`);
10
+ }
11
+ const packageJson = readJson(tree, '/package.json');
12
+ const scripts = packageJson.scripts ?? {};
13
+ const packageManager = detectPackageManager(tree);
14
+ const workflow = buildWorkflow(packageManager, Object.keys(scripts), tree.exists('/package-lock.json'));
15
+ if (tree.exists(workflowPath)) {
16
+ tree.overwrite(workflowPath, workflow);
17
+ }
18
+ else {
19
+ tree.create(workflowPath, workflow);
20
+ }
21
+ };
22
+ }
23
+ function buildWorkflowPath(name = 'ci') {
24
+ const normalizedName = name.trim().replace(/\.ya?ml$/, '');
25
+ if (!normalizedName || normalizedName.includes('/') || normalizedName.includes('\\')) {
26
+ throw new schematics_1.SchematicsException('CI workflow name must be a file name without path separators.');
27
+ }
28
+ return `/.github/workflows/${normalizedName}.yml`;
29
+ }
30
+ function detectPackageManager(tree) {
31
+ if (tree.exists('/pnpm-lock.yaml')) {
32
+ return 'pnpm';
33
+ }
34
+ if (tree.exists('/yarn.lock')) {
35
+ return 'yarn';
36
+ }
37
+ return 'npm';
38
+ }
39
+ function buildWorkflow(packageManager, scriptNames, hasNpmLockfile) {
40
+ const commands = getPackageManagerCommands(packageManager, hasNpmLockfile);
41
+ const runSteps = buildRunSteps(commands, scriptNames);
42
+ const setupPackageManagerStep = commands.setupStep ? `${commands.setupStep}\n` : '';
43
+ const cacheConfig = commands.cache ? ` cache: ${commands.cache}\n` : '';
44
+ return `name: CI
45
+
46
+ on:
47
+ push:
48
+ branches: [main]
49
+ pull_request:
50
+
51
+ jobs:
52
+ verify:
53
+ runs-on: ubuntu-latest
54
+
55
+ steps:
56
+ - name: Checkout
57
+ uses: actions/checkout@v4
58
+
59
+ ${setupPackageManagerStep} - name: Setup Node
60
+ uses: actions/setup-node@v4
61
+ with:
62
+ node-version: 20
63
+ ${cacheConfig}
64
+
65
+ - name: Install dependencies
66
+ run: ${commands.install}
67
+ ${runSteps}
68
+ `;
69
+ }
70
+ function getPackageManagerCommands(packageManager, hasNpmLockfile) {
71
+ if (packageManager === 'pnpm') {
72
+ return {
73
+ install: 'pnpm install --frozen-lockfile',
74
+ run: (script) => `pnpm run ${script}`,
75
+ setupStep: ` - name: Setup pnpm
76
+ uses: pnpm/action-setup@v4
77
+ with:
78
+ version: 9`,
79
+ cache: 'pnpm',
80
+ };
81
+ }
82
+ if (packageManager === 'yarn') {
83
+ return {
84
+ install: 'yarn install --frozen-lockfile',
85
+ run: (script) => `yarn ${script}`,
86
+ cache: 'yarn',
87
+ };
88
+ }
89
+ return {
90
+ install: hasNpmLockfile ? 'npm ci' : 'npm install',
91
+ run: (script) => `npm run ${script}`,
92
+ cache: hasNpmLockfile ? 'npm' : undefined,
93
+ };
94
+ }
95
+ function buildRunSteps(commands, scriptNames) {
96
+ const scripts = new Set(scriptNames);
97
+ const verificationScripts = scripts.has('verify')
98
+ ? ['verify']
99
+ : ['build', 'test', 'e2e'].filter((script) => scripts.has(script));
100
+ if (verificationScripts.length === 0) {
101
+ return `
102
+ - name: Check package scripts
103
+ run: echo "No verify, build, test, or e2e script found in package.json."
104
+ `;
105
+ }
106
+ return verificationScripts
107
+ .map((script) => `
108
+ - name: Run ${script}
109
+ run: ${commands.run(script)}
110
+ `)
111
+ .join('');
112
+ }
113
+ function readJson(tree, path) {
114
+ const content = tree.readText(path);
115
+ return JSON.parse(content);
116
+ }
117
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":";;AAYA,gBAmBC;AA/BD,2DAA6E;AAY7E,SAAgB,EAAE,CAAC,OAAe;IAChC,OAAO,CAAC,IAAU,EAAE,EAAE;QACpB,MAAM,YAAY,GAAG,iBAAiB,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QAErD,IAAI,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;YAChD,MAAM,IAAI,gCAAmB,CAAC,GAAG,YAAY,uDAAuD,CAAC,CAAC;QACxG,CAAC;QAED,MAAM,WAAW,GAAG,QAAQ,CAAC,IAAI,EAAE,eAAe,CAAC,CAAC;QACpD,MAAM,OAAO,GAAG,WAAW,CAAC,OAAO,IAAI,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AW,CAAC,CAAC;IACrC,MAAM,mBAAmB,GAAG,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC;QAC/C,CAAC,CAAC,CAAC,QAAQ,CAAC;QACZ,CAAC,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC;IAErE,IAAI,mBAAmB,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACrC,OAAO;;;CAGV,CAAC;IACA,CAAC;IAED,OAAO,mBAAmB;SACvB,GAAG,CACF,CAAC,MAAM,EAAE,EAAE,CAAC;oBACE,MAAM;eACX,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC;CAClC,CACI;SACA,IAAI,CAAC,EAAE,CAAC,CAAC;AACd,CAAC;AAED,SAAS,QAAQ,CAAC,IAAU,EAAE,IAAY;IACxC,MAAM,OAAO,GAAG,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IACpC,OAAO,IAAI,CAAC,KAAK,CAAC,OAAO,CAAwB,CAAC;AACpD,CAAC"}
@@ -0,0 +1,143 @@
1
+ import { Rule, SchematicsException, Tree } from '@angular-devkit/schematics';
2
+ import { Schema } from './schema';
3
+
4
+ type PackageManager = 'npm' | 'pnpm' | 'yarn';
5
+
6
+ interface PackageManagerCommands {
7
+ install: string;
8
+ run: (script: string) => string;
9
+ setupStep?: string;
10
+ cache?: string;
11
+ }
12
+
13
+ export function ci(options: Schema): Rule {
14
+ return (tree: Tree) => {
15
+ const workflowPath = buildWorkflowPath(options.name);
16
+
17
+ if (tree.exists(workflowPath) && !options.force) {
18
+ throw new SchematicsException(`${workflowPath} already exists. Re-run with --force to overwrite it.`);
19
+ }
20
+
21
+ const packageJson = readJson(tree, '/package.json');
22
+ const scripts = packageJson.scripts ?? {};
23
+ const packageManager = detectPackageManager(tree);
24
+ const workflow = buildWorkflow(packageManager, Object.keys(scripts), tree.exists('/package-lock.json'));
25
+
26
+ if (tree.exists(workflowPath)) {
27
+ tree.overwrite(workflowPath, workflow);
28
+ } else {
29
+ tree.create(workflowPath, workflow);
30
+ }
31
+ };
32
+ }
33
+
34
+ function buildWorkflowPath(name = 'ci'): string {
35
+ const normalizedName = name.trim().replace(/\.ya?ml$/, '');
36
+
37
+ if (!normalizedName || normalizedName.includes('/') || normalizedName.includes('\\')) {
38
+ throw new SchematicsException('CI workflow name must be a file name without path separators.');
39
+ }
40
+
41
+ return `/.github/workflows/${normalizedName}.yml`;
42
+ }
43
+
44
+ function detectPackageManager(tree: Tree): PackageManager {
45
+ if (tree.exists('/pnpm-lock.yaml')) {
46
+ return 'pnpm';
47
+ }
48
+
49
+ if (tree.exists('/yarn.lock')) {
50
+ return 'yarn';
51
+ }
52
+
53
+ return 'npm';
54
+ }
55
+
56
+ function buildWorkflow(packageManager: PackageManager, scriptNames: string[], hasNpmLockfile: boolean): string {
57
+ const commands = getPackageManagerCommands(packageManager, hasNpmLockfile);
58
+ const runSteps = buildRunSteps(commands, scriptNames);
59
+ const setupPackageManagerStep = commands.setupStep ? `${commands.setupStep}\n` : '';
60
+ const cacheConfig = commands.cache ? ` cache: ${commands.cache}\n` : '';
61
+
62
+ return `name: CI
63
+
64
+ on:
65
+ push:
66
+ branches: [main]
67
+ pull_request:
68
+
69
+ jobs:
70
+ verify:
71
+ runs-on: ubuntu-latest
72
+
73
+ steps:
74
+ - name: Checkout
75
+ uses: actions/checkout@v4
76
+
77
+ ${setupPackageManagerStep} - name: Setup Node
78
+ uses: actions/setup-node@v4
79
+ with:
80
+ node-version: 20
81
+ ${cacheConfig}
82
+
83
+ - name: Install dependencies
84
+ run: ${commands.install}
85
+ ${runSteps}
86
+ `;
87
+ }
88
+
89
+ function getPackageManagerCommands(packageManager: PackageManager, hasNpmLockfile: boolean): PackageManagerCommands {
90
+ if (packageManager === 'pnpm') {
91
+ return {
92
+ install: 'pnpm install --frozen-lockfile',
93
+ run: (script) => `pnpm run ${script}`,
94
+ setupStep: ` - name: Setup pnpm
95
+ uses: pnpm/action-setup@v4
96
+ with:
97
+ version: 9`,
98
+ cache: 'pnpm',
99
+ };
100
+ }
101
+
102
+ if (packageManager === 'yarn') {
103
+ return {
104
+ install: 'yarn install --frozen-lockfile',
105
+ run: (script) => `yarn ${script}`,
106
+ cache: 'yarn',
107
+ };
108
+ }
109
+
110
+ return {
111
+ install: hasNpmLockfile ? 'npm ci' : 'npm install',
112
+ run: (script) => `npm run ${script}`,
113
+ cache: hasNpmLockfile ? 'npm' : undefined,
114
+ };
115
+ }
116
+
117
+ function buildRunSteps(commands: PackageManagerCommands, scriptNames: string[]): string {
118
+ const scripts = new Set(scriptNames);
119
+ const verificationScripts = scripts.has('verify')
120
+ ? ['verify']
121
+ : ['build', 'test', 'e2e'].filter((script) => scripts.has(script));
122
+
123
+ if (verificationScripts.length === 0) {
124
+ return `
125
+ - name: Check package scripts
126
+ run: echo "No verify, build, test, or e2e script found in package.json."
127
+ `;
128
+ }
129
+
130
+ return verificationScripts
131
+ .map(
132
+ (script) => `
133
+ - name: Run ${script}
134
+ run: ${commands.run(script)}
135
+ `
136
+ )
137
+ .join('');
138
+ }
139
+
140
+ function readJson(tree: Tree, path: string): Record<string, any> {
141
+ const content = tree.readText(path);
142
+ return JSON.parse(content) as Record<string, any>;
143
+ }
@@ -0,0 +1,4 @@
1
+ export interface Schema {
2
+ force?: boolean;
3
+ name?: string;
4
+ }
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=schema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.js","sourceRoot":"","sources":["schema.ts"],"names":[],"mappings":""}
@@ -0,0 +1,20 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema",
3
+ "$id": "SemmetAngularCi",
4
+ "title": "Semmet Angular CI Options Schema",
5
+ "type": "object",
6
+ "description": "Generates a GitHub Actions CI workflow using the target workspace package scripts.",
7
+ "additionalProperties": false,
8
+ "properties": {
9
+ "force": {
10
+ "type": "boolean",
11
+ "default": false,
12
+ "description": "Overwrite an existing CI workflow."
13
+ },
14
+ "name": {
15
+ "type": "string",
16
+ "default": "ci",
17
+ "description": "The workflow file name to create under .github/workflows."
18
+ }
19
+ }
20
+ }
@@ -0,0 +1,4 @@
1
+ export interface Schema {
2
+ force?: boolean;
3
+ name?: string;
4
+ }
@@ -6,6 +6,11 @@
6
6
  "factory": "./ng-add/index#ngAdd",
7
7
  "schema": "./ng-add/schema.json"
8
8
  },
9
+ "ci": {
10
+ "description": "Generates a GitHub Actions CI workflow using existing package scripts.",
11
+ "factory": "./ci/index#ci",
12
+ "schema": "./ci/schema.json"
13
+ },
9
14
  "accordion": {
10
15
  "description": "Generates a standalone Angular Accordion component following the W3C ARIA Authoring Practices Guide.",
11
16
  "factory": "./accordion/index#accordion",