@erikbernardo/white-label-icons 1.0.1 → 1.0.2

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 (3) hide show
  1. package/README.md +58 -9
  2. package/bin/cli.js +178 -69
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Biblioteca de ícones moderna, ultraleve, **100% White-Label** e agnóstica a frameworks.
4
4
 
5
- Permite que **qualquer empresa ou projeto** utilize sua própria identidade de tags (`<empresa-icone>` ou `<meuapp-icon>`), classes CSS (`<i class="empresa-bx-user"></i>`) e diretórios de assets com zero acoplamento de marca e máxima performance com carregamento sob demanda (Lazy Loading e In-Memory Caching).
5
+ Permite que **qualquer empresa ou projeto** utilize sua própria identidade de tags (`<empresa-icone>` ou `<meuapp-icon>`), classes CSS (`<i class="empresa-bx-user"></i>`) e rotas de assets com zero acoplamento de marca e máxima performance com carregamento sob demanda (Lazy Loading e In-Memory Caching).
6
6
 
7
7
  🌐 **Demonstração & Catálogo Oficial**: [https://erikbernard.github.io/white-label-icons/](https://erikbernard.github.io/white-label-icons/)
8
8
 
@@ -10,38 +10,87 @@ Permite que **qualquer empresa ou projeto** utilize sua própria identidade de t
10
10
 
11
11
  ## ⚡ Início Rápido com CLI (Recomendado)
12
12
 
13
- O pacote inclui uma ferramenta CLI para configurar seu projeto em segundos (copiando os SVGs para a pasta de assets do seu projeto e gerando o arquivo de inicialização).
13
+ O pacote inclui uma ferramenta CLI que configura seu projeto em segundos. Para projetos Angular, o CLI **configura automaticamente o `angular.json`** para servir os SVGs direto do `node_modules` (sem poluir seu repositório Git com 7.000 arquivos).
14
+
15
+ ### 🌟 Como rodar o setup:
16
+
17
+ Execute no terminal da raiz do seu projeto:
14
18
 
15
- ### Modo Interativo (Perguntas no Terminal)
16
19
  ```bash
17
20
  npx @erikbernardo/white-label-icons init
18
21
  # ou
19
22
  npx wl-icons init
20
23
  ```
21
24
 
22
- ### Modo Direto (com Flags)
25
+ O CLI detecta automaticamente o ambiente do projeto ou exibe o menu interativo:
26
+
27
+ ```text
28
+ 1. Selecione o ambiente / framework do projeto:
29
+ [1] Angular 8 a 18 (NgModules / AppModule clássico)
30
+ [2] Angular 19 / 20+ (Standalone APIs / app.config.ts)
31
+ [3] React / Next.js / Vite
32
+ [4] Vue 2 / Vue 3 / Nuxt
33
+ [5] JavaScript Puro / Vanilla HTML
34
+ ```
35
+
36
+ ---
37
+
38
+ ### ⚡ Modo Direto (com Flags)
39
+
40
+ Você também pode rodar diretamente especificando o framework e prefixos sem perguntas interativas:
41
+
23
42
  ```bash
24
- npx wl-icons init --prefix=empresa --tag=empresa-icone --assets=src/assets/icones -y
43
+ # Angular 19 / 20+ (Standalone)
44
+ npx wl-icons init -f angular --prefix=minhaempresa -y
45
+
46
+ # React / Next.js / Vite
47
+ npx wl-icons init -f react --prefix=app -y
48
+
49
+ # Angular 8 a 18 (NgModule)
50
+ npx wl-icons init -f angular-legacy --prefix=empresa -y
51
+
52
+ # Vue 2 / Vue 3
53
+ npx wl-icons init -f vue --prefix=meuapp -y
25
54
  ```
26
55
 
27
- #### Opções do CLI:
56
+ #### Opções e Flags do CLI:
28
57
  | Flag | Descrição | Opções / Padrão |
29
58
  | :--- | :--- | :--- |
30
59
  | `-f, --framework <tipo>` | Framework do seu projeto | `angular-legacy` (8-18), `angular` (19/20+), `react`, `vue`, `vanilla` |
31
60
  | `-p, --prefix <valor>` | Prefixo das classes CSS (`<i class="{prefix}-user">`) | `wl` |
32
61
  | `-t, --tag <valor>` | Nome da tag Web Component | `{prefix}-icone` |
33
- | `-a, --assets <pasta>` | Pasta onde os 6.919 SVGs serão copiados | Auto-detectado por framework |
62
+ | `-b, --base-path <url>` | Rota pública base dos ícones (URL) | `/assets/icones/` (Angular) ou `/icones/` |
34
63
  | `-i, --init-file <caminho>` | Arquivo customizado gerado para o framework | Auto-detectado por framework |
35
64
  | `-y, --yes` | Pular perguntas e usar detecção automática | `false` |
65
+ | `--copy-svgs` | Forçar cópia de SVGs para disco (desnecessário no Angular) | `false` |
36
66
 
37
67
  ---
38
68
 
39
- ## 📦 Instalação Manual via NPM
69
+ ## 📦 Instalação Manual no Angular (Sem CLI)
40
70
 
71
+ Se preferir configurar manualmente sem o CLI:
72
+
73
+ ### 1. Instalar o pacote
41
74
  ```bash
42
75
  npm install @erikbernardo/white-label-icons
43
76
  ```
44
77
 
78
+ ### 2. Configurar o `angular.json`
79
+ No seu `angular.json`, dentro de `projects > [seu-projeto] > architect > build > options > assets`, adicione a regra de mapeamento:
80
+
81
+ ```json
82
+ "assets": [
83
+ "src/favicon.ico",
84
+ "src/assets",
85
+ {
86
+ "glob": "**/*.svg",
87
+ "input": "node_modules/@erikbernard/white-label-icons/icones",
88
+ "output": "/assets/icones/"
89
+ }
90
+ ]
91
+ ```
92
+ *(Repita também dentro de `architect > test > options > assets` caso queira suporte nos testes unitários).*
93
+
45
94
  ---
46
95
 
47
96
  ## 🚀 Integração por Framework
@@ -86,7 +135,7 @@ import { IconsModule } from './icons.module';
86
135
  export class AppModule {}
87
136
  ```
88
137
 
89
- #### Passo 2: Utilização nos Templates HTML
138
+ #### Utilização nos Templates HTML:
90
139
 
91
140
  ```html
92
141
  <!-- Opção A: Via Custom Element Nativo -->
package/bin/cli.js CHANGED
@@ -23,16 +23,33 @@ const c = {
23
23
  gray: '\x1b[90m',
24
24
  };
25
25
 
26
+ function getPackageInfo() {
27
+ try {
28
+ const pkg = JSON.parse(fs.readFileSync(path.join(PACKAGE_ROOT, 'package.json'), 'utf8'));
29
+ return {
30
+ name: pkg.name || '@erikbernardo/white-label-icons',
31
+ version: pkg.version || '1.0.0',
32
+ };
33
+ } catch {
34
+ return {
35
+ name: '@erikbernardo/white-label-icons',
36
+ version: '1.0.0',
37
+ };
38
+ }
39
+ }
40
+
41
+ const { name: PACKAGE_NAME, version: PACKAGE_VERSION } = getPackageInfo();
42
+
26
43
  function printBanner() {
27
44
  console.log(`\n${c.cyan}${c.bright}======================================================${c.reset}`);
28
- console.log(`${c.magenta}${c.bright} 🎨 White-Label Icons CLI (@erikbernardo/white-label-icons) ${c.reset}`);
45
+ console.log(`${c.magenta}${c.bright} 🎨 White-Label Icons CLI (${PACKAGE_NAME}) ${c.reset}`);
29
46
  console.log(`${c.cyan}${c.bright}======================================================${c.reset}\n`);
30
47
  }
31
48
 
32
49
  function printHelp() {
33
50
  printBanner();
34
51
  console.log(`Uso:
35
- ${c.green}npx @erikbernardo/white-label-icons init${c.reset} [opções]
52
+ ${c.green}npx ${PACKAGE_NAME} init${c.reset} [opções]
36
53
  ${c.green}npx wl-icons init${c.reset} [opções]
37
54
 
38
55
  Opções:
@@ -44,9 +61,10 @@ Opções:
44
61
  ${c.bright}vanilla${c.reset} (JavaScript Puro / HTML)
45
62
  ${c.yellow}-p, --prefix <valor>${c.reset} Prefixo das classes CSS (ex: 'empresa' para <i class="empresa-bx-user">)
46
63
  ${c.yellow}-t, --tag <valor>${c.reset} Nome da tag Web Component (ex: 'empresa-icone' ou 'empresa-icon')
47
- ${c.yellow}-a, --assets <pasta>${c.reset} Caminho de destino para os arquivos SVG
48
- ${c.yellow}-i, --init-file <caminho>${c.reset}Arquivo gerado específico para o framework
64
+ ${c.yellow}-b, --base-path <url>${c.reset} Caminho público dos ícones (padrão: '/assets/icones/')
65
+ ${c.yellow}-i, --init-file <caminho>${c.reset}Arquivo gerado de configuração para o framework
49
66
  ${c.yellow}-y, --yes${c.reset} Aceitar todos os padrões detectados sem perguntas interativas
67
+ ${c.yellow}--copy-svgs${c.reset} Forçar a cópia física dos arquivos SVG (não necessário para Angular)
50
68
  ${c.yellow}-h, --help${c.reset} Exibir esta ajuda
51
69
  ${c.yellow}-v, --version${c.reset} Exibir a versão instalada
52
70
  `);
@@ -58,9 +76,10 @@ function parseArgs(args) {
58
76
  framework: '',
59
77
  prefix: '',
60
78
  tag: '',
61
- assets: '',
79
+ basePath: '',
62
80
  initFile: '',
63
81
  yes: false,
82
+ copySvgs: false,
64
83
  help: false,
65
84
  version: false,
66
85
  };
@@ -75,6 +94,8 @@ function parseArgs(args) {
75
94
  parsed.version = true;
76
95
  } else if (arg === '-y' || arg === '--yes') {
77
96
  parsed.yes = true;
97
+ } else if (arg === '--copy-svgs') {
98
+ parsed.copySvgs = true;
78
99
  } else if (arg.startsWith('--framework=')) {
79
100
  parsed.framework = arg.split('=')[1];
80
101
  } else if (arg === '-f' && args[i + 1]) {
@@ -87,10 +108,10 @@ function parseArgs(args) {
87
108
  parsed.tag = arg.split('=')[1];
88
109
  } else if (arg === '-t' && args[i + 1]) {
89
110
  parsed.tag = args[++i];
90
- } else if (arg.startsWith('--assets=')) {
91
- parsed.assets = arg.split('=')[1];
92
- } else if (arg === '-a' && args[i + 1]) {
93
- parsed.assets = args[++i];
111
+ } else if (arg.startsWith('--base-path=') || arg.startsWith('--assets=')) {
112
+ parsed.basePath = arg.split('=')[1];
113
+ } else if ((arg === '-b' || arg === '-a') && args[i + 1]) {
114
+ parsed.basePath = args[++i];
94
115
  } else if (arg.startsWith('--init-file=')) {
95
116
  parsed.initFile = arg.split('=')[1];
96
117
  } else if (arg === '-i' && args[i + 1]) {
@@ -138,15 +159,6 @@ function copyDirectoryRecursive(src, dest) {
138
159
  return count;
139
160
  }
140
161
 
141
- function getPackageVersion() {
142
- try {
143
- const pkg = JSON.parse(fs.readFileSync(path.join(PACKAGE_ROOT, 'package.json'), 'utf8'));
144
- return pkg.version || '1.0.0';
145
- } catch {
146
- return '1.0.0';
147
- }
148
- }
149
-
150
162
  /**
151
163
  * Detecta o ambiente do projeto no diretório atual.
152
164
  */
@@ -215,38 +227,111 @@ function getFrameworkLabel(fw) {
215
227
  }
216
228
 
217
229
  function getDefaultPathsForFramework(fw, isTs) {
218
- const cwd = process.cwd();
219
- let defaultAssets = 'public/icones';
230
+ let defaultBasePath = '/assets/icones/';
220
231
  let defaultInitFile = isTs ? 'src/icons-init.ts' : 'src/icons-init.js';
221
232
 
222
233
  switch (fw) {
223
234
  case 'angular-legacy':
224
- defaultAssets = 'src/assets/icones';
235
+ defaultBasePath = '/assets/icones/';
225
236
  defaultInitFile = isTs ? 'src/app/icons.module.ts' : 'src/app/icons.module.js';
226
237
  break;
227
238
 
228
239
  case 'angular':
229
- defaultAssets = fs.existsSync(path.join(cwd, 'public')) ? 'public/icones' : 'src/assets/icones';
240
+ defaultBasePath = '/assets/icones/';
230
241
  defaultInitFile = 'src/app/icons.config.ts';
231
242
  break;
232
243
 
233
244
  case 'react':
234
- defaultAssets = 'public/icones';
245
+ defaultBasePath = '/icones/';
235
246
  defaultInitFile = isTs ? 'src/icons.tsx' : 'src/icons.jsx';
236
247
  break;
237
248
 
238
249
  case 'vue':
239
- defaultAssets = 'public/icones';
250
+ defaultBasePath = '/icones/';
240
251
  defaultInitFile = isTs ? 'src/plugins/icons.ts' : 'src/plugins/icons.js';
241
252
  break;
242
253
 
243
254
  default: // vanilla
244
- defaultAssets = fs.existsSync(path.join(cwd, 'public')) ? 'public/icones' : 'icones';
255
+ defaultBasePath = './icones/';
245
256
  defaultInitFile = isTs ? 'src/icons-init.ts' : 'icons-init.js';
246
257
  break;
247
258
  }
248
259
 
249
- return { defaultAssets, defaultInitFile };
260
+ return { defaultBasePath, defaultInitFile };
261
+ }
262
+
263
+ /**
264
+ * Atualiza o angular.json automaticamente para mapear os SVGs do node_modules
265
+ */
266
+ function configureAngularJson(basePath) {
267
+ const angularJsonPath = path.resolve(process.cwd(), 'angular.json');
268
+
269
+ if (!fs.existsSync(angularJsonPath)) {
270
+ return { success: false, reason: 'angular.json não encontrado' };
271
+ }
272
+
273
+ try {
274
+ const rawContent = fs.readFileSync(angularJsonPath, 'utf8');
275
+ const angularJson = JSON.parse(rawContent);
276
+ const projects = angularJson.projects || {};
277
+ let modified = false;
278
+
279
+ // Normaliza o caminho de saída (ex: '/assets/icones/' -> '/assets/icones/')
280
+ let outputDir = basePath;
281
+ if (!outputDir.startsWith('/')) outputDir = '/' + outputDir;
282
+ if (!outputDir.endsWith('/')) outputDir += '/';
283
+
284
+ const assetEntry = {
285
+ glob: '**/*.svg',
286
+ input: `node_modules/${PACKAGE_NAME}/icones`,
287
+ output: outputDir,
288
+ };
289
+
290
+ for (const [projectName, projectConfig] of Object.entries(projects)) {
291
+ const architect = projectConfig.architect || projectConfig.targets || {};
292
+
293
+ // 1. Configura no target "build"
294
+ if (architect.build && architect.build.options) {
295
+ if (!Array.isArray(architect.build.options.assets)) {
296
+ architect.build.options.assets = [];
297
+ }
298
+ const assets = architect.build.options.assets;
299
+ const exists = assets.some(
300
+ (a) => typeof a === 'object' && a.input && (a.input.includes(PACKAGE_NAME) || a.input.includes('white-label-icons') || a.input.includes('gt-controller-icones'))
301
+ );
302
+
303
+ if (!exists) {
304
+ assets.push(assetEntry);
305
+ modified = true;
306
+ }
307
+ }
308
+
309
+ // 2. Configura no target "test"
310
+ if (architect.test && architect.test.options) {
311
+ if (!Array.isArray(architect.test.options.assets)) {
312
+ architect.test.options.assets = [];
313
+ }
314
+ const assets = architect.test.options.assets;
315
+ const exists = assets.some(
316
+ (a) => typeof a === 'object' && a.input && (a.input.includes(PACKAGE_NAME) || a.input.includes('white-label-icons') || a.input.includes('gt-controller-icones'))
317
+ );
318
+
319
+ if (!exists) {
320
+ assets.push(assetEntry);
321
+ modified = true;
322
+ }
323
+ }
324
+ }
325
+
326
+ if (modified) {
327
+ fs.writeFileSync(angularJsonPath, JSON.stringify(angularJson, null, 2), 'utf8');
328
+ return { success: true, modified: true };
329
+ }
330
+
331
+ return { success: true, modified: false };
332
+ } catch (err) {
333
+ return { success: false, reason: err.message };
334
+ }
250
335
  }
251
336
 
252
337
  /**
@@ -257,10 +342,10 @@ function generateInitFileContent(framework, prefix, tag, webBasePath, isTs) {
257
342
  case 'angular-legacy':
258
343
  return `/**
259
344
  * Módulo de Ícones White-Label para Angular 8 a 18 (NgModule)
260
- * Gerado automaticamente pelo CLI @erikbernardo/white-label-icons
345
+ * Gerado automaticamente pelo CLI ${PACKAGE_NAME}
261
346
  */
262
347
  import { NgModule, CUSTOM_ELEMENTS_SCHEMA, APP_INITIALIZER } from '@angular/core';
263
- import { configureIcons } from '@erikbernardo/white-label-icons';
348
+ import { configureIcons } from '${PACKAGE_NAME}';
264
349
 
265
350
  export function initializeWhiteLabelIcons() {
266
351
  return () => {
@@ -289,10 +374,10 @@ export class IconsModule {}
289
374
  case 'angular':
290
375
  return `/**
291
376
  * Provider de Ícones White-Label para Angular 19 e 20+ (Standalone APIs)
292
- * Gerado automaticamente pelo CLI @erikbernardo/white-label-icons
377
+ * Gerado automaticamente pelo CLI ${PACKAGE_NAME}
293
378
  */
294
379
  import { EnvironmentProviders, makeEnvironmentProviders, ENVIRONMENT_INITIALIZER, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
295
- import { configureIcons, IconOptions } from '@erikbernardo/white-label-icons';
380
+ import { configureIcons, IconOptions } from '${PACKAGE_NAME}';
296
381
 
297
382
  /**
298
383
  * Adicione este provider no seu app.config.ts:
@@ -325,10 +410,10 @@ export const ICONS_SCHEMAS = [CUSTOM_ELEMENTS_SCHEMA];
325
410
  case 'react':
326
411
  return `/**
327
412
  * Wrapper de Ícones White-Label para React / Next.js
328
- * Gerado automaticamente pelo CLI @erikbernardo/white-label-icons
413
+ * Gerado automaticamente pelo CLI ${PACKAGE_NAME}
329
414
  */
330
415
  import React from 'react';
331
- import { configureIcons } from '@erikbernardo/white-label-icons';
416
+ import { configureIcons } from '${PACKAGE_NAME}';
332
417
 
333
418
  // Inicializa no cliente
334
419
  export function initIcons(): void {
@@ -372,9 +457,9 @@ export const Icon: React.FC<IconProps> = ({ name, size, color, rotate, flip, cla
372
457
  case 'vue':
373
458
  return `/**
374
459
  * Plugin de Ícones White-Label para Vue 2 / Vue 3
375
- * Gerado automaticamente pelo CLI @erikbernardo/white-label-icons
460
+ * Gerado automaticamente pelo CLI ${PACKAGE_NAME}
376
461
  */
377
- import { configureIcons } from '@erikbernardo/white-label-icons';
462
+ import { configureIcons } from '${PACKAGE_NAME}';
378
463
 
379
464
  export const IconsPlugin = {
380
465
  install(${isTs ? 'app: any' : 'app'}) {
@@ -401,9 +486,9 @@ if (typeof window !== 'undefined') {
401
486
  default: // vanilla
402
487
  return `/**
403
488
  * Configuração dos Ícones White-Label (JavaScript Puro / HTML)
404
- * Gerado automaticamente pelo CLI @erikbernardo/white-label-icons
489
+ * Gerado automaticamente pelo CLI ${PACKAGE_NAME}
405
490
  */
406
- import { configureIcons } from '@erikbernardo/white-label-icons';
491
+ import { configureIcons } from '${PACKAGE_NAME}';
407
492
 
408
493
  export function initAppIcons()${isTs ? ': void' : ''} {
409
494
  configureIcons({
@@ -431,7 +516,7 @@ async function runInit(options) {
431
516
  let framework = normalizeFramework(options.framework);
432
517
  let prefix = options.prefix;
433
518
  let tag = options.tag;
434
- let assetsPath = options.assets;
519
+ let basePath = options.basePath;
435
520
  let initFilePath = options.initFile;
436
521
 
437
522
  const isInteractive = !options.yes && process.stdin.isTTY;
@@ -457,7 +542,7 @@ async function runInit(options) {
457
542
  'angular': '2',
458
543
  'react': '3',
459
544
  'vue': '4',
460
- 'vanilla': '5'
545
+ 'vanilla': '5',
461
546
  };
462
547
  const defaultChoice = fwChoiceMap[detectedFw] || '1';
463
548
 
@@ -465,7 +550,7 @@ async function runInit(options) {
465
550
  framework = normalizeFramework(answer) || detectedFw;
466
551
  }
467
552
 
468
- const { defaultAssets, defaultInitFile } = getDefaultPathsForFramework(framework, isTs);
553
+ const { defaultBasePath, defaultInitFile } = getDefaultPathsForFramework(framework, isTs);
469
554
 
470
555
  if (!prefix) {
471
556
  prefix = await askQuestion(rl, '2. Qual prefixo de classe deseja usar para os ícones? (ex: empresa, app, wl)', 'wl');
@@ -476,8 +561,8 @@ async function runInit(options) {
476
561
  tag = await askQuestion(rl, `3. Qual tag Web Component deseja registrar?`, defaultTag);
477
562
  }
478
563
 
479
- if (!assetsPath) {
480
- assetsPath = await askQuestion(rl, '4. Onde deseja copiar os arquivos SVG no seu projeto?', defaultAssets);
564
+ if (!basePath) {
565
+ basePath = await askQuestion(rl, '4. Rota pública base dos ícones (URL):', defaultBasePath);
481
566
  }
482
567
 
483
568
  if (!initFilePath) {
@@ -491,8 +576,8 @@ async function runInit(options) {
491
576
  framework = framework || detectedFw || 'vanilla';
492
577
  prefix = prefix || 'wl';
493
578
  tag = tag || `${prefix}-icone`;
494
- const { defaultAssets, defaultInitFile } = getDefaultPathsForFramework(framework, isTs);
495
- assetsPath = assetsPath || defaultAssets;
579
+ const { defaultBasePath, defaultInitFile } = getDefaultPathsForFramework(framework, isTs);
580
+ basePath = basePath || defaultBasePath;
496
581
  initFilePath = initFilePath || defaultInitFile;
497
582
  }
498
583
 
@@ -502,34 +587,60 @@ async function runInit(options) {
502
587
  tag = `${tag}-icone`;
503
588
  }
504
589
 
505
- const targetAssetsDir = path.resolve(process.cwd(), assetsPath);
590
+ if (!basePath.startsWith('/') && !basePath.startsWith('./')) {
591
+ basePath = '/' + basePath;
592
+ }
593
+ if (!basePath.endsWith('/')) {
594
+ basePath += '/';
595
+ }
596
+
506
597
  const targetInitFile = path.resolve(process.cwd(), initFilePath);
507
598
 
508
599
  console.log(`${c.cyan}⚙️ Configurações selecionadas:${c.reset}`);
509
600
  console.log(` • Ambiente / Framework: ${c.green}${getFrameworkLabel(framework)}${c.reset}`);
510
601
  console.log(` • Prefixo CSS: ${c.green}${prefix}${c.reset} (ex: <i class="${prefix}-bx-user"></i>)`);
511
602
  console.log(` • Tag Web Component: ${c.green}<${tag}>${c.reset} (ex: <${tag} nome="bx-user"></${tag}>)`);
512
- console.log(` • Pasta de SVGs: ${c.green}${assetsPath}${c.reset}`);
603
+ console.log(` • Rota de Assets (URL): ${c.green}${basePath}${c.reset}`);
513
604
  console.log(` • Arquivo de Init: ${c.green}${initFilePath}${c.reset}\n`);
514
605
 
515
- // 1. Cópia de SVGs
516
- console.log(`${c.bright}📦 Copiando 6.919 ícones SVG para "${assetsPath}"...${c.reset}`);
517
- try {
518
- const copiedCount = copyDirectoryRecursive(SOURCE_ICONS_DIR, targetAssetsDir);
519
- console.log(`${c.green}✔ ${copiedCount} ícones SVG copiados com sucesso!${c.reset}\n`);
520
- } catch (err) {
521
- console.error(`${c.red}❌ Falha ao copiar ícones:${c.reset}`, err.message);
522
- process.exit(1);
606
+ // 1. Configuração Automática do angular.json (se for projeto Angular)
607
+ const isAngular = framework === 'angular' || framework === 'angular-legacy';
608
+ if (isAngular) {
609
+ console.log(`${c.bright}⚙️ Configurando mapeamento de assets no "angular.json"...${c.reset}`);
610
+ const ngResult = configureAngularJson(basePath);
611
+ if (ngResult.success) {
612
+ if (ngResult.modified) {
613
+ console.log(`${c.green}✔ "angular.json" atualizado com sucesso! (SVGs serão servidos direto do node_modules sem poluir o Git).${c.reset}\n`);
614
+ } else {
615
+ console.log(`${c.green}✔ "angular.json" já possuía a regra de assets configurada.${c.reset}\n`);
616
+ }
617
+ } else {
618
+ console.warn(`${c.yellow}⚠️ Aviso: Não foi possível atualizar o angular.json automaticamente (${ngResult.reason}).${c.reset}`);
619
+ console.warn(` Certifique-se de adicionar a seguinte regra manualmente em "assets":`);
620
+ console.warn(` {\n "glob": "**/*.svg",\n "input": "node_modules/${PACKAGE_NAME}/icones",\n "output": "${basePath}"\n }\n`);
621
+ }
523
622
  }
524
623
 
525
- // 2. Criação do arquivo de inicialização específico do framework
526
- console.log(`${c.bright}📝 Gerando arquivo de inicialização customizado para ${getFrameworkLabel(framework)}...${c.reset}`);
527
-
528
- let webBasePath = assetsPath.replace(/^src\//, '').replace(/^public\//, '');
529
- if (!webBasePath.startsWith('/')) webBasePath = '/' + webBasePath;
530
- if (!webBasePath.endsWith('/')) webBasePath += '/';
624
+ // 2. Cópia opcional para projetos não-Angular ou com flag --copy-svgs
625
+ if (options.copySvgs || (!isAngular && (framework === 'react' || framework === 'vue' || framework === 'vanilla'))) {
626
+ const publicDir = fs.existsSync(path.join(process.cwd(), 'public'))
627
+ ? path.join(process.cwd(), 'public/icones')
628
+ : path.join(process.cwd(), 'icones');
629
+
630
+ if (options.copySvgs) {
631
+ console.log(`${c.bright}📦 Copiando arquivos SVG para "${publicDir}" (--copy-svgs)...${c.reset}`);
632
+ try {
633
+ const copied = copyDirectoryRecursive(SOURCE_ICONS_DIR, publicDir);
634
+ console.log(`${c.green}✔ ${copied} ícones copiados para "${publicDir}".${c.reset}\n`);
635
+ } catch (err) {
636
+ console.warn(`${c.yellow}⚠️ Não foi possível copiar os ícones: ${err.message}${c.reset}\n`);
637
+ }
638
+ }
639
+ }
531
640
 
532
- const code = generateInitFileContent(framework, prefix, tag, webBasePath, isTs);
641
+ // 3. Criação do arquivo de inicialização específico do framework
642
+ console.log(`${c.bright}📝 Gerando arquivo de inicialização para ${getFrameworkLabel(framework)}...${c.reset}`);
643
+ const code = generateInitFileContent(framework, prefix, tag, basePath, isTs);
533
644
 
534
645
  try {
535
646
  fs.mkdirSync(path.dirname(targetInitFile), { recursive: true });
@@ -539,21 +650,20 @@ async function runInit(options) {
539
650
  console.error(`${c.red}❌ Falha ao criar arquivo de inicialização:${c.reset}`, err.message);
540
651
  }
541
652
 
542
- // 3. Verificações de Projetos e Instruções Específicas
543
- console.log(`${c.cyan}${c.bright}🚀 Pronto! Como utilizar no seu projeto:${c.reset}\n`);
653
+ // 4. Instruções Finais
654
+ console.log(`${c.cyan}${c.bright}🚀 Tudo pronto! Como utilizar no seu projeto:${c.reset}\n`);
544
655
 
545
656
  if (framework === 'angular-legacy') {
546
657
  console.log(`1. Importe o ${c.yellow}IconsModule${c.reset} no seu ${c.yellow}src/app/app.module.ts${c.reset}:`);
547
658
  console.log(` ${c.green}import { IconsModule } from './icons.module';${c.reset}`);
548
659
  console.log(` ${c.green}@NgModule({ imports: [IconsModule, ...], ... })${c.reset}\n`);
549
- console.log(`2. Certifique-se de que "${assetsPath}" está em "assets" no seu ${c.yellow}angular.json${c.reset}.`);
550
660
  } else if (framework === 'angular') {
551
661
  console.log(`1. Adicione o provider no seu ${c.yellow}src/app/app.config.ts${c.reset}:`);
552
662
  console.log(` ${c.green}import { provideWhiteLabelIcons } from './icons.config';${c.reset}`);
553
663
  console.log(` ${c.green}export const appConfig: ApplicationConfig = { providers: [provideWhiteLabelIcons(), ...] };${c.reset}\n`);
554
664
  console.log(`2. Em componentes Standalone que usam a tag <${tag}>, inclua o schema:`);
555
665
  console.log(` ${c.green}import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';${c.reset}`);
556
- console.log(` ${c.green}@Component({ schemas: [CUSTOM_ELEMENTS_SCHEMA], ... })${c.reset}`);
666
+ console.log(` ${c.green}@Component({ schemas: [CUSTOM_ELEMENTS_SCHEMA], ... })${c.reset}\n`);
557
667
  } else if (framework === 'react') {
558
668
  console.log(`1. Importe o componente no seu JSX/TSX:`);
559
669
  console.log(` ${c.green}import { Icon } from './${path.basename(initFilePath, path.extname(initFilePath))}';${c.reset}`);
@@ -562,14 +672,12 @@ async function runInit(options) {
562
672
  console.log(`1. Registre o plugin no seu ${c.yellow}src/main.ts${c.reset} / ${c.yellow}src/main.js${c.reset}:`);
563
673
  console.log(` ${c.green}import { IconsPlugin } from './plugins/icons';${c.reset}`);
564
674
  console.log(` ${c.green}app.use(IconsPlugin);${c.reset}\n`);
565
- console.log(`2. Se usar Vite, adicione a tag aos custom elements no ${c.yellow}vite.config.ts${c.reset}:`);
566
- console.log(` ${c.gray}vue({ template: { compilerOptions: { isCustomElement: (tag) => tag.startsWith('${prefix}-') } } })${c.reset}`);
567
675
  } else {
568
676
  console.log(`1. Importe o arquivo gerado no seu ponto de entrada (ex: ${c.yellow}index.html${c.reset} ou ${c.yellow}main.js${c.reset}):`);
569
- console.log(` ${c.green}<script type="module" src="./${initFilePath}"></script>${c.reset}`);
677
+ console.log(` ${c.green}<script type="module" src="./${initFilePath}"></script>${c.reset}\n`);
570
678
  }
571
679
 
572
- console.log(`\n${c.bright}Uso nos Templates / HTML:${c.reset}`);
680
+ console.log(`${c.bright}Uso nos Templates HTML:${c.reset}`);
573
681
  console.log(` • Via Custom Element: ${c.green}<${tag} nome="bx-user" tamanho="24" cor="#3b82f6"></${tag}>${c.reset}`);
574
682
  console.log(` • Via Classe CSS: ${c.green}<i class="${prefix}-bx-user"></i>${c.reset}\n`);
575
683
  }
@@ -579,7 +687,7 @@ async function main() {
579
687
  const options = parseArgs(args);
580
688
 
581
689
  if (options.version) {
582
- console.log(`v${getPackageVersion()}`);
690
+ console.log(`v${PACKAGE_VERSION}`);
583
691
  process.exit(0);
584
692
  }
585
693
 
@@ -595,3 +703,4 @@ main().catch((err) => {
595
703
  console.error(`${c.red}Erro inesperado:${c.reset}`, err);
596
704
  process.exit(1);
597
705
  });
706
+
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@erikbernardo/white-label-icons",
3
- "version": "1.0.1",
3
+ "version": "1.0.2",
4
4
  "description": "Biblioteca de ícones agnóstica de framework e 100% white-label (Angular, React, Vue, Web Components) com suporte a prefixos customizados e CLI de setup.",
5
5
  "type": "module",
6
6
  "main": "./index.js",