@nuvler/cli 0.4.5 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +10 -5
  2. package/dist/commands/theme/create.js +2 -2
  3. package/dist/commands/theme/dev.js +3 -1
  4. package/dist/commands/theme/dev.js.map +1 -1
  5. package/dist/commands/theme/migrate.js +7 -0
  6. package/dist/commands/theme/migrate.js.map +1 -1
  7. package/dist/index.js +1 -1
  8. package/dist/migrate/analysis/dependency-classifier.js +41 -0
  9. package/dist/migrate/analysis/dependency-classifier.js.map +1 -0
  10. package/dist/migrate/analysis/dependency-graph.js +210 -0
  11. package/dist/migrate/analysis/dependency-graph.js.map +1 -0
  12. package/dist/migrate/analyzer.js +102 -3
  13. package/dist/migrate/analyzer.js.map +1 -1
  14. package/dist/migrate/asset-copier.js +2 -2
  15. package/dist/migrate/asset-copier.js.map +1 -1
  16. package/dist/migrate/generation/fidelity-pass.js +233 -0
  17. package/dist/migrate/generation/fidelity-pass.js.map +1 -0
  18. package/dist/migrate/generator.js +1488 -64
  19. package/dist/migrate/generator.js.map +1 -1
  20. package/dist/migrate/resolvers/import-resolver.js +91 -0
  21. package/dist/migrate/resolvers/import-resolver.js.map +1 -0
  22. package/dist/migrate/transform/source-transformer.js +452 -0
  23. package/dist/migrate/transform/source-transformer.js.map +1 -0
  24. package/dist/migrate/transformer.js +326 -1
  25. package/dist/migrate/transformer.js.map +1 -1
  26. package/dist/nuvler.js +3601 -314
  27. package/dist/nuvler.js.map +1 -1
  28. package/dist/preview/prepare.js +8 -1
  29. package/dist/preview/prepare.js.map +1 -1
  30. package/dist/templates/nuvler-atelier/nuvler.theme.json +24 -10
  31. package/dist/templates/nuvler-atelier/package.json +3 -3
  32. package/dist/templates/nuvler-default/nuvler.theme.json +24 -10
  33. package/dist/templates/nuvler-default/package.json +9 -4
  34. package/dist/templates/nuvler-default/src/home.tsx +74 -2
  35. package/dist/templates/nuvler-default/src/theme-component.tsx +4 -3
  36. package/dist/templates/nuvler-default/src/theme.css +149 -0
  37. package/dist/templates/starter/nuvler.theme.json +1 -1
  38. package/dist/templates/starter/package.json +2 -2
  39. package/package.json +4 -4
  40. package/preview-host/package.json +1 -1
  41. package/preview-host/src/app/globals.css +5 -15
  42. package/preview-host/src/main.tsx +55 -5
  43. package/preview-host/vendor/theme-runtime/default-theme.tsx +131 -3
  44. package/preview-host/vite.config.ts +14 -0
@@ -1,7 +1,9 @@
1
1
  import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
+ import ts from "typescript";
3
4
  import { themeCreate } from "../commands/theme/create.js";
4
5
  import { copyMigrationAssets } from "./asset-copier.js";
6
+ import { mergeFidelityDependencies, runFidelityPass } from "./generation/fidelity-pass.js";
5
7
  function portable(file) {
6
8
  return file.split(path.sep).join("/");
7
9
  }
@@ -14,11 +16,6 @@ function profile(plan, role) {
14
16
  media: "", grid: "", card: "", content: "",
15
17
  };
16
18
  }
