@ngx-smz/ui-kit 21.10.0-next.25 → 21.10.0-next.26

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,134 @@
1
+ #!/usr/bin/env node
2
+ // CLI do tema do Design System SMZ (@ngx-smz/ui-kit).
3
+ //
4
+ // smz-theme build <arquivo-de-tema> [--out tema.css] [--export nome] [--full] [--scope seletor]
5
+ //
6
+ // Gera o CSS (variáveis --smz-*) de um arquivo de tema, para incluir nos estilos do app e ter o tema no primeiro
7
+ // paint, sem depender do runtime. O arquivo pode ser:
8
+ // .json o objeto de tema (mesmo formato de defineSmzTheme; ver tokens/theme.schema.json)
9
+ // .ts / .js / .mjs / .cjs um módulo que exporta o resultado de defineSmzTheme (ex.: src/app/app.theme.ts)
10
+ //
11
+ // Para módulos, `@ngx-smz/ui-kit` é trocado pelo motor em JS puro (tokens/theme-engine.cjs), então nada de Angular
12
+ // é carregado. A compilação usa o esbuild do próprio projeto (o Angular CLI já o instala).
13
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
14
+ import { createRequire } from 'node:module';
15
+ import { tmpdir } from 'node:os';
16
+ import { dirname, extname, join, resolve } from 'node:path';
17
+ import { fileURLToPath } from 'node:url';
18
+
19
+ const here = dirname(fileURLToPath(import.meta.url));
20
+ const enginePath = join(here, '..', 'tokens', 'theme-engine.cjs');
21
+ const require = createRequire(import.meta.url);
22
+
23
+ function fail(message) {
24
+ console.error(`smz-theme: ${message}`);
25
+ process.exit(1);
26
+ }
27
+
28
+ function usage() {
29
+ console.log([
30
+ 'Uso: smz-theme build <arquivo-de-tema> [opções]',
31
+ '',
32
+ ' --out <arquivo> grava o CSS no arquivo (padrão: saída padrão)',
33
+ ' --export <nome> nome do export do tema no módulo (padrão: o primeiro export que for um tema)',
34
+ ' --full emite todas as variáveis, e não só as que diferem do preset padrão',
35
+ ' --scope <seletor> aplica o tema a um contêiner em vez de :root',
36
+ ].join('\n'));
37
+ }
38
+
39
+ function parseArgs(argv) {
40
+ const options = { positional: [] };
41
+ for (let index = 0; index < argv.length; index += 1) {
42
+ const arg = argv[index];
43
+ if (arg === '--full') options.full = true;
44
+ else if (arg === '--help' || arg === '-h') options.help = true;
45
+ else if (arg === '--out' || arg === '--export' || arg === '--scope') {
46
+ index += 1;
47
+ if (argv[index] == null) fail(`falta o valor de ${arg}`);
48
+ options[arg.slice(2)] = argv[index];
49
+ } else if (arg.startsWith('--')) fail(`opção desconhecida: ${arg}`);
50
+ else options.positional.push(arg);
51
+ }
52
+
53
+ return options;
54
+ }
55
+
56
+ const isTheme = (value) => value != null && typeof value === 'object' && typeof value.overrides === 'object' && typeof value.name === 'string';
57
+
58
+ async function loadModuleTheme(file, exportName) {
59
+ let esbuild;
60
+ try {
61
+ esbuild = createRequire(join(process.cwd(), 'package.json'))('esbuild');
62
+ } catch {
63
+ fail('o esbuild não foi encontrado no projeto. Instale-o (npm i -D esbuild) ou use um tema em .json.');
64
+ }
65
+ const outdir = mkdtempSync(join(tmpdir(), 'smz-theme-'));
66
+ const outfile = join(outdir, 'theme.cjs');
67
+ try {
68
+ await esbuild.build({
69
+ entryPoints: [file],
70
+ bundle: true,
71
+ platform: 'node',
72
+ format: 'cjs',
73
+ outfile,
74
+ logLevel: 'silent',
75
+ plugins: [{
76
+ name: 'smz-theme-engine',
77
+ setup(build) {
78
+ build.onResolve({ filter: /^@ngx-smz\/ui-kit$/ }, () => ({ path: enginePath }));
79
+ },
80
+ }],
81
+ });
82
+ const exported = require(outfile);
83
+ const candidates = exportName != null ? [exported[exportName]] : [exported.default, ...Object.values(exported)];
84
+ const theme = candidates.find(isTheme);
85
+ if (theme == null) {
86
+ fail(exportName != null
87
+ ? `o export "${exportName}" de ${file} não é um tema (resultado de defineSmzTheme).`
88
+ : `${file} não exporta um tema (resultado de defineSmzTheme).`);
89
+ }
90
+
91
+ return theme;
92
+ } finally {
93
+ rmSync(outdir, { recursive: true, force: true });
94
+ }
95
+ }
96
+
97
+ function loadJsonTheme(file, engine) {
98
+ const { $schema: _schema, extends: parent, ...definition } = JSON.parse(readFileSync(file, 'utf8'));
99
+ if (parent != null && parent !== 'default') fail(`preset desconhecido em "extends": ${parent}`);
100
+
101
+ return engine.defineSmzTheme(definition);
102
+ }
103
+
104
+ async function build(options) {
105
+ const [input] = options.positional;
106
+ if (input == null) {
107
+ usage();
108
+ process.exit(1);
109
+ }
110
+ const file = resolve(process.cwd(), input);
111
+ const engine = require(enginePath);
112
+ let theme;
113
+ try {
114
+ theme = extname(file) === '.json' ? loadJsonTheme(file, engine) : await loadModuleTheme(file, options.export);
115
+ } catch (error) {
116
+ fail(error instanceof Error ? error.message : String(error));
117
+ }
118
+ for (const warning of engine.smzThemeCssBlocks(theme, { full: options.full }).warnings) console.error(`smz-theme: aviso: ${warning}`);
119
+ const css = `/* Tema "${theme.name}" gerado por smz-theme build. Não edite: altere o arquivo de tema e gere de novo. */\n${engine.smzThemeToCss(theme, { full: options.full, scope: options.scope })}`;
120
+ if (options.out != null) {
121
+ writeFileSync(resolve(process.cwd(), options.out), css);
122
+ console.error(`smz-theme: ${options.out} gravado.`);
123
+ } else {
124
+ process.stdout.write(css);
125
+ }
126
+ }
127
+
128
+ const [command, ...rest] = process.argv.slice(2);
129
+ const options = parseArgs(rest);
130
+ if (command === 'build' && !options.help) await build(options);
131
+ else {
132
+ usage();
133
+ process.exit(command == null || command === 'help' || options.help ? 0 : 1);
134
+ }