| 1 | /** |
| 2 | * ╔══════════════════════════════════════════════════════════════════╗ |
| 3 | * ║ POLYBOLOS SDK — Client Controller ║ |
| 4 | * ║ Unified Intelligence Fusion Engine ║ |
| 5 | * ║ ║ |
| 6 | * ║ Subscribes to OSIRIS feeds + external providers (Lattice), ║ |
| 7 | * ║ normalizes all data into PolybolosEntity[], and emits a ║ |
| 8 | * ║ fused Common Operating Picture stream. ║ |
| 9 | * ╚══════════════════════════════════════════════════════════════════╝ |
| 10 | */ |
| 11 | |
| 12 | import { |
| 13 | type PolybolosEntity, |
| 14 | type PolybolosClientConfig, |
| 15 | type SDKStatus, |
| 16 | type LatticeConnectionStatus, |
| 17 | Domain, |
| 18 | EntityType, |
| 19 | ThreatLevel, |
| 20 | Classification, |
| 21 | } from './types'; |
| 22 | import { LatticeAdapter } from './LatticeAdapter'; |
| 23 | |
| 24 | // ── OSIRIS Feed → Entity Translators ─────────────────────────────── |
| 25 | |
| 26 | function translateFlights(flights: any[], subtype: string): PolybolosEntity[] { |
| 27 | if (!flights?.length) return []; |
| 28 | const colorMap: Record<string, string> = { |
| 29 | commercial: '#00E5FF', private: '#00E676', jets: '#FF69B4', military: '#FF3D3D', |
| 30 | }; |
| 31 | const threatMap: Record<string, ThreatLevel> = { |
| 32 | commercial: ThreatLevel.NONE, private: ThreatLevel.NONE, |
| 33 | jets: ThreatLevel.LOW, military: ThreatLevel.ELEVATED, |
| 34 | }; |
| 35 | return flights.map((f: any) => ({ |
| 36 | id: `osiris-air-${f.icao24 || f.callsign || Math.random().toString(36).slice(2)}`, |
| 37 | name: f.callsign?.trim() || 'UNKNOWN', |
| 38 | domain: Domain.AIR, |
| 39 | entityType: EntityType.TRACK, |
| 40 | position: { lat: f.lat, lng: f.lng, alt: f.alt, heading: f.heading, speed: f.speed_knots }, |
| 41 | threat: threatMap[subtype] || ThreatLevel.NONE, |
| 42 | classification: Classification.UNCLASSIFIED, |
| 43 | source: { provider: 'osiris', feed: `flights-${subtype}`, originalId: f.icao24, confidence: 0.9 }, |
| 44 | timestamp: new Date().toISOString(), |
| 45 | properties: { model: f.model, registration: f.registration, icao24: f.icao24, subtype }, |
| 46 | display: { color: colorMap[subtype] || '#00E5FF', icon: `plane-${subtype === 'military' ? 'red' : 'cyan'}`, layerType: 'symbol' as const }, |
| 47 | })); |
| 48 | } |
| 49 | |
| 50 | function translateMaritime(ships: any[]): PolybolosEntity[] { |
| 51 | if (!ships?.length) return []; |
| 52 | return ships.map((s: any) => ({ |
| 53 | id: `osiris-sea-${s.mmsi || s.id || Math.random().toString(36).slice(2)}`, |
| 54 | name: s.name || `MMSI-${s.mmsi}`, |
| 55 | domain: Domain.SEA, |
| 56 | entityType: EntityType.TRACK, |
| 57 | position: { lat: s.lat, lng: s.lng, heading: s.heading, speed: s.speed }, |
| 58 | threat: s.type === 'military' ? ThreatLevel.ELEVATED : ThreatLevel.NONE, |
| 59 | classification: Classification.UNCLASSIFIED, |
| 60 | source: { provider: 'osiris', feed: 'maritime-ais', originalId: s.mmsi?.toString(), confidence: 0.85 }, |
| 61 | timestamp: new Date().toISOString(), |
| 62 | properties: { type: s.type, destination: s.destination, flag: s.flag, mmsi: s.mmsi }, |
| 63 | display: { |
| 64 | color: s.type === 'military' ? '#FF1744' : s.type === 'tanker' ? '#FF9500' : '#00BCD4', |
| 65 | icon: 'dot-orange', layerType: 'circle' as const, |
| 66 | }, |
| 67 | })); |
| 68 | } |
| 69 | |
| 70 | function translateEarthquakes(events: any[]): PolybolosEntity[] { |
| 71 | if (!events?.length) return []; |
| 72 | return events.map((eq: any) => ({ |
| 73 | id: `osiris-event-eq-${eq.id || Math.random().toString(36).slice(2)}`, |
| 74 | name: `M${eq.magnitude} ${eq.place || 'Earthquake'}`, |
| 75 | domain: Domain.LAND, |
| 76 | entityType: EntityType.EVENT, |
| 77 | position: { lat: eq.lat, lng: eq.lng }, |
| 78 | threat: eq.magnitude >= 6 ? ThreatLevel.CRITICAL : eq.magnitude >= 5 ? ThreatLevel.HIGH : eq.magnitude >= 4 ? ThreatLevel.ELEVATED : ThreatLevel.LOW, |
| 79 | classification: Classification.UNCLASSIFIED, |
| 80 | source: { provider: 'osiris', feed: 'usgs-earthquakes', originalId: eq.id, confidence: 0.99 }, |
| 81 | timestamp: new Date().toISOString(), |
| 82 | properties: { magnitude: eq.magnitude, depth: eq.depth, place: eq.place }, |
| 83 | display: { color: eq.magnitude >= 6 ? '#FF1744' : '#FF9500', icon: 'dot-red', layerType: 'circle' as const, glow: eq.magnitude >= 5 }, |
| 84 | })); |
| 85 | } |
| 86 | |
| 87 | function translateSatellites(sats: any[]): PolybolosEntity[] { |
| 88 | if (!sats?.length) return []; |
| 89 | return sats.map((s: any) => ({ |
| 90 | id: `osiris-space-${s.noradId || Math.random().toString(36).slice(2)}`, |
| 91 | name: s.name || 'UNKNOWN SAT', |
| 92 | domain: Domain.SPACE, |
| 93 | entityType: EntityType.TRACK, |
| 94 | position: { lat: s.lat, lng: s.lng, alt: s.alt ? s.alt * 1000 : undefined }, |
| 95 | threat: ThreatLevel.NONE, |
| 96 | classification: Classification.UNCLASSIFIED, |
| 97 | source: { provider: 'osiris', feed: 'satnogs', originalId: s.noradId?.toString(), confidence: 0.95 }, |
| 98 | timestamp: new Date().toISOString(), |
| 99 | properties: { mission: s.mission, noradId: s.noradId, color: s.color }, |
| 100 | display: { color: s.color || '#D4AF37', icon: 'dot-gold', layerType: 'circle' as const }, |
| 101 | })); |
| 102 | } |
| 103 | |
| 104 | function translateFires(fires: any[]): PolybolosEntity[] { |
| 105 | if (!fires?.length) return []; |
| 106 | return fires.map((f: any, i: number) => ({ |
| 107 | id: `osiris-event-fire-${i}`, |
| 108 | name: 'Active Fire', |
| 109 | domain: Domain.LAND, |
| 110 | entityType: EntityType.EVENT, |
| 111 | position: { lat: f.lat, lng: f.lng }, |
| 112 | threat: ThreatLevel.ELEVATED, |
| 113 | classification: Classification.UNCLASSIFIED, |
| 114 | source: { provider: 'osiris', feed: 'nasa-firms', confidence: 0.9 }, |
| 115 | timestamp: new Date().toISOString(), |
| 116 | properties: { brightness: f.brightness }, |
| 117 | display: { color: '#FF6B00', icon: 'dot-fire', layerType: 'circle' as const }, |
| 118 | })); |
| 119 | } |
| 120 | |
| 121 | function translateCCTV(cameras: any[]): PolybolosEntity[] { |
| 122 | if (!cameras?.length) return []; |
| 123 | return cameras.map((c: any) => ({ |
| 124 | id: `osiris-sensor-cctv-${c.id || Math.random().toString(36).slice(2)}`, |
| 125 | name: c.name || 'Camera', |
| 126 | domain: Domain.LAND, |
| 127 | entityType: EntityType.SENSOR, |
| 128 | position: { lat: c.lat, lng: c.lng }, |
| 129 | threat: ThreatLevel.NONE, |
| 130 | classification: Classification.UNCLASSIFIED, |
| 131 | source: { provider: 'osiris', feed: 'cctv-network', originalId: c.id, confidence: 1.0 }, |
| 132 | timestamp: new Date().toISOString(), |
| 133 | properties: { city: c.city, country: c.country, source: c.source, feed_url: c.feed_url, stream_url: c.stream_url }, |
| 134 | display: { color: '#39FF14', icon: 'dot-cctv', layerType: 'circle' as const }, |
| 135 | })); |
| 136 | } |
| 137 | |
| 138 | function translateRadiation(stations: any[]): PolybolosEntity[] { |
| 139 | if (!stations?.length) return []; |
| 140 | return stations.map((r: any) => ({ |
| 141 | id: `osiris-sensor-rad-${r.name || Math.random().toString(36).slice(2)}`, |
| 142 | name: r.name || 'Radiation Monitor', |
| 143 | domain: Domain.LAND, |
| 144 | entityType: EntityType.SENSOR, |
| 145 | position: { lat: r.lat, lng: r.lng }, |
| 146 | threat: r.status === 'DANGER' ? ThreatLevel.CRITICAL : r.status === 'WARNING' ? ThreatLevel.HIGH : ThreatLevel.LOW, |
| 147 | classification: Classification.UNCLASSIFIED, |
| 148 | source: { provider: 'osiris', feed: 'radiation-network', confidence: 0.95 }, |
| 149 | timestamp: new Date().toISOString(), |
| 150 | properties: { reading: r.reading, status: r.status, network: r.network, city: r.city, country: r.country }, |
| 151 | display: { |
| 152 | color: r.status === 'DANGER' ? '#FF1744' : r.status === 'WARNING' ? '#FF9500' : '#AB47BC', |
| 153 | icon: 'dot-red', layerType: 'circle' as const, glow: r.status === 'DANGER', |
| 154 | }, |
| 155 | })); |
| 156 | } |
| 157 | |
| 158 | // ── Main Client ──────────────────────────────────────────────────── |
| 159 | |
| 160 | export class PolybolosClient { |
| 161 | private config: PolybolosClientConfig; |
| 162 | private latticeAdapter: LatticeAdapter | null = null; |
| 163 | private entityStore: Map<string, PolybolosEntity> = new Map(); |
| 164 | private startTime: number = Date.now(); |
| 165 | private updateInterval: ReturnType<typeof setInterval> | null = null; |
| 166 | private sseConnection: EventSource | null = null; |
| 167 | |
| 168 | constructor(config: PolybolosClientConfig) { |
| 169 | this.config = config; |
| 170 | |
| 171 | // Initialize Lattice adapter if configured |
| 172 | if (config.lattice) { |
| 173 | this.latticeAdapter = new LatticeAdapter(config.lattice); |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | /** Initialize the SDK and connect all feeds */ |
| 178 | async initialize(): Promise<void> { |
| 179 | // Connect Lattice if configured |
| 180 | if (this.latticeAdapter) { |
| 181 | await this.latticeAdapter.connect(); |
| 182 | } |
| 183 | |
| 184 | // Try SSE stream first (for real-time updates) |
| 185 | this.connectSSE(); |
| 186 | |
| 187 | // Emit initial status |
| 188 | this.config.onStatusChange?.(this.getStatus()); |
| 189 | } |
| 190 | |
| 191 | /** Connect to the OSIRIS SSE stream endpoint */ |
| 192 | private connectSSE(): void { |
| 193 | if (typeof EventSource === 'undefined') return; |
| 194 | |
| 195 | try { |
| 196 | this.sseConnection = new EventSource( |
| 197 | `${this.config.osirisBaseUrl}/api/sdk/stream` |
| 198 | ); |
| 199 | |
| 200 | this.sseConnection.onmessage = (event) => { |
| 201 | try { |
| 202 | const data = JSON.parse(event.data); |
| 203 | if (data.type === 'entity_update' && Array.isArray(data.payload)) { |
| 204 | for (const entity of data.payload) { |
| 205 | this.entityStore.set(entity.id, entity); |
| 206 | } |
| 207 | this.emitUpdate(); |
| 208 | } |
| 209 | } catch { |
| 210 | // Skip malformed events |
| 211 | } |
| 212 | }; |
| 213 | |
| 214 | this.sseConnection.onerror = () => { |
| 215 | // SSE failed, connection will auto-retry |
| 216 | }; |
| 217 | } catch { |
| 218 | // EventSource not available or connection failed |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | /** |
| 223 | * Ingest raw OSIRIS data and translate it into Polybolos entities. |
| 224 | * This is the primary method called by page.tsx to feed data into the SDK. |
| 225 | */ |
| 226 | ingestOsirisData(data: Record<string, any>): void { |
| 227 | const entities: PolybolosEntity[] = []; |
| 228 | |
| 229 | // Air domain |
| 230 | entities.push(...translateFlights(data.commercial_flights, 'commercial')); |
| 231 | entities.push(...translateFlights(data.private_flights, 'private')); |
| 232 | entities.push(...translateFlights(data.private_jets, 'jets')); |
| 233 | entities.push(...translateFlights(data.military_flights, 'military')); |
| 234 | |
| 235 | // Sea domain |
| 236 | entities.push(...translateMaritime(data.maritime_ships || [])); |
| 237 | |
| 238 | // Space domain |
| 239 | entities.push(...translateSatellites(data.satellites || [])); |
| 240 | |
| 241 | // Land domain — Events |
| 242 | entities.push(...translateEarthquakes(data.earthquakes || [])); |
| 243 | entities.push(...translateFires(data.fires || [])); |
| 244 | |
| 245 | // Land domain — Sensors |
| 246 | entities.push(...translateCCTV(data.cameras || [])); |
| 247 | entities.push(...translateRadiation(data.radiation || [])); |
| 248 | |
| 249 | // Store all |
| 250 | for (const entity of entities) { |
| 251 | this.entityStore.set(entity.id, entity); |
| 252 | } |
| 253 | |
| 254 | // Merge Lattice entities |
| 255 | if (this.latticeAdapter) { |
| 256 | for (const entity of this.latticeAdapter.getEntities()) { |
| 257 | this.entityStore.set(entity.id, entity); |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | this.emitUpdate(); |
| 262 | } |
| 263 | |
| 264 | /** Get all entities, optionally filtered by domain */ |
| 265 | getEntities(domain?: Domain): PolybolosEntity[] { |
| 266 | const all = Array.from(this.entityStore.values()); |
| 267 | if (domain) return all.filter(e => e.domain === domain); |
| 268 | return all; |
| 269 | } |
| 270 | |
| 271 | /** Get entity count by domain */ |
| 272 | getEntityCountByDomain(): Record<Domain, number> { |
| 273 | const counts = {} as Record<Domain, number>; |
| 274 | for (const d of Object.values(Domain)) counts[d] = 0; |
| 275 | for (const entity of this.entityStore.values()) { |
| 276 | counts[entity.domain] = (counts[entity.domain] || 0) + 1; |
| 277 | } |
| 278 | return counts; |
| 279 | } |
| 280 | |
| 281 | /** Get entities above a certain threat level */ |
| 282 | getThreats(minLevel: ThreatLevel = ThreatLevel.ELEVATED): PolybolosEntity[] { |
| 283 | const levels = [ThreatLevel.NONE, ThreatLevel.LOW, ThreatLevel.ELEVATED, ThreatLevel.HIGH, ThreatLevel.CRITICAL]; |
| 284 | const minIndex = levels.indexOf(minLevel); |
| 285 | return Array.from(this.entityStore.values()) |
| 286 | .filter(e => levels.indexOf(e.threat) >= minIndex); |
| 287 | } |
| 288 | |
| 289 | /** Get current SDK status */ |
| 290 | getStatus(): SDKStatus { |
| 291 | return { |
| 292 | connected: true, |
| 293 | feedCount: this.getActiveFeedCount(), |
| 294 | entityCount: this.entityStore.size, |
| 295 | latticeStatus: this.latticeAdapter?.getStatus() || 'disconnected', |
| 296 | lastUpdate: new Date().toISOString(), |
| 297 | uptime: Date.now() - this.startTime, |
| 298 | }; |
| 299 | } |
| 300 | |
| 301 | /** Convert current entity store to GeoJSON FeatureCollection for MapLibre */ |
| 302 | toGeoJSON(domain?: Domain): GeoJSON.FeatureCollection { |
| 303 | const entities = this.getEntities(domain); |
| 304 | return { |
| 305 | type: 'FeatureCollection', |
| 306 | features: entities.map(e => ({ |
| 307 | type: 'Feature' as const, |
| 308 | geometry: { |
| 309 | type: 'Point' as const, |
| 310 | coordinates: [e.position.lng, e.position.lat], |
| 311 | }, |
| 312 | properties: { |
| 313 | id: e.id, |
| 314 | name: e.name, |
| 315 | domain: e.domain, |
| 316 | entityType: e.entityType, |
| 317 | threat: e.threat, |
| 318 | color: e.display.color, |
| 319 | icon: e.display.icon, |
| 320 | heading: e.position.heading || 0, |
| 321 | alt: e.position.alt, |
| 322 | speed: e.position.speed, |
| 323 | glow: e.display.glow || false, |
| 324 | scale: e.display.scale || 1.0, |
| 325 | source: e.source.provider, |
| 326 | ...e.properties, |
| 327 | }, |
| 328 | })), |
| 329 | }; |
| 330 | } |
| 331 | |
| 332 | /** Shutdown the SDK */ |
| 333 | destroy(): void { |
| 334 | if (this.updateInterval) clearInterval(this.updateInterval); |
| 335 | if (this.sseConnection) this.sseConnection.close(); |
| 336 | if (this.latticeAdapter) this.latticeAdapter.disconnect(); |
| 337 | this.entityStore.clear(); |
| 338 | } |
| 339 | |
| 340 | private emitUpdate(): void { |
| 341 | this.config.onEntityUpdate?.(Array.from(this.entityStore.values())); |
| 342 | this.config.onStatusChange?.(this.getStatus()); |
| 343 | } |
| 344 | |
| 345 | private getActiveFeedCount(): number { |
| 346 | let count = 0; |
| 347 | // Count OSIRIS feeds that have data |
| 348 | const feeds = ['commercial_flights', 'private_flights', 'military_flights', 'maritime_ships', |
| 349 | 'satellites', 'earthquakes', 'fires', 'cameras', 'radiation']; |
| 350 | for (const feed of feeds) { |
| 351 | if (this.entityStore.size > 0) count++; // Simplified: if store has data, feeds are active |
| 352 | } |
| 353 | if (this.latticeAdapter && this.latticeAdapter.getEntityCount() > 0) count++; |
| 354 | return Math.min(count, feeds.length); |
| 355 | } |
| 356 | } |