17
- function sourceText(plan, role, fallback) {
18
- const text = plan.selected[role]?.component.text
19
- .find((candidate) => candidate.length >= 3 && candidate.length <= 140);
20
- return text || fallback;
21
- }
22
19
  function headerSource(plan) {
23
20
  const style = profile(plan, "HEADER");
24
21
  return `import type { HeaderProps } from "@nuvler/theme-sdk";
@@ -30,16 +27,10 @@ export function Header({ site, categories, pages }: HeaderProps) {
30
27
  <a className=${classes("nuvler-migrated-brand", style.brand)} href="/">
31
28
  {site.settings?.logo?.url ? <img src={site.settings.logo.url} alt={site.settings.logo.alt || name} /> : <span>{name}</span>}
32
29
  </a>
33
- <nav className=${classes("nuvler-migrated-nav", style.navigation)} aria-label="Navegação principal">
34
- <a href="/">Início</a>
35
- {site.modules.includes("PRODUCTS") && <a href="/produtos">Produtos</a>}
30
+ <nav className=${classes("nuvler-migrated-nav", style.navigation)}>
36
31
  {categories.slice(0, 6).map((category) => <a href={\`/\${category.slug}\`} key={category.slug}>{category.name}</a>)}
37
32
  {pages.slice(0, 4).map((page) => <a href={\`/\${page.slug}\`} key={page.slug}>{page.title}</a>)}
38
33
  </nav>
39
- {site.modules.includes("PRODUCTS") && <form className="nuvler-migrated-search" action="/produtos">
40
- <input name="busca" type="search" placeholder="Buscar produtos" />
41
- <button className=${classes("nuvler-migrated-action", style.action)} type="submit">Buscar</button>
42
- </form>}
43
34
  </div>
44
35
  </header>;
45
36
  }
@@ -53,10 +44,8 @@ export function Footer({ site, pages, template }: FooterProps) {
53
44
  const name = site.settings?.siteName || site.tenant.name;
54
45
  return <footer className=${classes("nuvler-migrated-footer", style.root)}>
55
46
  <div className=${classes("nuvler-migrated-footer-inner", style.content)}>
56
- <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>
47
+ <div><strong className=${classes("nuvler-migrated-footer-brand", style.brand)}>{name}</strong>{site.settings?.description && <p className=${classes("nuvler-migrated-copy", style.text)}>{site.settings.description}</p>}</div>
57
48
  <nav className=${classes("nuvler-migrated-footer-nav", style.navigation)} aria-label={template.footerNavigationLabel}>
58
- <a href="/">Início</a>
59
- {site.modules.includes("PRODUCTS") && <a href="/produtos">Produtos</a>}
60
49
  {pages.map((page) => <a href={\`/\${page.slug}\`} key={page.slug}>{page.title}</a>)}
61
50
  </nav>
62
51
  <div className="nuvler-migrated-contact">
@@ -64,7 +53,7 @@ export function Footer({ site, pages, template }: FooterProps) {
64
53
  {site.settings?.contact.email && <a href={\`mailto:\${site.settings.contact.email}\`}>{site.settings.contact.email}</a>}
65
54
  </div>
66
55
  </div>
67
- <small>{template.footerNote}</small>
56
+ {template.footerNote && <small>{template.footerNote}</small>}
68
57
  </footer>;
69
58
  }
70
59
  `;
@@ -130,52 +119,455 @@ export function ProductDetail({ product, descriptionContent, onAddToCart }: Prod
130
119
  }
131
120
  `;
132
121
  }
133
- function homeSource(plan, assets) {
122
+ function fidelityHomeSource(fidelity) {
123
+ if (!fidelity.entryImportPath || !fidelity.entryExportName)
124
+ return null;
125
+ const pageImport = fidelity.entryDefaultExport
126
+ ? `import MigratedPage from ${JSON.stringify(fidelity.entryImportPath)};`
127
+ : `import { ${fidelity.entryExportName} as MigratedPage } from ${JSON.stringify(fidelity.entryImportPath)};`;
128
+ const layoutImports = fidelity.layoutImports.map((layout, index) => (layout.defaultExport
129
+ ? `import MigratedLayout${index} from ${JSON.stringify(layout.importPath)};`
130
+ : `import { ${layout.exportName} as MigratedLayout${index} } from ${JSON.stringify(layout.importPath)};`)).join("\n");
131
+ const content = fidelity.layoutImports.reduceRight((child, _layout, index) => `<MigratedLayout${index}>${child}</MigratedLayout${index}>`, "<MigratedPage />");
132
+ return `import type { HomeProps } from "@nuvler/theme-sdk";
133
+ import { MigratedContentProvider } from "../migrated-content.js";
134
+ ${pageImport}
135
+ ${layoutImports}
136
+
137
+ /** Fidelity Pass: a árvore original permanece ativa; somente o conteúdo é fornecido pelo Nuvler. */
138
+ export function Home(props: HomeProps) {
139
+ return <MigratedContentProvider {...props}>${content}</MigratedContentProvider>;
140
+ }
141
+ `;
142
+ }
143
+ function homeSource(plan, fidelity) {
144
+ const preserved = fidelityHomeSource(fidelity);
145
+ if (preserved)
146
+ return preserved;
134
147
  const home = profile(plan, "HOME");
135
- const hero = profile(plan, "HERO");
136
148
  const section = profile(plan, "SECTION");
137
- const heroText = sourceText(plan, "HERO", "Uma experiência criada para sua marca");
138
- const visual = assets.find(({ kind }) => ["image", "svg"].includes(kind));
139
- const visualDeclaration = visual
140
- ? `const migratedHeroAsset = new URL(${JSON.stringify(visual.importPath)}, import.meta.url).href;`
141
- : "const migratedHeroAsset: string | null = null;";
142
- return `import type { HomeProps, ThemeHomeSection } from "@nuvler/theme-sdk";
149
+ const bindings = plan.contentBindings.map(({ id, type, order, componentKey, classes: bindingClasses }) => ({
150
+ id, type, order, componentKey, classes: bindingClasses,
151
+ }));
152
+ return `import { useState, type FormEvent } from "react";
153
+ import type { HomeProps, ThemeContactSubmissionInput, ThemeEditorialItem, ThemeHomeSection } from "@nuvler/theme-sdk";
143
154
  import { ProductGrid } from "../components/ProductGrid.js";
144
155
 
145
- ${visualDeclaration}
156
+ type Binding = {
157
+ id: string;
158
+ type: ThemeHomeSection["type"];
159
+ order: number;
160
+ componentKey?: string;
161
+ classes: Record<"root" | "brand" | "navigation" | "title" | "text" | "action" | "media" | "grid" | "card" | "content", string>;
162
+ };
146
163
 
147
- function value(section: ThemeHomeSection | undefined, key: string): string {
148
- const candidate = section?.data[key];
164
+ const migratedBindings: Binding[] = ${JSON.stringify(bindings, null, 2)};
165
+
166
+ function cx(...values: Array<string | undefined>): string {
167
+ return values.filter(Boolean).join(" ");
168
+ }
169
+
170
+ function value(data: Record<string, unknown>, key: string): string {
171
+ const candidate = data[key];
149
172
  return typeof candidate === "string" ? candidate : "";
150
173
  }
151
174
 
152
- export function Home({ sections, products, site, template }: HomeProps) {
175
+ function limit(data: Record<string, unknown>): number {
176
+ const candidate = data.limit;
177
+ return typeof candidate === "number" && candidate > 0 ? Math.min(candidate, 24) : 8;
178
+ }
179
+
180
+ function record(value: unknown): Record<string, unknown> | null {
181
+ return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : null;
182
+ }
183
+
184
+ function media(data: Record<string, unknown>): { url: string; alt: string } | null {
185
+ const image = record(data.image);
186
+ const url = image ? value(image, "url") : value(data, "imageUrl");
187
+ if (!url) return null;
188
+ return { url, alt: (image ? value(image, "alt") : "") || value(data, "imageAlt") };
189
+ }
190
+
191
+ function bindingFor(section: ThemeHomeSection, index: number, sections: ThemeHomeSection[]): Binding | undefined {
192
+ if (section.id) {
193
+ const exact = migratedBindings.find((binding) => binding.id === section.id);
194
+ if (exact) return exact;
195
+ }
196
+ if (section.type === "theme-component" && typeof section.data.componentKey === "string") {
197
+ const custom = migratedBindings.find((binding) => binding.componentKey === section.data.componentKey);
198
+ if (custom) return custom;
199
+ }
200
+ const occurrence = sections.slice(0, index).filter((candidate) => candidate.type === section.type).length;
201
+ return migratedBindings.filter((binding) => binding.type === section.type)[occurrence]
202
+ ?? migratedBindings[index];
203
+ }
204
+
205
+ function heading(section: ThemeHomeSection, binding: Binding | undefined) {
206
+ const eyebrow = value(section.data, "eyebrow");
207
+ const title = value(section.data, "title");
208
+ if (!eyebrow && !title) return null;
209
+ return <header className="nuvler-migrated-section-heading">
210
+ {eyebrow && <span>{eyebrow}</span>}
211
+ {title && <h2 className={cx("nuvler-migrated-section-title", binding?.classes.title)}>{title}</h2>}
212
+ </header>;
213
+ }
214
+
215
+ function TextSection({ section, binding }: { section: ThemeHomeSection; binding?: Binding }) {
216
+ const eyebrow = value(section.data, "eyebrow");
217
+ const title = value(section.data, "title");
218
+ const description = value(section.data, "description") || value(section.data, "text") || value(section.data, "content");
219
+ const buttonLabel = value(section.data, "buttonLabel");
220
+ const buttonUrl = value(section.data, "buttonUrl");
221
+ const image = media(section.data);
222
+ if (!eyebrow && !title && !description && !image && !(buttonLabel && buttonUrl)) return null;
223
+ const hero = section.type === "hero";
224
+ return <section className={cx(hero ? "nuvler-migrated-hero" : "nuvler-migrated-section nuvler-migrated-generic", binding?.classes.root)} data-image-position={value(section.data, "imagePosition") || undefined}>
225
+ <div className={cx(hero ? "nuvler-migrated-hero-content" : "nuvler-migrated-section-content", binding?.classes.content)}>
226
+ {eyebrow && <span>{eyebrow}</span>}
227
+ {title && (hero
228
+ ? <h1 className={cx("nuvler-migrated-hero-title", binding?.classes.title)}>{title}</h1>
229
+ : <h2 className={cx("nuvler-migrated-section-title", binding?.classes.title)}>{title}</h2>)}
230
+ {description && <p className={cx("nuvler-migrated-copy", binding?.classes.text)}>{description}</p>}
231
+ {buttonLabel && buttonUrl && <a className={cx("nuvler-migrated-action", binding?.classes.action)} href={buttonUrl}>{buttonLabel}</a>}
232
+ </div>
233
+ {image && <div className={cx(hero ? "nuvler-migrated-hero-media" : "nuvler-migrated-section-media", binding?.classes.media)}><img src={image.url} alt={image.alt || title} /></div>}
234
+ </section>;
235
+ }
236
+
237
+ function ThemeComponent({ section, binding, submitContact }: { section: ThemeHomeSection; binding?: Binding; submitContact?: HomeProps["submitContact"] }) {
238
+ const props = record(section.data.props) ?? {};
239
+ const componentKey = value(section.data, "componentKey");
240
+ if (componentKey === "video") return <section className={cx("nuvler-migrated-section", binding?.classes.root)}><div className={binding?.classes.content}>{value(props, "eyebrow") && <span>{value(props, "eyebrow")}</span>}{value(props, "title") && <h2>{value(props, "title")}</h2>}{value(props, "description") && <p>{value(props, "description")}</p>}{value(props, "videoUrl") && <video className="nuvler-migrated-video" controls playsInline poster={value(props, "posterImageUrl") || undefined} src={value(props, "videoUrl")} />}</div></section>;
241
+ if (componentKey !== "contact-form") return <TextSection section={{ ...section, data: props }} binding={binding} />;
242
+ const configuredFields = Array.isArray(props.fields)
243
+ ? props.fields.map(record).filter((field): field is Record<string, unknown> => Boolean(field))
244
+ : [];
245
+ const fields = configuredFields.length ? configuredFields : [
246
+ { key: "name", label: "Nome", type: "text", required: true },
247
+ { key: "email", label: "E-mail", type: "email", required: true },
248
+ { key: "phone", label: "Telefone", type: "tel", required: false },
249
+ { key: "message", label: "Mensagem", type: "textarea", required: true },
250
+ ];
251
+ const [status, setStatus] = useState<"idle" | "sending" | "success" | "error">("idle");
252
+ const [error, setError] = useState("");
253
+ const submit = async (event: FormEvent<HTMLFormElement>) => {
254
+ event.preventDefault();
255
+ if (!submitContact) { setStatus("error"); setError("O envio de contatos ainda não está disponível."); return; }
256
+ const element = event.currentTarget;
257
+ const form = new FormData(element);
258
+ const values: ThemeContactSubmissionInput["values"] = {};
259
+ fields.forEach((field) => {
260
+ const key = value(field, "key");
261
+ if (!key) return;
262
+ if (value(field, "type") === "checkbox") { values[key] = form.has(key); return; }
263
+ const entries = form.getAll(key).map(String);
264
+ values[key] = entries.length > 1 ? entries : entries[0] ?? "";
265
+ });
266
+ setStatus("sending"); setError("");
267
+ try {
268
+ await submitContact({ formKey: componentKey, sectionId: section.id, values, pathname: typeof window === "undefined" ? undefined : window.location.pathname });
269
+ element.reset(); setStatus("success");
270
+ } catch (cause) {
271
+ setStatus("error"); setError(cause instanceof Error ? cause.message : "Não foi possível enviar o contato.");
272
+ }
273
+ };
274
+ return <section className={cx("nuvler-migrated-section nuvler-migrated-contact-form-section", binding?.classes.root)}>
275
+ <div className="nuvler-migrated-contact-form-copy">{value(props, "eyebrow") && <span>{value(props, "eyebrow")}</span>}<h2>{value(props, "title") || "Fale com nossa equipe"}</h2>{value(props, "description") && <p>{value(props, "description")}</p>}</div>
276
+ <form className="nuvler-migrated-contact-form" onSubmit={(event) => void submit(event)}>{fields.map((field) => {
277
+ const key = value(field, "key"); const type = value(field, "type") || "text"; const label = value(field, "label") || key; const required = field.required === true;
278
+ if (!key) return null;
279
+ if (type === "checkbox") return <label className="nuvler-migrated-form-wide nuvler-migrated-checkbox" key={key}><input name={key} required={required} type="checkbox" value="true" /><span>{label}</span></label>;
280
+ if (type === "select") { const options = Array.isArray(field.options) ? field.options.map(record).filter((item): item is Record<string, unknown> => Boolean(item)) : []; return <label key={key}><span>{label}</span><select name={key} required={required}>{options.map((option) => <option key={value(option, "value")} value={value(option, "value")}>{value(option, "label") || value(option, "value")}</option>)}</select></label>; }
281
+ return <label className={type === "textarea" ? "nuvler-migrated-form-wide" : ""} key={key}><span>{label}</span>{type === "textarea" ? <textarea name={key} placeholder={value(field, "placeholder")} required={required} rows={5} /> : <input name={key} placeholder={value(field, "placeholder")} required={required} type={["email", "tel", "url", "number"].includes(type) ? type : "text"} />}</label>;
282
+ })}<div className="nuvler-migrated-form-wide"><button className="nuvler-migrated-action" disabled={status === "sending"} type="submit">{status === "sending" ? "" : value(props, "submitLabel")}</button>{status === "success" && value(props, "successMessage") && <p role="status">{value(props, "successMessage")}</p>}{status === "error" && <p role="alert">{error}</p>}</div></form>
283
+ </section>;
284
+ }
285
+
286
+ function Banners({ section, binding }: { section: ThemeHomeSection; binding?: Binding }) {
287
+ const banners = Array.isArray(section.data.banners)
288
+ ? section.data.banners.map(record).filter((item): item is Record<string, unknown> => Boolean(item))
289
+ : [];
290
+ const configured = banners.map((banner) => ({ banner, image: media(banner) })).filter(({ image }) => Boolean(image));
291
+ if (!configured.length) return null;
292
+ return <section className={cx("nuvler-migrated-banners", binding?.classes.root)}>
293
+ {configured.map(({ banner, image }, index) => <article className={cx("nuvler-migrated-banner", binding?.classes.card)} key={value(banner, "id") || index}>
294
+ <img className={cx("nuvler-migrated-banner-media", binding?.classes.media)} src={image!.url} alt={image!.alt || value(banner, "title")} />
295
+ <div className={cx("nuvler-migrated-banner-content", binding?.classes.content)}>
296
+ {value(banner, "title") && <h2 className={binding?.classes.title}>{value(banner, "title")}</h2>}
297
+ {value(banner, "description") && <p className={binding?.classes.text}>{value(banner, "description")}</p>}
298
+ {value(banner, "buttonLabel") && value(banner, "buttonUrl") && <a className={cx("nuvler-migrated-action", binding?.classes.action)} href={value(banner, "buttonUrl")}>{value(banner, "buttonLabel")}</a>}
299
+ </div>
300
+ </article>)}
301
+ </section>;
302
+ }
303
+
304
+ function Products({ section, binding, products, site }: { section: ThemeHomeSection; binding?: Binding; products: HomeProps["products"]; site: HomeProps["site"] }) {
305
+ const category = value(section.data, "categorySlug");
306
+ const visible = products.filter((product) => !category || product.categories.some((item) => item.slug === category) || product.categoryPath?.includes(category)).slice(0, limit(section.data));
307
+ if (!visible.length) return null;
308
+ return <section className={cx("nuvler-migrated-section", binding?.classes.root)}>
309
+ {heading(section, binding)}
310
+ <div className={binding?.classes.grid}><ProductGrid products={visible} columns={site.settings?.catalog?.desktopColumns || 3} showCategory={site.settings?.catalog?.showCategory} showDescription={site.settings?.catalog?.showDescription} /></div>
311
+ </section>;
312
+ }
313
+
314
+ function EditorialCards({ section, binding, items, basePath }: { section: ThemeHomeSection; binding?: Binding; items: ThemeEditorialItem[]; basePath: string }) {
315
+ const visible = items.slice(0, limit(section.data));
316
+ if (!visible.length) return null;
317
+ return <section className={cx("nuvler-migrated-section", binding?.classes.root)}>
318
+ {heading(section, binding)}
319
+ <div className={cx("nuvler-migrated-editorial-grid", binding?.classes.grid)}>{visible.map((item) => {
320
+ const image = item.image ?? item.thumbnail ?? item.coverImage;
321
+ return <article className={cx("nuvler-migrated-editorial-card", binding?.classes.card)} key={item.slug}>
322
+ {image?.url && <a className={binding?.classes.media} href={\`\${basePath}/\${item.slug}\`}><img src={image.url} alt={image.alt || item.title} /></a>}
323
+ <div className={binding?.classes.content}><h3 className={binding?.classes.title}><a href={\`\${basePath}/\${item.slug}\`}>{item.title}</a></h3>{item.description && <p className={binding?.classes.text}>{item.description}</p>}</div>
324
+ </article>;
325
+ })}</div>
326
+ </section>;
327
+ }
328
+
329
+ function ConfiguredSection({ section, binding, products, posts, services, cases, site, submitContact }: { section: ThemeHomeSection; binding?: Binding } & Pick<HomeProps, "products" | "posts" | "services" | "cases" | "site" | "submitContact">) {
330
+ if (section.type === "theme-component") return <ThemeComponent section={section} binding={binding} submitContact={submitContact} />;
331
+ if (section.type === "banner-carousel") return <Banners section={section} binding={binding} />;
332
+ if (section.type === "products-grid" || section.type === "products-carousel") return <Products section={section} binding={binding} products={products} site={site} />;
333
+ if (section.type === "services-grid") return <EditorialCards section={section} binding={binding} items={services} basePath="/servicos" />;
334
+ if (section.type === "blog-grid") return <EditorialCards section={section} binding={binding} items={posts} basePath="/blog" />;
335
+ if (section.type === "cases-grid") return <EditorialCards section={section} binding={binding} items={cases} basePath="/cases" />;
336
+ return <TextSection section={section} binding={binding} />;
337
+ }
338
+
339
+ export function Home({ sections, products, posts, services, cases, site, submitContact }: HomeProps) {
153
340
  const enabled = sections.filter((item) => item.enabled).sort((left, right) => left.order - right.order);
154
- const heroSection = enabled.find((item) => item.type === "hero" || item.type === "banner-carousel");
155
- const productSection = enabled.find((item) => item.type === "products-grid" || item.type === "products-carousel");
156
- const name = site.settings?.siteName || site.tenant.name;
157
- const action = template.primaryAction(site.modules);
158
341
  return <main className=${classes("nuvler-migrated-home", home.root)}>
159
- <section className=${classes("nuvler-migrated-hero", hero.root || home.content)}>
160
- <div className=${classes("nuvler-migrated-hero-content", hero.content)}>
161
- <span>{${JSON.stringify(heroText)}}</span>
162
- <h1 className=${classes("nuvler-migrated-hero-title", hero.title)}>{value(heroSection, "title") || name}</h1>
163
- <p className=${classes("nuvler-migrated-copy", hero.text)}>{value(heroSection, "description") || site.settings?.description || "Conheça nossos produtos e soluções."}</p>
164
- <a className=${classes("nuvler-migrated-action", hero.action)} href={value(heroSection, "buttonUrl") || action.href}>{value(heroSection, "buttonLabel") || action.label}</a>
165
- </div>
166
- {migratedHeroAsset && <div className=${classes("nuvler-migrated-hero-media", hero.media)}><img src={migratedHeroAsset} alt="" /></div>}
167
- </section>
168
- {site.modules.includes("PRODUCTS") && <section className=${classes("nuvler-migrated-section", section.root)}>
169
- <header><span>Destaques</span><h2 className=${classes("nuvler-migrated-section-title", section.title)}>{value(productSection, "title") || "Produtos em destaque"}</h2></header>
170
- <ProductGrid products={products} columns={site.settings?.catalog?.desktopColumns || 3} showCategory={site.settings?.catalog?.showCategory} showDescription={site.settings?.catalog?.showDescription} />
171
- </section>}
172
- {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>)}
342
+ {enabled.map((item, index) => <ConfiguredSection section={item} binding={bindingFor(item, index, enabled)} products={products} posts={posts} services={services} cases={cases} site={site} submitContact={submitContact} key={item.id || \`\${item.type}-\${item.order}\`} />)}
173
343
  </main>;
174
344
  }
175
345
  `;
176
346
  }
