import { loadPageMetadata, loadPageState, normalizePageName, PAGE_VERSION, savePageMetadata, savePageState, saveChangeHtml, loadChangeHtml, getLatestChangeHtmlNumber, getLatestChangeNumber, clearChanges, saveChangeMessages, loadAllChangeMessages, deleteChange, migrateLegacyChangeFiles, ChatMessage } from "../pages"; import { getModelEntry, hasConfiguredSettings, loadSettings, renderUserProfile } from "../settings"; import { Application } from 'express'; import { transformPage, buildRouteHints, serverAPIs, AGENT_API_REFERENCE } from "./transformPage"; import { SynthOSConfig } from "../init"; import { createCompletePrompt } from "./createCompletePrompt"; import { completePrompt } from "../models"; import { green, red, dim, estimateTokens } from "./debugLog"; import { loadThemeInfo, loadThemeVersion, ThemeInfo } from "../themes"; import { Customizer } from "../customizer"; import { createBuilder, ContextSection, SectionMode, Attachment } from "../builders"; import { classifyRequest, ClassifierSection, ClassifyResult } from "../builders/anthropic"; import { getConnectorRegistry, ConnectorsConfig, ConnectorOAuthConfig } from "../connectors"; import { AgentConfig } from "../agents"; import { listScripts } from "../scripts"; import path from 'path'; import * as fs from 'fs'; import * as crypto from 'crypto'; import { checkIfExists, findFileInFolders, loadFile } from "../files"; import * as cheerio from 'cheerio'; import { listTables as listTableInfo, loadSchema } from "./sharedTableSchema"; /** * Required CDN imports that must be present on every v2 page. * Each entry maps a detection selector to the script tag src to inject. */ const REQUIRED_IMPORTS: { selector: string; src: string }[] = [ { selector: 'script[src*="marked"]', src: 'https://cdnjs.cloudflare.com/ajax/libs/marked/14.1.1/marked.min.js' }, { selector: 'script[src*="html2canvas"]', src: 'https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js' }, ]; // ensureRequiredImports is now ensureRequiredImports$() — operates on shared $ instance const HOME_PAGE_ROUTE = '/builder'; const PAGE_NOT_FOUND = 'Page not found'; const SHELL_PAGE_NAME = '_shell'; const NO_PERSIST_CATEGORIES = ['_Starters', 'System']; // Pages that are served as top-level documents (peers to _shell) — never wrapped // in the shell iframe chrome. The page itself owns the full viewport. const STANDALONE_PAGE_NAMES = ['_starters']; // --------------------------------------------------------------------------- // Cache-busting for /static assets // --------------------------------------------------------------------------- // Versions are computed lazily from file mtime + size, so any edit/deploy // produces a new ?v= suffix and clients fetch fresh content. let _staticFolders: readonly string[] = []; const _assetVersions = new Map(); function initStaticAssetVersioning(folders: readonly string[]): void { _staticFolders = folders; _assetVersions.clear(); } function getAssetVersion(filename: string): string { const cached = _assetVersions.get(filename); if (cached) return cached; for (const folder of _staticFolders) { try { const stat = fs.statSync(path.join(folder, filename)); const version = crypto.createHash('sha1') .update(`${stat.mtimeMs}:${stat.size}`) .digest('hex').slice(0, 8); _assetVersions.set(filename, version); return version; } catch { /* try next folder */ } } _assetVersions.set(filename, 'dev'); return 'dev'; } function assetUrl(filename: string): string { return `/static/${filename}?v=${getAssetVersion(filename)}`; } /** * Rewrite /static/ URLs in HTML to append cache-busting ?v=. * Matches href= and src= attributes only; leaves URLs with existing query strings alone. */ function applyAssetVersions(html: string): string { return html.replace( /(href|src)="\/static\/([^"?]+)"/g, (_m, attr, file) => `${attr}="${assetUrl(file)}"` ); } // --------------------------------------------------------------------------- // Per-page concurrency lock // --------------------------------------------------------------------------- // Serializes concurrent transform/patch requests for the same page to prevent // version clobbering (two requests reading the same currentVersion, both // writing to page.v{N+1}.html). Different pages run in parallel. const pageLocks = new Map>(); function withPageLock(page: string, fn: () => Promise): Promise { const prev = pageLocks.get(page) ?? Promise.resolve(); let releaseLock: () => void; const next = new Promise(resolve => { releaseLock = resolve; }); pageLocks.set(page, next); return prev.then(fn).finally(() => { releaseLock!(); // Clean up if no new work was queued behind us if (pageLocks.get(page) === next) pageLocks.delete(page); }); } /** Attributes safe to perform product-name replacement in (user-visible text). */ const SAFE_REPLACE_ATTRS = ['alt', 'placeholder', 'aria-label', 'title', 'content']; /** * Replace "SynthOS" (case-insensitive) with the custom product name in * user-visible text only. Skips `; // Replace any existing page-info script (may have a stale page name from the template) const existing = html.match(/]*><\/script>/); if (existing) { return html.replace(existing[0], tag); } const idx = html.indexOf(''); if (idx !== -1) { return html.slice(0, idx) + tag + '\n' + html.slice(idx); } return tag + '\n' + html; } // injectPageHelpers is now injectPageHelpers$() — operates on shared $ instance /** * Wrap each inline `; }); } // hoistExternalScriptsToHead is now hoistExternalScriptsToHead$() — operates on shared $ instance /** * Inline error-capture script injected as the first child of so it * registers window.onerror / unhandledrejection *before* any page scripts run. * Stripped before page transformation so the LLM never sees it. */ /** * Inject shell.v3.css and FluentLM base CSS/JS (always — the shell always emits * FluentLM-keyed modals). The theme-name class on stays gated to v3 so * pre-v3 themes don't accidentally activate scoped rules. */ function injectShellAssets(html: string, themeName: string, themeVersion: number, toolbarPosition?: string): string { const $ = cheerio.load(html, { decodeEntities: false }); const themeLink = $('link#theme-css'); // Favicon if ($('link#synthos-favicon').length === 0) { $('head').prepend(`\n`); } // shell.v3.css — always injected (provides toolbar + layout chrome) if ($('link#shell-css').length === 0) { const shellLink = ``; if (themeLink.length > 0) { themeLink.before(shellLink + '\n'); } else { $('head').append(shellLink + '\n'); } } // Theme-name class on — only for v3 themes that ship scoped rules if (themeVersion >= 3) { $('html').addClass(themeName); } // FluentLM CSS — always injected; shell modals depend on .flm-dialog-overlay if ($('link#fluentlm-css').length === 0) { const fluentLink = ``; const shellCss = $('link#shell-css'); if (shellCss.length > 0) { shellCss.before(fluentLink + '\n'); } else if (themeLink.length > 0) { themeLink.before(fluentLink + '\n'); } else { $('head').append(fluentLink + '\n'); } } // FluentLM JS — always injected if ($('script#fluentlm-js').length === 0) { const fluentScript = ``; $('body').append(fluentScript + '\n'); } $('html').attr('data-toolbar', toolbarPosition || 'left'); return $.html(); } // --------------------------------------------------------------------------- // iframe architecture helpers // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // Cheerio-based transform steps (operate on shared $ instance) // --------------------------------------------------------------------------- /** * Strip shell markup (toolbar, chat panel) from the in-memory DOM. */ function stripShellMarkup$($: cheerio.Root): void { $('.shell-toolbar').remove(); $('.chat-panel').remove(); $('#loadingOverlay').remove(); $('script#page-script').remove(); $('script#synthos-error-capture').remove(); // v2-legacy idle animation — the inline `; $('body').prepend(stubScript); } /** * Ensure every required CDN import is present in the page's . */ function ensureRequiredImports$($: cheerio.Root, pageVersion: number): void { if (pageVersion < 2) return; for (const imp of REQUIRED_IMPORTS) { if ($(imp.selector).length === 0) { $('head').append(`\n`); } } } /** * Inject FluentLM CSS/JS and theme class into page content for iframe rendering. */ function injectContentAssets$($: cheerio.Root, themeName: string, themeVersion: number): void { // Inject iframe viewport styles if ($('style#iframe-viewport').length === 0) { $('head').prepend( '\n' ); } // Move non-locked \n`); } } /** * Inject page-info script tag into . */ function injectPageInfoScript$($: cheerio.Root, pageName: string): void { const tag = ``; const existing = $('script#page-info'); if (existing.length > 0) { existing.replaceWith(tag); } else { $('head').append(tag + '\n'); } } /** * V3 helper script IDs and their static file names. * shell-bridge.v3.js loads first (creates window.synthos); the rest attach namespaces. */ const V3_HELPER_SCRIPTS = [ { id: 'shell-bridge-v3', file: 'shell-bridge.v3.js' }, { id: 'server-v3', file: 'server.v3.js' }, { id: 'storage-v3', file: 'storage.v3.js' }, { id: 'script-v3', file: 'script.v3.js' }, { id: 'connector-v3', file: 'connector.v3.js' }, { id: 'agent-v3', file: 'agent.v3.js' }, { id: 'extract-v3', file: 'extract.v3.js' }, ]; /** * Inject v3 helper scripts into the page. * shell-bridge.v3.js goes at end of (bridge must be last to initialize after DOM). * All other v3 scripts go into after page-info. */ function injectPageHelpers$($: cheerio.Root, pageVersion: number): void { if (pageVersion < 2) return; // Remove legacy monolithic helpers if present $('script#page-helpers').remove(); $('script#page-bridge').remove(); // Remove old bridge id in case pages were rendered with an older version $('script#shell-v3').remove(); // Inject v3 scripts for (const script of V3_HELPER_SCRIPTS) { if ($(`script#${script.id}`).length > 0) continue; const tag = ``; if (script.id === 'shell-bridge-v3') { // Bridge goes at end of body (needs to run after page DOM) $('body').append(tag + '\n'); } else { // API scripts go into head after page-info const pageInfo = $('script#page-info'); if (pageInfo.length > 0) { pageInfo.after('\n' + tag); } else { $('head').append(tag + '\n'); } } } } /** * @deprecated No longer needed — shell-bridge.v3.js replaces page-bridge.js. * Kept as a no-op for any call sites not yet updated. */ function injectPageBridge$($: cheerio.Root, pageVersion: number): void { // No-op: shell-bridge.v3.js is now injected by injectPageHelpers$ } /** * Move external `; // Inject before shell-modals.v3.js — it's the earliest consumer of window.__shellInit // and captures values at module-load time, so __shellInit MUST be set before it loads. // Match href with or without cache-bust query. const shellModalsIdx = shellHtml.search(/