export interface HomeStyle { id: string; name: string; description: string; imageUrl: string } export const record = (value: unknown): Record => ( value !== null && typeof value === 'object' && !Array.isArray(value) ? value as Record : {} ); export const safeImageUrl = (value: unknown, siteOrigin = ''): string => { if (typeof value !== 'string') return ''; try { const url = new URL(value); return (url.protocol === 'https:' || (url.protocol === 'http:' && url.origin === siteOrigin)) && !url.username && !url.password ? url.href : ''; } catch { return ''; } }; export const parseStyles = (payload: unknown, siteOrigin = ''): HomeStyle[] => { const rows = record(payload).styles; const seen = new Set(); if (!Array.isArray(rows)) return []; return rows.slice(0, 200).flatMap((value): HomeStyle[] => { const row = record(value); const id = typeof row.id === 'string' ? row.id : ''; if (!/^[a-zA-Z0-9_-]{1,160}$/.test(id) || seen.has(id) || typeof row.name !== 'string' || !row.name.trim()) return []; seen.add(id); return [{ id, name: row.name.slice(0, 200), description: typeof row.description === 'string' ? row.description.slice(0, 500) : '', imageUrl: safeImageUrl(row.imageUrl, siteOrigin) }]; }); }; /** Navigation is a suggestion; the current account catalog remains authority. */ export const styleRecipe = (id: unknown, styles: unknown, recipe: unknown): Record | null => { if (typeof id !== 'string' || !id || !Array.isArray(styles) || !styles.some((style) => record(style).id === id)) return null; const next = { ...record(recipe), style: id }; // A new ordinary style explicitly leaves current or unsubmitted older template intent. delete (next as Record).preset; delete (next as Record).lockedPreset; return next; };