347
+ function migratedContentSource(plan) {
348
+ const metadata = plan.contentBindings.map(({ id, type, order, componentKey }) => ({ id, type, order, componentKey }));
349
+ return `import { createContext, useContext, type FormEvent, type ReactNode } from "react";
350
+ import type { HomeProps, ThemeHomeSection } from "@nuvler/theme-sdk";
351
+
352
+ const MigratedContentContext = createContext<HomeProps | null>(null);
353
+ const bindingMetadata: ReadonlyArray<{ id: string; type: ThemeHomeSection["type"]; order: number; componentKey?: string }> = ${JSON.stringify(metadata, null, 2)};
354
+
355
+ export function MigratedContentProvider({ children, ...props }: HomeProps & { children: ReactNode }) {
356
+ return <MigratedContentContext.Provider value={props}>{children}</MigratedContentContext.Provider>;
357
+ }
358
+
359
+ function configuredSection(id: string, sections: ThemeHomeSection[]): ThemeHomeSection | undefined {
360
+ const exact = sections.find((section) => section.id === id);
361
+ if (exact) return exact;
362
+ const binding = bindingMetadata.find((candidate) => candidate.id === id);
363
+ if (!binding) return undefined;
364
+ if (binding.type === "theme-component" && binding.componentKey) {
365
+ const custom = sections.find((section) => section.enabled
366
+ && section.type === "theme-component"
367
+ && section.data.componentKey === binding.componentKey);
368
+ return custom;
369
+ }
370
+ const occurrence = bindingMetadata.filter((candidate) => candidate.type === binding.type && candidate.order < binding.order).length;
371
+ return sections.filter((section) => section.enabled && section.type === binding.type).sort((left, right) => left.order - right.order)[occurrence];
372
+ }
373
+
374
+ export function useMigratedSection(id: string): Record<string, unknown> {
375
+ const context = useContext(MigratedContentContext);
376
+ if (!context) return {};
377
+ if (id === "__header" || id === "__footer") {
378
+ const name = context.site.settings?.siteName || context.site.tenant.name;
379
+ const items = (context.menu ?? []).map((item) => ({ label: item.label, title: item.label, href: item.href, url: item.href }));
380
+ return {
381
+ title: name,
382
+ description: context.site.settings?.description || "",
383
+ image: context.site.settings?.logo || null,
384
+ imageUrl: context.site.settings?.logo?.url || "",
385
+ imageAlt: context.site.settings?.logo?.alt || name,
386
+ buttonLabel: "",
387
+ buttonUrl: "",
388
+ items,
389
+ };
390
+ }
391
+ const section = configuredSection(id, context.sections);
392
+ if (!section) return {};
393
+ if (section.type === "theme-component") {
394
+ const props = section.data.props;
395
+ return props && typeof props === "object" && !Array.isArray(props)
396
+ ? props as Record<string, unknown>
397
+ : {};
398
+ }
399
+ return section.data;
400
+ }
401
+
402
+ export function useMigratedContactForm(id: string) {
403
+ const context = useContext(MigratedContentContext);
404
+ return async (event: FormEvent<HTMLFormElement>): Promise<void> => {
405
+ event.preventDefault();
406
+ const element = event.currentTarget;
407
+ if (!context?.submitContact) {
408
+ element.dataset.nuvlerStatus = "unavailable";
409
+ element.dispatchEvent(new CustomEvent("nuvler:contact-error", { detail: { message: "Envio de contatos indisponível." } }));
410
+ return;
411
+ }
412
+ const section = configuredSection(id, context.sections);
413
+ const form = new FormData(element);
414
+ const values: Record<string, string | boolean | string[]> = {};
415
+ const configuredFields = section?.type === "theme-component" && section.data.props && typeof section.data.props === "object" && !Array.isArray(section.data.props)
416
+ ? migratedItems(section.data.props as Record<string, unknown>, "fields")
417
+ : [];
418
+ for (const field of configuredFields) {
419
+ const key = stringValue(field, "key");
420
+ if (key && stringValue(field, "type") === "checkbox") values[key] = form.has(key);
421
+ }
422
+ for (const key of new Set([...form.keys()])) {
423
+ const entries = form.getAll(key).filter((value): value is string => typeof value === "string");
424
+ values[key] = entries.length > 1 ? entries : entries[0] ?? "";
425
+ }
426
+ element.dataset.nuvlerStatus = "sending";
427
+ try {
428
+ const result = await context.submitContact({
429
+ formKey: section?.type === "theme-component" && typeof section.data.componentKey === "string" ? section.data.componentKey : "contact-form",
430
+ sectionId: section?.id,
431
+ values,
432
+ pathname: typeof window === "undefined" ? undefined : window.location.pathname,
433
+ });
434
+ element.reset();
435
+ element.dataset.nuvlerStatus = "success";
436
+ element.dispatchEvent(new CustomEvent("nuvler:contact-success", { detail: result }));
437
+ } catch (cause) {
438
+ const message = cause instanceof Error ? cause.message : "Não foi possível enviar o contato.";
439
+ element.dataset.nuvlerStatus = "error";
440
+ element.dispatchEvent(new CustomEvent("nuvler:contact-error", { detail: { message } }));
441
+ }
442
+ };
443
+ }
444
+
445
+ export function migratedItems(
446
+ data: Record<string, unknown>,
447
+ field = "items",
448
+ presentation: Record<string, unknown>[] = [],
449
+ ): Record<string, unknown>[] {
450
+ const value = data[field];
451
+ return Array.isArray(value)
452
+ ? value
453
+ .filter((item): item is Record<string, unknown> => Boolean(item) && typeof item === "object" && !Array.isArray(item))
454
+ .map((item, index) => {
455
+ const title = item.title ?? item.label ?? item.name;
456
+ const description = item.description ?? item.desc ?? item.text ?? item.sub;
457
+ const normalized = {
458
+ ...item,
459
+ ...(title === undefined ? {} : { title, label: item.label ?? title }),
460
+ ...(description === undefined ? {} : {
461
+ description,
462
+ desc: item.desc ?? description,
463
+ sub: item.sub ?? description,
464
+ }),
465
+ };
466
+ return presentation.length
467
+ ? { ...presentation[index % presentation.length], ...normalized }
468
+ : normalized;
469
+ })
470
+ : [];
471
+ }
472
+
473
+ export function MigratedContactFields({ data }: { data: Record<string, unknown> }) {
474
+ const configured = migratedItems(data, "fields");
475
+ const fields = configured;
476
+ return <>
477
+ {fields.map((field) => {
478
+ const key = stringValue(field, "key");
479
+ const type = stringValue(field, "type") || "text";
480
+ if (!key) return null;
481
+ if (type === "checkbox") return <label className="nuvler-migrated-form-wide nuvler-migrated-checkbox" data-field-key={key} key={key}>
482
+ <input name={key} required={field.required === true} type="checkbox" value="true" />
483
+ <span>{stringValue(field, "label") || key}{field.required === true ? " *" : ""}</span>
484
+ </label>;
485
+ if (type === "select") return <label data-field-key={key} key={key}>
486
+ <span>{stringValue(field, "label") || key}{field.required === true ? " *" : ""}</span>
487
+ <select name={key} required={field.required === true}>{migratedItems(field, "options").map((option) => <option key={stringValue(option, "value")} value={stringValue(option, "value")}>{stringValue(option, "label") || stringValue(option, "value")}</option>)}</select>
488
+ </label>;
489
+ return <label data-field-key={key} key={key}>
490
+ <span>{stringValue(field, "label") || key}{field.required === true ? " *" : ""}</span>
491
+ {type === "textarea"
492
+ ? <textarea name={key} placeholder={stringValue(field, "placeholder")} required={field.required === true} rows={5} />
493
+ : <input name={key} placeholder={stringValue(field, "placeholder")} required={field.required === true} type={["email", "tel", "url", "number"].includes(type) ? type : "text"} />}
494
+ </label>;
495
+ })}
496
+ <button type="submit">{stringValue(data, "submitLabel")}</button>
497
+ </>;
498
+ }
499
+
500
+ function stringValue(data: Record<string, unknown>, key: string): string {
501
+ const candidate = data[key];
502
+ return typeof candidate === "string" ? candidate : "";
503
+ }
504
+
505
+ export function migratedText(data: Record<string, unknown>, field: string): string {
506
+ if (field === "description") return stringValue(data, "description") || stringValue(data, "text") || stringValue(data, "content");
507
+ return stringValue(data, field);
508
+ }
509
+
510
+ export function migratedImage(data: Record<string, unknown>): string | undefined {
511
+ const image = data.image && typeof data.image === "object" && !Array.isArray(data.image)
512
+ ? data.image as Record<string, unknown>
513
+ : null;
514
+ return (image ? stringValue(image, "url") : "") || stringValue(data, "imageUrl") || stringValue(data, "posterImageUrl") || undefined;
515
+ }
516
+
517
+ export function migratedVideo(data: Record<string, unknown>): string | undefined {
518
+ return stringValue(data, "videoUrl") || undefined;
519
+ }
520
+
521
+ export function migratedLink(data: Record<string, unknown>): string | undefined {
522
+ return stringValue(data, "buttonUrl") || undefined;
523
+ }
524
+ `;
525
+ }
526
+ function migratedNextImageSource() {
527
+ return `import type { CSSProperties, ImgHTMLAttributes } from "react";
528
+
529
+ type StaticImage = { src: string; width?: number; height?: number };
530
+ type MigratedNextImageProps = Omit<ImgHTMLAttributes<HTMLImageElement>, "src"> & {
531
+ src: string | StaticImage;
532
+ alt: string;
533
+ fill?: boolean;
534
+ priority?: boolean;
535
+ quality?: number;
536
+ placeholder?: string;
537
+ blurDataURL?: string;
538
+ onLoadingComplete?: (image: HTMLImageElement) => void;
539
+ };
540
+
541
+ /** Adaptador browser-safe para projetos Next.js executados no preview Vite. */
542
+ export default function MigratedNextImage({
543
+ src, alt, fill, priority, quality: _quality, placeholder: _placeholder,
544
+ blurDataURL: _blurDataURL, onLoadingComplete, style, ...props
545
+ }: MigratedNextImageProps) {
546
+ const url = typeof src === "string" ? src : src?.src;
547
+ if (!url) return null;
548
+ const fillStyle: CSSProperties | undefined = fill
549
+ ? { position: "absolute", inset: 0, width: "100%", height: "100%", ...style }
550
+ : style;
551
+ return <img
552
+ {...props}
553
+ src={url}
554
+ alt={alt || ""}
555
+ loading={priority ? "eager" : props.loading}
556
+ style={fillStyle}
557
+ onLoad={onLoadingComplete ? (event) => onLoadingComplete(event.currentTarget) : props.onLoad}
558
+ />;
559
+ }
560
+ `;
561
+ }
177
562
  function definitionSource(plan) {
178
563
  const tokens = plan.tokens;
564
+ const fallbackSections = plan.contentBindings.map((binding) => ({
565
+ id: binding.id,
566
+ type: binding.type,
567
+ enabled: true,
568
+ order: binding.order,
569
+ data: blankBindingData(binding),
570
+ }));
179
571
  return `import manifestData from "../nuvler.theme.json" with { type: "json" };
180
572
  import { defineTheme, type ThemeHomeSection, type ThemeManifest } from "@nuvler/theme-sdk";
181
573
  import { Footer } from "./components/Footer.js";
@@ -184,9 +576,7 @@ import { ProductDetail } from "./components/ProductDetail.js";
184
576
  import { ProductGrid } from "./components/ProductGrid.js";
185
577
  import { Home } from "./sections/Home.js";
186
578
 
187
- function section(id: string, type: ThemeHomeSection["type"], order: number): ThemeHomeSection {
188
- return { id, type, enabled: true, order, data: {} };
189
- }
579
+ const migratedSections: ThemeHomeSection[] = ${JSON.stringify(fallbackSections, null, 2)};
190
580
 
191
581
  export const manifest = manifestData as ThemeManifest;
192
582
  export const themeDefinition = defineTheme({
@@ -203,13 +593,13 @@ export const themeDefinition = defineTheme({
203
593
  layout: ${JSON.stringify({ containerWidth: tokens.containerWidth, borderRadius: tokens.borderRadius })},
204
594
  },
205
595
  template: {
206
- announcement: ${JSON.stringify(plan.themeName)},
207
- footerTagline: "Experiência visual migrada para a plataforma Nuvler.",
596
+ announcement: "",
597
+ footerTagline: "",
208
598
  footerNavigationLabel: "Navegação",
209
- footerNote: ${JSON.stringify(plan.themeName)},
599
+ footerNote: "",
210
600
  socialLabel: "Redes sociais",
211
601
  benefits: [],
212
- fallbackSections: () => [section("migrated-hero", "hero", 0), section("migrated-products", "products-grid", 1)],
602
+ fallbackSections: () => migratedSections.map((section) => ({ ...section, data: { ...section.data } })),
213
603
  primaryAction: (modules) => modules.includes("PRODUCTS") ? { label: "Ver produtos", href: "/produtos" } : { label: "Saiba mais", href: "/" },
214
604
  },
215
605
  components: { Header, Footer, Home, ProductGrid, ProductDetail },
@@ -258,7 +648,7 @@ function statePageSource() {
258
648
  }
259
649
  `;
260
650
  }
