Skip to content

fix(migrate): close deterministic gaps between migrated and golden reference - #68

Closed
vibe-dex wants to merge 1 commit into
mainfrom
feat/migration-script-gaps
Closed

vibe-dex wants to merge 1 commit into
mainfrom
feat/migration-script-gaps

Conversation

@vibe-dex

@vibe-dex vibe-dex commented Apr 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes all script-fixable gaps identified by comparing the automated migration output against the manually migrated golden reference (casaevideo-storefront). Changes span 25 files across the migration pipeline.

Tier 1 — Pages not working (PDP, PLP, Search)

  • Section metadata analyzer: detect re-exported loader in barrel files and follow imports to check component-level device/mobile usage
  • Section-loaders template: register withDevice()/withMobile() for sections whose components need device info even without an explicit loader; remove hasLoader requirement for Account sections since vtexAccountLoaders provides loaders externally
  • Cleanup phase: add convertDirectComponentCalls() to transform <X.Component {...X?.props} .../> patterns to <RenderSection section={{...X, ...}} /> (fixes MountedPDP shipping simulation crash)
  • Scaffold phase: reorder to generate secrets.ts BEFORE commerce-loaders.ts so hasSecrets evaluates correctly, enabling ...secrets spread in productReviews and buyTogether loaders

Tier 2 — Visual differences

  • CSS template: use oklch(var(--x)) wrapping for oklch-formatted color variables instead of hardcoded hex; auto-detect --font-sans from @font-face declarations when theme config doesn't provide it

