import * as cheerio from 'cheerio'; import * as fs from 'fs/promises'; import path from 'path'; import { completePrompt } from './models'; import { deduplicateInlineScripts } from './service/transformPage'; /** * Registry of migration functions: fromVersion -> transform. * Each function transforms page HTML from version N to version N+1. */ const migrations: Record Promise> = { 1: migrateV1toV2, 2: migrateV2toV3, }; /** * Migrate a page's HTML from one version to another by applying * sequential migration steps. */ export async function migratePage(html: string, fromVersion: number, toVersion: number, completePrompt: completePrompt): Promise { let current = html; for (let v = fromVersion; v < toVersion; v++) { const migrate = migrations[v]; if (!migrate) { throw new Error(`No migration defined for version ${v} -> ${v + 1}`); } current = await migrate(current, completePrompt); } return current; } /** CSS selectors provided by the shared theme — used by post-processing to strip leftovers. */ const SHARED_CSS_SELECTORS = [ // Base ':root', '*', 'body', 'html', // Chat panel '.chat-panel', '.chat-header', '.chat-messages', '.chat-message', '.chat-message p', '.chat-message p strong', '.chat-message p code', '.chat-message strong', '.chat-message pre', '.chat-message code', '.chat-message a', 'form', '.chat-input', '.chat-input:focus', '.chat-input::placeholder', '.chat-input:disabled', '.chat-submit', '.chat-submit:hover', '.chat-submit:active', '.chat-submit:disabled', '.chat-input-wrapper', '.chat-input-wrapper .chat-input', // Viewer panel '.viewer-panel', '.viewer-panel::before', '.viewer-panel.full-viewer', // Loading '.loading-overlay', '.spinner', '#loadingOverlay', // Chat toggle '.chat-toggle', '.chat-toggle:hover', '.chat-toggle-dots', '.chat-toggle-dot', '.chat-toggle:hover .chat-toggle-dot', 'body.chat-collapsed .chat-panel', 'body.chat-collapsed .chat-toggle', // Modal system '.modal-overlay', '.modal-overlay.show', '.modal-content', '.modal-header', '.modal-body', '.modal-footer', '.modal-footer-right', '.modal-btn', '.modal-btn-primary', '.modal-btn-primary:hover', '.modal-btn-secondary', '.modal-btn-secondary:hover', '.modal-btn-danger', '.modal-btn-danger:hover', // Form elements '.form-group', '.form-group:last-child', '.form-label', '.form-input', '.form-input:focus', '.form-input:read-only', '.form-input::placeholder', '.checkbox-label', '.checkbox-label input[type="checkbox"]', '.checkbox-label span', // Brainstorm '.brainstorm-icon-btn', '.brainstorm-icon-btn:hover', '.brainstorm-modal .modal-content', '.brainstorm-modal .modal-header', '.brainstorm-close-btn', '.brainstorm-close-btn:hover', '.brainstorm-messages', '.brainstorm-message', '.brainstorm-user', '.brainstorm-assistant', '.brainstorm-input-row', '.brainstorm-input', '.brainstorm-input:focus', '.brainstorm-input::placeholder', '.brainstorm-send-btn', '.brainstorm-send-btn:hover', '.brainstorm-send-btn:disabled', '.brainstorm-assistant p', '.brainstorm-assistant pre', '.brainstorm-assistant code', '.brainstorm-build-row', '.brainstorm-build-btn', '.brainstorm-build-btn:hover', '.brainstorm-suggestions', '.brainstorm-suggestion-chip', '.brainstorm-suggestion-chip:hover', '.brainstorm-suggestion-chip:disabled', '.brainstorm-thinking', ]; /** Default chat panel HTML — restored by post-processing if the LLM removes it. */ const DEFAULT_CHAT_PANEL = `
SynthOS

Welcome! How can I help you?

`; /** * Load migration rules from the migration-rules/ folder. */ async function loadMigrationRules(filename: string): Promise { const rulesPath = path.join(__dirname, '..', 'migration-rules', filename); return await fs.readFile(rulesPath, 'utf8'); } /** * v1 -> v2: LLM-based migration that strips shared code and adds theme support. * Post-processes with cheerio to verify critical elements are present. */ async function migrateV1toV2(html: string, completePrompt: completePrompt): Promise { const rules = await loadMigrationRules('v1-to-v2.md'); const system = { role: 'system' as const, content: rules }; const prompt = { role: 'user' as const, content: `Convert this v1 page to v2 format:\n\n${html}` }; const result = await completePrompt({ prompt, system }); if (!result.completed || !result.value) { throw new Error('LLM migration failed: ' + (result.error?.message ?? 'no response')); } // Strip markdown fencing if present let migrated = result.value.trim(); if (migrated.startsWith('```')) { migrated = migrated.replace(/^```(?:html)?\s*\n?/, '').replace(/\n?```\s*$/, ''); } // Post-process with cheerio to verify and fix critical elements migrated = postProcessV2(migrated, html); return migrated; } /** * v2-compat CSS block — injected into the of every page migrated from v2 * to v3. Maps the legacy v2 CSS tokens (`--bg-*`, `--accent-*`, `--text-*`, * `--border-color`) onto the active v3 theme's semantic tokens (`--bodyBackground`, * `--themePrimary`, etc.), so a migrated page inherits whatever v3 theme is * active instead of being frozen on the old nebula-dusk palette. Layout-only * constants (`--header-*`) stay as literal values. * * Dropped from the previous compat block: baked `body`, `.viewer-panel`, * `.viewer-panel::before`, `@keyframes nebula-pulse`, and `::-webkit-scrollbar*` * rules. Those contained hardcoded purple/blue rgba values that looked wrong * under non-nebula v3 themes (aurora, cosmos, solar-flare, high-contrast). * The shell injects the iframe viewport height chain separately, and * FluentLM's base CSS covers global resets. * * Keep in sync with `migration-rules/v2-to-v3.md` §3. */ const V2_COMPAT_STYLE = ``; /** * v2 nebula-dusk palette → v3 token map. Each entry's `rgb` triple is the * hardcoded RGB that appeared in the v2 theme (and therefore in v2 page CSS * that was hand-matched to it). The `token` is the v3 semantic/palette var * that best fits the same role — so under light themes (nebula-dawn, * aurora-dawn, solar-flare-dawn, high-contrast-light) the color re-themes * instead of standing out as a dark purple-blue blob. * * Keep in sync with `migration-rules/v2-to-v3.md` §3 "Legacy color mapping". * * `rgba(0,0,0,*)` is intentionally NOT remapped — theme-neutral shadows read * fine under both light and dark themes. */ type LegacyColorRule = { rgb: [number, number, number]; token: string; hex: string }; const LEGACY_COLOR_RULES: LegacyColorRule[] = [ // Brand / accent family (v2 purple-blue ramp) { rgb: [102, 126, 234], token: 'var(--themePrimary)', hex: '#667eea' }, { rgb: [118, 75, 162], token: 'var(--themeDarkAlt)', hex: '#764ba2' }, { rgb: [138, 43, 226], token: 'var(--themeDarker)', hex: '#8a2be2' }, { rgb: [ 75, 0, 130], token: 'var(--themeDarker)', hex: '#4b0082' }, { rgb: [240, 147, 251], token: 'var(--themeSecondary)', hex: '#f093fb' }, { rgb: [183, 148, 246], token: 'var(--themeTertiary)', hex: '#b794f6' }, // Dark background family (v2 bg-primary/secondary/tertiary) — mapped to // SEMANTIC tokens that flip between light and dark themes. Palette tokens // would freeze these as dark under light themes (black blobs in dawn mode). { rgb: [ 26, 26, 46], token: 'var(--bodyBackground)', hex: '#1a1a2e' }, { rgb: [ 22, 33, 62], token: 'var(--bodyStandoutBackground)', hex: '#16213e' }, { rgb: [ 15, 15, 35], token: 'var(--bodyBackgroundHovered)', hex: '#0f0f23' }, // Status colors (Bootstrap danger/success/warning used pervasively in v2 pages) { rgb: [220, 53, 69], token: 'var(--red)', hex: '#dc3545' }, { rgb: [ 40, 167, 69], token: 'var(--green)', hex: '#28a745' }, { rgb: [255, 193, 7], token: 'var(--yellow)', hex: '#ffc107' }, ]; /** * Replace hardcoded v2-era RGB/hex colors in the full HTML (style blocks, * inline `style=""` attrs, and JS template literals) with theme-aware v3 * tokens. Alpha is preserved via `color-mix(in srgb, X%, transparent)`; * solid occurrences collapse to `var(--token)` directly. `rgba(0,0,0,*)` is * left as-is by design — theme-neutral shadows. * * The patterns match specific numeric triples and 6-digit hex codes only, so * false positives in non-color contexts (IDs, content text, URLs) are * negligible. Hex matches are guarded by `(? { const a = parseFloat(alpha); if (!isFinite(a) || a >= 1) return rule.token; const pct = Math.round(a * 1000) / 10; // 1 decimal return `color-mix(in srgb, ${rule.token} ${pct}%, transparent)`; }); // rgb(R,G,B) or rgba(R,G,B) without alpha — solid color const rgbPattern = new RegExp( `rgba?\\(\\s*${r}\\s*,\\s*${g}\\s*,\\s*${b}\\s*\\)`, 'gi' ); out = out.replace(rgbPattern, rule.token); // Bare 6-digit hex (case-insensitive, guarded to not split 8-digit hex) const hexEscaped = rule.hex.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); const hexPattern = new RegExp(`(? v3: Cheerio-based migration (no LLM). * - Strips v2 shell chrome (.chat-panel, .chat-toggle, #loadingOverlay) and * the inline scripts that only make sense alongside it (idle-animation, * first-run-check, legacy page-helpers/page-script). * - Injects