Compare commits
348
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f49a2e0a0a | ||
|
|
2aad665096 | ||
|
|
08645699f3 | ||
|
|
f5e8d25fe2 | ||
|
|
b2fcc57d19 | ||
|
|
91744aeaef | ||
|
|
0ab72867b0 | ||
|
|
7d85d56e53 | ||
|
|
3baed783b1 | ||
|
|
ed1fa39cff | ||
|
|
40eac1a0cb | ||
|
|
d277a018ee | ||
|
|
163fcb475e | ||
|
|
903267cf3c | ||
|
|
18f0641595 | ||
|
|
be18c0a412 | ||
|
|
94fde6e660 | ||
|
|
c81f3925c6 | ||
|
|
921dba0bf1 | ||
|
|
138ea6c721 | ||
|
|
dc10e8ad5c | ||
|
|
84f694f93b | ||
|
|
fa60f845c1 | ||
|
|
6e3a8ab625 | ||
|
|
34f85f6e57 | ||
|
|
0e0a8d6bad | ||
|
|
0785b29462 | ||
|
|
344e83376b | ||
|
|
150702d33f | ||
|
|
739bffa05b | ||
|
|
9888f11a4b | ||
|
|
7354b414e7 | ||
|
|
196380c0af | ||
|
|
06e919639d | ||
|
|
f948f2aaab | ||
|
|
a5125dba7b | ||
|
|
21a6c618c8 | ||
|
|
48a17bf3ee | ||
|
|
2e4c074f77 | ||
|
|
e2108f5049 | ||
|
|
b76067c0bb | ||
|
|
04e614e1ed | ||
|
|
0d14a63246 | ||
|
|
781fe9e790 | ||
|
|
f0c2d81e18 | ||
|
|
f86b7d1e94 | ||
|
|
28704e6fe1 | ||
|
|
01e291a40e | ||
|
|
909e150b3d | ||
|
|
1fe3a77383 | ||
|
|
998f98851e | ||
|
|
9c51cdb8a2 | ||
|
|
d74ae694a4 | ||
|
|
ec4c89fe51 | ||
|
|
44e8ff9b70 | ||
|
|
cc90d3c2a3 | ||
|
|
0e6268bf72 | ||
|
|
764af74d14 | ||
|
|
29269c668a | ||
|
|
c60a0c9d56 | ||
|
|
05b2dce394 | ||
|
|
390518be0f | ||
|
|
e07bc60672 | ||
|
|
d75618f9aa | ||
|
|
aa34e1c49d | ||
|
|
2f618ce2cf | ||
|
|
085f4aa90c | ||
|
|
c1ddb91268 | ||
|
|
b3bc62ad8e | ||
|
|
32a4df4952 | ||
|
|
3ac36446bf | ||
|
|
ac95a64115 | ||
|
|
1d07698df7 | ||
|
|
583622f091 | ||
|
|
bfdbd0313d | ||
|
|
a70f93af0a | ||
|
|
26970e6adc | ||
|
|
63bc49949a | ||
|
|
ce45f2d4b6 | ||
|
|
bec1080cb8 | ||
|
|
ed4826484c | ||
|
|
77e6bf1d55 | ||
|
|
fa6413e953 | ||
|
|
53a9931e94 | ||
|
|
055ead345a | ||
|
|
89c247e913 | ||
|
|
df7df20c46 | ||
|
|
b738072e05 | ||
|
|
414ac3b194 | ||
|
|
f3b48ac302 | ||
|
|
bea39455e6 | ||
|
|
1a984251b6 | ||
|
|
67ca2abdbc | ||
|
|
b10e7d0a7f | ||
|
|
6be56b9966 | ||
|
|
4951a2d047 | ||
|
|
3fa1aeb80c | ||
|
|
c6b27a6079 | ||
|
|
c8c619210f | ||
|
|
01f923b806 | ||
|
|
487cb46f03 | ||
|
|
d05f93e610 | ||
|
|
701b7b3b23 | ||
|
|
1eff015bbb | ||
|
|
84129f1d9e | ||
|
|
60dbc5af66 | ||
|
|
8abc2ea2ef | ||
|
|
76243e08c0 | ||
|
|
57d6bbbe02 | ||
|
|
e1910011aa | ||
|
|
f81d9315e0 | ||
|
|
48cf43e68d | ||
|
|
f30a539ebf | ||
|
|
57a602eb60 | ||
|
|
a2c8dd2f55 | ||
|
|
f272a9a617 | ||
|
|
8fe71c637d | ||
|
|
aee5154eaf | ||
|
|
ae8c422c2f | ||
|
|
e61928b2a1 | ||
|
|
7749804365 | ||
|
|
c115058008 | ||
|
|
86c97ec191 | ||
|
|
b5b925dd06 | ||
|
|
7488677f7a | ||
|
|
14a8bf5369 | ||
|
|
96e4a1c591 | ||
|
|
6cb6dfd1d6 | ||
|
|
c31871b321 | ||
|
|
245118412f | ||
|
|
a75a4f0f9a | ||
|
|
f8664d8255 | ||
|
|
dad91079b2 | ||
|
|
273112424c | ||
|
|
9cc51f483a | ||
|
|
0adef65616 | ||
|
|
5b2b8a0a8d | ||
|
|
f33e7efb8d | ||
|
|
425dcbbc8e | ||
|
|
484104a2b0 | ||
|
|
7e34ab6da0 | ||
|
|
5b45d79790 | ||
|
|
7684d23398 | ||
|
|
a5610f0c8d | ||
|
|
4d178544e5 | ||
|
|
8a58f4a732 | ||
|
|
026eaae074 | ||
|
|
6515b43711 | ||
|
|
94a0ca4731 | ||
|
|
de60ed3ffe | ||
|
|
f5898b253a | ||
|
|
561a44fe77 | ||
|
|
b431fc526a | ||
|
|
3deefc9607 | ||
|
|
20363d509b | ||
|
|
134c3a5443 | ||
|
|
ab4cb2553a | ||
|
|
3bc3b3461f | ||
|
|
11a75b6458 | ||
|
|
62b8436353 | ||
|
|
875eda7ea2 | ||
|
|
82246daab0 | ||
|
|
7513ff9dfa | ||
|
|
96b032c2d0 | ||
|
|
de4f77d250 | ||
|
|
7c59ba4dc3 | ||
|
|
951e070466 | ||
|
|
adadce06b1 | ||
|
|
2341409bb4 | ||
|
|
7fee8e9fcf | ||
|
|
682c21296c | ||
|
|
aec6f20edc | ||
|
|
c89b55884f | ||
|
|
ded3ae9416 | ||
|
|
0808326967 | ||
|
|
889bd5aade | ||
|
|
a17aafa6f6 | ||
|
|
18da3a492c | ||
|
|
2fd3f84b2f | ||
|
|
68d350572f | ||
|
|
7660e707f7 | ||
|
|
f510c7de34 | ||
|
|
35e9e7d70d | ||
|
|
74f3793313 | ||
|
|
913e25ccac | ||
|
|
2ec151c68b | ||
|
|
cf49eef883 | ||
|
|
b56dacf04f | ||
|
|
22bb77492e | ||
|
|
ca1447f26a | ||
|
|
7f1bf00ef7 | ||
|
|
aeb9ddb96b | ||
|
|
3852e1175d | ||
|
|
1474e28de0 | ||
|
|
8a5ace61b2 | ||
|
|
932713e7a2 | ||
|
|
50228a43c8 | ||
|
|
326c69e92f | ||
|
|
e3225d4dab | ||
|
|
23d1538ea2 | ||
|
|
5f89715ee6 | ||
|
|
22f22ead37 | ||
|
|
5eff117972 | ||
|
|
b92e5b3683 | ||
|
|
b79f0f025d | ||
|
|
f40615ee21 | ||
|
|
222ae0950e | ||
|
|
afe89f8c0e | ||
|
|
867e495353 | ||
|
|
6263f7766b | ||
|
|
d65600786f | ||
|
|
a3a04d84c0 | ||
|
|
f295609ea2 | ||
|
|
80064996e9 | ||
|
|
973bef6386 | ||
|
|
4e2287aa5f | ||
|
|
17b8c7bb62 | ||
|
|
d10c68004a | ||
|
|
10830efca5 | ||
|
|
c3d9b2b536 | ||
|
|
3a04c64e79 | ||
|
|
eea424a826 | ||
|
|
4edcce2468 | ||
|
|
d54d9a480c | ||
|
|
b7d76b5e58 | ||
|
|
e83e45e8b9 | ||
|
|
86b7550c38 | ||
|
|
09b4b44c3e | ||
|
|
c6b26d20bc | ||
|
|
36ee84857b | ||
|
|
25b19ec635 | ||
|
|
614d3af796 | ||
|
|
bc05d93ce8 | ||
|
|
c0789f831c | ||
|
|
3be23a3ebc | ||
|
|
abd40ede1b | ||
|
|
c7d980390d | ||
|
|
aab5e39aa3 | ||
|
|
05bc8856f6 | ||
|
|
562a53e853 | ||
|
|
419744e64b | ||
|
|
b008537694 | ||
|
|
11919731d2 | ||
|
|
2a285312b0 | ||
|
|
027672d885 | ||
|
|
e016342dea | ||
|
|
a56e2b6340 | ||
|
|
b1fa384476 | ||
|
|
efa886ad3e | ||
|
|
3d25b2642a | ||
|
|
ca7125f3ac | ||
|
|
c247e3dde0 | ||
|
|
a25d7ce09b | ||
|
|
1bbd97b382 | ||
|
|
5999ef7d8d | ||
|
|
a764eefcd8 | ||
|
|
f2bd3fecfe | ||
|
|
ee5702f21e | ||
|
|
c4e9dd3951 | ||
|
|
2e928d2d64 | ||
|
|
8ec9465274 | ||
|
|
de40d79662 | ||
|
|
853c173c37 | ||
|
|
fcef4d46fa | ||
|
|
3e8a54a541 | ||
|
|
5c97ceaa64 | ||
|
|
9312c40862 | ||
|
|
52a08dfd7b | ||
|
|
fe1c80e798 | ||
|
|
bce7da4006 | ||
|
|
534ccc03af | ||
|
|
0736b7a051 | ||
|
|
c706d83009 | ||
|
|
6b3f351d38 | ||
|
|
62c333e99a | ||
|
|
e46096dd87 | ||
|
|
48c4045f84 | ||
|
|
c656c86baa | ||
|
|
975c4b1d38 | ||
|
|
38fc546b12 | ||
|
|
66f9d705d7 | ||
|
|
652aa3f94f | ||
|
|
e6995e3a17 | ||
|
|
ba8d031d19 | ||
|
|
4d33d434c0 | ||
|
|
350f70c34f | ||
|
|
0c54d6ca1d | ||
|
|
9a92640469 | ||
|
|
44c05efd95 | ||
|
|
b19ec0af6e | ||
|
|
0a3d7c96ea | ||
|
|
665ad5317c | ||
|
|
5ca9be2070 | ||
|
|
e6dc172871 | ||
|
|
74d61f3e8c | ||
|
|
875e12cb22 | ||
|
|
c773eacceb | ||
|
|
91123ecc1b | ||
|
|
51b7fe01d5 | ||
|
|
f98615e198 | ||
|
|
0d795bf5e8 | ||
|
|
76b7fea27b | ||
|
|
2e93b45927 | ||
|
|
8b7b4204b4 | ||
|
|
5d62ce138a | ||
|
|
706fde7610 | ||
|
|
7db1980e0f | ||
|
|
60a584d03f | ||
|
|
9f9e0fb81a | ||
|
|
665893ef80 | ||
|
|
f5ea9d6432 | ||
|
|
f4c420a665 | ||
|
|
6c6f44cc7e | ||
|
|
c4f32ece18 | ||
|
|
6cfef39e1b | ||
|
|
bccdc6aa26 | ||
|
|
fcdea75bdc | ||
|
|
9748d02820 | ||
|
|
39c7324872 | ||
|
|
53f4a02d07 | ||
|
|
3f6c9bf7c7 | ||
|
|
3df54a8c47 | ||
|
|
1d90209d51 | ||
|
|
f64d5a61ba | ||
|
|
c995716d02 | ||
|
|
899d23e2e5 | ||
|
|
59b0c638c7 | ||
|
|
9e8ea82480 | ||
|
|
3c516ff021 | ||
|
|
e77626d84d | ||
|
|
5f85a1d9e8 | ||
|
|
4845b72cc8 | ||
|
|
3522c7646f | ||
|
|
97188a9c64 | ||
|
|
90b9c029df | ||
|
|
c2722856d8 | ||
|
|
1505b0902b | ||
|
|
83752b96c9 | ||
|
|
9db38cb0de | ||
|
|
522e976739 | ||
|
|
19b521c5ca | ||
|
|
e8e2311422 | ||
|
|
41e2413af4 | ||
|
|
a3e19cecef | ||
|
|
62daafc4a0 | ||
|
|
3f17dd21f8 | ||
|
|
400ac5aa13 | ||
|
|
83d329e407 |
No files matched your search
@@ -0,0 +1,16 @@
|
||||
# Database Migrations & Schema Modification Rules
|
||||
|
||||
## 1. Defensive Migrations
|
||||
When making database schema changes, you must ensure that generated migrations are resilient against environmental discrepancies.
|
||||
|
||||
- **Review Generated SQL**: Always review the `.sql` files generated by `npx prisma migrate dev`.
|
||||
- **Add "IF EXISTS" clauses**: Prisma can sometimes produce brittle drop statements (`DROP INDEX "my_index"`). To prevent migrations from crashing if a state desynchronization occurs, manually edit the migration file to use `DROP INDEX IF EXISTS "my_index";` or `DROP TABLE IF EXISTS "table_name";`.
|
||||
- **Data Preservation**: When dropping columns or renaming, carefully review the migration to ensure data is correctly mapped. In PostgreSQL, ensure that cascaded drops don't accidentally remove required data.
|
||||
|
||||
## 2. Managing Failed Migrations
|
||||
If a migration fails in production:
|
||||
- **Never blindly mark as resolved**: Do not run `prisma migrate resolve --applied <migration_name>` unless you have explicitly verified that the database schema precisely matches the expected state.
|
||||
- If you use `resolve --applied`, Prisma will permanently skip that migration in the future, leaving your database structurally out of sync with your Prisma Client.
|
||||
|
||||
## 3. Backups Before DDL
|
||||
Never perform direct DDL operations (ALTER, DROP, CREATE) on a production database without first confirming an automated backup exists, or manually taking a `pg_dump` backup of the database.
|
||||
@@ -1,95 +0,0 @@
|
||||
---
|
||||
trigger: model_decision
|
||||
description: This is an explanation of the purpose of the project
|
||||
---
|
||||
|
||||
WorldWideView is best described as a modular, real‑time geospatial intelligence engine built on top of a CesiumJS 3D globe, designed to ingest live data streams, transform them through a plugin system, and render them as high‑performance visual layers. The repository you have open shows a Next.js application with a generalized plugin architecture and a Cesium viewer at its core .
|
||||
|
||||
🌍 What WorldWideView fundamentally is
|
||||
WorldWideView is a real‑time situational awareness platform. It takes raw, fast‑moving geospatial signals—like aircraft positions, maritime AIS, satellite orbits, or any other sensor feed—and turns them into interactive, cinematic layers on a 3D globe. The system is built to be:
|
||||
|
||||
Modular, so each data source is a plugin.
|
||||
|
||||
High‑performance, using Cesium primitives instead of entities.
|
||||
|
||||
Extensible, allowing new data types without rewriting the core.
|
||||
|
||||
Real‑time, updating the globe smoothly as new data arrives.
|
||||
|
||||
Visual, using icons, arrows, and 3D models to represent moving objects.
|
||||
|
||||
It’s essentially your own open, customizable version of tools like SkyGlass, ADSBexchange 3D, or WorldView (Bilawal Sidhu’s demo), but engineered for long‑term scalability.
|
||||
|
||||
🧩 Core components of the system
|
||||
Plugin system (your recent commits)
|
||||
Your latest commit message—“generalize plugin system, remove aviation special treatment” —shows that the architecture now treats every data source as a plugin. This means:
|
||||
|
||||
Each plugin defines how it fetches, parses, and visualizes data.
|
||||
|
||||
The core engine doesn’t care whether the plugin is aviation, maritime, satellites, or something else.
|
||||
|
||||
You can add new intelligence layers without touching the core.
|
||||
|
||||
This is a major architectural milestone.
|
||||
|
||||
Cesium rendering engine
|
||||
The project initializes a Cesium globe inside a Next.js app. Cesium handles:
|
||||
|
||||
Globe rendering
|
||||
|
||||
Camera control
|
||||
|
||||
Terrain and imagery layers
|
||||
|
||||
Worker‑based geometry processing
|
||||
|
||||
High‑performance primitives for thousands of objects
|
||||
|
||||
Your open tabs (Cesium picking performance, CZML, map type switching) show you’re actively tuning this layer.
|
||||
|
||||
Real‑time data ingestion
|
||||
The system is designed to ingest live feeds such as:
|
||||
|
||||
ADS‑B aircraft positions
|
||||
|
||||
AIS maritime positions
|
||||
|
||||
Satellite TLE propagation
|
||||
|
||||
Custom sensor networks
|
||||
|
||||
Each plugin transforms raw data into Cesium‑ready primitives.
|
||||
|
||||
Visual representation
|
||||
Your recent work on low‑poly aircraft icons and arrow models shows the platform is moving toward:
|
||||
|
||||
Lightweight, directional markers
|
||||
|
||||
Orientation‑aware icons
|
||||
|
||||
Smooth fly‑to tracking
|
||||
|
||||
Cinematic camera behavior
|
||||
|
||||
This is what gives the platform its “WorldView‑like” feel.
|
||||
|
||||
🚀 What makes WorldWideView unique
|
||||
1. It’s modular from the ground up
|
||||
Most geospatial dashboards hard‑code aviation or maritime logic. You’ve removed that. Any data source can become a plugin.
|
||||
|
||||
2. It’s built for performance
|
||||
You’re migrating from Cesium Entities to Primitives, optimizing picking, and reducing GPU stalls—this is what allows thousands of objects to render smoothly.
|
||||
|
||||
3. It’s designed for real‑time intelligence
|
||||
Not just visualization—actual situational awareness. The architecture supports:
|
||||
|
||||
live updates
|
||||
|
||||
event‑driven pipelines
|
||||
|
||||
time‑dynamic objects
|
||||
|
||||
replay capability (future feature)
|
||||
|
||||
4. It’s open and extensible
|
||||
Unlike proprietary tools, your system can be extended by anyone who writes a plugin.
|
||||
@@ -1,12 +0,0 @@
|
||||
---
|
||||
description: cesium
|
||||
---
|
||||
|
||||
https://cesium.com/
|
||||
https://cesium.com/platform/cesiumjs/
|
||||
https://cesium.com/platform/cesiumjs/ion-sdk/
|
||||
https://sandcastle.cesium.com/?id=czml
|
||||
https://cesium.com/learn/cesiumjs-learn/
|
||||
https://cesium.com/learn/cesiumjs-learn/cesiumjs-camera/
|
||||
https://cesium.com/learn/cesiumjs-learn/cesiumjs-geometry-appearances/
|
||||
https://cesium.com/learn/cesiumjs-learn/cesiumjs-flight-tracker/
|
||||
@@ -0,0 +1,25 @@
|
||||
node_modules
|
||||
**/node_modules
|
||||
**/dist
|
||||
**/.next
|
||||
.git
|
||||
|
||||
# Database files at ANY depth
|
||||
/data
|
||||
packages/*/data
|
||||
**/*.db
|
||||
**/*.sqlite
|
||||
**/*.sqlite3
|
||||
**/*-journal
|
||||
**/*.db-wal
|
||||
**/*.db-shm
|
||||
|
||||
# Environment files
|
||||
.env*
|
||||
!*.env.example
|
||||
|
||||
# Non-build directories
|
||||
artifacts/
|
||||
performance/
|
||||
tmp/
|
||||
*.geojson
|
||||
@@ -0,0 +1,24 @@
|
||||
# PostgreSQL connection string.
|
||||
# For local dev: The platform will automatically spin up PostgreSQL via Docker Compose.
|
||||
# Set DATABASE_URL to: postgresql://postgres:postgres@localhost:5432/worldwideview?schema=public
|
||||
#
|
||||
# For cloud/production: Provide your external Postgres connection string (e.g. Supabase)
|
||||
# and set WWV_SKIP_LOCAL_DB=true to prevent Docker from spinning up a local database instance.
|
||||
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/worldwideview?schema=public
|
||||
|
||||
# Set this to true in production to prevent docker-compose or pnpm run dev from starting the local database.
|
||||
# WWV_SKIP_LOCAL_DB=false
|
||||
|
||||
# Default plugins enabled on boot for demo edition
|
||||
# Comma-separated list of plugin IDs
|
||||
NEXT_PUBLIC_DEMO_DEFAULT_PLUGINS=iranwarlive,satellite,gps-jamming
|
||||
|
||||
# Edition: "local" | "cloud" | "demo"
|
||||
NEXT_PUBLIC_WWV_EDITION=local
|
||||
|
||||
# Auth Secret (REQUIRED for Docker — generate with: openssl rand -hex 32)
|
||||
# Must be stable across container restarts to preserve sessions.
|
||||
# [WARNING] NEVER commit real secrets here. Real secrets must ONLY go into .env.local!
|
||||
AUTH_SECRET=changeme_d64c1f35b447da89cf6ed5a0988da1379b21904edb91a87c3f5a63942e3d23a4_changeme
|
||||
|
||||
|
||||
+50
-4
@@ -1,15 +1,61 @@
|
||||
# Environment Variables Example
|
||||
# ============================================================
|
||||
# .env — committed to git (non-secret defaults)
|
||||
# ============================================================
|
||||
# This file is tracked by git. Only put non-secret values here.
|
||||
# Prisma reads DATABASE_URL from this file.
|
||||
|
||||
# Cesium Ion Access Token (Required for terrain and default imagery)
|
||||
# Get your token at https://ion.cesium.com/
|
||||
# Database (SQLite for local — zero config; PostgreSQL for cloud)
|
||||
DATABASE_URL=file:./data/wwv.db
|
||||
|
||||
# ============================================================
|
||||
# .env.local — NOT committed (secrets & API keys)
|
||||
# ============================================================
|
||||
# Copy everything below into a new file called .env.local
|
||||
# .env.local is gitignored and overrides .env values.
|
||||
|
||||
# Auth Secret (REQUIRED — generate with: openssl rand -hex 32)
|
||||
# Must remain stable across restarts to preserve sessions and tokens.
|
||||
# For Docker: also set this in the host environment or a .env file
|
||||
# at the project root so docker-compose can inject it.
|
||||
AUTH_SECRET=
|
||||
|
||||
# Cesium Ion Access Token (optional — get one free at https://ion.cesium.com/)
|
||||
NEXT_PUBLIC_CESIUM_ION_TOKEN=
|
||||
|
||||
# Bing Maps API Key (Optional, for high-res imagery)
|
||||
# Get your key at https://www.bingmapsportal.com/
|
||||
NEXT_PUBLIC_BING_MAPS_KEY=
|
||||
|
||||
# Supabase Configuration (Required for persistence and historical data)
|
||||
# Supabase Configuration (Optional — cloud-only features)
|
||||
# Found in your Supabase Project Settings > API
|
||||
NEXT_PUBLIC_SUPABASE_URL=
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY=
|
||||
SUPABASE_SERVICE_ROLE_KEY=
|
||||
SUPABASE_DATABASE_URL=
|
||||
|
||||
# OpenSky Network — multi-account credential rotation
|
||||
# Comma-separated clientId:clientSecret pairs.
|
||||
# Example: OPENSKY_CREDENTIALS=acct1-id:acct1-secret,acct2-id:acct2-secret
|
||||
OPENSKY_CREDENTIALS=
|
||||
|
||||
# ACLED API — Civil Unrest & Conflict data (free for non-commercial use)
|
||||
# Register at https://developer.acleddata.com/ to obtain credentials.
|
||||
# Data is updated weekly (Mondays) with global protest, riot, and violence events.
|
||||
ACLED_EMAIL=
|
||||
ACLED_PASSWORD=
|
||||
|
||||
# Marketplace Bridge Token — shared secret for marketplace → WWV install requests
|
||||
# Generate any random string, then set the same value in the marketplace instance config.
|
||||
WWV_BRIDGE_TOKEN=
|
||||
|
||||
# Default plugins enabled on boot for demo edition
|
||||
# Comma-separated list of plugin IDs
|
||||
NEXT_PUBLIC_DEMO_DEFAULT_PLUGINS=
|
||||
|
||||
# Edition: "local" | "cloud" | "demo"
|
||||
NEXT_PUBLIC_WWV_EDITION=local
|
||||
|
||||
# Demo Admin Secret (demo edition only)
|
||||
# Allows operator plugin management on the demo instance via x-wwv-admin-secret header.
|
||||
# Generate any random string. Only set this on the demo deployment.
|
||||
# WWV_DEMO_ADMIN_SECRET=
|
||||
@@ -0,0 +1,29 @@
|
||||
---
|
||||
name: Bug Report
|
||||
about: Create a report to help us improve WorldWideView
|
||||
title: '[BUG] '
|
||||
labels: bug
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behavior:
|
||||
1. Go to '...'
|
||||
2. Click on '....'
|
||||
3. Scroll down to '....'
|
||||
4. See error
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Screenshots/Logs**
|
||||
If applicable, add screenshots or console output to help explain your problem.
|
||||
|
||||
**Environment (please complete the following information):**
|
||||
- OS: [e.g. Windows, macOS]
|
||||
- Browser [e.g. chrome, safari, firefox]
|
||||
- WorldWideView Edition [e.g. local, demo, cloud]
|
||||
@@ -0,0 +1,19 @@
|
||||
---
|
||||
name: Core Feature Request
|
||||
about: Suggest an idea for the core WorldWideView engine
|
||||
title: '[FEATURE] '
|
||||
labels: enhancement
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
**Note:** If this is about adding a new data source (like mapping vessels or plotting weather), please use the **Plugin Proposal** template instead! This template is for core engine features (like camera logic, filtering, or rendering pipeline upgrades).
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
name: Plugin Proposal
|
||||
about: Suggest a new real-time data source plugin
|
||||
title: '[PLUGIN] '
|
||||
labels: plugin-idea, help-wanted
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**What data source do you want to add?**
|
||||
Please provide a brief description of the intelligence data (e.g., Global Earthquakes, Shipping Vessels, Weather Radar, Local Train Networks).
|
||||
|
||||
**Is there an available API?**
|
||||
Please link to any public or authenticated APIs that provide this data.
|
||||
*(e.g., USGS Earthquake API: https://earthquake.usgs.gov/earthquakes/feed/v1.0/geojson.php)*
|
||||
|
||||
**What should the plugin render?**
|
||||
- What kind of marker? (e.g., dots, icons, 3D models)
|
||||
- Does it require historical tracking (paths), or just current position?
|
||||
|
||||
**Would you be interested in building this?**
|
||||
- [ ] Yes, I'd like to try building it!
|
||||
- [ ] No, just putting the idea out there.
|
||||
|
||||
*(Looking to build it yourself? Check out the [Build a Plugin in 5 Minutes](https://github.com/silvertakana/worldwideview#build-a-plugin-in-5-minutes) guide in the README!)*
|
||||
@@ -0,0 +1,44 @@
|
||||
## Summary
|
||||
|
||||
<!-- A short description of what this PR does and why. -->
|
||||
|
||||
## Type of Change
|
||||
|
||||
- [ ] Bug fix
|
||||
- [ ] New feature
|
||||
- [ ] New plugin
|
||||
- [ ] Refactor / code quality
|
||||
- [ ] Documentation
|
||||
- [ ] Performance improvement
|
||||
|
||||
## Related Issue
|
||||
|
||||
Closes #<!-- issue number -->
|
||||
|
||||
## Changes Made
|
||||
|
||||
<!-- List the key changes. Be specific about files and modules affected. -->
|
||||
|
||||
-
|
||||
-
|
||||
|
||||
## Testing
|
||||
|
||||
- [ ] I ran `npm test` and all tests pass
|
||||
- [ ] I manually tested this in the browser against a live data source
|
||||
- [ ] I added or updated tests for my changes
|
||||
|
||||
## Plugin Checklist (if applicable)
|
||||
|
||||
- [ ] Plugin is registered with `PluginRegistry`
|
||||
- [ ] Plugin does not import or depend on core rendering logic directly
|
||||
- [ ] Plugin cleans up Cesium primitives on unmount/disable
|
||||
- [ ] No hardcoded credentials or API keys committed
|
||||
|
||||
## Screenshots / Recordings
|
||||
|
||||
<!-- If this changes the UI or globe rendering, include a screenshot or screen recording. -->
|
||||
|
||||
## Notes for Reviewer
|
||||
|
||||
<!-- Any context that would help the reviewer understand the approach or trade-offs. -->
|
||||
@@ -0,0 +1,53 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
typecheck:
|
||||
name: Type Check
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: npx prisma generate
|
||||
- run: pnpm exec tsc --noEmit
|
||||
|
||||
test:
|
||||
name: Unit Tests
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: npx prisma generate
|
||||
- run: pnpm test
|
||||
|
||||
build:
|
||||
name: Build
|
||||
runs-on: ubuntu-latest
|
||||
needs: [typecheck, test]
|
||||
env:
|
||||
DATABASE_URL: postgresql://ci:ci@localhost:5432/ci
|
||||
AUTH_SECRET: ci-placeholder-secret-not-used-in-tests
|
||||
NEXT_PUBLIC_WWV_EDITION: local
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: npx prisma generate
|
||||
- run: pnpm build
|
||||
@@ -0,0 +1,44 @@
|
||||
name: Claude Code Review
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, synchronize, ready_for_review, reopened]
|
||||
# Optional: Only run on specific file changes
|
||||
# paths:
|
||||
# - "src/**/*.ts"
|
||||
# - "src/**/*.tsx"
|
||||
# - "src/**/*.js"
|
||||
# - "src/**/*.jsx"
|
||||
|
||||
jobs:
|
||||
claude-review:
|
||||
# Optional: Filter by PR author
|
||||
# if: |
|
||||
# github.event.pull_request.user.login == 'external-contributor' ||
|
||||
# github.event.pull_request.user.login == 'new-developer' ||
|
||||
# github.event.pull_request.author_association == 'FIRST_TIME_CONTRIBUTOR'
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
issues: read
|
||||
id-token: write
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Run Claude Code Review
|
||||
id: claude-review
|
||||
uses: anthropics/claude-code-action@v1
|
||||
with:
|
||||
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
|
||||
plugin_marketplaces: 'https://github.com/anthropics/claude-code.git'
|
||||
plugins: 'code-review@claude-code-plugins'
|
||||
prompt: '/code-review:code-review ${{ github.repository }}/pull/${{ github.event.pull_request.number }}'
|
||||
# See https://github.com/anthropics/claude-code-action/blob/main/docs/usage.md
|
||||
# or https://code.claude.com/docs/en/cli-reference for available options
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
name: Claude Code
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
pull_request_review_comment:
|
||||
types: [created]
|
||||
issues:
|
||||
types: [opened, assigned]
|
||||
pull_request_review:
|
||||
types: [submitted]
|
||||
|
||||
jobs:
|
||||
claude:
|
||||
if: |
|
||||
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
|
||||
(github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
issues: read
|
||||
id-token: write
|
||||
actions: read # Required for Claude to read CI results on PRs
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Run Claude Code
|
||||
id: claude
|
||||
uses: anthropics/claude-code-action@v1
|
||||
with:
|
||||
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
|
||||
|
||||
# This is an optional setting that allows Claude to read CI results on PRs
|
||||
additional_permissions: |
|
||||
actions: read
|
||||
|
||||
# Optional: Give a custom prompt to Claude. If this is not specified, Claude will perform the instructions specified in the comment that tagged it.
|
||||
# prompt: 'Update the pull request description to include a summary of changes.'
|
||||
|
||||
# Optional: Add claude_args to customize behavior and configuration
|
||||
# See https://github.com/anthropics/claude-code-action/blob/main/docs/usage.md
|
||||
# or https://code.claude.com/docs/en/cli-reference for available options
|
||||
# claude_args: '--allowed-tools Bash(gh pr *)'
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
name: Docker Build and Publish
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "main", "feat/docker-ci" ]
|
||||
pull_request:
|
||||
branches: [ "main" ]
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
IMAGE_NAME: ${{ github.repository }}
|
||||
|
||||
jobs:
|
||||
build-and-push:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Log in to the Container registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||
tags: |
|
||||
type=raw,value=latest,enable={{is_default_branch}}
|
||||
type=ref,event=branch
|
||||
type=ref,event=pr
|
||||
type=semver,pattern={{version}}
|
||||
type=sha
|
||||
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
@@ -0,0 +1,38 @@
|
||||
name: Publish Plugin to NPM
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "wwv-plugin-*-v*" # e.g. wwv-plugin-aviation-v1.0.1
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write # Required for OIDC trusted publishing (no NPM_TOKEN needed)
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
registry-url: "https://registry.npmjs.org"
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Detect package name from tag
|
||||
id: pkg
|
||||
run: |
|
||||
TAG="${{ github.ref_name }}"
|
||||
# Strips the -vX.Y.Z suffix: "wwv-plugin-aviation-v1.0.1" → "wwv-plugin-aviation"
|
||||
PKG=$(echo "$TAG" | sed 's/-v[0-9].*//')
|
||||
echo "package=$PKG" >> $GITHUB_OUTPUT
|
||||
echo "Publishing: $PKG"
|
||||
|
||||
- name: Build package
|
||||
run: npm run build -w packages/${{ steps.pkg.outputs.package }}
|
||||
|
||||
- name: Publish to NPM (OIDC)
|
||||
run: npm publish packages/${{ steps.pkg.outputs.package }} --access public --provenance
|
||||
+46
-1
@@ -1,7 +1,7 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
node_modules/
|
||||
/.pnp
|
||||
.pnp.*
|
||||
.yarn/*
|
||||
@@ -17,12 +17,37 @@
|
||||
/.next/
|
||||
/out/
|
||||
|
||||
# agents
|
||||
/.agents/
|
||||
|
||||
# claude code IDE config
|
||||
/.claude/
|
||||
/.cline/
|
||||
|
||||
# performance
|
||||
/performance/
|
||||
|
||||
# artifacts
|
||||
/artifacts/
|
||||
|
||||
# scripts (tracked, but temporary scratchpads should go in /local-scripts/)
|
||||
|
||||
|
||||
# local database
|
||||
/data/
|
||||
packages/*/data/
|
||||
*.db
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
*.db-shm
|
||||
*.db-wal
|
||||
|
||||
# temporary files and credentials
|
||||
/tmp/
|
||||
|
||||
# generated prisma client
|
||||
/src/generated/
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
@@ -38,6 +63,7 @@ yarn-error.log*
|
||||
|
||||
# env files (can opt-in for committing if needed)
|
||||
.env*
|
||||
!.env
|
||||
|
||||
# vercel
|
||||
.vercel
|
||||
@@ -45,3 +71,22 @@ yarn-error.log*
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
|
||||
# Plugin build artifacts
|
||||
packages/*/dist/
|
||||
|
||||
# Reference Reference Codebases
|
||||
/worldmonitor/
|
||||
|
||||
# Developmental scripts & temporary sandbox
|
||||
/local-scripts/
|
||||
/public/plugins-local/
|
||||
|
||||
# git worktrees
|
||||
/.worktrees/
|
||||
|
||||
# proprietary extracted services
|
||||
packages/wwv-data-engine/
|
||||
|
||||
# IDE workspace files
|
||||
*.code-workspace
|
||||
Vendored
+36
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Next.js: debug server-side",
|
||||
"type": "node-terminal",
|
||||
"request": "launch",
|
||||
"command": "pnpm run dev",
|
||||
"cwd": "${workspaceFolder}"
|
||||
},
|
||||
{
|
||||
"name": "Next.js: debug client-side",
|
||||
"type": "chrome",
|
||||
"request": "launch",
|
||||
"url": "http://localhost:3000",
|
||||
"webRoot": "${workspaceFolder}",
|
||||
"sourceMapPathOverrides": {
|
||||
"webpack://_N_E/*": "${webRoot}/*"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "WWV Data Engine: debug",
|
||||
"type": "node-terminal",
|
||||
"request": "launch",
|
||||
"command": "pnpm --filter wwv-data-engine run dev",
|
||||
"cwd": "${workspaceFolder}"
|
||||
},
|
||||
{
|
||||
"name": "Full Stack: debug",
|
||||
"type": "node-terminal",
|
||||
"request": "launch",
|
||||
"command": "pnpm run dev:all",
|
||||
"cwd": "${workspaceFolder}"
|
||||
}
|
||||
]
|
||||
}
|
||||
Vendored
+20
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
"label": "npm: dev:all",
|
||||
"type": "npm",
|
||||
"script": "dev:all",
|
||||
"problemMatcher": [],
|
||||
"isBackground": true,
|
||||
"presentation": {
|
||||
"reveal": "always",
|
||||
"panel": "new"
|
||||
},
|
||||
"group": {
|
||||
"kind": "build",
|
||||
"isDefault": true
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,382 @@
|
||||
# WorldWideView — Agent Rules
|
||||
|
||||
## 1. Project Identity
|
||||
|
||||
WorldWideView is a **real-time geospatial intelligence engine** that visualizes live global data on an interactive 3D globe. Built with **Next.js 16**, **CesiumJS**, **React 19**, and **Zustand**, it renders everything from live aircraft and maritime vessels to conflict events, satellites, and environmental data — all through a modular plugin architecture.
|
||||
|
||||
### Target Inspiration
|
||||
Our primary design, feature-set, and operational layout goal is to mimic the structure and capabilities of `www.worldmonitor.app`.
|
||||
- **Reference Codebase**: [GitHub - koala73/worldmonitor](https://github.com/koala73/worldmonitor)
|
||||
---
|
||||
|
||||
## 2. Tech Stack
|
||||
|
||||
| Layer | Technology |
|
||||
|---|---|
|
||||
| Framework | Next.js 16 (App Router, `output: "standalone"`) |
|
||||
| Language | TypeScript 5, strict mode |
|
||||
| 3D Engine | CesiumJS + Resium (Google Photorealistic 3D Tiles) |
|
||||
| State | Zustand (slice-based: globe, layers, timeline, UI, filters, data, config, favorites, geojson) |
|
||||
| Event Bus | Custom typed `DataBus` (pub/sub singleton) |
|
||||
| Styling | Vanilla CSS — **no Tailwind** |
|
||||
| Database | PostgreSQL via Prisma 7 (local and cloud) |
|
||||
| Auth | NextAuth v5 beta (Credentials provider, JWT sessions) |
|
||||
| Package Manager | pnpm (monorepo with `pnpm-workspace.yaml`) |
|
||||
| Testing | Vitest + jsdom + React Testing Library |
|
||||
| Deployment | Docker multi-stage build → Coolify |
|
||||
| Analytics | Vercel Analytics / custom `trackEvent` |
|
||||
|
||||
---
|
||||
|
||||
## 3. Directory Structure
|
||||
|
||||
```
|
||||
worldwideview/
|
||||
├── src/
|
||||
│ ├── app/ # Next.js App Router (pages, API routes, layouts)
|
||||
│ │ ├── api/ # Server-side API routes (auth, aviation, camera, etc.)
|
||||
│ │ ├── login/ # Login page
|
||||
│ │ ├── setup/ # First-time setup page
|
||||
│ │ └── globals.css # Root stylesheet
|
||||
│ ├── components/
|
||||
│ │ ├── common/ # Shared UI: BootOverlay, FloatingWindow, PluginIcon
|
||||
│ │ ├── layout/ # AppShell, Header, SearchBar, DataBusSubscriber
|
||||
│ │ ├── panels/ # LayerPanel, EntityInfoCard, FilterPanel, GraphicsSettings
|
||||
│ │ ├── timeline/ # Timeline component
|
||||
│ │ ├── marketplace/ # Plugin install/unverified dialogs
|
||||
│ │ ├── ui/ # Tooltip, ReloadToast
|
||||
│ │ └── video/ # Floating video manager
|
||||
│ ├── core/
|
||||
│ │ ├── data/ # DataBus, PollingManager, CacheLayer, SmartFetcher
|
||||
│ │ ├── filters/ # filterEngine (applies plugin filters to entities)
|
||||
│ │ ├── globe/ # GlobeView, EntityRenderer, AnimationLoop, StackManager,
|
||||
│ │ │ │ CameraController, InteractionHandler, SelectionHandler,
|
||||
│ │ │ │ ModelManager, ImageryProviderFactory
|
||||
│ │ │ └── hooks/ # useCameraActions, useEntityRendering, useModelRendering, etc.
|
||||
│ │ ├── hooks/ # useBootSequence, useIsMobile, useMarketplaceSync
|
||||
│ │ ├── plugins/ # PluginManager, PluginRegistry, PluginManifest,
|
||||
│ │ │ │ loadPluginFromManifest, validateManifest, InstalledPluginsLoader
|
||||
│ │ │ └── loaders/ # DeclarativePlugin, StaticDataPlugin, mapJsonToEntities
|
||||
│ │ └── state/ # Zustand store + slices (config, data, globe, layers, timeline, ui, etc.)
|
||||
│ ├── lib/ # auth, db, rateLimit, analytics, AIS stream, marketplace APIs
|
||||
│ ├── plugins/ # GeoJSON plugin registrations
|
||||
│ ├── styles/ # HUD animations CSS
|
||||
│ ├── types/ # GeoJSON types, Umami types
|
||||
│ └── generated/ # Prisma generated client (gitignored)
|
||||
├── packages/ # pnpm monorepo workspace packages
|
||||
│ ├── wwv-plugin-sdk/ # Plugin SDK: type definitions, manifest schema
|
||||
│ ├── wwv-plugin-aviation/
|
||||
│ ├── wwv-plugin-maritime/
|
||||
│ ├── wwv-plugin-wildfire/
|
||||
│ ├── wwv-plugin-borders/
|
||||
│ ├── wwv-plugin-camera/
|
||||
│ ├── wwv-plugin-military-aviation/
|
||||
│ ├── wwv-plugin-satellite/
|
||||
│ ├── wwv-plugin-iranwarlive/ # Includes standalone backend/ microservice
|
||||
│ └── wwv-plugin-{airports,embassies,lighthouses,nuclear,seaports,spaceports,volcanoes}/
|
||||
├── prisma/ # schema.prisma, migrations/
|
||||
├── public/ # Static assets, Cesium workers, plugin GeoJSON data
|
||||
├── scripts/ # Build scripts (copy-cesium, scaffold-osm-plugin, setup)
|
||||
├── data/ # PostgreSQL data volume (gitignored)
|
||||
├── Dockerfile # Multi-stage production build
|
||||
├── docker-compose.yml # Main app + microservice backends
|
||||
└── .agents/ # Agent documentation, rules, skills, workflows
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Architecture Patterns
|
||||
|
||||
### 4.1 Plugin System (Core Abstraction)
|
||||
|
||||
Every data source is a **plugin** implementing the `WorldPlugin` interface from `@worldwideview/wwv-plugin-sdk`. The lifecycle utilizes a real-time WebSocket Firehose pipeline:
|
||||
|
||||
```text
|
||||
PluginRegistry.register() → PluginManager.registerPlugin()
|
||||
→ plugin.initialize(context)
|
||||
|
||||
Visibility Toggle → DataBusSubscriber subscribes to layer via WsClient
|
||||
→ Engine responds with instantaneous websocket snapshots over /stream
|
||||
→ WsClient pipes to DataBus.emit("dataUpdated", WsStreamPayload)
|
||||
→ Store → EntityRenderer → Globe
|
||||
```
|
||||
|
||||
Four plugin architectures exist (All-Bundle Model):
|
||||
1. **Data Engine Seeder** — Standalone Fastify container with PostgreSQL microservice or unified seeders (e.g., `iranwarlive-backend`).
|
||||
2. **Dynamic CDN Loaded (Bundle)** — Externally developed plugins dynamically imported at runtime via ES module CDNs (e.g., `unpkg.com` version-pinned URLs).
|
||||
3. **Static Compiled (Bundle)** — Static GeoJSON data wrapped into JS bundles via `wwvStaticCompiler` during build/sync (previously `StaticDataPlugin`).
|
||||
4. **Active Proxied (Bundle)** — Next.js API routes bundled to provide frontend interactions (previously `DeclarativePlugin`).
|
||||
|
||||
All plugins are now dynamically imported at runtime as ES module bundles via `loadPluginFromManifest` utilizing `import(/* webpackIgnore: true */ entry)`. The legacy `StaticDataPlugin` and `DeclarativePlugin` runtimes are fully deprecated.
|
||||
|
||||
Plugin types are re-exported from SDK through `src/core/plugins/PluginTypes.ts` and `PluginManifest.ts` — **source of truth is always `@worldwideview/wwv-plugin-sdk`**.
|
||||
|
||||
### 4.2 State Management
|
||||
|
||||
Zustand store with **nine slices**: `globe`, `layers`, `timeline`, `ui`, `filter`, `data`, `config`, `favorites`, `geojson`. Each slice is in its own file under `src/core/state/`.
|
||||
|
||||
- Access via `useStore` hook or `useStore.getState()` outside React
|
||||
- Plugin settings stored in `configSlice.dataConfig.pluginSettings`
|
||||
- Polling intervals stored in `configSlice.dataConfig.pollingIntervals`
|
||||
|
||||
### 4.3 Data Pipeline
|
||||
|
||||
```text
|
||||
Engine push /stream → DataBusSubscriber WsClient router
|
||||
→ WsClient.handleMessage() → DataBus.emit("websocketData")
|
||||
→ DataBusSubscriber → _hydrateSnapshot() → Store.entitiesByPlugin
|
||||
→ GlobeView (memoized visible entities)
|
||||
→ EntityRenderer (billboard/point primitives)
|
||||
→ AnimationLoop (horizon culling, hover/selection)
|
||||
→ StackManager (co-located entity grouping)
|
||||
```
|
||||
|
||||
### 4.3.1 Split-Routing (Cloud Fallback)
|
||||
|
||||
When a local engine is detected at `localhost:5001`, the frontend fetches its `/manifest` to discover available seeders. Per-plugin routing via `resolveEngineUrl`:
|
||||
- Plugin's seeder is in local manifest → `ws://localhost:5001/stream`
|
||||
- Plugin's seeder is NOT in local manifest → `wss://dataengine.worldwideview.dev/stream`
|
||||
|
||||
This enables core contributors running the public (community) engine locally to see local data for their seeders while proprietary sources (aviation, maritime) continue streaming from the cloud.
|
||||
|
||||
The data engine uses a **public upstream / private fork** model:
|
||||
- `wwv-data-engine` (public) — community seeders, contributors fork and PR here
|
||||
- `wwv-data-engine-internal` (private) — all seeders, deploys to Coolify via `git merge upstream/main`
|
||||
|
||||
### 4.4 Rendering Pipeline
|
||||
|
||||
- **Primitive-based**: Uses `PointPrimitiveCollection`, `BillboardCollection`, `LabelCollection` — NOT Cesium Entity API
|
||||
- **Chunked processing**: Large datasets (10k+) rendered via `ChunkedProcessor`
|
||||
- **LOD system**: Model-type entities promoted to 3D models at close range (`useModelRendering`)
|
||||
- **Horizon culling**: Manual dot-product calculation against Earth radius (NOT depth testing)
|
||||
- **Stack/Spiderifier**: `StackManager` groups co-located entities; `stackAnimation` handles expansion
|
||||
|
||||
### 4.5 Edition System
|
||||
|
||||
Three editions controlled by `NEXT_PUBLIC_WWV_EDITION`:
|
||||
- **`local`** — Self-hosted, full features, auth enabled
|
||||
- **`cloud`** — Managed cloud instance, full features
|
||||
- **`demo`** — Public demo, auth disabled, optional admin via `WWV_DEMO_ADMIN_SECRET`
|
||||
|
||||
Feature flags derived from edition in `src/core/edition.ts`.
|
||||
|
||||
---
|
||||
|
||||
## 5. Critical Conventions
|
||||
|
||||
### 5.1 File Size
|
||||
|
||||
**Max 150 lines per file.** If a file grows beyond this, modularize it. Extract helpers, split components, use hooks.
|
||||
|
||||
### 5.2 Import Aliases
|
||||
|
||||
- `@/*` → `./src/*`
|
||||
- `@worldwideview/wwv-plugin-sdk` → `./packages/wwv-plugin-sdk/src`
|
||||
- Each plugin has its own alias in `tsconfig.json`
|
||||
|
||||
### 5.3 CSS Rules
|
||||
|
||||
- **Vanilla CSS only** — no Tailwind, no CSS-in-JS
|
||||
- Global styles in `src/app/globals.css`
|
||||
- Component-scoped styles use CSS Modules (`.module.css`) or co-located `.css` files
|
||||
- HUD animations in `src/styles/hud-animations.css`
|
||||
|
||||
### 5.4 Rendering Entity Rules
|
||||
|
||||
When returning `CesiumEntityOptions` from `renderEntity()`:
|
||||
|
||||
- **Points**: Use `type: "point"` with `color`, `size`, `outlineColor`, `outlineWidth`
|
||||
- **Billboards**: Use `type: "billboard"` with `iconUrl`, `color`, `iconScale`
|
||||
- **NEVER mix**: Do not use `size`/`outlineWidth`/`outlineColor` on billboard entities — causes GPU clipping
|
||||
|
||||
### 5.5 Plugin Registration
|
||||
|
||||
Built-in plugins are instantiated in `AppShell.tsx` and registered via `PluginRegistry` → `PluginManager`. Marketplace-installed plugins are loaded from the database via `InstalledPluginsLoader`.
|
||||
|
||||
### 5.6 Workspace Rules
|
||||
|
||||
- Always run `pnpm install` from project root after creating new packages
|
||||
- Plugin packages go in `packages/wwv-plugin-<name>/`
|
||||
- Microservice backends go in `packages/wwv-plugin-<name>/backend/`
|
||||
- Both globs (`packages/*` and `packages/*/backend`) are in `pnpm-workspace.yaml`
|
||||
- Add new plugins to `transpilePackages` in `next.config.ts` and `paths` in `tsconfig.json`
|
||||
|
||||
### 5.7 AI Meta-Directives: Antigravity Standard (Claude Code)
|
||||
|
||||
> [!NOTE]
|
||||
> This repository is orchestrated via the **Antigravity open standard** using **Claude Code** as the active agent. The entry point for Claude Code is `CLAUDE.md` at the project root.
|
||||
|
||||
> [!WARNING]
|
||||
> - **Always** use standard `.md` file extensions for rules, skills, and workflows.
|
||||
> - **Never** use proprietary `.mdc` extensions.
|
||||
> - **Never** reference Cursor IDE rules; we use the open `.agents/` standard.
|
||||
> - **MUST**: You MUST update Semantic Versioning numbering inside the relevant `package.json` file prior to executing any code commits, adhering strictly to the `[/commit]` workflow rules (`feat:` -> Minor, `fix/refactor/perf:` -> Patch).
|
||||
> - **MUST Detail Commit Levels & Bumps**: On description changes or release notes, you must detail the level of commit (Major/Minor/Fix) for *each* individual change. If there are multiple accumulated changes, you MUST EITHER commit them individually and bump the version each time, OR commit them all at once and bump the version multiple times.
|
||||
> - **MUST Explain Complex Concepts Simply**: Whenever providing a complicated technical explanation to the user, you MUST include a simple explanation below it. Use an analogy with reference to the correct terminology, comparing the concept to something from everyday life to ensure the user easily understands it.
|
||||
> - **MUST Be Transparent & Narrate Actions**: You MUST always be transparent about what you are doing. Narrate your goals, your current step in the process, and exactly what actions you are taking or tools you are executing **before** or **while** you do them, not after they are done. Do not work in silence or lock all your reasoning behind hidden "thought" blocks. Use visible chat messages to bring the user along the journey by describing your plan as it unfolds. **Crucially, keep this narration conversational and natural.** Avoid stiff, robotic templates (e.g., "My Goal: X. My Step: Y."). Just occasionally drop a brief, casual note about what you are checking or doing next so the user isn't left in the dark.
|
||||
|
||||
### 5.8 Workspace Hygiene
|
||||
Whenever agents generate temporary debugging scripts, test REST endpoints via `.mjs`, or dump traces/JSON outputs, they **MUST** save these exclusively inside `/local-scripts/`. The root directory is strictly for production configuration files.
|
||||
|
||||
---
|
||||
|
||||
## 6. Environment Variables
|
||||
|
||||
| Variable | Required | Description |
|
||||
|---|---|---|
|
||||
| `DATABASE_URL` | Yes | PostgreSQL connection string |
|
||||
| `AUTH_SECRET` | Yes | JWT signing secret (generate with `openssl rand -hex 32`) |
|
||||
| `NEXT_PUBLIC_CESIUM_ION_TOKEN` | No | Cesium Ion access token |
|
||||
| `NEXT_PUBLIC_BING_MAPS_KEY` | No | Bing Maps imagery |
|
||||
| `NEXT_PUBLIC_GOOGLE_MAPS_API_KEY` | No | Google 3D Tiles |
|
||||
| `NEXT_PUBLIC_WWV_EDITION` | No | `local` / `cloud` / `demo` (default: `local`) |
|
||||
| `NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL` | No | Override engine WebSocket URL (default: cloud) |
|
||||
| `OPENSKY_CREDENTIALS` | No | Comma-separated `id:secret` pairs for credential rotation |
|
||||
| `WWV_BRIDGE_TOKEN` | No | Shared secret for marketplace → WWV install bridge |
|
||||
| `WWV_DEMO_ADMIN_SECRET` | No | Demo edition admin password |
|
||||
| `IRANWARLIVE_BACKEND_URL` | No | Override for IranWarLive microservice URL |
|
||||
|
||||
Secrets go in `.env.local` (gitignored). Non-secrets go in `.env` (committed).
|
||||
|
||||
---
|
||||
|
||||
## 7. Development Commands
|
||||
|
||||
```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 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
|
||||
pnpm test # Run all Vitest tests (scoped to src/lib, src/core, src/plugins)
|
||||
pnpm db:reset # Reset and re-migrate the frontend database (destructive)
|
||||
pnpm start:backends # Start all plugin microservice backends in parallel
|
||||
pnpm clean:backends # Wipe all plugin database records
|
||||
pnpm run scaffold-osm-plugin <name> # Generate a new plugin from scaffold
|
||||
```
|
||||
|
||||
Frontend runs at `http://localhost:3000`.
|
||||
|
||||
---
|
||||
|
||||
## 8. Deployment
|
||||
|
||||
- **Docker**: Multi-stage Dockerfile using the Extractor Pattern (`deps` → `builder` → `runner`). The `node_modules` folders must be explicitly untracked in from `git` across the workspace to prevent corrupted BuildKit contextual cache overlaps during the `COPY . .` stage.
|
||||
- **Standalone output**: `next.config.ts` uses `output: "standalone"`.
|
||||
- **Cesium assets**: Copied to `public/cesium/` via `scripts/copy-cesium.mjs` at build time, excluded from output tracing.
|
||||
- **Prisma Configuration**: `prisma.config.ts` must export a native javascript object instead of dynamically importing CLI wrapper binaries (`prisma/config` or `dotenv`). The standalone Next.js tracer strips CLI devDependencies during the build, which will cause fatal runtime container crashes if imported.
|
||||
- **Microservices**: Separate containers defined in `docker-compose.yml`, proxied via `next.config.ts` rewrites.
|
||||
- **Coolify**: Deployed via Dockerfile builder natively mapping environment variables continuously into the container shell.
|
||||
- **Docker volumes**: Ensure PostgreSQL data and Redis volumes are mounted for persistence.
|
||||
|
||||
---
|
||||
|
||||
## 9. Testing Strategy
|
||||
|
||||
- **Framework**: Vitest with jsdom environment
|
||||
- **Coverage**: `src/lib/**`, `src/core/**`, `src/plugins/**`
|
||||
- **Run**: `pnpm test` (or `vitest run`)
|
||||
- **Key test files**: `rateLimit.test.ts`, `edition.test.ts`, `demoAdmin.test.ts`, `DeclarativePlugin.test.ts`, `cors.test.ts`, `repository.test.ts`, `marketplaceToken.test.ts`
|
||||
|
||||
---
|
||||
|
||||
## 10. Security Headers
|
||||
|
||||
Configured in `next.config.ts` `headers()`:
|
||||
- **CSP**: Restrictive with exceptions for CesiumJS (`unsafe-eval`, `unsafe-inline`), camera streams (`http: https:`), and analytics
|
||||
- **X-Frame-Options**: DENY
|
||||
- **X-Content-Type-Options**: nosniff
|
||||
- **Referrer-Policy**: strict-origin-when-cross-origin
|
||||
- **Permissions-Policy**: camera/microphone disabled, geolocation self-only
|
||||
|
||||
---
|
||||
|
||||
## 11. Related Repositories
|
||||
|
||||
| Repo | Purpose |
|
||||
|---|---|
|
||||
| `worldwideview` | Main application (this repo) |
|
||||
| `wwv-data-engine` | Open-source data engine — community seeders (PUBLIC) |
|
||||
| `wwv-data-engine-internal` | Proprietary data engine — all seeders (PRIVATE, deployed to Coolify) |
|
||||
| `worldwideview-marketplace` | Plugin marketplace web app |
|
||||
| `worldwideview-plugins` | Published npm plugin packages |
|
||||
| `worldwideview-web` | Marketing / landing page |
|
||||
|
||||
---
|
||||
|
||||
## 12. On-Demand Rules
|
||||
|
||||
Read the relevant rule file when working in that domain:
|
||||
|
||||
| Rule | When to use | Path |
|
||||
|---|---|---|
|
||||
| `monorepo-workflow` | pnpm commands, adding packages, workspace config | `.agents/rules/monorepo-workflow.md` |
|
||||
| `plugin-architecture` | Creating/modifying plugins, lifecycle, registration | `.agents/rules/plugin-architecture.md` |
|
||||
| `cesium-rendering` | Globe rendering, entity types, primitives, LOD, culling | `.agents/rules/cesium-rendering.md` |
|
||||
| `state-management` | Zustand slices, store access, plugin settings | `.agents/rules/state-management.md` |
|
||||
| `database-migrations` | Prisma schema changes, migrations, PostgreSQL | `.agents/rules/database-migrations.md` |
|
||||
| `continuous-improvement` | When to create/update rules, skills, or workflows | `.agents/rules/continuous-improvement.md` |
|
||||
| `context-and-memory` | How to orient and maintain project context between sessions | `.agents/rules/context-and-memory.md` |
|
||||
|
||||
---
|
||||
|
||||
## 13. Slash Commands / Workflows
|
||||
|
||||
Invoke by name. Read the skill/workflow file and follow its steps.
|
||||
|
||||
| Command | Description | File |
|
||||
|---|---|---|
|
||||
| `/commit` | **Required before every commit** — bump semver + conventional commit | `.agents/skills/commit/SKILL.md` |
|
||||
| `/remember` | Save a lesson, constraint, or fact into `.agents/` permanent memory | `.agents/skills/remember/SKILL.md` |
|
||||
| `/pr-review` | 6-role comprehensive pull request review | `.agents/skills/pr-review/SKILL.md` |
|
||||
| `/update-context` | Sync `.agents/context/` with current project state | Global skill |
|
||||
| `/local-dev` | Check, start, and troubleshoot local dev environment | `.agents/workflows/local-dev.md` |
|
||||
| `/data-engine-cli` | Use the wwv-data-engine CLI wrapper | `.agents/workflows/data-engine-cli.md` |
|
||||
| `/debugging-coolify` | Troubleshoot deployed apps on Coolify via MCP/SSH | `.agents/workflows/debugging-coolify.md` |
|
||||
| `/five` | Five Whys root cause analysis | `.agents/workflows/five.md` |
|
||||
| `/stitch-to-nextjs` | Generate UI with Stitch MCP, port into Next.js | `.agents/workflows/stitch-to-nextjs.md` |
|
||||
| `/bing-news-hydration` | Hydrate event attributes with Bing RSS news | `.agents/workflows/bing-news-hydration.md` |
|
||||
| `/generate-user-roadmap` | Generate updated user-facing roadmap | `.agents/workflows/generate-user-roadmap.md` |
|
||||
|
||||
---
|
||||
|
||||
## 14. Agent Skills Reference
|
||||
|
||||
Refer to these skill documents for specialized tasks:
|
||||
|
||||
### Project Skills (`.agents/skills/`)
|
||||
|
||||
| Skill | When to Use |
|
||||
|---|---|
|
||||
| `worldwideview-plugin-creation` | **Use when creating any plugin** — strict architectural checklist |
|
||||
| `plugin-creation-master-guide.md` | Decision matrix for choosing plugin architecture |
|
||||
| `osm-static-plugin-creation.md` | Creating static GeoJSON plugins from OpenStreetMap |
|
||||
| `microservice-plugin-creation.md` | Building standalone Fastify microservice backends |
|
||||
| `database-operations.md` | Prisma schema changes, migrations, database queries |
|
||||
| `database-incident-recovery-procedures.md` | Authoritative protocol for safely restoring a broken production database |
|
||||
| `index-documentation.md` | Maintaining project documentation index |
|
||||
| `context7` | Fetch up-to-date library docs via Context7 API |
|
||||
| `cesium-context7` | CesiumJS-specific documentation lookup |
|
||||
|
||||
### Global Skills
|
||||
|
||||
52 skills are available across all projects. See `.agents/global-skills-index.md` for the full list and invocation paths.
|
||||
|
||||
---
|
||||
|
||||
## 15. Pull Request & Commit Guidelines
|
||||
|
||||
- **Commit Format**: We strictly enforce Conventional Commits (`feat:`, `fix:`, `refactor:`, `perf:`).
|
||||
- **Workflow**: You **MUST** use the `/commit` workflow before every git commit to ensure proper semantic versioning bumps.
|
||||
- **Required Checks**: Ensure `pnpm test` and `pnpm build` complete successfully before proposing a merge.
|
||||
- **Review Process**: Use `/pr-review` to conduct a comprehensive multi-role review on any pull request.
|
||||
|
||||
---
|
||||
|
||||
## 16. Debugging and Troubleshooting
|
||||
|
||||
- **Prisma & PostgreSQL Sync Issues**: If the local database state falls out of sync with Prisma schema, do not manually drop tables. Instead, run `pnpm db:reset` to cleanly wipe and re-apply all migrations.
|
||||
- **Cesium Entity Clipping**: If `billboard` entities are clipping or failing to render correctly, verify that you are not mixing `point` primitive properties (like `size` or `outlineWidth`) into the `billboard` options.
|
||||
- **Build Exhaustion (Docker)**: Multi-stage pnpm builds generate massive cache layers. If a Coolify deployment fails silently or PostgreSQL crashes abruptly, check host disk space and run `docker builder prune -a -f`.
|
||||
- **Next.js Typechecking Failures**: If backend-only `scripts/` fail during Next.js build, verify that the scripts directory is properly listed in the `exclude` array of `tsconfig.json`.
|
||||
@@ -0,0 +1,55 @@
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
We as members, contributors, and maintainers of **WorldWideView** pledge to make participation in our project and community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, colour, religion, or sexual identity and orientation.
|
||||
|
||||
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
|
||||
|
||||
---
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behaviour that contributes to a positive environment:
|
||||
|
||||
- Using welcoming and inclusive language
|
||||
- Being respectful of differing viewpoints and experiences
|
||||
- Gracefully accepting constructive criticism
|
||||
- Focusing on what is best for the community
|
||||
- Showing empathy towards other community members
|
||||
|
||||
Examples of unacceptable behaviour:
|
||||
|
||||
- The use of sexualised language or imagery, and sexual attention or advances of any kind
|
||||
- Trolling, insulting or derogatory comments, and personal or political attacks
|
||||
- Public or private harassment
|
||||
- Publishing others' private information without explicit permission
|
||||
- Other conduct which could reasonably be considered inappropriate in a professional setting
|
||||
|
||||
---
|
||||
|
||||
## Enforcement Responsibilities
|
||||
|
||||
Maintainers are responsible for clarifying and enforcing our standards of acceptable behaviour and will take appropriate and fair corrective action in response to any behaviour that they deem inappropriate, threatening, offensive, or harmful.
|
||||
|
||||
Maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct.
|
||||
|
||||
---
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies within all project spaces — GitHub issues, pull requests, discussions, and any other official channels.
|
||||
|
||||
---
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behaviour may be reported by opening a GitHub issue marked **[CoC]** or by contacting the maintainer directly via GitHub.
|
||||
|
||||
All complaints will be reviewed and investigated promptly and fairly. The maintainer is obligated to respect the privacy and security of the reporter.
|
||||
|
||||
---
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org/), version 2.1.
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
# Contributing to WorldWideView
|
||||
|
||||
Thank you for your interest in contributing to **WorldWideView** — a modular, real-time geospatial intelligence engine!
|
||||
|
||||
This project is licensed under the [Elastic License 2.0](./LICENSE). By submitting a contribution, you agree that your code will be made available under those same terms.
|
||||
|
||||
---
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Getting Started](#getting-started)
|
||||
- [Development Setup](#development-setup)
|
||||
- [Project Structure](#project-structure)
|
||||
- [How to Contribute](#how-to-contribute)
|
||||
- [Plugin Contributions](#plugin-contributions)
|
||||
- [Code Standards](#code-standards)
|
||||
- [Commit & Branch Conventions](#commit--branch-conventions)
|
||||
- [Pull Request Process](#pull-request-process)
|
||||
- [Running Tests](#running-tests)
|
||||
|
||||
---
|
||||
|
||||
## Getting Started
|
||||
|
||||
1. **Fork** the repository on GitHub.
|
||||
2. **Clone** your fork locally:
|
||||
```bash
|
||||
git clone https://github.com/<your-username>/worldwideview.git
|
||||
cd worldwideview
|
||||
```
|
||||
3. **Install dependencies**:
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
4. **Generate environment file** (auto-creates `.env.local` with `AUTH_SECRET`):
|
||||
```bash
|
||||
npm run setup
|
||||
```
|
||||
5. **Start the dev server**:
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Visit `http://localhost:3000` to confirm everything is running.
|
||||
|
||||
---
|
||||
|
||||
## Development Setup
|
||||
|
||||
| Requirement | Version |
|
||||
|-------------|---------|
|
||||
| Node.js | 18+ |
|
||||
| npm | 9+ |
|
||||
|
||||
See [`docs/SETUP.md`](docs/SETUP.md) for detailed environment setup, including Cesium Ion token configuration.
|
||||
|
||||
---
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
src/
|
||||
core/ # Core engine: state, data bus, plugin registry
|
||||
plugins/ # Data source plugins (ADS-B, AIS, satellites, etc.)
|
||||
components/ # React UI components
|
||||
hooks/ # Custom React hooks
|
||||
docs/ # Architecture and user guides
|
||||
```
|
||||
|
||||
See [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) for a deep dive into the rendering pipeline and plugin lifecycle.
|
||||
|
||||
---
|
||||
|
||||
## How to Contribute
|
||||
|
||||
Ways you can help:
|
||||
|
||||
- 🐛 **Bug fixes** — Check the [issue tracker](https://github.com/silvertakana/worldwideview/issues)
|
||||
- 🧩 **New plugins** — Add a new data source layer (see below)
|
||||
- 📖 **Documentation** — Improve guides or add examples
|
||||
- ⚡ **Performance** — Cesium primitive optimizations, GPU stall reduction
|
||||
- 🧪 **Tests** — Expand Vitest coverage
|
||||
|
||||
For large features, **open an issue first** to discuss the design before writing code.
|
||||
|
||||
---
|
||||
|
||||
## Plugin Contributions
|
||||
|
||||
The core extension point of WorldWideView is its **plugin system**. Each plugin is a self-contained data layer that:
|
||||
|
||||
1. Fetches or subscribes to a data source
|
||||
2. Transforms raw data into Cesium-ready primitives
|
||||
3. Registers itself with the `PluginRegistry`
|
||||
|
||||
See [`docs/PLUGIN_GUIDE.md`](docs/PLUGIN_GUIDE.md) for a full walkthrough. New plugins are very welcome — if you have access to a live geospatial data feed, a plugin is the best way to contribute.
|
||||
|
||||
---
|
||||
|
||||
## Code Standards
|
||||
|
||||
This project follows these principles:
|
||||
|
||||
- **Single Responsibility Principle** — each file/module does one thing
|
||||
- **DRY & SOLID** — avoid duplication, favour composition
|
||||
- **Clean Architecture** — UI, logic, and data are separate concerns
|
||||
- **Defensive Programming** — validate inputs, handle edge cases explicitly
|
||||
- **File size** — keep files under 150 lines; split into modules if needed
|
||||
|
||||
Use TypeScript strictly. Avoid `any` unless absolutely unavoidable.
|
||||
|
||||
---
|
||||
|
||||
## Commit & Branch Conventions
|
||||
|
||||
**Branch naming:**
|
||||
```
|
||||
feat/short-description
|
||||
fix/short-description
|
||||
docs/short-description
|
||||
refactor/short-description
|
||||
```
|
||||
|
||||
**Commit messages** follow [Conventional Commits](https://www.conventionalcommits.org/):
|
||||
```
|
||||
feat: add maritime AIS plugin
|
||||
fix: resolve camera snap on globe reset
|
||||
docs: update plugin guide with lifecycle diagram
|
||||
refactor: extract billboard factory from CesiumMap
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Pull Request Process
|
||||
|
||||
1. Ensure your branch is up to date with `main`.
|
||||
2. Run tests and confirm they pass: `npm test`
|
||||
3. Fill out the [PR template](.github/PULL_REQUEST_TEMPLATE.md) completely.
|
||||
4. Request a review — PRs need at least one approval before merging.
|
||||
5. Squash commits on merge if the history is noisy.
|
||||
|
||||
---
|
||||
|
||||
## Running Tests
|
||||
|
||||
```bash
|
||||
npm test # Run all tests via Vitest
|
||||
npm run test:ui # Open Vitest UI (interactive)
|
||||
```
|
||||
|
||||
Tests live alongside source files in `__tests__/` directories or as `.test.ts` files.
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
# Stage 0: Extract package.json files for layer caching
|
||||
FROM alpine AS extractor
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
RUN find . -type f \! -name 'package.json' \! -name 'pnpm-workspace.yaml' \! -name 'pnpm-lock.yaml' -delete && \
|
||||
find . -type d -empty -delete
|
||||
|
||||
# Stage 1: Install ALL dependencies (needed for build)
|
||||
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 ./
|
||||
# Install dependencies with cache mount for pnpm store
|
||||
RUN --mount=type=cache,id=pnpm,target=/root/.local/share/pnpm/store pnpm install
|
||||
|
||||
|
||||
# Stage 3: Build the application
|
||||
FROM deps AS builder
|
||||
# Copy full source code
|
||||
COPY . .
|
||||
# Next.js inlines NEXT_PUBLIC_* vars at build time — must be declared as ARGs
|
||||
ARG NEXT_PUBLIC_CESIUM_ION_TOKEN
|
||||
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_ADSENSE_CLIENT_ID
|
||||
ARG NEXT_PUBLIC_SUPABASE_URL
|
||||
ARG NEXT_PUBLIC_SUPABASE_ANON_KEY
|
||||
|
||||
# Run our pregenerate schema swap script and then generate Prisma client
|
||||
RUN NEXT_PUBLIC_WWV_EDITION=$NEXT_PUBLIC_WWV_EDITION pnpm run generate
|
||||
|
||||
# Database migrations run at container startup via docker-entrypoint.sh
|
||||
# DATABASE_URL must be set to a PostgreSQL connection string
|
||||
|
||||
# Run Next.js build with Webpack cache mounted
|
||||
RUN --mount=type=cache,target=/app/.next/cache NODE_OPTIONS="--max_old_space_size=3072" pnpm run build
|
||||
RUN node scripts/copy-cesium.mjs
|
||||
|
||||
# Deploy flattened production dependencies
|
||||
RUN pnpm --filter worldwideview deploy --prod /app/prod
|
||||
|
||||
# Stage 4: Production runner
|
||||
FROM node:22-alpine AS runner
|
||||
WORKDIR /app
|
||||
|
||||
RUN apk add --no-cache openssl
|
||||
|
||||
ENV NODE_ENV=production
|
||||
ENV HOSTNAME=0.0.0.0
|
||||
ENV PORT=3000
|
||||
# DATABASE_URL must be provided via environment variable (no default)
|
||||
# Example: postgresql://user:pass@host:5432/dbname
|
||||
ENV AUTH_TRUST_HOST=true
|
||||
|
||||
# Copy Prisma schema + migrations for runtime DB init
|
||||
COPY --from=builder /app/prisma ./prisma
|
||||
COPY --from=builder /app/prisma.config.ts ./prisma.config.ts
|
||||
|
||||
# Copy Prisma generated client
|
||||
COPY --from=builder /app/src/generated ./src/generated
|
||||
|
||||
# Copy standalone server output
|
||||
COPY --from=builder /app/.next/standalone ./
|
||||
|
||||
# Copy deployed production node_modules
|
||||
COPY --from=builder /app/prod/node_modules ./node_modules
|
||||
|
||||
# We no longer copy proddeps/node_modules. Next.js standalone output
|
||||
# already traces and copies all the exact node_modules needed for production.
|
||||
|
||||
# Copy static assets that standalone mode does NOT include
|
||||
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
|
||||
|
||||
|
||||
# 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"]
|
||||
Binary file not shown.
@@ -1,250 +0,0 @@
|
||||
# World Wide View — Implementation Plan
|
||||
|
||||
A next-generation, open-source geospatial intelligence platform combining **Worldview's cinematic CesiumJS 3D globe** with **Worldmonitor's data-rich ingestion engine**, built around a **modular plugin ecosystem**, and designed for both **community self-hosting** and **commercial SaaS deployment**.
|
||||
|
||||
## User Review Required
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **CesiumJS + Google 3D Tiles (Recommended)**: For a "low cost, fast, and efficient" setup that looks like Bilawal's "Worldview" videos, I recommend **CesiumJS with Google Maps Photorealistic 3D Tiles**.
|
||||
> - **Cost**: Google Provides a **$200/month free credit**, which covers ~33,000 sessions (each session is 3 hours of 3D globe usage). This is essentially **$0 for small-to-medium volume**.
|
||||
> - **Efficiency**: CesiumJS is built natively for 3D Tiles and time-dynamic data (CZML), making it the "fastest" path to build the cinematic features you want.
|
||||
> - **Alternatives**: MapLibre GL JS is "lighter" for standard maps but lacks the high-end 3D terrain/building polish. Deck.gl is better suited for the dashboard overlays (which we can still integrate into Cesium).
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **Scope for this bootstrap**: This plan covers **Phase 1 — Foundation/MVP** only. This gets you a working 3D globe app with the plugin architecture, 3 live data layers, a timeline, cinematic camera, and a sidebar intelligence panel. Subsequent phases will be planned after Phase 1 ships.
|
||||
|
||||
> [!WARNING]
|
||||
> **API keys required**:
|
||||
> - **Google Maps Tile API Key** (Required for Photorealistic 3D Tiles — Includes $200/mo credit).
|
||||
> - **OpenSky Network** account (free at [opensky-network.org](https://opensky-network.org)).
|
||||
|
||||
|
||||
---
|
||||
|
||||
## Proposed Changes
|
||||
|
||||
### Project Scaffolding
|
||||
|
||||
Summary: Initialize a Next.js (App Router) + TypeScript project with a modular architecture, designed from day one as a plugin ecosystem.
|
||||
|
||||
#### [NEW] [package.json](file:///c:/dev/World%20Wide%20View/package.json)
|
||||
Root `package.json` with Next.js, React 18, TypeScript, CesiumJS, and Resium. Will include a custom `copy-cesium` script to move static assets to `/public/cesium` for Next.js compatibility.
|
||||
|
||||
#### [NEW] [next.config.mjs](file:///c:/dev/World%20Wide%20View/next.config.mjs)
|
||||
Next.js config with path aliases, environment variable handling, and specific Webpack exclusions for CesiumJS Node.js dependencies.
|
||||
|
||||
#### [NEW] [tsconfig.json](file:///c:/dev/World%20Wide%20View/tsconfig.json)
|
||||
TypeScript config with strict mode, path aliases for `@/core`, `@/plugins`, `@/components`.
|
||||
|
||||
#### [NEW] [.env.example](file:///c:/dev/World%20Wide%20View/.env.example)
|
||||
Template with all required/optional environment variables documented.
|
||||
|
||||
---
|
||||
|
||||
### Directory Structure
|
||||
|
||||
```
|
||||
c:\dev\World Wide View\
|
||||
├── public/ # Static assets (including /cesium)
|
||||
├── src/
|
||||
│ ├── app/ # Next.js App Router
|
||||
│ │ ├── page.tsx # Main entry (Client component)
|
||||
│ │ ├── layout.tsx # Root layout
|
||||
│ │ ├── globals.css # Global styles
|
||||
│ │ └── api/ # Next.js Route Handlers (Backend)
|
||||
│ │ ├── aviation/route.ts# OpenSky proxy
|
||||
│ │ ├── maritime/route.ts# AIS proxy
|
||||
│ │ └── wildfire/route.ts# NASA FIRMS proxy
|
||||
│ ├── core/ # Core platform code
|
||||
│ │ ├── globe/ # CesiumJS globe wrapper (Dynamic Import)
|
||||
│ │ │ ├── GlobeView.tsx # Main 3D globe component
|
||||
│ │ │ ├── CameraController.ts # Cinematic camera system
|
||||
│ │ │ ├── LayerRenderer.ts # Renders plugin data on globe
|
||||
│ │ │ └── TimelineSync.ts # Syncs Cesium clock with UI
|
||||
│ │ ├── plugins/ # Plugin system
|
||||
│ │ │ ├── PluginManager.ts # Plugin lifecycle manager
|
||||
│ │ │ ├── PluginTypes.ts # Plugin interface definitions
|
||||
│ │ │ └── PluginRegistry.ts# Registration & discovery
|
||||
│ │ ├── data/ # Data management
|
||||
│ │ │ ├── DataBus.ts # Event bus for data flow
|
||||
│ │ │ ├── CacheLayer.ts # In-memory + IndexedDB caching
|
||||
│ │ │ └── PollingManager.ts# Manages refresh intervals
|
||||
│ │ └── state/ # Global state management
|
||||
│ │ └── store.ts # Zustand store
|
||||
│ ├── plugins/ # Built-in data source plugins
|
||||
│ │ ├── aviation/ # OpenSky / ADS-B
|
||||
│ │ ├── maritime/ # AIS vessel tracking
|
||||
│ │ └── wildfire/ # NASA FIRMS
|
||||
│ ├── components/ # UI components
|
||||
│ │ ├── layout/ # AppShell, Header, Sidebar
|
||||
│ │ ├── panels/ # LayerPanel, IntelPanel, Detail
|
||||
│ │ ├── timeline/ # Timeline scrubber
|
||||
│ │ └── common/ # Loading, Toast, etc.
|
||||
│ └── utils/ # Helpers
|
||||
├── .env.example
|
||||
├── package.json
|
||||
├── tsconfig.json
|
||||
└── next.config.mjs
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Core Globe Component
|
||||
|
||||
#### [NEW] [GlobeView.tsx](file:///c:/dev/World%20Wide%20View/src/core/globe/GlobeView.tsx)
|
||||
- CesiumJS `Viewer` inside React using Resium
|
||||
- WGS84 ellipsoid, terrain, imagery layers
|
||||
- Request render mode for performance
|
||||
- Integrates with `TimelineSync` for time-based filtering
|
||||
|
||||
#### [NEW] [CameraController.ts](file:///c:/dev/World%20Wide%20View/src/core/globe/CameraController.ts)
|
||||
- Cinematic fly-to animations with easing (Worldview-style smooth transitions)
|
||||
- 8 regional presets (Global, Americas, Europe, MENA, Asia, Africa, Oceania, LatAm)
|
||||
- Orbit mode for idle/attract state
|
||||
- URL state sync (lat, lon, zoom, heading, pitch)
|
||||
|
||||
#### [NEW] [LayerRenderer.ts](file:///c:/dev/World%20Wide%20View/src/core/globe/LayerRenderer.ts)
|
||||
- Renders plugin data as Cesium entities (points, billboards, polylines, polygons)
|
||||
- Smart clustering via `EntityCluster`
|
||||
- Progressive disclosure (detail at higher zoom)
|
||||
- Color/size coding based on data attributes
|
||||
|
||||
#### [NEW] [TimelineSync.ts](file:///c:/dev/World%20Wide%20View/src/core/globe/TimelineSync.ts)
|
||||
- Bidirectional sync between Cesium clock and UI timeline
|
||||
- Time window filtering (1h, 6h, 24h, 48h, 7d)
|
||||
- Playback controls, speed multiplier
|
||||
- Notifies plugins of current time window
|
||||
|
||||
---
|
||||
|
||||
### Plugin System
|
||||
|
||||
The heart of the modular architecture. Every data source implements a standard interface.
|
||||
|
||||
#### [NEW] [PluginTypes.ts](file:///c:/dev/World%20Wide%20View/src/core/plugins/PluginTypes.ts)
|
||||
```typescript
|
||||
export interface WorldPlugin {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
icon: string;
|
||||
category: 'aviation' | 'maritime' | 'conflict' | 'natural-disaster' |
|
||||
'infrastructure' | 'cyber' | 'economic' | 'custom';
|
||||
version: string;
|
||||
|
||||
initialize(context: PluginContext): Promise<void>;
|
||||
destroy(): void;
|
||||
fetch(timeRange: TimeRange): Promise<GeoEntity[]>;
|
||||
getPollingInterval(): number;
|
||||
getLayerConfig(): LayerConfig;
|
||||
renderEntity(entity: GeoEntity): CesiumEntityOptions;
|
||||
|
||||
// Optional UI hooks
|
||||
getSidebarComponent?(): React.ComponentType;
|
||||
getDetailComponent?(): React.ComponentType<{ entity: GeoEntity }>;
|
||||
}
|
||||
```
|
||||
|
||||
#### [NEW] [PluginManager.ts](file:///c:/dev/World%20Wide%20View/src/core/plugins/PluginManager.ts)
|
||||
- Plugin lifecycle (register, initialize, enable, disable, destroy)
|
||||
- Routes data from plugins → `LayerRenderer`
|
||||
- Manages polling per plugin
|
||||
- Emits events via `DataBus`
|
||||
|
||||
#### [NEW] [PluginRegistry.ts](file:///c:/dev/World%20Wide%20View/src/core/plugins/PluginRegistry.ts)
|
||||
- Static registry of built-in plugins + dynamic registration API
|
||||
|
||||
---
|
||||
|
||||
### Built-in Plugins (3 for MVP)
|
||||
|
||||
#### [NEW] Aviation — [src/plugins/aviation/](file:///c:/dev/World%20Wide%20View/src/plugins/aviation/)
|
||||
- **Source**: OpenSky Network REST API
|
||||
- **Rendering**: Aircraft billboards with heading rotation, altitude coloring
|
||||
- **Polling**: 10s | **Backend proxy**: `/api/aviation`
|
||||
|
||||
#### [NEW] Maritime — [src/plugins/maritime/](file:///c:/dev/World%20Wide%20View/src/plugins/maritime/)
|
||||
- **Source**: Public AIS feeds
|
||||
- **Rendering**: Ship icons, color-coded by vessel type
|
||||
- **Polling**: 60s | **Backend proxy**: `/api/maritime`
|
||||
|
||||
#### [NEW] Wildfire — [src/plugins/wildfire/](file:///c:/dev/World%20Wide%20View/src/plugins/wildfire/)
|
||||
- **Source**: NASA FIRMS (VIIRS thermal hotspots)
|
||||
- **Rendering**: Heat-colored point clusters (FRP intensity)
|
||||
- **Polling**: 5min | **Backend proxy**: `/api/wildfire`
|
||||
|
||||
---
|
||||
|
||||
### UI Components
|
||||
|
||||
Dark, cinematic, premium interface — glassmorphism panels floating over the globe.
|
||||
|
||||
#### [NEW] [AppShell.tsx](file:///c:/dev/World%20Wide%20View/src/components/layout/AppShell.tsx)
|
||||
Full-viewport layout with globe as background, floating glassmorphism header, collapsible sidebars, bottom timeline.
|
||||
|
||||
#### [NEW] [Header.tsx](file:///c:/dev/World%20Wide%20View/src/components/layout/Header.tsx)
|
||||
Branding, Cmd+K search, region presets, time window selector, settings.
|
||||
|
||||
#### [NEW] [LayerPanel.tsx](file:///c:/dev/World%20Wide%20View/src/components/panels/LayerPanel.tsx)
|
||||
Toggleable plugin layers grouped by category with entity counts.
|
||||
|
||||
#### [NEW] [Timeline.tsx](file:///c:/dev/World%20Wide%20View/src/components/timeline/Timeline.tsx)
|
||||
Horizontal time scrubber, playback controls, event density sparkline.
|
||||
|
||||
#### [NEW] [index.css](file:///c:/dev/World%20Wide%20View/src/styles/index.css)
|
||||
Dark-mode-first design system: deep navy/charcoal palette, glassmorphism, Inter + JetBrains Mono typography, smooth micro-animations.
|
||||
|
||||
---
|
||||
|
||||
### Backend API (Next.js Route Handlers)
|
||||
|
||||
#### [NEW] [src/app/api/](file:///c:/dev/World%20Wide%20View/src/app/api/)
|
||||
Next.js Route Handlers utilizing Web Standard Request/Response APIs. Handles rate limiting, server-side data fetching (proxying), and caching (via Next.js `fetch` cache or in-memory). This replaces the need for a separate Express server.
|
||||
|
||||
#### [NEW] Route files
|
||||
- `src/app/api/aviation/route.ts` — OpenSky proxy
|
||||
- `src/app/api/maritime/route.ts` — AIS proxy
|
||||
- `src/app/api/wildfire/route.ts` — NASA FIRMS proxy
|
||||
|
||||
---
|
||||
|
||||
### State Management
|
||||
|
||||
#### [NEW] [store.ts](file:///c:/dev/World%20Wide%20View/src/core/state/store.ts)
|
||||
Zustand store with slices: `globe`, `layers`, `timeline`, `ui`, `data`.
|
||||
|
||||
---
|
||||
|
||||
## Verification Plan
|
||||
|
||||
### Automated Tests
|
||||
|
||||
**Build verification:**
|
||||
```bash
|
||||
cd "c:\dev\World Wide View"
|
||||
npm run build
|
||||
```
|
||||
|
||||
**Type checking:**
|
||||
```bash
|
||||
cd "c:\dev\World Wide View"
|
||||
npx tsc --noEmit
|
||||
```
|
||||
|
||||
### Browser Verification
|
||||
1. Open `http://localhost:5173` → CesiumJS globe renders with terrain, header/sidebar/timeline visible
|
||||
2. Enable aviation layer → aircraft icons appear, clicking shows detail
|
||||
3. Enable wildfire layer → fire hotspots render as colored points
|
||||
4. Scrub timeline → data filters by time window
|
||||
5. Click region presets → smooth cinematic fly-to animations
|
||||
|
||||
### Manual Verification
|
||||
1. Run `npm run dev` — starts the Next.js integrated development server
|
||||
2. Verify 3D globe renders with terrain and satellite imagery (ensuring SSR is properly disabled for the globe component)
|
||||
3. Toggle layers via layer panel
|
||||
4. Drag timeline to filter events
|
||||
5. Test camera preset fly-tos
|
||||
6. Resize browser — panels collapse gracefully
|
||||
|
||||
> [!TIP]
|
||||
> First run requires `VITE_CESIUM_TOKEN` in `.env` (free from [cesium.com/ion](https://cesium.com/ion)). App shows a warning if missing but still renders a basic globe.
|
||||
@@ -1,38 +1,89 @@
|
||||
<div align="center">
|
||||
|
||||
<!-- Generated: 2026-04-23 06:11:00 UTC -->
|
||||
# WorldWideView
|
||||
|
||||
**WorldWideView** is a modular, real-time geospatial intelligence engine built on top of a CesiumJS 3D globe. It is designed to ingest live data streams, transform them through a generalized plugin system, and render them as high-performance visual layers.
|
||||
**The Open-Source, Plugin-Driven Geospatial Intelligence Engine**
|
||||
|
||||
As a real-time situational awareness platform, it turns raw geospatial signals—such as aircraft positions, maritime AIS, or satellite orbits—into interactive, cinematic layers on a high-fidelity 3D globe.
|
||||
*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.*
|
||||
|
||||
## Key Philosophies
|
||||

|
||||
|
||||
- **Modular Intelligence**: Every data source is a plugin. The core engine is data-agnostic.
|
||||
- **High-Performance Rendering**: Engineered for scale using Cesium primitives to handle 100,000+ objects smoothly.
|
||||
- **Situational Awareness**: Designed for real-time updates and cinematic visualization (orientated icons, smooth tracking).
|
||||
- **Extensible & Open**: Add new intelligence layers without touching the core architecture.
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
git clone https://github.com/your-repo/worldwideview.git
|
||||
cd worldwideview
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Visit `http://localhost:3000` to see the live globe.
|
||||
|
||||
## Fair-Use Notice
|
||||
|
||||
This application may contain copyrighted material the use of which has not always been specifically authorized by the copyright owner. Such material is made available for educational purposes, situational awareness, and to advance understanding of global events. It is believed that this constitutes a "fair use" of any such copyrighted material as provided for in section 107 of the US Copyright Law.
|
||||
|
||||
## Key Documentation Sections
|
||||
|
||||
- **[Setup & Installation Guide](docs/SETUP.md)**: Detailed environment and local development setup.
|
||||
- **[Architecture (Engineering Depth)](docs/ARCHITECTURE.md)**: Deep dive into the Cesium rendering pipeline, event data bus, and performance optimizations.
|
||||
- **[Plugin System Guide](docs/PLUGIN_GUIDE.md)**: How to build and register custom data layers.
|
||||
- **[User Guide](docs/USER_GUIDE.md)**: Application features and navigation tips.
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
For a full list of resources, see the **[Documentation Index](docs/index.md)**.
|
||||
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.
|
||||
|
||||
## Core Technologies
|
||||
|
||||
- **Frontend:** Next.js 16 (App Router), React 19, TypeScript 5
|
||||
- **3D Engine:** CesiumJS + Resium (Google Photorealistic 3D Tiles)
|
||||
- **State Management:** Zustand
|
||||
- **Event Bus:** Custom typed `DataBus` for high-frequency WebSocket updates
|
||||
- **Database:** PostgreSQL via Prisma 7
|
||||
- **Deployment:** Docker multi-stage build, Coolify
|
||||
|
||||
## Quick Start (Self-Hosting)
|
||||
|
||||
WorldWideView uses a multi-stage Dockerfile designed for standalone output. To deploy instantly on your own server:
|
||||
|
||||
**Mac/Linux:**
|
||||
```bash
|
||||
mkdir worldwideview && cd worldwideview
|
||||
curl -fsSL https://raw.githubusercontent.com/silvertakana/worldwideview/main/setup.sh | bash
|
||||
```
|
||||
|
||||
**Windows (PowerShell):**
|
||||
```powershell
|
||||
mkdir worldwideview; cd worldwideview
|
||||
Invoke-WebRequest -Uri https://raw.githubusercontent.com/silvertakana/worldwideview/main/setup.ps1 -UseBasicParsing | Invoke-Expression
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> Ensure you connect a PostgreSQL database via the `DATABASE_URL` environment variable for production deployments.
|
||||
|
||||
## Quick Start (Local Development)
|
||||
|
||||
To run the source code locally for contributing or developing:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/silvertakana/worldwideview.git
|
||||
cd worldwideview
|
||||
pnpm install
|
||||
pnpm run setup # generates .env.local with AUTH_SECRET
|
||||
pnpm run dev:all # boots the UI, cache layers, and the data engine
|
||||
```
|
||||
Visit `http://localhost:3000` to see the live globe.
|
||||
|
||||
## 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.
|
||||
|
||||
- **[Plugin Quickstart Guide](docs/plugin-quickstart.md)**: Learn how to scaffold and link your first plugin using the `@worldwideview/cli`.
|
||||
- **[Advanced Plugin Guide](docs/plugin-advanced.md)**: Deep dive into microservice data seeders, WebSockets, complex 3D rendering, and Marketplace publishing.
|
||||
|
||||
## Repository Ecosystem
|
||||
|
||||
WorldWideView is distributed across several specialized repositories:
|
||||
|
||||
1. **`worldwideview`** (This Repo): Main frontend, CesiumJS rendering engine, and core plugin framework.
|
||||
2. **`wwv-data-engine`**: Open-source community data backend for polling public APIs.
|
||||
3. **`worldwideview-plugins`**: First-party maintained plugins.
|
||||
4. **`worldwideview-marketplace`**: The web application driving the plugin directory.
|
||||
5. **`worldwideview-web`**: Marketing and landing site.
|
||||
|
||||
## Documentation Index
|
||||
|
||||
Explore our comprehensive documentation suite for detailed engineering insights:
|
||||
|
||||
- **[Project Overview](docs/project-overview.md)**: High-level value proposition and technology stack.
|
||||
- **[Architecture](docs/architecture.md)**: DataBus event stream and Zustand state management.
|
||||
- **[Build System](docs/build-system.md)**: Monorepo structure, Next.js standalone output, and Docker builds.
|
||||
- **[Development](docs/development.md)**: Coding conventions and common implementation patterns.
|
||||
- **[Testing](docs/testing.md)**: Vitest setup and coverage targets.
|
||||
- **[Deployment](docs/deployment.md)**: Coolify integration and persistent volumes.
|
||||
- **[Files Catalog](docs/files.md)**: Comprehensive mapping of core source files.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **Fair-Use Notice:** This application may contain copyrighted material the use of which has not always been specifically authorized by the copyright owner. Such material is made available for educational purposes, situational awareness, and to advance understanding of global events under "fair use" (Section 107 of the US Copyright Law).
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
# WorldWideView — Implementation Roadmap
|
||||
|
||||
Each stage is **self-contained and demo-able**. Any stage can be shipped independently.
|
||||
|
||||
---
|
||||
|
||||
## Stage 1: Plugin SDK & Manifest Schema ✅
|
||||
**Demo:** "Here's the schema that defines a plugin. Our existing aviation plugin has a manifest file."
|
||||
|
||||
- [x] `plugin.json` manifest files for each existing plugin
|
||||
- [x] Manifest validation logic (`validateManifest()`)
|
||||
- [x] `type` field on `WorldPlugin` interface (`"data-layer" | "extension"`)
|
||||
- [x] `capabilities` field on `WorldPlugin` interface
|
||||
- [x] `@worldwideview/wwv-plugin-sdk` npm package — shared types published to npm
|
||||
|
||||
---
|
||||
|
||||
## Stage 2: Marketplace Browse UI (Static Catalog) ✅
|
||||
**Demo:** "Open the marketplace, see all available plugins with categories and search."
|
||||
|
||||
- [x] `worldwideview-marketplace` repo (Next.js)
|
||||
- [x] Browse page — grid of plugin cards with icons, descriptions, categories
|
||||
- [x] Search + category filter
|
||||
- [x] Plugin detail page (readme, version history, install count)
|
||||
|
||||
---
|
||||
|
||||
## Stage 3: Prisma ORM & Local Database ✅
|
||||
**Demo:** "Run `pnpm run dev` on a fresh clone with a valid DATABASE_URL. App works seamlessly."
|
||||
|
||||
- [x] Prisma (`prisma` + `@prisma/client`)
|
||||
- [x] Schema: `InstalledPlugin`, `Setting`, `User`, `AviationHistory`, `NpmCache`
|
||||
- [x] PostgreSQL default: `DATABASE_URL` required
|
||||
- [x] `predev` script: `prisma migrate deploy`
|
||||
- [x] DB auto-creates on first run — zero manual setup
|
||||
|
||||
---
|
||||
|
||||
## Stage 4: Bridge API & One-Click Install ✅
|
||||
**Demo:** "Click 'Install' on marketplace → plugin appears in your local WWV instance."
|
||||
|
||||
- [x] `GET /api/marketplace/install-redirect` — session-based redirect install flow
|
||||
- [x] `GET /api/marketplace/grant-token` — issues marketplace JWT without install
|
||||
- [x] `GET /api/marketplace/status` — list installed plugins (session or JWT auth)
|
||||
- [x] `POST /api/marketplace/uninstall` — delete installed plugin record
|
||||
- [x] `GET /api/marketplace/load` — serve valid manifests to client at startup
|
||||
- [x] `GET /api/auth/setup-status` — CORS-enabled connection test endpoint
|
||||
- [x] `src/lib/marketplace/marketplaceToken.ts` — `issueMarketplaceToken()` / `verifyMarketplaceToken()`
|
||||
- [x] `src/lib/marketplace/auth.ts` — `validateMarketplaceAuth()` (session → JWT → legacy token)
|
||||
- [x] `src/lib/marketplace/registryClient.ts` — Ed25519 registry verification + 5-min cache
|
||||
- [x] Marketplace: `InstanceConfig`, `InstallButton`, `useInstalledPlugins`, `InstalledPluginCard`, Manage page
|
||||
- [x] NPM-driven submission: Admin enters package name → marketplace fetches + parses `"worldwideview"` block from `package.json`
|
||||
- [x] `NpmCache` table — decouples marketplace from live NPM registry
|
||||
|
||||
---
|
||||
|
||||
## Stage 5: AI & Sharing Features (Immediate User Value)
|
||||
**Demo:** "Chat with the AI to explore the globe, record a narrated briefing, and share the view via a URL."
|
||||
|
||||
- [ ] Unified Data Format schema (WWVDocument) with snapshot radius bounding
|
||||
- [ ] Base64url view link sharing (`#v=...`)
|
||||
- [ ] Shared `ActionExecutor` core for Animation & Copilot
|
||||
- [ ] Animation Engine (TrackScheduler, Player, overlays, TTS voice)
|
||||
- [ ] MCP Server (tools wrapping the action vocabulary)
|
||||
- [ ] Hybrid Spatial Awareness (Pre-computed summaries + MCP spatial query tools)
|
||||
|
||||
---
|
||||
|
||||
## Stage 6: Publisher Workflow
|
||||
**Demo:** "A plugin author submits their plugin. After review, it appears in the catalog."
|
||||
|
||||
- [ ] Marketplace user accounts (Supabase Auth — email/password + GitHub OAuth)
|
||||
- [ ] Publisher submission form (upload bundle, fill metadata, declare capabilities)
|
||||
- [ ] Admin review queue (approve/reject with notes)
|
||||
- [ ] Version management (semver, changelogs)
|
||||
- [ ] Publisher dashboard (install counts, download analytics)
|
||||
- [ ] Publisher namespaces (`publisher.plugin-name`)
|
||||
|
||||
---
|
||||
|
||||
## Stage 7: Cloud Platform & Accounts
|
||||
**Demo:** "User registers, gets [user].app.worldwideview.dev, installs plugins from marketplace."
|
||||
|
||||
- [ ] `app.worldwideview.dev` — auth/register/dashboard
|
||||
- [ ] Auto-provisioning on signup (tenant DB row → instance live immediately)
|
||||
- [ ] RLS tenant isolation in PostgreSQL
|
||||
- [ ] Cloud edition adapters (`auth.ts`, `storage.ts`, `tenant.ts`)
|
||||
- [ ] Runtime settings store + setup wizard
|
||||
- [ ] License key validation with RSA public key
|
||||
- [ ] Tier gating (free/pro/enterprise feature flags)
|
||||
- [ ] Cloudflare Turnstile + nginx rate limiting for bot prevention
|
||||
- [ ] SSO: marketplace redirects to `app.worldwideview.dev` for login
|
||||
|
||||
---
|
||||
|
||||
## Stage 8: Built-In Data Services
|
||||
**Demo:** "Aviation and maritime data with full history, served from api.worldwideview.dev."
|
||||
|
||||
- [ ] `api.worldwideview.dev` — aviation/maritime polling + persistence
|
||||
- [ ] Redesign aviation as declarative plugin pointing to `api.worldwideview.dev`
|
||||
- [ ] Redesign maritime the same way
|
||||
- [ ] History/timeline with `%t` parameter substitution
|
||||
- [ ] Snapshot capture (pro tier — counts toward storage quota)
|
||||
- [ ] API key proxy with per-tenant-per-plugin rate limiting and response caching
|
||||
|
||||
---
|
||||
|
||||
## Stage 9: Trust Tiers, Extensions & Polish
|
||||
**Demo:** "Install a verified extension plugin that adds cockpit view to aviation."
|
||||
|
||||
- [x] Ed25519-signed plugin registry (`GET /api/registry` on marketplace)
|
||||
- [x] Server-side trust stamping at install time
|
||||
- [x] Trust tier badges (`TrustBadge` component — Official / Verified / Unverified)
|
||||
- [x] Unverified plugin warning dialog (`UnverifiedPluginDialog` + `useMarketplaceSync`)
|
||||
- [ ] Extension plugin type support in `PluginManager`
|
||||
- [ ] Activation events and contribution points
|
||||
- [ ] Capability enforcement at runtime (`PluginPermissionError`)
|
||||
- [ ] Web Worker sandboxing for unverified plugins (`comlink`)
|
||||
- [ ] Reviews & ratings system
|
||||
- [ ] Extension packs (bundles of related plugins)
|
||||
- [ ] Auto-update mechanism (local: manual opt-in; cloud: automatic CDN swap)
|
||||
- [ ] Plausible/Umami self-hosted analytics
|
||||
|
||||
---
|
||||
|
||||
## Stage 10: Infrastructure & Monetization
|
||||
**Demo:** "Buy Pro, paste license key, unlock snapshot history and higher rate limits."
|
||||
|
||||
- [ ] Coolify on ThinkPad T480s — deploy all services
|
||||
- [ ] Uptime Kuma monitoring (all subdomains)
|
||||
- [ ] Stripe Checkout for license purchase
|
||||
- [ ] Storage quota enforcement (cloud only)
|
||||
- [ ] Stripe Connect for marketplace revenue split on paid plugins
|
||||
- [ ] Cloudflare R2 as CDN for plugin bundles (`cdn.worldwideview.dev`)
|
||||
|
||||
---
|
||||
|
||||
## Resolved Architectural Decisions
|
||||
|
||||
| Decision | Resolution |
|
||||
|---|---|
|
||||
| **License** | EL2.0 for WorldWideView core; Open Source for marketplace |
|
||||
| **Shared types** | `@worldwideview/plugin-sdk` npm package (MIT) |
|
||||
| **Hosting** | Coolify (ThinkPad T480s). Landing page on Vercel (static export) |
|
||||
| **Database** | PostgreSQL, Prisma ORM |
|
||||
| **Tenant isolation** | Row-Level Security (RLS) in shared PostgreSQL |
|
||||
| **User settings** | Runtime settings store in DB, not `.env` |
|
||||
| **Bot prevention** | Email verification + Cloudflare Turnstile + rate limiting |
|
||||
| **Plugin execution** | Client-side (browser), not server-side |
|
||||
| **Plugin architecture** | VS Code model — activation events, contribution points, namespaces |
|
||||
| **Server-side compute** | Not supported — third-party backends handle compute |
|
||||
| **Auth** | Auth.js on `app.worldwideview.dev`. `Credentials` (local), `@auth/supabase-adapter` (cloud). Marketplace uses SSO redirect |
|
||||
| **Instance provisioning** | Auto-provision on signup — just a DB row insert |
|
||||
| **API proxy** | `apikey` plugins routed through cached proxy, per-tenant-per-plugin rate limits |
|
||||
| **History** | Third-party `historyUrl` with `%t` (all tiers), WWV snapshot capture (pro only) |
|
||||
| **Built-in data** | Aviation/maritime → declarative plugins → `api.worldwideview.dev` |
|
||||
| **CI/CD** | GitHub Actions → GHCR → Coolify webhook |
|
||||
| **Plugin trust registry** | Ed25519-signed JSON, public key hardcoded in WWV, trust stamped server-side at install |
|
||||
| **Package manager** | pnpm workspaces (migrated from npm) |
|
||||
| **NPM submission flow** | Admin enters package name → marketplace infers manifest from `"worldwideview"` block in `package.json` |
|
||||
| **NPM caching** | `NpmCache` table decouples marketplace from live NPM registry |
|
||||
@@ -1,46 +0,0 @@
|
||||
# WorldWideView — Phase 1 MVP Task Breakdown
|
||||
|
||||
## Planning
|
||||
- [/] Explore existing codebase and understand project state
|
||||
- [/] Write implementation plan for Phase 1 MVP
|
||||
- [ ] Get user approval on implementation plan
|
||||
|
||||
## Phase 1: Project Scaffolding
|
||||
- [ ] Initialize Next.js + TypeScript project with App Router
|
||||
- [ ] Configure CesiumJS integration (Webpack, static assets, SSR bypass)
|
||||
- [ ] Set up design system (CSS custom properties, glassmorphism, typography)
|
||||
- [ ] Configure Zustand state management
|
||||
- [ ] Set up path aliases and project structure
|
||||
|
||||
## Phase 2: Core Globe Component
|
||||
- [ ] Implement `GlobeView.tsx` — CesiumJS viewer with Google 3D Tiles
|
||||
- [ ] Implement `CameraController.ts` — cinematic fly-to, orbit mode, presets
|
||||
- [ ] Implement `LayerRenderer.ts` — entity rendering, clustering, progressive disclosure
|
||||
- [ ] Implement `TimelineSync.ts` — clock sync, time-window filtering, playback
|
||||
|
||||
## Phase 3: Plugin System
|
||||
- [ ] Define `PluginTypes.ts` — `WorldPlugin` interface, `GeoEntity`, `LayerConfig`
|
||||
- [ ] Implement `PluginManager.ts` — lifecycle, polling, data routing
|
||||
- [ ] Implement `PluginRegistry.ts` — static + dynamic registration
|
||||
- [ ] Implement `DataBus.ts` — event bus for cross-plugin communication
|
||||
- [ ] Implement `CacheLayer.ts` — in-memory + IndexedDB caching
|
||||
- [ ] Implement `PollingManager.ts` — per-plugin refresh
|
||||
|
||||
## Phase 4: Built-in Plugins (MVP)
|
||||
- [ ] Aviation plugin (OpenSky Network)
|
||||
- [ ] Maritime plugin (AIS feeds)
|
||||
- [ ] Wildfire plugin (NASA FIRMS)
|
||||
- [ ] Backend API proxy routes for each plugin
|
||||
|
||||
## Phase 5: UI Components
|
||||
- [ ] `AppShell.tsx` — full-viewport layout with floating panels
|
||||
- [ ] `Header.tsx` — branding, search, region presets, time selector
|
||||
- [ ] `LayerPanel.tsx` — toggleable layer list grouped by category
|
||||
- [ ] `Timeline.tsx` — horizontal scrubber with playback controls
|
||||
- [ ] `IntelPanel.tsx` — entity detail and intelligence sidebar
|
||||
- [ ] Global CSS design system (dark mode, glassmorphism, animations)
|
||||
|
||||
## Phase 6: Verification
|
||||
- [ ] Build verification (`npm run build` + type-check)
|
||||
- [ ] Browser verification — globe renders, layers toggle, camera presets work
|
||||
- [ ] Manual verification — time scrubbing, responsive layout, API proxies
|
||||
@@ -0,0 +1,7 @@
|
||||
# This file lists tools managed by Aftman, a cross-platform toolchain manager.
|
||||
# For more information, see https://github.com/LPGhatguy/aftman
|
||||
|
||||
# To add a new tool, add an entry to this table.
|
||||
[tools]
|
||||
rojo = "rojo-rbx/[email protected]"
|
||||
# rojo = "rojo-rbx/[email protected]"
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -0,0 +1 @@
|
||||
{"message":"fix(aviation): implement exponential backoff for rate limits","tree":"55c74a09dac7ce178ecf94d5cb48b2502e57e759","parents":["e25ddc0b648b757ea32b7376bab50d8e75d6d330"]}
|
||||
@@ -0,0 +1,54 @@
|
||||
const fs = require("fs");
|
||||
const { execSync } = require("child_process");
|
||||
|
||||
const uuidsToDelete = [
|
||||
"i331gbc1zzytx7via8lntdm6",
|
||||
"pow71xsobdas7etf5r3hy5ug",
|
||||
"l79dyd03lhtcpgi7swkoxm55",
|
||||
"ry6160tpy4gh2xjfwr011no0",
|
||||
"gfe78t8jm53lltentz19ze60",
|
||||
"e1cg7q8khyvpti5rkp351559",
|
||||
"c35cvvqxhdbslk8yc24g04wk",
|
||||
"ijj9pqkavlusy2wmzsbjtc74",
|
||||
"ghe6bzlr6ex6j51lgxzyhd46",
|
||||
"h3v45w2u1essulzeg56i27a3",
|
||||
"oxk05amog4fla0lskmkfx64x",
|
||||
"yxm4mn60lfp9qah0q4yf2hij",
|
||||
"ezjxo4ehs96lv0ji1n2r0auw",
|
||||
"t12x7pgptsqiu5gbvv35gun5",
|
||||
"urq1ll00a3vv9on6pulmpofe",
|
||||
"eb5zgw5wlgvio2gggbiphpam",
|
||||
"ld1h3pody4nxj3b44pbskl53",
|
||||
"x111xfygqxrlbf5wqlx59f6d",
|
||||
"se1weqr4dj7thp4p1l055wfc",
|
||||
"cqses6urxff0n94i0u6lktzt",
|
||||
"nvcir33nyuvzk5niy3s7eg9w",
|
||||
"s63onga2s6v8r3k10lrdwzth",
|
||||
"cf3uedqnjmwv48h7tm91d95r",
|
||||
"o9124dnnieau9wxoefyxvfgu",
|
||||
"kxzobc8qlvigbsk1d35dpiyi",
|
||||
"eh8lzjbsy2c9kwj2emztcmf6",
|
||||
"umfsos2vcmotfk2cfpqdoycc",
|
||||
"yn1mdh0fngiati6r4625qvv9"
|
||||
];
|
||||
|
||||
const token = "1|vPZPgvB8vVi8ZD5ZKS8lrCrwNlPofVv4I8Tjmqmyd01f92d2";
|
||||
const baseUrl = "https://coolify.worldwideview.dev/api/v1";
|
||||
const appUuid = "nmn55t4io3myfubs72worn7k";
|
||||
|
||||
async function run() {
|
||||
for (const id of uuidsToDelete) {
|
||||
console.log("Deleting", id);
|
||||
try {
|
||||
const res = await fetch(`${baseUrl}/applications/${appUuid}/envs/${id}`, {
|
||||
method: "DELETE",
|
||||
headers: { "Authorization": `Bearer ${token}` }
|
||||
});
|
||||
console.log(id, res.status);
|
||||
} catch(e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
run();
|
||||
@@ -0,0 +1,7 @@
|
||||
SUPABASE_PG_URL=postgresql://postgres:[email protected]:5432/postgres
|
||||
SUPABASE_URL=https://xyz.supabase.co
|
||||
SUPABASE_ANON_KEY=eyJ...
|
||||
SUPABASE_SERVICE_ROLE_KEY=eyJ...
|
||||
ACME_EMAIL=[email protected]
|
||||
STRIPE_SECRET_KEY=sk_test_...
|
||||
STRIPE_WEBHOOK_SECRET=whsec_...
|
||||
@@ -0,0 +1,47 @@
|
||||
services:
|
||||
db:
|
||||
image: postgres:15-alpine
|
||||
environment:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: password
|
||||
POSTGRES_DB: postgres
|
||||
ports:
|
||||
- "5432:5432"
|
||||
|
||||
wwv-cloud:
|
||||
build:
|
||||
context: ../..
|
||||
dockerfile: Dockerfile
|
||||
args:
|
||||
- NEXT_PUBLIC_WWV_EDITION=cloud
|
||||
restart: always
|
||||
environment:
|
||||
NEXT_PUBLIC_WWV_EDITION: cloud
|
||||
DATABASE_URL: postgresql://postgres:password@db:5432/postgres
|
||||
NEXT_PUBLIC_SUPABASE_URL: ${SUPABASE_URL:-http://dummy}
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY: ${SUPABASE_ANON_KEY:-dummy}
|
||||
SUPABASE_SERVICE_ROLE_KEY: ${SUPABASE_SERVICE_ROLE_KEY:-dummy}
|
||||
AUTH_SECRET: ${AUTH_SECRET:-dummy_secret_for_local_testing_only_1234567890}
|
||||
ports:
|
||||
- "3001:3000"
|
||||
labels:
|
||||
- "traefik.enable=true"
|
||||
- "traefik.http.routers.wwv.rule=HostRegexp(`{user:[a-z0-9-]+}.app.worldwideview.dev`) || Host(`app.worldwideview.dev`) || Host(`localhost`) || HostRegexp(`{user:[a-z0-9-]+}.localhost`)"
|
||||
- "traefik.http.routers.wwv.entrypoints=web,websecure"
|
||||
# - "traefik.http.routers.wwv.tls.certresolver=letsencrypt"
|
||||
- "traefik.http.services.wwv.loadbalancer.server.port=3000"
|
||||
depends_on:
|
||||
- db
|
||||
|
||||
traefik:
|
||||
image: traefik:v3.0
|
||||
command:
|
||||
- "--api.insecure=true"
|
||||
- "--providers.docker=true"
|
||||
- "--entrypoints.web.address=:80"
|
||||
- "--entrypoints.websecure.address=:443"
|
||||
ports:
|
||||
- "80:80"
|
||||
- "443:443"
|
||||
volumes:
|
||||
- "/var/run/docker.sock:/var/run/docker.sock:ro"
|
||||
@@ -0,0 +1,40 @@
|
||||
services:
|
||||
wwv:
|
||||
build: .
|
||||
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}"
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_started
|
||||
|
||||
db:
|
||||
image: postgres:15-alpine
|
||||
restart: always
|
||||
environment:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: postgres
|
||||
POSTGRES_DB: worldwideview
|
||||
ports:
|
||||
- "5432:5432"
|
||||
volumes:
|
||||
- postgres-data:/var/lib/postgresql/data
|
||||
profiles:
|
||||
- "${WWV_SKIP_LOCAL_DB:-}"
|
||||
|
||||
volumes:
|
||||
wwv-data:
|
||||
postgres-data:
|
||||
|
||||
networks:
|
||||
coolify:
|
||||
external: true
|
||||
@@ -0,0 +1,26 @@
|
||||
#!/bin/sh
|
||||
# ─── Docker Entrypoint ───────────────────────────────────────
|
||||
# Ensures the PostgreSQL database is migrated before starting
|
||||
# the application. DATABASE_URL must point to a PostgreSQL
|
||||
# instance (Supabase, self-hosted, etc).
|
||||
|
||||
set -e
|
||||
|
||||
echo "[entrypoint] Running database migrations..."
|
||||
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..."
|
||||
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
|
||||
if [ -f "./scripts/https-proxy.mjs" ]; then
|
||||
node ./scripts/https-proxy.mjs &
|
||||
fi
|
||||
|
||||
exec node server.js
|
||||
@@ -1,91 +0,0 @@
|
||||
# API Reference
|
||||
|
||||
This document provides a technical reference for the core internal services of WorldWideView. These services are designed to be used by plugins and core components for communication and data management.
|
||||
|
||||
## `DataBus`
|
||||
|
||||
The `DataBus` is a central event emitter used for decoupled, typed communication between different parts of the application.
|
||||
|
||||
- **Import**: `import { dataBus } from "@/core/data/DataBus";`
|
||||
- **Source**: `src/core/data/DataBus.ts`
|
||||
|
||||
### Methods
|
||||
|
||||
#### `on<K>(event: K, handler: Handler): () => void`
|
||||
Subscribes to an event. Returns an unsubscribe function.
|
||||
- **event**: The event name (keys of `DataBusEvents`).
|
||||
- **handler**: A callback function receiving the event data.
|
||||
|
||||
#### `off<K>(event: K, handler: Handler): void`
|
||||
Unsubscribes from an event.
|
||||
- **event**: The event name.
|
||||
- **handler**: The handler function to remove.
|
||||
|
||||
#### `emit<K>(event: K, data: T): void`
|
||||
Broadcasts an event to all subscribers.
|
||||
- **event**: The event name.
|
||||
- **data**: The payload for the event.
|
||||
|
||||
#### `removeAllListeners(event?: string): void`
|
||||
Removes all listeners for a specific event, or all listeners if no event is provided.
|
||||
|
||||
---
|
||||
|
||||
## `PluginRegistry`
|
||||
|
||||
The `PluginRegistry` manages the registration and discovery of all `WorldPlugin` implementations.
|
||||
|
||||
- **Import**: `import { pluginRegistry } from "@/core/plugins/PluginRegistry";`
|
||||
- **Source**: `src/core/plugins/PluginRegistry.ts`
|
||||
|
||||
### Methods
|
||||
|
||||
#### `register(plugin: WorldPlugin): void`
|
||||
Adds a new plugin to the registry. Throws a warning if the plugin ID is already registered.
|
||||
|
||||
#### `get(pluginId: string): WorldPlugin | undefined`
|
||||
Retrieves a plugin by its unique ID.
|
||||
|
||||
#### `getAll(): WorldPlugin[]`
|
||||
Returns an array of all registered plugins.
|
||||
|
||||
#### `getByCategory(category: string): WorldPlugin[]`
|
||||
Returns all plugins belonging to a specific category.
|
||||
|
||||
#### `has(pluginId: string): boolean`
|
||||
Checks if a plugin with the given ID is registered.
|
||||
|
||||
#### `unregister(pluginId: string): void`
|
||||
Removes a plugin from the registry.
|
||||
|
||||
---
|
||||
|
||||
## `CacheLayer`
|
||||
|
||||
The `CacheLayer` provides a two-tier caching mechanism for geographical entities.
|
||||
|
||||
- **Import**: `import { cacheLayer } from "@/core/data/CacheLayer";`
|
||||
- **Source**: `src/core/data/CacheLayer.ts`
|
||||
|
||||
### Methods
|
||||
|
||||
#### `init(): Promise<void>`
|
||||
Initializes the IndexedDB store. Must be called before persistent storage operations.
|
||||
|
||||
#### `set(pluginId: string, entities: GeoEntity[], ttlMs?: number): void`
|
||||
Caches entities for a plugin.
|
||||
- **pluginId**: Unique identifier for the data source.
|
||||
- **entities**: Array of `GeoEntity` objects.
|
||||
- **ttlMs**: Time-to-live in milliseconds (default: 30,000).
|
||||
|
||||
#### `get(pluginId: string): GeoEntity[] | null`
|
||||
Retrieves entities from the L1 (Memory) cache. Returns `null` if expired or missing.
|
||||
|
||||
#### `getFromPersistent(pluginId: string): Promise<GeoEntity[] | null>`
|
||||
Retrieves entities from the L2 (IndexedDB) cache. This method also populates the L1 cache on success.
|
||||
|
||||
#### `invalidate(pluginId: string): void`
|
||||
Removes entries for a plugin from both L1 and L2 caches.
|
||||
|
||||
#### `clear(): void`
|
||||
Purges all data from both cache tiers.
|
||||
+27
-56
@@ -1,62 +1,33 @@
|
||||
# System Architecture
|
||||
<!-- Generated: 2026-04-23 06:11:00 UTC -->
|
||||
# Architecture
|
||||
|
||||
WorldWideView is a high-performance, event-driven geospatial intelligence engine. It is designed to ingest live, fast-moving signals—such as aviation ADS-B, maritime AIS, or satellite feeds—and transform them into cinematic, real-time visual layers on a 3D globe.
|
||||
## Overview
|
||||
WorldWideView operates on a decoupled, plugin-based architecture designed for real-time visualization of geospatial data. The system is split between a Next.js 16 frontend that handles UI and CesiumJS 3D rendering, and a network of plugin data seeders that stream live updates via WebSockets.
|
||||
|
||||
## Module Breakdown
|
||||
The core design philosophy is the "All-Bundle Model," where plugins are dynamically imported at runtime as ES module bundles (`Dynamic CDN Loaded`). The frontend maintains a modular state architecture using Zustand, routing high-frequency data updates through a custom `DataBus` singleton to avoid React render cycle bottlenecks.
|
||||
|
||||
1. **`src/core/plugins`**: The registration and lifecycle management layer. Defines how plugins are booted and destroyed.
|
||||
2. **`src/core/data`**: The "Heartbeat" of the system.
|
||||
- **DataBus**: Decentralized event pipeline for all system actions.
|
||||
- **PollingManager**: Intelligent scheduler for external API calls with backoff logic.
|
||||
- **CacheLayer**: 2-stage persistent caching (In-Memory + IndexedDB).
|
||||
3. **`src/core/globe`**: The Rendering Engine.
|
||||
- **Cesium Integration**: Low-level control over the Cesium Viewer.
|
||||
- **EntityRenderer**: High-performance "Primitive" renderer.
|
||||
4. **`src/plugins`**: Domain-specific logic (Aviation, Maritime, etc.).
|
||||
## Component Map
|
||||
- **Frontend App Shell:** Next.js App Router providing layout and base API routes (in `src/app/`).
|
||||
- **Globe Rendering Engine:** CesiumJS wrapped in Resium, responsible for 3D primitive and model rendering (in `src/core/globe/`).
|
||||
- **State Management:** Zustand slice-based architecture (in `src/core/state/`).
|
||||
- **Data Pipeline:** Custom event bus (`DataBus`) and WebSocket clients (`DataBusSubscriber`) routing live data to state (in `src/core/data/`).
|
||||
- **Plugin System:** Registration, lifecycle management, and ES module loaders (in `src/core/plugins/`).
|
||||
- **Database Layer:** Prisma ORM connecting to PostgreSQL (in `prisma/`).
|
||||
|
||||
## Performance: Primitives vs. Entities
|
||||
## Key Files
|
||||
- `src/core/plugins/PluginManager.ts` - The PluginManager class. Core registry that instantiates plugins, calls `initialize()`, and handles lifecycle events.
|
||||
- `src/core/plugins/loaders/InstalledPluginsLoader.ts` - Dynamically fetches and imports `import(/* webpackIgnore: true */ ...)` marketplace plugins into the environment.
|
||||
- `src/core/data/DataBus.ts` - Custom typed event bus singleton that routes high-frequency data around the application.
|
||||
- `src/core/globe/GlobeView.tsx` - The main Cesium viewer container, handling imagery layers, cameras, and primitive collections.
|
||||
- `src/core/state/store.ts` - The main Zustand store registry linking the nine state slices (globe, layers, timeline, ui, filter, data, config, favorites, geojson).
|
||||
|
||||
One of our core design decisions is using **Cesium Primitives** instead of the standard high-level **Entity API** for high-count datasets.
|
||||
## Data Flow
|
||||
Real-time data follows a strict unidirectional stream optimized for sub-second updates:
|
||||
|
||||
| Feature | Entity API | Primitive API (WWV) |
|
||||
|---|---|---|
|
||||
| **Abstration** | High (Easy to use) | Low (Direct GPU access) |
|
||||
| **Overhead** | Significant per-entity JS objects | Minimal (Batched rendering) |
|
||||
| **Max Capacity** | ~1,000 entities | **100,000+ points/billboards** |
|
||||
| **WWV Use Case** | Info window content | Live data point visualization |
|
||||
|
||||
**Why?** The Entity API in Cesium is great for rich features but triggers significant CPU overhead when managing thousands of moving objects. By using `PointPrimitiveCollection` and `BillboardCollection`, WorldWideView batches these draw calls, ensuring 60FPS even with dense global data.
|
||||
|
||||
## Data Pipeline (Example: Aviation)
|
||||
|
||||
The following diagram trace the journey of a single data point from a remote sensor to the user's screen:
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant S as Remote API (e.g. OpenSky)
|
||||
participant P as Plugin (AviationPlugin)
|
||||
participant D as DataBus
|
||||
participant R as EntityRenderer
|
||||
participant G as GPU (Cesium)
|
||||
|
||||
Note over S, P: Polling Interval (e.g. 30s)
|
||||
S->>P: raw JSON data
|
||||
rect rgb(200, 230, 255)
|
||||
Note right of P: Mapping to GeoEntity
|
||||
P->>P: parse, filter, sanitize
|
||||
end
|
||||
P->>D: emit("dataUpdated", { entities })
|
||||
D->>R: trigger render cycle
|
||||
rect rgb(255, 230, 200)
|
||||
Note right of R: Batch Update Primitives
|
||||
R->>G: update collection buffer
|
||||
end
|
||||
G-->>G: 60FPS visualization
|
||||
```
|
||||
|
||||
## Design Principles
|
||||
|
||||
- **Single Responsibility (SRP)**: Plugins only handle data mapping; they don't know about the UI or the Cache.
|
||||
- **Dependency Inversion**: The `PluginManager` communicates with plugins through the `WorldPlugin` interface, allowing new plugins to be added without modifying core code.
|
||||
- **Event-Driven Architecture**: The system is reactive. Components subscribe to what they need, reducing prop-drilling and unnecessary re-renders.
|
||||
- **Defensive Programming**: All external API calls in plugins are wrapped in error boundaries and handled by the `PollingManager`'s backoff logic to prevent system-wide failures.
|
||||
1. **Engine Push:** A remote data engine pushes state over WebSocket (`/stream`) from either local seeders (`ws://localhost:5001/stream`) or the cloud fallback (`wss://dataengine.worldwideview.dev/stream`).
|
||||
2. **WebSocket Client Router:** `WsClient.handleMessage()` receives the payload and pipes it to the event bus.
|
||||
3. **DataBus Emission:** The bus fires `DataBus.emit("websocketData", WsStreamPayload)`.
|
||||
4. **State Hydration:** The `DataBusSubscriber` component listens to the bus and calls `_hydrateSnapshot()` to update the Zustand store's `entitiesByPlugin` cache.
|
||||
5. **Memoized Selection:** `GlobeView` selects the visible entities from the store.
|
||||
6. **Primitive Rendering:** The `EntityRenderer` translates store entities into Cesium `PointPrimitiveCollection` and `BillboardCollection` arrays for GPU rendering.
|
||||
7. **Animation & LOD:** `AnimationLoop` handles horizon culling and hover effects, while `useModelRendering` promotes close-range entities to 3D glTF models.
|
||||
@@ -1,452 +0,0 @@
|
||||
# WorldWideView Plugin Guide
|
||||
|
||||
Build custom data layer plugins for the WorldWideView 3D globe platform. This guide covers the full plugin lifecycle, available APIs, and step-by-step instructions for creating your own plugin.
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ UI Layer │
|
||||
│ LayerPanel ─ InfoCard ─ Timeline ─ ConfigPanel │
|
||||
└────────────────────┬────────────────────────────┘
|
||||
│ Zustand Store
|
||||
┌────────────────────┴────────────────────────────┐
|
||||
│ Plugin Manager │
|
||||
│ register → initialize → enable/disable → poll │
|
||||
│ ┌────────┴────────┐ │
|
||||
│ PluginRegistry PollingManager │
|
||||
│ │ │ │
|
||||
│ DataBus (events) CacheLayer (2-tier) │
|
||||
└────────────────────┬────────────────────────────┘
|
||||
│
|
||||
┌────────────────────┴────────────────────────────┐
|
||||
│ Your Plugin (WorldPlugin) │
|
||||
│ fetch() → GeoEntity[] → renderEntity() → Globe │
|
||||
└─────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Plugin Lifecycle
|
||||
|
||||
1. **Instantiation**: Your class is instantiated and passed to `pluginRegistry.register()`.
|
||||
2. **Registration**: The `PluginManager` discovers the plugin in the registry during the boot sequence.
|
||||
3. **Initialization**: `initialize(ctx)` is called. This is where you should set up your domain-specific API clients or static data.
|
||||
4. **Enabled State**: When a user toggles the layer in the UI, the `PluginManager` starts the polling cycle.
|
||||
5. **Fetch/Render Cycle**: `fetch()` is called periodically; `renderEntity()` is called for result.
|
||||
6. **Destruction**: `destroy()` is called if the plugin is unregistered or the application is unmounted.
|
||||
|
||||
### Data Flow
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant PM as PluginManager
|
||||
participant P as YourPlugin
|
||||
participant DB as DataBus
|
||||
|
||||
PM->>P: initialize(ctx)
|
||||
Note over PM, P: User toggles layer ON
|
||||
loop Every getPollingInterval()
|
||||
PM->>P: fetch(timeRange)
|
||||
P-->>PM: GeoEntity[]
|
||||
PM->>DB: emit("dataUpdated")
|
||||
end
|
||||
Note over PM, P: User toggles layer OFF
|
||||
PM->>PM: Stop Polling
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Quick Start: Minimal Plugin
|
||||
|
||||
```typescript
|
||||
// src/plugins/earthquakes/index.ts
|
||||
import { Activity } from "lucide-react";
|
||||
import type {
|
||||
WorldPlugin, GeoEntity, TimeRange, PluginContext,
|
||||
LayerConfig, CesiumEntityOptions,
|
||||
} from "@/core/plugins/PluginTypes";
|
||||
|
||||
export class EarthquakePlugin implements WorldPlugin {
|
||||
id = "earthquake";
|
||||
name = "Earthquakes";
|
||||
description = "Recent seismic activity from USGS";
|
||||
icon = Activity;
|
||||
category = "natural-disaster" as const;
|
||||
version = "1.0.0";
|
||||
|
||||
private context: PluginContext | null = null;
|
||||
|
||||
async initialize(ctx: PluginContext): Promise<void> {
|
||||
this.context = ctx;
|
||||
}
|
||||
|
||||
destroy(): void {
|
||||
this.context = null;
|
||||
}
|
||||
|
||||
async fetch(_timeRange: TimeRange): Promise<GeoEntity[]> {
|
||||
const res = await fetch("/api/earthquake");
|
||||
if (!res.ok) return [];
|
||||
const data = await res.json();
|
||||
return data.features.map((f: any): GeoEntity => ({
|
||||
id: `earthquake-${f.id}`,
|
||||
pluginId: "earthquake",
|
||||
latitude: f.geometry.coordinates[1],
|
||||
longitude: f.geometry.coordinates[0],
|
||||
altitude: 0,
|
||||
timestamp: new Date(f.properties.time),
|
||||
label: `M${f.properties.mag}`,
|
||||
properties: {
|
||||
magnitude: f.properties.mag,
|
||||
depth: f.geometry.coordinates[2],
|
||||
place: f.properties.place,
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
getPollingInterval(): number {
|
||||
return 120000; // 2 minutes
|
||||
}
|
||||
|
||||
getLayerConfig(): LayerConfig {
|
||||
return {
|
||||
color: "#ef4444",
|
||||
clusterEnabled: true,
|
||||
clusterDistance: 40,
|
||||
};
|
||||
}
|
||||
|
||||
renderEntity(entity: GeoEntity): CesiumEntityOptions {
|
||||
const mag = (entity.properties.magnitude as number) || 0;
|
||||
return {
|
||||
type: "point",
|
||||
color: mag >= 5 ? "#dc2626" : mag >= 3 ? "#f97316" : "#fbbf24",
|
||||
size: Math.max(4, mag * 2),
|
||||
outlineColor: "#000000",
|
||||
outlineWidth: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Register Your Plugin
|
||||
|
||||
In your app's initialization code (e.g. the root layout component):
|
||||
|
||||
```typescript
|
||||
import { pluginRegistry } from "@/core/plugins/PluginRegistry";
|
||||
import { EarthquakePlugin } from "@/plugins/earthquakes";
|
||||
|
||||
pluginRegistry.register(new EarthquakePlugin());
|
||||
```
|
||||
|
||||
That's it. The plugin will appear in the Layer Panel and can be toggled on/off.
|
||||
|
||||
---
|
||||
|
||||
## WorldPlugin Interface Reference
|
||||
|
||||
### Required Properties
|
||||
|
||||
| Property | Type | Description |
|
||||
|---|---|---|
|
||||
| `id` | `string` | Unique identifier (e.g. `"aviation"`, `"earthquake"`) |
|
||||
| `name` | `string` | Display name shown in the Layer Panel |
|
||||
| `description` | `string` | Short description shown below the name |
|
||||
| `icon` | `string \| ComponentType` | Lucide icon component or emoji string |
|
||||
| `category` | `PluginCategory` | Grouping in the Layer Panel |
|
||||
| `version` | `string` | Semver version string |
|
||||
|
||||
**Available categories:** `aviation`, `maritime`, `conflict`, `natural-disaster`, `infrastructure`, `cyber`, `economic`, `custom`
|
||||
|
||||
### Required Methods
|
||||
|
||||
#### `initialize(ctx: PluginContext): Promise<void>`
|
||||
|
||||
Called once when the plugin is registered. Store the context for later use.
|
||||
|
||||
```typescript
|
||||
interface PluginContext {
|
||||
apiBaseUrl: string; // Base URL for API calls
|
||||
timeRange: TimeRange; // Current time window
|
||||
onDataUpdate: (entities: GeoEntity[]) => void; // Push data updates
|
||||
onError: (error: Error) => void; // Report errors
|
||||
}
|
||||
```
|
||||
|
||||
#### `destroy(): void`
|
||||
|
||||
Cleanup when the plugin is unregistered. Release any resources.
|
||||
|
||||
#### `fetch(timeRange: TimeRange): Promise<GeoEntity[]>`
|
||||
|
||||
Called by the polling system at your declared interval. Return an array of `GeoEntity` objects representing your data points.
|
||||
|
||||
#### `getPollingInterval(): number`
|
||||
|
||||
Return the polling interval in milliseconds. This determines how often `fetch()` is called.
|
||||
|
||||
#### `getLayerConfig(): LayerConfig`
|
||||
|
||||
Return the default layer configuration. These values are used to initialize the UI and the renderer:
|
||||
|
||||
```typescript
|
||||
interface LayerConfig {
|
||||
color: string; // Default CSS color for primary visualization
|
||||
iconUrl?: string; // Default icon for billboards (if applicable)
|
||||
clusterEnabled: boolean; // Enable spatial clustering at high zoom levels
|
||||
clusterDistance: number; // Cluster radius in pixels (suggested: 40)
|
||||
minZoomLevel?: number; // Hide entities when camera is too far (meters)
|
||||
maxEntities?: number; // Limit for performance safety
|
||||
showLabelsByDefault?: boolean; // If true, labels show without hover
|
||||
}
|
||||
```
|
||||
|
||||
#### `renderEntity(entity: GeoEntity): CesiumEntityOptions`
|
||||
|
||||
Called for each entity to determine how it appears on the globe:
|
||||
|
||||
```typescript
|
||||
interface CesiumEntityOptions {
|
||||
type: "billboard" | "point" | "polyline" | "polygon" | "label";
|
||||
color?: string; // CSS color string
|
||||
size?: number; // Pixel size (for points)
|
||||
iconUrl?: string; // Image URL (for billboards)
|
||||
rotation?: number; // Degrees, applied to billboards
|
||||
outlineColor?: string; // CSS color for point outlines
|
||||
outlineWidth?: number; // Outline width in pixels
|
||||
labelText?: string; // Text label above the entity
|
||||
labelFont?: string; // CSS font string for labels
|
||||
}
|
||||
```
|
||||
|
||||
### Optional Methods
|
||||
|
||||
#### `getSelectionBehavior(entity: GeoEntity): SelectionBehavior | null`
|
||||
|
||||
Return trail rendering and camera behavior when an entity is selected. Return `null` for default behavior.
|
||||
|
||||
```typescript
|
||||
interface SelectionBehavior {
|
||||
showTrail?: boolean; // Render a trail polyline
|
||||
trailDurationSec?: number; // Trail length in seconds (default: 60)
|
||||
trailStepSec?: number; // Trail point spacing (default: 5)
|
||||
trailColor?: string; // CSS color (default: '#00fff7')
|
||||
flyToOffsetMultiplier?: number; // Camera offset multiplier (default: 3)
|
||||
flyToBaseDistance?: number; // Base camera distance in meters (default: 30000)
|
||||
}
|
||||
```
|
||||
|
||||
**Example:** Show trails only for airborne entities:
|
||||
```typescript
|
||||
getSelectionBehavior(entity: GeoEntity): SelectionBehavior | null {
|
||||
if (entity.properties.on_ground) return null;
|
||||
return { showTrail: true, trailColor: "#00fff7" };
|
||||
}
|
||||
```
|
||||
|
||||
#### `getServerConfig(): ServerPluginConfig`
|
||||
|
||||
Declare your plugin's server-side data layer requirements:
|
||||
|
||||
```typescript
|
||||
interface ServerPluginConfig {
|
||||
apiBasePath: string; // e.g. "/api/aviation"
|
||||
pollingIntervalMs: number; // Server-side polling interval
|
||||
requiresAuth?: boolean; // OAuth/API key needed
|
||||
historyEnabled?: boolean; // Supports timeline playback
|
||||
availabilityEnabled?: boolean; // Reports time ranges
|
||||
}
|
||||
```
|
||||
|
||||
> **Note:** The current server infrastructure (API routes, background polling) is set up per-plugin in `src/app/api/<pluginId>/` and `src/lib/`. See [Server-Side Data Layer](#server-side-data-layer) for the pattern.
|
||||
|
||||
#### `getSidebarComponent(): ComponentType`
|
||||
|
||||
Return a React component to render in the sidebar when this plugin's layer is active.
|
||||
|
||||
#### `getDetailComponent(): ComponentType<{ entity: GeoEntity }>`
|
||||
|
||||
Return a React component to render in the detail panel when an entity from this plugin is selected.
|
||||
|
||||
---
|
||||
|
||||
## GeoEntity
|
||||
|
||||
The universal data model for all plugin entities:
|
||||
|
||||
```typescript
|
||||
interface GeoEntity {
|
||||
id: string; // Unique ID (prefix with pluginId)
|
||||
pluginId: string; // Must match your plugin's `id`
|
||||
latitude: number; // WGS84 latitude
|
||||
longitude: number; // WGS84 longitude
|
||||
altitude?: number; // Meters above sea level
|
||||
heading?: number; // Degrees (0 = North, 90 = East)
|
||||
speed?: number; // Meters per second
|
||||
timestamp: Date; // When this data was captured
|
||||
label?: string; // Short display label
|
||||
properties: Record<string, unknown>; // Plugin-specific data
|
||||
}
|
||||
```
|
||||
|
||||
**Conventions:**
|
||||
- **`id`** — Prefix with your plugin ID to avoid collisions: `"earthquake-us7000abc"`
|
||||
- **`heading` + `speed`** — If both are set, the renderer will extrapolate movement between polls (smooth animation)
|
||||
- **`properties`** — Use for domain-specific data (e.g. magnitude, vessel type, altitude). These are accessible in info cards and detail panels
|
||||
|
||||
---
|
||||
|
||||
## Core Services
|
||||
|
||||
### DataBus — Event Communication
|
||||
|
||||
Subscribe to cross-plugin events:
|
||||
|
||||
```typescript
|
||||
import { dataBus } from "@/core/data/DataBus";
|
||||
|
||||
// Available events
|
||||
dataBus.on("dataUpdated", ({ pluginId, entities }) => { ... });
|
||||
dataBus.on("entitySelected", ({ entity }) => { ... });
|
||||
dataBus.on("layerToggled", ({ pluginId, enabled }) => { ... });
|
||||
dataBus.on("timeRangeChanged", ({ timeRange }) => { ... });
|
||||
dataBus.on("cameraPreset", ({ presetId }) => { ... });
|
||||
```
|
||||
|
||||
### CacheLayer — Two-Tier Caching
|
||||
|
||||
The PluginManager automatically caches your `fetch()` results in:
|
||||
1. **Memory** — instant recall within the same session
|
||||
2. **IndexedDB** — survives page refreshes
|
||||
|
||||
You don't need to interact with the cache directly — it's managed by the PluginManager.
|
||||
|
||||
### PollingManager — Automatic Polling
|
||||
|
||||
Your `getPollingInterval()` return value is used to set up automatic polling. Features:
|
||||
- **Exponential backoff** on errors (up to 60s max)
|
||||
- **Pause/resume** support
|
||||
- **Dynamic interval updates** — users can adjust intervals in the Config Panel
|
||||
|
||||
---
|
||||
|
||||
## Server-Side Data Layer
|
||||
|
||||
For plugins that need server-side processing (API proxying, database persistence, authentication), follow this pattern:
|
||||
|
||||
### 1. Create an API Route
|
||||
|
||||
```
|
||||
src/app/api/<your-plugin>/route.ts
|
||||
```
|
||||
|
||||
```typescript
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export async function GET() {
|
||||
// Fetch from your data source
|
||||
const res = await fetch("https://api.example.com/data", {
|
||||
headers: { "Authorization": `Bearer ${process.env.YOUR_API_KEY}` },
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
return NextResponse.json({ error: res.statusText }, { status: res.status });
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Optional: Background Polling
|
||||
|
||||
For APIs with rate limits, create a server-side polling module:
|
||||
|
||||
```
|
||||
src/lib/<your-plugin>-polling.ts
|
||||
```
|
||||
|
||||
Register it in `src/instrumentation.ts`:
|
||||
|
||||
```typescript
|
||||
export async function register() {
|
||||
if (process.env.NEXT_RUNTIME === "nodejs") {
|
||||
const { startYourPluginPolling } = await import("./lib/your-plugin-polling");
|
||||
startYourPluginPolling();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Optional: History Endpoint
|
||||
|
||||
For timeline/playback support, add a history route:
|
||||
|
||||
```
|
||||
src/app/api/<your-plugin>/history/route.ts
|
||||
```
|
||||
|
||||
Accept a `?time=<ms>` parameter and return the closest historical records.
|
||||
|
||||
### 4. Declare in Plugin
|
||||
|
||||
Use `getServerConfig()` to document your server-side setup:
|
||||
|
||||
```typescript
|
||||
getServerConfig(): ServerPluginConfig {
|
||||
return {
|
||||
apiBasePath: "/api/earthquake",
|
||||
pollingIntervalMs: 120000,
|
||||
historyEnabled: false,
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Rendering Details
|
||||
|
||||
### Billboard vs Point
|
||||
|
||||
| Feature | `billboard` | `point` |
|
||||
|---|---|---|
|
||||
| Custom image | Yes via `iconUrl` | No |
|
||||
| Rotation | Yes via `rotation` | No |
|
||||
| Performance | Good (GPU batched) | Best (single draw call) |
|
||||
| Outline | No | Yes via `outlineColor/Width` |
|
||||
|
||||
**Use billboards** for entities with custom icons and rotation (aircraft, vehicles).
|
||||
**Use points** for simpler markers (fires, earthquakes, vessels).
|
||||
|
||||
### Labels
|
||||
|
||||
Labels are automatically hidden at long distances and shown within 500km or on hover/selection. Configure via `labelText` and `labelFont` in your `renderEntity()` return.
|
||||
|
||||
### Position Extrapolation
|
||||
|
||||
If your `GeoEntity` has both `heading` and `speed` set, the globe renderer will automatically extrapolate smooth movement between polling intervals (up to 5 minutes). This creates fluid animation without increasing your API call frequency.
|
||||
|
||||
---
|
||||
|
||||
## Existing Plugin Examples
|
||||
|
||||
| Plugin | Category | Data Source | Rendering | Selection |
|
||||
|---|---|---|---|---|
|
||||
| [Aviation](../src/plugins/aviation/index.ts) | `aviation` | OpenSky Network (live + Supabase fallback) | Billboards with altitude-based coloring | Trail polyline for airborne entities |
|
||||
| [Maritime](../src/plugins/maritime/index.ts) | `maritime` | AIS feeds (with demo fallback) | Points with vessel-type coloring | Default |
|
||||
| [Wildfire](../src/plugins/wildfire/index.ts) | `natural-disaster` | NASA FIRMS (VIIRS) | Points with FRP-based sizing/coloring | Default |
|
||||
|
||||
---
|
||||
|
||||
## Checklist: Publishing a Plugin
|
||||
|
||||
- [ ] Implements all required `WorldPlugin` methods
|
||||
- [ ] `id` is unique and lowercase (no spaces)
|
||||
- [ ] All `GeoEntity.id` values are prefixed with your plugin ID
|
||||
- [ ] `GeoEntity.pluginId` matches your plugin's `id`
|
||||
- [ ] `renderEntity()` returns valid `CesiumEntityOptions`
|
||||
- [ ] API route created (if needed) at `src/app/api/<id>/`
|
||||
- [ ] Plugin registered in the app initialization code
|
||||
- [ ] Tested: toggle on/off in Layer Panel
|
||||
- [ ] Tested: entity hover and click selection
|
||||
- [ ] Tested: info card displays your `properties` correctly
|
||||
@@ -1,81 +0,0 @@
|
||||
# Setup & Installation
|
||||
|
||||
Follow these steps to set up your development environment and get WorldWideView running locally.
|
||||
|
||||
## Requirements
|
||||
|
||||
- **Node.js**: v18.17 or higher (tested on v20+)
|
||||
- **NPM**: v9 or higher
|
||||
- **Browser**: Chrome, Firefox, or Edge (CesiumJS requires WebGL support)
|
||||
|
||||
## Environment Setup
|
||||
|
||||
WorldWideView requires several API keys to function correctly. You can copy the provided `.env.example` file to `.env.local` and fill in the values:
|
||||
|
||||
```bash
|
||||
cp .env.example .env.local
|
||||
```
|
||||
|
||||
Or manually create a `.env.local` file in the root directory:
|
||||
|
||||
```env
|
||||
# Cesium Ion Access Token (Required for terrain and default imagery)
|
||||
NEXT_PUBLIC_CESIUM_ION_TOKEN=your_token_here
|
||||
|
||||
# Bing Maps API Key (Optional, for high-res imagery)
|
||||
NEXT_PUBLIC_BING_MAPS_KEY=your_key_here
|
||||
|
||||
# Supabase Configuration (Required for persistence and historical data)
|
||||
NEXT_PUBLIC_SUPABASE_URL=your_project_url
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY=your_anon_key
|
||||
SUPABASE_SERVICE_ROLE_KEY=your_service_role_key
|
||||
```
|
||||
|
||||
## Running Locally
|
||||
|
||||
1. **Install Dependencies**:
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
2. **Start Dev Server**:
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
*Note: Our `dev` script automatically runs `predev` to copy Cesium assets to the public directory.*
|
||||
|
||||
3. **Open Browser**:
|
||||
Navigate to [http://localhost:3000](http://localhost:3000).
|
||||
|
||||
## Folder Structure Explanation
|
||||
|
||||
Understanding the project layout:
|
||||
|
||||
```text
|
||||
worldwideview/
|
||||
├── .agents/ # Agentic AI workflows and memory
|
||||
├── docs/ # Project documentation (Markdowns)
|
||||
├── public/ # Static assets (Imagery, GeoJSON, Cesium dependencies)
|
||||
├── scripts/ # Build and utility scripts (e.g., copy-cesium.mjs)
|
||||
└── src/
|
||||
├── app/ # Next.js App Router (Layouts, Pages, API Routes)
|
||||
├── components/ # React UI components (HUD, LayersPanel, Panels)
|
||||
├── core/ # Core engine logic
|
||||
│ ├── data/ # Data management (DataBus, Polling, Cache)
|
||||
│ ├── globe/ # Cesium-specific hooks and view logic
|
||||
│ └── plugins/ # Plugin system base and registry
|
||||
├── lib/ # Utility libraries and server-side polling
|
||||
└── plugins/ # Feature-specific plugins (Aviation, Maritime, etc.)
|
||||
```
|
||||
|
||||
## Verification
|
||||
|
||||
To verify your setup:
|
||||
1. Ensure the globe loads without errors in the console.
|
||||
2. Check if the "Aviation" layer is visible in the Layers Panel.
|
||||
3. Verify that the HUD (top bar) displays live camera coordinates.
|
||||
|
||||
---
|
||||
|
||||
> [!IMPORTANT]
|
||||
> If you encounter issues with hot reloading (HMR), ensure you are running with the `--webpack` flag in the dev script (this is the default in our `package.json`).
|
||||
@@ -1,48 +0,0 @@
|
||||
# User Guide
|
||||
|
||||
Welcome to WorldWideView! This guide will help you navigate the 3D globe and interact with live data layers.
|
||||
|
||||
## Navigating the Globe
|
||||
|
||||
- **Rotate**: Left-click and drag.
|
||||
- **Zoom**: Use the mouse wheel or pinch on a trackpad.
|
||||
- **Tilt/Rotate Perspective**: Right-click and drag (or use Ctrl + Left-click).
|
||||
- **Fly to Location**: Double-click on an entity or use the search bar (if available).
|
||||
|
||||
## Application Panels
|
||||
|
||||
### Layers Panel
|
||||
Located on the left side of the screen, the Layers Panel allows you to toggle different data sources on and off.
|
||||
- **Search Layers**: Filter the available plugins.
|
||||
- **Toggle Visibility**: Enable or disable specific data layers like Aviation, Maritime, or Wildfires.
|
||||
- **Layer Configuration**: Some layers provide settings like clustering or color customization.
|
||||
|
||||
### HUD (Heads-Up Display)
|
||||
The HUD at the top provides real-time information about your current view:
|
||||
- **Camera Coordinates**: Latitude, Longitude, and Altitude.
|
||||
- **Pitch & Heading**: Current orientation of the camera.
|
||||
- **FPS Indicator**: Performance metrics.
|
||||
|
||||
### Timeline
|
||||
The timeline at the bottom allows you to track data over time.
|
||||
- **Current Time**: Displays the simulated time on the globe.
|
||||
- **Playback Controls**: If supported by the plugin, you can scrubbing through historical data.
|
||||
|
||||
## Interacting with Entities
|
||||
|
||||
- **Hover**: Hover over a marker (point or billboard) to see a quick label.
|
||||
- **Selection**: Click on an entity to open its **Info Card**.
|
||||
- **Info Card**: Displays detailed properties about the selected object (e.g., flight number, vessel type, fire intensity).
|
||||
- **Trails**: Some entities (like aircraft) show a historical trail when selected.
|
||||
|
||||
## Settings & Configuration
|
||||
|
||||
You can access global settings through the **Config Panel**. Here you can:
|
||||
- Adjust the **Polling Interval** for data updates.
|
||||
- Toggle **Night Mode** or change the **Imagery Base Map** (e.g., Satellite, Terrain, Street).
|
||||
- Manage **Cache Settings** to clear offline data.
|
||||
|
||||
---
|
||||
|
||||
> [!TIP]
|
||||
> Use the **[Keyboard Shortcuts]** (coming soon) for faster navigation and panel toggling.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 816 KiB |
@@ -0,0 +1,32 @@
|
||||
<!-- Generated: 2026-04-23 06:11:00 UTC -->
|
||||
# Build System
|
||||
|
||||
## Overview
|
||||
WorldWideView uses a pnpm monorepo workspace for managing both the main application and its associated SDK and plugin packages. The primary build system relies on Next.js 16 with custom Webpack optimizations, specifically designed to output a standalone trace for highly efficient Docker containerization.
|
||||
|
||||
The core build configuration resides in `package.json` and `next.config.ts`. A custom standalone tracer strips unnecessary CLI dependencies (`prisma`, `dotenv`) from the final build to prevent fatal container runtime crashes.
|
||||
|
||||
## Build Workflows
|
||||
|
||||
### Standard Development
|
||||
- **Install Dependencies:** `pnpm install` (Installs all workspace packages defined in `pnpm-workspace.yaml`).
|
||||
- **Initial Setup:** `pnpm run setup` (Executes `scripts/setup.mjs` to generate a `.env.local` with a fresh `AUTH_SECRET`).
|
||||
- **Run Development Server (All):** `pnpm dev:all` (Concurrently starts the Next.js frontend and the local `wwv-data-engine` backends).
|
||||
|
||||
### Production Build
|
||||
- **Build Command:** `pnpm build` (Executes `next build --webpack`).
|
||||
- **Output:** Generates a `.next/standalone/` folder ready for execution.
|
||||
- **Static Assets:** `scripts/copy-cesium.mjs` is executed during `predev` and `build` to copy pre-compiled CesiumJS static assets into the `public/cesium/` directory, keeping them out of the output tracer.
|
||||
|
||||
## Platform Setup
|
||||
|
||||
- **Database Migrations:** Prisma schema is located at `prisma/schema.prisma`. During development, `pnpm dev` triggers a `predev` hook running `npx prisma migrate deploy` to ensure PostgreSQL tables are initialized.
|
||||
- **Microservices:** Data engine seeders and standalone Fastify backend plugins (like `wwv-plugin-iranwarlive/backend`) are started via `pnpm start:backends` and managed locally inside `packages/*/backend`.
|
||||
- **Plugin Packages:** Internal plugin packages must be properly listed in `tsconfig.json` paths and `next.config.ts`'s `transpilePackages` array.
|
||||
|
||||
## Reference
|
||||
|
||||
- **Monorepo Config:** `pnpm-workspace.yaml` - defines package locations (`packages/*` and `packages/*/backend`).
|
||||
- **Next Config:** `next.config.ts` - controls the standalone output, `transpilePackages`, and restrictive security headers.
|
||||
- **Prisma Config:** `prisma.config.ts` - Native JavaScript object export used to bypass Next.js tracer issues with dynamic imports.
|
||||
- **Cesium Script:** `scripts/copy-cesium.mjs` - Handles static asset injection.
|
||||
@@ -0,0 +1,34 @@
|
||||
<!-- Generated: 2026-04-23 06:11:00 UTC -->
|
||||
# Deployment
|
||||
|
||||
## Overview
|
||||
WorldWideView utilizes a containerized deployment strategy based on Docker's multi-stage builds. To minimize the footprint of the Next.js runtime, it leverages the Next.js `standalone` output trace, effectively dropping unnecessary development dependencies and generating a highly optimized Node.js artifact.
|
||||
|
||||
## Package Types
|
||||
|
||||
### Main Application
|
||||
- **Build Output:** Located at `.next/standalone/`.
|
||||
- **Static Assets:** Cesium static workers are injected at build time via `scripts/copy-cesium.mjs`.
|
||||
|
||||
### Plugin Microservices
|
||||
- Standalone plugin backends (e.g., `wwv-plugin-iranwarlive/backend`) are isolated via individual `Dockerfile` configurations and orchestrated together in production using `docker-compose.yml`.
|
||||
|
||||
## Platform Deployment
|
||||
|
||||
### Coolify Integration
|
||||
WorldWideView deploys optimally to Coolify using a Dockerfile builder.
|
||||
- **Environment Variables:** Must be explicitly mapped in the Coolify UI (e.g., `DATABASE_URL`, `AUTH_SECRET`).
|
||||
- **Persistent Storage:** PostgreSQL databases must be hosted externally or mounted via persistent volumes to ensure the frontend registry (installed plugins, user configs) survives container rebuilds.
|
||||
- **Microservices Deployment:** The `wwv-data-engine-internal` and associated plugin seeders are deployed as separate Coolify services communicating over private internal networks.
|
||||
|
||||
### Docker Structure
|
||||
- **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`.
|
||||
|
||||
## 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.
|
||||
- **Docker Mounts:**
|
||||
- Main App: PostgreSQL data volume (if running in-cluster)
|
||||
- Data Engine: PostgreSQL data volume (if running in-cluster)
|
||||
- Cache: `/data` (Redis)
|
||||
@@ -0,0 +1,73 @@
|
||||
<!-- Generated: 2026-04-23 06:11:00 UTC -->
|
||||
# Development
|
||||
|
||||
## Overview
|
||||
Development on WorldWideView prioritizes modularity, high performance, and strict architectural boundaries between the UI and the 3D rendering context. We adhere to rigorous file size constraints and rely heavily on Vanilla CSS and Zustand slice-patterns to maintain clarity across the large ecosystem.
|
||||
|
||||
## Code Style
|
||||
|
||||
### File Size Limits
|
||||
- **Max 150 lines per file.** If a component or function grows beyond this, you must modularize it. Extract helper functions, split React components, and utilize custom hooks.
|
||||
|
||||
### Styling Conventions
|
||||
- **Vanilla CSS Only:** Do not use Tailwind CSS or CSS-in-JS.
|
||||
- **Global Styles:** Located at `src/app/globals.css`.
|
||||
- **Component Styles:** Use CSS Modules (`.module.css`) or co-locate `.css` files directly next to their components.
|
||||
- **HUD Animations:** Specialized interface animations are stored in `src/styles/hud-animations.css`.
|
||||
|
||||
### Import Aliases
|
||||
- Application core: `@/*` → `./src/*`
|
||||
- Plugin SDK: `@worldwideview/wwv-plugin-sdk` → `./packages/wwv-plugin-sdk/src`
|
||||
- Custom plugins use their respective names configured in `tsconfig.json`.
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Entity Rendering
|
||||
When translating raw plugin data into `CesiumEntityOptions` inside `renderEntity()`, follow these strict graphical rules:
|
||||
```typescript
|
||||
// Correct Point Pattern
|
||||
renderEntity(entity: GeoEntity): CesiumEntityOptions {
|
||||
return {
|
||||
type: "point",
|
||||
color: "#ff0000",
|
||||
size: 10,
|
||||
outlineColor: "#ffffff",
|
||||
outlineWidth: 2
|
||||
};
|
||||
}
|
||||
|
||||
// Correct Billboard Pattern
|
||||
renderEntity(entity: GeoEntity): CesiumEntityOptions {
|
||||
return {
|
||||
type: "billboard",
|
||||
color: "#ffffff",
|
||||
iconUrl: "/icons/aircraft.png",
|
||||
iconScale: 0.5
|
||||
};
|
||||
}
|
||||
```
|
||||
> [!WARNING]
|
||||
> **NEVER MIX PROPERTIES:** Do not apply `size`, `outlineWidth`, or `outlineColor` to a `billboard` entity. Mixing these parameters causes severe GPU clipping and rendering artifacts in Cesium.
|
||||
|
||||
### State Access
|
||||
Zustand is divided into slices. For performance, components must select exactly the properties they need to avoid over-rendering:
|
||||
```typescript
|
||||
// From src/components/panels/LayerPanel.tsx
|
||||
const activeLayers = useStore((state) => state.layers.active);
|
||||
const toggleLayer = useStore((state) => state.layers.toggle);
|
||||
```
|
||||
|
||||
## Workflows
|
||||
|
||||
### Debugging & Temporary Scripts
|
||||
Whenever generating temporary debugging scripts, testing REST endpoints via `.mjs`, or dumping traces/JSON outputs, **save these exclusively inside `/local-scripts/`**.
|
||||
- *Reference:* The root directory is strictly for production configuration files.
|
||||
|
||||
### Scaffold a New Component
|
||||
1. Create a new directory under `src/components/{category}/MyComponent`.
|
||||
2. Add `MyComponent.tsx` and `MyComponent.module.css`.
|
||||
3. Export from a local `index.ts` if creating a composite view.
|
||||
|
||||
## Reference
|
||||
- **Core Abstractions:** See `packages/wwv-plugin-sdk/src/PluginTypes.ts` for interface expectations.
|
||||
- **State Slices:** Located in `src/core/state/` (e.g., `globeSlice.ts`, `dataSlice.ts`).
|
||||
@@ -0,0 +1,33 @@
|
||||
<!-- Generated: 2026-04-23 06:11:00 UTC -->
|
||||
# Files Catalog
|
||||
|
||||
## Overview
|
||||
WorldWideView is structured as a pnpm monorepo. The primary application resides in the root `src/` directory, while external dependencies, plugins, and the core Plugin SDK are abstracted into the `packages/` directory.
|
||||
|
||||
The system is highly modularized to separate React UI rendering from heavy CesiumJS 3D operations and high-frequency real-time WebSocket state management.
|
||||
|
||||
## Core Source Files
|
||||
- `src/app/` - The Next.js App Router entry points. Contains `layout.tsx` (the core React shell), `page.tsx` (the globe view), and `/api/` (server-side NextAuth and API handlers).
|
||||
- `src/core/plugins/PluginManager.ts` - Central orchestration unit for dynamic plugins. Handles loading, lifecycle (`initialize`, `destroy`), and manifest resolution.
|
||||
- `src/core/globe/GlobeView.tsx` - The primary CesiumJS container. It memoizes Zustand state to prevent heavy re-renders while injecting `EntityRenderer` primitives.
|
||||
- `src/core/data/DataBus.ts` - Singleton pub/sub event bus handling all high-velocity WebSocket stream events without triggering React re-renders.
|
||||
- `src/core/state/store.ts` - The primary Zustand state registry exporting all nine discrete slices (`globe`, `layers`, `timeline`, `ui`, `filter`, `data`, `config`, `favorites`, `geojson`).
|
||||
|
||||
## Platform Implementation
|
||||
- `src/core/plugins/loaders/InstalledPluginsLoader.ts` - Platform-specific loader that dynamically injects ES module CDNs via `import(/* webpackIgnore: true */)`.
|
||||
- `src/core/globe/hooks/useCameraActions.ts` - Abstraction connecting React UI logic to raw CesiumJS camera math (flyTo, lookAt).
|
||||
- `src/lib/edition.ts` - Platform edition configuration. Exposes runtime feature flags for `local`, `cloud`, and `demo` deployments.
|
||||
|
||||
## Build System
|
||||
- `package.json` - Root monorepo configuration with `pnpm` workspace bindings.
|
||||
- `next.config.ts` - Next.js compiler settings, security headers, and standalone output configuration.
|
||||
- `docker-compose.yml` - Defines the orchestration of the frontend, Redis cache, and all local plugin microservice backends (`wwv-data-engine`).
|
||||
|
||||
## Configuration
|
||||
- `prisma/schema.prisma` - PostgreSQL database schema for storing user settings and installed plugin manifests.
|
||||
- `scripts/copy-cesium.mjs` - Crucial build-time script that extracts and copies CesiumJS static web workers to `public/cesium/`.
|
||||
- `public/` - Static assets, plugin icons, and compiled Cesium workers.
|
||||
|
||||
## Reference
|
||||
- **Plugins Directory:** All plugins conform to the `@worldwideview/wwv-plugin-sdk` interface and are developed inside `packages/wwv-plugin-<name>/`.
|
||||
- **Microservices Directory:** Standalone Fastify backends are nested within `packages/wwv-plugin-<name>/backend/`.
|
||||
@@ -0,0 +1,328 @@
|
||||
<!-- Generated: 2026-04-23 20:29:00 UTC -->
|
||||
# End-to-End Tutorial: Building a Real-Time ISS Tracking Plugin
|
||||
|
||||
Welcome! This tutorial is designed for complete beginners. If you have never built a WorldWideView plugin before, you are in the right place.
|
||||
|
||||
By following these steps exactly, you will build a complete, real-time International Space Station (ISS) tracker from scratch. You will learn how to set up your environment, stream live data using a backend seeder, render it in 3D on the globe, and publish your work to the world.
|
||||
|
||||
Let's get started.
|
||||
|
||||
---
|
||||
|
||||
## Step 1: Setting up your Workspace
|
||||
|
||||
Before we write any code, we need to prepare your computer. We will install the required tools and download the two main repositories that make up the WorldWideView platform.
|
||||
|
||||
### 1.1 Install Prerequisites
|
||||
|
||||
Ensure you have the following installed on your machine:
|
||||
1. **Node.js**: Download and install [Node.js](https://nodejs.org/) (Version 18 or higher is required).
|
||||
2. **Git**: Download and install [Git](https://git-scm.com/).
|
||||
3. **pnpm**: This is the package manager we use. Open your terminal and run:
|
||||
```bash
|
||||
npm install -g pnpm
|
||||
```
|
||||
|
||||
### 1.2 Clone the Repositories
|
||||
|
||||
You need both the frontend application and the backend data engine. Open your terminal and navigate to the folder where you want to store your code (e.g., `C:\dev`).
|
||||
|
||||
Run these commands to download the code:
|
||||
```bash
|
||||
git clone https://github.com/silvertakana/worldwideview.git
|
||||
git clone https://github.com/silvertakana/wwv-data-engine.git
|
||||
```
|
||||
|
||||
### 1.3 Install Dependencies
|
||||
|
||||
Next, we need to install the libraries that these projects depend on.
|
||||
|
||||
First, install dependencies for the Data Engine:
|
||||
```bash
|
||||
cd wwv-data-engine
|
||||
pnpm install
|
||||
```
|
||||
|
||||
Second, install dependencies for the main WorldWideView application:
|
||||
```bash
|
||||
cd ../worldwideview
|
||||
pnpm install
|
||||
```
|
||||
|
||||
### 1.4 Setup Environment Variables
|
||||
|
||||
WorldWideView needs a few basic configuration keys to run.
|
||||
|
||||
While still in the `worldwideview` folder, run the automated setup script. This will generate a `.env.local` file with the necessary secrets:
|
||||
```bash
|
||||
pnpm run setup
|
||||
```
|
||||
|
||||
Your workspace is now ready!
|
||||
|
||||
---
|
||||
|
||||
## Step 2: Creating the Data Engine Seeder (Backend)
|
||||
|
||||
The ISS moves incredibly fast. If our frontend tries to ask for its location every second, it will lag. Instead, we use the **Bring Your Own Backend (BYOB)** pattern. We will write a "Seeder" script in the Data Engine that fetches the ISS location and instantly broadcasts it to the frontend via WebSockets.
|
||||
|
||||
### 2.1 Create the Seeder File
|
||||
|
||||
Navigate to your data engine repository and create a new file named `iss.ts` in the `src/seeders` folder:
|
||||
`c:\dev\wwv-data-engine\src\seeders\iss.ts`
|
||||
|
||||
### 2.2 Write the Polling Logic
|
||||
|
||||
Open `iss.ts` in your text editor and paste the following code. This script reaches out to the free WhereTheISS.at API every 5 seconds and saves the data to the engine's memory (Redis).
|
||||
|
||||
```typescript
|
||||
import { setLiveSnapshot } from '../core/redis';
|
||||
import axios from 'axios';
|
||||
|
||||
const WTIA_URL = 'https://api.wheretheiss.at/v1/satellites/25544';
|
||||
const POLLING_INTERVAL = 5000; // 5 seconds
|
||||
|
||||
async function pollISS() {
|
||||
try {
|
||||
// 1. Fetch data from the API
|
||||
const response = await axios.get(WTIA_URL);
|
||||
const data = response.data;
|
||||
|
||||
// 2. Format the data into a GeoEntity object
|
||||
const stateObj = {
|
||||
id: 25544,
|
||||
name: "International Space Station",
|
||||
latitude: data.latitude,
|
||||
longitude: data.longitude,
|
||||
altitude: data.altitude * 1000, // Convert kilometers to meters
|
||||
velocity: data.velocity,
|
||||
visibility: data.visibility,
|
||||
footprint: data.footprint
|
||||
};
|
||||
|
||||
// 3. Save to Redis under the 'iss' namespace for 60 seconds
|
||||
await setLiveSnapshot('iss', { "25544": stateObj }, 60);
|
||||
console.log(`[ISS] Poll OK: updated position to ${data.latitude}, ${data.longitude}`);
|
||||
|
||||
} catch (error) {
|
||||
console.error(`[ISS] Polling error:`, error.message);
|
||||
} finally {
|
||||
// 4. Repeat the process after 5 seconds
|
||||
setTimeout(pollISS, POLLING_INTERVAL);
|
||||
}
|
||||
}
|
||||
|
||||
// Start the loop
|
||||
pollISS();
|
||||
```
|
||||
|
||||
### 2.3 Register the Seeder
|
||||
|
||||
The engine needs to know your seeder exists. Open `c:\dev\wwv-data-engine\src\seeders\index.ts` and add this line at the bottom:
|
||||
|
||||
```typescript
|
||||
import './iss';
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Step 3: Testing the Data Engine
|
||||
|
||||
Before we build the frontend, let's prove that our backend is actually fetching the ISS data.
|
||||
|
||||
### 3.1 Start the Engine
|
||||
|
||||
In your terminal, navigate to the `wwv-data-engine` folder and start the backend:
|
||||
```bash
|
||||
pnpm dev:backends
|
||||
```
|
||||
You should see `[ISS] Poll OK: updated position` appearing in your console every 5 seconds. Leave this terminal running.
|
||||
|
||||
### 3.2 Write a Quick Test Script
|
||||
|
||||
Open a *new* terminal window. Let's write a tiny script to peek into the engine's memory. Create a file called `test_iss.mjs` in the `wwv-data-engine` folder:
|
||||
|
||||
```javascript
|
||||
// test_iss.mjs
|
||||
import Redis from 'ioredis';
|
||||
const redis = new Redis();
|
||||
|
||||
async function verify() {
|
||||
const data = await redis.get('data:iss:live');
|
||||
if (data) {
|
||||
console.log("Success! We found the ISS:", JSON.parse(data));
|
||||
} else {
|
||||
console.log("No data found yet.");
|
||||
}
|
||||
process.exit(0);
|
||||
}
|
||||
verify();
|
||||
```
|
||||
|
||||
Run the script:
|
||||
```bash
|
||||
node test_iss.mjs
|
||||
```
|
||||
If you see a large block of data containing coordinates and altitude, your backend is working perfectly!
|
||||
|
||||
---
|
||||
|
||||
## Step 4: Creating the WorldWideView Plugin (Frontend)
|
||||
|
||||
Now we will build the visual part of the plugin that connects to our backend stream and draws the ISS on the 3D globe.
|
||||
|
||||
### 4.1 Scaffold the Plugin
|
||||
|
||||
In your terminal, navigate back to your main `c:\dev` folder. We will use the official CLI tool to generate a blank plugin template. Run:
|
||||
|
||||
```bash
|
||||
npx @worldwideview/create-plugin@latest wwv-plugin-iss
|
||||
```
|
||||
When prompted, name the folder `wwv-plugin-iss`.
|
||||
|
||||
Move into your new plugin folder and install its dependencies:
|
||||
```bash
|
||||
cd wwv-plugin-iss
|
||||
npm install
|
||||
```
|
||||
|
||||
### 4.2 Write the Plugin Logic
|
||||
|
||||
Open `c:\dev\wwv-plugin-iss\src\index.ts` in your text editor. Replace everything in the file with this code:
|
||||
|
||||
```typescript
|
||||
import type { WorldPlugin, GeoEntity, PluginContext, LayerConfig, CesiumEntityOptions } from "@worldwideview/wwv-plugin-sdk";
|
||||
|
||||
export class IssPlugin implements WorldPlugin {
|
||||
// The ID MUST match the namespace we used in the backend ('iss')
|
||||
id = "iss";
|
||||
name = "ISS Live Tracker";
|
||||
description = "Real-time International Space Station tracking.";
|
||||
icon = "Satellite";
|
||||
category = "space" as const;
|
||||
version = "1.0.0";
|
||||
|
||||
async initialize(ctx: PluginContext): Promise<void> {
|
||||
console.log("ISS Plugin loaded!");
|
||||
}
|
||||
|
||||
destroy(): void { }
|
||||
|
||||
async fetch(): Promise<GeoEntity[]> {
|
||||
// We return an empty array because the WebSockets handle the data automatically.
|
||||
return [];
|
||||
}
|
||||
|
||||
getPollingInterval(): number {
|
||||
return 0; // Disabled: we use continuous WebSockets instead of polling.
|
||||
}
|
||||
|
||||
getLayerConfig(): LayerConfig {
|
||||
return {
|
||||
color: "#00ffcc",
|
||||
clusterEnabled: false
|
||||
};
|
||||
}
|
||||
|
||||
renderEntity(entity: GeoEntity): CesiumEntityOptions {
|
||||
// Level of Detail (LOD): Use a 2D billboard from far away,
|
||||
// and transition to a 3D model when zooming in close.
|
||||
return {
|
||||
type: "billboard",
|
||||
color: "#ffffff",
|
||||
iconUrl: "https://unpkg.com/wwv-plugin-iss/assets/iss-icon.png",
|
||||
iconScale: 0.8,
|
||||
modelUrl: "https://unpkg.com/wwv-plugin-iss/assets/ISS_stationary.glb",
|
||||
modelScale: 2.5,
|
||||
heading: entity.heading || 0,
|
||||
};
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Step 5: Connecting and Testing Everything
|
||||
|
||||
Now we will link your new plugin to your local WorldWideView application to see it in action.
|
||||
|
||||
### 5.1 Link the Plugin
|
||||
|
||||
In your `wwv-plugin-iss` terminal, tell the CLI where your main WorldWideView folder is:
|
||||
```bash
|
||||
npx wwv config set wwv-path C:\dev\worldwideview
|
||||
```
|
||||
|
||||
Now, link the plugin. This creates a shortcut so WorldWideView can see your code:
|
||||
```bash
|
||||
npm run link
|
||||
```
|
||||
|
||||
Start the plugin watcher. This will automatically update your plugin if you make any changes to the code:
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
Leave this terminal running.
|
||||
|
||||
### 5.2 Start WorldWideView
|
||||
|
||||
Open a third, final terminal window. Navigate to your main `worldwideview` folder and start the frontend application:
|
||||
```bash
|
||||
cd C:\dev\worldwideview
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
### 5.3 View the ISS
|
||||
|
||||
1. Open your web browser and go to `http://localhost:3000`.
|
||||
2. Click the **Layers** icon on the left sidebar.
|
||||
3. Find **ISS Live Tracker** in the list and toggle it ON.
|
||||
4. The globe will instantly fly to the current location of the ISS, and you will see it moving in real-time!
|
||||
|
||||
> [!TIP]
|
||||
> **Troubleshooting missing points:**
|
||||
> - Ensure your Data Engine terminal (`pnpm dev:backends`) is still running.
|
||||
> - Press `F12` in your browser to open Developer Tools. Check the `Console` tab for any red errors.
|
||||
> - Ensure the `id` in your plugin (`"iss"`) exactly matches the name you used in the backend `setLiveSnapshot('iss', ...)`.
|
||||
|
||||
---
|
||||
|
||||
## Step 6: Publishing Your Plugin
|
||||
|
||||
You've built it, now share it with the world!
|
||||
|
||||
### 6.1 Update package.json
|
||||
|
||||
Open `c:\dev\wwv-plugin-iss\package.json`. You must add a `"worldwideview"` metadata block so the marketplace knows how to read your plugin. Ensure your file looks like this:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "wwv-plugin-iss",
|
||||
"version": "1.0.0",
|
||||
"main": "dist/index.js",
|
||||
"worldwideview": {
|
||||
"id": "iss",
|
||||
"name": "ISS Live Tracker",
|
||||
"version": "1.0.0",
|
||||
"icon": "Satellite",
|
||||
"category": "space"
|
||||
},
|
||||
"scripts": { ... }
|
||||
}
|
||||
```
|
||||
|
||||
### 6.2 Publish to NPM
|
||||
|
||||
In your plugin terminal, log in to NPM and publish your package:
|
||||
```bash
|
||||
npm login
|
||||
npm publish --access public
|
||||
```
|
||||
|
||||
### 6.3 Submit to the Marketplace
|
||||
|
||||
1. Go to the official marketplace at `https://marketplace.worldwideview.dev/submit`.
|
||||
2. Type in your package name (`wwv-plugin-iss`) and click submit.
|
||||
3. The system will automatically verify your code. Once approved, any WorldWideView user on the planet can click "Install" to add your ISS tracker to their globe.
|
||||
|
||||
**Congratulations!** You have successfully navigated the entire stack, from API polling and WebSockets to 3D rendering and global publishing.
|
||||
@@ -0,0 +1,80 @@
|
||||
<!-- Generated: 2026-04-23 06:11:00 UTC -->
|
||||
# Advanced Plugin Guide
|
||||
|
||||
This guide covers complex architectures, real-time telemetry streaming, and the deployment lifecycle for WorldWideView plugins. If you haven't built a basic plugin yet, start with the **[Quickstart](plugin-quickstart.md)**.
|
||||
|
||||
## Architecture Paradigm: The All-Bundle Model
|
||||
|
||||
WorldWideView operates on a strict **Dynamic CDN Loaded (Bundle)** architecture.
|
||||
|
||||
> [!WARNING]
|
||||
> **Deprecation Notice:** The legacy `StaticDataPlugin` (GeoJSON loaders) and `DeclarativePlugin` runtimes are fully deprecated. All new plugins must be dynamically imported at runtime as ES module bundles via `import(/* webpackIgnore: true */ entry)`.
|
||||
|
||||
### How Plugins Load
|
||||
1. A user clicks "Install" in the **Marketplace**.
|
||||
2. The marketplace sends the plugin manifest (containing an ES Module CDN URL, like `unpkg.com`) to the WorldWideView database.
|
||||
3. At runtime, the `InstalledPluginsLoader` dynamically fetches the JavaScript bundle.
|
||||
4. The plugin is instantiated, and its `initialize(ctx)` method is invoked.
|
||||
|
||||
## Real-Time Data: Bring Your Own Backend (BYOB)
|
||||
|
||||
Relying on the frontend `fetch()` method is insufficient for high-frequency real-time tracking (like aviation or maritime). For continuous telemetry, you must build a **Data Engine Seeder** — a containerized backend microservice.
|
||||
|
||||
### Microservice Seeder Architecture
|
||||
Instead of the frontend fetching data, your backend container connects to an upstream source, normalizes the data, and publishes it to the central Redis stream managed by `wwv-data-engine`.
|
||||
|
||||
1. **Scaffold a Backend:** Use the CLI to generate a backend template.
|
||||
```bash
|
||||
npx @worldwideview/cli create-backend my-plugin-backend
|
||||
```
|
||||
2. **Containerize:** This generates a Fastify Node.js server with a `Dockerfile` and `docker-compose.yml`.
|
||||
3. **Publish to Redis:** Your backend polls the external API (e.g., ADS-B Exchange) and pushes snapshots to the WorldWideView Redis pipeline.
|
||||
4. **WebSocket Delivery:** The central `wwv-data-engine` immediately broadcasts these updates over WebSockets to all connected clients.
|
||||
|
||||
> [!TIP]
|
||||
> **Debugging WebSockets:** If your frontend isn't receiving data from your backend seeder:
|
||||
> 1. Check the `wwv-data-engine` logs to ensure your seeder is publishing to Redis successfully.
|
||||
> 2. Verify the frontend is connected to the correct WebSocket endpoint. Local instances default to `ws://localhost:5001/stream`, while unrecognized seeders fall back to the cloud at `wss://dataengine.worldwideview.dev/stream`.
|
||||
|
||||
## Advanced Cesium Rendering
|
||||
|
||||
When returning `CesiumEntityOptions` in `renderEntity(entity)`, you have direct access to the 3D engine's capabilities.
|
||||
|
||||
### 3D Models vs. Billboards (LOD Strategy)
|
||||
To maintain 60 FPS with tens of thousands of entities, use WorldWideView's Level of Detail (LOD) promotion system.
|
||||
- Render distant entities as simple `billboard` or `point` primitives.
|
||||
- When the camera gets close, the system's `useModelRendering` hook can promote the entity to a full 3D glTF model.
|
||||
|
||||
```typescript
|
||||
renderEntity(entity: GeoEntity): CesiumEntityOptions {
|
||||
return {
|
||||
type: "billboard", // Primary lightweight renderer
|
||||
color: "#ffffff",
|
||||
iconUrl: "https://unpkg.com/my-plugin/assets/icon.png",
|
||||
iconScale: 0.5,
|
||||
// Provide a 3D model URL. The engine will swap it in automatically at close range.
|
||||
modelUrl: "https://unpkg.com/my-plugin/assets/model.glb",
|
||||
modelScale: 1.0,
|
||||
heading: entity.heading,
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
> [!CAUTION]
|
||||
> **GPU Clipping Bug:** NEVER mix `size`, `outlineWidth`, or `outlineColor` properties onto an entity of `type: "billboard"`. This will cause the WebGL compiler to panic and result in severe visual clipping artifacts.
|
||||
|
||||
## Publishing to the Marketplace
|
||||
|
||||
To distribute your plugin globally:
|
||||
|
||||
1. **Publish to NPM:**
|
||||
```bash
|
||||
npm publish --access public
|
||||
```
|
||||
2. **Submit:** Navigate to `https://marketplace.worldwideview.dev/submit`.
|
||||
3. **Register:** Enter your NPM package name. The marketplace automatically scrapes your `package.json` for the required `"worldwideview"` object block (containing your `id`, `icon`, and `category`).
|
||||
4. **Review:** Once approved, your plugin's ES Module bundle will be served via CDN to all WorldWideView instances worldwide.
|
||||
|
||||
### Debugging Marketplace Submissions
|
||||
- **"Invalid Manifest" Error:** Ensure you are using `@worldwideview/wwv-plugin-sdk` as a `peerDependency` (not a direct dependency) so the host application injects the context correctly.
|
||||
- **Icon Not Showing:** Icons must be valid Lucide icon strings (e.g., `"Plane"`, `"Anchor"`).
|
||||
@@ -0,0 +1,126 @@
|
||||
<!-- Generated: 2026-04-23 06:11:00 UTC -->
|
||||
# Quickstart: Creating Your First Plugin
|
||||
|
||||
Welcome to WorldWideView plugin development! This tutorial will guide you through creating your first custom data layer on the 3D globe.
|
||||
|
||||
By the end of this guide, you will have a working plugin that plots real-time data on the WorldWideView map.
|
||||
|
||||
## 1. Prerequisites
|
||||
|
||||
Before you start, ensure you have:
|
||||
- Node.js ≥ 18
|
||||
- `npm` or `pnpm` installed
|
||||
- A running instance of WorldWideView on your local machine (running at `http://localhost:3000`).
|
||||
|
||||
## 2. Scaffold Your Plugin
|
||||
|
||||
WorldWideView plugins are built as standard NPM packages. They are entirely decoupled from the core application, allowing you to develop and publish them independently.
|
||||
|
||||
To generate a new plugin template, use the official CLI:
|
||||
|
||||
```bash
|
||||
npx @worldwideview/create-plugin@latest my-first-plugin
|
||||
cd my-first-plugin
|
||||
npm install
|
||||
```
|
||||
|
||||
This creates a lightweight Vite-based project pre-configured with the `@worldwideview/wwv-plugin-sdk`.
|
||||
|
||||
## 3. Link Your Plugin to WorldWideView
|
||||
|
||||
To see your plugin live on the globe while you develop, you need to link it to your local WorldWideView instance.
|
||||
|
||||
First, tell the CLI where your WorldWideView repository is located:
|
||||
```bash
|
||||
npx wwv config set wwv-path C:\path\to\your\worldwideview
|
||||
```
|
||||
|
||||
Next, link the plugin. This creates a symlink so your local WorldWideView instance can dynamically load your code:
|
||||
```bash
|
||||
npm run link
|
||||
```
|
||||
|
||||
Finally, start the plugin watcher. This will automatically rebuild your plugin whenever you save a file:
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
> [!TIP]
|
||||
> **Debugging Link Issues:** If your plugin doesn't appear in the WorldWideView "Installed Plugins" list after linking, check your `package.json`. The `"worldwideview"` object block is strictly required. Ensure `id`, `name`, and `version` are populated correctly.
|
||||
|
||||
## 4. Explore the Code
|
||||
|
||||
Open `src/index.ts` in your text editor. You'll see a class that implements the `WorldPlugin` interface:
|
||||
|
||||
```typescript
|
||||
import type { WorldPlugin, GeoEntity, PluginContext, LayerConfig, CesiumEntityOptions } from "@worldwideview/wwv-plugin-sdk";
|
||||
|
||||
export class MyFirstPlugin implements WorldPlugin {
|
||||
id = "my-first-plugin";
|
||||
name = "My First Data Layer";
|
||||
description = "A simple example plugin.";
|
||||
icon = "MapPin";
|
||||
category = "custom" as const;
|
||||
version = "1.0.0";
|
||||
|
||||
async initialize(ctx: PluginContext): Promise<void> {
|
||||
console.log("Plugin initialized!");
|
||||
}
|
||||
|
||||
destroy(): void { }
|
||||
|
||||
async fetch(timeRange: TimeRange): Promise<GeoEntity[]> {
|
||||
// Generate a single dummy point over Paris
|
||||
return [{
|
||||
id: "test-point-1",
|
||||
pluginId: this.id,
|
||||
latitude: 48.8566,
|
||||
longitude: 2.3522,
|
||||
timestamp: new Date(),
|
||||
properties: { name: "Hello World" },
|
||||
}];
|
||||
}
|
||||
|
||||
getPollingInterval(): number {
|
||||
return 60_000; // Fetch every 60 seconds
|
||||
}
|
||||
|
||||
getLayerConfig(): LayerConfig {
|
||||
return {
|
||||
color: "#ff0000",
|
||||
clusterEnabled: false,
|
||||
clusterDistance: 40,
|
||||
};
|
||||
}
|
||||
|
||||
renderEntity(entity: GeoEntity): CesiumEntityOptions {
|
||||
return {
|
||||
type: "point",
|
||||
color: "#ff0000",
|
||||
size: 15,
|
||||
outlineColor: "#ffffff",
|
||||
outlineWidth: 2
|
||||
};
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 5. View Your Plugin
|
||||
|
||||
1. Ensure your WorldWideView main application is running (`pnpm dev` or `pnpm dev:all` in the main repo).
|
||||
2. Open your browser to `http://localhost:3000`.
|
||||
3. Open the **Layers** panel on the left sidebar.
|
||||
4. Locate "My First Data Layer" and toggle it on.
|
||||
5. The globe will fly to Paris, and you should see a red dot!
|
||||
|
||||
> [!WARNING]
|
||||
> **Debugging Missing Points:** If the layer is toggled on but you don't see the point:
|
||||
> 1. Check your browser's Developer Console (F12) for any `DataBus` errors.
|
||||
> 2. Ensure your `fetch()` method returns an array of `GeoEntity` objects with valid `latitude` and `longitude` properties.
|
||||
> 3. Verify that your `renderEntity()` function returns a valid type (`point`, `billboard`, etc.).
|
||||
|
||||
## Next Steps
|
||||
|
||||
Congratulations! You've successfully built and linked your first plugin.
|
||||
|
||||
For advanced features—like real-time WebSocket streaming, containerizing your own backend microservices, or publishing your plugin to the global Marketplace—proceed to the **[Advanced Plugin Guide](docs/plugin-advanced.md)**.
|
||||
@@ -0,0 +1,28 @@
|
||||
<!-- Generated: 2026-04-23 06:11:00 UTC -->
|
||||
# Project Overview
|
||||
|
||||
WorldWideView is a real-time geospatial intelligence engine that visualizes live global data on an interactive 3D globe. It leverages a modern frontend stack to render high-density datasets synchronously, including aircraft, maritime vessels, conflict events, satellites, and environmental data.
|
||||
|
||||
The core value proposition of WorldWideView is mapping diverse, decoupled intelligence streams onto a central geographic interface using a dynamically loaded plugin architecture. Data sources operate completely decoupled from the display platform, streaming observations via WebSockets for sub-second visual updates. The ecosystem consists of multiple repositories, including the main app (`worldwideview`), the plugin marketplace (`worldwideview-marketplace`), and the WebSocket push server (`wwv-data-engine`).
|
||||
|
||||
## Key Files
|
||||
- `package.json` (Lines 1-76) - Core dependencies and project metadata for the monorepo workspace.
|
||||
- `src/app/layout.tsx` - Global application shell and React structure.
|
||||
- `src/core/plugins/PluginManager.ts` - Heart of the engine, registers and lifecycle-manages external intelligence views.
|
||||
- `src/core/globe/GlobeView.tsx` - Main Cesium globe component rendering.
|
||||
|
||||
## Technology Stack
|
||||
- **Framework:** Next.js 16 (App Router) — `src/app/`
|
||||
- **Language:** TypeScript 5 (Strict Mode) — `tsconfig.json`
|
||||
- **3D Engine:** CesiumJS + Resium (Google Photorealistic 3D Tiles) — `src/core/globe/GlobeView.tsx`
|
||||
- **State Management:** Zustand — `src/core/state/` (slice-based store)
|
||||
- **Event Bus:** Custom typed `DataBus` — `src/core/data/DataBus.ts`
|
||||
- **Database:** PostgreSQL via Prisma 7 — `prisma/schema.prisma`
|
||||
- **Styling:** Vanilla CSS (no Tailwind) — `src/app/globals.css`
|
||||
|
||||
## Platform Support
|
||||
Built as a highly portable Next.js container, it supports multiple deployment profiles controlled by `NEXT_PUBLIC_WWV_EDITION` (default: `local`).
|
||||
- **Local (`local`)**: Self-hosted, full features, auth enabled.
|
||||
- **Cloud (`cloud`)**: Managed cloud instance, full features.
|
||||
- **Demo (`demo`)**: Public demo, auth disabled, optional admin via `WWV_DEMO_ADMIN_SECRET`.
|
||||
Feature flags are evaluated at runtime in `src/core/edition.ts`.
|
||||
@@ -0,0 +1,216 @@
|
||||
# Plugin Architecture Migration Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Migrate the WorldWideView plugin architecture from compile-time hardcoded imports to a dynamic, runtime-loaded ecosystem where external developers can build, host, and distribute plugins without touching the core repository.
|
||||
|
||||
**Architecture:** We will introduce a bundler (`tsup`) to the SDK to compile `bundle` plugins into browser-ready ECMAScript Modules (ESM). We will expose shared dependencies (`react`, `cesium`, `lucide-react`) via a global `window.__WWV_SHARED__` object. Finally, we will refactor `AppShell.tsx` to dynamically load all plugins at runtime via `import(/* webpackIgnore: true */)`, removing the hardcoded imports, and we will update `loadPluginFromManifest.ts` to seamlessly handle the global dependency injection.
|
||||
|
||||
**Tech Stack:** Next.js, React, CesiumJS, tsup.
|
||||
|
||||
---
|
||||
|
||||
## User Review Required
|
||||
|
||||
> [!WARNING]
|
||||
> **Breaking Change**: This migration will decouple your built-in plugins from `AppShell.tsx`. They will now act as true "external" plugins that are loaded at runtime. During the transition, if the build steps aren't executed, the plugins will temporarily stop appearing on the globe. We will mitigate this by ensuring the build step runs before `next dev`.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **Static GeoJSON Files**: Since static `.geojson` files currently live in `public/data`, we will leave them there during phase 1 of this migration to ensure the app doesn't break, but we will point the plugin manifests to load them via absolute or absolute-relative URLs (`/data/...`). In phase 2, we will introduce a symlink script to move them out of `public` entirely.
|
||||
|
||||
## Open Questions
|
||||
|
||||
1. **Build Tool Choice**: I am proposing `tsup` because it requires zero configuration to output multiple formats, automatically externalizes dependencies, and natively transpiles TypeScript/React. Are you comfortable adding `tsup` to the `wwv-plugin-sdk` package?
|
||||
2. **Local Serving**: To test "built-in" plugins using the dynamic loading method, we need the Next.js app to serve their compiled `plugin.js` bundles. My plan adds a quick copy script to the root `package.json` that copies their `dist` folders into `public/builtin-plugins/` so they can be fetched locally via HTTP. Does this sound good?
|
||||
|
||||
## Proposed Changes
|
||||
|
||||
### Task 1: Initialize Global Shared Dependencies
|
||||
|
||||
**Files:**
|
||||
- Modify: `c:\dev\worldwideview\src\components\layout\AppShell.tsx`
|
||||
- Create: `c:\dev\worldwideview\src\core\plugins\PluginGlobals.ts`
|
||||
|
||||
- [ ] **Step 1: Create the PluginGlobals initializer**
|
||||
|
||||
```typescript
|
||||
import React from "react";
|
||||
import ReactDOM from "react-dom";
|
||||
import * as ReactDomServer from "react-dom/server";
|
||||
import { Plane, Ship, Camera, Shield, Flame, Map, Swords, Atom, Landmark, Mountain, PlaneTakeoff, Anchor, Lamp, Rocket, SunMoon, Cable, Pickaxe, ShieldAlert, Crosshair, SatelliteDish, Hand, Radar, Scale } from "lucide-react";
|
||||
import * as Cesium from "cesium";
|
||||
import * as WWVPluginSDK from "@worldwideview/wwv-plugin-sdk";
|
||||
|
||||
export function initPluginGlobals() {
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
// Create a registry of Lucide icons commonly used by plugins to prevent them from bundling the massive icon library
|
||||
const lucideIcons = {
|
||||
Plane, Ship, Camera, Shield, Flame, Map, Swords, Atom, Landmark, Mountain,
|
||||
PlaneTakeoff, Anchor, Lamp, Rocket, SunMoon, Cable, Pickaxe, ShieldAlert,
|
||||
Crosshair, SatelliteDish, Hand, Radar, Scale
|
||||
};
|
||||
|
||||
(window as any).__WWV_SHARED__ = {
|
||||
"react": React,
|
||||
"react-dom": ReactDOM,
|
||||
"react-dom/server": ReactDomServer,
|
||||
"cesium": Cesium,
|
||||
"@worldwideview/wwv-plugin-sdk": WWVPluginSDK,
|
||||
"lucide-react": lucideIcons
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Inject globals in AppShell before anything loads**
|
||||
|
||||
In `AppShell.tsx`, import and call `initPluginGlobals()` at the top of the file, outside of any React components.
|
||||
|
||||
```tsx
|
||||
import { initPluginGlobals } from "@/core/plugins/PluginGlobals";
|
||||
import dynamic from "next/dynamic";
|
||||
|
||||
// Initialize globals immediately so they exist before any dynamic imports
|
||||
if (typeof window !== "undefined") {
|
||||
initPluginGlobals();
|
||||
}
|
||||
//... rest of the file
|
||||
```
|
||||
|
||||
### Task 2: Configure SDK Build Tool (`tsup`)
|
||||
|
||||
**Files:**
|
||||
- Modify: `c:\dev\worldwideview\packages\wwv-plugin-sdk\package.json`
|
||||
- Create: `c:\dev\worldwideview\packages\wwv-plugin-sdk\bin\wwv-plugin-build.js`
|
||||
|
||||
- [ ] **Step 1: Add tsup dependency**
|
||||
|
||||
Run: `pnpm --filter @worldwideview/wwv-plugin-sdk add -D tsup`
|
||||
|
||||
- [ ] **Step 2: Create the wwv-plugin-build CLI wrapper**
|
||||
|
||||
Add this to `wwv-plugin-sdk/bin/wwv-plugin-build.js`:
|
||||
|
||||
```javascript
|
||||
#!/usr/bin/env node
|
||||
const { build } = require("tsup");
|
||||
const path = require("path");
|
||||
|
||||
async function run() {
|
||||
const cwd = process.cwd();
|
||||
await build({
|
||||
entry: ["src/index.ts"],
|
||||
outDir: "dist",
|
||||
format: ["esm"],
|
||||
target: "es2022",
|
||||
clean: true,
|
||||
dts: false,
|
||||
minify: false,
|
||||
sourcemap: true,
|
||||
// Mark all these as externals so they aren't bundled
|
||||
external: ["react", "react-dom", "cesium", "@worldwideview/wwv-plugin-sdk", "lucide-react"],
|
||||
// Provide a shim that converts bare imports into global lookups
|
||||
esbuildPlugins: [{
|
||||
name: "wwv-globals",
|
||||
setup(build) {
|
||||
build.onResolve({ filter: /^(react|react-dom|cesium|@worldwideview\/wwv-plugin-sdk|lucide-react)$/ }, args => {
|
||||
return { path: args.path, namespace: "wwv-global" };
|
||||
});
|
||||
build.onLoad({ filter: /.*/, namespace: "wwv-global" }, args => {
|
||||
let globalKey = args.path;
|
||||
if (args.path === "lucide-react") return { contents: `module.exports = window.__WWV_SHARED__["lucide-react"];` };
|
||||
return { contents: `module.exports = window.__WWV_SHARED__["${globalKey}"];` };
|
||||
});
|
||||
}
|
||||
}]
|
||||
});
|
||||
}
|
||||
run();
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Update SDK package.json to expose the bin**
|
||||
|
||||
```json
|
||||
"bin": {
|
||||
"wwv-plugin-build": "./bin/wwv-plugin-build.js"
|
||||
},
|
||||
```
|
||||
|
||||
### Task 3: Refactor Plugins to use Build Tool and Manifests
|
||||
|
||||
**Files:**
|
||||
- Modify: `wwv-plugin-aviation/package.json`
|
||||
- Modify: `wwv-plugin-aviation/plugin.json` (Create)
|
||||
|
||||
- [ ] **Step 1: Add build script to aviation plugin**
|
||||
|
||||
```json
|
||||
"scripts": {
|
||||
"build": "wwv-plugin-build"
|
||||
},
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Create plugin.json for aviation**
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "aviation",
|
||||
"name": "Aviation",
|
||||
"version": "1.0.7",
|
||||
"type": "data-layer",
|
||||
"format": "bundle",
|
||||
"trust": "built-in",
|
||||
"capabilities": ["data:own", "network:fetch"],
|
||||
"category": "aviation",
|
||||
"icon": "Plane",
|
||||
"entry": "/builtin-plugins/aviation/index.mjs"
|
||||
}
|
||||
```
|
||||
|
||||
*(Repeat for all other built-in plugins)*
|
||||
|
||||
### Task 4: Dynamic Initial Loader
|
||||
|
||||
**Files:**
|
||||
- Modify: `c:\dev\worldwideview\src\components\layout\AppShell.tsx`
|
||||
- Modify: `c:\dev\worldwideview\package.json`
|
||||
|
||||
- [ ] **Step 1: Remove Hardcoded Plugins**
|
||||
|
||||
In `AppShell.tsx`, delete the `builtIns` array and `import` statements at the top.
|
||||
|
||||
- [ ] **Step 2: Fetch and load all plugins via manifest**
|
||||
|
||||
Modify `AppShell.tsx` `startPlatform`:
|
||||
|
||||
```typescript
|
||||
// Fetch the unified list of ALL installed plugins (both built-in and dynamic)
|
||||
const res = await fetch("/api/marketplace/load");
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
for (const manifest of data.manifests) {
|
||||
if (disabledIds.has(manifest.id)) continue;
|
||||
try {
|
||||
await pluginManager.loadFromManifest(manifest);
|
||||
initLayer(manifest.id);
|
||||
} catch (e) {
|
||||
console.error("Failed to load plugin", manifest.id, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Add predev copy-script**
|
||||
|
||||
Modify `package.json` to copy compiled plugin `dist` folders to `public/builtin-plugins` so the Next.js server can serve them at the `/builtin-plugins/...` path.
|
||||
|
||||
## Verification Plan
|
||||
|
||||
### Automated Tests
|
||||
- Run `pnpm --filter wwv-plugin-aviation build` to ensure `tsup` generates a valid ES Module with no bundled React.
|
||||
- Verify `dist/index.mjs` contains `window.__WWV_SHARED__["react"]` lookups.
|
||||
|
||||
### Manual Verification
|
||||
- Start the Next.js server.
|
||||
- Open network tab in browser and verify `GET /builtin-plugins/aviation/index.mjs` succeeds.
|
||||
- Verify the Aviation plugin appears on the globe and renders planes successfully, indicating that it successfully retrieved Cesium and React from the global shared context.
|
||||
@@ -0,0 +1,475 @@
|
||||
# Demo Google AdSense Panel Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Add a Google AdSense vertical ad strip to the right side of the demo instance, with a dismissible banner explaining it's temporary to fund hosting.
|
||||
|
||||
**Architecture:** Three layers: (1) load the AdSense script conditionally in the root layout only when `isDemo` is true, (2) a reusable `AdUnit` client component that calls `adsbygoogle.push({})`, (3) a `DemoAdStrip` shell component that wraps the ad unit + a "why ads?" dismissible message, positioned as a fixed vertical strip on the right edge. CSP headers in `next.config.ts` must be updated to allow the AdSense domains.
|
||||
|
||||
**Tech Stack:** Next.js 16 (App Router, `next/script`), Google AdSense, vanilla CSS, Vitest
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
| File | Action | Responsibility |
|
||||
|---|---|---|
|
||||
| `src/app/layout.tsx` | MODIFY | Conditionally load AdSense `<Script>` for demo |
|
||||
| `next.config.ts` | MODIFY | Add AdSense domains to CSP `script-src` and `frame-src` |
|
||||
| `.env` | MODIFY | Add `NEXT_PUBLIC_ADSENSE_CLIENT_ID` placeholder |
|
||||
| `src/components/ads/AdUnit.tsx` | CREATE | Generic reusable AdSense unit component |
|
||||
| `src/components/ads/DemoAdStrip.tsx` | CREATE | Demo-only vertical strip: ad + "why ads?" message |
|
||||
| `src/components/ads/DemoAdStrip.css` | CREATE | Styles for the vertical ad strip |
|
||||
| `src/components/layout/AppShell.tsx` | MODIFY | Import and render `<DemoAdStrip />` |
|
||||
| `src/types/adsense.d.ts` | CREATE | TypeScript ambient declaration for `window.adsbygoogle` |
|
||||
|
||||
---
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **Before starting:** You need a Google AdSense publisher ID (`ca-pub-XXXXXXXXXXXXXXXX`) and an ad slot ID. These go into `.env` as `NEXT_PUBLIC_ADSENSE_CLIENT_ID` and are passed to the ad unit component. You can get these from [Google AdSense](https://www.google.com/adsense/). Without them the ads will not render, but the component framework will still work.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: TypeScript Ambient Declaration for AdSense
|
||||
|
||||
**Files:**
|
||||
- Create: `src/types/adsense.d.ts`
|
||||
|
||||
- [ ] **Step 1: Create the ambient type declaration**
|
||||
|
||||
```ts
|
||||
// src/types/adsense.d.ts
|
||||
interface Window {
|
||||
adsbygoogle: Array<Record<string, unknown>>;
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Commit**
|
||||
|
||||
```bash
|
||||
git add src/types/adsense.d.ts
|
||||
git commit -m "chore: add adsense ambient type declaration"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Environment Variable
|
||||
|
||||
**Files:**
|
||||
- Modify: `.env`
|
||||
|
||||
- [ ] **Step 1: Add the AdSense client ID placeholder**
|
||||
|
||||
Add the following line to the end of `.env`:
|
||||
|
||||
```
|
||||
# Google AdSense — only used on demo edition
|
||||
NEXT_PUBLIC_ADSENSE_CLIENT_ID=
|
||||
```
|
||||
|
||||
The actual value (`ca-pub-XXXXXXXXXXXXXXXX`) should be set in `.env.local` for local testing or in the deployment environment. The ad slot IDs will be hardcoded in the component since there's only one placement.
|
||||
|
||||
- [ ] **Step 2: Commit**
|
||||
|
||||
```bash
|
||||
git add .env
|
||||
git commit -m "chore: add NEXT_PUBLIC_ADSENSE_CLIENT_ID env var"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: CSP Headers Update
|
||||
|
||||
**Files:**
|
||||
- Modify: `next.config.ts:29-52`
|
||||
|
||||
- [ ] **Step 1: Update CSP in next.config.ts**
|
||||
|
||||
In the `headers()` function, modify the `script-src` and `frame-src` directives to allow AdSense domains.
|
||||
|
||||
```ts
|
||||
// Change this line (line 39):
|
||||
"script-src 'self' 'unsafe-eval' 'unsafe-inline' blob: https://analytics.worldwideview.dev https://va.vercel-scripts.com",
|
||||
|
||||
// To this:
|
||||
"script-src 'self' 'unsafe-eval' 'unsafe-inline' blob: https://analytics.worldwideview.dev https://va.vercel-scripts.com https://pagead2.googlesyndication.com https://adservice.google.com https://www.googletagservices.com",
|
||||
```
|
||||
|
||||
```ts
|
||||
// Change this line (line 49):
|
||||
"frame-src 'self' *.youtube.com *.youtube-nocookie.com *.twitch.tv *.vimeo.com *.webcamera.pl *.ivideon.com *.rtsp.me *.bnu.tv",
|
||||
|
||||
// To this:
|
||||
"frame-src 'self' *.youtube.com *.youtube-nocookie.com *.twitch.tv *.vimeo.com *.webcamera.pl *.ivideon.com *.rtsp.me *.bnu.tv https://googleads.g.doubleclick.net https://tpc.googlesyndication.com",
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Commit**
|
||||
|
||||
```bash
|
||||
git add next.config.ts
|
||||
git commit -m "feat: add Google AdSense domains to CSP headers"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: AdSense Script in Root Layout
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/app/layout.tsx:24-39`
|
||||
|
||||
- [ ] **Step 1: Conditionally load AdSense script for demo edition**
|
||||
|
||||
Add the AdSense `<Script>` tag inside `<head>`, using the `NEXT_PUBLIC_` env var for the client ID and the `NEXT_PUBLIC_WWV_EDITION` env var to gate loading.
|
||||
|
||||
```tsx
|
||||
// src/app/layout.tsx — updated <head> section
|
||||
<head>
|
||||
{/* Load CesiumJS base styles (optional, but helps with UI widgets if used later) */}
|
||||
<link rel="stylesheet" href="/cesium/Widgets/widgets.css" />
|
||||
</head>
|
||||
<body suppressHydrationWarning>
|
||||
{children}
|
||||
<Analytics />
|
||||
<Script
|
||||
src="https://analytics.worldwideview.dev/script.js"
|
||||
data-website-id="2c8f6c09-2651-4a2a-af99-b8cee1612b9a"
|
||||
strategy="afterInteractive"
|
||||
/>
|
||||
{process.env.NEXT_PUBLIC_WWV_EDITION === "demo" &&
|
||||
process.env.NEXT_PUBLIC_ADSENSE_CLIENT_ID && (
|
||||
<Script
|
||||
src={`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${process.env.NEXT_PUBLIC_ADSENSE_CLIENT_ID}`}
|
||||
crossOrigin="anonymous"
|
||||
strategy="afterInteractive"
|
||||
/>
|
||||
)}
|
||||
</body>
|
||||
```
|
||||
|
||||
> **Note:** We use the raw env var at the layout level (Server Component) rather than importing `isDemo` which uses `process.env.NEXT_PUBLIC_WWV_EDITION` anyway. This avoids importing the edition module into the root layout.
|
||||
|
||||
- [ ] **Step 2: Commit**
|
||||
|
||||
```bash
|
||||
git add src/app/layout.tsx
|
||||
git commit -m "feat: conditionally load AdSense script on demo edition"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 5: Reusable AdUnit Component
|
||||
|
||||
**Files:**
|
||||
- Create: `src/components/ads/AdUnit.tsx`
|
||||
|
||||
- [ ] **Step 1: Create the generic AdSense unit component**
|
||||
|
||||
```tsx
|
||||
// src/components/ads/AdUnit.tsx
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
interface AdUnitProps {
|
||||
adSlot: string;
|
||||
adFormat?: string;
|
||||
style?: React.CSSProperties;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function AdUnit({ adSlot, adFormat = "auto", style, className }: AdUnitProps) {
|
||||
const pushed = useRef(false);
|
||||
const clientId = process.env.NEXT_PUBLIC_ADSENSE_CLIENT_ID;
|
||||
|
||||
useEffect(() => {
|
||||
if (pushed.current || !clientId) return;
|
||||
try {
|
||||
(window.adsbygoogle = window.adsbygoogle || []).push({});
|
||||
pushed.current = true;
|
||||
} catch (err) {
|
||||
console.error("[AdUnit] AdSense push error:", err);
|
||||
}
|
||||
}, [clientId]);
|
||||
|
||||
if (!clientId) return null;
|
||||
|
||||
return (
|
||||
<div className={className} style={style}>
|
||||
<ins
|
||||
className="adsbygoogle"
|
||||
style={{ display: "block" }}
|
||||
data-ad-client={clientId}
|
||||
data-ad-slot={adSlot}
|
||||
data-ad-format={adFormat}
|
||||
data-full-width-responsive="false"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
> **Key detail:** The `pushed` ref prevents double-push on React strict mode / hot reload. `data-full-width-responsive="false"` prevents the ad from expanding beyond the container — critical for a fixed-width vertical strip.
|
||||
|
||||
- [ ] **Step 2: Commit**
|
||||
|
||||
```bash
|
||||
git add src/components/ads/AdUnit.tsx
|
||||
git commit -m "feat: add reusable AdUnit component"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 6: DemoAdStrip Component + Styles
|
||||
|
||||
**Files:**
|
||||
- Create: `src/components/ads/DemoAdStrip.tsx`
|
||||
- Create: `src/components/ads/DemoAdStrip.css`
|
||||
|
||||
- [ ] **Step 1: Create the CSS for the vertical ad strip**
|
||||
|
||||
```css
|
||||
/* src/components/ads/DemoAdStrip.css */
|
||||
|
||||
.demo-ad-strip {
|
||||
position: fixed;
|
||||
right: 0;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
width: 160px;
|
||||
z-index: 45;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: var(--space-md);
|
||||
padding: var(--space-sm);
|
||||
pointer-events: none;
|
||||
transition: transform var(--duration-slow) var(--ease-smooth),
|
||||
opacity var(--duration-slow) var(--ease-smooth);
|
||||
}
|
||||
|
||||
.demo-ad-strip--hidden {
|
||||
transform: translateX(200px);
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.demo-ad-strip__ad {
|
||||
pointer-events: auto;
|
||||
width: 160px;
|
||||
min-height: 600px;
|
||||
}
|
||||
|
||||
.demo-ad-strip__banner {
|
||||
pointer-events: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: var(--space-xs);
|
||||
padding: var(--space-sm) var(--space-md);
|
||||
background: var(--bg-glass);
|
||||
backdrop-filter: blur(var(--glass-blur));
|
||||
-webkit-backdrop-filter: blur(var(--glass-blur));
|
||||
border: 1px solid var(--border-subtle);
|
||||
border-radius: var(--radius-md);
|
||||
max-width: 160px;
|
||||
text-align: center;
|
||||
cursor: pointer;
|
||||
transition: all var(--duration-fast) var(--ease-smooth);
|
||||
}
|
||||
|
||||
.demo-ad-strip__banner:hover {
|
||||
border-color: rgba(var(--accent-rgb), 0.3);
|
||||
box-shadow: var(--glow-cyan);
|
||||
}
|
||||
|
||||
.demo-ad-strip__banner-label {
|
||||
font-size: 9px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.12em;
|
||||
text-transform: uppercase;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.demo-ad-strip__banner-text {
|
||||
font-size: 11px;
|
||||
line-height: 1.4;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.demo-ad-strip__close {
|
||||
position: absolute;
|
||||
top: var(--space-xs);
|
||||
right: var(--space-xs);
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 50%;
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: var(--text-muted);
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: color var(--duration-fast) var(--ease-smooth);
|
||||
}
|
||||
|
||||
.demo-ad-strip__close:hover {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
/* Hide on mobile — ads shouldn't overlay the full-screen globe */
|
||||
@media (max-width: 768px) {
|
||||
.demo-ad-strip {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Create the DemoAdStrip component**
|
||||
|
||||
```tsx
|
||||
// src/components/ads/DemoAdStrip.tsx
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { isDemo } from "@/core/edition";
|
||||
import { AdUnit } from "./AdUnit";
|
||||
import { X } from "lucide-react";
|
||||
import "./DemoAdStrip.css";
|
||||
|
||||
/** The ad slot ID for the vertical skyscraper unit — set this in AdSense dashboard. */
|
||||
const VERTICAL_AD_SLOT = "REPLACE_WITH_YOUR_AD_SLOT_ID";
|
||||
|
||||
export function DemoAdStrip() {
|
||||
const [showMessage, setShowMessage] = useState(false);
|
||||
const [closed, setClosed] = useState(false);
|
||||
|
||||
if (!isDemo || closed) return null;
|
||||
|
||||
return (
|
||||
<aside className="demo-ad-strip" aria-label="Sponsored content">
|
||||
<AdUnit
|
||||
adSlot={VERTICAL_AD_SLOT}
|
||||
adFormat="vertical"
|
||||
className="demo-ad-strip__ad"
|
||||
/>
|
||||
|
||||
<div
|
||||
className="demo-ad-strip__banner"
|
||||
onClick={() => setShowMessage((prev) => !prev)}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onKeyDown={(e) => { if (e.key === "Enter") setShowMessage((prev) => !prev); }}
|
||||
>
|
||||
<button
|
||||
className="demo-ad-strip__close"
|
||||
onClick={(e) => { e.stopPropagation(); setClosed(true); }}
|
||||
aria-label="Dismiss ad panel"
|
||||
>
|
||||
<X size={12} />
|
||||
</button>
|
||||
<span className="demo-ad-strip__banner-label">Why ads?</span>
|
||||
{showMessage ? (
|
||||
<span className="demo-ad-strip__banner-text">
|
||||
This isn't permanent — it's temporary because I'm a single
|
||||
dev and need to cover hosting costs. Thank you for understanding.
|
||||
</span>
|
||||
) : (
|
||||
<span className="demo-ad-strip__banner-text">
|
||||
Click to learn more
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add src/components/ads/DemoAdStrip.tsx src/components/ads/DemoAdStrip.css
|
||||
git commit -m "feat: add DemoAdStrip with Google AdSense vertical unit"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 7: Integrate into AppShell
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/components/layout/AppShell.tsx:8-9,168`
|
||||
|
||||
- [ ] **Step 1: Add import**
|
||||
|
||||
After the existing `CameraStatsPanel` import (line 8), add:
|
||||
|
||||
```tsx
|
||||
import CameraStatsPanel from "@/components/panels/CameraStatsPanel";
|
||||
import { DemoAdStrip } from "@/components/ads/DemoAdStrip"; // ADD THIS
|
||||
import { Timeline } from "@/components/timeline/Timeline";
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Add the JSX**
|
||||
|
||||
After `<EntityInfoCard />` (line 168), add:
|
||||
|
||||
```tsx
|
||||
<EntityInfoCard />
|
||||
<DemoAdStrip />
|
||||
<Timeline />
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add src/components/layout/AppShell.tsx
|
||||
git commit -m "feat: integrate DemoAdStrip into AppShell"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 8: ads.txt for AdSense Verification
|
||||
|
||||
**Files:**
|
||||
- Create: `public/ads.txt`
|
||||
|
||||
- [ ] **Step 1: Create ads.txt**
|
||||
|
||||
```
|
||||
google.com, ca-pub-XXXXXXXXXXXXXXXX, DIRECT, f08c47fec0942fa0
|
||||
```
|
||||
|
||||
> Replace `ca-pub-XXXXXXXXXXXXXXXX` with your actual publisher ID. This file is required by AdSense for domain verification.
|
||||
|
||||
- [ ] **Step 2: Commit**
|
||||
|
||||
```bash
|
||||
git add public/ads.txt
|
||||
git commit -m "chore: add ads.txt for AdSense domain verification"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Open Questions
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **Do you have a Google AdSense publisher ID yet?** If not, you'll need to sign up at https://www.google.com/adsense/ and get your `ca-pub-XXXX` ID and create a 160x600 "Wide Skyscraper" ad unit to get the slot ID. The code will render nothing gracefully until these are configured.
|
||||
|
||||
> [!WARNING]
|
||||
> **CSP changes are required for AdSense to work.** The current CSP is restrictive and blocks `pagead2.googlesyndication.com` and `googleads.g.doubleclick.net`. Task 3 adds them. Without this, ads will be silently blocked by the browser.
|
||||
|
||||
---
|
||||
|
||||
## Verification Plan
|
||||
|
||||
### Manual Verification
|
||||
|
||||
1. Set `NEXT_PUBLIC_WWV_EDITION=demo` and `NEXT_PUBLIC_ADSENSE_CLIENT_ID=ca-pub-XXXX` in `.env.local`
|
||||
2. Run `pnpm dev`
|
||||
3. Verify: A 160px vertical strip appears on the right edge of the screen
|
||||
4. Verify: The "Why ads?" banner is clickable and toggles the explanation message
|
||||
5. Verify: Clicking the X dismisses the entire strip
|
||||
6. Verify: On mobile viewport widths (< 768px), the strip is hidden
|
||||
7. Verify: Set `NEXT_PUBLIC_WWV_EDITION=local` → strip does not render at all
|
||||
8. Verify: Browser console shows no CSP violations related to AdSense domains
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,145 @@
|
||||
# Expand OSM Chips Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Expand the available OSM search chips to include a curated list of ~30 pre-loaded OSINT-relevant tags, and add a live Taginfo API autocomplete search to dynamically find and select any of the millions of other OSM tags.
|
||||
|
||||
**Architecture:** We will replace the current small `COMMON_TAGS` array with a richer, categorized list inside the `OSMSidebar` file. To allow access to "all" tags without crashing the UI, we will add a debounced fetch hook that hits `https://taginfo.openstreetmap.org/api/4/tags/popular` (or the equivalent search endpoint) when the user types in the filter box. These dynamically fetched tags will temporarily populate the chip list.
|
||||
|
||||
**Tech Stack:** React, TypeScript, Taginfo API
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Update Pre-Loaded COMMON_TAGS
|
||||
|
||||
**Files:**
|
||||
- Modify: `c:\dev\worldwideview\packages\wwv-plugin-osm-search\src\components\OSMSidebar.tsx:6-11`
|
||||
|
||||
- [ ] **Step 1: Replace existing COMMON_TAGS array**
|
||||
|
||||
```tsx
|
||||
const COMMON_TAGS = [
|
||||
// Military & Security
|
||||
"military=base", "military=bunker", "amenity=police", "amenity=prison",
|
||||
// Aviation & Maritime
|
||||
"aeroway=aerodrome", "aeroway=helipad", "aeroway=hangar", "man_made=pier", "harbour=yes",
|
||||
// Infrastructure & Utilities
|
||||
"power=plant", "power=substation", "telecom=antenna", "man_made=communications_tower", "man_made=water_tower",
|
||||
// Transport
|
||||
"highway=bus_stop", "railway=station", "amenity=fuel", "amenity=parking",
|
||||
// Medical & Emergency
|
||||
"amenity=hospital", "amenity=fire_station", "amenity=clinic",
|
||||
// General Commercial & Industrial
|
||||
"shop=supermarket", "tourism=hotel", "industrial=factory", "landuse=industrial",
|
||||
// Education & Amenities
|
||||
"amenity=school", "amenity=university", "amenity=cafe", "building=house"
|
||||
];
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Commit**
|
||||
|
||||
```bash
|
||||
git add packages/wwv-plugin-osm-search/src/components/OSMSidebar.tsx
|
||||
git commit -m "feat(osm-search): expand quick preset tags with OSINT categories"
|
||||
```
|
||||
|
||||
### Task 2: Implement Taginfo Dynamic Autocomplete
|
||||
|
||||
**Files:**
|
||||
- Modify: `c:\dev\worldwideview\packages\wwv-plugin-osm-search\src\components\OSMSidebar.tsx`
|
||||
|
||||
- [ ] **Step 1: Add state and debounced fetch logic inside OSMSidebar component**
|
||||
|
||||
```tsx
|
||||
const [searchText, setSearchText] = useState("");
|
||||
const [activeTags, setActiveTags] = useState<string[]>([]);
|
||||
const [dynamicTags, setDynamicTags] = useState<string[]>([]);
|
||||
const [isSearchingApi, setIsSearchingApi] = useState(false);
|
||||
|
||||
// Add this useEffect below the useState hooks
|
||||
React.useEffect(() => {
|
||||
if (searchText.length < 3) {
|
||||
setDynamicTags([]);
|
||||
return;
|
||||
}
|
||||
|
||||
const timer = setTimeout(async () => {
|
||||
setIsSearchingApi(true);
|
||||
try {
|
||||
// Fetch tags matching the search term from OSM Taginfo
|
||||
const res = await fetch(`https://taginfo.openstreetmap.org/api/4/search/by_keyword?query=${encodeURIComponent(searchText)}`);
|
||||
const data = await res.json();
|
||||
if (data && data.data) {
|
||||
// Extract exact key=value pairs or just keys, format as "key=value"
|
||||
const tags = data.data
|
||||
.filter((item: any) => item.key && item.value)
|
||||
.map((item: any) => `${item.key}=${item.value}`)
|
||||
.slice(0, 15); // Limit to top 15 results
|
||||
setDynamicTags(tags);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Taginfo fetch failed", err);
|
||||
} finally {
|
||||
setIsSearchingApi(false);
|
||||
}
|
||||
}, 500); // 500ms debounce
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}, [searchText]);
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Update rendering logic to merge static and dynamic tags**
|
||||
|
||||
Look for the `renderedTags` definition and replace it:
|
||||
|
||||
```tsx
|
||||
// Combine filtered common tags with newly fetched dynamic tags, removing duplicates
|
||||
const filteredCommon = searchText
|
||||
? COMMON_TAGS.filter(t => t.toLowerCase().includes(searchText.toLowerCase()))
|
||||
: COMMON_TAGS;
|
||||
|
||||
const renderedTags = Array.from(new Set([...filteredCommon, ...dynamicTags]));
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Add loading indicator to the search input area**
|
||||
|
||||
Look for the `<input>` element for `searchText` and wrap it/add a loading indicator:
|
||||
|
||||
```tsx
|
||||
<div style={{ position: "relative" }}>
|
||||
<input
|
||||
style={{
|
||||
width: "100%",
|
||||
padding: "8px",
|
||||
paddingRight: "24px",
|
||||
backgroundColor: "rgba(0,0,0,0.3)",
|
||||
color: "#fff",
|
||||
border: "1px solid var(--border-subtle)",
|
||||
borderRadius: "4px",
|
||||
fontSize: "13px"
|
||||
}}
|
||||
placeholder="Filter or search OSM for tags..."
|
||||
value={searchText}
|
||||
onChange={e => setSearchText(e.target.value)}
|
||||
/>
|
||||
{isSearchingApi && (
|
||||
<span style={{
|
||||
position: "absolute",
|
||||
right: "8px",
|
||||
top: "50%",
|
||||
transform: "translateY(-50%)",
|
||||
fontSize: "10px",
|
||||
color: "var(--text-muted)"
|
||||
}}>
|
||||
⏳
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add packages/wwv-plugin-osm-search/src/components/OSMSidebar.tsx
|
||||
git commit -m "feat(osm-search): add live Taginfo autocomplete for unlisted tags"
|
||||
```
|
||||
@@ -0,0 +1,139 @@
|
||||
# Plugin Versioning Streamlining Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Refactor all WorldWideView plugin classes to derive their `version` property dynamically from their local `package.json` file rather than hardcoding string literals.
|
||||
|
||||
**Architecture:** We will replace the hardcoded `version = "x.y.z"` strings in the core `WorldPlugin` interface implementations across all monorepo packages. We will utilize TypeScript's JSON module resolution feature to `import pkg from "../package.json"` and map `version = pkg.version`. This ensures that `pnpm version patch` is the single source of truth and eliminates the double-bookkeeping that previously made CI fixes tedious.
|
||||
|
||||
**Tech Stack:** TypeScript, Next.js / bundler (JSON module resolution), pnpm workspaces.
|
||||
|
||||
---
|
||||
|
||||
## Task 1: Verify TypeScript Configuration
|
||||
|
||||
**Files:**
|
||||
- Modify: N/A (Verification step)
|
||||
|
||||
- [ ] **Step 1: Check `tsconfig.json` for JSON resolution**
|
||||
|
||||
Run: `cat tsconfig.json | grep resolveJsonModule`
|
||||
Expected: `"resolveJsonModule": true`
|
||||
|
||||
- [ ] **Step 2: Check compiler compatibility**
|
||||
|
||||
Run: `pnpm exec tsc --noEmit`
|
||||
Expected: PASS (exit code 0)
|
||||
|
||||
## Task 2: Refactor Group A Plugins (Core Infrastructure)
|
||||
|
||||
**Files:**
|
||||
- Modify: `packages/wwv-plugin-aviation/src/index.ts`
|
||||
- Modify: `packages/wwv-plugin-maritime/src/index.ts`
|
||||
- Modify: `packages/wwv-plugin-military-aviation/src/index.ts`
|
||||
|
||||
- [ ] **Step 1: Update plugin classes**
|
||||
|
||||
For each file above, modify the imports and the class body:
|
||||
|
||||
```typescript
|
||||
import pkg from "../package.json";
|
||||
// ...
|
||||
export class AviationPlugin implements WorldPlugin { // (or extends BasePlugin)
|
||||
// ...
|
||||
version = pkg.version;
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify compilation**
|
||||
|
||||
Run: `pnpm exec tsc --noEmit`
|
||||
Expected: PASS
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git commit -am "refactor(plugins): derive version dynamically for core infrastructure plugins [Patch]"
|
||||
```
|
||||
|
||||
## Task 3: Refactor Group B Plugins (Facilities & Infrastructure)
|
||||
|
||||
**Files:**
|
||||
- Modify: `packages/wwv-plugin-airports/src/index.ts`
|
||||
- Modify: `packages/wwv-plugin-seaports/src/index.ts`
|
||||
- Modify: `packages/wwv-plugin-spaceports/src/index.ts`
|
||||
- Modify: `packages/wwv-plugin-embassies/src/index.ts`
|
||||
- Modify: `packages/wwv-plugin-lighthouses/src/index.ts`
|
||||
- Modify: `packages/wwv-plugin-nuclear/src/index.ts`
|
||||
- Modify: `packages/wwv-plugin-undersea-cables/src/index.ts`
|
||||
- Modify: `packages/wwv-plugin-mineral-mines/src/index.ts`
|
||||
|
||||
- [ ] **Step 1: Update plugin classes**
|
||||
|
||||
For each file above, replace `version = "..."` with `version = pkg.version` and add `import pkg from "../package.json";`.
|
||||
|
||||
- [ ] **Step 2: Verify compilation**
|
||||
|
||||
Run: `pnpm exec tsc --noEmit`
|
||||
Expected: PASS
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git commit -am "refactor(plugins): derive version dynamically for facility plugins [Patch]"
|
||||
```
|
||||
|
||||
## Task 4: Refactor Group C Plugins (Hazards & Events)
|
||||
|
||||
**Files:**
|
||||
- Modify: `packages/wwv-plugin-earthquakes/src/index.ts`
|
||||
- Modify: `packages/wwv-plugin-volcanoes/src/index.ts`
|
||||
- Modify: `packages/wwv-plugin-wildfire/src/index.ts`
|
||||
- Modify: `packages/wwv-plugin-conflict-events/src/index.tsx`
|
||||
- Modify: `packages/wwv-plugin-conflict-zones/src/index.tsx`
|
||||
- Modify: `packages/wwv-plugin-civil-unrest/src/index.tsx`
|
||||
- Modify: `packages/wwv-plugin-cyber-attacks/src/index.tsx`
|
||||
- Modify: `packages/wwv-plugin-international-sanctions/src/index.tsx`
|
||||
|
||||
- [ ] **Step 1: Update plugin classes**
|
||||
|
||||
For each file above, replace `version = "..."` with `version = pkg.version` and add `import pkg from "../package.json";`. Note that some files are `.tsx`.
|
||||
|
||||
- [ ] **Step 2: Verify compilation**
|
||||
|
||||
Run: `pnpm exec tsc --noEmit`
|
||||
Expected: PASS
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git commit -am "refactor(plugins): derive version dynamically for event and hazard plugins [Patch]"
|
||||
```
|
||||
|
||||
## Task 5: Refactor Group D Plugins (Misc & Utilities)
|
||||
|
||||
**Files:**
|
||||
- Modify: `packages/wwv-plugin-satellite/src/index.ts`
|
||||
- Modify: `packages/wwv-plugin-surveillance-satellites/src/index.tsx`
|
||||
- Modify: `packages/wwv-plugin-osm-search/src/index.ts`
|
||||
- Modify: `packages/wwv-plugin-iranwarlive/src/index.ts`
|
||||
- Modify: `packages/wwv-plugin-daynight/src/index.ts`
|
||||
- Modify: `packages/wwv-plugin-camera/src/index.ts`
|
||||
- Modify: `packages/wwv-plugin-borders/src/index.ts`
|
||||
- Modify: `packages/wwv-plugin-gps-jamming/src/index.tsx`
|
||||
- Modify: `packages/wwv-plugin-air-defense/src/index.tsx`
|
||||
|
||||
- [ ] **Step 1: Update plugin classes**
|
||||
|
||||
For each file above, replace `version = "..."` with `version = pkg.version` and add `import pkg from "../package.json";`.
|
||||
|
||||
- [ ] **Step 2: Verify compilation and tests**
|
||||
|
||||
Run: `pnpm exec tsc --noEmit`
|
||||
Run: `pnpm test`
|
||||
Expected: PASS
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git commit -am "refactor(plugins): derive version dynamically for utility plugins [Patch]"
|
||||
```
|
||||
@@ -0,0 +1,124 @@
|
||||
# Demo Default Plugins Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Enable specific plugins by default on the demo edition via environment variables so the user is immediately impressed.
|
||||
|
||||
**Architecture:** Update `layersSlice.ts` to accept an optional `defaultEnabled` parameter in `initLayer`. In `AppShell.tsx`, look up `NEXT_PUBLIC_DEMO_DEFAULT_PLUGINS` when the edition is `demo`, and pass the flag true to `initLayer` for matching plugins during registration. Document the variable in `.env.example`.
|
||||
|
||||
**Tech Stack:** Next.js, Zustand, TypeScript.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Update layer slice definition
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/core/state/layersSlice.ts`
|
||||
|
||||
- [ ] **Step 1: Write the implementation**
|
||||
|
||||
Update `initLayer` in `src/core/state/layersSlice.ts` to accept a second parameter:
|
||||
|
||||
```typescript
|
||||
// Add defaultEnabled parameter to the interface
|
||||
export interface LayersSlice {
|
||||
// ...
|
||||
initLayer: (pluginId: string, defaultEnabled?: boolean) => void;
|
||||
}
|
||||
|
||||
// ...
|
||||
|
||||
// Use the parameter in the state updater
|
||||
initLayer: (pluginId, defaultEnabled = false) =>
|
||||
set((state) => ({
|
||||
layers: {
|
||||
...state.layers,
|
||||
[pluginId]: state.layers[pluginId] || { enabled: defaultEnabled, entityCount: 0, loading: false },
|
||||
},
|
||||
})),
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Commit**
|
||||
|
||||
```bash
|
||||
git add src/core/state/layersSlice.ts
|
||||
npm run commit -- "feat: add defaultEnabled param to initLayer in layers slice"
|
||||
```
|
||||
|
||||
### Task 2: Apply default configuration in AppShell
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/components/layout/AppShell.tsx`
|
||||
|
||||
- [ ] **Step 1: Write the implementation**
|
||||
|
||||
Add `isDemo` import at the top of `src/components/layout/AppShell.tsx`:
|
||||
|
||||
```typescript
|
||||
import { isDemo } from "@/core/edition";
|
||||
```
|
||||
|
||||
In `AppShell.tsx`, around line 71, inside `startPlatform()`, fetch the value from the environment if the instance is demo:
|
||||
|
||||
```typescript
|
||||
// Fetch disabled built-in plugins before registration
|
||||
let disabledIds = new Set<string>();
|
||||
// ... (keep existing try/catch block)
|
||||
|
||||
// Setup demo defaults
|
||||
const demoDefaultPlugins = new Set<string>();
|
||||
if (isDemo) {
|
||||
const envVar = process.env.NEXT_PUBLIC_DEMO_DEFAULT_PLUGINS || "";
|
||||
envVar.split(",").forEach(s => {
|
||||
const clean = s.trim();
|
||||
if (clean) demoDefaultPlugins.add(clean);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Then update the `pluginManager` registration loop to inject the boolean for `initLayer`:
|
||||
|
||||
```typescript
|
||||
for (const plugin of pluginRegistry.getAll()) {
|
||||
await pluginManager.registerPlugin(plugin);
|
||||
initLayer(plugin.id, demoDefaultPlugins.has(plugin.id));
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test to verify it passes**
|
||||
|
||||
Run type checks to verify no compilation issues:
|
||||
`npx tsc --noEmit`
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add src/components/layout/AppShell.tsx
|
||||
npm run commit -- "feat: parse and apply default demo plugins via NEXT_PUBLIC_DEMO_DEFAULT_PLUGINS"
|
||||
```
|
||||
|
||||
### Task 3: Document environment definitions
|
||||
|
||||
**Files:**
|
||||
- Modify: `.env.example`
|
||||
- Modify: `.env`
|
||||
|
||||
- [ ] **Step 1: Write the implementation**
|
||||
|
||||
Update `.env.example` and `.env` around the `NEXT_PUBLIC_WWV_EDITION=local` definition:
|
||||
|
||||
```dotenv
|
||||
# Default plugins enabled on boot for demo edition
|
||||
# Comma-separated list of plugin IDs (e.g. aviation,maritime,iranwarlive)
|
||||
NEXT_PUBLIC_DEMO_DEFAULT_PLUGINS=
|
||||
|
||||
# Edition: "local" | "cloud" | "demo"
|
||||
NEXT_PUBLIC_WWV_EDITION=local
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Commit**
|
||||
|
||||
```bash
|
||||
git add .env.example .env
|
||||
npm run commit -- "docs: add NEXT_PUBLIC_DEMO_DEFAULT_PLUGINS to env templates"
|
||||
```
|
||||
@@ -0,0 +1,177 @@
|
||||
# Decouple Plugin Proxies Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Strip out hardcoded proxy endpoints from the `worldwideview` core repository to enforce a fully decoupled plugin ecosystem, replacing them with direct browser fetching or a universal CORS proxy.
|
||||
|
||||
**Architecture:** Remove preferential API routes (`/api/earthquake`, `/api/undersea-cables`, `/api/camera/*`) from the `worldwideview` core app. Promote the existing camera proxy to a universal `/api/proxy` with strict SSRF defenses. Provide direct browser-fetch code for the `wwv-plugin-earthquakes` where CORS permits, and migrate traffic camera fetchers directly into the `wwv-plugin-camera` package to fetch via the universal proxy.
|
||||
|
||||
**Tech Stack:** Next.js 16 (App Router), TypeScript, pnpm workspace
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Promote Universal Proxy in Core Repository
|
||||
|
||||
**Files:**
|
||||
- Create (Move): `src/app/api/proxy/route.ts`
|
||||
- Delete: `src/app/api/camera/proxy/route.ts`
|
||||
|
||||
- [ ] **Step 1: Relocate the proxy route and update logs**
|
||||
|
||||
Move the existing camera proxy to act as a system-wide universal proxy.
|
||||
|
||||
Run: `mkdir -p src/app/api/proxy`
|
||||
Run: `mv src/app/api/camera/proxy/route.ts src/app/api/proxy/route.ts`
|
||||
|
||||
- [ ] **Step 2: Update the error logging prefix in the new file**
|
||||
|
||||
Modify `src/app/api/proxy/route.ts` near line 97:
|
||||
|
||||
```json
|
||||
{
|
||||
"instruction": "Update the error logging prefix",
|
||||
"replace_chunks": [
|
||||
{
|
||||
"start_line": 96,
|
||||
"end_line": 98,
|
||||
"target_content": " } catch (error: any) {\n console.error(\"[CameraProxy] Error fetching target URL:\", error);\n return NextResponse.json(",
|
||||
"replacement_content": " } catch (error: any) {\n console.error(\"[UniversalProxy] Error fetching target URL:\", error);\n return NextResponse.json("
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Commit the Universal Proxy**
|
||||
|
||||
```bash
|
||||
git add src/app/api/proxy/route.ts src/app/api/camera/proxy/route.ts
|
||||
git commit -m "refactor: promote camera proxy to universal proxy"
|
||||
```
|
||||
|
||||
### Task 2: Strip Preferential Proxy Routes From Core Application
|
||||
|
||||
**Files:**
|
||||
- Delete: `src/app/api/earthquake/route.ts`
|
||||
- Delete: `src/app/api/undersea-cables/route.ts`
|
||||
- Delete: everything in `src/app/api/camera` codebase (`caltrans`, `extract`, `gdot`, `test`, `tfl`, `traffic`)
|
||||
|
||||
- [ ] **Step 1: Delete all plugin-specific Next.js API routes**
|
||||
|
||||
Run: `rm -rf src/app/api/earthquake`
|
||||
Run: `rm -rf src/app/api/undersea-cables`
|
||||
|
||||
**WAIT**: For `src/app/api/camera`, we must physically copy the fetchers into `worldwideview-plugins` before we delete them.
|
||||
|
||||
Run: `cp -r src/app/api/camera/caltrans ../worldwideview-plugins/packages/wwv-plugin-camera/src/`
|
||||
Run: `cp -r src/app/api/camera/gdot ../worldwideview-plugins/packages/wwv-plugin-camera/src/`
|
||||
Run: `cp -r src/app/api/camera/tfl ../worldwideview-plugins/packages/wwv-plugin-camera/src/`
|
||||
Run: `rm -rf src/app/api/camera`
|
||||
|
||||
- [ ] **Step 2: Commit the deleted API routes**
|
||||
|
||||
```bash
|
||||
git add src/app/api/earthquake src/app/api/undersea-cables src/app/api/camera
|
||||
git commit -m "refactor!: strip preferential plugin APIs from core"
|
||||
```
|
||||
|
||||
### Task 3: Migrate Earthquakes and Undersea Cables Plugins
|
||||
|
||||
**Files:**
|
||||
- Modify: `../worldwideview-plugins/packages/wwv-plugin-earthquakes/src/index.ts`
|
||||
- Modify: `../worldwideview-plugins/packages/wwv-plugin-undersea-cables/src/index.ts`
|
||||
|
||||
- [ ] **Step 1: Update Earthquakes plugin to direct browser fetch (Option A)**
|
||||
|
||||
In `../worldwideview-plugins/packages/wwv-plugin-earthquakes/src/index.ts`, replace the `/api/earthquake` fetch with the USGS direct URL.
|
||||
|
||||
```json
|
||||
{
|
||||
"instruction": "Replace the API fetch with direct USGS fetch and remove apiBasePath",
|
||||
"replace_chunks": [
|
||||
{
|
||||
"start_line": 38,
|
||||
"end_line": 40,
|
||||
"target_content": " try {\n const res = await globalThis.fetch(`/api/earthquake`);\n if (!res.ok) {",
|
||||
"replacement_content": " try {\n const res = await globalThis.fetch(`https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson`);\n if (!res.ok) {"
|
||||
},
|
||||
{
|
||||
"start_line": 94,
|
||||
"end_line": 96,
|
||||
"target_content": " getServerConfig(): ServerPluginConfig {\n return { apiBasePath: \"/api/earthquake\", pollingIntervalMs: 120000, historyEnabled: false };\n }",
|
||||
"replacement_content": " getServerConfig(): ServerPluginConfig {\n return { pollingIntervalMs: 120000, historyEnabled: false };\n }"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Update Undersea Cables plugin to use Universal Proxy (Option B)**
|
||||
|
||||
In `../worldwideview-plugins/packages/wwv-plugin-undersea-cables/src/index.ts`:
|
||||
|
||||
```json
|
||||
{
|
||||
"instruction": "Proxy route to universal proxy",
|
||||
"replace_chunks": [
|
||||
{
|
||||
"start_line": 35,
|
||||
"end_line": 37,
|
||||
"target_content": " // Proxy route to bypass CORS for Telegeography submarine cable map API\n const url = \"/api/undersea-cables\";\n ",
|
||||
"replacement_content": " // Proxy route to bypass CORS for Telegeography submarine cable map API\n const targetUrl = encodeURIComponent(\"https://www.submarinecablemap.com/api/v3/cable/cable-geo.json\");\n const url = `/api/proxy?url=${targetUrl}`;\n "
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Commit the plugin migrations**
|
||||
|
||||
```bash
|
||||
cd ../worldwideview-plugins
|
||||
git add packages/wwv-plugin-earthquakes/src/index.ts packages/wwv-plugin-undersea-cables/src/index.ts
|
||||
git commit -m "refactor: transition earthquake and undersea cables to decoupled fetching"
|
||||
cd ../worldwideview
|
||||
```
|
||||
|
||||
### Task 4: Refactor Camera Plugin to Fetch Natively
|
||||
|
||||
**Files:**
|
||||
- Modify: `../worldwideview-plugins/packages/wwv-plugin-camera/src/index.ts`
|
||||
- Delete: `caltrans`, `gdot`, `tfl` previously copied components (combine into `trafficFetchers.ts`)
|
||||
|
||||
- [ ] **Step 1: Consolidate the camera fetchers**
|
||||
|
||||
Create `../worldwideview-plugins/packages/wwv-plugin-camera/src/trafficFetchers.ts`.
|
||||
Migrate the code from the `caltransFetcher.ts`, `gdotFetcher.ts`, and `tflFetcher.ts` files that we copied in Task 2.
|
||||
Crucially, when doing `fetch(...)` in these fetchers, if the endpoint doesn't support CORS, wrap it in `/api/proxy?url=${encodeURIComponent(...) }` so the browser can fetch it. Ensure the data models align.
|
||||
|
||||
- [ ] **Step 2: Update `wwv-plugin-camera/src/index.ts` to call the fetchers natively**
|
||||
|
||||
In `../worldwideview-plugins/packages/wwv-plugin-camera/src/index.ts` function `loadTrafficCameras()`:
|
||||
|
||||
```json
|
||||
{
|
||||
"instruction": "Replace API fetch with native client-side parallel fetching",
|
||||
"replace_chunks": [
|
||||
{
|
||||
"start_line": 106,
|
||||
"end_line": 118,
|
||||
"target_content": " private async loadTrafficCameras(): Promise<void> {\n try {\n const res = await fetch(\"/api/camera/traffic\");\n if (!res.ok) throw new Error(`API returned ${res.status}`);\n const data = await res.json();\n if (data.cameras && Array.isArray(data.cameras)) {\n this.sourceBuckets[\"default\"] = data.cameras.map(\n (f: unknown, i: number) => mapGeoJsonFeature(f, i, \"traffic\"),\n );\n }\n } catch (err) {\n console.warn(\"[CameraPlugin] Traffic cameras API failed:\", err);\n }",
|
||||
"replacement_content": " private async loadTrafficCameras(): Promise<void> {\n try {\n const { fetchCaltrans, fetchGdot, fetchTfl } = await import(\"./trafficFetchers\");\n const [caltrans, gdot, tfl] = await Promise.allSettled([\n fetchCaltrans(), fetchGdot(), fetchTfl()\n ]);\n \n const cameras = [];\n if (caltrans.status === \"fulfilled\") cameras.push(...caltrans.value);\n if (gdot.status === \"fulfilled\") cameras.push(...gdot.value);\n if (tfl.status === \"fulfilled\") cameras.push(...tfl.value);\n\n if (cameras.length > 0) {\n this.sourceBuckets[\"default\"] = cameras.map(\n (f: unknown, i: number) => mapGeoJsonFeature(f, i, \"traffic\"),\n );\n }\n } catch (err) {\n console.warn(\"[CameraPlugin] Traffic cameras API failed:\", err);\n }"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Remove the extra node API files from the plugin source tree**
|
||||
|
||||
Run: `rm -rf ../worldwideview-plugins/packages/wwv-plugin-camera/src/caltrans`
|
||||
Run: `rm -rf ../worldwideview-plugins/packages/wwv-plugin-camera/src/gdot`
|
||||
Run: `rm -rf ../worldwideview-plugins/packages/wwv-plugin-camera/src/tfl`
|
||||
|
||||
- [ ] **Step 4: Commit Camera plugin refactoring**
|
||||
|
||||
```bash
|
||||
cd ../worldwideview-plugins
|
||||
git add packages/wwv-plugin-camera/src
|
||||
git commit -m "feat: migrate traffic camera fetchers to client-side plugin bundle"
|
||||
cd ../worldwideview
|
||||
```
|
||||
@@ -0,0 +1,118 @@
|
||||
# Persistent Custom OSM Tags Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Allow users to persistently save custom OSM tags to local storage so they remain available across sessions, and track their usage via Umami analytics.
|
||||
|
||||
**Architecture:** We will use `useState` and `useEffect` in the `OSMSidebar` component to sync `customTags` to the browser's `localStorage`. When the user enters a custom tag, we'll store it, render it with a small delete button (so the list doesn't get cluttered over time), and fire an event to `window.umami.track`.
|
||||
|
||||
**Tech Stack:** React Hooks, `localStorage`, Umami Analytics
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Add Custom Tag State and Persistence
|
||||
|
||||
**Files:**
|
||||
- Modify: `c:\dev\worldwideview-plugins\packages\wwv-plugin-osm-search\src\components\OSMSidebar.tsx`
|
||||
|
||||
- [ ] **Step 1: Add customTags state and persistence effects**
|
||||
|
||||
In `OSMSidebar.tsx`, below the existing `const [activeTags, setActiveTags] = useState<string[]>([]);` line, add:
|
||||
|
||||
```tsx
|
||||
const [customTags, setCustomTags] = useState<string[]>([]);
|
||||
|
||||
React.useEffect(() => {
|
||||
try {
|
||||
const saved = localStorage.getItem("wwv_osm_custom_tags");
|
||||
if (saved) setCustomTags(JSON.parse(saved));
|
||||
} catch {}
|
||||
}, []);
|
||||
|
||||
React.useEffect(() => {
|
||||
localStorage.setItem("wwv_osm_custom_tags", JSON.stringify(customTags));
|
||||
}, [customTags]);
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Include customTags in the rendered list**
|
||||
|
||||
Replace `const customTagMatch = searchText.includes("=") ? [searchText.trim()] : [];` and `const renderedTags = ...` with:
|
||||
|
||||
```tsx
|
||||
const renderedTags = Array.from(new Set([...filteredCommon, ...dynamicTags, ...customTags]));
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Update Enter key handler to save tags and track**
|
||||
|
||||
Inside the `input`'s `onKeyDown` handler:
|
||||
|
||||
```tsx
|
||||
onKeyDown={e => {
|
||||
if (e.key === "Enter" && searchText.includes("=")) {
|
||||
const tag = searchText.trim();
|
||||
if (!activeTags.includes(tag)) {
|
||||
setActiveTags(prev => [...prev, tag]);
|
||||
}
|
||||
if (!customTags.includes(tag)) {
|
||||
setCustomTags(prev => [...prev, tag]);
|
||||
try {
|
||||
(window as any).umami?.track("osm-search-custom-tag", { tag });
|
||||
} catch {}
|
||||
}
|
||||
setSearchText("");
|
||||
}
|
||||
}}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Add a delete button to custom tags**
|
||||
|
||||
Inside the `.map(tag => {` block, update the `button` contents to include a delete span if it's a custom tag:
|
||||
|
||||
```tsx
|
||||
<button
|
||||
key={tag}
|
||||
style={{
|
||||
background: isActive ? "var(--accent-blue)" : "rgba(255,255,255,0.05)",
|
||||
color: isActive ? "#fff" : "var(--text-secondary)",
|
||||
padding: "4px 10px",
|
||||
borderRadius: "14px",
|
||||
border: `1px solid ${isActive ? "transparent" : "rgba(255,255,255,0.1)"}`,
|
||||
fontSize: "11px",
|
||||
cursor: "pointer",
|
||||
transition: "all 0.2s",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: "4px"
|
||||
}}
|
||||
onClick={() => setActiveTags(prev => prev.includes(tag) ? prev.filter(t=>t!==tag) : [...prev, tag])}
|
||||
>
|
||||
{tag.replace("=", ": ")}
|
||||
{customTags.includes(tag) && (
|
||||
<span
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setCustomTags(prev => prev.filter(t => t !== tag));
|
||||
setActiveTags(prev => prev.filter(t => t !== tag));
|
||||
}}
|
||||
style={{
|
||||
marginLeft: "2px",
|
||||
padding: "0 4px",
|
||||
borderRadius: "50%",
|
||||
background: "rgba(255,255,255,0.15)",
|
||||
display: "flex",
|
||||
justifyContent: "center",
|
||||
alignItems: "center"
|
||||
}}
|
||||
>
|
||||
×
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Commit changes**
|
||||
|
||||
```bash
|
||||
git add packages/wwv-plugin-osm-search/src/components/OSMSidebar.tsx
|
||||
git commit -m "feat(osm-search): persist custom tags and track via umami"
|
||||
```
|
||||
@@ -0,0 +1,132 @@
|
||||
# Robust Plugin Linking Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Ensure that when developers link local plugins using `wwv-cli link`, the main engine's database is automatically updated to prioritize the local code instead of accidentally loading the published version from the cloud CDN.
|
||||
|
||||
**Architecture:** We will implement a dedicated development API route in the main app (`/api/plugins/dev-link`) that allows the `wwv-cli` to safely push local plugin manifests directly into the `InstalledPlugin` database table without requiring Marketplace authentication. The CLI will be updated to make this request immediately after copying the bundle.
|
||||
|
||||
**Tech Stack:** Next.js API Routes, Prisma, Node.js `fetch`
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Create the Dev-Link API Route
|
||||
|
||||
**Files:**
|
||||
- Create: `c:\dev\worldwideview\src\app\api\plugins\dev-link\route.ts`
|
||||
|
||||
- [ ] **Step 1: Write the API Route**
|
||||
|
||||
```typescript
|
||||
import { NextResponse } from "next/server";
|
||||
import { upsertPlugin } from "@/lib/marketplace/repository";
|
||||
import { validateManifest } from "@/core/plugins/validateManifest";
|
||||
import { isPluginInstallEnabled } from "@/core/edition";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
// 1. Security Check: Only allow in development mode or local editions
|
||||
if (process.env.NODE_ENV !== "development" && !isPluginInstallEnabled) {
|
||||
return NextResponse.json({ error: "Dev-link is only available in development environments" }, { status: 403 });
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { manifest } = body;
|
||||
|
||||
if (!manifest || !manifest.id) {
|
||||
return NextResponse.json({ error: "Invalid payload. 'manifest' with an 'id' is required." }, { status: 400 });
|
||||
}
|
||||
|
||||
// 2. Validate the manifest
|
||||
const validation = validateManifest(manifest);
|
||||
if (!validation.valid) {
|
||||
console.error(`[Dev-Link] Invalid manifest for ${manifest.id}:`, validation.errors);
|
||||
return NextResponse.json({ error: "Invalid manifest", details: validation.errors }, { status: 400 });
|
||||
}
|
||||
|
||||
// 3. Upsert into database
|
||||
const config = JSON.stringify(manifest);
|
||||
const record = await upsertPlugin(manifest.id, manifest.version || "1.0.0", config);
|
||||
|
||||
console.log(`[Dev-Link] Successfully synced local plugin config for: ${manifest.id}`);
|
||||
|
||||
return NextResponse.json({ success: true, pluginId: record.pluginId });
|
||||
} catch (err) {
|
||||
console.error("[Dev-Link] Server Error:", err);
|
||||
return NextResponse.json({ error: "Internal server error" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Commit API Route**
|
||||
|
||||
```bash
|
||||
git add src/app/api/plugins/dev-link/route.ts
|
||||
git commit -m "feat(api): add dev-link route to sync local plugin manifests"
|
||||
```
|
||||
|
||||
### Task 2: Update the CLI Link Command
|
||||
|
||||
**Files:**
|
||||
- Modify: `c:\dev\worldwideview-plugins\packages\wwv-cli\src\commands\link.ts`
|
||||
|
||||
- [ ] **Step 1: Add the sync request to linkCommand**
|
||||
|
||||
Find the `linkCommand` function. Below the `fs.writeFileSync` that writes `plugin.json` (around line 67), add a network request to sync the database.
|
||||
|
||||
```typescript
|
||||
fs.writeFileSync(path.join(finalDestDir, 'plugin.json'), JSON.stringify(manifest, null, 2));
|
||||
console.log(green(`✅ Proxy manifest injected to WWV instance: ${pluginId}`));
|
||||
|
||||
// --- NEW CODE: Sync with database ---
|
||||
fetch('http://localhost:3000/api/plugins/dev-link', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ manifest })
|
||||
})
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
console.log(green(`✅ Database successfully synced to point to local files.`));
|
||||
} else {
|
||||
console.log(red(`⚠️ Warning: Database sync failed: ${data.error}`));
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
console.log(red(`⚠️ Warning: Could not reach dev server to sync DB. Is localhost:3000 running?`));
|
||||
});
|
||||
// --- END NEW CODE ---
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Rebuild the CLI**
|
||||
|
||||
```bash
|
||||
cd packages/wwv-cli
|
||||
pnpm build
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Commit CLI Update**
|
||||
|
||||
```bash
|
||||
git add packages/wwv-cli/src/commands/link.ts
|
||||
git commit -m "feat(cli): auto-sync local plugin manifests with engine database during link"
|
||||
```
|
||||
|
||||
### Task 3: Test the Integration
|
||||
|
||||
- [ ] **Step 1: Run the Sync Command**
|
||||
|
||||
Run the updated sync command in the plugins repo to verify it pushes the manifest properly to the API.
|
||||
|
||||
```bash
|
||||
cd c:\dev\worldwideview-plugins
|
||||
pnpm run sync:all
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify Output**
|
||||
|
||||
Expected output in the plugins terminal should include:
|
||||
`[wwv-plugin-osm-search] ✅ Database successfully synced to point to local files.`
|
||||
|
||||
Expected output in the main WorldWideView terminal should include:
|
||||
`[Dev-Link] Successfully synced local plugin config for: osm-search`
|
||||
@@ -0,0 +1,105 @@
|
||||
# Phase 1: Database Adapter Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Modify Prisma schema and client initialization to support both SQLite (local/demo) and PostgreSQL (cloud).
|
||||
|
||||
**Architecture:** We use a pre-generation script to swap the Prisma provider based on `NEXT_PUBLIC_WWV_EDITION`. Abstract `src/lib/db.ts` to inject the correct adapter (better-sqlite3 vs pg) based on the edition.
|
||||
|
||||
**Tech Stack:** Prisma, PostgreSQL, SQLite.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Create Schema Swap Script
|
||||
|
||||
**Files:**
|
||||
- Create: `scripts/prepare-schema.mjs`
|
||||
- Modify: `package.json`
|
||||
|
||||
- [ ] **Step 1: Create a schema swap script**
|
||||
|
||||
```javascript
|
||||
// scripts/prepare-schema.mjs
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
const schemaPath = path.join(process.cwd(), 'prisma', 'schema.prisma');
|
||||
let schema = fs.readFileSync(schemaPath, 'utf-8');
|
||||
|
||||
if (process.env.NEXT_PUBLIC_WWV_EDITION === 'cloud') {
|
||||
schema = schema.replace(/provider\s*=\s*"sqlite"/, 'provider = "postgresql"');
|
||||
console.log("Swapped Prisma provider to PostgreSQL for cloud edition.");
|
||||
} else {
|
||||
// Revert back to sqlite just in case it was swapped
|
||||
schema = schema.replace(/provider\s*=\s*"postgresql"/, 'provider = "sqlite"');
|
||||
}
|
||||
|
||||
fs.writeFileSync(schemaPath, schema);
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Update package.json scripts**
|
||||
|
||||
Modify `package.json` to run the prepare script before prisma generate:
|
||||
```json
|
||||
"pregenerate": "node scripts/prepare-schema.mjs",
|
||||
"generate": "prisma generate"
|
||||
```
|
||||
|
||||
### Task 2: Create DB Adapter Factory
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/lib/db.ts`
|
||||
- Create: `src/core/adapters/db.ts`
|
||||
|
||||
- [ ] **Step 1: Create the adapter factory**
|
||||
|
||||
```typescript
|
||||
// src/core/adapters/db.ts
|
||||
import { isCloud } from "@/core/edition";
|
||||
import { PrismaClient } from "../../generated/prisma/client";
|
||||
|
||||
export function createPrismaClient(): PrismaClient {
|
||||
if (isCloud) {
|
||||
// Cloud uses native pg driver or connection pool via standard url
|
||||
return new PrismaClient({
|
||||
datasources: {
|
||||
db: {
|
||||
url: process.env.DATABASE_URL,
|
||||
},
|
||||
},
|
||||
});
|
||||
} else {
|
||||
// Local uses better-sqlite3 adapter (already set up)
|
||||
const { PrismaBetterSqlite3 } = require("@prisma/adapter-better-sqlite3");
|
||||
const adapter = new PrismaBetterSqlite3({
|
||||
url: process.env.DATABASE_URL || "file:./data/wwv.db",
|
||||
});
|
||||
return new PrismaClient({ adapter });
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Refactor `src/lib/db.ts`**
|
||||
|
||||
```typescript
|
||||
// src/lib/db.ts
|
||||
import { PrismaClient } from "../generated/prisma/client";
|
||||
import { createPrismaClient } from "@/core/adapters/db";
|
||||
|
||||
const globalForPrisma = globalThis as unknown as {
|
||||
prisma: PrismaClient | undefined;
|
||||
};
|
||||
|
||||
export const prisma = globalForPrisma.prisma ?? createPrismaClient();
|
||||
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
globalForPrisma.prisma = prisma;
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add package.json scripts/ src/lib/ src/core/adapters/
|
||||
git commit -m "feat: multi-provider database adapter for cloud"
|
||||
```
|
||||
@@ -0,0 +1,152 @@
|
||||
# Phase 2: Tenant System Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Implement single-container multi-tenancy using PostgreSQL Row-Level Security (RLS) and Next.js middleware to resolve subdomains.
|
||||
|
||||
**Architecture:** Middleware extracts the subdomain (e.g., `acme.app.worldwideview.dev`) and sets an `x-tenant-id` header. Prisma extension wraps all queries to `SET LOCAL app.tenant_id = '...'` to enforce RLS in PostgreSQL.
|
||||
|
||||
**Tech Stack:** Next.js Middleware, Prisma Client Extensions, PostgreSQL RLS.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Database Schema Tenant Column
|
||||
|
||||
**Files:**
|
||||
- Modify: `prisma/schema.prisma`
|
||||
|
||||
- [ ] **Step 1: Add tenant columns to models**
|
||||
|
||||
Add `tenantId String?` to all relevant models (`InstalledPlugin`, `Favorite`, `Setting`).
|
||||
For local SQLite, `tenantId` is ignored (null). For cloud, it's enforced via RLS.
|
||||
|
||||
```prisma
|
||||
model InstalledPlugin {
|
||||
id String @id @default(uuid())
|
||||
tenantId String? // NULL for local, UUID for cloud
|
||||
pluginId String
|
||||
version String
|
||||
config String @default("{}")
|
||||
enabled Boolean @default(true)
|
||||
installedAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([tenantId, pluginId]) // Replaces @@unique([pluginId])
|
||||
@@map("installed_plugins")
|
||||
}
|
||||
|
||||
model Setting {
|
||||
id String @id @default(uuid())
|
||||
tenantId String?
|
||||
key String
|
||||
value String
|
||||
|
||||
@@unique([tenantId, key])
|
||||
@@map("settings")
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Update primary keys if needed**
|
||||
|
||||
Ensure `Setting` uses `id` as `@id` instead of `key` since `key` is no longer globally unique (it's unique per tenant).
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add prisma/schema.prisma
|
||||
git commit -m "feat: add tenantId columns to schema"
|
||||
```
|
||||
|
||||
### Task 2: Subdomain Middleware
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/middleware.ts` (or create if doesn't exist)
|
||||
|
||||
- [ ] **Step 1: Create Next.js middleware**
|
||||
|
||||
```typescript
|
||||
// src/middleware.ts
|
||||
import { NextResponse } from "next/server";
|
||||
import type { NextRequest } from "next/server";
|
||||
|
||||
export function middleware(req: NextRequest) {
|
||||
const hostname = req.headers.get("host") || "";
|
||||
|
||||
// Extract subdomain if on cloud
|
||||
if (process.env.NEXT_PUBLIC_WWV_EDITION === "cloud") {
|
||||
const isApp = hostname.includes(".app.worldwideview.dev");
|
||||
if (isApp) {
|
||||
const subdomain = hostname.replace(".app.worldwideview.dev", "");
|
||||
if (subdomain && subdomain !== "app") {
|
||||
const res = NextResponse.next();
|
||||
res.headers.set("x-tenant-subdomain", subdomain);
|
||||
return res;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
export const config = {
|
||||
matcher: ["/((?!api/auth|_next/static|_next/image|favicon.ico).*)"],
|
||||
};
|
||||
```
|
||||
|
||||
### Task 3: Prisma RLS Extension
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/core/adapters/db.ts`
|
||||
|
||||
- [ ] **Step 1: Wrap Prisma with RLS extension for Cloud**
|
||||
|
||||
Modify `createPrismaClient` to wrap the client if in cloud mode:
|
||||
|
||||
```typescript
|
||||
// src/core/adapters/db.ts
|
||||
import { isCloud } from "@/core/edition";
|
||||
import { PrismaClient } from "../../generated/prisma/client";
|
||||
import { headers } from "next/headers";
|
||||
|
||||
export function createPrismaClient() {
|
||||
if (isCloud) {
|
||||
const client = new PrismaClient({
|
||||
datasources: { db: { url: process.env.DATABASE_URL } },
|
||||
});
|
||||
|
||||
// Use Prisma Client Extension to inject RLS
|
||||
return client.$extends({
|
||||
query: {
|
||||
$allModels: {
|
||||
async $allOperations({ args, query }) {
|
||||
const headersList = await headers();
|
||||
const tenantSubdomain = headersList.get("x-tenant-subdomain");
|
||||
|
||||
if (tenantSubdomain) {
|
||||
const [, result] = await client.$transaction([
|
||||
client.$executeRaw`SELECT set_config('app.tenant_id', ${tenantSubdomain}, TRUE)`,
|
||||
query(args),
|
||||
]);
|
||||
return result;
|
||||
}
|
||||
return query(args);
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
} else {
|
||||
const { PrismaBetterSqlite3 } = require("@prisma/adapter-better-sqlite3");
|
||||
const adapter = new PrismaBetterSqlite3({
|
||||
url: process.env.DATABASE_URL || "file:./data/wwv.db",
|
||||
});
|
||||
return new PrismaClient({ adapter });
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Commit**
|
||||
|
||||
```bash
|
||||
git add src/middleware.ts src/core/adapters/db.ts
|
||||
git commit -m "feat: multi-tenant middleware and RLS prisma extension"
|
||||
```
|
||||
@@ -0,0 +1,117 @@
|
||||
# Phase 3: Auth Upgrade Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Integrate Supabase Auth for the cloud edition while maintaining the existing Credentials provider for the local edition.
|
||||
|
||||
**Architecture:** Use the NextAuth adapter pattern. Modify `src/lib/auth.ts` to dynamically include the Supabase provider and Supabase Adapter if `isCloud` is true.
|
||||
|
||||
**Tech Stack:** NextAuth v5, Supabase Auth.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Supabase Adapter Integration
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/lib/auth.ts`
|
||||
- Modify: `package.json`
|
||||
|
||||
- [ ] **Step 1: Install Supabase NextAuth Adapter**
|
||||
|
||||
Run: `pnpm add @auth/supabase-adapter`
|
||||
|
||||
- [ ] **Step 2: Update `src/lib/auth.ts` to branch providers**
|
||||
|
||||
```typescript
|
||||
// src/lib/auth.ts
|
||||
import NextAuth from "next-auth";
|
||||
import Credentials from "next-auth/providers/credentials";
|
||||
import { compareSync } from "bcryptjs";
|
||||
import { timingSafeEqual } from "crypto";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { isDemo, isCloud, getDemoAdminSecret, DEMO_ADMIN_ROLE } from "@/core/edition";
|
||||
import { authConfig } from "@/lib/auth.config";
|
||||
import { SupabaseAdapter } from "@auth/supabase-adapter";
|
||||
|
||||
// Extract local credentials logic to a helper
|
||||
const localCredentialsProvider = Credentials({
|
||||
credentials: {
|
||||
email: { label: "Email", type: "email" },
|
||||
password: { label: "Password", type: "password" },
|
||||
},
|
||||
async authorize(credentials) {
|
||||
// ... existing credentials logic ...
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||
...authConfig,
|
||||
session: { strategy: "jwt" },
|
||||
adapter: isCloud ? SupabaseAdapter({
|
||||
url: process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
||||
secret: process.env.SUPABASE_SERVICE_ROLE_KEY!,
|
||||
}) : undefined,
|
||||
providers: isCloud
|
||||
? [] // If using standard GoTrue via custom logic, or add providers here if using NextAuth OAuth
|
||||
: [localCredentialsProvider],
|
||||
callbacks: {
|
||||
...authConfig.callbacks,
|
||||
// ... existing callbacks ...
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### Task 2: Login Form Cloud Adaptation
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/app/login/page.tsx`
|
||||
- Modify: `src/app/login/actions.ts`
|
||||
|
||||
- [ ] **Step 1: Update Login Form for Cloud Mode**
|
||||
|
||||
```typescript
|
||||
// src/app/login/actions.ts
|
||||
import { signIn } from "@/lib/auth";
|
||||
import { isCloud } from "@/core/edition";
|
||||
import { createClient } from "@supabase/supabase-js";
|
||||
|
||||
export async function loginAction(formData: FormData) {
|
||||
const email = formData.get("email") as string;
|
||||
const password = formData.get("password") as string;
|
||||
|
||||
if (isCloud) {
|
||||
// Use Supabase GoTrue
|
||||
const supabase = createClient(
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
|
||||
);
|
||||
const { data, error } = await supabase.auth.signInWithPassword({
|
||||
email,
|
||||
password,
|
||||
});
|
||||
|
||||
if (error) return { success: false, error: error.message };
|
||||
return { success: true };
|
||||
} else {
|
||||
// Use NextAuth Credentials
|
||||
try {
|
||||
await signIn("credentials", {
|
||||
email,
|
||||
password,
|
||||
redirect: false,
|
||||
});
|
||||
return { success: true };
|
||||
} catch (error: any) {
|
||||
return { success: false, error: "Invalid credentials" };
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Commit**
|
||||
|
||||
```bash
|
||||
git add package.json pnpm-lock.yaml src/lib/auth.ts src/app/login/actions.ts
|
||||
git commit -m "feat: supabase auth adapter for cloud edition"
|
||||
```
|
||||
@@ -0,0 +1,99 @@
|
||||
# Phase 4: License Keys & Tiers Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Implement RSA-signed JWT license keys to gate Pro and Enterprise features on both Local and Cloud editions.
|
||||
|
||||
**Architecture:** A hardcoded public key verifies the JWT. The JWT payload dictates the tier (`free`, `pro`, `enterprise`) and expiration. The `uiSlice` state provides easy access to the active tier.
|
||||
|
||||
**Tech Stack:** `jose` for JWT verification.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: License Verification Module
|
||||
|
||||
**Files:**
|
||||
- Create: `src/core/license/verifyLicense.ts`
|
||||
- Create: `src/core/license/tiers.ts`
|
||||
|
||||
- [ ] **Step 1: Create Tier Definitions**
|
||||
|
||||
```typescript
|
||||
// src/core/license/tiers.ts
|
||||
export type LicenseTier = "free" | "pro" | "team" | "enterprise";
|
||||
|
||||
export interface TierFeatures {
|
||||
maxUsers: number;
|
||||
storageQuotaBytes: number;
|
||||
historyEnabled: boolean;
|
||||
snapshotCapture: boolean;
|
||||
customDomains: boolean;
|
||||
}
|
||||
|
||||
export const TIER_FEATURES: Record<LicenseTier, TierFeatures> = {
|
||||
free: { maxUsers: 3, storageQuotaBytes: 500 * 1024 * 1024, historyEnabled: false, snapshotCapture: false, customDomains: false },
|
||||
pro: { maxUsers: 20, storageQuotaBytes: 5 * 1024 * 1024 * 1024, historyEnabled: true, snapshotCapture: true, customDomains: false },
|
||||
team: { maxUsers: -1, storageQuotaBytes: -1, historyEnabled: true, snapshotCapture: true, customDomains: false },
|
||||
enterprise: { maxUsers: -1, storageQuotaBytes: -1, historyEnabled: true, snapshotCapture: true, customDomains: true },
|
||||
};
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Create JWT Verification**
|
||||
|
||||
```typescript
|
||||
// src/core/license/verifyLicense.ts
|
||||
import * as jose from "jose";
|
||||
|
||||
// Public key is safe to hardcode/ship to client
|
||||
const PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
|
||||
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu... (generate real one)
|
||||
-----END PUBLIC KEY-----`;
|
||||
|
||||
export interface LicensePayload {
|
||||
tier: "pro" | "team" | "enterprise";
|
||||
exp: number;
|
||||
org: string;
|
||||
}
|
||||
|
||||
export async function verifyLicenseKey(token: string): Promise<LicensePayload | null> {
|
||||
try {
|
||||
const publicKey = await jose.importSPKI(PUBLIC_KEY_PEM, "RS256");
|
||||
const { payload } = await jose.jwtVerify(token, publicKey);
|
||||
return payload as unknown as LicensePayload;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Task 2: State Integration
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/core/state/configSlice.ts`
|
||||
- Modify: `src/components/panels/SettingsPanel.tsx`
|
||||
|
||||
- [ ] **Step 1: Add license to configSlice**
|
||||
|
||||
```typescript
|
||||
// src/core/state/configSlice.ts
|
||||
// Add to DataConfig:
|
||||
export interface DataConfig {
|
||||
// ... existing ...
|
||||
licenseKey: string | null;
|
||||
activeTier: "free" | "pro" | "team" | "enterprise";
|
||||
}
|
||||
|
||||
// Add to initial state:
|
||||
// licenseKey: null, activeTier: "free"
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Add License input UI**
|
||||
|
||||
Add a text input in `SettingsPanel` for users to paste their license key, dispatching an action to verify and save it to the DB and Zustand store.
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add src/core/license/ src/core/state/configSlice.ts src/components/panels/
|
||||
git commit -m "feat: rsa jwt license key verification"
|
||||
```
|
||||
@@ -0,0 +1,76 @@
|
||||
# Phase 5: Cloud Deployment Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Create the Docker Compose configuration and routing layer necessary to run the multi-tenant cloud application.
|
||||
|
||||
**Architecture:** Use Traefik or nginx to route wildcard subdomains to the Next.js container. Provide environment variable overrides.
|
||||
|
||||
**Tech Stack:** Docker Compose, Traefik.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Docker Compose Setup
|
||||
|
||||
**Files:**
|
||||
- Create: `deploy/cloud/docker-compose.yml`
|
||||
- Create: `deploy/cloud/.env.example`
|
||||
|
||||
- [ ] **Step 1: Create compose file**
|
||||
|
||||
```yaml
|
||||
# deploy/cloud/docker-compose.yml
|
||||
services:
|
||||
wwv-cloud:
|
||||
image: ghcr.io/silvertakana/worldwideview:latest
|
||||
restart: always
|
||||
environment:
|
||||
NEXT_PUBLIC_WWV_EDITION: cloud
|
||||
DATABASE_URL: ${SUPABASE_PG_URL}
|
||||
NEXT_PUBLIC_SUPABASE_URL: ${SUPABASE_URL}
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY: ${SUPABASE_ANON_KEY}
|
||||
SUPABASE_SERVICE_ROLE_KEY: ${SUPABASE_SERVICE_ROLE_KEY}
|
||||
labels:
|
||||
- "traefik.enable=true"
|
||||
- "traefik.http.routers.wwv.rule=HostRegexp(`{user:[a-z0-9-]+}.app.worldwideview.dev`) || Host(`app.worldwideview.dev`)"
|
||||
- "traefik.http.routers.wwv.entrypoints=websecure"
|
||||
- "traefik.http.routers.wwv.tls.certresolver=letsencrypt"
|
||||
|
||||
traefik:
|
||||
image: traefik:v3.0
|
||||
command:
|
||||
- "--api.insecure=true"
|
||||
- "--providers.docker=true"
|
||||
- "--entrypoints.web.address=:80"
|
||||
- "--entrypoints.websecure.address=:443"
|
||||
- "--certificatesresolvers.letsencrypt.acme.tlschallenge=true"
|
||||
- "--certificatesresolvers.letsencrypt.acme.email=${ACME_EMAIL}"
|
||||
- "--certificatesresolvers.letsencrypt.acme.storage=/letsencrypt/acme.json"
|
||||
ports:
|
||||
- "80:80"
|
||||
- "443:443"
|
||||
volumes:
|
||||
- "/var/run/docker.sock:/var/run/docker.sock:ro"
|
||||
- "letsencrypt:/letsencrypt"
|
||||
|
||||
volumes:
|
||||
letsencrypt:
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Create example env file**
|
||||
|
||||
```env
|
||||
# deploy/cloud/.env.example
|
||||
SUPABASE_PG_URL=postgresql://postgres:[email protected]:5432/postgres
|
||||
SUPABASE_URL=https://xyz.supabase.co
|
||||
SUPABASE_ANON_KEY=eyJ...
|
||||
SUPABASE_SERVICE_ROLE_KEY=eyJ...
|
||||
ACME_EMAIL=[email protected]
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add deploy/
|
||||
git commit -m "chore: add cloud deployment compose configuration"
|
||||
```
|
||||
@@ -0,0 +1,77 @@
|
||||
# Phase 6: Stripe Billing Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Implement Stripe subscriptions for the cloud edition, generating license keys upon payment.
|
||||
|
||||
**Architecture:** Use Stripe Checkout Sessions for upgrades. Use Stripe Webhooks to listen for `checkout.session.completed` and `customer.subscription.updated` to update the user's tier in the database and generate their JWT license key.
|
||||
|
||||
**Tech Stack:** Stripe Node SDK, Next.js API Routes.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Stripe Integration
|
||||
|
||||
**Files:**
|
||||
- Modify: `package.json`
|
||||
- Create: `src/lib/stripe/client.ts`
|
||||
- Create: `src/app/api/billing/webhook/route.ts`
|
||||
- Create: `src/app/api/billing/checkout/route.ts`
|
||||
|
||||
- [ ] **Step 1: Install SDK**
|
||||
|
||||
Run: `pnpm add stripe`
|
||||
|
||||
- [ ] **Step 2: Create Stripe Client**
|
||||
|
||||
```typescript
|
||||
// src/lib/stripe/client.ts
|
||||
import Stripe from "stripe";
|
||||
|
||||
export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
|
||||
apiVersion: "2024-04-10",
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Create Checkout Route**
|
||||
|
||||
```typescript
|
||||
// src/app/api/billing/checkout/route.ts
|
||||
import { stripe } from "@/lib/stripe/client";
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth } from "@/lib/auth";
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const session = await auth();
|
||||
if (!session?.user) return new NextResponse("Unauthorized", { status: 401 });
|
||||
|
||||
const { priceId } = await req.json();
|
||||
|
||||
const checkoutSession = await stripe.checkout.sessions.create({
|
||||
mode: "subscription",
|
||||
payment_method_types: ["card"],
|
||||
line_items: [{ price: priceId, quantity: 1 }],
|
||||
success_url: `${process.env.NEXT_PUBLIC_APP_URL}/settings?success=true`,
|
||||
cancel_url: `${process.env.NEXT_PUBLIC_APP_URL}/settings?canceled=true`,
|
||||
client_reference_id: session.user.id,
|
||||
});
|
||||
|
||||
return NextResponse.json({ url: checkoutSession.url });
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Create Webhook Handler**
|
||||
|
||||
```typescript
|
||||
// src/app/api/billing/webhook/route.ts
|
||||
import { stripe } from "@/lib/stripe/client";
|
||||
import { NextResponse } from "next/server";
|
||||
// ... basic webhook payload verification and logging ...
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add package.json pnpm-lock.yaml src/lib/stripe/ src/app/api/billing/
|
||||
git commit -m "feat: stripe checkout and webhook integration"
|
||||
```
|
||||
@@ -0,0 +1,51 @@
|
||||
# Cloud Hosting & Plans — Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Transform WorldWideView from a local-only SQLite app into a multi-tenant cloud platform with `[user].app.worldwideview.dev` subdomains, PostgreSQL RLS isolation, Supabase Auth, cryptographic license keys, and Stripe billing.
|
||||
|
||||
**Architecture:** Single Docker container serves all tenants. nginx wildcard routes `*.app.worldwideview.dev` → Next.js. Middleware reads subdomain → sets `tenant_id` → PostgreSQL RLS scopes all queries. Same codebase, three editions (`local`/`cloud`/`demo`), adapter pattern for DB/auth/storage/tenant.
|
||||
|
||||
**Tech Stack:** Next.js 16, Prisma (multi-provider), PostgreSQL + RLS, Supabase Auth, Supabase Storage, RSA-signed JWTs (license keys), Stripe Checkout + Webhooks, nginx wildcard SSL.
|
||||
|
||||
---
|
||||
|
||||
## Current State Summary
|
||||
|
||||
| Component | Status |
|
||||
|---|---|
|
||||
| Edition system (`edition.ts`) | ✅ `local`/`cloud`/`demo` flags exist |
|
||||
| Auth (`src/lib/auth.ts`) | ✅ Credentials provider (bcrypt + SQLite) |
|
||||
| Database (`src/lib/db.ts`) | ⚠️ Hardcoded to `better-sqlite3` adapter |
|
||||
| Prisma schema | ⚠️ `provider = "sqlite"` only |
|
||||
| Tenant isolation | ❌ Not implemented |
|
||||
| Cloud auth (Supabase) | ❌ Not implemented |
|
||||
| License keys | ❌ Not implemented |
|
||||
| Storage adapter | ❌ Not implemented |
|
||||
| Stripe billing | ❌ Not implemented |
|
||||
| Cloud deployment repo | ❌ Not created |
|
||||
|
||||
---
|
||||
|
||||
## Phase Breakdown
|
||||
|
||||
Each phase is a self-contained deliverable. Phases 1–3 are foundational. Phases 4–6 add monetization.
|
||||
|
||||
| Phase | File | What It Builds | Depends On |
|
||||
|---|---|---|---|
|
||||
| 1 | [01-database-adapter.md](./01-database-adapter.md) | Prisma multi-provider (SQLite + PostgreSQL) | Nothing |
|
||||
| 2 | [02-tenant-system.md](./02-tenant-system.md) | RLS isolation, middleware, tenant context | Phase 1 |
|
||||
| 3 | [03-auth-upgrade.md](./03-auth-upgrade.md) | Supabase Auth provider for cloud edition | Phase 1 |
|
||||
| 4 | [04-license-keys.md](./04-license-keys.md) | RSA-signed JWT license keys, tier gating | Phase 1 |
|
||||
| 5 | [05-cloud-deployment.md](./05-cloud-deployment.md) | `worldwideview-cloud` repo, nginx, Docker Compose | Phases 1–3 |
|
||||
| 6 | [06-stripe-billing.md](./06-stripe-billing.md) | Stripe Checkout, webhooks, subscription management | Phases 3–4 |
|
||||
|
||||
---
|
||||
|
||||
## Key Design Decisions
|
||||
|
||||
1. **Adapter pattern** — Three thin files (`src/core/adapters/db.ts`, `auth.ts`, `storage.ts`, `tenant.ts`) branch on `edition`. Everything else is edition-unaware.
|
||||
2. **Prisma multi-provider** — Use a build-time script to swap the provider in `schema.prisma` before generating the client if building for cloud. One schema, two providers.
|
||||
3. **RLS over application-level filtering** — PostgreSQL physically refuses cross-tenant data. Even bugs can't leak.
|
||||
4. **License keys are RSA JWTs** — Marketplace signs with private key; app verifies with hardcoded public key. No phone-home required.
|
||||
5. **Stripe is the only payment processor** — Checkout Sessions for signup, Webhooks for lifecycle events.
|
||||
@@ -0,0 +1,533 @@
|
||||
# WorldWideView CLI Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Build `@worldwideview/cli`, a standalone CLI tool that scaffolds, hot-reloads, and packages WWV plugins using the Chrome Extension model, completely decoupled from the main monorepo build pipeline.
|
||||
|
||||
**Architecture:** A Node.js CLI built with `commander`. It uses `vite` programmatically to serve and build plugins. For dev mode, it attaches a `ws` WebSocket server to the Vite dev server to broadcast hot-reload events to the running WWV web app, and communicates with `/api/dev/load-unpacked` to inject the plugin. Publishing creates a `.wwvpkg` ZIP archive via `archiver`.
|
||||
|
||||
**Tech Stack:** Node.js, TypeScript, Commander, Vite, WebSocket (`ws`), Archiver, Vitest.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Initialize Package & CLI Entry Point
|
||||
|
||||
**Files:**
|
||||
- Create: `packages/wwv-cli/package.json`
|
||||
- Create: `packages/wwv-cli/tsconfig.json`
|
||||
- Create: `packages/wwv-cli/bin/wwv.js`
|
||||
- Create: `packages/wwv-cli/src/index.ts`
|
||||
- Create: `packages/wwv-cli/tests/index.test.ts`
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```typescript
|
||||
// packages/wwv-cli/tests/index.test.ts
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { execSync } from "child_process";
|
||||
import path from "path";
|
||||
|
||||
describe("wwv cli", () => {
|
||||
it("should print help information", () => {
|
||||
const binPath = path.resolve(__dirname, "../bin/wwv.js");
|
||||
const output = execSync(`node ${binPath} --help`).toString();
|
||||
expect(output).toContain("Usage: wwv [options] [command]");
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test to verify it fails**
|
||||
|
||||
Run: `cd packages/wwv-cli && pnpm test`
|
||||
Expected: FAIL (File not found or missing package.json setup)
|
||||
|
||||
- [ ] **Step 3: Write minimal implementation**
|
||||
|
||||
```json
|
||||
// packages/wwv-cli/package.json
|
||||
{
|
||||
"name": "@worldwideview/cli",
|
||||
"version": "1.0.0",
|
||||
"bin": { "wwv": "./bin/wwv.js" },
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"commander": "^11.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5.0.0",
|
||||
"vitest": "^1.0.0",
|
||||
"@types/node": "^20.0.0"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```json
|
||||
// packages/wwv-cli/tsconfig.json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "CommonJS",
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
},
|
||||
"include": ["src/**/*"]
|
||||
}
|
||||
```
|
||||
|
||||
```javascript
|
||||
// packages/wwv-cli/bin/wwv.js
|
||||
#!/usr/bin/env node
|
||||
require('../dist/index.js');
|
||||
```
|
||||
|
||||
```typescript
|
||||
// packages/wwv-cli/src/index.ts
|
||||
import { Command } from "commander";
|
||||
|
||||
const program = new Command();
|
||||
|
||||
program
|
||||
.name("wwv")
|
||||
.description("WorldWideView Plugin CLI")
|
||||
.version("1.0.0");
|
||||
|
||||
program.parse();
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run test to verify it passes**
|
||||
|
||||
Run: `cd packages/wwv-cli && pnpm install && pnpm run build && pnpm test`
|
||||
Expected: PASS
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add packages/wwv-cli
|
||||
git commit -m "feat(wwv-cli): initialize cli package and entry point"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Implement `wwv create` (Scaffolding)
|
||||
|
||||
**Files:**
|
||||
- Create: `packages/wwv-cli/src/commands/create.ts`
|
||||
- Create: `packages/wwv-cli/tests/create.test.ts`
|
||||
- Modify: `packages/wwv-cli/src/index.ts:10-15`
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```typescript
|
||||
// packages/wwv-cli/tests/create.test.ts
|
||||
import { describe, it, expect, afterEach } from "vitest";
|
||||
import { createPlugin } from "../src/commands/create";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
describe("create command", () => {
|
||||
const testDir = path.join(__dirname, "test-plugin");
|
||||
|
||||
afterEach(() => {
|
||||
if (fs.existsSync(testDir)) fs.rmSync(testDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("should scaffold a new plugin folder with manifest and index.ts", async () => {
|
||||
await createPlugin("test-plugin", __dirname);
|
||||
expect(fs.existsSync(path.join(testDir, "wwv-manifest.json"))).toBe(true);
|
||||
expect(fs.existsSync(path.join(testDir, "src", "index.ts"))).toBe(true);
|
||||
|
||||
const manifest = JSON.parse(fs.readFileSync(path.join(testDir, "wwv-manifest.json"), "utf-8"));
|
||||
expect(manifest.id).toBe("test-plugin");
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test to verify it fails**
|
||||
|
||||
Run: `cd packages/wwv-cli && pnpm test tests/create.test.ts`
|
||||
Expected: FAIL ("createPlugin is not defined")
|
||||
|
||||
- [ ] **Step 3: Write minimal implementation**
|
||||
|
||||
```typescript
|
||||
// packages/wwv-cli/src/commands/create.ts
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
export async function createPlugin(name: string, basePath: string = process.cwd()) {
|
||||
const targetDir = path.join(basePath, name);
|
||||
if (fs.existsSync(targetDir)) {
|
||||
throw new Error(`Directory ${name} already exists`);
|
||||
}
|
||||
|
||||
fs.mkdirSync(targetDir, { recursive: true });
|
||||
fs.mkdirSync(path.join(targetDir, "src"), { recursive: true });
|
||||
|
||||
const manifest = {
|
||||
manifest_version: 1,
|
||||
id: name,
|
||||
name: name,
|
||||
version: "1.0.0",
|
||||
description: "A WorldWideView plugin",
|
||||
type: "data-layer",
|
||||
category: "custom",
|
||||
icon: "Box",
|
||||
capabilities: ["data:own"],
|
||||
entry: "dist/frontend.mjs",
|
||||
dev_entry: "src/index.ts"
|
||||
};
|
||||
|
||||
fs.writeFileSync(
|
||||
path.join(targetDir, "wwv-manifest.json"),
|
||||
JSON.stringify(manifest, null, 2)
|
||||
);
|
||||
|
||||
const indexContent = `export default class MyPlugin {
|
||||
id = "${name}";
|
||||
name = "${name}";
|
||||
version = "1.0.0";
|
||||
category = "custom";
|
||||
icon = "Box";
|
||||
|
||||
async initialize(ctx) {
|
||||
console.log("Initialized", this.id);
|
||||
}
|
||||
|
||||
destroy() {}
|
||||
|
||||
async fetch(timeRange) {
|
||||
return [];
|
||||
}
|
||||
|
||||
getPollingInterval() {
|
||||
return 5000;
|
||||
}
|
||||
|
||||
getLayerConfig() {
|
||||
return { color: "#3b82f6", clusterEnabled: true, clusterDistance: 50 };
|
||||
}
|
||||
|
||||
renderEntity(entity) {
|
||||
return { type: "point", color: "#3b82f6", size: 6 };
|
||||
}
|
||||
}
|
||||
`;
|
||||
fs.writeFileSync(path.join(targetDir, "src", "index.ts"), indexContent);
|
||||
console.log(`Plugin ${name} scaffolded successfully in ./${name}`);
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// Modify packages/wwv-cli/src/index.ts (add this before program.parse())
|
||||
import { createPlugin } from "./commands/create";
|
||||
|
||||
program
|
||||
.command("create <name>")
|
||||
.description("Scaffold a new WorldWideView plugin")
|
||||
.action(async (name) => {
|
||||
try {
|
||||
await createPlugin(name);
|
||||
} catch (err: any) {
|
||||
console.error("Error:", err.message);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run test to verify it passes**
|
||||
|
||||
Run: `cd packages/wwv-cli && pnpm run build && pnpm test`
|
||||
Expected: PASS
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add packages/wwv-cli
|
||||
git commit -m "feat(wwv-cli): implement create command for scaffolding"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Implement `wwv dev` (Vite Server + WebSocket)
|
||||
|
||||
**Files:**
|
||||
- Create: `packages/wwv-cli/src/commands/dev.ts`
|
||||
- Create: `packages/wwv-cli/tests/dev.test.ts`
|
||||
- Modify: `packages/wwv-cli/src/index.ts:25-30`
|
||||
- Modify: `packages/wwv-cli/package.json:13-15` (Add vite, ws)
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```typescript
|
||||
// packages/wwv-cli/tests/dev.test.ts
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { startDevServer } from "../src/commands/dev";
|
||||
|
||||
// Mock vite and ws
|
||||
vi.mock("vite", () => ({
|
||||
createServer: vi.fn().mockResolvedValue({
|
||||
listen: vi.fn(),
|
||||
httpServer: { on: vi.fn() },
|
||||
ws: { on: vi.fn() }
|
||||
})
|
||||
}));
|
||||
|
||||
describe("dev command", () => {
|
||||
it("should export startDevServer function", () => {
|
||||
expect(typeof startDevServer).toBe("function");
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test to verify it fails**
|
||||
|
||||
Run: `cd packages/wwv-cli && pnpm test tests/dev.test.ts`
|
||||
Expected: FAIL ("startDevServer is not defined")
|
||||
|
||||
- [ ] **Step 3: Write minimal implementation**
|
||||
|
||||
Add `vite` and `ws` to dependencies in `packages/wwv-cli/package.json` and run `pnpm install`:
|
||||
```json
|
||||
"dependencies": {
|
||||
"commander": "^11.1.0",
|
||||
"vite": "^5.0.0",
|
||||
"ws": "^8.16.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/ws": "^8.5.10"
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// packages/wwv-cli/src/commands/dev.ts
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { createServer } from "vite";
|
||||
import { WebSocketServer } from "ws";
|
||||
|
||||
export async function startDevServer(targetUrl: string = "http://localhost:3000") {
|
||||
const cwd = process.cwd();
|
||||
const manifestPath = path.join(cwd, "wwv-manifest.json");
|
||||
|
||||
if (!fs.existsSync(manifestPath)) {
|
||||
throw new Error("No wwv-manifest.json found in current directory");
|
||||
}
|
||||
|
||||
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
|
||||
const port = 24601;
|
||||
|
||||
// Start Vite Dev Server
|
||||
const vite = await createServer({
|
||||
root: cwd,
|
||||
server: { port, cors: true, hmr: false }, // We handle HMR via custom WS
|
||||
plugins: [{
|
||||
name: 'wwv-hmr',
|
||||
handleHotUpdate({ server }) {
|
||||
// When Vite detects file changes, broadcast to our custom WS
|
||||
wss.clients.forEach(client => {
|
||||
client.send(JSON.stringify({ type: "plugin:updated", pluginId: manifest.id }));
|
||||
});
|
||||
return []; // Prevent default Vite HMR
|
||||
}
|
||||
}]
|
||||
});
|
||||
|
||||
await vite.listen();
|
||||
|
||||
// Attach custom WebSocket server for WWV DevModeSubscriber
|
||||
const wss = new WebSocketServer({ server: vite.httpServer as any, path: "/__wwv_dev__" });
|
||||
|
||||
wss.on("connection", (ws) => {
|
||||
console.log(`[WWV CLI] Connected to WorldWideView instance`);
|
||||
ws.send(JSON.stringify({ type: "plugin:added", manifest }));
|
||||
});
|
||||
|
||||
// Notify WorldWideView via API
|
||||
try {
|
||||
const fetch = (await import('node-fetch')).default || globalThis.fetch;
|
||||
await fetch(`${targetUrl}/api/dev/load-unpacked`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
...manifest,
|
||||
entry: `http://localhost:${port}/${manifest.dev_entry || "src/index.ts"}`
|
||||
})
|
||||
});
|
||||
console.log(`[WWV CLI] Registered with WorldWideView at ${targetUrl}`);
|
||||
} catch (err: any) {
|
||||
console.error(`[WWV CLI] Failed to connect to ${targetUrl}: ${err.message}`);
|
||||
console.log(`Waiting for WorldWideView to connect via WebSocket...`);
|
||||
}
|
||||
|
||||
console.log(`\n🚀 Dev server running on http://localhost:${port}`);
|
||||
console.log(`Watching for file changes in ${cwd}...\n`);
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// Modify packages/wwv-cli/src/index.ts (add this before program.parse())
|
||||
import { startDevServer } from "./commands/dev";
|
||||
|
||||
program
|
||||
.command("dev")
|
||||
.description("Start the plugin development server with hot-reload")
|
||||
.option("-t, --target <url>", "Target WorldWideView URL", "http://localhost:3000")
|
||||
.action(async (options) => {
|
||||
try {
|
||||
await startDevServer(options.target);
|
||||
} catch (err: any) {
|
||||
console.error("Error:", err.message);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run test to verify it passes**
|
||||
|
||||
Run: `cd packages/wwv-cli && pnpm run build && pnpm test`
|
||||
Expected: PASS
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add packages/wwv-cli
|
||||
git commit -m "feat(wwv-cli): implement dev command with vite and websockets"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Implement `wwv publish` (.wwvpkg creation)
|
||||
|
||||
**Files:**
|
||||
- Create: `packages/wwv-cli/src/commands/publish.ts`
|
||||
- Create: `packages/wwv-cli/tests/publish.test.ts`
|
||||
- Modify: `packages/wwv-cli/src/index.ts:40-45`
|
||||
- Modify: `packages/wwv-cli/package.json:16-17` (Add archiver)
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```typescript
|
||||
// packages/wwv-cli/tests/publish.test.ts
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { buildPackage } from "../src/commands/publish";
|
||||
|
||||
describe("publish command", () => {
|
||||
it("should export buildPackage function", () => {
|
||||
expect(typeof buildPackage).toBe("function");
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test to verify it fails**
|
||||
|
||||
Run: `cd packages/wwv-cli && pnpm test tests/publish.test.ts`
|
||||
Expected: FAIL ("buildPackage is not defined")
|
||||
|
||||
- [ ] **Step 3: Write minimal implementation**
|
||||
|
||||
Add `archiver` to dependencies in `packages/wwv-cli/package.json` and run `pnpm install`:
|
||||
```json
|
||||
"dependencies": {
|
||||
"archiver": "^7.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/archiver": "^6.0.2"
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// packages/wwv-cli/src/commands/publish.ts
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { build } from "vite";
|
||||
import archiver from "archiver";
|
||||
|
||||
export async function buildPackage() {
|
||||
const cwd = process.cwd();
|
||||
const manifestPath = path.join(cwd, "wwv-manifest.json");
|
||||
|
||||
if (!fs.existsSync(manifestPath)) {
|
||||
throw new Error("No wwv-manifest.json found in current directory");
|
||||
}
|
||||
|
||||
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
|
||||
|
||||
console.log(`[WWV CLI] Building production bundle...`);
|
||||
await build({
|
||||
root: cwd,
|
||||
build: {
|
||||
lib: {
|
||||
entry: path.resolve(cwd, manifest.dev_entry || "src/index.ts"),
|
||||
name: 'WWVPlugin',
|
||||
formats: ['es'],
|
||||
fileName: () => 'frontend.mjs'
|
||||
},
|
||||
outDir: 'dist',
|
||||
emptyOutDir: true
|
||||
}
|
||||
});
|
||||
|
||||
const pkgName = `${manifest.id}-${manifest.version}.wwvpkg`;
|
||||
const outputPath = path.join(cwd, pkgName);
|
||||
|
||||
console.log(`[WWV CLI] Creating archive ${pkgName}...`);
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const output = fs.createWriteStream(outputPath);
|
||||
const archive = archiver("zip", { zlib: { level: 9 } });
|
||||
|
||||
output.on("close", () => resolve());
|
||||
archive.on("error", (err) => reject(err));
|
||||
|
||||
archive.pipe(output);
|
||||
|
||||
archive.file(manifestPath, { name: "wwv-manifest.json" });
|
||||
archive.directory(path.join(cwd, "dist"), "dist");
|
||||
|
||||
if (fs.existsSync(path.join(cwd, "data"))) {
|
||||
archive.directory(path.join(cwd, "data"), "data");
|
||||
}
|
||||
|
||||
archive.finalize();
|
||||
});
|
||||
|
||||
console.log(`\n🎉 Success! Package created at ${outputPath}`);
|
||||
console.log(`You can now upload this file to the WorldWideView Marketplace.`);
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// Modify packages/wwv-cli/src/index.ts (add this before program.parse())
|
||||
import { buildPackage } from "./commands/publish";
|
||||
|
||||
program
|
||||
.command("publish")
|
||||
.description("Build and package the plugin into a .wwvpkg file")
|
||||
.action(async () => {
|
||||
try {
|
||||
await buildPackage();
|
||||
} catch (err: any) {
|
||||
console.error("Error:", err.message);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run test to verify it passes**
|
||||
|
||||
Run: `cd packages/wwv-cli && pnpm run build && pnpm test`
|
||||
Expected: PASS
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add packages/wwv-cli
|
||||
git commit -m "feat(wwv-cli): implement publish command for wwvpkg creation"
|
||||
```
|
||||
@@ -0,0 +1,323 @@
|
||||
# Split CLI Publish into Package and Publish Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Split the CLI publish command into `package` (for local .wwvpkg zip creation) and `publish` (for NPM distribution and marketplace registry updates).
|
||||
|
||||
**Architecture:**
|
||||
The current `publish` command creates a `.wwvpkg` file. We will rename this functionality to the `package` command. Then, we will create a true `publish` command that handles building the plugin, automatically generating a valid `package.json` from the `wwv-manifest.json`, running `npm publish` via a child process, and finally notifying the marketplace of the new release.
|
||||
|
||||
**Tech Stack:** TypeScript, Vite, Node.js `child_process`, Node.js `fs`.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Rename current publish to package
|
||||
|
||||
We will rename the file and its internal function from `buildPackage` to `packagePlugin`.
|
||||
|
||||
**Files:**
|
||||
- Modify: `packages/wwv-cli/src/commands/publish.ts` -> rename to `packages/wwv-cli/src/commands/package.ts`
|
||||
- Modify: `packages/wwv-cli/tests/publish.test.ts` -> rename to `packages/wwv-cli/tests/package.test.ts`
|
||||
|
||||
- [ ] **Step 1: Rename the command file and update function name**
|
||||
|
||||
```typescript
|
||||
// packages/wwv-cli/src/commands/package.ts
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { build } from "vite";
|
||||
import archiver from "archiver";
|
||||
|
||||
export async function packagePlugin() {
|
||||
const cwd = process.cwd();
|
||||
const manifestPath = path.join(cwd, "wwv-manifest.json");
|
||||
|
||||
if (!fs.existsSync(manifestPath)) {
|
||||
throw new Error("No wwv-manifest.json found in current directory");
|
||||
}
|
||||
|
||||
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
|
||||
|
||||
console.log(`[WWV CLI] Building production bundle...`);
|
||||
await build({
|
||||
root: cwd,
|
||||
build: {
|
||||
lib: {
|
||||
entry: path.resolve(cwd, manifest.dev_entry || "src/index.ts"),
|
||||
name: 'WWVPlugin',
|
||||
formats: ['es'],
|
||||
fileName: () => 'frontend.mjs'
|
||||
},
|
||||
outDir: 'dist',
|
||||
emptyOutDir: true
|
||||
}
|
||||
});
|
||||
|
||||
const pkgName = `${manifest.id}-${manifest.version}.wwvpkg`;
|
||||
const outputPath = path.join(cwd, pkgName);
|
||||
|
||||
console.log(`[WWV CLI] Creating archive ${pkgName}...`);
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const output = fs.createWriteStream(outputPath);
|
||||
const archive = archiver("zip", { zlib: { level: 9 } });
|
||||
|
||||
output.on("close", () => resolve());
|
||||
archive.on("error", (err) => reject(err));
|
||||
|
||||
archive.pipe(output);
|
||||
|
||||
archive.file(manifestPath, { name: "wwv-manifest.json" });
|
||||
archive.directory(path.join(cwd, "dist"), "dist");
|
||||
|
||||
if (fs.existsSync(path.join(cwd, "data"))) {
|
||||
archive.directory(path.join(cwd, "data"), "data");
|
||||
}
|
||||
|
||||
archive.finalize();
|
||||
});
|
||||
|
||||
console.log(`\n🎉 Success! Package created at ${outputPath}`);
|
||||
console.log(`You can use this file to sideload the plugin into your WWV instance.`);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Rename and update the test**
|
||||
|
||||
```typescript
|
||||
// packages/wwv-cli/tests/package.test.ts
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { packagePlugin } from "../src/commands/package";
|
||||
|
||||
describe("package command", () => {
|
||||
it("should export packagePlugin function", () => {
|
||||
expect(typeof packagePlugin).toBe("function");
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Remove old files**
|
||||
|
||||
Run: `git rm packages/wwv-cli/src/commands/publish.ts packages/wwv-cli/tests/publish.test.ts`
|
||||
Expected: Files deleted.
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add packages/wwv-cli/src/commands/package.ts packages/wwv-cli/tests/package.test.ts
|
||||
git commit -m "refactor(wwv-cli): rename publish to package for wwvpkg creation"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Implement true NPM Publish command
|
||||
|
||||
**Files:**
|
||||
- Create: `packages/wwv-cli/src/commands/publish.ts`
|
||||
- Create: `packages/wwv-cli/tests/publish.test.ts`
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```typescript
|
||||
// packages/wwv-cli/tests/publish.test.ts
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { publishToNpm } from "../src/commands/publish";
|
||||
|
||||
vi.mock("child_process", () => ({
|
||||
execSync: vi.fn()
|
||||
}));
|
||||
vi.mock("vite", () => ({
|
||||
build: vi.fn().mockResolvedValue({})
|
||||
}));
|
||||
|
||||
describe("publish command", () => {
|
||||
it("should export publishToNpm function", () => {
|
||||
expect(typeof publishToNpm).toBe("function");
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test to verify it fails**
|
||||
|
||||
Run: `pnpm test tests/publish.test.ts` inside `packages/wwv-cli`
|
||||
Expected: FAIL because `publishToNpm` does not exist.
|
||||
|
||||
- [ ] **Step 3: Write the publish implementation**
|
||||
|
||||
```typescript
|
||||
// packages/wwv-cli/src/commands/publish.ts
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { build } from "vite";
|
||||
import { execSync } from "child_process";
|
||||
|
||||
export async function publishToNpm() {
|
||||
const cwd = process.cwd();
|
||||
const manifestPath = path.join(cwd, "wwv-manifest.json");
|
||||
|
||||
if (!fs.existsSync(manifestPath)) {
|
||||
throw new Error("No wwv-manifest.json found in current directory");
|
||||
}
|
||||
|
||||
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
|
||||
|
||||
console.log(`[WWV CLI] Compiling bundle for NPM...`);
|
||||
await build({
|
||||
root: cwd,
|
||||
build: {
|
||||
lib: {
|
||||
entry: path.resolve(cwd, manifest.dev_entry || "src/index.ts"),
|
||||
name: 'WWVPlugin',
|
||||
formats: ['es'],
|
||||
fileName: () => 'frontend.mjs'
|
||||
},
|
||||
outDir: 'dist',
|
||||
emptyOutDir: true
|
||||
}
|
||||
});
|
||||
|
||||
console.log(`[WWV CLI] Generating package.json...`);
|
||||
// Create a temporary package.json required for NPM publish
|
||||
const packageJsonPath = path.join(cwd, "package.json");
|
||||
const packageJson = {
|
||||
name: manifest.id, // e.g. @username/my-plugin
|
||||
version: manifest.version,
|
||||
description: manifest.description,
|
||||
main: "dist/frontend.mjs",
|
||||
type: "module",
|
||||
files: ["dist", "wwv-manifest.json", "data"],
|
||||
keywords: ["worldwideview", "plugin", manifest.category],
|
||||
author: manifest.author || ""
|
||||
};
|
||||
|
||||
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
|
||||
|
||||
console.log(`[WWV CLI] Publishing to NPM...`);
|
||||
try {
|
||||
execSync(`npm publish --access public`, { stdio: "inherit", cwd });
|
||||
} catch (err) {
|
||||
console.error(`[WWV CLI] NPM publish failed. Please ensure you are logged in via 'npm login'.`);
|
||||
throw err;
|
||||
} finally {
|
||||
// Clean up the generated package.json so it doesn't clutter the dev's repo
|
||||
fs.unlinkSync(packageJsonPath);
|
||||
}
|
||||
|
||||
console.log(`[WWV CLI] Notifying WorldWideView Marketplace...`);
|
||||
try {
|
||||
const targetUrl = process.env.WWV_MARKETPLACE_URL || "https://marketplace.worldwideview.dev";
|
||||
await fetch(`${targetUrl}/api/webhooks/npm-publish`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ pluginId: manifest.id, version: manifest.version })
|
||||
});
|
||||
console.log(`[WWV CLI] Marketplace notified.`);
|
||||
} catch (err: any) {
|
||||
console.warn(`[WWV CLI] Could not notify marketplace: ${err.message}. It will be indexed on the next sweep.`);
|
||||
}
|
||||
|
||||
console.log(`\n🚀 Success! Version ${manifest.version} published globally to NPM.`);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run test to verify it passes**
|
||||
|
||||
Run: `pnpm test tests/publish.test.ts` inside `packages/wwv-cli`
|
||||
Expected: PASS
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add packages/wwv-cli/src/commands/publish.ts packages/wwv-cli/tests/publish.test.ts
|
||||
git commit -m "feat(wwv-cli): implement npm publish and marketplace webhook ping"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Update CLI Entry Point
|
||||
|
||||
**Files:**
|
||||
- Modify: `packages/wwv-cli/src/index.ts:36-50`
|
||||
|
||||
- [ ] **Step 1: Write the updated entry point logic**
|
||||
|
||||
Replace the existing `publish` command logic with both `package` and `publish`:
|
||||
|
||||
```typescript
|
||||
// Edit packages/wwv-cli/src/index.ts
|
||||
import { Command } from "commander";
|
||||
import { createPlugin } from "./commands/create";
|
||||
import { startDevServer } from "./commands/dev";
|
||||
import { packagePlugin } from "./commands/package";
|
||||
import { publishToNpm } from "./commands/publish";
|
||||
|
||||
const program = new Command();
|
||||
|
||||
program
|
||||
.name("wwv")
|
||||
.description("WorldWideView Plugin CLI")
|
||||
.version("1.0.0");
|
||||
|
||||
program
|
||||
.command("create <name>")
|
||||
.description("Scaffold a new WorldWideView plugin")
|
||||
.action(async (name) => {
|
||||
try {
|
||||
await createPlugin(name);
|
||||
} catch (err: any) {
|
||||
console.error("Error:", err.message);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
|
||||
program
|
||||
.command("dev")
|
||||
.description("Start the plugin development server with hot-reload")
|
||||
.option("-t, --target <url>", "Target WorldWideView URL", "http://localhost:3000")
|
||||
.action(async (options) => {
|
||||
try {
|
||||
await startDevServer(options.target);
|
||||
} catch (err: any) {
|
||||
console.error("Error:", err.message);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
|
||||
program
|
||||
.command("package")
|
||||
.description("Build and package the plugin into a .wwvpkg file for sideloading")
|
||||
.action(async () => {
|
||||
try {
|
||||
await packagePlugin();
|
||||
} catch (err: any) {
|
||||
console.error("Error:", err.message);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
|
||||
program
|
||||
.command("publish")
|
||||
.description("Publish the plugin to NPM and notify the WWV Marketplace")
|
||||
.action(async () => {
|
||||
try {
|
||||
await publishToNpm();
|
||||
} catch (err: any) {
|
||||
console.error("Error:", err.message);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
|
||||
program.parse();
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Build to verify no TypeScript errors**
|
||||
|
||||
Run: `pnpm run build` inside `packages/wwv-cli`
|
||||
Expected: Clean build.
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add packages/wwv-cli/src/index.ts
|
||||
git commit -m "feat(wwv-cli): register package and npm publish commands"
|
||||
```
|
||||
@@ -0,0 +1,53 @@
|
||||
# Prisma 7 Setup Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Finalize the Prisma 7 adapter architecture by removing legacy `url` parameters from the schema, syncing the local database, and validating the end-to-end connection.
|
||||
|
||||
**Architecture:** Prisma 7 strictly separates connection logic from the schema. The schema only defines the provider (`postgresql`), while connection strings for CLI commands like `db push` are handled by `prisma.config.ts`, and runtime connections are handled by the explicit `@prisma/adapter-pg` driver instance passed to the `PrismaClient` constructor.
|
||||
|
||||
**Tech Stack:** Prisma 7, PostgreSQL, Next.js, Node.js
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Update Prisma Schema
|
||||
|
||||
**Files:**
|
||||
- Modify: `prisma/schema.prisma:5-8`
|
||||
|
||||
- [ ] **Step 1: Remove the legacy `url` property from the datasource block**
|
||||
|
||||
```prisma
|
||||
datasource db {
|
||||
provider = "postgresql"
|
||||
}
|
||||
```
|
||||
|
||||
### Task 2: Push Schema to Local Database
|
||||
|
||||
- [ ] **Step 1: Execute Prisma db push to create the tables in the newly running Docker Postgres container**
|
||||
|
||||
Run: `npx dotenv-cli -e .env.local -- npx prisma db push`
|
||||
Expected: PASS with "Your database is now in sync with your schema."
|
||||
|
||||
### Task 3: Generate Prisma Client
|
||||
|
||||
- [ ] **Step 1: Regenerate the Prisma Client types to ensure they match the schema**
|
||||
|
||||
Run: `npx dotenv-cli -e .env.local -- npx prisma generate`
|
||||
Expected: PASS with "Generated Prisma Client"
|
||||
|
||||
### Task 4: Verify End-to-End Connection
|
||||
|
||||
- [ ] **Step 1: Run the user management script to prove the `adapter-pg` runtime can connect and query the new tables**
|
||||
|
||||
Run: `npx tsx --env-file=.env.local scripts/manage-users.ts list`
|
||||
Expected: PASS with no errors (it should just exit silently if there are no users, rather than throwing a `P2021 TableDoesNotExist` or `P1001` error).
|
||||
|
||||
### Task 5: Restart the Development Server
|
||||
|
||||
- [ ] **Step 1: Restart the Next.js dev server**
|
||||
Because the server has been running while we were debugging the `PrismaClientInitializationError`, Webpack may have cached the broken client. We need to kill the current `pnpm run dev` and start it fresh so we can test the API routes in the browser.
|
||||
|
||||
Run: Terminate the current `pnpm run dev` terminal, then run: `pnpm run dev`
|
||||
Expected: Next.js starts successfully without any Prisma instantiation crashes.
|
||||
@@ -0,0 +1,618 @@
|
||||
# Unify Database Adapter (PostgreSQL-Only) Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [x]`) syntax for tracking.
|
||||
|
||||
**Goal:** Replace the dual SQLite/PostgreSQL database system with a single PostgreSQL adapter, using Prisma's built-in `prisma dev` for zero-install local development.
|
||||
|
||||
**Architecture:** The app currently has two database paths — `@prisma/adapter-better-sqlite3` for local and `@prisma/adapter-pg` for cloud — which causes constant migration conflicts and config drift. We unify to `@prisma/adapter-pg` everywhere. Local developers use `npx prisma dev` (PGLite-backed local Postgres managed by Prisma CLI) or their own Postgres instance. Production connects to Supabase via the same adapter and connection string swap.
|
||||
|
||||
**Tech Stack:** Prisma 7, `@prisma/adapter-pg`, `pg`, PostgreSQL, Next.js 16
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
| Action | File | Responsibility |
|
||||
|---|---|---|
|
||||
| Modify | `prisma/schema.prisma` | Change provider to `postgresql` |
|
||||
| **Rewrite** | `src/lib/db.ts` | Single PostgreSQL adapter factory |
|
||||
| Delete | `src/core/adapters/db.ts` | Remove cloud-branch adapter factory (merge into `db.ts`) |
|
||||
| Modify | `package.json` | Remove `better-sqlite3` + adapter deps, add `pg` |
|
||||
| Modify | `next.config.ts` | Remove `better-sqlite3` from `serverExternalPackages` |
|
||||
| Modify | `docker-entrypoint.sh` | Update comments, remove SQLite references |
|
||||
| Modify | `Dockerfile` | Remove SQLite build step, update env defaults |
|
||||
| Modify | `local-dev.ps1` | Add `prisma dev` startup guidance |
|
||||
| Modify | `.env` | Change default `DATABASE_URL` to local PostgreSQL |
|
||||
| Modify | `prisma.config.ts` | No changes needed (already reads `DATABASE_URL`) |
|
||||
| Modify | `scripts/cleanup-plugins.ts` | Use shared `db.ts` instead of hardcoded SQLite |
|
||||
| Modify | `scripts/manage-users.ts` | Use shared `db.ts` instead of hardcoded SQLite |
|
||||
| Keep | `scripts/migrate-aviation-history.ts` | This is a one-off Supabase-to-SQLite migration tool. Leave as-is but mark deprecated |
|
||||
| **Delete** | `prisma/migrations/` | Remove old SQLite migrations (will regenerate for PostgreSQL) |
|
||||
| **Create** | `prisma/migrations/` | Fresh PostgreSQL init migration |
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Update Prisma Schema Provider
|
||||
|
||||
**Files:**
|
||||
- Modify: `prisma/schema.prisma:1-6`
|
||||
|
||||
- [x] **Step 1: Change the datasource provider from SQLite to PostgreSQL**
|
||||
|
||||
Open `prisma/schema.prisma` and replace the datasource block:
|
||||
|
||||
```prisma
|
||||
// Prisma schema — PostgreSQL for all environments.
|
||||
// Local dev: use `npx prisma dev` for a zero-install local PGLite instance.
|
||||
// Cloud/Production: set DATABASE_URL to your Supabase/Postgres connection string.
|
||||
|
||||
datasource db {
|
||||
provider = "postgresql"
|
||||
}
|
||||
```
|
||||
|
||||
Leave the `generator` block and all models unchanged.
|
||||
|
||||
- [x] **Step 2: Verify the schema is valid**
|
||||
|
||||
Run:
|
||||
```powershell
|
||||
npx prisma validate
|
||||
```
|
||||
|
||||
Expected: `The schema at prisma/schema.prisma is valid.`
|
||||
|
||||
- [x] **Step 3: Commit**
|
||||
|
||||
```powershell
|
||||
git add prisma/schema.prisma
|
||||
git commit -m "refactor(db): switch schema provider from sqlite to postgresql"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Remove SQLite Dependencies
|
||||
|
||||
**Files:**
|
||||
- Modify: `package.json:22-80`
|
||||
- Modify: `next.config.ts:5`
|
||||
|
||||
- [x] **Step 1: Remove better-sqlite3 packages from package.json**
|
||||
|
||||
In `package.json`, remove these lines from `dependencies`:
|
||||
```diff
|
||||
- "@prisma/adapter-better-sqlite3": "^7.5.0",
|
||||
```
|
||||
|
||||
Remove from `pnpm.onlyBuiltDependencies`:
|
||||
```diff
|
||||
- "better-sqlite3",
|
||||
```
|
||||
|
||||
Ensure `@prisma/adapter-pg` and `pg` remain (they're already present):
|
||||
```json
|
||||
"@prisma/adapter-pg": "^7.8.0",
|
||||
"pg": "^8.20.0",
|
||||
```
|
||||
|
||||
- [x] **Step 2: Update serverExternalPackages in next.config.ts**
|
||||
|
||||
In `next.config.ts` line 5, replace:
|
||||
```typescript
|
||||
serverExternalPackages: ["better-sqlite3", "@prisma/adapter-better-sqlite3", "@prisma/client", "prisma"],
|
||||
```
|
||||
|
||||
With:
|
||||
```typescript
|
||||
serverExternalPackages: ["@prisma/client", "prisma", "pg"],
|
||||
```
|
||||
|
||||
- [x] **Step 3: Install to update lockfile**
|
||||
|
||||
Run:
|
||||
```powershell
|
||||
pnpm install
|
||||
```
|
||||
|
||||
Expected: Clean install with no `better-sqlite3` compilation step.
|
||||
|
||||
- [x] **Step 4: Commit**
|
||||
|
||||
```powershell
|
||||
git add package.json next.config.ts pnpm-lock.yaml
|
||||
git commit -m "refactor(db): remove better-sqlite3 dependencies"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Rewrite the Database Adapter Factory
|
||||
|
||||
**Files:**
|
||||
- Rewrite: `src/lib/db.ts`
|
||||
|
||||
- [x] **Step 1: Replace db.ts with a unified PostgreSQL adapter**
|
||||
|
||||
Replace the entire contents of `src/lib/db.ts` with:
|
||||
|
||||
```typescript
|
||||
import { PrismaClient } from "../generated/prisma";
|
||||
import { PrismaPg } from "@prisma/adapter-pg";
|
||||
import { Pool } from "pg";
|
||||
|
||||
/**
|
||||
* Prisma client singleton — PostgreSQL only.
|
||||
*
|
||||
* Local dev: Run `npx prisma dev` for a zero-install local Postgres.
|
||||
* Production: Set DATABASE_URL to your Supabase/Postgres connection string.
|
||||
*
|
||||
* Uses globalThis to survive Next.js HMR in development.
|
||||
*/
|
||||
|
||||
const globalForPrisma = globalThis as unknown as {
|
||||
prisma: PrismaClient | undefined;
|
||||
};
|
||||
|
||||
function createPrismaClient(): PrismaClient {
|
||||
const connectionString = process.env.DATABASE_URL;
|
||||
|
||||
if (!connectionString) {
|
||||
throw new Error(
|
||||
"[db] DATABASE_URL is not set. " +
|
||||
"Run `npx prisma dev` for local development, " +
|
||||
"or set DATABASE_URL to your PostgreSQL connection string."
|
||||
);
|
||||
}
|
||||
|
||||
const pool = new Pool({ connectionString });
|
||||
const adapter = new PrismaPg(pool);
|
||||
|
||||
return new PrismaClient({ adapter } as any);
|
||||
}
|
||||
|
||||
export const prisma = globalForPrisma.prisma ?? createPrismaClient();
|
||||
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
globalForPrisma.prisma = prisma;
|
||||
}
|
||||
```
|
||||
|
||||
> **Note:** The `feature/cloud-hosting-core` branch has a more complex version at `src/core/adapters/db.ts` with tenant isolation via `applyTenantIsolation()`. When merging that branch later, the tenant isolation extension should be layered on top of this unified base — it does NOT need a separate SQLite path.
|
||||
|
||||
- [x] **Step 2: Verify TypeScript compilation**
|
||||
|
||||
Run:
|
||||
```powershell
|
||||
npx tsc --noEmit --pretty 2>&1 | Select-String "db.ts"
|
||||
```
|
||||
|
||||
Expected: No errors related to `db.ts`.
|
||||
|
||||
- [x] **Step 3: Commit**
|
||||
|
||||
```powershell
|
||||
git add src/lib/db.ts
|
||||
git commit -m "refactor(db): unify adapter to postgresql-only via PrismaPg"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Update Utility Scripts
|
||||
|
||||
**Files:**
|
||||
- Modify: `scripts/cleanup-plugins.ts`
|
||||
- Modify: `scripts/manage-users.ts`
|
||||
|
||||
- [x] **Step 1: Rewrite cleanup-plugins.ts to use shared db**
|
||||
|
||||
Replace the entire contents of `scripts/cleanup-plugins.ts`:
|
||||
|
||||
```typescript
|
||||
import { PrismaClient } from "../src/generated/prisma/index.js";
|
||||
import { PrismaPg } from "@prisma/adapter-pg";
|
||||
import { Pool } from "pg";
|
||||
|
||||
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
|
||||
const adapter = new PrismaPg(pool);
|
||||
const prisma = new PrismaClient({ adapter } as any);
|
||||
|
||||
async function main() {
|
||||
const plugins = await prisma.installedPlugin.findMany();
|
||||
console.log("Installed plugins:");
|
||||
plugins.forEach((p) => console.log(` ${p.pluginId} | config: ${p.config.substring(0, 60)}`));
|
||||
|
||||
const geojson = plugins.find((p) => p.pluginId === "geojson");
|
||||
if (geojson) {
|
||||
await prisma.installedPlugin.delete({ where: { id: geojson.id } });
|
||||
console.log("\nDeleted orphaned 'geojson' record.");
|
||||
} else {
|
||||
console.log("\nNo orphaned 'geojson' record found.");
|
||||
}
|
||||
|
||||
const remaining = await prisma.installedPlugin.findMany();
|
||||
console.log("\nRemaining plugins:");
|
||||
remaining.forEach((p) => console.log(` ${p.pluginId}`));
|
||||
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
```
|
||||
|
||||
- [x] **Step 2: Rewrite manage-users.ts to use shared db**
|
||||
|
||||
Replace the entire contents of `scripts/manage-users.ts`:
|
||||
|
||||
```typescript
|
||||
import { PrismaClient } from "../src/generated/prisma/index.js";
|
||||
import { PrismaPg } from "@prisma/adapter-pg";
|
||||
import { Pool } from "pg";
|
||||
import { hashSync } from "bcryptjs";
|
||||
|
||||
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
|
||||
const adapter = new PrismaPg(pool);
|
||||
const prisma = new PrismaClient({ adapter } as any);
|
||||
|
||||
async function main() {
|
||||
const action = process.argv[2];
|
||||
|
||||
if (action === "list") {
|
||||
const users = await prisma.user.findMany();
|
||||
if (users.length === 0) {
|
||||
console.log("No users found — visit /setup to create one.");
|
||||
} else {
|
||||
users.forEach((u) =>
|
||||
console.log(` ${u.email} | ${u.name} | ${u.role} | ${u.createdAt}`)
|
||||
);
|
||||
}
|
||||
} else if (action === "reset") {
|
||||
const email = process.argv[3];
|
||||
const newPass = process.argv[4];
|
||||
if (!email || !newPass) {
|
||||
console.log("Usage: tsx scripts/manage-users.ts reset <email> <password>");
|
||||
return;
|
||||
}
|
||||
const hashed = hashSync(newPass, 12);
|
||||
await prisma.user.update({
|
||||
where: { email },
|
||||
data: { hashedPassword: hashed },
|
||||
});
|
||||
console.log(`Password reset for ${email}`);
|
||||
} else if (action === "delete-all") {
|
||||
await prisma.user.deleteMany();
|
||||
console.log("All users deleted — visit /setup to create a new admin.");
|
||||
} else {
|
||||
console.log("Usage: tsx scripts/manage-users.ts <list|reset|delete-all>");
|
||||
}
|
||||
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
```
|
||||
|
||||
- [x] **Step 3: Add deprecation notice to migrate-aviation-history.ts**
|
||||
|
||||
Add this comment at the top of `scripts/migrate-aviation-history.ts`:
|
||||
|
||||
```typescript
|
||||
/**
|
||||
* @deprecated This script uses better-sqlite3 directly to migrate data
|
||||
* from Supabase into the legacy data engine's SQLite database.
|
||||
* It is NOT part of the main application's database layer.
|
||||
* It will be removed once the data engine migration is complete.
|
||||
*/
|
||||
```
|
||||
|
||||
- [x] **Step 4: Commit**
|
||||
|
||||
```powershell
|
||||
git add scripts/cleanup-plugins.ts scripts/manage-users.ts scripts/migrate-aviation-history.ts
|
||||
git commit -m "refactor(scripts): update utility scripts to use postgresql adapter"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 5: Create Fresh PostgreSQL Migration
|
||||
|
||||
**Files:**
|
||||
- Delete: `prisma/migrations/` (entire directory)
|
||||
- Create: `prisma/migrations/YYYYMMDD_init/migration.sql` (generated by Prisma)
|
||||
|
||||
- [x] **Step 1: Delete old SQLite migrations**
|
||||
|
||||
```powershell
|
||||
Remove-Item -Recurse -Force prisma/migrations
|
||||
```
|
||||
|
||||
- [x] **Step 2: Ensure a local PostgreSQL is available**
|
||||
|
||||
Either:
|
||||
- Run `npx prisma dev` in a separate terminal, OR
|
||||
- Use your existing local PostgreSQL at `127.0.0.1:5432`
|
||||
|
||||
Verify the connection string in `.env.local` points to a reachable PostgreSQL instance:
|
||||
```
|
||||
DATABASE_URL="postgresql://postgres:[email protected]:5432/postgres?schema=public"
|
||||
```
|
||||
|
||||
- [x] **Step 3: Reset and create initial migration**
|
||||
|
||||
```powershell
|
||||
npx prisma migrate reset --force
|
||||
npx prisma migrate dev --name init
|
||||
```
|
||||
|
||||
Expected output:
|
||||
```
|
||||
Applying migration `YYYYMMDDHHMMSS_init`
|
||||
The following migration(s) have been created and applied...
|
||||
```
|
||||
|
||||
- [x] **Step 4: Verify migration_lock.toml says postgresql**
|
||||
|
||||
```powershell
|
||||
Get-Content prisma/migrations/migration_lock.toml
|
||||
```
|
||||
|
||||
Expected:
|
||||
```
|
||||
provider = "postgresql"
|
||||
```
|
||||
|
||||
- [x] **Step 5: Commit**
|
||||
|
||||
```powershell
|
||||
git add prisma/migrations
|
||||
git commit -m "feat(db): create initial postgresql migration"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 6: Update Dockerfile and Entrypoint
|
||||
|
||||
**Files:**
|
||||
- Modify: `Dockerfile:11,36-38,49,54`
|
||||
- Modify: `docker-entrypoint.sh:3-5`
|
||||
|
||||
- [x] **Step 1: Update Dockerfile**
|
||||
|
||||
Make these changes to `Dockerfile`:
|
||||
|
||||
**Line 11** — Remove `python3 make g++` (no longer need to compile better-sqlite3 native bindings):
|
||||
```dockerfile
|
||||
RUN apk add --no-cache python3 make g++
|
||||
```
|
||||
Replace with:
|
||||
```dockerfile
|
||||
# python3/make/g++ no longer needed — removed better-sqlite3 native compilation
|
||||
```
|
||||
|
||||
**Lines 36-38** — Remove the conditional SQLite build step entirely:
|
||||
```dockerfile
|
||||
# Create an empty SQLite database with all tables applied ONLY IF NOT CLOUD
|
||||
# (For cloud, we'll run migrations against Postgres at runtime)
|
||||
RUN if [ "$NEXT_PUBLIC_WWV_EDITION" != "cloud" ]; then mkdir -p ./data && DATABASE_URL=file:./data/wwv.db npx prisma migrate deploy; fi
|
||||
```
|
||||
Replace with:
|
||||
```dockerfile
|
||||
# Database migrations run at container startup via docker-entrypoint.sh
|
||||
# DATABASE_URL must be set to a PostgreSQL connection string
|
||||
```
|
||||
|
||||
**Line 49** — Keep `prisma` global install (needed for `migrate deploy` at runtime).
|
||||
|
||||
**Line 54** — Remove the SQLite default DATABASE_URL:
|
||||
```dockerfile
|
||||
ENV DATABASE_URL=file:./data/wwv.db
|
||||
```
|
||||
Replace with:
|
||||
```dockerfile
|
||||
# DATABASE_URL must be provided via environment variable (no default)
|
||||
# Example: postgresql://user:pass@host:5432/dbname
|
||||
```
|
||||
|
||||
- [x] **Step 2: Update docker-entrypoint.sh comments**
|
||||
|
||||
Replace lines 2-5 of `docker-entrypoint.sh`:
|
||||
```bash
|
||||
# ─── Docker Entrypoint ───────────────────────────────────────
|
||||
# Ensures the SQLite database exists and is migrated before
|
||||
# starting the application. On first run with a fresh volume
|
||||
# the DB file won't exist yet, so we run prisma migrate deploy.
|
||||
```
|
||||
|
||||
With:
|
||||
```bash
|
||||
# ─── Docker Entrypoint ───────────────────────────────────────
|
||||
# Ensures the PostgreSQL database is migrated before starting
|
||||
# the application. DATABASE_URL must point to a PostgreSQL
|
||||
# instance (Supabase, self-hosted, etc).
|
||||
```
|
||||
|
||||
Remove `mkdir -p ./data` from line 9 (no longer creating a local SQLite file):
|
||||
```bash
|
||||
set -e
|
||||
|
||||
echo "[entrypoint] Running database migrations..."
|
||||
prisma migrate deploy
|
||||
echo "[entrypoint] Migrations complete."
|
||||
```
|
||||
|
||||
- [x] **Step 3: Commit**
|
||||
|
||||
```powershell
|
||||
git add Dockerfile docker-entrypoint.sh
|
||||
git commit -m "refactor(docker): remove sqlite from build and runtime"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 7: Update Environment Defaults and Dev Scripts
|
||||
|
||||
**Files:**
|
||||
- Modify: `.env:1`
|
||||
- Modify: `package.json:13` (predev script)
|
||||
- Modify: `local-dev.ps1`
|
||||
|
||||
- [x] **Step 1: Update .env default DATABASE_URL**
|
||||
|
||||
Replace line 1 of `.env`:
|
||||
```
|
||||
DATABASE_URL=file:./data/wwv.db
|
||||
```
|
||||
|
||||
With:
|
||||
```
|
||||
# PostgreSQL connection string.
|
||||
# For local dev: run `npx prisma dev` and use the URL it prints.
|
||||
# For production: set to your Supabase/Postgres connection string.
|
||||
# DATABASE_URL=postgresql://postgres:[email protected]:5432/worldwideview
|
||||
```
|
||||
|
||||
> **Important:** The default is now commented out. The `.env.local` file (or `npx prisma dev`) must provide the actual value. This forces contributors to explicitly set up their database rather than silently falling back to a potentially broken SQLite path.
|
||||
|
||||
- [x] **Step 2: Simplify the predev script**
|
||||
|
||||
In `package.json`, the `predev` script currently runs `npx prisma migrate deploy`. This will fail if no Postgres is running. Change it to only copy Cesium assets and generate the Prisma client:
|
||||
|
||||
```json
|
||||
"predev": "npx prisma generate && node scripts/copy-cesium.mjs",
|
||||
```
|
||||
|
||||
> **Rationale:** `prisma migrate deploy` should only run in production (Docker entrypoint) or explicitly by the developer. During local dev, `npx prisma dev` handles migrations automatically.
|
||||
|
||||
- [x] **Step 3: Update local-dev.ps1**
|
||||
|
||||
Replace the entire contents of `local-dev.ps1`:
|
||||
|
||||
```powershell
|
||||
Write-Host "[*] Setting up WorldWideView for Local Development..."
|
||||
|
||||
# Check for pnpm
|
||||
try {
|
||||
$null = Get-Command pnpm -ErrorAction Stop
|
||||
} catch {
|
||||
Write-Host "[Error] pnpm is not installed or not in PATH."
|
||||
Write-Host "Please install it first: https://pnpm.io/installation"
|
||||
exit 1
|
||||
}
|
||||
|
||||
Write-Host "[*] Installing dependencies..."
|
||||
pnpm install
|
||||
|
||||
Write-Host "[*] Running initial setup (generating secrets)..."
|
||||
pnpm run setup
|
||||
|
||||
Write-Host "[*] Generating Prisma client..."
|
||||
npx prisma generate
|
||||
|
||||
# Check for the sibling Data Engine repository
|
||||
if (-not (Test-Path "../wwv-data-engine")) {
|
||||
Write-Host ""
|
||||
Write-Host "=====================================================================" -ForegroundColor Yellow
|
||||
Write-Host "[!] NOTICE: Local Data Engine not found at ../wwv-data-engine" -ForegroundColor Yellow
|
||||
Write-Host ""
|
||||
Write-Host "Frontend-Only Mode: You are developing the frontend UI." -ForegroundColor Green
|
||||
Write-Host "WorldWideView will automatically stream data from the Cloud Engine." -ForegroundColor Green
|
||||
Write-Host ""
|
||||
Write-Host "Full-Stack Mode: If you want to develop backend data seeders, you" -ForegroundColor Cyan
|
||||
Write-Host "must clone the open-source data engine as a sibling directory:" -ForegroundColor Cyan
|
||||
Write-Host " cd ..; git clone https://github.com/silvertakana/wwv-data-engine"
|
||||
Write-Host " cd wwv-data-engine; pnpm install"
|
||||
Write-Host "=====================================================================" -ForegroundColor Yellow
|
||||
Write-Host ""
|
||||
}
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "=====================================================================" -ForegroundColor Cyan
|
||||
Write-Host "[!] DATABASE SETUP REQUIRED" -ForegroundColor Cyan
|
||||
Write-Host ""
|
||||
Write-Host "WorldWideView uses PostgreSQL. Choose one option:" -ForegroundColor White
|
||||
Write-Host ""
|
||||
Write-Host " Option A (Easiest): Run Prisma's built-in local database:" -ForegroundColor Green
|
||||
Write-Host " npx prisma dev" -ForegroundColor Yellow
|
||||
Write-Host " (Copy the DATABASE_URL it prints into your .env.local file)" -ForegroundColor Gray
|
||||
Write-Host ""
|
||||
Write-Host " Option B: Use your own PostgreSQL or Supabase instance:" -ForegroundColor Green
|
||||
Write-Host " Set DATABASE_URL in .env.local to your connection string" -ForegroundColor Gray
|
||||
Write-Host "=====================================================================" -ForegroundColor Cyan
|
||||
Write-Host ""
|
||||
|
||||
Write-Host "[*] Starting local Next.js frontend server..."
|
||||
Write-Host " (To run the data engine backends concurrently, run: pnpm dev:all)"
|
||||
pnpm run dev
|
||||
```
|
||||
|
||||
- [x] **Step 4: Commit**
|
||||
|
||||
```powershell
|
||||
git add .env package.json local-dev.ps1
|
||||
git commit -m "refactor(dev): update env defaults and dev scripts for postgresql"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 8: Run Tests and Validate
|
||||
|
||||
**Files:**
|
||||
- No file changes — validation only
|
||||
|
||||
- [x] **Step 1: Generate Prisma client**
|
||||
|
||||
```powershell
|
||||
npx prisma generate
|
||||
```
|
||||
|
||||
Expected: `Generated Prisma Client to ./src/generated/prisma`
|
||||
|
||||
- [x] **Step 2: Run the test suite**
|
||||
|
||||
```powershell
|
||||
pnpm test
|
||||
```
|
||||
|
||||
Expected: All tests pass. The repository tests mock `db.ts`, so the adapter change should be transparent to them.
|
||||
|
||||
- [x] **Step 3: Start the dev server**
|
||||
|
||||
Ensure your `.env.local` has a valid `DATABASE_URL` pointing to PostgreSQL, then:
|
||||
|
||||
```powershell
|
||||
pnpm run dev
|
||||
```
|
||||
|
||||
Expected: Server starts at `http://localhost:3000` without `P3005` or `P3018` errors.
|
||||
|
||||
- [x] **Step 4: Verify database operations work**
|
||||
|
||||
1. Navigate to `http://localhost:3000/setup` — create a test user
|
||||
2. Log in
|
||||
3. Open the Plugins panel — verify installed plugins load
|
||||
4. Star a favorite entity — verify it persists across reload
|
||||
|
||||
- [x] **Step 5: Final commit**
|
||||
|
||||
```powershell
|
||||
git add -A
|
||||
git commit -m "test(db): verify postgresql-only adapter works end-to-end"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Post-Implementation Notes
|
||||
|
||||
### For the `feature/cloud-hosting-core` merge
|
||||
|
||||
When merging the cloud-hosting-core branch back into main, the `src/core/adapters/db.ts` file with `applyTenantIsolation()` should be integrated into `src/lib/db.ts` as a wrapper around the single `PrismaPg` adapter. The conditional SQLite path in that file can be completely removed.
|
||||
|
||||
### For self-hosted Docker users
|
||||
|
||||
Add a note to the release changelog:
|
||||
|
||||
> **Breaking Change:** WorldWideView now requires a PostgreSQL database. SQLite is no longer supported.
|
||||
> Self-hosted users must provide a `DATABASE_URL` environment variable pointing to a PostgreSQL instance.
|
||||
> The easiest option is a free Supabase project, or run `docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=pass postgres:17-alpine` alongside your WWV container.
|
||||
|
||||
### For the migrate-aviation-history.ts script
|
||||
|
||||
This script uses `better-sqlite3` directly to talk to the data engine's separate SQLite database (not the platform database). It is unrelated to this migration and can remain as-is. If `better-sqlite3` is needed for this script, install it as a `devDependency` only, or move the script to the data engine repo where it belongs.
|
||||
@@ -0,0 +1,42 @@
|
||||
<!-- Generated: 2026-04-23 06:11:00 UTC -->
|
||||
# Testing
|
||||
|
||||
## Overview
|
||||
WorldWideView utilizes Vitest alongside a `jsdom` environment and the React Testing Library to ensure high reliability across core application logic, server APIs, and plugin loaders. Test coverage is strategically focused on shared libraries, core state logic, and the plugin ecosystem mechanisms.
|
||||
|
||||
## Test Types
|
||||
|
||||
### Unit Tests
|
||||
Focused on validating standalone functions and state slice reducers without mounting React components.
|
||||
- **Example:** Validating the runtime edition feature flags.
|
||||
- *File:* `src/core/edition.test.ts`
|
||||
- **Example:** Validating marketplace token exchanges and rate limiting logic.
|
||||
- *Files:* `src/lib/marketplaceToken.test.ts`, `src/lib/rateLimit.test.ts`
|
||||
|
||||
### Integration Tests
|
||||
Focused on ensuring module interaction, such as the event bus properly interacting with state, or plugin loaders successfully resolving manifests.
|
||||
- **Example:** Testing local database repositories.
|
||||
- *File:* `src/lib/repository.test.ts`
|
||||
- **Example:** Validating cross-origin resource sharing (CORS) handlers for data engine streaming.
|
||||
- *File:* `src/lib/cors.test.ts`
|
||||
- **Example:** Verifying demo-admin bypass secrets.
|
||||
- *File:* `src/lib/demoAdmin.test.ts`
|
||||
|
||||
## Running Tests
|
||||
|
||||
Execute the following commands from the root `worldwideview` directory:
|
||||
|
||||
- **Run all tests once:**
|
||||
```bash
|
||||
pnpm test
|
||||
```
|
||||
*(Alias for `vitest run`)*
|
||||
|
||||
- **Run tests in watch mode (for active development):**
|
||||
```bash
|
||||
npx vitest
|
||||
```
|
||||
|
||||
## Reference
|
||||
- **Coverage Scope:** The Vitest configuration primarily targets tests located inside `src/lib/**`, `src/core/**`, and `src/plugins/**`.
|
||||
- **Environment:** The test environment is configured as `jsdom` via `vite.config.ts` or `vitest.config.ts`, ensuring that DOM-specific API calls function outside of a real browser.
|
||||
@@ -0,0 +1,6 @@
|
||||
const { PrismaClient } = require('./src/generated/prisma');
|
||||
const prisma = new PrismaClient();
|
||||
prisma.installedPlugin.findMany().then(r => console.log(JSON.stringify(r.map(record => {
|
||||
const manifest = JSON.parse(record.config);
|
||||
return { id: manifest.id, entry: manifest.entry, format: manifest.format };
|
||||
}), null, 2))).catch(console.error).finally(() => prisma.$disconnect());
|
||||
@@ -0,0 +1,9 @@
|
||||
import sqlite3
|
||||
import json
|
||||
conn = sqlite3.connect('data/wwv.db')
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('SELECT id, dataSource FROM installed_plugins')
|
||||
rows = cursor.fetchall()
|
||||
for r in rows:
|
||||
if r[1]:
|
||||
print(f"plugin={r[0]}, dataSource={r[1]}")
|
||||
@@ -0,0 +1,55 @@
|
||||
Write-Host "[*] Setting up WorldWideView for Local Development..."
|
||||
|
||||
# Check for pnpm
|
||||
try {
|
||||
$null = Get-Command pnpm -ErrorAction Stop
|
||||
} catch {
|
||||
Write-Host "[Error] pnpm is not installed or not in PATH."
|
||||
Write-Host "Please install it first: https://pnpm.io/installation"
|
||||
exit 1
|
||||
}
|
||||
|
||||
Write-Host "[*] Installing dependencies..."
|
||||
pnpm install
|
||||
|
||||
Write-Host "[*] Running initial setup (generating secrets)..."
|
||||
pnpm run setup
|
||||
|
||||
Write-Host "[*] Generating Prisma client..."
|
||||
npx prisma generate
|
||||
|
||||
# Check for the sibling Data Engine repository
|
||||
if (-not (Test-Path "../wwv-data-engine")) {
|
||||
Write-Host ""
|
||||
Write-Host "=====================================================================" -ForegroundColor Yellow
|
||||
Write-Host "[!] NOTICE: Local Data Engine not found at ../wwv-data-engine" -ForegroundColor Yellow
|
||||
Write-Host ""
|
||||
Write-Host "Frontend-Only Mode: You are developing the frontend UI." -ForegroundColor Green
|
||||
Write-Host "WorldWideView will automatically stream data from the Cloud Engine." -ForegroundColor Green
|
||||
Write-Host ""
|
||||
Write-Host "Full-Stack Mode: If you want to develop backend data seeders, you" -ForegroundColor Cyan
|
||||
Write-Host "must clone the open-source data engine as a sibling directory:" -ForegroundColor Cyan
|
||||
Write-Host " cd ..; git clone https://github.com/silvertakana/wwv-data-engine"
|
||||
Write-Host " cd wwv-data-engine; pnpm install"
|
||||
Write-Host "=====================================================================" -ForegroundColor Yellow
|
||||
Write-Host ""
|
||||
}
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "=====================================================================" -ForegroundColor Cyan
|
||||
Write-Host "[!] DATABASE SETUP REQUIRED" -ForegroundColor Cyan
|
||||
Write-Host ""
|
||||
Write-Host "WorldWideView uses PostgreSQL. Choose one option:" -ForegroundColor White
|
||||
Write-Host ""
|
||||
Write-Host " Option A (Easiest): Run Prisma's built-in local database:" -ForegroundColor Green
|
||||
Write-Host " npx prisma dev" -ForegroundColor Yellow
|
||||
Write-Host " (Copy the DATABASE_URL it prints into your .env.local file)" -ForegroundColor Gray
|
||||
Write-Host ""
|
||||
Write-Host " Option B: Use your own PostgreSQL or Supabase instance:" -ForegroundColor Green
|
||||
Write-Host " Set DATABASE_URL in .env.local to your connection string" -ForegroundColor Gray
|
||||
Write-Host "=====================================================================" -ForegroundColor Cyan
|
||||
Write-Host ""
|
||||
|
||||
Write-Host "[*] Starting local Next.js frontend server..."
|
||||
Write-Host " (To run the data engine backends concurrently, run: pnpm dev:all)"
|
||||
pnpm run dev
|
||||
@@ -0,0 +1,38 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
echo "🌍 Setting up WorldWideView for Local Development..."
|
||||
|
||||
# Check for pnpm
|
||||
if ! command -v pnpm &> /dev/null; then
|
||||
echo "❌ Error: pnpm is required but not installed."
|
||||
echo "Please install it first: https://pnpm.io/installation"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "📦 Installing dependencies..."
|
||||
pnpm install
|
||||
|
||||
echo "🔐 Running initial setup (generating secrets)..."
|
||||
pnpm run setup
|
||||
|
||||
# Check for the sibling Data Engine repository
|
||||
if [ ! -d "../wwv-data-engine" ]; then
|
||||
echo ""
|
||||
echo "====================================================================="
|
||||
echo "⚠️ NOTICE: Local Data Engine not found at ../wwv-data-engine"
|
||||
echo ""
|
||||
echo "Frontend-Only Mode: You are developing the frontend UI."
|
||||
echo "WorldWideView will automatically stream data from the Cloud Engine."
|
||||
echo ""
|
||||
echo "Full-Stack Mode: If you want to develop backend data seeders, you"
|
||||
echo "must clone the open-source data engine as a sibling directory:"
|
||||
echo " cd .. && git clone https://github.com/silvertakana/wwv-data-engine"
|
||||
echo " cd wwv-data-engine && pnpm install"
|
||||
echo "====================================================================="
|
||||
echo ""
|
||||
fi
|
||||
|
||||
echo "🚀 Starting local Next.js frontend server..."
|
||||
echo " (To run the data engine backends concurrently, run: pnpm dev:all)"
|
||||
pnpm run dev
|
||||
Whitespace-only changes.
+336749
File diff suppressed because it is too large.
Load diff
+80
-37
@@ -1,46 +1,69 @@
|
||||
import type { NextConfig } from "next";
|
||||
import path from "path";
|
||||
import webpack from "webpack";
|
||||
import CopyPlugin from "copy-webpack-plugin";
|
||||
|
||||
const cesiumSource = path.resolve(__dirname, "node_modules/cesium/Build/Cesium");
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
output: "standalone",
|
||||
serverExternalPackages: ["@prisma/client", "prisma"],
|
||||
transpilePackages: ["@worldwideview/wwv-plugin-sdk", "resium", "react-player", "satellite.js"],
|
||||
allowedDevOrigins: process.env.ALLOWED_DEV_ORIGIN ? [process.env.ALLOWED_DEV_ORIGIN] : undefined,
|
||||
experimental: {
|
||||
memoryBasedWorkersCount: true,
|
||||
cpus: 2,
|
||||
optimizePackageImports: ["lucide-react"],
|
||||
},
|
||||
outputFileTracingIncludes: {
|
||||
"/*": ["./scripts/**/*"],
|
||||
},
|
||||
typescript: {
|
||||
ignoreBuildErrors: true,
|
||||
},
|
||||
async headers() {
|
||||
return [
|
||||
{
|
||||
source: "/(.*)",
|
||||
headers: [
|
||||
{
|
||||
key: "Content-Security-Policy",
|
||||
value: [
|
||||
"default-src 'self'",
|
||||
// CesiumJS requires unsafe-eval (worker compilation) and unsafe-inline (styles)
|
||||
"script-src 'self' 'unsafe-eval' 'unsafe-inline' blob: https://unpkg.com https://cdn.jsdelivr.net https://analytics.worldwideview.dev https://va.vercel-scripts.com https://pagead2.googlesyndication.com https://adservice.google.com https://www.googletagservices.com https://ep2.adtrafficquality.google https://static.cloudflareinsights.com",
|
||||
"style-src 'self' 'unsafe-inline' fonts.googleapis.com",
|
||||
"font-src 'self' fonts.gstatic.com",
|
||||
// Camera streams load images/MJPEG from arbitrary IPs worldwide — http: https: required
|
||||
"img-src 'self' data: blob: http: https:",
|
||||
// Camera HLS streams and external data fetches need arbitrary origins
|
||||
"connect-src 'self' http: https: ws: wss:",
|
||||
// HLS video streams from arbitrary camera sources
|
||||
"media-src 'self' blob: http: https:",
|
||||
// Embeddable video platforms for camera iframes
|
||||
"frame-src 'self' *.youtube.com *.youtube-nocookie.com *.twitch.tv *.vimeo.com *.webcamera.pl *.ivideon.com *.rtsp.me *.bnu.tv https://googleads.g.doubleclick.net https://tpc.googlesyndication.com https://ep2.adtrafficquality.google https://*.google.com",
|
||||
"worker-src 'self' blob:",
|
||||
"frame-ancestors 'none'",
|
||||
].join("; "),
|
||||
},
|
||||
{ key: "X-Frame-Options", value: "DENY" },
|
||||
{ key: "X-Content-Type-Options", value: "nosniff" },
|
||||
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
|
||||
{ key: "X-DNS-Prefetch-Control", value: "on" },
|
||||
{
|
||||
key: "Permissions-Policy",
|
||||
value: "camera=(), microphone=(), geolocation=(self)",
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
},
|
||||
|
||||
outputFileTracingExcludes: {
|
||||
"*": [
|
||||
"./public/cesium/**"
|
||||
],
|
||||
},
|
||||
env: {
|
||||
CESIUM_BASE_URL: "/cesium",
|
||||
},
|
||||
webpack: (config, { isServer }) => {
|
||||
webpack: (config, { isServer, webpack }) => {
|
||||
if (!isServer) {
|
||||
// Copy Cesium static assets to public/cesium (Production only)
|
||||
if (process.env.NODE_ENV === "production" || !isServer) {
|
||||
// We only add it here if it's production or if we're not using predev
|
||||
// To be safe, let's just make it only run if NOT in dev
|
||||
if (process.env.NODE_ENV === "production") {
|
||||
config.plugins?.push(
|
||||
new CopyPlugin({
|
||||
patterns: [
|
||||
{
|
||||
from: path.join(cesiumSource, "Workers"),
|
||||
to: path.resolve(__dirname, "public/cesium/Workers"),
|
||||
},
|
||||
{
|
||||
from: path.join(cesiumSource, "ThirdParty"),
|
||||
to: path.resolve(__dirname, "public/cesium/ThirdParty"),
|
||||
},
|
||||
{
|
||||
from: path.join(cesiumSource, "Assets"),
|
||||
to: path.resolve(__dirname, "public/cesium/Assets"),
|
||||
},
|
||||
{
|
||||
from: path.join(cesiumSource, "Widgets"),
|
||||
to: path.resolve(__dirname, "public/cesium/Widgets"),
|
||||
},
|
||||
],
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Define CESIUM_BASE_URL for Cesium's worker resolution
|
||||
config.plugins?.push(
|
||||
new webpack.DefinePlugin({
|
||||
@@ -64,4 +87,24 @@ const nextConfig: NextConfig = {
|
||||
},
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
import { withSentryConfig } from "@sentry/nextjs";
|
||||
|
||||
export default withSentryConfig(nextConfig, {
|
||||
// For all available options, see:
|
||||
// https://github.com/getsentry/sentry-webpack-plugin#options
|
||||
org: process.env.SENTRY_ORG,
|
||||
project: process.env.SENTRY_PROJECT,
|
||||
sentryUrl: process.env.GLITCHTIP_SERVER_URL,
|
||||
authToken: process.env.SENTRY_AUTH_TOKEN,
|
||||
|
||||
// Automatically tree-shake Sentry logger statements to reduce bundle size
|
||||
disableLogger: true,
|
||||
|
||||
// Hides source maps from generated client bundles
|
||||
sourcemaps: {
|
||||
disable: true,
|
||||
},
|
||||
|
||||
// Upload a larger set of source maps for prettier stack traces (increases build time)
|
||||
widenClientFileUpload: true,
|
||||
});
|
||||
Generated
-4480
File diff suppressed because it is too large.
Load diff
+54
-7
@@ -1,36 +1,83 @@
|
||||
{
|
||||
"name": "worldwideview",
|
||||
"version": "0.1.0",
|
||||
"version": "2.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"packageManager": "[email protected]",
|
||||
"scripts": {
|
||||
"setup": "node scripts/setup.mjs",
|
||||
"test-worktree": "node scripts/test-worktree.mjs",
|
||||
"clean": "node -e \"const fs=require('fs');fs.rmSync('.next',{recursive:true,force:true})\"",
|
||||
"dev": "next dev --webpack",
|
||||
"predev": "node scripts/copy-cesium.mjs",
|
||||
"dev:all": "concurrently -n \"next,backends\" -c \"magenta,blue\" \"pnpm dev\" \"pnpm dev:backends\"",
|
||||
"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",
|
||||
"build": "next build --webpack",
|
||||
"start": "next start"
|
||||
"start": "next start",
|
||||
"test": "vitest run",
|
||||
"db:reset": "npx prisma migrate reset --force",
|
||||
"generate": "prisma generate"
|
||||
},
|
||||
"dependencies": {
|
||||
"@auth/prisma-adapter": "^2.11.1",
|
||||
"@auth/supabase-adapter": "^1.11.2",
|
||||
"@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.139.0",
|
||||
"cheerio": "^1.2.0",
|
||||
"hls.js": "^1.6.15",
|
||||
"insecam-api": "^0.0.3",
|
||||
"jsdom": "^28.1.0",
|
||||
"jose": "^6.2.2",
|
||||
"lucide-react": "^0.576.0",
|
||||
"next": "16.1.6",
|
||||
"next": "16.2.3",
|
||||
"next-auth": "^5.0.0-beta.30",
|
||||
"pg": "^8.20.0",
|
||||
"prisma": "^7.6.0",
|
||||
"react": "19.2.3",
|
||||
"react-dom": "19.2.3",
|
||||
"react-player": "^3.4.0",
|
||||
"resium": "^1.19.4",
|
||||
"resium": "1.19.4",
|
||||
"satellite.js": "^7.0.0",
|
||||
"stripe": "^22.1.1",
|
||||
"tslib": "^2.8.1",
|
||||
"ws": "^8.14.2",
|
||||
"zustand": "^5.0.11"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@testing-library/dom": "^10.4.1",
|
||||
"@testing-library/react": "^16.3.2",
|
||||
"@types/bcryptjs": "^3.0.0",
|
||||
"@types/cesium": "^1.70.4",
|
||||
"@types/node": "^20",
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"@types/ws": "^8.18.1",
|
||||
"@vitejs/plugin-react": "^5.1.4",
|
||||
"concurrently": "^9.2.1",
|
||||
"copy-webpack-plugin": "^14.0.0",
|
||||
"typescript": "^5"
|
||||
"jsdom": "^28.1.0",
|
||||
"rollup-plugin-external-globals": "^0.13.0",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^5",
|
||||
"vite": "^8.0.8",
|
||||
"vitest": "^4.0.18"
|
||||
},
|
||||
"pnpm": {
|
||||
"onlyBuiltDependencies": [
|
||||
"@prisma/engines",
|
||||
"@sentry/cli",
|
||||
"prisma",
|
||||
"protobufjs",
|
||||
"sharp",
|
||||
"esbuild"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
# @worldwideview/wwv-plugin-sdk
|
||||
|
||||
Plugin SDK for building [WorldWideView](https://github.com/silvertakana/worldwideview) globe plugins. Provides TypeScript types, interfaces, and utilities that all plugins depend on.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install @worldwideview/wwv-plugin-sdk
|
||||
```
|
||||
|
||||
## Core Interfaces
|
||||
|
||||
| Interface | Purpose |
|
||||
|---|---|
|
||||
| `WorldPlugin` | Main plugin contract — lifecycle, data fetching, rendering |
|
||||
| `GeoEntity` | A positioned object on the globe (lat/lon/alt + properties) |
|
||||
| `PluginContext` | Host app context injected into every plugin at init |
|
||||
| `LayerConfig` | Visual layer settings (color, clustering, limits) |
|
||||
| `CesiumEntityOptions` | Per-entity Cesium rendering options (point, model, etc.) |
|
||||
| `SelectionBehavior` | Optional trail / fly-to behavior on entity selection |
|
||||
| `FilterDefinition` | Declarative filter UI (text, select, range, boolean) |
|
||||
| `ServerPluginConfig` | Server-side API routing and polling config |
|
||||
|
||||
## Quick Example
|
||||
|
||||
```ts
|
||||
import type { WorldPlugin, GeoEntity, TimeRange, PluginContext, LayerConfig, CesiumEntityOptions } from "@worldwideview/wwv-plugin-sdk";
|
||||
|
||||
export class MyPlugin implements WorldPlugin {
|
||||
id = "my-plugin";
|
||||
name = "My Plugin";
|
||||
description = "A custom WorldWideView plugin";
|
||||
icon = "🌍";
|
||||
category = "custom";
|
||||
version = "1.0.0";
|
||||
|
||||
async initialize(ctx: PluginContext) { /* setup */ }
|
||||
destroy() { /* cleanup */ }
|
||||
|
||||
async fetch(timeRange: TimeRange): Promise<GeoEntity[]> {
|
||||
// Return geo-positioned entities
|
||||
return [];
|
||||
}
|
||||
|
||||
getPollingInterval() { return 30000; }
|
||||
getLayerConfig(): LayerConfig {
|
||||
return { color: "#3b82f6", clusterEnabled: true, clusterDistance: 40 };
|
||||
}
|
||||
renderEntity(entity: GeoEntity): CesiumEntityOptions {
|
||||
return { type: "point", color: "#3b82f6", size: 6 };
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Changelog
|
||||
|
||||
- **v1.0.3** — Added README with core interfaces and usage docs.
|
||||
- **v1.0.2** — Package metadata updates.
|
||||
- **v1.0.1** — Package configuration fixes.
|
||||
- **v1.0.0** — Initial release with core types and interfaces.
|
||||
|
||||
## License
|
||||
|
||||
ISC
|
||||
+242
@@ -0,0 +1,242 @@
|
||||
import type { ComponentType } from "react";
|
||||
/** Standard SVG icon size (px) used by createSvgIconUrl when no size is given. */
|
||||
export declare const DEFAULT_ICON_SIZE = 32;
|
||||
export interface IconUrlOptions extends Record<string, unknown> {
|
||||
/** Icon color (stroke). */
|
||||
color?: string;
|
||||
/** SVG icon size in px (default: DEFAULT_ICON_SIZE). */
|
||||
size?: number;
|
||||
/** Show circle background behind icon (default: true). */
|
||||
background?: boolean;
|
||||
/** Background fill color (default: semi-transparent dark slate). */
|
||||
backgroundColor?: string;
|
||||
}
|
||||
/**
|
||||
* Convert a React icon component into a `data:image/svg+xml` URL for Cesium billboards.
|
||||
* By default wraps the icon in a filled circle for visibility on any terrain.
|
||||
* Pass `{ background: false }` to opt out.
|
||||
*/
|
||||
export declare function createSvgIconUrl(Icon: ComponentType<any>, opts?: IconUrlOptions): string;
|
||||
export type { PluginManifest, PluginFormat, PluginType, TrustTier, PluginCapability, DataSourceConfig, FieldMapping, RenderingConfig } from "./manifest";
|
||||
export type PluginCategory = "aviation" | "maritime" | "military" | "conflict" | "natural-disaster" | "infrastructure" | "space" | "cyber" | "economic" | "intelligence" | "custom";
|
||||
export interface TimeRange {
|
||||
start: Date;
|
||||
end: Date;
|
||||
}
|
||||
export type TimeWindow = "1h" | "6h" | "24h" | "48h" | "7d";
|
||||
export interface GeoEntity {
|
||||
id: string;
|
||||
pluginId: string;
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
altitude?: number;
|
||||
heading?: number;
|
||||
speed?: number;
|
||||
timestamp: Date;
|
||||
label?: string;
|
||||
properties: Record<string, unknown>;
|
||||
}
|
||||
export interface WsStreamPayload {
|
||||
type: "data" | "error";
|
||||
pluginId?: string;
|
||||
payload?: GeoEntity[];
|
||||
error?: string;
|
||||
}
|
||||
export interface LayerConfig {
|
||||
color: string;
|
||||
iconUrl?: string;
|
||||
clusterEnabled: boolean;
|
||||
clusterDistance: number;
|
||||
minZoomLevel?: number;
|
||||
maxEntities?: number;
|
||||
/** If true, the core primitive renderer and StackManager will ignore this plugin's entities. Use when getGlobeComponent completely manages rendering. */
|
||||
disableDefaultRendering?: boolean;
|
||||
}
|
||||
export interface CesiumEntityOptions {
|
||||
type: "billboard" | "point" | "polyline" | "polygon" | "label" | "model";
|
||||
color?: string;
|
||||
size?: number;
|
||||
iconUrl?: string;
|
||||
rotation?: number;
|
||||
outlineColor?: string;
|
||||
outlineWidth?: number;
|
||||
labelText?: string;
|
||||
labelFont?: string;
|
||||
distanceDisplayCondition?: {
|
||||
near: number;
|
||||
far: number;
|
||||
};
|
||||
disableDepthTestDistance?: number;
|
||||
/** Billboard scale override (default: 0.6). Plugin devs can set this to control icon size. */
|
||||
iconScale?: number;
|
||||
/** GPU Depth Test bias (meters). Negative values pull billboard towards camera (default: -1000 for visibility). */
|
||||
depthBias?: number;
|
||||
modelUrl?: string;
|
||||
modelScale?: number;
|
||||
modelMinPixelSize?: number;
|
||||
modelHeadingOffset?: number;
|
||||
trailOptions?: {
|
||||
width?: number;
|
||||
color?: string;
|
||||
dashPattern?: "solid" | "dashed";
|
||||
opacityFade?: boolean;
|
||||
};
|
||||
/** Skip mathematical horizon culling (useful for high-altitude objects like satellites) */
|
||||
disableManualHorizonCulling?: boolean;
|
||||
/** Skip combining this entity into clusters/stacks when zoomed out */
|
||||
disableClustering?: boolean;
|
||||
}
|
||||
export interface SelectionBehavior {
|
||||
showTrail?: boolean;
|
||||
trailDurationSec?: number;
|
||||
trailStepSec?: number;
|
||||
trailColor?: string;
|
||||
flyToOffsetMultiplier?: number;
|
||||
flyToBaseDistance?: number;
|
||||
}
|
||||
export interface ServerPluginConfig {
|
||||
apiBasePath: string;
|
||||
pollingIntervalMs: number;
|
||||
requiresAuth?: boolean;
|
||||
historyEnabled?: boolean;
|
||||
availabilityEnabled?: boolean;
|
||||
/** WebSocket URL for direct engine connection. Overrides the global default engine URL. */
|
||||
streamUrl?: string;
|
||||
}
|
||||
export interface PluginContext {
|
||||
apiBaseUrl: string;
|
||||
/**
|
||||
* Key-value map of generic environment variables.
|
||||
* The engine surfaces any variable starting with NEXT_PUBLIC_WWV_PLUGIN_
|
||||
*
|
||||
* WARNING: These are exposed to the client-side browser bundle.
|
||||
* DO NOT USE THIS FOR API KEYS. For sensitive tokens, use getSecret() if provided.
|
||||
*/
|
||||
env: Record<string, string>;
|
||||
/** The running edition of the WWV engine */
|
||||
edition: "local" | "cloud" | "demo";
|
||||
timeRange: TimeRange;
|
||||
onDataUpdate: (entities: GeoEntity[]) => void;
|
||||
onError: (error: Error) => void;
|
||||
/** Get plugin-specific settings from the app config store */
|
||||
getPluginSettings: <T = unknown>(pluginId: string) => T | undefined;
|
||||
/** Returns true if the app is in timeline playback mode */
|
||||
isPlaybackMode: () => boolean;
|
||||
/** Returns the current timeline time (relevant in playback mode) */
|
||||
getCurrentTime: () => Date;
|
||||
}
|
||||
export interface FilterSelectOption {
|
||||
value: string;
|
||||
label: string;
|
||||
}
|
||||
export interface FilterRangeConfig {
|
||||
min: number;
|
||||
max: number;
|
||||
step: number;
|
||||
}
|
||||
export interface FilterDefinition {
|
||||
id: string;
|
||||
label: string;
|
||||
type: "text" | "select" | "range" | "boolean";
|
||||
propertyKey: string;
|
||||
options?: FilterSelectOption[];
|
||||
range?: FilterRangeConfig;
|
||||
}
|
||||
export type FilterValue = {
|
||||
type: "text";
|
||||
value: string;
|
||||
} | {
|
||||
type: "select";
|
||||
values: string[];
|
||||
} | {
|
||||
type: "range";
|
||||
min: number;
|
||||
max: number;
|
||||
} | {
|
||||
type: "boolean";
|
||||
value: boolean;
|
||||
};
|
||||
export interface WorldPlugin {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
icon: string | ComponentType<{
|
||||
size?: number;
|
||||
color?: string;
|
||||
}>;
|
||||
category: PluginCategory;
|
||||
version: string;
|
||||
initialize(ctx: PluginContext): Promise<void>;
|
||||
destroy(): void;
|
||||
fetch(timeRange: TimeRange): Promise<GeoEntity[]>;
|
||||
getPollingInterval(): number;
|
||||
getLayerConfig(): LayerConfig;
|
||||
renderEntity(entity: GeoEntity): CesiumEntityOptions;
|
||||
getSelectionBehavior?(entity: GeoEntity): SelectionBehavior | null;
|
||||
getServerConfig?(): ServerPluginConfig;
|
||||
getFilterDefinitions?(): FilterDefinition[];
|
||||
getLegend?(): {
|
||||
label: string;
|
||||
color: string;
|
||||
filterId?: string;
|
||||
filterValue?: string;
|
||||
}[];
|
||||
getSidebarComponent?(): ComponentType<{
|
||||
plugin?: any;
|
||||
} | any>;
|
||||
getDetailComponent?(): ComponentType<{
|
||||
entity: GeoEntity;
|
||||
}>;
|
||||
getSettingsComponent?(): ComponentType<{
|
||||
pluginId: string;
|
||||
}>;
|
||||
/** Custom React component injected into the Globe view for rendering primitives/data sources (e.g. GeoJSON). */
|
||||
getGlobeComponent?(): ComponentType<{
|
||||
viewer: any;
|
||||
enabled: boolean;
|
||||
}>;
|
||||
requiresConfiguration?(settings: unknown): boolean;
|
||||
/** Map raw websocket payload into GeoEntity array. Optional existingEntities is provided so plugins can merge state (e.g. historical trails). */
|
||||
mapWebsocketPayload?(payload: any, existingEntities?: GeoEntity[]): GeoEntity[];
|
||||
}
|
||||
export type GlobePlugin = WorldPlugin;
|
||||
export type DataBusEvents = {
|
||||
pluginRegistered: {
|
||||
pluginId: string;
|
||||
defaultInterval: number;
|
||||
};
|
||||
dataUpdated: {
|
||||
pluginId: string;
|
||||
entities: GeoEntity[];
|
||||
};
|
||||
entitySelected: {
|
||||
entity: GeoEntity | null;
|
||||
};
|
||||
layerToggled: {
|
||||
pluginId: string;
|
||||
enabled: boolean;
|
||||
};
|
||||
timeRangeChanged: {
|
||||
timeRange: TimeRange;
|
||||
};
|
||||
cameraPreset: {
|
||||
presetId: string;
|
||||
};
|
||||
cameraFaceTowards: {
|
||||
lat: number;
|
||||
lon: number;
|
||||
alt: number;
|
||||
};
|
||||
cameraGoTo: {
|
||||
lat: number;
|
||||
lon: number;
|
||||
alt: number;
|
||||
distance?: number;
|
||||
maxPitch?: number;
|
||||
heading?: number;
|
||||
};
|
||||
globeReady: Record<string, never>;
|
||||
};
|
||||
export * from "./viteGlobals";
|
||||
export { wwvStaticCompiler } from "./vite/wwvStaticCompiler";
|
||||
//# sourceMappingURL=index.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAI3C,kFAAkF;AAClF,eAAO,MAAM,iBAAiB,KAAK,CAAC;AAKpC,MAAM,WAAW,cAAe,SAAQ,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAC3D,2BAA2B;IAC3B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,wDAAwD;IACxD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,0DAA0D;IAC1D,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,oEAAoE;IACpE,eAAe,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAC5B,IAAI,EAAE,aAAa,CAAC,GAAG,CAAC,EACxB,IAAI,GAAE,cAAmB,GAC1B,MAAM,CA4BR;AAGD,YAAY,EAAE,cAAc,EAAE,YAAY,EAAE,UAAU,EAAE,SAAS,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAGzJ,MAAM,MAAM,cAAc,GACpB,UAAU,GACV,UAAU,GACV,UAAU,GACV,UAAU,GACV,kBAAkB,GAClB,gBAAgB,GAChB,OAAO,GACP,OAAO,GACP,UAAU,GACV,cAAc,GACd,QAAQ,CAAC;AAGf,MAAM,WAAW,SAAS;IACtB,KAAK,EAAE,IAAI,CAAC;IACZ,GAAG,EAAE,IAAI,CAAC;CACb;AAED,MAAM,MAAM,UAAU,GAAG,IAAI,GAAG,IAAI,GAAG,KAAK,GAAG,KAAK,GAAG,IAAI,CAAC;AAG5D,MAAM,WAAW,SAAS;IACtB,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,IAAI,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACvC;AAED,MAAM,WAAW,eAAe;IAC5B,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC;IACvB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,SAAS,EAAE,CAAC;IACtB,KAAK,CAAC,EAAE,MAAM,CAAC;CAClB;AAGD,MAAM,WAAW,WAAW;IACxB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,cAAc,EAAE,OAAO,CAAC;IACxB,eAAe,EAAE,MAAM,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,yJAAyJ;IACzJ,uBAAuB,CAAC,EAAE,OAAO,CAAC;CACrC;AAGD,MAAM,WAAW,mBAAmB;IAChC,IAAI,EAAE,WAAW,GAAG,OAAO,GAAG,UAAU,GAAG,SAAS,GAAG,OAAO,GAAG,OAAO,CAAC;IACzE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,wBAAwB,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,GAAG,EAAE,MAAM,CAAA;KAAE,CAAC;IACzD,wBAAwB,CAAC,EAAE,MAAM,CAAC;IAClC,8FAA8F;IAC9F,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,mHAAmH;IACnH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,YAAY,CAAC,EAAE;QACX,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,WAAW,CAAC,EAAE,OAAO,GAAG,QAAQ,CAAC;QACjC,WAAW,CAAC,EAAE,OAAO,CAAC;KACzB,CAAC;IACF,2FAA2F;IAC3F,2BAA2B,CAAC,EAAE,OAAO,CAAC;IACtC,sEAAsE;IACtE,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC/B;AAGD,MAAM,WAAW,iBAAiB;IAC9B,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC9B;AAGD,MAAM,WAAW,kBAAkB;IAC/B,WAAW,EAAE,MAAM,CAAC;IACpB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,2FAA2F;IAC3F,SAAS,CAAC,EAAE,MAAM,CAAC;CACtB;AAKD,MAAM,WAAW,aAAa;IAC1B,UAAU,EAAE,MAAM,CAAC;IACnB;;;;;;OAMG;IACH,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC5B,4CAA4C;IAC5C,OAAO,EAAE,OAAO,GAAG,OAAO,GAAG,MAAM,CAAC;IACpC,SAAS,EAAE,SAAS,CAAC;IACrB,YAAY,EAAE,CAAC,QAAQ,EAAE,SAAS,EAAE,KAAK,IAAI,CAAC;IAC9C,OAAO,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IAChC,6DAA6D;IAC7D,iBAAiB,EAAE,CAAC,CAAC,GAAG,OAAO,EAAE,QAAQ,EAAE,MAAM,KAAK,CAAC,GAAG,SAAS,CAAC;IACpE,2DAA2D;IAC3D,cAAc,EAAE,MAAM,OAAO,CAAC;IAC9B,oEAAoE;IACpE,cAAc,EAAE,MAAM,IAAI,CAAC;CAC9B;AAGD,MAAM,WAAW,kBAAkB;IAAG,KAAK,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;CAAE;AACrE,MAAM,WAAW,iBAAiB;IAAG,GAAG,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;CAAE;AAC9E,MAAM,WAAW,gBAAgB;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,GAAG,QAAQ,GAAG,OAAO,GAAG,SAAS,CAAC;IAC9C,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,EAAE,kBAAkB,EAAE,CAAC;IAC/B,KAAK,CAAC,EAAE,iBAAiB,CAAC;CAC7B;AAED,MAAM,MAAM,WAAW,GACjB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAC/B;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,MAAM,EAAE,MAAM,EAAE,CAAA;CAAE,GACpC;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAC3C;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,KAAK,EAAE,OAAO,CAAA;CAAE,CAAC;AAG1C,MAAM,WAAW,WAAW;IACxB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,GAAG,aAAa,CAAC;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAChE,QAAQ,EAAE,cAAc,CAAC;IACzB,OAAO,EAAE,MAAM,CAAC;IAGhB,UAAU,CAAC,GAAG,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9C,OAAO,IAAI,IAAI,CAAC;IAGhB,KAAK,CAAC,SAAS,EAAE,SAAS,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC,CAAC;IAClD,kBAAkB,IAAI,MAAM,CAAC;IAG7B,cAAc,IAAI,WAAW,CAAC;IAC9B,YAAY,CAAC,MAAM,EAAE,SAAS,GAAG,mBAAmB,CAAC;IAGrD,oBAAoB,CAAC,CAAC,MAAM,EAAE,SAAS,GAAG,iBAAiB,GAAG,IAAI,CAAC;IACnE,eAAe,CAAC,IAAI,kBAAkB,CAAC;IACvC,oBAAoB,CAAC,IAAI,gBAAgB,EAAE,CAAC;IAC5C,SAAS,CAAC,IAAI;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAALine truncated
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
"use strict";
|
||||
// ─── WorldWideView Plugin SDK ─────────────────────────────────
|
||||
// The public API for building WorldWideView plugins.
|
||||
// Import from "@worldwideview/wwv-plugin-sdk" in your plugin.
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
||||
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
||||
};
|
||||
var __rest = (this && this.__rest) || function (s, e) {
|
||||
var t = {};
|
||||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
|
||||
t[p] = s[p];
|
||||
if (s != null && typeof Object.getOwnPropertySymbols === "function")
|
||||
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
|
||||
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
|
||||
t[p[i]] = s[p[i]];
|
||||
}
|
||||
return t;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.wwvStaticCompiler = exports.DEFAULT_ICON_SIZE = void 0;
|
||||
exports.createSvgIconUrl = createSvgIconUrl;
|
||||
const react_1 = require("react");
|
||||
const server_1 = require("react-dom/server");
|
||||
/** Standard SVG icon size (px) used by createSvgIconUrl when no size is given. */
|
||||
exports.DEFAULT_ICON_SIZE = 32;
|
||||
/** Default dark background color for icon circles. */
|
||||
const DEFAULT_BG_COLOR = "rgba(15, 23, 42, 0.85)";
|
||||
/**
|
||||
* Convert a React icon component into a `data:image/svg+xml` URL for Cesium billboards.
|
||||
* By default wraps the icon in a filled circle for visibility on any terrain.
|
||||
* Pass `{ background: false }` to opt out.
|
||||
*/
|
||||
function createSvgIconUrl(Icon, opts = {}) {
|
||||
const { background = true, backgroundColor = DEFAULT_BG_COLOR, size = exports.DEFAULT_ICON_SIZE } = opts, iconProps = __rest(opts, ["background", "backgroundColor", "size"]);
|
||||
const innerSvg = (0, server_1.renderToStaticMarkup)((0, react_1.createElement)(Icon, Object.assign({ size }, iconProps)));
|
||||
if (!background) {
|
||||
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(innerSvg)}`;
|
||||
}
|
||||
// Wrap the icon in a larger SVG with a filled circle behind it
|
||||
const padding = 6;
|
||||
const totalSize = size + padding * 2;
|
||||
const center = totalSize / 2;
|
||||
const radius = totalSize / 2 - 1;
|
||||
const wrappedSvg = [
|
||||
`<svg xmlns="http://www.w3.org/2000/svg" width="${totalSize}" height="${totalSize}" viewBox="0 0 ${totalSize} ${totalSize}">`,
|
||||
`<circle cx="${center}" cy="${center}" r="${radius}" fill="${backgroundColor}" />`,
|
||||
`<g transform="translate(${padding}, ${padding})">${innerSvg}</g>`,
|
||||
`</svg>`,
|
||||
].join("");
|
||||
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(wrappedSvg)}`;
|
||||
}
|
||||
__exportStar(require("./viteGlobals"), exports);
|
||||
var wwvStaticCompiler_1 = require("./vite/wwvStaticCompiler");
|
||||
Object.defineProperty(exports, "wwvStaticCompiler", { enumerable: true, get: function () { return wwvStaticCompiler_1.wwvStaticCompiler; } });
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
import type { PluginCategory } from "./index";
|
||||
export type PluginFormat = "declarative" | "static" | "bundle";
|
||||
export type PluginType = "data-layer" | "extension";
|
||||
export type TrustTier = "built-in" | "verified" | "unverified";
|
||||
export type PluginCapability = "data:own" | `data:read:${string}` | "ui:detail-panel" | "ui:sidebar" | "ui:toolbar" | "ui:settings" | "globe:overlay" | "globe:camera" | "storage:read" | "storage:write" | "network:fetch";
|
||||
export interface DataSourceConfig {
|
||||
url: string;
|
||||
method: "GET" | "POST";
|
||||
pollInterval: number;
|
||||
format: "geojson" | "json" | "csv";
|
||||
auth?: {
|
||||
type: "header" | "query";
|
||||
key: string;
|
||||
envVar: string;
|
||||
} | null;
|
||||
headers?: Record<string, string>;
|
||||
body?: Record<string, unknown>;
|
||||
arrayPath?: string;
|
||||
/** WebSocket URL for direct engine connection (e.g., wss://my-engine.example.com/stream). */
|
||||
streamUrl?: string;
|
||||
}
|
||||
export interface FieldMapping {
|
||||
id: string;
|
||||
latitude: string;
|
||||
longitude: string;
|
||||
altitude?: string;
|
||||
heading?: string;
|
||||
speed?: string;
|
||||
label?: string;
|
||||
timestamp?: string;
|
||||
properties?: Record<string, string>;
|
||||
}
|
||||
export interface RenderingConfig {
|
||||
entityType: "billboard" | "point" | "polyline" | "polygon" | "label" | "model";
|
||||
color?: string;
|
||||
icon?: string;
|
||||
sizeField?: string;
|
||||
labelField?: string;
|
||||
clusterEnabled?: boolean;
|
||||
clusterDistance?: number;
|
||||
modelUrl?: string;
|
||||
minZoomLevel?: number;
|
||||
maxEntities?: number;
|
||||
}
|
||||
export interface PluginManifest {
|
||||
id: string;
|
||||
name: string;
|
||||
version: string;
|
||||
description?: string;
|
||||
type: PluginType;
|
||||
format: PluginFormat;
|
||||
trust: TrustTier;
|
||||
capabilities: PluginCapability[];
|
||||
category: PluginCategory | string;
|
||||
icon?: string;
|
||||
compatibility?: {
|
||||
worldwideview: string;
|
||||
};
|
||||
requires?: {
|
||||
envVars?: string[];
|
||||
};
|
||||
dataSource?: DataSourceConfig;
|
||||
fieldMapping?: FieldMapping;
|
||||
dataFile?: string;
|
||||
rendering?: RenderingConfig;
|
||||
entry?: string;
|
||||
assets?: string[];
|
||||
extends?: string[];
|
||||
}
|
||||
//# sourceMappingURL=manifest.d.ts.map
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"manifest.d.ts","sourceRoot":"","sources":["../src/manifest.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAE9C,MAAM,MAAM,YAAY,GAAG,aAAa,GAAG,QAAQ,GAAG,QAAQ,CAAC;AAC/D,MAAM,MAAM,UAAU,GAAG,YAAY,GAAG,WAAW,CAAC;AACpD,MAAM,MAAM,SAAS,GAAG,UAAU,GAAG,UAAU,GAAG,YAAY,CAAC;AAE/D,MAAM,MAAM,gBAAgB,GACtB,UAAU,GACV,aAAa,MAAM,EAAE,GACrB,iBAAiB,GACjB,YAAY,GACZ,YAAY,GACZ,aAAa,GACb,eAAe,GACf,cAAc,GACd,cAAc,GACd,eAAe,GACf,eAAe,CAAC;AAEtB,MAAM,WAAW,gBAAgB;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,KAAK,GAAG,MAAM,CAAC;IACvB,YAAY,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,SAAS,GAAG,MAAM,GAAG,KAAK,CAAC;IACnC,IAAI,CAAC,EAAE;QAAE,IAAI,EAAE,QAAQ,GAAG,OAAO,CAAC;QAAC,GAAG,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;IACxE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC/B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,6FAA6F;IAC7F,SAAS,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,YAAY;IACzB,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACvC;AAED,MAAM,WAAW,eAAe;IAC5B,UAAU,EAAE,WAAW,GAAG,OAAO,GAAG,UAAU,GAAG,SAAS,GAAG,OAAO,GAAG,OAAO,CAAC;IAC/E,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,MAAM,WAAW,cAAc;IAC3B,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,IAAI,EAAE,UAAU,CAAC;IACjB,MAAM,EAAE,YAAY,CAAC;IACrB,KAAK,EAAE,SAAS,CAAC;IACjB,YAAY,EAAE,gBAAgB,EAAE,CAAC;IACjC,QAAQ,EAAE,cAAc,GAAG,MAAM,CAAC;IAClC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,aAAa,CAAC,EAAE;QAAE,aAAa,EAAE,MAAM,CAAA;KAAE,CAAC;IAC1C,QAAQ,CAAC,EAAE;QAAE,OAAO,CAAC,EAAE,MAAM,EAAE,CAAA;KAAE,CAAC;IAClC,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,YAAY,CAAC,EAAE,YAAY,CAAC;IAC5B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,eAAe,CAAC;IAC5B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;CACtB"}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
"use strict";
|
||||
// ─── Plugin Manifest Types ───────────────────────────────────
|
||||
// Schema for plugin.json manifest files.
|
||||
// Three formats: declarative (JSON-only), static (GeoJSON), bundle (JS code).
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"name": "@worldwideview/wwv-plugin-sdk",
|
||||
"version": "1.5.0",
|
||||
"description": "Plugin SDK — types, interfaces, and utilities for building WorldWideView globe plugins",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsc --project tsconfig.build.json",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"keywords": [
|
||||
"worldwideview",
|
||||
"wwv-plugin-sdk",
|
||||
"globe",
|
||||
"cesium",
|
||||
"plugin-sdk",
|
||||
"geospatial"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/silvertakana/worldwideview.git",
|
||||
"directory": "packages/wwv-plugin-sdk"
|
||||
},
|
||||
"homepage": "https://github.com/silvertakana/worldwideview#readme",
|
||||
"bugs": {
|
||||
"url": "https://github.com/silvertakana/worldwideview/issues"
|
||||
},
|
||||
"license": "ISC",
|
||||
"author": "WorldWideView",
|
||||
"peerDependencies": {
|
||||
"react": ">=18"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5",
|
||||
"@types/react": "^19"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
// ─── WorldWideView Plugin SDK ─────────────────────────────────
|
||||
// The public API for building WorldWideView plugins.
|
||||
// Import from "@worldwideview/wwv-plugin-sdk" in your plugin.
|
||||
|
||||
import type { ComponentType } from "react";
|
||||
import { createElement } from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
/** Standard SVG icon size (px) used by createSvgIconUrl when no size is given. */
|
||||
export const DEFAULT_ICON_SIZE = 32;
|
||||
|
||||
/** Default dark background color for icon circles. */
|
||||
const DEFAULT_BG_COLOR = "rgba(15, 23, 42, 0.85)";
|
||||
|
||||
export interface IconUrlOptions extends Record<string, unknown> {
|
||||
/** Icon color (stroke). */
|
||||
color?: string;
|
||||
/** SVG icon size in px (default: DEFAULT_ICON_SIZE). */
|
||||
size?: number;
|
||||
/** Show circle background behind icon (default: true). */
|
||||
background?: boolean;
|
||||
/** Background fill color (default: semi-transparent dark slate). */
|
||||
backgroundColor?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a React icon component into a `data:image/svg+xml` URL for Cesium billboards.
|
||||
* By default wraps the icon in a filled circle for visibility on any terrain.
|
||||
* Pass `{ background: false }` to opt out.
|
||||
*/
|
||||
export function createSvgIconUrl(
|
||||
Icon: ComponentType<any>,
|
||||
opts: IconUrlOptions = {},
|
||||
): string {
|
||||
const {
|
||||
background = true,
|
||||
backgroundColor = DEFAULT_BG_COLOR,
|
||||
size = DEFAULT_ICON_SIZE,
|
||||
...iconProps
|
||||
} = opts;
|
||||
|
||||
const innerSvg = renderToStaticMarkup(createElement(Icon, { size, ...iconProps }));
|
||||
|
||||
if (!background) {
|
||||
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(innerSvg)}`;
|
||||
}
|
||||
|
||||
// Wrap the icon in a larger SVG with a filled circle behind it
|
||||
const padding = 6;
|
||||
const totalSize = size + padding * 2;
|
||||
const center = totalSize / 2;
|
||||
const radius = totalSize / 2 - 1;
|
||||
|
||||
const wrappedSvg = [
|
||||
`<svg xmlns="http://www.w3.org/2000/svg" width="${totalSize}" height="${totalSize}" viewBox="0 0 ${totalSize} ${totalSize}">`,
|
||||
`<circle cx="${center}" cy="${center}" r="${radius}" fill="${backgroundColor}" />`,
|
||||
`<g transform="translate(${padding}, ${padding})">${innerSvg}</g>`,
|
||||
`</svg>`,
|
||||
].join("");
|
||||
|
||||
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(wrappedSvg)}`;
|
||||
}
|
||||
|
||||
// ─── Re-export manifest types ─────────────────────────────────
|
||||
export type { PluginManifest, PluginFormat, PluginType, TrustTier, PluginCapability, DataSourceConfig, FieldMapping, RenderingConfig } from "./manifest";
|
||||
|
||||
// ─── Categories ──────────────────────────────────────────────
|
||||
export type PluginCategory =
|
||||
| "aviation"
|
||||
| "maritime"
|
||||
| "military"
|
||||
| "conflict"
|
||||
| "natural-disaster"
|
||||
| "infrastructure"
|
||||
| "space"
|
||||
| "cyber"
|
||||
| "economic"
|
||||
| "intelligence"
|
||||
| "custom";
|
||||
|
||||
// ─── Time ────────────────────────────────────────────────────
|
||||
export interface TimeRange {
|
||||
start: Date;
|
||||
end: Date;
|
||||
}
|
||||
|
||||
export type TimeWindow = "1h" | "6h" | "24h" | "48h" | "7d";
|
||||
|
||||
// ─── Geo Entities ────────────────────────────────────────────
|
||||
export interface GeoEntity {
|
||||
id: string;
|
||||
pluginId: string;
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
altitude?: number;
|
||||
heading?: number;
|
||||
speed?: number;
|
||||
timestamp: Date;
|
||||
label?: string;
|
||||
properties: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface WsStreamPayload {
|
||||
type: "data" | "error";
|
||||
pluginId?: string;
|
||||
payload?: GeoEntity[];
|
||||
error?: string;
|
||||
}
|
||||
|
||||
// ─── Layer Config ────────────────────────────────────────────
|
||||
export interface LayerConfig {
|
||||
color: string;
|
||||
iconUrl?: string;
|
||||
clusterEnabled: boolean;
|
||||
clusterDistance: number;
|
||||
minZoomLevel?: number;
|
||||
maxEntities?: number;
|
||||
/** If true, the core primitive renderer and StackManager will ignore this plugin's entities. Use when getGlobeComponent completely manages rendering. */
|
||||
disableDefaultRendering?: boolean;
|
||||
}
|
||||
|
||||
// ─── Cesium Entity Options ───────────────────────────────────
|
||||
export interface CesiumEntityOptions {
|
||||
type: "billboard" | "point" | "polyline" | "polygon" | "label" | "model";
|
||||
color?: string;
|
||||
size?: number;
|
||||
iconUrl?: string;
|
||||
rotation?: number;
|
||||
outlineColor?: string;
|
||||
outlineWidth?: number;
|
||||
labelText?: string;
|
||||
labelFont?: string;
|
||||
distanceDisplayCondition?: { near: number; far: number };
|
||||
disableDepthTestDistance?: number;
|
||||
/** Billboard scale override (default: 0.6). Plugin devs can set this to control icon size. */
|
||||
iconScale?: number;
|
||||
/** GPU Depth Test bias (meters). Negative values pull billboard towards camera (default: -1000 for visibility). */
|
||||
depthBias?: number;
|
||||
modelUrl?: string;
|
||||
modelScale?: number;
|
||||
modelMinPixelSize?: number;
|
||||
modelHeadingOffset?: number;
|
||||
trailOptions?: {
|
||||
width?: number;
|
||||
color?: string;
|
||||
dashPattern?: "solid" | "dashed";
|
||||
opacityFade?: boolean;
|
||||
};
|
||||
/** Skip mathematical horizon culling (useful for high-altitude objects like satellites) */
|
||||
disableManualHorizonCulling?: boolean;
|
||||
/** Skip combining this entity into clusters/stacks when zoomed out */
|
||||
disableClustering?: boolean;
|
||||
}
|
||||
|
||||
// ─── Selection Behavior ──────────────────────────────────────
|
||||
export interface SelectionBehavior {
|
||||
showTrail?: boolean;
|
||||
trailDurationSec?: number;
|
||||
trailStepSec?: number;
|
||||
trailColor?: string;
|
||||
flyToOffsetMultiplier?: number;
|
||||
flyToBaseDistance?: number;
|
||||
}
|
||||
|
||||
// ─── Server Plugin Config ────────────────────────────────────
|
||||
export interface ServerPluginConfig {
|
||||
apiBasePath: string;
|
||||
pollingIntervalMs: number;
|
||||
requiresAuth?: boolean;
|
||||
historyEnabled?: boolean;
|
||||
availabilityEnabled?: boolean;
|
||||
/** WebSocket URL for direct engine connection. Overrides the global default engine URL. */
|
||||
streamUrl?: string;
|
||||
}
|
||||
|
||||
// ─── Plugin Context ──────────────────────────────────────────
|
||||
// Provided by the host app when initializing each plugin.
|
||||
// All plugins (built-in and 3rd party) receive the same context.
|
||||
export interface PluginContext {
|
||||
apiBaseUrl: string;
|
||||
/**
|
||||
* Key-value map of generic environment variables.
|
||||
* The engine surfaces any variable starting with NEXT_PUBLIC_WWV_PLUGIN_
|
||||
*
|
||||
* WARNING: These are exposed to the client-side browser bundle.
|
||||
* DO NOT USE THIS FOR API KEYS. For sensitive tokens, use getSecret() if provided.
|
||||
*/
|
||||
env: Record<string, string>;
|
||||
/** The running edition of the WWV engine */
|
||||
edition: "local" | "cloud" | "demo";
|
||||
timeRange: TimeRange;
|
||||
onDataUpdate: (entities: GeoEntity[]) => void;
|
||||
onError: (error: Error) => void;
|
||||
/** Get plugin-specific settings from the app config store */
|
||||
getPluginSettings: <T = unknown>(pluginId: string) => T | undefined;
|
||||
/** Returns true if the app is in timeline playback mode */
|
||||
isPlaybackMode: () => boolean;
|
||||
/** Returns the current timeline time (relevant in playback mode) */
|
||||
getCurrentTime: () => Date;
|
||||
}
|
||||
|
||||
// ─── Filter Definitions ──────────────────────────────────────
|
||||
export interface FilterSelectOption { value: string; label: string; }
|
||||
export interface FilterRangeConfig { min: number; max: number; step: number; }
|
||||
export interface FilterDefinition {
|
||||
id: string;
|
||||
label: string;
|
||||
type: "text" | "select" | "range" | "boolean";
|
||||
propertyKey: string;
|
||||
options?: FilterSelectOption[];
|
||||
range?: FilterRangeConfig;
|
||||
}
|
||||
|
||||
export type FilterValue =
|
||||
| { type: "text"; value: string }
|
||||
| { type: "select"; values: string[] }
|
||||
| { type: "range"; min: number; max: number }
|
||||
| { type: "boolean"; value: boolean };
|
||||
|
||||
// ─── World Plugin Interface ──────────────────────────────────
|
||||
export interface WorldPlugin {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
icon: string | ComponentType<{ size?: number; color?: string }>;
|
||||
category: PluginCategory;
|
||||
version: string;
|
||||
|
||||
// Lifecycle
|
||||
initialize(ctx: PluginContext): Promise<void>;
|
||||
destroy(): void;
|
||||
|
||||
// Data
|
||||
fetch(timeRange: TimeRange): Promise<GeoEntity[]>;
|
||||
getPollingInterval(): number;
|
||||
|
||||
// Rendering
|
||||
getLayerConfig(): LayerConfig;
|
||||
renderEntity(entity: GeoEntity): CesiumEntityOptions;
|
||||
|
||||
// Optional
|
||||
getSelectionBehavior?(entity: GeoEntity): SelectionBehavior | null;
|
||||
getServerConfig?(): ServerPluginConfig;
|
||||
getFilterDefinitions?(): FilterDefinition[];
|
||||
getLegend?(): { label: string; color: string; filterId?: string; filterValue?: string }[];
|
||||
getSidebarComponent?(): ComponentType<{ plugin?: any } | any>;
|
||||
getDetailComponent?(): ComponentType<{ entity: GeoEntity }>;
|
||||
getSettingsComponent?(): ComponentType<{ pluginId: string }>;
|
||||
/** Custom React component injected into the Globe view for rendering primitives/data sources (e.g. GeoJSON). */
|
||||
getGlobeComponent?(): ComponentType<{ viewer: any; enabled: boolean }>;
|
||||
requiresConfiguration?(settings: unknown): boolean;
|
||||
/** Map raw websocket payload into GeoEntity array. Optional existingEntities is provided so plugins can merge state (e.g. historical trails). */
|
||||
mapWebsocketPayload?(payload: any, existingEntities?: GeoEntity[]): GeoEntity[];
|
||||
}
|
||||
|
||||
// ─── Aliases for backwards compatibility ─────────────────────
|
||||
export type GlobePlugin = WorldPlugin;
|
||||
|
||||
// ─── Data Bus Event Types ────────────────────────────────────
|
||||
export type DataBusEvents = {
|
||||
pluginRegistered: { pluginId: string; defaultInterval: number };
|
||||
dataUpdated: { pluginId: string; entities: GeoEntity[] };
|
||||
entitySelected: { entity: GeoEntity | null };
|
||||
layerToggled: { pluginId: string; enabled: boolean };
|
||||
timeRangeChanged: { timeRange: TimeRange };
|
||||
cameraPreset: { presetId: string };
|
||||
cameraFaceTowards: { lat: number; lon: number; alt: number };
|
||||
cameraGoTo: { lat: number; lon: number; alt: number; distance?: number; maxPitch?: number; heading?: number };
|
||||
globeReady: Record<string, never>;
|
||||
};
|
||||
|
||||
export * from "./viteGlobals";
|
||||
export { wwvStaticCompiler } from "./vite/wwvStaticCompiler";
|
||||
@@ -0,0 +1,82 @@
|
||||
// ─── Plugin Manifest Types ───────────────────────────────────
|
||||
// Schema for plugin.json manifest files.
|
||||
// Three formats: declarative (JSON-only), static (GeoJSON), bundle (JS code).
|
||||
|
||||
import type { PluginCategory } from "./index";
|
||||
|
||||
export type PluginFormat = "declarative" | "static" | "bundle";
|
||||
export type PluginType = "data-layer" | "extension";
|
||||
export type TrustTier = "built-in" | "verified" | "unverified";
|
||||
|
||||
export type PluginCapability =
|
||||
| "data:own"
|
||||
| `data:read:${string}`
|
||||
| "ui:detail-panel"
|
||||
| "ui:sidebar"
|
||||
| "ui:toolbar"
|
||||
| "ui:settings"
|
||||
| "globe:overlay"
|
||||
| "globe:camera"
|
||||
| "storage:read"
|
||||
| "storage:write"
|
||||
| "network:fetch";
|
||||
|
||||
export interface DataSourceConfig {
|
||||
url: string;
|
||||
method: "GET" | "POST";
|
||||
pollInterval: number;
|
||||
format: "geojson" | "json" | "csv";
|
||||
auth?: { type: "header" | "query"; key: string; envVar: string } | null;
|
||||
headers?: Record<string, string>;
|
||||
body?: Record<string, unknown>;
|
||||
arrayPath?: string;
|
||||
/** WebSocket URL for direct engine connection (e.g., wss://my-engine.example.com/stream). */
|
||||
streamUrl?: string;
|
||||
}
|
||||
|
||||
export interface FieldMapping {
|
||||
id: string;
|
||||
latitude: string;
|
||||
longitude: string;
|
||||
altitude?: string;
|
||||
heading?: string;
|
||||
speed?: string;
|
||||
label?: string;
|
||||
timestamp?: string;
|
||||
properties?: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface RenderingConfig {
|
||||
entityType: "billboard" | "point" | "polyline" | "polygon" | "label" | "model";
|
||||
color?: string;
|
||||
icon?: string;
|
||||
sizeField?: string;
|
||||
labelField?: string;
|
||||
clusterEnabled?: boolean;
|
||||
clusterDistance?: number;
|
||||
modelUrl?: string;
|
||||
minZoomLevel?: number;
|
||||
maxEntities?: number;
|
||||
}
|
||||
|
||||
export interface PluginManifest {
|
||||
id: string;
|
||||
name: string;
|
||||
version: string;
|
||||
description?: string;
|
||||
type: PluginType;
|
||||
format: PluginFormat;
|
||||
trust: TrustTier;
|
||||
capabilities: PluginCapability[];
|
||||
category: PluginCategory | string;
|
||||
icon?: string;
|
||||
compatibility?: { worldwideview: string };
|
||||
requires?: { envVars?: string[] };
|
||||
dataSource?: DataSourceConfig;
|
||||
fieldMapping?: FieldMapping;
|
||||
dataFile?: string;
|
||||
rendering?: RenderingConfig;
|
||||
entry?: string;
|
||||
assets?: string[];
|
||||
extends?: string[];
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Vite plugin that auto-generates a WorldPlugin class for static plugins.
|
||||
*
|
||||
* If the plugin's package.json has `worldwideview.format: "static"` and
|
||||
* no `src/index.ts` exists, this plugin injects a virtual module that:
|
||||
* - Fetches GeoJSON data from the CDN at runtime
|
||||
* - Converts features into GeoEntity objects
|
||||
* - Renders with the manifest's rendering config
|
||||
*/
|
||||
export function wwvStaticCompiler(): any {
|
||||
let pluginRoot = "";
|
||||
let manifest: any = null;
|
||||
let generatedEntry = "";
|
||||
|
||||
return {
|
||||
name: "wwv-static-compiler",
|
||||
enforce: "pre" as const,
|
||||
|
||||
config(userConfig: any) {
|
||||
pluginRoot = userConfig.root || process.cwd();
|
||||
const pkgPath = path.join(pluginRoot, "package.json");
|
||||
if (!fs.existsSync(pkgPath)) return;
|
||||
|
||||
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
|
||||
manifest = pkg.worldwideview || null;
|
||||
if (!manifest) return;
|
||||
|
||||
manifest._packageName = pkg.name;
|
||||
manifest._packageVersion = pkg.version;
|
||||
manifest._description = pkg.description || "";
|
||||
|
||||
const srcIndex = path.join(pluginRoot, "src", "index.ts");
|
||||
if (fs.existsSync(srcIndex)) return; // real source exists
|
||||
|
||||
// Write a generated entry file
|
||||
const srcDir = path.join(pluginRoot, "src");
|
||||
if (!fs.existsSync(srcDir)) fs.mkdirSync(srcDir, { recursive: true });
|
||||
|
||||
generatedEntry = path.join(srcDir, "__generated_entry.js");
|
||||
const source = generateStaticPluginSource(manifest);
|
||||
fs.writeFileSync(generatedEntry, source, "utf-8");
|
||||
|
||||
// Redirect lib entry to the generated file
|
||||
if (userConfig.build?.lib) {
|
||||
userConfig.build.lib.entry = generatedEntry;
|
||||
}
|
||||
},
|
||||
|
||||
buildEnd() {
|
||||
// Clean up the generated file, but ONLY if we are not in watch mode
|
||||
const isWatchMode = process.argv.includes("--watch") || process.argv.includes("-w");
|
||||
if (!isWatchMode && generatedEntry && fs.existsSync(generatedEntry)) {
|
||||
fs.unlinkSync(generatedEntry);
|
||||
generatedEntry = "";
|
||||
}
|
||||
},
|
||||
|
||||
closeBundle() {
|
||||
// Also clean up on close (redundant safety)
|
||||
const isWatchMode = process.argv.includes("--watch") || process.argv.includes("-w");
|
||||
if (!isWatchMode && generatedEntry && fs.existsSync(generatedEntry)) {
|
||||
fs.unlinkSync(generatedEntry);
|
||||
generatedEntry = "";
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function generateStaticPluginSource(manifest: any): string {
|
||||
const pluginId = manifest.id;
|
||||
const pluginName = manifest.name || pluginId;
|
||||
const description = manifest._description || "";
|
||||
const category = manifest.category || "custom";
|
||||
const icon = manifest.icon || "MapPin";
|
||||
const version = manifest._packageVersion || "1.0.0";
|
||||
const packageName = manifest._packageName;
|
||||
|
||||
const color =
|
||||
manifest.rendering?.defaultColor ||
|
||||
manifest.rendering?.color ||
|
||||
"#3b82f6";
|
||||
const entityType = manifest.rendering?.entityType || "point";
|
||||
const clusterEnabled = manifest.rendering?.clusterEnabled ?? true;
|
||||
const clusterDistance = manifest.rendering?.clusterDistance ?? 50;
|
||||
const maxEntities = manifest.rendering?.maxEntities ?? 5000;
|
||||
const labelField = manifest.rendering?.labelField || "name";
|
||||
|
||||
const dataFileName = manifest.dataFile
|
||||
? path.basename(manifest.dataFile)
|
||||
: "data.json";
|
||||
|
||||
const renderBlock =
|
||||
entityType === "billboard"
|
||||
? `
|
||||
const cacheKey = "default";
|
||||
if (!this._iconUrls[cacheKey]) {
|
||||
this._iconUrls[cacheKey] = createSvgIconUrl(${icon}, { color: ${JSON.stringify(color)} });
|
||||
}
|
||||
return { type: "billboard", iconUrl: this._iconUrls[cacheKey], color: ${JSON.stringify(color)}, iconScale: 0.5 };`
|
||||
: `
|
||||
return { type: "point", color: ${JSON.stringify(color)}, size: 6 };`;
|
||||
|
||||
return `
|
||||
import { ${icon} } from "lucide-react";
|
||||
import { createSvgIconUrl } from "@worldwideview/wwv-plugin-sdk";
|
||||
import dataRaw from "../data/${dataFileName}?raw";
|
||||
|
||||
function representativePoint(geom) {
|
||||
if (!geom) return { lat: 0, lon: 0 };
|
||||
switch (geom.type) {
|
||||
case "Point":
|
||||
return { lat: geom.coordinates[1], lon: geom.coordinates[0], alt: geom.coordinates[2] };
|
||||
case "MultiPoint":
|
||||
case "LineString":
|
||||
return { lat: geom.coordinates[0][1], lon: geom.coordinates[0][0] };
|
||||
case "Polygon":
|
||||
case "MultiLineString":
|
||||
return { lat: geom.coordinates[0][0][1], lon: geom.coordinates[0][0][0] };
|
||||
case "MultiPolygon":
|
||||
return { lat: geom.coordinates[0][0][0][1], lon: geom.coordinates[0][0][0][0] };
|
||||
default:
|
||||
return { lat: 0, lon: 0 };
|
||||
}
|
||||
}
|
||||
|
||||
export default class AutoStaticPlugin {
|
||||
id = ${JSON.stringify(pluginId)};
|
||||
name = ${JSON.stringify(pluginName)};
|
||||
description = ${JSON.stringify(description)};
|
||||
icon = ${icon};
|
||||
category = ${JSON.stringify(category)};
|
||||
version = ${JSON.stringify(version)};
|
||||
|
||||
_context = null;
|
||||
_entities = [];
|
||||
_iconUrls = {};
|
||||
|
||||
async initialize(ctx) {
|
||||
this._context = ctx;
|
||||
let data = null;
|
||||
try {
|
||||
data = JSON.parse(dataRaw);
|
||||
} catch(e) {
|
||||
console.error("Failed to parse data for ${pluginId}", e);
|
||||
}
|
||||
if (data && Array.isArray(data.features)) {
|
||||
this._entities = data.features.map((f, i) => {
|
||||
const pt = representativePoint(f.geometry);
|
||||
return {
|
||||
id: "${pluginId}-" + (f.id ?? i),
|
||||
pluginId: ${JSON.stringify(pluginId)},
|
||||
latitude: pt.lat,
|
||||
longitude: pt.lon,
|
||||
altitude: pt.alt,
|
||||
timestamp: new Date(),
|
||||
label: f.properties?.${labelField} ?? f.properties?.name ?? undefined,
|
||||
properties: { ...f.properties, _geometryType: f.geometry?.type },
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
destroy() { this._context = null; this._entities = []; }
|
||||
async fetch(_timeRange) { return this._entities; }
|
||||
getPollingInterval() { return 0; }
|
||||
|
||||
getLayerConfig() {
|
||||
return {
|
||||
color: ${JSON.stringify(color)},
|
||||
clusterEnabled: ${clusterEnabled},
|
||||
clusterDistance: ${clusterDistance},
|
||||
maxEntities: ${maxEntities},
|
||||
};
|
||||
}
|
||||
|
||||
renderEntity(_entity) {${renderBlock}
|
||||
}
|
||||
}
|
||||
`;
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
|
||||
interface GlobalsMap {
|
||||
[moduleId: string]: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A Vite/Rollup plugin that resolves shared dependencies to the
|
||||
* `globalThis.__WWV_HOST__` object injected by the core WWV engine.
|
||||
*
|
||||
* This ensures that dynamically loaded CDN plugins inherit the exact
|
||||
* React, Zustand, and Cesium instances of the host application,
|
||||
* eliminating "Invalid Hook Call" and "useCallback" context mismatches.
|
||||
*/
|
||||
export function wwvPluginGlobals(): any {
|
||||
const HOST_MAPPINGS: GlobalsMap = {
|
||||
"react": "React",
|
||||
"react-dom": "ReactDOM",
|
||||
"react/jsx-runtime": "jsxRuntime",
|
||||
"cesium": "Cesium",
|
||||
"resium": "Resium",
|
||||
// zustand is also part of WWVHostGlobals or maybe not? Wait. I should check hostGlobals.ts!
|
||||
"@worldwideview/wwv-plugin-sdk": "WWVPluginSDK",
|
||||
"@/core/state/store": "useStore",
|
||||
"@/core/plugins/PluginManager": "pluginManager",
|
||||
"@/components/video/CameraStream": "CameraStream"
|
||||
};
|
||||
|
||||
return {
|
||||
name: "wwv-plugin-globals",
|
||||
enforce: "pre",
|
||||
resolveId(id: string) {
|
||||
if (id in HOST_MAPPINGS || id === "zustand") {
|
||||
// Ensure Rollup doesn't try to look for these modules in node_modules
|
||||
return "\0" + id;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
load(id: string) {
|
||||
if (!id.startsWith("\0")) return null;
|
||||
const originalId = id.slice(1);
|
||||
|
||||
if (originalId === "react") {
|
||||
return `
|
||||
const React = globalThis.__WWV_HOST__.React;
|
||||
export default React;
|
||||
export const { useState, useEffect, useRef, useMemo, useCallback, useContext, useReducer, useLayoutEffect, StrictMode, Suspense, createContext, createElement, cloneElement, isValidElement, Fragment, Children, Component, PureComponent, createRef, forwardRef, memo, lazy, startTransition, useTransition, useDeferredValue, useId, useSyncExternalStore, useInsertionEffect } = React;
|
||||
`;
|
||||
}
|
||||
if (originalId === "react-dom") {
|
||||
return `
|
||||
const ReactDOM = globalThis.__WWV_HOST__.ReactDOM;
|
||||
export default ReactDOM;
|
||||
export const { createPortal, flushSync } = ReactDOM;
|
||||
`;
|
||||
}
|
||||
if (originalId === "react/jsx-runtime") {
|
||||
return `
|
||||
const jsxRuntime = globalThis.__WWV_HOST__.jsxRuntime;
|
||||
export const jsx = jsxRuntime.jsx;
|
||||
export const jsxs = jsxRuntime.jsxs;
|
||||
export const Fragment = jsxRuntime.Fragment;
|
||||
`;
|
||||
}
|
||||
if (originalId === "cesium") {
|
||||
return `
|
||||
const Cesium = globalThis.__WWV_HOST__.Cesium;
|
||||
export default Cesium;
|
||||
// Export common bindings for direct destructuring
|
||||
export const { Viewer, Entity, Cartesian3, Cartesian2, Color, CallbackProperty, DistanceDisplayCondition, NearFarScalar, HeightReference, Resource, Rectangle, PolygonHierarchy, ClassificationType, ArcType, Math, JulianDate, TimeInterval, TimeIntervalCollection, SampledPositionProperty, GeoJsonDataSource, PinBuilder, CustomDataSource, ConstantProperty, ColorMaterialProperty, Cartographic } = Cesium;
|
||||
`;
|
||||
}
|
||||
if (originalId === "resium") {
|
||||
return `
|
||||
const Resium = globalThis.__WWV_HOST__.Resium;
|
||||
export default Resium;
|
||||
export const { Entity, PointGraphics, BillboardGraphics, CustomDataSource, Camera, PolygonGraphics, PolylineGraphics, EllipseGraphics, LabelGraphics, ModelGraphics, PathGraphics, BoxGraphics, GeoJsonDataSource, ScreenSpaceEventHandler, ScreenSpaceEvent } = Resium;
|
||||
`;
|
||||
}
|
||||
if (originalId === "@worldwideview/wwv-plugin-sdk") {
|
||||
return `
|
||||
const SDK = globalThis.__WWV_HOST__.WWVPluginSDK;
|
||||
export default SDK;
|
||||
export const { WorldPlugin, PluginManifest, createSvgIconUrl, DEFAULT_ICON_SIZE } = SDK;
|
||||
`;
|
||||
}
|
||||
// If zustand is required, wait, is Zustand in host globals?
|
||||
if (originalId === "zustand") {
|
||||
return `
|
||||
if (!globalThis.__WWV_HOST__.zustand) {
|
||||
console.warn("zustand was not found on WWV_HOST");
|
||||
}
|
||||
const zustand = globalThis.__WWV_HOST__.zustand || {};
|
||||
export default zustand;
|
||||
export const { create, createStore, useStore } = zustand;
|
||||
`;
|
||||
}
|
||||
if (originalId === "@/core/state/store") {
|
||||
return `export const useStore = globalThis.__WWV_HOST__.useStore;`;
|
||||
}
|
||||
if (originalId === "@/core/plugins/PluginManager") {
|
||||
return `export const pluginManager = globalThis.__WWV_HOST__.pluginManager;`;
|
||||
}
|
||||
if (originalId === "@/components/video/CameraStream") {
|
||||
return `export const CameraStream = globalThis.__WWV_HOST__.CameraStream;`;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"noEmit": false,
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"outDir": "dist",
|
||||
"module": "commonjs",
|
||||
"moduleResolution": "node"
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.tsx"]
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2017",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"isolatedModules": true,
|
||||
"resolveJsonModule": true
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.tsx"]
|
||||
}
|
||||
Generated
+7439
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,3 @@
|
||||
packages:
|
||||
- 'packages/*'
|
||||
- 'packages/*/backend'
|
||||
@@ -0,0 +1,35 @@
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
let dbUrl = process.env.DATABASE_URL;
|
||||
|
||||
if (!dbUrl) {
|
||||
try {
|
||||
const envLocalPath = path.resolve(process.cwd(), ".env.local");
|
||||
if (fs.existsSync(envLocalPath)) {
|
||||
const envContent = fs.readFileSync(envLocalPath, "utf8");
|
||||
const match = envContent.match(/^DATABASE_URL=["']?(.*?)["']?$/m);
|
||||
if (match) {
|
||||
dbUrl = match[1].trim();
|
||||
}
|
||||
}
|
||||
if (!dbUrl) {
|
||||
const envPath = path.resolve(process.cwd(), ".env");
|
||||
if (fs.existsSync(envPath)) {
|
||||
const envContent = fs.readFileSync(envPath, "utf8");
|
||||
const match = envContent.match(/^DATABASE_URL=["']?(.*?)["']?$/m);
|
||||
if (match) {
|
||||
dbUrl = match[1].trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// Ignore
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
datasource: {
|
||||
url: dbUrl,
|
||||
},
|
||||
};
|
||||
Loaded 100 of 528 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user