Tier 3 — Loader import cleanup

  • Replace inline getSegmentFromBag/fetchSafe/getISCookiesFromBag stubs (from dead-code transform) with proper imports from ~/lib/* modules
  • Rewrite ~/utils/retry imports to @decocms/start/sdk/retry
  • Rewrite Props type imports from non-existent productListingPage module to ~/types/vtex-loaders with new PLPProps type
  • Generate src/sdk/logger.ts console wrapper stub during scaffold

Tier 4 — Polish

  • Add "modalType" and "Modal Type" to useVariantPossiblities omit set (prevents broken variant selectors)
  • Add normalizeImportCasing cleanup step for case-sensitive filesystems (Linux CI)

Test plan

  • Run migration script against casaevideo source repo
  • Compare migrated output with golden reference (casaevideo-storefront)
  • Build migrated site (npm run build)
  • Deploy and verify homepage, PDP, PLP, search pages load correctly
  • Verify CSS colors match golden reference (oklch theming)
  • Verify Account pages render (vtexAccountLoaders registration)

Made with Cursor


Summary by cubic

Closes all script-fixable gaps between the migration output and the golden reference, fixing PDP/PLP/Search and aligning CSS and loader behavior. Reduces manual follow-ups so migrated stores build and run out of the box.

  • Bug Fixes

    • Detect loader re-exports and follow barrel imports; auto-register withDevice()/withMobile() for sections that need device info even without a local loader.
    • Convert <X.Component {...X?.props} /> to <RenderSection section={{ ...X, ... }} />, fixing the MountedPDP shipping crash.
    • Generate src/utils/secrets.ts before commerce loaders; spread secrets into product reviews and buy-together loaders.
    • Use oklch(var(--...)) for theme colors and auto-detect --font-sans from @font-face.
    • Replace stubbed helpers with ~/lib/* imports; rewrite retries to @decocms/start/sdk/retry; fix PLP types in ~/types/vtex-loaders.
    • Allow Account sections without local loaders (wired through registered vtexAccountLoaders); normalize import casing and add variant omit keys to prevent broken selectors.
  • Refactors

    • Add src/lib/* utility wrappers to bridge old VTEX helpers and signatures, reducing inline stubs.
    • Improve analyzers (islands and sections) with named re-export and device-usage detection.
    • Expand transforms: strip non-active platform code, remove jsdom/dompurify patterns, and remap VTEX hooks to local implementations.
    • Update templates: section loaders (account + device), commerce loaders (secrets-aware), routes/setup (font discovery), Picture component, and CSS generation; choose the largest block file when names collide.
    • Refresh server/Vite/Wrangler scaffolding with VTEX proxy defaults and invoke generation; add src/sdk/logger.ts.

Written for commit 7e4989b. Summary will update on new commits.

…ference

Tier 1 — Pages not working (PDP, PLP, Search):
- Analyzer: detect re-exported loaders and follow barrel files for device usage
- Section-loaders: register withDevice/withMobile for sections whose components
  need device info, even when the section file has no explicit loader
- Section-loaders: remove hasLoader requirement for Account sections (vtexAccountLoaders
  provides the loader externally)
- Cleanup: add convertDirectComponentCalls to transform <X.Component {...X?.props} .../>
  to <RenderSection section={{...X, ...}} /> (fixes MountedPDP shipping crash)
- Scaffold: reorder to generate secrets.ts BEFORE commerce-loaders.ts so the
  hasSecrets check works, enabling ...secrets spread in reviews/buyTogether loaders

Tier 2 — Visual differences:
- CSS: use oklch(var(--x)) wrapping for oklch-formatted color vars instead of
  hardcoded hex values; detect --font-sans from @font-face declarations

Tier 3 — Loader import cleanup:
- Replace inline getSegmentFromBag/fetchSafe/getISCookiesFromBag stubs with
  proper imports from ~/lib/* modules
- Rewrite ~/utils/retry imports to @decocms/start/sdk/retry
- Rewrite Props type imports from non-existent productListingPage module to
  ~/types/vtex-loaders with PLPProps type
- Generate src/sdk/logger.ts console wrapper stub

Tier 4 — Polish:
- Add modalType/Modal Type to useVariantPossiblities omit set
- Add normalizeImportCasing cleanup step for case-sensitive filesystems

Made-with: Cursor

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

10 issues found across 25 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="scripts/migrate/templates/app-css.ts">

<violation number="1" location="scripts/migrate/templates/app-css.ts:24">
P2: Sort the styles/ entries before choosing the first CSS file so migrations are deterministic when multiple CSS files exist.</violation>
</file>

<file name="scripts/migrate/templates/server-entry.ts">

<violation number="1" location="scripts/migrate/templates/server-entry.ts:108">
P1: Site-specific third-party CSP domains (Facebook, TikTok, Hotjar, Clarity, Bing Ads) are hardcoded in the generic migration template. Every migrated site will receive casaevideo's analytics domains instead of their own. Consider keeping the old pattern with generic VTEX wildcards and a clear `TODO` for site-specific additions, or extracting these from the site's actual configuration at migration time.</violation>
</file>

<file name="scripts/migrate/templates/ui-components.ts">

<violation number="1" location="scripts/migrate/templates/ui-components.ts:135">
P1: Escape "<" in JSON-LD before injecting to avoid `</script>` tag break‑out/XSS when jsonLDs includes user-controlled strings.</violation>
</file>

<file name="scripts/migrate/templates/section-loaders.ts">

<violation number="1" location="scripts/migrate/templates/section-loaders.ts:404">
P1: Hardcoded fallback `"casaevideonewio"` leaks the golden-reference account name into the template. When `ctx.vtexAccount` is `null` for a different store, the generated cookie check will look for the wrong `VtexIdclientAutCookie_*` cookie, silently breaking the logged-in detection for the PrivacyPolice section.</violation>
</file>

<file name="scripts/migrate/phase-cleanup.ts">

<violation number="1" location="scripts/migrate/phase-cleanup.ts:995">
P1: This condition is always false — `"<RenderSection"` is a superset of `"RenderSection"`, so the second `includes` check can never fail when the first succeeds. The auto-import for `RenderSection` will never fire, causing build errors when `convertDirectComponentCalls` introduces `<RenderSection` in files that don't already import it.

Check for the import statement specifically instead of the bare identifier.</violation>
</file>

<file name="scripts/migrate/phase-analyze.ts">

<violation number="1" location="scripts/migrate/phase-analyze.ts:159">
P2: The KNOWN_THIRD_PARTY regex doesn't anchor the end of the package name. `from\s+["']@sentry/react` will match `from "@sentry/react-native"`, adding the wrong dependency. Append `["'/]` to require the import to end with a quote (exact match) or `/` (sub-path import).</violation>

<violation number="2" location="scripts/migrate/phase-analyze.ts:415">
P2: The `\w+` fallback in the `dictMatch` alternation makes `\w+myvtex` and `\w+newio` redundant and causes the regex to match the first arbitrary `"word": "word"` pair in the file instead of specifically the VTEX account value. Either remove the `\w+` catch-all or, if a general fallback is needed, iterate all matches and prefer those with `myvtex`/`newio` suffixes.</violation>
</file>

<file name="scripts/migrate/templates/lib-utils.ts">

<violation number="1" location="scripts/migrate/templates/lib-utils.ts:68">
P2: The object branch of withDefaultParams overwrites existing params with defaults. Defaults should only fill missing keys; this currently replaces caller-provided values.</violation>
</file>

<file name="scripts/migrate/analyzers/section-metadata.ts">

<violation number="1" location="scripts/migrate/analyzers/section-metadata.ts:76">
P2: `readReExportTargetContent` only reads the first re-export target, so barrel files with multiple `export { ... } from` entries can miss the loader file and misclassify loader/device/url metadata. Consider iterating all re-export targets (or at least the one containing `loader`) and combining their contents.</violation>
</file>

<file name="scripts/migrate/analyzers/island-classifier.ts">

<violation number="1" location="scripts/migrate/analyzers/island-classifier.ts:53">
P2: `hasOtherCode` only allows single identifiers in multi-line export lists, so named re-export barrels that use `default as`, `Foo as Bar`, or `type Foo` are misclassified as standalone islands. That prevents wrapper detection for those valid export styles.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

"font-src 'self' fonts.gstatic.com data:",
// TODO: Add site-specific domains (analytics, CDN, tag managers)
"default-src 'self'",
"script-src 'self' 'unsafe-inline' 'unsafe-eval' https://www.googletagmanager.com https://connect.facebook.net https://analytics.tiktok.com https://script.hotjar.com https://static.hotjar.com https://scripts.clarity.ms https://www.clarity.ms https://sp.vtex.com https://bat.bing.com https://s.lilstts.com https://storage.googleapis.com",

@cubic-dev-ai cubic-dev-ai Bot Apr 6, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: Site-specific third-party CSP domains (Facebook, TikTok, Hotjar, Clarity, Bing Ads) are hardcoded in the generic migration template. Every migrated site will receive casaevideo's analytics domains instead of their own. Consider keeping the old pattern with generic VTEX wildcards and a clear TODO for site-specific additions, or extracting these from the site's actual configuration at migration time.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At scripts/migrate/templates/server-entry.ts, line 108:

<comment>Site-specific third-party CSP domains (Facebook, TikTok, Hotjar, Clarity, Bing Ads) are hardcoded in the generic migration template. Every migrated site will receive casaevideo's analytics domains instead of their own. Consider keeping the old pattern with generic VTEX wildcards and a clear `TODO` for site-specific additions, or extracting these from the site's actual configuration at migration time.</comment>

<file context>
@@ -70,115 +73,116 @@ export default createDecoWorkerEntry(serverEntry, {
-  "font-src 'self' fonts.gstatic.com data:",
-  // TODO: Add site-specific domains (analytics, CDN, tag managers)
+  "default-src 'self'",
+  "script-src 'self' 'unsafe-inline' 'unsafe-eval' https://www.googletagmanager.com https://connect.facebook.net https://analytics.tiktok.com https://script.hotjar.com https://static.hotjar.com https://scripts.clarity.ms https://www.clarity.ms https://sp.vtex.com https://bat.bing.com https://s.lilstts.com https://storage.googleapis.com",
+  "img-src 'self' data: https: blob:",
+  "style-src 'self' 'unsafe-inline' https:",
</file context>
Fix with Cubic

<script
key={i}
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLD) }}

@cubic-dev-ai cubic-dev-ai Bot Apr 6, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: Escape "<" in JSON-LD before injecting to avoid </script> tag break‑out/XSS when jsonLDs includes user-controlled strings.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At scripts/migrate/templates/ui-components.ts, line 135:

<comment>Escape "<" in JSON-LD before injecting to avoid `</script>` tag break‑out/XSS when jsonLDs includes user-controlled strings.</comment>

<file context>
@@ -107,6 +112,32 @@ export default function Video({
+        <script
+          key={i}
+          type="application/ld+json"
+          dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLD) }}
+        />
+      ))}
</file context>
Suggested change
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLD) }}
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLD).replace(/</g, "\\u003c") }}
Fix with Cubic

// ---------- Privacy cookie check ----------
if (isVtex && hasPrivacyPolice) {
entries.push(``);
const vtexAccount = ctx.vtexAccount || "casaevideonewio";

@cubic-dev-ai cubic-dev-ai Bot Apr 6, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: Hardcoded fallback "casaevideonewio" leaks the golden-reference account name into the template. When ctx.vtexAccount is null for a different store, the generated cookie check will look for the wrong VtexIdclientAutCookie_* cookie, silently breaking the logged-in detection for the PrivacyPolice section.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At scripts/migrate/templates/section-loaders.ts, line 404:

<comment>Hardcoded fallback `"casaevideonewio"` leaks the golden-reference account name into the template. When `ctx.vtexAccount` is `null` for a different store, the generated cookie check will look for the wrong `VtexIdclientAutCookie_*` cookie, silently breaking the logged-in detection for the PrivacyPolice section.</comment>

<file context>
@@ -100,6 +162,277 @@ export function generateSectionLoaders(ctx: MigrationContext): string {
+  // ---------- Privacy cookie check ----------
+  if (isVtex && hasPrivacyPolice) {
+    entries.push(``);
+    const vtexAccount = ctx.vtexAccount || "casaevideonewio";
+    entries.push(`  "site/sections/Account/PrivacyPolice.tsx": (props: any, req) => {`);
+    entries.push(`    const cookies = req.headers.get("cookie") ?? "";`);
</file context>
Fix with Cubic

});

// 4. Add RenderSection import if we introduced usages but no import exists
if (changed && result.includes("<RenderSection") && !result.includes("RenderSection")) {

@cubic-dev-ai cubic-dev-ai Bot Apr 6, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: This condition is always false — "<RenderSection" is a superset of "RenderSection", so the second includes check can never fail when the first succeeds. The auto-import for RenderSection will never fire, causing build errors when convertDirectComponentCalls introduces <RenderSection in files that don't already import it.

Check for the import statement specifically instead of the bare identifier.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At scripts/migrate/phase-cleanup.ts, line 995:

<comment>This condition is always false — `"<RenderSection"` is a superset of `"RenderSection"`, so the second `includes` check can never fail when the first succeeds. The auto-import for `RenderSection` will never fire, causing build errors when `convertDirectComponentCalls` introduces `<RenderSection` in files that don't already import it.

Check for the import statement specifically instead of the bare identifier.</comment>

<file context>
@@ -293,9 +339,961 @@ function cleanupJunkFromSrc(ctx: MigrationContext) {
+    });
+
+    // 4. Add RenderSection import if we introduced usages but no import exists
+    if (changed && result.includes("<RenderSection") && !result.includes("RenderSection")) {
+      result = `import { RenderSection } from "@decocms/start/hooks";\n` + result;
+    }
</file context>
Suggested change
if (changed && result.includes("<RenderSection") && !result.includes("RenderSection")) {
if (changed && result.includes("<RenderSection") && !/import\s*\{[^}]*RenderSection/.test(result)) {
Fix with Cubic

// Check for styles/ directory
const stylesDir = path.join(ctx.sourceDir, "styles");
if (fs.existsSync(stylesDir)) {
for (const file of fs.readdirSync(stylesDir)) {

@cubic-dev-ai cubic-dev-ai Bot Apr 6, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Sort the styles/ entries before choosing the first CSS file so migrations are deterministic when multiple CSS files exist.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At scripts/migrate/templates/app-css.ts, line 24:

<comment>Sort the styles/ entries before choosing the first CSS file so migrations are deterministic when multiple CSS files exist.</comment>

<file context>
@@ -1,6 +1,109 @@
+  // Check for styles/ directory
+  const stylesDir = path.join(ctx.sourceDir, "styles");
+  if (fs.existsSync(stylesDir)) {
+    for (const file of fs.readdirSync(stylesDir)) {
+      if (file.endsWith(".css") && file !== "tailwind.css") {
+        return fs.readFileSync(path.join(stylesDir, file), "utf-8");
</file context>
Suggested change
for (const file of fs.readdirSync(stylesDir)) {
for (const file of fs.readdirSync(stylesDir).sort()) {
Fix with Cubic

};
for (const [pkg, version] of Object.entries(KNOWN_THIRD_PARTY)) {
const escaped = pkg.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
if (new RegExp(`from\\s+["']${escaped}`, "m").test(content)) {

@cubic-dev-ai cubic-dev-ai Bot Apr 6, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The KNOWN_THIRD_PARTY regex doesn't anchor the end of the package name. from\s+["']@sentry/react will match from "@sentry/react-native", adding the wrong dependency. Append ["'/] to require the import to end with a quote (exact match) or / (sub-path import).

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At scripts/migrate/phase-analyze.ts, line 159:

<comment>The KNOWN_THIRD_PARTY regex doesn't anchor the end of the package name. `from\s+["']@sentry/react` will match `from "@sentry/react-native"`, adding the wrong dependency. Append `["'/]` to require the import to end with a quote (exact match) or `/` (sub-path import).</comment>

<file context>
@@ -141,10 +140,27 @@ function extractInlineNpmDeps(content: string): Record<string, string> {
+  };
+  for (const [pkg, version] of Object.entries(KNOWN_THIRD_PARTY)) {
+    const escaped = pkg.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+    if (new RegExp(`from\\s+["']${escaped}`, "m").test(content)) {
+      deps[pkg] = version;
+    }
</file context>
Suggested change
if (new RegExp(`from\\s+["']${escaped}`, "m").test(content)) {
if (new RegExp(`from\\s+["']${escaped}(["'/])`, "m").test(content)) {
Fix with Cubic

// Match patterns like: casaevideo: "casaevideonewio"
const match = content.match(/vtexAn|VTEX_AN/i);
if (match) {
const dictMatch = content.match(/["'](\w+)["']\s*:\s*["'](\w+myvtex|\w+newio|\w+)["']/);

@cubic-dev-ai cubic-dev-ai Bot Apr 6, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The \w+ fallback in the dictMatch alternation makes \w+myvtex and \w+newio redundant and causes the regex to match the first arbitrary "word": "word" pair in the file instead of specifically the VTEX account value. Either remove the \w+ catch-all or, if a general fallback is needed, iterate all matches and prefer those with myvtex/newio suffixes.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At scripts/migrate/phase-analyze.ts, line 415:

<comment>The `\w+` fallback in the `dictMatch` alternation makes `\w+myvtex` and `\w+newio` redundant and causes the regex to match the first arbitrary `"word": "word"` pair in the file instead of specifically the VTEX account value. Either remove the `\w+` catch-all or, if a general fallback is needed, iterate all matches and prefer those with `myvtex`/`newio` suffixes.</comment>

<file context>
@@ -374,6 +403,47 @@ function extractGtmId(sourceDir: string): string | null {
+    // Match patterns like: casaevideo: "casaevideonewio"
+    const match = content.match(/vtexAn|VTEX_AN/i);
+    if (match) {
+      const dictMatch = content.match(/["'](\w+)["']\s*:\s*["'](\w+myvtex|\w+newio|\w+)["']/);
+      if (dictMatch) return dictMatch[2];
+    }
</file context>
Fix with Cubic

}
return params;
}
return { ...params, ...defaults };

@cubic-dev-ai cubic-dev-ai Bot Apr 6, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The object branch of withDefaultParams overwrites existing params with defaults. Defaults should only fill missing keys; this currently replaces caller-provided values.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At scripts/migrate/templates/lib-utils.ts, line 68:

<comment>The object branch of withDefaultParams overwrites existing params with defaults. Defaults should only fill missing keys; this currently replaces caller-provided values.</comment>

<file context>
@@ -0,0 +1,255 @@
+    }
+    return params;
+  }
+  return { ...params, ...defaults };
+}
+`;
</file context>
Fix with Cubic

* Returns null if the section is not a barrel or the target can't be found.
*/
function readReExportTargetContent(content: string, sectionAbsPath: string, sourceDir: string): string | null {
const match = content.match(REEXPORT_FROM_RE);

@cubic-dev-ai cubic-dev-ai Bot Apr 6, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: readReExportTargetContent only reads the first re-export target, so barrel files with multiple export { ... } from entries can miss the loader file and misclassify loader/device/url metadata. Consider iterating all re-export targets (or at least the one containing loader) and combining their contents.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At scripts/migrate/analyzers/section-metadata.ts, line 76:

<comment>`readReExportTargetContent` only reads the first re-export target, so barrel files with multiple `export { ... } from` entries can miss the loader file and misclassify loader/device/url metadata. Consider iterating all re-export targets (or at least the one containing `loader`) and combining their contents.</comment>

<file context>
@@ -39,6 +42,50 @@ function isStatusOnlyLoader(content: string): boolean {
+ * Returns null if the section is not a barrel or the target can't be found.
+ */
+function readReExportTargetContent(content: string, sectionAbsPath: string, sourceDir: string): string | null {
+  const match = content.match(REEXPORT_FROM_RE);
+  if (!match) return null;
+
</file context>
Fix with Cubic

if (namedReExportMatch) {
const trimmedLines = nonEmptyLines.map((l) => l.trim());
const hasOtherCode = trimmedLines.some(
(l) => !l.startsWith("export") && !l.startsWith("//") && !l.startsWith("/*") && !l.startsWith("*") && !l.startsWith("}") && !l.startsWith(",") && !/^\w+,?$/.test(l)

@cubic-dev-ai cubic-dev-ai Bot Apr 6, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: hasOtherCode only allows single identifiers in multi-line export lists, so named re-export barrels that use default as, Foo as Bar, or type Foo are misclassified as standalone islands. That prevents wrapper detection for those valid export styles.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At scripts/migrate/analyzers/island-classifier.ts, line 53:

<comment>`hasOtherCode` only allows single identifiers in multi-line export lists, so named re-export barrels that use `default as`, `Foo as Bar`, or `type Foo` are misclassified as standalone islands. That prevents wrapper detection for those valid export styles.</comment>

<file context>
@@ -42,6 +43,28 @@ export function classifyIslands(ctx: MigrationContext): void {
+      if (namedReExportMatch) {
+        const trimmedLines = nonEmptyLines.map((l) => l.trim());
+        const hasOtherCode = trimmedLines.some(
+          (l) => !l.startsWith("export") && !l.startsWith("//") && !l.startsWith("/*") && !l.startsWith("*") && !l.startsWith("}") && !l.startsWith(",") && !/^\w+,?$/.test(l)
+        );
+        if (!hasOtherCode) {
</file context>
Suggested change
(l) => !l.startsWith("export") && !l.startsWith("//") && !l.startsWith("/*") && !l.startsWith("*") && !l.startsWith("}") && !l.startsWith(",") && !/^\w+,?$/.test(l)
(l) => !l.startsWith("export") && !l.startsWith("//") && !l.startsWith("/*") && !l.startsWith("*") && !l.startsWith("}") && !l.startsWith(",") && !/^(?:type\s+)?\w+(?:\s+as\s+\w+)?,?$/.test(l)
Fix with Cubic

@vibe-dex

vibe-dex commented May 1, 2026

Copy link
Copy Markdown
Contributor Author

Closing — superseded by main (everything already merged)

Did a deep file-by-file diff between main and this branch:

$ git diff --stat main..pr-68 -- scripts/
 scripts/generate-loaders.ts                   |  91 +++-------------------
 scripts/generate-schema.ts                    | 102 +++----------------------
 scripts/migrate/phase-analyze.ts              |  54 -------------
 scripts/migrate/phase-cleanup.ts              | 106 +-------------------------
 scripts/migrate/phase-transform.ts            |  42 ----------
 scripts/migrate/templates/commerce-loaders.ts |   2 +-
 scripts/migrate/templates/section-loaders.ts  |   5 +-
 scripts/migrate/transforms/imports.ts         |  28 +------
 scripts/migrate/types.ts                      |   4 +-
 9 files changed, 26 insertions(+), 408 deletions(-)

Reading: pr-68 has only +26 lines vs main, and −408 lines (i.e. main has 408 lines of features this branch lacks). Going through each tier:

Tier 1 (Pages) — ✅ already in main, with improvements

  • resolvePropsViaReExport (re-export traversal for sections that re-export their loader): present in main at scripts/generate-schema.ts:495. Main also adds a caching layer (SourceFileCache, ModuleResolutionCache, PropsSchemaCache) that this branch lacks.
  • Section metadata follow-imports: same.

Tier 2 (CSS) — ✅ already in main

  • findOriginalCss, extractCustomCss, transformApplyDirectives, extractPrimaryFontFromCss, isOklchCoordinates + oklch(var(--x)) wrapping: all present in scripts/migrate/templates/app-css.ts. Files are byte-identical.

Tier 4 (Polish) — ✅ already in main

  • useVariantPossiblities modalType handling, normalizeImportCasing for Linux CI: both in main.

What's actually different

The +26 lines on this branch are regressions:

  • commerce-loaders.ts: removes the request?: Request parameter from COMMERCE_LOADERS signature (main supports it)
  • section-loaders.ts: drops the as any cast safety net (main has it with explanatory comment)
  • types.ts: removes the use-component and sections-component-loader DetectedPattern entries

Closing this PR. All the design ideas behind it landed in main through other paths — this is exactly the "many small, focused PRs > one big PR" lesson playing out. Tracking in MIGRATION_TOOLING_PLAN.md.

@vibe-dex vibe-dex closed this May 1, 2026
hugo-ccabral added a commit that referenced this pull request Aug 18, 2026
…rnings-staging convention (#457)

## Summary

Consolidates the farmrio-storefront Fresh→TanStack migration's staged
learnings (`migration/learnings/`, ~69 completed targets,
coverage-verified against the live ledger) into this skill's reference
docs, per the epic's own consolidation target (`T40`).

22 new numbered gotchas (**#52–#73**), each carrying Severity, Symptom,
Root cause, Fix (with code), a discovery `rg`/`grep` command, and
empirical farmrio evidence (file counts, byte deltas, before/after
numbers, cross-refs). Distributed into the existing topic files rather
than one new dump file, matching this repo's own index-per-topic
convention:

| File | New gotchas | Headline finding |
|---|---|---|
| `async-rendering.md` | #52–54, #73 | Dead 3-arg `ctx` section loaders
— 28-file sweep, one was a site-wide dead cookie-consent banner |
| `hydration-fixes.md` | #55–58 | `DeferredSectionWrapper` skeleton
remount/CLS (cross-ref #448) + a content-refresh-safe `Lazy.tsx` unwrap
pattern |
| `vtex-commerce.md` | #59–64 | CMS multivariate-flag resolver only
recognizes 2 of 7 real resolveTypes — silently drops content (blocker) |
| `css-styling.md` | #65–67 | Theme-conversion DaisyUI slot mismapping +
v5's silent dark-theme bundling |
| `worker-cloudflare.md` | #68–71 | Device-segmented edge-cache
poisoning via SWR revalidation (novel); server-only secrets reachable
from client bundle via the invoke dispatch table (security) |
| `storefront-patterns.md` | #72 | `sitemap.xml` not auto-wired |

`references/migration-learnings-staging.md` (new file) proposes the
index-per-target-file learnings convention as the **starting** pattern
for the next migration's own staging area — citing this epic's own flat
`LEARNINGS.md` (282,249 bytes / 3,875 lines / 103 entries, costing
target sessions 60k+ tokens just to search before it was restructured
mid-epic on 2026-07-30) as the empirical case for adopting it from day
one instead. Linked from `SKILL.md`'s reference index.

Two gotchas (#55, #59) reference upstream PRs/issues already filed from
this same migration:
**[#448](#448
(`DeferredSectionWrapper` fix, open) and
**[#391](#391
(URL param coercion, referenced by #61).

## Codemod / audit-rule proposals for `packages/blocks-cli`

Proposal only (per this migration's own DoD, implementation is a bonus,
not required) — each was hit ≥3 times independently across the farmrio
migration:

1. **Dead-arity section-loader detector** — AST walk for 3-arg `(props,
req, ctx)` loader exports, cross-referenced against
`registerSectionLoaders` calls and each file's real `__resolveType` (not
its file path) in `blocks.gen.json`. Would have caught all 28 candidate
files in gotcha #52 at migration time.
2. **`typeof X === "function"` guard sweep** — flag this pattern on any
value that originates from CMS section resolution (gotcha #54); recurred
independently in 6+ files across the epic.
3. **Controlled-input-missing-`onChange` sweep** — `checked={...}` JSX
prop with no sibling `onChange` (gotcha #58); found and fixed
independently 3 separate times.
4. **`LoadingFallback` wrapper-function → literal-alias codemod** —
rewrite `export function LoadingFallback(props) { return <X
{...props}/>; }` to `export const LoadingFallback = X;` (gotcha #56).
5. **Redirect self-loop lint rule** — flag any `blocks.gen.json`
redirect block where `normalize(from) === normalize(to)` after
case-folding (gotcha #60); found 3 live instances across 2 targets once
the check existed as an ad-hoc script.
6. **Image-dimension backfill from source headers** — generic
migration-time step parsing real JPEG/PNG dimensions from each unique
image URL's own file header and writing `width`/`height` back into CMS
content, instead of leaving every un-dimensioned image to hit the
CLS-safety-net fallback one page at a time (gotcha #67).
7. **`deco-post-cleanup --strict` comment/string-literal awareness** —
several existing audit rules (`deco-cx-runtime-api`,
`style-string-props`, `htmx-residue`) are literal-substring scans with
no AST/JSX awareness, so they false-positive on matches inside comments
or inside a `dangerouslySetInnerHTML` HTML string. Farmrio counts: 7
comment-only false positives on one rule, 4 on another, 4-of-6 on a
third.

## Parity-destined findings

Filed separately against `decocms/parity` (issue, cross-linked from
`migration/learnings/INDEX.md` in farmrio-storefront) rather than
bundled into this PR — covers `--fail-on` requiring `--ci`, `--pages`
not scoping `flows`, a `banner-aspect-ratio` check double-counting
infinite-carousel clones, a `lazy-section-presence` heuristic
incompatible with TanStack's transport, and LLM visual-diff
hallucination on downscaled full-page screenshots.

## Test plan

- [x] Docs-only change — no code paths affected, nothing to typecheck or
build
- [x] Every new gotcha cross-checked against the current `gotchas.md`
numbering (#51 was the prior max, confirmed via `grep -rn "^## #\?[0-9]"
*.md`)
- [x] Every code snippet reproduced from the source learnings files, not
invented — cross-checked against the cited
`migration/learnings/T<ID>.md` file in `deco-sites/farmrio-storefront`

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Consolidates Farm Rio Fresh→TanStack migration learnings into this skill
and adds 22 numbered gotchas (#52–#73). Also documents an
index-per-target-file staging convention to keep future migrations fast
and cheap.

- Adds gotchas across async/rendering, hydration, VTEX commerce,
CSS/DaisyUI, Worker/Cloudflare, and storefront patterns, covering issues
like pre-`#305` 3‑arg loader pitfalls, `DeferredSectionWrapper` CLS,
multivariate resolver gaps, sitemap wiring, cache behavior, and a
client-bundle secret leak. Cross‑refs: `#448` and
`#391`.
- Introduces `references/migration-learnings-staging.md` and links it
from `SKILL.md` to replace flat learnings with an index-per-target
approach.

**Doc updates since review**
- #52: Clarifies that `@decocms/blocks` now supports an optional 3rd
`ctx` arg when registered; positions the fix as a ctx‑free alternative
for pre‑`#305` or unregistered loaders.
- #61: Splits discovery into two valid `rg` commands.
- #63: Corrects variant‑trim filter to use `priceComponentType` (not
`@type`), ensuring installment entries are removed.
- #65: Adds runnable discovery steps (`grep` + `jq`) for DaisyUI slot
mapping.
- #66: Flags the dark‑theme auto‑bundling gotcha as DaisyUI v5‑only.
- #72: Adds a `worker-entry.ts` wiring example for `/sitemap.xml` and
fixes the import path to `@decocms/apps-vtex`.

<sup>Written for commit 919eb12.
Summary will update on new commits.</sup>

<a href="https://cubic.dev/pr/decocms/blocks/pull/457?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>

<!-- End of auto-generated description by cubic. -->

---------

Co-authored-by: hugo-ccabral <[email protected]>
Co-authored-by: Claude Sonnet 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant