@nuvler/cli 0.3.0 → 0.4.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 +258 -38
- package/dist/api/client.js.map +1 -1
- package/dist/api/theme-registry.js.map +1 -1
- package/dist/commands/theme/create.js +73 -17
- package/dist/commands/theme/create.js.map +1 -1
- package/dist/commands/theme/migrate.js +117 -0
- package/dist/commands/theme/migrate.js.map +1 -0
- package/dist/config/developer-session.js.map +1 -1
- package/dist/index.js +28 -1
- package/dist/index.js.map +1 -1
- package/dist/migrate/analyzer.js +479 -0
- package/dist/migrate/analyzer.js.map +1 -0
- package/dist/migrate/asset-copier.js +40 -0
- package/dist/migrate/asset-copier.js.map +1 -0
- package/dist/migrate/classifier.js +107 -0
- package/dist/migrate/classifier.js.map +1 -0
- package/dist/migrate/generator.js +459 -0
- package/dist/migrate/generator.js.map +1 -0
- package/dist/migrate/transformer.js +134 -0
- package/dist/migrate/transformer.js.map +1 -0
- package/dist/migrate/types.js +2 -0
- package/dist/migrate/types.js.map +1 -0
- package/dist/migrate/validator.js +40 -0
- package/dist/migrate/validator.js.map +1 -0
- package/dist/nuvler.js +1559 -26
- package/dist/nuvler.js.map +1 -1
- package/dist/preview/launcher.js +8 -8
- package/dist/preview/launcher.js.map +1 -1
- package/dist/templates/nuvler-atelier/README.md +17 -1
- package/dist/templates/nuvler-atelier/package.json +1 -1
- package/dist/templates/nuvler-default/README.md +18 -4
- package/dist/templates/starter/README.md +18 -1
- package/dist/templates/starter/package.json +1 -1
- package/package.json +2 -1
- package/preview-host/vite.config.ts +1 -0
package/dist/nuvler.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { Command } from "commander";
|
|
3
3
|
import { existsSync } from "node:fs";
|
|
4
|
-
import { access, chmod, cp, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm, rmdir, stat,
|
|
4
|
+
import { access, chmod, copyFile, cp, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
import { fileURLToPath } from "node:url";
|
|
7
7
|
import { createHash, randomUUID } from "node:crypto";
|
|
@@ -13,6 +13,7 @@ import { stdin, stdout } from "node:process";
|
|
|
13
13
|
import os, { tmpdir } from "node:os";
|
|
14
14
|
import { spawn } from "node:child_process";
|
|
15
15
|
import { create } from "tar";
|
|
16
|
+
import ts from "typescript";
|
|
16
17
|
//#region \0rolldown/runtime.js
|
|
17
18
|
var __defProp = Object.defineProperty;
|
|
18
19
|
var __exportAll = (all, no_symbols) => {
|
|
@@ -28,7 +29,7 @@ var __exportAll = (all, no_symbols) => {
|
|
|
28
29
|
//#region src/commands/theme/create.ts
|
|
29
30
|
var THEME_ID_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
30
31
|
var NEW_THEME_VERSION = "0.1.0";
|
|
31
|
-
var CLI_VERSION_RANGE = "^0.
|
|
32
|
+
var CLI_VERSION_RANGE = "^0.4.0";
|
|
32
33
|
var SDK_VERSION_RANGE = "^1.1.0";
|
|
33
34
|
var THEME_TEMPLATES = [
|
|
34
35
|
{
|
|
@@ -128,7 +129,60 @@ async function customizeTemplate(directory, id, name, template) {
|
|
|
128
129
|
const definition = await readFile(definitionFile, "utf8");
|
|
129
130
|
await writeFile(definitionFile, definition.replaceAll("__NUVLER_THEME_ID__", id).replaceAll("__NUVLER_THEME_NAME__", name), "utf8");
|
|
130
131
|
}
|
|
131
|
-
const readme =
|
|
132
|
+
const readme = [
|
|
133
|
+
`# ${name}`,
|
|
134
|
+
"",
|
|
135
|
+
`Tema Nuvler criado a partir do template \`${template}\`.`,
|
|
136
|
+
"",
|
|
137
|
+
"## Primeiro uso",
|
|
138
|
+
"",
|
|
139
|
+
"```bash",
|
|
140
|
+
"npm install",
|
|
141
|
+
"npx nuvler theme configure --key CHAVE_COPIADA_DO_PAINEL",
|
|
142
|
+
"npm run validate",
|
|
143
|
+
"npm run dev",
|
|
144
|
+
"```",
|
|
145
|
+
"",
|
|
146
|
+
"A chave configura a API e a autenticação global. O projeto salva apenas",
|
|
147
|
+
"id, slug e nome do tenant em `.nuvler/config.json`, ignorado pelo Git. Não",
|
|
148
|
+
"crie um `.env` para API, token ou tenant.",
|
|
149
|
+
"",
|
|
150
|
+
"Edite `src/` e `nuvler.theme.json`. Não edite `dist` nem `artifacts`, pois",
|
|
151
|
+
"essas pastas são geradas pela CLI.",
|
|
152
|
+
"",
|
|
153
|
+
"## Comandos deste projeto",
|
|
154
|
+
"",
|
|
155
|
+
"| Comando | Finalidade |",
|
|
156
|
+
"| --- | --- |",
|
|
157
|
+
"| `npm run dev` | Inicia o preview com dados públicos da loja configurada |",
|
|
158
|
+
"| `npm run validate` | Valida manifesto, SDK, runtime, entrada e estilos |",
|
|
159
|
+
"| `npm run typecheck` | Verifica os tipos TypeScript |",
|
|
160
|
+
"| `npm run build` | Gera `dist/theme.js`, CSS e assets |",
|
|
161
|
+
"| `npm run pack` | Gera o artefato `.nuvler-theme.tgz` |",
|
|
162
|
+
"| `npm run publish` | Compila e envia ao Theme Registry |",
|
|
163
|
+
"",
|
|
164
|
+
"As opções completas estão em `npx nuvler theme <comando> --help`.",
|
|
165
|
+
"",
|
|
166
|
+
"## Build e publicação",
|
|
167
|
+
"",
|
|
168
|
+
"```bash",
|
|
169
|
+
"npm run typecheck",
|
|
170
|
+
"npm run build",
|
|
171
|
+
"npm run pack",
|
|
172
|
+
"npm run publish",
|
|
173
|
+
"```",
|
|
174
|
+
"",
|
|
175
|
+
`O artefato será gerado em \`artifacts/${id}-${NEW_THEME_VERSION}.nuvler-theme.tgz\`.`,
|
|
176
|
+
"Antes de publicar outra versão, incremente `version` em",
|
|
177
|
+
"`nuvler.theme.json`, pois versões publicadas são imutáveis.",
|
|
178
|
+
"",
|
|
179
|
+
"Por padrão, um projeto configurado publica um tema privado do tenant.",
|
|
180
|
+
"Use `npx nuvler theme publish --visibility unlisted` ou",
|
|
181
|
+
"`npx nuvler theme publish --visibility public` para outra visibilidade.",
|
|
182
|
+
"A opção `--official` é",
|
|
183
|
+
"reservada a uma sessão PLATFORM_ADMIN.",
|
|
184
|
+
""
|
|
185
|
+
].join("\n");
|
|
132
186
|
await writeFile(path.join(directory, "README.md"), readme, "utf8");
|
|
133
187
|
}
|
|
134
188
|
async function ensureEmptyTarget(directory) {
|
|
@@ -160,21 +214,24 @@ async function themeCreate(options) {
|
|
|
160
214
|
});
|
|
161
215
|
await rename(path.join(directory, "gitignore.template"), path.join(directory, ".gitignore"));
|
|
162
216
|
await customizeTemplate(directory, id, name, template);
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
217
|
+
if (!options.silent) {
|
|
218
|
+
console.log("");
|
|
219
|
+
console.log(`✓ Tema criado: ${name} (${id})`);
|
|
220
|
+
console.log(`✓ Template: ${template}`);
|
|
221
|
+
console.log(`✓ Pasta: ${directory}`);
|
|
222
|
+
console.log("");
|
|
223
|
+
console.log("Próximos passos:");
|
|
224
|
+
console.log(` cd ${path.relative(process.cwd(), directory) || "."}`);
|
|
225
|
+
console.log(" npm install");
|
|
226
|
+
console.log(" npx nuvler theme configure --key CHAVE_COPIADA_DO_PAINEL");
|
|
227
|
+
console.log(" npm run validate");
|
|
228
|
+
console.log(" npm run dev");
|
|
229
|
+
console.log(" npm run typecheck");
|
|
230
|
+
console.log(" npm run build");
|
|
231
|
+
console.log(" npm run pack");
|
|
232
|
+
console.log(" npm run publish");
|
|
233
|
+
console.log("");
|
|
234
|
+
}
|
|
178
235
|
}
|
|
179
236
|
//#endregion
|
|
180
237
|
//#region src/theme/artifact.ts
|
|
@@ -7171,17 +7228,15 @@ async function resolvePreviewHost() {
|
|
|
7171
7228
|
} catch {}
|
|
7172
7229
|
throw new Error("Preview host não encontrado no package da CLI nem no monorepo. Reinstale @nuvler/cli ou defina NUVLER_PREVIEW_HOST_DIR.");
|
|
7173
7230
|
}
|
|
7174
|
-
async function
|
|
7175
|
-
await unlink(file).catch(() => void 0);
|
|
7176
|
-
await rmdir(directory).catch(() => void 0);
|
|
7177
|
-
}
|
|
7178
|
-
async function runLocalPreview(contextFile, project, apiUrl, store, port) {
|
|
7231
|
+
async function runLocalPreview(contextFile, cacheDirectory, project, apiUrl, store, port) {
|
|
7179
7232
|
const previewHost = await resolvePreviewHost();
|
|
7180
7233
|
return new Promise((resolve, reject) => {
|
|
7181
7234
|
const child = spawn("npm", [
|
|
7182
7235
|
"run",
|
|
7183
7236
|
"dev",
|
|
7184
7237
|
"--",
|
|
7238
|
+
"--configLoader",
|
|
7239
|
+
"runner",
|
|
7185
7240
|
"--host",
|
|
7186
7241
|
"127.0.0.1",
|
|
7187
7242
|
"--port",
|
|
@@ -7194,6 +7249,7 @@ async function runLocalPreview(contextFile, project, apiUrl, store, port) {
|
|
|
7194
7249
|
env: {
|
|
7195
7250
|
...process.env,
|
|
7196
7251
|
NUVLER_THEME_CONTEXT_FILE: contextFile,
|
|
7252
|
+
NUVLER_PREVIEW_CACHE_DIR: cacheDirectory,
|
|
7197
7253
|
NUVLER_THEME_DIRECTORY: project.directory,
|
|
7198
7254
|
NUVLER_THEME_ENTRY: project.entryPath,
|
|
7199
7255
|
NUVLER_THEME_STYLES: JSON.stringify(project.stylePaths),
|
|
@@ -7231,14 +7287,18 @@ async function runLocalPreview(contextFile, project, apiUrl, store, port) {
|
|
|
7231
7287
|
async function launchPreview(context, project, options) {
|
|
7232
7288
|
const directory = await mkdtemp(path.join(tmpdir(), "nuvler-theme-"));
|
|
7233
7289
|
const contextFile = path.join(directory, "theme-context.json");
|
|
7290
|
+
const cacheDirectory = path.join(directory, "vite-cache");
|
|
7234
7291
|
try {
|
|
7235
7292
|
await writeFile(contextFile, JSON.stringify(context, null, 2), {
|
|
7236
7293
|
encoding: "utf8",
|
|
7237
7294
|
mode: 384
|
|
7238
7295
|
});
|
|
7239
|
-
await runLocalPreview(contextFile, project, options.apiUrl, options.store, options.port);
|
|
7296
|
+
await runLocalPreview(contextFile, cacheDirectory, project, options.apiUrl, options.store, options.port);
|
|
7240
7297
|
} finally {
|
|
7241
|
-
await
|
|
7298
|
+
await rm(directory, {
|
|
7299
|
+
recursive: true,
|
|
7300
|
+
force: true
|
|
7301
|
+
});
|
|
7242
7302
|
}
|
|
7243
7303
|
}
|
|
7244
7304
|
//#endregion
|
|
@@ -7833,6 +7893,1463 @@ async function themePublish(options) {
|
|
|
7833
7893
|
console.log("");
|
|
7834
7894
|
}
|
|
7835
7895
|
//#endregion
|
|
7896
|
+
//#region src/migrate/analyzer.ts
|
|
7897
|
+
var IGNORED_DIRECTORIES = /* @__PURE__ */ new Set([
|
|
7898
|
+
".git",
|
|
7899
|
+
".next",
|
|
7900
|
+
".nuxt",
|
|
7901
|
+
".output",
|
|
7902
|
+
".turbo",
|
|
7903
|
+
"artifacts",
|
|
7904
|
+
"build",
|
|
7905
|
+
"coverage",
|
|
7906
|
+
"dist",
|
|
7907
|
+
"node_modules",
|
|
7908
|
+
"out"
|
|
7909
|
+
]);
|
|
7910
|
+
var STYLE_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
7911
|
+
".css",
|
|
7912
|
+
".scss",
|
|
7913
|
+
".sass",
|
|
7914
|
+
".less"
|
|
7915
|
+
]);
|
|
7916
|
+
var ASSET_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
7917
|
+
".avif",
|
|
7918
|
+
".bmp",
|
|
7919
|
+
".eot",
|
|
7920
|
+
".gif",
|
|
7921
|
+
".ico",
|
|
7922
|
+
".jpeg",
|
|
7923
|
+
".jpg",
|
|
7924
|
+
".mp4",
|
|
7925
|
+
".ogg",
|
|
7926
|
+
".otf",
|
|
7927
|
+
".png",
|
|
7928
|
+
".svg",
|
|
7929
|
+
".ttf",
|
|
7930
|
+
".webm",
|
|
7931
|
+
".webp",
|
|
7932
|
+
".woff",
|
|
7933
|
+
".woff2"
|
|
7934
|
+
]);
|
|
7935
|
+
var MAX_SOURCE_FILES = 2e3;
|
|
7936
|
+
var MAX_SOURCE_BYTES = 2097152;
|
|
7937
|
+
function portable$2(file) {
|
|
7938
|
+
return file.split(path.sep).join("/");
|
|
7939
|
+
}
|
|
7940
|
+
function inside$1(root, candidate) {
|
|
7941
|
+
const relative = path.relative(root, candidate);
|
|
7942
|
+
return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
|
|
7943
|
+
}
|
|
7944
|
+
async function walk(directory) {
|
|
7945
|
+
const files = [];
|
|
7946
|
+
async function visit(current) {
|
|
7947
|
+
const entries = await readdir(current, { withFileTypes: true });
|
|
7948
|
+
for (const entry of entries) {
|
|
7949
|
+
if (entry.isSymbolicLink()) continue;
|
|
7950
|
+
if (entry.isDirectory() && IGNORED_DIRECTORIES.has(entry.name)) continue;
|
|
7951
|
+
const absolute = path.join(current, entry.name);
|
|
7952
|
+
if (entry.isDirectory()) await visit(absolute);
|
|
7953
|
+
else if (entry.isFile()) files.push(absolute);
|
|
7954
|
+
if (files.length > MAX_SOURCE_FILES) throw new Error(`O projeto excede o limite da V1 de ${MAX_SOURCE_FILES} arquivos analisáveis.`);
|
|
7955
|
+
}
|
|
7956
|
+
}
|
|
7957
|
+
await visit(directory);
|
|
7958
|
+
return files;
|
|
7959
|
+
}
|
|
7960
|
+
async function jsonFile(file) {
|
|
7961
|
+
try {
|
|
7962
|
+
return JSON.parse(await readFile(file, "utf8"));
|
|
7963
|
+
} catch (error) {
|
|
7964
|
+
throw new Error(`package.json inválido: ${file}`, { cause: error });
|
|
7965
|
+
}
|
|
7966
|
+
}
|
|
7967
|
+
function dependenciesOf(packageJson) {
|
|
7968
|
+
const result = {};
|
|
7969
|
+
for (const key of [
|
|
7970
|
+
"dependencies",
|
|
7971
|
+
"devDependencies",
|
|
7972
|
+
"peerDependencies"
|
|
7973
|
+
]) {
|
|
7974
|
+
const values = packageJson[key];
|
|
7975
|
+
if (!values || typeof values !== "object" || Array.isArray(values)) continue;
|
|
7976
|
+
for (const [name, version] of Object.entries(values)) if (typeof version === "string") result[name] = version;
|
|
7977
|
+
}
|
|
7978
|
+
return result;
|
|
7979
|
+
}
|
|
7980
|
+
function detectFramework(files, dependencies) {
|
|
7981
|
+
if (dependencies.next || files.some((file) => /^next\.config\./.test(path.basename(file)))) return "next";
|
|
7982
|
+
if (dependencies.vite || files.some((file) => /^vite\.config\./.test(path.basename(file)))) return "vite";
|
|
7983
|
+
throw new Error("Projeto não suportado pela V1: não foi possível identificar Next.js ou Vite.");
|
|
7984
|
+
}
|
|
7985
|
+
function detectSourceRoots(sourceDirectory, files) {
|
|
7986
|
+
const candidates = [
|
|
7987
|
+
"src",
|
|
7988
|
+
"app",
|
|
7989
|
+
"pages",
|
|
7990
|
+
"components"
|
|
7991
|
+
].filter((candidate) => files.some((file) => inside$1(path.join(sourceDirectory, candidate), file)));
|
|
7992
|
+
return candidates.length ? candidates : ["."];
|
|
7993
|
+
}
|
|
7994
|
+
function assetKind(extension) {
|
|
7995
|
+
if ([
|
|
7996
|
+
".woff",
|
|
7997
|
+
".woff2",
|
|
7998
|
+
".ttf",
|
|
7999
|
+
".otf",
|
|
8000
|
+
".eot"
|
|
8001
|
+
].includes(extension)) return "font";
|
|
8002
|
+
if ([
|
|
8003
|
+
".mp4",
|
|
8004
|
+
".webm",
|
|
8005
|
+
".ogg"
|
|
8006
|
+
].includes(extension)) return "media";
|
|
8007
|
+
if (extension === ".svg") return "svg";
|
|
8008
|
+
if (extension === ".ico") return "icon";
|
|
8009
|
+
return "image";
|
|
8010
|
+
}
|
|
8011
|
+
async function resolveImport(sourceFile, specifier, sourceDirectory) {
|
|
8012
|
+
if (!specifier.startsWith(".")) return null;
|
|
8013
|
+
const base = path.resolve(path.dirname(sourceFile), specifier);
|
|
8014
|
+
const candidates = [
|
|
8015
|
+
base,
|
|
8016
|
+
...[
|
|
8017
|
+
".ts",
|
|
8018
|
+
".tsx",
|
|
8019
|
+
".js",
|
|
8020
|
+
".jsx",
|
|
8021
|
+
".css",
|
|
8022
|
+
".scss",
|
|
8023
|
+
".sass",
|
|
8024
|
+
".less",
|
|
8025
|
+
...ASSET_EXTENSIONS
|
|
8026
|
+
].map((extension) => `${base}${extension}`),
|
|
8027
|
+
...[
|
|
8028
|
+
"index.ts",
|
|
8029
|
+
"index.tsx",
|
|
8030
|
+
"index.js",
|
|
8031
|
+
"index.jsx",
|
|
8032
|
+
"index.css"
|
|
8033
|
+
].map((entry) => path.join(base, entry))
|
|
8034
|
+
];
|
|
8035
|
+
for (const candidate of candidates) {
|
|
8036
|
+
if (!inside$1(sourceDirectory, candidate)) continue;
|
|
8037
|
+
try {
|
|
8038
|
+
if ((await stat(candidate)).isFile()) return candidate;
|
|
8039
|
+
} catch {}
|
|
8040
|
+
}
|
|
8041
|
+
return null;
|
|
8042
|
+
}
|
|
8043
|
+
function expressionClasses(expression) {
|
|
8044
|
+
if (ts.isStringLiteralLike(expression)) return expression.text.split(/\s+/).filter(Boolean);
|
|
8045
|
+
if (ts.isNoSubstitutionTemplateLiteral(expression)) return expression.text.split(/\s+/).filter(Boolean);
|
|
8046
|
+
if (ts.isPropertyAccessExpression(expression)) return [expression.name.text];
|
|
8047
|
+
if (ts.isCallExpression(expression)) return expression.arguments.flatMap(expressionClasses);
|
|
8048
|
+
if (ts.isConditionalExpression(expression)) return [...expressionClasses(expression.whenTrue), ...expressionClasses(expression.whenFalse)];
|
|
8049
|
+
if (ts.isBinaryExpression(expression)) return [...expressionClasses(expression.left), ...expressionClasses(expression.right)];
|
|
8050
|
+
if (ts.isArrayLiteralExpression(expression)) return expression.elements.flatMap((item) => ts.isExpression(item) ? expressionClasses(item) : []);
|
|
8051
|
+
return [];
|
|
8052
|
+
}
|
|
8053
|
+
function jsxClasses(attributes) {
|
|
8054
|
+
const classes = [];
|
|
8055
|
+
for (const property of attributes.properties) {
|
|
8056
|
+
if (!ts.isJsxAttribute(property) || property.name.getText() !== "className" || !property.initializer) continue;
|
|
8057
|
+
if (ts.isStringLiteral(property.initializer)) classes.push(...property.initializer.text.split(/\s+/));
|
|
8058
|
+
else if (ts.isJsxExpression(property.initializer) && property.initializer.expression) classes.push(...expressionClasses(property.initializer.expression));
|
|
8059
|
+
}
|
|
8060
|
+
return [...new Set(classes.filter(Boolean))];
|
|
8061
|
+
}
|
|
8062
|
+
function jsxTag(node) {
|
|
8063
|
+
return (ts.isJsxElement(node) ? node.openingElement.tagName : node.tagName).getText();
|
|
8064
|
+
}
|
|
8065
|
+
function jsxAttributes(node) {
|
|
8066
|
+
return ts.isJsxElement(node) ? node.openingElement.attributes : node.attributes;
|
|
8067
|
+
}
|
|
8068
|
+
function analyzeJsx(root) {
|
|
8069
|
+
const result = [];
|
|
8070
|
+
function visit(node, depth) {
|
|
8071
|
+
if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node)) {
|
|
8072
|
+
const attributes = jsxAttributes(node);
|
|
8073
|
+
const text = [];
|
|
8074
|
+
if (ts.isJsxElement(node)) {
|
|
8075
|
+
for (const child of node.children) if (ts.isJsxText(child) && child.text.trim()) text.push(child.text.trim().replace(/\s+/g, " "));
|
|
8076
|
+
}
|
|
8077
|
+
result.push({
|
|
8078
|
+
tag: jsxTag(node),
|
|
8079
|
+
depth,
|
|
8080
|
+
classes: jsxClasses(attributes),
|
|
8081
|
+
text,
|
|
8082
|
+
attributes: attributes.properties.filter(ts.isJsxAttribute).map((attribute) => attribute.name.getText())
|
|
8083
|
+
});
|
|
8084
|
+
ts.forEachChild(node, (child) => visit(child, depth + 1));
|
|
8085
|
+
return;
|
|
8086
|
+
}
|
|
8087
|
+
ts.forEachChild(node, (child) => visit(child, depth));
|
|
8088
|
+
}
|
|
8089
|
+
visit(root, 0);
|
|
8090
|
+
return result;
|
|
8091
|
+
}
|
|
8092
|
+
function containsJsx(node) {
|
|
8093
|
+
let found = false;
|
|
8094
|
+
function visit(child) {
|
|
8095
|
+
if (found) return;
|
|
8096
|
+
if (ts.isJsxElement(child) || ts.isJsxSelfClosingElement(child) || ts.isJsxFragment(child)) {
|
|
8097
|
+
found = true;
|
|
8098
|
+
return;
|
|
8099
|
+
}
|
|
8100
|
+
ts.forEachChild(child, visit);
|
|
8101
|
+
}
|
|
8102
|
+
visit(node);
|
|
8103
|
+
return found;
|
|
8104
|
+
}
|
|
8105
|
+
function componentNodes(source) {
|
|
8106
|
+
const result = [];
|
|
8107
|
+
const defaultNames = /* @__PURE__ */ new Set();
|
|
8108
|
+
for (const statement of source.statements) if (ts.isExportAssignment(statement) && ts.isIdentifier(statement.expression)) defaultNames.add(statement.expression.text);
|
|
8109
|
+
for (const statement of source.statements) {
|
|
8110
|
+
if (ts.isFunctionDeclaration(statement) && statement.body && containsJsx(statement)) {
|
|
8111
|
+
const modifiers = statement.modifiers ?? [];
|
|
8112
|
+
const fallback = path.basename(source.fileName, path.extname(source.fileName));
|
|
8113
|
+
const name = statement.name?.text || fallback;
|
|
8114
|
+
result.push({
|
|
8115
|
+
name,
|
|
8116
|
+
node: statement,
|
|
8117
|
+
exported: modifiers.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword),
|
|
8118
|
+
defaultExport: modifiers.some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword) || defaultNames.has(name)
|
|
8119
|
+
});
|
|
8120
|
+
}
|
|
8121
|
+
if (!ts.isVariableStatement(statement)) continue;
|
|
8122
|
+
const exported = statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) ?? false;
|
|
8123
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
8124
|
+
if (!ts.isIdentifier(declaration.name) || !declaration.initializer) continue;
|
|
8125
|
+
const initializer = declaration.initializer;
|
|
8126
|
+
if (!(ts.isArrowFunction(initializer) || ts.isFunctionExpression(initializer)) || !containsJsx(initializer)) continue;
|
|
8127
|
+
result.push({
|
|
8128
|
+
name: declaration.name.text,
|
|
8129
|
+
node: initializer,
|
|
8130
|
+
exported,
|
|
8131
|
+
defaultExport: defaultNames.has(declaration.name.text)
|
|
8132
|
+
});
|
|
8133
|
+
}
|
|
8134
|
+
}
|
|
8135
|
+
return result;
|
|
8136
|
+
}
|
|
8137
|
+
function importsOf(source) {
|
|
8138
|
+
return source.statements.filter(ts.isImportDeclaration).map((statement) => {
|
|
8139
|
+
const clause = statement.importClause;
|
|
8140
|
+
const names = [];
|
|
8141
|
+
if (clause?.name) names.push(clause.name.text);
|
|
8142
|
+
if (clause?.namedBindings && ts.isNamedImports(clause.namedBindings)) names.push(...clause.namedBindings.elements.map((item) => item.name.text));
|
|
8143
|
+
if (clause?.namedBindings && ts.isNamespaceImport(clause.namedBindings)) names.push(clause.namedBindings.name.text);
|
|
8144
|
+
return {
|
|
8145
|
+
module: statement.moduleSpecifier.text,
|
|
8146
|
+
names,
|
|
8147
|
+
typeOnly: clause?.isTypeOnly ?? false
|
|
8148
|
+
};
|
|
8149
|
+
});
|
|
8150
|
+
}
|
|
8151
|
+
function businessSignals(source, imports) {
|
|
8152
|
+
const signals = /* @__PURE__ */ new Set();
|
|
8153
|
+
for (const item of imports) {
|
|
8154
|
+
const module = item.module.toLowerCase();
|
|
8155
|
+
if (module.includes("axios")) signals.add("Axios/API externa");
|
|
8156
|
+
if (module.includes("react-router")) signals.add("React Router");
|
|
8157
|
+
if (module.includes("redux")) signals.add("Redux/store própria");
|
|
8158
|
+
if (module.includes("zustand")) signals.add("Zustand/store própria");
|
|
8159
|
+
if (module.includes("auth")) signals.add("autenticação");
|
|
8160
|
+
if (module.includes("checkout")) signals.add("checkout próprio");
|
|
8161
|
+
if (module.includes("cart") || module.includes("carrinho")) signals.add("carrinho próprio");
|
|
8162
|
+
}
|
|
8163
|
+
function visit(node) {
|
|
8164
|
+
if (ts.isCallExpression(node)) {
|
|
8165
|
+
const name = node.expression.getText(source).toLowerCase();
|
|
8166
|
+
if (name === "fetch" || name.endsWith(".fetch")) signals.add("fetch/API externa");
|
|
8167
|
+
if (name.includes("useselector") || name.includes("usedispatch")) signals.add("Redux/store própria");
|
|
8168
|
+
if (name.includes("usestore")) signals.add("store própria");
|
|
8169
|
+
if (name.includes("useauth")) signals.add("autenticação");
|
|
8170
|
+
if (name.includes("usecart") || name.includes("usecarrinho")) signals.add("carrinho próprio");
|
|
8171
|
+
}
|
|
8172
|
+
ts.forEachChild(node, visit);
|
|
8173
|
+
}
|
|
8174
|
+
visit(source);
|
|
8175
|
+
return [...signals];
|
|
8176
|
+
}
|
|
8177
|
+
function publicAssetFromAttribute(node, sourceDirectory) {
|
|
8178
|
+
if (![
|
|
8179
|
+
"src",
|
|
8180
|
+
"href",
|
|
8181
|
+
"poster"
|
|
8182
|
+
].includes(node.name.getText())) return null;
|
|
8183
|
+
if (!node.initializer || !ts.isStringLiteral(node.initializer)) return null;
|
|
8184
|
+
const value = node.initializer.text;
|
|
8185
|
+
if (!value.startsWith("/") || value.startsWith("//")) return null;
|
|
8186
|
+
return path.join(sourceDirectory, "public", value.replace(/^\/+/, ""));
|
|
8187
|
+
}
|
|
8188
|
+
function pageFile(relativeFile, framework) {
|
|
8189
|
+
if (framework === "next") return /(^|\/)app\/.*\/(?:page|layout)\.tsx$/.test(relativeFile) || /(^|\/)app\/(?:page|layout)\.tsx$/.test(relativeFile) || /(^|\/)pages\/(?!_)[^/]+\.tsx$/.test(relativeFile);
|
|
8190
|
+
return /(^|\/)(?:App|Home|Index|Landing)\.tsx$/i.test(relativeFile) || /(^|\/)pages\//.test(relativeFile);
|
|
8191
|
+
}
|
|
8192
|
+
async function analyzeComponentFile(absoluteFile, sourceDirectory, framework) {
|
|
8193
|
+
if ((await stat(absoluteFile)).size > MAX_SOURCE_BYTES) return {
|
|
8194
|
+
components: [],
|
|
8195
|
+
assets: [],
|
|
8196
|
+
styles: []
|
|
8197
|
+
};
|
|
8198
|
+
const content = await readFile(absoluteFile, "utf8");
|
|
8199
|
+
const source = ts.createSourceFile(absoluteFile, content, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
|
|
8200
|
+
const imports = importsOf(source);
|
|
8201
|
+
const relativeFile = portable$2(path.relative(sourceDirectory, absoluteFile));
|
|
8202
|
+
const styles = [];
|
|
8203
|
+
const assets = [];
|
|
8204
|
+
for (const item of imports) {
|
|
8205
|
+
const extension = path.extname(item.module).toLowerCase();
|
|
8206
|
+
const resolved = await resolveImport(absoluteFile, item.module, sourceDirectory);
|
|
8207
|
+
if (!resolved) continue;
|
|
8208
|
+
if (STYLE_EXTENSIONS.has(extension)) styles.push(resolved);
|
|
8209
|
+
if (ASSET_EXTENSIONS.has(extension)) assets.push(resolved);
|
|
8210
|
+
}
|
|
8211
|
+
function findPublicAssets(node) {
|
|
8212
|
+
if (ts.isJsxAttribute(node)) {
|
|
8213
|
+
const asset = publicAssetFromAttribute(node, sourceDirectory);
|
|
8214
|
+
if (asset) assets.push(asset);
|
|
8215
|
+
}
|
|
8216
|
+
ts.forEachChild(node, findPublicAssets);
|
|
8217
|
+
}
|
|
8218
|
+
findPublicAssets(source);
|
|
8219
|
+
const signals = businessSignals(source, imports);
|
|
8220
|
+
return {
|
|
8221
|
+
components: componentNodes(source).map(({ name, node, exported, defaultExport }, index) => {
|
|
8222
|
+
const jsx = analyzeJsx(node);
|
|
8223
|
+
return {
|
|
8224
|
+
id: `${relativeFile}#${name}-${index}`,
|
|
8225
|
+
name,
|
|
8226
|
+
file: relativeFile,
|
|
8227
|
+
exported,
|
|
8228
|
+
defaultExport,
|
|
8229
|
+
page: pageFile(relativeFile, framework),
|
|
8230
|
+
line: source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1,
|
|
8231
|
+
imports,
|
|
8232
|
+
styleImports: styles.map((file) => portable$2(path.relative(sourceDirectory, file))),
|
|
8233
|
+
assetImports: assets.map((file) => portable$2(path.relative(sourceDirectory, file))),
|
|
8234
|
+
jsx,
|
|
8235
|
+
rootClasses: jsx.find(({ depth }) => depth === 0)?.classes ?? jsx[0]?.classes ?? [],
|
|
8236
|
+
text: [...new Set(jsx.flatMap((item) => item.text))].slice(0, 30),
|
|
8237
|
+
businessSignals: signals,
|
|
8238
|
+
roles: []
|
|
8239
|
+
};
|
|
8240
|
+
}),
|
|
8241
|
+
assets,
|
|
8242
|
+
styles
|
|
8243
|
+
};
|
|
8244
|
+
}
|
|
8245
|
+
function tailwindAnalysis(files, dependencies, sourceDirectory) {
|
|
8246
|
+
const version = dependencies.tailwindcss ?? null;
|
|
8247
|
+
const match = version?.match(/(\d+)/);
|
|
8248
|
+
const config = files.find((file) => /^tailwind\.config\./.test(path.basename(file))) ?? null;
|
|
8249
|
+
const postcss = files.find((file) => /^postcss\.config\./.test(path.basename(file))) ?? null;
|
|
8250
|
+
return {
|
|
8251
|
+
detected: Boolean(version || config),
|
|
8252
|
+
version,
|
|
8253
|
+
major: match ? Number(match[1]) : null,
|
|
8254
|
+
configFile: config ? portable$2(path.relative(sourceDirectory, config)) : null,
|
|
8255
|
+
postcssFile: postcss ? portable$2(path.relative(sourceDirectory, postcss)) : null
|
|
8256
|
+
};
|
|
8257
|
+
}
|
|
8258
|
+
function addAsset(target, absolutePath, sourceDirectory, referencedBy) {
|
|
8259
|
+
if (!inside$1(sourceDirectory, absolutePath) || !ASSET_EXTENSIONS.has(path.extname(absolutePath).toLowerCase())) return;
|
|
8260
|
+
const key = path.resolve(absolutePath);
|
|
8261
|
+
const existing = target.get(key);
|
|
8262
|
+
if (existing) {
|
|
8263
|
+
if (!existing.referencedBy.includes(referencedBy)) existing.referencedBy.push(referencedBy);
|
|
8264
|
+
return;
|
|
8265
|
+
}
|
|
8266
|
+
target.set(key, {
|
|
8267
|
+
file: portable$2(path.relative(sourceDirectory, key)),
|
|
8268
|
+
absolutePath: key,
|
|
8269
|
+
kind: assetKind(path.extname(key).toLowerCase()),
|
|
8270
|
+
referencedBy: [referencedBy]
|
|
8271
|
+
});
|
|
8272
|
+
}
|
|
8273
|
+
function cssAssetReferences(content) {
|
|
8274
|
+
return [...content.matchAll(/url\(\s*(["']?)([^)'"\s]+)\1\s*\)/gi)].map((match) => match[2]).filter((value) => !/^(?:data:|https?:|#)/i.test(value));
|
|
8275
|
+
}
|
|
8276
|
+
async function analyzeReactProject(inputDirectory) {
|
|
8277
|
+
const sourceDirectory = path.resolve(inputDirectory);
|
|
8278
|
+
let details;
|
|
8279
|
+
try {
|
|
8280
|
+
details = await stat(sourceDirectory);
|
|
8281
|
+
} catch {
|
|
8282
|
+
throw new Error(`Projeto de origem não encontrado: ${sourceDirectory}`);
|
|
8283
|
+
}
|
|
8284
|
+
if (!details.isDirectory()) throw new Error(`A origem não é uma pasta: ${sourceDirectory}`);
|
|
8285
|
+
const packageJson = await jsonFile(path.join(sourceDirectory, "package.json"));
|
|
8286
|
+
const dependencies = dependenciesOf(packageJson);
|
|
8287
|
+
if (!dependencies.react) throw new Error("O projeto não declara React nas dependências.");
|
|
8288
|
+
const files = await walk(sourceDirectory);
|
|
8289
|
+
const framework = detectFramework(files, dependencies);
|
|
8290
|
+
const tsxFiles = files.filter((file) => file.endsWith(".tsx"));
|
|
8291
|
+
if (!tsxFiles.length) throw new Error("Nenhum componente TSX foi encontrado. A V1 exige React com TypeScript.");
|
|
8292
|
+
const components = [];
|
|
8293
|
+
const ignoredFiles = [];
|
|
8294
|
+
const referencedStyles = /* @__PURE__ */ new Set();
|
|
8295
|
+
const assetMap = /* @__PURE__ */ new Map();
|
|
8296
|
+
for (const file of tsxFiles) {
|
|
8297
|
+
const analyzed = await analyzeComponentFile(file, sourceDirectory, framework);
|
|
8298
|
+
components.push(...analyzed.components);
|
|
8299
|
+
analyzed.styles.forEach((style) => referencedStyles.add(path.resolve(style)));
|
|
8300
|
+
analyzed.assets.forEach((asset) => addAsset(assetMap, asset, sourceDirectory, portable$2(path.relative(sourceDirectory, file))));
|
|
8301
|
+
}
|
|
8302
|
+
for (const file of files.filter((candidate) => candidate.endsWith(".ts") && !candidate.endsWith(".d.ts"))) {
|
|
8303
|
+
if ((await stat(file)).size > MAX_SOURCE_BYTES) continue;
|
|
8304
|
+
const content = await readFile(file, "utf8");
|
|
8305
|
+
const source = ts.createSourceFile(file, content, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
8306
|
+
const signals = businessSignals(source, importsOf(source));
|
|
8307
|
+
if (!signals.length) continue;
|
|
8308
|
+
ignoredFiles.push({
|
|
8309
|
+
file: portable$2(path.relative(sourceDirectory, file)),
|
|
8310
|
+
reason: signals.join(", ")
|
|
8311
|
+
});
|
|
8312
|
+
}
|
|
8313
|
+
const styles = [];
|
|
8314
|
+
for (const file of files.filter((candidate) => STYLE_EXTENSIONS.has(path.extname(candidate).toLowerCase()))) {
|
|
8315
|
+
const content = await readFile(file, "utf8");
|
|
8316
|
+
const relativeFile = portable$2(path.relative(sourceDirectory, file));
|
|
8317
|
+
styles.push({
|
|
8318
|
+
file: relativeFile,
|
|
8319
|
+
absolutePath: file,
|
|
8320
|
+
module: /\.module\.(?:css|scss|sass|less)$/.test(file),
|
|
8321
|
+
imported: referencedStyles.has(path.resolve(file)) || /(^|\/)(?:global|globals|index|app)\.(?:css|scss|sass|less)$/.test(relativeFile),
|
|
8322
|
+
content
|
|
8323
|
+
});
|
|
8324
|
+
for (const reference of cssAssetReferences(content)) addAsset(assetMap, reference.startsWith("/") ? path.join(sourceDirectory, "public", reference.replace(/^\/+/, "")) : path.resolve(path.dirname(file), reference), sourceDirectory, relativeFile);
|
|
8325
|
+
}
|
|
8326
|
+
return {
|
|
8327
|
+
sourceDirectory,
|
|
8328
|
+
projectName: typeof packageJson.name === "string" && packageJson.name.trim() ? packageJson.name.trim() : path.basename(sourceDirectory),
|
|
8329
|
+
framework,
|
|
8330
|
+
sourceRoots: detectSourceRoots(sourceDirectory, files),
|
|
8331
|
+
packageJson,
|
|
8332
|
+
dependencies,
|
|
8333
|
+
components,
|
|
8334
|
+
styles,
|
|
8335
|
+
assets: [...assetMap.values()],
|
|
8336
|
+
tailwind: tailwindAnalysis(files, dependencies, sourceDirectory),
|
|
8337
|
+
ignoredFiles,
|
|
8338
|
+
warnings: styles.some(({ file }) => /\.(?:scss|sass|less)$/.test(file)) ? ["A V1 detecta Sass/Less, mas preserva automaticamente apenas CSS e CSS Modules."] : []
|
|
8339
|
+
};
|
|
8340
|
+
}
|
|
8341
|
+
//#endregion
|
|
8342
|
+
//#region src/migrate/classifier.ts
|
|
8343
|
+
var RULES = [
|
|
8344
|
+
{
|
|
8345
|
+
role: "HEADER",
|
|
8346
|
+
keywords: [
|
|
8347
|
+
"header",
|
|
8348
|
+
"navbar",
|
|
8349
|
+
"navigation",
|
|
8350
|
+
"menu",
|
|
8351
|
+
"cabecalho"
|
|
8352
|
+
],
|
|
8353
|
+
tags: ["header", "nav"],
|
|
8354
|
+
minimum: 5
|
|
8355
|
+
},
|
|
8356
|
+
{
|
|
8357
|
+
role: "FOOTER",
|
|
8358
|
+
keywords: ["footer", "rodape"],
|
|
8359
|
+
tags: ["footer"],
|
|
8360
|
+
minimum: 5
|
|
8361
|
+
},
|
|
8362
|
+
{
|
|
8363
|
+
role: "HERO",
|
|
8364
|
+
keywords: [
|
|
8365
|
+
"hero",
|
|
8366
|
+
"banner",
|
|
8367
|
+
"jumbotron",
|
|
8368
|
+
"masthead",
|
|
8369
|
+
"destaque"
|
|
8370
|
+
],
|
|
8371
|
+
tags: ["section"],
|
|
8372
|
+
minimum: 5
|
|
8373
|
+
},
|
|
8374
|
+
{
|
|
8375
|
+
role: "PRODUCT_CARD",
|
|
8376
|
+
keywords: [
|
|
8377
|
+
"productcard",
|
|
8378
|
+
"product-card",
|
|
8379
|
+
"produto-card",
|
|
8380
|
+
"cardproduto",
|
|
8381
|
+
"productitem"
|
|
8382
|
+
],
|
|
8383
|
+
tags: ["article"],
|
|
8384
|
+
minimum: 6
|
|
8385
|
+
},
|
|
8386
|
+
{
|
|
8387
|
+
role: "PRODUCT_GRID",
|
|
8388
|
+
keywords: [
|
|
8389
|
+
"productgrid",
|
|
8390
|
+
"product-grid",
|
|
8391
|
+
"products-grid",
|
|
8392
|
+
"produtos-grid",
|
|
8393
|
+
"productlist",
|
|
8394
|
+
"catalog"
|
|
8395
|
+
],
|
|
8396
|
+
minimum: 6
|
|
8397
|
+
},
|
|
8398
|
+
{
|
|
8399
|
+
role: "PRODUCT_DETAIL",
|
|
8400
|
+
keywords: [
|
|
8401
|
+
"productdetail",
|
|
8402
|
+
"product-detail",
|
|
8403
|
+
"produto-detalhe",
|
|
8404
|
+
"productpage",
|
|
8405
|
+
"produto/",
|
|
8406
|
+
"product/"
|
|
8407
|
+
],
|
|
8408
|
+
minimum: 6
|
|
8409
|
+
},
|
|
8410
|
+
{
|
|
8411
|
+
role: "HOME",
|
|
8412
|
+
keywords: [
|
|
8413
|
+
"homepage",
|
|
8414
|
+
"home-page",
|
|
8415
|
+
"landing",
|
|
8416
|
+
"inicio",
|
|
8417
|
+
"app.tsx",
|
|
8418
|
+
"page.tsx"
|
|
8419
|
+
],
|
|
8420
|
+
tags: ["main"],
|
|
8421
|
+
minimum: 6
|
|
8422
|
+
},
|
|
8423
|
+
{
|
|
8424
|
+
role: "SECTION",
|
|
8425
|
+
keywords: [
|
|
8426
|
+
"section",
|
|
8427
|
+
"features",
|
|
8428
|
+
"benefits",
|
|
8429
|
+
"services",
|
|
8430
|
+
"about",
|
|
8431
|
+
"cta"
|
|
8432
|
+
],
|
|
8433
|
+
tags: ["section"],
|
|
8434
|
+
minimum: 6
|
|
8435
|
+
},
|
|
8436
|
+
{
|
|
8437
|
+
role: "PAGE",
|
|
8438
|
+
keywords: [
|
|
8439
|
+
"page",
|
|
8440
|
+
"screen",
|
|
8441
|
+
"view"
|
|
8442
|
+
],
|
|
8443
|
+
tags: ["main"],
|
|
8444
|
+
minimum: 6
|
|
8445
|
+
}
|
|
8446
|
+
];
|
|
8447
|
+
function normalized$1(value) {
|
|
8448
|
+
return value.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase();
|
|
8449
|
+
}
|
|
8450
|
+
function componentCorpus(component) {
|
|
8451
|
+
return normalized$1([
|
|
8452
|
+
component.name,
|
|
8453
|
+
component.file,
|
|
8454
|
+
...component.rootClasses,
|
|
8455
|
+
...component.jsx.flatMap(({ classes, text }) => [...classes, ...text])
|
|
8456
|
+
].join(" "));
|
|
8457
|
+
}
|
|
8458
|
+
function roleScore(component, rule) {
|
|
8459
|
+
const corpus = componentCorpus(component);
|
|
8460
|
+
const name = normalized$1(component.name);
|
|
8461
|
+
const file = normalized$1(component.file);
|
|
8462
|
+
const reasons = [];
|
|
8463
|
+
let score = 0;
|
|
8464
|
+
for (const keyword of rule.keywords) {
|
|
8465
|
+
const term = normalized$1(keyword);
|
|
8466
|
+
if (name.includes(term)) {
|
|
8467
|
+
score += 7;
|
|
8468
|
+
reasons.push(`nome contém "${keyword}"`);
|
|
8469
|
+
} else if (file.includes(term)) {
|
|
8470
|
+
score += 5;
|
|
8471
|
+
reasons.push(`caminho contém "${keyword}"`);
|
|
8472
|
+
} else if (corpus.includes(term)) {
|
|
8473
|
+
score += 3;
|
|
8474
|
+
reasons.push(`JSX/classes contêm "${keyword}"`);
|
|
8475
|
+
}
|
|
8476
|
+
}
|
|
8477
|
+
for (const tag of rule.tags ?? []) if (component.jsx.some((node) => normalized$1(node.tag) === tag)) {
|
|
8478
|
+
score += 6;
|
|
8479
|
+
reasons.push(`usa <${tag}>`);
|
|
8480
|
+
}
|
|
8481
|
+
if (component.page && rule.role === "HOME" && /(^|\/)(?:app\/)?page\.tsx$/.test(component.file)) {
|
|
8482
|
+
score += 7;
|
|
8483
|
+
reasons.push("página inicial do framework");
|
|
8484
|
+
}
|
|
8485
|
+
if (component.page && rule.role === "PAGE") {
|
|
8486
|
+
score += 4;
|
|
8487
|
+
reasons.push("arquivo de página");
|
|
8488
|
+
}
|
|
8489
|
+
if (rule.role === "PRODUCT_CARD") {
|
|
8490
|
+
const hasProduct = corpus.includes("product") || corpus.includes("produto");
|
|
8491
|
+
const hasCard = corpus.includes("card") || component.jsx.some(({ tag }) => tag === "article");
|
|
8492
|
+
if (hasProduct && hasCard) {
|
|
8493
|
+
score += 7;
|
|
8494
|
+
reasons.push("combina produto e card/article");
|
|
8495
|
+
}
|
|
8496
|
+
}
|
|
8497
|
+
if (rule.role === "PRODUCT_GRID") {
|
|
8498
|
+
if (component.jsx.some(({ classes }) => classes.some((item) => /grid|list/.test(normalized$1(item))))) {
|
|
8499
|
+
score += 5;
|
|
8500
|
+
reasons.push("possui estrutura de grid/lista");
|
|
8501
|
+
}
|
|
8502
|
+
}
|
|
8503
|
+
if (rule.role === "PRODUCT_DETAIL") {
|
|
8504
|
+
if (corpus.includes("price") || corpus.includes("preco") || corpus.includes("sku")) {
|
|
8505
|
+
score += 4;
|
|
8506
|
+
reasons.push("exibe campos de detalhe de produto");
|
|
8507
|
+
}
|
|
8508
|
+
}
|
|
8509
|
+
if (rule.role === "HERO" && component.text.some((text) => text.length > 20)) {
|
|
8510
|
+
score += 2;
|
|
8511
|
+
reasons.push("possui chamada textual de destaque");
|
|
8512
|
+
}
|
|
8513
|
+
if (component.defaultExport) score += 1;
|
|
8514
|
+
return {
|
|
8515
|
+
role: rule.role,
|
|
8516
|
+
score,
|
|
8517
|
+
reasons
|
|
8518
|
+
};
|
|
8519
|
+
}
|
|
8520
|
+
function classifyProject(input) {
|
|
8521
|
+
const components = input.components.map((component) => ({
|
|
8522
|
+
...component,
|
|
8523
|
+
roles: RULES.map((rule) => roleScore(component, rule)).filter((candidate) => candidate.score >= (RULES.find(({ role }) => role === candidate.role)?.minimum ?? 6)).sort((left, right) => right.score - left.score)
|
|
8524
|
+
}));
|
|
8525
|
+
const ignoredFiles = [...input.ignoredFiles];
|
|
8526
|
+
for (const component of components) {
|
|
8527
|
+
if (!component.businessSignals.length || component.roles.length) continue;
|
|
8528
|
+
if (ignoredFiles.some(({ file }) => file === component.file)) continue;
|
|
8529
|
+
ignoredFiles.push({
|
|
8530
|
+
file: component.file,
|
|
8531
|
+
reason: component.businessSignals.join(", ")
|
|
8532
|
+
});
|
|
8533
|
+
}
|
|
8534
|
+
return {
|
|
8535
|
+
...input,
|
|
8536
|
+
components,
|
|
8537
|
+
ignoredFiles
|
|
8538
|
+
};
|
|
8539
|
+
}
|
|
8540
|
+
//#endregion
|
|
8541
|
+
//#region src/migrate/asset-copier.ts
|
|
8542
|
+
function portable$1(file) {
|
|
8543
|
+
return file.split(path.sep).join("/");
|
|
8544
|
+
}
|
|
8545
|
+
function safeRelative(file) {
|
|
8546
|
+
return portable$1(file).split("/").filter((part) => part && part !== "." && part !== "..").map((part) => part.replace(/[^a-zA-Z0-9._-]/g, "-")).join("/");
|
|
8547
|
+
}
|
|
8548
|
+
async function copyMigrationAssets(plan, outputDirectory) {
|
|
8549
|
+
const copied = [];
|
|
8550
|
+
const destinationRoot = path.join(outputDirectory, "src", "assets");
|
|
8551
|
+
for (const asset of plan.assets) {
|
|
8552
|
+
try {
|
|
8553
|
+
if (!(await stat(asset.absolutePath)).isFile()) continue;
|
|
8554
|
+
} catch {
|
|
8555
|
+
plan.warnings.push(`Asset não encontrado e ignorado: ${asset.file}`);
|
|
8556
|
+
continue;
|
|
8557
|
+
}
|
|
8558
|
+
const relative = safeRelative(asset.file.startsWith("public/") ? asset.file.slice(7) : asset.file);
|
|
8559
|
+
if (!relative) continue;
|
|
8560
|
+
const destination = path.join(destinationRoot, relative);
|
|
8561
|
+
await mkdir(path.dirname(destination), { recursive: true });
|
|
8562
|
+
await copyFile(asset.absolutePath, destination);
|
|
8563
|
+
copied.push({
|
|
8564
|
+
sourceFile: asset.absolutePath,
|
|
8565
|
+
outputFile: destination,
|
|
8566
|
+
importPath: `../assets/${portable$1(relative)}`,
|
|
8567
|
+
kind: asset.kind
|
|
8568
|
+
});
|
|
8569
|
+
}
|
|
8570
|
+
return copied;
|
|
8571
|
+
}
|
|
8572
|
+
//#endregion
|
|
8573
|
+
//#region src/migrate/generator.ts
|
|
8574
|
+
function portable(file) {
|
|
8575
|
+
return file.split(path.sep).join("/");
|
|
8576
|
+
}
|
|
8577
|
+
function classes(base, source = "") {
|
|
8578
|
+
return JSON.stringify([base, source].filter(Boolean).join(" "));
|
|
8579
|
+
}
|
|
8580
|
+
function profile(plan, role) {
|
|
8581
|
+
return plan.selected[role]?.classes ?? {
|
|
8582
|
+
root: "",
|
|
8583
|
+
brand: "",
|
|
8584
|
+
navigation: "",
|
|
8585
|
+
title: "",
|
|
8586
|
+
text: "",
|
|
8587
|
+
action: "",
|
|
8588
|
+
media: "",
|
|
8589
|
+
grid: "",
|
|
8590
|
+
card: "",
|
|
8591
|
+
content: ""
|
|
8592
|
+
};
|
|
8593
|
+
}
|
|
8594
|
+
function sourceText(plan, role, fallback) {
|
|
8595
|
+
return plan.selected[role]?.component.text.find((candidate) => candidate.length >= 3 && candidate.length <= 140) || fallback;
|
|
8596
|
+
}
|
|
8597
|
+
function headerSource(plan) {
|
|
8598
|
+
const style = profile(plan, "HEADER");
|
|
8599
|
+
return `import type { HeaderProps } from "@nuvler/theme-sdk";
|
|
8600
|
+
|
|
8601
|
+
export function Header({ site, categories, pages }: HeaderProps) {
|
|
8602
|
+
const name = site.settings?.siteName || site.tenant.name;
|
|
8603
|
+
return <header className=${classes("nuvler-migrated-header", style.root)}>
|
|
8604
|
+
<div className=${classes("nuvler-migrated-header-inner", style.content)}>
|
|
8605
|
+
<a className=${classes("nuvler-migrated-brand", style.brand)} href="/">
|
|
8606
|
+
{site.settings?.logo?.url ? <img src={site.settings.logo.url} alt={site.settings.logo.alt || name} /> : <span>{name}</span>}
|
|
8607
|
+
</a>
|
|
8608
|
+
<nav className=${classes("nuvler-migrated-nav", style.navigation)} aria-label="Navegação principal">
|
|
8609
|
+
<a href="/">Início</a>
|
|
8610
|
+
{site.modules.includes("PRODUCTS") && <a href="/produtos">Produtos</a>}
|
|
8611
|
+
{categories.slice(0, 6).map((category) => <a href={\`/categoria/\${category.slug}\`} key={category.slug}>{category.name}</a>)}
|
|
8612
|
+
{pages.slice(0, 4).map((page) => <a href={\`/\${page.slug}\`} key={page.slug}>{page.title}</a>)}
|
|
8613
|
+
</nav>
|
|
8614
|
+
{site.modules.includes("PRODUCTS") && <form className="nuvler-migrated-search" action="/produtos">
|
|
8615
|
+
<input name="busca" type="search" placeholder="Buscar produtos" />
|
|
8616
|
+
<button className=${classes("nuvler-migrated-action", style.action)} type="submit">Buscar</button>
|
|
8617
|
+
</form>}
|
|
8618
|
+
</div>
|
|
8619
|
+
</header>;
|
|
8620
|
+
}
|
|
8621
|
+
`;
|
|
8622
|
+
}
|
|
8623
|
+
function footerSource(plan) {
|
|
8624
|
+
const style = profile(plan, "FOOTER");
|
|
8625
|
+
return `import type { FooterProps } from "@nuvler/theme-sdk";
|
|
8626
|
+
|
|
8627
|
+
export function Footer({ site, pages, template }: FooterProps) {
|
|
8628
|
+
const name = site.settings?.siteName || site.tenant.name;
|
|
8629
|
+
return <footer className=${classes("nuvler-migrated-footer", style.root)}>
|
|
8630
|
+
<div className=${classes("nuvler-migrated-footer-inner", style.content)}>
|
|
8631
|
+
<div><strong className=${classes("nuvler-migrated-footer-brand", style.brand)}>{name}</strong><p className=${classes("nuvler-migrated-copy", style.text)}>{site.settings?.description || template.footerTagline}</p></div>
|
|
8632
|
+
<nav className=${classes("nuvler-migrated-footer-nav", style.navigation)} aria-label={template.footerNavigationLabel}>
|
|
8633
|
+
<a href="/">Início</a>
|
|
8634
|
+
{site.modules.includes("PRODUCTS") && <a href="/produtos">Produtos</a>}
|
|
8635
|
+
{pages.map((page) => <a href={\`/\${page.slug}\`} key={page.slug}>{page.title}</a>)}
|
|
8636
|
+
</nav>
|
|
8637
|
+
<div className="nuvler-migrated-contact">
|
|
8638
|
+
{site.settings?.contact.phone && <a href={\`tel:\${site.settings.contact.phone}\`}>{site.settings.contact.phone}</a>}
|
|
8639
|
+
{site.settings?.contact.email && <a href={\`mailto:\${site.settings.contact.email}\`}>{site.settings.contact.email}</a>}
|
|
8640
|
+
</div>
|
|
8641
|
+
</div>
|
|
8642
|
+
<small>{template.footerNote}</small>
|
|
8643
|
+
</footer>;
|
|
8644
|
+
}
|
|
8645
|
+
`;
|
|
8646
|
+
}
|
|
8647
|
+
function productCardSource(plan) {
|
|
8648
|
+
const style = profile(plan, "PRODUCT_CARD");
|
|
8649
|
+
return `import type { ThemeProduct } from "@nuvler/theme-sdk";
|
|
8650
|
+
|
|
8651
|
+
function money(value: number | null): string {
|
|
8652
|
+
return value === null ? "Consulte" : new Intl.NumberFormat("pt-BR", { style: "currency", currency: "BRL" }).format(value);
|
|
8653
|
+
}
|
|
8654
|
+
|
|
8655
|
+
export function ProductCard({ product, showCategory = true, showDescription = true }: { product: ThemeProduct; showCategory?: boolean; showDescription?: boolean }) {
|
|
8656
|
+
const price = product.promotionalPrice ?? product.price;
|
|
8657
|
+
return <article className=${classes("nuvler-migrated-product-card", style.root || style.card)}>
|
|
8658
|
+
<a className=${classes("nuvler-migrated-product-media", style.media)} href={\`/produto/\${product.slug}\`}>
|
|
8659
|
+
{product.image?.url ? <img src={product.image.url} alt={product.image.alt || product.title} /> : <span aria-hidden="true" />}
|
|
8660
|
+
</a>
|
|
8661
|
+
<div className=${classes("nuvler-migrated-product-content", style.content)}>
|
|
8662
|
+
{showCategory && <small>{product.categories[0]?.name || product.brand || "Produto"}</small>}
|
|
8663
|
+
<h3 className=${classes("nuvler-migrated-product-title", style.title)}><a href={\`/produto/\${product.slug}\`}>{product.title}</a></h3>
|
|
8664
|
+
{showDescription && product.description && <p className=${classes("nuvler-migrated-copy", style.text)}>{product.description}</p>}
|
|
8665
|
+
<strong>{money(price)}</strong>
|
|
8666
|
+
<a className=${classes("nuvler-migrated-action", style.action)} href={\`/produto/\${product.slug}\`}>Ver produto</a>
|
|
8667
|
+
</div>
|
|
8668
|
+
</article>;
|
|
8669
|
+
}
|
|
8670
|
+
`;
|
|
8671
|
+
}
|
|
8672
|
+
function productGridSource(plan) {
|
|
8673
|
+
const style = profile(plan, "PRODUCT_GRID");
|
|
8674
|
+
return `import type { ProductGridProps } from "@nuvler/theme-sdk";
|
|
8675
|
+
import { ProductCard } from "./ProductCard.js";
|
|
8676
|
+
|
|
8677
|
+
export function ProductGrid({ products, columns = 3, showCategory, showDescription }: ProductGridProps) {
|
|
8678
|
+
return <div className=${classes("nuvler-migrated-product-grid", style.root || style.grid)} data-columns={columns}>
|
|
8679
|
+
{products.map((product) => <ProductCard product={product} showCategory={showCategory} showDescription={showDescription} key={product.slug} />)}
|
|
8680
|
+
</div>;
|
|
8681
|
+
}
|
|
8682
|
+
`;
|
|
8683
|
+
}
|
|
8684
|
+
function productDetailSource(plan) {
|
|
8685
|
+
const style = profile(plan, "PRODUCT_DETAIL");
|
|
8686
|
+
return `import type { ProductDetailProps } from "@nuvler/theme-sdk";
|
|
8687
|
+
|
|
8688
|
+
function money(value: number | null): string {
|
|
8689
|
+
return value === null ? "Consulte" : new Intl.NumberFormat("pt-BR", { style: "currency", currency: "BRL" }).format(value);
|
|
8690
|
+
}
|
|
8691
|
+
|
|
8692
|
+
export function ProductDetail({ product, descriptionContent, onAddToCart }: ProductDetailProps) {
|
|
8693
|
+
const image = product.images[0] ?? product.image;
|
|
8694
|
+
return <article className=${classes("nuvler-migrated-product-detail", style.root)}>
|
|
8695
|
+
<div className=${classes("nuvler-migrated-detail-media", style.media)}>{image?.url ? <img src={image.url} alt={image.alt || product.title} /> : <span aria-hidden="true" />}</div>
|
|
8696
|
+
<div className=${classes("nuvler-migrated-detail-content", style.content)}>
|
|
8697
|
+
<small>{product.categories[0]?.name || product.brand || "Produto"}</small>
|
|
8698
|
+
<h1 className=${classes("nuvler-migrated-detail-title", style.title)}>{product.title}</h1>
|
|
8699
|
+
<strong className="nuvler-migrated-price">{money(product.promotionalPrice ?? product.price)}</strong>
|
|
8700
|
+
<div className=${classes("nuvler-migrated-copy", style.text)}>{descriptionContent}</div>
|
|
8701
|
+
<button className=${classes("nuvler-migrated-action", style.action)} type="button" onClick={() => onAddToCart?.({ productSlug: product.slug, title: product.title, sku: product.sku, image: product.image, unitPrice: product.promotionalPrice ?? product.price })}>Adicionar ao orçamento</button>
|
|
8702
|
+
</div>
|
|
8703
|
+
</article>;
|
|
8704
|
+
}
|
|
8705
|
+
`;
|
|
8706
|
+
}
|
|
8707
|
+
function homeSource(plan, assets) {
|
|
8708
|
+
const home = profile(plan, "HOME");
|
|
8709
|
+
const hero = profile(plan, "HERO");
|
|
8710
|
+
const section = profile(plan, "SECTION");
|
|
8711
|
+
const heroText = sourceText(plan, "HERO", "Uma experiência criada para sua marca");
|
|
8712
|
+
const visual = assets.find(({ kind }) => ["image", "svg"].includes(kind));
|
|
8713
|
+
return `import type { HomeProps, ThemeHomeSection } from "@nuvler/theme-sdk";
|
|
8714
|
+
import { ProductGrid } from "../components/ProductGrid.js";
|
|
8715
|
+
|
|
8716
|
+
${visual ? `const migratedHeroAsset = new URL(${JSON.stringify(visual.importPath)}, import.meta.url).href;` : "const migratedHeroAsset: string | null = null;"}
|
|
8717
|
+
|
|
8718
|
+
function value(section: ThemeHomeSection | undefined, key: string): string {
|
|
8719
|
+
const candidate = section?.data[key];
|
|
8720
|
+
return typeof candidate === "string" ? candidate : "";
|
|
8721
|
+
}
|
|
8722
|
+
|
|
8723
|
+
export function Home({ sections, products, site, template }: HomeProps) {
|
|
8724
|
+
const enabled = sections.filter((item) => item.enabled).sort((left, right) => left.order - right.order);
|
|
8725
|
+
const heroSection = enabled.find((item) => item.type === "hero" || item.type === "banner-carousel");
|
|
8726
|
+
const productSection = enabled.find((item) => item.type === "products-grid" || item.type === "products-carousel");
|
|
8727
|
+
const name = site.settings?.siteName || site.tenant.name;
|
|
8728
|
+
const action = template.primaryAction(site.modules);
|
|
8729
|
+
return <main className=${classes("nuvler-migrated-home", home.root)}>
|
|
8730
|
+
<section className=${classes("nuvler-migrated-hero", hero.root || home.content)}>
|
|
8731
|
+
<div className=${classes("nuvler-migrated-hero-content", hero.content)}>
|
|
8732
|
+
<span>{${JSON.stringify(heroText)}}</span>
|
|
8733
|
+
<h1 className=${classes("nuvler-migrated-hero-title", hero.title)}>{value(heroSection, "title") || name}</h1>
|
|
8734
|
+
<p className=${classes("nuvler-migrated-copy", hero.text)}>{value(heroSection, "description") || site.settings?.description || "Conheça nossos produtos e soluções."}</p>
|
|
8735
|
+
<a className=${classes("nuvler-migrated-action", hero.action)} href={value(heroSection, "buttonUrl") || action.href}>{value(heroSection, "buttonLabel") || action.label}</a>
|
|
8736
|
+
</div>
|
|
8737
|
+
{migratedHeroAsset && <div className=${classes("nuvler-migrated-hero-media", hero.media)}><img src={migratedHeroAsset} alt="" /></div>}
|
|
8738
|
+
</section>
|
|
8739
|
+
{site.modules.includes("PRODUCTS") && <section className=${classes("nuvler-migrated-section", section.root)}>
|
|
8740
|
+
<header><span>Destaques</span><h2 className=${classes("nuvler-migrated-section-title", section.title)}>{value(productSection, "title") || "Produtos em destaque"}</h2></header>
|
|
8741
|
+
<ProductGrid products={products} columns={site.settings?.catalog?.desktopColumns || 3} showCategory={site.settings?.catalog?.showCategory} showDescription={site.settings?.catalog?.showDescription} />
|
|
8742
|
+
</section>}
|
|
8743
|
+
{enabled.filter((item) => ["image-text", "rich-text", "cta"].includes(item.type)).map((item) => <section className=${classes("nuvler-migrated-section nuvler-migrated-generic", section.content)} key={item.id || \`\${item.type}-\${item.order}\`}><h2>{value(item, "title")}</h2><p>{value(item, "description") || value(item, "content")}</p>{value(item, "buttonUrl") && <a className="nuvler-migrated-action" href={value(item, "buttonUrl")}>{value(item, "buttonLabel") || "Saiba mais"}</a>}</section>)}
|
|
8744
|
+
</main>;
|
|
8745
|
+
}
|
|
8746
|
+
`;
|
|
8747
|
+
}
|
|
8748
|
+
function definitionSource(plan) {
|
|
8749
|
+
const tokens = plan.tokens;
|
|
8750
|
+
return `import manifestData from "../nuvler.theme.json" with { type: "json" };
|
|
8751
|
+
import { defineTheme, type ThemeHomeSection, type ThemeManifest } from "@nuvler/theme-sdk";
|
|
8752
|
+
import { Footer } from "./components/Footer.js";
|
|
8753
|
+
import { Header } from "./components/Header.js";
|
|
8754
|
+
import { ProductDetail } from "./components/ProductDetail.js";
|
|
8755
|
+
import { ProductGrid } from "./components/ProductGrid.js";
|
|
8756
|
+
import { Home } from "./sections/Home.js";
|
|
8757
|
+
|
|
8758
|
+
function section(id: string, type: ThemeHomeSection["type"], order: number): ThemeHomeSection {
|
|
8759
|
+
return { id, type, enabled: true, order, data: {} };
|
|
8760
|
+
}
|
|
8761
|
+
|
|
8762
|
+
export const manifest = manifestData as ThemeManifest;
|
|
8763
|
+
export const themeDefinition = defineTheme({
|
|
8764
|
+
manifest,
|
|
8765
|
+
tokens: {
|
|
8766
|
+
colors: ${JSON.stringify({
|
|
8767
|
+
primary: tokens.primary,
|
|
8768
|
+
secondary: tokens.secondary,
|
|
8769
|
+
background: tokens.background,
|
|
8770
|
+
text: tokens.text
|
|
8771
|
+
})},
|
|
8772
|
+
layout: ${JSON.stringify({
|
|
8773
|
+
containerWidth: tokens.containerWidth,
|
|
8774
|
+
borderRadius: tokens.borderRadius
|
|
8775
|
+
})},
|
|
8776
|
+
},
|
|
8777
|
+
template: {
|
|
8778
|
+
announcement: ${JSON.stringify(plan.themeName)},
|
|
8779
|
+
footerTagline: "Experiência visual migrada para a plataforma Nuvler.",
|
|
8780
|
+
footerNavigationLabel: "Navegação",
|
|
8781
|
+
footerNote: ${JSON.stringify(plan.themeName)},
|
|
8782
|
+
socialLabel: "Redes sociais",
|
|
8783
|
+
benefits: [],
|
|
8784
|
+
fallbackSections: () => [section("migrated-hero", "hero", 0), section("migrated-products", "products-grid", 1)],
|
|
8785
|
+
primaryAction: (modules) => modules.includes("PRODUCTS") ? { label: "Ver produtos", href: "/produtos" } : { label: "Saiba mais", href: "/" },
|
|
8786
|
+
},
|
|
8787
|
+
components: { Header, Footer, Home, ProductGrid, ProductDetail },
|
|
8788
|
+
});
|
|
8789
|
+
`;
|
|
8790
|
+
}
|
|
8791
|
+
function catalogPageSource() {
|
|
8792
|
+
return `import type { ThemeRoute, ThemeSite } from "@nuvler/theme-sdk";
|
|
8793
|
+
import { ProductGrid } from "../components/ProductGrid.js";
|
|
8794
|
+
|
|
8795
|
+
type CatalogRoute = Extract<ThemeRoute, { type: "catalog" }>;
|
|
8796
|
+
|
|
8797
|
+
export function CatalogPage({ route, site }: { route: CatalogRoute; site: ThemeSite }) {
|
|
8798
|
+
return <main className="nuvler-migrated-section nuvler-migrated-catalog">
|
|
8799
|
+
<header><span>Catálogo</span><h1>{route.search ? \`Busca: \${route.search}\` : "Produtos"}</h1><p>{route.pagination.total} produto(s)</p></header>
|
|
8800
|
+
<ProductGrid products={route.products} columns={site.settings?.catalog?.desktopColumns || 3} showCategory={site.settings?.catalog?.showCategory} showDescription={site.settings?.catalog?.showDescription} />
|
|
8801
|
+
</main>;
|
|
8802
|
+
}
|
|
8803
|
+
`;
|
|
8804
|
+
}
|
|
8805
|
+
function productPageSource() {
|
|
8806
|
+
return `import type { ThemeRoute, ThemeRuntimeSdk, ThemeSite } from "@nuvler/theme-sdk";
|
|
8807
|
+
import { ProductDetail } from "../components/ProductDetail.js";
|
|
8808
|
+
|
|
8809
|
+
type ProductRoute = Extract<ThemeRoute, { type: "product" }>;
|
|
8810
|
+
|
|
8811
|
+
export function ProductPage({ route, site, cart }: { route: ProductRoute; site: ThemeSite; cart?: ThemeRuntimeSdk["cart"] }) {
|
|
8812
|
+
return <main className="nuvler-migrated-section"><ProductDetail product={route.product} contact={site.settings?.contact} productUrl={null} descriptionContent={<p>{route.product.description}</p>} onAddToCart={cart?.add} /></main>;
|
|
8813
|
+
}
|
|
8814
|
+
`;
|
|
8815
|
+
}
|
|
8816
|
+
function editorialPageSource() {
|
|
8817
|
+
return `import type { ThemeRoute } from "@nuvler/theme-sdk";
|
|
8818
|
+
|
|
8819
|
+
type EditorialRoute = Extract<ThemeRoute, { type: "editorial-list" | "editorial-detail" }>;
|
|
8820
|
+
|
|
8821
|
+
export function EditorialPage({ route }: { route: EditorialRoute }) {
|
|
8822
|
+
if (route.type === "editorial-detail") return <main className="nuvler-migrated-section"><article><span>Conteúdo</span><h1>{route.item.title}</h1><p>{route.item.description}</p></article></main>;
|
|
8823
|
+
return <main className="nuvler-migrated-section"><h1>{route.title}</h1><div className="nuvler-migrated-editorial-grid">{route.items.map((item) => <article key={item.slug}><h2><a href={\`\${route.basePath}/\${item.slug}\`}>{item.title}</a></h2><p>{item.description}</p></article>)}</div></main>;
|
|
8824
|
+
}
|
|
8825
|
+
`;
|
|
8826
|
+
}
|
|
8827
|
+
function statePageSource() {
|
|
8828
|
+
return `export function StatePage({ title, pathname }: { title: string; pathname?: string }) {
|
|
8829
|
+
return <main className="nuvler-migrated-section nuvler-migrated-state"><span>{pathname || "Nuvler"}</span><h1>{title}</h1></main>;
|
|
8830
|
+
}
|
|
8831
|
+
`;
|
|
8832
|
+
}
|
|
8833
|
+
function themeSource() {
|
|
8834
|
+
return `import type { CSSProperties } from "react";
|
|
8835
|
+
import type { NuvlerThemeProps, ThemeSite } from "@nuvler/theme-sdk";
|
|
8836
|
+
import { themeDefinition } from "./definition.js";
|
|
8837
|
+
import { CatalogPage } from "./pages/CatalogPage.js";
|
|
8838
|
+
import { EditorialPage } from "./pages/EditorialPage.js";
|
|
8839
|
+
import { ProductPage } from "./pages/ProductPage.js";
|
|
8840
|
+
import { StatePage } from "./pages/StatePage.js";
|
|
8841
|
+
import "./styles/theme.css";
|
|
8842
|
+
|
|
8843
|
+
export { manifest, themeDefinition } from "./definition.js";
|
|
8844
|
+
|
|
8845
|
+
export default function Theme({ context, route = { type: "home" }, sdk }: NuvlerThemeProps) {
|
|
8846
|
+
const { Header, Footer, Home } = themeDefinition.components;
|
|
8847
|
+
const site: ThemeSite = { tenant: context.store, ...context.site };
|
|
8848
|
+
const configured = site.settings?.theme;
|
|
8849
|
+
const tokens = {
|
|
8850
|
+
colors: { ...themeDefinition.tokens.colors, ...configured?.colors },
|
|
8851
|
+
layout: { ...themeDefinition.tokens.layout, ...configured?.layout },
|
|
8852
|
+
};
|
|
8853
|
+
const style = {
|
|
8854
|
+
"--theme-primary": tokens.colors.primary,
|
|
8855
|
+
"--theme-secondary": tokens.colors.secondary,
|
|
8856
|
+
"--theme-background": tokens.colors.background,
|
|
8857
|
+
"--theme-text": tokens.colors.text,
|
|
8858
|
+
"--theme-radius": \`\${tokens.layout.borderRadius}px\`,
|
|
8859
|
+
"--theme-container": \`\${tokens.layout.containerWidth}px\`,
|
|
8860
|
+
} as CSSProperties;
|
|
8861
|
+
let content;
|
|
8862
|
+
if (route.type === "home") content = <Home sections={context.home.content.sections} products={context.catalog.products} posts={context.editorial.posts} services={context.editorial.services} cases={context.editorial.cases} site={site} template={themeDefinition.template} />;
|
|
8863
|
+
else if (route.type === "catalog") content = <CatalogPage route={route} site={site} />;
|
|
8864
|
+
else if (route.type === "product") content = <ProductPage route={route} site={site} cart={sdk?.cart} />;
|
|
8865
|
+
else if (route.type === "editorial-list" || route.type === "editorial-detail") content = <EditorialPage route={route} />;
|
|
8866
|
+
else content = <StatePage title={route.type === "loading" ? "Carregando…" : route.type === "page" ? route.title : "Conteúdo não encontrado"} pathname={"pathname" in route ? route.pathname : undefined} />;
|
|
8867
|
+
return <div className="nuvler-migrated-theme" style={style}><Header site={site} categories={context.navigation.categories} pages={context.navigation.pages} template={themeDefinition.template} /><div className="nuvler-migrated-page">{content}</div><Footer site={site} pages={context.navigation.pages} template={themeDefinition.template} /></div>;
|
|
8868
|
+
}
|
|
8869
|
+
`;
|
|
8870
|
+
}
|
|
8871
|
+
function baseCss(plan) {
|
|
8872
|
+
return `/* Fallback estrutural do adaptador Nuvler. Os estilos extraídos vêm depois deste bloco. */
|
|
8873
|
+
* { box-sizing: border-box; }
|
|
8874
|
+
body { margin: 0; }
|
|
8875
|
+
.nuvler-migrated-theme { min-height: 100vh; background: var(--theme-background); color: var(--theme-text); font-family: Inter, system-ui, sans-serif; }
|
|
8876
|
+
.nuvler-migrated-header-inner, .nuvler-migrated-footer-inner, .nuvler-migrated-section, .nuvler-migrated-hero { width: min(calc(100% - 32px), var(--theme-container)); margin-inline: auto; }
|
|
8877
|
+
.nuvler-migrated-header-inner { min-height: 72px; display: flex; align-items: center; gap: 24px; justify-content: space-between; }
|
|
8878
|
+
.nuvler-migrated-brand img { display: block; width: auto; max-width: 200px; max-height: 56px; }
|
|
8879
|
+
.nuvler-migrated-nav { display: flex; flex-wrap: wrap; gap: 18px; }
|
|
8880
|
+
.nuvler-migrated-nav a, .nuvler-migrated-brand, .nuvler-migrated-footer a { color: inherit; text-decoration: none; }
|
|
8881
|
+
.nuvler-migrated-search { display: flex; gap: 8px; }
|
|
8882
|
+
.nuvler-migrated-search input { min-width: 220px; border: 1px solid color-mix(in srgb, var(--theme-text), transparent 78%); border-radius: var(--theme-radius); padding: 10px 13px; }
|
|
8883
|
+
.nuvler-migrated-action { display: inline-flex; align-items: center; justify-content: center; border: 0; border-radius: var(--theme-radius); background: var(--theme-primary); color: #fff; padding: 12px 18px; text-decoration: none; cursor: pointer; }
|
|
8884
|
+
.nuvler-migrated-hero { display: grid; min-height: 520px; grid-template-columns: minmax(0, 1fr) minmax(320px, .9fr); align-items: center; gap: 40px; padding-block: 64px; }
|
|
8885
|
+
.nuvler-migrated-hero-title { margin: 12px 0; font-size: clamp(42px, 7vw, 82px); line-height: .98; }
|
|
8886
|
+
.nuvler-migrated-hero-media, .nuvler-migrated-product-media, .nuvler-migrated-detail-media { overflow: hidden; border-radius: var(--theme-radius); }
|
|
8887
|
+
.nuvler-migrated-hero-media img, .nuvler-migrated-product-media img, .nuvler-migrated-detail-media img { display: block; width: 100%; height: 100%; object-fit: cover; }
|
|
8888
|
+
.nuvler-migrated-section { padding-block: 56px; }
|
|
8889
|
+
.nuvler-migrated-product-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 20px; }
|
|
8890
|
+
.nuvler-migrated-product-grid[data-columns="4"] { grid-template-columns: repeat(4, minmax(0, 1fr)); }
|
|
8891
|
+
.nuvler-migrated-product-card { overflow: hidden; border: 1px solid color-mix(in srgb, var(--theme-text), transparent 85%); border-radius: var(--theme-radius); background: #fff; }
|
|
8892
|
+
.nuvler-migrated-product-media { display: block; aspect-ratio: 1; }
|
|
8893
|
+
.nuvler-migrated-product-content { display: grid; gap: 12px; padding: 20px; }
|
|
8894
|
+
.nuvler-migrated-product-content p { overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }
|
|
8895
|
+
.nuvler-migrated-product-detail { display: grid; grid-template-columns: minmax(0, 1fr) minmax(320px, .8fr); gap: 48px; }
|
|
8896
|
+
.nuvler-migrated-price { display: block; margin-block: 18px; font-size: 28px; }
|
|
8897
|
+
.nuvler-migrated-footer { margin-top: 64px; background: var(--theme-text); color: var(--theme-background); padding: 56px max(16px, calc((100% - var(--theme-container)) / 2)); }
|
|
8898
|
+
.nuvler-migrated-footer-inner { width: 100%; display: grid; grid-template-columns: 2fr 1fr 1fr; gap: 40px; }
|
|
8899
|
+
.nuvler-migrated-footer-nav, .nuvler-migrated-contact { display: grid; gap: 8px; }
|
|
8900
|
+
@media (max-width: 850px) { .nuvler-migrated-header-inner, .nuvler-migrated-hero { grid-template-columns: 1fr; flex-direction: column; align-items: stretch; } .nuvler-migrated-nav { overflow-x: auto; flex-wrap: nowrap; } .nuvler-migrated-search input { width: 100%; min-width: 0; } .nuvler-migrated-product-grid, .nuvler-migrated-product-grid[data-columns="4"], .nuvler-migrated-product-detail, .nuvler-migrated-footer-inner { grid-template-columns: 1fr; } }
|
|
8901
|
+
|
|
8902
|
+
:root {
|
|
8903
|
+
--theme-primary: ${plan.tokens.primary};
|
|
8904
|
+
--theme-secondary: ${plan.tokens.secondary};
|
|
8905
|
+
--theme-background: ${plan.tokens.background};
|
|
8906
|
+
--theme-text: ${plan.tokens.text};
|
|
8907
|
+
--theme-radius: ${plan.tokens.borderRadius}px;
|
|
8908
|
+
--theme-container: ${plan.tokens.containerWidth}px;
|
|
8909
|
+
}
|
|
8910
|
+
`;
|
|
8911
|
+
}
|
|
8912
|
+
function copiedAssetFor(style, reference, plan, copied) {
|
|
8913
|
+
const absolute = reference.startsWith("/") ? path.join(plan.analysis.sourceDirectory, "public", reference.replace(/^\/+/, "")) : path.resolve(path.dirname(style.absolutePath), reference);
|
|
8914
|
+
return copied.find((asset) => path.resolve(asset.sourceFile) === path.resolve(absolute));
|
|
8915
|
+
}
|
|
8916
|
+
function preservedCss(plan, copied) {
|
|
8917
|
+
return plan.styles.map((style) => {
|
|
8918
|
+
let content = style.content;
|
|
8919
|
+
content = content.replace(/@import\s+(["'])(?!https?:)(?!tailwindcss)([^"']+)\1\s*;?/gi, "");
|
|
8920
|
+
content = content.replace(/@tailwind\s+(?:base|components|utilities)\s*;?/gi, "");
|
|
8921
|
+
content = content.replace(/@import\s+["']tailwindcss["']\s*;?/gi, "");
|
|
8922
|
+
content = content.replace(/:global\(([^)]+)\)/g, "$1");
|
|
8923
|
+
content = content.replace(/url\(\s*(["']?)([^)'"\s]+)\1\s*\)/gi, (full, _quote, reference) => {
|
|
8924
|
+
if (/^(?:data:|https?:|#)/i.test(reference)) return full;
|
|
8925
|
+
const asset = copiedAssetFor(style, reference, plan, copied);
|
|
8926
|
+
if (!asset) return full;
|
|
8927
|
+
const output = portable(asset.outputFile);
|
|
8928
|
+
const markerIndex = output.lastIndexOf("/src/assets/");
|
|
8929
|
+
if (markerIndex < 0) return full;
|
|
8930
|
+
return `url(${JSON.stringify(`../assets/${output.slice(markerIndex + 12)}`)})`;
|
|
8931
|
+
});
|
|
8932
|
+
return `/* Origem: ${style.file}${style.module ? " (CSS Module convertido para CSS comum)" : ""} */\n${content}`;
|
|
8933
|
+
}).join("\n\n");
|
|
8934
|
+
}
|
|
8935
|
+
async function configureTailwind(plan, directory) {
|
|
8936
|
+
if (!plan.analysis.tailwind.detected) return "";
|
|
8937
|
+
const packageFile = path.join(directory, "package.json");
|
|
8938
|
+
const metadata = JSON.parse(await readFile(packageFile, "utf8"));
|
|
8939
|
+
metadata.devDependencies ??= {};
|
|
8940
|
+
const major = plan.analysis.tailwind.major ?? 3;
|
|
8941
|
+
metadata.devDependencies.tailwindcss = plan.analysis.tailwind.version || (major >= 4 ? "^4.0.0" : "^3.4.0");
|
|
8942
|
+
metadata.devDependencies.postcss = plan.analysis.dependencies.postcss || "^8.4.0";
|
|
8943
|
+
if (major >= 4) {
|
|
8944
|
+
metadata.devDependencies["@tailwindcss/postcss"] = plan.analysis.dependencies["@tailwindcss/postcss"] || "^4.0.0";
|
|
8945
|
+
await writeFile(path.join(directory, "postcss.config.mjs"), "export default { plugins: { \"@tailwindcss/postcss\": {} } };\n", "utf8");
|
|
8946
|
+
await writeFile(packageFile, `${JSON.stringify(metadata, null, 2)}\n`, "utf8");
|
|
8947
|
+
return "@import \"tailwindcss\";\n";
|
|
8948
|
+
}
|
|
8949
|
+
metadata.devDependencies.autoprefixer = plan.analysis.dependencies.autoprefixer || "^10.4.0";
|
|
8950
|
+
await writeFile(path.join(directory, "tailwind.config.cjs"), "module.exports = { content: [\"./src/**/*.{ts,tsx}\"], theme: { extend: {} }, plugins: [] };\n", "utf8");
|
|
8951
|
+
await writeFile(path.join(directory, "postcss.config.cjs"), "module.exports = { plugins: { tailwindcss: {}, autoprefixer: {} } };\n", "utf8");
|
|
8952
|
+
await writeFile(packageFile, `${JSON.stringify(metadata, null, 2)}\n`, "utf8");
|
|
8953
|
+
return "@tailwind base;\n@tailwind components;\n@tailwind utilities;\n";
|
|
8954
|
+
}
|
|
8955
|
+
async function generateMigratedTheme(plan, directory) {
|
|
8956
|
+
await themeCreate({
|
|
8957
|
+
directory,
|
|
8958
|
+
id: plan.themeId,
|
|
8959
|
+
name: plan.themeName,
|
|
8960
|
+
template: "starter",
|
|
8961
|
+
silent: true
|
|
8962
|
+
});
|
|
8963
|
+
await rm(path.join(directory, "src"), {
|
|
8964
|
+
recursive: true,
|
|
8965
|
+
force: true
|
|
8966
|
+
});
|
|
8967
|
+
await Promise.all([
|
|
8968
|
+
mkdir(path.join(directory, "src", "components"), { recursive: true }),
|
|
8969
|
+
mkdir(path.join(directory, "src", "sections"), { recursive: true }),
|
|
8970
|
+
mkdir(path.join(directory, "src", "styles"), { recursive: true }),
|
|
8971
|
+
mkdir(path.join(directory, "src", "pages"), { recursive: true })
|
|
8972
|
+
]);
|
|
8973
|
+
const copiedAssets = await copyMigrationAssets(plan, directory);
|
|
8974
|
+
const tailwindHeader = await configureTailwind(plan, directory);
|
|
8975
|
+
await Promise.all([
|
|
8976
|
+
writeFile(path.join(directory, "src/components/Header.tsx"), headerSource(plan), "utf8"),
|
|
8977
|
+
writeFile(path.join(directory, "src/components/Footer.tsx"), footerSource(plan), "utf8"),
|
|
8978
|
+
writeFile(path.join(directory, "src/components/ProductCard.tsx"), productCardSource(plan), "utf8"),
|
|
8979
|
+
writeFile(path.join(directory, "src/components/ProductGrid.tsx"), productGridSource(plan), "utf8"),
|
|
8980
|
+
writeFile(path.join(directory, "src/components/ProductDetail.tsx"), productDetailSource(plan), "utf8"),
|
|
8981
|
+
writeFile(path.join(directory, "src/sections/Home.tsx"), homeSource(plan, copiedAssets), "utf8"),
|
|
8982
|
+
writeFile(path.join(directory, "src/pages/CatalogPage.tsx"), catalogPageSource(), "utf8"),
|
|
8983
|
+
writeFile(path.join(directory, "src/pages/ProductPage.tsx"), productPageSource(), "utf8"),
|
|
8984
|
+
writeFile(path.join(directory, "src/pages/EditorialPage.tsx"), editorialPageSource(), "utf8"),
|
|
8985
|
+
writeFile(path.join(directory, "src/pages/StatePage.tsx"), statePageSource(), "utf8"),
|
|
8986
|
+
writeFile(path.join(directory, "src/definition.tsx"), definitionSource(plan), "utf8"),
|
|
8987
|
+
writeFile(path.join(directory, "src/theme.tsx"), themeSource(), "utf8"),
|
|
8988
|
+
writeFile(path.join(directory, "src/styles/theme.css"), `${tailwindHeader}${baseCss(plan)}\n${preservedCss(plan, copiedAssets)}\n`, "utf8"),
|
|
8989
|
+
writeFile(path.join(directory, "src/styles.d.ts"), "declare module \"*.css\";\ndeclare module \"*.svg\";\n", "utf8")
|
|
8990
|
+
]);
|
|
8991
|
+
const manifestFile = path.join(directory, "nuvler.theme.json");
|
|
8992
|
+
const manifest = JSON.parse(await readFile(manifestFile, "utf8"));
|
|
8993
|
+
manifest.entry = "src/theme.tsx";
|
|
8994
|
+
manifest.styles = ["src/styles/theme.css"];
|
|
8995
|
+
manifest.presentation = {
|
|
8996
|
+
description: `Tema ${plan.themeName} migrado de um projeto React + ${plan.analysis.framework === "next" ? "Next.js" : "Vite"}.`,
|
|
8997
|
+
templateId: "starter",
|
|
8998
|
+
colors: {
|
|
8999
|
+
primary: plan.tokens.primary,
|
|
9000
|
+
secondary: plan.tokens.secondary,
|
|
9001
|
+
background: plan.tokens.background,
|
|
9002
|
+
text: plan.tokens.text
|
|
9003
|
+
},
|
|
9004
|
+
layout: {
|
|
9005
|
+
containerWidth: plan.tokens.containerWidth,
|
|
9006
|
+
borderRadius: plan.tokens.borderRadius
|
|
9007
|
+
}
|
|
9008
|
+
};
|
|
9009
|
+
await writeFile(manifestFile, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
|
|
9010
|
+
const selectedComponents = {};
|
|
9011
|
+
for (const [role, selected] of Object.entries(plan.selected)) if (selected) selectedComponents[role] = {
|
|
9012
|
+
name: selected.component.name,
|
|
9013
|
+
file: selected.component.file
|
|
9014
|
+
};
|
|
9015
|
+
return {
|
|
9016
|
+
copiedAssets,
|
|
9017
|
+
report: {
|
|
9018
|
+
framework: plan.analysis.framework,
|
|
9019
|
+
sourceRoots: plan.analysis.sourceRoots,
|
|
9020
|
+
componentsAnalyzed: plan.analysis.components.length,
|
|
9021
|
+
selectedComponents,
|
|
9022
|
+
assetsCopied: copiedAssets.length,
|
|
9023
|
+
styleFilesPreserved: plan.styles.length,
|
|
9024
|
+
tailwind: plan.analysis.tailwind,
|
|
9025
|
+
ignoredFiles: plan.analysis.ignoredFiles,
|
|
9026
|
+
warnings: [...new Set(plan.warnings)],
|
|
9027
|
+
validation: {
|
|
9028
|
+
manifest: false,
|
|
9029
|
+
typecheck: false,
|
|
9030
|
+
build: false
|
|
9031
|
+
}
|
|
9032
|
+
}
|
|
9033
|
+
};
|
|
9034
|
+
}
|
|
9035
|
+
async function writeMigrationReport(directory, report) {
|
|
9036
|
+
await writeFile(path.join(directory, "migration-report.json"), `${JSON.stringify(report, null, 2)}\n`, "utf8");
|
|
9037
|
+
}
|
|
9038
|
+
//#endregion
|
|
9039
|
+
//#region src/migrate/transformer.ts
|
|
9040
|
+
var ROLES = [
|
|
9041
|
+
"HEADER",
|
|
9042
|
+
"FOOTER",
|
|
9043
|
+
"HERO",
|
|
9044
|
+
"HOME",
|
|
9045
|
+
"PRODUCT_CARD",
|
|
9046
|
+
"PRODUCT_GRID",
|
|
9047
|
+
"PRODUCT_DETAIL",
|
|
9048
|
+
"SECTION",
|
|
9049
|
+
"PAGE"
|
|
9050
|
+
];
|
|
9051
|
+
function normalized(value) {
|
|
9052
|
+
return value.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase();
|
|
9053
|
+
}
|
|
9054
|
+
function joinClasses(classes) {
|
|
9055
|
+
return [...new Set(classes)].join(" ");
|
|
9056
|
+
}
|
|
9057
|
+
function matchingNode(component, terms, tags = []) {
|
|
9058
|
+
return component.jsx.find((node) => {
|
|
9059
|
+
const corpus = normalized(`${node.tag} ${node.classes.join(" ")} ${node.text.join(" ")}`);
|
|
9060
|
+
return tags.includes(normalized(node.tag)) || terms.some((term) => corpus.includes(term));
|
|
9061
|
+
});
|
|
9062
|
+
}
|
|
9063
|
+
function classesFor(component, terms, fallback = "", tags = []) {
|
|
9064
|
+
return joinClasses(matchingNode(component, terms, tags)?.classes ?? []) || fallback;
|
|
9065
|
+
}
|
|
9066
|
+
function classProfile(component) {
|
|
9067
|
+
return {
|
|
9068
|
+
root: joinClasses(component.rootClasses),
|
|
9069
|
+
brand: classesFor(component, [
|
|
9070
|
+
"brand",
|
|
9071
|
+
"logo",
|
|
9072
|
+
"marca"
|
|
9073
|
+
]),
|
|
9074
|
+
navigation: classesFor(component, [
|
|
9075
|
+
"nav",
|
|
9076
|
+
"menu",
|
|
9077
|
+
"navigation"
|
|
9078
|
+
], "", ["nav"]),
|
|
9079
|
+
title: classesFor(component, [
|
|
9080
|
+
"title",
|
|
9081
|
+
"heading",
|
|
9082
|
+
"headline",
|
|
9083
|
+
"titulo"
|
|
9084
|
+
], "", ["h1", "h2"]),
|
|
9085
|
+
text: classesFor(component, [
|
|
9086
|
+
"description",
|
|
9087
|
+
"subtitle",
|
|
9088
|
+
"copy",
|
|
9089
|
+
"text",
|
|
9090
|
+
"descricao"
|
|
9091
|
+
], "", ["p"]),
|
|
9092
|
+
action: classesFor(component, [
|
|
9093
|
+
"button",
|
|
9094
|
+
"btn",
|
|
9095
|
+
"cta",
|
|
9096
|
+
"action"
|
|
9097
|
+
], "", ["button"]),
|
|
9098
|
+
media: classesFor(component, [
|
|
9099
|
+
"image",
|
|
9100
|
+
"media",
|
|
9101
|
+
"photo",
|
|
9102
|
+
"picture",
|
|
9103
|
+
"imagem"
|
|
9104
|
+
], "", ["img", "picture"]),
|
|
9105
|
+
grid: classesFor(component, [
|
|
9106
|
+
"grid",
|
|
9107
|
+
"list",
|
|
9108
|
+
"collection",
|
|
9109
|
+
"products"
|
|
9110
|
+
]),
|
|
9111
|
+
card: classesFor(component, [
|
|
9112
|
+
"card",
|
|
9113
|
+
"item",
|
|
9114
|
+
"product"
|
|
9115
|
+
], "", ["article"]),
|
|
9116
|
+
content: classesFor(component, [
|
|
9117
|
+
"content",
|
|
9118
|
+
"body",
|
|
9119
|
+
"inner",
|
|
9120
|
+
"container",
|
|
9121
|
+
"wrapper"
|
|
9122
|
+
])
|
|
9123
|
+
};
|
|
9124
|
+
}
|
|
9125
|
+
function selectedFor(analysis, role) {
|
|
9126
|
+
return analysis.components.filter((component) => component.roles.some((candidate) => candidate.role === role)).sort((left, right) => {
|
|
9127
|
+
const leftScore = left.roles.find((candidate) => candidate.role === role)?.score ?? 0;
|
|
9128
|
+
return (right.roles.find((candidate) => candidate.role === role)?.score ?? 0) - leftScore || Number(right.exported) - Number(left.exported);
|
|
9129
|
+
})[0];
|
|
9130
|
+
}
|
|
9131
|
+
function customProperty(css, terms) {
|
|
9132
|
+
for (const match of css.matchAll(/--([\w-]+)\s*:\s*(#[0-9a-f]{6})\b/gi)) {
|
|
9133
|
+
const name = normalized(match[1]);
|
|
9134
|
+
if (terms.some((term) => name.includes(term))) return match[2].toLowerCase();
|
|
9135
|
+
}
|
|
9136
|
+
return null;
|
|
9137
|
+
}
|
|
9138
|
+
function frequentColors(css) {
|
|
9139
|
+
const counts = /* @__PURE__ */ new Map();
|
|
9140
|
+
for (const match of css.matchAll(/#[0-9a-f]{6}\b/gi)) {
|
|
9141
|
+
const color = match[0].toLowerCase();
|
|
9142
|
+
counts.set(color, (counts.get(color) ?? 0) + 1);
|
|
9143
|
+
}
|
|
9144
|
+
return [...counts.entries()].sort((left, right) => right[1] - left[1]).map(([color]) => color);
|
|
9145
|
+
}
|
|
9146
|
+
function inferredTokens(analysis) {
|
|
9147
|
+
const css = analysis.styles.filter(({ imported }) => imported).map(({ content }) => content).join("\n");
|
|
9148
|
+
const nonNeutral = frequentColors(css).filter((color) => ![
|
|
9149
|
+
"#ffffff",
|
|
9150
|
+
"#000000",
|
|
9151
|
+
"#f8fafc",
|
|
9152
|
+
"#f9fafb",
|
|
9153
|
+
"#111827",
|
|
9154
|
+
"#0f172a"
|
|
9155
|
+
].includes(color));
|
|
9156
|
+
const widths = [...css.matchAll(/max-width\s*:\s*(\d{3,4})px/gi)].map((match) => Number(match[1])).filter((value) => value >= 960 && value <= 1600);
|
|
9157
|
+
const radii = [...css.matchAll(/border-radius\s*:\s*(\d{1,2})px/gi)].map((match) => Number(match[1])).filter((value) => value >= 0 && value <= 32);
|
|
9158
|
+
return {
|
|
9159
|
+
primary: customProperty(css, [
|
|
9160
|
+
"primary",
|
|
9161
|
+
"brand",
|
|
9162
|
+
"principal"
|
|
9163
|
+
]) ?? nonNeutral[0] ?? "#1d4ed8",
|
|
9164
|
+
secondary: customProperty(css, [
|
|
9165
|
+
"secondary",
|
|
9166
|
+
"accent",
|
|
9167
|
+
"destaque"
|
|
9168
|
+
]) ?? nonNeutral[1] ?? "#f59e0b",
|
|
9169
|
+
background: customProperty(css, [
|
|
9170
|
+
"background",
|
|
9171
|
+
"fundo",
|
|
9172
|
+
"bg"
|
|
9173
|
+
]) ?? "#f8fafc",
|
|
9174
|
+
text: customProperty(css, [
|
|
9175
|
+
"foreground",
|
|
9176
|
+
"text",
|
|
9177
|
+
"texto"
|
|
9178
|
+
]) ?? "#0f172a",
|
|
9179
|
+
containerWidth: widths[0] ?? 1200,
|
|
9180
|
+
borderRadius: radii[0] ?? 16
|
|
9181
|
+
};
|
|
9182
|
+
}
|
|
9183
|
+
function safeThemeId(value) {
|
|
9184
|
+
const id = value.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80);
|
|
9185
|
+
return id.length >= 2 ? id : "tema-migrado";
|
|
9186
|
+
}
|
|
9187
|
+
function themeName(value) {
|
|
9188
|
+
return value.replace(/^@[^/]+\//, "").split(/[-_\s]+/).filter(Boolean).map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" ").slice(0, 120) || "Tema Migrado";
|
|
9189
|
+
}
|
|
9190
|
+
function createMigrationPlan(analysis, options) {
|
|
9191
|
+
const selected = {};
|
|
9192
|
+
for (const role of ROLES) {
|
|
9193
|
+
const component = selectedFor(analysis, role);
|
|
9194
|
+
if (component) selected[role] = {
|
|
9195
|
+
role,
|
|
9196
|
+
component,
|
|
9197
|
+
classes: classProfile(component)
|
|
9198
|
+
};
|
|
9199
|
+
}
|
|
9200
|
+
const warnings = [...analysis.warnings];
|
|
9201
|
+
for (const item of Object.values(selected)) {
|
|
9202
|
+
if (!item?.component.businessSignals.length) continue;
|
|
9203
|
+
warnings.push(`${item.component.file}: ${item.component.businessSignals.join(", ")} removido(a); apenas a apresentação foi adaptada.`);
|
|
9204
|
+
}
|
|
9205
|
+
if (!selected.HEADER) warnings.push("Header não identificado; será usada a estrutura visual segura do tema base.");
|
|
9206
|
+
if (!selected.FOOTER) warnings.push("Footer não identificado; será usada a estrutura visual segura do tema base.");
|
|
9207
|
+
if (!selected.PRODUCT_CARD) warnings.push("ProductCard não identificado; será usado o card do tema base.");
|
|
9208
|
+
if (analysis.tailwind.detected) warnings.push("Tailwind detectado: classes observadas serão preservadas e recompiladas no tema gerado.");
|
|
9209
|
+
const outputName = path.basename(path.resolve(options.outputDirectory));
|
|
9210
|
+
return {
|
|
9211
|
+
analysis,
|
|
9212
|
+
themeId: safeThemeId(options.id?.trim() || outputName),
|
|
9213
|
+
themeName: options.name?.trim() || themeName(analysis.projectName),
|
|
9214
|
+
selected,
|
|
9215
|
+
styles: analysis.styles.filter(({ imported, file }) => imported && file.endsWith(".css")),
|
|
9216
|
+
assets: analysis.assets,
|
|
9217
|
+
tokens: inferredTokens(analysis),
|
|
9218
|
+
warnings: [...new Set(warnings)]
|
|
9219
|
+
};
|
|
9220
|
+
}
|
|
9221
|
+
//#endregion
|
|
9222
|
+
//#region src/migrate/validator.ts
|
|
9223
|
+
function diagnosticsMessage(diagnostics) {
|
|
9224
|
+
return ts.formatDiagnosticsWithColorAndContext(diagnostics, {
|
|
9225
|
+
getCanonicalFileName: (file) => file,
|
|
9226
|
+
getCurrentDirectory: () => process.cwd(),
|
|
9227
|
+
getNewLine: () => "\n"
|
|
9228
|
+
});
|
|
9229
|
+
}
|
|
9230
|
+
async function typecheck(directory) {
|
|
9231
|
+
const configFile = path.join(directory, "tsconfig.json");
|
|
9232
|
+
const config = ts.readConfigFile(configFile, ts.sys.readFile);
|
|
9233
|
+
if (config.error) throw new Error(`tsconfig inválido:\n${diagnosticsMessage([config.error])}`);
|
|
9234
|
+
const parsed = ts.parseJsonConfigFileContent(config.config, ts.sys, directory, { noEmit: true }, configFile);
|
|
9235
|
+
if (parsed.errors.length) throw new Error(`tsconfig inválido:\n${diagnosticsMessage(parsed.errors)}`);
|
|
9236
|
+
const program = ts.createProgram({
|
|
9237
|
+
rootNames: parsed.fileNames,
|
|
9238
|
+
options: parsed.options
|
|
9239
|
+
});
|
|
9240
|
+
const errors = ts.getPreEmitDiagnostics(program).filter(({ category }) => category === ts.DiagnosticCategory.Error);
|
|
9241
|
+
if (errors.length) throw new Error(`O tema gerado não passou no typecheck:\n${diagnosticsMessage(errors.slice(0, 30))}`);
|
|
9242
|
+
}
|
|
9243
|
+
async function validateMigratedTheme(directory, options) {
|
|
9244
|
+
await loadThemeProject(directory);
|
|
9245
|
+
const result = {
|
|
9246
|
+
manifest: true,
|
|
9247
|
+
typecheck: false,
|
|
9248
|
+
build: false
|
|
9249
|
+
};
|
|
9250
|
+
if (!options.runChecks) return result;
|
|
9251
|
+
await typecheck(directory);
|
|
9252
|
+
result.typecheck = true;
|
|
9253
|
+
await themeBuild({ themeDirectory: directory });
|
|
9254
|
+
result.build = true;
|
|
9255
|
+
return result;
|
|
9256
|
+
}
|
|
9257
|
+
//#endregion
|
|
9258
|
+
//#region src/commands/theme/migrate.ts
|
|
9259
|
+
function inside(root, candidate) {
|
|
9260
|
+
const relative = path.relative(root, candidate);
|
|
9261
|
+
return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
|
|
9262
|
+
}
|
|
9263
|
+
async function ensureTargetAvailable(directory) {
|
|
9264
|
+
try {
|
|
9265
|
+
if (!(await stat(directory)).isDirectory()) throw new Error(`O destino já existe e não é uma pasta: ${directory}`);
|
|
9266
|
+
if ((await readdir(directory)).length) throw new Error(`A pasta de destino precisa estar vazia: ${directory}`);
|
|
9267
|
+
return true;
|
|
9268
|
+
} catch (error) {
|
|
9269
|
+
if (error.code === "ENOENT") return false;
|
|
9270
|
+
throw error;
|
|
9271
|
+
}
|
|
9272
|
+
}
|
|
9273
|
+
async function installDependencies(directory) {
|
|
9274
|
+
await new Promise((resolve, reject) => {
|
|
9275
|
+
const child = spawn("npm", [
|
|
9276
|
+
"install",
|
|
9277
|
+
"--ignore-scripts",
|
|
9278
|
+
"--no-audit",
|
|
9279
|
+
"--no-fund"
|
|
9280
|
+
], {
|
|
9281
|
+
cwd: directory,
|
|
9282
|
+
stdio: "inherit",
|
|
9283
|
+
shell: false
|
|
9284
|
+
});
|
|
9285
|
+
child.once("error", reject);
|
|
9286
|
+
child.once("exit", (code, signal) => {
|
|
9287
|
+
if (code === 0) resolve();
|
|
9288
|
+
else reject(/* @__PURE__ */ new Error(`npm install falhou${signal ? ` (${signal})` : ` com código ${code ?? "desconhecido"}`}.`));
|
|
9289
|
+
});
|
|
9290
|
+
});
|
|
9291
|
+
}
|
|
9292
|
+
var ROLE_LABELS = {
|
|
9293
|
+
HEADER: "Header migrado",
|
|
9294
|
+
FOOTER: "Footer migrado",
|
|
9295
|
+
HERO: "Hero/Banner migrado",
|
|
9296
|
+
HOME: "Home recriada",
|
|
9297
|
+
PRODUCT_CARD: "ProductCard adaptado",
|
|
9298
|
+
PRODUCT_GRID: "ProductGrid adaptado",
|
|
9299
|
+
PRODUCT_DETAIL: "ProductDetail adaptado",
|
|
9300
|
+
SECTION: "Sections genéricas adaptadas"
|
|
9301
|
+
};
|
|
9302
|
+
function printReport(report, outputDirectory) {
|
|
9303
|
+
const framework = report.framework === "next" ? "Next.js" : "Vite";
|
|
9304
|
+
console.log("");
|
|
9305
|
+
console.log(`✓ React + ${framework} identificado`);
|
|
9306
|
+
for (const [role, label] of Object.entries(ROLE_LABELS)) if (report.selectedComponents[role]) console.log(`✓ ${label}`);
|
|
9307
|
+
console.log(`✓ ${report.assetsCopied} asset(s) copiado(s)`);
|
|
9308
|
+
console.log(`✓ ${report.styleFilesPreserved} arquivo(s) de estilo preservado(s)`);
|
|
9309
|
+
if (report.tailwind.detected) console.log("✓ Tailwind detectado e configurado");
|
|
9310
|
+
for (const ignored of report.ignoredFiles) console.log(`⚠ ${ignored.file} ignorado: ${ignored.reason}`);
|
|
9311
|
+
for (const warning of report.warnings) console.log(`⚠ ${warning}`);
|
|
9312
|
+
console.log("");
|
|
9313
|
+
console.log("✓ Manifesto Nuvler validado");
|
|
9314
|
+
if (report.validation.typecheck) console.log("✓ Typecheck concluído");
|
|
9315
|
+
if (report.validation.build) console.log("✓ Build do tema concluído");
|
|
9316
|
+
console.log(`✓ Tema Nuvler gerado em ${outputDirectory}`);
|
|
9317
|
+
console.log("");
|
|
9318
|
+
}
|
|
9319
|
+
async function themeMigrate(options) {
|
|
9320
|
+
const sourceDirectory = path.resolve(options.sourceDirectory);
|
|
9321
|
+
const outputDirectory = path.resolve(options.outputDirectory);
|
|
9322
|
+
if (inside(sourceDirectory, outputDirectory) || inside(outputDirectory, sourceDirectory)) throw new Error("A origem e o destino não podem conter uma à outra. Use uma pasta irmã para preservar o projeto original.");
|
|
9323
|
+
const existingEmptyTarget = await ensureTargetAvailable(outputDirectory);
|
|
9324
|
+
const parent = path.dirname(outputDirectory);
|
|
9325
|
+
const temporary = await mkdtemp(path.join(parent, `.${path.basename(outputDirectory)}.nuvler-migrate-`));
|
|
9326
|
+
try {
|
|
9327
|
+
console.log("");
|
|
9328
|
+
console.log(`Analisando projeto React em ${sourceDirectory}...`);
|
|
9329
|
+
const generated = await generateMigratedTheme(createMigrationPlan(classifyProject(await analyzeReactProject(sourceDirectory)), {
|
|
9330
|
+
outputDirectory,
|
|
9331
|
+
id: options.id,
|
|
9332
|
+
name: options.name
|
|
9333
|
+
}), temporary);
|
|
9334
|
+
if (options.installDependencies !== false) {
|
|
9335
|
+
console.log("Instalando dependências do tema gerado...");
|
|
9336
|
+
await installDependencies(temporary);
|
|
9337
|
+
}
|
|
9338
|
+
generated.report.validation = await validateMigratedTheme(temporary, { runChecks: options.runChecks !== false });
|
|
9339
|
+
await writeMigrationReport(temporary, generated.report);
|
|
9340
|
+
if (existingEmptyTarget) await rmdir(outputDirectory);
|
|
9341
|
+
await rename(temporary, outputDirectory);
|
|
9342
|
+
printReport(generated.report, outputDirectory);
|
|
9343
|
+
return generated.report;
|
|
9344
|
+
} catch (error) {
|
|
9345
|
+
await rm(temporary, {
|
|
9346
|
+
recursive: true,
|
|
9347
|
+
force: true
|
|
9348
|
+
});
|
|
9349
|
+
throw error;
|
|
9350
|
+
}
|
|
9351
|
+
}
|
|
9352
|
+
//#endregion
|
|
7836
9353
|
//#region src/commands/theme/validate.ts
|
|
7837
9354
|
async function themeValidate(options) {
|
|
7838
9355
|
const project = await loadThemeProject(options.themeDirectory);
|
|
@@ -7875,7 +9392,7 @@ async function authLogout() {
|
|
|
7875
9392
|
//#endregion
|
|
7876
9393
|
//#region src/index.ts
|
|
7877
9394
|
var program = new Command();
|
|
7878
|
-
program.name("nuvler").description("Nuvler Theme Development CLI").version("0.
|
|
9395
|
+
program.name("nuvler").description("Nuvler Theme Development CLI").version("0.4.0");
|
|
7879
9396
|
var theme = program.command("theme").description("Manage Nuvler themes");
|
|
7880
9397
|
var auth = program.command("auth").description("Manage developer authentication");
|
|
7881
9398
|
auth.command("login").requiredOption("--token <token>", "Developer token").option("--api-url <url>", "Nuvler API base URL (or use NUVLER_API_URL)").action(async (options) => {
|
|
@@ -7902,6 +9419,22 @@ auth.command("logout").action(async () => {
|
|
|
7902
9419
|
process.exitCode = 1;
|
|
7903
9420
|
}
|
|
7904
9421
|
});
|
|
9422
|
+
theme.command("migrate").description("Analyze a React TypeScript project and generate a Nuvler theme").argument("<source>", "Existing Vite or Next.js project").requiredOption("--output <directory>", "New directory that will receive the Nuvler theme").option("--id <id>", "Generated theme id (defaults to the output directory name)").option("--name <name>", "Generated theme name (defaults to the source project name)").option("--skip-install", "Do not install dependencies in the generated project").option("--skip-checks", "Validate only the manifest; skip typecheck and build").action(async (source, options) => {
|
|
9423
|
+
try {
|
|
9424
|
+
await themeMigrate({
|
|
9425
|
+
sourceDirectory: source,
|
|
9426
|
+
outputDirectory: options.output,
|
|
9427
|
+
id: options.id,
|
|
9428
|
+
name: options.name,
|
|
9429
|
+
installDependencies: !options.skipInstall,
|
|
9430
|
+
runChecks: !options.skipChecks
|
|
9431
|
+
});
|
|
9432
|
+
} catch (error) {
|
|
9433
|
+
const message = error instanceof Error ? error.message : "Erro desconhecido.";
|
|
9434
|
+
console.error(`Erro: ${message}`);
|
|
9435
|
+
process.exitCode = 1;
|
|
9436
|
+
}
|
|
9437
|
+
});
|
|
7905
9438
|
theme.command("create").description("Create a new theme project from an official template").argument("<directory>", "Directory that will receive the theme").option("--id <id>", "Theme id (defaults to the directory name)").option("--name <name>", "Public theme name").option("--template <template>", "Base template: starter, nuvler-default or nuvler-atelier", "starter").action(async (directory, options) => {
|
|
7906
9439
|
try {
|
|
7907
9440
|
await themeCreate({
|