Compare commits
38
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7cd85e085c | ||
|
|
ccd0e7af78 | ||
|
|
58aac77a0b | ||
|
|
0462ab1f88 | ||
|
|
60fca4d540 | ||
|
|
dba5d49448 | ||
|
|
1633c7bb7b | ||
|
|
7eda6c50a4 | ||
|
|
f2ae2a7de7 | ||
|
|
3210b3bd15 | ||
|
|
9fad051f75 | ||
|
|
a818822023 | ||
|
|
012184af30 | ||
|
|
c1f7ffb5b4 | ||
|
|
6816081644 | ||
|
|
433004598d | ||
|
|
02d8355a83 | ||
|
|
89010b2425 | ||
|
|
0ff1d23e4a | ||
|
|
fd29865e7a | ||
|
|
42564b537f | ||
|
|
598e00171c | ||
|
|
b849bb2b4d | ||
|
|
fc7dd02ee2 | ||
|
|
caf1638fdc | ||
|
|
ad3c7845a5 | ||
|
|
339bf6c0f3 | ||
|
|
16c82c9184 | ||
|
|
ad324a6592 | ||
|
|
0a51e198d7 | ||
|
|
1d6381182e | ||
|
|
beb295445f | ||
|
|
dd62116351 | ||
|
|
d675d91441 | ||
|
|
fb07195ec2 | ||
|
|
1838f1a5cd | ||
|
|
28e4e67043 | ||
|
|
594f85afb2 |
No files matched your search
@@ -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]
|
||||
|
||||
@@ -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.
|
||||
@@ -39,6 +39,17 @@ Frontend runs at `http://localhost:3000`.
|
||||
- **Type-Level Contract Testing**: When defining shared TypeScript interfaces/contracts (e.g., in `wwv-plugin-sdk`), you MUST use `expectTypeOf` from `vitest` to assert the actual contract shapes at compile-time instead of writing literal-value identity runtime assertions. You must also enforce `@ts-expect-error` negative type tests to ensure missing or invalid fields trigger compilation errors.
|
||||
- **Key test files**: `rateLimit.test.ts`, `edition.test.ts`, `demoAdmin.test.ts`, `DeclarativePlugin.test.ts`, `cors.test.ts`, `repository.test.ts`, `marketplaceToken.test.ts`
|
||||
|
||||
### E2E Testing (Playwright)
|
||||
|
||||
WorldWideView uses Playwright for End-to-End browser testing to verify the complete UI integration including NextAuth.
|
||||
|
||||
- **Run**: `pnpm run test:e2e` (Ensure your database is running before executing)
|
||||
- **Auth Bypass**: Playwright uses a `global.setup.ts` to directly insert a test user into the database and simulate a UI login to capture a `storageState.json` cookie file. This allows all tests to run pre-authenticated without bypassing production security logic.
|
||||
- **Database Access in Setup**: Because Playwright setup scripts run in a vanilla Node context, importing Next.js backend utilities like `src/lib/db.ts` will crash with `next/headers` resolution errors. You MUST instantiate `PrismaClient` directly using `@prisma/adapter-pg` in any Playwright `setup` or `teardown` scripts.
|
||||
- **Component Synchronization**: Do not use arbitrary timeouts. Tests MUST wait for the application boot sequence to finish by waiting for the `[data-testid="app-ready"]` marker on the `AppShell` to be attached.
|
||||
- **Stable Selectors**: Always use `data-testid` properties (e.g. `data-testid="panel-toggle-left"`) for interacting with UI components in E2E tests rather than fragile CSS classes or dynamic text.
|
||||
- **Worktree Port Conflicts**: If you are testing in a git worktree, configure `playwright.config.ts` to spawn the `webServer` on an alternative port (e.g. `3001`) to avoid colliding with other running worktrees.
|
||||
|
||||
## Security Headers
|
||||
|
||||
Configured in `next.config.ts` `headers()`:
|
||||
@@ -248,6 +259,9 @@ The production Coolify instance runs on a local server at `192.168.68.64`. Direc
|
||||
1. Push to `silvertakana/worldwideview`
|
||||
2. Coolify webhook triggers → automated BuildKit deployment on the host server.
|
||||
|
||||
**GitHub Actions Workflows:**
|
||||
- **Minimal Permissions:** CodeQL and GitHub security best practices dictate that `GITHUB_TOKEN` permissions should always be explicitly constrained. When creating or modifying `.github/workflows/*.yml` files, you MUST always include an explicit `permissions` block (e.g., `permissions: { contents: read }` or similar required scopes) at the top level or job level to adhere to the principle of least privilege.
|
||||
|
||||
**Coolify Deployment Rules & Gotchas (The "Redis 500k" Rule):**
|
||||
- **Coolify Pulls from GitHub:** Coolify does *not* deploy your local workspace files. It strictly clones the repository from GitHub.
|
||||
- **Push Before You Deploy:** If you make a critical infrastructure or optimization fix locally (e.g., swapping a massive `HSET` pipeline for a compressed 5-min throttled `setLiveSnapshot`), you **must** `git commit` and `git push` those changes to the `main` branch before triggering a Coolify deployment.
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
---
|
||||
trigger: testing
|
||||
description: Guidelines and architecture for the Playwright End-to-End (E2E) testing infrastructure.
|
||||
globs:
|
||||
- "tests/**"
|
||||
- "public/e2e-fixtures/**"
|
||||
- "playwright.config.ts"
|
||||
---
|
||||
|
||||
# E2E Testing Infrastructure
|
||||
|
||||
The WorldWideView project uses **Playwright** for end-to-end (E2E) testing. This document outlines the boundaries, architectural decisions, and conventions required when authoring or modifying E2E tests.
|
||||
|
||||
## 1. Resource Constraints & Parallelism
|
||||
- **Worker Limits:** The Playwright configuration (`playwright.config.ts`) is strictly limited to a maximum of **2 workers**.
|
||||
- **Reasoning:** Running Next.js compilation alongside a heavy Prisma connection pool inside multiple parallel test workers will lead to database connection exhaustion and resource contention on CI and local environments. Do not increase the worker count beyond 2 without careful consideration of the database pool limits.
|
||||
|
||||
## 2. Test User Lifecycle
|
||||
E2E tests require an authenticated user to access core application features. We manage this test user securely to ensure the environment stays pristine:
|
||||
|
||||
- **Setup (`tests/global.setup.ts`):** Before tests run, the global setup script defensively deletes any existing test user (`[email protected]`) and creates a fresh instance with the `ADMIN` role. It then performs a UI login to capture the authentication state, which is shared across all test files.
|
||||
- **Teardown (`tests/global.teardown.ts`):** After the entire test suite completes (regardless of success or failure), the global teardown script runs and completely purges the test user from the database.
|
||||
- **Safety:** Do not use `[email protected]` for manual testing. It is volatile and intended exclusively for the CI test runner.
|
||||
|
||||
## 3. UI Interaction Conventions
|
||||
- **Strict Selector Usage**: ALWAYS use `data-testid` selectors (e.g., `getByTestId('panel-toggle-left')`) for DOM interactions. **NEVER rely on CSS classes** (like `.layer-item__toggle` or `.dock-btn`) or deep DOM structures, as these are brittle and break during design refactors. If a `data-testid` is missing from an element you need to test, you MUST add it to the React component source code first.
|
||||
- **Dialog Interception:** WorldWideView relies on heavy frontend plugin discovery and dynamic rendering. For example, the `UnverifiedPluginBatchDialog` may unexpectedly appear and block UI interactions in a fresh browser context.
|
||||
- *Mitigation:* Ensure your test suites either explicitly handle these dialogs (e.g., in a `beforeEach` block) or inject mock plugins that bypass the verification flow entirely.
|
||||
|
||||
## 4. Mock Plugins
|
||||
- **Data Interface Strictness**: WorldWideView's `PluginManager` is extremely strict. **ALL mock plugins MUST implement `getPollingInterval`, `fetch`, and `renderEntity`**, even if they are purely UI-focused (like a bottom-panel plugin). Failure to implement these will crash the renderer.
|
||||
- **Capabilities**: If your mock UI plugin needs to be manually activated by the user, ensure its manifest includes the `"ui:sidebar"` capability so it appears in the layer list.
|
||||
- **Injection:** We inject safe, deterministic mock plugins into the database during the `global.setup.ts` phase to test the core rendering pipeline without relying on external APIs. Ensure your mock plugin is registered in the setup and teardown cleanup arrays.
|
||||
- **Location:** Mock plugin configurations and manifests are stored in `public/e2e-fixtures/`. When modifying the rendering engine, ensure you also update the mock plugin (`public/e2e-fixtures/mock-plugin.js`) to reflect any changes in the Plugin SDK capabilities.
|
||||
|
||||
## 5. Security Permissions
|
||||
- When integrating Playwright tests into GitHub Actions (e.g., `.github/workflows/playwright.yml`), you MUST include an explicit permissions block (e.g., `permissions: { contents: read }`) to adhere to CodeQL and least-privilege scoping rules.
|
||||
|
||||
> [!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`).
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
---
|
||||
name: playwright-testing
|
||||
description: Use when creating or modifying Playwright end-to-end tests, especially when injecting mock plugins to test platform features.
|
||||
---
|
||||
|
||||
# Playwright E2E Testing & Mock Plugin Guide
|
||||
|
||||
When you are tasked with testing a new feature or plugin in WorldWideView using Playwright, you must use this skill to ensure you follow the strict architecture rules of the platform.
|
||||
|
||||
## 1. Mock Plugin Requirements
|
||||
When creating a mock plugin (e.g., `public/e2e-fixtures/my-mock-plugin.js`) to test a specific UI feature, **you MUST implement the full Data Plugin interface**.
|
||||
|
||||
WorldWideView's `PluginManager` throws fatal runtime errors if a plugin is missing core data fetching methods, even if your plugin only tests a UI component like a bottom panel.
|
||||
|
||||
**Required Methods for EVERY Mock Plugin:**
|
||||
```javascript
|
||||
export default {
|
||||
id: "my-mock-plugin",
|
||||
name: "My Mock Plugin",
|
||||
// ...
|
||||
// MUST BE INCLUDED:
|
||||
fetch: async (timeRange) => { return []; },
|
||||
getPollingInterval: () => { return 60000; },
|
||||
getLayerConfig: () => { return { color: "#FFF", clusterEnabled: false, clusterDistance: 50 }; },
|
||||
renderEntity: (entity) => { return { type: "point", color: "#FFF", size: 5 }; },
|
||||
|
||||
// Your UI testing component (e.g., Sidebar, Bottom Panel)
|
||||
getBottomPanelComponent: () => { ... }
|
||||
}
|
||||
```
|
||||
|
||||
## 2. Mock Plugin Manifest Capabilities
|
||||
If your mock plugin needs to be toggled by the user in the Layers list, you MUST include the `"ui:sidebar"` capability in its `manifest.json`.
|
||||
```json
|
||||
{
|
||||
"capabilities": ["ui:bottom-panel", "ui:sidebar"],
|
||||
"extends": ["sidebar"]
|
||||
}
|
||||
```
|
||||
|
||||
## 3. Database Injection
|
||||
The frontend reads plugins from the database. You MUST inject your mock plugin during `tests/global.setup.ts` using Prisma:
|
||||
|
||||
```typescript
|
||||
const manifestPath = path.join(process.cwd(), 'public', 'e2e-fixtures', 'my-mock-plugin-manifest.json');
|
||||
const manifestStr = fs.readFileSync(manifestPath, 'utf-8');
|
||||
await prisma.installedPlugin.create({
|
||||
data: {
|
||||
pluginId: 'my-mock-plugin',
|
||||
version: '1.0.0',
|
||||
config: manifestStr,
|
||||
enabled: true
|
||||
}
|
||||
});
|
||||
```
|
||||
Make sure to add your new mock plugin ID to the cleanup logic in `global.setup.ts` as well:
|
||||
```typescript
|
||||
await prisma.installedPlugin.deleteMany({
|
||||
where: { pluginId: { in: ['e2e-mock-plugin', 'my-mock-plugin'] } }
|
||||
});
|
||||
```
|
||||
|
||||
## 4. UI Selectors
|
||||
**DO NOT use CSS classes for your locators.** CSS classes change frequently (e.g., `.dock-btn`, `.layer-item__toggle`).
|
||||
You MUST either:
|
||||
1. Add explicit `data-testid` attributes to the React components you are testing.
|
||||
2. Use stable accessibility locators (e.g., `getByRole('button', { name: /Text/ })`).
|
||||
|
||||
## 5. Execution Environment
|
||||
- Ensure `pnpm run dev:backends` is running before you execute tests locally.
|
||||
- Run tests using `pnpm run test:e2e` or `npx playwright test tests/your-test.spec.ts`.
|
||||
- **PowerShell Warning**: Remember you are running in Windows PowerShell. Do NOT chain commands with `&&`. Use `;` instead.
|
||||
@@ -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
|
||||
|
||||
@@ -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"
|
||||
@@ -0,0 +1,56 @@
|
||||
name: Playwright Tests
|
||||
on:
|
||||
push:
|
||||
branches: [ main, master ]
|
||||
pull_request:
|
||||
branches: [ main, master ]
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
test:
|
||||
timeout-minutes: 60
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
browser: [chromium, firefox, webkit]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v3
|
||||
with:
|
||||
version: 9.15.4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Install Playwright Browsers
|
||||
run: pnpm exec playwright install --with-deps
|
||||
|
||||
- name: Run Project Setup
|
||||
run: pnpm run setup
|
||||
|
||||
- name: Boot Database
|
||||
run: |
|
||||
docker network create coolify || true
|
||||
pnpm run predev
|
||||
|
||||
- name: Run Playwright tests
|
||||
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-${{ matrix.browser }}
|
||||
path: playwright-report/
|
||||
retention-days: 30
|
||||
+9
-6
@@ -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/
|
||||
@@ -127,4 +125,9 @@ skills-lock.json
|
||||
/wwv-seeders/
|
||||
/wwv-seeders-private/
|
||||
/wwv-test/
|
||||
worldwideview.code-workspace
|
||||
worldwideview.code-workspace
|
||||
|
||||
# Playwright
|
||||
/playwright-report/
|
||||
/test-results/
|
||||
/playwright/.auth/
|
||||
@@ -155,6 +155,7 @@ Read the relevant rule file when working in that domain:
|
||||
| `continuous-improvement` | When to create/update rules, skills, or workflows | `.agents/rules/continuous-improvement.md` |
|
||||
| `context-and-memory` | How to orient and maintain project context between sessions | `.agents/rules/context-and-memory.md` |
|
||||
| `troubleshooting-and-debugging` | Resolving plugin latency, namespace collisions, or deployment issues | `.agents/rules/troubleshooting-and-debugging.md` |
|
||||
| `e2e-testing` | Guidelines and architecture for the Playwright End-to-End (E2E) testing infrastructure | `.agents/rules/e2e-testing.md` |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
# Design System: WorldWideView
|
||||
**Project ID:** local-worldwideview-app
|
||||
|
||||
## 1. Visual Theme & Atmosphere
|
||||
The WorldWideView platform employs an **"Airy, High-Tech, and Geospatial-Focused"** aesthetic. The design philosophy centers around "Glassmorphism Pro Max"—keeping the user's primary focus on the rich, underlying 3D globe visualization while providing highly legible, structured, and floating Heads-Up Display (HUD) elements.
|
||||
|
||||
The mood is utilitarian yet premium, heavily relying on dense background blurring, delicate inner borders, and vibrant glowing accent states to establish depth, interactivity, and a sense of "live" intelligence.
|
||||
|
||||
## 2. Color Palette & Roles
|
||||
WorldWideView operates using a multi-theme architecture (Default Dark, Pure Black, Legacy OLED, and Light). The core semantic roles for the **Default Dark Theme** are outlined below:
|
||||
|
||||
* **Obsidian Canvas** (`#171717`) - `--bg-primary`: The foundational layer behind the application shell and globe.
|
||||
* **Translucent Slate Glass** (`rgba(38, 38, 38, 0.85)`) - `--bg-glass`: The primary background for floating HUD panels, sidebars, and dialogs. Provides a frosted glass effect that allows the map to bleed through.
|
||||
* **Frost White** (`#ffffff`) - `--text-primary`: Primary typography for headers, active states, and high-emphasis data.
|
||||
* **Muted Ash** (`#a3a3a3`) - `--text-muted`: Secondary typography used for labels, subtitles, and inactive states to establish visual hierarchy.
|
||||
* **Gossamer Edge** (`rgba(255, 255, 255, 0.15)`) - `--border-subtle`: Defines the subtle, crisp edges of glass panels, dividers, and default button states.
|
||||
* **Starlight Cyan** (`#ffffff` / *Legacy:* `#22d3ee`) - `--accent-cyan`: Used for primary actions, active tabs, timeline scrubbers, and play buttons. Often paired with a diffuse glow (`0 0 24px rgba(255, 255, 255, 0.15)`) for emphasis and technical flair.
|
||||
* **Telemetry Green** (`#22c55e`) - `--accent-green`: Used for live status indicators, pulsing connectivity badges, and positive data deltas.
|
||||
* **Warning Amber** (`#f59e0b`) - `--accent-amber`: Used for warnings, "Alpha" badges, or unavailable data states.
|
||||
|
||||
## 3. Typography Rules
|
||||
The system uses a dual-font strategy to balance clean user interfaces with technical precision.
|
||||
|
||||
* **UI Font (Inter):** Used for all general interface elements, headers, and buttons.
|
||||
* Headers and brand elements use a bold `600/700` weight with tight letter-spacing (`-0.02em`) for a sleek, modern feel.
|
||||
* Section titles, keys, and subtitles use a very small size (`11px`), a medium weight, uppercase transformation, and wide letter-spacing (`0.05em` to `0.1em`) to mimic aerospace or military HUD interfaces.
|
||||
* **Monospace Font (JetBrains Mono):** Used strictly for data values, coordinates, telemetry, and exact timestamps (`11px` to `12px`). Ensures tabular alignment, clear distinction between similar characters (e.g., 0 and O), and technical precision.
|
||||
|
||||
## 4. Component Stylings
|
||||
|
||||
* **Glass Panels (Cards/Containers):**
|
||||
* **Shape:** Generously rounded corners (`16px` / `var(--radius-lg)`).
|
||||
* **Surface:** Dense frosted background blur (`24px`).
|
||||
* **Depth:** Elevated significantly above the map using a dual-layered drop shadow (`0 8px 32px rgba(0, 0, 0, 0.4)` combined with `0 2px 8px rgba(0, 0, 0, 0.2)`). Features a crisp inner border (`inset 0 1px 1px rgba(255, 255, 255, 0.1)`) to simulate physical glass thickness.
|
||||
* **Buttons:**
|
||||
* **Shape:** Subtly rounded corners (`12px` / `var(--radius-md)`) with a standard height of `36px`.
|
||||
* **Surface:** Translucent glass background with a subtle border.
|
||||
* **Behavior:** Smooth, spring-based transitions. On hover, the background brightens, the element scales up/translates slightly (`translateY(-1px)`), and primary buttons emit a vivid neon glow. On click (active), buttons physically depress (`scale(0.97)`).
|
||||
* **Tabs & Selectors:**
|
||||
* **Shape:** Softly rounded (`8px` / `var(--radius-sm)`).
|
||||
* **Surface:** Clean, flat, and transparent by default.
|
||||
* **Behavior:** Transitions to a soft glass hover or active state. Active tabs use a highlighted background (`rgba(var(--accent-rgb), 0.1)`) and bright cyan text with increased font weight.
|
||||
* **Timeline Scrubber:**
|
||||
* **Track:** Slender `4px` tall track with softly rounded edges.
|
||||
* **Handle:** A circular `14px` handle that emits a cyan glow, expanding dynamically on hover (`scale(1.2)`).
|
||||
|
||||
## 5. Layout Principles
|
||||
* **Absolute Overlays:** The UI does not push the map; instead, it floats over a full-screen, `z-index: 0` globe canvas. Elements are anchored to the edges (Header to top, Sidebar to sides, Timeline to bottom).
|
||||
* **Strict 4/8dp Rhythm:** All spacing adheres to an 8-point grid base (`4px`, `8px`, `12px`, `16px`, `24px`, `32px`, `48px`).
|
||||
* **Dynamic Containment:** Sidebars and bottom panels push each other dynamically to prevent overlap and optimize map visibility (e.g., when the bottom panel opens, sidebars slide upward).
|
||||
* **Whitespace & Density:** Panels use a dense `16px` padding globally to maximize the amount of intelligence data visible while maintaining clear breathing room between individual data rows. Scrollable areas hide scrollbars until hovered to maintain the clean glass aesthetic.
|
||||
@@ -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`).
|
||||
+7
-9
@@ -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,6 +16,8 @@ export default [
|
||||
"local-seeders/**",
|
||||
".agents/**",
|
||||
".claude/**",
|
||||
".gemini/**",
|
||||
"*.cjs",
|
||||
],
|
||||
},
|
||||
...nextCoreWebVitals,
|
||||
@@ -33,20 +35,16 @@ export default [
|
||||
|
||||
// Pre-existing — flagged in the original code review (#96):
|
||||
"@typescript-eslint/no-explicit-any": "warn",
|
||||
"no-console": "warn",
|
||||
"no-console": "off",
|
||||
|
||||
// React 19 hook-purity rules from eslint-plugin-react-hooks 7+:
|
||||
"react-hooks/purity": "warn",
|
||||
"react-hooks/refs": "warn",
|
||||
"react-hooks/set-state-in-effect": "warn",
|
||||
"react-hooks/immutability": "warn",
|
||||
"react-hooks/static-components": "warn",
|
||||
|
||||
// (These were previously hallucinated or require extra plugins)
|
||||
// Misc one-offs across the codebase:
|
||||
"react/no-unescaped-entities": "warn",
|
||||
"@typescript-eslint/ban-ts-comment": "warn",
|
||||
"@next/next/no-assign-module-variable": "warn",
|
||||
"prefer-const": "warn",
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export default config;
|
||||
@@ -93,6 +93,4 @@ const nextConfig: NextConfig = {
|
||||
},
|
||||
};
|
||||
|
||||
import { withSentryConfig } from "@sentry/nextjs";
|
||||
|
||||
export default nextConfig;
|
||||
+25
-13
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "worldwideview",
|
||||
"version": "2.13.1",
|
||||
"private": true,
|
||||
"version": "2.16.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"packageManager": "[email protected]",
|
||||
"scripts": {
|
||||
@@ -18,6 +18,7 @@
|
||||
"build": "next build --webpack",
|
||||
"start": "next start",
|
||||
"test": "vitest run",
|
||||
"test:e2e": "playwright test",
|
||||
"test:mutate": "stryker run",
|
||||
"lint": "eslint .",
|
||||
"db:reset": "npx prisma migrate reset --force",
|
||||
@@ -30,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:*",
|
||||
@@ -41,25 +42,28 @@
|
||||
"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"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/compat": "^2.1.0",
|
||||
"@eslint/eslintrc": "^3.3.5",
|
||||
"@playwright/test": "^1.60.0",
|
||||
"@stryker-mutator/core": "^9.6.1",
|
||||
"@stryker-mutator/vitest-runner": "^9.6.1",
|
||||
"@testing-library/dom": "^10.4.1",
|
||||
@@ -70,19 +74,27 @@
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"@types/ws": "^8.18.1",
|
||||
"@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",
|
||||
"eslint": "^9",
|
||||
"eslint-config-airbnb": "^19.0.4",
|
||||
"eslint-config-airbnb-typescript": "^18.0.0",
|
||||
"eslint-config-next": "^16.2.6",
|
||||
"eslint-plugin-import": "^2.32.0",
|
||||
"eslint-plugin-jsx-a11y": "^6.10.2",
|
||||
"eslint-plugin-react": "^7.37.5",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"fast-check": "^4.8.0",
|
||||
"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": {
|
||||
|
||||
@@ -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,3 +1,4 @@
|
||||
/* eslint-disable no-console */
|
||||
import { Command } from 'commander';
|
||||
import { saveConfig } from '../utils/config.js';
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
/* eslint-disable no-console */
|
||||
import { Command } from 'commander';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
/* eslint-disable no-console */
|
||||
import { Command } from 'commander';
|
||||
import { execSync } from 'child_process';
|
||||
import path from 'path';
|
||||
@@ -50,7 +51,7 @@ export const publishCommand = new Command('publish')
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
let originalName = pkgContent.name;
|
||||
const originalName = pkgContent.name;
|
||||
let publishedName = originalName;
|
||||
|
||||
// Determine organization
|
||||
@@ -66,7 +67,7 @@ export const publishCommand = new Command('publish')
|
||||
try {
|
||||
const whoami = execSync('npm whoami', { stdio: 'pipe' }).toString().trim();
|
||||
targetOrg = whoami;
|
||||
} catch (e) {
|
||||
} catch (_e) {
|
||||
// Not logged in or errored, ignore
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@worldwideview/wwv-lib-aviation",
|
||||
"version": "1.0.1",
|
||||
"version": "1.0.2",
|
||||
"description": "Shared abstract base classes for WorldWideView aviation plugins (commercial, military, specialized)",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -69,7 +69,6 @@ export abstract class BaseAviationPlugin implements WorldPlugin {
|
||||
return {
|
||||
type: "model",
|
||||
iconUrl: this.iconUrl,
|
||||
size: isAirborne ? 8 : 5,
|
||||
modelUrl: this.modelUrl,
|
||||
modelScale: 2.56,
|
||||
modelMinPixelSize: 16,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@worldwideview/wwv-lib-incidents",
|
||||
"version": "1.0.1",
|
||||
"version": "1.0.2",
|
||||
"description": "Shared abstract base classes for WorldWideView incident plugins (earthquakes, wildfires, conflicts)",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -75,9 +75,7 @@ export abstract class BaseIncidentPlugin implements WorldPlugin {
|
||||
type: "billboard",
|
||||
iconUrl: this.iconUrls[cacheKey],
|
||||
color,
|
||||
size,
|
||||
outlineColor: "#000000",
|
||||
outlineWidth: 1,
|
||||
iconScale: size / 30,
|
||||
labelText: entity.label || undefined,
|
||||
labelFont: "11px JetBrains Mono, monospace" // Adds optional label standard
|
||||
};
|
||||
|
||||
+55
@@ -1,3 +1,10 @@
|
||||
/**
|
||||
* @file index.ts
|
||||
* @description Core SDK for WorldWideView plugin development.
|
||||
* Defines the foundational types, interfaces, and utilities required
|
||||
* to build data seeders, visualizers, and UI extensions.
|
||||
* @module @worldwideview/wwv-plugin-sdk
|
||||
*/
|
||||
import type { ComponentType } from "react";
|
||||
/** Standard SVG icon size (px) used by createSvgIconUrl when no size is given. */
|
||||
export declare const DEFAULT_ICON_SIZE = 32;
|
||||
@@ -24,16 +31,30 @@ export interface TimeRange {
|
||||
end: Date;
|
||||
}
|
||||
export type TimeWindow = "1h" | "6h" | "24h" | "48h" | "7d";
|
||||
/**
|
||||
* @interface GeoEntity
|
||||
* @description The primary data primitive representing a geospatial object.
|
||||
*/
|
||||
export interface GeoEntity {
|
||||
/** Globally unique identifier for this specific entity instance. */
|
||||
id: string;
|
||||
/** The ID of the plugin that owns this entity. */
|
||||
pluginId: string;
|
||||
/** WGS84 Latitude. */
|
||||
latitude: number;
|
||||
/** WGS84 Longitude. */
|
||||
longitude: number;
|
||||
/** Altitude in meters above ellipsoid (optional). */
|
||||
altitude?: number;
|
||||
/** Heading/Rotation in degrees (optional). */
|
||||
heading?: number;
|
||||
/** Speed in knots or meters/sec depending on domain (optional). */
|
||||
speed?: number;
|
||||
/** The moment this data was captured. */
|
||||
timestamp: Date;
|
||||
/** Short display string for labels. */
|
||||
label?: string;
|
||||
/** Arbitrary metadata associated with the entity. */
|
||||
properties: Record<string, unknown>;
|
||||
}
|
||||
export interface WsStreamPayload {
|
||||
@@ -164,6 +185,11 @@ export type FilterValue = {
|
||||
type: "boolean";
|
||||
value: boolean;
|
||||
};
|
||||
/**
|
||||
* @interface WorldPlugin
|
||||
* @description The core lifecycle interface for all WorldWideView extensions.
|
||||
* Every plugin (built-in or marketplace) must implement this interface.
|
||||
*/
|
||||
export interface WorldPlugin {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -203,6 +229,15 @@ export interface WorldPlugin {
|
||||
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.
|
||||
* If not provided, the plugin will not appear in the bottom dock.
|
||||
*/
|
||||
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). */
|
||||
mapWebsocketPayload?(payload: any, existingEntities?: GeoEntity[]): GeoEntity[];
|
||||
@@ -213,6 +248,16 @@ export type DataBusEvents = {
|
||||
pluginId: string;
|
||||
defaultInterval: number;
|
||||
};
|
||||
pluginUnregistered: {
|
||||
pluginId: string;
|
||||
};
|
||||
dynamicPluginCreate: {
|
||||
plugin: WorldPlugin;
|
||||
autoEnable?: boolean;
|
||||
};
|
||||
dynamicPluginRemove: {
|
||||
pluginId: string;
|
||||
};
|
||||
dataUpdated: {
|
||||
pluginId: string;
|
||||
entities: GeoEntity[];
|
||||
@@ -244,6 +289,16 @@ export type DataBusEvents = {
|
||||
heading?: number;
|
||||
};
|
||||
globeReady: Record<string, never>;
|
||||
pluginError: {
|
||||
pluginId?: string;
|
||||
message: string;
|
||||
error?: Error;
|
||||
};
|
||||
layerLoadingChanged: {
|
||||
pluginId: string;
|
||||
loading: boolean;
|
||||
};
|
||||
};
|
||||
export * from "./viteGlobals";
|
||||
export * from "./auth-contracts";
|
||||
//# sourceMappingURL=index.d.ts.map
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAI3C,kFAAkF;AAClF,eAAO,MAAM,iBAAiB,KAAK,CAAC;AAKpC,MAAM,WAAW,cAAe,SAAQ,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAC3D,2BAA2B;IAC3B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,wDAAwD;IACxD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,0DAA0D;IAC1D,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,oEAAoE;IACpE,eAAe,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAC5B,IAAI,EAAE,aAAa,CAAC,GAAG,CAAC,EACxB,IAAI,GAAE,cAAmB,GAC1B,MAAM,CA4BR;AAGD,YAAY,EAAE,cAAc,EAAE,YAAY,EAAE,UAAU,EAAE,SAAS,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAGzJ,MAAM,MAAM,cAAc,GACpB,UAAU,GACV,UAAU,GACV,UAAU,GACV,UAAU,GACV,kBAAkB,GAClB,gBAAgB,GAChB,OAAO,GACP,OAAO,GACP,UAAU,GACV,cAAc,GACd,QAAQ,CAAC;AAGf,MAAM,WAAW,SAAS;IACtB,KAA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AC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAC/B;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,MAAM,EAAE,MAAM,EAAE,CAAA;CAAE,GACpC;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAC3C;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,KAAK,EAAE,OAAO,CAAA;CAAE,CAAC;AAE1C;;;;GAIG;AACH,MAAM,WAAW,WAAW;IACxB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,GAAG,aAAa,CAAC;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAChE,QAAQ,EAAE,cAAc,CAAC;IACzB,OAAO,EAAE,MAAM,CAAC;IAGhB,UAAU,CAAC,GAAG,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9C,OAAO,IAAI,IAAI,CAAC;IAGhB,KAAK,CAAC,SAAS,EAAE,SAAS,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC,CAAC;IAClD,kBAAkB,IAAI,MAAM,CAAC;IAG7B,cAAc,IAAI,WAAW,CAAC;IAC9B,YAAY,CAAC,MAAM,EAAE,SAAS,GAAG,mBAAmB,CAAC;IAGLine truncated
|
||||
+9
-3
@@ -1,7 +1,11 @@
|
||||
"use strict";
|
||||
// ─── WorldWideView Plugin SDK ─────────────────────────────────
|
||||
// The public API for building WorldWideView plugins.
|
||||
// Import from "@worldwideview/wwv-plugin-sdk" in your plugin.
|
||||
/**
|
||||
* @file index.ts
|
||||
* @description Core SDK for WorldWideView plugin development.
|
||||
* Defines the foundational types, interfaces, and utilities required
|
||||
* to build data seeders, visualizers, and UI extensions.
|
||||
* @module @worldwideview/wwv-plugin-sdk
|
||||
*/
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
@@ -61,3 +65,5 @@ function createSvgIconUrl(Icon, opts = {}) {
|
||||
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(wrappedSvg)}`;
|
||||
}
|
||||
__exportStar(require("./viteGlobals"), exports);
|
||||
// ─── Auth Contracts ──────────────────────────────────────────
|
||||
__exportStar(require("./auth-contracts"), exports);
|
||||
+11
@@ -1,3 +1,10 @@
|
||||
/**
|
||||
* @file manifest.ts
|
||||
* @description Schema and types for the WorldWideView plugin manifest (plugin.json).
|
||||
* Defines the contract between the platform and external modules,
|
||||
* covering capabilities, security tiers, and data source configurations.
|
||||
* @module @worldwideview/wwv-plugin-sdk
|
||||
*/
|
||||
import type { PluginCategory } from "./index";
|
||||
export type PluginFormat = "declarative" | "static" | "bundle";
|
||||
export type PluginType = "data-layer" | "extension";
|
||||
@@ -42,6 +49,10 @@ export interface RenderingConfig {
|
||||
minZoomLevel?: number;
|
||||
maxEntities?: number;
|
||||
}
|
||||
/**
|
||||
* @interface PluginManifest
|
||||
* @description The structural definition of a plugin.json file.
|
||||
*/
|
||||
export interface PluginManifest {
|
||||
id: string;
|
||||
name: string;
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"file":"manifest.d.ts","sourceRoot":"","sources":["../src/manifest.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAE9C,MAAM,MAAM,YAAY,GAAG,aAAa,GAAG,QAAQ,GAAG,QAAQ,CAAC;AAC/D,MAAM,MAAM,UAAU,GAAG,YAAY,GAAG,WAAW,CAAC;AACpD,MAAM,MAAM,SAAS,GAAG,UAAU,GAAG,UAAU,GAAG,YAAY,CAAC;AAE/D,MAAM,MAAM,gBAAgB,GACtB,UAAU,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AC,EAAE,MAAM,EAAE,CAAC;CACtB"}
|
||||
+7
-3
@@ -1,5 +1,9 @@
|
||||
"use strict";
|
||||
// ─── Plugin Manifest Types ───────────────────────────────────
|
||||
// Schema for plugin.json manifest files.
|
||||
// Three formats: declarative (JSON-only), static (GeoJSON), bundle (JS code).
|
||||
/**
|
||||
* @file manifest.ts
|
||||
* @description Schema and types for the WorldWideView plugin manifest (plugin.json).
|
||||
* Defines the contract between the platform and external modules,
|
||||
* covering capabilities, security tiers, and data source configurations.
|
||||
* @module @worldwideview/wwv-plugin-sdk
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@worldwideview/wwv-plugin-sdk",
|
||||
"version": "1.6.0",
|
||||
"version": "1.7.1",
|
||||
"description": "Plugin SDK — types, interfaces, and utilities for building WorldWideView globe plugins",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
|
||||
@@ -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", () => {
|
||||
|
||||
@@ -277,6 +277,12 @@ export interface WorldPlugin {
|
||||
getSettingsComponent?(): ComponentType<{ pluginId: string }>;
|
||||
/** Custom React component injected into the Globe view for rendering primitives/data sources (e.g. GeoJSON). */
|
||||
getGlobeComponent?(): ComponentType<{ viewer: any; enabled: boolean }>;
|
||||
/**
|
||||
* 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.
|
||||
* If not provided, the plugin will not appear in the bottom dock.
|
||||
*/
|
||||
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). */
|
||||
mapWebsocketPayload?(payload: any, existingEntities?: GeoEntity[]): GeoEntity[];
|
||||
@@ -288,6 +294,9 @@ export type GlobePlugin = WorldPlugin;
|
||||
// ─── Data Bus Event Types ────────────────────────────────────
|
||||
export type DataBusEvents = {
|
||||
pluginRegistered: { pluginId: string; defaultInterval: number };
|
||||
pluginUnregistered: { pluginId: string };
|
||||
dynamicPluginCreate: { plugin: WorldPlugin; autoEnable?: boolean };
|
||||
dynamicPluginRemove: { pluginId: string };
|
||||
dataUpdated: { pluginId: string; entities: GeoEntity[] };
|
||||
entitySelected: { entity: GeoEntity | null };
|
||||
layerToggled: { pluginId: string; enabled: boolean };
|
||||
@@ -296,6 +305,8 @@ export type DataBusEvents = {
|
||||
cameraFaceTowards: { lat: number; lon: number; alt: number };
|
||||
cameraGoTo: { lat: number; lon: number; alt: number; distance?: number; maxPitch?: number; heading?: number };
|
||||
globeReady: Record<string, never>;
|
||||
pluginError: { pluginId?: string; message: string; error?: Error };
|
||||
layerLoadingChanged: { pluginId: string; loading: boolean };
|
||||
};
|
||||
|
||||
export * from "./viteGlobals";
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { defineConfig, devices } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* See https://playwright.dev/docs/test-configuration.
|
||||
*/
|
||||
export default defineConfig({
|
||||
timeout: 60000,
|
||||
expect: {
|
||||
timeout: 10000,
|
||||
},
|
||||
globalSetup: './tests/global.setup.ts',
|
||||
globalTeardown: './tests/global.teardown.ts',
|
||||
testDir: './tests',
|
||||
/* Run tests in files in parallel */
|
||||
fullyParallel: true,
|
||||
/* Fail the build on CI if you accidentally left test.only in the source code. */
|
||||
forbidOnly: !!process.env.CI,
|
||||
/* Retry on CI only */
|
||||
retries: process.env.CI ? 2 : 0,
|
||||
/* Opt out of parallel tests on CI. Restrict to 2 locally to prevent Next.js compilation overload. */
|
||||
workers: process.env.CI ? 1 : 2,
|
||||
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
|
||||
reporter: 'html',
|
||||
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
|
||||
use: {
|
||||
/* Base URL to use in actions like `await page.goto('/')`. */
|
||||
baseURL: 'http://localhost:3001',
|
||||
|
||||
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
|
||||
trace: 'on-first-retry',
|
||||
},
|
||||
|
||||
/* Configure projects for major browsers */
|
||||
projects: [
|
||||
{
|
||||
name: 'chromium',
|
||||
use: {
|
||||
...devices['Desktop Chrome'],
|
||||
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 */
|
||||
webServer: {
|
||||
command: 'pnpm dev',
|
||||
env: { PORT: '3001' },
|
||||
url: 'http://localhost:3001',
|
||||
reuseExistingServer: !process.env.CI,
|
||||
timeout: 120 * 1000,
|
||||
},
|
||||
});
|
||||
Generated
+1066
-667
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"id": "e2e-mock-bottom-panel",
|
||||
"name": "E2E Bottom Panel Mock",
|
||||
"version": "1.0.0",
|
||||
"description": "A static mock plugin used for Playwright E2E tests focusing on the bottom panel.",
|
||||
"author": "WorldWideView Automated Tests",
|
||||
"type": "extension",
|
||||
"format": "bundle",
|
||||
"trust": "unverified",
|
||||
"entry": "/e2e-fixtures/e2e-mock-bottom-panel.js",
|
||||
"capabilities": ["ui:bottom-panel", "ui:sidebar"],
|
||||
"extends": ["bottom-panel", "sidebar"],
|
||||
"category": "utility"
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// This file is loaded by the plugin manager in the E2E test environment.
|
||||
// It bypasses the build step and directly uses the host's injected React instance.
|
||||
|
||||
export default {
|
||||
id: "e2e-mock-bottom-panel",
|
||||
name: "E2E Bottom Panel Mock",
|
||||
description: "A mock plugin for Bottom Panel E2E testing.",
|
||||
icon: "data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=", // Empty SVG as fallback
|
||||
category: "custom",
|
||||
version: "1.0.0",
|
||||
|
||||
// Lifecycle
|
||||
initialize: async (ctx) => {
|
||||
console.log("[e2e-mock-bottom-panel] Initialized");
|
||||
},
|
||||
destroy: () => {
|
||||
console.log("[e2e-mock-bottom-panel] Destroyed");
|
||||
},
|
||||
|
||||
// Data
|
||||
fetch: async (timeRange) => {
|
||||
return []; // No entities for this mock
|
||||
},
|
||||
getPollingInterval: () => {
|
||||
return 60000;
|
||||
},
|
||||
|
||||
// Rendering
|
||||
getLayerConfig: () => {
|
||||
return {
|
||||
color: "#0000FF",
|
||||
clusterEnabled: false,
|
||||
clusterDistance: 50
|
||||
};
|
||||
},
|
||||
renderEntity: (entity) => {
|
||||
return {
|
||||
type: "point",
|
||||
color: "#0000FF",
|
||||
size: 5
|
||||
};
|
||||
},
|
||||
|
||||
// Provide a bottom panel UI component using the host's React instance
|
||||
getBottomPanelComponent: () => {
|
||||
// Access React from the global host object injected by WorldWideView
|
||||
const React = globalThis.__WWV_HOST__.React;
|
||||
|
||||
if (!React) {
|
||||
console.error("[e2e-mock-bottom-panel] Failed to resolve React from __WWV_HOST__");
|
||||
return null;
|
||||
}
|
||||
|
||||
// Return a component function
|
||||
return function MockBottomPanel() {
|
||||
return React.createElement(
|
||||
"div",
|
||||
{
|
||||
"data-testid": "e2e-bottom-panel-content",
|
||||
style: {
|
||||
padding: "16px",
|
||||
background: "rgba(0, 0, 255, 0.1)",
|
||||
border: "1px solid blue",
|
||||
height: "100%",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center"
|
||||
}
|
||||
},
|
||||
"Mock Bottom Panel Active"
|
||||
);
|
||||
};
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"id": "e2e-mock-plugin",
|
||||
"name": "E2E Mock Plugin",
|
||||
"version": "1.0.0",
|
||||
"description": "A static mock plugin used for Playwright E2E tests.",
|
||||
"author": "WorldWideView Automated Tests",
|
||||
"type": "extension",
|
||||
"format": "bundle",
|
||||
"trust": "unverified",
|
||||
"entry": "/e2e-fixtures/mock-plugin.js",
|
||||
"capabilities": ["ui:sidebar"],
|
||||
"category": "utility",
|
||||
"extends": ["sidebar"]
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// This file is loaded by the plugin manager in the E2E test environment.
|
||||
// It bypasses the build step and directly uses the host's injected React instance.
|
||||
|
||||
export default {
|
||||
// Basic plugin metadata required by WorldPlugin interface
|
||||
id: "e2e-mock-plugin",
|
||||
name: "E2E Mock Plugin",
|
||||
description: "A mock plugin for E2E testing.",
|
||||
icon: "data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=", // Empty SVG as fallback
|
||||
category: "custom",
|
||||
version: "1.0.0",
|
||||
|
||||
// Lifecycle
|
||||
initialize: async (ctx) => {
|
||||
console.log("[e2e-mock-plugin] Initialized");
|
||||
},
|
||||
destroy: () => {
|
||||
console.log("[e2e-mock-plugin] Destroyed");
|
||||
},
|
||||
|
||||
// Data
|
||||
fetch: async (timeRange) => {
|
||||
return []; // No entities for this mock
|
||||
},
|
||||
getPollingInterval: () => {
|
||||
return 60000;
|
||||
},
|
||||
|
||||
// Rendering
|
||||
getLayerConfig: () => {
|
||||
return {
|
||||
color: "#00FF00",
|
||||
clusterEnabled: false,
|
||||
clusterDistance: 50
|
||||
};
|
||||
},
|
||||
renderEntity: (entity) => {
|
||||
return {
|
||||
type: "point",
|
||||
color: "#00FF00",
|
||||
size: 5
|
||||
};
|
||||
},
|
||||
|
||||
// Provide a UI component using the host's React instance
|
||||
getSidebarComponent: () => {
|
||||
// Access React from the global host object injected by WorldWideView
|
||||
const React = globalThis.__WWV_HOST__.React;
|
||||
|
||||
if (!React) {
|
||||
console.error("[e2e-mock-plugin] Failed to resolve React from __WWV_HOST__");
|
||||
return null;
|
||||
}
|
||||
|
||||
// Return a component function, not just an element
|
||||
return function MockSidebar() {
|
||||
return React.createElement(
|
||||
"div",
|
||||
{ "data-testid": "e2e-mock-panel", style: { padding: "16px", background: "rgba(0, 255, 0, 0.1)", border: "1px solid green" } },
|
||||
"Mock Panel (E2E Test)"
|
||||
);
|
||||
};
|
||||
}
|
||||
};
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 9.8 KiB |
+57
-6
@@ -61,14 +61,65 @@ if (folderName !== 'worldwideview') {
|
||||
process.env.WWV_DB_PORT = port.toString();
|
||||
console.log(`🔌 Assigned deterministic database port: ${port}`);
|
||||
|
||||
// Rewrite DATABASE_URL in .env if it exists
|
||||
// Robust rewrite of DATABASE_URL in .env
|
||||
const envPath = path.resolve(cwd, '.env');
|
||||
if (fs.existsSync(envPath)) {
|
||||
let envContent = fs.readFileSync(envPath, 'utf8');
|
||||
const urlRegex = /(DATABASE_URL\s*=\s*["']?postgresql:\/\/[^:]+:[^@]+@localhost:)(\d+)(\/.*)/;
|
||||
if (urlRegex.test(envContent)) {
|
||||
envContent = envContent.replace(urlRegex, `$1${port}$3`);
|
||||
fs.writeFileSync(envPath, envContent, 'utf8');
|
||||
const envContent = fs.readFileSync(envPath, 'utf8');
|
||||
const lines = envContent.split(/\r?\n/);
|
||||
|
||||
const targetUrl = `DATABASE_URL="postgresql://postgres:[email protected]:${port}/worldwideview?schema=public"`;
|
||||
let foundTargetActive = false;
|
||||
let linesModified = false;
|
||||
|
||||
const newLines = lines.map(line => {
|
||||
// Check if line is an active DATABASE_URL
|
||||
if (/^\s*DATABASE_URL\s*=/.test(line)) {
|
||||
if (line.trim() === targetUrl) {
|
||||
foundTargetActive = true;
|
||||
return line;
|
||||
} else {
|
||||
console.warn(`⚠️ [Telemetry] Commenting out conflicting DATABASE_URL: ${line.trim()}`);
|
||||
linesModified = true;
|
||||
return `# ${line}`;
|
||||
}
|
||||
}
|
||||
return line;
|
||||
});
|
||||
|
||||
if (!foundTargetActive) {
|
||||
console.log(`🔌 [Telemetry] Injecting correct local DATABASE_URL for port ${port}.`);
|
||||
newLines.push(``);
|
||||
newLines.push(`# Dynamically injected by boot-db.mjs for worktree`);
|
||||
newLines.push(targetUrl);
|
||||
linesModified = true;
|
||||
}
|
||||
|
||||
if (linesModified) {
|
||||
const newContent = newLines.join('\n');
|
||||
|
||||
// File write with retries and telemetry
|
||||
const maxRetries = 3;
|
||||
let attempt = 0;
|
||||
while (attempt < maxRetries) {
|
||||
try {
|
||||
fs.writeFileSync(envPath, newContent, 'utf8');
|
||||
break; // Success
|
||||
} catch (err) {
|
||||
attempt++;
|
||||
if (err.code === 'EBUSY' || err.code === 'EPERM' || err.message.includes('os error 32')) {
|
||||
console.warn(`⚠️ [Telemetry] File lock encountered on .env (attempt ${attempt}/${maxRetries}). Retrying in 100ms...`);
|
||||
if (attempt >= maxRetries) {
|
||||
console.error('❌ Failed to write .env after multiple attempts due to file locks.');
|
||||
throw err;
|
||||
}
|
||||
// Synchronous sleep since boot-db.mjs isn't currently inside an async IIFE
|
||||
const start = Date.now();
|
||||
while (Date.now() - start < 100) {}
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ function copyDir(src, dest) {
|
||||
}
|
||||
const entries = fs.readdirSync(src, { withFileTypes: true });
|
||||
|
||||
for (let entry of entries) {
|
||||
for (const entry of entries) {
|
||||
const srcPath = path.join(src, entry.name);
|
||||
const destPath = path.join(dest, entry.name);
|
||||
|
||||
|
||||
+2
-2
@@ -7,7 +7,7 @@
|
||||
*/
|
||||
|
||||
import concurrently from 'concurrently';
|
||||
import kill from 'tree-kill';
|
||||
import kill from 'tree-kill/index.js';
|
||||
import { execSync } from 'child_process';
|
||||
import fs from 'fs';
|
||||
import process from 'process';
|
||||
@@ -40,7 +40,7 @@ const teardownDbOnExit = process.env.WWV_TEARDOWN_DB_ON_EXIT === 'true' || proce
|
||||
const { result, commands } = concurrently(
|
||||
[
|
||||
{ command: 'pnpm run dev:plugins', name: 'plugins', prefixColor: 'magenta' },
|
||||
{ command: 'next dev', name: 'next', prefixColor: 'blue' }
|
||||
{ command: 'pnpm exec next dev', name: 'next', prefixColor: 'blue' }
|
||||
],
|
||||
{
|
||||
prefix: 'name',
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
import { execSync } from 'child_process';
|
||||
|
||||
const dbUrl = process.env.DATABASE_URL || '';
|
||||
|
||||
if (!dbUrl) {
|
||||
console.error("❌ ERROR: DATABASE_URL is missing.");
|
||||
console.error(" Did you forget to run 'pnpm run setup' to generate your .env file?");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const isLocal = dbUrl.includes('localhost') || dbUrl.includes('127.0.0.1') || dbUrl.includes('host.docker.internal') || dbUrl.includes('postgres:postgres@db:5432');
|
||||
|
||||
if (!isLocal) {
|
||||
|
||||
+220
-24
@@ -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,43 +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 || "src/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)) {
|
||||
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,
|
||||
@@ -114,7 +276,7 @@ export async function buildPlugin({ dir, manifest, pluginDir }) {
|
||||
}
|
||||
}
|
||||
|
||||
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");
|
||||
@@ -151,7 +313,7 @@ export function syncToPublic({ dir, manifest, pluginDir }) {
|
||||
JSON.stringify(pluginJson, null, 2)
|
||||
);
|
||||
|
||||
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/
|
||||
@@ -166,6 +328,32 @@ function cleanStale(activeIds) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @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();
|
||||
|
||||
@@ -175,12 +363,20 @@ export async function syncAll() {
|
||||
return;
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
@@ -15,40 +15,66 @@ 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;
|
||||
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) {
|
||||
console.error(`[watch] Sync failed:`, err);
|
||||
} finally {
|
||||
isSyncing = false;
|
||||
if (pendingSync) {
|
||||
pendingSync = false;
|
||||
await runSync("pending changes");
|
||||
await runSync();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,11 +50,11 @@ function isAgentAction(v: unknown): v is AgentAction {
|
||||
if (!v || typeof v !== "object") return false;
|
||||
const a = (v as { action?: unknown }).action;
|
||||
return (
|
||||
a === "fly_to" ||
|
||||
a === "face_towards" ||
|
||||
a === "layer_toggle" ||
|
||||
a === "highlight_layer" ||
|
||||
a === "select_entity" ||
|
||||
a === "ping"
|
||||
a === "fly_to"
|
||||
|| a === "face_towards"
|
||||
|| a === "layer_toggle"
|
||||
|| a === "highlight_layer"
|
||||
|| a === "select_entity"
|
||||
|| a === "ping"
|
||||
);
|
||||
}
|
||||
@@ -62,7 +62,7 @@ export async function GET() {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream",
|
||||
"Cache-Control": "no-cache, no-transform",
|
||||
"Connection": "keep-alive",
|
||||
Connection: "keep-alive",
|
||||
"X-Accel-Buffering": "no",
|
||||
},
|
||||
});
|
||||
|
||||
@@ -22,14 +22,12 @@ function readMaybe(p: string): string | null {
|
||||
}
|
||||
}
|
||||
|
||||
const BUILD_ID =
|
||||
process.env.NEXT_PUBLIC_WWV_BUILD_ID ??
|
||||
readMaybe(path.join(process.cwd(), ".build-id")) ??
|
||||
"dev";
|
||||
const BUILD_AT =
|
||||
process.env.NEXT_PUBLIC_WWV_BUILD_AT ??
|
||||
readMaybe(path.join(process.cwd(), ".build-at")) ??
|
||||
null;
|
||||
const BUILD_ID = process.env.NEXT_PUBLIC_WWV_BUILD_ID
|
||||
?? readMaybe(path.join(process.cwd(), ".build-id"))
|
||||
?? "dev";
|
||||
const BUILD_AT = process.env.NEXT_PUBLIC_WWV_BUILD_AT
|
||||
?? readMaybe(path.join(process.cwd(), ".build-at"))
|
||||
?? null;
|
||||
|
||||
export async function GET() {
|
||||
return NextResponse.json({
|
||||
|
||||
@@ -14,8 +14,7 @@
|
||||
import type { CameraAdapter, CameraFeature } from "./types";
|
||||
|
||||
const BULK_URL = "https://eapps.ncdot.gov/services/traffic-prod/v1/cameras";
|
||||
const DETAIL_URL = (id: number) =>
|
||||
`https://eapps.ncdot.gov/services/traffic-prod/v1/cameras/${id}`;
|
||||
const DETAIL_URL = (id: number) => `https://eapps.ncdot.gov/services/traffic-prod/v1/cameras/${id}`;
|
||||
|
||||
const CONCURRENCY = 20;
|
||||
|
||||
@@ -64,7 +63,8 @@ async function mapWithConcurrency<T, R>(
|
||||
let next = 0;
|
||||
async function run() {
|
||||
while (next < items.length) {
|
||||
const i = next++;
|
||||
const i = next;
|
||||
next += 1;
|
||||
results[i] = await worker(items[i]);
|
||||
}
|
||||
}
|
||||
@@ -113,9 +113,7 @@ export const ncdotAdapter: CameraAdapter = {
|
||||
const bulk = (await bulkRes.json()) as BulkRecord[];
|
||||
if (!Array.isArray(bulk)) return [];
|
||||
|
||||
const details = await mapWithConcurrency(bulk, CONCURRENCY, (b) =>
|
||||
fetchDetail(b.id),
|
||||
);
|
||||
const details = await mapWithConcurrency(bulk, CONCURRENCY, (b) => fetchDetail(b.id),);
|
||||
|
||||
const features: CameraFeature[] = [];
|
||||
for (const d of details) {
|
||||
|
||||
@@ -55,8 +55,7 @@ export const osmSurveillanceAdapter: CameraAdapter = {
|
||||
if (!res.ok) throw new Error(`overpass ${res.status}`);
|
||||
const data = (await res.json()) as { elements?: OverpassNode[] };
|
||||
const nodes = (data.elements ?? []).filter(
|
||||
(e): e is OverpassNode =>
|
||||
e.type === "node" && typeof e.lat === "number",
|
||||
(e): e is OverpassNode => e.type === "node" && typeof e.lat === "number",
|
||||
);
|
||||
|
||||
return nodes.map<CameraFeature>((n) => {
|
||||
|
||||
@@ -113,12 +113,10 @@ export async function fetchAdapter(adapter: CameraAdapter): Promise<CameraFeatur
|
||||
try {
|
||||
const data = await Promise.race([
|
||||
adapter.fetch(),
|
||||
new Promise<CameraFeature[]>((_resolve, reject) =>
|
||||
setTimeout(
|
||||
new Promise<CameraFeature[]>((_resolve, reject) => setTimeout(
|
||||
() => reject(new Error(`Adapter ${adapter.id} timed out after ${ADAPTER_FETCH_TIMEOUT_MS}ms`)),
|
||||
ADAPTER_FETCH_TIMEOUT_MS,
|
||||
),
|
||||
),
|
||||
),),
|
||||
]);
|
||||
cache.set(adapter.id, {
|
||||
data,
|
||||
|
||||
@@ -29,7 +29,7 @@ export async function GET(req: NextRequest) {
|
||||
const ajaxRes = await fetch(ajaxUrl, {
|
||||
headers: {
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||||
"Referer": targetUrl
|
||||
Referer: targetUrl
|
||||
}
|
||||
});
|
||||
const ajaxHtml = await ajaxRes.text();
|
||||
@@ -37,9 +37,8 @@ export async function GET(req: NextRequest) {
|
||||
const streamMatch = ajaxHtml.match(/src:\s*'([^']+m3u8[^']+)'/);
|
||||
if (streamMatch && streamMatch[1]) {
|
||||
return NextResponse.json({ streamUrl: streamMatch[1] });
|
||||
} else {
|
||||
return NextResponse.json({ error: "Could not find m3u8 stream on balticlivecam backend" }, { status: 404 });
|
||||
}
|
||||
return NextResponse.json({ error: "Could not find m3u8 stream on balticlivecam backend" }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ error: "Unsupported extractor platform" }, { status: 400 });
|
||||
|
||||
@@ -5,9 +5,8 @@
|
||||
* until all features are retrieved.
|
||||
*/
|
||||
|
||||
const GDOT_BASE =
|
||||
"https://services1.arcgis.com/2iUE8l8JKrP2tygQ/arcgis/rest/services" +
|
||||
"/GDOT_Live_Traffic_Cameras/FeatureServer/0/query";
|
||||
const GDOT_BASE = "https://services1.arcgis.com/2iUE8l8JKrP2tygQ/arcgis/rest/services"
|
||||
+ "/GDOT_Live_Traffic_Cameras/FeatureServer/0/query";
|
||||
|
||||
const PAGE_SIZE = 2000;
|
||||
|
||||
|
||||
@@ -29,9 +29,9 @@ export async function GET(req: NextRequest) {
|
||||
|
||||
try {
|
||||
const upstream = await fetch(targetUrl, {
|
||||
headers: {
|
||||
headers: {
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
||||
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
|
||||
Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
|
||||
"Accept-Language": "en-US,en;q=0.5",
|
||||
},
|
||||
signal: AbortSignal.timeout(MAX_IFRAME_DURATION_MS),
|
||||
@@ -45,7 +45,7 @@ export async function GET(req: NextRequest) {
|
||||
}
|
||||
|
||||
const contentType = upstream.headers.get("content-type") || "text/html";
|
||||
|
||||
|
||||
// If it's not HTML, just proxy the stream directly (fallback)
|
||||
if (!contentType.includes("text/html")) {
|
||||
return new Response(upstream.body as ReadableStream, {
|
||||
|
||||
@@ -27,7 +27,7 @@ export async function GET(req: NextRequest) {
|
||||
const response = await safeFetch(targetUrl, {
|
||||
headers: {
|
||||
"User-Agent": "WorldWideView/1.0",
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
Accept: "application/json, text/plain, */*",
|
||||
},
|
||||
maxSize: 5 * 1024 * 1024, // 5MB
|
||||
timeout: 10000 // 10s
|
||||
|
||||
@@ -48,8 +48,7 @@ export async function GET(req: NextRequest) {
|
||||
);
|
||||
}
|
||||
|
||||
const contentType =
|
||||
upstream.headers.get("content-type") || "application/octet-stream";
|
||||
const contentType = upstream.headers.get("content-type") || "application/octet-stream";
|
||||
|
||||
return new Response(upstream.body as ReadableStream, {
|
||||
status: 200,
|
||||
|
||||
@@ -8,7 +8,7 @@ function isPrivateUrl(urlStr: string): boolean {
|
||||
const parsed = new URL(urlStr);
|
||||
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return true;
|
||||
const host = parsed.hostname;
|
||||
|
||||
|
||||
// If developer overrides local restrictions, bypass checks
|
||||
if (process.env.WWV_PROXY_ALLOW_LOCAL === "true") return false;
|
||||
|
||||
@@ -47,18 +47,19 @@ export async function GET(req: NextRequest) {
|
||||
headers: { "User-Agent": "WorldWideView/1.0" },
|
||||
signal: AbortSignal.timeout(TIMEOUT_MS)
|
||||
});
|
||||
} catch (headError: any) {
|
||||
// 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.
|
||||
} 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,13 +82,14 @@ export async function GET(req: NextRequest) {
|
||||
contentType: response.headers.get("content-type"),
|
||||
latencyMs: Date.now() - startTime
|
||||
});
|
||||
} 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
|
||||
@@ -95,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 });
|
||||
}
|
||||
|
||||
|
||||
@@ -13,8 +13,7 @@
|
||||
|
||||
import type { GdotCameraFeature } from "../gdot/gdotFetcher";
|
||||
|
||||
const WSDOT_BASE =
|
||||
"https://wsdot.wa.gov/Traffic/api/HighwayCameras/HighwayCamerasREST.svc/GetCamerasAsJson";
|
||||
const WSDOT_BASE = "https://wsdot.wa.gov/Traffic/api/HighwayCameras/HighwayCamerasREST.svc/GetCamerasAsJson";
|
||||
|
||||
interface WsdotCamera {
|
||||
CameraID: number;
|
||||
@@ -78,8 +77,8 @@ export async function fetchWsdotCameras(): Promise<GdotCameraFeature[]> {
|
||||
if (!key) {
|
||||
if (!warnedMissingKey) {
|
||||
console.warn(
|
||||
"[WSDOT] WSDOT_API_KEY not set — skipping. " +
|
||||
"Get a free key at https://wsdot.wa.gov/traffic/api/",
|
||||
"[WSDOT] WSDOT_API_KEY not set — skipping. "
|
||||
+ "Get a free key at https://wsdot.wa.gov/traffic/api/",
|
||||
);
|
||||
warnedMissingKey = true;
|
||||
}
|
||||
|
||||
@@ -30,10 +30,10 @@ export async function POST(request: Request) {
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
|
||||
|
||||
// Convert wwv-manifest.json format to PluginManifest format
|
||||
const manifest = parseWwvManifest(body);
|
||||
|
||||
|
||||
// Dev-loaded plugins are unverified by default
|
||||
manifest.trust = "unverified";
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ export async function GET(
|
||||
|
||||
// Await params as required in Next.js 15+
|
||||
const resolvedParams = await params;
|
||||
const subdomain = resolvedParams.subdomain;
|
||||
const {subdomain} = resolvedParams;
|
||||
|
||||
try {
|
||||
const workspace = await prisma.workspace.findUnique({
|
||||
|
||||
@@ -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 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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,22 +2,23 @@ import { NextRequest, NextResponse } from "next/server";
|
||||
import * as client from "openid-client";
|
||||
import { encryptCredential } from "@/lib/auth/encryption";
|
||||
import { prisma as db } from "@/lib/db";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const isHttps = req.nextUrl.protocol === "https:";
|
||||
const cookiePrefix = isHttps ? "__Host-" : "";
|
||||
|
||||
|
||||
const stateCookie = req.cookies.get(`${cookiePrefix}pkce_state`)?.value;
|
||||
const verifierCookie = req.cookies.get(`${cookiePrefix}pkce_verifier`)?.value;
|
||||
const urlState = req.nextUrl.searchParams.get("state");
|
||||
|
||||
|
||||
if (!stateCookie || urlState !== stateCookie) {
|
||||
return NextResponse.json({ error: "State mismatch" }, { status: 400 });
|
||||
}
|
||||
|
||||
|
||||
if (!verifierCookie) {
|
||||
return NextResponse.json({ error: "Missing code_verifier" }, { status: 400 });
|
||||
}
|
||||
|
||||
|
||||
const marketplaceUrl = process.env.NEXT_PUBLIC_WWV_MARKETPLACE_URL || "https://app.worldwideview.dev";
|
||||
const issuer = new URL(marketplaceUrl);
|
||||
const server = {
|
||||
@@ -33,7 +34,7 @@ export async function GET(req: NextRequest) {
|
||||
new URL(req.url),
|
||||
{ expectedState: stateCookie, pkceCodeVerifier: verifierCookie }
|
||||
);
|
||||
|
||||
|
||||
if (tokens.access_token) {
|
||||
const encrypted = await encryptCredential(tokens.access_token);
|
||||
await db.marketplaceCredential.upsert({
|
||||
@@ -57,9 +58,9 @@ export async function GET(req: NextRequest) {
|
||||
console.error("[PKCE] Exchange failed:", err.message);
|
||||
return NextResponse.json({ error: "Failed to exchange authorization code" }, { status: 500 });
|
||||
}
|
||||
|
||||
|
||||
const res = NextResponse.redirect(new URL("/", req.nextUrl.origin), 302);
|
||||
|
||||
|
||||
res.cookies.set(`${cookiePrefix}pkce_state`, "", {
|
||||
httpOnly: true,
|
||||
secure: isHttps,
|
||||
@@ -67,7 +68,7 @@ export async function GET(req: NextRequest) {
|
||||
path: "/api/marketplace/callback",
|
||||
maxAge: 0
|
||||
});
|
||||
|
||||
|
||||
res.cookies.set(`${cookiePrefix}pkce_verifier`, "", {
|
||||
httpOnly: true,
|
||||
secure: isHttps,
|
||||
@@ -75,6 +76,6 @@ export async function GET(req: NextRequest) {
|
||||
path: "/api/marketplace/callback",
|
||||
maxAge: 0
|
||||
});
|
||||
|
||||
|
||||
return res;
|
||||
}
|
||||
@@ -12,7 +12,7 @@ export async function GET(request: Request) {
|
||||
try {
|
||||
// Fetch currently installed plugins from PostgreSQL
|
||||
const installedPlugins = await getInstalledPlugins();
|
||||
|
||||
|
||||
// Exclude built-in versions, only check genuine semver strings or unverified records.
|
||||
const updatablePlugins = installedPlugins.filter((p: any) => p.version !== "built-in");
|
||||
|
||||
@@ -24,13 +24,13 @@ export async function GET(request: Request) {
|
||||
const res = await fetch(`${MARKETPLACE_URL}/api/plugins`, {
|
||||
next: { revalidate: 60 } // Cache for 60 seconds
|
||||
});
|
||||
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`Marketplace returned ${res.status}`);
|
||||
}
|
||||
|
||||
const marketplacePlugins = await res.json();
|
||||
|
||||
|
||||
// Build a lookup map of Market versions
|
||||
const marketVersions = new Map();
|
||||
for (const p of marketplacePlugins) {
|
||||
@@ -42,7 +42,7 @@ export async function GET(request: Request) {
|
||||
// Compare and flag updates
|
||||
for (const localPlugin of updatablePlugins) {
|
||||
const marketVersion = marketVersions.get(localPlugin.pluginId);
|
||||
|
||||
|
||||
// Only suggest an update if marketplace version exists and differs
|
||||
if (marketVersion && marketVersion !== "0.0.0" && marketVersion !== localPlugin.version) {
|
||||
updates[localPlugin.pluginId] = marketVersion;
|
||||
|
||||
@@ -5,9 +5,9 @@ export async function GET(req: NextRequest) {
|
||||
const state = client.randomState();
|
||||
const code_verifier = client.randomPKCECodeVerifier();
|
||||
const code_challenge = await client.calculatePKCECodeChallenge(code_verifier);
|
||||
|
||||
|
||||
const marketplaceUrl = process.env.NEXT_PUBLIC_WWV_MARKETPLACE_URL || "https://app.worldwideview.dev";
|
||||
|
||||
|
||||
const url = new URL("/oauth/authorize", marketplaceUrl);
|
||||
url.searchParams.set("client_id", "local-app");
|
||||
url.searchParams.set("response_type", "code");
|
||||
@@ -16,12 +16,12 @@ export async function GET(req: NextRequest) {
|
||||
url.searchParams.set("state", state);
|
||||
url.searchParams.set("redirect_uri", `${req.nextUrl.origin}/api/marketplace/callback`);
|
||||
url.searchParams.set("scope", "plugins:read");
|
||||
|
||||
|
||||
const res = NextResponse.redirect(url.toString(), 302);
|
||||
|
||||
|
||||
const isHttps = req.nextUrl.protocol === "https:";
|
||||
const cookiePrefix = isHttps ? "__Host-" : "";
|
||||
|
||||
|
||||
res.cookies.set(`${cookiePrefix}pkce_state`, state, {
|
||||
httpOnly: true,
|
||||
secure: isHttps,
|
||||
@@ -29,7 +29,7 @@ export async function GET(req: NextRequest) {
|
||||
path: "/api/marketplace/callback",
|
||||
maxAge: 60 * 10 // 10 minutes
|
||||
});
|
||||
|
||||
|
||||
res.cookies.set(`${cookiePrefix}pkce_verifier`, code_verifier, {
|
||||
httpOnly: true,
|
||||
secure: isHttps,
|
||||
@@ -37,6 +37,6 @@ export async function GET(req: NextRequest) {
|
||||
path: "/api/marketplace/callback",
|
||||
maxAge: 60 * 10 // 10 minutes
|
||||
});
|
||||
|
||||
|
||||
return res;
|
||||
}
|
||||
@@ -17,8 +17,8 @@ function isSafeRedirect(url: string): boolean {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
return (
|
||||
ALLOWED_REDIRECT_HOSTS.has(parsed.hostname) ||
|
||||
parsed.hostname.endsWith(".worldwideview.dev")
|
||||
ALLOWED_REDIRECT_HOSTS.has(parsed.hostname)
|
||||
|| parsed.hostname.endsWith(".worldwideview.dev")
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
@@ -53,7 +53,7 @@ export async function GET(request: NextRequest) {
|
||||
if (!session?.user) {
|
||||
const origin = getRequestOrigin(request);
|
||||
const loginUrl = new URL("/login", origin);
|
||||
|
||||
|
||||
// Construct a relative path for callback to ensure it redirects back to the identical host
|
||||
const callbackPath = request.nextUrl.pathname + request.nextUrl.search;
|
||||
loginUrl.searchParams.set("callbackUrl", callbackPath);
|
||||
|
||||
@@ -24,7 +24,7 @@ if (process.env.ALLOWED_DEV_ORIGIN) {
|
||||
function isSafeRedirect(url: string): boolean {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
const hostname = parsed.hostname;
|
||||
const {hostname} = parsed;
|
||||
return ALLOWED_REDIRECT_HOSTS.has(hostname) || hostname.endsWith(".worldwideview.dev");
|
||||
} catch {
|
||||
return false;
|
||||
@@ -126,7 +126,6 @@ export async function GET(request: NextRequest) {
|
||||
|
||||
// Token in fragment — never sent to server in logs/referer
|
||||
return NextResponse.redirect(`${successUrl.toString()}#token=${token}`);
|
||||
|
||||
} catch (err) {
|
||||
// Top-level catch: log and redirect to marketplace with error, don't expose raw 500
|
||||
console.error("[install-redirect] Unexpected error:", err);
|
||||
|
||||
@@ -21,8 +21,6 @@ export async function POST(request: Request) {
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
|
||||
const rateLimited = marketplaceApiLimiter.check(getClientIp(request));
|
||||
if (rateLimited) return withCors(rateLimited, request);
|
||||
|
||||
@@ -53,9 +51,9 @@ export async function POST(request: Request) {
|
||||
if (res.ok) {
|
||||
const card = await res.json();
|
||||
finalManifest = { ...card };
|
||||
|
||||
|
||||
// Reconstruct entry URL for plugins that are distributed via NPM.
|
||||
// We also forcefully coerce format to "bundle" here because
|
||||
// We also forcefully coerce format to "bundle" here because
|
||||
// the marketplace cache might still return "static" for plugins we recently converted.
|
||||
if (finalManifest.npmPackage) {
|
||||
const targetVersion = version || finalManifest.version || "1.0.0";
|
||||
@@ -73,9 +71,9 @@ export async function POST(request: Request) {
|
||||
const validation = validateManifest(finalManifest);
|
||||
if (!validation.valid) {
|
||||
console.error(
|
||||
`[Marketplace Install Route] ❌ MANIFEST VALIDATION FAILED for ${pluginId}\n` +
|
||||
`Errors: ${validation.errors.join(", ")}\n` +
|
||||
`Evaluated Payload:\n${JSON.stringify(finalManifest, null, 2)}`
|
||||
`[Marketplace Install Route] ❌ MANIFEST VALIDATION FAILED for ${pluginId}\n`
|
||||
+ `Errors: ${validation.errors.join(", ")}\n`
|
||||
+ `Evaluated Payload:\n${JSON.stringify(finalManifest, null, 2)}`
|
||||
);
|
||||
return withCors(
|
||||
NextResponse.json(
|
||||
|
||||
@@ -65,9 +65,7 @@ export async function GET(request: Request) {
|
||||
}
|
||||
|
||||
const allRecords = [...records, ...localPlugins];
|
||||
|
||||
|
||||
|
||||
const manifests = allRecords
|
||||
.map((r: any): PluginManifest | null => {
|
||||
try {
|
||||
@@ -92,10 +90,10 @@ export async function GET(request: Request) {
|
||||
// Skip bundle plugins whose entry is a bare module specifier
|
||||
// (e.g. "camera") — cannot be dynamically imported in the browser.
|
||||
if (
|
||||
m.format === "bundle" &&
|
||||
!m.entry.startsWith("/") &&
|
||||
!m.entry.startsWith("./") &&
|
||||
!m.entry.startsWith("http")
|
||||
m.format === "bundle"
|
||||
&& !m.entry.startsWith("/")
|
||||
&& !m.entry.startsWith("./")
|
||||
&& !m.entry.startsWith("http")
|
||||
) return false;
|
||||
|
||||
// For anything that looks like a real manifest, validate it and log if it fails
|
||||
@@ -103,7 +101,7 @@ export async function GET(request: Request) {
|
||||
if (!validation.valid) {
|
||||
const errorMessage = `Manifest validation failed for ${m.id}`;
|
||||
console.error(`[Marketplace API] ${errorMessage}:`, validation.errors);
|
||||
|
||||
|
||||
// Capture in Sentry so we have visibility into malformed third-party plugins
|
||||
Sentry.captureMessage(errorMessage, {
|
||||
level: "error",
|
||||
@@ -131,7 +129,7 @@ export async function GET(request: Request) {
|
||||
if (m.format === "declarative" && m.dataSource) {
|
||||
// Only omit headers and potentially sensitive auth params.
|
||||
// The URL might be needed by the client for polling, but headers like Bearer tokens shouldn't leak.
|
||||
// If the audit explicitly asks to strip URL, maybe just replace it entirely if it's sensitive,
|
||||
// If the audit explicitly asks to strip URL, maybe just replace it entirely if it's sensitive,
|
||||
// but usually headers are the sensitive part. We strip headers.
|
||||
if (m.dataSource.headers) {
|
||||
m.dataSource.headers = {};
|
||||
@@ -146,4 +144,3 @@ export async function GET(request: Request) {
|
||||
return withCors(NextResponse.json({ manifests: [] }), request);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import {
|
||||
describe, it, expect, vi, beforeEach
|
||||
} from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
import { GET as connectRoute } from "./connect/route";
|
||||
import { GET as callbackRoute } from "./callback/route";
|
||||
@@ -39,14 +41,14 @@ describe("PKCE Flow", () => {
|
||||
it("should generate PKCE parameters and redirect with secure cookies", async () => {
|
||||
const req = new NextRequest("https://localhost:3000/api/marketplace/connect");
|
||||
const res = await connectRoute(req);
|
||||
|
||||
|
||||
expect(res.status).toBe(302);
|
||||
|
||||
|
||||
// Check redirect URL
|
||||
const location = res.headers.get("Location");
|
||||
expect(location).toContain("response_type=code");
|
||||
expect(location).toContain("code_challenge_method=S256");
|
||||
|
||||
|
||||
// Check cookie flags
|
||||
const cookies = res.headers.get("Set-Cookie");
|
||||
expect(cookies).toBeDefined();
|
||||
@@ -63,7 +65,7 @@ describe("PKCE Flow", () => {
|
||||
it("should reject if state does not match", async () => {
|
||||
const req = new NextRequest("https://localhost:3000/api/marketplace/callback?state=wrong-state&code=test-code");
|
||||
req.cookies.set("__Host-pkce_state", "correct-state");
|
||||
|
||||
|
||||
const res = await callbackRoute(req);
|
||||
expect(res.status).toBe(400);
|
||||
expect(await res.json()).toEqual({ error: "State mismatch" });
|
||||
@@ -73,7 +75,7 @@ describe("PKCE Flow", () => {
|
||||
const req = new NextRequest("https://localhost:3000/api/marketplace/callback?state=correct-state&code=test-code");
|
||||
req.cookies.set("__Host-pkce_state", "correct-state");
|
||||
// code_verifier cookie is intentionally omitted
|
||||
|
||||
|
||||
const res = await callbackRoute(req);
|
||||
expect(res.status).toBe(400);
|
||||
expect(await res.json()).toEqual({ error: "Missing code_verifier" });
|
||||
@@ -83,19 +85,19 @@ describe("PKCE Flow", () => {
|
||||
const req = new NextRequest("https://localhost:3000/api/marketplace/callback?state=correct-state&code=test-code");
|
||||
req.cookies.set("__Host-pkce_state", "correct-state");
|
||||
req.cookies.set("__Host-pkce_verifier", "mock-verifier");
|
||||
|
||||
|
||||
const res = await callbackRoute(req);
|
||||
|
||||
|
||||
const cookies = res.headers.get("Set-Cookie");
|
||||
expect(cookies).toContain("__Host-pkce_state=;");
|
||||
expect(cookies).toContain("Max-Age=0");
|
||||
});
|
||||
|
||||
|
||||
it("should perform openid-client exchange and save encrypted token", async () => {
|
||||
const req = new NextRequest("https://localhost:3000/api/marketplace/callback?state=correct-state&code=test-code");
|
||||
req.cookies.set("__Host-pkce_state", "correct-state");
|
||||
req.cookies.set("__Host-pkce_verifier", "mock-verifier");
|
||||
|
||||
|
||||
const res = await callbackRoute(req);
|
||||
expect(res.status).toBe(302); // Redirect back to marketplace or app
|
||||
});
|
||||
|
||||
@@ -44,8 +44,7 @@ export async function GET(request: Request) {
|
||||
const authError = await validateMarketplaceAuth(request);
|
||||
canManagePlugins = authError === null;
|
||||
}
|
||||
|
||||
|
||||
return withCors(NextResponse.json({ plugins: [], canManagePlugins }), request);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,8 +19,6 @@ export async function POST(request: Request) {
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
|
||||
const rateLimited = marketplaceApiLimiter.check(getClientIp(request));
|
||||
if (rateLimited) return withCors(rateLimited, request);
|
||||
|
||||
@@ -59,4 +57,3 @@ export async function POST(request: Request) {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import https from "https";
|
||||
|
||||
const OVERPASS_MIRRORS = [
|
||||
"https://overpass-api.de/api/interpreter",
|
||||
"https://lz4.overpass-api.de/api/interpreter",
|
||||
"https://overpass.kumi.systems/api/interpreter"
|
||||
];
|
||||
|
||||
import https from "https";
|
||||
|
||||
async function tryMirror(urlStr: string, query: string, timeoutMs: number) {
|
||||
return new Promise<any>((resolve, reject) => {
|
||||
const url = new URL(urlStr);
|
||||
const bodyStr = `data=${encodeURIComponent(query)}`;
|
||||
|
||||
|
||||
const req = https.request(url, {
|
||||
method: "POST",
|
||||
family: 4, // Force IPv4 to avoid Docker IPv6 dropout
|
||||
@@ -24,7 +24,7 @@ async function tryMirror(urlStr: string, query: string, timeoutMs: number) {
|
||||
timeout: timeoutMs,
|
||||
}, (res) => {
|
||||
let data = "";
|
||||
res.on("data", chunk => data += chunk);
|
||||
res.on("data", (chunk) => data += chunk);
|
||||
res.on("end", () => {
|
||||
resolve({
|
||||
ok: res.statusCode && res.statusCode >= 200 && res.statusCode < 300,
|
||||
@@ -41,7 +41,7 @@ async function tryMirror(urlStr: string, query: string, timeoutMs: number) {
|
||||
req.destroy();
|
||||
reject(new Error("Request timed out"));
|
||||
});
|
||||
|
||||
|
||||
req.write(bodyStr);
|
||||
req.end();
|
||||
});
|
||||
@@ -92,7 +92,7 @@ export async function POST(req: Request) {
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{ error: "All Overpass mirrors failed or timed out. The OSM servers are likely under heavy load." },
|
||||
{ error: "All Overpass mirrors failed or timed out. The OSM servers are likely under heavy load." },
|
||||
{ status: 504 }
|
||||
);
|
||||
} catch (e: any) {
|
||||
|
||||
@@ -7,7 +7,7 @@ export async function GET() {
|
||||
const response = await fetch("https://www.submarinecablemap.com/api/v3/cable/cable-geo.json", {
|
||||
headers: {
|
||||
"User-Agent": "WorldWideView/1.0",
|
||||
"Accept": "application/json",
|
||||
Accept: "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ export async function GET(request: Request) {
|
||||
where: { userId: session.user.id },
|
||||
orderBy: { lastSeen: "desc" }
|
||||
});
|
||||
|
||||
|
||||
return NextResponse.json(favorites);
|
||||
} catch (e) {
|
||||
console.error("GET Favorites Error:", e);
|
||||
@@ -29,7 +29,9 @@ export async function POST(request: Request) {
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { entityId, pluginId, label, pluginName } = body;
|
||||
const {
|
||||
entityId, pluginId, label, pluginName
|
||||
} = body;
|
||||
|
||||
if (!entityId || !pluginId || !label || !pluginName) {
|
||||
return NextResponse.json({ error: "Missing required fields" }, { status: 400 });
|
||||
@@ -39,7 +41,7 @@ export async function POST(request: Request) {
|
||||
where: {
|
||||
userId_entityId: {
|
||||
userId: session.user.id,
|
||||
entityId: entityId
|
||||
entityId
|
||||
}
|
||||
},
|
||||
update: {
|
||||
@@ -70,7 +72,7 @@ export async function DELETE(request: Request) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const entityId = searchParams.get("entityId");
|
||||
|
||||
|
||||
if (!entityId) {
|
||||
return NextResponse.json({ error: "Missing entityId" }, { status: 400 });
|
||||
}
|
||||
@@ -79,7 +81,7 @@ export async function DELETE(request: Request) {
|
||||
where: {
|
||||
userId_entityId: {
|
||||
userId: session.user.id,
|
||||
entityId: entityId
|
||||
entityId
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
+225
-3
@@ -218,7 +218,7 @@ html, body {
|
||||
.sidebar {
|
||||
position: fixed;
|
||||
top: 80px; /* Reduced to ~12px gap from header */
|
||||
bottom: 140px; /* Reduced gap from timeline */
|
||||
bottom: var(--sidebar-bottom, 140px); /* Dynamically pushed by BottomPanelManager */
|
||||
width: 280px;
|
||||
z-index: 50;
|
||||
padding: var(--space-lg);
|
||||
@@ -230,8 +230,16 @@ html, body {
|
||||
bottom var(--duration-slow) var(--ease-smooth);
|
||||
}
|
||||
|
||||
.timeline-closed .sidebar {
|
||||
bottom: var(--space-lg);
|
||||
body.is-dragging-bottom-panel .sidebar {
|
||||
transition: transform var(--duration-slow) var(--ease-smooth),
|
||||
opacity var(--duration-slow) var(--ease-smooth);
|
||||
}
|
||||
|
||||
/* Force animation when crossing the threshold (overrides is-dragging) */
|
||||
body.sidebar-force-transition .sidebar {
|
||||
transition: transform var(--duration-slow) var(--ease-smooth),
|
||||
opacity var(--duration-slow) var(--ease-smooth),
|
||||
bottom var(--duration-slow) var(--ease-smooth) !important;
|
||||
}
|
||||
|
||||
.sidebar--left {
|
||||
@@ -1912,3 +1920,217 @@ body.is-resizing-sidebar .sidebar {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
/* ─── Bottom Panel Manager ───────────────────────────────── */
|
||||
.bottom-panel-system {
|
||||
position: absolute;
|
||||
bottom: var(--space-lg, 20px);
|
||||
left: var(--space-lg, 20px);
|
||||
right: calc(var(--ad-strip-inset, 0px) + var(--space-lg, 20px));
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
z-index: 1000;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.bottom-panel-dock {
|
||||
display: flex;
|
||||
margin-bottom: 0; /* Flush with panel */
|
||||
pointer-events: auto;
|
||||
transition: transform var(--duration-normal) var(--ease-smooth), gap var(--duration-fast) var(--ease-smooth);
|
||||
|
||||
/* Centered, horizontally scrollable container */
|
||||
max-width: 100%;
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
scrollbar-width: none; /* Firefox */
|
||||
-ms-overflow-style: none; /* IE/Edge */
|
||||
|
||||
/* Safely center items but prevent left-side clipping on overflow */
|
||||
justify-content: safe center;
|
||||
|
||||
/* Small negative gap so the slanted bases touch/overlap nicely */
|
||||
gap: -4px;
|
||||
padding: 0 12px;
|
||||
}
|
||||
|
||||
.bottom-panel-dock::-webkit-scrollbar {
|
||||
display: none; /* Safari/Chrome */
|
||||
}
|
||||
|
||||
/* The actual button container (transparent, straight rectangle) */
|
||||
.dock-btn {
|
||||
position: relative;
|
||||
flex-shrink: 0;
|
||||
height: 36px;
|
||||
padding: 0 24px; /* Wider padding to account for slanted sides */
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: var(--text-secondary);
|
||||
cursor: pointer;
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.05em;
|
||||
text-transform: uppercase;
|
||||
isolation: isolate; /* Create new stacking context so pseudo-elements don't escape */
|
||||
transition: color var(--duration-fast) var(--ease-smooth), padding var(--duration-fast) var(--ease-smooth);
|
||||
}
|
||||
|
||||
/* The angled background shape using 3D perspective */
|
||||
.dock-btn::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0; right: 0; bottom: 0; left: 0;
|
||||
z-index: -1;
|
||||
background: var(--bg-glass);
|
||||
backdrop-filter: blur(var(--glass-blur, 24px));
|
||||
border: var(--glass-border);
|
||||
border-bottom: none;
|
||||
border-radius: var(--radius-sm) var(--radius-sm) 0 0;
|
||||
/* Create the trapezoid slant by rotating back on the X axis */
|
||||
transform: perspective(20px) rotateX(5deg);
|
||||
transform-origin: bottom;
|
||||
transition: all var(--duration-fast) var(--ease-smooth);
|
||||
opacity: 0.6; /* More transparent when inactive */
|
||||
}
|
||||
|
||||
.dock-btn:hover {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.dock-btn:hover::before {
|
||||
background: var(--bg-glass-hover);
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
.dock-btn.active {
|
||||
color: var(--accent-cyan);
|
||||
font-weight: 600;
|
||||
z-index: 2; /* Bring active tab to front */
|
||||
}
|
||||
|
||||
.dock-btn.active::before {
|
||||
background: var(--bg-glass-active);
|
||||
border-color: rgba(var(--accent-rgb), 0.5);
|
||||
box-shadow: inset 0 0 40px rgba(var(--accent-rgb), 0.08), 0 -4px 15px rgba(var(--accent-rgb), 0.15); /* Tint + Glow upwards */
|
||||
opacity: 1; /* Fully opaque (relative to the rgba alpha) when active */
|
||||
}
|
||||
|
||||
.dock-btn-label {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* ─── Floating Pills Mode (when no panel is active) ─── */
|
||||
.bottom-panel-dock.floating-pills {
|
||||
gap: 8px; /* Give them breathing room */
|
||||
}
|
||||
|
||||
.bottom-panel-dock.floating-pills .dock-btn {
|
||||
padding: 0 16px; /* Less horizontal padding since it's not a trapezoid */
|
||||
}
|
||||
|
||||
.bottom-panel-dock.floating-pills .dock-btn::before {
|
||||
border-radius: var(--radius-full);
|
||||
transform: none; /* Remove trapezoid slant */
|
||||
border-bottom: var(--glass-border); /* Restore full border */
|
||||
}
|
||||
|
||||
.bottom-panel {
|
||||
width: 100%;
|
||||
/* border-radius: var(--radius-lg); - handled by .glass-panel */
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
pointer-events: auto;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
/* Transition applied to height in style, but we can animate opacity/transform too */
|
||||
transition: height var(--duration-slow) var(--ease-smooth), opacity var(--duration-normal) var(--ease-smooth);
|
||||
|
||||
/* Removed background override so it inherits .glass-panel perfectly */
|
||||
margin-top: -1px; /* Overlap the 1px border so tabs sit perfectly flush */
|
||||
}
|
||||
|
||||
/* Disable height transition during drag to prevent lag */
|
||||
body.is-dragging-bottom-panel .bottom-panel {
|
||||
transition: opacity var(--duration-normal) var(--ease-smooth);
|
||||
}
|
||||
|
||||
.bottom-panel.closed {
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
border: none;
|
||||
}
|
||||
|
||||
.bottom-panel.open {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.bottom-panel-resize-handle {
|
||||
height: 12px;
|
||||
width: 100%;
|
||||
cursor: ns-resize;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
background: transparent;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.bottom-panel-resize-handle:hover .resize-grip {
|
||||
background: rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
|
||||
.resize-grip {
|
||||
width: 40px;
|
||||
height: 4px;
|
||||
border-radius: 2px;
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
.bottom-panel-close-btn {
|
||||
position: absolute;
|
||||
top: 12px;
|
||||
right: 12px;
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
cursor: pointer;
|
||||
padding: 4px;
|
||||
border-radius: 4px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 10;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.bottom-panel-close-btn:hover {
|
||||
color: white;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.bottom-panel-content {
|
||||
padding: 24px;
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
/* Ensure the content sits below the resize handle */
|
||||
margin-top: 12px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
/* Timeline adjustments inside the new panel */
|
||||
.timeline__content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
height: 100%;
|
||||
}
|
||||
+2
-2
@@ -38,9 +38,9 @@ export default function RootLayout({
|
||||
)}
|
||||
{/* Load CesiumJS base styles (optional, but helps with UI widgets if used later) */}
|
||||
<link rel="stylesheet" href="/cesium/Widgets/widgets.css" />
|
||||
<Script
|
||||
<script
|
||||
id="theme-hydration"
|
||||
strategy="beforeInteractive"
|
||||
suppressHydrationWarning
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: `
|
||||
try {
|
||||
|
||||
@@ -27,10 +27,10 @@ export async function loginAction(formData: FormData): Promise<LoginResult> {
|
||||
email,
|
||||
password,
|
||||
});
|
||||
|
||||
|
||||
if (error) return { success: false, error: error.message };
|
||||
return { success: true };
|
||||
} else {
|
||||
}
|
||||
try {
|
||||
await signIn("credentials", {
|
||||
email,
|
||||
@@ -49,5 +49,4 @@ export async function loginAction(formData: FormData): Promise<LoginResult> {
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
+37
-38
@@ -2,8 +2,8 @@
|
||||
|
||||
import { Suspense, useState } from "react";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { loginAction } from "./actions";
|
||||
import { isDemo } from "@/core/edition";
|
||||
import { loginAction } from "./actions";
|
||||
import styles from "../setup/setup.module.css";
|
||||
|
||||
/** Allow relative paths or absolute URLs on the same origin. */
|
||||
@@ -48,52 +48,51 @@ function LoginForm() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
<div className={styles.card}>
|
||||
<div className={styles.logo}>W</div>
|
||||
<h1 className={styles.title}>Sign in to WorldWideView</h1>
|
||||
<p className={styles.subtitle}>Enter your credentials to continue</p>
|
||||
<div className={styles.container}>
|
||||
<div className={styles.card}>
|
||||
<div className={styles.logo}>W</div>
|
||||
<h1 className={styles.title}>Sign in to WorldWideView</h1>
|
||||
<p className={styles.subtitle}>Enter your credentials to continue</p>
|
||||
|
||||
<form onSubmit={handleSubmit} method="post" className={styles.form}>
|
||||
<label className={styles.label} htmlFor="email">
|
||||
{isDemo ? "Username" : "Email"}
|
||||
</label>
|
||||
<input
|
||||
id="email"
|
||||
name="email"
|
||||
type={isDemo ? "text" : "email"}
|
||||
required
|
||||
className={styles.input}
|
||||
placeholder={isDemo ? "admin" : "[email protected]"}
|
||||
/>
|
||||
<form onSubmit={handleSubmit} method="post" className={styles.form}>
|
||||
<label className={styles.label} htmlFor="email">
|
||||
{isDemo ? "Username" : "Email"}
|
||||
<input
|
||||
id="email"
|
||||
name="email"
|
||||
type={isDemo ? "text" : "email"}
|
||||
required
|
||||
className={styles.input}
|
||||
placeholder={isDemo ? "admin" : "[email protected]"}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className={styles.label} htmlFor="password">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
required
|
||||
className={styles.input}
|
||||
/>
|
||||
<label className={styles.label} htmlFor="password">
|
||||
Password
|
||||
<input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
required
|
||||
className={styles.input}
|
||||
/>
|
||||
</label>
|
||||
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
|
||||
<button type="submit" disabled={loading} className={styles.button}>
|
||||
{loading ? "Signing in..." : "Sign In"}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
<button type="submit" disabled={loading} className={styles.button}>
|
||||
{loading ? "Signing in..." : "Sign In"}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function LoginPage() {
|
||||
return (
|
||||
<Suspense>
|
||||
<LoginForm />
|
||||
</Suspense>
|
||||
<Suspense>
|
||||
<LoginForm />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -32,7 +32,9 @@ export async function createAdminAccount(formData: FormData): Promise<SetupResul
|
||||
|
||||
const hashedPassword = hashSync(password, 12);
|
||||
await prisma.user.create({
|
||||
data: { name, email, hashedPassword, role: "admin" },
|
||||
data: {
|
||||
name, email, hashedPassword, role: "admin"
|
||||
},
|
||||
});
|
||||
|
||||
return { success: true };
|
||||
|
||||
+57
-64
@@ -27,76 +27,69 @@ export default function SetupPage() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
<div className={styles.card}>
|
||||
<div className={styles.logo}>W</div>
|
||||
<h1 className={styles.title}>Welcome to WorldWideView</h1>
|
||||
<p className={styles.subtitle}>Create your admin account to get started</p>
|
||||
<div className={styles.container}>
|
||||
<div className={styles.card}>
|
||||
<div className={styles.logo}>W</div>
|
||||
<h1 className={styles.title}>Welcome to WorldWideView</h1>
|
||||
<p className={styles.subtitle}>Create your admin account to get started</p>
|
||||
|
||||
{/* Legacy Data Detection Banner */}
|
||||
<div className={styles.legacyNotice}>
|
||||
<strong>💡 Upgrading from an older version?</strong>
|
||||
<p>We've detected legacy SQLite data. Once your new Postgres database is connected, you can import your favorites by running the migration command in your terminal.</p>
|
||||
<code>docker compose exec wwv node scripts/migrate-legacy.mjs</code>
|
||||
</div>
|
||||
<form onSubmit={handleSubmit} className={styles.form}>
|
||||
<label className={styles.label} htmlFor="name">
|
||||
Display Name
|
||||
<input
|
||||
id="name"
|
||||
name="name"
|
||||
type="text"
|
||||
required
|
||||
className={styles.input}
|
||||
placeholder="Admin"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<form onSubmit={handleSubmit} className={styles.form}>
|
||||
<label className={styles.label} htmlFor="name">
|
||||
Display Name
|
||||
</label>
|
||||
<input
|
||||
id="name"
|
||||
name="name"
|
||||
type="text"
|
||||
required
|
||||
className={styles.input}
|
||||
placeholder="Admin"
|
||||
/>
|
||||
<label className={styles.label} htmlFor="email">
|
||||
Email
|
||||
<input
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
required
|
||||
className={styles.input}
|
||||
placeholder="[email protected]"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className={styles.label} htmlFor="email">
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
required
|
||||
className={styles.input}
|
||||
placeholder="[email protected]"
|
||||
/>
|
||||
<label className={styles.label} htmlFor="password">
|
||||
Password
|
||||
<input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
required
|
||||
minLength={8}
|
||||
className={styles.input}
|
||||
placeholder="Min. 8 characters"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className={styles.label} htmlFor="password">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
required
|
||||
minLength={8}
|
||||
className={styles.input}
|
||||
placeholder="Min. 8 characters"
|
||||
/>
|
||||
<label className={styles.label} htmlFor="confirm">
|
||||
Confirm Password
|
||||
<input
|
||||
id="confirm"
|
||||
name="confirm"
|
||||
type="password"
|
||||
required
|
||||
minLength={8}
|
||||
className={styles.input}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className={styles.label} htmlFor="confirm">
|
||||
Confirm Password
|
||||
</label>
|
||||
<input
|
||||
id="confirm"
|
||||
name="confirm"
|
||||
type="password"
|
||||
required
|
||||
minLength={8}
|
||||
className={styles.input}
|
||||
/>
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
|
||||
<button type="submit" disabled={loading} className={styles.button}>
|
||||
{loading ? "Creating..." : "Create Admin Account"}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
<button type="submit" disabled={loading} className={styles.button}>
|
||||
{loading ? "Creating..." : "Create Admin Account"}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -103,27 +103,3 @@
|
||||
.button:hover { opacity: 0.9; }
|
||||
.button:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
|
||||
.legacyNotice {
|
||||
margin: 1.5rem 0;
|
||||
padding: 1rem;
|
||||
background: rgba(255, 191, 0, 0.05);
|
||||
border: 1px solid rgba(255, 191, 0, 0.3);
|
||||
text-align: left;
|
||||
font-size: 0.8rem;
|
||||
color: #ffbf00;
|
||||
}
|
||||
|
||||
.legacyNotice strong {
|
||||
display: block;
|
||||
margin-bottom: 0.4rem;
|
||||
}
|
||||
|
||||
.legacyNotice code {
|
||||
display: block;
|
||||
margin-top: 0.75rem;
|
||||
padding: 0.5rem;
|
||||
background: #000;
|
||||
color: #0f0;
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
word-break: break-all;
|
||||
}
|
||||
@@ -1,16 +1,24 @@
|
||||
import React, { useState, useEffect } from "react";
|
||||
import styles from "./page.module.css";
|
||||
import { CameraStream } from "@/components/video/CameraStream";
|
||||
import styles from "./page.module.css";
|
||||
import type { TestResult } from "./types";
|
||||
|
||||
const 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)}s</span>;
|
||||
};
|
||||
return (
|
||||
<span>
|
||||
{(Math.max(0, now - effectiveStart) / 1000).toFixed(1)}
|
||||
s
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
interface CameraTestCardProps {
|
||||
result: TestResult;
|
||||
@@ -21,8 +29,12 @@ interface CameraTestCardProps {
|
||||
onRetest: (globalIndex: number) => void;
|
||||
}
|
||||
|
||||
export function CameraTestCard({ result, index, globalIndex, previewId, onSetPreview, onRetest }: CameraTestCardProps) {
|
||||
const { feature, status, httpStatus, contentType, latencyMs, errorMsg } = result;
|
||||
export function CameraTestCard({
|
||||
result, index, globalIndex, previewId, onSetPreview, onRetest
|
||||
}: CameraTestCardProps) {
|
||||
const {
|
||||
feature, status, httpStatus, contentType, latencyMs, errorMsg
|
||||
} = result;
|
||||
const { stream, name, source } = feature.properties;
|
||||
const id = stream + index.toString();
|
||||
|
||||
@@ -33,69 +45,79 @@ export function CameraTestCard({ result, index, globalIndex, previewId, onSetPre
|
||||
else if (status === "testing") statusClass += ` ${styles.badgeTesting}`;
|
||||
|
||||
return (
|
||||
<div className={styles.card}>
|
||||
<div className={styles.cardHeader}>
|
||||
<h3 className={styles.title} title={name}>{name || "Unknown Camera"}</h3>
|
||||
<span className={styles.badge}>{source}</span>
|
||||
</div>
|
||||
<div className={styles.card}>
|
||||
<div className={styles.cardHeader}>
|
||||
<h3 className={styles.title} title={name}>{name || "Unknown Camera"}</h3>
|
||||
<span className={styles.badge}>{source}</span>
|
||||
</div>
|
||||
|
||||
<div className={styles.badges}>
|
||||
<span className={statusClass}>
|
||||
{status === "testing" ? (
|
||||
<>Testing... <LiveTimer start={result.testStartTime || Date.now()} /></>
|
||||
<div className={styles.badges}>
|
||||
<span className={statusClass}>
|
||||
{status === "testing" ? (
|
||||
<>
|
||||
Testing...
|
||||
<LiveTimer start={result.testStartTime} />
|
||||
</>
|
||||
) : (
|
||||
status.toUpperCase()
|
||||
)}
|
||||
{httpStatus && ` (${httpStatus})`}
|
||||
</span>
|
||||
{latencyMs !== undefined && <span className={styles.badge}>{latencyMs}ms</span>}
|
||||
{contentType && <span className={styles.badge}>{contentType.split(';')[0]}</span>}
|
||||
</div>
|
||||
{httpStatus && ` (${httpStatus})`}
|
||||
</span>
|
||||
{latencyMs !== undefined && (
|
||||
<span className={styles.badge}>
|
||||
{latencyMs}
|
||||
ms
|
||||
</span>
|
||||
)}
|
||||
{contentType && <span className={styles.badge}>{contentType.split(';')[0]}</span>}
|
||||
</div>
|
||||
|
||||
<div className={styles.url}>
|
||||
{stream || "No stream URL"}
|
||||
</div>
|
||||
<div className={styles.url}>
|
||||
{stream || "No stream URL"}
|
||||
</div>
|
||||
|
||||
{errorMsg && <div className={styles.errorMsg}>{errorMsg}</div>}
|
||||
{errorMsg && <div className={styles.errorMsg}>{errorMsg}</div>}
|
||||
|
||||
<div style={{ marginTop: 'auto', display: 'flex', gap: '0.5rem' }}>
|
||||
<button
|
||||
className={styles.button}
|
||||
style={{
|
||||
<div style={{ marginTop: 'auto', display: 'flex', gap: '0.5rem' }}>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.button}
|
||||
style={{
|
||||
padding: '0.4rem 0.8rem',
|
||||
fontSize: '0.8rem',
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
background: 'rgba(255,255,255,0.1)'
|
||||
}}
|
||||
onClick={() => onRetest(globalIndex)}
|
||||
>
|
||||
🔄 Retest
|
||||
</button>
|
||||
<button
|
||||
className={styles.button}
|
||||
style={{
|
||||
onClick={() => onRetest(globalIndex)}
|
||||
>
|
||||
🔄 Retest
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.button}
|
||||
style={{
|
||||
padding: '0.4rem 0.8rem',
|
||||
fontSize: '0.8rem',
|
||||
flex: 2,
|
||||
justifyContent: 'center',
|
||||
background: previewId === id ? 'rgba(255,255,255,0.15)' : '#334155'
|
||||
}}
|
||||
onClick={() => onSetPreview(previewId === id ? null : id)}
|
||||
disabled={!stream}
|
||||
>
|
||||
{previewId === id ? "Close Preview" : "Live Preview"}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{previewId === id && stream && (
|
||||
<div className={styles.preview}>
|
||||
<CameraStream
|
||||
streamUrl={stream}
|
||||
label={name}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
onClick={() => onSetPreview(previewId === id ? null : id)}
|
||||
disabled={!stream}
|
||||
>
|
||||
{previewId === id ? "Close Preview" : "Live Preview"}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{previewId === id && stream && (
|
||||
<div className={styles.preview}>
|
||||
<CameraStream
|
||||
streamUrl={stream}
|
||||
label={name}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+173
-96
@@ -12,119 +12,195 @@ export default function CameraTestPage() {
|
||||
const [testStatuses, setTestStatuses] = useState<string[]>(["all"]);
|
||||
const [previewId, setPreviewId] = useState<string | null>(null);
|
||||
|
||||
const { cameras, loading, testing, runTests, stopTests, retestCamera } = useCameraTestRunner(testSources, testStatuses);
|
||||
const {
|
||||
cameras, loading, testing, runTests, stopTests, retestCamera
|
||||
} = useCameraTestRunner(testSources, testStatuses);
|
||||
|
||||
const filtered = cameras.filter(c => {
|
||||
const filtered = cameras.filter((c) => {
|
||||
const sourceMatches = filterSources.includes("all") || filterSources.includes(c.feature.properties.source || "Unknown");
|
||||
const statusMatches = filterStatuses.includes("all") || filterStatuses.includes(c.status);
|
||||
return sourceMatches && statusMatches;
|
||||
});
|
||||
|
||||
const handleMultiSelect = (e: React.ChangeEvent<HTMLSelectElement>, setter: React.Dispatch<React.SetStateAction<string[]>>) => {
|
||||
const selected = Array.from(e.target.selectedOptions, o => o.value);
|
||||
const selected = Array.from(e.target.selectedOptions, (o) => o.value);
|
||||
if (selected.length === 0) setter(["all"]);
|
||||
else setter(selected);
|
||||
};
|
||||
|
||||
const stats = {
|
||||
total: cameras.length,
|
||||
ok: cameras.filter(c => c.status === "ok").length,
|
||||
error: cameras.filter(c => c.status === "error").length,
|
||||
timeout: cameras.filter(c => c.status === "timeout").length,
|
||||
pending: cameras.filter(c => c.status === "pending").length,
|
||||
testing: cameras.filter(c => c.status === "testing").length
|
||||
ok: cameras.filter((c) => c.status === "ok").length,
|
||||
error: cameras.filter((c) => c.status === "error").length,
|
||||
timeout: cameras.filter((c) => c.status === "timeout").length,
|
||||
pending: cameras.filter((c) => c.status === "pending").length,
|
||||
testing: cameras.filter((c) => c.status === "testing").length
|
||||
};
|
||||
|
||||
const dStats = {
|
||||
total: filtered.length,
|
||||
ok: filtered.filter(c => c.status === "ok").length,
|
||||
error: filtered.filter(c => c.status === "error").length,
|
||||
timeout: filtered.filter(c => c.status === "timeout").length,
|
||||
pending: filtered.filter(c => c.status === "pending").length,
|
||||
testing: filtered.filter(c => c.status === "testing").length
|
||||
ok: filtered.filter((c) => c.status === "ok").length,
|
||||
error: filtered.filter((c) => c.status === "error").length,
|
||||
timeout: filtered.filter((c) => c.status === "timeout").length,
|
||||
pending: filtered.filter((c) => c.status === "pending").length,
|
||||
testing: filtered.filter((c) => c.status === "testing").length
|
||||
};
|
||||
|
||||
const sources = Array.from(new Set(cameras.map(c => c.feature.properties.source || "Unknown"))).sort();
|
||||
const sources = Array.from(new Set(cameras.map((c) => c.feature.properties.source || "Unknown"))).sort();
|
||||
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
<div className={styles.header}>
|
||||
<h1>Camera Stream Diagnostics</h1>
|
||||
<p>Run parallel checks on all traffic camera streams to detect compatibility and offline issues.</p>
|
||||
</div>
|
||||
<div className={styles.container}>
|
||||
<div className={styles.header}>
|
||||
<h1>Camera Stream Diagnostics</h1>
|
||||
<p>Run parallel checks on all traffic camera streams to detect compatibility and offline issues.</p>
|
||||
</div>
|
||||
|
||||
<div className={styles.stats}>
|
||||
<div className={styles.statCard}><h3>Total Cameras</h3><p>{stats.total} <span style={{ fontSize: '0.8rem', opacity: 0.7 }}>({dStats.total} shown)</span></p></div>
|
||||
<div className={styles.statCard}><h3>Responsive (OK)</h3><p className={styles.badgeOk} style={{ background: 'none', padding: 0, border: 'none' }}>{stats.ok} <span style={{ fontSize: '0.8rem', opacity: 0.7 }}>({dStats.ok} shown)</span></p></div>
|
||||
<div className={styles.statCard}><h3>Errors / Blocked</h3><p className={styles.badgeError} style={{ background: 'none', padding: 0, border: 'none' }}>{stats.error} <span style={{ fontSize: '0.8rem', opacity: 0.7 }}>({dStats.error} shown)</span></p></div>
|
||||
<div className={styles.statCard}><h3>Timeouts</h3><p className={styles.badgeWarn} style={{ background: 'none', padding: 0, border: 'none' }}>{stats.timeout} <span style={{ fontSize: '0.8rem', opacity: 0.7 }}>({dStats.timeout} shown)</span></p></div>
|
||||
<div className={styles.statCard}><h3>Pending</h3><p className={stats.testing > 0 ? styles.badgeTesting : ''} style={{ background: 'none', padding: 0, border: 'none', color: stats.testing > 0 ? '#60a5fa' : 'inherit' }}>{stats.pending + stats.testing} <span style={{ fontSize: '0.8rem', opacity: 0.7 }}>({dStats.pending + dStats.testing} shown)</span></p></div>
|
||||
</div>
|
||||
<div className={styles.stats}>
|
||||
<div className={styles.statCard}>
|
||||
<h3>Total Cameras</h3>
|
||||
<p>
|
||||
{stats.total}
|
||||
{' '}
|
||||
<span style={{ fontSize: '0.8rem', opacity: 0.7 }}>
|
||||
(
|
||||
{dStats.total}
|
||||
{' '}
|
||||
shown)
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
<div className={styles.statCard}>
|
||||
<h3>Responsive (OK)</h3>
|
||||
<p className={styles.badgeOk} style={{ background: 'none', padding: 0, border: 'none' }}>
|
||||
{stats.ok}
|
||||
{' '}
|
||||
<span style={{ fontSize: '0.8rem', opacity: 0.7 }}>
|
||||
(
|
||||
{dStats.ok}
|
||||
{' '}
|
||||
shown)
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
<div className={styles.statCard}>
|
||||
<h3>Errors / Blocked</h3>
|
||||
<p className={styles.badgeError} style={{ background: 'none', padding: 0, border: 'none' }}>
|
||||
{stats.error}
|
||||
{' '}
|
||||
<span style={{ fontSize: '0.8rem', opacity: 0.7 }}>
|
||||
(
|
||||
{dStats.error}
|
||||
{' '}
|
||||
shown)
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
<div className={styles.statCard}>
|
||||
<h3>Timeouts</h3>
|
||||
<p className={styles.badgeWarn} style={{ background: 'none', padding: 0, border: 'none' }}>
|
||||
{stats.timeout}
|
||||
{' '}
|
||||
<span style={{ fontSize: '0.8rem', opacity: 0.7 }}>
|
||||
(
|
||||
{dStats.timeout}
|
||||
{' '}
|
||||
shown)
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
<div className={styles.statCard}>
|
||||
<h3>Pending</h3>
|
||||
<p
|
||||
className={stats.testing > 0 ? styles.badgeTesting : ''}
|
||||
style={{
|
||||
background: 'none', padding: 0, border: 'none', color: stats.testing > 0 ? '#60a5fa' : 'inherit'
|
||||
}}
|
||||
>
|
||||
{stats.pending + stats.testing}
|
||||
{' '}
|
||||
<span style={{ fontSize: '0.8rem', opacity: 0.7 }}>
|
||||
(
|
||||
{dStats.pending + dStats.testing}
|
||||
{' '}
|
||||
shown)
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={styles.controls} style={{ borderBottom: '1px solid rgba(255,255,255,0.1)', paddingBottom: '1.5rem', marginBottom: '0.5rem', alignItems: 'flex-start' }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
|
||||
<span style={{ fontWeight: 600 }}>Target Tests:</span>
|
||||
<span style={{ fontSize: '0.75rem', opacity: 0.7 }}>Hold Ctrl/Cmd to select multiple</span>
|
||||
</div>
|
||||
<div
|
||||
className={styles.controls}
|
||||
style={{
|
||||
borderBottom: '1px solid rgba(255,255,255,0.1)', paddingBottom: '1.5rem', marginBottom: '0.5rem', alignItems: 'flex-start'
|
||||
}}
|
||||
>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
|
||||
<span style={{ fontWeight: 600 }}>Target Tests:</span>
|
||||
<span style={{ fontSize: '0.75rem', opacity: 0.7 }}>Hold Ctrl/Cmd to select multiple</span>
|
||||
</div>
|
||||
|
||||
<select multiple className={styles.select} style={{ height: '120px' }} value={testSources} onChange={e => handleMultiSelect(e, setTestSources)} disabled={testing}>
|
||||
<option value="all">🌍 All Sources</option>
|
||||
{sources.map(src => (
|
||||
<option key={src as string} value={src as string}>
|
||||
{String(src).toUpperCase()}
|
||||
</option>
|
||||
<select multiple className={styles.select} style={{ height: '120px' }} value={testSources} onChange={(e) => handleMultiSelect(e, setTestSources)} disabled={testing}>
|
||||
<option value="all">🌍 All Sources</option>
|
||||
{sources.map((src) => (
|
||||
<option key={src as string} value={src as string}>
|
||||
{String(src).toUpperCase()}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</select>
|
||||
|
||||
<select multiple className={styles.select} style={{ height: '120px' }} value={testStatuses} onChange={e => handleMultiSelect(e, setTestStatuses)} disabled={testing}>
|
||||
<option value="all">🔍 All Statuses</option>
|
||||
<option value="ok">✅ OK</option>
|
||||
<option value="error">❌ Error</option>
|
||||
<option value="timeout">⏱️ Timeout</option>
|
||||
<option value="pending">⏳ Pending</option>
|
||||
</select>
|
||||
<select multiple className={styles.select} style={{ height: '120px' }} value={testStatuses} onChange={(e) => handleMultiSelect(e, setTestStatuses)} disabled={testing}>
|
||||
<option value="all">🔍 All Statuses</option>
|
||||
<option value="ok">✅ OK</option>
|
||||
<option value="error">❌ Error</option>
|
||||
<option value="timeout">⏱️ Timeout</option>
|
||||
<option value="pending">⏳ Pending</option>
|
||||
</select>
|
||||
|
||||
{loading ? (
|
||||
<button className={styles.button} disabled>
|
||||
<span>Loading Cameras...</span>
|
||||
</button>
|
||||
{loading ? (
|
||||
<button type="button" className={styles.button} disabled>
|
||||
<span>Loading Cameras...</span>
|
||||
</button>
|
||||
) : testing ? (
|
||||
<button className={styles.button} onClick={stopTests} style={{ background: '#ef4444' }}>
|
||||
🛑 Stop Tests
|
||||
</button>
|
||||
<button type="button" className={styles.button} onClick={stopTests} style={{ background: '#ef4444' }}>
|
||||
🛑 Stop Tests
|
||||
</button>
|
||||
) : (
|
||||
<button className={styles.button} onClick={runTests} disabled={cameras.length === 0}>
|
||||
▶ Run Tests
|
||||
</button>
|
||||
<button type="button" className={styles.button} onClick={runTests} disabled={cameras.length === 0}>
|
||||
▶ Run Tests
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={styles.controls} style={{ alignItems: 'flex-start' }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
|
||||
<span style={{ fontWeight: 600 }}>Display View:</span>
|
||||
<span style={{ fontSize: '0.75rem', opacity: 0.7 }}>Hold Ctrl/Cmd to select multiple</span>
|
||||
</div>
|
||||
<div className={styles.controls} style={{ alignItems: 'flex-start' }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
|
||||
<span style={{ fontWeight: 600 }}>Display View:</span>
|
||||
<span style={{ fontSize: '0.75rem', opacity: 0.7 }}>Hold Ctrl/Cmd to select multiple</span>
|
||||
</div>
|
||||
|
||||
<select multiple className={styles.select} style={{ height: '140px' }} value={filterSources} onChange={e => handleMultiSelect(e, setFilterSources)}>
|
||||
<option value="all">🌍 Show All Sources</option>
|
||||
{sources.map(src => (
|
||||
<option key={src as string} value={src as string}>
|
||||
{String(src).toUpperCase()}
|
||||
</option>
|
||||
<select multiple className={styles.select} style={{ height: '140px' }} value={filterSources} onChange={(e) => handleMultiSelect(e, setFilterSources)}>
|
||||
<option value="all">🌍 Show All Sources</option>
|
||||
{sources.map((src) => (
|
||||
<option key={src as string} value={src as string}>
|
||||
{String(src).toUpperCase()}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</select>
|
||||
|
||||
<select multiple className={styles.select} style={{ height: '140px' }} value={filterStatuses} onChange={e => handleMultiSelect(e, setFilterStatuses)}>
|
||||
<option value="all">🔍 Show All Statuses</option>
|
||||
<option value="ok">✅ OK</option>
|
||||
<option value="error">❌ Error</option>
|
||||
<option value="timeout">⏱️ Timeout</option>
|
||||
<option value="pending">⏳ Pending</option>
|
||||
<option value="testing">🔄 Testing</option>
|
||||
</select>
|
||||
<select multiple className={styles.select} style={{ height: '140px' }} value={filterStatuses} onChange={(e) => handleMultiSelect(e, setFilterStatuses)}>
|
||||
<option value="all">🔍 Show All Statuses</option>
|
||||
<option value="ok">✅ OK</option>
|
||||
<option value="error">❌ Error</option>
|
||||
<option value="timeout">⏱️ Timeout</option>
|
||||
<option value="pending">⏳ Pending</option>
|
||||
<option value="testing">🔄 Testing</option>
|
||||
</select>
|
||||
|
||||
<button className={styles.button} style={{ background: 'rgba(255,255,255,0.1)', marginLeft: 'auto' }} onClick={() => {
|
||||
const exportData = cameras.map(c => ({
|
||||
<button
|
||||
type="button"
|
||||
className={styles.button}
|
||||
style={{ background: 'rgba(255,255,255,0.1)', marginLeft: 'auto' }}
|
||||
onClick={() => {
|
||||
const exportData = cameras.map((c) => ({
|
||||
id: c.feature.properties.name,
|
||||
source: c.feature.properties.source,
|
||||
url: c.feature.properties.stream,
|
||||
@@ -139,24 +215,25 @@ export default function CameraTestPage() {
|
||||
a.href = url;
|
||||
a.download = `camera-diagnostics-${new Date().toISOString().split('T')[0]}.json`;
|
||||
a.click();
|
||||
}}>
|
||||
⬇ Export Report
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className={styles.grid}>
|
||||
{filtered.map((c, i) => (
|
||||
<CameraTestCard
|
||||
key={c.feature.properties.stream + i}
|
||||
result={c}
|
||||
index={i}
|
||||
globalIndex={cameras.indexOf(c)}
|
||||
previewId={previewId}
|
||||
onSetPreview={setPreviewId}
|
||||
onRetest={retestCamera}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
}}
|
||||
>
|
||||
⬇ Export Report
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className={styles.grid}>
|
||||
{filtered.map((c, i) => (
|
||||
<CameraTestCard
|
||||
key={c.feature.properties.stream + i}
|
||||
result={c}
|
||||
index={i}
|
||||
globalIndex={cameras.indexOf(c)}
|
||||
previewId={previewId}
|
||||
onSetPreview={setPreviewId}
|
||||
onRetest={retestCamera}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
import { useState, useRef, useEffect, useCallback } from "react";
|
||||
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[]>([]);
|
||||
@@ -13,44 +16,48 @@ export function useCameraTestRunner(testSources: string[], testStatuses: string[
|
||||
const res = await fetch("/api/camera/traffic");
|
||||
const data = await res.json();
|
||||
|
||||
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) {
|
||||
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) {
|
||||
console.error("Failed to fetch static cameras:", staticErr);
|
||||
void staticErr; // Ignore static fetch errors
|
||||
}
|
||||
|
||||
let combinedFeatures: any[] = [];
|
||||
let combinedFeatures: GdotCameraFeature[] = [];
|
||||
if (data.cameras) {
|
||||
combinedFeatures = [...data.cameras];
|
||||
}
|
||||
combinedFeatures = [...combinedFeatures, ...staticFeatures];
|
||||
|
||||
setCameras(combinedFeatures.map((c: any) => ({
|
||||
setCameras(combinedFeatures.map((c: GdotCameraFeature) => ({
|
||||
feature: c,
|
||||
status: "pending"
|
||||
})));
|
||||
} catch (err) {
|
||||
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 () => {
|
||||
@@ -61,7 +68,7 @@ export function useCameraTestRunner(testSources: string[], testStatuses: string[
|
||||
abortControllerRef.current.abort();
|
||||
}
|
||||
abortControllerRef.current = new AbortController();
|
||||
const signal = abortControllerRef.current.signal;
|
||||
const {signal} = abortControllerRef.current;
|
||||
|
||||
const maxConcurrent = 20;
|
||||
let index = 0;
|
||||
@@ -75,10 +82,12 @@ export function useCameraTestRunner(testSources: string[], testStatuses: string[
|
||||
return sourceMatches && statusMatches;
|
||||
});
|
||||
|
||||
setCameras(prev => {
|
||||
setCameras((prev) => {
|
||||
const nextState = [...prev];
|
||||
for (const { originalIndex } of itemsToTest) {
|
||||
nextState[originalIndex] = { ...nextState[originalIndex], status: "pending", testStartTime: undefined, latencyMs: undefined, errorMsg: undefined, httpStatus: undefined, contentType: undefined };
|
||||
nextState[originalIndex] = {
|
||||
...nextState[originalIndex], status: "pending", testStartTime: undefined, latencyMs: undefined, errorMsg: undefined, httpStatus: undefined, contentType: undefined
|
||||
};
|
||||
}
|
||||
return nextState;
|
||||
});
|
||||
@@ -90,15 +99,16 @@ export function useCameraTestRunner(testSources: string[], testStatuses: string[
|
||||
return;
|
||||
}
|
||||
while (active < maxConcurrent && index < itemsToTest.length) {
|
||||
const item = itemsToTest[index++];
|
||||
const item = itemsToTest[index];
|
||||
index += 1;
|
||||
const currentIndex = item.originalIndex;
|
||||
active++;
|
||||
active += 1;
|
||||
|
||||
const cam = item.c;
|
||||
let streamUrl = cam.feature.properties.stream;
|
||||
const streamUrl = cam.feature.properties.stream;
|
||||
|
||||
if (!streamUrl) {
|
||||
setCameras(prev => {
|
||||
setCameras((prev) => {
|
||||
const nextState = [...prev];
|
||||
nextState[currentIndex] = {
|
||||
...nextState[currentIndex],
|
||||
@@ -107,21 +117,21 @@ export function useCameraTestRunner(testSources: string[], testStatuses: string[
|
||||
};
|
||||
return nextState;
|
||||
});
|
||||
active--;
|
||||
active -= 1;
|
||||
next();
|
||||
continue;
|
||||
}
|
||||
|
||||
setCameras(prev => {
|
||||
setCameras((prev) => {
|
||||
const nextState = [...prev];
|
||||
nextState[currentIndex] = { ...nextState[currentIndex], status: "testing", testStartTime: Date.now() };
|
||||
return nextState;
|
||||
});
|
||||
|
||||
fetch(`/api/camera/test?url=${encodeURIComponent(streamUrl)}`, { signal })
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
setCameras(prev => {
|
||||
.then((res) => res.json())
|
||||
.then((data) => {
|
||||
setCameras((prev) => {
|
||||
const nextState = [...prev];
|
||||
const isOk = data.status === 200 || data.status === 204 || data.status === 206;
|
||||
nextState[currentIndex] = {
|
||||
@@ -135,9 +145,9 @@ export function useCameraTestRunner(testSources: string[], testStatuses: string[
|
||||
return nextState;
|
||||
});
|
||||
})
|
||||
.catch(err => {
|
||||
.catch((err) => {
|
||||
if (err.name === 'AbortError') return;
|
||||
setCameras(prev => {
|
||||
setCameras((prev) => {
|
||||
const nextState = [...prev];
|
||||
nextState[currentIndex] = {
|
||||
...nextState[currentIndex],
|
||||
@@ -148,7 +158,7 @@ export function useCameraTestRunner(testSources: string[], testStatuses: string[
|
||||
});
|
||||
})
|
||||
.finally(() => {
|
||||
active--;
|
||||
active -= 1;
|
||||
next();
|
||||
});
|
||||
}
|
||||
@@ -175,16 +185,18 @@ export function useCameraTestRunner(testSources: string[], testStatuses: string[
|
||||
const streamUrl = cam.feature.properties.stream;
|
||||
if (!streamUrl) return;
|
||||
|
||||
setCameras(prev => {
|
||||
setCameras((prev) => {
|
||||
const nextState = [...prev];
|
||||
nextState[globalIndex] = { ...nextState[globalIndex], status: "testing", testStartTime: Date.now(), latencyMs: undefined, errorMsg: undefined, httpStatus: undefined, contentType: undefined };
|
||||
nextState[globalIndex] = {
|
||||
...nextState[globalIndex], status: "testing", testStartTime: Date.now(), latencyMs: undefined, errorMsg: undefined, httpStatus: undefined, contentType: undefined
|
||||
};
|
||||
return nextState;
|
||||
});
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/camera/test?url=${encodeURIComponent(streamUrl)}`);
|
||||
const data = await res.json();
|
||||
setCameras(prev => {
|
||||
setCameras((prev) => {
|
||||
const nextState = [...prev];
|
||||
const isOk = data.status === 200 || data.status === 204 || data.status === 206;
|
||||
nextState[globalIndex] = {
|
||||
@@ -197,18 +209,21 @@ export function useCameraTestRunner(testSources: string[], testStatuses: string[
|
||||
};
|
||||
return nextState;
|
||||
});
|
||||
} catch (err: any) {
|
||||
setCameras(prev => {
|
||||
} 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;
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return { cameras, loading, testing, runTests, stopTests, retestCamera };
|
||||
return {
|
||||
cameras, loading, testing, runTests, stopTests, retestCamera
|
||||
};
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
/**
|
||||
* @file AdUnit.tsx
|
||||
* @description Standardized Google AdSense wrapper component.
|
||||
* @description Standardized Google AdSense wrapper component.
|
||||
* Handles client-side script pushing and provides a development-mode mock UI.
|
||||
* @module src/components/ads
|
||||
*/
|
||||
@@ -19,23 +19,25 @@ interface AdUnitProps {
|
||||
/**
|
||||
* @component AdUnit
|
||||
* @description Renders a Google AdSense advertisement unit.
|
||||
*
|
||||
*
|
||||
* @param {AdUnitProps} props - Component properties.
|
||||
* @param {string} props.adSlot - The AdSense slot ID.
|
||||
* @param {string} [props.adFormat="auto"] - The AdSense format (auto, rectangle, etc).
|
||||
* @param {React.CSSProperties} [props.style] - Optional inline styles for the container.
|
||||
* @param {string} [props.className] - Optional CSS class for the container.
|
||||
*/
|
||||
export function AdUnit({ adSlot, adFormat = "auto", style, className }: AdUnitProps) {
|
||||
export function AdUnit({
|
||||
adSlot, adFormat, style, className
|
||||
}: AdUnitProps) {
|
||||
const insRef = useRef<HTMLModElement>(null);
|
||||
const pushed = useRef(false);
|
||||
const clientId = process.env.NEXT_PUBLIC_ADSENSE_CLIENT_ID;
|
||||
|
||||
useEffect(() => {
|
||||
if (pushed.current || !clientId) return;
|
||||
|
||||
|
||||
// Next.js Dev / CSS injection often causes a brief moment where
|
||||
// the ad container has 0 width. Wait until the browser calculates
|
||||
// the ad container has 0 width. Wait until the browser calculates
|
||||
// the true CSS width before asking AdSense to fetch an ad.
|
||||
const timer = setInterval(() => {
|
||||
if (insRef.current && insRef.current.offsetWidth > 0) {
|
||||
@@ -62,24 +64,39 @@ export function AdUnit({ adSlot, adFormat = "auto", style, className }: AdUnitPr
|
||||
// Google AdSense natively returns 400 Bad Request if requested from localhost.
|
||||
if (process.env.NODE_ENV === "development") {
|
||||
return (
|
||||
<div className={className} style={{ ...style, display: "flex", alignItems: "center", justifyContent: "center", backgroundColor: "rgba(255, 255, 255, 0.05)", color: "#888", fontSize: "12px", border: "1px dashed rgba(255, 255, 255, 0.1)", textAlign: "center", padding: "1rem", minHeight: "250px" }}>
|
||||
<span>AdSense Mock<br/>(Disabled on Localhost)</span>
|
||||
</div>
|
||||
<div
|
||||
className={className}
|
||||
style={{
|
||||
...style, display: "flex", alignItems: "center", justifyContent: "center", backgroundColor: "rgba(255, 255, 255, 0.05)", color: "#888", fontSize: "12px", border: "1px dashed rgba(255, 255, 255, 0.1)", textAlign: "center", padding: "1rem", minHeight: "250px"
|
||||
}}
|
||||
>
|
||||
<span>
|
||||
AdSense Mock
|
||||
<br />
|
||||
(Disabled on Localhost)
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={className} style={style}>
|
||||
<ins
|
||||
ref={insRef}
|
||||
className="adsbygoogle"
|
||||
style={{ display: "block" }}
|
||||
data-ad-client={clientId}
|
||||
data-ad-slot={adSlot}
|
||||
data-ad-format={adFormat}
|
||||
data-full-width-responsive="true"
|
||||
data-adtest="on"
|
||||
/>
|
||||
</div>
|
||||
<div className={className} style={style}>
|
||||
<ins
|
||||
ref={insRef}
|
||||
className="adsbygoogle"
|
||||
style={{ display: "block" }}
|
||||
data-ad-client={clientId}
|
||||
data-ad-slot={adSlot}
|
||||
data-ad-format={adFormat}
|
||||
data-full-width-responsive="true"
|
||||
data-adtest="on"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
AdUnit.defaultProps = {
|
||||
adFormat: "auto",
|
||||
style: {},
|
||||
className: "",
|
||||
};
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
/**
|
||||
* @file DemoAdStrip.tsx
|
||||
* @description specialized sidebar for the demo edition that hosts AdSense
|
||||
* @description specialized sidebar for the demo edition that hosts AdSense
|
||||
* units and a small banner explaining the monetization model.
|
||||
* @module src/components/ads
|
||||
*/
|
||||
@@ -10,8 +10,8 @@
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { isDemo } from "@/core/edition";
|
||||
import { dataBus } from "@/core/data/DataBus";
|
||||
import { AdUnit } from "./AdUnit";
|
||||
import { X } from "lucide-react";
|
||||
import { AdUnit } from "./AdUnit";
|
||||
import "./DemoAdStrip.css";
|
||||
|
||||
/** Ad slot IDs — replace with your AdSense slot IDs. */
|
||||
@@ -68,63 +68,62 @@ export function DemoAdStrip() {
|
||||
if (!isDemo || !ENABLE_ADS) return null;
|
||||
|
||||
return (
|
||||
<aside
|
||||
className="demo-ad-strip"
|
||||
aria-label="Sponsored content"
|
||||
style={{
|
||||
opacity: isReady ? 1 : 0,
|
||||
<aside
|
||||
className="demo-ad-strip"
|
||||
aria-label="Sponsored content"
|
||||
style={{
|
||||
opacity: isReady ? 1 : 0,
|
||||
pointerEvents: isReady ? "auto" : "none",
|
||||
transition: "opacity 1200ms var(--ease-smooth)"
|
||||
transition: "opacity 1200ms var(--ease-smooth)"
|
||||
}}
|
||||
>
|
||||
<AdUnit
|
||||
adSlot={TOP_AD_SLOT}
|
||||
adFormat="auto"
|
||||
className="demo-ad-strip__ad"
|
||||
/>
|
||||
{!isShortScreen && (
|
||||
<AdUnit
|
||||
adSlot={BOTTOM_AD_SLOT}
|
||||
adFormat="auto"
|
||||
className="demo-ad-strip__ad"
|
||||
/>
|
||||
>
|
||||
<AdUnit
|
||||
adSlot={TOP_AD_SLOT}
|
||||
adFormat="auto"
|
||||
className="demo-ad-strip__ad"
|
||||
/>
|
||||
{!isShortScreen && (
|
||||
<AdUnit
|
||||
adSlot={BOTTOM_AD_SLOT}
|
||||
adFormat="auto"
|
||||
className="demo-ad-strip__ad"
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
{!bannerDismissed && (
|
||||
<div
|
||||
className="demo-ad-strip__banner"
|
||||
onClick={() => setShowMessage((prev) => !prev)}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onKeyDown={(e: React.KeyboardEvent<HTMLDivElement>) => {
|
||||
{!bannerDismissed && (
|
||||
<div
|
||||
className="demo-ad-strip__banner"
|
||||
onClick={() => setShowMessage((prev) => !prev)}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onKeyDown={(e: React.KeyboardEvent<HTMLDivElement>) => {
|
||||
if (e.key === "Enter") setShowMessage((prev) => !prev);
|
||||
}}
|
||||
>
|
||||
<button
|
||||
className="demo-ad-strip__close"
|
||||
onClick={(e: React.MouseEvent<HTMLButtonElement>) => {
|
||||
>
|
||||
<button
|
||||
className="demo-ad-strip__close"
|
||||
onClick={(e: React.MouseEvent<HTMLButtonElement>) => {
|
||||
e.stopPropagation();
|
||||
setBannerDismissed(true);
|
||||
}}
|
||||
aria-label="Dismiss banner"
|
||||
>
|
||||
<X size={12} />
|
||||
</button>
|
||||
<span className="demo-ad-strip__banner-label">Why ads?</span>
|
||||
{showMessage ? (
|
||||
<span className="demo-ad-strip__banner-text">
|
||||
This isn't permanent — it's temporary
|
||||
because I'm a single dev and need to cover
|
||||
hosting costs. Thank you for understanding.
|
||||
</span>
|
||||
aria-label="Dismiss banner"
|
||||
>
|
||||
<X size={12} />
|
||||
</button>
|
||||
<span className="demo-ad-strip__banner-label">Why ads?</span>
|
||||
{showMessage ? (
|
||||
<span className="demo-ad-strip__banner-text">
|
||||
This isn't permanent — it's temporary
|
||||
because I'm a single dev and need to cover
|
||||
hosting costs. Thank you for understanding.
|
||||
</span>
|
||||
) : (
|
||||
<span className="demo-ad-strip__banner-text">
|
||||
Click to learn more
|
||||
</span>
|
||||
<span className="demo-ad-strip__banner-text">
|
||||
Click to learn more
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</aside>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -20,23 +20,23 @@ interface BootOverlayProps {
|
||||
/**
|
||||
* @component BootOverlay
|
||||
* @description Animated splash screen for initial system boot.
|
||||
*
|
||||
*
|
||||
* @param {BootOverlayProps} props - Component properties.
|
||||
*/
|
||||
export function BootOverlay({ visible }: BootOverlayProps) {
|
||||
return (
|
||||
<div className={`boot-overlay ${visible ? "" : "boot-overlay--hidden"}`}>
|
||||
{/* Orbital rings */}
|
||||
<div className="boot-overlay__rings">
|
||||
<div className="boot-overlay__ring boot-overlay__ring--1" />
|
||||
<div className="boot-overlay__ring boot-overlay__ring--2" />
|
||||
<div className="boot-overlay__ring boot-overlay__ring--3" />
|
||||
<div className="boot-overlay__core" />
|
||||
</div>
|
||||
|
||||
{/* Brand + status */}
|
||||
<div className="boot-overlay__title">WorldWideView</div>
|
||||
<div className="boot-overlay__status">Initializing Systems...</div>
|
||||
<div className={`boot-overlay ${visible ? "" : "boot-overlay--hidden"}`}>
|
||||
{/* Orbital rings */}
|
||||
<div className="boot-overlay__rings">
|
||||
<div className="boot-overlay__ring boot-overlay__ring--1" />
|
||||
<div className="boot-overlay__ring boot-overlay__ring--2" />
|
||||
<div className="boot-overlay__ring boot-overlay__ring--3" />
|
||||
<div className="boot-overlay__core" />
|
||||
</div>
|
||||
|
||||
{/* Brand + status */}
|
||||
<div className="boot-overlay__title">WorldWideView</div>
|
||||
<div className="boot-overlay__status">Initializing Systems...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -15,22 +15,27 @@ interface DiscordIconProps {
|
||||
|
||||
/**
|
||||
* Renders the Discord logo as an SVG.
|
||||
*
|
||||
*
|
||||
* @param props - Component properties.
|
||||
* @returns React component rendering the Discord icon.
|
||||
*/
|
||||
export function DiscordIcon({ size = 18, className }: DiscordIconProps) {
|
||||
export function DiscordIcon({ size, className }: DiscordIconProps) {
|
||||
return (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill="currentColor"
|
||||
className={className}
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.947 2.418-2.157 2.418z" />
|
||||
</svg>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill="currentColor"
|
||||
className={className}
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.947 2.418-2.157 2.418z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
DiscordIcon.defaultProps = {
|
||||
size: 18,
|
||||
className: "",
|
||||
};
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* @file FeedbackDialog.tsx
|
||||
* @description A comprehensive feedback and bug reporting interface.
|
||||
* Supports categorization, screenshot capture via getDisplayMedia,
|
||||
* Supports categorization, screenshot capture via getDisplayMedia,
|
||||
* file uploads, and automatic diagnostic log attachment.
|
||||
*/
|
||||
|
||||
@@ -9,16 +9,17 @@
|
||||
|
||||
import React, { useState, useEffect, useRef } from "react";
|
||||
import { X, Paperclip, Upload } from "lucide-react";
|
||||
import Image from "next/image";
|
||||
import { useStore } from "@/core/state/store";
|
||||
import { getCapturedLogs } from "@/lib/logCatcher";
|
||||
import styles from "./FeedbackDialog.module.css";
|
||||
import { trackEvent } from "@/lib/analytics";
|
||||
import styles from "./FeedbackDialog.module.css";
|
||||
|
||||
/**
|
||||
* A modal dialog that allows users to submit bug reports, feature requests,
|
||||
* and general feedback. The component captures application state, diagnostic
|
||||
* A modal dialog that allows users to submit bug reports, feature requests,
|
||||
* and general feedback. The component captures application state, diagnostic
|
||||
* logs, and user-provided visuals to facilitate debugging.
|
||||
*
|
||||
*
|
||||
* @returns React component for the feedback portal.
|
||||
*/
|
||||
export function FeedbackDialog() {
|
||||
@@ -30,18 +31,18 @@ export function FeedbackDialog() {
|
||||
const [description, setDescription] = useState("");
|
||||
const [steps, setSteps] = useState("");
|
||||
const [attachLogs, setAttachLogs] = useState(true);
|
||||
const [email, setEmail] = useState("");
|
||||
const [email, setEmail] = useState(() => {
|
||||
if (typeof window !== "undefined") {
|
||||
return localStorage.getItem("wwv_feedback_email") || "";
|
||||
}
|
||||
return "";
|
||||
});
|
||||
const [screenshots, setScreenshots] = useState<string[]>([]);
|
||||
const [takingScreenshot, setTakingScreenshot] = useState(false);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const savedEmail = localStorage.getItem("wwv_feedback_email");
|
||||
if (savedEmail) {
|
||||
setEmail(savedEmail);
|
||||
}
|
||||
}, []);
|
||||
// Initial state set via useState initializer
|
||||
|
||||
const handleEmailChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const newEmail = e.target.value;
|
||||
@@ -53,44 +54,42 @@ export function FeedbackDialog() {
|
||||
const files = Array.from(e.target.files || []);
|
||||
if (files.length === 0) return;
|
||||
|
||||
const readers = files.map(file => {
|
||||
return new Promise<string>((resolve) => {
|
||||
const readers = files.map((file) => new Promise<string>((resolve) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (event) => {
|
||||
resolve((event.target?.result as string) || "");
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
}));
|
||||
|
||||
Promise.all(readers).then((dataUrls) => {
|
||||
setScreenshots((prev) => [...prev, ...dataUrls.filter(Boolean)]);
|
||||
});
|
||||
|
||||
Promise.all(readers).then(dataUrls => {
|
||||
setScreenshots(prev => [...prev, ...dataUrls.filter(Boolean)]);
|
||||
});
|
||||
|
||||
// Reset input
|
||||
e.target.value = "";
|
||||
};
|
||||
|
||||
const handleTakeScreenshot = async () => {
|
||||
setTakingScreenshot(true);
|
||||
|
||||
|
||||
// Wait for React to render the hidden dialog state
|
||||
await new Promise(r => setTimeout(r, 50));
|
||||
await new Promise((r) => { setTimeout(r, 50); });
|
||||
|
||||
try {
|
||||
// @ts-ignore - preferCurrentTab is a recent addition
|
||||
// @ts-expect-error - preferCurrentTab is a recent addition
|
||||
const stream = await navigator.mediaDevices.getDisplayMedia({ video: { preferCurrentTab: true } });
|
||||
const video = document.createElement("video");
|
||||
video.srcObject = stream;
|
||||
video.play();
|
||||
|
||||
|
||||
await new Promise((resolve) => {
|
||||
video.onloadedmetadata = resolve;
|
||||
});
|
||||
|
||||
// Wait 800ms to allow the browser's native "Choose what to share" dialog
|
||||
// Wait 800ms to allow the browser's native "Choose what to share" dialog
|
||||
// to completely finish its fade-out animation from the OS before we capture the frame.
|
||||
await new Promise(r => setTimeout(r, 800));
|
||||
await new Promise((r) => { setTimeout(r, 800); });
|
||||
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = video.videoWidth;
|
||||
@@ -98,10 +97,10 @@ export function FeedbackDialog() {
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (ctx) {
|
||||
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
|
||||
setScreenshots(prev => [...prev, canvas.toDataURL("image/jpeg", 0.9)]);
|
||||
setScreenshots((prev) => [...prev, canvas.toDataURL("image/jpeg", 0.9)]);
|
||||
}
|
||||
|
||||
stream.getTracks().forEach(t => t.stop());
|
||||
|
||||
stream.getTracks().forEach((t) => t.stop());
|
||||
} catch (err) {
|
||||
console.error("Screen capture failed or was cancelled:", err);
|
||||
} finally {
|
||||
@@ -110,7 +109,7 @@ export function FeedbackDialog() {
|
||||
};
|
||||
|
||||
const removeScreenshot = (index: number) => {
|
||||
setScreenshots(prev => prev.filter((_, i) => i !== index));
|
||||
setScreenshots((prev) => prev.filter((_, i) => i !== index));
|
||||
};
|
||||
|
||||
if (!feedbackDialogOpen || takingScreenshot) return null;
|
||||
@@ -119,7 +118,7 @@ export function FeedbackDialog() {
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!isFormValid) return;
|
||||
|
||||
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
const payload = {
|
||||
@@ -134,7 +133,7 @@ export function FeedbackDialog() {
|
||||
};
|
||||
|
||||
const webhookUrl = process.env.NEXT_PUBLIC_FEEDBACK_WEBHOOK_URL || "https://n8n.arfquant.com/webhook/feedback";
|
||||
|
||||
|
||||
const response = await fetch(webhookUrl, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
@@ -162,139 +161,169 @@ export function FeedbackDialog() {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={styles.overlay} onClick={() => setFeedbackDialogOpen(false)}>
|
||||
<div className={styles.dialog} onClick={(e) => e.stopPropagation()}>
|
||||
<div className={styles.header}>
|
||||
<div className={styles.title}>Provide Feedback</div>
|
||||
<button className={styles.closeButton} onClick={() => setFeedbackDialogOpen(false)}>
|
||||
<X size={18} />
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
className={styles.overlay}
|
||||
onClick={() => setFeedbackDialogOpen(false)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
setFeedbackDialogOpen(false);
|
||||
}
|
||||
}}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label="Close dialog"
|
||||
>
|
||||
<div
|
||||
className={styles.dialog}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onKeyDown={(e) => e.stopPropagation()}
|
||||
role="presentation"
|
||||
>
|
||||
<div className={styles.header}>
|
||||
<div className={styles.title}>Provide Feedback</div>
|
||||
<button type="button" className={styles.closeButton} onClick={() => setFeedbackDialogOpen(false)}>
|
||||
<X size={18} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className={styles.content}>
|
||||
<div className={styles.section}>
|
||||
<div className={styles.label}>Feedback Type</div>
|
||||
<div className={styles.radioGroup}>
|
||||
{["Bug Report", "Feature Request", "Auth and Billing", "General Feedback"].map((opt) => (
|
||||
<label key={opt} className={styles.radioOption}>
|
||||
<input
|
||||
type="radio"
|
||||
name="feedbackType"
|
||||
value={opt}
|
||||
checked={type === opt}
|
||||
onChange={(e) => setType(e.target.value)}
|
||||
className={styles.radioInput}
|
||||
/>
|
||||
<span className={styles.radioLabel}>{opt}</span>
|
||||
</label>
|
||||
<div className={styles.content}>
|
||||
<div className={styles.section}>
|
||||
<div className={styles.label}>Feedback Type</div>
|
||||
<div className={styles.radioGroup}>
|
||||
{["Bug Report", "Feature Request", "Auth and Billing", "General Feedback"].map((opt) => (
|
||||
<label key={opt} className={styles.radioOption}>
|
||||
<input
|
||||
type="radio"
|
||||
name="feedbackType"
|
||||
value={opt}
|
||||
checked={type === opt}
|
||||
onChange={(e) => setType(e.target.value)}
|
||||
className={styles.radioInput}
|
||||
/>
|
||||
<span className={styles.radioLabel}>{opt}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={styles.section}>
|
||||
<div className={styles.label}>Description</div>
|
||||
<div className={styles.description}>
|
||||
Please describe the issue in detail. The more actionable your feedback, the quicker our team can address your request. Some helpful information includes:
|
||||
<ul className={styles.descriptionList}>
|
||||
<li>Steps to reproduce the issue</li>
|
||||
<li>Expected behavior</li>
|
||||
<li>Actual behavior</li>
|
||||
<li>Any error messages</li>
|
||||
<li>Any relevant information</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div className={styles.textareaContainer}>
|
||||
<textarea
|
||||
className={styles.textarea}
|
||||
placeholder="Describe the bug you encountered..."
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
/>
|
||||
<div className={`${styles.charCount} ${isFormValid ? styles.valid : ""}`}>
|
||||
{description.length}/50
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles.section}>
|
||||
<div className={styles.label}>Description</div>
|
||||
<div className={styles.description}>
|
||||
Please describe the issue in detail. The more actionable your feedback, the quicker our team can address your request. Some helpful information includes:
|
||||
<ul className={styles.descriptionList}>
|
||||
<li>Steps to reproduce the issue</li>
|
||||
<li>Expected behavior</li>
|
||||
<li>Actual behavior</li>
|
||||
<li>Any error messages</li>
|
||||
<li>Any relevant information</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div className={styles.textareaContainer}>
|
||||
<textarea
|
||||
className={styles.textarea}
|
||||
placeholder="Describe the bug you encountered..."
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
/>
|
||||
<div className={`${styles.charCount} ${isFormValid ? styles.valid : ""}`}>
|
||||
{description.length}
|
||||
/50
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={styles.section}>
|
||||
<div className={styles.label}>Steps to Reproduce</div>
|
||||
<div className={styles.textareaContainer}>
|
||||
<textarea
|
||||
className={styles.textarea}
|
||||
placeholder="Please list the steps to reproduce the issue"
|
||||
value={steps}
|
||||
onChange={(e) => setSteps(e.target.value)}
|
||||
style={{ minHeight: "80px" }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles.section}>
|
||||
<div className={styles.label}>Steps to Reproduce</div>
|
||||
<div className={styles.textareaContainer}>
|
||||
<textarea
|
||||
className={styles.textarea}
|
||||
placeholder="Please list the steps to reproduce the issue"
|
||||
value={steps}
|
||||
onChange={(e) => setSteps(e.target.value)}
|
||||
style={{ minHeight: "80px" }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={styles.checkboxGroup}>
|
||||
{screenshots.length > 0 && (
|
||||
<div className={styles.previewList}>
|
||||
{screenshots.map((src, i) => (
|
||||
<div key={i} className={styles.previewContainer}>
|
||||
<img src={src} alt={`Screenshot ${i + 1}`} className={styles.previewImage} />
|
||||
<button className={styles.removeScreenshot} onClick={() => removeScreenshot(i)} title="Remove screenshot">
|
||||
<X size={10} strokeWidth={3} />
|
||||
</button>
|
||||
</div>
|
||||
<div className={styles.checkboxGroup}>
|
||||
{screenshots.length > 0 && (
|
||||
<div className={styles.previewList}>
|
||||
{screenshots.map((src, i) => (
|
||||
<div key={i} className={styles.previewContainer}>
|
||||
<Image
|
||||
src={src}
|
||||
alt={`Screenshot ${i + 1}`}
|
||||
className={styles.previewImage}
|
||||
width={100}
|
||||
height={60}
|
||||
unoptimized
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.removeScreenshot}
|
||||
onClick={() => removeScreenshot(i)}
|
||||
title="Remove screenshot"
|
||||
>
|
||||
<X size={10} strokeWidth={3} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={styles.actionRow}>
|
||||
<button className={styles.attachAction} onClick={handleTakeScreenshot}>
|
||||
<Paperclip size={16} />
|
||||
<span>Take screenshot</span>
|
||||
</button>
|
||||
<button className={styles.attachAction} onClick={() => fileInputRef.current?.click()}>
|
||||
<Upload size={16} />
|
||||
<span>Upload image</span>
|
||||
</button>
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
ref={fileInputRef}
|
||||
style={{ display: "none" }}
|
||||
onChange={handleFileUpload}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.actionRow}>
|
||||
<button type="button" className={styles.attachAction} onClick={handleTakeScreenshot}>
|
||||
<Paperclip size={16} />
|
||||
<span>Take screenshot</span>
|
||||
</button>
|
||||
<button type="button" className={styles.attachAction} onClick={() => fileInputRef.current?.click()}>
|
||||
<Upload size={16} />
|
||||
<span>Upload image</span>
|
||||
</button>
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
ref={fileInputRef}
|
||||
style={{ display: "none" }}
|
||||
onChange={handleFileUpload}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<label className={styles.checkboxOption}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={attachLogs}
|
||||
onChange={(e) => setAttachLogs(e.target.checked)}
|
||||
className={styles.checkboxInput}
|
||||
/>
|
||||
<span className={styles.checkboxLabel}>Attach WorldWideView diagnostic logs and information</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className={styles.section}>
|
||||
<div className={styles.label}>Email Address</div>
|
||||
<input
|
||||
type="email"
|
||||
className={styles.input}
|
||||
placeholder="[email protected]"
|
||||
value={email}
|
||||
onChange={handleEmailChange}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={styles.footer}>
|
||||
<button
|
||||
className={`${styles.submitButton} ${isSubmitting ? styles.submitting : ""} ${isFormValid ? styles.enabled : ""}`}
|
||||
onClick={handleSubmit}
|
||||
disabled={isSubmitting || !isFormValid}
|
||||
>
|
||||
{isSubmitting ? "Submitting..." : "Submit"}
|
||||
</button>
|
||||
</div>
|
||||
<label className={styles.checkboxOption}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={attachLogs}
|
||||
onChange={(e) => setAttachLogs(e.target.checked)}
|
||||
className={styles.checkboxInput}
|
||||
/>
|
||||
<span className={styles.checkboxLabel}>Attach WorldWideView diagnostic logs and information</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className={styles.section}>
|
||||
<div className={styles.label}>Email Address</div>
|
||||
<input
|
||||
type="email"
|
||||
className={styles.input}
|
||||
placeholder="[email protected]"
|
||||
value={email}
|
||||
onChange={handleEmailChange}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={styles.footer}>
|
||||
<button
|
||||
type="button"
|
||||
className={`${styles.submitButton} ${isSubmitting ? styles.submitting : ""} ${isFormValid ? styles.enabled : ""} `}
|
||||
onClick={handleSubmit}
|
||||
disabled={isSubmitting || !isFormValid}
|
||||
>
|
||||
{isSubmitting ? "Submitting..." : "Submit"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -7,7 +7,9 @@
|
||||
|
||||
"use client";
|
||||
|
||||
import React, { useState, useEffect, useRef, useCallback } from "react";
|
||||
import React, {
|
||||
useState, useEffect, useRef, useCallback
|
||||
} from "react";
|
||||
import { X } from "lucide-react";
|
||||
|
||||
/**
|
||||
@@ -38,7 +40,7 @@ interface FloatingWindowProps {
|
||||
* @component FloatingWindow
|
||||
* @description A floating, interactive container used for data streams and secondary tools.
|
||||
* Implements a custom drag-and-resize engine compatible with both desktop and mobile.
|
||||
*
|
||||
*
|
||||
* @param {FloatingWindowProps} props - Component properties.
|
||||
*/
|
||||
export const FloatingWindow: React.FC<FloatingWindowProps> = ({
|
||||
@@ -85,7 +87,7 @@ export const FloatingWindow: React.FC<FloatingWindowProps> = ({
|
||||
} else if (isResizing) {
|
||||
const deltaX = e.clientX - dragStart.current.x;
|
||||
const deltaY = e.clientY - dragStart.current.y;
|
||||
setSize(prev => ({
|
||||
setSize((prev) => ({
|
||||
width: Math.max(minWidth, prev.width + deltaX),
|
||||
height: Math.max(minHeight, prev.height + deltaY),
|
||||
}));
|
||||
@@ -138,7 +140,7 @@ export const FloatingWindow: React.FC<FloatingWindowProps> = ({
|
||||
} else if (isResizing) {
|
||||
const deltaX = touch.clientX - dragStart.current.x;
|
||||
const deltaY = touch.clientY - dragStart.current.y;
|
||||
setSize(prev => ({
|
||||
setSize((prev) => ({
|
||||
width: Math.max(minWidth, prev.width + deltaX),
|
||||
height: Math.max(minHeight, prev.height + deltaY),
|
||||
}));
|
||||
@@ -170,9 +172,9 @@ export const FloatingWindow: React.FC<FloatingWindowProps> = ({
|
||||
}, [isDragging, isResizing, handleTouchMove, handleTouchEnd]);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={windowRef}
|
||||
style={{
|
||||
<div
|
||||
ref={windowRef}
|
||||
style={{
|
||||
position: "fixed",
|
||||
left: pos.x,
|
||||
top: pos.y,
|
||||
@@ -190,10 +192,10 @@ export const FloatingWindow: React.FC<FloatingWindowProps> = ({
|
||||
color: "white",
|
||||
touchAction: "none", // prevent browser gestures on the window itself
|
||||
}}
|
||||
>
|
||||
{/* Header / Title Bar */}
|
||||
<div
|
||||
style={{
|
||||
>
|
||||
{/* Header / Title Bar */}
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
@@ -204,17 +206,20 @@ export const FloatingWindow: React.FC<FloatingWindowProps> = ({
|
||||
userSelect: "none",
|
||||
touchAction: "none",
|
||||
}}
|
||||
onMouseDown={handleMouseDown}
|
||||
onTouchStart={handleTouchStartDrag}
|
||||
>
|
||||
<span style={{ fontSize: "12px", fontWeight: 600, color: "rgba(255, 255, 255, 0.8)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
|
||||
{title}
|
||||
</span>
|
||||
onMouseDown={handleMouseDown}
|
||||
onTouchStart={handleTouchStartDrag}
|
||||
>
|
||||
<span style={{
|
||||
fontSize: "12px", fontWeight: 600, color: "rgba(255, 255, 255, 0.8)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap"
|
||||
}}
|
||||
>
|
||||
{title}
|
||||
</span>
|
||||
|
||||
<div className="window-controls" style={{ display: "flex", gap: "8px" }}>
|
||||
<button
|
||||
onClick={onClose}
|
||||
style={{
|
||||
<div className="window-controls" style={{ display: "flex", gap: "8px" }}>
|
||||
<button
|
||||
onClick={onClose}
|
||||
style={{
|
||||
background: "none",
|
||||
border: "none",
|
||||
color: "rgba(255, 255, 255, 0.4)",
|
||||
@@ -226,28 +231,28 @@ export const FloatingWindow: React.FC<FloatingWindowProps> = ({
|
||||
borderRadius: "4px",
|
||||
transition: "all 0.2s"
|
||||
}}
|
||||
onMouseEnter={(e) => {
|
||||
onMouseEnter={(e) => {
|
||||
e.currentTarget.style.color = "#ef4444";
|
||||
e.currentTarget.style.backgroundColor = "rgba(239, 68, 68, 0.1)";
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
onMouseLeave={(e) => {
|
||||
e.currentTarget.style.color = "rgba(255, 255, 255, 0.4)";
|
||||
e.currentTarget.style.backgroundColor = "transparent";
|
||||
}}
|
||||
>
|
||||
<X size={14} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
>
|
||||
<X size={14} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content Area */}
|
||||
<div style={{ flex: 1, position: "relative", overflow: "hidden" }}>
|
||||
{children}
|
||||
</div>
|
||||
{/* Content Area */}
|
||||
<div style={{ flex: 1, position: "relative", overflow: "hidden" }}>
|
||||
{children}
|
||||
</div>
|
||||
|
||||
{/* Resize Handle */}
|
||||
<div
|
||||
style={{
|
||||
{/* Resize Handle */}
|
||||
<div
|
||||
style={{
|
||||
position: "absolute",
|
||||
bottom: 0,
|
||||
right: 0,
|
||||
@@ -261,11 +266,14 @@ export const FloatingWindow: React.FC<FloatingWindowProps> = ({
|
||||
padding: "4px",
|
||||
touchAction: "none",
|
||||
}}
|
||||
onMouseDown={handleResizeMouseDown}
|
||||
onTouchStart={handleTouchStartResize}
|
||||
>
|
||||
<div style={{ width: "6px", height: "6px", backgroundColor: "rgba(255, 255, 255, 0.3)", borderRadius: "1px" }} />
|
||||
</div>
|
||||
onMouseDown={handleResizeMouseDown}
|
||||
onTouchStart={handleTouchStartResize}
|
||||
>
|
||||
<div style={{
|
||||
width: "6px", height: "6px", backgroundColor: "rgba(255, 255, 255, 0.3)", borderRadius: "1px"
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
Loaded 100 of 293 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user