Compare commits
24
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f49a2e0a0a | ||
|
|
2aad665096 | ||
|
|
08645699f3 | ||
|
|
f5e8d25fe2 | ||
|
|
b2fcc57d19 | ||
|
|
91744aeaef | ||
|
|
0ab72867b0 | ||
|
|
7d85d56e53 | ||
|
|
3baed783b1 | ||
|
|
ed1fa39cff | ||
|
|
40eac1a0cb | ||
|
|
d277a018ee | ||
|
|
163fcb475e | ||
|
|
903267cf3c | ||
|
|
18f0641595 | ||
|
|
be18c0a412 | ||
|
|
94fde6e660 | ||
|
|
c81f3925c6 | ||
|
|
921dba0bf1 | ||
|
|
34f85f6e57 | ||
|
|
0e0a8d6bad | ||
|
|
0785b29462 | ||
|
|
344e83376b | ||
|
|
150702d33f |
No files matched your search
@@ -1,34 +0,0 @@
|
||||
---
|
||||
trigger: glob
|
||||
description: Strict guidelines for rendering geospatial entities, handling 3D terrain clipping, and applying dynamic animation properties against Cesium's runtime engine.
|
||||
globs: "src/core/globe/**/*"
|
||||
---
|
||||
|
||||
# Cesium Rendering Rules
|
||||
|
||||
## Purpose
|
||||
Strict guidelines for rendering geospatial entities, handling 3D terrain clipping, and applying dynamic animation properties against Cesium's runtime engine.
|
||||
|
||||
## When to Apply
|
||||
Whenever writing code for plugins, visual layers, or modifying components like `EntityRenderer` or `GlobeView`.
|
||||
|
||||
## Critical Limitations
|
||||
|
||||
### `HeightReference.CLAMP_TO_GROUND` Warning
|
||||
> [!WARNING]
|
||||
> Do **not** apply `HeightReference.CLAMP_TO_GROUND` to label text rendering (`LabelGraphics`). Due to a known issue in Cesium 1.121+, clamping tens of thousands of dynamic labels blocks the UI thread continuously because Cesium recalculates the terrain intersection each frame.
|
||||
|
||||
### Primitive Restrictions
|
||||
When creating primitive objects:
|
||||
- **Points** (`PointPrimitive`): Can use `size`, `outlineWidth`, and `outlineColor`.
|
||||
- **Billboards** (`BillboardGraphics` for SVG/Icons): Must **NOT** use `size`, `outlineWidth`, or `outlineColor`. You must use `iconScale` to resize them. Mixing point properties on billboards causes severe shader clipping.
|
||||
|
||||
## Performance Culling
|
||||
|
||||
> [!TIP]
|
||||
> Do not rely solely on depth buffering (`disableDepthTestDistance`) when viewing the backside of the globe. Use CPU-side calculating (dot-product against the Earth's radius) to implement manual horizon culling. Render nothing if the scalar projection is behind the tangential threshold.
|
||||
|
||||
## LOD & Stacking
|
||||
1. Convert distant entities to `billboard` representations.
|
||||
2. If closely grouped, the `StackManager` should spiderify components circularly. Non-hub objects fade to 0.4 opacity when expanded to reduce visual clutter.
|
||||
3. Use the `useModelRendering` hook exclusively for transitioning high-importance entities (like aircraft or ships) into full 3D GLTF models on approach.
|
||||
@@ -1,21 +0,0 @@
|
||||
---
|
||||
trigger: always_on
|
||||
---
|
||||
|
||||
# Context and Memory Synchronization
|
||||
|
||||
## 1. Purpose
|
||||
This specification ensures that any agent maintains persistent, accurate project context by pointing them directly to the Single Source of Truth for this repository.
|
||||
|
||||
## 2. Synchronization Target
|
||||
The agent MUST orient itself by immediately reading:
|
||||
1. `c:\dev\worldwideview\AGENTS.md` (The root index of all technical stack details)
|
||||
2. `c:\dev\worldwideview\.agents\context\01-platform-overview.md` (The high-level platform goals)
|
||||
|
||||
If deep technical rules are required for a specific domain (e.g., UI state, Map Rendering, Monorepo management), the agent MUST consult the relevant file in `c:\dev\worldwideview\.agents\rules\`.
|
||||
|
||||
## 3. Reflecting Changes
|
||||
If the architecture fundamentally changes (e.g., migrating off Zustand, or removing Cesium), the agent MUST proactively update the `AGENTS.md` and relevant files in `.agents/rules/` to reflect this new reality.
|
||||
|
||||
## 4. Goal
|
||||
A new chat instance MUST be able to reconstruct an accurate, comprehensive understanding of the project solely from reading the root `AGENTS.md` file and branching out to the specific rules as necessary. This prevents context bloat and ensures accuracy.
|
||||
@@ -1,30 +0,0 @@
|
||||
---
|
||||
trigger: model_decision
|
||||
description: Strict rules for operating within the pnpm monorepo workspace environment structure across frontend and backend services.
|
||||
globs: ""
|
||||
---
|
||||
|
||||
# Monorepo Workflow Guidelines
|
||||
|
||||
## Purpose
|
||||
Strict rules for operating within the `pnpm` monorepo workspace environment structure across frontend and backend services.
|
||||
|
||||
## Directory Isolation
|
||||
|
||||
- The Next.js frontend is located at root `.`.
|
||||
- Individual standalone plugins are located at `packages/wwv-plugin-[name]`.
|
||||
- For heavy plugin processing, microservice backends are located at `packages/wwv-plugin-[name]/backend`.
|
||||
|
||||
## Critical Workspace Rule
|
||||
|
||||
> [!IMPORTANT]
|
||||
> Because plugins use internal workspace references, you MUST strictly use `"workspace:*"` instead of `"*"` in `package.json` dependencies (e.g. `"@worldwideview/wwv-plugin-sdk": "workspace:*"`). Using `"*"` can cause pnpm to eagerly resolve cached registry versions instead of strictly linking your local code, resulting in opaque TypeScript and compilation errors.
|
||||
> **Whenever you add a new plugin package or adjust the SDK, you MUST run `pnpm install` then `pnpm build` from the project ROOT directory to propagate TS types properly.**
|
||||
|
||||
## Start/Exec Flow
|
||||
|
||||
Running `pnpm start:backends` from the project root employs `concurrently` to spin up Fastify services attached to specific plugins containing `/backend` folders.
|
||||
|
||||
## Next.js Monorepo Exceptions
|
||||
|
||||
When modifying `next.config.ts`, if new UI components or plugins are added that require SSR/transpilation, ensure they are appended to the `transpilePackages: []` array, or they will throw Next-Router unresolved import errors on production build.
|
||||
@@ -1,83 +0,0 @@
|
||||
---
|
||||
trigger: model_decision
|
||||
description: The standard operating procedure for instantiating, modifying, and registering a new data source plugin within the engine.
|
||||
---
|
||||
|
||||
# Plugin Architecture & Data Flow
|
||||
|
||||
## Purpose
|
||||
The standard operating procedure for instantiating, modifying, and registering a new data source plugin within the engine.
|
||||
|
||||
## The WorldPlugin Contract
|
||||
|
||||
All data ingest flows through `WorldPlugin` (defined entirely within `@worldwideview/wwv-plugin-sdk`).
|
||||
A valid plugin class MUST provide:
|
||||
1. `id` and `version` (The `version` MUST be dynamically imported via `import pkg from "../package.json"` to prevent duplicate tracking during CI/releases for built-in plugins).
|
||||
2. `fetch(timeRange)` method logic.
|
||||
3. `renderEntity(GeoEntity)` to determine visual style.
|
||||
4. `getPollingInterval()` (defaults fallback securely to standard store config).
|
||||
|
||||
## Plugin Architectures (Manifest Formats)
|
||||
|
||||
Plugins are defined via `PluginManifest` and operate on an **All-Bundle** architecture.
|
||||
All frontend extensions must eventually be compiled into a JS bundle that exports a `WorldPlugin`.
|
||||
|
||||
1. **`bundle` (Dynamic CDN Loaded / Internal)**: Plugins dynamically imported at runtime via ES module references (e.g., `unpkg.com` or local `/plugins/myplugin/frontend.mjs`). Handled by `loadPluginFromManifest` referencing `manifest.entry`.
|
||||
2. **`static` (Legacy)**: Now compiled via `wwvStaticCompiler` into a dynamic bundle. The raw `StaticDataPlugin` runtime class has been removed.
|
||||
3. **`declarative` (Legacy)**: Now compiled or wrapped into bundles.
|
||||
|
||||
No matter the source, the engine evaluates it by directly loading the `entry` file dynamically:
|
||||
`const module = await import(/* webpackIgnore: true */ entry);`
|
||||
|
||||
## Package Metadata (`package.json`)
|
||||
|
||||
All plugins MUST define their identity and compatibility via a `"worldwideview"` block in their `package.json`. This acts as the source-of-truth for generating the `PluginManifest` for the registry. If a plugin does not define `"type"`, validation functions will reject the manifest entirely or rely on legacy fallbacks.
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "@worldwideview/wwv-plugin-myplugin",
|
||||
"version": "1.0.0",
|
||||
"worldwideview": {
|
||||
"id": "myplugin", // REQUIRED: Must match the directory name & API routes.
|
||||
"type": "data-layer", // REQUIRED: "data-layer" or "extension"
|
||||
"format": "bundle", // REQUIRED: "bundle", "declarative", or "static"
|
||||
"category": "Aviation", // REQUIRED: Matches PluginCategory union in SDK
|
||||
"icon": "Plane", // RECOMMENDED: Lucide icon name
|
||||
"capabilities": [ // REQUIRED: What the plugin can do
|
||||
"data:own", // (e.g. injects its own data)
|
||||
"globe:overlay", // (e.g. renders 3D elements)
|
||||
"network:fetch"
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## The Registration Pipeline
|
||||
|
||||
> [!NOTE]
|
||||
> All plugin interactions run through three singleton services:
|
||||
> `PluginRegistry` / `InstalledPluginsLoader` -> `PluginManager` -> `PollingManager` -> `DataBus`
|
||||
|
||||
### `InstalledPluginsLoader`
|
||||
Scans the PostgreSQL database at startup for dynamically installed marketplace manifests. Parses, validates (`validateManifest`), and registers valid plugins via `pluginManager.loadFromManifest`.
|
||||
|
||||
### `PluginManager`
|
||||
The orchestrator. Exposes `registerPlugin`, `enablePlugin`, `disablePlugin`. Never bypass the manager to push data manually to the cache. Supports dynamic loading via `loadFromManifest`.
|
||||
|
||||
### `PollingManager`
|
||||
Coordinates interval execution. Implements **exponential backoff**. When a plugin errors, it retries at increasing scales (e.g., 2s → 4s → 8s) automatically.
|
||||
|
||||
### `DataBus`
|
||||
The typed generic event bus separating React UI components from background execution.
|
||||
|
||||
```typescript
|
||||
// How data gets pushed onto the rendering surface securely:
|
||||
DataBus.getInstance().emit('dataUpdated', {
|
||||
pluginId: "mytracker",
|
||||
entities: newEntities
|
||||
});
|
||||
```
|
||||
|
||||
## When to Apply
|
||||
When writing `fetch` implementations for plugins, or tracing why an entity dropped off the map. Ensure missing data correctly triggers the cache fallback via the DataBus. Ensure all new external plugins use the `bundle` format and exist in the marketplace registry to avoid CDN 404 hydrating crashes.
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
---
|
||||
trigger: glob
|
||||
description: Guidelines on managing the single source of truth across WorldWideView using Zustand, avoiding prop-drilling, and isolating UI rerenders.
|
||||
globs: "src/core/state/**/*, src/components/**/*"
|
||||
---
|
||||
|
||||
# Zustand State Management
|
||||
|
||||
## Purpose
|
||||
Guidelines on managing the single source of truth across WorldWideView using Zustand, avoiding prop-drilling, and isolating UI rerenders.
|
||||
|
||||
## Single Centralized State
|
||||
WorldWideView utilizes a monolithic Zustand store located at `src/core/state/store.ts`. It is broken down into exactly 9 semantic slices.
|
||||
|
||||
| Slice Name | Purpose | Example State |
|
||||
|---|---|---|
|
||||
| **Globe** | Cesium Viewer state | `cameraPosition`, `selectedEntity` |
|
||||
| **Layers** | Loaded map tiles/overlays | `activeTileSets` |
|
||||
| **Timeline** | Application current time | `currentTimeRange` |
|
||||
| **UI** | Global overlay states | `isFilterMenuOpen` |
|
||||
| **Filters** | Active visual filtration | `searchQuery`, `categoryFilter` |
|
||||
| **Data** | Entity registry | `entitiesByPlugin` |
|
||||
| **Config** | User preferences | `pollingIntervals`, `pluginSettings` |
|
||||
| **Favorites**| Pinned entities | `favoriteIds` |
|
||||
| **GeoJSON** | Local files loaded in | `localImports` |
|
||||
|
||||
## When to Apply
|
||||
When passing deep state across components, or when a plugin must push state configurations onto the screen.
|
||||
|
||||
## Best Practices
|
||||
|
||||
### Avoid Prop Drilling
|
||||
**Never** pass props further than two levels down. If a component deeper in the tree needs access to something (e.g., `cameraPosition`), it must `useStore(s => s.globe.cameraPosition)`.
|
||||
|
||||
### Selector Destructuring Avoidance
|
||||
> [!WARNING]
|
||||
> Do not destructure wide objects in selectors.
|
||||
> Right: `const isHUD = useStore(state => state.ui.hudVisible);`
|
||||
> Wrong: `const { hudVisible } = useStore(state => state.ui);`
|
||||
> The wrong approach rerenders the component any time *anything* in the `ui` slice changes.
|
||||
|
||||
### Config and Plugins
|
||||
If your plugin has user-configurable values (e.g., color settings, toggle states), its data MUST live inside `state.config.dataConfig.pluginSettings[pluginId]`. Do not spawn un-bound `useState` hooks for UI properties if they affect the global app state.
|
||||
+2
-2
@@ -4,8 +4,8 @@
|
||||
# This file is tracked by git. Only put non-secret values here.
|
||||
# Prisma reads DATABASE_URL from this file.
|
||||
|
||||
# Database (PostgreSQL)
|
||||
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/worldwideview
|
||||
# Database (SQLite for local — zero config; PostgreSQL for cloud)
|
||||
DATABASE_URL=file:./data/wwv.db
|
||||
|
||||
# ============================================================
|
||||
# .env.local — NOT committed (secrets & API keys)
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
version: 2
|
||||
updates:
|
||||
# 1. Maintain Node.js / pnpm dependencies
|
||||
- package-ecosystem: "npm"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
day: "monday"
|
||||
# Group all minor/patch updates into a single PR so it doesn't spam you
|
||||
groups:
|
||||
dependencies:
|
||||
patterns:
|
||||
- "*"
|
||||
update-types:
|
||||
- "minor"
|
||||
- "patch"
|
||||
|
||||
# 2. Maintain Docker base images
|
||||
- package-ecosystem: "docker"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
day: "monday"
|
||||
|
||||
# 3. Maintain GitHub Actions workflows
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "monthly" # Actions update less frequently, monthly is fine
|
||||
@@ -9,9 +9,9 @@ jobs:
|
||||
name: Type Check
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: pnpm/action-setup@v6
|
||||
- uses: actions/setup-node@v6
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
@@ -23,9 +23,9 @@ jobs:
|
||||
name: Unit Tests
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: pnpm/action-setup@v6
|
||||
- uses: actions/setup-node@v6
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
@@ -42,9 +42,9 @@ jobs:
|
||||
AUTH_SECRET: ci-placeholder-secret-not-used-in-tests
|
||||
NEXT_PUBLIC_WWV_EDITION: local
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: pnpm/action-setup@v6
|
||||
- uses: actions/setup-node@v6
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
|
||||
@@ -27,7 +27,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ jobs:
|
||||
actions: read # Required for Claude to read CI results on PRs
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
|
||||
@@ -20,10 +20,10 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Log in to the Container registry
|
||||
uses: docker/login-action@v3
|
||||
@@ -34,7 +34,7 @@ jobs:
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@v6
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||
tags: |
|
||||
|
||||
@@ -12,9 +12,9 @@ jobs:
|
||||
contents: read
|
||||
id-token: write # Required for OIDC trusted publishing (no NPM_TOKEN needed)
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
registry-url: "https://registry.npmjs.org"
|
||||
|
||||
@@ -245,7 +245,7 @@ Secrets go in `.env.local` (gitignored). Non-secrets go in `.env` (committed).
|
||||
```bash
|
||||
pnpm install # Install all workspace dependencies
|
||||
pnpm run setup # Generate .env.local with AUTH_SECRET (first-time setup)
|
||||
pnpm dev # Next.js frontend only (auto-runs prisma db push + copy-cesium)
|
||||
pnpm dev # Next.js frontend only (auto-runs prisma migrate deploy + copy-cesium)
|
||||
pnpm dev:all # Frontend + wwv-data-engine concurrently (normal development)
|
||||
pnpm dev:backends # Run only the data engine in dev mode
|
||||
pnpm build # Production build
|
||||
|
||||
+6
-6
@@ -6,9 +6,9 @@ RUN find . -type f \! -name 'package.json' \! -name 'pnpm-workspace.yaml' \! -na
|
||||
find . -type d -empty -delete
|
||||
|
||||
# Stage 1: Install ALL dependencies (needed for build)
|
||||
FROM node:26-alpine AS deps
|
||||
FROM node:22-alpine AS deps
|
||||
RUN npm install -g [email protected]
|
||||
|
||||
# python3/make/g++ no longer needed — removed better-sqlite3 native compilation
|
||||
WORKDIR /app
|
||||
# Copy only the extracted package.jsons
|
||||
COPY --from=extractor /app ./
|
||||
@@ -26,7 +26,6 @@ ARG NEXT_PUBLIC_GOOGLE_MAPS_API_KEY
|
||||
ARG NEXT_PUBLIC_BING_MAPS_KEY
|
||||
ARG NEXT_PUBLIC_WWV_EDITION
|
||||
ARG NEXT_PUBLIC_WS_ENGINE_URL
|
||||
ARG NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL
|
||||
ARG NEXT_PUBLIC_ADSENSE_CLIENT_ID
|
||||
ARG NEXT_PUBLIC_SUPABASE_URL
|
||||
ARG NEXT_PUBLIC_SUPABASE_ANON_KEY
|
||||
@@ -45,11 +44,10 @@ RUN node scripts/copy-cesium.mjs
|
||||
RUN pnpm --filter worldwideview deploy --prod /app/prod
|
||||
|
||||
# Stage 4: Production runner
|
||||
FROM node:26-alpine AS runner
|
||||
FROM node:22-alpine AS runner
|
||||
WORKDIR /app
|
||||
|
||||
RUN apk add --no-cache openssl
|
||||
RUN npm install -g [email protected]
|
||||
|
||||
ENV NODE_ENV=production
|
||||
ENV HOSTNAME=0.0.0.0
|
||||
@@ -78,13 +76,15 @@ COPY --from=builder /app/prod/node_modules ./node_modules
|
||||
COPY --from=builder /app/.next/static ./.next/static
|
||||
COPY --from=builder /app/public ./public
|
||||
COPY --from=builder /app/scripts/https-proxy.mjs ./scripts/https-proxy.mjs
|
||||
COPY --from=builder /app/scripts/migrate-legacy.mjs ./scripts/migrate-legacy.mjs
|
||||
|
||||
|
||||
# Entrypoint: migrate DB on first run, then start server
|
||||
COPY docker-entrypoint.sh ./docker-entrypoint.sh
|
||||
RUN sed -i 's/\r$//' ./docker-entrypoint.sh
|
||||
RUN chmod +x ./docker-entrypoint.sh
|
||||
|
||||
|
||||
|
||||
EXPOSE 3000 3001
|
||||
|
||||
ENTRYPOINT ["./docker-entrypoint.sh"]
|
||||
@@ -7,20 +7,6 @@
|
||||
|
||||
*A modular situational awareness platform designed to ingest live data streams and render them as interactive, cinematic layers on a high-fidelity CesiumJS 3D globe.*
|
||||
|
||||
[](https://github.com/silvertakana/worldwideview/actions/workflows/ci.yml)
|
||||
[](https://codecov.io/gh/silvertakana/worldwideview)
|
||||
[](https://www.npmjs.com/package/@worldwideview/wwv-plugin-sdk)
|
||||
[](https://github.com/silvertakana/worldwideview/releases)
|
||||
[](https://github.com/silvertakana/worldwideview/graphs/contributors)
|
||||
<br>
|
||||
[](https://nextjs.org/)
|
||||
[](https://cesium.com/)
|
||||
[](https://www.typescriptlang.org/)
|
||||
[](https://www.docker.com/)
|
||||
[](LICENSE)
|
||||
[](#)
|
||||
[](https://makeapullrequest.com)
|
||||
|
||||

|
||||
|
||||
</div>
|
||||
@@ -29,14 +15,6 @@
|
||||
|
||||
WorldWideView is a real-time geospatial engine visualizing live global data on an interactive 3D globe. Utilizing a dynamic "All-Bundle" plugin architecture, independent data sources—like live aircraft, maritime vessels, or conflict events—are ingested and rendered decoupled from the core 3D viewer.
|
||||
|
||||
## Key Features
|
||||
|
||||
- **"All-Bundle" Plugin Architecture**: Ingest any data source dynamically without touching the core platform.
|
||||
- **High-Fidelity 3D Rendering**: Google Photorealistic 3D Tiles and LOD modeling powered by CesiumJS.
|
||||
- **Real-Time Data Pipeline**: High-frequency WebSocket updates managed by a custom `DataBus`.
|
||||
- **Advanced Entity Management**: Automatic horizon culling, chunked primitive rendering, and 3D stacking/spiderification.
|
||||
- **Marketplace Integration**: Download and sync new plugins directly from the UI.
|
||||
|
||||
## Core Technologies
|
||||
|
||||
- **Frontend:** Next.js 16 (App Router), React 19, TypeScript 5
|
||||
@@ -46,39 +24,6 @@ WorldWideView is a real-time geospatial engine visualizing live global data on a
|
||||
- **Database:** PostgreSQL via Prisma 7
|
||||
- **Deployment:** Docker multi-stage build, Coolify
|
||||
|
||||
## Project Architecture
|
||||
|
||||
WorldWideView separates the data acquisition layer from the frontend rendering loop, using a real-time event bus to bridge them.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
subgraph Data Sources
|
||||
A[Public APIs] -->|Poll| B[Data Engine Seeders]
|
||||
C[Microservices] -->|Stream| B
|
||||
end
|
||||
|
||||
subgraph Frontend Pipeline
|
||||
B -->|WebSocket /stream| D[DataBus & WsClient]
|
||||
D -->|Hydrate| E[Zustand Store]
|
||||
E -->|Memoized Entities| F[Entity Renderer]
|
||||
F -->|Primitives| G[CesiumJS Globe]
|
||||
end
|
||||
|
||||
subgraph Plugins
|
||||
H[Plugin Registry] -->|Load| I[Dynamic Import CDNs]
|
||||
end
|
||||
|
||||
H -.-> D
|
||||
```
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before running the application, ensure you have the following installed:
|
||||
- [Node.js](https://nodejs.org/) (v18+)
|
||||
- [pnpm](https://pnpm.io/) (v9+)
|
||||
- [Docker](https://www.docker.com/) (for self-hosting or full local dev)
|
||||
- PostgreSQL (or rely on the `coolify-db` / local compose container)
|
||||
|
||||
## Quick Start (Self-Hosting)
|
||||
|
||||
WorldWideView uses a multi-stage Dockerfile designed for standalone output. To deploy instantly on your own server:
|
||||
@@ -111,24 +56,6 @@ pnpm run dev:all # boots the UI, cache layers, and the data engine
|
||||
```
|
||||
Visit `http://localhost:3000` to see the live globe.
|
||||
|
||||
## Project Structure
|
||||
|
||||
The codebase utilizes a `pnpm` monorepo configuration:
|
||||
|
||||
```text
|
||||
worldwideview/
|
||||
├── src/ # Core frontend app
|
||||
│ ├── app/ # Next.js App Router (pages, API routes)
|
||||
│ ├── components/ # Shared UI, Globe panels, and 3D layouts
|
||||
│ ├── core/ # DataBus, Polling, PluginManager, Store
|
||||
│ └── plugins/ # Built-in plugins and registry logic
|
||||
├── packages/ # Monorepo packages
|
||||
│ ├── wwv-plugin-sdk/ # SDK interfaces and manifest schemas
|
||||
│ └── wwv-plugin-*/ # Individual plugins & their backends
|
||||
├── prisma/ # Database schemas & migrations
|
||||
└── .agents/ # Agent rules, workflows, and documentation
|
||||
```
|
||||
|
||||
## Plugin Ecosystem
|
||||
|
||||
WorldWideView operates on an open-core philosophy. The platform itself is data-agnostic; all data sources are dynamically imported as plugins at runtime.
|
||||
@@ -146,22 +73,6 @@ WorldWideView is distributed across several specialized repositories:
|
||||
4. **`worldwideview-marketplace`**: The web application driving the plugin directory.
|
||||
5. **`worldwideview-web`**: Marketing and landing site.
|
||||
|
||||
## Development & Workflow
|
||||
|
||||
- **Branching & Commits:** We strictly enforce [Conventional Commits](https://www.conventionalcommits.org/) (`feat:`, `fix:`, `refactor:`). Every commit should utilize our semantic versioning `[/commit]` workflow.
|
||||
- **Coding Standards:** We emphasize vanilla CSS (no Tailwind), strict TypeScript 5, and file modularity (max 150 lines per file).
|
||||
- **Testing:** We use Vitest with `jsdom`. All new core logic should be accompanied by tests, running via `pnpm test`.
|
||||
|
||||
See [Docs: Development](docs/development.md) and [Docs: Testing](docs/testing.md) for more details.
|
||||
|
||||
## Contributing
|
||||
|
||||
We welcome community contributions! Please review our coding standards and PR processes before submitting code. For detailed instructions on local development and setting up your environment, see our [CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
||||
|
||||
## Documentation Index
|
||||
|
||||
Explore our comprehensive documentation suite for detailed engineering insights:
|
||||
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
# Security Policy
|
||||
|
||||
Security is a priority for our project. We appreciate the efforts of security researchers and the open-source community in helping us keep our software secure.
|
||||
|
||||
## Supported Versions
|
||||
|
||||
Security updates are provided for the following versions of the project. We highly recommend all users stay on the latest stable release.
|
||||
|
||||
| Version | Supported | Notes |
|
||||
| ------- | ------------------ | ----- |
|
||||
| 2.x.x | :white_check_mark: | Current main release. Receives all security updates. |
|
||||
| 1.x.x | :x: | Legacy version. No longer receiving updates. |
|
||||
| < 1.0 | :x: | Beta versions are not supported. |
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
**Please do not report security vulnerabilities through public GitHub issues.**
|
||||
|
||||
If you believe you have found a security vulnerability in this project, please report it privately so we have time to fix it before the vulnerability is made public.
|
||||
|
||||
### How to Report
|
||||
|
||||
1. **Email us directly:** Send your report to **[support@worldwideview.dev]**.
|
||||
2. **GitHub Security Advisories:** Alternatively, if this repository has Private Vulnerability Reporting enabled, you can click on the `Security` tab -> `Advisories` -> `Report a vulnerability`.
|
||||
|
||||
### What to Include
|
||||
To help us quickly validate and fix the issue, please include the following in your report:
|
||||
* A description of the vulnerability and its potential impact.
|
||||
* The steps required to reproduce the issue (a proof of concept is highly appreciated).
|
||||
* Any relevant environment details (OS, browser, version).
|
||||
|
||||
### What to Expect
|
||||
* **Acknowledgment:** We will acknowledge receipt of your vulnerability report within **48 hours**.
|
||||
* **Triage & Fix:** We will review the report, determine its severity, and work on a patch. We will keep you updated on our progress.
|
||||
* **Disclosure:** Once the vulnerability is patched and a new version is released, we will publish a security advisory. We are happy to credit you for the discovery if you would like!
|
||||
|
||||
*Note: As an open-source project, we currently do not offer financial bug bounties, but we deeply appreciate your contributions to keeping our users safe.*
|
||||
+1
-7
@@ -15,7 +15,7 @@ services:
|
||||
- "DATABASE_URL=${DATABASE_URL:-postgresql://postgres:postgres@db:5432/worldwideview?schema=public}"
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
condition: service_started
|
||||
|
||||
db:
|
||||
image: postgres:15-alpine
|
||||
@@ -28,12 +28,6 @@ services:
|
||||
- "5432:5432"
|
||||
volumes:
|
||||
- postgres-data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U postgres -d worldwideview"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 60s
|
||||
profiles:
|
||||
- "${WWV_SKIP_LOCAL_DB:-}"
|
||||
|
||||
|
||||
+4
-25
@@ -6,37 +6,16 @@
|
||||
|
||||
set -e
|
||||
|
||||
if [ -z "$DATABASE_URL" ]; then
|
||||
echo "────────────────────────────────────────────────────────────────"
|
||||
echo "🚨 CRITICAL: DATABASE_URL IS NOT SET"
|
||||
echo "────────────────────────────────────────────────────────────────"
|
||||
echo "WorldWideView has migrated to PostgreSQL. If you are an old user,"
|
||||
echo "please update your docker-compose.yml to include a Postgres service."
|
||||
echo ""
|
||||
echo "To migrate your legacy data after setting up Postgres, run:"
|
||||
echo "docker exec -it <container_name> node scripts/migrate-legacy.mjs"
|
||||
echo "────────────────────────────────────────────────────────────────"
|
||||
|
||||
# If dev.db exists, we know they are upgrading. Don't crash, just wait for config.
|
||||
if [ -f "prisma/dev.db" ]; then
|
||||
echo "[entrypoint] Legacy data detected. Waiting for DATABASE_URL to be configured..."
|
||||
# We don't exit here, we'll let the app try to start or just sleep.
|
||||
# For now, let's just let it proceed so they can see the setup page error.
|
||||
else
|
||||
echo "[entrypoint] Exiting. Please provide a DATABASE_URL."
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "[entrypoint] Running database migrations..."
|
||||
prisma migrate deploy
|
||||
npx -y prisma migrate deploy
|
||||
echo "[entrypoint] Migrations complete."
|
||||
|
||||
|
||||
|
||||
# Generate self-signed SSL certificates for local HTTPS bridging if they don't exist
|
||||
if [ ! -f "./data/localhost.crt" ] || [ ! -f "./data/localhost.key" ]; then
|
||||
echo "[entrypoint] Generating self-signed SSL certificates for port 3001..."
|
||||
mkdir -p ./data
|
||||
openssl req -nodes -new -x509 -keyout ./data/localhost.key -out ./data/localhost.crt -days 365 -subj "/CN=localhost" 2>/dev/null || echo "[entrypoint] Warning: Failed to generate SSL certs"
|
||||
openssl req -nodes -new -x509 -keyout ./data/localhost.key -out ./data/localhost.crt -days 365 -subj "/CN=localhost" 2>/dev/null
|
||||
fi
|
||||
|
||||
# Start the HTTPS proxy in the background
|
||||
|
||||
@@ -25,38 +25,6 @@ WorldWideView deploys optimally to Coolify using a Dockerfile builder.
|
||||
- **Dockerfile:** Found at the project root (`Dockerfile`). Uses an Extractor Pattern (`deps` → `builder` → `runner`). The `.git` and `node_modules` folders must be explicitly untracked to prevent cache overlap.
|
||||
- **Compose:** Local multi-container emulation is handled via `docker-compose.yml`.
|
||||
|
||||
## Reverse Proxies (Nginx Proxy Manager)
|
||||
|
||||
When deploying WorldWideView behind a reverse proxy like Nginx Proxy Manager (NPM), you must configure both the proxy and the container environment correctly to prevent NextAuth from hanging during login, and to allow the real-time Cesium data stream to function.
|
||||
|
||||
### Container Environment Variables
|
||||
NextAuth v5 requires strict host trust when placed behind a proxy. Add the following to your Docker `.env` file or Coolify environment variables:
|
||||
|
||||
```bash
|
||||
# Required: Tells NextAuth to trust the reverse proxy headers
|
||||
AUTH_TRUST_HOST=true
|
||||
|
||||
# Required: The exact external URL your users visit
|
||||
NEXTAUTH_URL=https://your-domain.com
|
||||
```
|
||||
|
||||
### Nginx Proxy Manager Configuration
|
||||
In the NPM UI for your WorldWideView Proxy Host:
|
||||
1. **Details Tab:** Ensure **Websockets Support** is toggled **ON** (Required for the live `/stream` telemetry).
|
||||
2. **Details Tab:** Ensure **Force SSL** is toggled **ON**. NextAuth will often refuse authentication flows over plain HTTP.
|
||||
3. **Advanced Tab:** Nginx Proxy Manager sometimes fails to pass the correct host headers required by Next.js. Add the following to the Custom Nginx Configuration box:
|
||||
|
||||
```nginx
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header X-Forwarded-Host $host;
|
||||
proxy_set_header Host $host;
|
||||
|
||||
# Optional: Disable proxy buffering if 3D tiles load slowly
|
||||
proxy_buffering off;
|
||||
proxy_request_buffering off;
|
||||
```
|
||||
|
||||
## Reference
|
||||
- **Standalone Config:** `next.config.ts` (sets `output: "standalone"`).
|
||||
- **Prisma Export:** `prisma.config.ts` ensures no CLI wrappers are invoked inside the standalone container, preventing fatal `MODULE_NOT_FOUND` runtime crashes.
|
||||
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+18
-19
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "worldwideview",
|
||||
"version": "2.1.6",
|
||||
"version": "2.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"packageManager": "[email protected]",
|
||||
@@ -13,7 +13,6 @@
|
||||
"dev:backends": "cd ../wwv-data-engine && pnpm dev",
|
||||
"predev": "node scripts/boot-db.mjs && npx dotenv-cli -e .env.local -c -- npx prisma db push --accept-data-loss && npx prisma generate && node scripts/copy-cesium.mjs",
|
||||
"copy-cesium": "node scripts/copy-cesium.mjs",
|
||||
"prebuild": "node scripts/check-build-env.mjs",
|
||||
"build": "next build --webpack",
|
||||
"start": "next start",
|
||||
"test": "vitest run",
|
||||
@@ -21,36 +20,36 @@
|
||||
"generate": "prisma generate"
|
||||
},
|
||||
"dependencies": {
|
||||
"@auth/prisma-adapter": "^2.11.2",
|
||||
"@auth/prisma-adapter": "^2.11.1",
|
||||
"@auth/supabase-adapter": "^1.11.2",
|
||||
"@prisma/adapter-pg": "^7.8.0",
|
||||
"@prisma/client": "^7.8.0",
|
||||
"@prisma/client-runtime-utils": "7.8.0",
|
||||
"@sentry/nextjs": "^10.52.0",
|
||||
"@supabase/supabase-js": "^2.105.4",
|
||||
"@prisma/adapter-pg": "^7.6.0",
|
||||
"@prisma/client": "^7.6.0",
|
||||
"@prisma/client-runtime-utils": "7.6.0",
|
||||
"@sentry/nextjs": "^10.48.0",
|
||||
"@supabase/supabase-js": "^2.98.0",
|
||||
"@types/pg": "^8.20.0",
|
||||
"@vercel/analytics": "^1.6.1",
|
||||
"@worldwideview/wwv-plugin-sdk": "workspace:*",
|
||||
"bcryptjs": "^3.0.3",
|
||||
"cesium": "^1.141.0",
|
||||
"cesium": "^1.139.0",
|
||||
"cheerio": "^1.2.0",
|
||||
"hls.js": "^1.6.16",
|
||||
"hls.js": "^1.6.15",
|
||||
"insecam-api": "^0.0.3",
|
||||
"jose": "^6.2.3",
|
||||
"jose": "^6.2.2",
|
||||
"lucide-react": "^0.576.0",
|
||||
"next": "16.2.6",
|
||||
"next": "16.2.3",
|
||||
"next-auth": "^5.0.0-beta.30",
|
||||
"pg": "^8.20.0",
|
||||
"prisma": "^7.8.0",
|
||||
"react": "19.2.6",
|
||||
"react-dom": "19.2.6",
|
||||
"prisma": "^7.6.0",
|
||||
"react": "19.2.3",
|
||||
"react-dom": "19.2.3",
|
||||
"react-player": "^3.4.0",
|
||||
"resium": "1.21.0",
|
||||
"resium": "1.19.4",
|
||||
"satellite.js": "^7.0.0",
|
||||
"stripe": "^22.1.1",
|
||||
"tslib": "^2.8.1",
|
||||
"ws": "^8.14.2",
|
||||
"zustand": "^5.0.13"
|
||||
"zustand": "^5.0.11"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@testing-library/dom": "^10.4.1",
|
||||
@@ -68,8 +67,8 @@
|
||||
"rollup-plugin-external-globals": "^0.13.0",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^5",
|
||||
"vite": "^8.0.11",
|
||||
"vitest": "^4.1.5"
|
||||
"vite": "^8.0.8",
|
||||
"vitest": "^4.0.18"
|
||||
},
|
||||
"pnpm": {
|
||||
"onlyBuiltDependencies": [
|
||||
|
||||
Generated
+1011
-916
File diff suppressed because it is too large.
Load diff
File mode changed.
@@ -1,30 +0,0 @@
|
||||
/**
|
||||
* Pre-build sanity check for build-time public env vars.
|
||||
*
|
||||
* Some NEXT_PUBLIC_* vars are inlined into the client bundle by Next.js at
|
||||
* build time, so they must be set when `next build` runs (not just at runtime).
|
||||
* Missing ones don't fail the build — most have library defaults — but they
|
||||
* surface as opaque runtime 401s / blank panes that are painful to diagnose.
|
||||
*
|
||||
* This script prints actionable warnings instead.
|
||||
*/
|
||||
|
||||
const checks = [
|
||||
{
|
||||
name: "NEXT_PUBLIC_CESIUM_ION_TOKEN",
|
||||
why: "Cesium ships a built-in default Ion token, but Cesium periodically revokes it. Without your own token, base imagery and world terrain may return 401 Unauthorized at runtime.",
|
||||
how: "Get a free token at https://ion.cesium.com and set NEXT_PUBLIC_CESIUM_ION_TOKEN before building (e.g. in .env).",
|
||||
},
|
||||
];
|
||||
|
||||
const missing = checks.filter(c => !process.env[c.name]);
|
||||
if (missing.length === 0) process.exit(0);
|
||||
|
||||
const yellow = (s) => `\x1b[33m${s}\x1b[0m`;
|
||||
console.warn(yellow("\n⚠ Build-time env vars not set:"));
|
||||
for (const c of missing) {
|
||||
console.warn(yellow(`\n ${c.name}`));
|
||||
console.warn(` ${c.why}`);
|
||||
console.warn(` Fix: ${c.how}`);
|
||||
}
|
||||
console.warn(yellow("\nContinuing build — these are warnings, not errors.\n"));
|
||||
@@ -1,97 +0,0 @@
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import { PrismaClient } from "../src/generated/prisma/index.js";
|
||||
import { PrismaPg } from "@prisma/adapter-pg";
|
||||
import pg from "pg";
|
||||
import path from "node:path";
|
||||
import fs from "node:fs";
|
||||
|
||||
async function migrate() {
|
||||
const targetPath = process.argv[2] || "data/wwv.db";
|
||||
const sqlitePath = path.resolve(process.cwd(), targetPath);
|
||||
|
||||
if (!fs.existsSync(sqlitePath)) {
|
||||
console.error(`❌ No legacy SQLite database found at ${targetPath}`);
|
||||
console.error("💡 Usage: node scripts/migrate-legacy.mjs [path-to-db]");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(`📂 Found legacy database at ${targetPath}. Initializing migration...`);
|
||||
|
||||
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
|
||||
const adapter = new PrismaPg(pool);
|
||||
const prisma = new PrismaClient({ adapter });
|
||||
const db = new DatabaseSync(sqlitePath);
|
||||
|
||||
try {
|
||||
// 1. Migrate Users
|
||||
console.log("👤 Migrating users...");
|
||||
const users = db.prepare("SELECT * FROM users").all();
|
||||
for (const user of users) {
|
||||
await prisma.user.upsert({
|
||||
where: { id: user.id },
|
||||
update: {},
|
||||
create: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
hashedPassword: user.hashedPassword,
|
||||
role: user.role,
|
||||
createdAt: new Date(user.createdAt),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 2. Migrate Favorites
|
||||
console.log("⭐️ Migrating favorites...");
|
||||
const favorites = db.prepare("SELECT * FROM favorites").all();
|
||||
for (const fav of favorites) {
|
||||
await prisma.favorite.upsert({
|
||||
where: { id: fav.id },
|
||||
update: {},
|
||||
create: {
|
||||
id: fav.id,
|
||||
userId: fav.userId,
|
||||
entityId: fav.entityId,
|
||||
pluginId: fav.pluginId,
|
||||
label: fav.label,
|
||||
pluginName: fav.pluginName,
|
||||
lastSeen: new Date(fav.lastSeen),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 3. Migrate Settings
|
||||
console.log("⚙️ Migrating settings...");
|
||||
const settings = db.prepare("SELECT * FROM settings").all();
|
||||
for (const setting of settings) {
|
||||
const existing = await prisma.setting.findFirst({
|
||||
where: { key: setting.key, tenantId: setting.tenantId || null }
|
||||
});
|
||||
if (existing) {
|
||||
await prisma.setting.update({
|
||||
where: { id: existing.id },
|
||||
data: { value: setting.value }
|
||||
});
|
||||
} else {
|
||||
await prisma.setting.create({
|
||||
data: {
|
||||
id: setting.id || undefined, // Let Prisma generate if undefined
|
||||
tenantId: setting.tenantId || null,
|
||||
key: setting.key,
|
||||
value: setting.value,
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
console.log("✅ Migration successful! All data moved to PostgreSQL.");
|
||||
console.log("💡 You can now safely delete prisma/dev.db");
|
||||
|
||||
} catch (error) {
|
||||
console.error("❌ Migration failed:", error);
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
migrate();
|
||||
@@ -0,0 +1,129 @@
|
||||
import { execSync } from "child_process";
|
||||
import fs from "fs";
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
import { PrismaPg } from "@prisma/adapter-pg";
|
||||
import pg from "pg";
|
||||
const { Pool } = pg;
|
||||
|
||||
const SQLITE_DB_PATH = "./data/wwv.db";
|
||||
const MIGRATED_MARKER = "./data/wwv.db.migrated";
|
||||
|
||||
async function run() {
|
||||
if (!fs.existsSync(SQLITE_DB_PATH)) {
|
||||
// No SQLite database found, nothing to migrate
|
||||
return;
|
||||
}
|
||||
|
||||
if (fs.existsSync(MIGRATED_MARKER)) {
|
||||
console.log("[migration] SQLite database already migrated. Skipping.");
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("[migration] Legacy SQLite database detected. Initiating migration to PostgreSQL...");
|
||||
|
||||
// Initialize Prisma client connecting to PostgreSQL natively via adapter
|
||||
const connectionString = process.env.DATABASE_URL;
|
||||
if (!connectionString) {
|
||||
console.error("[migration] DATABASE_URL environment variable is missing.");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const pool = new Pool({ connectionString });
|
||||
const adapter = new PrismaPg(pool);
|
||||
const prisma = new PrismaClient({ adapter });
|
||||
|
||||
try {
|
||||
await prisma.$connect();
|
||||
|
||||
const tablesToMigrate = [
|
||||
{ sqlite: "users", prisma: prisma.user, key: "id" },
|
||||
{ sqlite: "workspaces", prisma: prisma.workspace, key: "id" },
|
||||
{ sqlite: "workspace_members", prisma: prisma.workspaceMember, key: "id" },
|
||||
{ sqlite: "favorites", prisma: prisma.favorite, key: "id" },
|
||||
{ sqlite: "installed_plugins", prisma: prisma.installedPlugin, key: "id" },
|
||||
{ sqlite: "settings", prisma: prisma.setting, key: "id" }
|
||||
];
|
||||
|
||||
for (const table of tablesToMigrate) {
|
||||
console.log(`[migration] Migrating table: ${table.sqlite}...`);
|
||||
let rowsJson = "[]";
|
||||
try {
|
||||
// Read data from SQLite
|
||||
const isWindows = process.platform === "win32";
|
||||
const cmd = isWindows
|
||||
? `docker run --rm -v "${process.cwd().replace(/\\/g, '/')}/data:/data" keinos/sqlite3 sqlite3 --json /data/wwv.db "SELECT * FROM ${table.sqlite};"`
|
||||
: `sqlite3 --json ${SQLITE_DB_PATH} "SELECT * FROM ${table.sqlite};"`;
|
||||
|
||||
const output = execSync(cmd, { encoding: "utf-8", stdio: ['pipe', 'pipe', 'ignore'] });
|
||||
if (output && output.trim()) {
|
||||
rowsJson = output;
|
||||
}
|
||||
} catch (err) {
|
||||
// Table might not exist in SQLite (e.g., workspaces was newly added), that's fine
|
||||
console.log(`[migration] Skipping table ${table.sqlite} (might not exist in legacy DB).`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const rows = JSON.parse(rowsJson);
|
||||
if (rows.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
console.log(`[migration] Found ${rows.length} rows in ${table.sqlite}. Insertions...`);
|
||||
let inserted = 0;
|
||||
for (const row of rows) {
|
||||
// Handle boolean fields which are 1/0 in SQLite
|
||||
if (table.sqlite === "installed_plugins" && "enabled" in row) {
|
||||
row.enabled = row.enabled === 1;
|
||||
}
|
||||
|
||||
// Handle dates which are strings/numbers in SQLite
|
||||
const dateFields = ["createdAt", "updatedAt", "lastSeen", "installedAt", "joinedAt"];
|
||||
for (const field of dateFields) {
|
||||
if (row[field]) {
|
||||
// SQLite dates might be stored as Unix timestamps or strings
|
||||
// If it's a number, it could be seconds or milliseconds. Prisma stores ms.
|
||||
if (typeof row[field] === "number") {
|
||||
// If it's in seconds (typical Unix timestamp), multiply by 1000
|
||||
// A timestamp in 2024 is around 1.7e9, in ms it's 1.7e12
|
||||
const isSeconds = row[field] < 1e11;
|
||||
row[field] = new Date(isSeconds ? row[field] * 1000 : row[field]);
|
||||
} else {
|
||||
row[field] = new Date(row[field]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
// All these tables have "id" as the primary key.
|
||||
const exists = await table.prisma.findUnique({
|
||||
where: { id: row.id }
|
||||
});
|
||||
|
||||
if (!exists) {
|
||||
await table.prisma.create({
|
||||
data: row
|
||||
});
|
||||
inserted++;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[migration] Failed to insert row into ${table.sqlite}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
console.log(`[migration] Inserted ${inserted} new rows into PostgreSQL table ${table.sqlite}.`);
|
||||
}
|
||||
|
||||
// Mark as migrated
|
||||
fs.writeFileSync(MIGRATED_MARKER, new Date().toISOString(), "utf8");
|
||||
console.log("[migration] SQLite to PostgreSQL migration completed successfully!");
|
||||
console.log("[migration] Note: You can safely delete ./data/wwv.db now.");
|
||||
|
||||
} catch (err) {
|
||||
console.error("[migration] Fatal error during migration:", err);
|
||||
process.exit(1);
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
run();
|
||||
@@ -1,42 +0,0 @@
|
||||
services:
|
||||
wwv:
|
||||
image: ghcr.io/silvertakana/worldwideview:latest
|
||||
pull_policy: always
|
||||
ports:
|
||||
- "3000:3000"
|
||||
volumes:
|
||||
- wwv-data:/app/data
|
||||
env_file:
|
||||
- path: .env
|
||||
required: false
|
||||
environment:
|
||||
- "AUTH_SECRET=${AUTH_SECRET:-default_secret_for_local_dev}"
|
||||
- "WWV_DEMO_ADMIN_SECRET=${WWV_DEMO_ADMIN_SECRET:-}"
|
||||
- "WWV_BRIDGE_TOKEN=${WWV_BRIDGE_TOKEN:-}"
|
||||
- "DATABASE_URL=${DATABASE_URL:-postgresql://postgres:postgres@db:5432/worldwideview?schema=public}"
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
|
||||
db:
|
||||
image: postgres:15-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: postgres
|
||||
POSTGRES_DB: worldwideview
|
||||
ports:
|
||||
- "5432:5432"
|
||||
volumes:
|
||||
- postgres-data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U postgres -d worldwideview"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 60s
|
||||
|
||||
volumes:
|
||||
wwv-data:
|
||||
postgres-data:
|
||||
+21
-8
@@ -20,8 +20,25 @@ try {
|
||||
}
|
||||
|
||||
# Generate docker-compose.yml
|
||||
Write-Host "[*] Downloading docker-compose.yml..."
|
||||
Invoke-WebRequest -Uri "https://raw.githubusercontent.com/silvertakana/worldwideview/main/self-host/docker-compose.yml" -OutFile docker-compose.yml
|
||||
Write-Host "[*] Creating docker-compose.yml..."
|
||||
|
||||
$dockerCompose = @(
|
||||
"services:"
|
||||
" wwv:"
|
||||
" image: ghcr.io/silvertakana/worldwideview:latest"
|
||||
" ports:"
|
||||
" - `"3000:3000`""
|
||||
" volumes:"
|
||||
" - wwv-data:/app/data"
|
||||
" env_file:"
|
||||
" - .env"
|
||||
" restart: unless-stopped"
|
||||
""
|
||||
"volumes:"
|
||||
" wwv-data:"
|
||||
)
|
||||
|
||||
$dockerCompose | Out-File -FilePath docker-compose.yml -Encoding utf8
|
||||
|
||||
# Generate .env
|
||||
if (-Not (Test-Path .env)) {
|
||||
@@ -29,12 +46,8 @@ if (-Not (Test-Path .env)) {
|
||||
$bytes = New-Object Byte[] 32
|
||||
[System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($bytes)
|
||||
$secret = -join ($bytes | ForEach-Object { $_.ToString("x2") })
|
||||
Write-Host "[*] Downloading .env template..."
|
||||
Invoke-WebRequest -Uri "https://raw.githubusercontent.com/silvertakana/worldwideview/main/.env.example" -OutFile .env
|
||||
|
||||
$envContent = Get-Content .env -Raw
|
||||
$envContent = $envContent -replace "(?m)^AUTH_SECRET=.*", "AUTH_SECRET=$secret"
|
||||
$envContent | Out-File -FilePath .env -Encoding utf8
|
||||
"AUTH_SECRET=$secret" | Out-File -FilePath .env -Encoding ascii
|
||||
"NEXT_PUBLIC_WWV_EDITION=local" | Out-File -FilePath .env -Encoding ascii -Append
|
||||
} else {
|
||||
Write-Host "[Success] .env already exists, skipping generation."
|
||||
}
|
||||
|
||||
+19
-9
@@ -17,9 +17,23 @@ if ! docker compose version > /dev/null 2>&1; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 1. Download docker-compose.yml
|
||||
echo "📦 Downloading docker-compose.yml..."
|
||||
curl -fsSL -o docker-compose.yml https://raw.githubusercontent.com/silvertakana/worldwideview/main/self-host/docker-compose.yml
|
||||
# 1. Generate docker-compose.yml
|
||||
echo "📦 Creating docker-compose.yml..."
|
||||
cat > docker-compose.yml << 'EOF'
|
||||
services:
|
||||
wwv:
|
||||
image: ghcr.io/silvertakana/worldwideview:latest
|
||||
ports:
|
||||
- "3000:3000"
|
||||
volumes:
|
||||
- wwv-data:/app/data
|
||||
env_file:
|
||||
- .env
|
||||
restart: unless-stopped # ← Auto-starts on boot
|
||||
|
||||
volumes:
|
||||
wwv-data:
|
||||
EOF
|
||||
|
||||
# 2. Generate .env with a persistent secret
|
||||
if [ ! -f .env ]; then
|
||||
@@ -30,12 +44,8 @@ if [ ! -f .env ]; then
|
||||
else
|
||||
SECRET=$(head -c 32 /dev/urandom | xxd -p)
|
||||
fi
|
||||
echo "📥 Downloading .env template..."
|
||||
curl -fsSL -o .env https://raw.githubusercontent.com/silvertakana/worldwideview/main/.env.example
|
||||
|
||||
# Replace AUTH_SECRET= with the generated secret
|
||||
# (macOS sed requires an empty string backup extension, Linux does not. Perl is safer across platforms)
|
||||
perl -pi -e "s/^AUTH_SECRET=.*$/AUTH_SECRET=$SECRET/" .env
|
||||
echo "AUTH_SECRET=$SECRET" > .env
|
||||
echo "NEXT_PUBLIC_WWV_EDITION=local" >> .env
|
||||
else
|
||||
echo "✅ .env already exists, skipping generation."
|
||||
fi
|
||||
|
||||
@@ -20,8 +20,25 @@ try {
|
||||
}
|
||||
|
||||
# Generate docker-compose.yml
|
||||
Write-Host "[*] Downloading docker-compose.yml..."
|
||||
Invoke-WebRequest -Uri "https://raw.githubusercontent.com/silvertakana/worldwideview/main/self-host/docker-compose.yml" -OutFile docker-compose.yml
|
||||
Write-Host "[*] Creating docker-compose.yml..."
|
||||
|
||||
$dockerCompose = @(
|
||||
"services:"
|
||||
" wwv:"
|
||||
" image: ghcr.io/silvertakana/worldwideview:latest"
|
||||
" ports:"
|
||||
" - `"3000:3000`""
|
||||
" volumes:"
|
||||
" - wwv-data:/app/data"
|
||||
" env_file:"
|
||||
" - .env"
|
||||
" restart: unless-stopped"
|
||||
""
|
||||
"volumes:"
|
||||
" wwv-data:"
|
||||
)
|
||||
|
||||
$dockerCompose | Out-File -FilePath docker-compose.yml -Encoding utf8
|
||||
|
||||
# Generate .env
|
||||
if (-Not (Test-Path .env)) {
|
||||
@@ -29,19 +46,12 @@ if (-Not (Test-Path .env)) {
|
||||
$bytes = New-Object Byte[] 32
|
||||
[System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($bytes)
|
||||
$secret = -join ($bytes | ForEach-Object { $_.ToString("x2") })
|
||||
Write-Host "[*] Downloading .env template..."
|
||||
Invoke-WebRequest -Uri "https://raw.githubusercontent.com/silvertakana/worldwideview/main/.env.example" -OutFile .env
|
||||
|
||||
$envContent = Get-Content .env -Raw
|
||||
$envContent = $envContent -replace "(?m)^AUTH_SECRET=.*", "AUTH_SECRET=$secret"
|
||||
$envContent | Out-File -FilePath .env -Encoding utf8
|
||||
"AUTH_SECRET=$secret" | Out-File -FilePath .env -Encoding ascii
|
||||
"NEXT_PUBLIC_WWV_EDITION=local" | Out-File -FilePath .env -Encoding ascii -Append
|
||||
} else {
|
||||
Write-Host "[Success] .env already exists, skipping generation."
|
||||
}
|
||||
|
||||
Write-Host "[*] Pulling latest image updates..."
|
||||
docker compose pull
|
||||
|
||||
Write-Host "[*] Starting Docker container..."
|
||||
docker compose up -d
|
||||
|
||||
|
||||
@@ -17,9 +17,23 @@ if ! docker compose version > /dev/null 2>&1; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 1. Download docker-compose.yml
|
||||
echo "📦 Downloading docker-compose.yml..."
|
||||
curl -fsSL -o docker-compose.yml https://raw.githubusercontent.com/silvertakana/worldwideview/main/self-host/docker-compose.yml
|
||||
# 1. Generate docker-compose.yml
|
||||
echo "📦 Creating docker-compose.yml..."
|
||||
cat > docker-compose.yml << 'EOF'
|
||||
services:
|
||||
wwv:
|
||||
image: ghcr.io/silvertakana/worldwideview:latest
|
||||
ports:
|
||||
- "3000:3000"
|
||||
volumes:
|
||||
- wwv-data:/app/data
|
||||
env_file:
|
||||
- .env
|
||||
restart: unless-stopped # ← Auto-starts on boot
|
||||
|
||||
volumes:
|
||||
wwv-data:
|
||||
EOF
|
||||
|
||||
# 2. Generate .env with a persistent secret
|
||||
if [ ! -f .env ]; then
|
||||
@@ -30,20 +44,13 @@ if [ ! -f .env ]; then
|
||||
else
|
||||
SECRET=$(head -c 32 /dev/urandom | xxd -p)
|
||||
fi
|
||||
echo "📥 Downloading .env template..."
|
||||
curl -fsSL -o .env https://raw.githubusercontent.com/silvertakana/worldwideview/main/.env.example
|
||||
|
||||
# Replace AUTH_SECRET= with the generated secret
|
||||
# (macOS sed requires an empty string backup extension, Linux does not. Perl is safer across platforms)
|
||||
perl -pi -e "s/^AUTH_SECRET=.*$/AUTH_SECRET=$SECRET/" .env
|
||||
echo "AUTH_SECRET=$SECRET" > .env
|
||||
echo "NEXT_PUBLIC_WWV_EDITION=local" >> .env
|
||||
else
|
||||
echo "✅ .env already exists, skipping generation."
|
||||
fi
|
||||
|
||||
# 3. Start it
|
||||
echo "📥 Pulling latest image updates..."
|
||||
docker compose pull
|
||||
|
||||
echo "🚀 Starting Docker container..."
|
||||
docker compose up -d
|
||||
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
import { fetchCaltransCameras } from "../caltrans/caltransFetcher";
|
||||
import type { CameraAdapter, CameraFeature } from "./types";
|
||||
|
||||
export const caltransAdapter: CameraAdapter = {
|
||||
id: "caltrans",
|
||||
displayName: "Caltrans (California)",
|
||||
region: "United States — California",
|
||||
fetch: async () => (await fetchCaltransCameras()) as CameraFeature[],
|
||||
};
|
||||
@@ -1,35 +0,0 @@
|
||||
import { fetchGdotCameras } from "../gdot/gdotFetcher";
|
||||
import type { CameraAdapter, CameraFeature } from "./types";
|
||||
|
||||
// GDOT's snapshot infrastructure (navigator-c2c.dot.ga.gov, vss5live.dot.ga.gov)
|
||||
// has been retired upstream as of 2026 — both hosts NXDOMAIN. The metadata
|
||||
// API still returns those URLs, so strip them so the client doesn't trigger
|
||||
// DNS errors on click. Drop these entries from the filter list once GDOT
|
||||
// publishes a working snapshot endpoint.
|
||||
const DEAD_STREAM_HOSTS = [
|
||||
"navigator-c2c.dot.ga.gov",
|
||||
"vss5live.dot.ga.gov",
|
||||
];
|
||||
|
||||
function isDeadHost(url: string | null | undefined): boolean {
|
||||
if (!url) return false;
|
||||
return DEAD_STREAM_HOSTS.some((h) => url.includes(h));
|
||||
}
|
||||
|
||||
export const gdotAdapter: CameraAdapter = {
|
||||
id: "gdot",
|
||||
displayName: "GDOT (Georgia)",
|
||||
region: "United States — Georgia",
|
||||
fetch: async () => {
|
||||
const features = (await fetchGdotCameras()) as CameraFeature[];
|
||||
return features.map((f) => {
|
||||
const p = f.properties;
|
||||
const stream = isDeadHost(p.stream) ? null : (p.stream ?? null);
|
||||
const hls = isDeadHost(p.hls) ? null : (p.hls ?? null);
|
||||
return {
|
||||
...f,
|
||||
properties: { ...p, stream, hls },
|
||||
};
|
||||
});
|
||||
},
|
||||
};
|
||||
@@ -1,9 +0,0 @@
|
||||
import { fetch511NyCameras } from "../ny511/ny511Fetcher";
|
||||
import type { CameraAdapter, CameraFeature } from "./types";
|
||||
|
||||
export const ny511Adapter: CameraAdapter = {
|
||||
id: "ny511",
|
||||
displayName: "511NY (New York State)",
|
||||
region: "United States — New York",
|
||||
fetch: async () => (await fetch511NyCameras()) as CameraFeature[],
|
||||
};
|
||||
@@ -1,131 +0,0 @@
|
||||
import type { CameraAdapter, CameraAdapterMeta, CameraFeature } from "./types";
|
||||
import { caltransAdapter } from "./caltrans";
|
||||
import { gdotAdapter } from "./gdot";
|
||||
import { tflAdapter } from "./tfl";
|
||||
import { ny511Adapter } from "./ny511";
|
||||
import { wsdotAdapter } from "./wsdot";
|
||||
|
||||
/**
|
||||
* All registered adapters. To add a new source, add an import + push the
|
||||
* adapter object here. No other file needs to change for the new source
|
||||
* to appear in `/api/camera/list`, `/api/camera/traffic?sources=...`, and
|
||||
* the client's source-picker UI.
|
||||
*/
|
||||
export const ALL_ADAPTERS: CameraAdapter[] = [
|
||||
caltransAdapter,
|
||||
gdotAdapter,
|
||||
tflAdapter,
|
||||
ny511Adapter,
|
||||
wsdotAdapter,
|
||||
];
|
||||
|
||||
const ADAPTERS_BY_ID: Map<string, CameraAdapter> = new Map(
|
||||
ALL_ADAPTERS.map((a) => [a.id, a]),
|
||||
);
|
||||
|
||||
const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
interface CacheEntry {
|
||||
data: CameraFeature[];
|
||||
expiry: number;
|
||||
fetchedAt: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
const cache: Map<string, CacheEntry> = new Map();
|
||||
|
||||
export function getAdapter(id: string): CameraAdapter | undefined {
|
||||
return ADAPTERS_BY_ID.get(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a `?sources=` query value into a list of adapter ids.
|
||||
* - empty / unset / "all" → all known adapter ids
|
||||
* - "none" → empty list (clients use this to short-circuit)
|
||||
* - comma-separated list → only the registered ones, unknown ids dropped
|
||||
*/
|
||||
export function resolveSources(raw: string | null): string[] {
|
||||
if (!raw || raw === "all") return ALL_ADAPTERS.map((a) => a.id);
|
||||
if (raw === "none") return [];
|
||||
const requested = raw.split(",").map((s) => s.trim()).filter(Boolean);
|
||||
return requested.filter((id) => ADAPTERS_BY_ID.has(id));
|
||||
}
|
||||
|
||||
function isKeyAvailable(adapter: CameraAdapter): boolean {
|
||||
if (!adapter.requiresKey) return true;
|
||||
return !!process.env[adapter.requiresKey.envVar];
|
||||
}
|
||||
|
||||
/** Return all adapter metadata for `/api/camera/list`. */
|
||||
export function getAdapterMetadata(): CameraAdapterMeta[] {
|
||||
return ALL_ADAPTERS.map((a) => {
|
||||
const c = cache.get(a.id);
|
||||
const keyOk = isKeyAvailable(a);
|
||||
return {
|
||||
id: a.id,
|
||||
displayName: a.displayName,
|
||||
region: a.region,
|
||||
requiresKey: a.requiresKey,
|
||||
healthy: keyOk && !!c && !c.error,
|
||||
lastFetchedAt: c?.fetchedAt ?? null,
|
||||
lastFeatureCount: c ? c.data.length : null,
|
||||
lastError: c?.error,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a single adapter's data with per-adapter caching.
|
||||
* Each adapter has its own TTL (default 24h, overridable via `cacheTtlMs`),
|
||||
* so fast sources can refresh hourly while slow ones stay daily.
|
||||
*
|
||||
* On error: returns the stale cached value if present, or rethrows. Either
|
||||
* way, the cache entry's `error` field is set so `/api/camera/list` can
|
||||
* report unhealthy adapters.
|
||||
*/
|
||||
export async function fetchAdapter(adapter: CameraAdapter): Promise<CameraFeature[]> {
|
||||
if (!isKeyAvailable(adapter)) {
|
||||
return [];
|
||||
}
|
||||
const now = Date.now();
|
||||
const ttl = adapter.cacheTtlMs ?? DEFAULT_TTL_MS;
|
||||
const c = cache.get(adapter.id);
|
||||
if (c && now < c.expiry && !c.error) {
|
||||
return c.data;
|
||||
}
|
||||
try {
|
||||
const data = await adapter.fetch();
|
||||
cache.set(adapter.id, {
|
||||
data,
|
||||
expiry: now + ttl,
|
||||
fetchedAt: new Date(now).toISOString(),
|
||||
});
|
||||
return data;
|
||||
} catch (e: any) {
|
||||
const errMsg = e?.message ?? String(e);
|
||||
if (c) {
|
||||
cache.set(adapter.id, { ...c, error: errMsg });
|
||||
return c.data;
|
||||
}
|
||||
cache.set(adapter.id, {
|
||||
data: [],
|
||||
expiry: now + 60_000, // short retry window on first failure
|
||||
fetchedAt: new Date(now).toISOString(),
|
||||
error: errMsg,
|
||||
});
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** Fetch many adapters in parallel and merge the results. */
|
||||
export async function fetchManyAdapters(ids: string[]): Promise<CameraFeature[]> {
|
||||
const adapters = ids
|
||||
.map((id) => ADAPTERS_BY_ID.get(id))
|
||||
.filter((a): a is CameraAdapter => !!a);
|
||||
const results = await Promise.allSettled(adapters.map(fetchAdapter));
|
||||
const out: CameraFeature[] = [];
|
||||
for (const r of results) {
|
||||
if (r.status === "fulfilled") out.push(...r.value);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
import { fetchTflCameras } from "../tfl/tflFetcher";
|
||||
import type { CameraAdapter, CameraFeature } from "./types";
|
||||
|
||||
export const tflAdapter: CameraAdapter = {
|
||||
id: "tfl",
|
||||
displayName: "TfL JamCams (London)",
|
||||
region: "United Kingdom — London",
|
||||
fetch: async () => (await fetchTflCameras()) as CameraFeature[],
|
||||
};
|
||||
@@ -1,97 +0,0 @@
|
||||
/**
|
||||
* Public-camera adapter interface.
|
||||
*
|
||||
* Each upstream camera source (Caltrans, GDOT, TfL, 511NY, WSDOT, …)
|
||||
* implements `CameraAdapter`. The registry collects them; `/api/camera/traffic`
|
||||
* merges; `/api/camera/list` exposes their metadata for client-side source
|
||||
* discovery + selection UI.
|
||||
*
|
||||
* `CameraFeature` is the normalized record shape every adapter returns.
|
||||
* Replaces the legacy `GdotCameraFeature` alias which leaked the first
|
||||
* adapter's name into every other one.
|
||||
*/
|
||||
|
||||
export type StreamType = "image" | "hls" | "mp4" | "iframe" | null;
|
||||
|
||||
export interface CameraFeature {
|
||||
type: "Feature";
|
||||
geometry: {
|
||||
type: "Point";
|
||||
coordinates: [number, number]; // [lon, lat]
|
||||
};
|
||||
properties: {
|
||||
/** Stable identifier within source (used as React key on client). */
|
||||
id?: string;
|
||||
/**
|
||||
* Adapter id ("caltrans", "gdot", "ny511", ...). Plugins use this
|
||||
* for filtering and for routing clicks to the right player.
|
||||
*/
|
||||
source: string;
|
||||
/**
|
||||
* Direct snapshot/stream URL the client should render. May be null
|
||||
* when the upstream source provides location-only data or the
|
||||
* adapter has detected a dead host.
|
||||
*/
|
||||
stream: string | null;
|
||||
streamType?: StreamType;
|
||||
/** Optional HLS-specific URL when both image + HLS are available. */
|
||||
hls?: string | null;
|
||||
// Display + filter fields — adapters fill what they have.
|
||||
name?: string;
|
||||
country?: string;
|
||||
region?: string;
|
||||
city?: string;
|
||||
route?: string;
|
||||
direction?: string;
|
||||
location_description?: string;
|
||||
categories?: string[];
|
||||
/**
|
||||
* Adapter-specific extras (mile markers, county ids, etc.). Kept
|
||||
* under one key so the top-level shape stays predictable.
|
||||
*/
|
||||
extra?: Record<string, unknown>;
|
||||
};
|
||||
}
|
||||
|
||||
/** Metadata about an adapter, exposed via `/api/camera/list`. */
|
||||
export interface CameraAdapterMeta {
|
||||
/** Stable id used in `?sources=` and as the `properties.source` value. */
|
||||
id: string;
|
||||
/** Human-readable name for settings UI ("Caltrans (California)"). */
|
||||
displayName: string;
|
||||
/** Geographic scope, used for grouping in source-picker UIs. */
|
||||
region: string;
|
||||
/** True if the adapter requires an env var to function. */
|
||||
requiresKey?: {
|
||||
envVar: string;
|
||||
signupUrl: string;
|
||||
};
|
||||
/** True iff a successful fetch landed within the last cache window. */
|
||||
healthy: boolean;
|
||||
/** ISO timestamp of the last successful fetch, or null if never. */
|
||||
lastFetchedAt: string | null;
|
||||
/** Number of features returned by the most recent successful fetch. */
|
||||
lastFeatureCount: number | null;
|
||||
/** Brief error from the last fetch, if any. */
|
||||
lastError?: string;
|
||||
}
|
||||
|
||||
/** Adapter implementation contract. */
|
||||
export interface CameraAdapter {
|
||||
readonly id: string;
|
||||
readonly displayName: string;
|
||||
readonly region: string;
|
||||
readonly requiresKey?: { envVar: string; signupUrl: string };
|
||||
/** Default cache TTL for this adapter's feed. Defaults to 24h. */
|
||||
readonly cacheTtlMs?: number;
|
||||
/** Fetch the source's full feed and normalize to CameraFeature[]. */
|
||||
fetch(): Promise<CameraFeature[]>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Legacy alias — every existing fetcher imports this name. Kept as alias
|
||||
* to `CameraFeature` so old code keeps compiling while we migrate.
|
||||
*
|
||||
* @deprecated Use `CameraFeature` from `adapters/types` directly.
|
||||
*/
|
||||
export type GdotCameraFeatureLegacy = CameraFeature;
|
||||
@@ -1,13 +0,0 @@
|
||||
import { fetchWsdotCameras } from "../wsdot/wsdotFetcher";
|
||||
import type { CameraAdapter, CameraFeature } from "./types";
|
||||
|
||||
export const wsdotAdapter: CameraAdapter = {
|
||||
id: "wsdot",
|
||||
displayName: "WSDOT (Washington State)",
|
||||
region: "United States — Washington",
|
||||
requiresKey: {
|
||||
envVar: "WSDOT_API_KEY",
|
||||
signupUrl: "https://wsdot.wa.gov/traffic/api/",
|
||||
},
|
||||
fetch: async () => (await fetchWsdotCameras()) as CameraFeature[],
|
||||
};
|
||||
@@ -0,0 +1,31 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { fetchGdotCameras, type GdotCameraFeature } from "./gdotFetcher";
|
||||
|
||||
/** In-memory cache with TTL. */
|
||||
let cache: { data: GdotCameraFeature[]; expiry: number } | null = null;
|
||||
const CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const now = Date.now();
|
||||
|
||||
if (cache && now < cache.expiry) {
|
||||
return NextResponse.json({ cameras: cache.data, cached: true });
|
||||
}
|
||||
|
||||
const cameras = await fetchGdotCameras();
|
||||
cache = { data: cameras, expiry: now + CACHE_TTL_MS };
|
||||
|
||||
return NextResponse.json({ cameras, cached: false });
|
||||
} catch (error: any) {
|
||||
console.error("[GDOT API] Error:", error);
|
||||
// Serve stale cache on error if available
|
||||
if (cache) {
|
||||
return NextResponse.json({ cameras: cache.data, cached: true, stale: true });
|
||||
}
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch GDOT cameras" },
|
||||
{ status: 502 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { getAdapterMetadata } from "../adapters/registry";
|
||||
|
||||
/**
|
||||
* Returns metadata for every registered camera adapter so the client plugin
|
||||
* can render a dynamic settings UI (source toggles, key-required hints,
|
||||
* health indicators) without hardcoding the adapter list. Adding a source
|
||||
* to `adapters/registry.ts` makes it appear here automatically.
|
||||
*/
|
||||
export async function GET() {
|
||||
return NextResponse.json({ adapters: getAdapterMetadata() });
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
/**
|
||||
* Fetches all NYSDOT / 511NY traffic cameras.
|
||||
*
|
||||
* API: https://511ny.org/api/getcameras?key=<KEY>&format=json
|
||||
* Public API; key parameter is required but the endpoint accepts any value.
|
||||
* Self-hosters can set NY511_API_KEY to a real key (free at
|
||||
* https://511ny.org/developers) for first-class rate-limit treatment.
|
||||
*
|
||||
* Returns ~1,500 enabled cameras across NY State, ~80% with HLS streams.
|
||||
*/
|
||||
|
||||
import type { GdotCameraFeature } from "../gdot/gdotFetcher";
|
||||
|
||||
const NY511_BASE = "https://511ny.org/api/getcameras";
|
||||
|
||||
interface Ny511Camera {
|
||||
Latitude: number;
|
||||
Longitude: number;
|
||||
ID: string;
|
||||
Name: string | null;
|
||||
DirectionOfTravel: string | null;
|
||||
RoadwayName: string | null;
|
||||
Url: string | null;
|
||||
VideoUrl: string | null;
|
||||
Disabled: boolean;
|
||||
Blocked: boolean;
|
||||
}
|
||||
|
||||
/** Pull a county/region hint out of `RoadwayName [Region]` if present. */
|
||||
function extractCity(roadwayName: string | null): string {
|
||||
if (!roadwayName) return "New York";
|
||||
const m = roadwayName.match(/\[([^\]]+)\]/);
|
||||
return m ? m[1].trim() : "New York";
|
||||
}
|
||||
|
||||
function toGeoJsonFeature(c: Ny511Camera): GdotCameraFeature | null {
|
||||
if (c.Disabled || c.Blocked) return null;
|
||||
if (typeof c.Latitude !== "number" || typeof c.Longitude !== "number") return null;
|
||||
|
||||
const hls = c.VideoUrl ?? null;
|
||||
|
||||
return {
|
||||
type: "Feature",
|
||||
geometry: { type: "Point", coordinates: [c.Longitude, c.Latitude] },
|
||||
properties: {
|
||||
stream: hls || c.Url || "",
|
||||
hls,
|
||||
country: "United States",
|
||||
region: "New York",
|
||||
city: extractCity(c.RoadwayName),
|
||||
source: "ny511",
|
||||
name: c.ID || "",
|
||||
route: c.RoadwayName?.replace(/\s*\[[^\]]+\]\s*$/, "").trim() || "",
|
||||
direction: c.DirectionOfTravel === "Unknown" ? "" : (c.DirectionOfTravel ?? ""),
|
||||
location_description: c.Name ?? "",
|
||||
categories: ["traffic"],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Fetch all 511NY cameras. */
|
||||
export async function fetch511NyCameras(): Promise<GdotCameraFeature[]> {
|
||||
const key = process.env.NY511_API_KEY || "test";
|
||||
const url = `${NY511_BASE}?key=${encodeURIComponent(key)}&format=json`;
|
||||
|
||||
const res = await fetch(url, {
|
||||
headers: { "User-Agent": "WorldWideView/1.0" },
|
||||
});
|
||||
if (!res.ok) throw new Error(`511NY API returned ${res.status}`);
|
||||
|
||||
const data = await res.json();
|
||||
if (!Array.isArray(data)) return [];
|
||||
|
||||
const cameras: GdotCameraFeature[] = [];
|
||||
for (const c of data) {
|
||||
const f = toGeoJsonFeature(c as Ny511Camera);
|
||||
if (f) cameras.push(f);
|
||||
}
|
||||
return cameras;
|
||||
}
|
||||
@@ -1,38 +1,60 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { fetchManyAdapters, resolveSources } from "../adapters/registry";
|
||||
import { NextResponse } from "next/server";
|
||||
import { fetchGdotCameras, type GdotCameraFeature } from "../gdot/gdotFetcher";
|
||||
import { fetchTflCameras } from "../tfl/tflFetcher";
|
||||
import { fetchCaltransCameras } from "../caltrans/caltransFetcher";
|
||||
|
||||
/** In-memory cache for traffic cameras with 24h TTL. */
|
||||
let cache: { data: GdotCameraFeature[]; expiry: number } | null = null;
|
||||
const CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
||||
|
||||
/**
|
||||
* Aggregator. Reads the adapter registry and fetches the requested sources.
|
||||
* Per-adapter caching lives in the registry, so individual sources can have
|
||||
* different TTLs without colliding here.
|
||||
*
|
||||
* Query params:
|
||||
* ?sources=caltrans,gdot → only those adapters
|
||||
* ?sources=all (default) → all registered adapters (back-compat with
|
||||
* the old behavior — every existing client
|
||||
* that hits this URL with no query continues
|
||||
* to receive the merged-everything payload)
|
||||
* ?sources=none → empty list (used by clients to short-circuit
|
||||
* without changing the default-on behavior of
|
||||
* this endpoint)
|
||||
*
|
||||
* Response shape kept backwards-compatible with the old /traffic endpoint:
|
||||
* { cameras: CameraFeature[], total: number, sources: string[] }
|
||||
* Merge all traffic camera sources.
|
||||
* Add new fetchers here as they are implemented.
|
||||
*/
|
||||
export async function GET(req: NextRequest) {
|
||||
const sources = resolveSources(req.nextUrl.searchParams.get("sources"));
|
||||
if (sources.length === 0) {
|
||||
return NextResponse.json({ cameras: [], total: 0, sources: [] });
|
||||
async function fetchAllTrafficCameras(): Promise<GdotCameraFeature[]> {
|
||||
const results = await Promise.allSettled([
|
||||
fetchGdotCameras(),
|
||||
fetchTflCameras(),
|
||||
fetchCaltransCameras(),
|
||||
]);
|
||||
|
||||
const all: GdotCameraFeature[] = [];
|
||||
for (const r of results) {
|
||||
if (r.status === "fulfilled") all.push(...r.value);
|
||||
}
|
||||
return all;
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const cameras = await fetchManyAdapters(sources);
|
||||
const now = Date.now();
|
||||
|
||||
if (cache && now < cache.expiry) {
|
||||
return NextResponse.json({
|
||||
cameras: cache.data,
|
||||
total: cache.data.length,
|
||||
cached: true,
|
||||
});
|
||||
}
|
||||
|
||||
const cameras = await fetchAllTrafficCameras();
|
||||
cache = { data: cameras, expiry: now + CACHE_TTL_MS };
|
||||
|
||||
return NextResponse.json({
|
||||
cameras,
|
||||
total: cameras.length,
|
||||
sources,
|
||||
cached: false,
|
||||
});
|
||||
} catch (error: any) {
|
||||
console.error("[TrafficCameras] Error:", error);
|
||||
if (cache) {
|
||||
return NextResponse.json({
|
||||
cameras: cache.data,
|
||||
total: cache.data.length,
|
||||
cached: true,
|
||||
stale: true,
|
||||
});
|
||||
}
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch traffic cameras" },
|
||||
{ status: 502 },
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
/**
|
||||
* Fetches all WSDOT (Washington State DOT) highway cameras.
|
||||
*
|
||||
* API: https://wsdot.wa.gov/Traffic/api/HighwayCameras/HighwayCamerasREST.svc/GetCamerasAsJson?AccessCode=<KEY>
|
||||
* Requires a free WSDOT Traveler Information API key
|
||||
* (https://wsdot.wa.gov/traffic/api/). Returns ~1,600 active cameras across
|
||||
* Washington State plus ~70 ODOT-shared cameras at I-5/I-205 border
|
||||
* crossings into Oregon. All cameras return direct JPG snapshot URLs.
|
||||
*
|
||||
* Without WSDOT_API_KEY set, the fetcher returns [] (logged once on first
|
||||
* call) so the combined endpoint stays operational.
|
||||
*/
|
||||
|
||||
import type { GdotCameraFeature } from "../gdot/gdotFetcher";
|
||||
|
||||
const WSDOT_BASE =
|
||||
"https://wsdot.wa.gov/Traffic/api/HighwayCameras/HighwayCamerasREST.svc/GetCamerasAsJson";
|
||||
|
||||
interface WsdotCamera {
|
||||
CameraID: number;
|
||||
CameraLocation: {
|
||||
Description: string | null;
|
||||
Direction: string | null;
|
||||
Latitude: number;
|
||||
Longitude: number;
|
||||
MilePost: number | null;
|
||||
RoadName: string | null;
|
||||
};
|
||||
CameraOwner: string | null;
|
||||
Description: string | null;
|
||||
DisplayLatitude: number;
|
||||
DisplayLongitude: number;
|
||||
ImageHeight: number;
|
||||
ImageWidth: number;
|
||||
ImageURL: string;
|
||||
IsActive: boolean;
|
||||
OwnerURL: string | null;
|
||||
Region: string | null;
|
||||
SortOrder: number;
|
||||
Title: string | null;
|
||||
}
|
||||
|
||||
let warnedMissingKey = false;
|
||||
|
||||
function toGeoJsonFeature(c: WsdotCamera): GdotCameraFeature | null {
|
||||
if (!c.IsActive) return null;
|
||||
if (!c.ImageURL) return null;
|
||||
|
||||
const lat = c.DisplayLatitude ?? c.CameraLocation?.Latitude;
|
||||
const lon = c.DisplayLongitude ?? c.CameraLocation?.Longitude;
|
||||
if (typeof lat !== "number" || typeof lon !== "number") return null;
|
||||
|
||||
const owner = c.CameraOwner ?? "";
|
||||
const isOdot = /odot|tripcheck/i.test(owner);
|
||||
|
||||
return {
|
||||
type: "Feature",
|
||||
geometry: { type: "Point", coordinates: [lon, lat] },
|
||||
properties: {
|
||||
stream: c.ImageURL,
|
||||
hls: null,
|
||||
country: "United States",
|
||||
region: isOdot ? "Oregon" : "Washington",
|
||||
city: isOdot ? "Oregon" : "Washington",
|
||||
source: "wsdot",
|
||||
name: c.Title ?? `Camera ${c.CameraID}`,
|
||||
route: c.CameraLocation?.RoadName ?? "",
|
||||
direction: c.CameraLocation?.Direction ?? "",
|
||||
location_description: c.Title ?? c.Description ?? "",
|
||||
categories: ["traffic"],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Fetch all WSDOT cameras. Requires WSDOT_API_KEY env var. */
|
||||
export async function fetchWsdotCameras(): Promise<GdotCameraFeature[]> {
|
||||
const key = process.env.WSDOT_API_KEY;
|
||||
if (!key) {
|
||||
if (!warnedMissingKey) {
|
||||
console.warn(
|
||||
"[WSDOT] WSDOT_API_KEY not set — skipping. " +
|
||||
"Get a free key at https://wsdot.wa.gov/traffic/api/",
|
||||
);
|
||||
warnedMissingKey = true;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
const url = `${WSDOT_BASE}?AccessCode=${encodeURIComponent(key)}`;
|
||||
const res = await fetch(url, {
|
||||
headers: { "User-Agent": "WorldWideView/1.0" },
|
||||
});
|
||||
if (!res.ok) throw new Error(`WSDOT API returned ${res.status}`);
|
||||
|
||||
const data = await res.json();
|
||||
if (!Array.isArray(data)) return [];
|
||||
|
||||
const cameras: GdotCameraFeature[] = [];
|
||||
for (const c of data) {
|
||||
const f = toGeoJsonFeature(c as WsdotCamera);
|
||||
if (f) cameras.push(f);
|
||||
}
|
||||
return cameras;
|
||||
}
|
||||
+5
-7
@@ -40,13 +40,11 @@ export default function RootLayout({
|
||||
<body suppressHydrationWarning>
|
||||
{children}
|
||||
{process.env.VERCEL && <Analytics />}
|
||||
{process.env.NEXT_PUBLIC_WWV_ANALYTICS === "true" && (
|
||||
<Script
|
||||
src="https://analytics.worldwideview.dev/script.js"
|
||||
data-website-id="2c8f6c09-2651-4a2a-af99-b8cee1612b9a"
|
||||
strategy="afterInteractive"
|
||||
/>
|
||||
)}
|
||||
<Script
|
||||
src="https://analytics.worldwideview.dev/script.js"
|
||||
data-website-id="2c8f6c09-2651-4a2a-af99-b8cee1612b9a"
|
||||
strategy="afterInteractive"
|
||||
/>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
|
||||
@@ -33,13 +33,6 @@ export default function SetupPage() {
|
||||
<h1 className={styles.title}>Welcome to WorldWideView</h1>
|
||||
<p className={styles.subtitle}>Create your admin account to get started</p>
|
||||
|
||||
{/* Legacy Data Detection Banner */}
|
||||
<div className={styles.legacyNotice}>
|
||||
<strong>💡 Upgrading from an older version?</strong>
|
||||
<p>We've detected legacy SQLite data. Once your new Postgres database is connected, you can import your favorites by running the migration command in your terminal.</p>
|
||||
<code>docker compose exec wwv node scripts/migrate-legacy.mjs</code>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className={styles.form}>
|
||||
<label className={styles.label} htmlFor="name">
|
||||
Display Name
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
max-width: 420px;
|
||||
background: var(--bg-secondary, #13131a);
|
||||
border: 1px solid var(--border-primary, rgba(255, 255, 255, 0.08));
|
||||
border-radius: 0px;
|
||||
border-radius: 12px;
|
||||
padding: 2.5rem 2rem;
|
||||
text-align: center;
|
||||
}
|
||||
@@ -21,7 +21,7 @@
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
margin: 0 auto 1rem;
|
||||
border-radius: 0px;
|
||||
border-radius: 10px;
|
||||
background: rgb(var(--accent-rgb, 200, 30, 30));
|
||||
color: #fff;
|
||||
font-weight: 700;
|
||||
@@ -63,7 +63,7 @@
|
||||
padding: 0.6rem 0.75rem;
|
||||
background: var(--bg-primary, #0a0a0f);
|
||||
border: 1px solid var(--border-primary, rgba(255, 255, 255, 0.08));
|
||||
border-radius: 0px;
|
||||
border-radius: 8px;
|
||||
color: var(--text-primary, #e5e5e5);
|
||||
font-size: 0.9rem;
|
||||
outline: none;
|
||||
@@ -86,7 +86,7 @@
|
||||
background: rgb(var(--accent-rgb, 200, 30, 30));
|
||||
color: #fff;
|
||||
border: none;
|
||||
border-radius: 0px;
|
||||
border-radius: 8px;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
@@ -95,28 +95,3 @@
|
||||
|
||||
.button:hover { opacity: 0.9; }
|
||||
.button:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
|
||||
.legacyNotice {
|
||||
margin: 1.5rem 0;
|
||||
padding: 1rem;
|
||||
background: rgba(255, 191, 0, 0.05);
|
||||
border: 1px solid rgba(255, 191, 0, 0.3);
|
||||
text-align: left;
|
||||
font-size: 0.8rem;
|
||||
color: #ffbf00;
|
||||
}
|
||||
|
||||
.legacyNotice strong {
|
||||
display: block;
|
||||
margin-bottom: 0.4rem;
|
||||
}
|
||||
|
||||
.legacyNotice code {
|
||||
display: block;
|
||||
margin-top: 0.75rem;
|
||||
padding: 0.5rem;
|
||||
background: #000;
|
||||
color: #0f0;
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
word-break: break-all;
|
||||
}
|
||||
@@ -1,317 +0,0 @@
|
||||
import { useState, useCallback, useEffect, useRef } from "react";
|
||||
import { Eye, EyeOff, Trash2, Key, CheckCircle, XCircle, Loader, ShieldCheck } from "lucide-react";
|
||||
import {
|
||||
API_KEY_REGISTRY,
|
||||
getUserApiKey,
|
||||
setUserApiKey,
|
||||
clearAllUserApiKeys,
|
||||
} from "@/lib/userApiKeys";
|
||||
import { sectionHeaderStyle, inputGroupStyle, labelStyle } from "../panels/DataConfig/sharedStyles";
|
||||
import ReloadToast from "@/components/ui/ReloadToast";
|
||||
import { useStore } from "@/core/state/store";
|
||||
import { verifyLicenseKey } from "@/core/license/verifyLicense";
|
||||
type VerifyStatus = "idle" | "verifying" | "valid" | "invalid";
|
||||
|
||||
const keyInputStyle: React.CSSProperties = {
|
||||
background: "var(--bg-tertiary)",
|
||||
border: "1px solid var(--border-subtle)",
|
||||
color: "var(--text-primary)",
|
||||
padding: "var(--space-xs) var(--space-sm)",
|
||||
borderRadius: "var(--radius-sm)",
|
||||
fontSize: 12,
|
||||
width: "100%",
|
||||
outline: "none",
|
||||
fontFamily: "monospace",
|
||||
};
|
||||
|
||||
const toggleBtnStyle: React.CSSProperties = {
|
||||
background: "none",
|
||||
border: "none",
|
||||
color: "var(--text-muted)",
|
||||
cursor: "pointer",
|
||||
padding: "var(--space-xs)",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
};
|
||||
|
||||
const DEBOUNCE_MS = 800;
|
||||
const MIN_KEY_LENGTH = 20;
|
||||
|
||||
function StatusIcon({ status }: { status: VerifyStatus }) {
|
||||
if (status === "verifying")
|
||||
return (
|
||||
<span style={{ display: "flex", alignItems: "center", color: "var(--text-muted)" }}>
|
||||
<Loader size={13} style={{ animation: "spin 1s linear infinite" }} />
|
||||
</span>
|
||||
);
|
||||
if (status === "valid")
|
||||
return <CheckCircle size={13} style={{ color: "#22c55e", flexShrink: 0 }} />;
|
||||
if (status === "invalid")
|
||||
return <XCircle size={13} style={{ color: "#ef4444", flexShrink: 0 }} />;
|
||||
return null;
|
||||
}
|
||||
|
||||
export function ApiKeysTab() {
|
||||
const [keys, setKeys] = useState<Record<string, string>>(() => {
|
||||
const initial: Record<string, string> = {};
|
||||
API_KEY_REGISTRY.forEach((e) => {
|
||||
initial[e.service] = getUserApiKey(e.service);
|
||||
});
|
||||
return initial;
|
||||
});
|
||||
|
||||
const licenseKey = useStore((s) => s.dataConfig.licenseKey);
|
||||
const activeTier = useStore((s) => s.dataConfig.activeTier);
|
||||
const updateDataConfig = useStore((s) => s.updateDataConfig);
|
||||
|
||||
const [licenseInput, setLicenseInput] = useState(licenseKey || "");
|
||||
const [licenseStatus, setLicenseStatus] = useState<VerifyStatus>("idle");
|
||||
const [licenseError, setLicenseError] = useState("");
|
||||
|
||||
const [visible, setVisible] = useState<Record<string, boolean>>({});
|
||||
const [status, setStatus] = useState<Record<string, VerifyStatus>>({});
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const [needsReload, setNeedsReload] = useState(false);
|
||||
const debounceRefs = useRef<Record<string, ReturnType<typeof setTimeout>>>({});
|
||||
|
||||
const verifyKey = useCallback(async (service: string, key: string) => {
|
||||
setStatus((prev) => ({ ...prev, [service]: "verifying" }));
|
||||
setErrors((prev) => ({ ...prev, [service]: "" }));
|
||||
try {
|
||||
const res = await fetch("/api/keys/verify", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ service, key }),
|
||||
});
|
||||
const data = await res.json();
|
||||
setStatus((prev) => ({ ...prev, [service]: data.valid ? "valid" : "invalid" }));
|
||||
if (!data.valid) {
|
||||
setErrors((prev) => ({ ...prev, [service]: data.error || "Invalid key" }));
|
||||
} else if (service === "google_maps") {
|
||||
setNeedsReload(true);
|
||||
}
|
||||
} catch {
|
||||
setStatus((prev) => ({ ...prev, [service]: "invalid" }));
|
||||
setErrors((prev) => ({ ...prev, [service]: "Verification failed" }));
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleChange = useCallback((service: string, value: string) => {
|
||||
setKeys((prev) => ({ ...prev, [service]: value }));
|
||||
setUserApiKey(service, value);
|
||||
setStatus((prev) => ({ ...prev, [service]: "idle" }));
|
||||
setErrors((prev) => ({ ...prev, [service]: "" }));
|
||||
|
||||
clearTimeout(debounceRefs.current[service]);
|
||||
if (value.length >= MIN_KEY_LENGTH) {
|
||||
debounceRefs.current[service] = setTimeout(() => verifyKey(service, value), DEBOUNCE_MS);
|
||||
}
|
||||
}, [verifyKey]);
|
||||
|
||||
const handleManualVerify = useCallback((service: string) => {
|
||||
const key = keys[service];
|
||||
if (key && key.length >= MIN_KEY_LENGTH) verifyKey(service, key);
|
||||
}, [keys, verifyKey]);
|
||||
|
||||
// Verify pre-loaded keys on mount
|
||||
useEffect(() => {
|
||||
API_KEY_REGISTRY.forEach((e) => {
|
||||
const key = getUserApiKey(e.service);
|
||||
if (key.length >= MIN_KEY_LENGTH) verifyKey(e.service, key);
|
||||
});
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
const toggleVisibility = useCallback(
|
||||
(service: string) => setVisible((prev) => ({ ...prev, [service]: !prev[service] })),
|
||||
[]
|
||||
);
|
||||
|
||||
const handleClearAll = useCallback(() => {
|
||||
clearAllUserApiKeys();
|
||||
const cleared: Record<string, string> = {};
|
||||
API_KEY_REGISTRY.forEach((e) => (cleared[e.service] = ""));
|
||||
setKeys(cleared);
|
||||
setStatus({});
|
||||
setErrors({});
|
||||
}, []);
|
||||
|
||||
const handleVerifyLicense = useCallback(async () => {
|
||||
if (!licenseInput) return;
|
||||
setLicenseStatus("verifying");
|
||||
setLicenseError("");
|
||||
const payload = await verifyLicenseKey(licenseInput);
|
||||
if (payload) {
|
||||
setLicenseStatus("valid");
|
||||
updateDataConfig({ licenseKey: licenseInput, activeTier: payload.tier });
|
||||
} else {
|
||||
setLicenseStatus("invalid");
|
||||
setLicenseError("Invalid or expired license key");
|
||||
updateDataConfig({ licenseKey: null, activeTier: "free" });
|
||||
}
|
||||
}, [licenseInput, updateDataConfig]);
|
||||
|
||||
const handleClearLicense = useCallback(() => {
|
||||
setLicenseInput("");
|
||||
setLicenseStatus("idle");
|
||||
setLicenseError("");
|
||||
updateDataConfig({ licenseKey: null, activeTier: "free" });
|
||||
}, [updateDataConfig]);
|
||||
|
||||
const hasAnyKey = Object.values(keys).some((v) => v.length > 0);
|
||||
|
||||
return (
|
||||
<>
|
||||
<style>{`@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }`}</style>
|
||||
<div style={{ marginBottom: "var(--space-lg)" }}>
|
||||
<div style={sectionHeaderStyle}>
|
||||
<Key size={10} style={{ marginRight: 4, verticalAlign: "middle" }} />
|
||||
License Key
|
||||
</div>
|
||||
<div style={{ fontSize: 11, color: "var(--text-muted)", marginBottom: "var(--space-md)" }}>
|
||||
Current Tier: <strong style={{ color: "var(--text-primary)", textTransform: "capitalize" }}>{activeTier}</strong>
|
||||
</div>
|
||||
|
||||
<div style={{ marginBottom: "var(--space-md)" }}>
|
||||
<div style={{ display: "flex", gap: 4, alignItems: "center" }}>
|
||||
<input
|
||||
type="password"
|
||||
value={licenseInput}
|
||||
placeholder="eyJhbGciOiJSUzI1NiI..."
|
||||
onChange={(e) => setLicenseInput(e.target.value)}
|
||||
style={{
|
||||
...keyInputStyle,
|
||||
border: `1px solid ${licenseStatus === "valid" ? "rgba(34,197,94,0.5)" : licenseStatus === "invalid" ? "rgba(239,68,68,0.5)" : "var(--border-subtle)"}`
|
||||
}}
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
/>
|
||||
<StatusIcon status={licenseStatus} />
|
||||
<button
|
||||
onClick={handleVerifyLicense}
|
||||
disabled={!licenseInput || licenseStatus === "verifying"}
|
||||
title="Verify license"
|
||||
style={{
|
||||
...toggleBtnStyle,
|
||||
color: licenseStatus === "valid" ? "#22c55e" : licenseStatus === "invalid" ? "#ef4444" : "var(--text-muted)",
|
||||
opacity: (!licenseInput || licenseStatus === "verifying") ? 0.4 : 1,
|
||||
cursor: (!licenseInput || licenseStatus === "verifying") ? "not-allowed" : "pointer",
|
||||
}}
|
||||
>
|
||||
<ShieldCheck size={14} />
|
||||
</button>
|
||||
{licenseInput && (
|
||||
<button
|
||||
style={toggleBtnStyle}
|
||||
onClick={handleClearLicense}
|
||||
title="Clear License"
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{licenseStatus === "invalid" && licenseError && (
|
||||
<div style={{ fontSize: 10, color: "#ef4444", marginTop: 3 }}>{licenseError}</div>
|
||||
)}
|
||||
{licenseStatus === "valid" && (
|
||||
<div style={{ fontSize: 10, color: "#22c55e", marginTop: 3 }}>License verified ✓</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ marginBottom: "var(--space-lg)" }}>
|
||||
<div style={sectionHeaderStyle}>
|
||||
<Key size={10} style={{ marginRight: 4, verticalAlign: "middle" }} />
|
||||
Your API Keys
|
||||
</div>
|
||||
<div style={{ fontSize: 11, color: "var(--text-muted)", marginBottom: "var(--space-md)" }}>
|
||||
Optional — if set, your key is used instead of the shared default.
|
||||
Keys are stored only in your browser.
|
||||
</div>
|
||||
|
||||
{API_KEY_REGISTRY.map((entry) => {
|
||||
const st = status[entry.service] ?? "idle";
|
||||
const err = errors[entry.service];
|
||||
const borderColor =
|
||||
st === "valid" ? "rgba(34,197,94,0.5)"
|
||||
: st === "invalid" ? "rgba(239,68,68,0.5)"
|
||||
: "var(--border-subtle)";
|
||||
|
||||
return (
|
||||
<div key={entry.service} style={{ marginBottom: "var(--space-md)" }}>
|
||||
<div style={{ ...inputGroupStyle, marginBottom: "var(--space-xs)" }}>
|
||||
<label style={labelStyle}>{entry.label}</label>
|
||||
</div>
|
||||
<div style={{ display: "flex", gap: 4, alignItems: "center" }}>
|
||||
<input
|
||||
type={visible[entry.service] ? "text" : "password"}
|
||||
value={keys[entry.service]}
|
||||
placeholder={entry.placeholder}
|
||||
onChange={(e) => handleChange(entry.service, e.target.value)}
|
||||
style={{ ...keyInputStyle, border: `1px solid ${borderColor}` }}
|
||||
spellCheck={false}
|
||||
autoComplete="new-password"
|
||||
data-form-type="other"
|
||||
data-lpignore="true"
|
||||
name={`wwv-apikey-${entry.service}`}
|
||||
/>
|
||||
<StatusIcon status={st} />
|
||||
<button
|
||||
onClick={() => handleManualVerify(entry.service)}
|
||||
disabled={!keys[entry.service] || keys[entry.service].length < MIN_KEY_LENGTH || st === "verifying"}
|
||||
title="Verify key"
|
||||
style={{
|
||||
...toggleBtnStyle,
|
||||
color: st === "valid" ? "#22c55e" : st === "invalid" ? "#ef4444" : "var(--text-muted)",
|
||||
opacity: (!keys[entry.service] || keys[entry.service].length < MIN_KEY_LENGTH || st === "verifying") ? 0.4 : 1,
|
||||
cursor: (!keys[entry.service] || keys[entry.service].length < MIN_KEY_LENGTH || st === "verifying") ? "not-allowed" : "pointer",
|
||||
}}
|
||||
>
|
||||
<ShieldCheck size={14} />
|
||||
</button>
|
||||
<button
|
||||
style={toggleBtnStyle}
|
||||
onClick={() => toggleVisibility(entry.service)}
|
||||
title={visible[entry.service] ? "Hide" : "Show"}
|
||||
>
|
||||
{visible[entry.service] ? <EyeOff size={14} /> : <Eye size={14} />}
|
||||
</button>
|
||||
</div>
|
||||
{st === "invalid" && err && (
|
||||
<div style={{ fontSize: 10, color: "#ef4444", marginTop: 3 }}>{err}</div>
|
||||
)}
|
||||
{st === "valid" && (
|
||||
<div style={{ fontSize: 10, color: "#22c55e", marginTop: 3 }}>Key verified ✓</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{hasAnyKey && (
|
||||
<button
|
||||
onClick={handleClearAll}
|
||||
style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 6,
|
||||
background: "rgba(239, 68, 68, 0.1)",
|
||||
color: "#ef4444",
|
||||
border: "1px solid rgba(239, 68, 68, 0.3)",
|
||||
borderRadius: "var(--radius-sm)",
|
||||
padding: "var(--space-xs) var(--space-sm)",
|
||||
fontSize: 12,
|
||||
cursor: "pointer",
|
||||
width: "100%",
|
||||
justifyContent: "center",
|
||||
}}
|
||||
>
|
||||
<Trash2 size={12} />
|
||||
Clear All Keys
|
||||
</button>
|
||||
)}
|
||||
|
||||
{needsReload && <ReloadToast message="Google Maps API Key validated. Reload to apply." />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -4,13 +4,12 @@ import { useEffect, useRef, useState } from "react";
|
||||
import { useStore } from "@/core/state/store";
|
||||
import { dataBus } from "@/core/data/DataBus";
|
||||
import { pluginManager } from "@/core/plugins/PluginManager";
|
||||
import { Globe,Key } from "lucide-react";
|
||||
import { Globe } from "lucide-react";
|
||||
import { trackEvent } from "@/lib/analytics";
|
||||
import { isDemo, DEMO_ADMIN_ROLE } from "@/core/edition";
|
||||
|
||||
import { SearchBar } from "./SearchBar";
|
||||
import { useIsMobile } from "@/core/hooks/useIsMobile";
|
||||
import { ApiKeysTab } from "./ApiKeysTab";
|
||||
|
||||
const REGIONS = [
|
||||
{ id: "global", label: "Global", icon: Globe },
|
||||
@@ -32,7 +31,6 @@ export function Header() {
|
||||
|
||||
const scrollContainerRef = useRef<HTMLDivElement>(null);
|
||||
const [isDemoAdmin, setIsDemoAdmin] = useState(false);
|
||||
const [showApiKeys, setShowApiKeys] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isDemo) return;
|
||||
@@ -75,7 +73,7 @@ export function Header() {
|
||||
</div>
|
||||
|
||||
<div className="header__actions">
|
||||
|
||||
|
||||
<div className="status-badge">
|
||||
<span className="status-badge__dot" />
|
||||
LIVE
|
||||
@@ -87,7 +85,6 @@ export function Header() {
|
||||
|
||||
// Desktop: full header
|
||||
return (
|
||||
<>
|
||||
<header className="header glass-panel">
|
||||
<div className="header__brand">
|
||||
<a href="https://worldwideview.dev/" target="_blank" rel="noopener noreferrer" style={{ textDecoration: "none", color: "inherit", cursor: "pointer" }}>
|
||||
@@ -121,44 +118,25 @@ export function Header() {
|
||||
</button>
|
||||
))}
|
||||
<div style={{ width: 1, height: 20, background: "var(--border-subtle)", flexShrink: 0 }} />
|
||||
<button
|
||||
className="btn btn--glow"
|
||||
onClick={() => setShowApiKeys(true)}
|
||||
title="API Keys"
|
||||
style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: "6px",
|
||||
}}
|
||||
>
|
||||
<Key size={14} />
|
||||
</button>
|
||||
<div style={{ width: 1, height: 20, background: "var(--border-subtle)", flexShrink: 0 }} />
|
||||
<select
|
||||
id="time"
|
||||
className="btn"
|
||||
value={timeWindow}
|
||||
onChange={(e) => {
|
||||
const tw = e.target.value as typeof TIME_WINDOWS[number];
|
||||
|
||||
setTimeWindow(tw);
|
||||
|
||||
const range = useStore.getState().timeRange;
|
||||
pluginManager.updateTimeRange(range);
|
||||
|
||||
trackEvent("time-window-change", { window: tw });
|
||||
}}
|
||||
style={{ flexShrink: 0 }}
|
||||
>
|
||||
{TIME_WINDOWS.map((tw) => (
|
||||
<option key={tw} value={tw}>
|
||||
{tw}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{TIME_WINDOWS.map((tw) => (
|
||||
<button
|
||||
key={tw}
|
||||
className={`btn ${timeWindow === tw ? "btn--active" : ""}`}
|
||||
style={{ flexShrink: 0 }}
|
||||
onClick={() => {
|
||||
setTimeWindow(tw);
|
||||
const range = useStore.getState().timeRange;
|
||||
pluginManager.updateTimeRange(range);
|
||||
trackEvent("time-window-change", { window: tw });
|
||||
}}
|
||||
>
|
||||
{tw}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="header__actions">
|
||||
<div style={{ width: 1, height: 20, background: "var(--border-subtle)" }} />
|
||||
|
||||
<div className="status-badge">
|
||||
<span className="status-badge__dot" />
|
||||
LIVE
|
||||
@@ -166,57 +144,5 @@ export function Header() {
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
{showApiKeys && (
|
||||
<div
|
||||
style={{
|
||||
position: "fixed",
|
||||
inset: 0,
|
||||
background: "rgba(0,0,0,0.45)",
|
||||
display: "flex",
|
||||
alignItems: "flex-start",
|
||||
justifyContent: "center",
|
||||
paddingTop: "5vh",
|
||||
paddingBottom: "5vh",
|
||||
overflowY: "auto",
|
||||
zIndex: 9999,
|
||||
}}
|
||||
onClick={() => setShowApiKeys(false)}
|
||||
>
|
||||
<div
|
||||
className="glass-panel"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
style={{
|
||||
width: "min(700px, 90vw)",
|
||||
maxHeight: "80vh",
|
||||
overflowY: "auto",
|
||||
padding: "24px",
|
||||
borderRadius: "16px",
|
||||
margin: "20px",
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
marginBottom: "16px",
|
||||
}}
|
||||
>
|
||||
<h2 style={{ margin: 0 }}>API Keys</h2>
|
||||
|
||||
<button
|
||||
className="btn"
|
||||
onClick={() => setShowApiKeys(false)}
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<ApiKeysTab />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
|
||||
}
|
||||
@@ -3,7 +3,6 @@ import { pluginManager } from "@/core/plugins/PluginManager";
|
||||
import { sectionHeaderStyle, inputGroupStyle, labelStyle, inputStyle, checkboxStyle } from "./sharedStyles";
|
||||
import { PluginErrorBoundary } from "@/components/common/PluginErrorBoundary";
|
||||
|
||||
|
||||
export function OverlayTab() {
|
||||
const dataConfig = useStore((s) => s.dataConfig);
|
||||
const updateDataConfig = useStore((s) => s.updateDataConfig);
|
||||
@@ -100,48 +99,11 @@ export function OverlayTab() {
|
||||
</div>
|
||||
|
||||
<div style={{ marginBottom: "var(--space-lg)" }}>
|
||||
<div style={sectionHeaderStyle}>Cache & Limits</div>
|
||||
|
||||
<div style={inputGroupStyle}>
|
||||
<label style={labelStyle}>Enable Cache</label>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={dataConfig.cacheEnabled}
|
||||
onChange={(e) => updateDataConfig({ cacheEnabled: e.target.checked })}
|
||||
style={checkboxStyle}
|
||||
/>
|
||||
<div style={sectionHeaderStyle}>Map Overlays</div>
|
||||
<div style={{ fontSize: 12, color: "var(--text-secondary)" }}>
|
||||
Map overlays such as Borders & Labels can now be found in the Layers Panel.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={inputGroupStyle}>
|
||||
<label style={labelStyle}>Cache Max Age (ms)</label>
|
||||
<input
|
||||
type="number"
|
||||
value={dataConfig.cacheMaxAge}
|
||||
onChange={(e) => updateDataConfig({ cacheMaxAge: parseInt(e.target.value) || 0 })}
|
||||
style={inputStyle}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div style={inputGroupStyle}>
|
||||
<label style={labelStyle}>Max Concurrent Req</label>
|
||||
<input
|
||||
type="number"
|
||||
value={dataConfig.maxConcurrentRequests}
|
||||
onChange={(e) => updateDataConfig({ maxConcurrentRequests: parseInt(e.target.value) || 0 })}
|
||||
style={inputStyle}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div style={inputGroupStyle}>
|
||||
<label style={labelStyle}>Retry Attempts</label>
|
||||
<input
|
||||
type="number"
|
||||
value={dataConfig.retryAttempts}
|
||||
onChange={(e) => updateDataConfig({ retryAttempts: parseInt(e.target.value) || 0 })}
|
||||
style={inputStyle}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import { useResizablePanel } from "@/core/hooks/useResizablePanel";
|
||||
import { IntelTab } from "./IntelTab";
|
||||
import { CacheTab } from "./CacheTab";
|
||||
import { OverlayTab } from "./OverlayTab";
|
||||
import { ApiKeysTab } from "./ApiKeysTab";
|
||||
import { sectionHeaderStyle } from "./sharedStyles";
|
||||
|
||||
export function DataConfigPanel() {
|
||||
@@ -56,30 +57,37 @@ export function DataConfigPanel() {
|
||||
className={`panel-tab ${activeTab === "intel" ? "panel-tab--active" : ""}`}
|
||||
onClick={() => setActiveTab("intel")}
|
||||
>
|
||||
<Info size={15} style={{ marginRight: 4 }} />
|
||||
<div style={{fontSize: "13px"}}>
|
||||
Intel
|
||||
</div>
|
||||
<Info size={12} style={{ marginRight: 4 }} />
|
||||
Intel
|
||||
</button>
|
||||
<button
|
||||
className={`panel-tab ${activeTab === "filters" ? "panel-tab--active" : ""}`}
|
||||
onClick={() => setActiveTab("filters")}
|
||||
>
|
||||
<div style={{fontSize: "13px"}}>
|
||||
Filters
|
||||
</div>
|
||||
Filters
|
||||
</button>
|
||||
<button
|
||||
className={`panel-tab ${activeTab === "cache" ? "panel-tab--active" : ""}`}
|
||||
onClick={() => setActiveTab("cache")}
|
||||
>
|
||||
Cache & Limits
|
||||
</button>
|
||||
<button
|
||||
className={`panel-tab ${activeTab === "overlay" ? "panel-tab--active" : ""}`}
|
||||
onClick={() => setActiveTab("overlay")}
|
||||
>
|
||||
<div style={{fontSize: "13px"}}>
|
||||
Config & Overlay
|
||||
</div>
|
||||
Config & Overlay
|
||||
</button>
|
||||
<button
|
||||
className={`panel-tab ${activeTab === "apikeys" ? "panel-tab--active" : ""}`}
|
||||
onClick={() => setActiveTab("apikeys")}
|
||||
>
|
||||
<Key size={12} style={{ marginRight: 4 }} />
|
||||
API Keys
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div style={{ flex: 1, overflowY: "auto", minHeight: 50, display: "flex", flexDirection: "column", paddingRight: "var(--space-xs)" }}>
|
||||
<div style={{ flex: 1, overflowY: "auto", minHeight: 0, display: "flex", flexDirection: "column", paddingRight: "var(--space-xs)" }}>
|
||||
{activeTab === "intel" && (
|
||||
<div style={{ marginBottom: "var(--space-lg)" }}>
|
||||
<div style={sectionHeaderStyle}>Intelligence</div>
|
||||
@@ -93,7 +101,10 @@ export function DataConfigPanel() {
|
||||
<FilterSection />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === "cache" && <CacheTab />}
|
||||
{activeTab === "overlay" && <OverlayTab />}
|
||||
{activeTab === "apikeys" && <ApiKeysTab />}
|
||||
</div>
|
||||
|
||||
<button
|
||||
|
||||
@@ -36,8 +36,6 @@ export function LayerPanel() {
|
||||
// Group by category
|
||||
const grouped: Record<string, typeof allPlugins> = {};
|
||||
const query = searchQuery.toLowerCase();
|
||||
|
||||
|
||||
|
||||
allPlugins.forEach((managed) => {
|
||||
if (
|
||||
@@ -98,7 +96,6 @@ export function LayerPanel() {
|
||||
};
|
||||
|
||||
const [activeTab, setActiveTab] = useState<"layers" | "imagery" | "favorites" | "import" | "plugins">("layers");
|
||||
const fontSize = "13px";
|
||||
|
||||
return (
|
||||
<aside
|
||||
@@ -133,42 +130,31 @@ export function LayerPanel() {
|
||||
className={`panel-tab ${activeTab === "layers" ? "panel-tab--active" : ""}`}
|
||||
onClick={() => { setActiveTab("layers"); trackEvent("panel-tab-switch", { tab: "layers" }); }}
|
||||
>
|
||||
<div style={{fontSize: fontSize}}>
|
||||
Data Layers
|
||||
</div>
|
||||
Data Layers
|
||||
</button>
|
||||
<button
|
||||
className={`panel-tab ${activeTab === "imagery" ? "panel-tab--active" : ""}`}
|
||||
onClick={() => { setActiveTab("imagery"); trackEvent("panel-tab-switch", { tab: "imagery" }); }}
|
||||
>
|
||||
<div style={{fontSize: fontSize}}>
|
||||
Imagery
|
||||
</div>
|
||||
|
||||
Imagery
|
||||
</button>
|
||||
<button
|
||||
className={`panel-tab ${activeTab === "favorites" ? "panel-tab--active" : ""}`}
|
||||
onClick={() => { setActiveTab("favorites"); trackEvent("panel-tab-switch", { tab: "favorites" }); }}
|
||||
>
|
||||
<div style={{fontSize: fontSize}}>
|
||||
Favorites
|
||||
</div>
|
||||
Favorites
|
||||
</button>
|
||||
<button
|
||||
className={`panel-tab ${activeTab === "import" ? "panel-tab--active" : ""}`}
|
||||
onClick={() => { setActiveTab("import"); trackEvent("panel-tab-switch", { tab: "import" }); }}
|
||||
>
|
||||
<div style={{fontSize: fontSize}}>
|
||||
Import
|
||||
</div>
|
||||
Import
|
||||
</button>
|
||||
<button
|
||||
className={`panel-tab ${activeTab === "plugins" ? "panel-tab--active" : ""}`}
|
||||
onClick={() => { setActiveTab("plugins"); trackEvent("panel-tab-switch", { tab: "plugins" }); }}
|
||||
>
|
||||
<div style={{fontSize: fontSize}}>
|
||||
Plugins
|
||||
</div>
|
||||
Plugins
|
||||
</button>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -162,10 +162,10 @@
|
||||
.plugins-tab__browse {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
gap: 4px;
|
||||
gap: var(--space-sm);
|
||||
padding: var(--space-md) var(--space-lg);
|
||||
margin-top: var(--space-md);
|
||||
background: linear-gradient(
|
||||
135deg,
|
||||
rgba(var(--accent-rgb), 0.1),
|
||||
@@ -179,9 +179,7 @@
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all var(--duration-fast) var(--ease-smooth);
|
||||
flex-shrink: 0%;
|
||||
width: 100%;
|
||||
min-height: 25%;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.plugins-tab__browse:hover {
|
||||
@@ -199,21 +197,17 @@
|
||||
.plugins-tab__actions-bottom {
|
||||
margin-top: auto;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
flex-direction: column;
|
||||
gap: var(--space-sm);
|
||||
justify-content: stretch;
|
||||
padding-top: var(--space-md);
|
||||
}
|
||||
|
||||
.plugins-tab__actions-bottom > * {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.plugins-tab__update-all {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 4px;
|
||||
gap: var(--space-sm);
|
||||
padding: var(--space-sm) var(--space-md);
|
||||
background: rgba(var(--accent-rgb), 0.15);
|
||||
border: 1px solid rgba(var(--accent-rgb), 0.3);
|
||||
@@ -224,9 +218,7 @@
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all var(--duration-fast) var(--ease-smooth);
|
||||
flex-shrink: 0%;
|
||||
width: 100%;
|
||||
min-height: 25%;
|
||||
}
|
||||
|
||||
.plugins-tab__update-all:hover {
|
||||
@@ -241,10 +233,9 @@
|
||||
|
||||
.plugins-tab__check-updates {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 4px;
|
||||
gap: var(--space-sm);
|
||||
padding: var(--space-sm) var(--space-md);
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
|
||||
@@ -54,7 +54,7 @@ function BrowseLink() {
|
||||
onClick={() => trackEvent("marketplace-browse-click")}
|
||||
>
|
||||
<ExternalLink size={14} />
|
||||
Marketplace
|
||||
Browse Marketplace
|
||||
</a>
|
||||
);
|
||||
}
|
||||
@@ -309,8 +309,6 @@ export function PluginsTab() {
|
||||
|
||||
{canInstall && (
|
||||
<div className="plugins-tab__actions-bottom">
|
||||
<BrowseLink />
|
||||
|
||||
<button
|
||||
className="plugins-tab__check-updates"
|
||||
onClick={handleCheckUpdates}
|
||||
@@ -319,7 +317,7 @@ export function PluginsTab() {
|
||||
<RefreshCw size={14} className={checkingUpdates ? "spinning" : ""} />
|
||||
{checkingUpdates ? "Checking..." : "Check for Updates"}
|
||||
</button>
|
||||
|
||||
|
||||
{Object.keys(updates).length > 1 && (
|
||||
<button
|
||||
className="plugins-tab__update-all"
|
||||
@@ -332,6 +330,8 @@ export function PluginsTab() {
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<BrowseLink />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -24,10 +24,6 @@ export const CameraStream: React.FC<CameraStreamProps> = ({
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [hlsFailed, setHlsFailed] = useState(false);
|
||||
const [activeStreamUrl, setActiveStreamUrl] = useState(streamUrl);
|
||||
// Cache-buster tick that increments every JPEG_REFRESH_MS while playing,
|
||||
// so static-image / MJPEG sources actually feel "live" instead of freezing
|
||||
// on the first frame the browser cached.
|
||||
const [imgRefreshTick, setImgRefreshTick] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
setIsPlaying(false); setError(null); setIsLoading(false); setHlsFailed(false);
|
||||
@@ -67,24 +63,6 @@ export const CameraStream: React.FC<CameraStreamProps> = ({
|
||||
e?.stopPropagation(); setError(null); setIsLoading(true); setIsPlaying(true);
|
||||
};
|
||||
|
||||
// For JPEG / MJPEG / static-image sources, re-fetch every JPEG_REFRESH_MS
|
||||
// by bumping a cache-buster query param. Skip for HLS / iframe / known
|
||||
// video platforms — they manage their own playback. Cleared when the
|
||||
// stream stops (handleStop sets isPlaying false → effect cleanup runs).
|
||||
const JPEG_REFRESH_MS = 10_000;
|
||||
const isImageSource =
|
||||
!isHlsUrl(activeStreamUrl) &&
|
||||
!isIframe &&
|
||||
!isKnownVideoPlatform(activeStreamUrl);
|
||||
useEffect(() => {
|
||||
if (!isPlaying || !isImageSource) return;
|
||||
const t = setInterval(
|
||||
() => setImgRefreshTick((v) => v + 1),
|
||||
JPEG_REFRESH_MS,
|
||||
);
|
||||
return () => clearInterval(t);
|
||||
}, [isPlaying, isImageSource]);
|
||||
|
||||
const handleStop = (e?: React.MouseEvent) => {
|
||||
e?.stopPropagation(); setIsPlaying(false); setIsLoading(false); setError(null); setHlsFailed(false);
|
||||
};
|
||||
@@ -126,19 +104,13 @@ export const CameraStream: React.FC<CameraStreamProps> = ({
|
||||
);
|
||||
}
|
||||
|
||||
// Fallback: static image / MJPEG snapshot (proxy HTTP→HTTPS if needed).
|
||||
// When HLS failed and a preview JPEG exists, show that instead.
|
||||
// Fallback: static image / MJPEG snapshot (proxy HTTP→HTTPS if needed)
|
||||
// When HLS failed and a preview JPEG exists, show that instead
|
||||
const fallbackUrl = hlsFailed && previewUrl ? previewUrl : activeStreamUrl;
|
||||
const resolvedUrl = getProxiedStreamUrl(fallbackUrl);
|
||||
// Cache-bust the URL on every refresh tick so the browser actually
|
||||
// re-fetches instead of serving the same frame from disk cache.
|
||||
const sep = resolvedUrl.includes("?") ? "&" : "?";
|
||||
const refreshedUrl = imgRefreshTick > 0
|
||||
? `${resolvedUrl}${sep}_t=${imgRefreshTick}`
|
||||
: resolvedUrl;
|
||||
return (
|
||||
<img
|
||||
src={refreshedUrl}
|
||||
src={resolvedUrl}
|
||||
alt={label || "Live camera stream"}
|
||||
style={{ maxWidth: "100%", maxHeight: "100%", objectFit: "contain" }}
|
||||
onLoad={() => setIsLoading(false)}
|
||||
|
||||
@@ -50,20 +50,6 @@ class PluginManager {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Next.js inlines `process.env.NEXT_PUBLIC_*` only at known static
|
||||
// reference sites. The iteration above can come back empty in the
|
||||
// browser bundle even when NEXT_PUBLIC_WWV_PLUGIN_* is set at build,
|
||||
// because `Object.entries(process.env)` is not a static reference and
|
||||
// the bundler doesn't expose every NEXT_PUBLIC_ key on the runtime
|
||||
// object. Add explicit static references so the values reach plugin
|
||||
// contexts. Add new known keys here as they're introduced.
|
||||
const explicitVars: Record<string, string | undefined> = {
|
||||
DATA_ENGINE_URL: process.env.NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL,
|
||||
};
|
||||
for (const [k, v] of Object.entries(explicitVars)) {
|
||||
if (v && !envVars[k]) envVars[k] = v;
|
||||
}
|
||||
|
||||
const edition = (process.env.NEXT_PUBLIC_WWV_EDITION || "local") as "local" | "cloud" | "demo";
|
||||
|
||||
|
||||
+1
-11
@@ -103,20 +103,10 @@ export default async function proxy(req: NextRequest) {
|
||||
}
|
||||
}
|
||||
|
||||
// Check JWT session from Auth.js cookie.
|
||||
// Behind a TLS-terminating reverse proxy, the cookie was set with the
|
||||
// `__Secure-` prefix (because the public URL is https), but the request
|
||||
// reaching us is plain http, so getToken's auto-detection looks for the
|
||||
// unprefixed name and misses it. Detect via X-Forwarded-Proto / AUTH_URL.
|
||||
const xfProto = req.headers.get("x-forwarded-proto");
|
||||
const authUrl = process.env.AUTH_URL ?? process.env.NEXTAUTH_URL ?? "";
|
||||
const isSecure = xfProto === "https"
|
||||
|| authUrl.startsWith("https://")
|
||||
|| req.nextUrl.protocol === "https:";
|
||||
// Check JWT session from Auth.js cookie
|
||||
const token = await getToken({
|
||||
req,
|
||||
secret: process.env.AUTH_SECRET,
|
||||
secureCookie: isSecure,
|
||||
});
|
||||
|
||||
if (token) {
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
|
||||
services:
|
||||
app:
|
||||
image: alpine
|
||||
command: echo "app running"
|
||||
db:
|
||||
image: alpine
|
||||
command: echo "db running"
|
||||
profiles: ["${DB_PROFILE:-}"]
|
||||
|
||||
Reference in new issue
Block a user