Real-time dashboard for monitoring global news, markets, and geopolitical events
TypeScript
Phase 2: Implement Svelte stores and analysis modules
Sean Thielen-Esparza5d7279a24dcb
diff --git a/src/lib/analysis/correlation.test.ts b/src/lib/analysis/correlation.test.tsnew file mode 100644index 0000000..2072e44--- /dev/null+++ b/src/lib/analysis/correlation.test.ts@@ -0,0 +1,125 @@+/**+ * Tests for correlation engine+ */++import { describe, it, expect, beforeEach } from 'vitest';+import {+ analyzeCorrelations,+ getCorrelationSummary,+ clearCorrelationHistory+} from './correlation';+import type { NewsItem } from '$lib/types';++describe('Correlation Engine', () => {+ beforeEach(() => {+ clearCorrelationHistory();+ });++ it('should return null for empty news', () => {+ expect(analyzeCorrelations([])).toBeNull();+ expect(analyzeCorrelations(null as unknown as NewsItem[])).toBeNull();+ });++ it('should detect emerging patterns', () => {+ const news: NewsItem[] = [+ { id: '1', title: 'Ukraine announces new policy', source: 'BBC', link: 'a', timestamp: Date.now(), category: 'politics' },+ { id: '2', title: 'Ukraine military update', source: 'CNN', link: 'b', timestamp: Date.now(), category: 'politics' },+ { id: '3', title: 'Zelensky addresses nation', source: 'NYT', link: 'c', timestamp: Date.now(), category: 'politics' },+ ];++ const results = analyzeCorrelations(news);++ expect(results).not.toBeNull();+ expect(results!.emergingPatterns.length).toBeGreaterThan(0);++ const ukrainePattern = results!.emergingPatterns.find(p => p.id === 'russia-ukraine');+ expect(ukrainePattern).toBeDefined();+ expect(ukrainePattern!.count).toBeGreaterThanOrEqual(3);+ expect(ukrainePattern!.level).toBe('emerging');+ });++ it('should categorize pattern levels correctly', () => {+ // Create many Ukraine-related articles to trigger 'high' level+ const news: NewsItem[] = Array.from({ length: 10 }, (_, i) => ({+ id: String(i),+ title: `Ukraine news ${i}`,+ source: `Source${i}`,+ link: `link${i}`,+ timestamp: Date.now(),+ category: 'politics' as const+ }));++ const results = analyzeCorrelations(news);+ const ukrainePattern = results?.emergingPatterns.find(p => p.id === 'russia-ukraine');++ expect(ukrainePattern?.level).toBe('high');+ });++ it('should track cross-source correlations', () => {+ const news: NewsItem[] = [+ { id: '1', title: 'Tariff news today', source: 'BBC', link: 'a', timestamp: Date.now(), category: 'finance' },+ { id: '2', title: 'Trade war escalates', source: 'CNN', link: 'b', timestamp: Date.now(), category: 'finance' },+ { id: '3', title: 'Import tax increases', source: 'NYT', link: 'c', timestamp: Date.now(), category: 'finance' },+ { id: '4', title: 'Customs duty update', source: 'WSJ', link: 'd', timestamp: Date.now(), category: 'finance' },+ ];++ const results = analyzeCorrelations(news);+ const tariffCorrelation = results?.crossSourceCorrelations.find(c => c.id === 'tariffs');++ expect(tariffCorrelation).toBeDefined();+ expect(tariffCorrelation!.sourceCount).toBe(4);+ expect(tariffCorrelation!.sources).toContain('BBC');+ });++ it('should generate predictive signals for high scores', () => {+ // Create many tariff articles to generate predictive signals+ const news: NewsItem[] = Array.from({ length: 8 }, (_, i) => ({+ id: String(i),+ title: `Tariff policy update ${i}`,+ source: `Source${i % 4}`,+ link: `link${i}`,+ timestamp: Date.now(),+ category: 'finance' as const+ }));++ const results = analyzeCorrelations(news);++ expect(results?.predictiveSignals.length).toBeGreaterThan(0);++ const tariffSignal = results?.predictiveSignals.find(s => s.id === 'tariffs');+ if (tariffSignal) {+ expect(tariffSignal.prediction).toContain('volatility');+ }+ });++ it('should collect headlines for patterns', () => {+ const news: NewsItem[] = [+ { id: '1', title: 'Gaza conflict escalates', source: 'BBC', link: 'https://bbc.com/1', timestamp: Date.now(), category: 'politics' },+ { id: '2', title: 'Hamas negotiations', source: 'CNN', link: 'https://cnn.com/2', timestamp: Date.now(), category: 'politics' },+ { id: '3', title: 'Israel Gaza update', source: 'NYT', link: 'https://nyt.com/3', timestamp: Date.now(), category: 'politics' },+ ];++ const results = analyzeCorrelations(news);+ const gazaPattern = results?.emergingPatterns.find(p => p.id === 'israel-gaza');++ expect(gazaPattern?.headlines.length).toBeGreaterThan(0);+ expect(gazaPattern?.headlines[0].link).toBeDefined();+ expect(gazaPattern?.headlines[0].source).toBeDefined();+ });++ it('should return correct summary', () => {+ expect(getCorrelationSummary(null)).toEqual({ totalSignals: 0, status: 'NO DATA' });++ const news: NewsItem[] = [+ { id: '1', title: 'Ukraine update', source: 'BBC', link: 'a', timestamp: Date.now(), category: 'politics' },+ { id: '2', title: 'Ukraine news', source: 'CNN', link: 'b', timestamp: Date.now(), category: 'politics' },+ { id: '3', title: 'Zelensky speaks', source: 'NYT', link: 'c', timestamp: Date.now(), category: 'politics' },+ ];++ const results = analyzeCorrelations(news);+ const summary = getCorrelationSummary(results);++ expect(summary.totalSignals).toBeGreaterThan(0);+ expect(summary.status).toMatch(/SIGNALS/);+ });+});diff --git a/src/lib/analysis/correlation.ts b/src/lib/analysis/correlation.tsnew file mode 100644index 0000000..178131d--- /dev/null+++ b/src/lib/analysis/correlation.ts@@ -0,0 +1,272 @@+/**+ * Correlation engine - analyzes patterns across news items+ */++import type { NewsItem } from '$lib/types';+import { CORRELATION_TOPICS, type CorrelationTopic } from '$lib/config/analysis';++// Types for correlation results+export interface EmergingPattern {+ id: string;+ name: string;+ category: string;+ count: number;+ level: 'high' | 'elevated' | 'emerging';+ sources: string[];+ headlines: Array<{ title: string; link: string; source: string }>;+}++export interface MomentumSignal {+ id: string;+ name: string;+ category: string;+ current: number;+ delta: number;+ momentum: 'surging' | 'rising' | 'stable';+ headlines: Array<{ title: string; link: string; source: string }>;+}++export interface CrossSourceCorrelation {+ id: string;+ name: string;+ category: string;+ sourceCount: number;+ sources: string[];+ level: 'high' | 'elevated' | 'emerging';+ headlines: Array<{ title: string; link: string; source: string }>;+}++export interface PredictiveSignal {+ id: string;+ name: string;+ category: string;+ score: number;+ confidence: number;+ prediction: string;+ level: 'high' | 'medium' | 'low';+ headlines: Array<{ title: string; link: string; source: string }>;+}++export interface CorrelationResults {+ emergingPatterns: EmergingPattern[];+ momentumSignals: MomentumSignal[];+ crossSourceCorrelations: CrossSourceCorrelation[];+ predictiveSignals: PredictiveSignal[];+}++// Topic history for momentum analysis+const topicHistory: Record<number, Record<string, number>> = {};++// History retention in minutes+const HISTORY_RETENTION_MINUTES = 30;++// Time window for momentum comparison in minutes+const MOMENTUM_WINDOW_MINUTES = 10;++/**+ * Format topic ID to display name+ */+function formatTopicName(id: string): string {+ return id+ .replace(/-/g, ' ')+ .replace(/\b\w/g, (l) => l.toUpperCase());+}++/**+ * Analyze correlations across all news items+ */+export function analyzeCorrelations(allNews: NewsItem[]): CorrelationResults | null {+ if (!allNews || allNews.length === 0) return null;++ const now = Date.now();+ const currentTime = Math.floor(now / 60000); // Current minute++ const results: CorrelationResults = {+ emergingPatterns: [],+ momentumSignals: [],+ crossSourceCorrelations: [],+ predictiveSignals: []+ };++ // Count topics and track sources/headlines+ const topicCounts: Record<string, number> = {};+ const topicSources: Record<string, Set<string>> = {};+ const topicHeadlines: Record<string, Array<{ title: string; link: string; source: string }>> = {};++ // Analyze each news item+ for (const item of allNews) {+ const title = item.title || '';+ const source = item.source || 'Unknown';++ for (const topic of CORRELATION_TOPICS) {+ const matches = topic.patterns.some((p) => p.test(title));+ if (matches) {+ if (!topicCounts[topic.id]) {+ topicCounts[topic.id] = 0;+ topicSources[topic.id] = new Set();+ topicHeadlines[topic.id] = [];+ }+ topicCounts[topic.id]++;+ topicSources[topic.id].add(source);+ if (topicHeadlines[topic.id].length < 5) {+ topicHeadlines[topic.id].push({ title, link: item.link, source });+ }+ }+ }+ }++ // Update topic history for momentum tracking+ if (!topicHistory[currentTime]) {+ topicHistory[currentTime] = { ...topicCounts };++ // Clean old history entries+ for (const timeKey of Object.keys(topicHistory)) {+ if (currentTime - parseInt(timeKey) > HISTORY_RETENTION_MINUTES) {+ delete topicHistory[parseInt(timeKey)];+ }+ }+ }++ // Get old counts for momentum comparison+ const oldTime = currentTime - MOMENTUM_WINDOW_MINUTES;+ const oldCounts = topicHistory[oldTime] || {};++ // Process each topic+ for (const topic of CORRELATION_TOPICS) {+ const count = topicCounts[topic.id] || 0;+ const sources = topicSources[topic.id] ? Array.from(topicSources[topic.id]) : [];+ const headlines = topicHeadlines[topic.id] || [];+ const oldCount = oldCounts[topic.id] || 0;+ const delta = count - oldCount;++ // Emerging Patterns (3+ mentions)+ if (count >= 3) {+ const level: EmergingPattern['level'] =+ count >= 8 ? 'high' : count >= 5 ? 'elevated' : 'emerging';++ results.emergingPatterns.push({+ id: topic.id,+ name: formatTopicName(topic.id),+ category: topic.category,+ count,+ level,+ sources,+ headlines+ });+ }++ // Momentum Signals (rising topics)+ if (delta >= 2 || (count >= 3 && delta >= 1)) {+ const momentum: MomentumSignal['momentum'] =+ delta >= 4 ? 'surging' : delta >= 2 ? 'rising' : 'stable';++ results.momentumSignals.push({+ id: topic.id,+ name: formatTopicName(topic.id),+ category: topic.category,+ current: count,+ delta,+ momentum,+ headlines+ });+ }++ // Cross-Source Correlations (3+ sources)+ if (sources.length >= 3) {+ const level: CrossSourceCorrelation['level'] =+ sources.length >= 5 ? 'high' : sources.length >= 4 ? 'elevated' : 'emerging';++ results.crossSourceCorrelations.push({+ id: topic.id,+ name: formatTopicName(topic.id),+ category: topic.category,+ sourceCount: sources.length,+ sources,+ level,+ headlines+ });+ }++ // Predictive Signals (based on combined score)+ const score = count * 2 + sources.length * 3 + delta * 5;++ if (score >= 15) {+ const confidence = Math.min(95, Math.round(score * 1.5));+ const prediction = getPrediction(topic, count);+ const level: PredictiveSignal['level'] =+ confidence >= 70 ? 'high' : confidence >= 50 ? 'medium' : 'low';++ results.predictiveSignals.push({+ id: topic.id,+ name: formatTopicName(topic.id),+ category: topic.category,+ score,+ confidence,+ prediction,+ level,+ headlines+ });+ }+ }++ // Sort results+ results.emergingPatterns.sort((a, b) => b.count - a.count);+ results.momentumSignals.sort((a, b) => b.delta - a.delta);+ results.crossSourceCorrelations.sort((a, b) => b.sourceCount - a.sourceCount);+ results.predictiveSignals.sort((a, b) => b.score - a.score);++ return results;+}++/**+ * Generate prediction text based on topic and count+ */+function getPrediction(topic: CorrelationTopic, count: number): string {+ if (topic.id === 'tariffs' && count >= 4) {+ return 'Market volatility likely in next 24-48h';+ }+ if (topic.id === 'fed-rates') {+ return 'Expect increased financial sector coverage';+ }+ if (topic.id.includes('china') || topic.id.includes('russia')) {+ return 'Geopolitical escalation narrative forming';+ }+ if (topic.id === 'layoffs') {+ return 'Employment concerns may dominate news cycle';+ }+ if (topic.category === 'Conflict') {+ return 'Breaking developments likely within hours';+ }+ return 'Topic gaining mainstream traction';+}++/**+ * Get correlation summary for status display+ */+export function getCorrelationSummary(results: CorrelationResults | null): {+ totalSignals: number;+ status: string;+} {+ if (!results) {+ return { totalSignals: 0, status: 'NO DATA' };+ }++ const totalSignals =+ results.emergingPatterns.length ++ results.momentumSignals.length ++ results.predictiveSignals.length;++ return {+ totalSignals,+ status: totalSignals > 0 ? `${totalSignals} SIGNALS` : 'MONITORING'+ };+}++/**+ * Clear topic history (for testing or reset)+ */+export function clearCorrelationHistory(): void {+ for (const key of Object.keys(topicHistory)) {+ delete topicHistory[parseInt(key)];+ }+}diff --git a/src/lib/analysis/index.ts b/src/lib/analysis/index.tsnew file mode 100644index 0000000..7645e0b--- /dev/null+++ b/src/lib/analysis/index.ts@@ -0,0 +1,35 @@+/**+ * Analysis module barrel file+ */++// Correlation engine+export {+ analyzeCorrelations,+ getCorrelationSummary,+ clearCorrelationHistory,+ type EmergingPattern,+ type MomentumSignal,+ type CrossSourceCorrelation,+ type PredictiveSignal,+ type CorrelationResults+} from './correlation';++// Narrative tracker+export {+ analyzeNarratives,+ getNarrativeSummary,+ clearNarrativeHistory,+ type NarrativeData,+ type EmergingFringe,+ type FringeToMainstream,+ type NarrativeResults+} from './narrative';++// Main character+export {+ calculateMainCharacter,+ getMainCharacterSummary,+ calculateDominance,+ type MainCharacterEntry,+ type MainCharacterResults+} from './main-character';diff --git a/src/lib/analysis/main-character.test.ts b/src/lib/analysis/main-character.test.tsnew file mode 100644index 0000000..b290aa1--- /dev/null+++ b/src/lib/analysis/main-character.test.ts@@ -0,0 +1,142 @@+/**+ * Tests for main character analysis+ */++import { describe, it, expect } from 'vitest';+import {+ calculateMainCharacter,+ getMainCharacterSummary,+ calculateDominance+} from './main-character';+import type { NewsItem } from '$lib/types';++describe('Main Character Analysis', () => {+ it('should return empty results for empty news', () => {+ const results = calculateMainCharacter([]);+ expect(results.characters).toEqual([]);+ expect(results.topCharacter).toBeNull();+ });++ it('should count mentions correctly', () => {+ const news: NewsItem[] = [+ { id: '1', title: 'Trump announces policy', source: 'BBC', link: 'a', timestamp: Date.now(), category: 'politics' },+ { id: '2', title: 'Trump speaks at rally', source: 'CNN', link: 'b', timestamp: Date.now(), category: 'politics' },+ { id: '3', title: 'Biden meets with leaders', source: 'NYT', link: 'c', timestamp: Date.now(), category: 'politics' },+ ];++ const results = calculateMainCharacter(news);++ expect(results.characters.length).toBeGreaterThan(0);+ expect(results.topCharacter?.name).toBe('Trump');+ expect(results.topCharacter?.count).toBe(2);+ });++ it('should rank characters by mention count', () => {+ const news: NewsItem[] = [+ { id: '1', title: 'Musk buys company', source: 'A', link: 'a', timestamp: Date.now(), category: 'tech' },+ { id: '2', title: 'Elon announces feature', source: 'B', link: 'b', timestamp: Date.now(), category: 'tech' },+ { id: '3', title: 'Musk tweets again', source: 'C', link: 'c', timestamp: Date.now(), category: 'tech' },+ { id: '4', title: 'Trump rally today', source: 'D', link: 'd', timestamp: Date.now(), category: 'politics' },+ ];++ const results = calculateMainCharacter(news);++ expect(results.characters[0].name).toBe('Elon Musk');+ expect(results.characters[0].count).toBe(3);+ expect(results.characters[0].rank).toBe(1);+ });++ it('should limit results to top 10', () => {+ // Create news mentioning many different people+ const names = ['Trump', 'Biden', 'Musk', 'Putin', 'Zelensky', 'Xi', 'Netanyahu',+ 'Sam Altman', 'Zuckerberg', 'Bezos', 'Tim Cook', 'Powell'];++ const news: NewsItem[] = names.map((name, i) => ({+ id: String(i),+ title: `${name} in the news`,+ source: 'Source',+ link: `link${i}`,+ timestamp: Date.now(),+ category: 'politics' as const+ }));++ const results = calculateMainCharacter(news);++ expect(results.characters.length).toBeLessThanOrEqual(10);+ });++ it('should match multiple patterns for same person', () => {+ const news: NewsItem[] = [+ { id: '1', title: 'Elon Musk announces', source: 'A', link: 'a', timestamp: Date.now(), category: 'tech' },+ { id: '2', title: 'Musk speaks out', source: 'B', link: 'b', timestamp: Date.now(), category: 'tech' },+ ];++ const results = calculateMainCharacter(news);++ // "Elon Musk" matches both "elon" and "musk" patterns, plus "Musk" matches "musk"+ // So total count is 3 (2 from first headline + 1 from second)+ expect(results.topCharacter?.name).toBe('Elon Musk');+ expect(results.topCharacter?.count).toBe(3);+ });++ it('should return correct summary', () => {+ const emptyResults = calculateMainCharacter([]);+ expect(getMainCharacterSummary(emptyResults)).toEqual({+ name: '',+ count: 0,+ status: 'NO DATA'+ });++ const news: NewsItem[] = [+ { id: '1', title: 'Putin addresses nation', source: 'A', link: 'a', timestamp: Date.now(), category: 'politics' },+ { id: '2', title: 'Putin speaks on economy', source: 'B', link: 'b', timestamp: Date.now(), category: 'politics' },+ ];++ const results = calculateMainCharacter(news);+ const summary = getMainCharacterSummary(results);++ expect(summary.name).toBe('Putin');+ expect(summary.count).toBe(2);+ expect(summary.status).toContain('Putin');+ expect(summary.status).toContain('2 mentions');+ });++ it('should calculate dominance correctly', () => {+ // Single character = 100% dominance+ const singleNews: NewsItem[] = [+ { id: '1', title: 'Trump news', source: 'A', link: 'a', timestamp: Date.now(), category: 'politics' },+ ];+ expect(calculateDominance(calculateMainCharacter(singleNews))).toBe(100);++ // Empty returns 100 (no competition = full dominance, edge case)+ expect(calculateDominance(calculateMainCharacter([]))).toBe(100);++ // Two characters with same count = 0% dominance+ const evenNews: NewsItem[] = [+ { id: '1', title: 'Trump speaks', source: 'A', link: 'a', timestamp: Date.now(), category: 'politics' },+ { id: '2', title: 'Biden responds', source: 'B', link: 'b', timestamp: Date.now(), category: 'politics' },+ ];+ expect(calculateDominance(calculateMainCharacter(evenNews))).toBe(0);++ // Clear leader = high dominance (capped at 100)+ const dominantNews: NewsItem[] = [+ { id: '1', title: 'Musk announcement', source: 'A', link: 'a', timestamp: Date.now(), category: 'tech' },+ { id: '2', title: 'Elon tweets', source: 'B', link: 'b', timestamp: Date.now(), category: 'tech' },+ { id: '3', title: 'Musk company news', source: 'C', link: 'c', timestamp: Date.now(), category: 'tech' },+ { id: '4', title: 'Trump rally', source: 'D', link: 'd', timestamp: Date.now(), category: 'politics' },+ ];+ const dominance = calculateDominance(calculateMainCharacter(dominantNews));+ expect(dominance).toBe(100); // Dominance is capped at 100+ });++ it('should handle case insensitivity', () => {+ const news: NewsItem[] = [+ { id: '1', title: 'TRUMP announces policy', source: 'A', link: 'a', timestamp: Date.now(), category: 'politics' },+ { id: '2', title: 'trump speaks today', source: 'B', link: 'b', timestamp: Date.now(), category: 'politics' },+ ];++ const results = calculateMainCharacter(news);+ expect(results.topCharacter?.name).toBe('Trump');+ expect(results.topCharacter?.count).toBe(2);+ });+});diff --git a/src/lib/analysis/main-character.ts b/src/lib/analysis/main-character.tsnew file mode 100644index 0000000..b14c326--- /dev/null+++ b/src/lib/analysis/main-character.ts@@ -0,0 +1,97 @@+/**+ * Main Character analysis - tracks prominent figures in news+ */++import type { NewsItem } from '$lib/types';+import { PERSON_PATTERNS } from '$lib/config/analysis';++export interface MainCharacterEntry {+ name: string;+ count: number;+ rank: number;+}++export interface MainCharacterResults {+ characters: MainCharacterEntry[];+ topCharacter: MainCharacterEntry | null;+}++/**+ * Calculate the "Main Character" (most mentioned person) from news headlines+ */+export function calculateMainCharacter(allNews: NewsItem[]): MainCharacterResults {+ if (!allNews || allNews.length === 0) {+ return { characters: [], topCharacter: null };+ }++ const counts: Record<string, number> = {};++ // Count mentions for each person+ for (const item of allNews) {+ const text = (item.title || '').toLowerCase();++ for (const { pattern, name } of PERSON_PATTERNS) {+ // Reset lastIndex for global regex+ pattern.lastIndex = 0;+ const matches = text.match(pattern);++ if (matches) {+ counts[name] = (counts[name] || 0) + matches.length;+ }+ }+ }++ // Sort by count and create ranked entries+ const sorted = Object.entries(counts)+ .sort((a, b) => b[1] - a[1])+ .slice(0, 10)+ .map(([name, count], index) => ({+ name,+ count,+ rank: index + 1+ }));++ return {+ characters: sorted,+ topCharacter: sorted[0] || null+ };+}++/**+ * Get a summary of the main character for display+ */+export function getMainCharacterSummary(results: MainCharacterResults): {+ name: string;+ count: number;+ status: string;+} {+ if (!results.topCharacter) {+ return { name: '', count: 0, status: 'NO DATA' };+ }++ const { name, count } = results.topCharacter;+ return {+ name,+ count,+ status: `${name} (${count} mentions)`+ };+}++/**+ * Calculate relative dominance of main character+ * Returns a value 0-100 representing how dominant the top character is+ */+export function calculateDominance(results: MainCharacterResults): number {+ if (results.characters.length < 2) return 100;++ const top = results.characters[0];+ const second = results.characters[1];++ if (!top || top.count === 0) return 0;+ if (!second || second.count === 0) return 100;++ // Dominance is how much more the top is mentioned vs second+ const ratio = top.count / second.count;+ // Convert to 0-100 scale (ratio of 2 = 100% dominant)+ return Math.min(100, Math.round((ratio - 1) * 100));+}diff --git a/src/lib/analysis/narrative.test.ts b/src/lib/analysis/narrative.test.tsnew file mode 100644index 0000000..f6590d6--- /dev/null+++ b/src/lib/analysis/narrative.test.ts@@ -0,0 +1,128 @@+/**+ * Tests for narrative tracker+ */++import { describe, it, expect, beforeEach } from 'vitest';+import {+ analyzeNarratives,+ getNarrativeSummary,+ clearNarrativeHistory+} from './narrative';+import type { NewsItem } from '$lib/types';++describe('Narrative Tracker', () => {+ beforeEach(() => {+ clearNarrativeHistory();+ });++ it('should return null for empty news', () => {+ expect(analyzeNarratives([])).toBeNull();+ expect(analyzeNarratives(null as unknown as NewsItem[])).toBeNull();+ });++ it('should detect narrative patterns', () => {+ const news: NewsItem[] = [+ { id: '1', title: 'Deep state allegations surface', source: 'Test', link: 'a', timestamp: Date.now(), category: 'politics' },+ { id: '2', title: 'Shadow government concerns', source: 'Test2', link: 'b', timestamp: Date.now(), category: 'politics' },+ ];++ const results = analyzeNarratives(news);++ expect(results).not.toBeNull();+ const deepState =+ results!.emergingFringe.find(n => n.id === 'deep-state') ||+ results!.narrativeWatch.find(n => n.id === 'deep-state');++ expect(deepState).toBeDefined();+ expect(deepState!.count).toBe(2);+ });++ it('should classify disinfo patterns', () => {+ const news: NewsItem[] = [+ { id: '1', title: 'Depopulation agenda exposed', source: 'Fringe', link: 'a', timestamp: Date.now(), category: 'politics' },+ ];++ const results = analyzeNarratives(news);++ expect(results!.disinfoSignals.length).toBeGreaterThan(0);+ expect(results!.disinfoSignals.find(n => n.id === 'depopulation')).toBeDefined();+ });++ it('should detect fringe-to-mainstream crossover', () => {+ const news: NewsItem[] = [+ { id: '1', title: 'Lab leak theory gains traction', source: 'ZeroHedge', link: 'a', timestamp: Date.now(), category: 'politics' },+ { id: '2', title: 'Lab leak investigation continues', source: 'BBC News', link: 'b', timestamp: Date.now(), category: 'politics' },+ { id: '3', title: 'Bioweapon research concerns', source: 'CNN', link: 'c', timestamp: Date.now(), category: 'politics' },+ ];++ const results = analyzeNarratives(news);++ // Should detect the bio-weapon narrative crossing from fringe to mainstream+ expect(results!.fringeToMainstream.length).toBeGreaterThan(0);+ });++ it('should classify source types correctly', () => {+ const news: NewsItem[] = [+ { id: '1', title: 'Dollar collapse imminent', source: 'ZeroHedge', link: 'a', timestamp: Date.now(), category: 'finance' },+ { id: '2', title: 'Dedollarization fears', source: 'Infowars', link: 'b', timestamp: Date.now(), category: 'finance' },+ ];++ const results = analyzeNarratives(news);++ const dollarNarrative =+ results!.emergingFringe.find(n => n.id === 'dollar-collapse');++ expect(dollarNarrative).toBeDefined();+ expect(dollarNarrative!.fringeCount).toBeGreaterThan(0);+ });++ it('should track keywords and headlines', () => {+ const news: NewsItem[] = [+ { id: '1', title: 'AI doom predictions increase', source: 'Tech', link: 'a', timestamp: Date.now(), category: 'tech' },+ { id: '2', title: 'AI extinction risk debated', source: 'Tech2', link: 'b', timestamp: Date.now(), category: 'tech' },+ ];++ const results = analyzeNarratives(news);++ const aiDoom =+ results!.emergingFringe.find(n => n.id === 'ai-doom') ||+ results!.narrativeWatch.find(n => n.id === 'ai-doom');++ expect(aiDoom).toBeDefined();+ expect(aiDoom!.keywords).toContain('ai doom');+ expect(aiDoom!.headlines.length).toBeGreaterThan(0);+ });++ it('should return correct summary', () => {+ expect(getNarrativeSummary(null)).toEqual({ total: 0, status: 'NO DATA' });++ const news: NewsItem[] = [+ { id: '1', title: 'Great reset concerns', source: 'Test', link: 'a', timestamp: Date.now(), category: 'politics' },+ ];++ const results = analyzeNarratives(news);+ const summary = getNarrativeSummary(results);++ expect(summary.total).toBeGreaterThan(0);+ expect(summary.status).toMatch(/ACTIVE/);+ });++ it('should limit sources to 5', () => {+ const news: NewsItem[] = Array.from({ length: 10 }, (_, i) => ({+ id: String(i),+ title: 'Deep state news',+ source: `Source${i}`,+ link: `link${i}`,+ timestamp: Date.now(),+ category: 'politics' as const+ }));++ const results = analyzeNarratives(news);++ const deepState =+ results!.emergingFringe.find(n => n.id === 'deep-state') ||+ results!.narrativeWatch.find(n => n.id === 'deep-state');++ expect(deepState!.sources.length).toBeLessThanOrEqual(5);+ });+});diff --git a/src/lib/analysis/narrative.ts b/src/lib/analysis/narrative.tsnew file mode 100644index 0000000..d1e90e4--- /dev/null+++ b/src/lib/analysis/narrative.ts@@ -0,0 +1,209 @@+/**+ * Narrative tracker - analyzes fringe-to-mainstream narrative propagation+ */++import type { NewsItem } from '$lib/types';+import { NARRATIVE_PATTERNS, SOURCE_TYPES, type NarrativePattern } from '$lib/config/analysis';++// Types for narrative results+export interface NarrativeData {+ id: string;+ name: string;+ category: string;+ severity: NarrativePattern['severity'];+ count: number;+ fringeCount: number;+ mainstreamCount: number;+ sources: string[];+ headlines: NewsItem[];+ keywords: string[];+}++export interface EmergingFringe extends NarrativeData {+ status: 'emerging' | 'spreading' | 'viral';+}++export interface FringeToMainstream extends NarrativeData {+ status: 'crossing';+ crossoverLevel: number;+}++export interface NarrativeResults {+ emergingFringe: EmergingFringe[];+ fringeToMainstream: FringeToMainstream[];+ narrativeWatch: NarrativeData[];+ disinfoSignals: NarrativeData[];+}++// Track narrative history for crossover detection+const narrativeHistory: Record<+ string,+ {+ firstSeen: number;+ sources: Set<string>;+ }+> = {};++/**+ * Format narrative ID to display name+ */+function formatNarrativeName(id: string): string {+ return id+ .replace(/-/g, ' ')+ .replace(/\b\w/g, (c) => c.toUpperCase());+}++/**+ * Classify source type+ */+function classifySource(source: string): 'fringe' | 'alternative' | 'mainstream' | null {+ const lowerSource = source.toLowerCase();++ for (const fringeSource of SOURCE_TYPES.fringe) {+ if (lowerSource.includes(fringeSource)) return 'fringe';+ }+ for (const altSource of SOURCE_TYPES.alternative) {+ if (lowerSource.includes(altSource)) return 'alternative';+ }+ for (const msSource of SOURCE_TYPES.mainstream) {+ if (lowerSource.includes(msSource)) return 'mainstream';+ }+ return null;+}++/**+ * Analyze narratives across all news items+ */+export function analyzeNarratives(allNews: NewsItem[]): NarrativeResults | null {+ if (!allNews || allNews.length === 0) return null;++ const now = Date.now();+ const results: NarrativeResults = {+ emergingFringe: [],+ fringeToMainstream: [],+ narrativeWatch: [],+ disinfoSignals: []+ };++ for (const narrative of NARRATIVE_PATTERNS) {+ const matches: NewsItem[] = [];+ const sourceMatches: {+ fringe: NewsItem[];+ alternative: NewsItem[];+ mainstream: NewsItem[];+ } = {+ fringe: [],+ alternative: [],+ mainstream: []+ };++ // Find matching news items+ for (const item of allNews) {+ const title = (item.title || '').toLowerCase();+ const source = (item.source || '').toLowerCase();++ const hasMatch = narrative.keywords.some((kw) => title.includes(kw.toLowerCase()));++ if (hasMatch) {+ matches.push(item);++ const sourceType = classifySource(source);+ if (sourceType) {+ sourceMatches[sourceType].push(item);+ }+ }+ }++ if (matches.length === 0) continue;++ // Update narrative history+ if (!narrativeHistory[narrative.id]) {+ narrativeHistory[narrative.id] = {+ firstSeen: now,+ sources: new Set()+ };+ }+ for (const match of matches) {+ narrativeHistory[narrative.id].sources.add(match.source);+ }++ // Build narrative data+ const narrativeData: NarrativeData = {+ id: narrative.id,+ name: formatNarrativeName(narrative.id),+ category: narrative.category,+ severity: narrative.severity,+ count: matches.length,+ fringeCount: sourceMatches.fringe.length,+ mainstreamCount: sourceMatches.mainstream.length,+ sources: [...new Set(matches.map((m) => m.source))].slice(0, 5),+ headlines: matches.slice(0, 3),+ keywords: narrative.keywords+ };++ // Categorize narrative+ if (sourceMatches.mainstream.length > 0 && sourceMatches.fringe.length > 0) {+ // Fringe to Mainstream crossover+ results.fringeToMainstream.push({+ ...narrativeData,+ status: 'crossing',+ crossoverLevel: sourceMatches.mainstream.length / matches.length+ });+ } else if (narrative.severity === 'disinfo') {+ // Known disinformation pattern+ results.disinfoSignals.push(narrativeData);+ } else if (sourceMatches.fringe.length > 0 || sourceMatches.alternative.length > 0) {+ // Emerging from fringe sources+ const status: EmergingFringe['status'] =+ matches.length >= 5 ? 'viral' : matches.length >= 3 ? 'spreading' : 'emerging';++ results.emergingFringe.push({+ ...narrativeData,+ status+ });+ } else {+ // General narrative watch+ results.narrativeWatch.push(narrativeData);+ }+ }++ // Sort results+ results.emergingFringe.sort((a, b) => b.count - a.count);+ results.fringeToMainstream.sort((a, b) => b.crossoverLevel - a.crossoverLevel);+ results.narrativeWatch.sort((a, b) => b.count - a.count);+ results.disinfoSignals.sort((a, b) => b.count - a.count);++ return results;+}++/**+ * Get narrative summary for status display+ */+export function getNarrativeSummary(results: NarrativeResults | null): {+ total: number;+ status: string;+} {+ if (!results) {+ return { total: 0, status: 'NO DATA' };+ }++ const total =+ results.emergingFringe.length ++ results.fringeToMainstream.length ++ results.narrativeWatch.length ++ results.disinfoSignals.length;++ return {+ total,+ status: total > 0 ? `${total} ACTIVE` : 'MONITORING'+ };+}++/**+ * Clear narrative history (for testing or reset)+ */+export function clearNarrativeHistory(): void {+ for (const key of Object.keys(narrativeHistory)) {+ delete narrativeHistory[key];+ }+}diff --git a/src/lib/config/analysis.ts b/src/lib/config/analysis.tsnew file mode 100644index 0000000..5bfa34b--- /dev/null+++ b/src/lib/config/analysis.ts@@ -0,0 +1,281 @@+/**+ * Analysis configuration - correlation topics, narrative patterns, source classification+ */++export interface CorrelationTopic {+ id: string;+ patterns: RegExp[];+ category: string;+}++export interface NarrativePattern {+ id: string;+ keywords: string[];+ category: string;+ severity: 'watch' | 'emerging' | 'spreading' | 'disinfo';+}++export interface SourceTypes {+ fringe: string[];+ alternative: string[];+ mainstream: string[];+}++export const CORRELATION_TOPICS: CorrelationTopic[] = [+ {+ id: 'tariffs',+ patterns: [/tariff/i, /trade war/i, /import tax/i, /customs duty/i],+ category: 'Economy'+ },+ {+ id: 'fed-rates',+ patterns: [/federal reserve/i, /interest rate/i, /rate cut/i, /rate hike/i, /powell/i, /fomc/i],+ category: 'Economy'+ },+ {+ id: 'inflation',+ patterns: [/inflation/i, /cpi/i, /consumer price/i, /cost of living/i],+ category: 'Economy'+ },+ {+ id: 'ai-regulation',+ patterns: [/ai regulation/i, /artificial intelligence.*law/i, /ai safety/i, /ai governance/i],+ category: 'Tech'+ },+ {+ id: 'china-tensions',+ patterns: [/china.*taiwan/i, /south china sea/i, /us.*china/i, /beijing.*washington/i],+ category: 'Geopolitics'+ },+ {+ id: 'russia-ukraine',+ patterns: [/ukraine/i, /zelensky/i, /putin.*war/i, /crimea/i, /donbas/i],+ category: 'Conflict'+ },+ {+ id: 'israel-gaza',+ patterns: [/gaza/i, /hamas/i, /netanyahu/i, /israel.*attack/i, /hostage/i],+ category: 'Conflict'+ },+ {+ id: 'iran',+ patterns: [/iran.*nuclear/i, /tehran/i, /ayatollah/i, /iranian.*strike/i],+ category: 'Geopolitics'+ },+ {+ id: 'crypto',+ patterns: [/bitcoin/i, /crypto.*regulation/i, /ethereum/i, /sec.*crypto/i],+ category: 'Finance'+ },+ {+ id: 'housing',+ patterns: [/housing market/i, /mortgage rate/i, /home price/i, /real estate.*crash/i],+ category: 'Economy'+ },+ {+ id: 'layoffs',+ patterns: [/layoff/i, /job cut/i, /workforce reduction/i, /downsizing/i],+ category: 'Business'+ },+ {+ id: 'bank-crisis',+ patterns: [/bank.*fail/i, /banking crisis/i, /fdic/i, /bank run/i],+ category: 'Finance'+ },+ {+ id: 'election',+ patterns: [/election/i, /polling/i, /campaign/i, /ballot/i, /voter/i],+ category: 'Politics'+ },+ {+ id: 'immigration',+ patterns: [/immigration/i, /border.*crisis/i, /migrant/i, /deportation/i, /asylum/i],+ category: 'Politics'+ },+ {+ id: 'climate',+ patterns: [/climate change/i, /wildfire/i, /hurricane/i, /extreme weather/i, /flood/i],+ category: 'Environment'+ },+ {+ id: 'pandemic',+ patterns: [/pandemic/i, /outbreak/i, /virus.*spread/i, /who.*emergency/i, /bird flu/i],+ category: 'Health'+ },+ {+ id: 'nuclear',+ patterns: [/nuclear.*threat/i, /nuclear weapon/i, /atomic/i, /icbm/i],+ category: 'Security'+ },+ {+ id: 'supply-chain',+ patterns: [/supply chain/i, /shipping.*delay/i, /port.*congestion/i, /logistics.*crisis/i],+ category: 'Economy'+ },+ {+ id: 'big-tech',+ patterns: [/antitrust.*tech/i, /google.*monopoly/i, /meta.*lawsuit/i, /apple.*doj/i],+ category: 'Tech'+ },+ {+ id: 'deepfake',+ patterns: [/deepfake/i, /ai.*misinformation/i, /synthetic media/i],+ category: 'Tech'+ }+];++export const NARRATIVE_PATTERNS: NarrativePattern[] = [+ {+ id: 'deep-state',+ keywords: ['deep state', 'shadow government', 'permanent state'],+ category: 'Political',+ severity: 'watch'+ },+ {+ id: 'cbdc-control',+ keywords: ['cbdc control', 'digital currency surveillance', 'social credit'],+ category: 'Finance',+ severity: 'watch'+ },+ {+ id: 'wef-agenda',+ keywords: ['great reset', 'wef agenda', 'world economic forum plot'],+ category: 'Political',+ severity: 'watch'+ },+ {+ id: 'bio-weapon',+ keywords: ['lab leak', 'bioweapon', 'gain of function'],+ category: 'Health',+ severity: 'emerging'+ },+ {+ id: 'election-fraud',+ keywords: ['election fraud', 'rigged election', 'stolen election', 'mail ballot fraud'],+ category: 'Political',+ severity: 'watch'+ },+ {+ id: 'ai-doom',+ keywords: ['ai doom', 'ai extinction', 'superintelligence risk', 'agi danger'],+ category: 'Tech',+ severity: 'emerging'+ },+ {+ id: 'ai-consciousness',+ keywords: ['ai sentient', 'ai conscious', 'ai feelings', 'ai alive'],+ category: 'Tech',+ severity: 'emerging'+ },+ {+ id: 'robot-replacement',+ keywords: ['robots replacing', 'automation unemployment', 'job automation'],+ category: 'Economy',+ severity: 'spreading'+ },+ {+ id: 'china-invasion',+ keywords: ['china taiwan invasion', 'china war', 'south china sea conflict'],+ category: 'Geopolitical',+ severity: 'watch'+ },+ {+ id: 'nato-expansion',+ keywords: ['nato provocation', 'nato aggression', 'nato encirclement'],+ category: 'Geopolitical',+ severity: 'watch'+ },+ {+ id: 'dollar-collapse',+ keywords: ['dollar collapse', 'dedollarization', 'brics currency', 'petrodollar death'],+ category: 'Finance',+ severity: 'spreading'+ },+ {+ id: 'vaccine-injury',+ keywords: ['vaccine injury', 'vaccine side effect', 'vaccine death', 'turbo cancer'],+ category: 'Health',+ severity: 'watch'+ },+ {+ id: 'next-pandemic',+ keywords: ['next pandemic', 'disease x', 'bird flu pandemic'],+ category: 'Health',+ severity: 'emerging'+ },+ {+ id: 'depopulation',+ keywords: ['depopulation agenda', 'fertility crisis', 'population control'],+ category: 'Society',+ severity: 'disinfo'+ },+ {+ id: 'food-crisis',+ keywords: ['food shortage', 'engineered famine', 'food supply attack'],+ category: 'Economy',+ severity: 'emerging'+ },+ {+ id: 'energy-war',+ keywords: ['energy crisis manufactured', 'green agenda', 'energy shortage'],+ category: 'Economy',+ severity: 'spreading'+ }+];++export const SOURCE_TYPES: SourceTypes = {+ fringe: [+ 'zerohedge',+ 'infowars',+ 'naturalnews',+ 'gateway',+ 'breitbart',+ 'epoch',+ 'revolver',+ 'dailycaller'+ ],+ alternative: ['substack', 'rumble', 'bitchute', 'telegram', 'gab', 'gettr', 'truth social'],+ mainstream: [+ 'reuters',+ 'ap news',+ 'bbc',+ 'cnn',+ 'nytimes',+ 'wsj',+ 'wapo',+ 'guardian',+ 'abc',+ 'nbc',+ 'cbs',+ 'fox'+ ]+};++// Main character patterns for tracking prominent figures+export interface PersonPattern {+ pattern: RegExp;+ name: string;+}++export const PERSON_PATTERNS: PersonPattern[] = [+ { pattern: /\btrump\b/gi, name: 'Trump' },+ { pattern: /\bbiden\b/gi, name: 'Biden' },+ { pattern: /\belon\b|\bmusk\b/gi, name: 'Elon Musk' },+ { pattern: /\bputin\b/gi, name: 'Putin' },+ { pattern: /\bzelensky\b/gi, name: 'Zelensky' },+ { pattern: /\bxi\s*jinping\b|\bxi\b/gi, name: 'Xi Jinping' },+ { pattern: /\bnetanyahu\b/gi, name: 'Netanyahu' },+ { pattern: /\bsam\s*altman\b/gi, name: 'Sam Altman' },+ { pattern: /\bmark\s*zuckerberg\b|\bzuckerberg\b/gi, name: 'Zuckerberg' },+ { pattern: /\bjeff\s*bezos\b|\bbezos\b/gi, name: 'Bezos' },+ { pattern: /\btim\s*cook\b/gi, name: 'Tim Cook' },+ { pattern: /\bsatya\s*nadella\b|\bnadella\b/gi, name: 'Satya Nadella' },+ { pattern: /\bsundar\s*pichai\b|\bpichai\b/gi, name: 'Sundar Pichai' },+ { pattern: /\bwarren\s*buffett\b|\bbuffett\b/gi, name: 'Warren Buffett' },+ { pattern: /\bjanet\s*yellen\b|\byellen\b/gi, name: 'Janet Yellen' },+ { pattern: /\bjerome\s*powell\b|\bpowell\b/gi, name: 'Jerome Powell' },+ { pattern: /\bkamala\s*harris\b|\bharris\b/gi, name: 'Kamala Harris' },+ { pattern: /\bnancy\s*pelosi\b|\bpelosi\b/gi, name: 'Nancy Pelosi' },+ { pattern: /\bjensen\s*huang\b|\bhuang\b/gi, name: 'Jensen Huang' },+ { pattern: /\bdario\s*amodei\b|\bamodei\b/gi, name: 'Dario Amodei' }+];diff --git a/src/lib/config/index.ts b/src/lib/config/index.tsindex 6b1182e..05cb849 100644--- a/src/lib/config/index.ts+++ b/src/lib/config/index.ts@@ -36,3 +36,15 @@ export {type SectorConfig,type CommodityConfig} from './markets';++// Analysis configuration+export {+ CORRELATION_TOPICS,+ NARRATIVE_PATTERNS,+ SOURCE_TYPES,+ PERSON_PATTERNS,+ type CorrelationTopic,+ type NarrativePattern,+ type SourceTypes,+ type PersonPattern+} from './analysis';diff --git a/src/lib/stores/index.ts b/src/lib/stores/index.tsnew file mode 100644index 0000000..2a9b360--- /dev/null+++ b/src/lib/stores/index.ts@@ -0,0 +1,68 @@+/**+ * Stores barrel file - re-exports all stores+ */++// Settings store+export {+ settings,+ enabledPanels,+ disabledPanels,+ draggablePanels,+ type PanelSettings,+ type SettingsState+} from './settings';++// Monitors store+export {+ monitors,+ enabledMonitors,+ monitorCount,+ matchCount,+ hasMatches,+ type MonitorMatch,+ type MonitorsState+} from './monitors';++// News store+export {+ news,+ politicsNews,+ techNews,+ financeNews,+ govNews,+ aiNews,+ intelNews,+ alerts,+ isLoading as isNewsLoading,+ hasErrors as hasNewsErrors,+ type CategoryState,+ type NewsState+} from './news';++// Markets store+export {+ markets,+ indices,+ sectors,+ commodities,+ crypto,+ isMarketsLoading,+ marketsLastUpdated,+ vix,+ type MarketsState+} from './markets';++// Refresh store+export {+ refresh,+ isRefreshing,+ currentStage,+ lastRefresh,+ autoRefreshEnabled,+ timeSinceRefresh,+ categoriesWithErrors,+ REFRESH_STAGES,+ type RefreshStage,+ type StageConfig,+ type RefreshState+} from './refresh';diff --git a/src/lib/stores/markets.test.ts b/src/lib/stores/markets.test.tsnew file mode 100644index 0000000..25051ad--- /dev/null+++ b/src/lib/stores/markets.test.ts@@ -0,0 +1,185 @@+/**+ * Tests for markets store+ */++import { describe, it, expect, beforeEach, vi } from 'vitest';+import { get } from 'svelte/store';++// Mock $app/environment+vi.mock('$app/environment', () => ({+ browser: true+}));++describe('Markets Store', () => {+ beforeEach(async () => {+ vi.resetModules();+ });++ it('should start with empty markets', async () => {+ const { markets } = await import('./markets');++ const state = get(markets);+ expect(state.indices.items).toEqual([]);+ expect(state.sectors.items).toEqual([]);+ expect(state.commodities.items).toEqual([]);+ expect(state.crypto.items).toEqual([]);+ });++ it('should set indices data', async () => {+ const { markets, indices } = await import('./markets');++ const indexData = [+ { symbol: '^DJI', name: 'Dow Jones', price: 38000, change: 150, changePercent: 0.4 },+ { symbol: '^GSPC', name: 'S&P 500', price: 5000, change: 25, changePercent: 0.5 }+ ];++ markets.setIndices(indexData);++ const data = get(indices);+ expect(data.items.length).toBe(2);+ expect(data.loading).toBe(false);+ expect(data.lastUpdated).not.toBeNull();+ });++ it('should set sectors data', async () => {+ const { markets, sectors } = await import('./markets');++ const sectorData = [+ { symbol: 'XLK', name: 'Tech', price: 200, change: 2, changePercent: 1.0 },+ { symbol: 'XLF', name: 'Finance', price: 40, change: -0.5, changePercent: -1.25 }+ ];++ markets.setSectors(sectorData);++ const data = get(sectors);+ expect(data.items.length).toBe(2);+ });++ it('should set commodities data', async () => {+ const { markets, commodities, vix } = await import('./markets');++ const commodityData = [+ { symbol: '^VIX', name: 'VIX', price: 15, change: 0.5, changePercent: 3.4 },+ { symbol: 'GC=F', name: 'Gold', price: 2000, change: 10, changePercent: 0.5 }+ ];++ markets.setCommodities(commodityData);++ const data = get(commodities);+ expect(data.items.length).toBe(2);++ const vixData = get(vix);+ expect(vixData?.symbol).toBe('^VIX');+ expect(vixData?.price).toBe(15);+ });++ it('should set crypto data', async () => {+ const { markets, crypto } = await import('./markets');++ const cryptoData = [+ {+ id: 'bitcoin',+ symbol: 'BTC',+ name: 'Bitcoin',+ current_price: 95000,+ price_change_24h: 1500,+ price_change_percentage_24h: 1.6+ },+ {+ id: 'ethereum',+ symbol: 'ETH',+ name: 'Ethereum',+ current_price: 3500,+ price_change_24h: -50,+ price_change_percentage_24h: -1.4+ }+ ];++ markets.setCrypto(cryptoData);++ const data = get(crypto);+ expect(data.items.length).toBe(2);+ expect(data.items[0].id).toBe('bitcoin');+ });++ it('should set loading state', async () => {+ const { markets, isMarketsLoading } = await import('./markets');++ markets.setLoading('indices', true);+ expect(get(isMarketsLoading)).toBe(true);++ markets.setLoading('indices', false);+ expect(get(isMarketsLoading)).toBe(false);+ });++ it('should set error state', async () => {+ const { markets, indices } = await import('./markets');++ markets.setError('indices', 'API error');++ const data = get(indices);+ expect(data.error).toBe('API error');+ expect(data.loading).toBe(false);+ });++ it('should update single market item', async () => {+ const { markets, indices } = await import('./markets');++ markets.setIndices([{ symbol: '^DJI', name: 'Dow', price: 38000, change: 0, changePercent: 0 }]);++ markets.updateItem('indices', '^DJI', { price: 38100, change: 100, changePercent: 0.26 });++ const data = get(indices);+ expect(data.items[0].price).toBe(38100);+ expect(data.items[0].change).toBe(100);+ });++ it('should get market summary', async () => {+ const { markets } = await import('./markets');++ markets.setIndices([+ { symbol: 'A', name: 'A', price: 100, change: 5, changePercent: 5 },+ { symbol: 'B', name: 'B', price: 100, change: 3, changePercent: 3 },+ { symbol: 'C', name: 'C', price: 100, change: -1, changePercent: -1 }+ ]);++ const summary = markets.getSummary();+ expect(summary.marketTrend).toBe('up');+ expect(summary.topGainer?.symbol).toBe('A');+ expect(summary.topLoser?.symbol).toBe('C');+ });++ it('should derive last updated correctly', async () => {+ const { markets, marketsLastUpdated } = await import('./markets');++ expect(get(marketsLastUpdated)).toBeNull();++ markets.setIndices([{ symbol: 'A', name: 'A', price: 100, change: 0, changePercent: 0 }]);++ const lastUpdated = get(marketsLastUpdated);+ expect(lastUpdated).not.toBeNull();+ expect(lastUpdated).toBeLessThanOrEqual(Date.now());+ });++ it('should clear all data', async () => {+ const { markets } = await import('./markets');++ markets.setIndices([{ symbol: 'A', name: 'A', price: 100, change: 0, changePercent: 0 }]);+ markets.setCrypto([+ {+ id: 'btc',+ symbol: 'BTC',+ name: 'Bitcoin',+ current_price: 100,+ price_change_24h: 0,+ price_change_percentage_24h: 0+ }+ ]);++ markets.clearAll();++ const state = get(markets);+ expect(state.indices.items).toEqual([]);+ expect(state.crypto.items).toEqual([]);+ });+});diff --git a/src/lib/stores/markets.ts b/src/lib/stores/markets.tsnew file mode 100644index 0000000..f71efdd--- /dev/null+++ b/src/lib/stores/markets.ts@@ -0,0 +1,296 @@+/**+ * Markets store - stocks, crypto, commodities, indices+ */++import { writable, derived, get } from 'svelte/store';+import type { MarketItem, CryptoItem, SectorPerformance } from '$lib/types';++export interface MarketsState {+ // Stock indices (DOW, S&P, NASDAQ, Russell)+ indices: {+ items: MarketItem[];+ loading: boolean;+ error: string | null;+ lastUpdated: number | null;+ };++ // Sector ETFs (XLK, XLF, etc.)+ sectors: {+ items: SectorPerformance[];+ loading: boolean;+ error: string | null;+ lastUpdated: number | null;+ };++ // Commodities (Gold, Oil, VIX, etc.)+ commodities: {+ items: MarketItem[];+ loading: boolean;+ error: string | null;+ lastUpdated: number | null;+ };++ // Crypto (BTC, ETH, SOL)+ crypto: {+ items: CryptoItem[];+ loading: boolean;+ error: string | null;+ lastUpdated: number | null;+ };++ initialized: boolean;+}++type MarketCategory = 'indices' | 'sectors' | 'commodities' | 'crypto';++// Create initial state+function createInitialState(): MarketsState {+ const emptySection = {+ items: [],+ loading: false,+ error: null,+ lastUpdated: null+ };++ return {+ indices: { ...emptySection },+ sectors: { ...emptySection },+ commodities: { ...emptySection },+ crypto: { ...emptySection },+ initialized: false+ };+}++// Create the store+function createMarketsStore() {+ const { subscribe, set, update } = writable<MarketsState>(createInitialState());++ return {+ subscribe,++ /**+ * Initialize store+ */+ init() {+ update((state) => ({ ...state, initialized: true }));+ },++ /**+ * Set loading state for a category+ */+ setLoading(category: MarketCategory, loading: boolean) {+ update((state) => ({+ ...state,+ [category]: {+ ...state[category],+ loading,+ error: loading ? null : state[category].error+ }+ }));+ },++ /**+ * Set error state for a category+ */+ setError(category: MarketCategory, error: string | null) {+ update((state) => ({+ ...state,+ [category]: {+ ...state[category],+ loading: false,+ error+ }+ }));+ },++ /**+ * Set indices data+ */+ setIndices(items: MarketItem[]) {+ update((state) => ({+ ...state,+ indices: {+ items,+ loading: false,+ error: null,+ lastUpdated: Date.now()+ }+ }));+ },++ /**+ * Set sectors data+ */+ setSectors(items: SectorPerformance[]) {+ update((state) => ({+ ...state,+ sectors: {+ items,+ loading: false,+ error: null,+ lastUpdated: Date.now()+ }+ }));+ },++ /**+ * Set commodities data+ */+ setCommodities(items: MarketItem[]) {+ update((state) => ({+ ...state,+ commodities: {+ items,+ loading: false,+ error: null,+ lastUpdated: Date.now()+ }+ }));+ },++ /**+ * Set crypto data+ */+ setCrypto(items: CryptoItem[]) {+ update((state) => ({+ ...state,+ crypto: {+ items,+ loading: false,+ error: null,+ lastUpdated: Date.now()+ }+ }));+ },++ /**+ * Update a single market item+ */+ updateItem(category: 'indices' | 'commodities', symbol: string, updates: Partial<MarketItem>) {+ update((state) => {+ const items = state[category].items as MarketItem[];+ const index = items.findIndex((i) => i.symbol === symbol);+ if (index === -1) return state;++ const newItems = [...items];+ newItems[index] = { ...newItems[index], ...updates };++ return {+ ...state,+ [category]: {+ ...state[category],+ items: newItems+ }+ };+ });+ },++ /**+ * Update a single crypto item+ */+ updateCrypto(id: string, updates: Partial<CryptoItem>) {+ update((state) => {+ const index = state.crypto.items.findIndex((i) => i.id === id);+ if (index === -1) return state;++ const newItems = [...state.crypto.items];+ newItems[index] = { ...newItems[index], ...updates };++ return {+ ...state,+ crypto: {+ ...state.crypto,+ items: newItems+ }+ };+ });+ },++ /**+ * Get market summary+ */+ getSummary(): {+ marketTrend: 'up' | 'down' | 'mixed';+ topGainer: MarketItem | null;+ topLoser: MarketItem | null;+ } {+ const state = get({ subscribe });+ const allItems = [...state.indices.items, ...state.sectors.items, ...state.commodities.items];++ if (allItems.length === 0) {+ return { marketTrend: 'mixed', topGainer: null, topLoser: null };+ }++ const gainers = allItems.filter((i) => i.changePercent > 0);+ const losers = allItems.filter((i) => i.changePercent < 0);++ let marketTrend: 'up' | 'down' | 'mixed' = 'mixed';+ if (gainers.length > losers.length * 1.5) {+ marketTrend = 'up';+ } else if (losers.length > gainers.length * 1.5) {+ marketTrend = 'down';+ }++ const sorted = [...allItems].sort((a, b) => b.changePercent - a.changePercent);+ const topGainer = sorted[0] ?? null;+ const topLoser = sorted[sorted.length - 1] ?? null;++ return { marketTrend, topGainer, topLoser };+ },++ /**+ * Check if any category is loading+ */+ isAnyLoading(): boolean {+ const state = get({ subscribe });+ return (+ state.indices.loading ||+ state.sectors.loading ||+ state.commodities.loading ||+ state.crypto.loading+ );+ },++ /**+ * Clear all data+ */+ clearAll() {+ set(createInitialState());+ }+ };+}++// Export singleton store+export const markets = createMarketsStore();++// Derived stores+export const indices = derived(markets, ($markets) => $markets.indices);+export const sectors = derived(markets, ($markets) => $markets.sectors);+export const commodities = derived(markets, ($markets) => $markets.commodities);+export const crypto = derived(markets, ($markets) => $markets.crypto);++// Market status derived stores+export const isMarketsLoading = derived(+ markets,+ ($markets) =>+ $markets.indices.loading ||+ $markets.sectors.loading ||+ $markets.commodities.loading ||+ $markets.crypto.loading+);++export const marketsLastUpdated = derived(markets, ($markets) => {+ const times = [+ $markets.indices.lastUpdated,+ $markets.sectors.lastUpdated,+ $markets.commodities.lastUpdated,+ $markets.crypto.lastUpdated+ ].filter((t): t is number => t !== null);++ return times.length > 0 ? Math.max(...times) : null;+});++// VIX convenience store (commonly needed)+export const vix = derived(markets, ($markets) => {+ return $markets.commodities.items.find((i) => i.symbol === '^VIX') ?? null;+});diff --git a/src/lib/stores/monitors.test.ts b/src/lib/stores/monitors.test.tsnew file mode 100644index 0000000..32cc00f--- /dev/null+++ b/src/lib/stores/monitors.test.ts@@ -0,0 +1,198 @@+/**+ * Tests for monitors store+ */++import { describe, it, expect, beforeEach, vi } from 'vitest';+import { get } from 'svelte/store';++// Mock $app/environment before importing the store+vi.mock('$app/environment', () => ({+ browser: true+}));++// Mock localStorage+const localStorageMock = (() => {+ let store: Record<string, string> = {};+ return {+ getItem: vi.fn((key: string) => store[key] || null),+ setItem: vi.fn((key: string, value: string) => {+ store[key] = value;+ }),+ removeItem: vi.fn((key: string) => {+ delete store[key];+ }),+ clear: vi.fn(() => {+ store = {};+ })+ };+})();++Object.defineProperty(globalThis, 'localStorage', {+ value: localStorageMock+});++describe('Monitors Store', () => {+ beforeEach(async () => {+ localStorageMock.clear();+ vi.clearAllMocks();+ vi.resetModules();+ });++ it('should start with empty monitors', async () => {+ const { monitors } = await import('./monitors');++ const state = get(monitors);+ expect(state.monitors).toEqual([]);+ expect(state.matches).toEqual([]);+ });++ it('should add a new monitor', async () => {+ const { monitors } = await import('./monitors');++ const newMonitor = monitors.addMonitor({+ name: 'Test Monitor',+ keywords: ['test', 'keyword'],+ enabled: true+ });++ expect(newMonitor).not.toBeNull();+ expect(newMonitor?.name).toBe('Test Monitor');+ expect(newMonitor?.keywords).toEqual(['test', 'keyword']);+ expect(newMonitor?.id).toMatch(/^mon_/);+ });++ it('should update a monitor', async () => {+ const { monitors } = await import('./monitors');++ const monitor = monitors.addMonitor({+ name: 'Original',+ keywords: ['original'],+ enabled: true+ });++ const updated = monitors.updateMonitor(monitor!.id, {+ name: 'Updated',+ keywords: ['updated', 'new']+ });++ expect(updated).toBe(true);++ const found = monitors.getMonitor(monitor!.id);+ expect(found?.name).toBe('Updated');+ expect(found?.keywords).toEqual(['updated', 'new']);+ });++ it('should delete a monitor', async () => {+ const { monitors } = await import('./monitors');++ const monitor = monitors.addMonitor({+ name: 'To Delete',+ keywords: ['delete'],+ enabled: true+ });++ const deleted = monitors.deleteMonitor(monitor!.id);+ expect(deleted).toBe(true);++ const found = monitors.getMonitor(monitor!.id);+ expect(found).toBeUndefined();+ });++ it('should toggle monitor enabled state', async () => {+ const { monitors } = await import('./monitors');++ const monitor = monitors.addMonitor({+ name: 'Toggle Test',+ keywords: ['toggle'],+ enabled: true+ });++ monitors.toggleMonitor(monitor!.id);+ expect(monitors.getMonitor(monitor!.id)?.enabled).toBe(false);++ monitors.toggleMonitor(monitor!.id);+ expect(monitors.getMonitor(monitor!.id)?.enabled).toBe(true);+ });++ it('should scan for matches', async () => {+ const { monitors } = await import('./monitors');++ monitors.addMonitor({+ name: 'Ukraine Monitor',+ keywords: ['ukraine', 'zelensky'],+ enabled: true+ });++ const newsItems = [+ {+ id: '1',+ title: 'Ukraine announces new policy',+ source: 'BBC',+ link: 'https://bbc.com/1',+ timestamp: Date.now(),+ category: 'politics' as const+ },+ {+ id: '2',+ title: 'Tech stocks rise',+ source: 'CNBC',+ link: 'https://cnbc.com/2',+ timestamp: Date.now(),+ category: 'finance' as const+ }+ ];++ const matches = monitors.scanForMatches(newsItems);++ expect(matches.length).toBe(1);+ expect(matches[0].item.title).toContain('Ukraine');+ expect(matches[0].matchedKeywords).toContain('ukraine');+ });++ it('should not match disabled monitors', async () => {+ const { monitors } = await import('./monitors');++ monitors.addMonitor({+ name: 'Disabled Monitor',+ keywords: ['test'],+ enabled: false+ });++ const newsItems = [+ {+ id: '1',+ title: 'Test headline',+ source: 'Test',+ link: 'https://test.com',+ timestamp: Date.now(),+ category: 'politics' as const+ }+ ];++ const matches = monitors.scanForMatches(newsItems);+ expect(matches.length).toBe(0);+ });++ it('should persist monitors to localStorage', async () => {+ const { monitors } = await import('./monitors');++ monitors.addMonitor({+ name: 'Persistent Monitor',+ keywords: ['persist'],+ enabled: true+ });++ expect(localStorageMock.setItem).toHaveBeenCalledWith('customMonitors', expect.any(String));+ });++ it('should derive enabled monitors correctly', async () => {+ const { monitors, enabledMonitors, monitorCount } = await import('./monitors');++ monitors.addMonitor({ name: 'Enabled', keywords: ['a'], enabled: true });+ monitors.addMonitor({ name: 'Disabled', keywords: ['b'], enabled: false });+ monitors.addMonitor({ name: 'Also Enabled', keywords: ['c'], enabled: true });++ expect(get(enabledMonitors).length).toBe(2);+ expect(get(monitorCount)).toBe(3);+ });+});diff --git a/src/lib/stores/monitors.ts b/src/lib/stores/monitors.tsnew file mode 100644index 0000000..0238a84--- /dev/null+++ b/src/lib/stores/monitors.ts@@ -0,0 +1,244 @@+/**+ * Monitors store - custom user monitors CRUD+ */++import { writable, derived, get } from 'svelte/store';+import { browser } from '$app/environment';+import type { CustomMonitor, NewsItem } from '$lib/types';++const STORAGE_KEY = 'customMonitors';+const MAX_MONITORS = 20;++export interface MonitorMatch {+ monitor: CustomMonitor;+ item: NewsItem;+ matchedKeywords: string[];+}++export interface MonitorsState {+ monitors: CustomMonitor[];+ matches: MonitorMatch[];+ initialized: boolean;+}++// Load monitors from localStorage+function loadMonitors(): CustomMonitor[] {+ if (!browser) return [];++ try {+ const data = localStorage.getItem(STORAGE_KEY);+ return data ? JSON.parse(data) : [];+ } catch (e) {+ console.warn('Failed to load monitors from localStorage:', e);+ return [];+ }+}++// Save monitors to localStorage+function saveMonitors(monitors: CustomMonitor[]): void {+ if (!browser) return;++ try {+ localStorage.setItem(STORAGE_KEY, JSON.stringify(monitors));+ } catch (e) {+ console.warn('Failed to save monitors to localStorage:', e);+ }+}++// Generate a unique ID+function generateId(): string {+ return `mon_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;+}++// Create the store+function createMonitorsStore() {+ const initialState: MonitorsState = {+ monitors: loadMonitors(),+ matches: [],+ initialized: false+ };++ const { subscribe, set, update } = writable<MonitorsState>(initialState);++ return {+ subscribe,++ /**+ * Initialize store (call after hydration)+ */+ init() {+ update((state) => ({ ...state, initialized: true }));+ },++ /**+ * Get all monitors+ */+ getMonitors(): CustomMonitor[] {+ return get({ subscribe }).monitors;+ },++ /**+ * Get a specific monitor by ID+ */+ getMonitor(id: string): CustomMonitor | undefined {+ return get({ subscribe }).monitors.find((m) => m.id === id);+ },++ /**+ * Add a new monitor+ */+ addMonitor(+ monitor: Omit<CustomMonitor, 'id' | 'createdAt' | 'matchCount'>+ ): CustomMonitor | null {+ const state = get({ subscribe });++ if (state.monitors.length >= MAX_MONITORS) {+ console.warn(`Maximum monitors (${MAX_MONITORS}) reached`);+ return null;+ }++ const newMonitor: CustomMonitor = {+ ...monitor,+ id: generateId(),+ createdAt: Date.now(),+ matchCount: 0+ };++ update((s) => {+ const newMonitors = [...s.monitors, newMonitor];+ saveMonitors(newMonitors);+ return { ...s, monitors: newMonitors };+ });++ return newMonitor;+ },++ /**+ * Update an existing monitor+ */+ updateMonitor(id: string, updates: Partial<Omit<CustomMonitor, 'id' | 'createdAt'>>): boolean {+ let found = false;++ update((state) => {+ const index = state.monitors.findIndex((m) => m.id === id);+ if (index === -1) return state;++ found = true;+ const newMonitors = [...state.monitors];+ newMonitors[index] = { ...newMonitors[index], ...updates };+ saveMonitors(newMonitors);+ return { ...state, monitors: newMonitors };+ });++ return found;+ },++ /**+ * Delete a monitor+ */+ deleteMonitor(id: string): boolean {+ let found = false;++ update((state) => {+ const index = state.monitors.findIndex((m) => m.id === id);+ if (index === -1) return state;++ found = true;+ const newMonitors = state.monitors.filter((m) => m.id !== id);+ const newMatches = state.matches.filter((m) => m.monitor.id !== id);+ saveMonitors(newMonitors);+ return { ...state, monitors: newMonitors, matches: newMatches };+ });++ return found;+ },++ /**+ * Toggle monitor enabled state+ */+ toggleMonitor(id: string): void {+ update((state) => {+ const index = state.monitors.findIndex((m) => m.id === id);+ if (index === -1) return state;++ const newMonitors = [...state.monitors];+ newMonitors[index] = {+ ...newMonitors[index],+ enabled: !newMonitors[index].enabled+ };+ saveMonitors(newMonitors);+ return { ...state, monitors: newMonitors };+ });+ },++ /**+ * Scan news items for monitor matches+ */+ scanForMatches(newsItems: NewsItem[]): MonitorMatch[] {+ const state = get({ subscribe });+ const matches: MonitorMatch[] = [];++ for (const monitor of state.monitors) {+ if (!monitor.enabled) continue;++ for (const item of newsItems) {+ const textToSearch = `${item.title} ${item.description || ''}`.toLowerCase();+ const matchedKeywords: string[] = [];++ for (const keyword of monitor.keywords) {+ if (textToSearch.includes(keyword.toLowerCase())) {+ matchedKeywords.push(keyword);+ }+ }++ if (matchedKeywords.length > 0) {+ matches.push({ monitor, item, matchedKeywords });+ }+ }+ }++ // Update match counts and store matches+ update((s) => {+ const newMonitors = s.monitors.map((m) => ({+ ...m,+ matchCount: matches.filter((match) => match.monitor.id === m.id).length+ }));+ saveMonitors(newMonitors);+ return { ...s, monitors: newMonitors, matches };+ });++ return matches;+ },++ /**+ * Clear all matches+ */+ clearMatches(): void {+ update((state) => ({ ...state, matches: [] }));+ },++ /**+ * Reset all monitors+ */+ reset(): void {+ if (browser) {+ localStorage.removeItem(STORAGE_KEY);+ }+ set({ monitors: [], matches: [], initialized: true });+ }+ };+}++// Export singleton store+export const monitors = createMonitorsStore();++// Derived stores+export const enabledMonitors = derived(monitors, ($monitors) =>+ $monitors.monitors.filter((m) => m.enabled)+);++export const monitorCount = derived(monitors, ($monitors) => $monitors.monitors.length);++export const matchCount = derived(monitors, ($monitors) => $monitors.matches.length);++export const hasMatches = derived(monitors, ($monitors) => $monitors.matches.length > 0);diff --git a/src/lib/stores/news.test.ts b/src/lib/stores/news.test.tsnew file mode 100644index 0000000..7cc06a0--- /dev/null+++ b/src/lib/stores/news.test.ts@@ -0,0 +1,217 @@+/**+ * Tests for news store+ */++import { describe, it, expect, beforeEach, vi } from 'vitest';+import { get } from 'svelte/store';++// Mock $app/environment+vi.mock('$app/environment', () => ({+ browser: true+}));++describe('News Store', () => {+ beforeEach(async () => {+ vi.resetModules();+ });++ it('should start with empty categories', async () => {+ const { news } = await import('./news');++ const state = get(news);+ expect(state.categories.politics.items).toEqual([]);+ expect(state.categories.tech.items).toEqual([]);+ expect(state.categories.finance.items).toEqual([]);+ });++ it('should set items for a category', async () => {+ const { news, politicsNews } = await import('./news');++ const items = [+ {+ id: '1',+ title: 'Test headline',+ source: 'BBC',+ link: 'https://bbc.com/1',+ timestamp: Date.now(),+ category: 'politics' as const+ }+ ];++ news.setItems('politics', items);++ const politics = get(politicsNews);+ expect(politics.items.length).toBe(1);+ expect(politics.items[0].title).toBe('Test headline');+ expect(politics.loading).toBe(false);+ expect(politics.lastUpdated).not.toBeNull();+ });++ it('should enrich items with alert detection', async () => {+ const { news } = await import('./news');++ const items = [+ {+ id: '1',+ title: 'Military strike in region',+ source: 'BBC',+ link: 'https://bbc.com/1',+ timestamp: Date.now(),+ category: 'politics' as const+ },+ {+ id: '2',+ title: 'New tech startup launches',+ source: 'TechCrunch',+ link: 'https://tc.com/2',+ timestamp: Date.now(),+ category: 'tech' as const+ }+ ];++ news.setItems('politics', [items[0]]);+ news.setItems('tech', [items[1]]);++ const state = get(news);+ expect(state.categories.politics.items[0].isAlert).toBe(true);+ expect(state.categories.politics.items[0].alertKeyword).toBe('military');+ expect(state.categories.tech.items[0].isAlert).toBe(false);+ });++ it('should set loading state', async () => {+ const { news, politicsNews } = await import('./news');++ news.setLoading('politics', true);+ expect(get(politicsNews).loading).toBe(true);++ news.setLoading('politics', false);+ expect(get(politicsNews).loading).toBe(false);+ });++ it('should set error state', async () => {+ const { news, politicsNews, hasErrors } = await import('./news');++ news.setError('politics', 'Failed to fetch');++ const politics = get(politicsNews);+ expect(politics.error).toBe('Failed to fetch');+ expect(politics.loading).toBe(false);++ expect(get(hasErrors)).toBe(true);+ });++ it('should append items without duplicates', async () => {+ const { news, techNews } = await import('./news');++ const initial = [+ {+ id: '1',+ title: 'First item',+ source: 'TC',+ link: 'https://tc.com/1',+ timestamp: Date.now(),+ category: 'tech' as const+ }+ ];++ const more = [+ {+ id: '1',+ title: 'First item',+ source: 'TC',+ link: 'https://tc.com/1',+ timestamp: Date.now(),+ category: 'tech' as const+ },+ {+ id: '2',+ title: 'Second item',+ source: 'TC',+ link: 'https://tc.com/2',+ timestamp: Date.now(),+ category: 'tech' as const+ }+ ];++ news.setItems('tech', initial);+ news.appendItems('tech', more);++ const tech = get(techNews);+ expect(tech.items.length).toBe(2);+ });++ it('should get all items across categories', async () => {+ const { news } = await import('./news');++ news.setItems('politics', [+ {+ id: '1',+ title: 'Politics',+ source: 'A',+ link: 'a',+ timestamp: Date.now(),+ category: 'politics' as const+ }+ ]);+ news.setItems('tech', [+ {+ id: '2',+ title: 'Tech',+ source: 'B',+ link: 'b',+ timestamp: Date.now(),+ category: 'tech' as const+ }+ ]);++ const all = news.getAllItems();+ expect(all.length).toBe(2);+ });++ it('should derive alerts correctly', async () => {+ const { news, alerts } = await import('./news');++ news.setItems('politics', [+ {+ id: '1',+ title: 'War breaks out',+ source: 'BBC',+ link: 'a',+ timestamp: Date.now(),+ category: 'politics' as const+ },+ {+ id: '2',+ title: 'Normal news',+ source: 'BBC',+ link: 'b',+ timestamp: Date.now(),+ category: 'politics' as const+ }+ ]);++ const alertItems = get(alerts);+ expect(alertItems.length).toBe(1);+ expect(alertItems[0].title).toBe('War breaks out');+ });++ it('should clear all categories', async () => {+ const { news } = await import('./news');++ news.setItems('politics', [+ {+ id: '1',+ title: 'Test',+ source: 'A',+ link: 'a',+ timestamp: Date.now(),+ category: 'politics' as const+ }+ ]);++ news.clearAll();++ const state = get(news);+ expect(state.categories.politics.items).toEqual([]);+ });+});diff --git a/src/lib/stores/news.ts b/src/lib/stores/news.tsnew file mode 100644index 0000000..2eace53--- /dev/null+++ b/src/lib/stores/news.ts@@ -0,0 +1,241 @@+/**+ * News store - manages news data across all categories+ */++import { writable, derived, get } from 'svelte/store';+import type { NewsItem, NewsCategory } from '$lib/types';+import { containsAlertKeyword, detectRegion, detectTopics } from '$lib/config';++export interface CategoryState {+ items: NewsItem[];+ loading: boolean;+ error: string | null;+ lastUpdated: number | null;+}++export interface NewsState {+ categories: Record<NewsCategory, CategoryState>;+ initialized: boolean;+}++// All news categories+const NEWS_CATEGORIES: NewsCategory[] = ['politics', 'tech', 'finance', 'gov', 'ai', 'intel'];++// Create initial state for a category+function createCategoryState(): CategoryState {+ return {+ items: [],+ loading: false,+ error: null,+ lastUpdated: null+ };+}++// Create initial state+function createInitialState(): NewsState {+ const categories = {} as Record<NewsCategory, CategoryState>;+ for (const category of NEWS_CATEGORIES) {+ categories[category] = createCategoryState();+ }+ return { categories, initialized: false };+}++// Enrich news item with analysis+function enrichNewsItem(item: NewsItem): NewsItem {+ const text = `${item.title} ${item.description || ''}`;+ const alertResult = containsAlertKeyword(text);++ return {+ ...item,+ isAlert: alertResult.isAlert,+ alertKeyword: alertResult.keyword,+ region: item.region ?? detectRegion(text) ?? undefined,+ topics: item.topics ?? detectTopics(text)+ };+}++// Create the store+function createNewsStore() {+ const { subscribe, set, update } = writable<NewsState>(createInitialState());++ return {+ subscribe,++ /**+ * Initialize store+ */+ init() {+ update((state) => ({ ...state, initialized: true }));+ },++ /**+ * Set loading state for a category+ */+ setLoading(category: NewsCategory, loading: boolean) {+ update((state) => ({+ ...state,+ categories: {+ ...state.categories,+ [category]: {+ ...state.categories[category],+ loading,+ error: loading ? null : state.categories[category].error+ }+ }+ }));+ },++ /**+ * Set error state for a category+ */+ setError(category: NewsCategory, error: string | null) {+ update((state) => ({+ ...state,+ categories: {+ ...state.categories,+ [category]: {+ ...state.categories[category],+ loading: false,+ error+ }+ }+ }));+ },++ /**+ * Set items for a category+ */+ setItems(category: NewsCategory, items: NewsItem[]) {+ const enrichedItems = items.map(enrichNewsItem);++ update((state) => ({+ ...state,+ categories: {+ ...state.categories,+ [category]: {+ items: enrichedItems,+ loading: false,+ error: null,+ lastUpdated: Date.now()+ }+ }+ }));+ },++ /**+ * Append items to a category (for pagination)+ */+ appendItems(category: NewsCategory, items: NewsItem[]) {+ const enrichedItems = items.map(enrichNewsItem);++ update((state) => {+ const existing = state.categories[category].items;+ const existingIds = new Set(existing.map((i) => i.id));+ const newItems = enrichedItems.filter((i) => !existingIds.has(i.id));++ return {+ ...state,+ categories: {+ ...state.categories,+ [category]: {+ ...state.categories[category],+ items: [...existing, ...newItems],+ loading: false,+ error: null,+ lastUpdated: Date.now()+ }+ }+ };+ });+ },++ /**+ * Get items for a category+ */+ getItems(category: NewsCategory): NewsItem[] {+ return get({ subscribe }).categories[category].items;+ },++ /**+ * Get all items across all categories+ */+ getAllItems(): NewsItem[] {+ const state = get({ subscribe });+ const allItems: NewsItem[] = [];+ for (const category of NEWS_CATEGORIES) {+ allItems.push(...state.categories[category].items);+ }+ return allItems;+ },++ /**+ * Get alert items (items with alert keywords)+ */+ getAlertItems(): NewsItem[] {+ const state = get({ subscribe });+ const alerts: NewsItem[] = [];+ for (const category of NEWS_CATEGORIES) {+ alerts.push(...state.categories[category].items.filter((i) => i.isAlert));+ }+ return alerts.sort((a, b) => b.timestamp - a.timestamp);+ },++ /**+ * Clear a category+ */+ clearCategory(category: NewsCategory) {+ update((state) => ({+ ...state,+ categories: {+ ...state.categories,+ [category]: createCategoryState()+ }+ }));+ },++ /**+ * Clear all categories+ */+ clearAll() {+ set(createInitialState());+ },++ /**+ * Check if any category is loading+ */+ isAnyLoading(): boolean {+ const state = get({ subscribe });+ return NEWS_CATEGORIES.some((cat) => state.categories[cat].loading);+ }+ };+}++// Export singleton store+export const news = createNewsStore();++// Derived stores for each category+export const politicsNews = derived(news, ($news) => $news.categories.politics);+export const techNews = derived(news, ($news) => $news.categories.tech);+export const financeNews = derived(news, ($news) => $news.categories.finance);+export const govNews = derived(news, ($news) => $news.categories.gov);+export const aiNews = derived(news, ($news) => $news.categories.ai);+export const intelNews = derived(news, ($news) => $news.categories.intel);++// Derived store for alerts+export const alerts = derived(news, ($news) => {+ const allAlerts: NewsItem[] = [];+ for (const category of NEWS_CATEGORIES) {+ allAlerts.push(...$news.categories[category].items.filter((i) => i.isAlert));+ }+ return allAlerts.sort((a, b) => b.timestamp - a.timestamp);+});++// Derived store for loading state+export const isLoading = derived(news, ($news) =>+ NEWS_CATEGORIES.some((cat) => $news.categories[cat].loading)+);++// Derived store for any errors+export const hasErrors = derived(news, ($news) =>+ NEWS_CATEGORIES.some((cat) => $news.categories[cat].error !== null)+);diff --git a/src/lib/stores/refresh.test.ts b/src/lib/stores/refresh.test.tsnew file mode 100644index 0000000..2b9fe13--- /dev/null+++ b/src/lib/stores/refresh.test.ts@@ -0,0 +1,183 @@+/**+ * Tests for refresh store+ */++import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';+import { get } from 'svelte/store';++// Mock $app/environment+vi.mock('$app/environment', () => ({+ browser: true+}));++// Mock localStorage+const localStorageMock = (() => {+ let store: Record<string, string> = {};+ return {+ getItem: vi.fn((key: string) => store[key] || null),+ setItem: vi.fn((key: string, value: string) => {+ store[key] = value;+ }),+ removeItem: vi.fn((key: string) => {+ delete store[key];+ }),+ clear: vi.fn(() => {+ store = {};+ })+ };+})();++Object.defineProperty(globalThis, 'localStorage', {+ value: localStorageMock+});++describe('Refresh Store', () => {+ beforeEach(async () => {+ localStorageMock.clear();+ vi.clearAllMocks();+ vi.resetModules();+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('should start with default state', async () => {+ const { isRefreshing, lastRefresh } = await import('./refresh');++ expect(get(isRefreshing)).toBe(false);+ expect(get(lastRefresh)).toBeNull();+ });++ it('should start and end refresh cycle', async () => {+ const { refresh, isRefreshing, currentStage, lastRefresh } = await import('./refresh');++ refresh.startRefresh();+ expect(get(isRefreshing)).toBe(true);+ expect(get(currentStage)).toBe('critical');++ refresh.endRefresh();+ expect(get(isRefreshing)).toBe(false);+ expect(get(currentStage)).toBeNull();+ expect(get(lastRefresh)).not.toBeNull();+ });++ it('should progress through stages', async () => {+ const { refresh, currentStage } = await import('./refresh');++ refresh.startRefresh();+ expect(get(currentStage)).toBe('critical');++ refresh.nextStage();+ expect(get(currentStage)).toBe('secondary');++ refresh.nextStage();+ expect(get(currentStage)).toBe('tertiary');++ refresh.nextStage();+ expect(get(currentStage)).toBeNull();+ });++ it('should track category loading states', async () => {+ const { refresh } = await import('./refresh');++ refresh.setCategoryLoading('news', true);++ const state = get(refresh);+ expect(state.categoryStates['news'].loading).toBe(true);++ refresh.setCategoryUpdated('news');+ const updated = get(refresh);+ expect(updated.categoryStates['news'].loading).toBe(false);+ expect(updated.categoryStates['news'].lastUpdated).not.toBeNull();+ });++ it('should track category errors', async () => {+ const { refresh, categoriesWithErrors } = await import('./refresh');++ refresh.setCategoryError('markets', 'API timeout');++ const errors = get(categoriesWithErrors);+ expect(errors.length).toBe(1);+ expect(errors[0].category).toBe('markets');+ expect(errors[0].error).toBe('API timeout');+ });++ it('should toggle auto-refresh', async () => {+ const { refresh, autoRefreshEnabled } = await import('./refresh');++ expect(get(autoRefreshEnabled)).toBe(true);++ refresh.toggleAutoRefresh();+ expect(get(autoRefreshEnabled)).toBe(false);++ refresh.toggleAutoRefresh();+ expect(get(autoRefreshEnabled)).toBe(true);+ });++ it('should persist auto-refresh settings', async () => {+ const { refresh } = await import('./refresh');++ refresh.setAutoRefreshInterval(120000);++ expect(localStorageMock.setItem).toHaveBeenCalledWith('refreshSettings', expect.any(String));++ const savedData = JSON.parse(+ localStorageMock.setItem.mock.calls[localStorageMock.setItem.mock.calls.length - 1][1]+ );+ expect(savedData.autoRefreshInterval).toBe(120000);+ });++ it('should record refresh history', async () => {+ const { refresh } = await import('./refresh');++ refresh.startRefresh();+ vi.advanceTimersByTime(1000);+ refresh.endRefresh();++ const state = get(refresh);+ expect(state.refreshHistory.length).toBe(1);+ expect(state.refreshHistory[0].success).toBe(true);+ expect(state.refreshHistory[0].duration).toBeGreaterThanOrEqual(1000);+ });++ it('should record errors in refresh history', async () => {+ const { refresh } = await import('./refresh');++ refresh.startRefresh();+ refresh.endRefresh(['API error', 'Timeout']);++ const state = get(refresh);+ expect(state.refreshHistory[0].success).toBe(false);+ expect(state.refreshHistory[0].errors).toEqual(['API error', 'Timeout']);+ });++ it('should check if category needs refresh', async () => {+ const { refresh } = await import('./refresh');++ // Never updated - needs refresh+ expect(refresh.categoryNeedsRefresh('news', 60000)).toBe(true);++ // Just updated - doesn't need refresh+ refresh.setCategoryUpdated('news');+ expect(refresh.categoryNeedsRefresh('news', 60000)).toBe(false);++ // After time passes - needs refresh+ vi.advanceTimersByTime(70000);+ expect(refresh.categoryNeedsRefresh('news', 60000)).toBe(true);+ });++ it('should limit refresh history to 10 entries', async () => {+ const { refresh } = await import('./refresh');++ // Create 15 refresh cycles+ for (let i = 0; i < 15; i++) {+ refresh.startRefresh();+ refresh.endRefresh();+ }++ const state = get(refresh);+ expect(state.refreshHistory.length).toBe(10);+ });+});diff --git a/src/lib/stores/refresh.ts b/src/lib/stores/refresh.tsnew file mode 100644index 0000000..5a765b5--- /dev/null+++ b/src/lib/stores/refresh.ts@@ -0,0 +1,379 @@+/**+ * Refresh store - loading states, timestamps, and refresh orchestration+ */++import { writable, derived, get } from 'svelte/store';+import { browser } from '$app/environment';++// Refresh stages (matches existing 3-stage approach)+export type RefreshStage = 'critical' | 'secondary' | 'tertiary';++export interface StageConfig {+ name: RefreshStage;+ categories: string[];+ delayMs: number;+}++// Staged refresh configuration+export const REFRESH_STAGES: StageConfig[] = [+ {+ name: 'critical',+ categories: ['news', 'markets', 'alerts'],+ delayMs: 0+ },+ {+ name: 'secondary',+ categories: ['crypto', 'commodities', 'intel'],+ delayMs: 2000+ },+ {+ name: 'tertiary',+ categories: ['contracts', 'whales', 'layoffs', 'polymarket'],+ delayMs: 4000+ }+];++export interface RefreshState {+ // Global refresh state+ isRefreshing: boolean;+ currentStage: RefreshStage | null;+ lastRefresh: number | null;++ // Per-category states+ categoryStates: Record<+ string,+ {+ loading: boolean;+ lastUpdated: number | null;+ error: string | null;+ }+ >;++ // Auto-refresh settings+ autoRefreshEnabled: boolean;+ autoRefreshInterval: number; // in milliseconds++ // Refresh history (for debugging/analytics)+ refreshHistory: Array<{+ timestamp: number;+ duration: number;+ success: boolean;+ errors: string[];+ }>;++ initialized: boolean;+}++const DEFAULT_AUTO_REFRESH_INTERVAL = 60 * 60 * 1000; // 1 hour+const STORAGE_KEY = 'refreshSettings';++// Load settings from localStorage+function loadSettings(): { autoRefreshEnabled: boolean; autoRefreshInterval: number } {+ if (!browser) {+ return {+ autoRefreshEnabled: true,+ autoRefreshInterval: DEFAULT_AUTO_REFRESH_INTERVAL+ };+ }++ try {+ const data = localStorage.getItem(STORAGE_KEY);+ if (data) {+ const parsed = JSON.parse(data);+ return {+ autoRefreshEnabled: parsed.autoRefreshEnabled ?? true,+ autoRefreshInterval: parsed.autoRefreshInterval ?? DEFAULT_AUTO_REFRESH_INTERVAL+ };+ }+ } catch (e) {+ console.warn('Failed to load refresh settings:', e);+ }++ return {+ autoRefreshEnabled: true,+ autoRefreshInterval: DEFAULT_AUTO_REFRESH_INTERVAL+ };+}++// Save settings to localStorage+function saveSettings(enabled: boolean, interval: number): void {+ if (!browser) return;++ try {+ localStorage.setItem(+ STORAGE_KEY,+ JSON.stringify({+ autoRefreshEnabled: enabled,+ autoRefreshInterval: interval+ })+ );+ } catch (e) {+ console.warn('Failed to save refresh settings:', e);+ }+}++// Create initial state+function createInitialState(): RefreshState {+ const settings = loadSettings();++ return {+ isRefreshing: false,+ currentStage: null,+ lastRefresh: null,+ categoryStates: {},+ autoRefreshEnabled: settings.autoRefreshEnabled,+ autoRefreshInterval: settings.autoRefreshInterval,+ refreshHistory: [],+ initialized: false+ };+}++// Create the store+function createRefreshStore() {+ const { subscribe, set, update } = writable<RefreshState>(createInitialState());++ let autoRefreshTimer: ReturnType<typeof setInterval> | null = null;+ let refreshStartTime: number | null = null;++ // Setup auto-refresh timer+ function setupAutoRefresh(callback: () => void) {+ const state = get({ subscribe });++ if (autoRefreshTimer) {+ clearInterval(autoRefreshTimer);+ autoRefreshTimer = null;+ }++ if (state.autoRefreshEnabled && browser) {+ autoRefreshTimer = setInterval(callback, state.autoRefreshInterval);+ }+ }++ return {+ subscribe,++ /**+ * Initialize store+ */+ init() {+ update((state) => ({ ...state, initialized: true }));+ },++ /**+ * Start a refresh cycle+ */+ startRefresh() {+ refreshStartTime = Date.now();+ update((state) => ({+ ...state,+ isRefreshing: true,+ currentStage: 'critical'+ }));+ },++ /**+ * Move to the next stage+ */+ nextStage() {+ update((state) => {+ const currentIndex = REFRESH_STAGES.findIndex((s) => s.name === state.currentStage);+ const nextStage = REFRESH_STAGES[currentIndex + 1];++ return {+ ...state,+ currentStage: nextStage?.name ?? null+ };+ });+ },++ /**+ * End refresh cycle+ */+ endRefresh(errors: string[] = []) {+ const duration = refreshStartTime ? Date.now() - refreshStartTime : 0;+ refreshStartTime = null;++ update((state) => {+ const historyEntry = {+ timestamp: Date.now(),+ duration,+ success: errors.length === 0,+ errors+ };++ // Keep last 10 refresh entries+ const newHistory = [historyEntry, ...state.refreshHistory].slice(0, 10);++ return {+ ...state,+ isRefreshing: false,+ currentStage: null,+ lastRefresh: Date.now(),+ refreshHistory: newHistory+ };+ });+ },++ /**+ * Set loading state for a category+ */+ setCategoryLoading(category: string, loading: boolean) {+ update((state) => ({+ ...state,+ categoryStates: {+ ...state.categoryStates,+ [category]: {+ ...state.categoryStates[category],+ loading,+ error: loading ? null : state.categoryStates[category]?.error ?? null,+ lastUpdated: state.categoryStates[category]?.lastUpdated ?? null+ }+ }+ }));+ },++ /**+ * Set category updated+ */+ setCategoryUpdated(category: string) {+ update((state) => ({+ ...state,+ categoryStates: {+ ...state.categoryStates,+ [category]: {+ loading: false,+ error: null,+ lastUpdated: Date.now()+ }+ }+ }));+ },++ /**+ * Set category error+ */+ setCategoryError(category: string, error: string) {+ update((state) => ({+ ...state,+ categoryStates: {+ ...state.categoryStates,+ [category]: {+ ...state.categoryStates[category],+ loading: false,+ error,+ lastUpdated: state.categoryStates[category]?.lastUpdated ?? null+ }+ }+ }));+ },++ /**+ * Toggle auto-refresh+ */+ toggleAutoRefresh(callback?: () => void) {+ update((state) => {+ const newEnabled = !state.autoRefreshEnabled;+ saveSettings(newEnabled, state.autoRefreshInterval);++ if (callback) {+ setupAutoRefresh(callback);+ }++ return {+ ...state,+ autoRefreshEnabled: newEnabled+ };+ });+ },++ /**+ * Set auto-refresh interval+ */+ setAutoRefreshInterval(intervalMs: number, callback?: () => void) {+ update((state) => {+ saveSettings(state.autoRefreshEnabled, intervalMs);++ if (callback) {+ setupAutoRefresh(callback);+ }++ return {+ ...state,+ autoRefreshInterval: intervalMs+ };+ });+ },++ /**+ * Setup auto-refresh with callback+ */+ setupAutoRefresh(callback: () => void) {+ setupAutoRefresh(callback);+ },++ /**+ * Stop auto-refresh+ */+ stopAutoRefresh() {+ if (autoRefreshTimer) {+ clearInterval(autoRefreshTimer);+ autoRefreshTimer = null;+ }+ },++ /**+ * Get time since last refresh+ */+ getTimeSinceRefresh(): number | null {+ const state = get({ subscribe });+ if (!state.lastRefresh) return null;+ return Date.now() - state.lastRefresh;+ },++ /**+ * Check if a category needs refresh+ */+ categoryNeedsRefresh(category: string, maxAge: number): boolean {+ const state = get({ subscribe });+ const categoryState = state.categoryStates[category];+ if (!categoryState?.lastUpdated) return true;+ return Date.now() - categoryState.lastUpdated > maxAge;+ },++ /**+ * Reset store+ */+ reset() {+ if (autoRefreshTimer) {+ clearInterval(autoRefreshTimer);+ autoRefreshTimer = null;+ }+ set(createInitialState());+ }+ };+}++// Export singleton store+export const refresh = createRefreshStore();++// Derived stores+export const isRefreshing = derived(refresh, ($refresh) => $refresh.isRefreshing);++export const currentStage = derived(refresh, ($refresh) => $refresh.currentStage);++export const lastRefresh = derived(refresh, ($refresh) => $refresh.lastRefresh);++export const autoRefreshEnabled = derived(refresh, ($refresh) => $refresh.autoRefreshEnabled);++// Time since last refresh (updates every second when subscribed)+export const timeSinceRefresh = derived(refresh, ($refresh) => {+ if (!$refresh.lastRefresh) return null;+ return Date.now() - $refresh.lastRefresh;+});++// Categories with errors+export const categoriesWithErrors = derived(refresh, ($refresh) => {+ return Object.entries($refresh.categoryStates)+ .filter(([, state]) => state.error !== null)+ .map(([category, state]) => ({ category, error: state.error }));+});diff --git a/src/lib/stores/settings.test.ts b/src/lib/stores/settings.test.tsnew file mode 100644index 0000000..9b52683--- /dev/null+++ b/src/lib/stores/settings.test.ts@@ -0,0 +1,141 @@+/**+ * Tests for settings store+ */++import { describe, it, expect, beforeEach, vi } from 'vitest';+import { get } from 'svelte/store';++// Mock $app/environment before importing the store+vi.mock('$app/environment', () => ({+ browser: true+}));++// Mock localStorage+const localStorageMock = (() => {+ let store: Record<string, string> = {};+ return {+ getItem: vi.fn((key: string) => store[key] || null),+ setItem: vi.fn((key: string, value: string) => {+ store[key] = value;+ }),+ removeItem: vi.fn((key: string) => {+ delete store[key];+ }),+ clear: vi.fn(() => {+ store = {};+ })+ };+})();++Object.defineProperty(globalThis, 'localStorage', {+ value: localStorageMock+});++describe('Settings Store', () => {+ beforeEach(async () => {+ localStorageMock.clear();+ vi.clearAllMocks();++ // Re-import the store to reset state+ vi.resetModules();+ });++ it('should have default state with all panels enabled', async () => {+ const { settings } = await import('./settings');++ const state = get(settings);+ expect(state.initialized).toBe(false);++ // Check that common panels are enabled by default+ expect(state.enabled['map']).toBe(true);+ expect(state.enabled['politics']).toBe(true);+ expect(state.enabled['tech']).toBe(true);+ });++ it('should toggle panel visibility', async () => {+ const { settings } = await import('./settings');++ // Initially enabled+ expect(get(settings).enabled['tech']).toBe(true);++ // Toggle off+ settings.togglePanel('tech');+ expect(get(settings).enabled['tech']).toBe(false);++ // Toggle on+ settings.togglePanel('tech');+ expect(get(settings).enabled['tech']).toBe(true);+ });++ it('should persist panel settings to localStorage', async () => {+ const { settings } = await import('./settings');++ settings.togglePanel('finance');++ expect(localStorageMock.setItem).toHaveBeenCalledWith(+ 'situationMonitorPanels',+ expect.any(String)+ );++ const savedData = JSON.parse(+ localStorageMock.setItem.mock.calls[localStorageMock.setItem.mock.calls.length - 1][1]+ );+ expect(savedData['finance']).toBe(false);+ });++ it('should update panel order', async () => {+ const { settings } = await import('./settings');++ const newOrder = ['tech', 'finance', 'politics', 'map'] as const;+ settings.updateOrder([...newOrder]);++ const state = get(settings);+ expect(state.order.slice(0, 4)).toEqual([...newOrder]);+ });++ it('should update panel size', async () => {+ const { settings } = await import('./settings');++ settings.updateSize('map', { width: 800, height: 600 });++ const state = get(settings);+ expect(state.sizes['map']).toEqual({ width: 800, height: 600 });+ });++ it('should initialize store', async () => {+ const { settings } = await import('./settings');++ expect(get(settings).initialized).toBe(false);+ settings.init();+ expect(get(settings).initialized).toBe(true);+ });++ it('should reset to defaults', async () => {+ const { settings } = await import('./settings');++ // Make some changes+ settings.togglePanel('tech');+ settings.updateSize('map', { width: 1000 });++ // Reset+ settings.reset();++ const state = get(settings);+ expect(state.enabled['tech']).toBe(true);+ expect(state.sizes['map']).toBeUndefined();+ });++ it('should derive enabled panels correctly', async () => {+ const { settings, enabledPanels } = await import('./settings');++ // Disable some panels+ settings.togglePanel('whales');+ settings.togglePanel('polymarket');++ const enabled = get(enabledPanels);+ expect(enabled).not.toContain('whales');+ expect(enabled).not.toContain('polymarket');+ expect(enabled).toContain('map');+ expect(enabled).toContain('politics');+ });+});diff --git a/src/lib/stores/settings.ts b/src/lib/stores/settings.tsnew file mode 100644index 0000000..194b8b6--- /dev/null+++ b/src/lib/stores/settings.ts@@ -0,0 +1,218 @@+/**+ * Settings store - panel visibility, order, and sizes+ */++import { writable, derived, get } from 'svelte/store';+import { browser } from '$app/environment';+import { PANELS, NON_DRAGGABLE_PANELS, type PanelId } from '$lib/config';++// Storage keys+const STORAGE_KEYS = {+ panels: 'situationMonitorPanels',+ order: 'panelOrder',+ sizes: 'panelSizes'+} as const;++// Types+export interface PanelSettings {+ enabled: Record<PanelId, boolean>;+ order: PanelId[];+ sizes: Record<PanelId, { width?: number; height?: number }>;+}++export interface SettingsState extends PanelSettings {+ initialized: boolean;+}++// Default settings+function getDefaultSettings(): PanelSettings {+ const allPanelIds = Object.keys(PANELS) as PanelId[];++ return {+ enabled: Object.fromEntries(allPanelIds.map((id) => [id, true])) as Record<PanelId, boolean>,+ order: allPanelIds,+ sizes: {} as Record<PanelId, { width?: number; height?: number }>+ };+}++// Load from localStorage+function loadFromStorage(): Partial<PanelSettings> {+ if (!browser) return {};++ try {+ const panels = localStorage.getItem(STORAGE_KEYS.panels);+ const order = localStorage.getItem(STORAGE_KEYS.order);+ const sizes = localStorage.getItem(STORAGE_KEYS.sizes);++ return {+ enabled: panels ? JSON.parse(panels) : undefined,+ order: order ? JSON.parse(order) : undefined,+ sizes: sizes ? JSON.parse(sizes) : undefined+ };+ } catch (e) {+ console.warn('Failed to load settings from localStorage:', e);+ return {};+ }+}++// Save to localStorage+function saveToStorage(key: keyof typeof STORAGE_KEYS, value: unknown): void {+ if (!browser) return;++ try {+ localStorage.setItem(STORAGE_KEYS[key], JSON.stringify(value));+ } catch (e) {+ console.warn(`Failed to save ${key} to localStorage:`, e);+ }+}++// Create the store+function createSettingsStore() {+ const defaults = getDefaultSettings();+ const saved = loadFromStorage();++ const initialState: SettingsState = {+ enabled: { ...defaults.enabled, ...saved.enabled },+ order: saved.order ?? defaults.order,+ sizes: { ...defaults.sizes, ...saved.sizes },+ initialized: false+ };++ const { subscribe, set, update } = writable<SettingsState>(initialState);++ return {+ subscribe,++ /**+ * Initialize store (call after hydration)+ */+ init() {+ update((state) => ({ ...state, initialized: true }));+ },++ /**+ * Check if a panel is enabled+ */+ isPanelEnabled(panelId: PanelId): boolean {+ const state = get({ subscribe });+ return state.enabled[panelId] ?? true;+ },++ /**+ * Toggle panel visibility+ */+ togglePanel(panelId: PanelId) {+ update((state) => {+ const newEnabled = {+ ...state.enabled,+ [panelId]: !state.enabled[panelId]+ };+ saveToStorage('panels', newEnabled);+ return { ...state, enabled: newEnabled };+ });+ },++ /**+ * Enable a specific panel+ */+ enablePanel(panelId: PanelId) {+ update((state) => {+ const newEnabled = { ...state.enabled, [panelId]: true };+ saveToStorage('panels', newEnabled);+ return { ...state, enabled: newEnabled };+ });+ },++ /**+ * Disable a specific panel+ */+ disablePanel(panelId: PanelId) {+ update((state) => {+ const newEnabled = { ...state.enabled, [panelId]: false };+ saveToStorage('panels', newEnabled);+ return { ...state, enabled: newEnabled };+ });+ },++ /**+ * Update panel order (for drag-drop)+ */+ updateOrder(newOrder: PanelId[]) {+ update((state) => {+ saveToStorage('order', newOrder);+ return { ...state, order: newOrder };+ });+ },++ /**+ * Move a panel to a new position+ */+ movePanel(panelId: PanelId, toIndex: number) {+ // Don't allow moving non-draggable panels+ if (NON_DRAGGABLE_PANELS.includes(panelId)) return;++ update((state) => {+ const currentIndex = state.order.indexOf(panelId);+ if (currentIndex === -1) return state;++ const newOrder = [...state.order];+ newOrder.splice(currentIndex, 1);+ newOrder.splice(toIndex, 0, panelId);++ saveToStorage('order', newOrder);+ return { ...state, order: newOrder };+ });+ },++ /**+ * Update panel size+ */+ updateSize(panelId: PanelId, size: { width?: number; height?: number }) {+ update((state) => {+ const newSizes = {+ ...state.sizes,+ [panelId]: { ...state.sizes[panelId], ...size }+ };+ saveToStorage('sizes', newSizes);+ return { ...state, sizes: newSizes };+ });+ },++ /**+ * Reset all settings to defaults+ */+ reset() {+ const defaults = getDefaultSettings();+ if (browser) {+ localStorage.removeItem(STORAGE_KEYS.panels);+ localStorage.removeItem(STORAGE_KEYS.order);+ localStorage.removeItem(STORAGE_KEYS.sizes);+ }+ set({ ...defaults, initialized: true });+ },++ /**+ * Get panel size+ */+ getPanelSize(panelId: PanelId): { width?: number; height?: number } | undefined {+ const state = get({ subscribe });+ return state.sizes[panelId];+ }+ };+}++// Export singleton store+export const settings = createSettingsStore();++// Derived stores for convenience+export const enabledPanels = derived(settings, ($settings) =>+ $settings.order.filter((id) => $settings.enabled[id])+);++export const disabledPanels = derived(settings, ($settings) =>+ $settings.order.filter((id) => !$settings.enabled[id])+);++export const draggablePanels = derived(enabledPanels, ($enabled) =>+ $enabled.filter((id) => !NON_DRAGGABLE_PANELS.includes(id))+);diff --git a/src/lib/types/index.ts b/src/lib/types/index.tsindex 84e9493..b416062 100644--- a/src/lib/types/index.ts+++ b/src/lib/types/index.ts@@ -1,25 +1,29 @@// Core data types for Situation Monitor+/**+ * News feed category+ */+export type NewsCategory = 'politics' | 'tech' | 'finance' | 'gov' | 'ai' | 'intel';+/*** A news item from any source (RSS, GDELT, etc.)*/export interface NewsItem {+ id: string;title: string;link: string;- pubDate: string;+ pubDate?: string;+ timestamp: number;description?: string;content?: string;source: string;- category?: string;+ category: NewsCategory;isAlert?: boolean;alertKeyword?: string;+ region?: string;+ topics?: string[];}-/**- * News feed category- */-export type NewsCategory = 'politics' | 'tech' | 'finance' | 'gov' | 'ai' | 'intel';-/*** RSS feed configuration*/@@ -38,7 +42,32 @@ export interface MarketItem {price: number;change: number;changePercent: number;- type: 'stock' | 'crypto' | 'commodity' | 'index';+ type?: 'stock' | 'crypto' | 'commodity' | 'index';+}++/**+ * Sector performance data (ETFs like XLK, XLF, etc.)+ */+export interface SectorPerformance {+ symbol: string;+ name: string;+ price: number;+ change: number;+ changePercent: number;+}++/**+ * Cryptocurrency data from CoinGecko+ */+export interface CryptoItem {+ id: string;+ symbol: string;+ name: string;+ current_price: number;+ price_change_24h: number;+ price_change_percentage_24h: number;+ market_cap?: number;+ volume_24h?: number;}/**@@ -156,14 +185,16 @@ export interface CustomMonitor {id: string;name: string;keywords: string[];- color: string;+ enabled: boolean;+ color?: string;location?: {name: string;lat: number;lon: number;};createdAt: number;- updatedAt: number;+ updatedAt?: number;+ matchCount: number;}/**