Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5ef7335574 | ||
|
|
628394f572 | ||
|
|
04beadc0e2 | ||
|
|
cf67c5d96f | ||
|
|
e6c7dcf295 |
No files matched your search
@@ -253,6 +253,7 @@ The production Coolify instance runs on a local server at `192.168.68.64`. Direc
|
||||
- **The "Rollback DDOS" Risk:** If you update environmental variables (like a new Upstash Redis URL) inside Coolify and deploy *without* pushing your local optimized code to GitHub, Coolify will pull the *older, unoptimized* repository code and aim it at your new endpoints. This will immediately exhaust the 500,000 requests/month Upstash free limit.
|
||||
- **Redis Connection Errors:** If the data engine crashes on startup with `MaxRetriesPerRequestError: Reached the max retries per request limit (which is 3)` and `ECONNRESET`, the `REDIS_URL` in your Coolify environment variables is incorrectly using `redis://` instead of the TLS-required `rediss://`.
|
||||
- **Immediate Rollback on Failure:** Whenever a Coolify deployment fails or introduces a critical bug (such as rate-limit exhaustion), **immediately select the last known working deployment in the Coolify dashboard and redeploy it.** Do not leave a broken deployment hanging while trying to debug directly in production. Roll back to stability first, debug locally, commit the verified fix, and then deploy forward.
|
||||
- **Public Port Binding:** Both the `wwv` (Next.js frontend) and `wwv-data-engine` containers are meant to be directly exposed to the internet, rather than relying on Traefik internal network routing. They MUST use `ports: - "3000:3000"` and `ports: - "5000:5000"` respectively in `docker-compose.yml`. Using `expose` hides them behind internal Docker routing. Only backend infrastructure like `db` and `wwv-redis` should use `expose`.
|
||||
|
||||
**Local verification:**
|
||||
Before pushing infrastructure changes, run `docker build -t wwv-test .` to verify that the Next.js `standalone` isolated multi-stage build works correctly.
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
---
|
||||
name: architectural-decision-records
|
||||
description: Use when making significant architectural decisions, adding new patterns, or altering core workflows. This skill ensures that all major technical choices are documented via ADRs.
|
||||
---
|
||||
|
||||
# Architectural Decision Records (ADRs)
|
||||
|
||||
## When to use this skill
|
||||
Trigger this skill whenever you are about to introduce a new architectural pattern, make a load-bearing contract change, or bypass an established standard for a necessary reason.
|
||||
|
||||
## Guidelines
|
||||
1. **Never make a major architectural change without an ADR**.
|
||||
2. Store ADRs in `docs/architecture/decisions/` (create this directory if it doesn't exist).
|
||||
3. An ADR must follow this exact structure:
|
||||
- **Title**: Short, descriptive noun phrase.
|
||||
- **Context**: What is the problem we are solving? What forces are at play? (Be objective).
|
||||
- **Decision**: What is the specific change or pattern we are adopting?
|
||||
- **Consequences**: What becomes easier because of this change? What becomes harder? (There are always trade-offs).
|
||||
|
||||
## Actionable Steps
|
||||
When tasked with a major architecture change, pause and explicitly state: *"This requires an Architectural Decision Record."* Draft the ADR and ask the user to approve the reasoning *before* writing the implementation code.
|
||||
@@ -0,0 +1,32 @@
|
||||
---
|
||||
name: typescript-docs
|
||||
description: Use when writing new TypeScript code or refactoring existing code to ensure strict TSDoc/JSDoc hygiene is applied to all methods and interfaces.
|
||||
---
|
||||
|
||||
# Strict TypeScript Documentation
|
||||
|
||||
## When to use this skill
|
||||
Trigger this skill automatically whenever you are creating a new function, class, or interface, OR when you are modifying an existing undocumented function. This is the "Nutrition Label" rule.
|
||||
|
||||
## Guidelines
|
||||
1. **JSDoc/TSDoc format is mandatory**. Always use `/** ... */` above the definition.
|
||||
2. The block MUST include a short, plain-English description of *what* the function does and *why* it exists.
|
||||
3. MUST explicitly list all parameters using `@param name - Description`.
|
||||
4. MUST explicitly define the return value using `@returns Description`.
|
||||
5. If the function intentionally throws an error, use `@throws {ErrorType} Description`.
|
||||
|
||||
## Example
|
||||
```ts
|
||||
/**
|
||||
* Resolves the appropriate WebSocket engine URL for a given plugin.
|
||||
* Prioritizes the local engine during development before falling back to cloud.
|
||||
*
|
||||
* @param pluginId - The unique string identifier of the plugin.
|
||||
* @returns The fully qualified WebSocket URL for the stream.
|
||||
* @throws {Error} If the plugin ID is undefined or missing.
|
||||
*/
|
||||
export function resolveEngineUrl(pluginId: string): string { ... }
|
||||
```
|
||||
|
||||
## Actionable Steps
|
||||
Never consider a PR or code edit "done" unless the new or modified functions have these strict labels attached. If you spot an undocumented function nearby while working, clean it up!
|
||||
@@ -0,0 +1,17 @@
|
||||
# TSDoc Review Log
|
||||
|
||||
This document tracks the progress of the codebase-wide TSDoc update.
|
||||
|
||||
## Ambiguous Functions Requiring 3.1 Pro Review
|
||||
If a function's purpose cannot be deduced from its signature or body, it is listed here along with its file path and the specific confusion.
|
||||
|
||||
| File Path | Function/Interface Name | Reason for Ambiguity |
|
||||
| :--- | :--- | :--- |
|
||||
<!-- Flash: Append rows here as you work -->
|
||||
|
||||
## Completed Directories
|
||||
- [/] `src/core/plugins` (In Progress: PluginRegistry.ts documented)
|
||||
- [ ] `src/core/state`
|
||||
- [x] `src/components` (Completed: Layout, Panels, Marketplace, Timeline, UI)
|
||||
- [x] `packages/wwv-plugin-sdk`
|
||||
- [x] `scripts`
|
||||
@@ -278,3 +278,284 @@ Refer to these skill documents for specialized tasks:
|
||||
- **Cesium Entity Clipping**: If `billboard` entities are clipping or failing to render correctly, verify that you are not mixing `point` primitive properties (like `size` or `outlineWidth`) into the `billboard` options.
|
||||
- **Build Exhaustion (Docker)**: Multi-stage pnpm builds generate massive cache layers. If a Coolify deployment fails silently or PostgreSQL crashes abruptly, check host disk space and run `docker builder prune -a -f`.
|
||||
- **Next.js Typechecking Failures**: If backend-only `scripts/` fail during Next.js build, verify that the scripts directory is properly listed in the `exclude` array of `tsconfig.json`.
|
||||
|
||||
## 17. Coding Principles
|
||||
|
||||
You are about to write or modify code. **Read this file first.** It exists to prevent the failure mode where every fix makes the next harder — the kind of accumulated coupling and band-aid-on-band-aid that turns a clean codebase into a fragile one over months. This file is the constitution that keeps that from happening.
|
||||
|
||||
### The hard rule
|
||||
|
||||
> **Always interface-based, extensible, composable, modular. Never band-aids on band-aids.**
|
||||
|
||||
If you find yourself adding a flag, an `if`-check, or a special case to make a problem go away, you are probably band-aiding. Stop and find the seam where the abstraction broke. Fix it there.
|
||||
|
||||
### Core principles
|
||||
|
||||
#### 1. Interfaces before implementations
|
||||
|
||||
Define the contract first. The contract is what other components depend on; the implementation is replaceable. Public functions accept the interface, not the concrete type.
|
||||
|
||||
```ts
|
||||
// Yes
|
||||
function attachSource(source: DataSource) { ... }
|
||||
|
||||
// No
|
||||
function attachPostgresSource(pg: PostgresInstance) { ... }
|
||||
```
|
||||
|
||||
When a pattern repeats across two modules, refactor it into an interface immediately. Don't wait for the third copy to "earn" the abstraction — by then the costs have compounded.
|
||||
|
||||
#### 2. Loose coupling through explicit contracts
|
||||
|
||||
Components communicate through well-defined contracts: typed function signatures, events on a bus, message queues, or capability registries. Pick the form that fits, but pick *one* and make it the only path.
|
||||
|
||||
Components do **not** communicate through:
|
||||
|
||||
- Direct imports of each other's internal modules
|
||||
- Shared mutable state outside the contract
|
||||
- Synchronous request/response when async fits the actual data flow
|
||||
- "Just this once" backdoors that bypass the contract
|
||||
|
||||
If you're tempted to write `import { internalThing } from '../other-module/internal'`, you are doing it wrong. If the symbol you need isn't part of the other module's public contract, either it should be — propose adding it — or you're solving the problem in the wrong place.
|
||||
|
||||
#### 3. Domain boundaries are sacred
|
||||
|
||||
Each domain (module, service, bounded context, plugin) owns its own state and its own surface. Cross-domain access is **explicit, gated, and audited** — never a shortcut.
|
||||
|
||||
Forbidden:
|
||||
- Reading another domain's storage directly
|
||||
- Calling another domain's private functions
|
||||
- Hardcoded `if (tenant === 'X')` or `if (mode === 'special')` branches in shared code
|
||||
|
||||
Allowed:
|
||||
- A documented capability or API on the other domain that you call
|
||||
- A configuration field on the relevant record that drives the strategy
|
||||
- Cross-domain access gated by explicit policy (default **deny**, opt-in per case), with the access itself logged
|
||||
|
||||
The rule of thumb: if removing a domain would require code archaeology in three other domains to figure out what depends on its internals, the boundary has already been violated. Treat that as a bug.
|
||||
|
||||
#### 4. Don't bend your architecture to fit a dependency
|
||||
|
||||
When you bring in a library or framework, use it where it fits cleanly; build natively where it doesn't.
|
||||
|
||||
Let the dependency handle (don't reinvent):
|
||||
- The thing it's specifically good at, in the shape it expects
|
||||
|
||||
Your code owns (the dependency can't represent):
|
||||
- Anything that's specifically your domain
|
||||
- Anything that requires identity, lifecycle, or invariants the dependency doesn't model
|
||||
- The integration seams between the dependency and your domain
|
||||
|
||||
If you find yourself bending your design to fit a library convenience, stop. Either the library has a hook for what you need, or you build it natively. Don't compromise architecture for the convenience of pulling in someone else's defaults.
|
||||
|
||||
#### 5. Data lifetimes are deliberate, not incidental
|
||||
|
||||
Different data has different lifetimes. Get this wrong and you'll either retain garbage forever or delete things users care about. Common categories:
|
||||
|
||||
- **Operational telemetry** (logs, metrics, internal events) — short rolling window. Useful for crash recovery and immediate investigation; not useful enough to keep forever.
|
||||
- **User content** (messages, documents, records the user created or that represent their lived experience with the system) — **permanent unless the user explicitly deletes it.** Never pruned by a sweep, never deleted by a retention policy authored for telemetry.
|
||||
- **Resumable session state** — bounded window appropriate to the use case; archived (state flag flipped) rather than deleted.
|
||||
|
||||
Name each category in your codebase. Write the retention policy for each one separately. Never propose a sweep that crosses categories — "delete events older than 30 days" is fine if events are telemetry; the same policy applied to user content is data loss masquerading as housekeeping. If storage pressure ever becomes real for content, introduce cold-tiered storage, not deletion.
|
||||
|
||||
#### 6. Optional features must be truly removable
|
||||
|
||||
Every optional feature (plugin, extension, integration, side module) declares its surface explicitly and communicates through the same contracts as everything else. No optional feature reaches into another's internals.
|
||||
|
||||
Test for whether something is core vs. optional: **if removing this feature should break the system, it's core. Otherwise it's optional, and it should be removable without leaving residue.**
|
||||
|
||||
If you can't delete an "optional" module's directory and have the system keep running, it isn't optional. Either fix the coupling or move it into core honestly.
|
||||
|
||||
#### 7. Put code where it belongs
|
||||
|
||||
When a feature spans layers (a trigger lives here, the action lives there, the data model lives somewhere else), resist the urge to fold it all into one place "for convenience." The feature lives in three places because each piece belongs to a different domain. Routing across them is the job — not collapsing them.
|
||||
|
||||
The general rule: if a feature needs to read/write durable state, it's a tool/extension on top of the layer that owns that state; if it's "the system should know about this concept," it's a configuration or contract change. Often it's both, with a thin handler that wires them together. That thin handler is fine — it's load-bearing — but it doesn't justify smashing the layers together.
|
||||
|
||||
### Antipatterns to refuse
|
||||
|
||||
These are common failure modes that, repeated over time, calcify a codebase. Refuse them when you catch yourself reaching for them.
|
||||
|
||||
| Antipattern | Better answer |
|
||||
|---|---|
|
||||
| Adding a new flag to an existing function instead of extracting a strategy | Extract the strategy interface; existing call sites pass the default strategy |
|
||||
| Patching around a bug at the call site | Find the seam where the abstraction broke; fix it there |
|
||||
| Direct database access from a feature module | Go through the layer that owns the data; if no surface exists, propose one |
|
||||
| Hardcoded paths, model names, IDs, environment specifics in business logic | Configuration; or look up via registry |
|
||||
| `if (tenant === 'X') { ... }` in shared code | Strategy on the record, or a per-tenant config field |
|
||||
| Inheriting one layer's concerns into another (or vice versa) | Cross the boundary through the documented contract |
|
||||
| "It works for now" — inline coupling between layers | If the layers are real, draw the contract; if they're not, merge them honestly |
|
||||
| Adding a defensive `try/catch` to swallow an error | Find why the error happens; gate cleanly at the right boundary |
|
||||
| Writing a comment to explain what code does | Rename and refactor so the code reads itself |
|
||||
| Copying a snippet from one module into another "to avoid the dependency" | Either it belongs in a shared module, or the duplicate will drift — pick |
|
||||
|
||||
### Debugging discipline
|
||||
|
||||
When something breaks:
|
||||
|
||||
1. **Reproduce it.** Don't trust intuition about what's failing.
|
||||
2. **Find the seam.** Where did the abstraction break? Which contract is being violated, and by whom?
|
||||
3. **Fix at the seam.** Not at the call site. Not at the consumer. At the boundary that's wrong.
|
||||
4. **If you can't find the seam, surface it.** Tell the user explicitly: "this is a design gap; the right fix needs an architectural decision, not a patch." Do not paper over.
|
||||
|
||||
If a fix doesn't work, **don't add another guard on top.** Find the real seam and gate cleanly. Stacked defensive layers are how clean codebases become unmaintainable.
|
||||
|
||||
### Lifecycle invariants and state-changing operations
|
||||
|
||||
Most recurring bugs cluster around the same shape: an operation crosses lifecycle state without checking, and the result is silent corruption, lost data, or orphan rows. The recipe that prevents recurrences:
|
||||
|
||||
1. **Name the invariant.** "Closed sessions don't accept work." "Scoped grants need a scope id." "Subscriptions past retention can't deliver swept events." Write it down before reaching for code.
|
||||
2. **Throw a typed error at the seam.** The single function that crosses the invariant refuses the bad case with a typed, named error — not a boolean return, not a silent skip, not a generic `Error`.
|
||||
3. **Pre-check at every call site that mutates *before* reaching the seam.** If the seam check fires after `store.append()`, you've left an orphan row. The pre-check is hygiene; the seam check is correctness — both are required. When the same pre-check appears at a second call site, extract a helper.
|
||||
4. **Validate, then mutate — never the reverse.** Within a single function, resolve all inputs that could fail (key derivation, lookups, permission checks) before touching durable state. A validation throw should leave nothing half-applied. If you can't separate validation from mutation, the function is doing two jobs.
|
||||
5. **A documented unsafe API is still unsafe.** A docstring that says "don't use this when X" is a foot-gun, not a warranty disclaimer. Either make the API safe in case X (drain, throw, refuse) or remove it.
|
||||
|
||||
If you're tempted to skip step 3 because "the seam check covers it," check whether the call site writes anything before reaching the seam. If yes, you need the pre-check.
|
||||
|
||||
### Definition of done — checklist for adding or updating a function
|
||||
|
||||
Every code change must satisfy the relevant checklist before merge. Refusal triggers below mean **stop and surface to the user** — do not ship a half-met checklist.
|
||||
|
||||
#### Adding a new function
|
||||
|
||||
All must be true:
|
||||
|
||||
- [ ] Belongs in this module (not somewhere else)
|
||||
- [ ] Fulfills an existing interface, OR a new interface is added with it (and reasons documented in a spec doc / ADR)
|
||||
- [ ] Has a doc-comment header (purpose + params + returns + thrown errors if relevant)
|
||||
- [ ] Has at least one test that targets the contract (not implementation details)
|
||||
- [ ] Test passes locally and in CI
|
||||
- [ ] Doesn't introduce direct cross-module imports of internals — communication through public contracts only
|
||||
- [ ] Doesn't touch storage owned by another component — route through that component's surface
|
||||
- [ ] Matches the spec doc's contract for this component (if no spec covers it, update the spec first)
|
||||
- [ ] Name is clear enough that the header comment is a summary, not an explanation
|
||||
|
||||
#### Updating an existing function
|
||||
|
||||
All must be true:
|
||||
|
||||
- [ ] Reason for change is clear (bug fix / new requirement / refactor / spec change)
|
||||
- [ ] Doc-comment still accurate after change (update if not)
|
||||
- [ ] Existing tests cover the new behavior (add new tests if not)
|
||||
- [ ] Build is green (all tests passing)
|
||||
- [ ] If this changes the contract: spec doc updated AND an ADR added if the change is load-bearing
|
||||
- [ ] Fix is at the seam, not at the symptom (no band-aid patches)
|
||||
- [ ] No new flags or special cases added in lieu of strategy extraction
|
||||
|
||||
#### Refusal triggers (any one means stop)
|
||||
|
||||
- Adding `if (tenant === 'X')` to shared code → use per-tenant config instead
|
||||
- Adding a flag to make a problem go away → extract the abstraction the flag implies
|
||||
- Direct DB or filesystem access from a feature module → route through the owning component
|
||||
- `try`/`catch` swallowing an error → find why the error happens, gate cleanly
|
||||
- Test omitted because "it's trivial" → no
|
||||
- Function-header skipped because "it's obvious" → no
|
||||
- "Just add another guard here" when a guard didn't work → find the real seam
|
||||
- Patch shipped to "unblock the build" without root-cause fix → no, surface the design gap
|
||||
|
||||
If any criterion isn't met, stop. Surface to the user as a design question. Don't paper over.
|
||||
|
||||
### Code-style minimums
|
||||
|
||||
#### Comments
|
||||
|
||||
**Every function gets a doc-comment header** in your language's idiomatic format (TSDoc, JSDoc, Python docstrings, Rust `///`, Javadoc, etc.). Not optional. Long-running codebases get re-read after gaps; function-header docs are how re-onboarding stays cheap.
|
||||
|
||||
Required content:
|
||||
|
||||
- One-line summary at a contract level (what the function guarantees, not what the code does line-by-line)
|
||||
- Each parameter and what it represents
|
||||
- Return value
|
||||
- Thrown errors / failure conditions if relevant
|
||||
- Example usage when the call shape is non-obvious
|
||||
|
||||
Apply this to public, internal, exported, and private functions. Apply to methods on classes too.
|
||||
|
||||
**Inline comments inside function bodies** still follow the standard rule: only for non-obvious WHY (hidden constraints, workarounds, surprising behavior, references to bug reports). Don't comment WHAT the code does — well-named identifiers and the function-header doc cover that.
|
||||
|
||||
#### Tests
|
||||
|
||||
**Every function ships with at least one test. Tests passing is a build requirement.**
|
||||
|
||||
- Tests target the contract (function signature + documented behavior + invariants), not implementation details. Refactoring should not break tests; behavior changes should.
|
||||
- A new implementation of an interface must pass the same contract test suite (write tests against the interface, not against a specific implementation).
|
||||
- Test names describe the case being verified, not the function: `it('refuses resume after archival window expires')` not `it('resumeSession')`.
|
||||
- For storage code: tests use a real (temporary) instance of the storage layer, created and torn down per test or per suite. Don't mock the storage engine — you're testing the wrong thing if you do.
|
||||
- For integration code that depends on an external library's hooks: contract tests against that library's surface so a dependency bump catches behavior changes.
|
||||
- Build pipeline (CI or local) runs all tests; non-zero exit = build fails. There is no "build succeeded but tests failed" state.
|
||||
|
||||
#### Logging
|
||||
|
||||
**Every new feature with a non-happy-path ships with a log line at each rare branch.** Use a structured logger with module-scoped child loggers. The log file is where "something's not working" turns into "what actually happened."
|
||||
|
||||
Level guidance:
|
||||
|
||||
- **info** — expected-but-noteworthy edges: a UI race that hits a closed resource, a permission bypass for a privileged principal. Correct behavior an operator might want to confirm fired.
|
||||
- **warn** — should be rare and worth investigating: race past a pre-check, lost events past retention, programmer/operator errors (calling a method after stop, a key that should have resolved didn't).
|
||||
- **error** — actual failures the operator must respond to: handler crashes, dispatch loop crashes, integration failures.
|
||||
- **debug** — high-volume internal state changes; always pair with a `module` field so it can be filtered.
|
||||
|
||||
Pass structured fields, not interpolated strings — fields are what makes a log queryable:
|
||||
|
||||
```ts
|
||||
// Yes
|
||||
logger.warn({ session_id, state }, "rejected append against non-live session");
|
||||
|
||||
// No
|
||||
logger.warn(`session ${session_id} (${state}) rejected append`);
|
||||
```
|
||||
|
||||
If you add a new typed error or a new event topic, also log it. The typed error tells the immediate caller; the event tells subscribers; the log tells the operator. The three are independent surfaces for the same fact, and all three are needed — events don't show up in the log, logs don't show up on the bus, errors don't survive the catch.
|
||||
|
||||
#### Structure
|
||||
|
||||
- Keep modules small. If a file is over ~500 lines, ask whether it has more than one responsibility.
|
||||
- Prefer explicit composition (caller wires things together) over implicit dependency-injection magic.
|
||||
- One public concept per module. If a file exports both `Foo` and `unrelatedHelperUsedNowhereElse`, the helper has the wrong home.
|
||||
|
||||
#### Dependencies
|
||||
|
||||
**Always check the registry for the current version before adding or updating a dependency.** Don't pick versions from memory.
|
||||
|
||||
The simple test: did you actually run `<package-manager> view <pkg> version` (or its equivalent) before pinning? If not, you're guessing — and the guess is almost always behind, sometimes by a major version with active deprecation.
|
||||
|
||||
Why this matters:
|
||||
|
||||
- **Long-running codebases.** Stale dependency anchors compound. A v3 you picked because that's what was on your mind will still be v3 a year later, and the v4 migration gets harder every month it waits.
|
||||
- **Active deprecations are real.** Common libraries are mid-deprecation cycles for older majors. Pinning to a soon-deprecated version on day one means the eventual upgrade is forced rather than chosen.
|
||||
- **"Latest" doesn't mean "use without thinking."** Read the changelog for breaking changes; decide whether to take them now or pin behind explicitly. But the *default* posture should be: pick latest, and justify in writing if pinning behind.
|
||||
|
||||
If you must pin behind latest, leave a comment in the manifest (or a CHANGELOG note) explaining why — a known incompatibility with another dep, an in-progress migration, a tested-and-rejected major bump. *"I haven't checked"* is not an acceptable reason.
|
||||
|
||||
Apply to: adding a new dep, updating an existing one, scaffolding a new package. *Not* required for routine no-op installs that don't touch versions.
|
||||
|
||||
#### Doc-vs-spec discipline
|
||||
|
||||
Specification documents (the deeper ones that describe how a component must behave) are **functional specifications**, not narrative essays. The discipline:
|
||||
|
||||
- **Concrete data structures** — type definitions, schemas, DDL, JSON examples
|
||||
- **Concrete function signatures** — input/output types, error types
|
||||
- **Concrete event/message payloads** — name + schema + example
|
||||
- **Concrete API signatures** — input/output schemas, side effects, permission requirements
|
||||
- **Flow pseudocode** — when orchestration is non-obvious
|
||||
- **Invariants** — explicitly listed: "after X happens, Y is always true"
|
||||
- **Failure modes** — enumerated: "if X fails, the system does Y"
|
||||
- **Acceptance tests** — statements another engineer can implement: "given input X, output Y"
|
||||
|
||||
Avoid in spec docs:
|
||||
- Long prose explaining motivation (that goes in ADRs / decision records)
|
||||
- Discussion of alternatives considered (also ADRs)
|
||||
- Background context (README handles this)
|
||||
- Marketing/aspirational tone
|
||||
|
||||
Spec docs are for implementation. Read one and you should know what to build.
|
||||
|
||||
### When in doubt
|
||||
|
||||
Ask the human user. Specifically:
|
||||
|
||||
- "I don't see a clean seam for this; the options I see are A or B. Which fits the architecture you have in mind?"
|
||||
- "This requires a new contract / capability / interface. Should I draft it before implementing?"
|
||||
- "I'm about to add a special case here; that smells like a missing abstraction. Do you want me to extract the abstraction or note the smell and defer?"
|
||||
|
||||
Don't ship band-aids and ask forgiveness later. The user has explicitly said: prevent that pattern.
|
||||
+12
-2
@@ -1,7 +1,17 @@
|
||||
services:
|
||||
wwv:
|
||||
image: ghcr.io/silvertakana/worldwideview:latest
|
||||
pull_policy: always
|
||||
build:
|
||||
context: .
|
||||
args:
|
||||
- NEXT_PUBLIC_WWV_EDITION=${NEXT_PUBLIC_WWV_EDITION:-local}
|
||||
- NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL=${NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL:-}
|
||||
- NEXT_PUBLIC_SUPABASE_URL=${NEXT_PUBLIC_SUPABASE_URL:-}
|
||||
- NEXT_PUBLIC_SUPABASE_ANON_KEY=${NEXT_PUBLIC_SUPABASE_ANON_KEY:-}
|
||||
- NEXT_PUBLIC_GOOGLE_MAPS_API_KEY=${NEXT_PUBLIC_GOOGLE_MAPS_API_KEY:-}
|
||||
- NEXT_PUBLIC_BING_MAPS_KEY=${NEXT_PUBLIC_BING_MAPS_KEY:-}
|
||||
- NEXT_PUBLIC_CESIUM_ION_TOKEN=${NEXT_PUBLIC_CESIUM_ION_TOKEN:-}
|
||||
- NEXT_PUBLIC_ADSENSE_CLIENT_ID=${NEXT_PUBLIC_ADSENSE_CLIENT_ID:-}
|
||||
ports:
|
||||
- "3000:3000"
|
||||
volumes:
|
||||
@@ -46,7 +56,7 @@ services:
|
||||
wwv-data-engine:
|
||||
image: ghcr.io/silvertakana/wwv-data-engine:latest
|
||||
ports:
|
||||
- '5000:5000'
|
||||
- "5000:5000"
|
||||
environment:
|
||||
- PORT=5000
|
||||
- REDIS_URL=redis://wwv-redis:6379
|
||||
|
||||
+41
-1
@@ -38,5 +38,45 @@ Execute the following commands from the root `worldwideview` directory:
|
||||
```
|
||||
|
||||
## Reference
|
||||
- **Coverage Scope:** The Vitest configuration primarily targets tests located inside `src/lib/**`, `src/core/**`, and `src/plugins/**`.
|
||||
- **Coverage Scope:** The Vitest configuration targets tests located inside `src/lib/**`, `src/core/**`, `src/plugins/**`, `src/app/**`, and `packages/**`.
|
||||
- **Environment:** The test environment is configured as `jsdom` via `vite.config.ts` or `vitest.config.ts`, ensuring that DOM-specific API calls function outside of a real browser.
|
||||
|
||||
## Patterns
|
||||
|
||||
### Plain function — no mocks needed
|
||||
Pull in the function, call it with representative inputs, assert the output. See `src/lib/marketplace/cors.test.ts` or `src/app/api/camera/adapters/registry.test.ts` for examples.
|
||||
|
||||
### Stateful singleton — reset in `afterEach`
|
||||
Most of the data layer (`dataBus`, `cacheLayer`, `pollingManager`) is exported as a singleton instance. Tests pass when run alone but fail when run together if state leaks. `DataBus.test.ts` shows the canonical cleanup:
|
||||
|
||||
```typescript
|
||||
import { dataBus } from "./DataBus";
|
||||
|
||||
afterEach(() => {
|
||||
dataBus.removeAllListeners();
|
||||
});
|
||||
```
|
||||
|
||||
### Module-level dependency — mock with `vi.mock`
|
||||
When the module under test pulls in something heavy (the store, the database, Cesium), mock that module before the import. `vi.mock` calls are hoisted, so they take effect even when written below the import in source order. See `src/lib/marketplace/repository.test.ts` (Prisma client) or `src/core/data/PollingManager.test.ts` (Zustand store).
|
||||
|
||||
### Timers — fake them per test
|
||||
`vi.useFakeTimers()` in `beforeEach`, `vi.useRealTimers()` in `afterEach`. Advance time explicitly with `vi.advanceTimersByTimeAsync(ms)`.
|
||||
|
||||
> [!CAUTION]
|
||||
> `vi.runOnlyPendingTimersAsync()` ticks `setInterval`s scheduled on the same tick as the call. For tests where a function runs once synchronously and then schedules a recurring interval, this double-counts the first call. To drain microtasks without advancing the clock, use `await Promise.resolve()` a few times — see `PollingManager.test.ts` for the `flushMicrotasks()` helper.
|
||||
|
||||
## What NOT to Test (Yet)
|
||||
|
||||
- **Cesium-heavy components.** Anything that mounts a `<Viewer>` or renders entities to the globe needs WebGL, which jsdom doesn't provide. These belong in Playwright-style E2E tests rather than unit tests.
|
||||
- **Live database round-trips.** Mock the Prisma client at the module boundary — `repository.test.ts` is the reference pattern. Spinning up a real Postgres in CI is expensive and unreliable.
|
||||
- **Dynamic-import plugin bundles.** The loader uses `import(/* webpackIgnore: true */ entry)` at runtime against a real URL. Test the loader's pre-import logic with a fake module object, not a real dynamic import.
|
||||
|
||||
## Philosophy
|
||||
|
||||
A small focused suite is more valuable than a large one that's expensive to maintain. Each test should answer: *what specific regression does this catch that I'd otherwise discover from a user bug report?*
|
||||
|
||||
Two practical rules:
|
||||
|
||||
1. **Prefer testing pure logic over orchestration.** If a function takes inputs and returns outputs, test it directly. If it coordinates a half-dozen other things (the globe, the store, Cesium primitives), either refactor the pure parts out or use an integration test.
|
||||
2. **Add a test when you fix a bug.** A one-line test that fails today and passes after the fix is enough to prevent the bug from coming back. Land the test in the same PR as the fix.
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "worldwideview",
|
||||
"version": "2.9.1",
|
||||
"version": "2.9.10",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"packageManager": "[email protected]",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@worldwideview/wwv-plugin-sdk",
|
||||
"version": "1.5.0",
|
||||
"version": "1.5.1",
|
||||
"description": "Plugin SDK — types, interfaces, and utilities for building WorldWideView globe plugins",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
// ─── 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
|
||||
*/
|
||||
|
||||
import type { ComponentType } from "react";
|
||||
import { createElement } from "react";
|
||||
@@ -86,17 +90,30 @@ export interface TimeRange {
|
||||
|
||||
export type TimeWindow = "1h" | "6h" | "24h" | "48h" | "7d";
|
||||
|
||||
// ─── Geo Entities ────────────────────────────────────────────
|
||||
/**
|
||||
* @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>;
|
||||
}
|
||||
|
||||
@@ -225,7 +242,11 @@ export type FilterValue =
|
||||
| { type: "range"; min: number; max: number }
|
||||
| { type: "boolean"; value: boolean };
|
||||
|
||||
// ─── World Plugin Interface ──────────────────────────────────
|
||||
/**
|
||||
* @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;
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
// ─── 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
|
||||
*/
|
||||
|
||||
import type { PluginCategory } from "./index";
|
||||
|
||||
@@ -59,6 +63,10 @@ export interface RenderingConfig {
|
||||
maxEntities?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* @interface PluginManifest
|
||||
* @description The structural definition of a plugin.json file.
|
||||
*/
|
||||
export interface PluginManifest {
|
||||
id: string;
|
||||
name: string;
|
||||
|
||||
@@ -1,15 +1,26 @@
|
||||
/**
|
||||
* @file viteGlobals.ts
|
||||
* @description Build-time utility for externalizing shared dependencies.
|
||||
* Provides a Vite plugin that maps core libraries (React, Cesium, Zustand)
|
||||
* to the host application's global context, ensuring singleton stability
|
||||
* for dynamic plugin bundles.
|
||||
* @module @worldwideview/wwv-plugin-sdk
|
||||
*/
|
||||
|
||||
interface GlobalsMap {
|
||||
[moduleId: string]: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A Vite/Rollup plugin that resolves shared dependencies to the
|
||||
* `globalThis.__WWV_HOST__` object injected by the core WWV engine.
|
||||
* @function wwvPluginGlobals
|
||||
* @description Creates a Vite/Rollup plugin that resolves shared dependencies to
|
||||
* the `globalThis.__WWV_HOST__` object.
|
||||
*
|
||||
* This ensures that dynamically loaded CDN plugins inherit the exact
|
||||
* React, Zustand, and Cesium instances of the host application,
|
||||
* eliminating "Invalid Hook Call" and "useCallback" context mismatches.
|
||||
* This ensures that dynamically loaded plugins inherit the exact library
|
||||
* instances of the host application, preventing version mismatches and
|
||||
* context errors.
|
||||
*
|
||||
* @returns {any} A Vite plugin object.
|
||||
*/
|
||||
export function wwvPluginGlobals(): any {
|
||||
const HOST_MAPPINGS: GlobalsMap = {
|
||||
|
||||
@@ -1,8 +1,21 @@
|
||||
/**
|
||||
* @file boot-db.mjs
|
||||
* @description Database bootstrapping utility.
|
||||
* Automates the startup of the local PostgreSQL container via Docker Compose
|
||||
* and ensures the environment is ready for Prisma migrations.
|
||||
* @module scripts
|
||||
*/
|
||||
|
||||
import { execSync } from 'child_process';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
// Load environment variables manually since dotenv might not be installed globally
|
||||
/**
|
||||
* @function loadEnv
|
||||
* @description Manually parses a .env file into process.env to avoid
|
||||
* external dependencies like 'dotenv' during early boot.
|
||||
*/
|
||||
const loadEnv = (file) => {
|
||||
try {
|
||||
if (fs.existsSync(file)) {
|
||||
|
||||
+5
-6
@@ -1,11 +1,10 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* setup.mjs — One-command local setup
|
||||
*
|
||||
* Generates a .env.local file from .env.example
|
||||
* and auto-fills AUTH_SECRET with a secure random value.
|
||||
*
|
||||
* Usage: npm run setup
|
||||
* @file setup.mjs
|
||||
* @description One-command local setup utility.
|
||||
* Generates a .env file from .env.example and auto-fills sensitive
|
||||
* secrets (like AUTH_SECRET) with secure random values.
|
||||
* @module scripts
|
||||
*/
|
||||
|
||||
import { existsSync, readFileSync, writeFileSync } from "fs";
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
// scripts/sync-local-plugins.mjs
|
||||
// Scans local-plugins/ for valid wwv-manifest.json files,
|
||||
// builds each with Vite, and copies output to public/plugins-local/.
|
||||
/**
|
||||
* @file sync-local-plugins.mjs
|
||||
* @description Local plugin synchronization and build utility.
|
||||
* Scans `local-plugins/`, compiles bundles using Vite, and hydrates the
|
||||
* `public/plugins-local/` directory for the Next.js dev server.
|
||||
* @module scripts
|
||||
*/
|
||||
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { build } from "vite";
|
||||
@@ -21,6 +26,12 @@ const EXTERNAL_GLOBALS = {
|
||||
"resium": "globalThis.__WWV_HOST__.Resium",
|
||||
};
|
||||
|
||||
/**
|
||||
* @function discoverLocalPlugins
|
||||
* @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}>}
|
||||
*/
|
||||
export function discoverLocalPlugins() {
|
||||
if (!fs.existsSync(LOCAL_PLUGINS_DIR)) return [];
|
||||
|
||||
@@ -43,6 +54,11 @@ export function discoverLocalPlugins() {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @function buildPlugin
|
||||
* @description Invokes the Vite build engine to compile a plugin's source
|
||||
* into a single ES module, externalizing shared host dependencies.
|
||||
*/
|
||||
export async function buildPlugin({ dir, manifest, pluginDir }) {
|
||||
const devEntry = manifest.dev_entry || "src/index.ts";
|
||||
let entryFile = path.join(pluginDir, devEntry);
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { resolveSources, ALL_ADAPTERS } from "./registry";
|
||||
|
||||
/**
|
||||
* `resolveSources` is the input-sanitizer at the top of every
|
||||
* /api/camera/traffic and /api/camera/list call. Wrong behaviour here
|
||||
* either denies legitimate clients or lets the aggregator hit adapters
|
||||
* that aren't registered. Easy to test, high blast radius.
|
||||
*/
|
||||
|
||||
describe("camera adapter registry — resolveSources", () => {
|
||||
it("returns every registered adapter id when raw is 'all'", () => {
|
||||
const result = resolveSources("all");
|
||||
const expected = ALL_ADAPTERS.map((a) => a.id);
|
||||
expect(result.sort()).toEqual(expected.sort());
|
||||
});
|
||||
|
||||
it("returns every registered adapter id when raw is null (default behaviour)", () => {
|
||||
const result = resolveSources(null);
|
||||
const expected = ALL_ADAPTERS.map((a) => a.id);
|
||||
expect(result.sort()).toEqual(expected.sort());
|
||||
});
|
||||
|
||||
it("returns an empty list when raw is 'none' — clients use this to short-circuit", () => {
|
||||
expect(resolveSources("none")).toEqual([]);
|
||||
});
|
||||
|
||||
it("drops unknown ids from a comma-separated list without erroring", () => {
|
||||
const knownId = ALL_ADAPTERS[0]?.id;
|
||||
if (!knownId) throw new Error("registry has zero adapters — test precondition broken");
|
||||
|
||||
const result = resolveSources(`${knownId},completely-fake-adapter,${knownId}`);
|
||||
expect(result).toContain(knownId);
|
||||
expect(result).not.toContain("completely-fake-adapter");
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,12 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* @file AdUnit.tsx
|
||||
* @description Standardized Google AdSense wrapper component.
|
||||
* Handles client-side script pushing and provides a development-mode mock UI.
|
||||
* @module src/components/ads
|
||||
*/
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
interface AdUnitProps {
|
||||
@@ -9,6 +16,16 @@ interface AdUnitProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* @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) {
|
||||
const insRef = useRef<HTMLModElement>(null);
|
||||
const pushed = useRef(false);
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* @file DemoAdStrip.tsx
|
||||
* @description specialized sidebar for the demo edition that hosts AdSense
|
||||
* units and a small banner explaining the monetization model.
|
||||
* @module src/components/ads
|
||||
*/
|
||||
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { isDemo } from "@/core/edition";
|
||||
import { dataBus } from "@/core/data/DataBus";
|
||||
@@ -17,6 +24,11 @@ const AD_STRIP_WIDTH = 160;
|
||||
/** Toggle to temporarily disable ads in the demo edition. */
|
||||
const ENABLE_ADS = false;
|
||||
|
||||
/**
|
||||
* @component DemoAdStrip
|
||||
* @description Renders a vertical ad column on the right side of the screen.
|
||||
* Automatically injects layout offsets into the page root to prevent HUD overlap.
|
||||
*/
|
||||
export function DemoAdStrip() {
|
||||
const [showMessage, setShowMessage] = useState(false);
|
||||
const [bannerDismissed, setBannerDismissed] = useState(false);
|
||||
|
||||
@@ -1,11 +1,28 @@
|
||||
/**
|
||||
* @file BootOverlay.tsx
|
||||
* @description A high-fidelity loading overlay displayed during application initialization.
|
||||
* Features animated orbital rings and brand identity.
|
||||
* @module src/components/common
|
||||
*/
|
||||
|
||||
"use client";
|
||||
|
||||
import "./BootOverlay.css";
|
||||
|
||||
/**
|
||||
* Props for the BootOverlay component.
|
||||
*/
|
||||
interface BootOverlayProps {
|
||||
/** Whether the overlay is currently visible on top of the application. */
|
||||
visible: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* @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"}`}>
|
||||
|
||||
@@ -1,13 +1,24 @@
|
||||
/**
|
||||
* Discord brand icon as a React SVG component.
|
||||
* Matches the lucide-react icon API (size, className props).
|
||||
* @file DiscordIcon.tsx
|
||||
* @description SVG component for the Discord brand identity.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Props for the DiscordIcon component.
|
||||
*/
|
||||
interface DiscordIconProps {
|
||||
/** Dimension (width and height) in pixels. Defaults to 18. */
|
||||
size?: number;
|
||||
/** Optional CSS class names for styling. */
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
return (
|
||||
<svg
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
/**
|
||||
* @file FeedbackDialog.tsx
|
||||
* @description A comprehensive feedback and bug reporting interface.
|
||||
* Supports categorization, screenshot capture via getDisplayMedia,
|
||||
* file uploads, and automatic diagnostic log attachment.
|
||||
*/
|
||||
|
||||
"use client";
|
||||
|
||||
import React, { useState, useEffect, useRef } from "react";
|
||||
@@ -7,6 +14,13 @@ import { getCapturedLogs } from "@/lib/logCatcher";
|
||||
import styles from "./FeedbackDialog.module.css";
|
||||
import { trackEvent } from "@/lib/analytics";
|
||||
|
||||
/**
|
||||
* 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() {
|
||||
const feedbackDialogOpen = useStore((s) => s.feedbackDialogOpen);
|
||||
const setFeedbackDialogOpen = useStore((s) => s.setFeedbackDialogOpen);
|
||||
|
||||
@@ -1,20 +1,46 @@
|
||||
/**
|
||||
* @file FloatingWindow.tsx
|
||||
* @description A draggable and resizable modal window container.
|
||||
* Supports mouse and touch interactions, boundary constraints, and persistence callbacks.
|
||||
* @module src/components/common
|
||||
*/
|
||||
|
||||
"use client";
|
||||
|
||||
import React, { useState, useEffect, useRef, useCallback } from "react";
|
||||
import { X } from "lucide-react";
|
||||
|
||||
/**
|
||||
* Props for the FloatingWindow component.
|
||||
*/
|
||||
interface FloatingWindowProps {
|
||||
/** Unique identifier for the window instance. */
|
||||
id: string;
|
||||
/** Title text displayed in the header bar. */
|
||||
title: string;
|
||||
/** Inner content to be rendered within the window body. */
|
||||
children: React.ReactNode;
|
||||
/** Initial screen coordinates for the window. */
|
||||
initialPosition?: { x: number; y: number };
|
||||
/** Initial dimensions for the window. */
|
||||
initialSize?: { width: number; height: number };
|
||||
/** Callback triggered when the close button is clicked. */
|
||||
onClose: () => void;
|
||||
/** Callback triggered when the window is moved or resized. */
|
||||
onUpdate?: (updates: { position?: { x: number; y: number }; size?: { width: number; height: number } }) => void;
|
||||
/** Minimum allowed width during resize. Defaults to 300. */
|
||||
minWidth?: number;
|
||||
/** Minimum allowed height during resize. Defaults to 200. */
|
||||
minHeight?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* @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> = ({
|
||||
id,
|
||||
title,
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
/**
|
||||
* @file PannableView.tsx
|
||||
* @description A high-performance 2D navigation container providing panning and
|
||||
* pinch-zoom capabilities for inner content.
|
||||
* @module src/components/common
|
||||
*/
|
||||
|
||||
"use client";
|
||||
|
||||
import React, { useState, useRef, useCallback } from "react";
|
||||
import { RotateCcw } from "lucide-react";
|
||||
|
||||
/**
|
||||
* Props for the PannableView component.
|
||||
*/
|
||||
interface PannableViewProps {
|
||||
/** The content to be rendered within the pannable and zoomable area. */
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
@@ -11,6 +22,13 @@ const MIN_ZOOM = 1;
|
||||
const MAX_ZOOM = 8;
|
||||
const ZOOM_STEP = 0.15;
|
||||
|
||||
/**
|
||||
* @component PannableView
|
||||
* @description Wraps content in a 2D viewport that supports infinite panning and multi-touch zoom.
|
||||
* Ideal for secondary maps, floor plans, or large interactive diagrams.
|
||||
*
|
||||
* @param {PannableViewProps} props - Component properties.
|
||||
*/
|
||||
export const PannableView: React.FC<PannableViewProps> = ({ children }) => {
|
||||
const [zoom, setZoom] = useState(1);
|
||||
const [pan, setPan] = useState({ x: 0, y: 0 });
|
||||
|
||||
@@ -1,16 +1,38 @@
|
||||
/**
|
||||
* @file PluginErrorBoundary.tsx
|
||||
* @description Fault-isolation container for dynamic plugin components.
|
||||
* Ensures a single plugin crash does not bring down the entire application.
|
||||
* @module src/components/common
|
||||
*/
|
||||
|
||||
"use client";
|
||||
|
||||
import React, { Component, ErrorInfo, ReactNode } from "react";
|
||||
|
||||
/**
|
||||
* Props for the PluginErrorBoundary component.
|
||||
*/
|
||||
interface Props {
|
||||
/** The unique identifier of the plugin being wrapped. */
|
||||
pluginId: string;
|
||||
/** The child components to monitor for render errors. */
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* State for the PluginErrorBoundary.
|
||||
*/
|
||||
interface State {
|
||||
/** Whether an error has been caught in the current lifecycle. */
|
||||
hasError: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* @component PluginErrorBoundary
|
||||
* @description A standard React error boundary used to isolate failures in third-party
|
||||
* or dynamic plugin components. When a crash occurs, the boundary renders
|
||||
* nothing (null), allowing the rest of the UI (sidebar, globe) to remain functional.
|
||||
*/
|
||||
export class PluginErrorBoundary extends Component<Props, State> {
|
||||
public state: State = {
|
||||
hasError: false
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
/**
|
||||
* @file PluginIcon.tsx
|
||||
* @description Central icon resolver for plugins. Supports Lucide string names,
|
||||
* emoji fallbacks, and custom React component icons.
|
||||
*/
|
||||
|
||||
"use client";
|
||||
|
||||
import type { ComponentType } from "react";
|
||||
@@ -5,17 +11,28 @@ import { icons, type LucideIcon } from "lucide-react";
|
||||
|
||||
const FallbackIcon = icons.Package;
|
||||
|
||||
/**
|
||||
* Props for the PluginIcon component.
|
||||
*/
|
||||
interface PluginIconProps {
|
||||
/**
|
||||
* The icon to render. Can be a Lucide icon name (e.g., "Airplay"),
|
||||
* a raw emoji string, or a React component.
|
||||
*/
|
||||
icon: string | ComponentType<{ size?: number; color?: string }>;
|
||||
/** The size in pixels for the icon. Defaults to 18. */
|
||||
size?: number;
|
||||
/** The CSS color for the icon stroke/fill. */
|
||||
color?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a plugin icon consistently across the app.
|
||||
* Resolves any valid lucide-react icon name string dynamically,
|
||||
* so new plugins can use any icon without updating this component.
|
||||
* Also supports emoji strings and React component icons.
|
||||
* Renders a consistent icon representation for plugins.
|
||||
* Dynamically resolves Lucide icons by name to allow plugins to declare
|
||||
* icons in their manifests without bundling dependencies.
|
||||
*
|
||||
* @param props - Component properties.
|
||||
* @returns React component for the plugin icon.
|
||||
*/
|
||||
export function PluginIcon({ icon, size = 18, color }: PluginIconProps) {
|
||||
if (typeof icon === "string") {
|
||||
|
||||
@@ -1,3 +1,11 @@
|
||||
/**
|
||||
* @file ApiKeysTab.tsx
|
||||
* @description Manages user-provided API keys and license verification.
|
||||
* Allows users to override default keys for services like Google Maps or
|
||||
* proprietary data sources.
|
||||
* @module src/components/layout
|
||||
*/
|
||||
|
||||
import { useState, useCallback, useEffect, useRef } from "react";
|
||||
import { Eye, EyeOff, Trash2, Key, CheckCircle, XCircle, Loader, ShieldCheck } from "lucide-react";
|
||||
import {
|
||||
@@ -37,6 +45,13 @@ const toggleBtnStyle: React.CSSProperties = {
|
||||
const DEBOUNCE_MS = 800;
|
||||
const MIN_KEY_LENGTH = 20;
|
||||
|
||||
/**
|
||||
* @function StatusIcon
|
||||
* @description Renders a status icon (loading, valid, invalid) for key verification.
|
||||
* @param {Object} props - Component properties.
|
||||
* @param {VerifyStatus} props.status - The current verification state.
|
||||
* @returns {JSX.Element | null}
|
||||
*/
|
||||
function StatusIcon({ status }: { status: VerifyStatus }) {
|
||||
if (status === "verifying")
|
||||
return (
|
||||
@@ -51,6 +66,11 @@ function StatusIcon({ status }: { status: VerifyStatus }) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @component ApiKeysTab
|
||||
* @description A configuration interface for managing license keys and service API keys.
|
||||
* Handles persistence to local storage and asynchronous verification of keys.
|
||||
*/
|
||||
export function ApiKeysTab() {
|
||||
const [keys, setKeys] = useState<Record<string, string>>(() => {
|
||||
const initial: Record<string, string> = {};
|
||||
|
||||
@@ -1,3 +1,11 @@
|
||||
/**
|
||||
* @file AppShell.tsx
|
||||
* @description The root layout and orchestration component for WorldWideView.
|
||||
* Responsible for platform initialization, plugin registration, global state hydration,
|
||||
* and managing the transition from boot sequence to interactive state.
|
||||
* @module src/components/layout
|
||||
*/
|
||||
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
@@ -37,6 +45,17 @@ const GlobeView = dynamic(() => import("@/core/globe/GlobeView"), {
|
||||
ssr: false,
|
||||
});
|
||||
|
||||
/**
|
||||
* @component AppShell
|
||||
* @description The primary application wrapper.
|
||||
*
|
||||
* Orchestrates the following:
|
||||
* 1. Theme hydration from localStorage.
|
||||
* 2. Injection of host globals for dynamic ES module plugins.
|
||||
* 3. Loading of marketplace and built-in plugins.
|
||||
* 4. Synchronization with the Cesium globe lifecycle.
|
||||
* 5. Managing the "Boot" animation sequence and HUD entry.
|
||||
*/
|
||||
export function AppShell() {
|
||||
const initLayer = useStore((s) => s.initLayer);
|
||||
const boot = useBootSequence();
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
/**
|
||||
* @file DataBusSubscriber.tsx
|
||||
* @description Headless component that bridges the DataBus event system with the Zustand store.
|
||||
* Handles automatic WebSocket subscription/unsubscription when layers are toggled.
|
||||
* @module src/components/layout
|
||||
*/
|
||||
|
||||
"use client";
|
||||
|
||||
import { useEffect } from "react";
|
||||
@@ -9,8 +16,9 @@ import { resolveEngineUrl } from "@/core/data/resolveEngineUrl";
|
||||
import { fetchLocalEngineManifest } from "@/core/data/engineManifest";
|
||||
|
||||
/**
|
||||
* Subscribes to DataBus events and syncs state.
|
||||
* Renders nothing — purely a side-effect component.
|
||||
* @component DataBusSubscriber
|
||||
* @description Orchestrates side-effects between the event-driven DataBus and the React state store.
|
||||
* This component renders no UI; it strictly manages the data pipeline lifecycle.
|
||||
*/
|
||||
export function DataBusSubscriber() {
|
||||
const setPollingInterval = useStore((s) => s.setPollingInterval);
|
||||
|
||||
@@ -1,9 +1,22 @@
|
||||
/**
|
||||
* @file DevModeSubscriber.tsx
|
||||
* @description Development-only component that connects to the `wwv-cli` dev server.
|
||||
* Enables hot-reloading of local plugins during development.
|
||||
*/
|
||||
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { pluginManager } from "@/core/plugins/PluginManager";
|
||||
import { useStore } from "@/core/state/store";
|
||||
|
||||
/**
|
||||
* Headless component that listens for plugin updates over a local WebSocket.
|
||||
* Only active in `development` environments. Allows for real-time plugin
|
||||
* addition and reloading without full page refreshes.
|
||||
*
|
||||
* @returns null
|
||||
*/
|
||||
export function DevModeSubscriber() {
|
||||
const [connected, setConnected] = useState(false);
|
||||
const initLayer = useStore((s) => s.initLayer);
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* @file Header.tsx
|
||||
* @description Primary application header providing branding, search, region presets,
|
||||
* theme selection, and system-wide controls.
|
||||
* @module src/components/layout
|
||||
*/
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useStore } from "@/core/state/store";
|
||||
import { dataBus } from "@/core/data/DataBus";
|
||||
@@ -33,6 +40,17 @@ const THEMES = [
|
||||
|
||||
const TIME_WINDOWS = ["1h", "6h", "24h", "48h", "7d"] as const;
|
||||
|
||||
/**
|
||||
* @component Header
|
||||
* @description The main navigation and control bar of the application.
|
||||
* Handles responsive layout between mobile and desktop, including time windows,
|
||||
* theme selection, and region-based camera presets.
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* <Header />
|
||||
* ```
|
||||
*/
|
||||
export function Header() {
|
||||
const isMobile = useIsMobile();
|
||||
const timeWindow = useStore((s) => s.timeWindow);
|
||||
|
||||
@@ -1,11 +1,26 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* @file SearchBar.tsx
|
||||
* @description Integrated search component providing geocoding, entity lookup,
|
||||
* and history functionality with a high-performance dropdown interface.
|
||||
* @module src/components/layout
|
||||
*/
|
||||
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { Search, MapPin } from "lucide-react";
|
||||
import { useSearch } from "./useSearch";
|
||||
import type { SearchResult, SearchSection } from "./useSearch";
|
||||
import { useIsMobile } from "@/core/hooks/useIsMobile";
|
||||
|
||||
/**
|
||||
* @function HighlightMatch
|
||||
* @description Helper component that highlights matching query text within a string.
|
||||
* @param {Object} props - Component properties.
|
||||
* @param {string} props.text - The full text to display.
|
||||
* @param {string} props.query - The search string to highlight.
|
||||
* @returns {JSX.Element} The text with highlighted spans.
|
||||
*/
|
||||
function HighlightMatch({ text, query }: { text: string; query: string }) {
|
||||
if (!query) return <>{text}</>;
|
||||
// Trim query to handle trailing spaces safely
|
||||
@@ -22,6 +37,11 @@ function HighlightMatch({ text, query }: { text: string; query: string }) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @component SearchBar
|
||||
* @description Primary search input field that manages focus, keyboard navigation,
|
||||
* and result dropdown visibility.
|
||||
*/
|
||||
export function SearchBar() {
|
||||
const isMobile = useIsMobile();
|
||||
const {
|
||||
|
||||
@@ -1,8 +1,18 @@
|
||||
"use client";
|
||||
/**
|
||||
* @file CameraStatsPanel.tsx
|
||||
* @description Head-up display (HUD) overlay providing real-time camera position,
|
||||
* orientation, and performance metrics (FPS).
|
||||
* @module src/components/panels
|
||||
*/
|
||||
|
||||
import React, { useState } from "react";
|
||||
import { useStore } from "@/core/state/store";
|
||||
|
||||
/**
|
||||
* @component CameraStatsPanel
|
||||
* @description A minimal HUD component that displays latitude, longitude,
|
||||
* altitude, heading, pitch, roll, and FPS. Can be collapsed by the user.
|
||||
*/
|
||||
export default function CameraStatsPanel() {
|
||||
const [collapsed, setCollapsed] = useState(false);
|
||||
|
||||
|
||||
@@ -1,6 +1,17 @@
|
||||
/**
|
||||
* @file CacheTab.tsx
|
||||
* @module Panels/DataConfig
|
||||
* @description Specialized view for managing data engine caching parameters.
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
import { useStore } from "@/core/state/store";
|
||||
import { sectionHeaderStyle, inputGroupStyle, labelStyle, inputStyle, checkboxStyle } from "./sharedStyles";
|
||||
|
||||
/**
|
||||
* @component CacheTab
|
||||
* @description Provides a management interface for the data engine's caching strategy.
|
||||
*/
|
||||
export function CacheTab() {
|
||||
const dataConfig = useStore((s) => s.dataConfig);
|
||||
const updateDataConfig = useStore((s) => s.updateDataConfig);
|
||||
|
||||
@@ -1,3 +1,11 @@
|
||||
/**
|
||||
* @file IntelTab.tsx
|
||||
* @module Panels/DataConfig
|
||||
* @description Advanced intelligence dossier component for the right sidebar.
|
||||
* Includes interactive legends, color overrides, and plugin-specific sidebar integrations.
|
||||
* @version 1.1.0
|
||||
*/
|
||||
|
||||
import { useStore } from "@/core/state/store";
|
||||
import { pluginManager } from "@/core/plugins/PluginManager";
|
||||
import { PluginIcon } from "@/components/common/PluginIcon";
|
||||
@@ -9,6 +17,11 @@ import { DynamicPropertiesRender } from "../properties/DynamicPropertiesRender";
|
||||
import { useRef, useEffect } from "react";
|
||||
import { PluginErrorBoundary } from "@/components/common/PluginErrorBoundary";
|
||||
|
||||
/**
|
||||
* @component LegendItem
|
||||
* @description Renders a single entry in the map legend, allowing for color customization
|
||||
* and visibility filtering based on categorical data.
|
||||
*/
|
||||
function LegendItem({
|
||||
label,
|
||||
color,
|
||||
@@ -159,6 +172,12 @@ function LegendItem({
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @component IntelTab
|
||||
* @description The primary data visualization tab for the right sidebar.
|
||||
* Displays selected entity metadata or contextual layer information (Legend, Plugin Sidebar)
|
||||
* when no entity is selected.
|
||||
*/
|
||||
export function IntelTab() {
|
||||
const selectedEntity = useStore((s) => s.selectedEntity);
|
||||
const lockedEntityId = useStore((s) => s.lockedEntityId);
|
||||
|
||||
@@ -1,9 +1,21 @@
|
||||
/**
|
||||
* @file OverlayTab.tsx
|
||||
* @module Panels/DataConfig
|
||||
* @description Master configuration tab for active layers and experimental engine features.
|
||||
* Provides per-plugin polling control and global cache/concurrency limits.
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
import { useStore } from "@/core/state/store";
|
||||
import { pluginManager } from "@/core/plugins/PluginManager";
|
||||
import { sectionHeaderStyle, inputGroupStyle, labelStyle, inputStyle, checkboxStyle } from "./sharedStyles";
|
||||
import { PluginErrorBoundary } from "@/components/common/PluginErrorBoundary";
|
||||
|
||||
|
||||
/**
|
||||
* @component OverlayTab
|
||||
* @description Renders a comprehensive settings interface for all active plugins
|
||||
* and experimental platform features (Predictive Loading, Clustering, etc.).
|
||||
*/
|
||||
export function OverlayTab() {
|
||||
const dataConfig = useStore((s) => s.dataConfig);
|
||||
const updateDataConfig = useStore((s) => s.updateDataConfig);
|
||||
|
||||
@@ -1,3 +1,11 @@
|
||||
/**
|
||||
* @file index.tsx
|
||||
* @module Panels/DataConfig
|
||||
* @description Orchestration component for the right-side configuration panel.
|
||||
* Manages resizable sidebar state and tab switching between Intel, Filters, and Overlay settings.
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
import { useStore } from "@/core/state/store";
|
||||
import { FilterSection } from "@/components/panels/FilterPanel";
|
||||
import { Cog, FilterIcon, Info, Key, MessageSquare } from "lucide-react";
|
||||
@@ -11,6 +19,11 @@ import { sectionHeaderStyle } from "./sharedStyles";
|
||||
|
||||
import "./index.css";
|
||||
|
||||
/**
|
||||
* @component DataConfigPanel
|
||||
* @description Renders the right-hand resizable sidebar containing contextual information
|
||||
* and configuration tools.
|
||||
*/
|
||||
export function DataConfigPanel() {
|
||||
const isMobile = useIsMobile();
|
||||
const { width, startResizing } = useResizablePanel(320, 260, 800, 'right');
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
/**
|
||||
* @file sharedStyles.ts
|
||||
* @module Panels/DataConfig
|
||||
* @description Shared CSS-in-JS style objects for DataConfig sub-components.
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
import React from "react";
|
||||
|
||||
export const sectionHeaderStyle: React.CSSProperties = {
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* @file EntityInfoCard.tsx
|
||||
* @description Floating tooltip card that follows the mouse cursor to display
|
||||
* quick intel for the currently hovered map entity.
|
||||
* @module src/components/panels
|
||||
*/
|
||||
|
||||
import { useStore } from "@/core/state/store";
|
||||
import { pluginManager } from "@/core/plugins/PluginManager";
|
||||
import { PluginIcon } from "@/components/common/PluginIcon";
|
||||
@@ -19,6 +26,12 @@ const SEVERITY_LABELS: Record<number, string> = {
|
||||
5: "Critical", 4: "High", 3: "Elevated", 2: "Watchlist",
|
||||
};
|
||||
|
||||
/**
|
||||
* @component EntityInfoCard
|
||||
* @description A screen-space overlay that provides real-time entity snapshots.
|
||||
* It dynamically adjusts its screen position to remain visible and switches
|
||||
* content based on the hovered entity's plugin-specific properties.
|
||||
*/
|
||||
export function EntityInfoCard() {
|
||||
const hoveredEntity = useStore((s) => s.hoveredEntity);
|
||||
const screenPos = useStore((s) => s.hoveredScreenPosition);
|
||||
|
||||
@@ -1,7 +1,19 @@
|
||||
/**
|
||||
* @file FavoritesTab.tsx
|
||||
* @description Tab panel for managing user-saved "favorite" map entities.
|
||||
* Categorizes favorites into accessible (layer enabled) and inaccessible (layer disabled).
|
||||
* @module src/components/panels
|
||||
*/
|
||||
|
||||
import { useStore } from "@/core/state/store";
|
||||
import { Trash2 } from "lucide-react";
|
||||
import { trackEvent } from "@/lib/analytics";
|
||||
|
||||
/**
|
||||
* @component FavoritesTab
|
||||
* @description Displays a list of entities the user has starred.
|
||||
* Provides quick selection and removal capabilities.
|
||||
*/
|
||||
export function FavoritesTab() {
|
||||
const favorites = useStore((s) => s.favorites);
|
||||
const removeFavorite = useStore((s) => s.removeFavorite);
|
||||
|
||||
@@ -1,13 +1,32 @@
|
||||
/**
|
||||
* @file FilterControls.tsx
|
||||
* @module Panels/Filters
|
||||
* @description Specialized input controls for dynamic plugin data filtering,
|
||||
* including text search, multi-select chips, range sliders, and boolean toggles.
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
"use client";
|
||||
|
||||
import type { FilterDefinition, FilterValue } from "@/core/plugins/PluginTypes";
|
||||
|
||||
/**
|
||||
* @interface FilterControlProps
|
||||
* @description Common properties for all individual filter control components.
|
||||
* @property {FilterDefinition} definition - The structural metadata defining the filter's behavior.
|
||||
* @property {FilterValue} [value] - The current state of the filter.
|
||||
* @property {(value: FilterValue) => void} onChange - Callback triggered when the filter value changes.
|
||||
*/
|
||||
interface FilterControlProps {
|
||||
definition: FilterDefinition;
|
||||
value: FilterValue | undefined;
|
||||
onChange: (value: FilterValue) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* @component TextFilter
|
||||
* @description Renders a text input field for fuzzy-matching string filtering.
|
||||
*/
|
||||
export function TextFilter({ definition, value, onChange }: FilterControlProps) {
|
||||
const textVal = value?.type === "text" ? value.value : "";
|
||||
return (
|
||||
@@ -24,6 +43,10 @@ export function TextFilter({ definition, value, onChange }: FilterControlProps)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @component SelectFilter
|
||||
* @description Renders a collection of toggleable chips for multi-select filtering.
|
||||
*/
|
||||
export function SelectFilter({ definition, value, onChange }: FilterControlProps) {
|
||||
const selected = value?.type === "select" ? value.values : [];
|
||||
const options = definition.options || [];
|
||||
@@ -53,6 +76,10 @@ export function SelectFilter({ definition, value, onChange }: FilterControlProps
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @component RangeFilter
|
||||
* @description Renders a dual-handle range slider for numerical interval filtering.
|
||||
*/
|
||||
export function RangeFilter({ definition, value, onChange }: FilterControlProps) {
|
||||
const range = definition.range;
|
||||
if (!range) return null;
|
||||
@@ -105,6 +132,10 @@ export function RangeFilter({ definition, value, onChange }: FilterControlProps)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @component BooleanFilter
|
||||
* @description Renders a simple toggle button for binary (Yes/No) filtering.
|
||||
*/
|
||||
export function BooleanFilter({ definition, value, onChange }: FilterControlProps) {
|
||||
const boolVal = value?.type === "boolean" ? value.value : false;
|
||||
const isActive = value !== undefined;
|
||||
@@ -132,3 +163,27 @@ export function BooleanFilter({ definition, value, onChange }: FilterControlProp
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @component FilterControl
|
||||
* @description Master dispatcher that dynamically selects the correct UI control
|
||||
* based on the provided FilterDefinition type.
|
||||
*/
|
||||
export function FilterControl({ def, value, onChange }: {
|
||||
def: FilterDefinition;
|
||||
value: FilterValue | undefined;
|
||||
onChange: (v: FilterValue) => void
|
||||
}) {
|
||||
switch (def.type) {
|
||||
case "text":
|
||||
return <TextFilter definition={def} value={value} onChange={onChange} />;
|
||||
case "select":
|
||||
return <SelectFilter definition={def} value={value} onChange={onChange} />;
|
||||
case "range":
|
||||
return <RangeFilter definition={def} value={value} onChange={onChange} />;
|
||||
case "boolean":
|
||||
return <BooleanFilter definition={def} value={value} onChange={onChange} />;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,29 +1,23 @@
|
||||
"use client";
|
||||
/**
|
||||
* @file FilterPanel.tsx
|
||||
* @description UI components for managing dynamic data filters across all active plugins.
|
||||
* Supports text search, value selection, range sliders, and boolean toggles.
|
||||
* @module src/components/panels
|
||||
*/
|
||||
|
||||
import { useState } from "react";
|
||||
import { useStore } from "@/core/state/store";
|
||||
import { pluginManager } from "@/core/plugins/PluginManager";
|
||||
import { TextFilter, SelectFilter, RangeFilter, BooleanFilter } from "./FilterControls";
|
||||
import { TextFilter, SelectFilter, RangeFilter, BooleanFilter, FilterControl } from "./FilterControls";
|
||||
import { PluginIcon } from "@/components/common/PluginIcon";
|
||||
import type { FilterDefinition, FilterValue } from "@/core/plugins/PluginTypes";
|
||||
import { trackEvent } from "@/lib/analytics";
|
||||
|
||||
function FilterControl({ def, value, onChange }: {
|
||||
def: FilterDefinition;
|
||||
value: FilterValue | undefined;
|
||||
onChange: (v: FilterValue) => void;
|
||||
}) {
|
||||
const props = { definition: def, value, onChange };
|
||||
switch (def.type) {
|
||||
case "text": return <TextFilter {...props} />;
|
||||
case "select": return <SelectFilter {...props} />;
|
||||
case "range": return <RangeFilter {...props} />;
|
||||
case "boolean": return <BooleanFilter {...props} />;
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Embeddable filter section — designed to be placed inside DataConfigPanel */
|
||||
/**
|
||||
* @component FilterSection
|
||||
* @description An embeddable list of filter controls, grouped by plugin.
|
||||
* Only displays filters for plugins that are currently enabled in the LayerPanel.
|
||||
*/
|
||||
export function FilterSection() {
|
||||
const layers = useStore((s) => s.layers);
|
||||
const filters = useStore((s) => s.filters);
|
||||
|
||||
@@ -1,3 +1,11 @@
|
||||
/**
|
||||
* @file GraphicsSettings.tsx
|
||||
* @module Panels/Settings
|
||||
* @description UI panel for managing CesiumJS engine performance and visual quality settings,
|
||||
* including resolution scaling, anti-aliasing, and lighting toggles.
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
"use client";
|
||||
|
||||
import React, { useEffect } from "react";
|
||||
@@ -5,6 +13,10 @@ import { useStore } from "@/core/state/store";
|
||||
import { trackEvent } from "@/lib/analytics";
|
||||
import "./graphics-settings.css";
|
||||
|
||||
/**
|
||||
* @constant DEFAULT_GRAPHICS
|
||||
* @description Fallback values for the graphics configuration.
|
||||
*/
|
||||
const DEFAULT_GRAPHICS = {
|
||||
resolutionScale: 1.0,
|
||||
enableFxaa: false,
|
||||
@@ -32,6 +44,11 @@ const AA_OPTIONS = [
|
||||
{ label: "MSAA 8× (Ultra)", value: "msaa8x" },
|
||||
];
|
||||
|
||||
/**
|
||||
* @component GraphicsSettings
|
||||
* @description Provides a granular interface for adjusting 3D engine performance.
|
||||
* Persists settings to browser cookies for session stability.
|
||||
*/
|
||||
export function GraphicsSettings() {
|
||||
const mapConfig = useStore((s) => s.mapConfig);
|
||||
const update = useStore((s) => s.updateMapConfig);
|
||||
|
||||
@@ -1,3 +1,11 @@
|
||||
/**
|
||||
* @file ImageryPicker.tsx
|
||||
* @module Panels/Settings
|
||||
* @description Interactive selector for switching base map providers (Imagery Layers)
|
||||
* and scene viewing modes (2D, 2.5D, 3D).
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
"use client";
|
||||
|
||||
import React from "react";
|
||||
@@ -7,6 +15,11 @@ import { Globe, Grid2X2, Layout, Layers } from "lucide-react";
|
||||
import { trackEvent } from "@/lib/analytics";
|
||||
import { GraphicsSettings } from "./GraphicsSettings";
|
||||
|
||||
/**
|
||||
* @component ImageryPicker
|
||||
* @description Renders a grid of imagery providers and view mode toggles.
|
||||
* Handles fallback states when premium imagery providers fail due to API key issues.
|
||||
*/
|
||||
export function ImageryPicker() {
|
||||
const baseLayerId = useStore((s) => s.mapConfig.baseLayerId);
|
||||
const fallbackLayerId = useStore((s) => s.mapConfig.fallbackLayerId);
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* @file LayerItem.tsx
|
||||
* @description Individual layer item component used within the LayerPanel.
|
||||
* Displays plugin metadata, status indicators, and toggle controls.
|
||||
* @module src/components/panels
|
||||
*/
|
||||
|
||||
import { ShieldAlert } from "lucide-react";
|
||||
import { PluginIcon } from "@/components/common/PluginIcon";
|
||||
import { Tooltip } from "@/components/ui/Tooltip";
|
||||
@@ -47,6 +54,17 @@ function TrustIcon({ trust }: { trust: TrustTier }) {
|
||||
|
||||
// ─── LayerItem Component ────────────────────────────────────
|
||||
|
||||
/**
|
||||
* @interface LayerItemProps
|
||||
* @description Properties for the LayerItem component.
|
||||
* @property {WorldPlugin} plugin - The plugin instance to represent.
|
||||
* @property {boolean} isEnabled - Whether the layer is currently active on the globe.
|
||||
* @property {boolean} isLoading - Whether the layer is currently fetching data.
|
||||
* @property {number} entityCount - The number of entities currently rendered for this layer.
|
||||
* @property {boolean} [isSelected] - Whether this layer is focused in the config panel.
|
||||
* @property {function} onToggle - Callback to toggle the layer's enabled state.
|
||||
* @property {function} [onSelect] - Callback to focus the layer in the config panel.
|
||||
*/
|
||||
interface LayerItemProps {
|
||||
plugin: WorldPlugin;
|
||||
isEnabled: boolean;
|
||||
@@ -57,6 +75,10 @@ interface LayerItemProps {
|
||||
onSelect?: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* @component LayerItem
|
||||
* @description A list item representing a single data layer with status feedback.
|
||||
*/
|
||||
export function LayerItem({
|
||||
plugin,
|
||||
isEnabled,
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* @file LayerPanel.tsx
|
||||
* @description Primary left-sidebar panel for managing data sources, imagery,
|
||||
* favorites, and plugin installations.
|
||||
* @module src/components/panels
|
||||
*/
|
||||
|
||||
import { useState } from "react";
|
||||
import { CircuitBoard, Download, DownloadCloud, Globe2, Puzzle, Search, Star } from "lucide-react";
|
||||
|
||||
@@ -18,6 +25,12 @@ import { trackEvent } from "@/lib/analytics";
|
||||
|
||||
import "./LayerPanel.css"
|
||||
|
||||
/**
|
||||
* @component LayerPanel
|
||||
* @description The main sidebar orchestration component for data navigation.
|
||||
* Manages tabs for layers, imagery, favorites, geojson imports, and plugins.
|
||||
* Handles the recursive search and categorization of active plugins.
|
||||
*/
|
||||
export function LayerPanel() {
|
||||
const isMobile = useIsMobile();
|
||||
const { width, startResizing } = useResizablePanel(280, 260, 800, 'left');
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* @file PluginsTab.tsx
|
||||
* @description Advanced management interface for the plugin ecosystem.
|
||||
* Handles discovery, installation, updates, and lifecycle management of
|
||||
* both built-in and marketplace plugins.
|
||||
* @module src/components/panels
|
||||
*/
|
||||
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import { Trash2, ExternalLink, RefreshCw, Download, PowerOff, Power } from "lucide-react";
|
||||
import { ShieldCheck, ShieldAlert, Shield } from "lucide-react";
|
||||
@@ -97,6 +105,12 @@ function getName(record: PluginRecord): string {
|
||||
|
||||
// ─── PluginsTab ─────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* @component PluginsTab
|
||||
* @description The marketplace and plugin management view.
|
||||
* Facilitates asynchronous plugin operations (install/uninstall/update)
|
||||
* and verifies integrity via trust badges.
|
||||
*/
|
||||
export function PluginsTab() {
|
||||
const [plugins, setPlugins] = useState<PluginRecord[]>([]);
|
||||
const [removing, setRemoving] = useState<string | null>(null);
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
/**
|
||||
* @file DynamicPropertiesRender.tsx
|
||||
* @description Heuristic-based property renderer that automatically detects
|
||||
* content types (images, URLs, long text) from raw entity properties.
|
||||
* @module src/components/panels/properties
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { GeoEntity } from '@worldwideview/wwv-plugin-sdk';
|
||||
import { ImageProperty } from './ImageProperty';
|
||||
@@ -5,6 +12,12 @@ import { UrlProperty } from './UrlProperty';
|
||||
import { LongTextProperty } from './LongTextProperty';
|
||||
import { IntelPropertyRow } from './IntelPropertyRow';
|
||||
|
||||
/**
|
||||
* @interface DynamicPropertiesRenderProps
|
||||
* @description Properties for the DynamicPropertiesRender component.
|
||||
* @property {GeoEntity} entity - The entity whose properties should be rendered.
|
||||
* @property {string} [classNamePrefix] - CSS class prefix for styling (defaults to "intel-panel").
|
||||
*/
|
||||
interface DynamicPropertiesRenderProps {
|
||||
entity: GeoEntity;
|
||||
classNamePrefix?: string;
|
||||
|
||||
@@ -1,7 +1,23 @@
|
||||
/**
|
||||
* @file ImageProperty.tsx
|
||||
* @description Specialized property renderer for image URLs.
|
||||
* Supports inline preview and popout to a floating window.
|
||||
* @module src/components/panels/properties
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { Maximize2 } from 'lucide-react';
|
||||
import { useStore } from '../../../core/state/store';
|
||||
|
||||
/**
|
||||
* @interface ImagePropertyProps
|
||||
* @description Properties for the ImageProperty component.
|
||||
* @property {string} label - The display name for the image.
|
||||
* @property {string} imageUrl - The URL of the image to display.
|
||||
* @property {string} entityId - The ID of the parent entity.
|
||||
* @property {string} [entityLabel] - The display label of the parent entity.
|
||||
* @property {string} [classNamePrefix] - CSS class prefix for styling (defaults to "intel-panel").
|
||||
*/
|
||||
interface ImagePropertyProps {
|
||||
label: string;
|
||||
imageUrl: string;
|
||||
|
||||
@@ -1,5 +1,20 @@
|
||||
/**
|
||||
* @file IntelPropertyRow.tsx
|
||||
* @description Base layout component for displaying key-value property rows
|
||||
* within entity information panels.
|
||||
* @module src/components/panels/properties
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
|
||||
/**
|
||||
* @interface IntelPropertyRowProps
|
||||
* @description Properties for the IntelPropertyRow component.
|
||||
* @property {string} label - The label for the property (the "key").
|
||||
* @property {boolean} [isColumn] - If true, renders the value below the label instead of beside it.
|
||||
* @property {string} [classNamePrefix] - CSS class prefix for styling (defaults to "intel-panel").
|
||||
* @property {React.ReactNode} children - The value content to display.
|
||||
*/
|
||||
interface IntelPropertyRowProps {
|
||||
label: string;
|
||||
isColumn?: boolean;
|
||||
|
||||
@@ -1,6 +1,20 @@
|
||||
/**
|
||||
* @file LongTextProperty.tsx
|
||||
* @description Specialized property renderer for long text blocks (descriptions, summaries).
|
||||
* Uses a column layout and handles overflow/scrolling for large amounts of text.
|
||||
* @module src/components/panels/properties
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { IntelPropertyRow } from './IntelPropertyRow';
|
||||
|
||||
/**
|
||||
* @interface LongTextPropertyProps
|
||||
* @description Properties for the LongTextProperty component.
|
||||
* @property {string} label - The display label for the text block.
|
||||
* @property {string} text - The long text content to display.
|
||||
* @property {string} [classNamePrefix] - CSS class prefix for styling (defaults to "intel-panel").
|
||||
*/
|
||||
interface LongTextPropertyProps {
|
||||
label: string;
|
||||
text: string;
|
||||
|
||||
@@ -1,6 +1,19 @@
|
||||
/**
|
||||
* @file TimestampProperty.tsx
|
||||
* @description Specialized property renderer for date/time values.
|
||||
* Allows users to toggle between local time and UTC.
|
||||
* @module src/components/panels/properties
|
||||
*/
|
||||
|
||||
import React, { useState } from 'react';
|
||||
import { IntelPropertyRow } from './IntelPropertyRow';
|
||||
|
||||
/**
|
||||
* @interface TimestampPropertyProps
|
||||
* @description Properties for the TimestampProperty component.
|
||||
* @property {string | number | Date} timestamp - The raw timestamp to display.
|
||||
* @property {string} [classNamePrefix] - CSS class prefix for styling (defaults to "intel-panel").
|
||||
*/
|
||||
interface TimestampPropertyProps {
|
||||
timestamp: string | number | Date;
|
||||
classNamePrefix?: string;
|
||||
|
||||
@@ -1,6 +1,20 @@
|
||||
/**
|
||||
* @file UrlProperty.tsx
|
||||
* @description Specialized property renderer for URLs.
|
||||
* Provides a clickable link and displays the raw URL in a monospace font.
|
||||
* @module src/components/panels/properties
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { ExternalLink } from 'lucide-react';
|
||||
|
||||
/**
|
||||
* @interface UrlPropertyProps
|
||||
* @description Properties for the UrlProperty component.
|
||||
* @property {string} label - The display label for the URL.
|
||||
* @property {string} url - The URL to link to.
|
||||
* @property {string} [classNamePrefix] - CSS class prefix for styling (defaults to "intel-panel").
|
||||
*/
|
||||
interface UrlPropertyProps {
|
||||
label: string;
|
||||
url: string;
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
/**
|
||||
* @file CacheLimitsTab.tsx
|
||||
* @module Panels/Tabs
|
||||
* @description Configuration interface for managing frontend data caching and request throttling.
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
import { useStore } from "@/core/state/store";
|
||||
|
||||
const sectionHeaderStyle: React.CSSProperties = {
|
||||
@@ -40,6 +47,11 @@ const checkboxStyle: React.CSSProperties = {
|
||||
accentColor: "var(--accent-cyan)",
|
||||
};
|
||||
|
||||
/**
|
||||
* @component CacheLimitsTab
|
||||
* @description Provides a management interface for the data engine's caching strategy,
|
||||
* including TTL settings and concurrent request limits to prevent network congestion.
|
||||
*/
|
||||
export function CacheLimitsTab() {
|
||||
const dataConfig = useStore((s) => s.dataConfig);
|
||||
const updateDataConfig = useStore((s) => s.updateDataConfig);
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
/**
|
||||
* @file IntelTab.tsx
|
||||
* @description Tab panel for displaying the "Intelligence" report for a selected entity.
|
||||
* Provides real-time positional data, plugin-specific properties, and camera action controls.
|
||||
* @module src/components/panels/tabs
|
||||
*/
|
||||
|
||||
import { useStore } from "@/core/state/store";
|
||||
import { pluginManager } from "@/core/plugins/PluginManager";
|
||||
import { PluginIcon } from "@/components/common/PluginIcon";
|
||||
@@ -17,6 +24,12 @@ const sectionHeaderStyle: React.CSSProperties = {
|
||||
paddingBottom: "var(--space-xs)"
|
||||
};
|
||||
|
||||
/**
|
||||
* @component IntelTab
|
||||
* @description Renders the intelligence dossier for the currently selected map entity.
|
||||
* Includes geographic coordinates, detailed properties, and action buttons for
|
||||
* camera manipulation (Face, Go To, Lock).
|
||||
*/
|
||||
export function IntelTab() {
|
||||
const selectedEntity = useStore((s) => s.selectedEntity);
|
||||
const lockedEntityId = useStore((s) => s.lockedEntityId);
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
/**
|
||||
* @file OverlayConfigTab.tsx
|
||||
* @description Configuration panel for managing layer-specific settings,
|
||||
* experimental features, and global polling intervals.
|
||||
* @module src/components/panels/tabs
|
||||
*/
|
||||
|
||||
import { useStore } from "@/core/state/store";
|
||||
import { pluginManager } from "@/core/plugins/PluginManager";
|
||||
|
||||
@@ -41,6 +48,11 @@ const checkboxStyle: React.CSSProperties = {
|
||||
accentColor: "var(--accent-cyan)",
|
||||
};
|
||||
|
||||
/**
|
||||
* @component OverlayConfigTab
|
||||
* @description Provides a granular interface for adjusting technical parameters
|
||||
* of active plugins, including polling frequencies and experimental data loading features.
|
||||
*/
|
||||
export function OverlayConfigTab() {
|
||||
const dataConfig = useStore((s) => s.dataConfig);
|
||||
const updateDataConfig = useStore((s) => s.updateDataConfig);
|
||||
|
||||
@@ -1,9 +1,23 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* @file Timeline.tsx
|
||||
* @description Application-wide temporal navigation controller.
|
||||
* Manages live/playback mode switching, time scrubbing, and
|
||||
* historical data availability visualization.
|
||||
* @module src/components/timeline
|
||||
*/
|
||||
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { useStore } from "@/core/state/store";
|
||||
import { isHistoryEnabled as default_isHistoryEnabled, isDemo, DEMO_ADMIN_ROLE } from "@/core/edition";
|
||||
|
||||
/**
|
||||
* @component Timeline
|
||||
* @description A horizontal navigation bar for controlling application time.
|
||||
* Features include playback speed controls, real-time mode toggles,
|
||||
* and a scrubbable track with data availability highlights.
|
||||
*/
|
||||
export function Timeline() {
|
||||
const currentTime = useStore((s) => s.currentTime);
|
||||
const isPlaying = useStore((s) => s.isPlaying);
|
||||
|
||||
@@ -1,10 +1,23 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* @file ErrorToast.tsx
|
||||
* @description Global error notification component.
|
||||
* Displays critical system errors or validation failures in a
|
||||
* non-blocking overlay with auto-dismiss functionality.
|
||||
* @module src/components/ui
|
||||
*/
|
||||
|
||||
import { useEffect } from "react";
|
||||
import { useStore } from "@/core/state/store";
|
||||
import { AlertTriangle, X } from "lucide-react";
|
||||
import styles from "./ErrorToast.module.css";
|
||||
|
||||
/**
|
||||
* @component ErrorToast
|
||||
* @description Renders a dismissible error message anchored to the viewport.
|
||||
* Automatically clears after a timeout via the Zustand global store.
|
||||
*/
|
||||
export default function ErrorToast() {
|
||||
const errorToastMessage = useStore((state) => state.errorToastMessage);
|
||||
const clearErrorToast = useStore((state) => state.clearErrorToast);
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* @file ReloadToast.tsx
|
||||
* @description Life-cycle notification for runtime updates.
|
||||
* Prompts the user for a manual refresh when dynamic changes (like
|
||||
* plugin installs) require a fresh application state.
|
||||
* @module src/components/ui
|
||||
*/
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import styles from "./ReloadToast.module.css";
|
||||
@@ -9,9 +17,12 @@ interface ReloadToastProps {
|
||||
}
|
||||
|
||||
/**
|
||||
* Floating toast prompting user to reload after plugin changes.
|
||||
* Dismissible, with a Reload button that triggers a full page refresh.
|
||||
* Rendered via portal to escape panel boundaries and z-index contexts.
|
||||
* @component ReloadToast
|
||||
* @description Floating toast prompting user to reload after plugin changes.
|
||||
* Rendered via React Portal to ensure visibility above all UI layers.
|
||||
*
|
||||
* @param {ReloadToastProps} props - Component properties.
|
||||
* @param {string} [props.message] - Custom message to display.
|
||||
*/
|
||||
export default function ReloadToast({ message }: ReloadToastProps) {
|
||||
const [dismissed, setDismissed] = useState(false);
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* @file Tooltip.tsx
|
||||
* @description Lightweight accessibility-focused tooltip system.
|
||||
* Uses React Portals for overflow safety and features smart positioning
|
||||
* with configurable delay and hover/focus triggers.
|
||||
* @module src/components/ui
|
||||
*/
|
||||
|
||||
import React, { useState, useRef, useEffect } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
|
||||
@@ -9,6 +17,15 @@ interface TooltipProps {
|
||||
delay?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* @component Tooltip
|
||||
* @description Renders a floating content box near a target element on hover/focus.
|
||||
*
|
||||
* @param {TooltipProps} props - Component properties.
|
||||
* @param {React.ReactNode} props.children - The trigger element.
|
||||
* @param {React.ReactNode} props.content - Content to display inside the tooltip.
|
||||
* @param {number} [props.delay=300] - Delay in ms before showing the tooltip.
|
||||
*/
|
||||
export function Tooltip({ children, content, delay = 300 }: TooltipProps) {
|
||||
const [visible, setVisible] = useState(false);
|
||||
const [coords, setCoords] = useState({ top: 0, left: 0 });
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* @file CameraStream.tsx
|
||||
* @description Robust multi-format video streaming component.
|
||||
* Supports HLS, MJPEG, YouTube/Twitch iframes, and static image fallback
|
||||
* with automatic proxying and temporal cache-busting.
|
||||
* @module src/components/video
|
||||
*/
|
||||
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { Play, Square, Loader2, AlertCircle, ExternalLink, Maximize2 } from "lucide-react";
|
||||
import { useStore } from "@/core/state/store";
|
||||
@@ -7,15 +15,30 @@ import { HlsPlayer } from "./HlsPlayer";
|
||||
import { isHlsUrl, isKnownVideoPlatform, getYouTubeEmbedUrl, getStreamErrorMessage, getProxiedStreamUrl, getProxiedIframeUrl } from "./streamUtils";
|
||||
import { PannableView } from "@/components/common/PannableView";
|
||||
|
||||
interface CameraStreamProps {
|
||||
/**
|
||||
* Properties for the CameraStream component.
|
||||
*/
|
||||
export interface CameraStreamProps {
|
||||
/** The URL of the video stream or static source. */
|
||||
streamUrl: string;
|
||||
/** Optional static image to display before playback starts. */
|
||||
previewUrl?: string;
|
||||
/** Whether to force iframe rendering for the source. */
|
||||
isIframe?: boolean;
|
||||
/** Human-readable label for the stream, shown in tooltips. */
|
||||
label?: string;
|
||||
/** Optional CSS class name for styling the container. */
|
||||
className?: string;
|
||||
/** Unique identifier for the stream instance. */
|
||||
id?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* @component CameraStream
|
||||
* @description A high-performance video player for live sensor data.
|
||||
*
|
||||
* @param props - Component properties.
|
||||
*/
|
||||
export const CameraStream: React.FC<CameraStreamProps> = ({
|
||||
streamUrl, previewUrl, isIframe = false, label, className = "", id,
|
||||
}) => {
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* @file FloatingVideoManager.tsx
|
||||
* @description Orchestrator for multiple floating video/image feeds.
|
||||
* Manages the lifecycle and spatial state of draggable camera windows
|
||||
* across the viewport.
|
||||
* @module src/components/video
|
||||
*/
|
||||
|
||||
import React, { useEffect, useRef } from "react";
|
||||
import { useStore } from "@/core/state/store";
|
||||
import { FloatingWindow } from "@/components/common/FloatingWindow";
|
||||
@@ -7,6 +15,11 @@ import { CameraStream } from "./CameraStream";
|
||||
import { PannableView } from "@/components/common/PannableView";
|
||||
import { trackEvent } from "@/lib/analytics";
|
||||
|
||||
/**
|
||||
* @component FloatingVideoManager
|
||||
* @description A controller component that renders all active floating streams.
|
||||
* Integrates with the global store to track and update window positions/sizes.
|
||||
*/
|
||||
export const FloatingVideoManager: React.FC = () => {
|
||||
const { floatingStreams, removeFloatingStream, updateFloatingStream } = useStore();
|
||||
const trackedIds = useRef<Set<string>>(new Set());
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* @file HlsPlayer.tsx
|
||||
* @description specialized player for HTTP Live Streaming (.m3u8).
|
||||
* Leverages native Safari/iOS support and falls back to dynamic hls.js
|
||||
* loading for other environments.
|
||||
* @module src/components/video
|
||||
*/
|
||||
|
||||
import React, { useRef, useEffect, useCallback } from "react";
|
||||
|
||||
interface HlsPlayerProps {
|
||||
@@ -9,10 +17,13 @@ interface HlsPlayerProps {
|
||||
}
|
||||
|
||||
/**
|
||||
* Video player that handles HLS (.m3u8) streams.
|
||||
*
|
||||
* - Safari/iOS: uses native HLS support via <video>.
|
||||
* - Other browsers: dynamically imports hls.js to demux the stream.
|
||||
* @component HlsPlayer
|
||||
* @description A high-performance HLS playback engine.
|
||||
*
|
||||
* @param {HlsPlayerProps} props - Component properties.
|
||||
* @param {string} props.src - The HLS (.m3u8) source URL.
|
||||
* @param {() => void} [props.onReady] - Callback triggered when playback begins.
|
||||
* @param {(msg: string) => void} [props.onError] - Callback triggered on fatal errors.
|
||||
*/
|
||||
export const HlsPlayer: React.FC<HlsPlayerProps> = ({ src, onReady, onError }) => {
|
||||
const videoRef = useRef<HTMLVideoElement>(null);
|
||||
|
||||
@@ -1,15 +1,25 @@
|
||||
/**
|
||||
* Utility functions for stream URL detection and error messaging.
|
||||
* @file streamUtils.ts
|
||||
* @description specialized utilities for detecting, transforming, and
|
||||
* proxying video streams to ensure cross-origin compatibility and
|
||||
* playback stability.
|
||||
* @module src/components/video
|
||||
*/
|
||||
|
||||
/** Returns true if the URL points to an HLS manifest (.m3u8). */
|
||||
/**
|
||||
* Returns true if the URL points to an HLS manifest (.m3u8).
|
||||
* @param {string} url - The URL to check.
|
||||
*/
|
||||
export function isHlsUrl(url: string): boolean {
|
||||
if (!url) return false;
|
||||
const lower = url.toLowerCase();
|
||||
return lower.endsWith(".m3u8") || lower.includes(".m3u8?");
|
||||
}
|
||||
|
||||
/** Returns true if the URL belongs to a known embeddable video platform. */
|
||||
/**
|
||||
* Returns true if the URL belongs to a known embeddable video platform.
|
||||
* @param {string} url - The URL to check.
|
||||
*/
|
||||
export function isKnownVideoPlatform(url: string): boolean {
|
||||
if (!url) return false;
|
||||
const lower = url.toLowerCase();
|
||||
@@ -29,7 +39,10 @@ export function isKnownVideoPlatform(url: string): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
/** Convert a YouTube watch / short URL into an embeddable URL with autoplay. */
|
||||
/**
|
||||
* Convert a YouTube watch / short URL into an embeddable URL with autoplay.
|
||||
* @param {string} url - The raw YouTube URL.
|
||||
*/
|
||||
export function getYouTubeEmbedUrl(url: string): string {
|
||||
if (!url) return url;
|
||||
if (
|
||||
@@ -65,6 +78,7 @@ export function getYouTubeEmbedUrl(url: string): string {
|
||||
/**
|
||||
* Proxy stream URLs through our server-side proxy to avoid mixed-content blocks
|
||||
* and bypass restrictive CORS policies from camera providers.
|
||||
* @param {string} url - The raw stream URL.
|
||||
*/
|
||||
export function getProxiedStreamUrl(url: string): string {
|
||||
if (!url) return url;
|
||||
@@ -76,13 +90,17 @@ export function getProxiedStreamUrl(url: string): string {
|
||||
/**
|
||||
* Proxy iframe HTML to inject <base> tags and strip X-Frame-Options / CSP headers
|
||||
* that prevent embedding.
|
||||
* @param {string} url - The iframe source URL.
|
||||
*/
|
||||
export function getProxiedIframeUrl(url: string): string {
|
||||
if (!url) return url;
|
||||
return `/api/camera/proxy/iframe?url=${encodeURIComponent(url)}`;
|
||||
}
|
||||
|
||||
/** Return a user-friendly error message for a failed stream URL. */
|
||||
/**
|
||||
* Return a user-friendly error message for a failed stream URL.
|
||||
* @param {string} streamUrl - The URL that failed.
|
||||
*/
|
||||
export function getStreamErrorMessage(streamUrl: string): string {
|
||||
if (
|
||||
streamUrl.startsWith("http://") &&
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
|
||||
import { cacheLayer } from "./CacheLayer";
|
||||
import type { GeoEntity } from "@/core/plugins/PluginTypes";
|
||||
|
||||
/**
|
||||
* In-memory cache contract. The persistent (IndexedDB) layer needs a
|
||||
* real browser and isn't exercised here — these tests cover only the
|
||||
* Map-backed first tier that every plugin enable/disable cycle hits.
|
||||
*
|
||||
* We `clear()` between tests because cacheLayer is a process-wide
|
||||
* singleton; without it, residual entries from one test would mask
|
||||
* failures in another.
|
||||
*/
|
||||
|
||||
function entity(id: string): GeoEntity {
|
||||
return {
|
||||
id,
|
||||
pluginId: "test",
|
||||
latitude: 0,
|
||||
longitude: 0,
|
||||
timestamp: new Date(),
|
||||
properties: {},
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
cacheLayer.clear();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("CacheLayer (memory tier)", () => {
|
||||
it("round-trips entities by pluginId within the TTL window", () => {
|
||||
const entities = [entity("a"), entity("b")];
|
||||
cacheLayer.set("aviation", entities, 60_000);
|
||||
|
||||
expect(cacheLayer.get("aviation")).toEqual(entities);
|
||||
});
|
||||
|
||||
it("returns null and evicts the entry once the TTL expires", () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date("2026-01-01T00:00:00Z"));
|
||||
|
||||
cacheLayer.set("aviation", [entity("a")], 5_000);
|
||||
expect(cacheLayer.get("aviation")).not.toBeNull();
|
||||
|
||||
vi.advanceTimersByTime(5_001);
|
||||
expect(cacheLayer.get("aviation")).toBeNull();
|
||||
|
||||
// Second get confirms the eviction happened — the entry is gone
|
||||
// from the underlying Map, not just rejected on lookup.
|
||||
expect(cacheLayer.get("aviation")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, it, expect, vi, afterEach } from "vitest";
|
||||
import { dataBus } from "./DataBus";
|
||||
|
||||
/**
|
||||
* DataBus is a typed singleton event bus used by every plugin and most
|
||||
* of the UI for cross-component communication. A regression here would
|
||||
* be silent and immediate — events stop arriving, layers go blank, the
|
||||
* agent bus stops responding — so it's worth pinning down the basics.
|
||||
*
|
||||
* Each test removes the listeners it adds in `afterEach` so the
|
||||
* singleton state doesn't leak between tests.
|
||||
*/
|
||||
|
||||
afterEach(() => {
|
||||
dataBus.removeAllListeners();
|
||||
});
|
||||
|
||||
describe("DataBus", () => {
|
||||
it("dispatches emit() payloads to subscribers of the matching event", () => {
|
||||
const handler = vi.fn();
|
||||
dataBus.on("dataUpdated", handler);
|
||||
|
||||
dataBus.emit("dataUpdated", { pluginId: "test", entities: [] });
|
||||
|
||||
expect(handler).toHaveBeenCalledTimes(1);
|
||||
expect(handler).toHaveBeenCalledWith({ pluginId: "test", entities: [] });
|
||||
});
|
||||
|
||||
it("returns an unsubscribe function from on() that detaches the handler", () => {
|
||||
const handler = vi.fn();
|
||||
const unsubscribe = dataBus.on("dataUpdated", handler);
|
||||
|
||||
unsubscribe();
|
||||
dataBus.emit("dataUpdated", { pluginId: "test", entities: [] });
|
||||
|
||||
expect(handler).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("isolates handler failures so one throw doesn't block other subscribers", () => {
|
||||
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const throwing = vi.fn(() => {
|
||||
throw new Error("intentional");
|
||||
});
|
||||
const surviving = vi.fn();
|
||||
dataBus.on("layerToggled", throwing);
|
||||
dataBus.on("layerToggled", surviving);
|
||||
|
||||
dataBus.emit("layerToggled", { pluginId: "test", enabled: true });
|
||||
|
||||
expect(throwing).toHaveBeenCalledTimes(1);
|
||||
expect(surviving).toHaveBeenCalledTimes(1);
|
||||
errorSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
|
||||
|
||||
// The store import in PollingManager's constructor pulls in Cesium,
|
||||
// zustand middleware, and the entire UI state tree. Mock it before the
|
||||
// module loads so the polling-manager singleton wakes up against a
|
||||
// shape that's safe in jsdom.
|
||||
vi.mock("@/core/state/store", () => ({
|
||||
useStore: {
|
||||
getState: () => ({ dataConfig: { pollingIntervals: {} } }),
|
||||
subscribe: () => () => {},
|
||||
},
|
||||
}));
|
||||
|
||||
import { pollingManager } from "./PollingManager";
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Clean up timers and any tasks registered in this test so the next
|
||||
// one starts from a known state. The singleton doesn't expose a
|
||||
// reset method, but `stopAll` + `unregister` covers our cases.
|
||||
pollingManager.stopAll();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
// Helper: drain the microtask queue so the immediate `run()` Promise
|
||||
// scheduled inside `start()` resolves before we assert on call counts.
|
||||
// We can't use `runAllTimersAsync` here because setInterval is unbounded
|
||||
// and `runOnlyPendingTimersAsync` advances the next interval tick too,
|
||||
// which would double-count.
|
||||
async function flushMicrotasks() {
|
||||
for (let i = 0; i < 5; i++) await Promise.resolve();
|
||||
}
|
||||
|
||||
describe("PollingManager", () => {
|
||||
it("runs the callback once immediately when start() is called", async () => {
|
||||
const callback = vi.fn(async () => {});
|
||||
pollingManager.register("test", 60_000, callback);
|
||||
|
||||
pollingManager.start("test");
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("schedules recurring calls at intervalMs after the initial run", async () => {
|
||||
const callback = vi.fn(async () => {});
|
||||
pollingManager.register("test", 1_000, callback);
|
||||
|
||||
pollingManager.start("test");
|
||||
await flushMicrotasks();
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1_000);
|
||||
expect(callback).toHaveBeenCalledTimes(2);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(2_000);
|
||||
expect(callback).toHaveBeenCalledTimes(4);
|
||||
});
|
||||
|
||||
it("stops scheduling further calls after stop()", async () => {
|
||||
const callback = vi.fn(async () => {});
|
||||
pollingManager.register("test", 1_000, callback);
|
||||
|
||||
pollingManager.start("test");
|
||||
await flushMicrotasks();
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
|
||||
pollingManager.stop("test");
|
||||
await vi.advanceTimersByTimeAsync(10_000);
|
||||
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { applyFilters } from "./filterEngine";
|
||||
import type { GeoEntity, FilterDefinition, FilterValue } from "@/core/plugins/PluginTypes";
|
||||
|
||||
/**
|
||||
* Helper to keep the fixture set small and on-spec. `GeoEntity` requires
|
||||
* `latitude`, `longitude`, `timestamp`, and `properties`; everything
|
||||
* else (label, altitude, heading, speed) is optional. We omit the
|
||||
* optional fields except where a specific test exercises them.
|
||||
*/
|
||||
function entity(overrides: Partial<GeoEntity> & Pick<GeoEntity, "id" | "pluginId" | "properties">): GeoEntity {
|
||||
return {
|
||||
latitude: 0,
|
||||
longitude: 0,
|
||||
timestamp: new Date(0),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("applyFilters", () => {
|
||||
it("returns the original array unchanged when no active filters are provided", () => {
|
||||
const entities: GeoEntity[] = [
|
||||
entity({ id: "1", pluginId: "test", properties: {} }),
|
||||
entity({ id: "2", pluginId: "test", properties: {} }),
|
||||
];
|
||||
|
||||
expect(applyFilters(entities, [], {})).toEqual(entities);
|
||||
});
|
||||
|
||||
it("returns a subset (or equal) of the input when filtering by text", () => {
|
||||
const entities: GeoEntity[] = [
|
||||
entity({ id: "1", pluginId: "test", label: "alpha", properties: { name: "alpha" } }),
|
||||
entity({ id: "2", pluginId: "test", label: "beta", properties: { name: "beta" } }),
|
||||
entity({ id: "3", pluginId: "test", label: "gamma", properties: { name: "gamma" } }),
|
||||
];
|
||||
const definitions: FilterDefinition[] = [
|
||||
{ id: "name", label: "Name", type: "text", propertyKey: "name" },
|
||||
];
|
||||
const activeFilters: Record<string, FilterValue> = {
|
||||
name: { type: "text", value: "a" },
|
||||
};
|
||||
|
||||
const result = applyFilters(entities, definitions, activeFilters);
|
||||
|
||||
expect(result.length).toBeLessThanOrEqual(entities.length);
|
||||
for (const item of result) expect(entities).toContainEqual(item);
|
||||
});
|
||||
|
||||
it("handles each filter type and the missing-definition / unknown-type fallbacks", () => {
|
||||
const entities: GeoEntity[] = [
|
||||
entity({
|
||||
id: "1",
|
||||
pluginId: "test",
|
||||
label: "test1",
|
||||
properties: { category: "A", speed: 50, active: true, invalidNum: "NaN" },
|
||||
}),
|
||||
entity({
|
||||
id: "2",
|
||||
pluginId: "test",
|
||||
label: "test2",
|
||||
properties: { category: "B", speed: 100, active: false, noProp: undefined },
|
||||
}),
|
||||
];
|
||||
|
||||
// 1. Missing definition — filter is silently ignored
|
||||
expect(
|
||||
applyFilters(entities, [], { missing: { type: "boolean", value: true } }),
|
||||
).toEqual(entities);
|
||||
|
||||
// 2. Select filter
|
||||
const selectDef: FilterDefinition = {
|
||||
id: "cat",
|
||||
label: "Category",
|
||||
type: "select",
|
||||
propertyKey: "category",
|
||||
};
|
||||
expect(applyFilters(entities, [selectDef], { cat: { type: "select", values: ["A"] } })).toEqual([
|
||||
entities[0],
|
||||
]);
|
||||
expect(applyFilters(entities, [selectDef], { cat: { type: "select", values: [] } })).toEqual(
|
||||
entities,
|
||||
); // empty select == no filter
|
||||
expect(applyFilters(entities, [selectDef], { cat: { type: "select", values: ["C"] } })).toEqual(
|
||||
[],
|
||||
);
|
||||
|
||||
// 3. Range filter — note: `range` is a NESTED config on FilterDefinition
|
||||
const rangeDef: FilterDefinition = {
|
||||
id: "spd",
|
||||
label: "Speed",
|
||||
type: "range",
|
||||
propertyKey: "speed",
|
||||
range: { min: 0, max: 200, step: 1 },
|
||||
};
|
||||
expect(applyFilters(entities, [rangeDef], { spd: { type: "range", min: 60, max: 150 } })).toEqual(
|
||||
[entities[1]],
|
||||
);
|
||||
|
||||
const invalidRangeDef: FilterDefinition = {
|
||||
id: "inv",
|
||||
label: "Invalid",
|
||||
type: "range",
|
||||
propertyKey: "invalidNum",
|
||||
range: { min: 0, max: 200, step: 1 },
|
||||
};
|
||||
// entities[0] has invalidNum: "NaN" → fails; entities[1] has it undefined → 0 → matches
|
||||
expect(
|
||||
applyFilters(entities, [invalidRangeDef], { inv: { type: "range", min: 0, max: 100 } }),
|
||||
).toEqual([entities[1]]);
|
||||
|
||||
// 4. Boolean filter
|
||||
const boolDef: FilterDefinition = {
|
||||
id: "act",
|
||||
label: "Active",
|
||||
type: "boolean",
|
||||
propertyKey: "active",
|
||||
};
|
||||
expect(applyFilters(entities, [boolDef], { act: { type: "boolean", value: false } })).toEqual([
|
||||
entities[1],
|
||||
]);
|
||||
|
||||
// 5. Unknown filter type — falls through unchanged
|
||||
const unknownDef: FilterDefinition = {
|
||||
id: "unk",
|
||||
label: "Unknown",
|
||||
type: "unknown" as unknown as FilterDefinition["type"],
|
||||
propertyKey: "active",
|
||||
};
|
||||
expect(
|
||||
applyFilters(entities, [unknownDef], {
|
||||
unk: { type: "unknown" as unknown as FilterValue["type"] } as unknown as FilterValue,
|
||||
}),
|
||||
).toEqual(entities);
|
||||
|
||||
// 6. Text filter with empty value — no filtering
|
||||
const textDef: FilterDefinition = {
|
||||
id: "txt",
|
||||
label: "Text",
|
||||
type: "text",
|
||||
propertyKey: "label",
|
||||
};
|
||||
expect(applyFilters(entities, [textDef], { txt: { type: "text", value: "" } })).toEqual(
|
||||
entities,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,8 @@
|
||||
// ─── Installed Plugins Loader ────────────────────────────────
|
||||
// Scans data/plugins/ at startup for previously installed plugin manifests.
|
||||
// Validates each and registers with PluginManager.
|
||||
/**
|
||||
* @file InstalledPluginsLoader.ts
|
||||
* @description Scans the database for previously installed marketplace plugins,
|
||||
* parses their stored manifests, and registers them with the PluginManager.
|
||||
*/
|
||||
|
||||
import type { PluginManifest } from "@/core/plugins/PluginManifest";
|
||||
import { validateManifest } from "@/core/plugins/validateManifest";
|
||||
@@ -8,9 +10,13 @@ import { pluginManager } from "@/core/plugins/PluginManager";
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
/**
|
||||
* Load all marketplace-installed plugins from the database.
|
||||
* Reads InstalledPlugin records | parses stored config as manifest | registers each.
|
||||
* Errors are logged but never thrown — invalid plugins are skipped.
|
||||
* Loads all marketplace-installed plugins from the persistent database store.
|
||||
* This is a critical bootstrap phase for the "Local" and "Cloud" editions,
|
||||
* ensuring that user-installed layers are restored across server restarts
|
||||
* and browser refreshes. It handles the full hydration cycle: DB fetch ->
|
||||
* manifest parse -> validation -> PluginManager registration.
|
||||
*
|
||||
* @returns A promise resolving to the number of successfully hydrated plugins.
|
||||
*/
|
||||
export async function loadInstalledPlugins(): Promise<number> {
|
||||
let loaded = 0;
|
||||
@@ -53,10 +59,20 @@ export async function loadInstalledPlugins(): Promise<number> {
|
||||
return loaded;
|
||||
}
|
||||
|
||||
/** Parse the stored config JSON as a PluginManifest. */
|
||||
/**
|
||||
* Sanitizes and parses a stored configuration string into a PluginManifest.
|
||||
* This acts as an adapter layer, ensuring that legacy database records or
|
||||
* records missing explicit IDs are coerced into the correct runtime manifest
|
||||
* format before being passed to the validation engine.
|
||||
*
|
||||
* @param pluginId - The unique ID of the plugin from the database record key.
|
||||
* @param config - The stringified JSON configuration blob stored in the database.
|
||||
* @returns The parsed and coerced PluginManifest, or null if the JSON is malformed.
|
||||
*/
|
||||
function parseConfig(pluginId: string, config: string): PluginManifest | null {
|
||||
try {
|
||||
const parsed = JSON.parse(config);
|
||||
// Ensure the ID from the DB record is reflected in the manifest if missing
|
||||
if (!parsed.id) parsed.id = pluginId;
|
||||
return parsed as PluginManifest;
|
||||
} catch {
|
||||
|
||||
@@ -14,6 +14,11 @@ import { trackEvent } from "@/lib/analytics";
|
||||
import { resolveEngineUrl } from "@/core/data/resolveEngineUrl";
|
||||
import { fetchLocalEngineManifest } from "@/core/data/engineManifest";
|
||||
|
||||
/**
|
||||
* ManagedPlugin represents the internal state and instance of a registered data source.
|
||||
* It wraps the raw WorldPlugin with system-level tracking for its enabled status,
|
||||
* current data snapshot (entities), and the execution context provided by the manager.
|
||||
*/
|
||||
interface ManagedPlugin {
|
||||
plugin: WorldPlugin;
|
||||
enabled: boolean;
|
||||
@@ -22,9 +27,10 @@ interface ManagedPlugin {
|
||||
}
|
||||
|
||||
/**
|
||||
* Plugin lifecycle manager.
|
||||
* Handles: register → initialize → enable/disable → destroy
|
||||
* Routes data from plugins → store → LayerRenderer
|
||||
* PluginManager is the central orchestrator for the entire data ingestion pipeline.
|
||||
* It is responsible for the full lifecycle of data sources—from initial registration
|
||||
* and environment injection to polling orchestration, data caching, and routing
|
||||
* snapshots to the global state and event bus.
|
||||
*/
|
||||
class PluginManager {
|
||||
private plugins: Map<string, ManagedPlugin> = new Map();
|
||||
@@ -32,12 +38,28 @@ class PluginManager {
|
||||
private initialized = false;
|
||||
private configCacheMaxAge = 3600000;
|
||||
|
||||
/**
|
||||
* Initializes the PluginManager and prepares the persistent cache layer.
|
||||
* This must be called before any plugins are enabled to ensure that
|
||||
* initial data hydration from IndexedDB/Localstorage is possible.
|
||||
*
|
||||
* @returns A promise that resolves once the cache layer is ready.
|
||||
*/
|
||||
async init(): Promise<void> {
|
||||
if (this.initialized) return;
|
||||
await cacheLayer.init();
|
||||
this.initialized = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a new plugin and establishes its execution environment.
|
||||
* This method is responsible for injecting `NEXT_PUBLIC_WWV_PLUGIN_*` environment
|
||||
* variables, resolving the correct Data Engine URLs, and setting up the
|
||||
* pub/sub routing for the plugin's data updates and error telemetry.
|
||||
*
|
||||
* @param plugin - The WorldPlugin instance to onboard into the manager.
|
||||
* @returns A promise that resolves when initialization and polling registration are complete.
|
||||
*/
|
||||
async registerPlugin(plugin: WorldPlugin): Promise<void> {
|
||||
if (this.plugins.has(plugin.id)) {
|
||||
console.warn(`[PluginManager] Plugin "${plugin.id}" already registered`);
|
||||
@@ -147,6 +169,14 @@ class PluginManager {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Activates a plugin and initiates its data retrieval cycle.
|
||||
* This method attempts an immediate cache hydration to ensure the UI feels
|
||||
* instantaneous, then signals the polling manager to begin background fetching.
|
||||
*
|
||||
* @param pluginId - The unique identifier of the plugin to enable.
|
||||
* @returns A promise that resolves when the plugin status is updated and cached data is emitted.
|
||||
*/
|
||||
async enablePlugin(pluginId: string): Promise<void> {
|
||||
const start = performance.now();
|
||||
console.debug(`[PluginManager] enablePlugin called for ${pluginId}`);
|
||||
@@ -181,6 +211,13 @@ class PluginManager {
|
||||
dataBus.emit("layerToggled", { pluginId, enabled: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* Deactivates a plugin and ceases all background activity.
|
||||
* This stops the polling cycle, clears in-memory entity buffers, and
|
||||
* notifies the UI to remove the corresponding layer from the globe.
|
||||
*
|
||||
* @param pluginId - The unique identifier of the plugin to disable.
|
||||
*/
|
||||
disablePlugin(pluginId: string): void {
|
||||
console.debug(`[PluginManager] disablePlugin called for ${pluginId}`);
|
||||
const managed = this.plugins.get(pluginId);
|
||||
@@ -196,6 +233,12 @@ class PluginManager {
|
||||
dataBus.emit("dataUpdated", { pluginId, entities: [] });
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience method to toggle a plugin's enabled state.
|
||||
* Primarily used by UI switch components in the Layers or Marketplace panels.
|
||||
*
|
||||
* @param pluginId - The ID of the plugin to toggle.
|
||||
*/
|
||||
togglePlugin(pluginId: string): void {
|
||||
const managed = this.plugins.get(pluginId);
|
||||
if (!managed) return;
|
||||
@@ -206,6 +249,15 @@ class PluginManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Manually triggers a data fetch for a plugin, bypassing the polling interval.
|
||||
* Useful for timeline scrubbing, playback, or on-demand refreshes when
|
||||
* the user interacts with specific time windows.
|
||||
*
|
||||
* @param pluginId - The ID of the plugin to refresh.
|
||||
* @param timeRange - The new temporal window for the data request.
|
||||
* @returns A promise that resolves when the new data is fetched and processed.
|
||||
*/
|
||||
async fetchForPlugin(pluginId: string, timeRange: TimeRange): Promise<void> {
|
||||
const managed = this.plugins.get(pluginId);
|
||||
if (!managed || !managed.enabled) return;
|
||||
@@ -214,26 +266,66 @@ class PluginManager {
|
||||
this.handleDataUpdate(pluginId, entities);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the management wrapper for a specific plugin ID.
|
||||
* Used internally by rendering components to check individual plugin state.
|
||||
*
|
||||
* @param pluginId - The unique ID of the plugin.
|
||||
* @returns The ManagedPlugin state object or undefined.
|
||||
*/
|
||||
getPlugin(pluginId: string): ManagedPlugin | undefined {
|
||||
return this.plugins.get(pluginId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a collection of all managed plugins in the system.
|
||||
*
|
||||
* @returns An array of all ManagedPlugin instances.
|
||||
*/
|
||||
getAllPlugins(): ManagedPlugin[] {
|
||||
return Array.from(this.plugins.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all currently active and enabled plugins.
|
||||
* This is the source for the global rendering loop to determine which
|
||||
* layers should be active on the globe.
|
||||
*
|
||||
* @returns An array of enabled ManagedPlugin instances.
|
||||
*/
|
||||
getEnabledPlugins(): ManagedPlugin[] {
|
||||
return this.getAllPlugins().filter((p) => p.enabled);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current entity snapshot for a specific plugin.
|
||||
*
|
||||
* @param pluginId - The ID of the plugin.
|
||||
* @returns An array of current GeoEntities for that plugin.
|
||||
*/
|
||||
getEntities(pluginId: string): GeoEntity[] {
|
||||
return this.plugins.get(pluginId)?.entities ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Aggregates all entities from all enabled plugins into a single array.
|
||||
* Used by global analytics or debugging tools to see the entire visible
|
||||
* geospatial dataset.
|
||||
*
|
||||
* @returns A flattened array of all visible GeoEntities.
|
||||
*/
|
||||
getAllEntities(): GeoEntity[] {
|
||||
return this.getEnabledPlugins().flatMap((p) => p.entities);
|
||||
}
|
||||
|
||||
/**
|
||||
* Synchronously updates the time range for all enabled plugins.
|
||||
* Used during global timeline changes or playback to ensure all data
|
||||
* sources are reflecting the same temporal slice.
|
||||
*
|
||||
* @param timeRange - The global time range to apply.
|
||||
* @returns A promise that settles after all fetch attempts are complete.
|
||||
*/
|
||||
async updateTimeRange(timeRange: TimeRange): Promise<void> {
|
||||
const promises = this.getEnabledPlugins().map((managed) =>
|
||||
this.fetchForPlugin(managed.plugin.id, timeRange)
|
||||
@@ -241,13 +333,25 @@ class PluginManager {
|
||||
await Promise.allSettled(promises);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the global maximum age for the data config cache.
|
||||
* Determines how long entities remain in the fast-access cache layer
|
||||
* before requiring a fresh fetch.
|
||||
*
|
||||
* @param age - Maximum cache lifetime in milliseconds.
|
||||
*/
|
||||
setCacheMaxAge(age: number): void {
|
||||
this.configCacheMaxAge = age;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a plugin from a PluginManifest.
|
||||
* Validates, instantiates the correct loader, and registers it.
|
||||
* Resolves a plugin manifest into a live instance and registers it.
|
||||
* This is the core engine for the marketplace and dynamic loading,
|
||||
* instantiating the correct loader strategy (Static, Proxied, etc.)
|
||||
* based on the manifest declarations.
|
||||
*
|
||||
* @param manifest - The PluginManifest configuration to load.
|
||||
* @returns A promise that resolves when the plugin is fully registered and initialized.
|
||||
*/
|
||||
async loadFromManifest(manifest: PluginManifest): Promise<void> {
|
||||
const plugin = await loadPluginFromManifest(manifest);
|
||||
@@ -259,10 +363,23 @@ class PluginManager {
|
||||
await this.registerPlugin(plugin);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the original manifest used to load a specific plugin.
|
||||
* Useful for checking plugin capabilities or marketplace metadata
|
||||
* after the plugin has been instantiated.
|
||||
*
|
||||
* @param pluginId - The ID of the plugin.
|
||||
* @returns The PluginManifest if available, otherwise undefined.
|
||||
*/
|
||||
getManifest(pluginId: string): PluginManifest | undefined {
|
||||
return this.loadedManifests.get(pluginId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tears down the entire plugin management system.
|
||||
* Stops all polling, calls destroy on all plugins, and clears the registry.
|
||||
* Essential for hot-module reloading and clean application shutdown.
|
||||
*/
|
||||
destroy(): void {
|
||||
pollingManager.stopAll();
|
||||
this.plugins.forEach((managed) => {
|
||||
@@ -275,6 +392,14 @@ class PluginManager {
|
||||
this.plugins.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Orchestrates the internal data flow when a plugin receives new entities.
|
||||
* This updates the in-memory cache, commits to the persistent cache layer,
|
||||
* emits to the DataBus, and clears the loading state in the UI.
|
||||
*
|
||||
* @param pluginId - The ID of the plugin providing the update.
|
||||
* @param entities - The new array of GeoEntities.
|
||||
*/
|
||||
private handleDataUpdate(pluginId: string, entities: GeoEntity[]): void {
|
||||
const managed = this.plugins.get(pluginId);
|
||||
if (!managed) return;
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
// ─── Re-export all manifest types from the WorldWideView Plugin SDK ───
|
||||
/**
|
||||
* Re-exports manifest-related types from the WorldWideView Plugin SDK.
|
||||
* This file allows the application to reference plugin manifest structures
|
||||
* while keeping the SDK as the authoritative source of truth.
|
||||
*/
|
||||
// Source of truth for manifest types is now @worldwideview/wwv-plugin-sdk.
|
||||
export type {
|
||||
PluginFormat,
|
||||
|
||||
@@ -1,12 +1,22 @@
|
||||
import type { WorldPlugin } from "@/core/plugins/PluginTypes";
|
||||
|
||||
/**
|
||||
* Static registry of plugins + dynamic registration API.
|
||||
* Plugins are registered at startup, then discovered by the PluginManager.
|
||||
* PluginRegistry is the central coordinator for all active data sources in WorldWideView.
|
||||
* It provides a standardized API for registration, discovery, and lifecycle management,
|
||||
* ensuring that the application remains modular and that plugins can be hot-swapped
|
||||
* or dynamically loaded from the marketplace without affecting core engine logic.
|
||||
*/
|
||||
class PluginRegistry {
|
||||
private plugins: Map<string, WorldPlugin> = new Map();
|
||||
|
||||
/**
|
||||
* Registers a new plugin in the registry if it does not already exist.
|
||||
* This is the entry point for both built-in and marketplace plugins to enter
|
||||
* the system. It prevents namespace collisions by enforcing unique IDs,
|
||||
* ensuring that the PluginManager and UI have a stable map of available sources.
|
||||
*
|
||||
* @param plugin - The WorldPlugin instance to be registered.
|
||||
*/
|
||||
register(plugin: WorldPlugin): void {
|
||||
if (this.plugins.has(plugin.id)) {
|
||||
console.warn(`[PluginRegistry] Plugin "${plugin.id}" already registered`);
|
||||
@@ -15,22 +25,63 @@ class PluginRegistry {
|
||||
this.plugins.set(plugin.id, plugin);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a registered plugin by its unique identifier.
|
||||
* Use this method to access specific plugin metadata or capabilities
|
||||
* (e.g., icons, categories) when targeting a single data source outside
|
||||
* of the global collection.
|
||||
*
|
||||
* @param pluginId - The unique ID of the plugin to retrieve.
|
||||
* @returns The WorldPlugin instance if found, otherwise undefined.
|
||||
*/
|
||||
get(pluginId: string): WorldPlugin | undefined {
|
||||
return this.plugins.get(pluginId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of all currently registered plugins.
|
||||
* This is primarily used by the PluginManager during initialization and the
|
||||
* UI components (like PluginsTab) to render the full list of available
|
||||
* data layers for the user.
|
||||
*
|
||||
* @returns An array containing all WorldPlugin instances.
|
||||
*/
|
||||
getAll(): WorldPlugin[] {
|
||||
return Array.from(this.plugins.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters and returns all registered plugins belonging to a specific category.
|
||||
* This method powers the categorical grouping in the UI dashboard, enabling
|
||||
* users to quickly filter between 'Aviation', 'Maritime', or 'Environment' layers.
|
||||
*
|
||||
* @param category - The category string to filter by.
|
||||
* @returns An array of WorldPlugin instances matching the category.
|
||||
*/
|
||||
getByCategory(category: string): WorldPlugin[] {
|
||||
return this.getAll().filter((p) => p.category === category);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a plugin with the given ID is already registered.
|
||||
* A lightweight utility for components that need to verify plugin availability
|
||||
* or handle conditional rendering without retrieving the entire plugin object.
|
||||
*
|
||||
* @param pluginId - The unique ID to check.
|
||||
* @returns True if the plugin exists in the registry, false otherwise.
|
||||
*/
|
||||
has(pluginId: string): boolean {
|
||||
return this.plugins.has(pluginId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a plugin from the registry by its ID.
|
||||
* Critical for managing the cleanup phase of dynamic plugins when they are
|
||||
* uninstalled or disabled via the marketplace, preventing memory leaks and
|
||||
* ensuring the UI stays synchronized with actual active sources.
|
||||
*
|
||||
* @param pluginId - The unique ID of the plugin to remove.
|
||||
*/
|
||||
unregister(pluginId: string): void {
|
||||
this.plugins.delete(pluginId);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
// ─── Re-export all types from the WorldWideView Plugin SDK ───
|
||||
// This keeps all existing app imports working without changes.
|
||||
/**
|
||||
* Re-exports core types from the WorldWideView Plugin SDK.
|
||||
* This file serves as a local proxy for the SDK types to maintain backward compatibility
|
||||
* for the application's imports while keeping the SDK as the single source of truth.
|
||||
*/
|
||||
// Source of truth for types is now @worldwideview/wwv-plugin-sdk.
|
||||
export type {
|
||||
PluginCategory,
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
// ─── Host Globals ────────────────────────────────────────────
|
||||
// Exposes host libraries on globalThis so dynamically loaded
|
||||
// plugins can use React without bundling their own copy.
|
||||
/**
|
||||
* @file hostGlobals.ts
|
||||
* @description Exposes essential host libraries (React, Cesium, SDK, etc.) on `globalThis`.
|
||||
* This allows dynamically loaded ES module plugins to share the host's dependencies
|
||||
* rather than bundling their own copies, preventing version conflicts and reducing bundle size.
|
||||
*/
|
||||
|
||||
import React from "react";
|
||||
import * as ReactDOM from "react-dom";
|
||||
@@ -31,7 +34,14 @@ declare global {
|
||||
var __WWV_HOST__: WWVHostGlobals | undefined;
|
||||
}
|
||||
|
||||
/** Inject host globals. Call once at app startup, before any plugin loads. */
|
||||
/**
|
||||
* Injects the required libraries and configuration onto the global scope.
|
||||
*
|
||||
* This must be called exactly once during the application's initial boot sequence,
|
||||
* before any dynamic plugins are imported.
|
||||
*
|
||||
* @returns A promise that resolves when all globals have been injected.
|
||||
*/
|
||||
export async function injectHostGlobals(): Promise<void> {
|
||||
if (globalThis.__WWV_HOST__) return;
|
||||
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
// ─── Plugin Loader ───────────────────────────────────────────
|
||||
// All plugins are bundles. Given a manifest, dynamically import
|
||||
// the entry and return a WorldPlugin instance.
|
||||
/**
|
||||
* @file loadPluginFromManifest.ts
|
||||
* @description Handles the dynamic loading and instantiation of WorldWideView plugins from ES module bundles.
|
||||
*/
|
||||
|
||||
import type { WorldPlugin } from "./PluginTypes";
|
||||
import type { PluginManifest } from "./PluginManifest";
|
||||
import { validateManifest } from "./validateManifest";
|
||||
|
||||
/**
|
||||
* Custom error class for failures occurring during the plugin manifest loading process.
|
||||
* Includes detailed validation errors to help developers debug malformed marketplace bundles.
|
||||
*/
|
||||
export class ManifestLoadError extends Error {
|
||||
constructor(
|
||||
public readonly manifestId: string,
|
||||
@@ -17,10 +22,23 @@ export class ManifestLoadError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
/** Load a bundle plugin via dynamic import. */
|
||||
/**
|
||||
* Orchestrates the dynamic ES module import of a plugin bundle.
|
||||
* This method is the core of our "Bundled Plugin" architecture, bypassing standard
|
||||
* build-time dependencies to load external code at runtime. It aggressively
|
||||
* probes the imported module for a valid WorldPlugin implementation, checking
|
||||
* default exports, named class exports, and object literals with 'initialize' hooks.
|
||||
*
|
||||
* @param entry - The URL or path to the ES module entry point (e.g., unpkg.com URL).
|
||||
* @returns A promise resolving to an instantiated WorldPlugin implementation.
|
||||
* @throws Error if the module cannot be reached or no valid plugin interface is discovered.
|
||||
*/
|
||||
async function loadBundlePlugin(entry: string): Promise<WorldPlugin> {
|
||||
const module = await import(/* webpackIgnore: true */ entry);
|
||||
|
||||
/**
|
||||
* Helper to safely instantiate a class and verify its compliance with WorldPlugin.
|
||||
*/
|
||||
const instantiate = (maybeClass: any): WorldPlugin | null => {
|
||||
if (typeof maybeClass === "function") {
|
||||
try {
|
||||
@@ -42,11 +60,13 @@ async function loadBundlePlugin(entry: string): Promise<WorldPlugin> {
|
||||
return module.default as WorldPlugin;
|
||||
}
|
||||
|
||||
// Probe all named exports for a class implementation
|
||||
for (const key in module) {
|
||||
const instance = instantiate(module[key]);
|
||||
if (instance) return instance;
|
||||
}
|
||||
|
||||
// Fallback: check for object literals that look like plugins (legacy/utility bundles)
|
||||
for (const key in module) {
|
||||
const exp = module[key];
|
||||
if (exp && typeof exp === "object" && typeof exp.initialize === "function") {
|
||||
@@ -61,8 +81,14 @@ async function loadBundlePlugin(entry: string): Promise<WorldPlugin> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a PluginManifest, returns a fully constructed WorldPlugin instance.
|
||||
* @throws ManifestLoadError if validation fails or loading fails
|
||||
* Validates a plugin manifest and returns a fully constructed WorldPlugin instance.
|
||||
* This is the primary system entry point for turning a JSON marketplace declaration
|
||||
* into a live, interactive data layer. It enforces strict schema validation
|
||||
* before attempting the expensive network request for the module bundle.
|
||||
*
|
||||
* @param manifest - The raw JSON manifest declaration for the plugin.
|
||||
* @returns A promise resolving to a constructed WorldPlugin.
|
||||
* @throws ManifestLoadError if the schema is invalid or the network bundle fails to resolve.
|
||||
*/
|
||||
export async function loadPluginFromManifest(
|
||||
manifest: PluginManifest,
|
||||
|
||||
@@ -204,4 +204,156 @@ describe("DeclarativePlugin", () => {
|
||||
expect(opts.color).toBe("#ff0000");
|
||||
expect(opts.labelText).toBe("Test");
|
||||
});
|
||||
|
||||
test("destroy clears context", async () => {
|
||||
const plugin = new DeclarativePlugin(makeManifest());
|
||||
await plugin.initialize({} as any);
|
||||
// We can't strictly observe context, but we can verify it doesn't throw
|
||||
expect(() => plugin.destroy()).not.toThrow();
|
||||
});
|
||||
|
||||
test("fetch uses query auth if specified", async () => {
|
||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ features: [] }),
|
||||
}));
|
||||
|
||||
const originalEnv = process.env;
|
||||
process.env = { ...originalEnv, API_KEY: "secret123" };
|
||||
|
||||
const plugin = new DeclarativePlugin(makeManifest({
|
||||
dataSource: {
|
||||
url: "https://api.example.com/data?type=test",
|
||||
method: "GET",
|
||||
pollInterval: 60000,
|
||||
format: "geojson",
|
||||
auth: { type: "query", key: "token", envVar: "API_KEY" }
|
||||
}
|
||||
}));
|
||||
|
||||
await plugin.fetch({ start: new Date(), end: new Date() });
|
||||
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
"https://api.example.com/data?type=test&token=secret123",
|
||||
expect.any(Object)
|
||||
);
|
||||
|
||||
process.env = originalEnv;
|
||||
});
|
||||
|
||||
test("fetch does not use query auth if envVar is missing", async () => {
|
||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ features: [] }),
|
||||
}));
|
||||
|
||||
const originalEnv = process.env;
|
||||
process.env = { ...originalEnv };
|
||||
delete process.env.MISSING_KEY;
|
||||
|
||||
const plugin = new DeclarativePlugin(makeManifest({
|
||||
dataSource: {
|
||||
url: "https://api.example.com/data",
|
||||
method: "GET",
|
||||
pollInterval: 60000,
|
||||
format: "geojson",
|
||||
auth: { type: "query", key: "token", envVar: "MISSING_KEY" }
|
||||
}
|
||||
}));
|
||||
|
||||
await plugin.fetch({ start: new Date(), end: new Date() });
|
||||
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
"https://api.example.com/data",
|
||||
expect.any(Object)
|
||||
);
|
||||
|
||||
process.env = originalEnv;
|
||||
});
|
||||
|
||||
test("fetch uses header auth if specified", async () => {
|
||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ features: [] }),
|
||||
}));
|
||||
|
||||
const originalEnv = process.env;
|
||||
process.env = { ...originalEnv, HEADER_KEY: "bearer 123" };
|
||||
|
||||
const plugin = new DeclarativePlugin(makeManifest({
|
||||
dataSource: {
|
||||
url: "https://api.example.com/data",
|
||||
method: "GET",
|
||||
pollInterval: 60000,
|
||||
format: "geojson",
|
||||
auth: { type: "header", key: "Authorization", envVar: "HEADER_KEY" }
|
||||
}
|
||||
}));
|
||||
|
||||
await plugin.fetch({ start: new Date(), end: new Date() });
|
||||
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
"https://api.example.com/data",
|
||||
expect.objectContaining({
|
||||
headers: expect.objectContaining({
|
||||
"Authorization": "bearer 123"
|
||||
})
|
||||
})
|
||||
);
|
||||
|
||||
process.env = originalEnv;
|
||||
});
|
||||
|
||||
test("fetch handles request body", async () => {
|
||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ features: [] }),
|
||||
}));
|
||||
|
||||
const plugin = new DeclarativePlugin(makeManifest({
|
||||
dataSource: {
|
||||
url: "https://api.example.com/data",
|
||||
method: "POST",
|
||||
pollInterval: 60000,
|
||||
format: "geojson",
|
||||
body: { query: "test" }
|
||||
}
|
||||
}));
|
||||
|
||||
await plugin.fetch({ start: new Date(), end: new Date() });
|
||||
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
"https://api.example.com/data",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
body: JSON.stringify({ query: "test" })
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
test("fetch returns empty if mapping is missing", async () => {
|
||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ features: [] }),
|
||||
}));
|
||||
|
||||
const plugin = new DeclarativePlugin(makeManifest({
|
||||
fieldMapping: undefined
|
||||
}));
|
||||
|
||||
const result = await plugin.fetch({ start: new Date(), end: new Date() });
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
test("renderEntity returns billboard correctly", () => {
|
||||
const plugin = new DeclarativePlugin(makeManifest({
|
||||
rendering: {
|
||||
entityType: "billboard",
|
||||
icon: "/icon.png"
|
||||
}
|
||||
}));
|
||||
const opts = plugin.renderEntity({} as any);
|
||||
expect(opts.type).toBe("billboard");
|
||||
expect(opts.iconUrl).toBe("/icon.png");
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,9 @@
|
||||
/**
|
||||
* @file DeclarativePlugin.ts
|
||||
* @description Generic WorldPlugin implementation for declarative (JSON-only) plugins.
|
||||
* Note: This runtime is legacy and primarily used as a fallback for simple data layers.
|
||||
*/
|
||||
|
||||
import type {
|
||||
WorldPlugin,
|
||||
GeoEntity,
|
||||
@@ -13,8 +19,7 @@ import { mapGeoJsonToEntities } from "./mapGeoJsonToEntities";
|
||||
import { mapJsonToEntities } from "./mapJsonToEntities";
|
||||
|
||||
/**
|
||||
* Generic WorldPlugin implementation for declarative (JSON-only) plugins.
|
||||
* Reads a PluginManifest to know where to fetch, how to parse, and how to render.
|
||||
* A generic plugin implementation that derives its logic from a JSON manifest.
|
||||
*/
|
||||
export class DeclarativePlugin implements WorldPlugin {
|
||||
readonly id: string;
|
||||
@@ -35,14 +40,29 @@ export class DeclarativePlugin implements WorldPlugin {
|
||||
this.version = manifest.version;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the plugin with the provided context.
|
||||
*
|
||||
* @param ctx - The host context provided by the manager.
|
||||
* @returns A promise that resolves when initialization is complete.
|
||||
*/
|
||||
async initialize(ctx: PluginContext): Promise<void> {
|
||||
this.context = ctx;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleans up internal state and stops all active processes.
|
||||
*/
|
||||
destroy(): void {
|
||||
this.context = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches fresh data from the remote data source defined in the manifest.
|
||||
*
|
||||
* @param _timeRange - The current globe time range (unused in this implementation).
|
||||
* @returns A promise resolving to an array of GeoEntities.
|
||||
*/
|
||||
async fetch(_timeRange: TimeRange): Promise<GeoEntity[]> {
|
||||
const ds = this.manifest.dataSource;
|
||||
if (!ds) return [];
|
||||
@@ -66,10 +86,20 @@ export class DeclarativePlugin implements WorldPlugin {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the polling interval from the manifest configuration.
|
||||
*
|
||||
* @returns The poll interval in milliseconds (defaults to 30s).
|
||||
*/
|
||||
getPollingInterval(): number {
|
||||
return this.manifest.dataSource?.pollInterval ?? 30_000;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the visual configuration for the map layer.
|
||||
*
|
||||
* @returns The LayerConfig object.
|
||||
*/
|
||||
getLayerConfig(): LayerConfig {
|
||||
const r = this.manifest.rendering;
|
||||
return {
|
||||
@@ -80,6 +110,12 @@ export class DeclarativePlugin implements WorldPlugin {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines how a single GeoEntity should be represented on the Cesium globe.
|
||||
*
|
||||
* @param entity - The entity to render.
|
||||
* @returns The Cesium-specific rendering options.
|
||||
*/
|
||||
renderEntity(entity: GeoEntity): CesiumEntityOptions {
|
||||
const r = this.manifest.rendering;
|
||||
const type = r?.entityType === "billboard" ? "billboard" : "point";
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
/**
|
||||
* @file getNestedValue.ts
|
||||
* @description Utility for resolving deeply nested properties using dot-path notation.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Resolves a dot-path (with optional bracket notation) on an object.
|
||||
*
|
||||
*
|
||||
* @param obj - The source object to traverse.
|
||||
* @param path - The dot-notation path (e.g., "a.b[1].c").
|
||||
* @returns The value at the specified path, or undefined if not found.
|
||||
*
|
||||
* @example
|
||||
* getNestedValue({ a: { b: [10, 20] } }, "a.b[1]") // → 20
|
||||
* getNestedValue({ x: 1 }, "y.z") // → undefined
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import { describe, test, expect } from "vitest";
|
||||
import { mapGeoJsonToEntities } from "./mapGeoJsonToEntities";
|
||||
|
||||
describe("mapGeoJsonToEntities", () => {
|
||||
test("handles valid geojson with full mapping", () => {
|
||||
const data = {
|
||||
features: [
|
||||
{
|
||||
id: "feat-1",
|
||||
geometry: { type: "Point", coordinates: [174, -36, 10] },
|
||||
properties: { speed: 100, heading: 90, time: "2026-05-14T00:00:00Z", label: "Test" }
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
const entities = mapGeoJsonToEntities(data, {
|
||||
id: "id",
|
||||
latitude: "geometry.coordinates[1]",
|
||||
longitude: "geometry.coordinates[0]",
|
||||
altitude: "geometry.coordinates[2]",
|
||||
speed: "properties.speed",
|
||||
heading: "properties.heading",
|
||||
timestamp: "properties.time",
|
||||
label: "properties.label",
|
||||
properties: { custom: "properties.speed" }
|
||||
}, "plugin1");
|
||||
|
||||
expect(entities).toHaveLength(1);
|
||||
expect(entities[0].altitude).toBe(10);
|
||||
expect(entities[0].speed).toBe(100);
|
||||
expect(entities[0].heading).toBe(90);
|
||||
expect(entities[0].timestamp.toISOString()).toBe("2026-05-14T00:00:00.000Z");
|
||||
expect(entities[0].properties.custom).toBe(100);
|
||||
});
|
||||
|
||||
test("handles missing properties definition", () => {
|
||||
const data = {
|
||||
features: [
|
||||
{
|
||||
geometry: { type: "Point", coordinates: [174, -36] },
|
||||
properties: {}
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
const entities = mapGeoJsonToEntities(data, {
|
||||
id: "id",
|
||||
latitude: "geometry.coordinates[1]",
|
||||
longitude: "geometry.coordinates[0]",
|
||||
}, "plugin1");
|
||||
|
||||
expect(entities).toHaveLength(1);
|
||||
expect(entities[0].properties).toEqual({});
|
||||
expect(entities[0].id).toBe("plugin1-0"); // fallback to index
|
||||
});
|
||||
|
||||
test("handles asNumber edge cases (null, non-finite)", () => {
|
||||
const data = {
|
||||
features: [
|
||||
{
|
||||
id: "feat-2",
|
||||
geometry: { type: "Point", coordinates: [174, -36] },
|
||||
properties: { speed: null, heading: "NaN", alt: "Infinity" }
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
const entities = mapGeoJsonToEntities(data, {
|
||||
id: "id",
|
||||
latitude: "geometry.coordinates[1]",
|
||||
longitude: "geometry.coordinates[0]",
|
||||
speed: "properties.speed",
|
||||
heading: "properties.heading",
|
||||
altitude: "properties.alt"
|
||||
}, "plugin1");
|
||||
|
||||
expect(entities).toHaveLength(1);
|
||||
expect(entities[0].speed).toBeUndefined(); // null -> undefined
|
||||
expect(entities[0].heading).toBeUndefined(); // NaN -> undefined
|
||||
expect(entities[0].altitude).toBeUndefined(); // Infinity -> undefined
|
||||
});
|
||||
|
||||
test("handles parseTimestamp edge cases (invalid string, fallback)", () => {
|
||||
const data = {
|
||||
features: [
|
||||
{
|
||||
geometry: { type: "Point", coordinates: [174, -36] },
|
||||
properties: { time1: "invalid-date", time2: null }
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
const entities = mapGeoJsonToEntities(data, {
|
||||
id: "id",
|
||||
latitude: "geometry.coordinates[1]",
|
||||
longitude: "geometry.coordinates[0]",
|
||||
timestamp: "properties.time1"
|
||||
}, "plugin1");
|
||||
|
||||
expect(entities).toHaveLength(1);
|
||||
// Invalid string falls back to current date, we just check it's a valid date
|
||||
expect(entities[0].timestamp).toBeInstanceOf(Date);
|
||||
expect(isNaN(entities[0].timestamp.getTime())).toBe(false);
|
||||
|
||||
const entities2 = mapGeoJsonToEntities(data, {
|
||||
id: "id",
|
||||
latitude: "geometry.coordinates[1]",
|
||||
longitude: "geometry.coordinates[0]",
|
||||
timestamp: "properties.time2"
|
||||
}, "plugin1");
|
||||
|
||||
expect(entities2).toHaveLength(1);
|
||||
expect(entities2[0].timestamp).toBeInstanceOf(Date);
|
||||
expect(isNaN(entities2[0].timestamp.getTime())).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,8 @@
|
||||
/**
|
||||
* @file mapGeoJsonToEntities.ts
|
||||
* @description Logic for transforming GeoJSON responses into the standardized `GeoEntity` format.
|
||||
*/
|
||||
|
||||
import type { GeoEntity } from "../PluginTypes";
|
||||
import type { FieldMapping } from "../PluginManifest";
|
||||
import { getNestedValue } from "./getNestedValue";
|
||||
@@ -9,8 +14,12 @@ interface GeoJsonFeature {
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a GeoJSON response to GeoEntity[].
|
||||
* Expects `data.features` to be an array of GeoJSON Feature objects.
|
||||
* Maps a GeoJSON response (FeatureCollection or individual Feature) to an array of `GeoEntity` objects.
|
||||
*
|
||||
* @param data - The raw GeoJSON response.
|
||||
* @param mapping - The field mapping configuration for non-geometry fields.
|
||||
* @param pluginId - The ID of the plugin performing the mapping.
|
||||
* @returns An array of mapped GeoEntities.
|
||||
*/
|
||||
export function mapGeoJsonToEntities(
|
||||
data: unknown,
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { describe, test, expect } from "vitest";
|
||||
import { mapJsonToEntities } from "./mapJsonToEntities";
|
||||
|
||||
describe("mapJsonToEntities", () => {
|
||||
test("handles arrayPath resolution", () => {
|
||||
const data = {
|
||||
wrapper: {
|
||||
items: [
|
||||
{ id: 1, lat: 10, lon: 20 }
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
const entities = mapJsonToEntities(data, {
|
||||
id: "id",
|
||||
latitude: "lat",
|
||||
longitude: "lon"
|
||||
}, "plugin1", "wrapper.items");
|
||||
|
||||
expect(entities).toHaveLength(1);
|
||||
expect(entities[0].id).toBe("plugin1-1");
|
||||
});
|
||||
|
||||
test("handles non-array resolution gracefully", () => {
|
||||
const data = { wrapper: { items: "not-an-array" } };
|
||||
|
||||
const entities = mapJsonToEntities(data, {
|
||||
id: "id",
|
||||
latitude: "lat",
|
||||
longitude: "lon"
|
||||
}, "plugin1", "wrapper.items");
|
||||
|
||||
expect(entities).toEqual([]);
|
||||
});
|
||||
|
||||
test("handles asNumber and parseTimestamp edge cases", () => {
|
||||
const data = [
|
||||
{ id: 1, lat: 10, lon: 20, speed: null, alt: "Infinity", time: "invalid-date" }
|
||||
];
|
||||
|
||||
const entities = mapJsonToEntities(data, {
|
||||
id: "id",
|
||||
latitude: "lat",
|
||||
longitude: "lon",
|
||||
speed: "speed",
|
||||
altitude: "alt",
|
||||
timestamp: "time"
|
||||
}, "plugin1");
|
||||
|
||||
expect(entities).toHaveLength(1);
|
||||
expect(entities[0].speed).toBeUndefined();
|
||||
expect(entities[0].altitude).toBeUndefined();
|
||||
expect(entities[0].timestamp).toBeInstanceOf(Date);
|
||||
expect(isNaN(entities[0].timestamp.getTime())).toBe(false);
|
||||
});
|
||||
|
||||
test("skips items missing lat or lon", () => {
|
||||
const data = [
|
||||
{ id: 1, lat: 10 }, // missing lon
|
||||
{ id: 2, lon: 20 }, // missing lat
|
||||
{ id: 3, lat: null, lon: 20 }
|
||||
];
|
||||
|
||||
const entities = mapJsonToEntities(data, {
|
||||
id: "id",
|
||||
latitude: "lat",
|
||||
longitude: "lon"
|
||||
}, "plugin1");
|
||||
|
||||
expect(entities).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,24 @@
|
||||
/**
|
||||
* @file mapJsonToEntities.ts
|
||||
* @description Logic for transforming arbitrary JSON API responses into the standardized `GeoEntity` format
|
||||
* using declarative field mappings.
|
||||
*/
|
||||
|
||||
import type { GeoEntity } from "../PluginTypes";
|
||||
import type { FieldMapping } from "../PluginManifest";
|
||||
import { getNestedValue } from "./getNestedValue";
|
||||
|
||||
/**
|
||||
* Maps a plain JSON response to GeoEntity[].
|
||||
* Uses dot-path field mapping to extract each field from each item.
|
||||
* Maps a plain JSON response to an array of `GeoEntity` objects.
|
||||
*
|
||||
* Uses dot-path field mapping to extract core geospatial fields (lat, lon, id, etc.)
|
||||
* from each item in the data set.
|
||||
*
|
||||
* @param data - The raw JSON response data.
|
||||
* @param mapping - The field mapping configuration from the plugin manifest.
|
||||
* @param pluginId - The ID of the plugin performing the mapping.
|
||||
* @param arrayPath - Optional dot-path to the array within the JSON response.
|
||||
* @returns An array of successfully mapped GeoEntities.
|
||||
*/
|
||||
export function mapJsonToEntities(
|
||||
data: unknown,
|
||||
|
||||
@@ -1,22 +1,38 @@
|
||||
/**
|
||||
* @file parseWwvManifest.ts
|
||||
* @description Utilities for parsing and sanitizing raw JSON manifests into the internal `PluginManifest` type.
|
||||
*/
|
||||
|
||||
import type { PluginManifest } from "./PluginManifest";
|
||||
|
||||
/**
|
||||
* Validates and converts a wwv-manifest.json into an internal PluginManifest.
|
||||
* Validates and converts a raw `wwv-manifest.json` object into an internal `PluginManifest`.
|
||||
* This utility implements the 'Safe-Hydration' pattern, ensuring that arbitrary JSON
|
||||
* fetched from external marketplace sources is coerced into our strictly-typed
|
||||
* internal model. It provides sensible defaults (e.g., category: 'custom',
|
||||
* format: 'bundle') to ensure compatibility with older or minimalist manifests.
|
||||
*
|
||||
* @param rawManifest - The raw, untrusted JSON object typically fetched from a remote server or CDN.
|
||||
* @returns A sanitized and properly structured PluginManifest object.
|
||||
* @throws Error if the raw input is not a valid JSON object.
|
||||
*/
|
||||
export function parseWwvManifest(rawManifest: any): PluginManifest {
|
||||
if (!rawManifest || typeof rawManifest !== "object") {
|
||||
throw new Error("Manifest must be a JSON object");
|
||||
}
|
||||
|
||||
// Required fields mapping
|
||||
/**
|
||||
* Partial construction allows us to explicitly map and default fields
|
||||
* before casting to the final strict interface.
|
||||
*/
|
||||
const manifest: Partial<PluginManifest> = {
|
||||
id: rawManifest.id,
|
||||
name: rawManifest.name,
|
||||
version: rawManifest.version,
|
||||
description: rawManifest.description,
|
||||
type: rawManifest.type || "data-layer",
|
||||
format: "bundle", // wwv-manifest plugins are always bundles
|
||||
trust: "unverified", // Will be overridden if fetched from marketplace
|
||||
format: "bundle", // Modern wwv-manifest plugins are always ES module bundles
|
||||
trust: "unverified", // Default trust level; overridden by marketplace signature verification
|
||||
capabilities: rawManifest.capabilities || [],
|
||||
category: rawManifest.category || "custom",
|
||||
icon: rawManifest.icon,
|
||||
|
||||
@@ -1,22 +1,41 @@
|
||||
// ─── Plugin Manifest Validation ──────────────────────────────
|
||||
// Validates a plugin manifest. All plugins are now bundles.
|
||||
/**
|
||||
* @file validateManifest.ts
|
||||
* @description Validates PluginManifest objects against the required schema and security constraints.
|
||||
*/
|
||||
|
||||
import type { PluginManifest } from "./PluginManifest";
|
||||
|
||||
/**
|
||||
* Result of a manifest validation operation.
|
||||
* Used by the loader to prevent malformed or insecure plugins from entering the runtime.
|
||||
*/
|
||||
export interface ValidationResult {
|
||||
/** True if the manifest satisfies all structural and security requirements. */
|
||||
valid: boolean;
|
||||
/** List of human-readable descriptions for each validation failure. */
|
||||
errors: string[];
|
||||
}
|
||||
|
||||
const VALID_TYPES = ["data-layer", "extension"] as const;
|
||||
const VALID_TRUSTS = ["built-in", "verified", "unverified"] as const;
|
||||
|
||||
/**
|
||||
* Validates a plugin manifest for structural integrity and security compliance.
|
||||
* This is the primary security gate for the WorldWideView plugin ecosystem.
|
||||
* It ensures that all required fields are present and, crucially, enforces
|
||||
* an 'Entry URL Allowlist' to prevent Remote Code Execution (RCE) from
|
||||
* untrusted domains. All external bundles must originate from approved
|
||||
* CDNs or official WorldWideView infrastructure.
|
||||
*
|
||||
* @param manifest - The manifest object to validate (potentially partial during parsing).
|
||||
* @returns A ValidationResult indicating success or a list of identified security/structural risks.
|
||||
*/
|
||||
export function validateManifest(
|
||||
manifest: Partial<PluginManifest>,
|
||||
): ValidationResult {
|
||||
const errors: string[] = [];
|
||||
|
||||
// Default type for older manifests missing the field
|
||||
// Default type for older manifests missing the field to ensure backward compatibility
|
||||
if (manifest && !manifest.type) {
|
||||
manifest.type = "data-layer";
|
||||
}
|
||||
@@ -35,7 +54,7 @@ export function validateManifest(
|
||||
errors.push("capabilities must be a non-empty array");
|
||||
}
|
||||
|
||||
// Entry is required — all plugins are bundles now
|
||||
// Entry point validation - critical for preventing RCE
|
||||
if (!manifest.entry?.trim()) {
|
||||
errors.push("Missing required field: entry");
|
||||
} else {
|
||||
@@ -50,7 +69,7 @@ export function validateManifest(
|
||||
}
|
||||
}
|
||||
|
||||
// Extension plugins require extends
|
||||
// Extension plugins require a target to extend
|
||||
if (manifest.type === "extension") {
|
||||
if (!Array.isArray(manifest.extends) || manifest.extends.length === 0) {
|
||||
errors.push("Extension plugins require a non-empty extends array");
|
||||
|
||||
@@ -1,44 +1,83 @@
|
||||
/**
|
||||
* @file configSlice.ts
|
||||
* @description State slice managing application-wide settings, data engine configuration,
|
||||
* and map rendering parameters.
|
||||
*/
|
||||
|
||||
import type { StateCreator } from "zustand";
|
||||
import type { AppStore } from "./store";
|
||||
|
||||
// ─── Data Configuration ──────────────────────────────────────
|
||||
/**
|
||||
* Configuration settings related to data fetching, caching, and tiers.
|
||||
*/
|
||||
export interface DataConfig {
|
||||
/** Map of plugin IDs to their custom polling intervals (ms). */
|
||||
pollingIntervals: Record<string, number>;
|
||||
/** Whether local caching of plugin data is enabled. */
|
||||
cacheEnabled: boolean;
|
||||
/** Maximum age of cached data in milliseconds. */
|
||||
cacheMaxAge: number;
|
||||
/** Number of simultaneous fetch requests allowed. */
|
||||
maxConcurrentRequests: number;
|
||||
/** Number of times to retry failed requests. */
|
||||
retryAttempts: number;
|
||||
/** Feature flags for experimental system behaviors. */
|
||||
experimentalFeatures: {
|
||||
predictiveLoading: boolean;
|
||||
realtimeStreaming: boolean;
|
||||
clusteringEnabled: boolean;
|
||||
showTimelineHighlight: boolean;
|
||||
};
|
||||
/** Generic storage for plugin-specific settings. */
|
||||
pluginSettings: Record<string, any>;
|
||||
/** Cryptographic license key for paid tiers. */
|
||||
licenseKey: string | null;
|
||||
/** The active subscription tier of the user. */
|
||||
activeTier: "free" | "pro" | "team" | "enterprise";
|
||||
}
|
||||
|
||||
export type AntiAliasingMode = "none" | "fxaa" | "msaa2x" | "msaa4x" | "msaa8x";
|
||||
|
||||
/**
|
||||
* Settings related to the 3D globe rendering and visual fidelity.
|
||||
*/
|
||||
export interface MapConfig {
|
||||
/** Show the FPS counter in the HUD. */
|
||||
showFps: boolean;
|
||||
/** Scaling factor for screen resolution (0.1 to 2.0). */
|
||||
resolutionScale: number;
|
||||
/** Selected anti-aliasing algorithm. */
|
||||
antiAliasing: AntiAliasingMode;
|
||||
/** Threshold for detail level in 3D tiles (higher = faster, lower = prettier). */
|
||||
maxScreenSpaceError: number;
|
||||
/** Whether dynamic shadows are enabled. */
|
||||
shadowsEnabled: boolean;
|
||||
/** Whether lighting from the sun/moon is enabled. */
|
||||
enableLighting: boolean;
|
||||
/** ID of the active base map layer. */
|
||||
baseLayerId: string;
|
||||
/** Optional fallback layer if base layer fails to load. */
|
||||
fallbackLayerId: string | null;
|
||||
sceneMode: 1 | 2 | 3; // 1: Columbus View, 2: 2D, 3: 3D
|
||||
/** The active scene mode (2D, 2.5D, or 3D). */
|
||||
sceneMode: 1 | 2 | 3;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zustand state slice for application configuration.
|
||||
*/
|
||||
export interface ConfigSlice {
|
||||
/** Active data and engine settings. */
|
||||
dataConfig: DataConfig;
|
||||
/** Active map rendering settings. */
|
||||
mapConfig: MapConfig;
|
||||
/** Updates one or more data configuration fields. */
|
||||
updateDataConfig: (config: Partial<DataConfig>) => void;
|
||||
/** Updates one or more map rendering fields and persists layer choice to localStorage. */
|
||||
updateMapConfig: (config: Partial<MapConfig>) => void;
|
||||
/** Overrides the default polling interval for a specific plugin. */
|
||||
setPollingInterval: (pluginId: string, intervalMs: number) => void;
|
||||
/** Updates internal settings stored for a specific plugin. */
|
||||
updatePluginSettings: (pluginId: string, settings: any) => void;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,24 @@
|
||||
/**
|
||||
* @file dataSlice.ts
|
||||
* @description State slice managing the core geospatial entities retrieved from all active plugins.
|
||||
*/
|
||||
|
||||
import type { StateCreator } from "zustand";
|
||||
import type { AppStore } from "./store";
|
||||
import type { GeoEntity } from "@/core/plugins/PluginTypes";
|
||||
|
||||
// ─── Data Slice ──────────────────────────────────────────────
|
||||
/**
|
||||
* Zustand state slice for storing and retrieving geospatial entity data.
|
||||
*/
|
||||
export interface DataSlice {
|
||||
/** Map of plugin IDs to their currently loaded arrays of GeoEntities. */
|
||||
entitiesByPlugin: Record<string, GeoEntity[]>;
|
||||
/** Updates the entity list for a specific plugin and refreshes selection if needed. */
|
||||
setEntities: (pluginId: string, entities: GeoEntity[]) => void;
|
||||
/** Removes all entities associated with a specific plugin from memory. */
|
||||
clearEntities: (pluginId: string) => void;
|
||||
/** Retrieves a flattened array of all visible entities from all active plugins. */
|
||||
getAllEntities: () => GeoEntity[];
|
||||
}
|
||||
|
||||
|
||||
@@ -1,21 +1,43 @@
|
||||
/**
|
||||
* @file favoritesSlice.ts
|
||||
* @description State slice for managing user-bookmarked entities.
|
||||
* Supports cross-session persistence via Cookies (demo mode) or PostgreSQL (local/cloud editions).
|
||||
*/
|
||||
|
||||
import type { StateCreator } from "zustand";
|
||||
import type { AppStore } from "./store";
|
||||
import type { GeoEntity } from "@/core/plugins/PluginTypes";
|
||||
import { isDemo } from "@/core/edition";
|
||||
|
||||
/**
|
||||
* A bookmarked entity with metadata for quick retrieval.
|
||||
*/
|
||||
export interface FavoriteItem {
|
||||
/** Unique ID of the bookmarked entity. */
|
||||
id: string;
|
||||
/** ID of the plugin that owns this entity. */
|
||||
pluginId: string;
|
||||
/** Human-readable label for the favorite. */
|
||||
label: string;
|
||||
/** Display name of the plugin for UI purposes. */
|
||||
pluginName: string;
|
||||
/** Optional React icon element (not persisted to DB/Cookie). */
|
||||
icon?: any;
|
||||
/** Timestamp of when the bookmark was created or last updated. */
|
||||
lastSeen: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zustand state slice for managing user favorites.
|
||||
*/
|
||||
export interface FavoritesSlice {
|
||||
/** List of all bookmarked items. */
|
||||
favorites: FavoriteItem[];
|
||||
/** Adds a new entity to the favorites list and persists it to the backend/cookie. */
|
||||
addFavorite: (entity: GeoEntity, pluginName: string, icon?: any) => void;
|
||||
/** Removes an entity from favorites and updates the persistence layer. */
|
||||
removeFavorite: (id: string) => void;
|
||||
/** Replaces the entire favorites list (typically called during initial app hydration). */
|
||||
initFavorites: (favorites: FavoriteItem[]) => void;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,24 @@
|
||||
/**
|
||||
* @file filterSlice.ts
|
||||
* @description State slice managing active data filters applied to different plugin layers.
|
||||
*/
|
||||
|
||||
import type { StateCreator } from "zustand";
|
||||
import type { AppStore } from "./store";
|
||||
import type { FilterValue } from "@/core/plugins/PluginTypes";
|
||||
|
||||
// ─── Filter Slice ────────────────────────────────────────────
|
||||
/**
|
||||
* Zustand state slice for managing layer-specific and global filters.
|
||||
*/
|
||||
export interface FilterSlice {
|
||||
/** Nested map of [pluginId][filterId] to the active FilterValue. */
|
||||
filters: Record<string, Record<string, FilterValue>>;
|
||||
/** Sets or updates a specific filter for a plugin. */
|
||||
setFilter: (pluginId: string, filterId: string, value: FilterValue) => void;
|
||||
/** Resets all filters associated with a specific plugin. */
|
||||
clearFilters: (pluginId: string) => void;
|
||||
/** Resets all filters for all plugins in the application. */
|
||||
clearAllFilters: () => void;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,22 +1,44 @@
|
||||
/**
|
||||
* @file geojsonSlice.ts
|
||||
* @description State slice managing locally imported GeoJSON layers (files uploaded by the user).
|
||||
*/
|
||||
|
||||
import type { StateCreator } from "zustand";
|
||||
import type { AppStore } from "./store";
|
||||
import type { GeoJsonFeatureCollection } from "@/types/geojson";
|
||||
|
||||
// ─── Imported GeoJSON Layer ──────────────────────────────────
|
||||
/**
|
||||
* A GeoJSON layer imported manually by the user.
|
||||
*/
|
||||
export interface ImportedLayer {
|
||||
/** Unique ID for the imported layer. */
|
||||
id: string;
|
||||
/** Display name chosen by the user. */
|
||||
name: string;
|
||||
/** Optional description of the layer contents. */
|
||||
description: string;
|
||||
/** Hex color code used to style features in this layer. */
|
||||
color: string;
|
||||
/** Whether the layer is currently rendered on the map. */
|
||||
visible: boolean;
|
||||
/** The raw GeoJSON data. */
|
||||
featureCollection: GeoJsonFeatureCollection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zustand state slice for managing user-imported GeoJSON data.
|
||||
*/
|
||||
export interface GeoJsonSlice {
|
||||
/** List of all currently imported GeoJSON layers. */
|
||||
importedLayers: ImportedLayer[];
|
||||
/** Adds a new GeoJSON layer to the collection. */
|
||||
addImportedLayer: (layer: ImportedLayer) => void;
|
||||
/** Permanently removes an imported layer from memory. */
|
||||
removeImportedLayer: (id: string) => void;
|
||||
/** Toggles the map visibility of a specific imported layer. */
|
||||
toggleImportedLayerVisibility: (id: string) => void;
|
||||
/** Updates metadata (name, description, color) for an existing imported layer. */
|
||||
updateImportedLayer: (
|
||||
id: string,
|
||||
patch: Partial<Pick<ImportedLayer, "name" | "description" | "color">>,
|
||||
|
||||
@@ -1,16 +1,33 @@
|
||||
/**
|
||||
* @file globeSlice.ts
|
||||
* @description State slice managing the 3D camera position, orientation, and globe-level rendering metrics.
|
||||
*/
|
||||
|
||||
import type { StateCreator } from "zustand";
|
||||
import type { AppStore } from "./store";
|
||||
|
||||
// ─── Globe Slice ─────────────────────────────────────────────
|
||||
/**
|
||||
* Zustand state slice for the 3D globe camera and viewport state.
|
||||
*/
|
||||
export interface GlobeSlice {
|
||||
/** Current camera latitude in degrees. */
|
||||
cameraLat: number;
|
||||
/** Current camera longitude in degrees. */
|
||||
cameraLon: number;
|
||||
/** Current camera altitude in meters above the ellipsoid. */
|
||||
cameraAlt: number;
|
||||
/** Current camera heading (yaw) in degrees. */
|
||||
cameraHeading: number;
|
||||
/** Current camera pitch in degrees. */
|
||||
cameraPitch: number;
|
||||
/** Current camera roll in degrees. */
|
||||
cameraRoll: number;
|
||||
/** Whether a programmatic camera transition (flyTo) is currently active. */
|
||||
isAnimating: boolean;
|
||||
/** Current rendering performance in frames per second. */
|
||||
fps: number;
|
||||
/** Updates the full camera transform (position and orientation). */
|
||||
setCameraPosition: (
|
||||
lat: number,
|
||||
lon: number,
|
||||
@@ -19,7 +36,9 @@ export interface GlobeSlice {
|
||||
pitch?: number,
|
||||
roll?: number
|
||||
) => void;
|
||||
/** Sets the current animation state of the camera. */
|
||||
setAnimating: (val: boolean) => void;
|
||||
/** Updates the current FPS metric. */
|
||||
setFps: (fps: number) => void;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,19 +1,39 @@
|
||||
/**
|
||||
* @file layersSlice.ts
|
||||
* @description State slice managing the lifecycle, visibility, and loading status of data layers (plugins).
|
||||
*/
|
||||
|
||||
import type { StateCreator } from "zustand";
|
||||
import type { AppStore } from "./store";
|
||||
|
||||
// ─── Layers Slice ────────────────────────────────────────────
|
||||
/**
|
||||
* Runtime state for a single data layer.
|
||||
*/
|
||||
export interface LayerState {
|
||||
/** Whether the layer is currently active and fetching/rendering data. */
|
||||
enabled: boolean;
|
||||
/** The number of entities currently loaded in this layer. */
|
||||
entityCount: number;
|
||||
/** Whether the layer is currently waiting for a network response. */
|
||||
loading: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zustand state slice for managing plugin layers.
|
||||
*/
|
||||
export interface LayersSlice {
|
||||
/** Map of plugin IDs to their current LayerState. */
|
||||
layers: Record<string, LayerState>;
|
||||
/** Toggles the active status of a layer. */
|
||||
toggleLayer: (pluginId: string) => void;
|
||||
/** Explicitly enables or disables a specific layer. */
|
||||
setLayerEnabled: (pluginId: string, enabled: boolean) => void;
|
||||
/** Updates the entity count displayed in the UI for a specific layer. */
|
||||
setEntityCount: (pluginId: string, count: number) => void;
|
||||
/** Updates the loading state indicator for a specific layer. */
|
||||
setLayerLoading: (pluginId: string, loading: boolean) => void;
|
||||
/** Initializes a new layer entry in the state if it doesn't already exist. */
|
||||
initLayer: (pluginId: string, defaultEnabled?: boolean) => void;
|
||||
}
|
||||
|
||||
|
||||
+15
-1
@@ -1,3 +1,9 @@
|
||||
/**
|
||||
* @file store.ts
|
||||
* @description The central state management hub for WorldWideView.
|
||||
* Combines multiple Zustand slices into a single unified store for the entire application.
|
||||
*/
|
||||
|
||||
import { create } from "zustand";
|
||||
import { createGlobeSlice, type GlobeSlice } from "./globeSlice";
|
||||
import { createLayersSlice, type LayersSlice } from "./layersSlice";
|
||||
@@ -9,7 +15,9 @@ import { createConfigSlice, type ConfigSlice } from "./configSlice";
|
||||
import { createFavoritesSlice, type FavoritesSlice } from "./favoritesSlice";
|
||||
import { createGeoJsonSlice, type GeoJsonSlice } from "./geojsonSlice";
|
||||
|
||||
// Re-export slice types for convenience
|
||||
/**
|
||||
* Re-exporting slice types for easier access from components and utilities.
|
||||
*/
|
||||
export type { MapConfig, DataConfig } from "./configSlice";
|
||||
export type { LayerState } from "./layersSlice";
|
||||
export type { ImportedLayer } from "./geojsonSlice";
|
||||
@@ -27,6 +35,12 @@ export type AppStore = GlobeSlice &
|
||||
FavoritesSlice &
|
||||
GeoJsonSlice;
|
||||
|
||||
/**
|
||||
* The primary hook for accessing and modifying the application state.
|
||||
*
|
||||
* This combined store provides access to all nine state slices:
|
||||
* globe, layers, timeline, ui, filter, data, config, favorites, and geojson.
|
||||
*/
|
||||
export const useStore = create<AppStore>((...args) => ({
|
||||
...createGlobeSlice(...args),
|
||||
...createLayersSlice(...args),
|
||||
|
||||
@@ -1,24 +1,49 @@
|
||||
/**
|
||||
* @file timelineSlice.ts
|
||||
* @description State slice managing the application's temporal context, including time windows,
|
||||
* playback controls, and historical data availability.
|
||||
*/
|
||||
|
||||
import type { StateCreator } from "zustand";
|
||||
import type { AppStore } from "./store";
|
||||
import type { TimeRange, TimeWindow } from "@/core/plugins/PluginTypes";
|
||||
|
||||
// ─── Timeline Slice ──────────────────────────────────────────
|
||||
/**
|
||||
* Zustand state slice for temporal management and historical playback.
|
||||
*/
|
||||
export interface TimelineSlice {
|
||||
/** The active reference time for data filtering and display. */
|
||||
currentTime: Date;
|
||||
/** The selected duration for the historical window (e.g., "1h", "24h"). */
|
||||
timeWindow: TimeWindow;
|
||||
/** The absolute start and end dates derived from the timeWindow. */
|
||||
timeRange: TimeRange;
|
||||
/** Whether historical playback animation is currently active. */
|
||||
isPlaying: boolean;
|
||||
/** The multiplier for playback speed (e.g., 1x, 10x, 100x). */
|
||||
playbackSpeed: number;
|
||||
/** Whether the application is in "Live" mode or "Playback" mode. */
|
||||
isPlaybackMode: boolean;
|
||||
/** The Unix timestamp representing the current position in the playback loop. */
|
||||
playbackTime: number;
|
||||
/** Map of plugin IDs to arrays of available time intervals for historical data. */
|
||||
timelineAvailability: Record<string, { start: number; end: number }[]>;
|
||||
/** Updates the reference current time. */
|
||||
setCurrentTime: (time: Date) => void;
|
||||
/** Updates the active time window and re-calculates the absolute time range. */
|
||||
setTimeWindow: (window: TimeWindow) => void;
|
||||
/** Manually overrides the absolute time range. */
|
||||
setTimeRange: (range: TimeRange) => void;
|
||||
/** Toggles the playback animation state. */
|
||||
setPlaying: (playing: boolean) => void;
|
||||
/** Updates the playback speed multiplier. */
|
||||
setPlaybackSpeed: (speed: number) => void;
|
||||
/** Toggles between live and historical playback modes. */
|
||||
setPlaybackMode: (mode: boolean) => void;
|
||||
/** Updates the current position in the playback timeline. */
|
||||
setPlaybackTime: (time: number) => void;
|
||||
/** Updates the known historical data availability for a specific plugin. */
|
||||
setTimelineAvailability: (pluginId: string, availability: { start: number; end: number }[]) => void;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,56 +1,113 @@
|
||||
/**
|
||||
* @file uiSlice.ts
|
||||
* @description State slice managing the application's user interface, including themes,
|
||||
* sidebars, panels, entity selection, and floating data streams.
|
||||
*/
|
||||
|
||||
import type { StateCreator } from "zustand";
|
||||
import type { AppStore } from "./store";
|
||||
import type { GeoEntity } from "@/core/plugins/PluginTypes";
|
||||
|
||||
// ─── UI Slice ────────────────────────────────────────────────
|
||||
/**
|
||||
* Represents a floating window container for external data streams (e.g., video feeds, telemetry iframes).
|
||||
*/
|
||||
export interface FloatingStream {
|
||||
/** Unique identifier for the stream window. */
|
||||
id: string;
|
||||
/** The source URL for the stream content. */
|
||||
streamUrl: string;
|
||||
/** Whether to render the content inside an iframe. */
|
||||
isIframe: boolean;
|
||||
/** Human-readable label for the window header. */
|
||||
label: string;
|
||||
/** Screen coordinates of the window's top-left corner. */
|
||||
position: { x: number; y: number };
|
||||
/** Dimensions of the floating window. */
|
||||
size: { width: number; height: number };
|
||||
/** Whether the window is currently collapsed to its header. */
|
||||
isMinimized?: boolean;
|
||||
/** Hint for content rendering optimization. */
|
||||
type?: "video" | "image";
|
||||
}
|
||||
|
||||
/**
|
||||
* Zustand state slice for managing HUD visibility and UI interactions.
|
||||
*/
|
||||
export interface UISlice {
|
||||
/** The active visual theme. */
|
||||
theme: "dark" | "light" | "legacy" | "black";
|
||||
/** Visibility of the left navigation/plugin sidebar. */
|
||||
leftSidebarOpen: boolean;
|
||||
/** Visibility of the right details/intel sidebar. */
|
||||
rightSidebarOpen: boolean;
|
||||
/** Visibility of the main configuration/settings panel. */
|
||||
configPanelOpen: boolean;
|
||||
/** Visibility of the global filtering panel. */
|
||||
filterPanelOpen: boolean;
|
||||
/** The currently clicked/selected entity for details view. */
|
||||
selectedEntity: GeoEntity | null;
|
||||
/** The entity currently under the mouse cursor. */
|
||||
hoveredEntity: GeoEntity | null;
|
||||
/** Screen coordinates of the current hover target for tooltips. */
|
||||
hoveredScreenPosition: { x: number; y: number } | null;
|
||||
/** The ID of an entity the camera is currently following or focused on. */
|
||||
lockedEntityId: string | null;
|
||||
/** List of active floating stream windows. */
|
||||
floatingStreams: FloatingStream[];
|
||||
/** The active sub-tab within the configuration panel. */
|
||||
activeConfigTab: "intel" | "filters" | "cache" | "overlay" | "apikeys";
|
||||
/** The ID of a layer currently being highlighted/flashed in the UI. */
|
||||
highlightLayerId: string | null;
|
||||
/** Active panel in mobile view layout. */
|
||||
openMobilePanel: "left" | "right" | null;
|
||||
/** Whether to show a notification glow on the mobile right panel button. */
|
||||
mobileRightPanelGlow: boolean;
|
||||
/** Cycles through available UI themes. */
|
||||
toggleTheme: () => void;
|
||||
/** Directly sets a specific UI theme. */
|
||||
setTheme: (theme: "dark" | "light" | "legacy" | "black") => void;
|
||||
/** Toggles the left sidebar state. */
|
||||
toggleLeftSidebar: () => void;
|
||||
/** Toggles the right sidebar state. */
|
||||
toggleRightSidebar: () => void;
|
||||
/** Toggles the central config panel state. */
|
||||
toggleConfigPanel: () => void;
|
||||
/** Toggles the filter panel state. */
|
||||
toggleFilterPanel: () => void;
|
||||
/** Visibility of the user feedback submission dialog. */
|
||||
feedbackDialogOpen: boolean;
|
||||
/** Sets the feedback dialog visibility. */
|
||||
setFeedbackDialogOpen: (open: boolean) => void;
|
||||
/** Selects an entity and opens relevant panels for details display. */
|
||||
setSelectedEntity: (entity: GeoEntity | null) => void;
|
||||
/** Updates the currently hovered entity and its screen position. */
|
||||
setHoveredEntity: (entity: GeoEntity | null, screenPos?: { x: number; y: number } | null) => void;
|
||||
/** Sets the ID of the entity to lock the camera onto. */
|
||||
setLockedEntityId: (id: string | null) => void;
|
||||
/** Spawns a new floating stream window. */
|
||||
addFloatingStream: (stream: Omit<FloatingStream, "position" | "size">) => void;
|
||||
/** Closes a floating stream window by ID. */
|
||||
removeFloatingStream: (id: string) => void;
|
||||
/** Updates properties (position, size, state) of an existing stream window. */
|
||||
updateFloatingStream: (id: string, updates: Partial<FloatingStream>) => void;
|
||||
/** Switches between configuration tabs. */
|
||||
setActiveConfigTab: (tab: "intel" | "filters" | "cache" | "overlay" | "apikeys") => void;
|
||||
/** Triggers a visual highlight on a specific layer in the layer list. */
|
||||
setHighlightLayerId: (id: string | null) => void;
|
||||
/** Explicitly sets the configuration panel visibility. */
|
||||
setConfigPanelOpen: (open: boolean) => void;
|
||||
/** Controls which panel is visible in responsive/mobile layouts. */
|
||||
setOpenMobilePanel: (panel: "left" | "right" | null) => void;
|
||||
/** The current message displayed in the global error toast, if any. */
|
||||
errorToastMessage: string | null;
|
||||
/** Triggers a global error notification toast. */
|
||||
showErrorToast: (message: string) => void;
|
||||
/** Dismisses the active error toast. */
|
||||
clearErrorToast: () => void;
|
||||
/** Visibility of the temporal timeline controller. */
|
||||
timelineOpen: boolean;
|
||||
/** Sets the timeline visibility. */
|
||||
setTimelineOpen: (open: boolean) => void;
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,11 @@ function fakeRequest(origin?: string): Request {
|
||||
|
||||
describe("CORS utility", () => {
|
||||
describe("corsHeaders", () => {
|
||||
it("returns empty object if no origin is provided", () => {
|
||||
const headers = corsHeaders(fakeRequest(""));
|
||||
expect(headers).toEqual({});
|
||||
});
|
||||
|
||||
it("returns allowed origin for localhost:3001", () => {
|
||||
const headers = corsHeaders(fakeRequest("http://localhost:3001"));
|
||||
expect(headers["Access-Control-Allow-Origin"]).toBe("http://localhost:3001");
|
||||
|
||||
@@ -97,4 +97,25 @@ describe("marketplaceToken", () => {
|
||||
await expect(verifyMarketplaceToken(noSub)).rejects.toThrow("subject");
|
||||
});
|
||||
});
|
||||
|
||||
describe("revokeMarketplaceToken", () => {
|
||||
it("revokes a token and rejects it on verify", async () => {
|
||||
const { revokeMarketplaceToken } = await import("./marketplaceToken");
|
||||
const token = await issueMarketplaceToken(TEST_USER_ID);
|
||||
const payload = await verifyMarketplaceToken(token);
|
||||
|
||||
expect(payload.jti).toBeDefined();
|
||||
|
||||
// Revoke it
|
||||
revokeMarketplaceToken(payload.jti!);
|
||||
|
||||
// Now it should throw
|
||||
await expect(verifyMarketplaceToken(token)).rejects.toThrow("revoked");
|
||||
});
|
||||
|
||||
it("does nothing when passed an empty jti", async () => {
|
||||
const { revokeMarketplaceToken } = await import("./marketplaceToken");
|
||||
expect(() => revokeMarketplaceToken("")).not.toThrow();
|
||||
});
|
||||
});
|
||||
});
|
||||
+14
-1
@@ -10,6 +10,19 @@ export default defineConfig({
|
||||
alias: {
|
||||
'@': path.resolve(__dirname, './src'),
|
||||
},
|
||||
include: ['src/lib/**/*.{test,spec}.{js,ts,jsx,tsx}', 'src/core/**/*.{test,spec}.{js,ts,jsx,tsx}', 'src/plugins/**/*.{test,spec}.{js,ts,jsx,tsx}', 'packages/**/*.{test,spec}.{js,ts,jsx,tsx}'],
|
||||
include: [
|
||||
'src/lib/**/*.{test,spec}.{js,ts,jsx,tsx}',
|
||||
'src/core/**/*.{test,spec}.{js,ts,jsx,tsx}',
|
||||
'src/plugins/**/*.{test,spec}.{js,ts,jsx,tsx}',
|
||||
'src/app/**/*.{test,spec}.{js,ts,jsx,tsx}',
|
||||
'packages/**/*.{test,spec}.{js,ts,jsx,tsx}',
|
||||
],
|
||||
coverage: {
|
||||
thresholds: {
|
||||
branches: 80,
|
||||
functions: 80,
|
||||
statements: 80,
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user