@nuvler/cli 0.4.3 → 0.4.5

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/dist/nuvler.js CHANGED
@@ -7,7 +7,7 @@ import { fileURLToPath } from "node:url";
7
7
  import { createHash, randomUUID } from "node:crypto";
8
8
  import { build, normalizePath } from "vite";
9
9
  import { THEME_API_VERSION, THEME_RUNTIME_VERSION, THEME_SCHEMA_VERSION, THEME_SCHEMA_VERSION as THEME_SCHEMA_VERSION$1 } from "@nuvler/theme-sdk";
10
- import { satisfies, validRange } from "semver";
10
+ import { gt, inc, minVersion, satisfies, valid, validRange } from "semver";
11
11
  import { createInterface } from "node:readline/promises";
12
12
  import { stdin, stdout } from "node:process";
13
13
  import os, { tmpdir } from "node:os";
@@ -30,7 +30,7 @@ var __exportAll = (all, no_symbols) => {
30
30
  //#region src/commands/theme/create.ts
31
31
  var THEME_ID_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
32
32
  var NEW_THEME_VERSION = "0.1.0";
33
- var CLI_VERSION_RANGE = "^0.4.3";
33
+ var CLI_VERSION_RANGE = "^0.4.5";
34
34
  var SDK_VERSION_RANGE = "^1.2.2";
35
35
  var THEME_TEMPLATES = [
36
36
  {
@@ -110,6 +110,7 @@ async function customizeTemplate(directory, id, name, template) {
110
110
  build: "nuvler theme build --theme .",
111
111
  pack: "nuvler theme pack --theme .",
112
112
  publish: "nuvler theme publish --theme .",
113
+ upgrade: "nuvler theme upgrade --theme .",
113
114
  typecheck: "tsc -p tsconfig.json --noEmit"
114
115
  };
115
116
  packageMetadata.dependencies = {
@@ -161,6 +162,7 @@ async function customizeTemplate(directory, id, name, template) {
161
162
  "| `npm run build` | Gera `dist/theme.js`, CSS e assets |",
162
163
  "| `npm run pack` | Gera o artefato `.nuvler-theme.tgz` |",
163
164
  "| `npm run publish` | Compila e envia ao Theme Registry |",
165
+ "| `npm run upgrade` | Atualiza o Theme SDK e o CLI local |",
164
166
  "",
165
167
  "As opções completas estão em `npx nuvler theme <comando> --help`.",
166
168
  "",
@@ -174,8 +176,8 @@ async function customizeTemplate(directory, id, name, template) {
174
176
  "```",
175
177
  "",
176
178
  `O artefato será gerado em \`artifacts/${id}-${NEW_THEME_VERSION}.nuvler-theme.tgz\`.`,
177
- "Antes de publicar outra versão, incremente `version` em",
178
- "`nuvler.theme.json`, pois versões publicadas são imutáveis.",
179
+ "Antes de publicar outra versão, execute `npx nuvler theme version patch`,",
180
+ "pois versões publicadas são imutáveis.",
179
181
  "",
180
182
  "Por padrão, um projeto configurado publica um tema privado do tenant.",
181
183
  "Use `npx nuvler theme publish --visibility unlisted` ou",
@@ -7965,7 +7967,7 @@ async function walk(directory) {
7965
7967
  await visit(directory);
7966
7968
  return files;
7967
7969
  }
7968
- async function jsonFile(file) {
7970
+ async function jsonFile$1(file) {
7969
7971
  try {
7970
7972
  return JSON.parse(await readFile(file, "utf8"));
7971
7973
  } catch (error) {
@@ -8017,11 +8019,11 @@ function assetKind(extension) {
8017
8019
  return "image";
8018
8020
  }
8019
8021
  async function resolveImport(sourceFile, specifier, sourceDirectory) {
8020
- if (!specifier.startsWith(".")) return null;
8021
- const base = path.resolve(path.dirname(sourceFile), specifier);
8022
+ const bases = specifier.startsWith(".") ? [path.resolve(path.dirname(sourceFile), specifier)] : specifier.startsWith("@/") || specifier.startsWith("~/") ? [path.resolve(sourceDirectory, "src", specifier.slice(2)), path.resolve(sourceDirectory, specifier.slice(2))] : [];
8023
+ if (!bases.length) return null;
8022
8024
  const candidates = [
8023
- base,
8024
- ...[
8025
+ ...bases,
8026
+ ...bases.flatMap((base) => [
8025
8027
  ".ts",
8026
8028
  ".tsx",
8027
8029
  ".js",
@@ -8031,14 +8033,14 @@ async function resolveImport(sourceFile, specifier, sourceDirectory) {
8031
8033
  ".sass",
8032
8034
  ".less",
8033
8035
  ...ASSET_EXTENSIONS
8034
- ].map((extension) => `${base}${extension}`),
8035
- ...[
8036
+ ].map((extension) => `${base}${extension}`)),
8037
+ ...bases.flatMap((base) => [
8036
8038
  "index.ts",
8037
8039
  "index.tsx",
8038
8040
  "index.js",
8039
8041
  "index.jsx",
8040
8042
  "index.css"
8041
- ].map((entry) => path.join(base, entry))
8043
+ ].map((entry) => path.join(base, entry)))
8042
8044
  ];
8043
8045
  for (const candidate of candidates) {
8044
8046
  if (!inside$1(sourceDirectory, candidate)) continue;
@@ -8052,10 +8054,19 @@ function expressionClasses(expression) {
8052
8054
  if (ts.isStringLiteralLike(expression)) return expression.text.split(/\s+/).filter(Boolean);
8053
8055
  if (ts.isNoSubstitutionTemplateLiteral(expression)) return expression.text.split(/\s+/).filter(Boolean);
8054
8056
  if (ts.isPropertyAccessExpression(expression)) return [expression.name.text];
8057
+ if (ts.isElementAccessExpression(expression) && expression.argumentExpression && ts.isStringLiteralLike(expression.argumentExpression)) return [expression.argumentExpression.text];
8058
+ if (ts.isTemplateExpression(expression)) return [...expression.head.text.split(/\s+/), ...expression.templateSpans.flatMap((span) => [...expressionClasses(span.expression), ...span.literal.text.split(/\s+/)])].filter(Boolean);
8055
8059
  if (ts.isCallExpression(expression)) return expression.arguments.flatMap(expressionClasses);
8056
8060
  if (ts.isConditionalExpression(expression)) return [...expressionClasses(expression.whenTrue), ...expressionClasses(expression.whenFalse)];
8057
8061
  if (ts.isBinaryExpression(expression)) return [...expressionClasses(expression.left), ...expressionClasses(expression.right)];
8058
8062
  if (ts.isArrayLiteralExpression(expression)) return expression.elements.flatMap((item) => ts.isExpression(item) ? expressionClasses(item) : []);
8063
+ if (ts.isObjectLiteralExpression(expression)) return expression.properties.flatMap((property) => {
8064
+ if (ts.isPropertyAssignment(property) || ts.isShorthandPropertyAssignment(property)) {
8065
+ const name = property.name;
8066
+ return ts.isIdentifier(name) || ts.isStringLiteralLike(name) ? [name.text] : [];
8067
+ }
8068
+ return [];
8069
+ });
8059
8070
  return [];
8060
8071
  }
8061
8072
  function jsxClasses(attributes) {
@@ -8113,7 +8124,40 @@ function containsJsx(node) {
8113
8124
  function componentNodes(source) {
8114
8125
  const result = [];
8115
8126
  const defaultNames = /* @__PURE__ */ new Set();
8116
- for (const statement of source.statements) if (ts.isExportAssignment(statement) && ts.isIdentifier(statement.expression)) defaultNames.add(statement.expression.text);
8127
+ function referencedIdentifiers(expression) {
8128
+ if (ts.isIdentifier(expression)) {
8129
+ defaultNames.add(expression.text);
8130
+ return;
8131
+ }
8132
+ if (ts.isParenthesizedExpression(expression)) referencedIdentifiers(expression.expression);
8133
+ if (ts.isCallExpression(expression)) {
8134
+ for (const argument of expression.arguments) if (ts.isIdentifier(argument) || ts.isParenthesizedExpression(argument) || ts.isCallExpression(argument)) referencedIdentifiers(argument);
8135
+ }
8136
+ }
8137
+ for (const statement of source.statements) if (ts.isExportAssignment(statement)) referencedIdentifiers(statement.expression);
8138
+ function wrappedFunction(expression) {
8139
+ if (ts.isArrowFunction(expression) || ts.isFunctionExpression(expression)) return expression;
8140
+ if (ts.isParenthesizedExpression(expression)) return wrappedFunction(expression.expression);
8141
+ if (ts.isCallExpression(expression)) for (const argument of expression.arguments) {
8142
+ if (!ts.isExpression(argument)) continue;
8143
+ const candidate = wrappedFunction(argument);
8144
+ if (candidate) return candidate;
8145
+ }
8146
+ return null;
8147
+ }
8148
+ for (const statement of source.statements) {
8149
+ if (!ts.isExportAssignment(statement) || ts.isIdentifier(statement.expression)) continue;
8150
+ const node = wrappedFunction(statement.expression);
8151
+ if (!node || !containsJsx(node)) continue;
8152
+ const fallback = path.basename(source.fileName, path.extname(source.fileName));
8153
+ const name = ts.isFunctionExpression(node) && node.name?.text ? node.name.text : fallback;
8154
+ result.push({
8155
+ name,
8156
+ node,
8157
+ exported: true,
8158
+ defaultExport: true
8159
+ });
8160
+ }
8117
8161
  for (const statement of source.statements) {
8118
8162
  if (ts.isFunctionDeclaration(statement) && statement.body && containsJsx(statement)) {
8119
8163
  const modifiers = statement.modifiers ?? [];
@@ -8130,8 +8174,8 @@ function componentNodes(source) {
8130
8174
  const exported = statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) ?? false;
8131
8175
  for (const declaration of statement.declarationList.declarations) {
8132
8176
  if (!ts.isIdentifier(declaration.name) || !declaration.initializer) continue;
8133
- const initializer = declaration.initializer;
8134
- if (!(ts.isArrowFunction(initializer) || ts.isFunctionExpression(initializer)) || !containsJsx(initializer)) continue;
8177
+ const initializer = wrappedFunction(declaration.initializer);
8178
+ if (!initializer || !containsJsx(initializer)) continue;
8135
8179
  result.push({
8136
8180
  name: declaration.name.text,
8137
8181
  node: initializer,
@@ -8158,15 +8202,16 @@ function importsOf(source) {
8158
8202
  }
8159
8203
  function businessSignals(source, imports) {
8160
8204
  const signals = /* @__PURE__ */ new Set();
8205
+ const moduleBoundary = (module, term) => new RegExp(`(?:^|[/@._-])${term}(?:$|[/._-])`).test(module);
8161
8206
  for (const item of imports) {
8162
8207
  const module = item.module.toLowerCase();
8163
8208
  if (module.includes("axios")) signals.add("Axios/API externa");
8164
8209
  if (module.includes("react-router")) signals.add("React Router");
8165
8210
  if (module.includes("redux")) signals.add("Redux/store própria");
8166
8211
  if (module.includes("zustand")) signals.add("Zustand/store própria");
8167
- if (module.includes("auth")) signals.add("autenticação");
8168
- if (module.includes("checkout")) signals.add("checkout próprio");
8169
- if (module.includes("cart") || module.includes("carrinho")) signals.add("carrinho próprio");
8212
+ if (moduleBoundary(module, "auth") || moduleBoundary(module, "authentication")) signals.add("autenticação");
8213
+ if (moduleBoundary(module, "checkout")) signals.add("checkout próprio");
8214
+ if (moduleBoundary(module, "cart") || moduleBoundary(module, "carrinho")) signals.add("carrinho próprio");
8170
8215
  }
8171
8216
  function visit(node) {
8172
8217
  if (ts.isCallExpression(node)) {
@@ -8174,8 +8219,8 @@ function businessSignals(source, imports) {
8174
8219
  if (name === "fetch" || name.endsWith(".fetch")) signals.add("fetch/API externa");
8175
8220
  if (name.includes("useselector") || name.includes("usedispatch")) signals.add("Redux/store própria");
8176
8221
  if (name.includes("usestore")) signals.add("store própria");
8177
- if (name.includes("useauth")) signals.add("autenticação");
8178
- if (name.includes("usecart") || name.includes("usecarrinho")) signals.add("carrinho próprio");
8222
+ if (/(?:^|\.)useauth(?:entication)?(?:<|\()/.test(name)) signals.add("autenticação");
8223
+ if (/(?:^|\.)use(?:cart|carrinho)(?:<|\()/.test(name)) signals.add("carrinho próprio");
8179
8224
  }
8180
8225
  ts.forEachChild(node, visit);
8181
8226
  }
@@ -8250,6 +8295,34 @@ async function analyzeComponentFile(absoluteFile, sourceDirectory, framework) {
8250
8295
  styles
8251
8296
  };
8252
8297
  }
8298
+ function propertyName(node) {
8299
+ if (ts.isIdentifier(node) || ts.isStringLiteralLike(node) || ts.isNumericLiteral(node)) return node.text;
8300
+ return null;
8301
+ }
8302
+ function tailwindColors(configFile) {
8303
+ if (!configFile) return {};
8304
+ const content = ts.sys.readFile(configFile);
8305
+ if (!content) return {};
8306
+ const source = ts.createSourceFile(configFile, content, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
8307
+ const colors = {};
8308
+ function collect(object, prefix = "") {
8309
+ for (const property of object.properties) {
8310
+ if (!ts.isPropertyAssignment(property)) continue;
8311
+ const name = propertyName(property.name);
8312
+ if (!name) continue;
8313
+ const key = name === "DEFAULT" ? prefix : prefix ? `${prefix}-${name}` : name;
8314
+ if (!key) continue;
8315
+ if (ts.isStringLiteralLike(property.initializer) && /^(?:#|rgb|hsl)/i.test(property.initializer.text)) colors[key] = property.initializer.text;
8316
+ else if (ts.isObjectLiteralExpression(property.initializer)) collect(property.initializer, key);
8317
+ }
8318
+ }
8319
+ function visit(node) {
8320
+ if (ts.isPropertyAssignment(node) && propertyName(node.name) === "colors" && ts.isObjectLiteralExpression(node.initializer)) collect(node.initializer);
8321
+ ts.forEachChild(node, visit);
8322
+ }
8323
+ visit(source);
8324
+ return colors;
8325
+ }
8253
8326
  function tailwindAnalysis(files, dependencies, sourceDirectory) {
8254
8327
  const version = dependencies.tailwindcss ?? null;
8255
8328
  const match = version?.match(/(\d+)/);
@@ -8260,7 +8333,8 @@ function tailwindAnalysis(files, dependencies, sourceDirectory) {
8260
8333
  version,
8261
8334
  major: match ? Number(match[1]) : null,
8262
8335
  configFile: config ? portable$2(path.relative(sourceDirectory, config)) : null,
8263
- postcssFile: postcss ? portable$2(path.relative(sourceDirectory, postcss)) : null
8336
+ postcssFile: postcss ? portable$2(path.relative(sourceDirectory, postcss)) : null,
8337
+ colors: tailwindColors(config)
8264
8338
  };
8265
8339
  }
8266
8340
  function addAsset(target, absolutePath, sourceDirectory, referencedBy) {
@@ -8281,6 +8355,12 @@ function addAsset(target, absolutePath, sourceDirectory, referencedBy) {
8281
8355
  function cssAssetReferences(content) {
8282
8356
  return [...content.matchAll(/url\(\s*(["']?)([^)'"\s]+)\1\s*\)/gi)].map((match) => match[2]).filter((value) => !/^(?:data:|https?:|#)/i.test(value));
8283
8357
  }
8358
+ function colorLiterals(content) {
8359
+ return [...content.matchAll(/#[0-9a-f]{3,8}\b|(?:rgb|hsl)a?\([^)]*\)/gi)].map((match) => match[0]);
8360
+ }
8361
+ function cssImports(content) {
8362
+ return [...content.matchAll(/@import\s+(?:url\(\s*)?["']([^"']+)["']\s*\)?/gi)].map((match) => match[1]).filter((value) => !/^(?:https?:|data:|tailwindcss)/i.test(value));
8363
+ }
8284
8364
  async function analyzeReactProject(inputDirectory) {
8285
8365
  const sourceDirectory = path.resolve(inputDirectory);
8286
8366
  let details;
@@ -8290,7 +8370,7 @@ async function analyzeReactProject(inputDirectory) {
8290
8370
  throw new Error(`Projeto de origem não encontrado: ${sourceDirectory}`);
8291
8371
  }
8292
8372
  if (!details.isDirectory()) throw new Error(`A origem não é uma pasta: ${sourceDirectory}`);
8293
- const packageJson = await jsonFile(path.join(sourceDirectory, "package.json"));
8373
+ const packageJson = await jsonFile$1(path.join(sourceDirectory, "package.json"));
8294
8374
  const dependencies = dependenciesOf(packageJson);
8295
8375
  if (!dependencies.react) throw new Error("O projeto não declara React nas dependências.");
8296
8376
  const files = await walk(sourceDirectory);
@@ -8298,10 +8378,12 @@ async function analyzeReactProject(inputDirectory) {
8298
8378
  const tsxFiles = files.filter((file) => file.endsWith(".tsx"));
8299
8379
  if (!tsxFiles.length) throw new Error("Nenhum componente TSX foi encontrado. A V1 exige React com TypeScript.");
8300
8380
  const components = [];
8381
+ const detectedColors = /* @__PURE__ */ new Set();
8301
8382
  const ignoredFiles = [];
8302
8383
  const referencedStyles = /* @__PURE__ */ new Set();
8303
8384
  const assetMap = /* @__PURE__ */ new Map();
8304
8385
  for (const file of tsxFiles) {
8386
+ colorLiterals(await readFile(file, "utf8")).forEach((color) => detectedColors.add(color));
8305
8387
  const analyzed = await analyzeComponentFile(file, sourceDirectory, framework);
8306
8388
  components.push(...analyzed.components);
8307
8389
  analyzed.styles.forEach((style) => referencedStyles.add(path.resolve(style)));
@@ -8321,6 +8403,7 @@ async function analyzeReactProject(inputDirectory) {
8321
8403
  const styles = [];
8322
8404
  for (const file of files.filter((candidate) => STYLE_EXTENSIONS.has(path.extname(candidate).toLowerCase()))) {
8323
8405
  const content = await readFile(file, "utf8");
8406
+ colorLiterals(content).forEach((color) => detectedColors.add(color));
8324
8407
  const relativeFile = portable$2(path.relative(sourceDirectory, file));
8325
8408
  styles.push({
8326
8409
  file: relativeFile,
@@ -8331,6 +8414,19 @@ async function analyzeReactProject(inputDirectory) {
8331
8414
  });
8332
8415
  for (const reference of cssAssetReferences(content)) addAsset(assetMap, reference.startsWith("/") ? path.join(sourceDirectory, "public", reference.replace(/^\/+/, "")) : path.resolve(path.dirname(file), reference), sourceDirectory, relativeFile);
8333
8416
  }
8417
+ const stylesByPath = new Map(styles.map((style) => [path.resolve(style.absolutePath), style]));
8418
+ let importsChanged = true;
8419
+ while (importsChanged) {
8420
+ importsChanged = false;
8421
+ for (const style of styles.filter(({ imported }) => imported)) for (const reference of cssImports(style.content)) {
8422
+ const extension = path.extname(reference) ? "" : ".css";
8423
+ const imported = stylesByPath.get(path.resolve(path.dirname(style.absolutePath), `${reference}${extension}`));
8424
+ if (imported && !imported.imported) {
8425
+ imported.imported = true;
8426
+ importsChanged = true;
8427
+ }
8428
+ }
8429
+ }
8334
8430
  return {
8335
8431
  sourceDirectory,
8336
8432
  projectName: typeof packageJson.name === "string" && packageJson.name.trim() ? packageJson.name.trim() : path.basename(sourceDirectory),
@@ -8342,6 +8438,7 @@ async function analyzeReactProject(inputDirectory) {
8342
8438
  styles,
8343
8439
  assets: [...assetMap.values()],
8344
8440
  tailwind: tailwindAnalysis(files, dependencies, sourceDirectory),
8441
+ colorLiterals: [...detectedColors],
8345
8442
  ignoredFiles,
8346
8443
  warnings: styles.some(({ file }) => /\.(?:scss|sass|less)$/.test(file)) ? ["A V1 detecta Sass/Less, mas preserva automaticamente apenas CSS e CSS Modules."] : []
8347
8444
  };
@@ -8460,7 +8557,11 @@ function componentCorpus(component) {
8460
8557
  component.name,
8461
8558
  component.file,
8462
8559
  ...component.rootClasses,
8463
- ...component.jsx.flatMap(({ classes, text }) => [...classes, ...text])
8560
+ ...component.jsx.flatMap(({ tag, classes, text }) => [
8561
+ tag,
8562
+ ...classes,
8563
+ ...text
8564
+ ])
8464
8565
  ].join(" "));
8465
8566
  }
8466
8567
  function roleScore(component, rule) {
@@ -8482,9 +8583,9 @@ function roleScore(component, rule) {
8482
8583
  reasons.push(`JSX/classes contêm "${keyword}"`);
8483
8584
  }
8484
8585
  }
8485
- for (const tag of rule.tags ?? []) if (component.jsx.some((node) => normalized$1(node.tag) === tag)) {
8586
+ for (const tag of rule.tags ?? []) if (component.jsx.some((node) => node.depth === 0 && normalized$1(node.tag) === tag)) {
8486
8587
  score += 6;
8487
- reasons.push(`usa <${tag}>`);
8588
+ reasons.push(`raiz usa <${tag}>`);
8488
8589
  }
8489
8590
  if (component.page && rule.role === "HOME" && /(^|\/)(?:app\/)?page\.tsx$/.test(component.file)) {
8490
8591
  score += 7;
@@ -8503,7 +8604,7 @@ function roleScore(component, rule) {
8503
8604
  }
8504
8605
  }
8505
8606
  if (rule.role === "PRODUCT_GRID") {
8506
- if (component.jsx.some(({ classes }) => classes.some((item) => /grid|list/.test(normalized$1(item))))) {
8607
+ if ((corpus.includes("product") || corpus.includes("produto") || corpus.includes("catalog")) && component.jsx.some(({ classes }) => classes.some((item) => /grid|list/.test(normalized$1(item))))) {
8507
8608
  score += 5;
8508
8609
  reasons.push("possui estrutura de grid/lista");
8509
8610
  }
@@ -8515,8 +8616,14 @@ function roleScore(component, rule) {
8515
8616
  }
8516
8617
  }
8517
8618
  if (rule.role === "HERO" && component.text.some((text) => text.length > 20)) {
8518
- score += 2;
8519
- reasons.push("possui chamada textual de destaque");
8619
+ if (rule.keywords.some((keyword) => corpus.includes(normalized$1(keyword)))) {
8620
+ score += 2;
8621
+ reasons.push("possui chamada textual de destaque");
8622
+ }
8623
+ }
8624
+ if (/(^|\/)(?:ui|primitives)\//.test(file)) {
8625
+ score -= 8;
8626
+ reasons.push("componente primitivo de UI");
8520
8627
  }
8521
8628
  if (component.defaultExport) score += 1;
8522
8629
  return {
@@ -8959,9 +9066,10 @@ function copiedAssetFor(style, reference, plan, copied) {
8959
9066
  function preservedCss(plan, copied) {
8960
9067
  return plan.styles.map((style) => {
8961
9068
  let content = style.content;
8962
- content = content.replace(/@import\s+(["'])(?!https?:)(?!tailwindcss)([^"']+)\1\s*;?/gi, "");
9069
+ content = content.replace(/@import\s+(?:url\(\s*)?(["'])(?:https?:\/\/[^"']+)\1\s*\)?[^;]*;?/gi, "");
9070
+ content = content.replace(/@import\s+(?:url\(\s*)?(["'])(?!https?:)(?!tailwindcss)([^"']+)\1\s*\)?[^;\r\n]*(?:;|$)/gim, "");
8963
9071
  content = content.replace(/@tailwind\s+(?:base|components|utilities)\s*;?/gi, "");
8964
- content = content.replace(/@import\s+["']tailwindcss["']\s*;?/gi, "");
9072
+ content = content.replace(/@import\s+(?:url\(\s*)?["']tailwindcss["']\s*\)?[^;\r\n]*(?:;|$)/gim, "");
8965
9073
  content = content.replace(/:global\(([^)]+)\)/g, "$1");
8966
9074
  content = content.replace(/url\(\s*(["']?)([^)'"\s]+)\1\s*\)/gi, (full, _quote, reference) => {
8967
9075
  if (/^(?:data:|https?:|#)/i.test(reference)) return full;
@@ -8975,6 +9083,10 @@ function preservedCss(plan, copied) {
8975
9083
  return `/* Origem: ${style.file}${style.module ? " (CSS Module convertido para CSS comum)" : ""} */\n${content}`;
8976
9084
  }).join("\n\n");
8977
9085
  }
9086
+ function externalCssImports(plan) {
9087
+ const imports = plan.styles.flatMap(({ content }) => [...content.matchAll(/@import\s+(?:url\(\s*)?(["'])(?:https?:\/\/[^"']+)\1\s*\)?[^;]*;?/gi)].map((match) => match[0].trim()));
9088
+ return [...new Set(imports)].join("\n");
9089
+ }
8978
9090
  async function configureTailwind(plan, directory) {
8979
9091
  if (!plan.analysis.tailwind.detected) return "";
8980
9092
  const packageFile = path.join(directory, "package.json");
@@ -8990,7 +9102,8 @@ async function configureTailwind(plan, directory) {
8990
9102
  return "@import \"tailwindcss\";\n";
8991
9103
  }
8992
9104
  metadata.devDependencies.autoprefixer = plan.analysis.dependencies.autoprefixer || "^10.4.0";
8993
- await writeFile(path.join(directory, "tailwind.config.cjs"), "module.exports = { content: [\"./src/**/*.{ts,tsx}\"], theme: { extend: {} }, plugins: [] };\n", "utf8");
9105
+ const migratedColors = JSON.stringify(plan.analysis.tailwind.colors);
9106
+ await writeFile(path.join(directory, "tailwind.config.cjs"), `module.exports = { content: ["./src/**/*.{ts,tsx}"], theme: { extend: { colors: ${migratedColors} } }, plugins: [] };\n`, "utf8");
8994
9107
  await writeFile(path.join(directory, "postcss.config.cjs"), "module.exports = { plugins: { tailwindcss: {}, autoprefixer: {} } };\n", "utf8");
8995
9108
  await writeFile(packageFile, `${JSON.stringify(metadata, null, 2)}\n`, "utf8");
8996
9109
  return "@tailwind base;\n@tailwind components;\n@tailwind utilities;\n";
@@ -9028,7 +9141,7 @@ async function generateMigratedTheme(plan, directory) {
9028
9141
  writeFile(path.join(directory, "src/pages/StatePage.tsx"), statePageSource(), "utf8"),
9029
9142
  writeFile(path.join(directory, "src/definition.tsx"), definitionSource(plan), "utf8"),
9030
9143
  writeFile(path.join(directory, "src/theme.tsx"), themeSource(), "utf8"),
9031
- writeFile(path.join(directory, "src/styles/theme.css"), `${tailwindHeader}${baseCss(plan)}\n${preservedCss(plan, copiedAssets)}\n`, "utf8"),
9144
+ writeFile(path.join(directory, "src/styles/theme.css"), `${tailwindHeader}${externalCssImports(plan)}\n${baseCss(plan)}\n${preservedCss(plan, copiedAssets)}\n`, "utf8"),
9032
9145
  writeFile(path.join(directory, "src/styles.d.ts"), "declare module \"*.css\";\ndeclare module \"*.svg\";\n", "utf8")
9033
9146
  ]);
9034
9147
  const manifestFile = path.join(directory, "nuvler.theme.json");
@@ -9128,7 +9241,8 @@ function classProfile(component) {
9128
9241
  navigation: classesFor(component, [
9129
9242
  "nav",
9130
9243
  "menu",
9131
- "navigation"
9244
+ "navigation",
9245
+ "links"
9132
9246
  ], "", ["nav"]),
9133
9247
  title: classesFor(component, [
9134
9248
  "title",
@@ -9172,7 +9286,9 @@ function classProfile(component) {
9172
9286
  "body",
9173
9287
  "inner",
9174
9288
  "container",
9175
- "wrapper"
9289
+ "wrapper",
9290
+ "shell",
9291
+ "layout"
9176
9292
  ])
9177
9293
  };
9178
9294
  }
@@ -9182,24 +9298,173 @@ function selectedFor(analysis, role) {
9182
9298
  return (right.roles.find((candidate) => candidate.role === role)?.score ?? 0) - leftScore || Number(right.exported) - Number(left.exported);
9183
9299
  })[0];
9184
9300
  }
9185
- function customProperty(css, terms) {
9186
- for (const match of css.matchAll(/--([\w-]+)\s*:\s*(#[0-9a-f]{6})\b/gi)) {
9187
- const name = normalized(match[1]);
9188
- if (terms.some((term) => name.includes(term))) return match[2].toLowerCase();
9301
+ function byte(value) {
9302
+ return Math.max(0, Math.min(255, Math.round(value))).toString(16).padStart(2, "0");
9303
+ }
9304
+ function normalizedColor(input, variables = /* @__PURE__ */ new Map()) {
9305
+ let value = input.trim().toLowerCase();
9306
+ const variable = value.match(/^var\(\s*(--[\w-]+)/);
9307
+ if (variable) {
9308
+ const resolved = variables.get(variable[1]);
9309
+ return resolved && resolved !== input ? normalizedColor(resolved, variables) : null;
9310
+ }
9311
+ const named = {
9312
+ black: "#000000",
9313
+ white: "#ffffff"
9314
+ };
9315
+ if (named[value]) return named[value];
9316
+ const hex = value.match(/^#([0-9a-f]{3,8})\b/i)?.[1];
9317
+ if (hex) {
9318
+ if (hex.length === 3 || hex.length === 4) return `#${hex.slice(0, 3).split("").map((part) => part + part).join("")}`;
9319
+ return `#${hex.slice(0, 6)}`;
9320
+ }
9321
+ const rgb = value.match(/^rgba?\(\s*([\d.]+)%?[,\s]+([\d.]+)%?[,\s]+([\d.]+)%?/);
9322
+ if (rgb) {
9323
+ const factor = value.slice(0, value.indexOf(")")).includes("%") ? 2.55 : 1;
9324
+ return `#${byte(Number(rgb[1]) * factor)}${byte(Number(rgb[2]) * factor)}${byte(Number(rgb[3]) * factor)}`;
9325
+ }
9326
+ const hsl = value.match(/^hsla?\(\s*([\d.]+)(?:deg)?[,\s]+([\d.]+)%[,\s]+([\d.]+)%/);
9327
+ if (hsl) {
9328
+ const hue = (Number(hsl[1]) % 360 + 360) % 360;
9329
+ const saturation = Number(hsl[2]) / 100;
9330
+ const lightness = Number(hsl[3]) / 100;
9331
+ const chroma = (1 - Math.abs(2 * lightness - 1)) * saturation;
9332
+ const segment = hue / 60;
9333
+ const middle = chroma * (1 - Math.abs(segment % 2 - 1));
9334
+ const [red, green, blue] = segment < 1 ? [
9335
+ chroma,
9336
+ middle,
9337
+ 0
9338
+ ] : segment < 2 ? [
9339
+ middle,
9340
+ chroma,
9341
+ 0
9342
+ ] : segment < 3 ? [
9343
+ 0,
9344
+ chroma,
9345
+ middle
9346
+ ] : segment < 4 ? [
9347
+ 0,
9348
+ middle,
9349
+ chroma
9350
+ ] : segment < 5 ? [
9351
+ middle,
9352
+ 0,
9353
+ chroma
9354
+ ] : [
9355
+ chroma,
9356
+ 0,
9357
+ middle
9358
+ ];
9359
+ const offset = lightness - chroma / 2;
9360
+ return `#${byte((red + offset) * 255)}${byte((green + offset) * 255)}${byte((blue + offset) * 255)}`;
9189
9361
  }
9190
9362
  return null;
9191
9363
  }
9192
- function frequentColors(css) {
9364
+ function cssVariables(css) {
9365
+ const variables = /* @__PURE__ */ new Map();
9366
+ for (const match of css.matchAll(/(--[\w-]+)\s*:\s*([^;}]+)/gi)) variables.set(match[1].toLowerCase(), match[2].trim());
9367
+ return variables;
9368
+ }
9369
+ function customProperty(css, terms, variables) {
9370
+ const candidates = [];
9371
+ for (const match of css.matchAll(/--([\w-]+)\s*:\s*([^;}]+)/gi)) {
9372
+ const name = normalized(match[1]);
9373
+ const color = normalizedColor(match[2], variables);
9374
+ if (!color) continue;
9375
+ const score = Math.max(...terms.map((term) => name === term ? 100 : name.startsWith(`${term}-`) || name.endsWith(`-${term}`) ? 60 : name.includes(term) ? 20 : 0));
9376
+ if (score) candidates.push({
9377
+ color,
9378
+ score
9379
+ });
9380
+ }
9381
+ return candidates.sort((left, right) => right.score - left.score)[0]?.color ?? null;
9382
+ }
9383
+ function frequentColors(css, literals, variables) {
9193
9384
  const counts = /* @__PURE__ */ new Map();
9194
- for (const match of css.matchAll(/#[0-9a-f]{6}\b/gi)) {
9195
- const color = match[0].toLowerCase();
9385
+ const candidates = [...css.matchAll(/#[0-9a-f]{3,8}\b|(?:rgb|hsl)a?\([^)]*\)/gi)].map((match) => match[0]);
9386
+ for (const candidate of [...candidates, ...literals]) {
9387
+ const color = normalizedColor(candidate, variables);
9388
+ if (!color) continue;
9196
9389
  counts.set(color, (counts.get(color) ?? 0) + 1);
9197
9390
  }
9198
9391
  return [...counts.entries()].sort((left, right) => right[1] - left[1]).map(([color]) => color);
9199
9392
  }
9200
- function inferredTokens(analysis) {
9393
+ function ruleColor(css, component, property, variables) {
9394
+ if (!component) return null;
9395
+ const classes = new Set(component.jsx.flatMap((node) => node.classes).filter((name) => /^[a-z_-][\w-]*$/i.test(name)));
9396
+ for (const match of css.matchAll(/([^{}]+)\{([^{}]+)\}/g)) {
9397
+ const selector = match[1];
9398
+ if (![...classes].some((name) => new RegExp(`\\.${name}(?![\\w-])`).test(selector))) continue;
9399
+ const declaration = [...match[2].matchAll(new RegExp(`(?:^|;)\\s*${property}\\s*:\\s*([^;!]+)`, "gi"))].at(-1);
9400
+ const color = declaration ? normalizedColor(declaration[1], variables) : null;
9401
+ if (color) return color;
9402
+ }
9403
+ return null;
9404
+ }
9405
+ var TAILWIND_COLORS = {
9406
+ black: "#000000",
9407
+ white: "#ffffff",
9408
+ "slate-50": "#f8fafc",
9409
+ "slate-200": "#e2e8f0",
9410
+ "slate-500": "#64748b",
9411
+ "slate-900": "#0f172a",
9412
+ "gray-50": "#f9fafb",
9413
+ "gray-200": "#e5e7eb",
9414
+ "gray-500": "#6b7280",
9415
+ "gray-900": "#111827",
9416
+ "red-500": "#ef4444",
9417
+ "red-600": "#dc2626",
9418
+ "orange-500": "#f97316",
9419
+ "amber-500": "#f59e0b",
9420
+ "yellow-500": "#eab308",
9421
+ "green-500": "#22c55e",
9422
+ "emerald-500": "#10b981",
9423
+ "teal-500": "#14b8a6",
9424
+ "cyan-500": "#06b6d4",
9425
+ "sky-500": "#0ea5e9",
9426
+ "blue-500": "#3b82f6",
9427
+ "blue-600": "#2563eb",
9428
+ "blue-900": "#1e3a8a",
9429
+ "indigo-500": "#6366f1",
9430
+ "violet-500": "#8b5cf6",
9431
+ "purple-500": "#a855f7",
9432
+ "pink-500": "#ec4899"
9433
+ };
9434
+ function tailwindNodeColor(analysis, nodes, prefix) {
9435
+ const palette = {
9436
+ ...TAILWIND_COLORS,
9437
+ ...analysis.tailwind.colors
9438
+ };
9439
+ for (const original of nodes.flatMap((node) => node.classes)) {
9440
+ const utility = original.split(":").at(-1) ?? original;
9441
+ if (!utility.startsWith(`${prefix}-`)) continue;
9442
+ const name = utility.slice(prefix.length + 1);
9443
+ const arbitrary = name.match(/^\[(.+)\](?:\/.+)?$/)?.[1]?.replaceAll("_", " ");
9444
+ const color = arbitrary ? normalizedColor(arbitrary) : normalizedColor(palette[name] ?? "");
9445
+ if (color) return color;
9446
+ }
9447
+ return null;
9448
+ }
9449
+ function tailwindColor(analysis, component, prefix) {
9450
+ return component ? tailwindNodeColor(analysis, component.jsx, prefix) : null;
9451
+ }
9452
+ function actionColor(analysis, component, prefix) {
9453
+ if (!component) return null;
9454
+ return tailwindNodeColor(analysis, component.jsx.filter(({ tag }) => ["a", "button"].includes(normalized(tag))), prefix);
9455
+ }
9456
+ function contrastColor(background) {
9457
+ const channels = [
9458
+ background.slice(1, 3),
9459
+ background.slice(3, 5),
9460
+ background.slice(5, 7)
9461
+ ].map((channel) => Number.parseInt(channel, 16) / 255).map((channel) => channel <= .04045 ? channel / 12.92 : ((channel + .055) / 1.055) ** 2.4);
9462
+ return channels[0] * .2126 + channels[1] * .7152 + channels[2] * .0722 > .42 ? "#0f172a" : "#ffffff";
9463
+ }
9464
+ function inferredTokens(analysis, selected) {
9201
9465
  const css = analysis.styles.filter(({ imported }) => imported).map(({ content }) => content).join("\n");
9202
- const nonNeutral = frequentColors(css).filter((color) => ![
9466
+ const variables = cssVariables(css);
9467
+ const nonNeutral = frequentColors(css, analysis.colorLiterals, variables).filter((color) => ![
9203
9468
  "#ffffff",
9204
9469
  "#000000",
9205
9470
  "#f8fafc",
@@ -9209,55 +9474,60 @@ function inferredTokens(analysis) {
9209
9474
  ].includes(color));
9210
9475
  const widths = [...css.matchAll(/max-width\s*:\s*(\d{3,4})px/gi)].map((match) => Number(match[1])).filter((value) => value >= 960 && value <= 1600);
9211
9476
  const radii = [...css.matchAll(/border-radius\s*:\s*(\d{1,2})px/gi)].map((match) => Number(match[1])).filter((value) => value >= 0 && value <= 32);
9212
- const primary = customProperty(css, [
9477
+ const component = (role) => selected[role]?.component;
9478
+ const primary = actionColor(analysis, component("HERO"), "bg") ?? actionColor(analysis, component("HEADER"), "bg") ?? customProperty(css, [
9213
9479
  "primary",
9214
9480
  "brand",
9215
9481
  "principal"
9216
- ]) ?? nonNeutral[0] ?? "#1d4ed8";
9217
- const secondary = customProperty(css, ["secondary", "destaque"]) ?? nonNeutral[1] ?? "#f59e0b";
9482
+ ], variables) ?? ruleColor(css, component("PRODUCT_CARD"), "background(?:-color)?", variables) ?? tailwindColor(analysis, component("HERO"), "bg") ?? nonNeutral[0] ?? "#1d4ed8";
9483
+ const secondary = customProperty(css, ["secondary", "destaque"], variables) ?? nonNeutral.find((color) => color !== primary) ?? "#f59e0b";
9218
9484
  const background = customProperty(css, [
9219
9485
  "background",
9220
9486
  "fundo",
9221
- "bg"
9222
- ]) ?? "#f8fafc";
9487
+ "page-bg"
9488
+ ], variables) ?? ruleColor(css, component("HOME"), "background(?:-color)?", variables) ?? tailwindColor(analysis, component("HOME"), "bg") ?? "#f8fafc";
9223
9489
  const text = customProperty(css, [
9224
9490
  "foreground",
9225
9491
  "text",
9226
9492
  "texto"
9227
- ]) ?? "#0f172a";
9493
+ ], variables) ?? ruleColor(css, component("HOME"), "color", variables) ?? tailwindColor(analysis, component("HOME"), "text") ?? "#0f172a";
9228
9494
  const surface = customProperty(css, [
9229
9495
  "surface",
9230
9496
  "card",
9231
9497
  "panel"
9232
- ]) ?? "#ffffff";
9498
+ ], variables) ?? ruleColor(css, component("PRODUCT_CARD"), "background(?:-color)?", variables) ?? "#ffffff";
9499
+ const headerBackground = customProperty(css, ["header-background", "header-bg"], variables) ?? ruleColor(css, component("HEADER"), "background(?:-color)?", variables) ?? tailwindColor(analysis, component("HEADER"), "bg") ?? surface;
9500
+ const headerText = customProperty(css, ["header-text", "header-foreground"], variables) ?? ruleColor(css, component("HEADER"), "color", variables) ?? tailwindColor(analysis, component("HEADER"), "text") ?? text;
9501
+ const footerBackground = customProperty(css, ["footer-background", "footer-bg"], variables) ?? ruleColor(css, component("FOOTER"), "background(?:-color)?", variables) ?? tailwindColor(analysis, component("FOOTER"), "bg") ?? text;
9502
+ const footerText = customProperty(css, ["footer-text", "footer-foreground"], variables) ?? ruleColor(css, component("FOOTER"), "color", variables) ?? tailwindColor(analysis, component("FOOTER"), "text") ?? background;
9233
9503
  return {
9234
9504
  primary,
9235
- primaryText: customProperty(css, ["on-primary", "primary-text"]) ?? "#ffffff",
9505
+ primaryText: actionColor(analysis, component("HERO"), "text") ?? actionColor(analysis, component("HEADER"), "text") ?? customProperty(css, ["on-primary", "primary-text"], variables) ?? ruleColor(css, component("PRODUCT_CARD"), "color", variables) ?? contrastColor(primary),
9236
9506
  secondary,
9237
- secondaryText: customProperty(css, ["on-secondary", "secondary-text"]) ?? text,
9238
- accent: customProperty(css, ["accent", "destaque"]) ?? secondary,
9507
+ secondaryText: customProperty(css, ["on-secondary", "secondary-text"], variables) ?? contrastColor(secondary),
9508
+ accent: customProperty(css, ["accent", "destaque"], variables) ?? secondary,
9239
9509
  background,
9240
9510
  surface,
9241
9511
  surfaceAlt: customProperty(css, [
9242
9512
  "surface-alt",
9243
9513
  "surface-muted",
9244
9514
  "subtle"
9245
- ]) ?? background,
9515
+ ], variables) ?? background,
9246
9516
  text,
9247
9517
  textMuted: customProperty(css, [
9248
9518
  "muted",
9249
9519
  "text-secondary",
9250
9520
  "subtle-text"
9251
- ]) ?? "#64748b",
9521
+ ], variables) ?? "#64748b",
9252
9522
  border: customProperty(css, [
9253
9523
  "border",
9254
9524
  "line",
9255
9525
  "divider"
9256
- ]) ?? "#e2e8f0",
9257
- headerBackground: customProperty(css, ["header-background", "header-bg"]) ?? surface,
9258
- headerText: customProperty(css, ["header-text", "header-foreground"]) ?? text,
9259
- footerBackground: customProperty(css, ["footer-background", "footer-bg"]) ?? text,
9260
- footerText: customProperty(css, ["footer-text", "footer-foreground"]) ?? background,
9526
+ ], variables) ?? ruleColor(css, component("PRODUCT_CARD"), "border(?:-color)?", variables) ?? "#e2e8f0",
9527
+ headerBackground,
9528
+ headerText,
9529
+ footerBackground,
9530
+ footerText,
9261
9531
  containerWidth: widths[0] ?? 1200,
9262
9532
  borderRadius: radii[0] ?? 16
9263
9533
  };
@@ -9296,7 +9566,7 @@ function createMigrationPlan(analysis, options) {
9296
9566
  selected,
9297
9567
  styles: analysis.styles.filter(({ imported, file }) => imported && file.endsWith(".css")),
9298
9568
  assets: analysis.assets,
9299
- tokens: inferredTokens(analysis),
9569
+ tokens: inferredTokens(analysis, selected),
9300
9570
  warnings: [...new Set(warnings)]
9301
9571
  };
9302
9572
  }
@@ -9597,6 +9867,136 @@ async function themeValidate(options) {
9597
9867
  return performance;
9598
9868
  }
9599
9869
  //#endregion
9870
+ //#region src/commands/theme/upgrade.ts
9871
+ async function jsonFile(file, label) {
9872
+ try {
9873
+ return JSON.parse(await readFile(file, "utf8"));
9874
+ } catch (error) {
9875
+ throw new Error(`${label} inválido ou não encontrado: ${file}`, { cause: error });
9876
+ }
9877
+ }
9878
+ async function writeJson(file, value) {
9879
+ await writeFile(file, `${JSON.stringify(value, null, 2)}\n`, "utf8");
9880
+ }
9881
+ function exactVersion(input, label) {
9882
+ const version = valid(input.trim());
9883
+ if (!version) throw new Error(`${label} deve ser "latest" ou uma versão SemVer exata.`);
9884
+ return version;
9885
+ }
9886
+ async function npmInstall(directory, dependency, development) {
9887
+ const args = [
9888
+ "install",
9889
+ development ? "--save-dev" : "--save",
9890
+ dependency,
9891
+ "--ignore-scripts",
9892
+ "--no-audit",
9893
+ "--no-fund"
9894
+ ];
9895
+ await new Promise((resolve, reject) => {
9896
+ const child = spawn("npm", args, {
9897
+ cwd: directory,
9898
+ stdio: "inherit",
9899
+ shell: false
9900
+ });
9901
+ child.once("error", reject);
9902
+ child.once("exit", (code, signal) => {
9903
+ if (code === 0) resolve();
9904
+ else reject(/* @__PURE__ */ new Error(`npm install falhou${signal ? ` (${signal})` : ` com código ${code ?? "desconhecido"}`}.`));
9905
+ });
9906
+ });
9907
+ }
9908
+ function dependencyVersion(value, packageName) {
9909
+ const version = value ? minVersion(value)?.version : null;
9910
+ if (!version) throw new Error(`O npm não registrou uma versão válida para ${packageName}.`);
9911
+ return version;
9912
+ }
9913
+ function nextThemeVersion(current, release) {
9914
+ const requested = release.trim().toLowerCase();
9915
+ const next = [
9916
+ "patch",
9917
+ "minor",
9918
+ "major"
9919
+ ].includes(requested) ? inc(current, requested) : valid(requested);
9920
+ if (!next) throw new Error("Versão inválida. Use patch, minor, major ou uma versão SemVer exata.");
9921
+ if (!gt(next, current)) throw new Error(`A nova versão (${next}) precisa ser maior que a atual (${current}).`);
9922
+ return next;
9923
+ }
9924
+ async function themeVersion(options) {
9925
+ const directory = path.resolve(options.themeDirectory);
9926
+ const manifestFile = path.join(directory, "nuvler.theme.json");
9927
+ const packageFile = path.join(directory, "package.json");
9928
+ const lockFile = path.join(directory, "package-lock.json");
9929
+ const manifest = ThemeManifestSchema.parse(await jsonFile(manifestFile, "Manifesto do tema"));
9930
+ const packageMetadata = await jsonFile(packageFile, "package.json");
9931
+ const version = nextThemeVersion(manifest.version, options.release);
9932
+ manifest.version = version;
9933
+ packageMetadata.version = version;
9934
+ let lockMetadata = null;
9935
+ try {
9936
+ lockMetadata = await jsonFile(lockFile, "package-lock.json");
9937
+ lockMetadata.version = version;
9938
+ if (lockMetadata.packages?.[""]) lockMetadata.packages[""].version = version;
9939
+ } catch (error) {
9940
+ if (error.cause && error.cause.code !== "ENOENT") throw error;
9941
+ }
9942
+ await Promise.all([
9943
+ writeJson(manifestFile, manifest),
9944
+ writeJson(packageFile, packageMetadata),
9945
+ ...lockMetadata ? [writeJson(lockFile, lockMetadata)] : []
9946
+ ]);
9947
+ console.log(`✓ Versão do tema: ${manifest.id}@${version}`);
9948
+ return version;
9949
+ }
9950
+ async function themeUpgrade(options) {
9951
+ const directory = path.resolve(options.themeDirectory);
9952
+ const manifestFile = path.join(directory, "nuvler.theme.json");
9953
+ const packageFile = path.join(directory, "package.json");
9954
+ const sdkTarget = options.sdk?.trim() || "latest";
9955
+ const cliTarget = options.cli?.trim() || "latest";
9956
+ const install = options.installDependencies !== false;
9957
+ const manifest = ThemeManifestSchema.parse(await jsonFile(manifestFile, "Manifesto do tema"));
9958
+ await jsonFile(packageFile, "package.json");
9959
+ if (!install && (sdkTarget === "latest" || cliTarget === "latest")) throw new Error("Com --skip-install, informe versões exatas em --sdk e --cli.");
9960
+ if (sdkTarget !== "latest") exactVersion(sdkTarget, "A versão do SDK");
9961
+ if (cliTarget !== "latest") exactVersion(cliTarget, "A versão do CLI");
9962
+ if (install) {
9963
+ await npmInstall(directory, `@nuvler/theme-sdk@${sdkTarget}`, false);
9964
+ await npmInstall(directory, `@nuvler/cli@${cliTarget}`, true);
9965
+ }
9966
+ const installedPackage = await jsonFile(packageFile, "package.json");
9967
+ const sdkVersion = install ? dependencyVersion(installedPackage.dependencies?.["@nuvler/theme-sdk"], "@nuvler/theme-sdk") : exactVersion(sdkTarget, "A versão do SDK");
9968
+ const cliVersion = install ? dependencyVersion(installedPackage.devDependencies?.["@nuvler/cli"], "@nuvler/cli") : exactVersion(cliTarget, "A versão do CLI");
9969
+ const sdkRange = `^${sdkVersion}`;
9970
+ const cliRange = `^${cliVersion}`;
9971
+ const updatedPackage = installedPackage;
9972
+ updatedPackage.dependencies = {
9973
+ ...updatedPackage.dependencies,
9974
+ "@nuvler/theme-sdk": sdkRange
9975
+ };
9976
+ updatedPackage.devDependencies = {
9977
+ ...updatedPackage.devDependencies,
9978
+ "@nuvler/cli": cliRange
9979
+ };
9980
+ manifest.sdkVersion = sdkRange;
9981
+ await Promise.all([writeJson(manifestFile, manifest), writeJson(packageFile, updatedPackage)]);
9982
+ let version = manifest.version;
9983
+ if (options.bump) version = await themeVersion({
9984
+ themeDirectory: directory,
9985
+ release: options.bump
9986
+ });
9987
+ console.log("");
9988
+ console.log(`✓ Theme SDK atualizado: ${sdkRange}`);
9989
+ console.log(`✓ CLI local atualizado: ${cliRange}`);
9990
+ console.log("✓ package.json e nuvler.theme.json sincronizados");
9991
+ if (!install) console.log("⚠ Instalação ignorada; regenere o lockfile com npm install.");
9992
+ console.log("");
9993
+ return {
9994
+ sdkVersion,
9995
+ cliVersion,
9996
+ themeVersion: version
9997
+ };
9998
+ }
9999
+ //#endregion
9600
10000
  //#region src/commands/auth.ts
9601
10001
  async function authLogin(options) {
9602
10002
  const apiUrl = options.apiUrl?.trim() || process.env.NUVLER_API_URL?.trim();
@@ -9625,7 +10025,7 @@ async function authLogout() {
9625
10025
  //#endregion
9626
10026
  //#region src/index.ts
9627
10027
  var program = new Command();
9628
- program.name("nuvler").description("Nuvler Theme Development CLI").version("0.4.3");
10028
+ program.name("nuvler").description("Nuvler Theme Development CLI").version("0.4.5");
9629
10029
  var theme = program.command("theme").description("Manage Nuvler themes");
9630
10030
  var auth = program.command("auth").description("Manage developer authentication");
9631
10031
  auth.command("login").requiredOption("--token <token>", "Developer token").option("--api-url <url>", "Nuvler API base URL (or use NUVLER_API_URL)").action(async (options) => {
@@ -9688,6 +10088,31 @@ theme.command("templates").description("List the templates available for theme c
9688
10088
  for (const template of THEME_TEMPLATES) console.log(` ${template.id.padEnd(16)} ${template.description}`);
9689
10089
  console.log("");
9690
10090
  });
10091
+ theme.command("upgrade").description("Update the local Theme SDK and CLI and synchronize the manifest").option("--theme <directory>", "Theme directory", ".").option("--sdk <version>", "Theme SDK version or latest", "latest").option("--cli <version>", "Local CLI version or latest", "latest").option("--bump <release>", "Also bump theme version: patch, minor, major or exact").option("--skip-install", "Only update metadata; requires exact --sdk and --cli versions").action(async (options) => {
10092
+ try {
10093
+ await themeUpgrade({
10094
+ themeDirectory: options.theme,
10095
+ sdk: options.sdk,
10096
+ cli: options.cli,
10097
+ bump: options.bump,
10098
+ installDependencies: !options.skipInstall
10099
+ });
10100
+ } catch (error) {
10101
+ console.error(`Erro: ${error instanceof Error ? error.message : "Erro desconhecido."}`);
10102
+ process.exitCode = 1;
10103
+ }
10104
+ });
10105
+ theme.command("version").description("Bump and synchronize the published theme version").argument("<release>", "patch, minor, major or an exact SemVer version").option("--theme <directory>", "Theme directory", ".").action(async (release, options) => {
10106
+ try {
10107
+ await themeVersion({
10108
+ themeDirectory: options.theme,
10109
+ release
10110
+ });
10111
+ } catch (error) {
10112
+ console.error(`Erro: ${error instanceof Error ? error.message : "Erro desconhecido."}`);
10113
+ process.exitCode = 1;
10114
+ }
10115
+ });
9691
10116
  theme.command("configure").description("Configure this theme project for an authorized tenant").option("--theme <directory>", "Theme directory", ".").option("--tenant <slug-or-id>", "Authorized tenant slug or ID").option("--key <connection-key>", "Nuvler connection key from the tenant panel").action(async (options) => {
9692
10117
  try {
9693
10118
  await themeConfigure({