Compare commits

..
Author SHA1 Message Date
Antigravity AI 461944271b Resolve merge conflicts with main 2026-05-10 11:28:49 +12:00
dependabot[bot] 0b64459cfe build(deps): bump the dependencies group with 17 updates (#73)
Bumps the dependencies group with 17 updates:

| Package | From | To |
| --- | --- | --- |
| [@auth/prisma-adapter](https://github.com/nextauthjs/next-auth) | `2.11.1` | `2.11.2` |
| [@prisma/adapter-pg](https://github.com/prisma/prisma/tree/HEAD/packages/adapter-pg) | `7.6.0` | `7.8.0` |
| [@prisma/client](https://github.com/prisma/prisma/tree/HEAD/packages/client) | `7.6.0` | `7.8.0` |
| [@prisma/client-runtime-utils](https://github.com/prisma/prisma/tree/HEAD/packages/client-runtime-utils) | `7.6.0` | `7.8.0` |
| [@sentry/nextjs](https://github.com/getsentry/sentry-javascript) | `10.48.0` | `10.52.0` |
| [@supabase/supabase-js](https://github.com/supabase/supabase-js/tree/HEAD/packages/core/supabase-js) | `2.100.1` | `2.105.4` |
| [cesium](https://github.com/CesiumGS/cesium) | `1.139.1` | `1.141.0` |
| [hls.js](https://github.com/video-dev/hls.js) | `1.6.15` | `1.6.16` |
| [jose](https://github.com/panva/jose) | `6.2.2` | `6.2.3` |
| [next](https://github.com/vercel/next.js) | `16.2.3` | `16.2.6` |
| [prisma](https://github.com/prisma/prisma/tree/HEAD/packages/cli) | `7.6.0` | `7.8.0` |
| [react](https://github.com/facebook/react/tree/HEAD/packages/react) | `19.2.3` | `19.2.6` |
| [react-dom](https://github.com/facebook/react/tree/HEAD/packages/react-dom) | `19.2.3` | `19.2.6` |
| [resium](https://github.com/reearth/resium) | `1.19.4` | `1.21.0` |
| [zustand](https://github.com/pmndrs/zustand) | `5.0.12` | `5.0.13` |
| [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) | `8.0.8` | `8.0.11` |
| [vitest](https://github.com/vitest-dev/vitest/tree/HEAD/packages/vitest) | `4.1.2` | `4.1.5` |


Updates `@auth/prisma-adapter` from 2.11.1 to 2.11.2
- [Release notes](https://github.com/nextauthjs/next-auth/releases)
- [Commits](https://github.com/nextauthjs/next-auth/compare/@auth/[email protected]...@auth/[email protected])

Updates `@prisma/adapter-pg` from 7.6.0 to 7.8.0
- [Release notes](https://github.com/prisma/prisma/releases)
- [Commits](https://github.com/prisma/prisma/commits/7.8.0/packages/adapter-pg)

Updates `@prisma/client` from 7.6.0 to 7.8.0
- [Release notes](https://github.com/prisma/prisma/releases)
- [Commits](https://github.com/prisma/prisma/commits/7.8.0/packages/client)

Updates `@prisma/client-runtime-utils` from 7.6.0 to 7.8.0
- [Release notes](https://github.com/prisma/prisma/releases)
- [Commits](https://github.com/prisma/prisma/commits/7.8.0/packages/client-runtime-utils)

Updates `@sentry/nextjs` from 10.48.0 to 10.52.0
- [Release notes](https://github.com/getsentry/sentry-javascript/releases)
- [Changelog](https://github.com/getsentry/sentry-javascript/blob/develop/CHANGELOG.md)
- [Commits](https://github.com/getsentry/sentry-javascript/compare/10.48.0...10.52.0)

Updates `@supabase/supabase-js` from 2.100.1 to 2.105.4
- [Release notes](https://github.com/supabase/supabase-js/releases)
- [Changelog](https://github.com/supabase/supabase-js/blob/develop/packages/core/supabase-js/CHANGELOG.md)
- [Commits](https://github.com/supabase/supabase-js/commits/v2.105.4/packages/core/supabase-js)

Updates `cesium` from 1.139.1 to 1.141.0
- [Release notes](https://github.com/CesiumGS/cesium/releases)
- [Changelog](https://github.com/CesiumGS/cesium/blob/main/CHANGES.md)
- [Commits](https://github.com/CesiumGS/cesium/compare/1.139.1...1.141)

Updates `hls.js` from 1.6.15 to 1.6.16
- [Release notes](https://github.com/video-dev/hls.js/releases)
- [Changelog](https://github.com/video-dev/hls.js/blob/master/docs/release-process.md)
- [Commits](https://github.com/video-dev/hls.js/compare/v1.6.15...v1.6.16)

Updates `jose` from 6.2.2 to 6.2.3
- [Release notes](https://github.com/panva/jose/releases)
- [Changelog](https://github.com/panva/jose/blob/main/CHANGELOG.md)
- [Commits](https://github.com/panva/jose/compare/v6.2.2...v6.2.3)

Updates `next` from 16.2.3 to 16.2.6
- [Release notes](https://github.com/vercel/next.js/releases)
- [Changelog](https://github.com/vercel/next.js/blob/canary/release.js)
- [Commits](https://github.com/vercel/next.js/compare/v16.2.3...v16.2.6)

Updates `prisma` from 7.6.0 to 7.8.0
- [Release notes](https://github.com/prisma/prisma/releases)
- [Commits](https://github.com/prisma/prisma/commits/7.8.0/packages/cli)

Updates `react` from 19.2.3 to 19.2.6
- [Release notes](https://github.com/facebook/react/releases)
- [Changelog](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [Commits](https://github.com/facebook/react/commits/v19.2.6/packages/react)

Updates `react-dom` from 19.2.3 to 19.2.6
- [Release notes](https://github.com/facebook/react/releases)
- [Changelog](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [Commits](https://github.com/facebook/react/commits/v19.2.6/packages/react-dom)

Updates `resium` from 1.19.4 to 1.21.0
- [Release notes](https://github.com/reearth/resium/releases)
- [Changelog](https://github.com/reearth/resium/blob/main/CHANGELOG.md)
- [Commits](https://github.com/reearth/resium/compare/v1.19.4...v1.21.0)

Updates `zustand` from 5.0.12 to 5.0.13
- [Release notes](https://github.com/pmndrs/zustand/releases)
- [Commits](https://github.com/pmndrs/zustand/compare/v5.0.12...v5.0.13)

Updates `vite` from 8.0.8 to 8.0.11
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v8.0.11/packages/vite)

Updates `vitest` from 4.1.2 to 4.1.5
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.5/packages/vitest)

---
updated-dependencies:
- dependency-name: "@auth/prisma-adapter"
  dependency-version: 2.11.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: "@prisma/adapter-pg"
  dependency-version: 7.8.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: "@prisma/client"
  dependency-version: 7.8.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: "@prisma/client-runtime-utils"
  dependency-version: 7.8.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: "@sentry/nextjs"
  dependency-version: 10.52.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: "@supabase/supabase-js"
  dependency-version: 2.105.4
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: cesium
  dependency-version: 1.141.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: hls.js
  dependency-version: 1.6.16
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: jose
  dependency-version: 6.2.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: next
  dependency-version: 16.2.6
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: prisma
  dependency-version: 7.8.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: react
  dependency-version: 19.2.6
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: react-dom
  dependency-version: 19.2.6
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: resium
  dependency-version: 1.21.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: zustand
  dependency-version: 5.0.13
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: vite
  dependency-version: 8.0.11
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: vitest
  dependency-version: 4.1.5
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dependencies
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-10 11:10:16 +12:00
dependabot[bot] e917caf7f1 build(deps): bump docker/setup-buildx-action from 3 to 4 (#72)
Bumps [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action) from 3 to 4.
- [Release notes](https://github.com/docker/setup-buildx-action/releases)
- [Commits](https://github.com/docker/setup-buildx-action/compare/v3...v4)

---
updated-dependencies:
- dependency-name: docker/setup-buildx-action
  dependency-version: '4'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-10 11:10:11 +12:00
dependabot[bot] 6730aaff13 build(deps): bump actions/setup-node from 4 to 6 (#71)
Bumps [actions/setup-node](https://github.com/actions/setup-node) from 4 to 6.
- [Release notes](https://github.com/actions/setup-node/releases)
- [Commits](https://github.com/actions/setup-node/compare/v4...v6)

---
updated-dependencies:
- dependency-name: actions/setup-node
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-10 11:10:07 +12:00
dependabot[bot] 7c1fce98bd build(deps): bump actions/checkout from 4 to 6 (#70)
Bumps [actions/checkout](https://github.com/actions/checkout) from 4 to 6.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v4...v6)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-10 11:10:02 +12:00
GodisDeadxandnullptr 30bee799e1 modified: .gitignore (#65)
modified:   AGENTS.md
	modified:   package.json
	modified:   public/cesium/ThirdParty/zip-module.wasm
	new file:   src/components/layout/ApiKeysTab.tsx
	modified:   src/components/layout/Header.tsx
	modified:   src/components/panels/DataConfig/OverlayTab.tsx
	modified:   src/components/panels/DataConfig/index.tsx
	modified:   src/components/panels/LayerPanel.tsx
	modified:   src/components/panels/PluginsTab.css
	modified:   src/components/panels/PluginsTab.tsx

Co-authored-by: nullptr <[email protected]>
2026-05-10 11:06:55 +12:00
031a073cf9 fix(plugins): surface NEXT_PUBLIC_WWV_PLUGIN_* vars to plugin context (#60)
`PluginManager.registerPlugin` builds `ctx.env` for each plugin by iterating
`Object.entries(process.env)` and copying entries whose keys start with
`NEXT_PUBLIC_WWV_PLUGIN_`. In the browser bundle this loop comes back
empty even when those vars are set at build time, because Next.js only
inlines `process.env.NEXT_PUBLIC_*` at *static reference sites* — and
`Object.entries(process.env)` isn't a static reference. The result: any
plugin reading `ctx.env.SOMETHING` to override a default URL silently
gets `undefined` and falls back to its hardcoded cloud URL.

Concrete impact: setting `NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL` to a
self-hosted data-engine URL has no effect on the marketplace plugins that
read `ctx.env.DATA_ENGINE_URL` (e.g. `wwv-plugin-aviation`) — they keep
calling `https://dataengine.worldwideview.dev/data/...` even when the
operator has explicitly redirected away from it.

Add explicit static references so the values land in `envVars`. Done as
a small allow-list (currently just `DATA_ENGINE_URL`) so adding new keys
is one line.

Also declare `ARG NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL` in the
Dockerfile next to the existing public-arg block. Without it, the build
arg passed in via compose isn't visible to Next.js at build time, so
Webpack inlines `undefined` even when the operator sets the env var.

Co-authored-by: Sapphire <sapphire@tiktokcoach>
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
2026-05-10 11:02:56 +12:00
43d6a057ba feat(analytics): make first-party analytics opt-in (default off) (#57)
The hosted Umami beacon at analytics.worldwideview.dev/script.js is
loaded unconditionally from src/app/layout.tsx, so every self-hosted
instance (anyone running this from GitHub) phones page-view and event
data home to the maintainer's analytics server. There is no env var,
no docs note, and no opt-out — operators discover the call only by
inspecting their browser's network tab.

Self-hosting is the default audience for an open-source project
distributed on GitHub. Defaulting telemetry on for that audience
silently routes their usage data to a third party they didn't choose
to send it to. Privacy posture aside, it's a surprise.

Gate the Umami script tag behind NEXT_PUBLIC_WWV_ANALYTICS === "true".
Default off — the maintainer's own hosted deployment can flip it on
explicitly via build env, status quo for that environment. Self-hosters
get no analytics by default and can opt in if they choose to.

This does not remove the integration, change Umami's website-id, or
alter the CSP allow-list. It only makes the script-tag conditional.

Co-authored-by: Sapphire <sapphire@tiktokcoach>
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
2026-05-10 11:02:51 +12:00
9c03edb65c feat(build): warn when NEXT_PUBLIC_CESIUM_ION_TOKEN is missing at build time (#55)
Self-hosters who skip Cesium Ion token setup get a globe that boots fine,
then 401s on world terrain and base imagery from `api.cesium.com`. The
cause is invisible — Cesium ships a default Ion token inside its npm
package that they periodically revoke when usage spikes — and most users
don't realize the build inlined an empty `NEXT_PUBLIC_CESIUM_ION_TOKEN`
until they're staring at network logs.

Add a `prebuild` step that prints an actionable warning (token name,
why it matters, where to get a free one) when the var is missing, so
the gap is surfaced when it can still be fixed cheaply. Non-fatal —
build continues — because demo and existing setups may legitimately
rely on the bundled default until it stops working for them.

Co-authored-by: Sapphire <sapphire@tiktokcoach>
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
2026-05-10 11:02:45 +12:00
9f1f39203e fix(proxy): detect secure cookie when behind TLS-terminating reverse proxy (#54)
When self-hosted behind a reverse proxy that terminates TLS (e.g. Caddy,
Nginx, Traefik), Auth.js sets the session cookie with the `__Secure-`
prefix because the public URL is https. The middleware's `getToken()` call,
however, sees a plain-http request internally and its auto-detection looks
for the unprefixed cookie name — which never exists — so authenticated
users are infinite-looped back to /login.

Detect the public scheme via X-Forwarded-Proto, AUTH_URL/NEXTAUTH_URL, or
the request URL's own protocol, and pass `secureCookie` explicitly to
getToken().

Co-authored-by: Sapphire <sapphire@tiktokcoach>
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
2026-05-10 11:02:40 +12:00
9b459206d6 feat(camera): auto-refresh JPEG/MJPEG snapshot sources (#61)
Most state DOTs (NCDOT, WSDOT, GDOT, fallback HLS-failure paths from
Caltrans/511NY) serve traffic cameras as JPEG snapshots that update
server-side every 5–30 seconds rather than as continuous video streams.
The current `<img src={resolvedUrl}>` in `CameraStream.tsx` renders the
URL once and the browser caches the result — so the camera "loads" then
freezes on the first frame, which reads as broken even when the source
is fine.

Add a cache-busted refresh tick that increments every 10s while the
stream is playing and an image source is active. Skipped for HLS, iframe,
and known video platforms (they manage their own playback). Interval is
cleared when the stream stops, so no leaks on tab switch / pop-out.

The bumped query param is namespaced (`_t=`) and appended with the
correct separator depending on whether the source URL already has query
params (NCDOT's `?filename=...` pattern in particular).

Co-authored-by: Sapphire <sapphire@tiktokcoach>
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Co-authored-by: Silvertakana <[email protected]>
2026-05-10 11:01:50 +12:00
cd44a41c5d refactor(api/camera): adapter pattern + registry + selectable sources (#62)
The five existing camera fetchers (Caltrans, GDOT, TfL — and 511NY +
WSDOT, here introduced as adapters) follow the same shape — fetch from
upstream, normalize, return GeoJSON features — but each one is wired up
by hand: a fetcher file, often a route file, plus an entry in
`traffic/route.ts`'s `Promise.allSettled` block. Adding a new source
required surgery in three places, the shared type was named after the
first adapter (`GdotCameraFeature`), and the aggregator was take-it-or-
leave-it (no way to ask for a subset).

This PR introduces a small adapter pattern:

- `adapters/types.ts` defines `CameraFeature` (replacing the old
  `GdotCameraFeature` alias) and a `CameraAdapter` interface.
- `adapters/registry.ts` collects all adapters, manages per-adapter
  caching with overridable TTL, exposes `getAdapterMetadata()` for
  client-side discovery, and provides `fetchManyAdapters(ids)` for
  selective merging.
- `adapters/{caltrans,gdot,tfl,ny511,wsdot}.ts` are thin wrappers
  around the existing fetcher functions. The GDOT adapter additionally
  filters out URLs from the retired `navigator-c2c.dot.ga.gov` and
  `vss5live.dot.ga.gov` hosts so clients don't ERR_NAME_NOT_RESOLVED
  on click.
- 511NY (`/data/getcameras`, ~1,500 enabled cams w/ HLS) and WSDOT
  (`/HighwayCameras/.../GetCamerasAsJson`, ~1,600 cams + ~70 ODOT
  border crossings) are introduced here. WSDOT requires a key
  (`WSDOT_API_KEY`); the adapter declares this so the client can
  surface a "needs key, sign up here" hint.
- `traffic/route.ts` reads from the registry and accepts `?sources=`
  (comma-separated ids, "all", or "none"). Default behavior with no
  query is unchanged — all adapters merge — so existing clients
  continue working without modification.
- New `list/route.ts` returns adapter metadata for client-side source
  pickers (settings UIs that render dynamic checkboxes per source,
  including health/key-required state).
- Old `gdot/route.ts` removed (subsumed by the registry); the matching
  `gdotFetcher.ts` is retained so adapters can `import` from it.

After this lands, adding a new state's DOT to the system is one new
file in `adapters/` plus one line in `registry.ts`. No more
`traffic/route.ts` edits, no merge conflicts when two source PRs are
in flight, no plugin updates required (clients pick up new sources via
`/list`).

Supersedes the standalone 511NY (#58) and WSDOT (#59) PRs, which I've
closed; their fetchers and adapters land here as part of the cohesive
restructure.

Co-authored-by: Sapphire <sapphire@tiktokcoach>
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
2026-05-10 11:00:08 +12:00
dependabot[bot] 82cc79fa45 build(deps): bump node from 22-alpine to 26-alpine (#69)
Bumps node from 22-alpine to 26-alpine.

---
updated-dependencies:
- dependency-name: node
  dependency-version: 26-alpine
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-10 10:57:40 +12:00
dependabot[bot] fdc722de51 build(deps): bump pnpm/action-setup from 4 to 6 (#68)
Bumps [pnpm/action-setup](https://github.com/pnpm/action-setup) from 4 to 6.
- [Release notes](https://github.com/pnpm/action-setup/releases)
- [Commits](https://github.com/pnpm/action-setup/compare/v4...v6)

---
updated-dependencies:
- dependency-name: pnpm/action-setup
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-10 10:57:35 +12:00
dependabot[bot] be692fadaa build(deps): bump docker/metadata-action from 5 to 6 (#67)
Bumps [docker/metadata-action](https://github.com/docker/metadata-action) from 5 to 6.
- [Release notes](https://github.com/docker/metadata-action/releases)
- [Commits](https://github.com/docker/metadata-action/compare/v5...v6)

---
updated-dependencies:
- dependency-name: docker/metadata-action
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-10 10:57:30 +12:00
Silvertakana eb12866d03 Configure Dependabot for multiple ecosystems
Added configurations for npm, Docker, and GitHub Actions updates.
2026-05-10 10:49:31 +12:00
Silvertakana c279b7c3d1 Revise SECURITY.md with support versions and reporting (#66)
Updated the security policy to include supported versions and reporting guidelines.
2026-05-10 10:46:03 +12:00
Antigravity AI b6d14dd720 docs(readme): enhance README with standard badges and architecture overview
- docs: added CI, Codecov, NPM, and Discord badges
- docs: added mermaid project architecture diagram
- docs: added key features, structure tree, and prerequisites
- chore: relocated old plan documents to .agents/plans
2026-05-10 10:30:57 +12:00
Antigravity AI 72f485f405 docs(agents): track all remaining agent rules 2026-05-10 10:14:29 +12:00
Antigravity AI 8f82310e3d docs(agents): update gitignore and add coding principles rule 2026-05-10 10:04:15 +12:00
Antigravity AI 3fe9edf6f3 checkout: temporary commit for worktree checkout 2026-05-10 09:51:44 +12:00
Antigravity AI 0156ead243 fix(deployment): resolve stale image issues and legacy migration commands
- Bump version to 2.1.6
- fix: update setup scripts to pull latest image before starting
- fix: set pull_policy to always in self-host compose file
- fix: auto-detect compose container for legacy migration script in setup UI
2026-05-10 01:20:22 +12:00
Antigravity AI 7bd6b32121 refactor: change default legacy DB path to data/wwv.db 2026-05-10 00:41:08 +12:00
Antigravity AI bc10b09788 fix: resolve undefined ID error when migrating settings from legacy SQLite 2026-05-10 00:40:29 +12:00
Antigravity AI 45c41fd2a0 refactor: update setup scripts to download docker-compose.yml and .env.example 2026-05-10 00:34:26 +12:00
Antigravity AI 78fb1dc484 fix(core): update legacy migration script and Dockerfile for Prisma 7 [Patch]
- fix migrate-legacy.mjs to use explicit pg adapter and accept db path arg [Patch]

- copy migrate-legacy.mjs to final docker image [Patch]
2026-05-10 00:06:33 +12:00
Antigravity AI 5fb36069ac fix(core): migrate changes and resolve cors issues [Patch]
- fix marketplace CORS by allowing x-marketplace-ping header [Patch]

- update setup page and docker entrypoint for legacy migrations [Patch]
2026-05-09 23:30:18 +12:00
Silvertakana c4207bd6e1 feat(core): migrate to Prisma 7 and unify PostgreSQL architecture (#56)
* feat(cloud): implement Postgres DB adapter, fix static build crashes, and containerize NextAuth/Stripe integrations

* test(marketplace): fix mocks and assertions for multi-tenant Postgres architecture

* feat: rsa jwt license key verification and state integration

* feat: add internal workspace validation route for Edge Functions

* refactor: clean up hub routes and finalize db proxy/adapter for multi-tenant cloud deploy

* feat(cloud): finalize multi-tenant Prisma extensions and workspace routing

* fix(db): correct Prisma 7 better-sqlite3 adapter initialization [Patch]

- update better-sqlite3 adapter instantiation to use configuration object ({ url }) required by Prisma 7 instead of raw Database instance [Patch]
- fix PrismaClientConstructorValidationError by generating client with adapter support [Patch]

* fix(auth): support dynamic origins for local proxies and multi-tenant subdomains [Patch]

- prioritize forwarded headers and request host over hardcoded envOrigin in getRequestOrigin to support subdomain routing [Patch]
- allow ALLOWED_DEV_ORIGIN in marketplace install redirect checks to fix local network development login flows [Patch]

* fix(marketplace): enable dynamic CORS reflection for marketplace API [Patch]

- remove explicit origin array, replacing with origin header reflection to allow marketplace hosted on any domain or local IP [Patch]

- remove global wildcard CORS headers from next.config.ts to harden security against broader app injection [Patch]

* feat(db): create initial postgresql migration

* refactor(db): update remaining files for postgresql

* feat(db): unify database adapter to PostgreSQL-only [Minor]

- replace SQLite adapter with PostgreSQL PrismaPg [Minor]
- remove better-sqlite3 dependencies [Patch]
- finalize docs and implementation plan [Patch]

* fix: resolve prisma client generation and script execution issues with tsx and type module

* feat(db): port tenant isolation logic to new PostgreSQL adapter

* docs: add rule for transparent and narrated agent actions

* BREAKING CHANGE(core): migrate to PostgreSQL and add auto-migration pipeline [Major]

- unified database adapter to exclusively use PostgreSQL [Major]
- implement auto-migration pipeline to pipe legacy SQLite data to Postgres [Major]
- add sqlite to runner stage to support extraction pipeline [Patch]

* feat(core): migrate to Prisma 7 and unify PostgreSQL architecture [Minor]

- removed legacy Prisma SQLite driver and all Better-Sqlite dependencies [Minor]
- updated schema to utilize purely postgresql providers [Patch]
- modified migration scripts to seamlessly convert local sqlite DBs to PostgreSQL containers using keinos/sqlite3 [Minor]
- updated deployment scripts, Coolify pipelines, and Nginx proxy support [Patch]
- injected Prisma Client Extensions for multi-tenant Row Level Security isolation [Minor]
- stabilized PrismaClient initialization utilizing the official adapter-pg runtime pattern [Patch]
- bumped version to 2.1.0

* fix(core): resolve TypeScript compilation errors for CI [Patch]

- fixed NextResponse.json() 3-arg calls to use 2-arg ResponseInit form [Patch]
- replaced invalid 'developer' TrustTier with 'unverified' in parseWwvManifest and load-unpacked route [Patch]
- removed non-existent pluginManager.hotReload() call in DevModeSubscriber, replaced with disable/reload cycle [Patch]
- updated Stripe API version from '2024-04-10' to '2026-04-22.dahlia' to match installed SDK [Patch]
- excluded local-scripts/ from tsconfig to prevent debug scripts from breaking CI [Patch]

* fix(ci): resolve pnpm version conflict in GitHub Actions [Patch]

- removed explicit version: 9 from pnpm/action-setup@v4 — v4 auto-reads packageManager from package.json [Patch]
- updated build job DATABASE_URL from SQLite to PostgreSQL format [Patch]

* fix(docker): add explicit Prisma generator output path for Docker builds [Patch]

- Prisma 7 changed default output location, causing COPY --from=builder to fail
- added output = '../src/generated/prisma' to generator block for consistency

* fix(prisma): update client import path and resolve CI type errors [Patch]

- updated PrismaClient import in db.ts to point to custom generated output path
- resolved implicit 'any' error in marketplace check-updates route
- verified clean local build with tsc --noEmit

* chore(deps): sync Prisma versions to 7.6.0 [Patch]
2026-05-09 22:44:30 +12:00
Antigravity AI 9ae8e58380 fix(core): allow universal CORS access in marketplace [Patch]
- allow any origin in marketplace bridge to ensure universal connectivity [Patch]
- remove dead origin filter code [Patch]
- bump version to 1.20.5 [Patch]
2026-05-09 15:45:33 +12:00
Antigravity AI 91e09ff53a fix(core): install prisma globally in docker to prevent offline network failures [Patch] 2026-05-09 15:39:24 +12:00
77 changed files with 2732 additions and 1418 deletions

No files matched your search

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