Compare commits

..
Author SHA1 Message Date
Antigravity AIandClaude Sonnet 4.6 7cd85e085c test(ws): pin Math.random to 0 so reconnect backoff test is deterministic
With jitter (Math.random()*4000), advancing timers by exactly 5000ms no
longer guaranteed to trigger the reconnect. Mocking Math.random to 0 in
beforeEach makes the delay deterministic (base only, no jitter) across
the full test suite.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-05-21 00:43:52 +12:00
Antigravity AIandClaude Opus 4.7 ccd0e7af78 fix(ws): exponential backoff + jitter on WsClient reconnect
Replaces the fixed 5-second reconnect delay with an exponential backoff
(5s→10s→20s→40s→60s cap, +4s random jitter) so simultaneous browser
sessions don't thunder-herd the engine on restart.

- Backoff resets only after a stable 5-second connection, not on every
  successful open, so rapid reconnect cycles don't mask the retry.
- Stale-timer bookkeeping added to the cleanup/unsubscribe path.

Also bundles two companion fixes discovered during the same session:

fix(scripts): BOM-safe JSON parsing in sync/watch-local-plugins (Fix)
  PowerShell 5.1 emits a UTF-8 BOM that Node's JSON.parse rejects;
  readJsonFile() strips U+FEFF before parsing, matching pnpm behavior.

docs(agents): add UTF-8 BOM troubleshooting entry (Fix)
  Documents diagnosis, fix, and prevention for the BOM crash.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-05-21 00:40:04 +12:00
