@acropole/skills 0.0.0-stage → 1.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.
- package/README.md +181 -2
- package/agents/revisor-deploy.md +73 -0
- package/agents/revisor-documentacao.md +78 -0
- package/agents/revisor-orfeu.md +80 -0
- package/agents/revisor-trismegisto.md +81 -0
- package/bin/install.js +252 -0
- package/package.json +15 -4
- package/skills/acropole/SKILL.md +80 -0
- package/skills/acropole/references/arquitetura.md +174 -0
- package/skills/acropole/references/fluxos/app-novo.md +34 -0
- package/skills/acropole/references/fluxos/doctor.md +55 -0
- package/skills/acropole/references/fluxos/endpoint-novo.md +22 -0
- package/skills/acropole/references/fluxos/revisar.md +56 -0
- package/skills/acropole/references/fluxos/tela-nova.md +27 -0
- package/skills/acropole/scripts/doctor.mjs +439 -0
- package/skills/angular/SKILL.md +155 -0
- package/skills/angular/references/armadilhas.md +99 -0
- package/skills/angular/references/dados.md +251 -0
- package/skills/angular/references/estrutura.md +279 -0
- package/skills/angular/references/features.md +219 -0
- package/skills/angular/references/testes-build.md +257 -0
- package/skills/angular/scripts/checar.mjs +182 -0
- package/skills/angular/scripts/nucleo.mjs +227 -0
- package/skills/apollo/SKILL.md +226 -0
- package/skills/apollo/references/armadilhas.md +99 -0
- package/skills/apollo/references/envelope-erros.md +120 -0
- package/skills/apollo/references/estrutura-bootstrap.md +310 -0
- package/skills/apollo/references/schema-resolvers.md +183 -0
- package/skills/apollo/references/subscriptions.md +224 -0
- package/skills/apollo/references/testes-build.md +181 -0
- package/skills/apollo/scripts/checar.mjs +160 -0
- package/skills/apollo/scripts/nucleo.mjs +227 -0
- package/skills/docker/SKILL.md +102 -0
- package/skills/docker/references/modelos.md +251 -0
- package/skills/docker/references/porques.md +286 -0
- package/skills/documentacao/SKILL.md +146 -0
- package/skills/documentacao/references/checklist-coerencia.md +59 -0
- package/skills/documentacao/references/ligar-app-novo.md +107 -0
- package/skills/documentacao/references/modelo-especificacao.md +51 -0
- package/skills/documentacao/references/modelo-readme.md +75 -0
- package/skills/documentacao/scripts/checar.mjs +454 -0
- package/skills/documentacao/scripts/nucleo.mjs +227 -0
- package/skills/express/SKILL.md +156 -0
- package/skills/express/references/dados.md +180 -0
- package/skills/express/references/estrutura.md +157 -0
- package/skills/express/references/middlewares.md +227 -0
- package/skills/express/references/rotas-erros.md +286 -0
- package/skills/express/references/testes-deploy.md +154 -0
- package/skills/express/scripts/checar.mjs +115 -0
- package/skills/express/scripts/nucleo.mjs +227 -0
- package/skills/fastapi/SKILL.md +132 -0
- package/skills/fastapi/references/banco.md +197 -0
- package/skills/fastapi/references/estrutura.md +325 -0
- package/skills/fastapi/references/integracoes.md +145 -0
- package/skills/fastapi/references/rotas-erros.md +140 -0
- package/skills/fastapi/references/testes-deploy.md +190 -0
- package/skills/fastapi/scripts/checar.mjs +108 -0
- package/skills/fastapi/scripts/nucleo.mjs +227 -0
- package/skills/hefesto/SKILL.md +119 -0
- package/skills/hefesto/references/conceitos.md +131 -0
- package/skills/hefesto/references/diagnostico.md +70 -0
- package/skills/hefesto/references/fluxo.md +122 -0
- package/skills/hefesto/references/preparar-app.md +105 -0
- package/skills/orfeu/SKILL.md +162 -0
- package/skills/orfeu/references/angular-api.md +201 -0
- package/skills/orfeu/references/angular-armadilhas.md +116 -0
- package/skills/orfeu/references/angular-recipes.md +474 -0
- package/skills/orfeu/references/angular.md +212 -0
- package/skills/orfeu/references/diferencas.md +56 -0
- package/skills/orfeu/references/node-api.md +354 -0
- package/skills/orfeu/references/node-armadilhas.md +158 -0
- package/skills/orfeu/references/node-recipes.md +541 -0
- package/skills/orfeu/references/node.md +204 -0
- package/skills/orfeu/references/python-api.md +346 -0
- package/skills/orfeu/references/python-recipes.md +479 -0
- package/skills/orfeu/references/python.md +240 -0
- package/skills/orfeu/scripts/checar.mjs +126 -0
- package/skills/orfeu/scripts/nucleo.mjs +227 -0
- package/skills/trismegisto/SKILL.md +194 -0
- package/skills/trismegisto/references/angular-api.md +2788 -0
- package/skills/trismegisto/references/angular-exports.md +4020 -0
- package/skills/trismegisto/references/angular-recipes.md +1883 -0
- package/skills/trismegisto/references/angular-types.md +492 -0
- package/skills/trismegisto/references/angular.md +390 -0
- package/skills/trismegisto/references/catalogo/icones.json +912 -0
- package/skills/trismegisto/references/catalogo/seletores.json +7013 -0
- package/skills/trismegisto/references/catalogo/tokens.json +240 -0
- package/skills/trismegisto/references/spine-api.md +1530 -0
- package/skills/trismegisto/references/spine-recipes.md +581 -0
- package/skills/trismegisto/references/spine.md +343 -0
- package/skills/trismegisto/scripts/checar.mjs +216 -0
- package/skills/trismegisto/scripts/nucleo.mjs +227 -0
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
# Testes, lint, build e Docker
|
|
2
|
+
|
|
3
|
+
## Testes unitários
|
|
4
|
+
|
|
5
|
+
Os apps usam **Karma + Jasmine** pelo builder `@angular/build:karma` (`ng test` / `npm test`), com
|
|
6
|
+
`zone.js` e `zone.js/testing` nos polyfills do alvo `test` e `tsconfig.spec.json` incluindo
|
|
7
|
+
`src/**/*.spec.ts` com `types: ["jasmine"]`. Vitest ainda não é usado nos apps; não migre o runner
|
|
8
|
+
junto com uma feature.
|
|
9
|
+
|
|
10
|
+
Spec fica ao lado do arquivo (`pedidos.component.spec.ts`). Teste o que a tela promete (dado
|
|
11
|
+
renderizado, estado de erro, ação disparando a operação certa), não detalhe de implementação.
|
|
12
|
+
|
|
13
|
+
### Teste das rotas (`features.routes.spec.ts`)
|
|
14
|
+
|
|
15
|
+
Um spec por app confere o mapa de telas — é o que pega `import()` quebrado e `id` repetido, que o build
|
|
16
|
+
não pega (tela lazy só carrega em runtime):
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { reflectComponentType } from '@angular/core';
|
|
20
|
+
import { components } from 'src/app/features/features.routes';
|
|
21
|
+
|
|
22
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
23
|
+
|
|
24
|
+
describe('features.routes', () => {
|
|
25
|
+
it('ids são UUID e únicos (sem diferenciar maiúsculas)', () => {
|
|
26
|
+
const ids = components.map((c) => String(c.id).toLowerCase());
|
|
27
|
+
expect(new Set(ids).size).toBe(ids.length);
|
|
28
|
+
for (const id of ids) expect(id).toMatch(UUID);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it('todo load() resolve para um componente standalone', async () => {
|
|
32
|
+
for (const rota of components) {
|
|
33
|
+
const tipo = await rota.load!();
|
|
34
|
+
expect(reflectComponentType(tipo as any)?.isStandalone).withContext(String(rota.id)).toBeTrue();
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
});
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
- Formato de cada entrada: `load: () => import('...').then((m) => m.X)` (um chunk por tela); nada de
|
|
41
|
+
importar a classe estaticamente.
|
|
42
|
+
- Com `document`, confira também que `document.load()` devolve texto não vazio.
|
|
43
|
+
|
|
44
|
+
### Specs fixos do core (todo app tem)
|
|
45
|
+
|
|
46
|
+
| Spec | Confere |
|
|
47
|
+
| --- | --- |
|
|
48
|
+
| `src/core/app.config.spec.ts` | Monta os providers num `createEnvironmentInjector` filho do TestBed (sem bootstrap; filtra o `CORE_PROVIDERS[0]`, as animações) e lê os tokens: `SPINE_CONFIG` (clientId, appName, logo), `ROUTES` contém `APP_ROUTES`, `AUTH_CONFIG` = `environment.authorizationServer` e `AUTH_OPTIONS.eagerInit`, `AUTO_SERVICE_CONFIG`/`SPINE_ADMIN_API`, `COMPONENT_ROUTES` com as telas do app + `BASE_COMPONENTS`, `APP_PACKAGE_INFO` |
|
|
49
|
+
| `src/core/core.providers.spec.ts` | São três (animações, HttpClient, GraphQL); `ANIMATION_MODULE_TYPE` = `BrowserAnimations`; o HttpClient passa pelos interceptors do DI; um cliente Apollo por endpoint do environment (`PLATFORM_ID` = `server` para não abrir WebSocket) |
|
|
50
|
+
| `src/core/environments/environments.spec.ts` | Mesmas chaves nos cinco arquivos, só `prod` é `production`, `environment.ts` = `local`, client/realm iguais, URLs sem barra final |
|
|
51
|
+
| `src/core/core.component.spec.ts` | Título da aba |
|
|
52
|
+
| `src/app/features/features.routes.spec.ts` | Ids UUID únicos (sem diferenciar maiúsculas), todo `load()` standalone, documentação carregável |
|
|
53
|
+
|
|
54
|
+
Teste de initializer que mexe em login (`provideAppInitializer`): troque `AuthorizationService` e `Title`
|
|
55
|
+
por dublês no injetor, rode os `APP_INITIALIZER` com `runInInjectionContext` e confira o efeito — inclusive
|
|
56
|
+
quando o login falha (o título não pode depender do login).
|
|
57
|
+
|
|
58
|
+
### Componente que usa service GraphQL: Apollo falso
|
|
59
|
+
|
|
60
|
+
O `injectGraphqlClient` chama `apollo.use(nome).query(...)` e espera um Observable. Substitua o
|
|
61
|
+
`Apollo` inteiro e responda pelo **nome da operação**:
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
import { TestBed } from '@angular/core/testing';
|
|
65
|
+
import { provideNoopAnimations } from '@angular/platform-browser/animations';
|
|
66
|
+
import { provideRouter } from '@angular/router';
|
|
67
|
+
import { Apollo } from 'apollo-angular';
|
|
68
|
+
import { defer, of } from 'rxjs';
|
|
69
|
+
import { NotificationService } from '@trismegisto/spine/notification';
|
|
70
|
+
|
|
71
|
+
import { PedidosComponent } from 'src/app/features/pedidos/pedidos.component';
|
|
72
|
+
import { envelope, failure } from 'src/testing/graphql';
|
|
73
|
+
|
|
74
|
+
function fakeApollo(respostas: Record<string, unknown>) {
|
|
75
|
+
return {
|
|
76
|
+
use: () => ({
|
|
77
|
+
query: (opts: { query: any }) => defer(() => {
|
|
78
|
+
const nome = opts.query?.definitions?.[0]?.name?.value;
|
|
79
|
+
return Promise.resolve({ data: respostas[nome] ?? {} });
|
|
80
|
+
}),
|
|
81
|
+
mutate: () => defer(() => Promise.resolve({ data: {} })),
|
|
82
|
+
subscribe: () => of(),
|
|
83
|
+
}),
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function setup(respostas: Record<string, unknown>) {
|
|
88
|
+
TestBed.configureTestingModule({
|
|
89
|
+
imports: [PedidosComponent],
|
|
90
|
+
providers: [
|
|
91
|
+
provideRouter([]),
|
|
92
|
+
provideNoopAnimations(),
|
|
93
|
+
{ provide: Apollo, useValue: fakeApollo(respostas) },
|
|
94
|
+
{ provide: NotificationService, useValue: { addNotification: () => undefined } },
|
|
95
|
+
],
|
|
96
|
+
});
|
|
97
|
+
const fixture = TestBed.createComponent(PedidosComponent);
|
|
98
|
+
fixture.detectChanges();
|
|
99
|
+
await fixture.whenStable();
|
|
100
|
+
fixture.detectChanges();
|
|
101
|
+
return { fixture, cmp: fixture.componentInstance, el: fixture.nativeElement as HTMLElement };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
describe('PedidosComponent', () => {
|
|
105
|
+
it('lista os pedidos do envelope', async () => {
|
|
106
|
+
const { cmp } = await setup({ ListarPedidos: { pedidos: envelope([{ id: '1', numero: 'A-1' }]) } });
|
|
107
|
+
expect(cmp.itens().length).toBe(1);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
it('403 vira estado de erro, não lista vazia', async () => {
|
|
111
|
+
const { cmp } = await setup({ ListarPedidos: { pedidos: failure(403, 'Sem permissão') } });
|
|
112
|
+
expect(cmp.erro()).toBe('Sem permissão');
|
|
113
|
+
});
|
|
114
|
+
});
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Helper compartilhado em `src/testing/graphql.ts`:
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
import type { DocumentNode, OperationDefinitionNode } from 'graphql';
|
|
121
|
+
|
|
122
|
+
export const envelope = <T>(data: T, status = 200, message = '') => ({ status, message, data });
|
|
123
|
+
export const failure = (status: number, message: string) => ({ status, message, data: null });
|
|
124
|
+
|
|
125
|
+
const operation = (doc: DocumentNode): OperationDefinitionNode =>
|
|
126
|
+
doc.definitions.find((d): d is OperationDefinitionNode => d.kind === 'OperationDefinition')!;
|
|
127
|
+
export const operationName = (doc: DocumentNode): string => operation(doc).name?.value ?? '';
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
Dicas:
|
|
131
|
+
- Fixture grande (payload real anonimizado) em `<tela>.fixture.ts` ao lado da spec; use
|
|
132
|
+
`structuredClone` ao devolvê-la para um teste não contaminar o outro.
|
|
133
|
+
- Signals: leia direto (`cmp.itens()`); para input de signal, `fixture.componentRef.setInput('x', v)`.
|
|
134
|
+
- Componente `hm-*` que não reflete propriedade como atributo do DOM: leia pelo componente
|
|
135
|
+
(`ng.getComponent(el)`), não pelo atributo.
|
|
136
|
+
- Valide só o que mudou (spec da tela alterada), não a bateria inteira a cada ajuste.
|
|
137
|
+
|
|
138
|
+
## Lint de acessibilidade
|
|
139
|
+
|
|
140
|
+
`eslint.a11y.config.js` separado do lint principal, com o preset de acessibilidade de template do
|
|
141
|
+
`angular-eslint` rebaixado para `warn`:
|
|
142
|
+
|
|
143
|
+
```js
|
|
144
|
+
// @ts-check
|
|
145
|
+
const tseslint = require('typescript-eslint');
|
|
146
|
+
const angular = require('angular-eslint');
|
|
147
|
+
|
|
148
|
+
const toWarn = (configs) => configs.map((c) => !c.rules ? c : {
|
|
149
|
+
...c,
|
|
150
|
+
rules: Object.fromEntries(Object.entries(c.rules).map(([k, v]) => [k, Array.isArray(v) ? ['warn', ...v.slice(1)] : 'warn'])),
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
module.exports = tseslint.config({
|
|
154
|
+
files: ['**/*.html'],
|
|
155
|
+
extends: [...toWarn(angular.configs.templateAccessibility)],
|
|
156
|
+
});
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
Script: `"lint:a11y": "eslint --config eslint.a11y.config.js \"src/**/*.html\""`. Dependências:
|
|
160
|
+
`eslint`, `angular-eslint`, `typescript-eslint`. `label-has-associated-control` dá falso positivo
|
|
161
|
+
quando a associação é feita em runtime pelo componente: confira o DOM renderizado antes de "corrigir".
|
|
162
|
+
|
|
163
|
+
### axe no navegador
|
|
164
|
+
|
|
165
|
+
`scripts/axe-check.js` é **o mesmo arquivo em todo app** (puppeteer + `axe-core`). Lê as telas do
|
|
166
|
+
`features.routes.ts` (cada `{ id, load }`, pelo `id:` e o `.then(m => m.X)`), cruza com o `routeIdToPath` do
|
|
167
|
+
`axe-routes.config.json` (na raiz do app) e roda o axe em `staticRoutes` + nas telas com path conhecido;
|
|
168
|
+
avisa das que não têm. As URLs vêm do Argos em runtime: o `routeIdToPath` é preenchido navegando logado.
|
|
169
|
+
|
|
170
|
+
```json
|
|
171
|
+
{
|
|
172
|
+
"baseUrl": "http://localhost:4200/meu-app/",
|
|
173
|
+
"staticRoutes": ["/login", "/home", "/no-permission"],
|
|
174
|
+
"routeIdToPath": {}
|
|
175
|
+
}
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
- `baseUrl` = origem **e** caminho base do `start:local` (o `baseHref` da configuração `local`); as rotas
|
|
179
|
+
são resolvidas a partir dele (`/login` → `…/meu-app/login`). Sem o caminho base, o axe audita a página 404.
|
|
180
|
+
- Rotas logadas exigem `AXE_STORAGE_STATE=<json com cookies/localStorage>`; sem ele, o que redireciona para
|
|
181
|
+
`/login` é relatado como "sem auth", não como violação. `AXE_FAIL_ON` (padrão `serious`) define a saída 1.
|
|
182
|
+
|
|
183
|
+
## Build
|
|
184
|
+
|
|
185
|
+
| Configuração | Para quê | Environment |
|
|
186
|
+
| --- | --- | --- |
|
|
187
|
+
| `prod` (**padrão** do `ng build`) | produção: otimizado, `outputHashing: all`, budgets | `environment.prod.ts` |
|
|
188
|
+
| `homol` | homologação | `environment.homol.ts` |
|
|
189
|
+
| `dev` | ambiente de desenvolvimento em container | `environment.dev.ts` |
|
|
190
|
+
| `local` | `ng serve` nativo apontando para serviços locais | `environment.local.ts` |
|
|
191
|
+
| `development` | padrão do `ng serve`, sem troca de environment | `environment.ts` |
|
|
192
|
+
|
|
193
|
+
`ng build --configuration prod` (ou só `ng build`). Saída em `dist/<outputPath>/browser`.
|
|
194
|
+
|
|
195
|
+
### Budgets
|
|
196
|
+
|
|
197
|
+
```json
|
|
198
|
+
"budgets": [
|
|
199
|
+
{ "type": "initial", "maximumWarning": "4MB", "maximumError": "5MB" },
|
|
200
|
+
{ "type": "anyComponentStyle", "maximumWarning": "16kB", "maximumError": "32kB" }
|
|
201
|
+
]
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
- O inicial é alto por natureza: CSS global do DS (`tokens.css` + `core.css`) e shell/auth são
|
|
205
|
+
carregados antes de qualquer rota. `@defer` e lazy de tela não mexem nisso.
|
|
206
|
+
- Para baixar o inicial: `provideAnimationsAsync()`, `import()` lazy em libs pesadas
|
|
207
|
+
(`provideEchartsCore({ echarts: () => import('echarts') })`), não importar lib pesada em
|
|
208
|
+
`app.config.ts`/`core`.
|
|
209
|
+
- `anyComponentStyle` estourando = estilo de tela grande demais: extraia subcomponentes ou use os
|
|
210
|
+
componentes/tokens do DS em vez de CSS próprio.
|
|
211
|
+
|
|
212
|
+
### `styles.scss`
|
|
213
|
+
|
|
214
|
+
Só o que é global e próprio do app (ponte para classes legadas, tema próprio via `@use`). Sempre com
|
|
215
|
+
tokens `--hm-*`, nunca cor/tamanho cravado. Estilo de tela fica no `.scss` da tela. Tokens e temas:
|
|
216
|
+
`trismegisto`.
|
|
217
|
+
|
|
218
|
+
## Docker
|
|
219
|
+
|
|
220
|
+
Padrão multi-stage: um estágio para dev-server, um para o build e um final só com os arquivos
|
|
221
|
+
estáticos.
|
|
222
|
+
|
|
223
|
+
```dockerfile
|
|
224
|
+
FROM node:22-slim AS dev
|
|
225
|
+
WORKDIR /app
|
|
226
|
+
COPY package.json package-lock.json ./
|
|
227
|
+
RUN --mount=type=cache,target=/root/.npm,sharing=locked \
|
|
228
|
+
timeout -k 10 600 npm ci --prefer-offline --no-audit --no-fund
|
|
229
|
+
COPY . .
|
|
230
|
+
EXPOSE 4200
|
|
231
|
+
CMD ["./node_modules/.bin/ng", "serve", "--configuration", "dev", "--host", "0.0.0.0", "--no-hmr", "--port", "4200"]
|
|
232
|
+
|
|
233
|
+
FROM node:22-slim AS build
|
|
234
|
+
WORKDIR /app
|
|
235
|
+
COPY package.json package-lock.json ./
|
|
236
|
+
RUN --mount=type=cache,target=/root/.npm,sharing=locked \
|
|
237
|
+
timeout -k 10 600 npm ci --prefer-offline --no-audit --no-fund
|
|
238
|
+
COPY . .
|
|
239
|
+
# ARG depois do install: declarado antes, cada ambiente invalidaria o cache do npm ci.
|
|
240
|
+
ARG CONFIGURATION=prod
|
|
241
|
+
RUN --mount=type=cache,target=/app/.angular/cache,sharing=locked \
|
|
242
|
+
timeout -k 10 300 ./node_modules/.bin/ng build --configuration $CONFIGURATION
|
|
243
|
+
|
|
244
|
+
# Imagem só para extrair o site (docker create + docker cp): o build estático em /dist.
|
|
245
|
+
FROM scratch AS site
|
|
246
|
+
COPY --from=build /app/dist/meu-app/browser /dist
|
|
247
|
+
CMD ["unused"]
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
- `timeout -k` em passo que baixa/compila: build travado não fica rodando para sempre.
|
|
251
|
+
- **Não copie `.npmrc`** nem passe credencial por `ARG`/`ENV`: fica gravado na imagem. Os pacotes
|
|
252
|
+
`@trismegisto/*` e `@orfeu/*` vêm do npm público.
|
|
253
|
+
- `.dockerignore` com `node_modules`, `dist`, `.angular`.
|
|
254
|
+
- Para servir com nginx (ou outro servidor estático): copie `/dist` para o `root`, sirva sob o mesmo
|
|
255
|
+
prefixo do `baseHref` e faça fallback de SPA para o `index.html`
|
|
256
|
+
(`try_files $uri $uri/ /<prefixo>/index.html;`). Arquivos com hash podem ter cache longo;
|
|
257
|
+
`index.html` sem cache.
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Verificador da skill `angular`: padrões de app Angular (22+, standalone, signals).
|
|
3
|
+
// node checar.mjs [caminhos...] [--json] (instalado: ~/.claude/skills/angular/scripts/checar.mjs)
|
|
4
|
+
// Exceção: `// acropole-ignore-next-line <regra> -- motivo` (ou `<!-- ... -->` no HTML) na linha anterior.
|
|
5
|
+
import { executar, templates } from './nucleo.mjs';
|
|
6
|
+
|
|
7
|
+
const ehTs = (a) => a.ext === '.ts';
|
|
8
|
+
const ehCodigo = (a) => ehTs(a) && !/\.spec\.ts$/.test(a.nome);
|
|
9
|
+
|
|
10
|
+
/** Achados de um regex no texto sem comentários. */
|
|
11
|
+
function procurar(arq, texto, inicio, re, fazer) {
|
|
12
|
+
const out = [];
|
|
13
|
+
for (const m of texto.matchAll(re)) out.push({ linha: arq.linhaDe(inicio + m.index), ...fazer(m) });
|
|
14
|
+
return out;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Índice do `)`/`}` que fecha o `(`/`{` em `inicio` (conta só o mesmo tipo; strings de template são raras aqui). */
|
|
18
|
+
function fecha(texto, inicio) {
|
|
19
|
+
const abre = texto[inicio];
|
|
20
|
+
const fechaCh = abre === '(' ? ')' : '}';
|
|
21
|
+
let prof = 0;
|
|
22
|
+
for (let i = inicio; i < texto.length; i++) {
|
|
23
|
+
if (texto[i] === abre) prof++;
|
|
24
|
+
else if (texto[i] === fechaCh && --prof === 0) return i;
|
|
25
|
+
}
|
|
26
|
+
return texto.length;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Tags HTML de um trecho de template: `{ tag, pos, atributos: [{ nome, valor, pos }] }`. */
|
|
30
|
+
function* tags(trecho) {
|
|
31
|
+
const re = /<([a-zA-Z][\w-]*)(?![\w-])/g;
|
|
32
|
+
let m;
|
|
33
|
+
while ((m = re.exec(trecho))) {
|
|
34
|
+
let i = re.lastIndex;
|
|
35
|
+
let aspas = '';
|
|
36
|
+
for (; i < trecho.length; i++) {
|
|
37
|
+
const ch = trecho[i];
|
|
38
|
+
if (aspas) {
|
|
39
|
+
if (ch === aspas) aspas = '';
|
|
40
|
+
} else if (ch === '"' || ch === "'") aspas = ch;
|
|
41
|
+
else if (ch === '>') break;
|
|
42
|
+
}
|
|
43
|
+
const corpo = trecho.slice(re.lastIndex, i);
|
|
44
|
+
const atributos = [];
|
|
45
|
+
for (const a of corpo.matchAll(/([^\s=/>"']+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g)) {
|
|
46
|
+
atributos.push({ nome: a[1], valor: a[2] ?? a[3] ?? a[4], pos: re.lastIndex + a.index });
|
|
47
|
+
}
|
|
48
|
+
yield { tag: m[1], pos: m.index, atributos };
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// `toISOString()` cortado para virar data `AAAA-MM-DD`.
|
|
53
|
+
const ISO_CORTADO = /toISOString\(\)\s*\.\s*(?:(?:slice|substring|substr)\(\s*0\s*,\s*10\s*\)|split\(\s*(['"`])T\1\s*\)\s*\[\s*0\s*\])/g;
|
|
54
|
+
|
|
55
|
+
const regras = [
|
|
56
|
+
{
|
|
57
|
+
id: 'decorator-input-output',
|
|
58
|
+
resumo: '@Input()/@Output()/new EventEmitter em vez de input()/output()/model()',
|
|
59
|
+
aceita: ehCodigo,
|
|
60
|
+
checar: (arq) =>
|
|
61
|
+
procurar(arq, arq.limpo, 0, /@(Input|Output)\s*\(|\bnew\s+EventEmitter\b/g, (m) => ({
|
|
62
|
+
mensagem: m[1] ? `\`@${m[1]}()\` é a API antiga de decorators` : '`EventEmitter` é a API antiga de outputs',
|
|
63
|
+
correcao: m[1] === 'Input' ? 'use `readonly x = input<T>()` (ou `input.required<T>()`, `model<T>()` para two-way)' : 'use `readonly x = output<T>()`',
|
|
64
|
+
})),
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
id: 'diretiva-estrutural',
|
|
68
|
+
resumo: '*ngIf/*ngFor/*ngSwitchCase no template (use @if/@for/@switch)',
|
|
69
|
+
aceita: (a) => a.ext === '.html' || ehTs(a),
|
|
70
|
+
checar(arq) {
|
|
71
|
+
const out = [];
|
|
72
|
+
const novo = { ngIf: '@if (cond) { … } @else { … }', ngFor: '@for (item of itens; track item.id) { … }', ngSwitchCase: '@switch (x) { @case (v) { … } }', ngSwitchDefault: '@switch … @default { … }' };
|
|
73
|
+
for (const seg of templates(arq)) {
|
|
74
|
+
out.push(
|
|
75
|
+
...procurar(arq, seg.texto, seg.inicio, /\*(ngIf|ngFor|ngSwitchCase|ngSwitchDefault)\b/g, (m) => ({
|
|
76
|
+
mensagem: `\`*${m[1]}\` é a sintaxe antiga de controle de fluxo`,
|
|
77
|
+
correcao: `use \`${novo[m[1]]}\` (migração automática: \`ng generate @angular/core:control-flow\`)`,
|
|
78
|
+
})),
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
return out;
|
|
82
|
+
},
|
|
83
|
+
},
|
|
84
|
+
{
|
|
85
|
+
id: 'http-sem-interceptors',
|
|
86
|
+
resumo: 'provideHttpClient( sem withInterceptorsFromDi() no mesmo arquivo',
|
|
87
|
+
aceita: ehCodigo,
|
|
88
|
+
checar(arq) {
|
|
89
|
+
if (/\bwithInterceptorsFromDi\s*\(/.test(arq.limpo)) return [];
|
|
90
|
+
return procurar(arq, arq.limpo, 0, /\bprovideHttpClient\s*\(/g, () => ({
|
|
91
|
+
mensagem: '`provideHttpClient` sem `withInterceptorsFromDi()`: o interceptor do spine não roda e o `x-route-id` da auditoria se perde',
|
|
92
|
+
correcao: 'use `provideHttpClient(withInterceptorsFromDi())` (outros `with*` podem vir junto)',
|
|
93
|
+
}));
|
|
94
|
+
},
|
|
95
|
+
},
|
|
96
|
+
{
|
|
97
|
+
id: 'standalone-redundante',
|
|
98
|
+
resumo: 'standalone: true (já é o padrão)',
|
|
99
|
+
aceita: ehTs,
|
|
100
|
+
checar: (arq) =>
|
|
101
|
+
procurar(arq, arq.limpo, 0, /\bstandalone\s*:\s*true\b/g, () => ({
|
|
102
|
+
mensagem: '`standalone: true` é redundante: componentes, diretivas e pipes já são standalone por padrão',
|
|
103
|
+
correcao: 'apague a linha',
|
|
104
|
+
})),
|
|
105
|
+
},
|
|
106
|
+
{
|
|
107
|
+
id: 'track-objeto-inteiro',
|
|
108
|
+
resumo: '@for com `track item` (o objeto) quando o item tem id (`item.id`, `item.xId`...)',
|
|
109
|
+
aceita: (a) => a.ext === '.html' || ehTs(a),
|
|
110
|
+
checar(arq) {
|
|
111
|
+
const out = [];
|
|
112
|
+
for (const seg of templates(arq)) {
|
|
113
|
+
const t = seg.texto;
|
|
114
|
+
for (const m of t.matchAll(/@for\s*\(/g)) {
|
|
115
|
+
const abre = m.index + m[0].length - 1;
|
|
116
|
+
const fim = fecha(t, abre);
|
|
117
|
+
const cab = t.slice(abre + 1, fim).match(/^\s*([A-Za-z_$][\w$]*)\s+of\s[\s\S]*?;\s*track\s+([^;]+?)\s*(?:;|$)/);
|
|
118
|
+
if (!cab || cab[2] !== cab[1]) continue;
|
|
119
|
+
// Só acusa quando o próprio bloco lê um identificador do item: aí ele é objeto e tem chave estável.
|
|
120
|
+
const corpoIni = t.indexOf('{', fim);
|
|
121
|
+
if (corpoIni < 0) continue;
|
|
122
|
+
const corpo = t.slice(corpoIni, fecha(t, corpoIni));
|
|
123
|
+
const v = cab[1].replace(/\$/g, '\\$');
|
|
124
|
+
const id = corpo.match(new RegExp(`(?<![\\w$.])${v}\\s*\\??\\.\\s*(id|uuid|key|[a-z]\\w*Id|[a-z]\\w*_id)\\b`));
|
|
125
|
+
if (!id) continue;
|
|
126
|
+
out.push({
|
|
127
|
+
linha: arq.linhaDe(seg.inicio + m.index),
|
|
128
|
+
mensagem: `\`track ${cab[1]}\` rastreia o objeto: a cada recarga a lista vem com objetos novos e tudo é recriado (perde foco, expansão, seleção)`,
|
|
129
|
+
correcao: `use \`track ${cab[1]}.${id[1]}\``,
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return out;
|
|
134
|
+
},
|
|
135
|
+
},
|
|
136
|
+
{
|
|
137
|
+
id: 'data-utc-em-formulario',
|
|
138
|
+
resumo: 'toISOString().slice(0, 10) / .split(\'T\')[0] como data local (hoje, formulário)',
|
|
139
|
+
aceita: ehCodigo,
|
|
140
|
+
checar(arq) {
|
|
141
|
+
const linhas = arq.limpo.split('\n');
|
|
142
|
+
return procurar(arq, arq.limpo, 0, ISO_CORTADO, () => ({})).filter((a) => {
|
|
143
|
+
const l = linhas[a.linha - 1];
|
|
144
|
+
if (/Date\.UTC\(|getTimezoneOffset|getUTC\w+\(/.test(l)) return false; // UTC de propósito
|
|
145
|
+
return /new Date\(\s*\)|\bform\w*\b|[cC]ontrol\b|\.getRawValue\(|\.value\b|\b(?:hoje|today|now|agora)\b/.test(l);
|
|
146
|
+
}).map((a) => ({
|
|
147
|
+
linha: a.linha,
|
|
148
|
+
mensagem: '`toISOString()` é UTC: cortado para `AAAA-MM-DD`, dá o dia seguinte à noite no Brasil (depois das 21h em UTC-3) e o dia errado para a data escolhida no formulário',
|
|
149
|
+
correcao: 'monte a data local: `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, \'0\')}-${String(d.getDate()).padStart(2, \'0\')}` (ou `formatDate(d, \'yyyy-MM-dd\', locale)`)',
|
|
150
|
+
}));
|
|
151
|
+
},
|
|
152
|
+
},
|
|
153
|
+
{
|
|
154
|
+
id: 'disabled-com-form-control',
|
|
155
|
+
resumo: '[disabled] no mesmo elemento que [formControl]/formControlName',
|
|
156
|
+
aceita: (a) => a.ext === '.html' || ehTs(a),
|
|
157
|
+
checar(arq) {
|
|
158
|
+
const out = [];
|
|
159
|
+
for (const seg of templates(arq)) {
|
|
160
|
+
for (const t of tags(seg.texto)) {
|
|
161
|
+
const nomes = t.atributos.map((a) => a.nome);
|
|
162
|
+
if (!nomes.some((n) => /^\[?formControl(Name)?\]?$/.test(n))) continue;
|
|
163
|
+
const dis = t.atributos.find((a) => a.nome === '[disabled]');
|
|
164
|
+
if (!dis) continue;
|
|
165
|
+
out.push({
|
|
166
|
+
linha: arq.linhaDe(seg.inicio + dis.pos),
|
|
167
|
+
mensagem: `\`[disabled]\` junto de formulário reativo em \`<${t.tag}>\`: o Angular avisa no console e o controle continua habilitado no modelo (entra no \`form.value\` e na validação) mesmo com o campo cinza`,
|
|
168
|
+
correcao: 'tire o `[disabled]` e use `control.disable()` / `control.enable()` (num `effect()` se depende de signal)',
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
return out;
|
|
173
|
+
},
|
|
174
|
+
},
|
|
175
|
+
];
|
|
176
|
+
|
|
177
|
+
process.exitCode = executar({
|
|
178
|
+
skill: 'angular',
|
|
179
|
+
descricao: 'APIs antigas (@Input/@Output, *ngIf/*ngFor), standalone redundante, HttpClient sem interceptors de DI, track pelo objeto, data de formulário em UTC e [disabled] com formulário reativo.',
|
|
180
|
+
regras,
|
|
181
|
+
extensoes: ['.ts', '.html'],
|
|
182
|
+
});
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
// Núcleo dos verificadores das skills (`skills/<skill>/scripts/checar.mjs`). Sem dependências, só Node ≥ 18.
|
|
2
|
+
// FONTE ÚNICA: este arquivo é copiado para `skills/<skill>/scripts/nucleo.mjs` pelo `npm run sync`
|
|
3
|
+
// (cada skill é instalada sozinha, então leva a própria cópia). Edite aqui, nunca a cópia.
|
|
4
|
+
//
|
|
5
|
+
// Uso (pelo checar.mjs de cada skill): node checar.mjs [caminhos...] [--json]
|
|
6
|
+
// sem caminhos: a pasta atual (ignora node_modules, dist, .angular, .git, venvs e caches).
|
|
7
|
+
// saída: `arquivo:linha regra mensagem → correção`; código de saída 1 se achar algo.
|
|
8
|
+
// Exceção pontual, na linha ANTERIOR, em comentário da linguagem:
|
|
9
|
+
// // acropole-ignore-next-line <regra>[,<regra>] -- motivo
|
|
10
|
+
// Sem motivo depois de `--`, a exceção não vale.
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
|
|
14
|
+
const PASTAS_IGNORADAS = new Set(['node_modules', 'dist', '.angular', '.git', '.venv', 'venv', '__pycache__', '.pytest_cache', '.mypy_cache', 'coverage', '.nx', '.turbo']);
|
|
15
|
+
|
|
16
|
+
const C_LIKE = new Set(['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.mts', '.cts', '.scss', '.less']);
|
|
17
|
+
|
|
18
|
+
/** Troca cada caractere (menos quebras de linha) de `s[a..b)` por espaço. */
|
|
19
|
+
function apagar(chars, a, b) {
|
|
20
|
+
for (let i = a; i < b; i++) if (chars[i] !== '\n') chars[i] = ' ';
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Texto com os comentários apagados (mesmo tamanho, mesmas linhas). Strings ficam. */
|
|
24
|
+
export function semComentarios(texto, ext) {
|
|
25
|
+
const c = texto.split('');
|
|
26
|
+
const n = texto.length;
|
|
27
|
+
if (ext === '.html' || ext === '.htm') {
|
|
28
|
+
for (const m of texto.matchAll(/<!--[\s\S]*?(-->|$)/g)) apagar(c, m.index, m.index + m[0].length);
|
|
29
|
+
return c.join('');
|
|
30
|
+
}
|
|
31
|
+
if (ext === '.py') {
|
|
32
|
+
for (let i = 0; i < n; i++) {
|
|
33
|
+
const ch = texto[i];
|
|
34
|
+
if (ch === '#') {
|
|
35
|
+
const fim = texto.indexOf('\n', i);
|
|
36
|
+
apagar(c, i, fim < 0 ? n : fim);
|
|
37
|
+
i = fim < 0 ? n : fim;
|
|
38
|
+
} else if (ch === '"' || ch === "'") {
|
|
39
|
+
const triplo = texto.startsWith(ch.repeat(3), i);
|
|
40
|
+
const fecha = triplo ? ch.repeat(3) : ch;
|
|
41
|
+
let j = i + fecha.length;
|
|
42
|
+
while (j < n && !texto.startsWith(fecha, j)) {
|
|
43
|
+
if (texto[j] === '\\') j++;
|
|
44
|
+
else if (!triplo && texto[j] === '\n') break;
|
|
45
|
+
j++;
|
|
46
|
+
}
|
|
47
|
+
i = j + fecha.length - 1;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return c.join('');
|
|
51
|
+
}
|
|
52
|
+
const barraDupla = C_LIKE.has(ext); // .css puro só tem /* */
|
|
53
|
+
for (let i = 0; i < n; i++) {
|
|
54
|
+
const ch = texto[i];
|
|
55
|
+
if (ch === '/' && texto[i + 1] === '*') {
|
|
56
|
+
const fim = texto.indexOf('*/', i + 2);
|
|
57
|
+
const f = fim < 0 ? n : fim + 2;
|
|
58
|
+
apagar(c, i, f);
|
|
59
|
+
i = f - 1;
|
|
60
|
+
} else if (barraDupla && ch === '/' && texto[i + 1] === '/' && texto[i - 1] !== ':') {
|
|
61
|
+
const fim = texto.indexOf('\n', i);
|
|
62
|
+
apagar(c, i, fim < 0 ? n : fim);
|
|
63
|
+
i = fim < 0 ? n : fim;
|
|
64
|
+
} else if (ch === '"' || ch === "'" || ch === '`') {
|
|
65
|
+
let j = i + 1;
|
|
66
|
+
while (j < n && texto[j] !== ch) {
|
|
67
|
+
if (texto[j] === '\\') j++;
|
|
68
|
+
else if (ch !== '`' && texto[j] === '\n') break;
|
|
69
|
+
j++;
|
|
70
|
+
}
|
|
71
|
+
i = j;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
let out = c.join('');
|
|
75
|
+
// Comentário HTML dentro de template inline.
|
|
76
|
+
if (ext === '.ts') out = out.replace(/<!--[\s\S]*?-->/g, (m) => m.replace(/[^\n]/g, ' '));
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Monta o objeto de arquivo que as regras recebem. */
|
|
81
|
+
export function lerArquivo(caminho, rel, raiz = path.dirname(caminho)) {
|
|
82
|
+
const texto = fs.readFileSync(caminho, 'utf8').replace(/\r\n?/g, '\n');
|
|
83
|
+
const ext = path.extname(caminho).toLowerCase();
|
|
84
|
+
const inicios = [0];
|
|
85
|
+
for (let i = 0; i < texto.length; i++) if (texto[i] === '\n') inicios.push(i + 1);
|
|
86
|
+
const linhaDe = (idx) => {
|
|
87
|
+
let lo = 0;
|
|
88
|
+
let hi = inicios.length - 1;
|
|
89
|
+
while (lo < hi) {
|
|
90
|
+
const mid = (lo + hi + 1) >> 1;
|
|
91
|
+
if (inicios[mid] <= idx) lo = mid;
|
|
92
|
+
else hi = mid - 1;
|
|
93
|
+
}
|
|
94
|
+
return lo + 1;
|
|
95
|
+
};
|
|
96
|
+
// relRaiz: relativo ao caminho pedido na linha de comando (para regras que olham pastas, ex.: tests/).
|
|
97
|
+
const relRaiz = path.relative(raiz, caminho).split(path.sep).join('/') || path.basename(caminho);
|
|
98
|
+
return { caminho, rel, relRaiz, ext, nome: path.basename(caminho), texto, limpo: semComentarios(texto, ext), linhaDe };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Trechos de template HTML: o arquivo `.html` inteiro ou `template: \`...\`` de um `.ts`. `{ texto, inicio }`. */
|
|
102
|
+
export function templates(arq) {
|
|
103
|
+
if (arq.ext === '.html') return [{ texto: arq.limpo, inicio: 0 }];
|
|
104
|
+
if (arq.ext !== '.ts') return [];
|
|
105
|
+
const out = [];
|
|
106
|
+
for (const m of arq.limpo.matchAll(/\btemplate\s*:\s*`/g)) {
|
|
107
|
+
const ini = m.index + m[0].length;
|
|
108
|
+
const fim = arq.limpo.indexOf('`', ini);
|
|
109
|
+
if (fim > ini) out.push({ texto: arq.limpo.slice(ini, fim), inicio: ini });
|
|
110
|
+
}
|
|
111
|
+
return out;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Trechos de CSS: `.css`/`.scss` inteiros ou `styles: \`...\`` / `styles: [\`...\`]` de um `.ts`. */
|
|
115
|
+
export function estilos(arq) {
|
|
116
|
+
if (arq.ext === '.css' || arq.ext === '.scss' || arq.ext === '.less') return [{ texto: arq.limpo, inicio: 0 }];
|
|
117
|
+
if (arq.ext !== '.ts') return [];
|
|
118
|
+
const out = [];
|
|
119
|
+
for (const m of arq.limpo.matchAll(/\bstyles\s*:\s*\[?/g)) {
|
|
120
|
+
let i = m.index + m[0].length;
|
|
121
|
+
for (;;) {
|
|
122
|
+
while (/[\s,]/.test(arq.limpo[i] ?? '')) i++;
|
|
123
|
+
const q = arq.limpo[i];
|
|
124
|
+
if (q !== '`' && q !== "'" && q !== '"') break;
|
|
125
|
+
const fim = arq.limpo.indexOf(q, i + 1);
|
|
126
|
+
if (fim < 0) break;
|
|
127
|
+
// O conteúdo da string é CSS: apaga os /* */ dele.
|
|
128
|
+
out.push({ texto: semComentarios(arq.limpo.slice(i + 1, fim), '.css'), inicio: i + 1 });
|
|
129
|
+
i = fim + 1;
|
|
130
|
+
if (arq.limpo[m.index + m[0].length - 1] !== '[') break;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return out;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Lista os arquivos a verificar: `[{ caminho, raiz }]` (raiz = o caminho pedido que o contém). */
|
|
137
|
+
export function listarArquivos(caminhos, cwd, aceita) {
|
|
138
|
+
const out = new Map();
|
|
139
|
+
let raiz = '';
|
|
140
|
+
const visitar = (p, explicito) => {
|
|
141
|
+
let st;
|
|
142
|
+
try {
|
|
143
|
+
st = fs.statSync(p);
|
|
144
|
+
} catch {
|
|
145
|
+
throw new Error(`caminho não encontrado: ${p}`);
|
|
146
|
+
}
|
|
147
|
+
if (st.isDirectory()) {
|
|
148
|
+
if (!explicito && PASTAS_IGNORADAS.has(path.basename(p))) return;
|
|
149
|
+
if (explicito) raiz = p;
|
|
150
|
+
for (const e of fs.readdirSync(p).sort()) visitar(path.join(p, e), false);
|
|
151
|
+
} else if ((explicito || aceita(p)) && !out.has(p)) out.set(p, explicito ? path.dirname(p) : raiz);
|
|
152
|
+
};
|
|
153
|
+
for (const c of caminhos.length ? caminhos : ['.']) visitar(path.resolve(cwd, c), true);
|
|
154
|
+
return [...out].filter(([p]) => aceita(p)).map(([caminho, r]) => ({ caminho, raiz: r }));
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const IGNORE = /acropole-ignore-next-line\s+([\w,-]+)(?:\s+--(.*?))?\s*(?:\*\/|-->)?\s*$/;
|
|
158
|
+
|
|
159
|
+
/** Exceção declarada na linha anterior: `{ regras: Set, motivo }` ou null. */
|
|
160
|
+
function excecao(arq, linha) {
|
|
161
|
+
const anterior = arq.texto.split('\n')[linha - 2];
|
|
162
|
+
const m = anterior && anterior.match(IGNORE);
|
|
163
|
+
if (!m) return null;
|
|
164
|
+
return { regras: new Set(m[1].split(',').filter(Boolean)), motivo: (m[2] ?? '').trim() };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Roda as regras. `regras`: `[{ id, aceita(arq) => bool, checar(arq, ctx) => [{ linha, mensagem, correcao }] }]`.
|
|
169
|
+
* `preparar(arquivos, ctx)` opcional roda antes, com todos os arquivos lidos (ex.: coletar declarações).
|
|
170
|
+
*/
|
|
171
|
+
export function verificar({ regras, caminhos = [], cwd = process.cwd(), extensoes, preparar }) {
|
|
172
|
+
const aceita = (p) => extensoes.includes(path.extname(p).toLowerCase()) || extensoes.includes(path.basename(p));
|
|
173
|
+
const arquivos = listarArquivos(caminhos, cwd, aceita).map(({ caminho, raiz }) =>
|
|
174
|
+
lerArquivo(caminho, path.relative(cwd, caminho).split(path.sep).join('/') || path.basename(caminho), raiz),
|
|
175
|
+
);
|
|
176
|
+
const ctx = {};
|
|
177
|
+
if (preparar) preparar(arquivos, ctx);
|
|
178
|
+
const achados = [];
|
|
179
|
+
for (const arq of arquivos) {
|
|
180
|
+
for (const regra of regras) {
|
|
181
|
+
if (regra.aceita && !regra.aceita(arq)) continue;
|
|
182
|
+
for (const a of regra.checar(arq, ctx) ?? []) {
|
|
183
|
+
const exc = excecao(arq, a.linha);
|
|
184
|
+
let correcao = a.correcao;
|
|
185
|
+
if (exc && exc.regras.has(regra.id)) {
|
|
186
|
+
if (exc.motivo) continue;
|
|
187
|
+
correcao += ' (a exceção acropole-ignore-next-line precisa de motivo depois de "--")';
|
|
188
|
+
}
|
|
189
|
+
achados.push({ arquivo: arq.rel, linha: a.linha, regra: regra.id, mensagem: a.mensagem, correcao });
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
achados.sort((a, b) => (a.arquivo < b.arquivo ? -1 : a.arquivo > b.arquivo ? 1 : a.linha - b.linha || (a.regra < b.regra ? -1 : 1)));
|
|
194
|
+
// Mesmo achado duas vezes na mesma linha (ex.: duas cores) vira um só por regra+mensagem.
|
|
195
|
+
const unicos = [...new Map(achados.map((a) => [`${a.arquivo}:${a.linha}:${a.regra}:${a.mensagem}`, a])).values()];
|
|
196
|
+
return { arquivos: arquivos.length, achados: unicos };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Ponto de entrada dos checar.mjs: lê argv, imprime e define o código de saída. */
|
|
200
|
+
export function executar({ skill, descricao, regras, extensoes, preparar, argv = process.argv.slice(2) }) {
|
|
201
|
+
if (argv.includes('--help') || argv.includes('-h')) {
|
|
202
|
+
console.log(`Verificador da skill ${skill}: ${descricao}
|
|
203
|
+
|
|
204
|
+
Uso: node checar.mjs [caminhos...] [--json]
|
|
205
|
+
sem caminhos, verifica a pasta atual (ignora node_modules, dist, .angular...).
|
|
206
|
+
Exceção (linha anterior, em comentário): acropole-ignore-next-line <regra> -- motivo
|
|
207
|
+
|
|
208
|
+
Regras:
|
|
209
|
+
${regras.map((r) => ` ${r.id.padEnd(28)} ${r.resumo}`).join('\n')}`);
|
|
210
|
+
return 0;
|
|
211
|
+
}
|
|
212
|
+
const json = argv.includes('--json');
|
|
213
|
+
const caminhos = argv.filter((a) => a !== '--json');
|
|
214
|
+
let r;
|
|
215
|
+
try {
|
|
216
|
+
r = verificar({ regras, caminhos, extensoes, preparar });
|
|
217
|
+
} catch (e) {
|
|
218
|
+
console.error(`checar (${skill}): ${e.message}`);
|
|
219
|
+
return 2;
|
|
220
|
+
}
|
|
221
|
+
if (json) console.log(JSON.stringify({ skill, arquivos: r.arquivos, achados: r.achados }, null, 2));
|
|
222
|
+
else {
|
|
223
|
+
for (const a of r.achados) console.log(`${a.arquivo}:${a.linha} ${a.regra} ${a.mensagem} → ${a.correcao}`);
|
|
224
|
+
console.log(r.achados.length ? `\n${r.achados.length} problema(s) em ${r.arquivos} arquivo(s) verificado(s).` : `Nada encontrado (${r.arquivos} arquivo(s) verificado(s)).`);
|
|
225
|
+
}
|
|
226
|
+
return r.achados.length ? 1 : 0;
|
|
227
|
+
}
|