261
- function themeSource() {
651
+ function themeSource(hasFidelityHome) {
262
652
  return `import type { CSSProperties } from "react";
263
653
  import type { NuvlerThemeProps, ThemeSite } from "@nuvler/theme-sdk";
264
654
  import { themeDefinition } from "./definition.js";
@@ -297,16 +687,980 @@ export default function Theme({ context, route = { type: "home" }, sdk }: Nuvler
297
687
  "--theme-radius": \`\${tokens.layout.borderRadius}px\`,
298
688
  "--theme-container": \`\${tokens.layout.containerWidth}px\`,
299
689
  } as CSSProperties;
690
+ const homeSections = context.home.content.sections.length
691
+ ? context.home.content.sections
692
+ : themeDefinition.template.fallbackSections();
300
693
  let content;
301
- 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} />;
694
+ if (route.type === "home") content = <Home sections={homeSections} products={context.catalog.products} posts={context.editorial.posts} services={context.editorial.services} cases={context.editorial.cases} site={site} menu={context.navigation.menu} pages={context.navigation.pages} submitContact={sdk?.contact?.submit} template={themeDefinition.template} />;
302
695
  else if (route.type === "catalog") content = <CatalogPage route={route} site={site} />;
303
696
  else if (route.type === "product") content = <ProductPage route={route} site={site} cart={sdk?.cart} />;
304
697
  else if (route.type === "editorial-list" || route.type === "editorial-detail") content = <EditorialPage route={route} />;
305
698
  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} />;
699
+ if (${JSON.stringify(hasFidelityHome)} && route.type === "home") {
700
+ return <div className="nuvler-migrated-theme nuvler-migrated-fidelity" style={style}>{content}</div>;
701
+ }
306
702
  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>;
307
703
  }
308
704
  `;
309
705
  }
706
+ function blankSectionData(type) {
707
+ if (type === "banner-carousel")
708
+ return { banners: [], autoplay: true };
709
+ if (type === "hero")
710
+ return { eyebrow: "", title: "", description: "", imageId: "", imageUrl: "", imageAlt: "", buttonLabel: "", buttonUrl: "" };
711
+ if (type === "image-text")
712
+ return { eyebrow: "", title: "", description: "", imageId: "", imageUrl: "", imageAlt: "", imagePosition: "left" };
713
+ if (type === "rich-text")
714
+ return { eyebrow: "", title: "", text: "" };
715
+ if (type === "cta")
716
+ return { eyebrow: "", title: "", description: "", buttonLabel: "", buttonUrl: "" };
717
+ if (type === "products-grid" || type === "products-carousel")
718
+ return { eyebrow: "", title: "", limit: 6, categorySlug: "" };
719
+ if (type === "theme-component")
720
+ return { componentKey: "custom-component", schemaVersion: 1, props: {} };
721
+ return { eyebrow: "", title: "", limit: 6 };
722
+ }
723
+ function blankBindingData(binding) {
724
+ if (binding.type !== "theme-component" || !binding.componentDefinition || !binding.componentKey) {
725
+ return blankSectionData(binding.type);
726
+ }
727
+ const props = {};
728
+ for (const field of binding.componentDefinition.fields) {
729
+ if (field.defaultValue !== undefined)
730
+ props[field.key] = field.defaultValue;
731
+ else if (field.control === "repeater")
732
+ props[field.key] = [];
733
+ else if (field.control === "contact-fields")
734
+ props[field.key] = [];
735
+ else if (field.control === "boolean")
736
+ props[field.key] = false;
737
+ else if (field.control === "number")
738
+ props[field.key] = field.min ?? 0;
739
+ else
740
+ props[field.key] = "";
741
+ }
742
+ return {
743
+ componentKey: binding.componentKey,
744
+ schemaVersion: binding.componentDefinition.schemaVersion,
745
+ props,
746
+ };
747
+ }
748
+ /** Mirrors the labels shown by the Gestão Home builder. */
749
+ const PANEL_SECTION_DEFINITIONS = {
750
+ hero: {
751
+ name: "Banner principal",
752
+ category: "Destaques",
753
+ description: "Uma abertura marcante com imagem, texto e botão.",
754
+ controls: [
755
+ { label: "Imagem do banner principal", fields: ["imageId", "imageUrl", "imageAlt"], note: "Ao escolher a imagem, URL e texto alternativo são preenchidos pelo painel." },
756
+ { label: "Chamada pequena", fields: ["eyebrow"] },
757
+ { label: "Título da seção", fields: ["title"] },
758
+ { label: "Descrição", fields: ["description"] },
759
+ { label: "Texto do botão", fields: ["buttonLabel"] },
760
+ { label: "Destino do botão", fields: ["buttonUrl"] },
761
+ ],
762
+ },
763
+ "banner-carousel": {
764
+ name: "Carrossel de banners",
765
+ category: "Destaques",
766
+ description: "Vários destaques alternando no topo da página.",
767
+ controls: [
768
+ { label: "Troca automática", fields: ["autoplay"] },
769
+ { label: "Banner 1, Banner 2…", fields: ["banners"], note: "Em cada banner: Imagem, Título, Descrição, Texto do botão e Destino do botão." },
770
+ ],
771
+ },
772
+ "image-text": {
773
+ name: "Imagem e texto",
774
+ category: "Conteúdo",
775
+ description: "Apresente uma história com conteúdo lado a lado.",
776
+ controls: [
777
+ { label: "Imagem da seção", fields: ["imageId", "imageUrl", "imageAlt"], note: "Ao escolher a imagem, URL e texto alternativo são preenchidos pelo painel." },
778
+ { label: "Chamada pequena", fields: ["eyebrow"] },
779
+ { label: "Título da seção", fields: ["title"] },
780
+ { label: "Texto", fields: ["description"] },
781
+ { label: "Posição da imagem", fields: ["imagePosition"] },
782
+ ],
783
+ },
784
+ "rich-text": {
785
+ name: "Bloco de texto",
786
+ category: "Conteúdo",
787
+ description: "Um título e texto livre para explicar o que quiser.",
788
+ controls: [
789
+ { label: "Chamada pequena", fields: ["eyebrow"] },
790
+ { label: "Título da seção", fields: ["title"] },
791
+ { label: "Conteúdo", fields: ["text"] },
792
+ ],
793
+ },
794
+ cta: {
795
+ name: "Chamada para ação",
796
+ category: "Conteúdo",
797
+ description: "Convide a pessoa a dar o próximo passo.",
798
+ controls: [
799
+ { label: "Chamada pequena", fields: ["eyebrow"] },
800
+ { label: "Título da seção", fields: ["title"] },
801
+ { label: "Descrição", fields: ["description"] },
802
+ { label: "Texto do botão", fields: ["buttonLabel"] },
803
+ { label: "Destino do botão", fields: ["buttonUrl"] },
804
+ ],
805
+ },
806
+ "services-grid": {
807
+ name: "Grade de serviços",
808
+ category: "Conteúdo automático",
809
+ description: "Mostra automaticamente os serviços cadastrados.",
810
+ controls: [
811
+ { label: "Chamada pequena", fields: ["eyebrow"] },
812
+ { label: "Título da seção", fields: ["title"] },
813
+ { label: "Quantidade de itens", fields: ["limit"] },
814
+ ],
815
+ contentSource: {
816
+ location: "Serviços → Lista de serviços",
817
+ description: "Os cards, textos e imagens da grade vêm dos serviços cadastrados.",
818
+ },
819
+ },
820
+ "blog-grid": {
821
+ name: "Últimos do blog",
822
+ category: "Conteúdo automático",
823
+ description: "Mantém as publicações recentes em evidência.",
824
+ controls: [
825
+ { label: "Chamada pequena", fields: ["eyebrow"] },
826
+ { label: "Título da seção", fields: ["title"] },
827
+ { label: "Quantidade de itens", fields: ["limit"] },
828
+ ],
829
+ contentSource: {
830
+ location: "Blog → Postagens",
831
+ description: "Os cards, textos e imagens da grade vêm das postagens publicadas.",
832
+ },
833
+ },
834
+ "cases-grid": {
835
+ name: "Cases de sucesso",
836
+ category: "Conteúdo automático",
837
+ description: "Exibe projetos e resultados já cadastrados.",
838
+ controls: [
839
+ { label: "Chamada pequena", fields: ["eyebrow"] },
840
+ { label: "Título da seção", fields: ["title"] },
841
+ { label: "Quantidade de itens", fields: ["limit"] },
842
+ ],
843
+ contentSource: {
844
+ location: "Cases → Cases",
845
+ description: "Os cards, textos e imagens da grade vêm dos cases publicados.",
846
+ },
847
+ },
848
+ "products-grid": {
849
+ name: "Grade de produtos",
850
+ category: "Conteúdo automático",
851
+ description: "Uma vitrine organizada de produtos cadastrados.",
852
+ controls: [
853
+ { label: "Chamada pequena", fields: ["eyebrow"] },
854
+ { label: "Título da seção", fields: ["title"] },
855
+ { label: "Quantidade de itens", fields: ["limit"] },
856
+ { label: "Categoria de produtos", fields: ["categorySlug"] },
857
+ ],
858
+ contentSource: {
859
+ location: "Produtos → Produtos",
860
+ description: "Os cards, textos e imagens da grade vêm dos produtos cadastrados.",
861
+ },
862
+ },
863
+ "products-carousel": {
864
+ name: "Carrossel de produtos",
865
+ category: "Conteúdo automático",
866
+ description: "Uma vitrine compacta para navegar pelos produtos.",
867
+ controls: [
868
+ { label: "Chamada pequena", fields: ["eyebrow"] },
869
+ { label: "Título da seção", fields: ["title"] },
870
+ { label: "Quantidade de itens", fields: ["limit"] },
871
+ { label: "Categoria de produtos", fields: ["categorySlug"] },
872
+ ],
873
+ contentSource: {
874
+ location: "Produtos → Produtos",
875
+ description: "Os cards, textos e imagens do carrossel vêm dos produtos cadastrados.",
876
+ },
877
+ },
878
+ "theme-component": {
879
+ name: "Componente do tema",
880
+ category: "Conteúdo",
881
+ description: "Componente configurável declarado pelo tema ativo.",
882
+ controls: [],
883
+ },
884
+ };
885
+ function panelDefinition(binding) {
886
+ const custom = binding.componentDefinition;
887
+ if (!custom)
888
+ return PANEL_SECTION_DEFINITIONS[binding.type];
889
+ return {
890
+ name: custom.name,
891
+ category: custom.category,
892
+ description: custom.description,
893
+ controls: custom.fields.map((field) => ({
894
+ label: field.label,
895
+ fields: [field.key],
896
+ note: field.control === "repeater"
897
+ ? "Lista repetível controlada pelo cliente no Gestão."
898
+ : field.control === "contact-fields"
899
+ ? "Permite escolher, ordenar e tornar obrigatórios os campos do formulário."
900
+ : undefined,
901
+ })),
902
+ };
903
+ }
904
+ function panelCompatibility(binding) {
905
+ if (binding.type === "theme-component") {
906
+ return {
907
+ level: "direct",
908
+ label: "Direto",
909
+ note: "O tema declara este componente e seus campos editáveis para o Construtor da Home.",
910
+ };
911
+ }
912
+ if (binding.type !== "rich-text") {
913
+ return {
914
+ level: "direct",
915
+ label: "Direto",
916
+ note: "Existe um bloco equivalente no Construtor da Home.",
917
+ };
918
+ }
919
+ const component = binding.component.toLowerCase();
920
+ if (/(video|faq|form|benefit|number|stat|metric|feature|evaluation|avali|app|forwhom|quem)/.test(component)) {
921
+ return {
922
+ level: "v1-fallback",
923
+ label: "Fallback V1",
924
+ note: "O Gestão ainda não possui um bloco nativo para esta estrutura; na V1 apenas título e texto ficam configuráveis como Bloco de texto.",
925
+ };
926
+ }
927
+ return {
928
+ level: "direct",
929
+ label: "Direto",
930
+ note: "O conteúdo textual pode ser configurado diretamente como Bloco de texto.",
931
+ };
932
+ }
933
+ function sourceKind(file) {
934
+ const extension = path.extname(file).toLowerCase();
935
+ if (extension === ".tsx")
936
+ return ts.ScriptKind.TSX;
937
+ if (extension === ".jsx")
938
+ return ts.ScriptKind.JSX;
939
+ if ([".js", ".mjs", ".cjs"].includes(extension))
940
+ return ts.ScriptKind.JS;
941
+ return ts.ScriptKind.TS;
942
+ }
943
+ function unwrappedExpression(expression) {
944
+ if (ts.isAsExpression(expression) || ts.isTypeAssertionExpression(expression) || ts.isParenthesizedExpression(expression)) {
945
+ return unwrappedExpression(expression.expression);
946
+ }
947
+ return expression;
948
+ }
949
+ function propertyKey(property) {
950
+ if (!(ts.isPropertyAssignment(property) || ts.isShorthandPropertyAssignment(property)))
951
+ return null;
952
+ const name = property.name;
953
+ return ts.isIdentifier(name) || ts.isStringLiteralLike(name) || ts.isNumericLiteral(name) ? name.text : null;
954
+ }
955
+ function propertyValue(object, key) {
956
+ const property = object.properties.find((candidate) => propertyKey(candidate) === key);
957
+ return property && ts.isPropertyAssignment(property) ? property.initializer : null;
958
+ }
959
+ function flattenStringObject(object, prefix = "", result = new Map()) {
960
+ for (const property of object.properties) {
961
+ if (!ts.isPropertyAssignment(property))
962
+ continue;
963
+ const key = propertyKey(property);
964
+ if (!key)
965
+ continue;
966
+ const compound = prefix ? `${prefix}.${key}` : key;
967
+ const value = unwrappedExpression(property.initializer);
968
+ if (ts.isStringLiteralLike(value) || ts.isNoSubstitutionTemplateLiteral(value))
969
+ result.set(compound, value.text);
970
+ else if (ts.isObjectLiteralExpression(value))
971
+ flattenStringObject(value, compound, result);
972
+ }
973
+ return result;
974
+ }
975
+ function translationValues(source) {
976
+ const result = new Map();
977
+ function visit(node) {
978
+ if (ts.isVariableDeclaration(node)
979
+ && ts.isIdentifier(node.name)
980
+ && /^(?:translations?|messages?|dictionary|locales?)$/i.test(node.name.text)
981
+ && node.initializer) {
982
+ const initializer = unwrappedExpression(node.initializer);
983
+ if (ts.isObjectLiteralExpression(initializer)) {
984
+ const locale = ["pt", "pt-BR", "pt_BR", "default"]
985
+ .map((key) => propertyValue(initializer, key))
986
+ .find((value) => Boolean(value));
987
+ const selected = locale ? unwrappedExpression(locale) : initializer;
988
+ if (ts.isObjectLiteralExpression(selected)) {
989
+ for (const [key, value] of flattenStringObject(selected))
990
+ result.set(key, value);
991
+ }
992
+ }
993
+ }
994
+ ts.forEachChild(node, visit);
995
+ }
996
+ visit(source);
997
+ return result;
998
+ }
999
+ function contentField(key) {
1000
+ const normalized = key.toLowerCase();
1001
+ const last = normalized.split(".").at(-1) ?? normalized;
1002
+ if (/^(?:eyebrow|overline|kicker)$/.test(last))
1003
+ return "eyebrow";
1004
+ if (/^(?:title|headline|heading)$/.test(last))
1005
+ return "title";
1006
+ if (/^(?:subtitle|subheadline|description|desc|text|content)$/.test(last))
1007
+ return "description";
1008
+ if (/(?:^|\.)(?:cta|button|action)(?:\.|$)/.test(normalized) || /^(?:cta|button|label)$/.test(last))
1009
+ return "buttonLabel";
1010
+ return undefined;
1011
+ }
1012
+ function jsxTagForText(node) {
1013
+ const parent = node.parent;
1014
+ return ts.isJsxElement(parent) ? parent.openingElement.tagName.getText() : "text";
1015
+ }
1016
+ function fieldForTag(tag) {
1017
+ if (/^h[1-6]$/i.test(tag))
1018
+ return "title";
1019
+ if (/^(?:p|blockquote)$/i.test(tag))
1020
+ return "description";
1021
+ if (/^(?:a|button)$/i.test(tag))
1022
+ return "buttonLabel";
1023
+ if (/^(?:span|small)$/i.test(tag))
1024
+ return "eyebrow";
1025
+ return undefined;
1026
+ }
1027
+ function markdownCell(value) {
1028
+ return value.replace(/\|/g, "\\|").replace(/\r?\n/g, "<br>");
1029
+ }
1030
+ async function extractContentCatalog(plan) {
1031
+ const sources = new Map();
1032
+ const translations = new Map();
1033
+ const constantNodes = new Map();
1034
+ const constants = new Map();
1035
+ for (const module of plan.analysis.sourceGraph.modules.filter(({ kind }) => kind === "SOURCE")) {
1036
+ const content = await readFile(module.absolutePath, "utf8");
1037
+ const source = ts.createSourceFile(module.absolutePath, content, ts.ScriptTarget.Latest, true, sourceKind(module.absolutePath));
1038
+ sources.set(module.file, { source, content });
1039
+ for (const [key, value] of translationValues(source))
1040
+ translations.set(key, value);
1041
+ function collectConstants(node) {
1042
+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer) {
1043
+ constantNodes.set(node.name.text, node.initializer);
1044
+ }
1045
+ ts.forEachChild(node, collectConstants);
1046
+ }
1047
+ collectConstants(source);
1048
+ }
1049
+ function resolvedString(expression, stack = new Set()) {
1050
+ const value = unwrappedExpression(expression);
1051
+ if (ts.isStringLiteralLike(value) || ts.isNoSubstitutionTemplateLiteral(value))
1052
+ return value.text;
1053
+ if (ts.isIdentifier(value)) {
1054
+ if (constants.has(value.text))
1055
+ return constants.get(value.text);
1056
+ if (stack.has(value.text))
1057
+ return null;
1058
+ const initializer = constantNodes.get(value.text);
1059
+ if (!initializer)
1060
+ return null;
1061
+ const next = new Set(stack).add(value.text);
1062
+ const resolved = resolvedString(initializer, next);
1063
+ if (resolved !== null)
1064
+ constants.set(value.text, resolved);
1065
+ return resolved;
1066
+ }
1067
+ if (ts.isTemplateExpression(value)) {
1068
+ let output = value.head.text;
1069
+ for (const span of value.templateSpans) {
1070
+ const resolved = resolvedString(span.expression, stack);
1071
+ if (resolved === null)
1072
+ return null;
1073
+ output += resolved + span.literal.text;
1074
+ }
1075
+ return output;
1076
+ }
1077
+ if (ts.isBinaryExpression(value) && value.operatorToken.kind === ts.SyntaxKind.PlusToken) {
1078
+ const left = resolvedString(value.left, stack);
1079
+ const right = resolvedString(value.right, stack);
1080
+ return left === null || right === null ? null : left + right;
1081
+ }
1082
+ return null;
1083
+ }
1084
+ for (const [name, expression] of constantNodes) {
1085
+ const value = resolvedString(expression);
1086
+ if (value !== null)
1087
+ constants.set(name, value);
1088
+ }
1089
+ const sections = plan.contentBindings.map((binding) => {
1090
+ const parsed = sources.get(binding.file);
1091
+ const componentAnalysis = plan.analysis.components.find((component) => component.file === binding.file && component.name === binding.component);
1092
+ const values = [];
1093
+ const extractedRepeaters = new Map();
1094
+ const formFields = [];
1095
+ const seen = new Set();
1096
+ const counters = new Map();
1097
+ const importedAssets = new Map();
1098
+ const add = (candidate) => {
1099
+ const value = candidate.value.trim().replace(/\s+/g, " ");
1100
+ if (!value || seen.has(`${candidate.kind}:${candidate.key}:${value}`))
1101
+ return;
1102
+ seen.add(`${candidate.kind}:${candidate.key}:${value}`);
1103
+ values.push({ ...candidate, value });
1104
+ };
1105
+ if (parsed) {
1106
+ const source = parsed.source;
1107
+ const attributeValue = (attributes, name) => {
1108
+ const attribute = attributes.properties.find((candidate) => (ts.isJsxAttribute(candidate) && candidate.name.getText(source) === name));
1109
+ if (!attribute?.initializer)
1110
+ return null;
1111
+ if (ts.isStringLiteral(attribute.initializer))
1112
+ return attribute.initializer.text;
1113
+ if (ts.isJsxExpression(attribute.initializer) && attribute.initializer.expression) {
1114
+ return resolvedString(attribute.initializer.expression);
1115
+ }
1116
+ return null;
1117
+ };
1118
+ const hasAttribute = (attributes, name) => attributes.properties.some((candidate) => (ts.isJsxAttribute(candidate) && candidate.name.getText(source) === name));
1119
+ const nodeText = (node) => {
1120
+ const chunks = [];
1121
+ const collect = (candidate) => {
1122
+ if (ts.isJsxText(candidate) && candidate.text.trim())
1123
+ chunks.push(candidate.text);
1124
+ else if (ts.isJsxExpression(candidate) && candidate.expression) {
1125
+ const value = resolvedString(candidate.expression);
1126
+ if (value)
1127
+ chunks.push(value);
1128
+ }
1129
+ ts.forEachChild(candidate, collect);
1130
+ };
1131
+ collect(node);
1132
+ return chunks.join(" ").trim().replace(/\s+/g, " ");
1133
+ };
1134
+ const fieldLabelText = (node) => {
1135
+ const chunks = [];
1136
+ const collect = (candidate) => {
1137
+ if ((ts.isJsxElement(candidate) || ts.isJsxSelfClosingElement(candidate))) {
1138
+ const tag = (ts.isJsxElement(candidate) ? candidate.openingElement.tagName : candidate.tagName).getText(source).toLowerCase();
1139
+ if (["input", "textarea", "select", "option"].includes(tag))
1140
+ return;
1141
+ }
1142
+ if (ts.isJsxText(candidate) && candidate.text.trim())
1143
+ chunks.push(candidate.text);
1144
+ else if (ts.isJsxExpression(candidate) && candidate.expression) {
1145
+ const value = resolvedString(candidate.expression);
1146
+ if (value)
1147
+ chunks.push(value);
1148
+ }
1149
+ ts.forEachChild(candidate, collect);
1150
+ };
1151
+ collect(node);
1152
+ return chunks.join(" ").trim().replace(/\s+/g, " ");
1153
+ };
1154
+ const nearbyFieldLabel = (node, type) => {
1155
+ let ancestor = node.parent;
1156
+ while (ancestor && !ts.isFunctionLike(ancestor)) {
1157
+ if (ts.isJsxElement(ancestor) && ancestor.openingElement.tagName.getText(source).toLowerCase() === "label") {
1158
+ const label = fieldLabelText(ancestor);
1159
+ if (label)
1160
+ return label;
1161
+ }
1162
+ if (ts.isJsxElement(ancestor)) {
1163
+ const index = ancestor.children.findIndex((child) => child === node || child.pos <= node.pos && child.end >= node.end);
1164
+ if (index >= 0) {
1165
+ const before = ancestor.children.slice(0, index).reverse();
1166
+ const after = ancestor.children.slice(index + 1);
1167
+ const siblings = type === "checkbox"
1168
+ ? [...after, ...before]
1169
+ : [...before, ...after];
1170
+ for (const sibling of siblings) {
1171
+ if (!sibling)
1172
+ continue;
1173
+ const label = fieldLabelText(sibling);
1174
+ if (label)
1175
+ return label;
1176
+ }
1177
+ }
1178
+ }
1179
+ ancestor = ancestor.parent;
1180
+ }
1181
+ return "";
1182
+ };
1183
+ const collectFormField = (node) => {
1184
+ if (binding.componentKey !== "contact-form")
1185
+ return;
1186
+ const opening = ts.isJsxElement(node) ? node.openingElement : node;
1187
+ const tag = opening.tagName.getText(source).toLowerCase();
1188
+ if (!["input", "textarea", "select"].includes(tag))
1189
+ return;
1190
+ const key = attributeValue(opening.attributes, "name")?.trim();
1191
+ if (!key || formFields.some((field) => field.key === key))
1192
+ return;
1193
+ const rawType = tag === "textarea" ? "textarea" : tag === "select" ? "select" : attributeValue(opening.attributes, "type") ?? "text";
1194
+ const type = ["text", "email", "tel", "url", "number", "textarea", "select", "checkbox"].includes(rawType)
1195
+ ? rawType
1196
+ : "text";
1197
+ const label = nearbyFieldLabel(node, type) || key;
1198
+ const field = {
1199
+ key,
1200
+ label,
1201
+ type,
1202
+ required: hasAttribute(opening.attributes, "required"),
1203
+ };
1204
+ const placeholder = attributeValue(opening.attributes, "placeholder")?.trim();
1205
+ if (placeholder)
1206
+ field.placeholder = placeholder;
1207
+ if (tag === "select" && ts.isJsxElement(node)) {
1208
+ const options = [];
1209
+ const visitOption = (candidate) => {
1210
+ if (ts.isJsxElement(candidate) && candidate.openingElement.tagName.getText(source).toLowerCase() === "option") {
1211
+ const optionLabel = nodeText(candidate);
1212
+ const optionValue = attributeValue(candidate.openingElement.attributes, "value") ?? optionLabel;
1213
+ if (optionLabel)
1214
+ options.push({ label: optionLabel, value: optionValue });
1215
+ return;
1216
+ }
1217
+ ts.forEachChild(candidate, visitOption);
1218
+ };
1219
+ visitOption(node);
1220
+ if (options.length)
1221
+ field.options = options;
1222
+ }
1223
+ formFields.push(field);
1224
+ };
1225
+ for (const statement of source.statements.filter(ts.isImportDeclaration)) {
1226
+ const specifier = statement.moduleSpecifier;
1227
+ if (!ts.isStringLiteralLike(specifier) || !statement.importClause)
1228
+ continue;
1229
+ const extension = path.extname(specifier.text).toLowerCase();
1230
+ if (!/[.](?:avif|gif|jpe?g|png|svg|webp|mp4|webm|ogg)$/i.test(extension))
1231
+ continue;
1232
+ const assetReference = specifier.text.startsWith(".")
1233
+ ? portable(path.normalize(path.join(path.dirname(binding.file), specifier.text)))
1234
+ : specifier.text;
1235
+ if (statement.importClause.name)
1236
+ importedAssets.set(statement.importClause.name.text, assetReference);
1237
+ if (statement.importClause.namedBindings && ts.isNamedImports(statement.importClause.namedBindings)) {
1238
+ for (const item of statement.importClause.namedBindings.elements)
1239
+ importedAssets.set(item.name.text, assetReference);
1240
+ }
1241
+ }
1242
+ function componentName(node) {
1243
+ if ("name" in node && node.name && ts.isIdentifier(node.name))
1244
+ return node.name.text;
1245
+ const parent = node.parent;
1246
+ return ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name) ? parent.name.text : null;
1247
+ }
1248
+ function extractRepeaters(body) {
1249
+ const contentLists = binding.contentLists ?? componentAnalysis?.contentLists ?? [];
1250
+ if (!contentLists.length)
1251
+ return;
1252
+ const declarations = new Map();
1253
+ function collectDeclarations(candidate) {
1254
+ if (ts.isVariableDeclaration(candidate) && ts.isIdentifier(candidate.name) && candidate.initializer) {
1255
+ const initializer = unwrappedExpression(candidate.initializer);
1256
+ if (ts.isArrayLiteralExpression(initializer))
1257
+ declarations.set(candidate.name.text, initializer);
1258
+ }
1259
+ ts.forEachChild(candidate, collectDeclarations);
1260
+ }
1261
+ collectDeclarations(source);
1262
+ const directArrays = [];
1263
+ function collectDirectArrays(candidate) {
1264
+ if (ts.isCallExpression(candidate)
1265
+ && ts.isPropertyAccessExpression(candidate.expression)
1266
+ && candidate.expression.name.text === "map") {
1267
+ const receiver = unwrappedExpression(candidate.expression.expression);
1268
+ if (ts.isArrayLiteralExpression(receiver))
1269
+ directArrays.push(receiver);
1270
+ }
1271
+ ts.forEachChild(candidate, collectDirectArrays);
1272
+ }
1273
+ collectDirectArrays(body);
1274
+ let directIndex = 0;
1275
+ for (const list of contentLists) {
1276
+ const array = list.sourceName ? declarations.get(list.sourceName) : directArrays[directIndex++];
1277
+ if (!array)
1278
+ continue;
1279
+ const items = [];
1280
+ for (const element of array.elements) {
1281
+ if (!ts.isExpression(element))
1282
+ continue;
1283
+ const value = unwrappedExpression(element);
1284
+ if (list.primitive) {
1285
+ const item = resolvedString(value) ?? (ts.isNumericLiteral(value) ? value.text : null);
1286
+ if (item !== null)
1287
+ items.push({ title: item });
1288
+ continue;
1289
+ }
1290
+ if (!ts.isObjectLiteralExpression(value))
1291
+ continue;
1292
+ const item = {};
1293
+ for (const property of value.properties) {
1294
+ if (!ts.isPropertyAssignment(property))
1295
+ continue;
1296
+ const key = propertyKey(property);
1297
+ if (!key || !list.itemFields.includes(key))
1298
+ continue;
1299
+ const itemValue = resolvedString(property.initializer)
1300
+ ?? (ts.isNumericLiteral(unwrappedExpression(property.initializer)) ? unwrappedExpression(property.initializer).getText(source) : null);
1301
+ if (itemValue !== null)
1302
+ item[key] = itemValue;
1303
+ }
1304
+ if (Object.keys(item).length)
1305
+ items.push(item);
1306
+ }
1307
+ extractedRepeaters.set(list.fieldKey, items);
1308
+ }
1309
+ }
1310
+ function visitContent(node) {
1311
+ if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node))
1312
+ collectFormField(node);
1313
+ if (binding.componentKey === "feature-list" && ts.isArrayLiteralExpression(node)) {
1314
+ for (const element of node.elements) {
1315
+ const item = resolvedString(element);
1316
+ if (item)
1317
+ add({ key: "data.item", value: item, kind: "text" });
1318
+ }
1319
+ }
1320
+ if (ts.isCallExpression(node)
1321
+ && ts.isIdentifier(node.expression)
1322
+ && node.expression.text === "t"
1323
+ && node.arguments[0]
1324
+ && ts.isStringLiteralLike(node.arguments[0])) {
1325
+ const key = node.arguments[0].text;
1326
+ add({ key, value: translations.get(key) ?? `[tradução não localizada: ${key}]`, kind: "text", field: contentField(key) });
1327
+ return;
1328
+ }
1329
+ if (ts.isJsxText(node) && node.text.trim()) {
1330
+ const tag = jsxTagForText(node);
1331
+ const count = (counters.get(tag) ?? 0) + 1;
1332
+ counters.set(tag, count);
1333
+ add({ key: `jsx.${tag}.${count}`, value: node.text, kind: "text", field: fieldForTag(tag) });
1334
+ return;
1335
+ }
1336
+ if (ts.isPropertyAssignment(node)) {
1337
+ const key = propertyKey(node);
1338
+ const value = resolvedString(node.initializer);
1339
+ if (key && value !== null && /^(?:title|headline|heading|subtitle|description|desc|text|content|label|cta|price|period|badge|question|answer|q|a|name|value|number|metric|num|role|email|phone|tel)$/i.test(key)) {
1340
+ add({ key: `data.${key}`, value, kind: "text", field: contentField(key) });
1341
+ }
1342
+ }
1343
+ if (ts.isJsxAttribute(node) && node.initializer) {
1344
+ const name = node.name.getText(source);
1345
+ const tag = node.parent.parent.tagName.getText(source).toLowerCase();
1346
+ let expression = null;
1347
+ if (ts.isStringLiteral(node.initializer))
1348
+ expression = node.initializer;
1349
+ else if (ts.isJsxExpression(node.initializer) && node.initializer.expression)
1350
+ expression = node.initializer.expression;
1351
+ const literal = expression ? resolvedString(expression) : null;
1352
+ const imported = expression && ts.isIdentifier(expression) ? importedAssets.get(expression.text) : undefined;
1353
+ const value = literal ?? imported ?? null;
1354
+ if (value && name === "href" && (tag === "a" || tag === "button"))
1355
+ add({ key: `${tag}.href`, value, kind: "link", field: "buttonUrl" });
1356
+ if (value && ["src", "poster"].includes(name) && ["img", "image", "video", "source", "iframe"].includes(tag)) {
1357
+ const field = name === "poster"
1358
+ ? "posterImageUrl"
1359
+ : binding.componentKey === "video" && (tag === "video" || tag === "source" || tag === "iframe")
1360
+ ? "videoUrl"
1361
+ : "imageUrl";
1362
+ add({ key: `${tag}.${name}`, value, kind: "media", field });
1363
+ }
1364
+ if (value && name === "alt" && ["img", "image"].includes(tag))
1365
+ add({ key: `${tag}.alt`, value, kind: "text", field: "imageAlt" });
1366
+ }
1367
+ ts.forEachChild(node, visitContent);
1368
+ }
1369
+ function findComponent(node) {
1370
+ if ((ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) || ts.isArrowFunction(node))
1371
+ && componentName(node) === binding.component
1372
+ && node.body) {
1373
+ extractRepeaters(node.body);
1374
+ visitContent(node.body);
1375
+ return;
1376
+ }
1377
+ ts.forEachChild(node, findComponent);
1378
+ }
1379
+ findComponent(source);
1380
+ }
1381
+ const sectionData = blankBindingData(binding);
1382
+ const data = binding.type === "theme-component"
1383
+ ? sectionData.props
1384
+ : sectionData;
1385
+ const availableFields = new Set(binding.fields);
1386
+ const selected = new Set();
1387
+ const assign = (field, candidate) => {
1388
+ if (!candidate || !availableFields.has(field))
1389
+ return;
1390
+ data[field] = candidate.kind === "media" ? "" : candidate.value;
1391
+ selected.add(candidate.key);
1392
+ };
1393
+ const rank = (field, item) => {
1394
+ if (field === "title" && /^jsx\.h[1-6]\./.test(item.key))
1395
+ return 0;
1396
+ if (field === "description" && /^jsx\.(?:p|blockquote)\./.test(item.key))
1397
+ return 0;
1398
+ if (field === "buttonLabel" && /^jsx\.(?:button|a)\./.test(item.key))
1399
+ return 0;
1400
+ if (field === "eyebrow" && /^jsx\.(?:span|small)\./.test(item.key))
1401
+ return 0;
1402
+ if (item.key.startsWith("jsx."))
1403
+ return 1;
1404
+ if (item.key.startsWith("data."))
1405
+ return 3;
1406
+ return 2;
1407
+ };
1408
+ const ranked = (field) => values
1409
+ .filter((item) => item.field === field && !(field === "eyebrow" && /(?:lgpd|consent|privacidade|tratamento dos meus dados|autorizo)/i.test(item.value)))
1410
+ .sort((left, right) => rank(field, left) - rank(field, right) || left.key.split(".").length - right.key.split(".").length)[0];
1411
+ const inferredEyebrow = ranked("eyebrow") ?? values.find((item) => (/^jsx\.div\./.test(item.key)
1412
+ && item.value.length <= 100
1413
+ && item.value === item.value.toLocaleUpperCase("pt-BR")
1414
+ && /[A-ZÀ-Ü]/.test(item.value)
1415
+ && !/(?:lgpd|consent|privacidade|tratamento dos meus dados|autorizo)/i.test(item.value)));
1416
+ assign("eyebrow", inferredEyebrow);
1417
+ assign("title", ranked("title"));
1418
+ const description = ranked("description");
1419
+ assign(availableFields.has("description") ? "description" : "text", description);
1420
+ assign("buttonLabel", ranked("buttonLabel"));
1421
+ assign("buttonUrl", ranked("buttonUrl"));
1422
+ assign("imageAlt", ranked("imageAlt"));
1423
+ assign("videoUrl", ranked("videoUrl"));
1424
+ assign("posterImageUrl", ranked("posterImageUrl"));
1425
+ if (binding.componentKey === "contact-form" && formFields.length && availableFields.has("fields")) {
1426
+ data.fields = formFields;
1427
+ }
1428
+ for (const [field, items] of extractedRepeaters) {
1429
+ if (availableFields.has(field))
1430
+ data[field] = items;
1431
+ }
1432
+ const media = ranked("imageUrl");
1433
+ if (media && availableFields.has("imageUrl"))
1434
+ selected.add(media.key);
1435
+ if (availableFields.has("text") && !data.text) {
1436
+ const remaining = values.filter(({ kind, key }) => kind === "text" && !selected.has(key) && !key.includes("tradução não localizada"));
1437
+ data.text = remaining.map(({ value }) => value).join("\n\n");
1438
+ }
1439
+ if (binding.type === "theme-component" && availableFields.has("items")) {
1440
+ const properties = values.filter(({ key, kind }) => key.startsWith("data.") && kind === "text");
1441
+ const items = [];
1442
+ if (binding.componentKey === "faq") {
1443
+ for (let index = 0; index < properties.length; index += 1) {
1444
+ const question = properties[index];
1445
+ if (!/(?:question|q)$/.test(question.key.toLowerCase()))
1446
+ continue;
1447
+ const answer = properties.slice(index + 1).find(({ key }) => /(?:answer|a)$/.test(key.toLowerCase()));
1448
+ items.push({ question: question.value, answer: answer?.value ?? "" });
1449
+ }
1450
+ }
1451
+ else if (binding.componentKey === "metrics") {
1452
+ let current = {};
1453
+ for (const property of properties) {
1454
+ const key = property.key.toLowerCase();
1455
+ if (/(?:value|number|metric)$/.test(key)) {
1456
+ if (Object.keys(current).length)
1457
+ items.push(current);
1458
+ current = { value: property.value };
1459
+ }
1460
+ else if (/(?:title|label|name)$/.test(key) && !current.title)
1461
+ current.title = property.value;
1462
+ else if (/(?:description|desc|text)$/.test(key) && !current.description)
1463
+ current.description = property.value;
1464
+ }
1465
+ if (Object.keys(current).length)
1466
+ items.push(current);
1467
+ }
1468
+ else if (binding.componentKey === "steps") {
1469
+ let current = {};
1470
+ for (const property of properties) {
1471
+ const key = property.key.toLowerCase();
1472
+ if (/(?:num|number|value)$/.test(key)) {
1473
+ if (Object.keys(current).length)
1474
+ items.push(current);
1475
+ current = { num: property.value };
1476
+ }
1477
+ else if (/(?:title|label|name)$/.test(key))
1478
+ current.title = property.value;
1479
+ else if (/(?:description|desc|text)$/.test(key))
1480
+ current.desc = property.value;
1481
+ }
1482
+ if (Object.keys(current).length)
1483
+ items.push(current);
1484
+ }
1485
+ else if (binding.componentKey === "contacts") {
1486
+ let current = {};
1487
+ for (const property of properties) {
1488
+ const key = property.key.toLowerCase();
1489
+ if (/(?:role)$/.test(key)) {
1490
+ if (Object.keys(current).length)
1491
+ items.push(current);
1492
+ current = { role: property.value };
1493
+ }
1494
+ else if (/(?:name)$/.test(key))
1495
+ current.name = property.value;
1496
+ else if (/(?:email)$/.test(key))
1497
+ current.email = property.value;
1498
+ else if (/(?:phone|tel)$/.test(key))
1499
+ current.phone = property.value;
1500
+ }
1501
+ if (Object.keys(current).length)
1502
+ items.push(current);
1503
+ }
1504
+ else if (binding.componentKey === "feature-list") {
1505
+ items.push(...values.filter(({ key }) => key === "data.item").map(({ value }) => ({ title: value })));
1506
+ }
1507
+ else {
1508
+ let current = {};
1509
+ for (const property of properties) {
1510
+ const key = property.key.toLowerCase();
1511
+ if (/(?:title|label|name)$/.test(key)) {
1512
+ if (current.title)
1513
+ items.push(current);
1514
+ current = { title: property.value };
1515
+ }
1516
+ else if (/(?:description|desc|text)$/.test(key) && current.title && !current.description) {
1517
+ current.description = property.value;
1518
+ }
1519
+ }
1520
+ if (Object.keys(current).length)
1521
+ items.push(current);
1522
+ }
1523
+ data.items = items;
1524
+ }
1525
+ return { id: binding.id, component: binding.component, file: binding.file, type: binding.type, order: binding.order, data: sectionData, sourceContent: values };
1526
+ });
1527
+ return {
1528
+ version: 1,
1529
+ locale: translations.size ? "pt" : "original",
1530
+ note: "Conteúdo de referência extraído do projeto original. Cadastre-o no painel; este arquivo não é carregado pelo tema em runtime.",
1531
+ sections,
1532
+ };
1533
+ }
1534
+ function homeConfiguration(plan) {
1535
+ return `${JSON.stringify({
1536
+ version: 1,
1537
+ sections: plan.contentBindings.map((binding) => ({ id: binding.id, type: binding.type, enabled: true, order: binding.order, data: blankBindingData(binding) })),
1538
+ }, null, 2)}\n`;
1539
+ }
1540
+ function contentMap(plan, catalog) {
1541
+ return `${JSON.stringify({
1542
+ version: 1,
1543
+ sourceProject: plan.analysis.projectName,
1544
+ note: "Preencha estes campos no painel Nuvler. Os valores extraídos estão em migration-content-seed.json; o tema não os publica hardcoded.",
1545
+ management: {
1546
+ location: "Home → Construtor",
1547
+ mode: "Montar",
1548
+ finalAction: "Salvar rascunho e Publicar",
1549
+ },
1550
+ sections: plan.contentBindings.map((binding) => {
1551
+ const serializableBinding = {
1552
+ id: binding.id,
1553
+ component: binding.component,
1554
+ file: binding.file,
1555
+ type: binding.type,
1556
+ order: binding.order,
1557
+ fields: binding.fields,
1558
+ componentKey: binding.componentKey,
1559
+ componentDefinition: binding.componentDefinition,
1560
+ };
1561
+ const definition = panelDefinition(binding);
1562
+ const compatibility = panelCompatibility(binding);
1563
+ return {
1564
+ ...serializableBinding,
1565
+ visualLink: `${binding.component} → ${definition.name} → ${binding.type}`,
1566
+ panel: {
1567
+ location: "Home → Construtor → Montar",
1568
+ category: definition.category,
1569
+ name: definition.name,
1570
+ description: definition.description,
1571
+ sectionId: binding.id,
1572
+ type: binding.type,
1573
+ order: binding.order,
1574
+ compatibility,
1575
+ controls: definition.controls,
1576
+ contentSource: definition.contentSource ?? null,
1577
+ data: blankBindingData(binding),
1578
+ },
1579
+ template: {
1580
+ hook: `useMigratedSection(${JSON.stringify(binding.id)})`,
1581
+ reads: binding.fields.map((field) => ({
1582
+ field,
1583
+ accessor: binding.type === "theme-component"
1584
+ ? `section.data.props.${field}`
1585
+ : `section.data.${field}`,
1586
+ })),
1587
+ },
1588
+ extractedContent: catalog.sections.find(({ id }) => id === binding.id)?.sourceContent ?? [],
1589
+ };
1590
+ }),
1591
+ }, null, 2)}\n`;
1592
+ }
1593
+ function contentGuide(plan, catalog) {
1594
+ const rows = plan.contentBindings.map((binding) => {
1595
+ const definition = panelDefinition(binding);
1596
+ const compatibility = panelCompatibility(binding);
1597
+ const source = definition.contentSource?.location ?? "Nesta própria seção";
1598
+ return `| ${binding.order + 1} | ${binding.component} | **${definition.name}** | \`${binding.type}\` | ${compatibility.label} | ${source} |`;
1599
+ }).join("\n");
1600
+ const details = catalog.sections.map((section) => {
1601
+ const binding = plan.contentBindings.find(({ id }) => id === section.id);
1602
+ const definition = binding ? panelDefinition(binding) : PANEL_SECTION_DEFINITIONS[section.type];
1603
+ const compatibility = binding ? panelCompatibility(binding) : null;
1604
+ const populatedData = Object.fromEntries(Object.entries(section.data).filter(([, value]) => value !== ""));
1605
+ const detected = section.sourceContent.map(({ key, value, kind, field }) => (`| \`${markdownCell(key)}\` | ${markdownCell(value)} | ${kind === "media" ? "mídia: faça upload no painel" : field ? `\`${field}\`` : "conteúdo adicional"} |`)).join("\n");
1606
+ const controls = definition.controls.map((control) => (`| ${control.label} | ${control.fields.map((field) => `\`${field}\``).join(", ")} | ${control.note ?? "-"} |`)).join("\n");
1607
+ const contentSource = definition.contentSource
1608
+ ? `\n**Conteúdo dos itens:** abra **${definition.contentSource.location}**. ${definition.contentSource.description}\n`
1609
+ : "";
1610
+ return `## ${section.order + 1}. ${section.component} → ${definition.name}
1611
+
1612
+ No Gestão: **Home → Construtor → Montar → ${definition.category} → ${definition.name}**.
1613
+ O nome técnico enviado pela API é \`${section.type}\`.
1614
+ ${compatibility ? `\n**Compatibilidade:** ${compatibility.label}. ${compatibility.note}\n` : ""}
1615
+ ${contentSource}
1616
+ | Rótulo que aparece no Gestão | Chave na API | Observação |
1617
+ | --- | --- | --- |
1618
+ ${controls}
1619
+
1620
+ Valores encontrados no projeto original para copiar no painel:
1621
+
1622
+ \`\`\`json
1623
+ ${JSON.stringify(populatedData, null, 2)}
1624
+ \`\`\`
1625
+
1626
+ Conteúdo encontrado no projeto original:
1627
+
1628
+ | Origem | Valor original | Destino sugerido |
1629
+ | --- | --- | --- |
1630
+ ${detected || "| - | Nenhum valor literal localizado | revise o componente original |"}
1631
+ `;
1632
+ }).join("\n");
1633
+ return `# Configuração de conteúdo no Nuvler
1634
+
1635
+ Este tema mantém os componentes e a estilização do projeto original. Textos,
1636
+ imagens e links são lidos das seções configuradas em **Home** no painel Nuvler.
1637
+
1638
+ No Gestão, abra **Home → Construtor**, mantenha o modo **Montar** e escolha os
1639
+ blocos pelos nomes da coluna **Bloco no Gestão**. Depois use **Salvar rascunho**
1640
+ e **Publicar**. Não procure por nomes técnicos como \`hero\`: na tela ele aparece
1641
+ como **Banner principal**.
1642
+
1643
+ Crie as seções abaixo na mesma ordem. O tema prioriza o ID descrito em
1644
+ \`nuvler.home.json\`; quando o painel gerar outro ID, ele associa por tipo e
1645
+ ocorrência na ordem da Home.
1646
+
1647
+ | Ordem | Componente no projeto | Bloco no Gestão | Tipo técnico/API | Compatibilidade | Onde cadastrar os itens |
1648
+ | ---: | --- | --- | --- | --- | --- |
1649
+ ${rows || "| - | Nenhuma seção detectada | - | - | - | - |"}
1650
+
1651
+ O arquivo \`nuvler.home.json\` é o blueprint vazio usado para conferir a estrutura.
1652
+ \`migration-content-seed.json\` guarda os valores extraídos para cadastro no painel,
1653
+ sem incluí-los no runtime do tema. \`migration-content-map.json\` documenta a ligação
1654
+ entre o componente, o painel e o template.
1655
+
1656
+ Referências de mídia apontam para o arquivo do projeto original. Faça o upload no
1657
+ painel e use a URL ou o ID retornado pelo Nuvler. Conteúdos adicionais sem campo
1658
+ equivalente ficam documentados abaixo; repeaters e schemas customizados continuam
1659
+ fora da V1.
1660
+
1661
+ ${details}
1662
+ `;
1663
+ }
310
1664
  function baseCss(plan) {
311
1665
  return `/* Fallback estrutural do adaptador Nuvler. Os estilos extraídos vêm depois deste bloco. */
312
1666
  * { box-sizing: border-box; }
@@ -326,6 +1680,16 @@ body { margin: 0; }
326
1680
  .nuvler-migrated-hero-media, .nuvler-migrated-product-media, .nuvler-migrated-detail-media { overflow: hidden; border-radius: var(--theme-radius); }
327
1681
  .nuvler-migrated-hero-media img, .nuvler-migrated-product-media img, .nuvler-migrated-detail-media img { display: block; width: 100%; height: 100%; object-fit: cover; }
328
1682
  .nuvler-migrated-section { padding-block: 56px; }
1683
+ .nuvler-migrated-contact-form-section { display: grid; grid-template-columns: minmax(0, .8fr) minmax(0, 1.2fr); align-items: start; gap: 48px; }
1684
+ .nuvler-migrated-contact-form-copy h2 { margin-block: 10px; }
1685
+ .nuvler-migrated-contact-form-copy p { color: var(--theme-text-muted); line-height: 1.7; }
1686
+ .nuvler-migrated-contact-form { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; border: 1px solid var(--theme-border); border-radius: var(--theme-radius); background: var(--theme-surface); padding: 24px; }
1687
+ .nuvler-migrated-contact-form label { display: grid; gap: 7px; }
1688
+ .nuvler-migrated-contact-form input, .nuvler-migrated-contact-form textarea, .nuvler-migrated-contact-form select { width: 100%; border: 1px solid var(--theme-border); border-radius: var(--theme-radius); background: var(--theme-background); color: var(--theme-text); padding: 12px 14px; font: inherit; }
1689
+ .nuvler-migrated-form-wide { grid-column: 1 / -1; }
1690
+ .nuvler-migrated-contact-form .nuvler-migrated-checkbox { display: flex; flex-direction: row; align-items: flex-start; gap: 10px; line-height: 1.55; }
1691
+ .nuvler-migrated-contact-form .nuvler-migrated-checkbox input { width: 18px; height: 18px; margin-top: 2px; padding: 0; accent-color: var(--theme-primary); }
1692
+ .nuvler-migrated-video { display: block; width: 100%; max-height: 720px; margin-top: 24px; border-radius: var(--theme-radius); background: #000; }
329
1693
  .nuvler-migrated-product-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 20px; }
330
1694
  .nuvler-migrated-product-grid[data-columns="4"] { grid-template-columns: repeat(4, minmax(0, 1fr)); }
331
1695
  .nuvler-migrated-product-card { overflow: hidden; border: 1px solid var(--theme-border); border-radius: var(--theme-radius); background: var(--theme-surface); }
@@ -337,7 +1701,7 @@ body { margin: 0; }
337
1701
  .nuvler-migrated-footer { margin-top: 64px; background: var(--theme-footer-background); color: var(--theme-footer-text); padding: 56px max(16px, calc((100% - var(--theme-container)) / 2)); }
338
1702
  .nuvler-migrated-footer-inner { width: 100%; display: grid; grid-template-columns: 2fr 1fr 1fr; gap: 40px; }
339
1703
  .nuvler-migrated-footer-nav, .nuvler-migrated-contact { display: grid; gap: 8px; }
340
- @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; } }
1704
+ @media (max-width: 850px) { .nuvler-migrated-header-inner, .nuvler-migrated-hero, .nuvler-migrated-contact-form-section, .nuvler-migrated-contact-form { grid-template-columns: 1fr; flex-direction: column; align-items: stretch; } .nuvler-migrated-form-wide { grid-column: auto; } .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; } }
341
1705
 
342
1706
  :root {
343
1707
  --theme-primary: ${plan.tokens.primary};
@@ -377,6 +1741,9 @@ function preservedCss(plan, copied) {
377
1741
  content = content.replace(/url\(\s*(["']?)([^)'"\s]+)\1\s*\)/gi, (full, _quote, reference) => {
378
1742
  if (/^(?:data:|https?:|#)/i.test(reference))
379
1743
  return full;
1744
+ const sourceAsset = sourceAssetFor(style, reference, plan);
1745
+ if (sourceAsset && sourceAsset.kind !== "font")
1746
+ return "none";
380
1747
  const asset = copiedAssetFor(style, reference, plan, copied);
381
1748
  if (!asset)
382
1749
  return full;
@@ -390,6 +1757,18 @@ function preservedCss(plan, copied) {
390
1757
  return `/* Origem: ${style.file}${style.module ? " (CSS Module convertido para CSS comum)" : ""} */\n${content}`;
391
1758
  }).join("\n\n");
392
1759
  }
1760
+ function sourceAssetFor(style, reference, plan) {
1761
+ const absolute = reference.startsWith("/")
1762
+ ? path.join(plan.analysis.sourceDirectory, "public", reference.replace(/^\/+/, ""))
1763
+ : path.resolve(path.dirname(style.absolutePath), reference);
1764
+ return plan.assets.find((asset) => path.resolve(asset.absolutePath) === path.resolve(absolute));
1765
+ }
1766
+ function classCatalog(plan) {
1767
+ const classNames = plan.analysis.components
1768
+ .flatMap((component) => component.jsx.flatMap((node) => node.classes))
1769
+ .filter((className) => !className.includes("url("));
1770
+ return `/** Classes observadas no projeto original. Mantém utilitários visuais sem copiar conteúdo. */\nexport const migratedClassCatalog = ${JSON.stringify([...new Set(classNames)].join(" "))};\n`;
1771
+ }
393
1772
  function externalCssImports(plan) {
394
1773
  const imports = plan.styles.flatMap(({ content }) => ([...content.matchAll(/@import\s+(?:url\(\s*)?(["'])(?:https?:\/\/[^"']+)\1\s*\)?[^;]*;?/gi)]
395
1774
  .map((match) => match[0].trim())));
@@ -408,7 +1787,11 @@ async function configureTailwind(plan, directory) {
408
1787
  metadata.devDependencies["@tailwindcss/postcss"] = plan.analysis.dependencies["@tailwindcss/postcss"] || "^4.0.0";
409
1788
  await writeFile(path.join(directory, "postcss.config.mjs"), "export default { plugins: { \"@tailwindcss/postcss\": {} } };\n", "utf8");
410
1789
  await writeFile(packageFile, `${JSON.stringify(metadata, null, 2)}\n`, "utf8");
411
- return '@import "tailwindcss";\n';
1790
+ // The production build reaches the copied TSX through the theme entry and
1791
+ // Tailwind discovers its classes automatically. The preview imports the
1792
+ // stylesheet from a Vite virtual module, so it needs an explicit source or
1793
+ // only the preview host's own classes are generated.
1794
+ return '@import "tailwindcss";\n@source "../**/*.{ts,tsx,js,jsx}";\n';
412
1795
  }
413
1796
  metadata.devDependencies.autoprefixer = plan.analysis.dependencies.autoprefixer || "^10.4.0";
414
1797
  const migratedColors = JSON.stringify(plan.analysis.tailwind.colors);
@@ -432,26 +1815,59 @@ export async function generateMigratedTheme(plan, directory) {
432
1815
  mkdir(path.join(directory, "src", "styles"), { recursive: true }),
433
1816
  mkdir(path.join(directory, "src", "pages"), { recursive: true }),
434
1817
  ]);
435
- const copiedAssets = await copyMigrationAssets(plan, directory);
1818
+ const fidelityEnabled = Boolean(plan.analysis.sourceGraph.entrypoint);
1819
+ const styleFiles = new Set(plan.styles.map((style) => style.file));
1820
+ const legacyAssets = fidelityEnabled
1821
+ ? plan.assets.filter((asset) => asset.kind === "font" && asset.referencedBy.some((file) => styleFiles.has(file)))
1822
+ : plan.assets;
1823
+ const copiedAssets = await copyMigrationAssets(plan, directory, legacyAssets);
1824
+ const fidelity = await runFidelityPass(plan, directory);
1825
+ await mergeFidelityDependencies(plan, directory);
1826
+ for (const file of fidelity.adaptedBusinessFiles) {
1827
+ plan.warnings.push(`${file}: regra de negócio isolada pela Nuvler Adaptation Pass; apresentação dependente preservada.`);
1828
+ }
436
1829
  const tailwindHeader = await configureTailwind(plan, directory);
1830
+ const extractedContent = await extractContentCatalog(plan);
437
1831
  await Promise.all([
438
1832
  writeFile(path.join(directory, "src/components/Header.tsx"), headerSource(plan), "utf8"),
439
1833
  writeFile(path.join(directory, "src/components/Footer.tsx"), footerSource(plan), "utf8"),
440
1834
  writeFile(path.join(directory, "src/components/ProductCard.tsx"), productCardSource(plan), "utf8"),
441
1835
  writeFile(path.join(directory, "src/components/ProductGrid.tsx"), productGridSource(plan), "utf8"),
442
1836
  writeFile(path.join(directory, "src/components/ProductDetail.tsx"), productDetailSource(plan), "utf8"),
443
- writeFile(path.join(directory, "src/sections/Home.tsx"), homeSource(plan, copiedAssets), "utf8"),
1837
+ writeFile(path.join(directory, "src/sections/Home.tsx"), homeSource(plan, fidelity), "utf8"),
444
1838
  writeFile(path.join(directory, "src/pages/CatalogPage.tsx"), catalogPageSource(), "utf8"),
445
1839
  writeFile(path.join(directory, "src/pages/ProductPage.tsx"), productPageSource(), "utf8"),
446
1840
  writeFile(path.join(directory, "src/pages/EditorialPage.tsx"), editorialPageSource(), "utf8"),
447
1841
  writeFile(path.join(directory, "src/pages/StatePage.tsx"), statePageSource(), "utf8"),
448
1842
  writeFile(path.join(directory, "src/definition.tsx"), definitionSource(plan), "utf8"),
449
- writeFile(path.join(directory, "src/theme.tsx"), themeSource(), "utf8"),
450
- writeFile(path.join(directory, "src/styles/theme.css"), `${tailwindHeader}${externalCssImports(plan)}\n${baseCss(plan)}\n${preservedCss(plan, copiedAssets)}\n`, "utf8"),
451
- writeFile(path.join(directory, "src/styles.d.ts"), 'declare module "*.css";\ndeclare module "*.svg";\n', "utf8"),
1843
+ writeFile(path.join(directory, "src/theme.tsx"), themeSource(Boolean(fidelity.entryImportPath)), "utf8"),
1844
+ writeFile(path.join(directory, "src/migrated-content.tsx"), migratedContentSource(plan), "utf8"),
1845
+ writeFile(path.join(directory, "src/migrated-next-image.tsx"), migratedNextImageSource(), "utf8"),
1846
+ writeFile(path.join(directory, "src/migrated-class-catalog.ts"), classCatalog(plan), "utf8"),
1847
+ writeFile(path.join(directory, "nuvler.home.json"), homeConfiguration(plan), "utf8"),
1848
+ writeFile(path.join(directory, "migration-content-seed.json"), `${JSON.stringify(extractedContent, null, 2)}\n`, "utf8"),
1849
+ writeFile(path.join(directory, "migration-content-map.json"), contentMap(plan, extractedContent), "utf8"),
1850
+ writeFile(path.join(directory, "CONTENT_SETUP.md"), contentGuide(plan, extractedContent), "utf8"),
1851
+ writeFile(path.join(directory, "src/styles/theme.css"), `${externalCssImports(plan)}\n${tailwindHeader}${baseCss(plan)}\n${preservedCss(plan, copiedAssets)}\n`, "utf8"),
1852
+ writeFile(path.join(directory, "src/styles.d.ts"), `declare module "*.module.css" { const classes: Record<string, string>; export default classes; }
1853
+ declare module "*.css";
1854
+ declare module "*.scss";
1855
+ declare module "*.sass";
1856
+ declare module "*.less";
1857
+ declare module "*.svg" { const url: string; export default url; }
1858
+ declare module "*.png" { const url: string; export default url; }
1859
+ declare module "*.jpg" { const url: string; export default url; }
1860
+ declare module "*.jpeg" { const url: string; export default url; }
1861
+ declare module "*.webp" { const url: string; export default url; }
1862
+ declare module "*.gif" { const url: string; export default url; }
1863
+ declare module "*.mp4" { const url: string; export default url; }
1864
+ declare module "*.webm" { const url: string; export default url; }
1865
+ `, "utf8"),
452
1866
  ]);
453
1867
  const manifestFile = path.join(directory, "nuvler.theme.json");
454
1868
  const manifest = JSON.parse(await readFile(manifestFile, "utf8"));
1869
+ const homeComponents = [...new Map(plan.contentBindings
1870
+ .flatMap((binding) => binding.componentDefinition ? [[binding.componentDefinition.key, binding.componentDefinition]] : [])).values()];
455
1871
  manifest.entry = "src/theme.tsx";
456
1872
  manifest.styles = ["src/styles/theme.css"];
457
1873
  manifest.presentation = {
@@ -478,6 +1894,7 @@ export async function generateMigratedTheme(plan, directory) {
478
1894
  containerWidth: plan.tokens.containerWidth,
479
1895
  borderRadius: plan.tokens.borderRadius,
480
1896
  },
1897
+ ...(homeComponents.length ? { homeComponents } : {}),
481
1898
  };
482
1899
  await writeFile(manifestFile, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
483
1900
  const selectedComponents = {};
@@ -493,8 +1910,15 @@ export async function generateMigratedTheme(plan, directory) {
493
1910
  sourceRoots: plan.analysis.sourceRoots,
494
1911
  componentsAnalyzed: plan.analysis.components.length,
495
1912
  selectedComponents,
496
- assetsCopied: copiedAssets.length,
497
- styleFilesPreserved: plan.styles.length,
1913
+ contentBindings: plan.contentBindings.map(({ classes: _classes, ...binding }) => binding),
1914
+ assetsCopied: fidelity.copiedAssets + copiedAssets.length,
1915
+ styleFilesPreserved: new Set([
1916
+ ...plan.styles.map((style) => style.file),
1917
+ ...plan.analysis.sourceGraph.modules.filter((module) => module.kind === "STYLE").map((module) => module.file),
1918
+ ]).size,
1919
+ sourceFilesPreserved: fidelity.copiedFiles,
1920
+ entrypoint: plan.analysis.sourceGraph.entrypoint,
1921
+ dependencies: plan.analysis.sourceGraph.dependencies,
498
1922
  tailwind: plan.analysis.tailwind,
499
1923
  ignoredFiles: plan.analysis.ignoredFiles,
500
1924
  warnings: [...new Set(plan.warnings)],