SilvertakanaandClaude Sonnet 4.6 58aac77a0b fix(engine): resolve plugin 404s and local engine routing (#166)
* refactor(marketplace): drive auto-seeding from signed verified registry

Retires the hard-coded DEFAULT_PLUGIN_IDS list and makes the signed
verified registry the single source of truth for what lands in a fresh
install. Publishing a plugin to the verified registry now auto-seeds
it; no code change required to add new defaults.

Also fixes the diagnosed plugins-404: fortiguard and nz-traffic-cameras
were in the static list but not published to npm, causing every fresh
boot to hit manifest 404s. Those entries are gone with the list.

- Delete src/lib/marketplace/defaultPlugins.ts (legacy static list).
- Seeder iterates getVerifiedPluginIds() from registryClient.
- Skip markSeeded when the verified set is empty so a registry outage
  doesn't lock fresh installs into zero plugins; the next request
  retries (5-min cache in registryClient bounds the request rate).
- Stamp every seeded plugin as trust=verified by definition.
- Tests rewritten against a fake verified set; new test asserts
  empty-registry deferral.
- Sync marketplace-architecture rule + migrate-legacy-plugin skill
  with the new model.
- Patch bump: 2.15.15 -> 2.15.16.

* fix(engine): resolve plugin 404s and local engine routing (#fix/diagnose-plugins-404)

- fix: engineManifest + resolveEngineUrl: port 5001→5000 to match docker-compose
  binding; removed NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL from local engine
  detection — it was poisoning local routing with the production engine URL (Patch)
- fix: WsClient: added normalizePluginId() converting underscore IDs to kebab-case
  so engine WebSocket messages route to the correct frontend plugin (Patch)
- fix: docker-compose: added ./local-seeders:/app/seeders volume mount to
  wwv-data-engine so locally-developed seeders are visible to the engine (Patch)
- feat: sync-local-plugins: added wwvHostRedirectPlugin — Vite plugin that
  intercepts @/ host-app imports in local plugin builds and redirects them to
  runtime host globals, preventing full app tree from being bundled into plugins (Minor)
- docs: plugin-architecture.md: added Plugin Data Delivery Types section (REST-only,
  WS-only, hybrid), peerDependencies rule, .tsx extension rule, mapWebsocketPayload
  signature contract (Patch)
- docs: data-engine-architecture.md: added §7 WebSocket Payload Format Contract
  documenting WsClient's three payload handling cases and the silent-drop footgun
  for plugins that send object payloads without mapWebsocketPayload (Patch)
- docs: worldwideview-plugin-creation SKILL.md: fixed ISS example which was missing
  mapWebsocketPayload and would have silently dropped all WS data; clarified
  mapWebsocketPayload requirement for non-array payloads; fixed architecture
  decision tree (Patch)
- docs: cesium-rendering.md: added Sizing Conventions table with defaults/ranges
  for point/billboard/model, cross-plugin parity rules, and silent-ignore footgun
  warning for size on billboard entities (Patch)
- docs: added ADR-0002 documenting seeder exported name as canonical plugin ID (Patch)

Version bumps: fix × 3 (Patch), feat × 1 (Minor) → 2.15.16 → 2.16.0

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* test(engine): update resolveEngineUrl test assertion from port 5001 to 5000

Follows the port correction in engineManifest.ts and resolveEngineUrl.ts.
The test was asserting the old default (5001) instead of the corrected
local engine port (5000), causing the Unit Tests CI check to fail.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

---------

Co-authored-by: Claude Sonnet 4.6 <[email protected]>
2026-05-20 22:44:47 +12:00
dependabot[bot] 0462ab1f88 build(deps-dev): bump @vitejs/plugin-react from 5.2.0 to 6.0.2
Bumps [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) from 5.2.0 to 6.0.2.
- [Release notes](https://github.com/vitejs/vite-plugin-react/releases)
- [Changelog](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite-plugin-react/commits/[email protected]/packages/plugin-react)

---
updated-dependencies:
- dependency-name: "@vitejs/plugin-react"
  dependency-version: 6.0.2
  dependency-type: direct:development
  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-20 21:18:07 +12:00
dependabot[bot] 60fca4d540 build(deps-dev): bump @types/node from 20.19.41 to 25.9.1
Bumps [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) from 20.19.41 to 25.9.1.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

---
updated-dependencies:
- dependency-name: "@types/node"
  dependency-version: 25.9.0
  dependency-type: direct:development
  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-20 21:17:37 +12:00
dependabot[bot] dba5d49448 build(deps): bump commander from 12.1.0 to 14.0.3
Bumps [commander](https://github.com/tj/commander.js) from 12.1.0 to 14.0.3.
- [Release notes](https://github.com/tj/commander.js/releases)
- [Changelog](https://github.com/tj/commander.js/blob/master/CHANGELOG.md)
- [Commits](https://github.com/tj/commander.js/compare/v12.1.0...v14.0.3)

---
updated-dependencies:
- dependency-name: commander
  dependency-version: 14.0.3
  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-20 21:13:39 +12:00
dependabot[bot] 1633c7bb7b build(deps): bump the dependencies group with 11 updates (#161)
Bumps the dependencies group with 11 updates:

| Package | From | To |
| --- | --- | --- |
| [@sentry/nextjs](https://github.com/getsentry/sentry-javascript) | `10.52.0` | `10.53.1` |
| [@supabase/supabase-js](https://github.com/supabase/supabase-js/tree/HEAD/packages/core/supabase-js) | `2.105.4` | `2.106.0` |
| [lucide-react](https://github.com/lucide-icons/lucide/tree/HEAD/packages/lucide-react) | `1.14.0` | `1.16.0` |
| [pg](https://github.com/brianc/node-postgres/tree/HEAD/packages/pg) | `8.20.0` | `8.21.0` |
| [resium](https://github.com/reearth/resium) | `1.21.0` | `1.21.1` |
| [satellite.js](https://github.com/shashwatak/satellite-js) | `7.0.0` | `7.0.1` |
| [undici](https://github.com/nodejs/undici) | `8.2.0` | `8.3.0` |
| [@typescript-eslint/eslint-plugin](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/eslint-plugin) | `8.59.3` | `8.59.4` |
| [@typescript-eslint/parser](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/parser) | `8.59.3` | `8.59.4` |
| [tsx](https://github.com/privatenumber/tsx) | `4.21.0` | `4.22.2` |
| [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) | `8.0.12` | `8.0.13` |


Updates `@sentry/nextjs` from 10.52.0 to 10.53.1
- [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.52.0...10.53.1)

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

Updates `lucide-react` from 1.14.0 to 1.16.0
- [Release notes](https://github.com/lucide-icons/lucide/releases)
- [Commits](https://github.com/lucide-icons/lucide/commits/1.16.0/packages/lucide-react)

Updates `pg` from 8.20.0 to 8.21.0
- [Changelog](https://github.com/brianc/node-postgres/blob/master/CHANGELOG.md)
- [Commits](https://github.com/brianc/node-postgres/commits/[email protected]/packages/pg)

Updates `resium` from 1.21.0 to 1.21.1
- [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.21.0...v1.21.1)

Updates `satellite.js` from 7.0.0 to 7.0.1
- [Release notes](https://github.com/shashwatak/satellite-js/releases)
- [Changelog](https://github.com/shashwatak/satellite-js/blob/develop/CHANGELOG.md)
- [Commits](https://github.com/shashwatak/satellite-js/compare/7.0.0...7.0.1)

Updates `undici` from 8.2.0 to 8.3.0
- [Release notes](https://github.com/nodejs/undici/releases)
- [Commits](https://github.com/nodejs/undici/compare/v8.2.0...v8.3.0)

Updates `@typescript-eslint/eslint-plugin` from 8.59.3 to 8.59.4
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.59.4/packages/eslint-plugin)

Updates `@typescript-eslint/parser` from 8.59.3 to 8.59.4
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/parser/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.59.4/packages/parser)

Updates `tsx` from 4.21.0 to 4.22.2
- [Release notes](https://github.com/privatenumber/tsx/releases)
- [Changelog](https://github.com/privatenumber/tsx/blob/master/release.config.cjs)
- [Commits](https://github.com/privatenumber/tsx/compare/v4.21.0...v4.22.2)

Updates `vite` from 8.0.12 to 8.0.13
- [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.13/packages/vite)

---
updated-dependencies:
- dependency-name: "@sentry/nextjs"
  dependency-version: 10.53.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: "@supabase/supabase-js"
  dependency-version: 2.106.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: lucide-react
  dependency-version: 1.16.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: pg
  dependency-version: 8.21.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: resium
  dependency-version: 1.21.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: satellite.js
  dependency-version: 7.0.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: undici
  dependency-version: 8.3.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: "@typescript-eslint/eslint-plugin"
  dependency-version: 8.59.4
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: "@typescript-eslint/parser"
  dependency-version: 8.59.4
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: tsx
  dependency-version: 4.22.2
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: vite
  dependency-version: 8.0.13
  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-20 21:04:04 +12:00
SilvertakanaandClaude Sonnet 4.6 7eda6c50a4 fix: disable Firefox MSAA/AT-SPI to fix CI hangs (#165)
* fix: disable Firefox MSAA/AT-SPI accessibility on CI to prevent hangs

Adds `accessibility.force_disabled: 1` to Firefox's user prefs in the
Playwright config. On Linux CI (GitHub Actions / ubuntu-latest) Firefox
attempts to connect to the AT-SPI accessibility bus, which causes the
browser to hang for ~20 minutes before timing out. Disabling the
accessibility layer at the browser level eliminates the hang without
affecting test coverage.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix: set NO_AT_BRIDGE=1 for firefox in CI to prevent AT-SPI hang

The firefoxUserPrefs approach alone is insufficient — Firefox on Linux
loads the AT-SPI accessibility bridge at the GTK level before user prefs
apply. Setting NO_AT_BRIDGE=1 cuts the connection at the OS/GTK layer,
which is what actually prevents the ~20 min hang on ubuntu-latest runners.
Scoped to the firefox matrix leg only; chromium and webkit are unaffected.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix: add 20s safety boot fallback for environments where globe never initialises

On headless Linux CI (ubuntu-latest), Firefox uses Mesa software rendering
which can prevent CesiumJS from mounting its WebGL context. When that
happens, the `globeReady` DataBus event never fires, `startBoot()` is
never called, and `data-testid="app-ready"` never appears — causing every
Playwright test to time out at 45 s.

The fix guards `boot.startBoot()` behind a `bootStarted` flag so only the
first caller wins, then adds a 20 s `setTimeout` safety fallback in
AppShell. Normal flow (globe loads) fires the boot immediately via
`globeReady`; the safety timer is cleared. Degraded flow (WebGL absent)
still reaches the `app-ready` state after ~23.5 s (20 s + 3.5 s
animation), well within the 45 s test timeout.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

---------

Co-authored-by: Claude Sonnet 4.6 <[email protected]>
2026-05-20 21:02:16 +12:00
Antigravity AI f2ae2a7de7 chore: update .gitignore to remove IDE config and refine env file rules 2026-05-20 13:45:23 +12:00
Antigravity AI 3210b3bd15 chore: convert .claude from text file to git symlink pointing to .agents 2026-05-20 10:52:00 +12:00
Antigravity AI 9fad051f75 Merge branch 'main' of https://github.com/silvertakana/worldwideview 2026-05-19 23:25:23 +12:00
Antigravity AI a818822023 chore: add CLAUDE.md symlink pointing to AGENTS.md for Claude Code 2026-05-19 23:24:59 +12:00
Silvertakana 012184af30 Fix: Plugin fetch error (#159)
* fix(plugin-manager): downgrade non-fatal 'Failed to fetch' errors to warn, remove polling re-throw

* fix(codeql): resolve format string vulnerability in console logging

* fix(ci): restore playwright dependencies and configure tsconfig properly

* fix(plugins): ensure plugin fetch uses HTTP scheme instead of WSS
2026-05-18 11:10:04 +12:00
SilvertakanaandCopilot Autofix powered by AI c1f7ffb5b4 Refactor: High quality standards (#156)
* chore(merge): resolve conflicts, fix mockWs error, and apply refactor standards

* Potential fix for pull request finding 'CodeQL / Incomplete URL substring sanitization'

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

* Potential fix for pull request finding 'CodeQL / Incomplete URL substring sanitization'

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

* Potential fix for pull request finding 'CodeQL / Incomplete URL substring sanitization'

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

* fix(ci): Stabilize github actions and resolve test failures

- fix(tests): update WsClient mock to use standard function for Vitest constructor compatibility

- fix(db): correct PrismaClient import path to use generated output directory

- fix(e2e): add predev database boot step to playwright CI workflow

- chore: sync pnpm-lock.yaml after merge conflict resolution

* refactor(plugins): decouple GeoJSON plugin and implement data bus lifecycle

- feat(sdk): [Minor] Added dynamicPluginCreate, dynamicPluginRemove, and pluginUnregistered to DataBusEvents.

- feat(core): [Minor] Implemented unregisterPlugin in PluginManager.ts for automated IndexedDB caching cleanup and polling teardown.

- feat(core): [Minor] Added removeLayer to layersSlice.ts to support safe removal of plugin states.

- refactor(plugins): [Patch] Refactored useGeoJsonImport.ts and ImportedLayerList.tsx to decouple from direct manager imports, utilizing DataBus for lifecycle events.

- refactor(core): [Patch] Added pluginUnregistered listener to DataBusSubscriber.tsx to handle state and cache cleanup synchronously via event.

* fix(types): resolve PluginManager type errors

* refactor(core): decouple PluginManager and fix rendering invariants

- refactor(core): Replace Zustand mutations in PluginManager with DataBus events (Patch)
- refactor(sdk): Add layerLoadingChanged, pluginError, pluginUnregistered to DataBusEvents (Patch)
- refactor(ui): Subscribe to new DataBus events in DataBusSubscriber (Patch)
- fix(plugins): Remove size from BaseAviationPlugin to fix model rendering clipping (Patch)
- fix(plugins): Migrate BaseIncidentPlugin from size to iconScale to fix billboard clipping (Patch)

* chore: resolve lockfile conflict

* fix: restore BottomPanelManager in AppShell and fix vitest config

* fix(layout): restore bottom panel positioning and transition styling

This commit corrects the missing bottom panel issue by resolving CSS aggregation errors and fixing transition logic. The version is bumped to 2.15.5.

* refactor(core): harden typescript and fix linting violations

This commit addresses the remaining any types and linting errors across the core engine.

* fix(eslint): resolve react-hook immutability and cascading render violations

---------

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2026-05-18 11:08:00 +12:00
Silvertakanaandsnyk-bot 6816081644 Fix: Snyk vulnerability fix (#158)
* fix: package.json to reduce vulnerabilities

The following vulnerabilities are fixed with an upgrade:
- https://snyk.io/vuln/SNYK-JS-WS-16722635

* fix: update pnpm-lock.yaml for ws dependency bump and bump version to 2.15.11

---------

Co-authored-by: snyk-bot <[email protected]>
2026-05-18 11:06:39 +12:00
Antigravity AI 433004598d Merge branch 'fix/lint-cleanups'
# Conflicts:
#	eslint.config.mjs
#	package.json
2026-05-17 22:08:13 +12:00
Antigravity AI 02d8355a83 feat: add inverted app icon and update lockfile dependencies 2026-05-17 22:05:48 +12:00
Silvertakana 89010b2425 feat(ui): Bottom Panel System and E2E Testing (#147)
* test(bottom-panel): add e2e resize testing and data-testid

* test(e2e): fix playwright drag events skipping React state
2026-05-17 20:14:18 +12:00
Antigravity AI 0ff1d23e4a chore(lint): clean up legacy linting errors and hallucinated rules 2026-05-17 20:04:13 +12:00
Silvertakanaandsnyk-bot fd29865e7a [Snyk] Security upgrade ws from 8.20.0 to 8.20.1 (#151)
* fix: package.json to reduce vulnerabilities

The following vulnerabilities are fixed with an upgrade:
- https://snyk.io/vuln/SNYK-JS-WS-16722635

* fix: update pnpm-lock.yaml for ws dependency bump and bump version to 2.15.11

---------

Co-authored-by: snyk-bot <[email protected]>
2026-05-17 19:54:03 +12:00
Silvertakana 42564b537f ci(playwright): Add multi-browser test matrix (#150)
* ci(playwright): Add multi-browser test matrix (Patch)

* fix(cesium): Disable MSAA in Firefox to prevent readPixels crash (Patch)
2026-05-17 19:14:54 +12:00
Antigravity AI 598e00171c fix(cesium): Disable MSAA in Firefox to prevent readPixels crash (Patch) 2026-05-17 18:35:09 +12:00
devangpratap b849bb2b4d feat(api): add ISS Tracker proxy routes (#143)
* feat(api): add ISS position proxy route

Server-side proxy to the Where the ISS at? API (NORAD 25544).
Returns current latitude, longitude, altitude, velocity, visibility,
and footprint with 10-second revalidation and input validation.

Closes #8

* test(iss): add unit tests for ISS position route

Covers: valid response, field stripping, upstream failure,
invalid coordinates, and network error scenarios.

* feat(api): add ISS TLE orbit data route

Exposes the latest Two-Line Element set for NORAD 25544 via
/api/iss/tle. TLE data enables client-side orbit prediction
with satellite.js. Cached for 1 hour since TLEs update infrequently.

* test(iss): add unit tests for ISS TLE route

Covers: valid TLE response, field normalization (snake_case to
camelCase), upstream failure, empty TLE lines, and network errors.

* feat(api): add ISS historical positions route with tests

Batch endpoint at /api/iss/positions?timestamps=t1,t2,... returns
multiple past positions for orbit trail rendering. Validates input
(max 10 timestamps, numeric only), filters invalid upstream data,
and strips extraneous fields. Includes 7 test cases covering
happy path, validation, overflow, and upstream failure.

* fix(iss): harden validation and add missing edge case tests

- Remove unused TypeScript interfaces from route validators,
  align with earthquake route's bare validation style
- Add velocity validation to positions route (was missing,
  inconsistent with main route)
- Add null body tests for position and TLE routes
- Add empty string timestamps test for positions route
- Add NaN velocity rejection test for positions route
- Add network error test for positions route (was missing)
2026-05-17 17:36:51 +12:00
SilvertakanaandCopilot Autofix powered by AI fc7dd02ee2 refactor(core): harden typescript and fix linting violations (#146)
* chore(merge): resolve conflicts, fix mockWs error, and apply refactor standards

* Potential fix for pull request finding 'CodeQL / Incomplete URL substring sanitization'

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

* Potential fix for pull request finding 'CodeQL / Incomplete URL substring sanitization'

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

* Potential fix for pull request finding 'CodeQL / Incomplete URL substring sanitization'

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

* fix(ci): Stabilize github actions and resolve test failures

- fix(tests): update WsClient mock to use standard function for Vitest constructor compatibility

- fix(db): correct PrismaClient import path to use generated output directory

- fix(e2e): add predev database boot step to playwright CI workflow

- chore: sync pnpm-lock.yaml after merge conflict resolution

* refactor(plugins): decouple GeoJSON plugin and implement data bus lifecycle

- feat(sdk): [Minor] Added dynamicPluginCreate, dynamicPluginRemove, and pluginUnregistered to DataBusEvents.

- feat(core): [Minor] Implemented unregisterPlugin in PluginManager.ts for automated IndexedDB caching cleanup and polling teardown.

- feat(core): [Minor] Added removeLayer to layersSlice.ts to support safe removal of plugin states.

- refactor(plugins): [Patch] Refactored useGeoJsonImport.ts and ImportedLayerList.tsx to decouple from direct manager imports, utilizing DataBus for lifecycle events.

- refactor(core): [Patch] Added pluginUnregistered listener to DataBusSubscriber.tsx to handle state and cache cleanup synchronously via event.

* fix(types): resolve PluginManager type errors

* refactor(core): decouple PluginManager and fix rendering invariants

- refactor(core): Replace Zustand mutations in PluginManager with DataBus events (Patch)
- refactor(sdk): Add layerLoadingChanged, pluginError, pluginUnregistered to DataBusEvents (Patch)
- refactor(ui): Subscribe to new DataBus events in DataBusSubscriber (Patch)
- fix(plugins): Remove size from BaseAviationPlugin to fix model rendering clipping (Patch)
- fix(plugins): Migrate BaseIncidentPlugin from size to iconScale to fix billboard clipping (Patch)

* chore: resolve lockfile conflict

* fix: restore BottomPanelManager in AppShell and fix vitest config

* fix(layout): restore bottom panel positioning and transition styling

This commit corrects the missing bottom panel issue by resolving CSS aggregation errors and fixing transition logic. The version is bumped to 2.15.5.

* refactor(core): harden typescript and fix linting violations

This commit addresses the remaining any types and linting errors across the core engine.

* fix(eslint): resolve react-hook immutability and cascading render violations

---------

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2026-05-17 17:36:33 +12:00
Antigravity AI caf1638fdc ci(playwright): Add multi-browser test matrix (Patch) 2026-05-17 15:51:48 +12:00
191 changed files with 3579 additions and 1993 deletions

No files matched your search

+17
View File
@@ -23,6 +23,23 @@ 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.
## Sizing Conventions
| Entity type | Knob | Default | Typical band | Source |
|-------------|--------------|------------------------------------|------------------|--------|
| `point` | `size` | `8` desktop / `12` mobile | 5–12 | `src/core/globe/primitiveOps.ts` (`defaultPointSize`) |
| `billboard` | `iconScale` | `0.7` (`DEFAULT_BILLBOARD_SCALE`) | 0.6–0.9 | `src/core/globe/primitiveOps.ts` (`DEFAULT_BILLBOARD_SCALE`) |
| `model` | `modelScale` | `1.0` + `modelMinPixelSize` | varies per asset | `src/core/globe/ModelManager.ts`, `src/core/globe/hooks/useModelRendering.ts` |
> [!IMPORTANT]
> **Cross-plugin parity rule.** If your plugin renders alongside maritime / aviation / military-aviation on the globe, **leave `iconScale` unset** (or pick a value inside 0.6–0.9). A value below 0.5 will look visibly broken next to peer plugins. A value above 1.0 will dominate the globe.
> [!CAUTION]
> **Silent-ignore footgun.** `size` is a `PointPrimitive` property. If you set `size` on a `billboard` entity it is **silently dropped** — Cesium does not error and the billboard simply renders at `DEFAULT_BILLBOARD_SCALE`. When converting a point plugin to a billboard plugin, replace `size: N` with `iconScale: ~N/16` (the canvas base is `getBaseSize() = 48px` desktop) — do not delete it and do not translate it literally as `iconScale: N/10`. This footgun has shipped at least once (see commit history on `local-plugins/wwv-plugin-satellite`).
> [!NOTE]
> **Backdrop stack.** `createSvgIconUrl` (in the SDK) already wraps the icon in a 44×44 SVG with a dark backdrop circle. `src/core/globe/iconUpscaler.ts` then redraws onto a 48px canvas with **another** backdrop circle (`DEFAULT_BG = "rgba(15, 23, 42, 0.55)"`). Pass `background: false` to `createSvgIconUrl` when you want only the host's circle. Don't add a third backdrop in your own SVG.
## Performance Culling
> [!TIP]
+57
View File
@@ -29,3 +29,60 @@ In production, the `wwv-data-engine-v2` does NOT mount the local file system. In
## 5. Namespace Separation Rule
To prevent collisions and `404` or `ERR_MODULE_NOT_FOUND` errors, seeders **MUST NOT** exist simultaneously in both the community (`wwv-seeders-community`) and private (`wwv-seeders-private`) repositories. Namespace overlaps will cause module resolution failures when the V2 engine attempts to load them. Private seeders have priority.
## 6. Plugin ID Contract — Single Source of Truth
> **See ADR-0002** (`docs/architecture/decisions/adr-0002-seeder-exported-name-as-canonical-plugin-id.md`) for full rationale and alternatives considered.
**Rule:** Every seeder MUST export a `name` field that exactly matches the corresponding frontend plugin's `id` field (kebab-case).
```typescript
// ✅ Correct — seeder src/index.ts
export default {
name: "gps-jamming", // MUST equal the frontend plugin id
cron: "0 0 * * *",
fn: seedGpsJam,
};
// ❌ Wrong — do not use folder names, camelCase, or abbreviations
export default {
name: "gpsjam", // mismatch — frontend plugin is "gps-jamming"
...
};
```
**How the engine uses it:** `seeder-loader.ts` reads each seeder's exported `name` as the canonical plugin ID. This ID is used for:
- The `/manifest` endpoint's `plugins` array (what the frontend checks for local routing)
- WebSocket data messages (`pluginId` field)
- Redis keys (`data:<name>:live`)
- Scheduler logs
**Folder names are organizational only.** The engine warns at startup if `toKebabCase(folderName) !== seeder.name`, but this is cosmetic — the seeder's exported `name` always wins. Folder renames are a future cleanup, not a functional requirement.
**Frontend side:** `resolveEngineUrl(pluginId)` checks `localEngineHasPlugin(pluginId)` against the manifest. If the names match, the plugin routes to `ws://localhost:5000/stream`. No alias maps or translation layers are needed.
## 7. WebSocket Payload Format Contract
When a seeder calls `setLiveSnapshot(pluginId, payload, ttl)`, the engine broadcasts:
```json
{ "type": "data", "pluginId": "my-plugin", "payload": <whatever you passed> }
```
**`WsClient` payload handling rules (in order):**
1. Plugin has `mapWebsocketPayload(payload, existingEntities)` → called with raw payload → must return `GeoEntity[]`
2. No handler + payload **is** a flat `GeoEntity[]` array → used directly (timestamp normalized)
3. No handler + payload is **any other object** → **silently dropped** with a console warning
This means:
| Seeder sends | Frontend needs | Notes |
|---|---|---|
| `[{id, latitude, longitude, ...}]` | Nothing (WsClient handles) | ✅ Simplest for basic point data |
| `{ items: [{...}] }` | `mapWebsocketPayload` | Standard engine snapshot format |
| `{ satellites: [{...}] }` | `mapWebsocketPayload` | Named-collection format |
**Recommendation:** If the seeder and frontend plugin are developed together, use a **flat `GeoEntity[]` array** — no `mapWebsocketPayload` needed. Use named objects (e.g. `{ satellites: [...] }`) only when the seeder data has a domain-specific shape worth preserving; in that case you **must** implement `mapWebsocketPayload` on the frontend plugin.
> [!CAUTION]
> The most common silent bug: seeder sends `{ items: [...] }` (an object), frontend plugin omits `mapWebsocketPayload`. Data arrives but WsClient drops it with a console warning. The globe stays empty. Always implement `mapWebsocketPayload` for any plugin whose seeder sends an object payload.
+6
View File
@@ -38,3 +38,9 @@ E2E tests require an authenticated user to access core application features. We
> [!WARNING]
> If you encounter flaky tests or `ECONNREFUSED` errors during Playwright runs, check if the local Next.js dev server or the Docker engine stack is competing for ports (e.g., port 5432 or 3000). Ensure `pnpm run dev:backends` is running and stable before launching the test suite.
## 6. Execution Environment & Tooling Limitations
The development environment operates on **Windows PowerShell**. Agents MUST adhere to the following strict execution rules when running commands or interacting with the testing infrastructure:
- **No Double Ampersands (`&&`)**: Standard Windows PowerShell (prior to v7) does not support the `&&` operator. Use the semicolon (`;`) to chain commands, or rely on `pnpm` package.json scripts which manage cross-platform execution properly.
- **Avoid Non-existent Database CLI Commands**: Do not attempt to use raw `pg` or `psql` commands unless explicitly verified to exist in the path. Instead, use Prisma (`npx prisma studio`, `npx prisma migrate`) or Docker executions (`docker exec -it wwv-db psql ...`) for database interactions.
- **Creating Test Plugins**: You will repeatedly need to create mock test plugins for verifying different platform features (e.g. bottom-panel resizing, new UI widgets). When doing so, you MUST review this `e2e-testing.md` file to ensure compliance with the `PluginManager` strict interface rules (implementing `getPollingInterval`, `fetch`, and `renderEntity`).
+12
View File
@@ -16,6 +16,18 @@ Plugins from the marketplace use the `bundle` format and are imported at runtime
- `pluginManager.loadFromManifest()` validates and registers these plugins.
- Ensure any schema changes to the marketplace tables follow the `database-migrations.md` rule.
## 4. Fresh-Install Seeding
Fresh installs (no rows in `InstalledPlugin`) auto-seed a starter set so the globe isn't empty on day one. The source of truth is the **signed verified registry** (`marketplace.worldwideview.dev/api/registry`, loaded by `registryClient.getVerifiedPluginIds()`).
- **No hard-coded plugin lists.** Publishing a plugin to the verified registry is what makes it part of the fresh-install starter set.
- **Idempotent**: a `defaults_seeded` row in the `Setting` table prevents re-runs. If the registry is unreachable on first attempt, the guard is NOT set — the next request retries.
- **Existing instances** with `defaults_seeded=true` are untouched. To pull in newly-verified plugins, users install via the marketplace UI.
- **Demo edition** uses an independent path (`NEXT_PUBLIC_DEMO_DEFAULT_PLUGINS` env var, handled in `AppShell.tsx` and `useMarketplaceSync.ts`) — not this seeder.
> [!CAUTION]
> Do not reintroduce a static `DEFAULT_PLUGIN_IDS` constant or any other hard-coded plugin list. That drifted from npm reality, caused 404s for unpublished IDs, and conflated "verified" with "auto-installed."
## Current Implementation State
+80
View File
@@ -17,6 +17,59 @@ A valid plugin class MUST provide:
3. `renderEntity(GeoEntity)` to determine visual style.
4. `getPollingInterval()` (defaults fallback securely to standard store config).
## Plugin Data Delivery Types
Plugins receive entity data in one of three modes. Choose the right mode before writing code — mixing them causes silent data loss.
| Mode | `getPollingInterval()` | `fetch()` | `mapWebsocketPayload()` | When to use |
|---|---|---|---|---|
| **REST-only** | `> 0` (ms) | Returns `GeoEntity[]` | Not needed | Static or slow-changing data (< every 30s). No seeder required. |
| **WebSocket-only** | `0` | Return `[]` immediately | **Required** if seeder sends object payload | Live-streaming data from a seeder (satellites, AIS, flights) |
| **Hybrid** | `> 0` | Returns initial snapshot | **Required** if seeder sends object payload | Needs both immediate data on load AND live updates |
### WebSocket-Only Pattern (most live-data plugins)
```typescript
getPollingInterval(): number {
return 0; // WS-only — do NOT call REST on enable
}
async fetch(_timeRange: TimeRange): Promise<GeoEntity[]> {
return []; // Initial data arrives via mapWebsocketPayload within seconds
}
mapWebsocketPayload(payload: any, _existingEntities: GeoEntity[]): GeoEntity[] {
// Transform raw engine payload → GeoEntity[]
// payload shape depends on what the seeder calls setLiveSnapshot() with
const items = payload?.items ?? (Array.isArray(payload) ? payload : []);
return items.map((item: any): GeoEntity => ({
id: `my-plugin-${item.id}`,
pluginId: "my-plugin",
latitude: item.lat,
longitude: item.lon,
altitude: item.alt ?? 0,
timestamp: new Date(),
label: item.name,
properties: item,
}));
}
```
> [!WARNING]
> If `getPollingInterval()` returns `0` but the seeder sends an object payload, you **MUST** implement `mapWebsocketPayload`. Without it, `WsClient` drops the data silently. See `data-engine-architecture.md §7` for the exact rule.
### `mapWebsocketPayload` Signature
```typescript
mapWebsocketPayload(payload: any, existingEntities: GeoEntity[]): GeoEntity[]
```
- `payload` — raw value from `setLiveSnapshot()` in the seeder (whatever shape the seeder stores)
- `existingEntities` — current entities in the store for this plugin (use for incremental updates)
- Must return a **complete replacement** `GeoEntity[]` (not a diff)
---
## Plugin Architectures (Manifest Formats)
Plugins are defined via `PluginManifest` and operate on an **All-Bundle** architecture.
@@ -52,6 +105,33 @@ All plugins MUST define their identity and compatibility via a `"worldwideview"`
}
```
### `peerDependencies` Rule for npm-Published Plugins
Plugins published to npm **MUST** declare the following as `peerDependencies`, not `dependencies`:
```json
{
"peerDependencies": {
"@worldwideview/wwv-plugin-sdk": "*",
"react": ">=19",
"lucide-react": "*"
}
}
```
Also peer (never bundle): `react-dom`, `cesium`, `resium`, `zustand`.
Bundling these causes multiple React instances in the host app, breaking hooks (`Invalid hook call` at runtime).
### File Extension Rule
- Files containing **JSX** (any `<Component />` syntax, `return (<div>...)`) → must use `.tsx`
- Files with no JSX (pure TypeScript, even importing React types) → use `.ts`
This is enforced by the TypeScript compiler. A `.ts` file with JSX will fail to build.
---
## The Registration Pipeline
> [!NOTE]
+23 -1
View File
@@ -26,7 +26,29 @@ When an AI agent or developer is executing CLI commands via tools in this projec
- **Rule**: NEVER use the `&&` operator to chain commands in PowerShell. It will result in parser errors.
- **Resolution**: Use sequential execution, run commands separately, or use PowerShell-safe chaining like `; if ($?) { }`.
## 5. Next.js vs. Undici Fetch Type Mismatches
## 5. UTF-8 BOM in `package.json` Crashing Node Scripts
If `pnpm dev` (or any workspace script) dies with `SyntaxError: Unexpected token '', "{ ..." is not valid JSON`, the offending file has a UTF-8 BOM (`EF BB BF`) at byte 0.
- **Root Cause**: Windows PowerShell 5.1 `Set-Content -Encoding UTF8` and Notepad's "Save as UTF-8" both emit a BOM. Node's `fs.readFileSync(p, 'utf-8')` does NOT strip it, so `JSON.parse` rejects the leading ``. pnpm/npm strip BOMs silently, which is why this only blows up in custom workspace scripts.
- **Diagnosis** (PowerShell):
```powershell
Get-ChildItem local-plugins -Directory | ForEach-Object {
$p = Join-Path $_.FullName 'package.json'
if (Test-Path $p) {
$b = [System.IO.File]::ReadAllBytes($p) | Select-Object -First 3
if ($b[0] -eq 0xEF -and $b[1] -eq 0xBB -and $b[2] -eq 0xBF) { $_.Name }
}
}
```
- **Fix at the seam (preferred)**: In any script that parses externally-authored JSON, strip the BOM before parsing. See `readJsonFile()` in [`scripts/sync-local-plugins.mjs`](../../scripts/sync-local-plugins.mjs) as the canonical helper:
```js
let text = fs.readFileSync(filePath, "utf-8");
if (text.charCodeAt(0) === 0xFEFF) text = text.slice(1);
return JSON.parse(text);
```
- **Clean existing files** (one-time): rewrite each file without its first 3 bytes via `[System.IO.File]::WriteAllBytes($p, $bytes[3..($bytes.Length - 1)])`.
- **Prevention**: When authoring files via PowerShell, use `Out-File -Encoding utf8NoBOM` (PS 7+) or `[System.IO.File]::WriteAllText($p, $text, [System.Text.UTF8Encoding]::new($false))` (any PS). Never edit `package.json` in Notepad.
## 6. Next.js vs. Undici Fetch Type Mismatches
When implementing SSRF protections (e.g., DNS IP Pinning via custom `Dispatcher`), you will likely use `undici.Agent`.
- **Root Cause**: Passing global Next.js `RequestInit` options directly into `undici.fetch` will throw strict TypeScript errors because the `BodyInit` and `RequestCache` signatures differ, and `dns.lookup` returns a generic `number` instead of exactly `4 | 6` for IP families.
- **Resolution**: Strip out Next.js specific keys, explicitly cast `body` as `any`, and explicitly type `resolvedFamily: number` when interfacing between Next.js request streams and the `undici` library.
@@ -38,7 +38,7 @@ Moves a WorldWideView plugin from the old `packages/` monorepo location (or the
> ```
> Example: `node scripts/migrate-plugin.mjs gps-jamming`
>
> The script will automatically copy the frontend plugin, inject peerDependencies, refactor `index.tsx` routing, fix the backend seeder's build settings and `SEEDERS_DIR` paths, and register the plugin in `defaultPlugins.ts`.
> The script will automatically copy the frontend plugin, inject peerDependencies, refactor `index.tsx` routing, and fix the backend seeder's build settings and `SEEDERS_DIR` paths. (Fresh-install seeding no longer involves a hard-coded list — once published to npm with a valid `worldwideview` block, the plugin is registered via the signed verified registry.)
> **You still need to run `pnpm install` and verify the builds manually as described below.**
> [!IMPORTANT]
@@ -29,20 +29,15 @@ A WorldWideView plugin is a self-contained data source that renders geospatial e
## Architecture Decision
```dot
digraph plugin_type {
rankdir=TB;
node [shape=diamond];
"Does it need live\nexternal API data?" -> "Is polling\nfrequency > 30s?" [label="yes"];
"Does it need live\nexternal API data?" -> "Static GeoJSON\n(wwvStaticCompiler)" [label="no"];
"Is polling\nfrequency > 30s?" -> "Cron Seeder\n(engine)" [label="yes"];
"Is polling\nfrequency > 30s?" -> "Init Seeder\n(engine)" [label="no"];
"Static GeoJSON\n(wwvStaticCompiler)" [shape=box];
"Cron Seeder\n(engine)" [shape=box];
"Init Seeder\n(engine)" [shape=box];
}
```
Does it need live external API data?
├── NO → Static GeoJSON plugin (wwvStaticCompiler in vite.config.ts)
│ No seeder needed. Place data in data/data.json.
└── YES → Does it update more often than every 30s?
├── NO → Cron Seeder (engine, registerSeeder with cron string)
│ getPollingInterval() = 0, mapWebsocketPayload() required
└── YES → Init Seeder (engine, registerSeeder with init function)
getPollingInterval() = 0, mapWebsocketPayload() required
```
---
@@ -146,7 +141,7 @@ export default class WildfiresPlugin implements WorldPlugin {
| `getLayerConfig()` | Layer appearance (color, clustering, max entities) |
| `renderEntity(entity)` | Per-entity Cesium rendering options |
**Optional:**
**Optional (but `mapWebsocketPayload` is REQUIRED for WS-only plugins with object payloads):**
| Method | Purpose |
|---|---|
@@ -158,7 +153,7 @@ export default class WildfiresPlugin implements WorldPlugin {
| `getDetailComponent()` | Custom detail panel for selected entity |
| `getSettingsComponent()` | Plugin settings UI |
| `getGlobeComponent()` | React component injected into globe view |
| `mapWebsocketPayload(payload, existing)` | Transform raw WS data into `GeoEntity[]` |
| `mapWebsocketPayload(payload, existing)` | **Required if seeder payload is an object** (not a flat array). Transforms raw engine payload → `GeoEntity[]`. Without it, `WsClient` drops object payloads silently. |
| `requiresConfiguration(settings)` | Return `true` if plugin needs setup first |
### 1.3 Package Metadata
@@ -518,14 +513,30 @@ export default class IssPlugin implements WorldPlugin {
destroy(): void {}
async fetch(timeRange: TimeRange): Promise<GeoEntity[]> {
return []; // WS-only plugin
async fetch(_timeRange: TimeRange): Promise<GeoEntity[]> {
return []; // WS-only — data arrives via mapWebsocketPayload
}
getPollingInterval(): number {
return 0; // WS-only
}
// REQUIRED: seeder sends { source, fetchedAt, items: [...], totalCount } (an object).
// Without this, WsClient drops the payload silently — the globe stays empty.
mapWebsocketPayload(payload: any, _existingEntities: GeoEntity[]): GeoEntity[] {
const items: any[] = payload?.items ?? (Array.isArray(payload) ? payload : []);
return items.map((item: any): GeoEntity => ({
id: `iss-${item.id}`,
pluginId: "iss",
latitude: item.lat,
longitude: item.lon,
altitude: item.alt ?? 0,
timestamp: new Date(),
label: "International Space Station",
properties: { speed: item.speed },
}));
}
getLayerConfig(): LayerConfig {
return {
color: "#ffffff",
@@ -644,7 +655,9 @@ Categories are **lowercase**: `"aviation"` not `"Aviation"`, `"natural-disaster"
- [ ] **Engine:** Seeder file in `wwv-seeders/src/seeders/<name>.ts` (or private repo)
- [ ] **Engine:** `registerSeeder({ name })` matches frontend plugin `id`
- [ ] **Engine:** Calls `setLiveSnapshot()` with correct plugin ID key
- [ ] **Engine:** Data shape is an object with `items` array (or plugin implements `mapWebsocketPayload`)
- [ ] **Engine:** Seeder payload is either a flat `GeoEntity[]` array OR plugin implements `mapWebsocketPayload` (any other object is silently dropped by WsClient)
- [ ] **Frontend (WS-only):** `getPollingInterval()` returns `0` and `fetch()` returns `[]`
- [ ] **Frontend (WS-only):** `mapWebsocketPayload(payload, existingEntities)` implemented if seeder sends an object
- [ ] **Engine:** SQLite table created in `db.ts` if historical data needed
- [ ] **Verification:** `GET localhost:5000/manifest` includes the plugin ID
- [ ] **Verification:** `GET localhost:5000/health` shows seeder last-run timestamp
-1
View File
@@ -1 +0,0 @@
.agents
Symlink
+1
View File
@@ -0,0 +1 @@
.agents
+6
View File
@@ -4,5 +4,11 @@ install_deps = "pnpm install"
[[pre-start]]
copy_env = """powershell -Command "if (Test-Path '../worldwideview/.env') { Copy-Item '../worldwideview/.env' '.env' -Force }""""
[[pre-start]]
copy_local_plugins = """powershell -Command "if (Test-Path '../worldwideview/local-plugins') { robocopy '../worldwideview/local-plugins' 'local-plugins' /E /XD node_modules dist .next coverage /XF '*.log' /NFL /NDL /NJH /NJS | Out-Null }""""
[[pre-start]]
copy_local_seeders = """powershell -Command "if (Test-Path '../worldwideview/local-seeders') { robocopy '../worldwideview/local-seeders' 'local-seeders' /E /XD .pnpm-store node_modules /NFL /NDL /NJH /NJS | Out-Null }""""
[[pre-remove]]
docker_clean = "docker compose down -v"
+11 -2
View File
@@ -10,6 +10,10 @@ jobs:
test:
timeout-minutes: 60
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
browser: [chromium, firefox, webkit]
steps:
- uses: actions/checkout@v4
@@ -37,11 +41,16 @@ jobs:
pnpm run predev
- name: Run Playwright tests
run: pnpm test:e2e
env:
# Prevent Firefox from loading the AT-SPI/MSAA accessibility bridge on
# Linux CI — without this, Firefox hangs for ~20 min waiting for a bus
# that doesn't exist on ubuntu-latest runners.
NO_AT_BRIDGE: ${{ matrix.browser == 'firefox' && '1' || '0' }}
run: pnpm test:e2e --project=${{ matrix.browser }}
- uses: actions/upload-artifact@v4
if: ${{ !cancelled() }}
with:
name: playwright-report
name: playwright-report-${{ matrix.browser }}
path: playwright-report/
retention-days: 30
+3 -5
View File
@@ -22,10 +22,6 @@ node_modules/
/.agents/context
/.agents/research/
# claude code IDE config
/.claude/
/.cline/
# performance
/performance/
@@ -64,7 +60,8 @@ yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
.env
.env.local
# vercel
.vercel
@@ -96,6 +93,7 @@ packages/wwv-data-engine/
# IDE workspace files
*.code-workspace
*.vscode
# Build outputs and generated assets
/public/cesium/
Symlink
+1
View File
@@ -0,0 +1 @@
AGENTS.md
+2
View File
@@ -63,6 +63,8 @@ services:
cd /app && node dist/server.js"
ports:
- "5000:5000"
volumes:
- ./local-seeders:/app/seeders
environment:
- PORT=5000
- REDIS_URL=redis://wwv-redis:6379
@@ -0,0 +1,158 @@
# ADR-0002: Source-of-truth for plugin identity and registration
## Status
Accepted
## Date
2026-05-20
## Context
Two related problems in the plugin system surfaced in the same period, and both have the same root cause: canonical plugin information was being derived in middleware translation layers (folder names, hard-coded lists) rather than at its proper source. Each problem is fixed by pushing the canonical truth back to its rightful owner and removing the static translation in the middle. Documenting them together makes the shared principle explicit and discourages future regressions of the same shape.
### Problem 1 — Engine seeder ID derived from folder name
The WorldWideView local data engine discovers seeders by scanning the filesystem under `/app/seeders`. Historically, the engine assigned each seeder an ID equal to its **folder name** (e.g., the folder `gpsjam/` became plugin ID `"gpsjam"`).
The frontend, however, identifies plugins by a separate **`id` field** declared in each plugin class (e.g., `"gps-jamming"`). The engine's `/manifest` endpoint listed available plugins using folder-derived IDs, and the frontend's `localEngineHasPlugin(pluginId)` performed an exact string match against that list.
This created a silent failure mode: six seeders had folder names that did not match their corresponding frontend plugin IDs:
| Folder name | Frontend plugin `id` |
|---|---|
| `gpsjam/` | `gps-jamming` |
| `sanctions/` | `international-sanctions` |
| `wildfires/` | `wildfire` |
| `civilUnrest/` | `civil-unrest` |
| `conflictEvents/` | `conflict-events` |
| `cyberAttacks/` | `cyber-attacks` |
When `localEngineHasPlugin('gps-jamming')` returned `false` (because the manifest listed `"gpsjam"`), the frontend silently fell through to the production cloud engine, bypassing the local engine entirely. The bug was invisible — no error, just incorrect routing.
A short-term patch introduced `SEEDER_ID_ALIASES` in `src/core/data/engineManifest.ts` — a frontend translation map from folder names to plugin IDs. This was explicitly a band-aid: it duplicated knowledge in a consumer rather than fixing the contract at the source, and would go stale as new seeders were added.
The engine's TypeScript source (`seeder-loader.ts`) also had a `toKebabCase()` helper intended to normalize camelCase folder names (e.g., `civilUnrest` → `civil-unrest`), but its compiled `dist/` was stale (the production image had not been rebuilt to include it), and `toKebabCase` alone cannot resolve abbreviation mismatches like `gpsjam` → `gps-jamming`.
### Problem 2 — Fresh-install plugin set hard-coded
The marketplace auto-seeder ([src/lib/marketplace/seedDefaultPlugins.ts](../../../src/lib/marketplace/seedDefaultPlugins.ts)) writes a starter set of plugins to the database on first boot so the globe isn't empty on day one. The list of plugins to seed lived in a hard-coded constant `DEFAULT_PLUGIN_IDS` ([src/lib/marketplace/defaultPlugins.ts](../../../src/lib/marketplace/defaultPlugins.ts)).
Two failure modes followed from the static list:
1. **Drift**: ten plugins were published to npm under `@worldwideview/*` and verified — surveillance-satellites, military-bases, embassies, seaports, lighthouses, spaceports, iranwarlive, undersea-cables, mineral-mines, nuclear-facilities — but never added to `DEFAULT_PLUGIN_IDS`. Fresh installs missed them silently.
2. **Phantom 404s**: two entries in the list (`fortiguard`, `nz-traffic-cameras`) were dev-only sandboxes in `local-plugins/`, never published to npm. Every fresh boot hit `https://marketplace.worldwideview.dev/api/plugins/fortiguard` → 404, logged a warning, and continued. The branch `fix/diagnose-plugins-404` was opened to diagnose those.
A separate, signed verified-plugins registry already existed at `marketplace.worldwideview.dev/api/registry`, loaded by [registryClient.ts](../../../src/lib/marketplace/registryClient.ts) with Ed25519 verification. It was used for trust-stamping installed plugins but not for selecting which plugins to seed. That registry is the authoritative list of plugins that have been reviewed and verified — exactly the list a starter set should come from.
### Shared shape
Both problems wrap the same anti-pattern: a consumer (frontend, seeder) maintains a static translation/list derived from the producer's actual identity (seeder export, npm publication). The translation drifts. The fix in both cases is the same: stop translating in the consumer; let the producer declare the truth and consume it directly.
## Decisions
### Decision 1 — The seeder's exported `name` field is the canonical plugin ID
The engine reads each seeder's `dist/index.mjs` default export's `name` property and uses it as the plugin ID everywhere:
- `/manifest` endpoint `plugins` array
- WebSocket welcome message plugin list
- WebSocket data message `pluginId` field
- Redis key (`data:<name>:live`)
- Scheduler logs
The folder name is used only as a filesystem fallback if the seeder exports no `name`. The engine logs a warning at startup whenever the kebab-cased folder name differs from the seeder's exported `name`, making drift visible without blocking startup.
**Contract:** Every seeder MUST export a `name` field that exactly equals the corresponding frontend plugin's `id` field (kebab-case). This is a two-place contract: declare the same ID string in the seeder export and in the frontend plugin class.
Implementation: `seeder-loader.ts` was updated to set `id = seederConfig.name || toKebabCase(folderName)` instead of `id = toKebabCase(folderName)`. The frontend `SEEDER_ID_ALIASES` map was removed entirely. No translation layer exists between the engine's manifest and the frontend's plugin lookup.
### Decision 2 — The signed verified registry is the source-of-truth for fresh-install auto-seeding
The marketplace auto-seeder iterates the set returned by `getVerifiedPluginIds()` (the signed registry) instead of a hard-coded `DEFAULT_PLUGIN_IDS` constant. Publishing a plugin to the verified registry automatically makes it part of the fresh-install starter set on subsequent boots, with no code change.
The static `DEFAULT_PLUGIN_IDS` list is deleted. There is no fallback list in code — if the registry is unreachable on first attempt, the seeder defers without marking-seeded so the next request retries (the 5-min in-memory cache in `registryClient.ts` bounds the request rate during outages).
Trust stamping is collapsed: every plugin landed by the seeder is `verified` by definition, so the per-plugin `verified.has(pluginId)` check inside the seeder is dropped — `manifest.trust = "verified"` is set directly.
**Contract:** A plugin is part of the fresh-install starter set iff it appears in the signed verified-plugins registry. There is no other list to maintain.
## Shared principle
> **Canonical plugin truth lives at the source. Reject static translation/lookup layers in the middle.**
This is the architectural rule both decisions encode. Concrete corollaries for future contributions:
- Don't introduce a static map in a consumer to compensate for a producer that mis-labels itself. Fix the producer.
- Don't introduce a static list in code to enumerate what a registry or filesystem already enumerates. Read from the registry/filesystem.
- A translation layer that "just needs an entry added each time we publish a plugin" is a foot-gun — it will silently drift the moment someone forgets.
## Alternatives Considered
### For Decision 1
#### Folder renames (rejected as primary fix)
Rename the six mismatched folders to match their frontend plugin IDs (e.g., `gpsjam/` → `gps-jamming/`). This would make the folder name the canonical ID.
- **Rejected as primary fix** because Windows Docker Desktop holds NTFS volume mount locks on running containers, making renames impossible without a full Docker Desktop shutdown. More importantly, it makes the canonical ID fragile — any accidental folder rename breaks routing silently.
- Folder renames remain a cosmetic cleanup option, now that the seeder export is the actual source of truth.
#### Frontend alias map (`SEEDER_ID_ALIASES`)
Maintain a static mapping in `engineManifest.ts` that translates engine-reported IDs to frontend plugin IDs.
- **Rejected** because it puts translation responsibility on the consumer rather than the producer. Every new seeder with a naming mismatch requires a manual alias entry. The map goes stale silently — no warning if an alias is wrong or missing.
#### `toKebabCase()` normalization only
Apply `toKebabCase()` to folder names in the engine and rely on the convention that folder names encode the plugin ID in camelCase.
- **Rejected** because `toKebabCase` cannot resolve abbreviation mismatches (`gpsjam` → still `gpsjam`, not `gps-jamming`) or singular/plural differences (`wildfires` → still `wildfires`, not `wildfire`). It only handles camelCase-to-kebab conversion.
#### Strict validation with engine startup failure
Refuse to load any seeder whose folder name doesn't match its exported `name`, blocking startup until inconsistencies are resolved.
- **Rejected** as too aggressive for a local dev environment. A warning is sufficient — startup continues, mismatches are visible, and the system keeps working.
### For Decision 2
#### Add the missing 10 IDs to `DEFAULT_PLUGIN_IDS` (rejected)
Extend the static list to include the newly-published plugins.
- **Rejected** because it ships a fix that resolves the immediate symptom while preserving the underlying drift mechanism. The list would go stale again the next time a plugin is published.
#### Hybrid: registry as default + static fallback list
Read from the registry; fall back to a hard-coded list if the registry is empty/unreachable.
- **Rejected** because it reintroduces the static list as a permanent shadow source-of-truth. Fallback lists go stale silently. The chosen "defer seeding on empty registry" behavior is safer — fresh installs retry on the next request rather than locking in a stale set.
#### Delete auto-seeding entirely (rejected)
Drop the seeder and let users install everything from the marketplace UI starting from an empty globe.
- **Rejected** because fresh installs should have something to look at on day one. The user explicitly stated this requirement: "we want the user to have something to get started with."
## Consequences
### Easier
**Decision 1 — engine seeder identity**
- Self-documenting identity. Reading any seeder's `src/index.ts` immediately tells you its plugin ID. No external registry to consult.
- Filesystem layout is irrelevant. Folders can be named for readability or organized in subdirectories without affecting routing.
- No translation layers. The frontend receives the correct ID directly from the manifest; `localEngineHasPlugin()` works with a direct string comparison.
- Drift is visible. The engine warns on startup when folder names diverge from exported names, catching mistakes during development rather than silently at runtime.
- Adding a new seeder requires only: (1) export `name: '<plugin-id>'` matching the frontend plugin's `id`, (2) no registration step, no alias map entry.
**Decision 2 — marketplace seeding**
- Publishing a plugin to the verified registry is sufficient to add it to the starter set. No code change, no PR to add an ID to a constant.
- Phantom 404s are gone. The seeder only queries IDs that exist in the verified registry, which by construction reflects what's actually published.
- Trust semantics align. "Verified" and "auto-seeded on fresh install" are now the same condition, not two near-overlapping lists that can drift.
- Registry outages no longer brick fresh installs. The deferral semantics ensure the seeder retries instead of marking-seeded with zero rows.
### Harder
**Decision 1 — engine seeder identity**
- Seeder author bears responsibility. If a seeder exports the wrong `name`, routing fails silently (same failure mode as before, but now localized to the seeder rather than the folder). The startup warning mitigates this.
- Contract validation is advisory, not enforced. There is no build-time check that the seeder's `name` matches an actual frontend plugin `id`. A validation script (`scripts/validate-seeder-ids.mjs`) is the recommended mitigation.
- Engine image must be kept up to date. The fix lives in `dist/seeder-loader.js` inside the Docker image. If the published `ghcr.io/silvertakana/wwv-data-engine:latest` image is behind the local source, the behavior reverts to folder-name-based IDs. Local changes require `docker cp` injection or an image rebuild until the fix is published.
**Decision 2 — marketplace seeding**
- The verified registry must be kept accurate. A newly-published plugin doesn't auto-seed until it's added to the registry and the registry is re-signed. Operational responsibility shifts from "remember to add the ID to a code constant" to "remember to add the ID to the registry" — a similar discipline, but now at the right layer (the marketplace, not the consumer).
- Existing instances are not back-filled. Users whose `Setting` table already has `defaults_seeded=true` will not automatically receive newly-verified plugins; they must install via the marketplace UI. This is by design — re-seeding could reinstall plugins a user explicitly uninstalled.
- Dev-only sandboxes (`local-plugins/<name>/`) no longer "tag along" via the default list. `fortiguard` and `nz-traffic-cameras` only reach users once published to npm and added to the verified registry. The local-plugins folder discovery in `/api/marketplace/load` still surfaces them in dev (`NODE_ENV=development` or `WWV_PLUGIN_DEV=true`).
+20 -16
View File
@@ -1,7 +1,7 @@
import nextCoreWebVitals from "eslint-config-next/core-web-vitals";
import nextTypeScript from "eslint-config-next/typescript";
export default [
const config = [
{
ignores: [
"node_modules/**",
@@ -16,31 +16,35 @@ export default [
"local-seeders/**",
".agents/**",
".claude/**",
".gemini/**",
"*.cjs",
],
},
...nextCoreWebVitals,
...nextTypeScript,
{
rules: {
// ─── Re-enabled Strict Rules ─────────────────────────────
// The codebase has been baselined with suppress-eslint-errors.
// All new code must adhere to these strict rules.
// ─── Demoted on first introduction ─────────────────────────────
// The existing codebase has hundreds of violations across these
// rules. To make the lint job runnable in CI without blocking on
// pre-existing debt, every rule that currently fires errors is
// demoted to `warn`. Promote back to `error` once the backlog
// is addressed (recommended in this order: prefer-const,
// no-unescaped-entities, ban-ts-comment, then the react-hooks
// family once the team agrees on the React 19 hook-purity rules).
"@typescript-eslint/no-explicit-any": "error",
"no-console": "error",
// Pre-existing — flagged in the original code review (#96):
"@typescript-eslint/no-explicit-any": "warn",
"no-console": "off",
// React 19 hook-purity rules from eslint-plugin-react-hooks 7+:
"react-hooks/purity": "error",
"react-hooks/refs": "error",
"react-hooks/set-state-in-effect": "error",
"react-hooks/immutability": "error",
"react-hooks/static-components": "error",
// (These were previously hallucinated or require extra plugins)
// Misc one-offs across the codebase:
"react/no-unescaped-entities": "error",
"@typescript-eslint/ban-ts-comment": "error",
"@next/next/no-assign-module-variable": "error",
"prefer-const": "error",
"@typescript-eslint/ban-ts-comment": "warn",
"@next/next/no-assign-module-variable": "warn",
"prefer-const": "warn",
},
},
];
export default config;
-2
View File
@@ -93,6 +93,4 @@ const nextConfig: NextConfig = {
},
};
import { withSentryConfig } from "@sentry/nextjs";
export default nextConfig;
+15 -16
View File
@@ -1,7 +1,7 @@
{
"name": "worldwideview",
"version": "2.15.5",
"private": true,
"version": "2.16.1",
"private": true,
"type": "module",
"packageManager": "[email protected]",
"scripts": {
@@ -21,7 +21,6 @@
"test:e2e": "playwright test",
"test:mutate": "stryker run",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"db:reset": "npx prisma migrate reset --force",
"db:prune": "node scripts/db-prune.mjs",
"generate": "prisma generate"
@@ -32,8 +31,8 @@
"@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",
"@sentry/nextjs": "^10.53.1",
"@supabase/supabase-js": "^2.106.0",
"@types/pg": "^8.20.0",
"@vercel/analytics": "^1.6.1",
"@worldwideview/wwv-plugin-sdk": "workspace:*",
@@ -43,21 +42,21 @@
"hls.js": "^1.6.16",
"insecam-api": "^0.0.3",
"jose": "^6.2.3",
"lucide-react": "^1.14.0",
"lucide-react": "^1.16.0",
"next": "16.2.6",
"next-auth": "^5.0.0-beta.30",
"openid-client": "^6.8.4",
"pg": "^8.20.0",
"pg": "^8.21.0",
"prisma": "^7.8.0",
"react": "19.2.6",
"react-dom": "19.2.6",
"react-player": "^3.4.0",
"resium": "1.21.0",
"satellite.js": "^7.0.0",
"resium": "1.21.1",
"satellite.js": "^7.0.1",
"stripe": "^22.1.1",
"tslib": "^2.8.1",
"undici": "^8.2.0",
"ws": "^8.14.2",
"undici": "^8.3.0",
"ws": "^8.20.1",
"zod": "^4.4.3",
"zustand": "^5.0.13"
},
@@ -75,9 +74,9 @@
"@types/react": "^19",
"@types/react-dom": "^19",
"@types/ws": "^8.18.1",
"@typescript-eslint/eslint-plugin": "^8.59.3",
"@typescript-eslint/parser": "^8.59.3",
"@vitejs/plugin-react": "^5.1.4",
"@typescript-eslint/eslint-plugin": "^8.59.4",
"@typescript-eslint/parser": "^8.59.4",
"@vitejs/plugin-react": "^6.0.2",
"@vitest/coverage-v8": "4.1.6",
"concurrently": "^9.2.1",
"copy-webpack-plugin": "^14.0.0",
@@ -93,9 +92,9 @@
"jsdom": "^28.1.0",
"rollup-plugin-external-globals": "^0.13.0",
"tree-kill": "^1.2.2",
"tsx": "^4.21.0",
"tsx": "^4.22.2",
"typescript": "^5",
"vite": "^8.0.12",
"vite": "^8.0.13",
"vitest": "^4.1.6"
},
"pnpm": {
+2 -2
View File
@@ -13,11 +13,11 @@
"clean": "rm -rf dist"
},
"dependencies": {
"commander": "^12.1.0",
"commander": "^14.0.3",
"prompts": "^2.4.2"
},
"devDependencies": {
"@types/node": "^20.0.0",
"@types/node": "^25.9.1",
"@types/prompts": "^2.4.9",
"typescript": "^5.0.0"
}
+1 -6
View File
@@ -1,3 +1,4 @@
/* eslint-disable no-console */
import { Command } from 'commander';
import { saveConfig } from '../utils/config.js';
@@ -8,20 +9,14 @@ export const configCommand = new Command('config')
.argument('<value>', 'Config value (e.g., your-username)')
.action((action, key, value) => {
if (action !== 'set') {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error(`[wwv-cli] Unknown config action: ${action}`);
process.exit(1);
}
if (key === 'org') {
saveConfig({ org: value });
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.log(`[wwv-cli] Successfully set default organization to @${value}`);
} else {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error(`[wwv-cli] Unknown config key: ${key}. Valid keys: org`);
process.exit(1);
}
+1 -10
View File
@@ -1,3 +1,4 @@
/* eslint-disable no-console */
import { Command } from 'commander';
import fs from 'fs';
import path from 'path';
@@ -68,8 +69,6 @@ export const createCommand = new Command('create')
]);
if (!response.pluginId) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.log('Plugin creation cancelled.');
return;
}
@@ -80,8 +79,6 @@ export const createCommand = new Command('create')
const pluginDir = path.join(process.cwd(), targetBaseDir, `wwv-plugin-${pluginId}`);
if (fs.existsSync(pluginDir)) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error(`Error: Directory ${pluginDir} already exists.`);
process.exit(1);
}
@@ -196,8 +193,6 @@ ${fetchBoilerplate}
fs.mkdirSync(path.join(pluginDir, 'src'), { recursive: true });
fs.writeFileSync(path.join(pluginDir, 'src', 'index.ts'), indexTsContent);
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.log(`\n✅ Successfully created plugin frontend at ${pluginDir}`);
// Generate seeder backend if requested
@@ -228,14 +223,10 @@ export default async function run(context) {
}
`;
fs.writeFileSync(path.join(seederDir, 'seeder.mjs'), seederContent);
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.log(`✅ Successfully created plugin seeder at ${seederDir}`);
}
}
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.log(`\nNext steps:
1. Run \`pnpm install\` from the project root.
2. Edit \`index.ts\` in your plugin directory.
+4 -35
View File
@@ -1,3 +1,4 @@
/* eslint-disable no-console */
import { Command } from 'commander';
import { execSync } from 'child_process';
import path from 'path';
@@ -10,8 +11,6 @@ export const publishCommand = new Command('publish')
.argument('[pluginName]', 'Name of the plugin to publish (if running from root)')
.option('--org <orgName>', 'NPM organization to publish to (e.g., your-username)')
.action(async (pluginName, options) => {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.log('[wwv-cli] Preparing to publish plugin...');
let cwd = process.cwd();
@@ -31,21 +30,15 @@ export const publishCommand = new Command('publish')
} else if (fs.existsSync(packagesPath)) {
cwd = packagesPath;
} else {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error(`[wwv-cli] Error: Could not find plugin '${pluginName}' in local-plugins or packages.`);
process.exit(1);
}
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.log(`[wwv-cli] Found plugin at: ${cwd}`);
}
const pkgPath = path.join(cwd, 'package.json');
if (!fs.existsSync(pkgPath)) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error('[wwv-cli] Error: No package.json found in directory: ' + cwd);
process.exit(1);
}
@@ -54,15 +47,11 @@ export const publishCommand = new Command('publish')
const pkgContent = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
if (!pkgContent.worldwideview) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error('[wwv-cli] Error: package.json is missing the "worldwideview" manifest block. Is this a WWV plugin?');
process.exit(1);
}
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line prefer-const
let originalName = pkgContent.name;
const originalName = pkgContent.name;
let publishedName = originalName;
// Determine organization
@@ -72,15 +61,13 @@ export const publishCommand = new Command('publish')
if (!targetOrg) {
if (config.org) {
targetOrg = config.org;
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.log(`[wwv-cli] Using default organization from config: @${targetOrg}`);
} else {
// Fallback to NPM whoami if possible
try {
const whoami = execSync('npm whoami', { stdio: 'pipe' }).toString().trim();
targetOrg = whoami;
} catch (e) {
} catch (_e) {
// Not logged in or errored, ignore
}
@@ -93,16 +80,12 @@ export const publishCommand = new Command('publish')
});
if (!response.org) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.log('Publish cancelled.');
return;
}
targetOrg = response.org;
saveConfig({ org: targetOrg });
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.log(`[wwv-cli] Saved @${targetOrg} as your default organization.`);
}
} else {
@@ -118,34 +101,20 @@ export const publishCommand = new Command('publish')
if (originalName !== publishedName) {
pkgContent.name = publishedName;
fs.writeFileSync(pkgPath, JSON.stringify(pkgContent, null, 2) + '\n');
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.log(`[wwv-cli] Updated package name to ${publishedName}`);
}
}
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.log(`[wwv-cli] Publishing ${publishedName}@${pkgContent.version} to NPM...`);
// Execute npm publish
execSync('npm publish --access public', { stdio: 'inherit', cwd });
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.log('[wwv-cli] Successfully published to NPM!');
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.log('[wwv-cli] To submit this plugin to the WorldWideView Marketplace, please visit: https://marketplace.worldwideview.dev/submit');
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.log(`[wwv-cli] Package Name: ${publishedName}`);
} // TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
catch (err: any) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
} catch (err: any) {
console.error('[wwv-cli] Error during publish:', err.message);
process.exit(1);
}
-4
View File
@@ -18,8 +18,6 @@ export abstract class BaseAviationPlugin implements WorldPlugin {
abstract id: string;
abstract name: string;
abstract description: string;
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
abstract icon: any;
category = "aviation" as const;
abstract version: string;
@@ -37,8 +35,6 @@ export abstract class BaseAviationPlugin implements WorldPlugin {
// Implementations must define how payload comes via fetch and websocket
abstract fetch(timeRange: TimeRange): Promise<GeoEntity[]>;
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
abstract mapWebsocketPayload(payload: any): GeoEntity[];
// Server backend configurations
-4
View File
@@ -15,8 +15,6 @@ export abstract class BaseIncidentPlugin implements WorldPlugin {
abstract id: string;
abstract name: string;
abstract description: string;
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
abstract icon: any;
abstract category: PluginCategory;
abstract version: string;
@@ -39,8 +37,6 @@ export abstract class BaseIncidentPlugin implements WorldPlugin {
protected abstract getSeverityColor(value: number): string;
protected abstract getSeveritySize(value: number): number;
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
protected getEntityIcon(entity: GeoEntity): any {
return this.icon;
}
@@ -1,3 +1,4 @@
import { describe, it, expectTypeOf } from "vitest";
import type {
TokenExchangeRequest,
@@ -21,7 +22,8 @@ describe("Auth Contracts", () => {
expectTypeOf<TokenExchangeRequest>().toHaveProperty("audience").toEqualTypeOf<string>();
// @ts-expect-error - missing required apiKey
const badReq: TokenExchangeRequest = { audience: "engine-123" };
const _badReq: TokenExchangeRequest = { audience: "engine-123" };
void _badReq;
});
it("TokenExchangeResponse has exact required properties", () => {
@@ -31,7 +33,8 @@ describe("Auth Contracts", () => {
expectTypeOf<TokenExchangeResponse>().toHaveProperty("tier").toEqualTypeOf<Tier | undefined>();
// @ts-expect-error - missing required token
const badRes: TokenExchangeResponse = { expiresAt: 123456789, kid: "key-1" };
const _badRes: TokenExchangeResponse = { expiresAt: 123456789, kid: "key-1" };
void _badRes;
});
it("WebSocketAuthMessage has exact required properties including protocol version", () => {
@@ -40,10 +43,12 @@ describe("Auth Contracts", () => {
expectTypeOf<WebSocketAuthMessage>().toHaveProperty("token").toEqualTypeOf<SensitiveString>();
// @ts-expect-error - missing version
const badMsg: WebSocketAuthMessage = { type: "auth", token: "jwt-token-here" as SensitiveString };
const _badMsg: WebSocketAuthMessage = { type: "auth", token: "jwt-token-here" as SensitiveString };
void _badMsg;
// @ts-expect-error - wrong version
const badVersion: WebSocketAuthMessage = { type: "auth", v: 2, token: "jwt-token-here" as SensitiveString };
const _badVersion: WebSocketAuthMessage = { type: "auth", v: 2, token: "jwt-token-here" as SensitiveString };
void _badVersion;
});
it("WebSocketMessage is a discriminated union correctly containing WebSocketAuthMessage", () => {
+8 -13
View File
@@ -32,9 +32,10 @@ export interface IconUrlOptions extends Record<string, unknown> {
* By default wraps the icon in a filled circle for visibility on any terrain.
* Pass `{ background: false }` to opt out.
*/
export // TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function createSvgIconUrl(Icon: ComponentType<any>, opts: IconUrlOptions = {}): string {
export function createSvgIconUrl(
Icon: ComponentType<any>,
opts: IconUrlOptions = {},
): string {
const {
background = true,
backgroundColor = DEFAULT_BG_COLOR,
@@ -271,15 +272,11 @@ export interface WorldPlugin {
getServerConfig?(): ServerPluginConfig;
getFilterDefinitions?(): FilterDefinition[];
getLegend?(): { label: string; color: string; filterId?: string; filterValue?: string }[];
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
getSidebarComponent?(): ComponentType<{ plugin?: any } | any>
getSidebarComponent?(): ComponentType<{ plugin?: any } | any>;
getDetailComponent?(): ComponentType<{ entity: GeoEntity }>;
getSettingsComponent?(): ComponentType<{ pluginId: string }>
getSettingsComponent?(): ComponentType<{ pluginId: string }>;
/** Custom React component injected into the Globe view for rendering primitives/data sources (e.g. GeoJSON). */
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
getGlobeComponent?(): ComponentType<{ viewer: any; enabled: boolean }>
getGlobeComponent?(): ComponentType<{ viewer: any; enabled: boolean }>;
/**
* Returns a React component to be rendered inside the Bottom Panel when this plugin's
* dock button is selected. The panel is resizable and can be expanded to fullscreen.
@@ -288,9 +285,7 @@ export interface WorldPlugin {
getBottomPanelComponent?(): ComponentType<{ pluginId: string; enabled: boolean }>;
requiresConfiguration?(settings: unknown): boolean;
/** Map raw websocket payload into GeoEntity array. Optional existingEntities is provided so plugins can merge state (e.g. historical trails). */
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
mapWebsocketPayload?(payload: any, existingEntities?: GeoEntity[]): GeoEntity[]
mapWebsocketPayload?(payload: any, existingEntities?: GeoEntity[]): GeoEntity[];
}
// ─── Aliases for backwards compatibility ─────────────────────
@@ -12,12 +12,8 @@ import path from "path";
* - Converts features into GeoEntity objects
* - Renders with the manifest's rendering config
*/
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function wwvStaticCompiler(): any {
let pluginRoot = "";
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let manifest: any = null;
let generatedEntry = "";
@@ -25,8 +21,6 @@ export function wwvStaticCompiler(): any {
name: "wwv-static-compiler",
enforce: "pre" as const,
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config(userConfig: any) {
pluginRoot = userConfig.root || process.cwd();
const pkgPath = path.join(pluginRoot, "package.json");
@@ -77,8 +71,6 @@ export function wwvStaticCompiler(): any {
};
}
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function generateStaticPluginSource(manifest: any): string {
const pluginId = manifest.id;
const pluginName = manifest.name || pluginId;
@@ -22,8 +22,6 @@ interface GlobalsMap {
*
* @returns {any} A Vite plugin object.
*/
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function wwvPluginGlobals(): any {
const HOST_MAPPINGS: GlobalsMap = {
"react": "React",
+20
View File
@@ -39,6 +39,26 @@ export default defineConfig({
storageState: 'playwright/.auth/user.json'
},
},
{
name: 'firefox',
use: {
...devices['Desktop Firefox'],
storageState: 'playwright/.auth/user.json',
launchOptions: {
firefoxUserPrefs: {
// Disable MSAA/AT-SPI accessibility layer — causes hangs on Linux CI
'accessibility.force_disabled': 1,
},
},
},
},
{
name: 'webkit',
use: {
...devices['Desktop Safari'],
storageState: 'playwright/.auth/user.json'
},
},
],
/* Run your local dev server before starting the tests */
+1842 -637
View File
File diff suppressed because it is too large. Load diff
@@ -11,11 +11,9 @@ export default {
// Lifecycle
initialize: async (ctx) => {
// eslint-disable-next-line no-console
console.log("[e2e-mock-bottom-panel] Initialized");
},
destroy: () => {
// eslint-disable-next-line no-console
console.log("[e2e-mock-bottom-panel] Destroyed");
},
@@ -49,7 +47,6 @@ export default {
const React = globalThis.__WWV_HOST__.React;
if (!React) {
// eslint-disable-next-line no-console
console.error("[e2e-mock-bottom-panel] Failed to resolve React from __WWV_HOST__");
return null;
}
-3
View File
@@ -12,11 +12,9 @@ export default {
// Lifecycle
initialize: async (ctx) => {
// eslint-disable-next-line no-console
console.log("[e2e-mock-plugin] Initialized");
},
destroy: () => {
// eslint-disable-next-line no-console
console.log("[e2e-mock-plugin] Destroyed");
},
@@ -50,7 +48,6 @@ export default {
const React = globalThis.__WWV_HOST__.React;
if (!React) {
// eslint-disable-next-line no-console
console.error("[e2e-mock-plugin] Failed to resolve React from __WWV_HOST__");
return null;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

-14
View File
@@ -43,7 +43,6 @@ loadEnv('.env');
const skipLocalDb = process.env.WWV_SKIP_LOCAL_DB === 'true' || process.env.WWV_SKIP_LOCAL_DB === '1';
if (skipLocalDb) {
// eslint-disable-next-line no-console
console.log('⏭️ Skipping local PostgreSQL startup (WWV_SKIP_LOCAL_DB is set).');
process.exit(0);
}
@@ -60,7 +59,6 @@ if (folderName !== 'worldwideview') {
}
process.env.WWV_DB_PORT = port.toString();
// eslint-disable-next-line no-console
console.log(`🔌 Assigned deterministic database port: ${port}`);
// Robust rewrite of DATABASE_URL in .env
@@ -80,7 +78,6 @@ if (fs.existsSync(envPath)) {
foundTargetActive = true;
return line;
} else {
// eslint-disable-next-line no-console
console.warn(`⚠️ [Telemetry] Commenting out conflicting DATABASE_URL: ${line.trim()}`);
linesModified = true;
return `# ${line}`;
@@ -90,7 +87,6 @@ if (fs.existsSync(envPath)) {
});
if (!foundTargetActive) {
// eslint-disable-next-line no-console
console.log(`🔌 [Telemetry] Injecting correct local DATABASE_URL for port ${port}.`);
newLines.push(``);
newLines.push(`# Dynamically injected by boot-db.mjs for worktree`);
@@ -111,10 +107,8 @@ if (fs.existsSync(envPath)) {
} catch (err) {
attempt++;
if (err.code === 'EBUSY' || err.code === 'EPERM' || err.message.includes('os error 32')) {
// eslint-disable-next-line no-console
console.warn(`⚠️ [Telemetry] File lock encountered on .env (attempt ${attempt}/${maxRetries}). Retrying in 100ms...`);
if (attempt >= maxRetries) {
// eslint-disable-next-line no-console
console.error('❌ Failed to write .env after multiple attempts due to file locks.');
throw err;
}
@@ -130,7 +124,6 @@ if (fs.existsSync(envPath)) {
}
// eslint-disable-next-line no-console
console.log('🚀 Checking local PostgreSQL database...');
try {
@@ -138,26 +131,19 @@ try {
try {
execSync('docker --version', { stdio: 'ignore' });
} catch (e) {
// eslint-disable-next-line no-console
console.log('⚠️ Docker is not installed or not in PATH. Skipping local database startup.');
// eslint-disable-next-line no-console
console.log('💡 If you want to run a local database automatically, please install Docker Desktop.');
process.exit(0);
}
// Start the db service and wait for it to be healthy
// eslint-disable-next-line no-console
console.log('📦 Starting PostgreSQL via Docker Compose...');
execSync('docker compose up -d --wait db', { stdio: 'inherit' });
// eslint-disable-next-line no-console
console.log('✅ Local PostgreSQL database is ready!');
} catch (error) {
// eslint-disable-next-line no-console
console.error('❌ Failed to start local database:', error.message);
// eslint-disable-next-line no-console
console.log('💡 Ensure that docker is running and try again');
// eslint-disable-next-line no-console
console.log('💡 You may need to start it manually or set WWV_SKIP_LOCAL_DB=true to use an external database.');
}
-5
View File
@@ -21,15 +21,10 @@ const missing = checks.filter(c => !process.env[c.name]);
if (missing.length === 0) process.exit(0);
const yellow = (s) => `\x1b[33m${s}\x1b[0m`;
// eslint-disable-next-line no-console
console.warn(yellow("\n⚠ Build-time env vars not set:"));
for (const c of missing) {
// eslint-disable-next-line no-console
console.warn(yellow(`\n ${c.name}`));
// eslint-disable-next-line no-console
console.warn(` ${c.why}`);
// eslint-disable-next-line no-console
console.warn(` Fix: ${c.how}`);
}
// eslint-disable-next-line no-console
console.warn(yellow("\nContinuing build — these are warnings, not errors.\n"));
-7
View File
@@ -2,29 +2,22 @@ import { prisma } from "../src/lib/db";
async function main() {
const plugins = await prisma.installedPlugin.findMany();
// eslint-disable-next-line no-console
console.log("Installed plugins:");
// eslint-disable-next-line no-console
plugins.forEach((p) => console.log(` ${p.pluginId} | config: ${p.config.substring(0, 60)}`));
const geojson = plugins.find((p) => p.pluginId === "geojson");
if (geojson) {
await prisma.installedPlugin.delete({ where: { id: geojson.id } });
// eslint-disable-next-line no-console
console.log("\nDeleted orphaned 'geojson' record.");
} else {
// eslint-disable-next-line no-console
console.log("\nNo orphaned 'geojson' record found.");
}
const remaining = await prisma.installedPlugin.findMany();
// eslint-disable-next-line no-console
console.log("\nRemaining plugins:");
// eslint-disable-next-line no-console
remaining.forEach((p) => console.log(` ${p.pluginId}`));
await prisma.$disconnect();
}
// eslint-disable-next-line no-console
main().catch(console.error);
-2
View File
@@ -12,7 +12,5 @@ const geoJson = convertToGeoJson(raw);
writeFileSync(outputPath, JSON.stringify(geoJson, null, 2), "utf-8");
// eslint-disable-next-line no-console
console.log(`✅ Converted ${geoJson.features.length} features`);
// eslint-disable-next-line no-console
console.log(` Output: ${outputPath}`);
+1 -6
View File
@@ -15,8 +15,7 @@ function copyDir(src, dest) {
}
const entries = fs.readdirSync(src, { withFileTypes: true });
// eslint-disable-next-line prefer-const
for (let entry of entries) {
for (const entry of entries) {
const srcPath = path.join(src, entry.name);
const destPath = path.join(dest, entry.name);
@@ -28,19 +27,15 @@ function copyDir(src, dest) {
}
}
// eslint-disable-next-line no-console
console.log('Copying Cesium assets...');
folders.forEach(folder => {
const src = path.join(cesiumSource, folder);
const dest = path.join(targetBase, folder);
if (fs.existsSync(src)) {
copyDir(src, dest);
// eslint-disable-next-line no-console
console.log(`Copied ${folder}`);
} else {
// eslint-disable-next-line no-console
console.warn(`Source folder not found: ${src}`);
}
});
// eslint-disable-next-line no-console
console.log('Cesium assets copied successfully.');
-7
View File
@@ -9,7 +9,6 @@ import { execSync } from 'child_process';
import fs from 'fs';
import path from 'path';
// eslint-disable-next-line no-console
console.log('🧹 Starting Garbage Collection for orphaned WorldWideView Docker volumes...');
try {
@@ -24,7 +23,6 @@ try {
);
if (wwvVolumes.length === 0) {
// eslint-disable-next-line no-console
console.log('✅ No WorldWideView volumes found.');
process.exit(0);
}
@@ -52,28 +50,23 @@ try {
}
if (!activeProjectNames.has(projectName)) {
// eslint-disable-next-line no-console
console.log(`🗑️ Deleting orphaned volume: ${volume}`);
try {
execSync(`docker volume rm ${volume}`, { stdio: 'inherit' });
orphanedCount++;
} catch (rmError) {
// eslint-disable-next-line no-console
console.warn(`⚠️ Could not remove volume ${volume}. It may still be in use.`);
}
}
}
if (orphanedCount === 0) {
// eslint-disable-next-line no-console
console.log('✅ All existing volumes belong to active worktrees. Nothing to prune.');
} else {
// eslint-disable-next-line no-console
console.log(`✅ Successfully pruned ${orphanedCount} orphaned volume(s).`);
}
} catch (error) {
// eslint-disable-next-line no-console
console.error('❌ Failed to prune volumes:', error.message);
process.exit(1);
}
-3
View File
@@ -19,7 +19,6 @@ for (const dir of dirs) {
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
if (!pkg.worldwideview) {
// eslint-disable-next-line no-console
console.log(`Skipped ${dir} - No worldwideview metadata in package.json`);
continue;
}
@@ -46,10 +45,8 @@ for (const dir of dirs) {
fs.copyFileSync(distPath, path.join(targetDir, "frontend.mjs"));
fs.writeFileSync(path.join(targetDir, "plugin.json"), JSON.stringify(manifest, null, 2));
// eslint-disable-next-line no-console
console.log(`Deployed ${publicName} to public/plugins`);
} else {
// eslint-disable-next-line no-console
console.log(`Skipped ${dir} - dist or package.json not found.`);
}
}
-4
View File
@@ -54,7 +54,6 @@ const shutdown = () => {
if (isShuttingDown) return;
isShuttingDown = true;
// eslint-disable-next-line no-console
console.log('\n🛑 Shutting down dev servers...');
// Forcefully kill the process tree of each command cross-platform
@@ -65,14 +64,11 @@ const shutdown = () => {
});
if (teardownDbOnExit) {
// eslint-disable-next-line no-console
console.log('📦 Tearing down local PostgreSQL database...');
try {
execSync('docker compose stop db', { stdio: 'inherit' });
// eslint-disable-next-line no-console
console.log('✅ Local database stopped.');
} catch (e) {
// eslint-disable-next-line no-console
console.error('⚠️ Failed to stop database container.');
}
}
-1
View File
@@ -49,7 +49,6 @@ export default defineConfig({
// Add vite.config.ts
fs.writeFileSync(path.join(packagesDir, dir, "vite.config.ts"), viteConfigContent);
// eslint-disable-next-line no-console
console.log(`Added vite.config.ts to ${dir} (entry: ${entryFile})`);
}
}
-3
View File
@@ -12,7 +12,6 @@ const certPath = path.join(process.cwd(), 'data', 'localhost.crt');
const keyPath = path.join(process.cwd(), 'data', 'localhost.key');
if (!fs.existsSync(certPath) || !fs.existsSync(keyPath)) {
// eslint-disable-next-line no-console
console.error('[HTTPS Proxy] Certificates not found. Proxy will not start.');
process.exit(1);
}
@@ -39,7 +38,6 @@ const server = https.createServer(options, (req, res) => {
});
proxyReq.on('error', (e) => {
// eslint-disable-next-line no-console
console.error(`[HTTPS Proxy] Error proxying request to ${req.url}:`, e.message);
res.writeHead(502);
res.end('Bad Gateway');
@@ -49,6 +47,5 @@ const server = https.createServer(options, (req, res) => {
});
server.listen(listenPort, '0.0.0.0', () => {
// eslint-disable-next-line no-console
console.log(`[HTTPS Proxy] Secure bridge listening on https://0.0.0.0:${listenPort} (forwarding to http://127.0.0.1:${targetPort})`);
});
-7
View File
@@ -7,11 +7,9 @@ async function main() {
if (action === "list") {
const users = await prisma.user.findMany();
if (users.length === 0) {
// eslint-disable-next-line no-console
console.log("No users found — visit /setup to create one.");
} else {
users.forEach((u) =>
// eslint-disable-next-line no-console
console.log(` ${u.email} | ${u.name} | ${u.role} | ${u.createdAt}`)
);
}
@@ -19,7 +17,6 @@ async function main() {
const email = process.argv[3];
const newPass = process.argv[4];
if (!email || !newPass) {
// eslint-disable-next-line no-console
console.log("Usage: tsx scripts/manage-users.ts reset <email> <password>");
return;
}
@@ -28,19 +25,15 @@ async function main() {
where: { email },
data: { hashedPassword: hashed },
});
// eslint-disable-next-line no-console
console.log(`Password reset for ${email}`);
} else if (action === "delete-all") {
await prisma.user.deleteMany();
// eslint-disable-next-line no-console
console.log("All users deleted — visit /setup to create a new admin.");
} else {
// eslint-disable-next-line no-console
console.log("Usage: tsx scripts/manage-users.ts <list|reset|delete-all>");
}
await prisma.$disconnect();
}
// eslint-disable-next-line no-console
main().catch(console.error);
-8
View File
@@ -22,7 +22,6 @@ const SUPABASE_URL = process.env.NEXT_PUBLIC_SUPABASE_URL!;
const SUPABASE_KEY = process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;
if (!SUPABASE_URL || !SUPABASE_KEY) {
// eslint-disable-next-line no-console
console.error("Missing Supabase credentials in .env.local");
process.exit(1);
}
@@ -32,7 +31,6 @@ const supabase = createClient(SUPABASE_URL, SUPABASE_KEY);
// Connect to SQLite DB (respects DB_PATH, fallback to data engine location)
const defaultDbPath = path.resolve(process.cwd(), "packages/wwv-data-engine/data/engine.db");
const dbPath = process.env.DB_PATH || defaultDbPath;
// eslint-disable-next-line no-console
console.log(`Connecting to SQLite at ${dbPath}...`);
// Ensure DB directory exists
@@ -65,7 +63,6 @@ const insertHistory = db.prepare(`
`);
async function migrate() {
// eslint-disable-next-line no-console
console.log("Fetching existing aviation_history records from Supabase...");
let offset = 0;
const limit = 10000; // Chunk size
@@ -78,18 +75,15 @@ async function migrate() {
.range(offset, offset + limit - 1);
if (error) {
// eslint-disable-next-line no-console
console.error("Fetch error:", error);
process.exit(1);
}
if (!data || data.length === 0) {
// eslint-disable-next-line no-console
console.log("No more records to fetch.");
break;
}
// eslint-disable-next-line no-console
console.log(`Processing ${data.length} records (Offset: ${offset})...`);
// Batch insert to SQLite
@@ -115,7 +109,6 @@ async function migrate() {
insertMany(data);
totalInserted += data.length;
} catch (err) {
// eslint-disable-next-line no-console
console.error("SQLite Insert Error:", err);
}
@@ -126,7 +119,6 @@ async function migrate() {
offset += limit;
}
// eslint-disable-next-line no-console
console.log(`Migration complete! Successfully injected ~${totalInserted} records into SQLite.`);
}
-6
View File
@@ -3,9 +3,7 @@ import { execSync } from 'child_process';
const dbUrl = process.env.DATABASE_URL || '';
if (!dbUrl) {
// eslint-disable-next-line no-console
console.error("❌ ERROR: DATABASE_URL is missing.");
// eslint-disable-next-line no-console
console.error(" Did you forget to run 'pnpm run setup' to generate your .env file?");
process.exit(1);
}
@@ -13,15 +11,11 @@ if (!dbUrl) {
const isLocal = dbUrl.includes('localhost') || dbUrl.includes('127.0.0.1') || dbUrl.includes('host.docker.internal') || dbUrl.includes('postgres:postgres@db:5432');
if (!isLocal) {
// eslint-disable-next-line no-console
console.error("❌ ERROR: DATABASE_URL points to a remote database.");
// eslint-disable-next-line no-console
console.error(" Running 'prisma db push --accept-data-loss' on production/staging data is forbidden.");
// eslint-disable-next-line no-console
console.error(" If you truly need to migrate a remote db, run prisma db push manually.");
process.exit(1);
}
// eslint-disable-next-line no-console
console.log("🔒 Local database detected. Safely running prisma db push...");
execSync('npx prisma db push --accept-data-loss', { stdio: 'inherit' });
-6
View File
@@ -16,15 +16,12 @@ const EXAMPLE = resolve(ROOT, ".env.example");
const TARGET = resolve(ROOT, ".env");
if (existsSync(TARGET)) {
// eslint-disable-next-line no-console
console.log("✅ .env already exists — skipping setup.");
// eslint-disable-next-line no-console
console.log(" Delete it and re-run if you want to regenerate.");
process.exit(0);
}
if (!existsSync(EXAMPLE)) {
// eslint-disable-next-line no-console
console.error("❌ .env.example not found. Are you in the right directory?");
process.exit(1);
}
@@ -51,9 +48,6 @@ content = content
writeFileSync(TARGET, content, "utf8");
// eslint-disable-next-line no-console
console.log("✅ .env created with a generated AUTH_SECRET.");
// eslint-disable-next-line no-console
console.log(" Fill in any optional API keys (Cesium, Bing, OpenSky, etc.)");
// eslint-disable-next-line no-console
console.log(" then run: npm run dev");
+220 -32
View File
@@ -7,6 +7,7 @@
*/
import fs from "fs";
import os from "os";
import path from "path";
import { build } from "vite";
import { fileURLToPath } from "url";
@@ -26,9 +27,72 @@ const EXTERNAL_GLOBALS = {
"resium": "globalThis.__WWV_HOST__.Resium",
};
/**
* Synthetic host-module exports for `@/` imports that plugins use to access
* the host application's runtime objects (store, plugin manager, components).
*
* When a plugin sub-component does `import { useStore } from "@/core/state/store"`,
* the tsconfig `@/*` alias (inherited from the main app root tsconfig) would normally
* resolve that to the actual `src/core/state/store.ts` file — pulling the entire Zustand
* store (and its transitive deps like `src/core/edition.ts`) into the bundle.
* This plugin intercepts those imports at the resolveId stage, before Vite touches
* the filesystem, and substitutes a synthetic module that reads from the host globals
* injected at runtime by `hostGlobals.ts`.
*/
const HOST_MODULE_SYNTHETICS = {
"@/core/state/store": `export const useStore = globalThis.__WWV_HOST__.useStore;`,
"@/core/plugins/PluginManager": `export const pluginManager = globalThis.__WWV_HOST__.pluginManager;`,
"@/components/video/CameraStream": `export const CameraStream = globalThis.__WWV_HOST__.CameraStream;`,
"zustand": `
const zustand = globalThis.__WWV_HOST__.zustand || {};
export default zustand;
export const { create, createStore } = zustand;
`,
};
/**
* @function wwvHostRedirectPlugin
* @description Vite plugin that intercepts host-app module imports (`@/core/...`,
* `@/components/...`) in local plugin builds and redirects them to the runtime
* host globals instead of bundling the full app source tree.
*
* @returns {import('vite').Plugin}
*/
function wwvHostRedirectPlugin() {
return {
name: "wwv-host-redirect",
enforce: "pre",
resolveId(id) {
if (id in HOST_MODULE_SYNTHETICS) return `\0${id}`;
return null;
},
load(id) {
if (!id.startsWith("\0")) return null;
const originalId = id.slice(1);
return HOST_MODULE_SYNTHETICS[originalId] ?? null;
},
};
}
/**
* @function readJsonFile
* @description Reads a UTF-8 JSON file, tolerating a leading BOM (U+FEFF).
* Node's `fs.readFileSync(p, 'utf-8')` preserves the BOM byte, which `JSON.parse`
* then rejects with "Unexpected token". Scaffolders and editors on Windows
* occasionally emit BOMs into `package.json`; pnpm/npm strip them silently,
* so we match that behavior here to avoid breaking dev on otherwise-valid files.
* @param {string} filePath
* @returns {any}
*/
function readJsonFile(filePath) {
let text = fs.readFileSync(filePath, "utf-8");
if (text.charCodeAt(0) === 0xFEFF) text = text.slice(1);
return JSON.parse(text);
}
/**
* @function discoverLocalPlugins
* @description Finds all directories in `local-plugins/` that contain a valid
* @description Finds all directories in `local-plugins/` that contain a valid
* `package.json` with a `worldwideview` manifest block.
* @returns {Array<{dir: string, manifest: any, pluginDir: string}>}
*/
@@ -40,44 +104,141 @@ export function discoverLocalPlugins() {
if (dir.startsWith(".")) return false;
const pkgPath = path.join(LOCAL_PLUGINS_DIR, dir, "package.json");
if (!fs.existsSync(pkgPath)) return false;
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
const pkg = readJsonFile(pkgPath);
return !!pkg.worldwideview;
})
.map(dir => {
const pkgPath = path.join(LOCAL_PLUGINS_DIR, dir, "package.json");
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
const pkg = readJsonFile(pkgPath);
const manifest = pkg.worldwideview;
manifest.version = pkg.version;
manifest.name = pkg.name;
manifest.description = pkg.description;
return { dir, manifest, pluginDir: path.join(LOCAL_PLUGINS_DIR, dir) };
return { dir, manifest, pkg, pluginDir: path.join(LOCAL_PLUGINS_DIR, dir) };
});
}
/**
* @function buildPlugin
* @description Invokes the Vite build engine to compile a plugin's source
* into a single ES module, externalizing shared host dependencies.
* @function resolvePluginEntry
* @description Resolves the TypeScript source entry file for a plugin.
*
* Resolution order:
* 1. `worldwideview.dev_entry` — explicit override in the manifest block
* 2. `pkg.types` — if it points to a .ts/.tsx source file (not a .d.ts declaration)
* 3. `pkg.source` — explicit source field (less common, but valid)
* 4. Heuristic fallback: src/index.ts → src/index.tsx → index.ts → index.tsx
*
* @param {string} pluginDir - Absolute path to the plugin directory.
* @param {any} manifest - The parsed `worldwideview` manifest block.
* @param {any} pkg - The full parsed package.json object.
* @returns {string|null} Absolute path to the entry file, or null if not found.
*/
export async function buildPlugin({ dir, manifest, pluginDir }) {
const devEntry = manifest.dev_entry || "index.ts";
let entryFile = path.join(pluginDir, devEntry);
function resolvePluginEntry(pluginDir, manifest, pkg) {
const candidates = [];
// Fallback: check for .tsx
if (!fs.existsSync(entryFile)) {
const tsxEntry = devEntry.replace(".ts", ".tsx");
entryFile = path.join(pluginDir, tsxEntry);
if (!fs.existsSync(entryFile)) {
// eslint-disable-next-line no-console
console.warn(`[sync] ⚠ No entry file found for ${dir}, skipping`);
return false;
if (manifest.dev_entry) {
candidates.push(path.join(pluginDir, manifest.dev_entry));
}
// pkg.types points to the TS source in all WWV plugins (e.g. "src/index.ts")
if (pkg.types && !pkg.types.endsWith(".d.ts")) {
candidates.push(path.join(pluginDir, pkg.types));
}
if (pkg.source) {
candidates.push(path.join(pluginDir, pkg.source));
}
// Heuristic fallbacks
for (const rel of ["src/index.ts", "src/index.tsx", "index.ts", "index.tsx"]) {
candidates.push(path.join(pluginDir, rel));
}
return candidates.find(f => fs.existsSync(f)) ?? null;
}
const SKIP_DIRS = new Set(["dist", "node_modules", ".git", ".turbo", ".vite"]);
/**
* @function latestSourceMtime
* @description Walks a plugin directory and returns the newest mtime (ms) across
* source files. Used to decide whether a cached `dist/frontend.mjs` is still valid.
* Skips build/output dirs so this is fast even on cold disks.
* @param {string} rootDir
* @returns {number} newest mtime in ms, or 0 if no files found
*/
function latestSourceMtime(rootDir) {
let newest = 0;
/** @param {string} dir */
function walk(dir) {
let entries;
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
if (entry.name.startsWith(".") && entry.name !== ".env") continue;
if (SKIP_DIRS.has(entry.name)) continue;
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
walk(full);
} else if (entry.isFile()) {
const m = fs.statSync(full).mtimeMs;
if (m > newest) newest = m;
}
}
}
walk(rootDir);
return newest;
}
/**
* @function isBuildFresh
* @description Returns true if the plugin's existing `dist/frontend.mjs` is newer
* than every source file under its directory — meaning Vite would produce a
* byte-identical bundle and the build can be skipped.
* @param {string} pluginDir
* @returns {boolean}
*/
function isBuildFresh(pluginDir) {
const distFile = path.join(pluginDir, "dist", "frontend.mjs");
if (!fs.existsSync(distFile)) return false;
const distMtime = fs.statSync(distFile).mtimeMs;
const sourceMtime = latestSourceMtime(pluginDir);
return distMtime >= sourceMtime;
}
/**
* @function buildPlugin
* @description Invokes the Vite build engine to compile a plugin's source
* into a single ES module, externalizing shared host dependencies.
*
* Returns `"fresh"` if an up-to-date `dist/frontend.mjs` already exists (no build run),
* `true` if Vite produced a new bundle, or `false` on failure.
*/
export async function buildPlugin({ dir, manifest, pkg, pluginDir }) {
if (isBuildFresh(pluginDir)) {
return "fresh";
}
const entryFile = resolvePluginEntry(pluginDir, manifest, pkg ?? {});
if (!entryFile) {
console.warn(`[sync] ⚠ No entry file found for ${dir}, skipping`);
return false;
}
try {
await build({
root: pluginDir,
// Disable auto-loading the plugin's own vite.config.ts — the local
// plugins' node_modules may be symlinked to a different repo's SDK
// build (worktree scenario), which breaks config loading. The sync
// script provides all necessary config inline.
configFile: false,
logLevel: "warn",
plugins: [wwvHostRedirectPlugin()],
build: {
lib: {
entry: entryFile,
@@ -110,20 +271,18 @@ export async function buildPlugin({ dir, manifest, pluginDir }) {
});
return true;
} catch (err) {
// eslint-disable-next-line no-console
console.error(`[sync] ❌ Build failed for ${dir}:`, err.message);
return false;
}
}
export function syncToPublic({ dir, manifest, pluginDir }) {
export function syncToPublic({ dir, manifest, pluginDir }, { quiet = false } = {}) {
const publicName = manifest.id || dir.replace("wwv-plugin-", "");
const targetDir = path.join(OUTPUT_DIR, publicName);
const distFile = path.join(pluginDir, "dist", "frontend.mjs");
const distMap = path.join(pluginDir, "dist", "frontend.mjs.map");
if (!fs.existsSync(distFile)) {
// eslint-disable-next-line no-console
console.warn(`[sync] ⚠ No dist for ${dir}, skipping sync`);
return;
}
@@ -154,8 +313,7 @@ export function syncToPublic({ dir, manifest, pluginDir }) {
JSON.stringify(pluginJson, null, 2)
);
// eslint-disable-next-line no-console
console.log(`[sync] ✅ ${publicName} → public/plugins-local/${publicName}/`);
if (!quiet) console.log(`[sync] ✅ ${publicName} → public/plugins-local/${publicName}/`);
}
// Clean stale plugins from public/plugins-local/ that no longer exist in local-plugins/
@@ -165,29 +323,60 @@ function cleanStale(activeIds) {
for (const dir of fs.readdirSync(OUTPUT_DIR)) {
if (!activeSet.has(dir)) {
fs.rmSync(path.join(OUTPUT_DIR, dir), { recursive: true, force: true });
// eslint-disable-next-line no-console
console.log(`[sync] 🗑 Removed stale plugin: ${dir}`);
}
}
}
/**
* @function runWithConcurrency
* @description Runs an async worker over `items` with a fixed concurrency cap.
* Vite builds are CPU-bound; running all ~30 in parallel thrashes the scheduler
* and balloons RSS. A cap around half the logical cores keeps wall-clock low
* without starving the rest of the dev environment (Next.js, the data engine).
* @template T, R
* @param {T[]} items
* @param {number} concurrency
* @param {(item: T) => Promise<R>} worker
* @returns {Promise<R[]>}
*/
async function runWithConcurrency(items, concurrency, worker) {
const results = new Array(items.length);
let cursor = 0;
const workers = Array.from({ length: Math.min(concurrency, items.length) }, async () => {
while (true) {
const i = cursor++;
if (i >= items.length) return;
results[i] = await worker(items[i]);
}
});
await Promise.all(workers);
return results;
}
export async function syncAll() {
const plugins = discoverLocalPlugins();
if (plugins.length === 0) {
// eslint-disable-next-line no-console
console.log("[sync] No local plugins found.");
cleanStale([]);
return;
}
// eslint-disable-next-line no-console
console.log(`[sync] Found ${plugins.length} local plugin(s): ${plugins.map(p => p.dir).join(", ")}`);
const concurrency = Math.max(2, Math.min(plugins.length, Math.ceil(os.cpus().length / 2)));
console.log(`[sync] Found ${plugins.length} local plugin(s); building with concurrency=${concurrency}`);
const started = Date.now();
for (const plugin of plugins) {
const ok = await buildPlugin(plugin);
if (ok) syncToPublic(plugin);
}
let freshCount = 0;
let builtCount = 0;
await runWithConcurrency(plugins, concurrency, async (plugin) => {
const result = await buildPlugin(plugin);
if (result === "fresh") freshCount++;
else if (result) builtCount++;
if (result) syncToPublic(plugin, { quiet: result === "fresh" });
});
console.log(`[sync] Done in ${((Date.now() - started) / 1000).toFixed(1)}s (${builtCount} built, ${freshCount} cached)`);
const activeIds = plugins.map(p => p.manifest.id || p.dir.replace("wwv-plugin-", ""));
cleanStale(activeIds);
@@ -197,7 +386,6 @@ export async function syncAll() {
const isDirectRun = process.argv[1] && path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url));
if (isDirectRun) {
syncAll().catch(err => {
// eslint-disable-next-line no-console
console.error("[sync] Fatal:", err);
process.exit(1);
});
-21
View File
@@ -6,9 +6,7 @@ import net from 'node:net';
// 1. Get branch argument
const branchName = process.argv[2];
if (!branchName) {
// eslint-disable-next-line no-console
console.error('\x1b[31mError: Please provide a worktree branch name.\x1b[0m');
// eslint-disable-next-line no-console
console.error('Usage: pnpm run test-worktree <branch-name>');
process.exit(1);
}
@@ -35,7 +33,6 @@ try {
}
}
} catch (err) {
// eslint-disable-next-line no-console
console.warn('\x1b[33mWarning: Failed to parse git worktree list.\x1b[0m');
}
@@ -47,52 +44,41 @@ if (!worktreePath) {
// 3. Validate worktree exists
if (!fs.existsSync(worktreePath)) {
// eslint-disable-next-line no-console
console.error(`\x1b[31mError: Worktree directory not found for branch '${branchName}'\x1b[0m`);
// eslint-disable-next-line no-console
console.error(`Searched path: ${worktreePath}`);
// eslint-disable-next-line no-console
console.error(`Ensure you have created it using 'git worktree add <path> -b ${branchName}'`);
process.exit(1);
}
// 3. Setup Environment
// eslint-disable-next-line no-console
console.log(`\x1b[34m[1/5] Checking environment in ${worktreePath}...\x1b[0m`);
const rootEnvPath = path.join(rootDir, '.env.local');
const worktreeEnvPath = path.join(worktreePath, '.env.local');
if (!fs.existsSync(worktreeEnvPath) && fs.existsSync(rootEnvPath)) {
fs.copyFileSync(rootEnvPath, worktreeEnvPath);
// eslint-disable-next-line no-console
console.log('Copied .env.local from root.');
}
// 4. Install Dependencies
// eslint-disable-next-line no-console
console.log(`\x1b[34m[2/5] Symlinking modules and generating local clients...\x1b[0m`);
// eslint-disable-next-line no-console
console.log('Running pnpm install in worktree...');
execSync('pnpm install', { cwd: worktreePath, stdio: 'inherit' });
// eslint-disable-next-line no-console
console.log('Generating Prisma Clients (Root)...');
execSync('npx prisma generate', { cwd: worktreePath, stdio: 'inherit' });
// eslint-disable-next-line no-console
console.log('Generating Prisma Clients (Data Engine)...');
const enginePath = path.join(worktreePath, 'packages', 'wwv-data-engine');
if (fs.existsSync(enginePath)) {
try {
execSync('npx prisma generate', { cwd: enginePath, stdio: 'inherit' });
} catch (err) {
// eslint-disable-next-line no-console
console.warn('\x1b[33m[Warning] Could not generate Data Engine Prisma client. This happens on Windows when another workspace is running and locking the shared pnpm DLL. It is safe to ignore as the client already exists in the cache.\x1b[0m');
}
}
// 5. Setup databases
// eslint-disable-next-line no-console
console.log(`\x1b[34m[3/5] Setting up local databases...\x1b[0m`);
const rootDataDir = path.join(worktreePath, 'data');
const engineDataDir = path.join(enginePath, 'data');
@@ -122,18 +108,14 @@ function findFreePort(startPort) {
// 7. Start the Servers
async function start() {
// eslint-disable-next-line no-console
console.log(`\x1b[34m[4/5] Assigning isolated ports...\x1b[0m`);
// Start scanning *after* the default main dev ports to absolutely ensure we don't accidentally grab them
const frontendPort = await findFreePort(3002);
const backendPort = await findFreePort(5002);
// eslint-disable-next-line no-console
console.log(`Next.js Frontend Port: \x1b[32m${frontendPort}\x1b[0m`);
// eslint-disable-next-line no-console
console.log(`Data Engine Backend Port: \x1b[32m${backendPort}\x1b[0m`);
// eslint-disable-next-line no-console
console.log(`\x1b[34m[4/5] Booting isolated servers...\x1b[0m`);
// Start Backend First
@@ -167,11 +149,9 @@ async function start() {
frontendProcess.stderr.on('data', (data) => process.stderr.write(`[\x1b[31mNext.js Error\x1b[0m] ${data}`));
// 7. Open Browser
// eslint-disable-next-line no-console
console.log(`\x1b[34m[5/5] Launching browser...\x1b[0m`);
setTimeout(() => {
const url = `http://localhost:${frontendPort}`;
// eslint-disable-next-line no-console
console.log(`Opening \x1b[32m${url}\x1b[0m...`);
const startCmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open';
execSync(`${startCmd} ${url}`);
@@ -184,5 +164,4 @@ async function start() {
});
}
// eslint-disable-next-line no-console
start().catch(console.error);
+36 -16
View File
@@ -15,62 +15,82 @@ if (!fs.existsSync(LOCAL_PLUGINS_DIR)) {
let debounceTimeout = null;
let isSyncing = false;
let pendingSync = false;
/** Files changed since last sync completed — collected during the debounce window */
const pendingChanges = new Set();
function handleFileChange(eventType, filename) {
if (filename && (
filename.includes("dist") ||
filename.includes("node_modules") ||
if (!filename) return;
if (
filename.includes("dist") ||
filename.includes("node_modules") ||
filename.endsWith(".map") ||
filename.includes(".git")
)) return; // ignore build artifacts and git internals
) return; // ignore build artifacts and git internals
pendingChanges.add(filename);
if (debounceTimeout) {
clearTimeout(debounceTimeout);
}
debounceTimeout = setTimeout(async () => {
if (isSyncing) {
pendingSync = true;
return;
}
await runSync(filename);
await runSync();
}, 500);
}
async function runSync(filename) {
/**
* Pulls plugin slugs out of changed file paths so we can name what triggered the rebuild.
* fs.watch on `local-plugins/` emits paths like `aviation/src/index.ts` (POSIX or Windows).
*/
function summarizeChangedPlugins(files) {
const slugs = new Set();
for (const f of files) {
const head = f.split(/[\\/]/)[0];
if (head) slugs.add(head);
}
return [...slugs];
}
async function runSync() {
isSyncing = true;
// eslint-disable-next-line no-console
console.log(`\n[watch] Change detected in local plugins (file: ${filename}). Syncing...`);
const changed = summarizeChangedPlugins(pendingChanges);
pendingChanges.clear();
const label = changed.length === 0
? "pending changes"
: changed.length <= 3
? changed.join(", ")
: `${changed.slice(0, 3).join(", ")} (+${changed.length - 3} more)`;
console.log(`\n[watch] 🔄 Change detected in: ${label}`);
try {
await syncAll();
console.log(`[watch] ✨ Hot-reload ready`);
} catch (err) {
// eslint-disable-next-line no-console
console.error(`[watch] Sync failed:`, err);
} finally {
isSyncing = false;
if (pendingSync) {
pendingSync = false;
await runSync("pending changes");
await runSync();
}
}
}
// Initial sync
// eslint-disable-next-line no-console
console.log(`[watch] Starting initial sync...`);
isSyncing = true;
syncAll().then(() => {
isSyncing = false;
if (pendingSync) {
pendingSync = false;
// eslint-disable-next-line no-console
runSync("pending changes").catch(console.error);
}
// eslint-disable-next-line no-console
console.log(`[watch] Watching ${LOCAL_PLUGINS_DIR} for changes...`);
fs.watch(LOCAL_PLUGINS_DIR, { recursive: true }, handleFileChange);
}).catch(err => {
isSyncing = false;
// eslint-disable-next-line no-console
console.error(`[watch] Initial sync failed:`, err);
});
-2
View File
@@ -48,8 +48,6 @@ export async function GET() {
}
}, 25_000);
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(controller as any)._cleanup = () => {
clearInterval(heartbeat);
unsubscribe();
-2
View File
@@ -21,8 +21,6 @@ export async function GET(request: Request) {
for (const [k, v] of Object.entries(headers)) res.headers.set(k, v);
return res;
} catch (err) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("[setup-status] Database error:", err);
const res = NextResponse.json(
{ error: "database_unavailable", edition },
+1 -5
View File
@@ -13,15 +13,11 @@ export async function POST(req: Request) {
sig!,
process.env.STRIPE_WEBHOOK_SECRET!
);
} // TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
catch (err: any) {
} catch (err: any) {
return new NextResponse(`Webhook Error: ${err.message}`, { status: 400 });
}
if (event.type === "checkout.session.completed") {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.log("Subscription completed!");
// Update user tier in DB, send license key via email
}
+1 -3
View File
@@ -124,9 +124,7 @@ export async function fetchAdapter(adapter: CameraAdapter): Promise<CameraFeatur
fetchedAt: new Date(now).toISOString(),
});
return data;
} // TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
catch (e: any) {
} catch (e: any) {
const errMsg = e?.message ?? String(e);
if (c) {
cache.set(adapter.id, { ...c, error: errMsg });
@@ -15,8 +15,6 @@ function districtUrl(d: number): string {
return `https://cwwp2.dot.ca.gov/data/d${d}/cctv/cctvStatusD${padded}.json`;
}
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function toGeoJsonFeature(raw: any): GdotCameraFeature | null {
const cam = raw.cctv;
if (!cam?.location) return null;
+1 -5
View File
@@ -42,11 +42,7 @@ export async function GET(req: NextRequest) {
}
return NextResponse.json({ error: "Unsupported extractor platform" }, { status: 400 });
} // TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
catch (error: any) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
} catch (error: any) {
console.error("[CameraExtractor] Error:", error.message);
return NextResponse.json({ error: "Failed to extract stream" }, { status: 500 });
}
-2
View File
@@ -29,8 +29,6 @@ export interface GdotCameraFeature {
}
/** Convert a raw ArcGIS feature into our GeoJSON format. */
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function toGeoJsonFeature(raw: any): GdotCameraFeature | null {
const { attributes: a, geometry: g } = raw;
if (!g?.x || !g?.y) return null;
-2
View File
@@ -82,8 +82,6 @@ export async function GET(req: NextRequest) {
});
} catch (error: unknown) {
const message = error instanceof Error ? error.message : "Unknown error";
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("[IframeProxy] Error:", message);
return NextResponse.json(
{ error: "Failed to proxy iframe" },
+1 -5
View File
@@ -51,11 +51,7 @@ export async function GET(req: NextRequest) {
{ status: 502 },
);
}
} // TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
catch (error: any) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
} catch (error: any) {
console.error("[CameraProxy] Error fetching target URL:", error);
const status = error.message.includes("SSRF Error") ? 403 : 500;
return NextResponse.json(
-2
View File
@@ -62,8 +62,6 @@ export async function GET(req: NextRequest) {
});
} catch (error: unknown) {
const message = error instanceof Error ? error.message : "Unknown error";
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("[StreamProxy] Error:", message);
const status = message.includes("SSRF Error") ? 403 : 502;
return NextResponse.json(
+11 -11
View File
@@ -47,18 +47,19 @@ export async function GET(req: NextRequest) {
headers: { "User-Agent": "WorldWideView/1.0" },
signal: AbortSignal.timeout(TIMEOUT_MS)
});
} catch (headError: any) {
} catch (headError: unknown) {
const err = headError as Error & { cause?: { code?: string } };
// Primitive IP camera servers (like Insecam sources) often aggressively drop the TCP connection
// instead of returning 405 when they see an unsupported HTTP method like HEAD.
// If the socket was closed unexpectedly, retry with GET.
if (headError.cause?.code === 'UND_ERR_SOCKET' || headError.message?.includes('fetch failed')) {
if (err.cause?.code === 'UND_ERR_SOCKET' || err.message?.includes('fetch failed')) {
response = await fetch(url, {
method: "GET",
headers: { "User-Agent": "WorldWideView/1.0" },
signal: AbortSignal.timeout(TIMEOUT_MS)
});
} else {
throw headError;
throw err;
}
}
@@ -81,15 +82,14 @@ export async function GET(req: NextRequest) {
contentType: response.headers.get("content-type"),
latencyMs: Date.now() - startTime
});
} // TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
catch (error: any) {
const realError = error.cause || error;
const code = realError?.code || error?.code || realError?.name || error?.name;
} catch (error: unknown) {
const err = error as Error & { cause?: { code?: string, message?: string, name?: string }, code?: string };
const realError = err.cause || err;
const code = realError?.code || err?.code || realError?.name || err?.name;
let displayError = error?.message || "Unknown error";
let displayError = err?.message || "Unknown error";
if (code && code !== 'TypeError' && code !== 'Error') {
displayError = `[${code}] ${realError?.message || error?.message || ""}`;
displayError = `[${code}] ${realError?.message || err?.message || ""}`;
}
// Make sure we don't accidentally categorize a malformed HTTP response as a timeout
@@ -97,7 +97,7 @@ export async function GET(req: NextRequest) {
return NextResponse.json({ status: "error", error: displayError, latencyMs: Date.now() - startTime });
}
if (error?.name === "TimeoutError" || displayError.includes("timeout") || code === "UND_ERR_CONNECT_TIMEOUT") {
if (err?.name === "TimeoutError" || displayError.includes("timeout") || code === "UND_ERR_CONNECT_TIMEOUT") {
return NextResponse.json({ status: "timeout", error: "Connection timed out", latencyMs: Date.now() - startTime });
}
-6
View File
@@ -11,18 +11,12 @@ import type { GdotCameraFeature } from "../gdot/gdotFetcher";
const TFL_URL = "https://api.tfl.gov.uk/Place/Type/JamCam";
/** Extract a named property from TfL additionalProperties array. */
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function getProp(props: any[], key: string): string {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const found = props?.find((p: any) => p.key === key);
return found?.value || "";
}
/** Convert a raw TfL JamCam place into our GeoJSON format. */
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function toGeoJsonFeature(raw: any): GdotCameraFeature | null {
if (!raw.lat || !raw.lon) return null;
+1 -5
View File
@@ -31,11 +31,7 @@ export async function GET(req: NextRequest) {
total: cameras.length,
sources,
});
} // TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
catch (error: any) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
} catch (error: any) {
console.error("[TrafficCameras] Error:", error);
return NextResponse.json(
{ error: "Failed to fetch traffic cameras" },
-2
View File
@@ -76,8 +76,6 @@ export async function fetchWsdotCameras(): Promise<GdotCameraFeature[]> {
const key = process.env.WSDOT_API_KEY;
if (!key) {
if (!warnedMissingKey) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.warn(
"[WSDOT] WSDOT_API_KEY not set — skipping. "
+ "Get a free key at https://wsdot.wa.gov/traffic/api/",
-2
View File
@@ -50,8 +50,6 @@ export async function POST(request: Request) {
{ status: 200, headers: { "Access-Control-Allow-Origin": "*" } }
);
} catch (err) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("[Load Unpacked] Error:", err);
return NextResponse.json(
{ error: "Failed to parse or load unpacked manifest" },
-4
View File
@@ -4,8 +4,6 @@ export const revalidate = 120;
const FEED_URL = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson";
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function isValidFeature(feature: any): boolean {
const coordinates = feature?.geometry?.coordinates;
const time = feature?.properties?.time;
@@ -46,8 +44,6 @@ export async function GET() {
features,
});
} catch (error) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("[EarthquakeRoute] Error:", error);
return NextResponse.json(
{ error: "Failed to fetch earthquake feed" },
+1 -7
View File
@@ -24,18 +24,12 @@ export async function POST(req: NextRequest) {
if (!response.ok) {
const errorText = await response.text();
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("GlitchTip tunnel rejected payload:", response.status, errorText);
return NextResponse.json({ status: "error", message: "GlitchTip rejected payload" }, { status: response.status });
}
return NextResponse.json({ status: "ok" });
} // TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
catch (error: any) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
} catch (error: any) {
console.error("GlitchTip tunnel internal error:", error);
return NextResponse.json({ status: "error", message: "Tunnel relay failed" }, { status: 500 });
}
@@ -26,8 +26,6 @@ export async function GET(
return NextResponse.json(workspace);
} catch (e) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("Failed to lookup workspace", e);
return NextResponse.json({ error: "Internal server error" }, { status: 500 });
}
+88
View File
@@ -0,0 +1,88 @@
import { NextResponse } from "next/server";
export const revalidate = 60;
const WTIA_POSITIONS_URL = "https://api.wheretheiss.at/v1/satellites/25544/positions";
const MAX_TIMESTAMPS = 10;
function isValidPosition(item: any): boolean {
return (
item != null
&& typeof item === "object"
&& Number.isFinite(item.latitude)
&& Number.isFinite(item.longitude)
&& Number.isFinite(item.altitude)
&& Number.isFinite(item.velocity)
&& Number.isFinite(item.timestamp)
);
}
export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const timestampsParam = searchParams.get("timestamps");
if (!timestampsParam) {
return NextResponse.json(
{ error: "Missing required 'timestamps' query parameter" },
{ status: 400 },
);
}
const timestamps = timestampsParam
.split(",")
.map((t) => t.trim())
.filter((t) => /^\d+$/.test(t));
if (timestamps.length === 0) {
return NextResponse.json(
{ error: "No valid timestamps provided" },
{ status: 400 },
);
}
if (timestamps.length > MAX_TIMESTAMPS) {
return NextResponse.json(
{ error: `Maximum ${MAX_TIMESTAMPS} timestamps allowed per request` },
{ status: 400 },
);
}
try {
const url = `${WTIA_POSITIONS_URL}?timestamps=${timestamps.join(",")}&units=kilometers`;
const response = await fetch(url, {
headers: {
Accept: "application/json",
"User-Agent": "WorldWideView/1.0",
},
next: { revalidate },
});
if (!response.ok) {
return NextResponse.json(
{ error: "Failed to fetch ISS positions" },
{ status: 502 },
);
}
const data = await response.json();
const positions = (Array.isArray(data) ? data : [])
.filter(isValidPosition)
.map((p) => ({
latitude: p.latitude,
longitude: p.longitude,
altitude: p.altitude,
velocity: p.velocity,
visibility: p.visibility,
timestamp: p.timestamp,
}));
return NextResponse.json({ positions });
} catch (error) {
console.error("[IssPositionsRoute] Error:", error);
return NextResponse.json(
{ error: "Failed to fetch ISS positions" },
{ status: 502 },
);
}
}
+64
View File
@@ -0,0 +1,64 @@
import { NextResponse } from "next/server";
export const revalidate = 10;
const WTIA_URL = "https://api.wheretheiss.at/v1/satellites/25544";
function isValidResponse(data: any): boolean {
return (
data != null
&& typeof data === "object"
&& Number.isFinite(data.latitude)
&& Number.isFinite(data.longitude)
&& Number.isFinite(data.altitude)
&& Number.isFinite(data.velocity)
&& Number.isFinite(data.timestamp)
);
}
export async function GET() {
try {
const response = await fetch(WTIA_URL, {
headers: {
Accept: "application/json",
"User-Agent": "WorldWideView/1.0",
},
next: { revalidate },
});
if (!response.ok) {
return NextResponse.json(
{ error: "Failed to fetch ISS position" },
{ status: 502 },
);
}
const data = await response.json();
if (!isValidResponse(data)) {
return NextResponse.json(
{ error: "Invalid ISS position data" },
{ status: 502 },
);
}
return NextResponse.json({
id: data.id,
name: data.name,
latitude: data.latitude,
longitude: data.longitude,
altitude: data.altitude,
velocity: data.velocity,
visibility: data.visibility,
footprint: data.footprint,
timestamp: data.timestamp,
units: data.units,
});
} catch (error) {
console.error("[IssRoute] Error:", error);
return NextResponse.json(
{ error: "Failed to fetch ISS position" },
{ status: 502 },
);
}
}
+60
View File
@@ -0,0 +1,60 @@
import { NextResponse } from "next/server";
export const revalidate = 3600;
const WTIA_TLE_URL = "https://api.wheretheiss.at/v1/satellites/25544/tles/latest";
function isValidTle(data: any): boolean {
return (
data != null
&& typeof data === "object"
&& typeof data.line1 === "string"
&& typeof data.line2 === "string"
&& data.line1.length > 0
&& data.line2.length > 0
&& Number.isFinite(data.tle_timestamp)
);
}
export async function GET() {
try {
const response = await fetch(WTIA_TLE_URL, {
headers: {
Accept: "application/json",
"User-Agent": "WorldWideView/1.0",
},
next: { revalidate },
});
if (!response.ok) {
return NextResponse.json(
{ error: "Failed to fetch ISS TLE data" },
{ status: 502 },
);
}
const data = await response.json();
if (!isValidTle(data)) {
return NextResponse.json(
{ error: "Invalid ISS TLE data" },
{ status: 502 },
);
}
return NextResponse.json({
id: data.id,
name: data.name,
header: data.header,
line1: data.line1,
line2: data.line2,
tleTimestamp: data.tle_timestamp,
});
} catch (error) {
console.error("[IssTleRoute] Error:", error);
return NextResponse.json(
{ error: "Failed to fetch ISS TLE data" },
{ status: 502 },
);
}
}
-2
View File
@@ -62,8 +62,6 @@ export async function POST(request: Request) {
return NextResponse.json({ error: `Unknown service: ${service}` }, { status: 400 });
}
} catch (err) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("[KeyVerify] Unexpected error:", err);
return NextResponse.json({ error: "Verification request failed" }, { status: 500 });
}
+1 -7
View File
@@ -30,8 +30,6 @@ export async function GET(req: NextRequest) {
try {
const tokens = await client.authorizationCodeGrant(
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config as any,
new URL(req.url),
{ expectedState: stateCookie, pkceCodeVerifier: verifierCookie }
@@ -56,11 +54,7 @@ export async function GET(req: NextRequest) {
}
});
}
} // TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
catch (err: any) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
} catch (err: any) {
console.error("[PKCE] Exchange failed:", err.message);
return NextResponse.json({ error: "Failed to exchange authorization code" }, { status: 500 });
}
@@ -14,8 +14,6 @@ export async function GET(request: Request) {
const installedPlugins = await getInstalledPlugins();
// Exclude built-in versions, only check genuine semver strings or unverified records.
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const updatablePlugins = installedPlugins.filter((p: any) => p.version !== "built-in");
if (updatablePlugins.length === 0) {
@@ -53,8 +51,6 @@ export async function GET(request: Request) {
return NextResponse.json({ updates });
} catch (err) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("[marketplace/check-updates] Error:", err);
return NextResponse.json(
{ error: "Failed to check for updates" },
-2
View File
@@ -38,8 +38,6 @@ export async function POST(request: Request) {
await disablePlugin(pluginId);
return withCors(NextResponse.json({ status: "disabled", pluginId }), request);
} catch (err) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("[marketplace/disable] Error:", err);
return withCors(
NextResponse.json({ error: "Disable failed" }, { status: 500 }),
@@ -24,8 +24,6 @@ export async function GET(request: Request) {
request,
);
} catch (err) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("[marketplace/disabled-builtins] Error:", err);
return withCors(
NextResponse.json({ disabledIds: [] }),
-2
View File
@@ -38,8 +38,6 @@ export async function POST(request: Request) {
await enablePlugin(pluginId);
return withCors(NextResponse.json({ status: "enabled", pluginId }), request);
} catch (err) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("[marketplace/enable] Error:", err);
return withCors(
NextResponse.json({ error: "Enable failed" }, { status: 500 }),
@@ -73,8 +73,6 @@ export async function GET(request: NextRequest) {
// Token in fragment — never sent to server in logs/referer
return NextResponse.redirect(`${dest.toString()}#token=${token}`);
} catch (err) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("[grant-token] Unexpected error:", err);
return NextResponse.json({ error: "Internal server error" }, { status: 500 });
}
@@ -104,8 +104,6 @@ export async function GET(request: NextRequest) {
try {
await upsertPlugin(pluginId, version, JSON.stringify(manifest));
} catch (err) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("[install-redirect] upsertPlugin failed:", err);
if (isSafeRedirect(redirectTo)) {
const errorUrl = new URL(redirectTo);
@@ -130,8 +128,6 @@ export async function GET(request: NextRequest) {
return NextResponse.redirect(`${successUrl.toString()}#token=${token}`);
} catch (err) {
// Top-level catch: log and redirect to marketplace with error, don't expose raw 500
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("[install-redirect] Unexpected error:", err);
if (isSafeRedirect(redirectTo)) {
const errorUrl = new URL(redirectTo);
-10
View File
@@ -30,8 +30,6 @@ export async function POST(request: Request) {
try {
const body = await request.json();
const { pluginId, version, manifest } = body;
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.log(`[Marketplace Install Route] Installing plugin: ${pluginId} v${version || "1.0.0"}`);
if (!pluginId || typeof pluginId !== "string") {
@@ -64,8 +62,6 @@ export async function POST(request: Request) {
}
}
} catch (e) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error(`[Marketplace Install Route] Failed to fetch manifest for ${pluginId}`, e);
}
}
@@ -74,8 +70,6 @@ export async function POST(request: Request) {
if (finalManifest) {
const validation = validateManifest(finalManifest);
if (!validation.valid) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error(
`[Marketplace Install Route] ❌ MANIFEST VALIDATION FAILED for ${pluginId}\n`
+ `Errors: ${validation.errors.join(", ")}\n`
@@ -92,8 +86,6 @@ export async function POST(request: Request) {
} else {
// We cannot proceed safely if we don't have a manifest and it's missing from DB.
// If we do have an existing db record, we could technically merge, but we'll enforce manifest req here.
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.warn(`[Marketplace Install] No manifest provided or found for ${pluginId}`);
}
@@ -117,8 +109,6 @@ export async function POST(request: Request) {
request,
);
} catch (err) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("[Bridge/install] Error:", err);
return withCors(
NextResponse.json(
+3 -19
View File
@@ -42,8 +42,6 @@ export async function GET(request: Request) {
]);
// Support local sandbox workflows by checking /public/plugins-local
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const localPlugins: any[] = [];
try {
if (process.env.NODE_ENV === "development" || process.env.WWV_PLUGIN_DEV === "true") {
@@ -56,8 +54,6 @@ export async function GET(request: Request) {
const config = fs.readFileSync(manifestPath, "utf-8");
localPlugins.push({ pluginId: folder, config });
} catch (e) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error(`Error reading local plugin ${folder}:`, e);
}
}
@@ -65,17 +61,13 @@ export async function GET(request: Request) {
}
}
} catch (e) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("Error scanning local plugins directory:", e);
}
const allRecords = [...records, ...localPlugins];
const manifests = allRecords
.// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
map((r: any): PluginManifest | null => {
.map((r: any): PluginManifest | null => {
try {
const manifest = JSON.parse(r.config);
if (!manifest.id) manifest.id = r.pluginId;
@@ -85,9 +77,7 @@ export async function GET(request: Request) {
return null;
}
})
.// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
filter((m: any): m is PluginManifest => {
.filter((m: any): m is PluginManifest => {
if (!m) return false;
// Skip built-in plugins — already registered by AppShell
if (m.trust === "built-in") return false;
@@ -110,8 +100,6 @@ export async function GET(request: Request) {
const validation = validateManifest(m);
if (!validation.valid) {
const errorMessage = `Manifest validation failed for ${m.id}`;
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error(`[Marketplace API] ${errorMessage}:`, validation.errors);
// Capture in Sentry so we have visibility into malformed third-party plugins
@@ -126,9 +114,7 @@ export async function GET(request: Request) {
}
return validation.valid;
})
.// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
map((m: any) => {
.map((m: any) => {
// Re-stamp trust against the live registry so revoked plugins
// are correctly gated by the unverified dialog on the client.
if (m.trust !== "built-in") {
@@ -154,8 +140,6 @@ export async function GET(request: Request) {
return withCors(NextResponse.json({ manifests }), request);
} catch (err) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("[Marketplace/load] Error:", err);
return withCors(NextResponse.json({ manifests: [] }), request);
}
@@ -33,8 +33,6 @@ export async function POST(request: Request) {
return NextResponse.json({ status: "sideloaded", manifest });
} catch (err) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("[Sideload] Error:", err);
return NextResponse.json(
{ error: "Sideload failed" },
-4
View File
@@ -25,8 +25,6 @@ export async function GET(request: Request) {
try {
const dbPlugins = await getInstalledPlugins();
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const dbMap = new Map(dbPlugins.map((p: any) => [p.pluginId, p]));
// Collect all DB plugins (enabled and disabled)
@@ -40,8 +38,6 @@ export async function GET(request: Request) {
return withCors(NextResponse.json({ plugins, canManagePlugins }), request);
} catch (err) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("[marketplace/status] Error:", err);
let canManagePlugins = !isDemo;
if (isDemo) {
@@ -50,8 +50,6 @@ export async function POST(request: Request) {
return withCors(NextResponse.json({ status: "uninstalled", pluginId }), request);
} catch (err) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("[marketplace/uninstall] Error:", err);
return withCors(
NextResponse.json({ error: "Uninstall failed" }, { status: 500 }),
-6
View File
@@ -17,8 +17,6 @@ export async function GET(request: Request) {
const isValidUserKey = userKey && userKey.length >= 20;
const apiKey = isValidUserKey ? userKey : process.env.GOOGLE_MAPS_API_KEY;
if (!apiKey) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("GOOGLE_MAPS_API_KEY is not defined and no user key provided");
return NextResponse.json({ error: "Server configuration error" }, { status: 500 });
}
@@ -40,8 +38,6 @@ export async function GET(request: Request) {
const data = await response.json();
if (data.status !== "OK") {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("Google Places Details API Error:", data);
return NextResponse.json({ error: "Failed to fetch place details" }, { status: 500 });
}
@@ -61,8 +57,6 @@ export async function GET(request: Request) {
cache.set(cacheId, { data: result, expiresAt: Date.now() + TTL_MS });
return NextResponse.json(result);
} catch (error) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("Error in Places Details route:", error);
return NextResponse.json({ error: "Internal server error" }, { status: 500 });
}
-8
View File
@@ -17,8 +17,6 @@ export async function GET(request: Request) {
const isValidUserKey = userKey && userKey.length >= 20;
const apiKey = isValidUserKey ? userKey : process.env.GOOGLE_MAPS_API_KEY;
if (!apiKey) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("GOOGLE_MAPS_API_KEY is not defined and no user key provided");
return NextResponse.json({ error: "Server configuration error" }, { status: 500 });
}
@@ -41,14 +39,10 @@ export async function GET(request: Request) {
const data = await response.json();
if (data.status !== "OK" && data.status !== "ZERO_RESULTS") {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("Google Places API Error:", data);
return NextResponse.json({ error: "Failed to fetch predictions" }, { status: 500 });
}
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const predictions = data.predictions.map((p: any) => ({
description: p.description,
placeId: p.place_id,
@@ -61,8 +55,6 @@ export async function GET(request: Request) {
cache.set(cacheKey, { data: result, expiresAt: Date.now() + TTL_MS });
return NextResponse.json(result);
} catch (error) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("Error in Places Autocomplete route:", error);
return NextResponse.json({ error: "Internal server error" }, { status: 500 });
}
+3 -27
View File
@@ -9,8 +9,6 @@ const OVERPASS_MIRRORS = [
];
async function tryMirror(urlStr: string, query: string, timeoutMs: number) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return new Promise<any>((resolve, reject) => {
const url = new URL(urlStr);
const bodyStr = `data=${encodeURIComponent(query)}`;
@@ -58,15 +56,11 @@ export async function POST(req: Request) {
return NextResponse.json({ error: "Missing query" }, { status: 400 });
}
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.log(`[OSMSearchProxy] Querying Overpass API mirrors... (length: ${query.length})`);
let lastError = null;
for (const mirror of OVERPASS_MIRRORS) {
try {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.log(`[OSMSearchProxy] Trying mirror: ${mirror}`);
const res = await tryMirror(mirror, query, 25000); // 25s per mirror
@@ -76,16 +70,12 @@ export async function POST(req: Request) {
return NextResponse.json({ data: data.elements });
}
if (data.remark) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.warn(`[OSMSearchProxy] ${mirror} returned remark: ${data.remark}`);
// If it's a specific query error (remark), don't bother retrying mirrors
return NextResponse.json({ error: data.remark }, { status: 400 });
}
} else {
const text = await res.text();
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.warn(`[OSMSearchProxy] Mirror ${mirror} failed: ${res.status} ${res.statusText}`);
lastError = { status: res.status, statusText: res.statusText, details: text };
// If it's a 4xx error (except 429), it's probably a bad query, so don't retry
@@ -93,20 +83,10 @@ export async function POST(req: Request) {
break;
}
}
} // TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
catch (err: any) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
} catch (err: any) {
console.warn(`[OSMSearchProxy] Mirror ${mirror} threw error:`);
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.warn(err);
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
if (err instanceof Error)
// eslint-disable-next-line no-console
console.warn(err.stack);
if (err instanceof Error) console.warn(err.stack);
lastError = { status: 500, statusText: "Internal Error", details: String(err && err.message ? err.message : err) };
}
}
@@ -115,11 +95,7 @@ export async function POST(req: Request) {
{ error: "All Overpass mirrors failed or timed out. The OSM servers are likely under heavy load." },
{ status: 504 }
);
} // TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
catch (e: any) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
} catch (e: any) {
console.error(`[OSMSearchProxy] Internal error:`, e);
return NextResponse.json({ error: "Internal server error" }, { status: 500 });
}
+1 -5
View File
@@ -20,11 +20,7 @@ export async function GET() {
const data = await response.json();
return NextResponse.json(data);
} // TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
catch (error: any) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
} catch (error: any) {
console.error("[UnderseaCablesProxy] Error:", error);
return NextResponse.json(
{ error: "Failed to proxy request" },
-6
View File
@@ -16,8 +16,6 @@ export async function GET(request: Request) {
return NextResponse.json(favorites);
} catch (e) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("GET Favorites Error:", e);
return NextResponse.json({ error: "Failed to fetch favorites" }, { status: 500 });
}
@@ -60,8 +58,6 @@ export async function POST(request: Request) {
return NextResponse.json(fav);
} catch (e) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("POST Favorites Error:", e);
return NextResponse.json({ error: "Failed to create favorite" }, { status: 500 });
}
@@ -92,8 +88,6 @@ export async function DELETE(request: Request) {
return NextResponse.json({ success: true });
} catch (e) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("DELETE Favorites Error:", e);
return NextResponse.json({ error: "Failed to delete favorite" }, { status: 500 });
}
+7 -4
View File
@@ -3,15 +3,18 @@ import { CameraStream } from "@/components/video/CameraStream";
import styles from "./page.module.css";
import type { TestResult } from "./types";
function LiveTimer({ start }: { start: number }) {
const [now, setNow] = useState(Date.now());
function LiveTimer({ start }: { start?: number }) {
const [now, setNow] = useState(() => Date.now());
const [fallbackStart] = useState(() => Date.now());
const effectiveStart = start || fallbackStart;
useEffect(() => {
const interval = setInterval(() => setNow(Date.now()), 100);
return () => clearInterval(interval);
}, []);
return (
<span>
{(Math.max(0, now - start) / 1000).toFixed(1)}
{(Math.max(0, now - effectiveStart) / 1000).toFixed(1)}
s
</span>
);
@@ -53,7 +56,7 @@ export function CameraTestCard({
{status === "testing" ? (
<>
Testing...
<LiveTimer start={result.testStartTime || Date.now()} />
<LiveTimer start={result.testStartTime} />
</>
) : (
status.toUpperCase()
+22 -28
View File
@@ -2,6 +2,7 @@ import {
useState, useRef, useEffect, useCallback
} from "react";
import type { TestResult } from "./types";
import type { GdotCameraFeature } from "@/app/api/camera/gdot/gdotFetcher";
export function useCameraTestRunner(testSources: string[], testStatuses: string[]) {
const [cameras, setCameras] = useState<TestResult[]>([]);
@@ -15,56 +16,48 @@ export function useCameraTestRunner(testSources: string[], testStatuses: string[
const res = await fetch("/api/camera/traffic");
const data = await res.json();
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let staticFeatures: any[] = [];
let staticFeatures: GdotCameraFeature[] = [];
try {
const staticRes = await fetch("/public-cameras.json");
if (staticRes.ok) {
const staticData = await staticRes.json();
if (staticData.features) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
staticFeatures = staticData.features.map((f: any) => ({
...f,
properties: {
...f.properties,
name: f.properties.city || f.properties.region || "Public Camera",
source: f.properties.source || "cameras_json"
}
}));
staticFeatures = staticData.features.map((f: Record<string, unknown>) => {
const props = (f.properties || {}) as Record<string, unknown>;
return {
...f,
properties: {
...props,
name: props.city || props.region || "Public Camera",
source: props.source || "cameras_json"
}
} as unknown as GdotCameraFeature;
});
}
}
} catch (staticErr) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("Failed to fetch static cameras:", staticErr);
void staticErr; // Ignore static fetch errors
}
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let combinedFeatures: any[] = [];
let combinedFeatures: GdotCameraFeature[] = [];
if (data.cameras) {
combinedFeatures = [...data.cameras];
}
combinedFeatures = [...combinedFeatures, ...staticFeatures];
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
setCameras(combinedFeatures.map((c: any) => ({
setCameras(combinedFeatures.map((c: GdotCameraFeature) => ({
feature: c,
status: "pending"
})));
} catch (err) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error(err);
void err; // Ignore errors
}
setLoading(false);
}, []);
useEffect(() => {
fetchCameras();
// eslint-disable-next-line react-hooks/set-state-in-effect
void fetchCameras();
}, [fetchCameras]);
const runTests = async () => {
@@ -216,13 +209,14 @@ export function useCameraTestRunner(testSources: string[], testStatuses: string[
};
return nextState;
});
} catch (err: any) {
} catch (err: unknown) {
const errorMsg = err instanceof Error ? err.message : String(err);
setCameras((prev) => {
const nextState = [...prev];
nextState[globalIndex] = {
...nextState[globalIndex],
status: "error",
errorMsg: err.message
errorMsg
};
return nextState;
});
-2
View File
@@ -47,8 +47,6 @@ export function AdUnit({
(window.adsbygoogle = window.adsbygoogle || []).push({});
pushed.current = true;
} catch (err) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("[AdUnit] AdSense push error:", err);
}
}
-4
View File
@@ -102,8 +102,6 @@ export function FeedbackDialog() {
stream.getTracks().forEach((t) => t.stop());
} catch (err) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("Screen capture failed or was cancelled:", err);
} finally {
setTakingScreenshot(false);
@@ -155,8 +153,6 @@ export function FeedbackDialog() {
setScreenshots([]);
setFeedbackDialogOpen(false);
} catch (error) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("Failed to submit feedback:", error);
showErrorToast("Failed to submit feedback. Please try again later.");
} finally {
@@ -43,8 +43,6 @@ export class PluginErrorBoundary extends Component<Props, State> {
}
public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error(`[PluginErrorBoundary] Plugin component '${this.props.pluginId}' crashed during render and was isolated:`, error);
}
+1 -2
View File
@@ -102,6 +102,7 @@ export function AgentBusSubscriber() {
const buildId = process.env.NEXT_PUBLIC_WWV_BUILD_ID ?? "dev";
const builtAt = process.env.NEXT_PUBLIC_WWV_BUILD_AT ?? "";
const agentBusEnabled = process.env.NEXT_PUBLIC_WWV_AGENT_BUS_ENABLED === "true";
// eslint-disable-next-line no-console
console.log(
`[wwv build] id=${buildId} built_at=${builtAt} agent_bus=${agentBusEnabled ? "on" : "off"}`,
);
@@ -115,7 +116,6 @@ export function AgentBusSubscriber() {
const msg = JSON.parse(event.data) as AgentMessage;
applyAction(msg);
} catch (err) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.warn("[AgentBus] malformed message", err);
}
@@ -123,7 +123,6 @@ export function AgentBusSubscriber() {
es.onerror = (err) => {
// EventSource auto-reconnects on its own with the `retry:` value
// we send from the server. Just log; don't tear down.
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.debug("[AgentBus] stream error (auto-reconnecting)", err);
};
+19 -15
View File
@@ -62,9 +62,7 @@ export function AppShell() {
const initLayer = useStore((s) => s.initLayer);
const boot = useBootSequence();
const isMobile = useIsMobile();
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line react-hooks/purity
const bootStartRef = useRef(Date.now());
const [bootStart] = useState(() => Date.now());
const [hostReady, setHostReady] = useState(false);
const {
needsReload, pendingUnverified, approveSelected, denyAll
@@ -84,8 +82,6 @@ export function AppShell() {
useEffect(() => {
const startPlatform = async () => {
initLogCatcher();
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.log("[AppShell] Initializing Platform...");
// Inject host libraries for dynamic plugin loading
@@ -130,22 +126,30 @@ export function AppShell() {
}
}
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.log("[AppShell] Platform Ready. Waiting for globe tiles...");
};
// Start boot sequence when globe tiles are loaded
const unsubGlobe = dataBus.on("globeReady", () => {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.log("[AppShell] Globe ready — starting boot sequence.");
// Guard so boot only starts once regardless of which trigger fires first.
let bootStarted = false;
const startBootOnce = (reason: string) => {
if (bootStarted) return;
bootStarted = true;
console.log(`[AppShell] Starting boot sequence (${reason}).`);
boot.startBoot();
});
};
// Primary trigger: globe signals it is ready.
const unsubGlobe = dataBus.on("globeReady", () => startBootOnce("globeReady"));
// Safety fallback: if the globe never initialises (e.g. WebGL unavailable
// in headless CI environments), force the boot sequence after 20 s so the
// app still reaches the "ready" state and tests are not left hanging.
const safetyTimer = setTimeout(() => startBootOnce("safety-timeout"), 20_000);
startPlatform();
return () => {
clearTimeout(safetyTimer);
unsubGlobe();
boot.cleanup();
pluginManager.destroy();
@@ -161,10 +165,10 @@ export function AppShell() {
// Track when boot completes
useEffect(() => {
if (boot.phase === "ready") {
const duration = Date.now() - bootStartRef.current;
const duration = Date.now() - bootStart;
trackEvent("platform-boot", { duration });
}
}, [boot.phase]);
}, [boot.phase, bootStart]);
const activeBottomPanel = useStore((s) => s.activeBottomPanel);
const rootClasses = [
@@ -179,6 +179,7 @@ export function BottomPanelManager() {
<>
<div
className="bottom-panel-resize-handle"
data-testid="bottom-panel-resize-handle"
ref={resizeRef}
onMouseDown={() => setIsDragging(true)}
>
@@ -57,21 +57,13 @@ export function DataBusSubscriber() {
const unsubToggle = dataBus.on("layerToggled", ({ pluginId, enabled }) => {
const t0 = performance.now();
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.debug(`[DataBusSubscriber] layerToggled event received for ${pluginId}, enabled: ${enabled}`);
const engineUrl = resolveEngineUrl(pluginId);
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.debug(`[DataBusSubscriber] Resolved engine URL for ${pluginId} to ${engineUrl}. Took ${(performance.now() - t0).toFixed(2)}ms`);
if (enabled) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.debug(`[DataBusSubscriber] Calling wsClient.subscribe(${pluginId}, ${engineUrl})`);
wsClient.subscribe(pluginId, engineUrl);
} else {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.debug(`[DataBusSubscriber] Calling wsClient.unsubscribe(${pluginId}, ${engineUrl})`);
wsClient.unsubscribe(pluginId, engineUrl);
}
@@ -33,8 +33,6 @@ export function DevModeSubscriber() {
ws = new WebSocket("ws://localhost:24601/__wwv_dev__");
ws.onopen = () => {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.log("[DevMode] Connected to WWV Dev Server 🔧");
setConnected(true);
};
@@ -44,15 +42,11 @@ export function DevModeSubscriber() {
const data = JSON.parse(event.data);
if (data.type === "plugin:added") {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.log(`[DevMode] Plugin added from CLI: ${data.manifest.id}`);
await pluginManager.loadFromManifest(data.manifest);
initLayer(data.manifest.id, true);
await pluginManager.enablePlugin(data.manifest.id);
} else if (data.type === "plugin:updated") {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.log(`[DevMode] Reloading plugin: ${data.pluginId}`);
// Destroy and re-load from manifest for dev hot-reload
pluginManager.disablePlugin(data.pluginId);
@@ -62,22 +56,16 @@ export function DevModeSubscriber() {
await pluginManager.enablePlugin(data.manifest.id);
}
} else if (data.type === "plugin:error") {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error(`[DevMode] Dev Server Build Error: ${data.error}`);
useStore.getState().showErrorToast?.(`Build Error in ${data.pluginId}: ${data.error}`);
}
} catch (err) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.error("[DevMode] Error handling message:", err);
}
};
ws.onclose = () => {
if (connected) {
// TODO: Legacy Airbnb linting violation
// eslint-disable-next-line no-console
console.log("[DevMode] Disconnected from WWV Dev Server.");
setConnected(false);
}
Loaded 100 of 191 files, more files were not shown because too many files have changed in this diff. Show more