Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
34951de90d | ||
|
|
b849bb2b4d | ||
|
|
fc7dd02ee2 |
No files matched your search
+6
-8
@@ -1,7 +1,7 @@
|
|||||||
import nextCoreWebVitals from "eslint-config-next/core-web-vitals";
|
import nextCoreWebVitals from "eslint-config-next/core-web-vitals";
|
||||||
import nextTypeScript from "eslint-config-next/typescript";
|
import nextTypeScript from "eslint-config-next/typescript";
|
||||||
|
|
||||||
export default [
|
const config = [
|
||||||
{
|
{
|
||||||
ignores: [
|
ignores: [
|
||||||
"node_modules/**",
|
"node_modules/**",
|
||||||
@@ -16,6 +16,8 @@ export default [
|
|||||||
"local-seeders/**",
|
"local-seeders/**",
|
||||||
".agents/**",
|
".agents/**",
|
||||||
".claude/**",
|
".claude/**",
|
||||||
|
".gemini/**",
|
||||||
|
"*.cjs",
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
...nextCoreWebVitals,
|
...nextCoreWebVitals,
|
||||||
@@ -35,18 +37,14 @@ export default [
|
|||||||
"@typescript-eslint/no-explicit-any": "warn",
|
"@typescript-eslint/no-explicit-any": "warn",
|
||||||
"no-console": "warn",
|
"no-console": "warn",
|
||||||
|
|
||||||
// React 19 hook-purity rules from eslint-plugin-react-hooks 7+:
|
|
||||||
"react-hooks/purity": "warn",
|
|
||||||
"react-hooks/refs": "warn",
|
|
||||||
"react-hooks/set-state-in-effect": "warn",
|
|
||||||
"react-hooks/immutability": "warn",
|
|
||||||
"react-hooks/static-components": "warn",
|
|
||||||
|
|
||||||
// Misc one-offs across the codebase:
|
// Misc one-offs across the codebase:
|
||||||
"react/no-unescaped-entities": "warn",
|
|
||||||
"@typescript-eslint/ban-ts-comment": "warn",
|
"@typescript-eslint/ban-ts-comment": "warn",
|
||||||
"@next/next/no-assign-module-variable": "warn",
|
"@next/next/no-assign-module-variable": "warn",
|
||||||
"prefer-const": "warn",
|
"prefer-const": "warn",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
export default config;
|
||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "worldwideview",
|
"name": "worldwideview",
|
||||||
"version": "2.15.7",
|
"version": "2.15.10",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"packageManager": "[email protected]",
|
"packageManager": "[email protected]",
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable no-console */
|
||||||
import { Command } from 'commander';
|
import { Command } from 'commander';
|
||||||
import { saveConfig } from '../utils/config.js';
|
import { saveConfig } from '../utils/config.js';
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable no-console */
|
||||||
import { Command } from 'commander';
|
import { Command } from 'commander';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
|
|||||||
@@ -50,7 +50,7 @@ export const publishCommand = new Command('publish')
|
|||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
let originalName = pkgContent.name;
|
const originalName = pkgContent.name;
|
||||||
let publishedName = originalName;
|
let publishedName = originalName;
|
||||||
|
|
||||||
// Determine organization
|
// Determine organization
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
|
||||||
import { describe, it, expectTypeOf } from "vitest";
|
import { describe, it, expectTypeOf } from "vitest";
|
||||||
import type {
|
import type {
|
||||||
TokenExchangeRequest,
|
TokenExchangeRequest,
|
||||||
@@ -21,7 +22,8 @@ describe("Auth Contracts", () => {
|
|||||||
expectTypeOf<TokenExchangeRequest>().toHaveProperty("audience").toEqualTypeOf<string>();
|
expectTypeOf<TokenExchangeRequest>().toHaveProperty("audience").toEqualTypeOf<string>();
|
||||||
|
|
||||||
// @ts-expect-error - missing required apiKey
|
// @ts-expect-error - missing required apiKey
|
||||||
const badReq: TokenExchangeRequest = { audience: "engine-123" };
|
const _badReq: TokenExchangeRequest = { audience: "engine-123" };
|
||||||
|
void _badReq;
|
||||||
});
|
});
|
||||||
|
|
||||||
it("TokenExchangeResponse has exact required properties", () => {
|
it("TokenExchangeResponse has exact required properties", () => {
|
||||||
@@ -31,7 +33,8 @@ describe("Auth Contracts", () => {
|
|||||||
expectTypeOf<TokenExchangeResponse>().toHaveProperty("tier").toEqualTypeOf<Tier | undefined>();
|
expectTypeOf<TokenExchangeResponse>().toHaveProperty("tier").toEqualTypeOf<Tier | undefined>();
|
||||||
|
|
||||||
// @ts-expect-error - missing required token
|
// @ts-expect-error - missing required token
|
||||||
const badRes: TokenExchangeResponse = { expiresAt: 123456789, kid: "key-1" };
|
const _badRes: TokenExchangeResponse = { expiresAt: 123456789, kid: "key-1" };
|
||||||
|
void _badRes;
|
||||||
});
|
});
|
||||||
|
|
||||||
it("WebSocketAuthMessage has exact required properties including protocol version", () => {
|
it("WebSocketAuthMessage has exact required properties including protocol version", () => {
|
||||||
@@ -40,10 +43,12 @@ describe("Auth Contracts", () => {
|
|||||||
expectTypeOf<WebSocketAuthMessage>().toHaveProperty("token").toEqualTypeOf<SensitiveString>();
|
expectTypeOf<WebSocketAuthMessage>().toHaveProperty("token").toEqualTypeOf<SensitiveString>();
|
||||||
|
|
||||||
// @ts-expect-error - missing version
|
// @ts-expect-error - missing version
|
||||||
const badMsg: WebSocketAuthMessage = { type: "auth", token: "jwt-token-here" as SensitiveString };
|
const _badMsg: WebSocketAuthMessage = { type: "auth", token: "jwt-token-here" as SensitiveString };
|
||||||
|
void _badMsg;
|
||||||
|
|
||||||
// @ts-expect-error - wrong version
|
// @ts-expect-error - wrong version
|
||||||
const badVersion: WebSocketAuthMessage = { type: "auth", v: 2, token: "jwt-token-here" as SensitiveString };
|
const _badVersion: WebSocketAuthMessage = { type: "auth", v: 2, token: "jwt-token-here" as SensitiveString };
|
||||||
|
void _badVersion;
|
||||||
});
|
});
|
||||||
|
|
||||||
it("WebSocketMessage is a discriminated union correctly containing WebSocketAuthMessage", () => {
|
it("WebSocketMessage is a discriminated union correctly containing WebSocketAuthMessage", () => {
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ function copyDir(src, dest) {
|
|||||||
}
|
}
|
||||||
const entries = fs.readdirSync(src, { withFileTypes: true });
|
const entries = fs.readdirSync(src, { withFileTypes: true });
|
||||||
|
|
||||||
for (let entry of entries) {
|
for (const entry of entries) {
|
||||||
const srcPath = path.join(src, entry.name);
|
const srcPath = path.join(src, entry.name);
|
||||||
const destPath = path.join(dest, entry.name);
|
const destPath = path.join(dest, entry.name);
|
||||||
|
|
||||||
|
|||||||
@@ -47,18 +47,19 @@ export async function GET(req: NextRequest) {
|
|||||||
headers: { "User-Agent": "WorldWideView/1.0" },
|
headers: { "User-Agent": "WorldWideView/1.0" },
|
||||||
signal: AbortSignal.timeout(TIMEOUT_MS)
|
signal: AbortSignal.timeout(TIMEOUT_MS)
|
||||||
});
|
});
|
||||||
} catch (headError: any) {
|
} catch (headError: unknown) {
|
||||||
|
const err = headError as Error & { cause?: { code?: string } };
|
||||||
// Primitive IP camera servers (like Insecam sources) often aggressively drop the TCP connection
|
// Primitive IP camera servers (like Insecam sources) often aggressively drop the TCP connection
|
||||||
// instead of returning 405 when they see an unsupported HTTP method like HEAD.
|
// instead of returning 405 when they see an unsupported HTTP method like HEAD.
|
||||||
// If the socket was closed unexpectedly, retry with GET.
|
// If the socket was closed unexpectedly, retry with GET.
|
||||||
if (headError.cause?.code === 'UND_ERR_SOCKET' || headError.message?.includes('fetch failed')) {
|
if (err.cause?.code === 'UND_ERR_SOCKET' || err.message?.includes('fetch failed')) {
|
||||||
response = await fetch(url, {
|
response = await fetch(url, {
|
||||||
method: "GET",
|
method: "GET",
|
||||||
headers: { "User-Agent": "WorldWideView/1.0" },
|
headers: { "User-Agent": "WorldWideView/1.0" },
|
||||||
signal: AbortSignal.timeout(TIMEOUT_MS)
|
signal: AbortSignal.timeout(TIMEOUT_MS)
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
throw headError;
|
throw err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -81,13 +82,14 @@ export async function GET(req: NextRequest) {
|
|||||||
contentType: response.headers.get("content-type"),
|
contentType: response.headers.get("content-type"),
|
||||||
latencyMs: Date.now() - startTime
|
latencyMs: Date.now() - startTime
|
||||||
});
|
});
|
||||||
} catch (error: any) {
|
} catch (error: unknown) {
|
||||||
const realError = error.cause || error;
|
const err = error as Error & { cause?: { code?: string, message?: string, name?: string }, code?: string };
|
||||||
const code = realError?.code || error?.code || realError?.name || error?.name;
|
const realError = err.cause || err;
|
||||||
|
const code = realError?.code || err?.code || realError?.name || err?.name;
|
||||||
|
|
||||||
let displayError = error?.message || "Unknown error";
|
let displayError = err?.message || "Unknown error";
|
||||||
if (code && code !== 'TypeError' && code !== 'Error') {
|
if (code && code !== 'TypeError' && code !== 'Error') {
|
||||||
displayError = `[${code}] ${realError?.message || error?.message || ""}`;
|
displayError = `[${code}] ${realError?.message || err?.message || ""}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Make sure we don't accidentally categorize a malformed HTTP response as a timeout
|
// Make sure we don't accidentally categorize a malformed HTTP response as a timeout
|
||||||
@@ -95,7 +97,7 @@ export async function GET(req: NextRequest) {
|
|||||||
return NextResponse.json({ status: "error", error: displayError, latencyMs: Date.now() - startTime });
|
return NextResponse.json({ status: "error", error: displayError, latencyMs: Date.now() - startTime });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (error?.name === "TimeoutError" || displayError.includes("timeout") || code === "UND_ERR_CONNECT_TIMEOUT") {
|
if (err?.name === "TimeoutError" || displayError.includes("timeout") || code === "UND_ERR_CONNECT_TIMEOUT") {
|
||||||
return NextResponse.json({ status: "timeout", error: "Connection timed out", latencyMs: Date.now() - startTime });
|
return NextResponse.json({ status: "timeout", error: "Connection timed out", latencyMs: Date.now() - startTime });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
|
||||||
|
export const revalidate = 60;
|
||||||
|
|
||||||
|
const WTIA_POSITIONS_URL = "https://api.wheretheiss.at/v1/satellites/25544/positions";
|
||||||
|
const MAX_TIMESTAMPS = 10;
|
||||||
|
|
||||||
|
function isValidPosition(item: any): boolean {
|
||||||
|
return (
|
||||||
|
item != null
|
||||||
|
&& typeof item === "object"
|
||||||
|
&& Number.isFinite(item.latitude)
|
||||||
|
&& Number.isFinite(item.longitude)
|
||||||
|
&& Number.isFinite(item.altitude)
|
||||||
|
&& Number.isFinite(item.velocity)
|
||||||
|
&& Number.isFinite(item.timestamp)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function GET(request: Request) {
|
||||||
|
const { searchParams } = new URL(request.url);
|
||||||
|
const timestampsParam = searchParams.get("timestamps");
|
||||||
|
|
||||||
|
if (!timestampsParam) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Missing required 'timestamps' query parameter" },
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const timestamps = timestampsParam
|
||||||
|
.split(",")
|
||||||
|
.map((t) => t.trim())
|
||||||
|
.filter((t) => /^\d+$/.test(t));
|
||||||
|
|
||||||
|
if (timestamps.length === 0) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "No valid timestamps provided" },
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (timestamps.length > MAX_TIMESTAMPS) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: `Maximum ${MAX_TIMESTAMPS} timestamps allowed per request` },
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const url = `${WTIA_POSITIONS_URL}?timestamps=${timestamps.join(",")}&units=kilometers`;
|
||||||
|
|
||||||
|
const response = await fetch(url, {
|
||||||
|
headers: {
|
||||||
|
Accept: "application/json",
|
||||||
|
"User-Agent": "WorldWideView/1.0",
|
||||||
|
},
|
||||||
|
next: { revalidate },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Failed to fetch ISS positions" },
|
||||||
|
{ status: 502 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
const positions = (Array.isArray(data) ? data : [])
|
||||||
|
.filter(isValidPosition)
|
||||||
|
.map((p) => ({
|
||||||
|
latitude: p.latitude,
|
||||||
|
longitude: p.longitude,
|
||||||
|
altitude: p.altitude,
|
||||||
|
velocity: p.velocity,
|
||||||
|
visibility: p.visibility,
|
||||||
|
timestamp: p.timestamp,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return NextResponse.json({ positions });
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[IssPositionsRoute] Error:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Failed to fetch ISS positions" },
|
||||||
|
{ status: 502 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
|
||||||
|
export const revalidate = 10;
|
||||||
|
|
||||||
|
const WTIA_URL = "https://api.wheretheiss.at/v1/satellites/25544";
|
||||||
|
|
||||||
|
function isValidResponse(data: any): boolean {
|
||||||
|
return (
|
||||||
|
data != null
|
||||||
|
&& typeof data === "object"
|
||||||
|
&& Number.isFinite(data.latitude)
|
||||||
|
&& Number.isFinite(data.longitude)
|
||||||
|
&& Number.isFinite(data.altitude)
|
||||||
|
&& Number.isFinite(data.velocity)
|
||||||
|
&& Number.isFinite(data.timestamp)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
try {
|
||||||
|
const response = await fetch(WTIA_URL, {
|
||||||
|
headers: {
|
||||||
|
Accept: "application/json",
|
||||||
|
"User-Agent": "WorldWideView/1.0",
|
||||||
|
},
|
||||||
|
next: { revalidate },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Failed to fetch ISS position" },
|
||||||
|
{ status: 502 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (!isValidResponse(data)) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Invalid ISS position data" },
|
||||||
|
{ status: 502 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
id: data.id,
|
||||||
|
name: data.name,
|
||||||
|
latitude: data.latitude,
|
||||||
|
longitude: data.longitude,
|
||||||
|
altitude: data.altitude,
|
||||||
|
velocity: data.velocity,
|
||||||
|
visibility: data.visibility,
|
||||||
|
footprint: data.footprint,
|
||||||
|
timestamp: data.timestamp,
|
||||||
|
units: data.units,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[IssRoute] Error:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Failed to fetch ISS position" },
|
||||||
|
{ status: 502 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
|
||||||
|
export const revalidate = 3600;
|
||||||
|
|
||||||
|
const WTIA_TLE_URL = "https://api.wheretheiss.at/v1/satellites/25544/tles/latest";
|
||||||
|
|
||||||
|
function isValidTle(data: any): boolean {
|
||||||
|
return (
|
||||||
|
data != null
|
||||||
|
&& typeof data === "object"
|
||||||
|
&& typeof data.line1 === "string"
|
||||||
|
&& typeof data.line2 === "string"
|
||||||
|
&& data.line1.length > 0
|
||||||
|
&& data.line2.length > 0
|
||||||
|
&& Number.isFinite(data.tle_timestamp)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
try {
|
||||||
|
const response = await fetch(WTIA_TLE_URL, {
|
||||||
|
headers: {
|
||||||
|
Accept: "application/json",
|
||||||
|
"User-Agent": "WorldWideView/1.0",
|
||||||
|
},
|
||||||
|
next: { revalidate },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Failed to fetch ISS TLE data" },
|
||||||
|
{ status: 502 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (!isValidTle(data)) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Invalid ISS TLE data" },
|
||||||
|
{ status: 502 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
id: data.id,
|
||||||
|
name: data.name,
|
||||||
|
header: data.header,
|
||||||
|
line1: data.line1,
|
||||||
|
line2: data.line2,
|
||||||
|
tleTimestamp: data.tle_timestamp,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[IssTleRoute] Error:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Failed to fetch ISS TLE data" },
|
||||||
|
{ status: 502 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,15 +3,18 @@ import { CameraStream } from "@/components/video/CameraStream";
|
|||||||
import styles from "./page.module.css";
|
import styles from "./page.module.css";
|
||||||
import type { TestResult } from "./types";
|
import type { TestResult } from "./types";
|
||||||
|
|
||||||
function LiveTimer({ start }: { start: number }) {
|
function LiveTimer({ start }: { start?: number }) {
|
||||||
const [now, setNow] = useState(Date.now());
|
const [now, setNow] = useState(() => Date.now());
|
||||||
|
const [fallbackStart] = useState(() => Date.now());
|
||||||
|
const effectiveStart = start || fallbackStart;
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const interval = setInterval(() => setNow(Date.now()), 100);
|
const interval = setInterval(() => setNow(Date.now()), 100);
|
||||||
return () => clearInterval(interval);
|
return () => clearInterval(interval);
|
||||||
}, []);
|
}, []);
|
||||||
return (
|
return (
|
||||||
<span>
|
<span>
|
||||||
{(Math.max(0, now - start) / 1000).toFixed(1)}
|
{(Math.max(0, now - effectiveStart) / 1000).toFixed(1)}
|
||||||
s
|
s
|
||||||
</span>
|
</span>
|
||||||
);
|
);
|
||||||
@@ -53,7 +56,7 @@ export function CameraTestCard({
|
|||||||
{status === "testing" ? (
|
{status === "testing" ? (
|
||||||
<>
|
<>
|
||||||
Testing...
|
Testing...
|
||||||
<LiveTimer start={result.testStartTime || Date.now()} />
|
<LiveTimer start={result.testStartTime} />
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
status.toUpperCase()
|
status.toUpperCase()
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import {
|
|||||||
useState, useRef, useEffect, useCallback
|
useState, useRef, useEffect, useCallback
|
||||||
} from "react";
|
} from "react";
|
||||||
import type { TestResult } from "./types";
|
import type { TestResult } from "./types";
|
||||||
|
import type { GdotCameraFeature } from "@/app/api/camera/gdot/gdotFetcher";
|
||||||
|
|
||||||
export function useCameraTestRunner(testSources: string[], testStatuses: string[]) {
|
export function useCameraTestRunner(testSources: string[], testStatuses: string[]) {
|
||||||
const [cameras, setCameras] = useState<TestResult[]>([]);
|
const [cameras, setCameras] = useState<TestResult[]>([]);
|
||||||
@@ -15,44 +16,48 @@ export function useCameraTestRunner(testSources: string[], testStatuses: string[
|
|||||||
const res = await fetch("/api/camera/traffic");
|
const res = await fetch("/api/camera/traffic");
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
|
|
||||||
let staticFeatures: any[] = [];
|
let staticFeatures: GdotCameraFeature[] = [];
|
||||||
try {
|
try {
|
||||||
const staticRes = await fetch("/public-cameras.json");
|
const staticRes = await fetch("/public-cameras.json");
|
||||||
if (staticRes.ok) {
|
if (staticRes.ok) {
|
||||||
const staticData = await staticRes.json();
|
const staticData = await staticRes.json();
|
||||||
if (staticData.features) {
|
if (staticData.features) {
|
||||||
staticFeatures = staticData.features.map((f: any) => ({
|
staticFeatures = staticData.features.map((f: Record<string, unknown>) => {
|
||||||
...f,
|
const props = (f.properties || {}) as Record<string, unknown>;
|
||||||
properties: {
|
return {
|
||||||
...f.properties,
|
...f,
|
||||||
name: f.properties.city || f.properties.region || "Public Camera",
|
properties: {
|
||||||
source: f.properties.source || "cameras_json"
|
...props,
|
||||||
}
|
name: props.city || props.region || "Public Camera",
|
||||||
}));
|
source: props.source || "cameras_json"
|
||||||
|
}
|
||||||
|
} as unknown as GdotCameraFeature;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (staticErr) {
|
} catch (staticErr) {
|
||||||
console.error("Failed to fetch static cameras:", staticErr);
|
void staticErr; // Ignore static fetch errors
|
||||||
}
|
}
|
||||||
|
|
||||||
let combinedFeatures: any[] = [];
|
let combinedFeatures: GdotCameraFeature[] = [];
|
||||||
if (data.cameras) {
|
if (data.cameras) {
|
||||||
combinedFeatures = [...data.cameras];
|
combinedFeatures = [...data.cameras];
|
||||||
}
|
}
|
||||||
combinedFeatures = [...combinedFeatures, ...staticFeatures];
|
combinedFeatures = [...combinedFeatures, ...staticFeatures];
|
||||||
|
|
||||||
setCameras(combinedFeatures.map((c: any) => ({
|
setCameras(combinedFeatures.map((c: GdotCameraFeature) => ({
|
||||||
feature: c,
|
feature: c,
|
||||||
status: "pending"
|
status: "pending"
|
||||||
})));
|
})));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
void err; // Ignore errors
|
||||||
}
|
}
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchCameras();
|
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||||
|
void fetchCameras();
|
||||||
}, [fetchCameras]);
|
}, [fetchCameras]);
|
||||||
|
|
||||||
const runTests = async () => {
|
const runTests = async () => {
|
||||||
@@ -204,13 +209,14 @@ export function useCameraTestRunner(testSources: string[], testStatuses: string[
|
|||||||
};
|
};
|
||||||
return nextState;
|
return nextState;
|
||||||
});
|
});
|
||||||
} catch (err: any) {
|
} catch (err: unknown) {
|
||||||
|
const errorMsg = err instanceof Error ? err.message : String(err);
|
||||||
setCameras((prev) => {
|
setCameras((prev) => {
|
||||||
const nextState = [...prev];
|
const nextState = [...prev];
|
||||||
nextState[globalIndex] = {
|
nextState[globalIndex] = {
|
||||||
...nextState[globalIndex],
|
...nextState[globalIndex],
|
||||||
status: "error",
|
status: "error",
|
||||||
errorMsg: err.message
|
errorMsg
|
||||||
};
|
};
|
||||||
return nextState;
|
return nextState;
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -102,6 +102,7 @@ export function AgentBusSubscriber() {
|
|||||||
const buildId = process.env.NEXT_PUBLIC_WWV_BUILD_ID ?? "dev";
|
const buildId = process.env.NEXT_PUBLIC_WWV_BUILD_ID ?? "dev";
|
||||||
const builtAt = process.env.NEXT_PUBLIC_WWV_BUILD_AT ?? "";
|
const builtAt = process.env.NEXT_PUBLIC_WWV_BUILD_AT ?? "";
|
||||||
const agentBusEnabled = process.env.NEXT_PUBLIC_WWV_AGENT_BUS_ENABLED === "true";
|
const agentBusEnabled = process.env.NEXT_PUBLIC_WWV_AGENT_BUS_ENABLED === "true";
|
||||||
|
// eslint-disable-next-line no-console
|
||||||
console.log(
|
console.log(
|
||||||
`[wwv build] id=${buildId} built_at=${builtAt} agent_bus=${agentBusEnabled ? "on" : "off"}`,
|
`[wwv build] id=${buildId} built_at=${builtAt} agent_bus=${agentBusEnabled ? "on" : "off"}`,
|
||||||
);
|
);
|
||||||
@@ -115,12 +116,14 @@ export function AgentBusSubscriber() {
|
|||||||
const msg = JSON.parse(event.data) as AgentMessage;
|
const msg = JSON.parse(event.data) as AgentMessage;
|
||||||
applyAction(msg);
|
applyAction(msg);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
// eslint-disable-next-line no-console
|
||||||
console.warn("[AgentBus] malformed message", err);
|
console.warn("[AgentBus] malformed message", err);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
es.onerror = (err) => {
|
es.onerror = (err) => {
|
||||||
// EventSource auto-reconnects on its own with the `retry:` value
|
// EventSource auto-reconnects on its own with the `retry:` value
|
||||||
// we send from the server. Just log; don't tear down.
|
// we send from the server. Just log; don't tear down.
|
||||||
|
// eslint-disable-next-line no-console
|
||||||
console.debug("[AgentBus] stream error (auto-reconnecting)", err);
|
console.debug("[AgentBus] stream error (auto-reconnecting)", err);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ export function AppShell() {
|
|||||||
const initLayer = useStore((s) => s.initLayer);
|
const initLayer = useStore((s) => s.initLayer);
|
||||||
const boot = useBootSequence();
|
const boot = useBootSequence();
|
||||||
const isMobile = useIsMobile();
|
const isMobile = useIsMobile();
|
||||||
const bootStartRef = useRef(Date.now());
|
const [bootStart] = useState(() => Date.now());
|
||||||
const [hostReady, setHostReady] = useState(false);
|
const [hostReady, setHostReady] = useState(false);
|
||||||
const {
|
const {
|
||||||
needsReload, pendingUnverified, approveSelected, denyAll
|
needsReload, pendingUnverified, approveSelected, denyAll
|
||||||
@@ -153,10 +153,10 @@ export function AppShell() {
|
|||||||
// Track when boot completes
|
// Track when boot completes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (boot.phase === "ready") {
|
if (boot.phase === "ready") {
|
||||||
const duration = Date.now() - bootStartRef.current;
|
const duration = Date.now() - bootStart;
|
||||||
trackEvent("platform-boot", { duration });
|
trackEvent("platform-boot", { duration });
|
||||||
}
|
}
|
||||||
}, [boot.phase]);
|
}, [boot.phase, bootStart]);
|
||||||
const activeBottomPanel = useStore((s) => s.activeBottomPanel);
|
const activeBottomPanel = useStore((s) => s.activeBottomPanel);
|
||||||
|
|
||||||
const rootClasses = [
|
const rootClasses = [
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ export function BottomPanelManager() {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (activeBottomPanel) {
|
if (activeBottomPanel) {
|
||||||
|
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||||
setMountedPanel(activeBottomPanel);
|
setMountedPanel(activeBottomPanel);
|
||||||
} else {
|
} else {
|
||||||
// Keep the panel mounted for the duration of the CSS exit transition (400ms)
|
// Keep the panel mounted for the duration of the CSS exit transition (400ms)
|
||||||
|
|||||||
@@ -46,14 +46,14 @@ export function useSearch() {
|
|||||||
const flatResults = sections.flatMap((s) => s.results);
|
const flatResults = sections.flatMap((s) => s.results);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!query.trim()) {
|
|
||||||
setLiveSections((prev) => (prev.length === 0 ? prev : []));
|
|
||||||
setSelectedIndex((prev) => (prev === 0 ? prev : 0));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let isStale = false;
|
let isStale = false;
|
||||||
|
|
||||||
const run = async () => {
|
const run = async () => {
|
||||||
|
if (!query.trim()) {
|
||||||
|
setLiveSections((prev) => (prev.length === 0 ? prev : []));
|
||||||
|
setSelectedIndex((prev) => (prev === 0 ? prev : 0));
|
||||||
|
return;
|
||||||
|
}
|
||||||
const currentLayers = useStore.getState().layers;
|
const currentLayers = useStore.getState().layers;
|
||||||
const newSections = searchEntities(query, currentLayers);
|
const newSections = searchEntities(query, currentLayers);
|
||||||
const locationSection = await searchLocations(query);
|
const locationSection = await searchLocations(query);
|
||||||
|
|||||||
@@ -240,6 +240,7 @@ export function IntelTab() {
|
|||||||
{SidebarComp && (
|
{SidebarComp && (
|
||||||
<div style={{ marginBottom: "var(--space-lg)", paddingBottom: "var(--space-lg)", borderBottom: "1px solid var(--border-subtle)" }}>
|
<div style={{ marginBottom: "var(--space-lg)", paddingBottom: "var(--space-lg)", borderBottom: "1px solid var(--border-subtle)" }}>
|
||||||
<PluginErrorBoundary pluginId={layerPlugin.plugin.id}>
|
<PluginErrorBoundary pluginId={layerPlugin.plugin.id}>
|
||||||
|
{/* eslint-disable-next-line react-hooks/static-components */}
|
||||||
<SidebarComp plugin={layerPlugin.plugin} />
|
<SidebarComp plugin={layerPlugin.plugin} />
|
||||||
</PluginErrorBoundary>
|
</PluginErrorBoundary>
|
||||||
</div>
|
</div>
|
||||||
@@ -293,7 +294,7 @@ export function IntelTab() {
|
|||||||
label={item.label}
|
label={item.label}
|
||||||
color={item.color}
|
color={item.color}
|
||||||
pluginId={pluginId}
|
pluginId={pluginId}
|
||||||
colorOverrides={colorOverrides}
|
colorOverrides={colorOverrides as Record<string, string> | undefined}
|
||||||
updatePluginSettings={updatePluginSettings}
|
updatePluginSettings={updatePluginSettings}
|
||||||
isFilterable={isFilterable}
|
isFilterable={isFilterable}
|
||||||
isActive={isActive}
|
isActive={isActive}
|
||||||
@@ -309,7 +310,7 @@ export function IntelTab() {
|
|||||||
pluginId={pluginId}
|
pluginId={pluginId}
|
||||||
updatePluginSettings={updatePluginSettings}
|
updatePluginSettings={updatePluginSettings}
|
||||||
isDefault
|
isDefault
|
||||||
customLayerColor={settings.customLayerColor}
|
customLayerColor={settings.customLayerColor as string | undefined}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -399,6 +400,7 @@ export function IntelTab() {
|
|||||||
{DetailComp ? (
|
{DetailComp ? (
|
||||||
<div className="intel-panel__custom-detail" style={{ marginTop: "var(--space-md)", maxWidth: "100%", overflow: "hidden" }}>
|
<div className="intel-panel__custom-detail" style={{ marginTop: "var(--space-md)", maxWidth: "100%", overflow: "hidden" }}>
|
||||||
<PluginErrorBoundary pluginId={selectedEntity.pluginId}>
|
<PluginErrorBoundary pluginId={selectedEntity.pluginId}>
|
||||||
|
{/* eslint-disable-next-line react-hooks/static-components */}
|
||||||
<DetailComp entity={selectedEntity} />
|
<DetailComp entity={selectedEntity} />
|
||||||
</PluginErrorBoundary>
|
</PluginErrorBoundary>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -55,6 +55,7 @@ export function GraphicsSettings() {
|
|||||||
const update = useStore((s) => s.updateMapConfig);
|
const update = useStore((s) => s.updateMapConfig);
|
||||||
|
|
||||||
// Save to cookie on change
|
// Save to cookie on change
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const { resolutionScale, antiAliasing, maxScreenSpaceError, shadowsEnabled, enableLighting, showFps, showOsmBuildings } = mapConfig;
|
const { resolutionScale, antiAliasing, maxScreenSpaceError, shadowsEnabled, enableLighting, showFps, showOsmBuildings } = mapConfig;
|
||||||
const graphicsToSave = { resolutionScale, antiAliasing, maxScreenSpaceError, shadowsEnabled, enableLighting, showFps, showOsmBuildings };
|
const graphicsToSave = { resolutionScale, antiAliasing, maxScreenSpaceError, shadowsEnabled, enableLighting, showFps, showOsmBuildings };
|
||||||
@@ -93,7 +94,7 @@ export function GraphicsSettings() {
|
|||||||
className="gfx-settings__select"
|
className="gfx-settings__select"
|
||||||
value={mapConfig.antiAliasing}
|
value={mapConfig.antiAliasing}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
const v = e.target.value as any;
|
const v = e.target.value as "none" | "fxaa" | "msaa2x" | "msaa4x" | "msaa8x";
|
||||||
update({ antiAliasing: v });
|
update({ antiAliasing: v });
|
||||||
trackEvent("graphics-setting", { key: "antiAliasing", value: v });
|
trackEvent("graphics-setting", { key: "antiAliasing", value: v });
|
||||||
}}
|
}}
|
||||||
|
|||||||
@@ -160,6 +160,7 @@ export function PluginsTab() {
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||||
loadPlugins();
|
loadPlugins();
|
||||||
}, [loadPlugins]);
|
}, [loadPlugins]);
|
||||||
|
|
||||||
|
|||||||
@@ -89,6 +89,7 @@ export function IntelTab() {
|
|||||||
if (DetailComp) {
|
if (DetailComp) {
|
||||||
return (
|
return (
|
||||||
<div className="intel-panel__custom-detail" style={{ marginTop: "var(--space-md)", maxWidth: "100%", overflow: "hidden" }}>
|
<div className="intel-panel__custom-detail" style={{ marginTop: "var(--space-md)", maxWidth: "100%", overflow: "hidden" }}>
|
||||||
|
{/* eslint-disable-next-line react-hooks/static-components */}
|
||||||
<DetailComp entity={selectedEntity} />
|
<DetailComp entity={selectedEntity} />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -119,7 +119,7 @@ export function IntelTab() {
|
|||||||
className="intel-panel__action-btn"
|
className="intel-panel__action-btn"
|
||||||
title="Face towards"
|
title="Face towards"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
console.log("[Intel] Face button clicked", selectedEntity.latitude, selectedEntity.longitude);
|
|
||||||
dataBus.emit("cameraFaceTowards", {
|
dataBus.emit("cameraFaceTowards", {
|
||||||
lat: selectedEntity.latitude,
|
lat: selectedEntity.latitude,
|
||||||
lon: selectedEntity.longitude,
|
lon: selectedEntity.longitude,
|
||||||
@@ -134,7 +134,7 @@ export function IntelTab() {
|
|||||||
className="intel-panel__action-btn"
|
className="intel-panel__action-btn"
|
||||||
title="Go to entity"
|
title="Go to entity"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
console.log("[Intel] Go To button clicked", selectedEntity.latitude, selectedEntity.longitude);
|
|
||||||
dataBus.emit("cameraGoTo", {
|
dataBus.emit("cameraGoTo", {
|
||||||
lat: selectedEntity.latitude,
|
lat: selectedEntity.latitude,
|
||||||
lon: selectedEntity.longitude,
|
lon: selectedEntity.longitude,
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ export function Timeline() {
|
|||||||
const [isDemoAdmin, setIsDemoAdmin] = useState(false);
|
const [isDemoAdmin, setIsDemoAdmin] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||||
setMounted(true);
|
setMounted(true);
|
||||||
if (!isDemo) return;
|
if (!isDemo) return;
|
||||||
fetch("/api/auth/session")
|
fetch("/api/auth/session")
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ export default function ReloadToast({ message }: ReloadToastProps) {
|
|||||||
const [mounted, setMounted] = useState(false);
|
const [mounted, setMounted] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||||
setMounted(true);
|
setMounted(true);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
|||||||
@@ -58,6 +58,7 @@ export const CameraStream: React.FC<CameraStreamProps> = ({
|
|||||||
const [imgRefreshTick, setImgRefreshTick] = useState(0);
|
const [imgRefreshTick, setImgRefreshTick] = useState(0);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||||
setIsPlaying(false); setError(null); setIsLoading(false); setHlsFailed(false);
|
setIsPlaying(false); setError(null); setIsLoading(false); setHlsFailed(false);
|
||||||
setActiveStreamUrl(streamUrl);
|
setActiveStreamUrl(streamUrl);
|
||||||
|
|
||||||
@@ -85,6 +86,7 @@ export const CameraStream: React.FC<CameraStreamProps> = ({
|
|||||||
const handlePopOut = (e: React.MouseEvent) => {
|
const handlePopOut = (e: React.MouseEvent) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
addFloatingStream({
|
addFloatingStream({
|
||||||
|
// eslint-disable-next-line react-hooks/purity
|
||||||
id: id || `stream-${Math.random().toString(36).substr(2, 9)}`,
|
id: id || `stream-${Math.random().toString(36).substr(2, 9)}`,
|
||||||
streamUrl: activeStreamUrl,
|
streamUrl: activeStreamUrl,
|
||||||
isIframe,
|
isIframe,
|
||||||
@@ -189,6 +191,7 @@ label: label || "Camera Stream",
|
|||||||
const refreshedUrl = imgRefreshTick > 0
|
const refreshedUrl = imgRefreshTick > 0
|
||||||
? `${resolvedUrl}${sep}_t=${imgRefreshTick}`
|
? `${resolvedUrl}${sep}_t=${imgRefreshTick}`
|
||||||
: resolvedUrl;
|
: resolvedUrl;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<img
|
<img
|
||||||
src={refreshedUrl}
|
src={refreshedUrl}
|
||||||
@@ -227,6 +230,7 @@ label: label || "Camera Stream",
|
|||||||
onClick={handlePlay}
|
onClick={handlePlay}
|
||||||
>
|
>
|
||||||
{previewUrl && (
|
{previewUrl && (
|
||||||
|
// eslint-disable-next-line @next/next/no-img-element
|
||||||
<img
|
<img
|
||||||
src={getProxiedStreamUrl(previewUrl)}
|
src={getProxiedStreamUrl(previewUrl)}
|
||||||
alt={label || "Camera preview"}
|
alt={label || "Camera preview"}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||||
import {
|
import {
|
||||||
describe, it, expect, vi, beforeEach
|
describe, it, expect, vi, beforeEach
|
||||||
} from "vitest";
|
} from "vitest";
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||||
import {
|
import {
|
||||||
describe, it, expect, vi, beforeEach, afterEach
|
describe, it, expect, vi, beforeEach, afterEach
|
||||||
} from "vitest";
|
} from "vitest";
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
/* eslint-disable react-hooks/refs */
|
||||||
|
|
||||||
// @refresh reset
|
// @refresh reset
|
||||||
|
|
||||||
@@ -92,8 +93,8 @@ enableLighting,
|
|||||||
if (!Array.isArray(entities)) return;
|
if (!Array.isArray(entities)) return;
|
||||||
|
|
||||||
const settings = pluginSettings[pluginId];
|
const settings = pluginSettings[pluginId];
|
||||||
const colorOverrides = settings?.colorOverrides;
|
const colorOverrides = settings?.colorOverrides as Record<string, string> | undefined;
|
||||||
const customLayerColor = settings?.customLayerColor;
|
const customLayerColor = settings?.customLayerColor as string | undefined;
|
||||||
|
|
||||||
const defs = managed.plugin.getFilterDefinitions?.() || [];
|
const defs = managed.plugin.getFilterDefinitions?.() || [];
|
||||||
const active = filters[pluginId] || {};
|
const active = filters[pluginId] || {};
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||||
import {
|
import {
|
||||||
describe, it, expect, vi, beforeEach
|
describe, it, expect, vi, beforeEach
|
||||||
} from "vitest";
|
} from "vitest";
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable react-hooks/immutability */
|
||||||
import { useEffect, useRef } from "react";
|
import { useEffect, useRef } from "react";
|
||||||
import type { Viewer as CesiumViewer } from "cesium";
|
import type { Viewer as CesiumViewer } from "cesium";
|
||||||
import { Cartographic, Math as CesiumMath } from "cesium";
|
import { Cartographic, Math as CesiumMath } from "cesium";
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable react-hooks/immutability */
|
||||||
import { useEffect, useRef } from "react";
|
import { useEffect, useRef } from "react";
|
||||||
import type { Viewer as CesiumViewer } from "cesium";
|
import type { Viewer as CesiumViewer } from "cesium";
|
||||||
import { Cartographic, Cartesian3 } from "cesium";
|
import { Cartographic, Cartesian3 } from "cesium";
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
* Uses a dedicated persistent Billboard per stack for the textual hub badge.
|
* Uses a dedicated persistent Billboard per stack for the textual hub badge.
|
||||||
*/
|
*/
|
||||||
import {
|
import {
|
||||||
Cartesian2, Cartesian3, HorizontalOrigin, VerticalOrigin, NearFarScalar, HeightReference, Color
|
Cartesian2, Cartesian3, HorizontalOrigin, VerticalOrigin, NearFarScalar, Color
|
||||||
} from "cesium";
|
} from "cesium";
|
||||||
import type { LabelCollection, BillboardCollection } from "cesium";
|
import type { LabelCollection, BillboardCollection } from "cesium";
|
||||||
import {
|
import {
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable react-hooks/refs */
|
||||||
import { useEffect, useRef } from "react";
|
import { useEffect, useRef } from "react";
|
||||||
import {
|
import {
|
||||||
GeoJsonDataSource,
|
GeoJsonDataSource,
|
||||||
@@ -18,7 +19,7 @@ import {
|
|||||||
LabelStyle,
|
LabelStyle,
|
||||||
HeightReference,
|
HeightReference,
|
||||||
NearFarScalar,
|
NearFarScalar,
|
||||||
Ellipsoid,
|
|
||||||
Cartographic,
|
Cartographic,
|
||||||
} from "cesium";
|
} from "cesium";
|
||||||
import type { Viewer as CesiumViewer } from "cesium";
|
import type { Viewer as CesiumViewer } from "cesium";
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable react-hooks/immutability */
|
||||||
import { useEffect, useRef } from "react";
|
import { useEffect, useRef } from "react";
|
||||||
import {
|
import {
|
||||||
Viewer as CesiumViewer,
|
Viewer as CesiumViewer,
|
||||||
@@ -10,7 +11,8 @@ import {
|
|||||||
import { useStore } from "@/core/state/store";
|
import { useStore } from "@/core/state/store";
|
||||||
import { createImageryProvider, createOsmProvider } from "./ImageryProviderFactory";
|
import { createImageryProvider, createOsmProvider } from "./ImageryProviderFactory";
|
||||||
|
|
||||||
export function useImageryManager(viewer: CesiumViewer | null, viewerReady: boolean) {
|
export function useImageryManager(viewerInstance: CesiumViewer | null, viewerReady: boolean) {
|
||||||
|
const viewer = viewerInstance;
|
||||||
const baseLayerId = useStore((s) => s.mapConfig.baseLayerId);
|
const baseLayerId = useStore((s) => s.mapConfig.baseLayerId);
|
||||||
const fallbackLayerId = useStore((s) => s.mapConfig.fallbackLayerId);
|
const fallbackLayerId = useStore((s) => s.mapConfig.fallbackLayerId);
|
||||||
const sceneMode = useStore((s) => s.mapConfig.sceneMode);
|
const sceneMode = useStore((s) => s.mapConfig.sceneMode);
|
||||||
@@ -20,7 +22,7 @@ export function useImageryManager(viewer: CesiumViewer | null, viewerReady: bool
|
|||||||
const activeLayerId = fallbackLayerId || baseLayerId;
|
const activeLayerId = fallbackLayerId || baseLayerId;
|
||||||
|
|
||||||
const currentImageryLayerRef = useRef<ImageryLayer | null>(null);
|
const currentImageryLayerRef = useRef<ImageryLayer | null>(null);
|
||||||
const googleTilesetRef = useRef<Cesium3DTileset | null>(null);
|
// const googleTilesetRef = useRef<Cesium3DTileset | null>(null);
|
||||||
const osmBuildingsRef = useRef<Cesium3DTileset | null>(null);
|
const osmBuildingsRef = useRef<Cesium3DTileset | null>(null);
|
||||||
|
|
||||||
// 1. Manage Scene Mode (2D / 3D / Columbus)
|
// 1. Manage Scene Mode (2D / 3D / Columbus)
|
||||||
|
|||||||
@@ -182,6 +182,7 @@ export function useMarketplaceSync(hostReady: boolean) {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!hostReady) return;
|
if (!hostReady) return;
|
||||||
|
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||||
syncPlugins();
|
syncPlugins();
|
||||||
|
|
||||||
const handleFocus = () => { syncPlugins(); };
|
const handleFocus = () => { syncPlugins(); };
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable no-console */
|
||||||
/**
|
/**
|
||||||
* @file InstalledPluginsLoader.ts
|
* @file InstalledPluginsLoader.ts
|
||||||
* @description Scans the database for previously installed marketplace plugins,
|
* @description Scans the database for previously installed marketplace plugins,
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable no-console */
|
||||||
import type {
|
import type {
|
||||||
WorldPlugin,
|
WorldPlugin,
|
||||||
GeoEntity,
|
GeoEntity,
|
||||||
@@ -158,7 +159,7 @@ class PluginManager {
|
|||||||
trackEvent("plugin-error", { plugin: plugin.id, error: error.message });
|
trackEvent("plugin-error", { plugin: plugin.id, error: error.message });
|
||||||
dataBus.emit("pluginError", { pluginId: plugin.id, message: `[${plugin.name || plugin.id}] ${error.message}`, error });
|
dataBus.emit("pluginError", { pluginId: plugin.id, message: `[${plugin.name || plugin.id}] ${error.message}`, error });
|
||||||
},
|
},
|
||||||
getPluginSettings: (pluginId) => useStore.getState().dataConfig.pluginSettings[pluginId] as ReturnType<typeof useStore.getState>["dataConfig"]["pluginSettings"][string],
|
getPluginSettings: <T = unknown>(pluginId: string) => useStore.getState().dataConfig.pluginSettings[pluginId] as T | undefined,
|
||||||
isPlaybackMode: () => useStore.getState().isPlaybackMode,
|
isPlaybackMode: () => useStore.getState().isPlaybackMode,
|
||||||
getCurrentTime: () => useStore.getState().currentTime,
|
getCurrentTime: () => useStore.getState().currentTime,
|
||||||
};
|
};
|
||||||
@@ -192,7 +193,7 @@ class PluginManager {
|
|||||||
try {
|
try {
|
||||||
const entities = await plugin.fetch(managed.context.timeRange);
|
const entities = await plugin.fetch(managed.context.timeRange);
|
||||||
this.handleDataUpdate(plugin.id, entities);
|
this.handleDataUpdate(plugin.id, entities);
|
||||||
} catch (err: any) {
|
} catch (err: unknown) {
|
||||||
dataBus.emit("layerLoadingChanged", { pluginId: plugin.id, loading: false });
|
dataBus.emit("layerLoadingChanged", { pluginId: plugin.id, loading: false });
|
||||||
managed.context.onError(err instanceof Error ? err : new Error(String(err)));
|
managed.context.onError(err instanceof Error ? err : new Error(String(err)));
|
||||||
// Do not re-throw: onError already handled reporting.
|
// Do not re-throw: onError already handled reporting.
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable no-console */
|
||||||
import type { WorldPlugin } from "@/core/plugins/PluginTypes";
|
import type { WorldPlugin } from "@/core/plugins/PluginTypes";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable no-console */
|
||||||
/**
|
/**
|
||||||
* @file hostGlobals.ts
|
* @file hostGlobals.ts
|
||||||
* @description Exposes essential host libraries (React, Cesium, SDK, etc.) on `globalThis`.
|
* @description Exposes essential host libraries (React, Cesium, SDK, etc.) on `globalThis`.
|
||||||
@@ -66,15 +67,15 @@ export async function injectHostGlobals(): Promise<void> {
|
|||||||
// resolveEngineUrl.ts during plugin routing. These variables act as global fallbacks.
|
// resolveEngineUrl.ts during plugin routing. These variables act as global fallbacks.
|
||||||
const envDataEngine = process.env.NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL;
|
const envDataEngine = process.env.NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL;
|
||||||
if (envDataEngine) {
|
if (envDataEngine) {
|
||||||
(globalThis as any).__WWV_ENGINE_URL__ = envDataEngine;
|
(globalThis as Record<string, unknown>).__WWV_ENGINE_URL__ = envDataEngine;
|
||||||
} else {
|
} else {
|
||||||
// ALWAYS default to the cloud engine unless explicitly told otherwise via env var
|
// ALWAYS default to the cloud engine unless explicitly told otherwise via env var
|
||||||
(globalThis as any).__WWV_ENGINE_URL__ = 'https://dataengine.worldwideview.dev';
|
(globalThis as Record<string, unknown>).__WWV_ENGINE_URL__ = 'https://dataengine.worldwideview.dev';
|
||||||
}
|
}
|
||||||
|
|
||||||
// WebSocket Engine URL
|
// WebSocket Engine URL
|
||||||
const fallbackWs = envDataEngine ? `${envDataEngine.replace(/^http/, "ws")}/stream` : 'wss://dataengine.worldwideview.dev/stream';
|
const fallbackWs = envDataEngine ? `${envDataEngine.replace(/^http/, "ws")}/stream` : 'wss://dataengine.worldwideview.dev/stream';
|
||||||
(globalThis as any).__WWV_WS_ENGINE_URL__ = fallbackWs;
|
(globalThis as Record<string, unknown>).__WWV_WS_ENGINE_URL__ = fallbackWs;
|
||||||
|
|
||||||
console.log("[HostGlobals] React and SDK injected for dynamic plugins");
|
console.log("[HostGlobals] React and SDK injected for dynamic plugins");
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||||
import {
|
import {
|
||||||
describe, it, expect, vi, beforeEach
|
describe, it, expect, vi, beforeEach
|
||||||
} from "vitest";
|
} from "vitest";
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable no-console */
|
||||||
/**
|
/**
|
||||||
* @file loadPluginFromManifest.ts
|
* @file loadPluginFromManifest.ts
|
||||||
* @description Handles the dynamic loading and instantiation of WorldWideView plugins from ES module bundles.
|
* @description Handles the dynamic loading and instantiation of WorldWideView plugins from ES module bundles.
|
||||||
@@ -39,12 +40,13 @@ async function loadBundlePlugin(entry: string): Promise<WorldPlugin> {
|
|||||||
/**
|
/**
|
||||||
* Helper to safely instantiate a class and verify its compliance with WorldPlugin.
|
* Helper to safely instantiate a class and verify its compliance with WorldPlugin.
|
||||||
*/
|
*/
|
||||||
const instantiate = (maybeClass: any): WorldPlugin | null => {
|
const instantiate = (maybeClass: unknown): WorldPlugin | null => {
|
||||||
if (typeof maybeClass === "function") {
|
if (typeof maybeClass === "function") {
|
||||||
try {
|
try {
|
||||||
const instance = new maybeClass();
|
const Constructor = maybeClass as new () => Record<string, unknown>;
|
||||||
|
const instance = new Constructor();
|
||||||
if (instance && typeof instance.initialize === "function") {
|
if (instance && typeof instance.initialize === "function") {
|
||||||
return instance as WorldPlugin;
|
return instance as unknown as WorldPlugin;
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||||
import {
|
import {
|
||||||
describe, test, expect, vi, beforeEach
|
describe, test, expect, vi, beforeEach
|
||||||
} from "vitest";
|
} from "vitest";
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ import type {
|
|||||||
PluginCategory,
|
PluginCategory,
|
||||||
} from "../PluginTypes";
|
} from "../PluginTypes";
|
||||||
import type { PluginManifest } from "../PluginManifest";
|
import type { PluginManifest } from "../PluginManifest";
|
||||||
import { getNestedValue } from "./getNestedValue";
|
|
||||||
import { mapGeoJsonToEntities } from "./mapGeoJsonToEntities";
|
import { mapGeoJsonToEntities } from "./mapGeoJsonToEntities";
|
||||||
import { mapJsonToEntities } from "./mapJsonToEntities";
|
import { mapJsonToEntities } from "./mapJsonToEntities";
|
||||||
|
|
||||||
|
|||||||
@@ -59,7 +59,7 @@ describe("getNestedValue", () => {
|
|||||||
try {
|
try {
|
||||||
getNestedValue(obj, path);
|
getNestedValue(obj, path);
|
||||||
return true;
|
return true;
|
||||||
} catch (e) {
|
} catch {
|
||||||
return false; // Should never reach here
|
return false; // Should never reach here
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,30 +16,32 @@ import type { PluginManifest } from "./PluginManifest";
|
|||||||
* @returns A sanitized and properly structured PluginManifest object.
|
* @returns A sanitized and properly structured PluginManifest object.
|
||||||
* @throws Error if the raw input is not a valid JSON object.
|
* @throws Error if the raw input is not a valid JSON object.
|
||||||
*/
|
*/
|
||||||
export function parseWwvManifest(rawManifest: any): PluginManifest {
|
export function parseWwvManifest(rawManifest: unknown): PluginManifest {
|
||||||
if (!rawManifest || typeof rawManifest !== "object") {
|
if (!rawManifest || typeof rawManifest !== "object") {
|
||||||
throw new Error("Manifest must be a JSON object");
|
throw new Error("Manifest must be a JSON object");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const raw = rawManifest as Record<string, unknown>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Partial construction allows us to explicitly map and default fields
|
* Partial construction allows us to explicitly map and default fields
|
||||||
* before casting to the final strict interface.
|
* before casting to the final strict interface.
|
||||||
*/
|
*/
|
||||||
const manifest: Partial<PluginManifest> = {
|
const manifest: Partial<PluginManifest> = {
|
||||||
id: rawManifest.id,
|
id: raw.id as string | undefined,
|
||||||
name: rawManifest.name,
|
name: raw.name as string | undefined,
|
||||||
version: rawManifest.version,
|
version: raw.version as string | undefined,
|
||||||
description: rawManifest.description,
|
description: raw.description as string | undefined,
|
||||||
type: rawManifest.type || "data-layer",
|
type: (raw.type as PluginManifest["type"]) || "data-layer",
|
||||||
format: "bundle", // Modern wwv-manifest plugins are always ES module bundles
|
format: "bundle", // Modern wwv-manifest plugins are always ES module bundles
|
||||||
trust: "unverified", // Default trust level; overridden by marketplace signature verification
|
trust: "unverified", // Default trust level; overridden by marketplace signature verification
|
||||||
capabilities: rawManifest.capabilities || [],
|
capabilities: (raw.capabilities as PluginManifest["capabilities"]) || [],
|
||||||
category: rawManifest.category || "custom",
|
category: (raw.category as string | undefined) || "custom",
|
||||||
icon: rawManifest.icon,
|
icon: raw.icon as string | undefined,
|
||||||
compatibility: rawManifest.compatibility,
|
compatibility: raw.compatibility as PluginManifest["compatibility"],
|
||||||
entry: rawManifest.entry,
|
entry: raw.entry as string | undefined,
|
||||||
assets: rawManifest.assets,
|
assets: raw.assets as PluginManifest["assets"],
|
||||||
extends: rawManifest.extends,
|
extends: raw.extends as PluginManifest["extends"],
|
||||||
};
|
};
|
||||||
|
|
||||||
return manifest as PluginManifest;
|
return manifest as PluginManifest;
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||||
import { describe, it, expect } from "vitest";
|
import { describe, it, expect } from "vitest";
|
||||||
import { validateManifest } from "./validateManifest";
|
import { validateManifest } from "./validateManifest";
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||||
import {
|
import {
|
||||||
describe, it, expect, vi, beforeEach
|
describe, it, expect, vi, beforeEach
|
||||||
} from "vitest";
|
} from "vitest";
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||||
import {
|
import {
|
||||||
describe, it, expect, beforeEach, vi
|
describe, it, expect, beforeEach, vi
|
||||||
} from 'vitest';
|
} from 'vitest';
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ export interface DataConfig {
|
|||||||
showTimelineHighlight: boolean;
|
showTimelineHighlight: boolean;
|
||||||
};
|
};
|
||||||
/** Generic storage for plugin-specific settings. */
|
/** Generic storage for plugin-specific settings. */
|
||||||
pluginSettings: Record<string, any>;
|
pluginSettings: Record<string, Record<string, unknown>>;
|
||||||
/** Cryptographic license key for paid tiers. */
|
/** Cryptographic license key for paid tiers. */
|
||||||
licenseKey: string | null;
|
licenseKey: string | null;
|
||||||
/** The active subscription tier of the user. */
|
/** The active subscription tier of the user. */
|
||||||
@@ -80,7 +80,7 @@ export interface ConfigSlice {
|
|||||||
/** Overrides the default polling interval for a specific plugin. */
|
/** Overrides the default polling interval for a specific plugin. */
|
||||||
setPollingInterval: (pluginId: string, intervalMs: number) => void;
|
setPollingInterval: (pluginId: string, intervalMs: number) => void;
|
||||||
/** Updates internal settings stored for a specific plugin. */
|
/** Updates internal settings stored for a specific plugin. */
|
||||||
updatePluginSettings: (pluginId: string, settings: any) => void;
|
updatePluginSettings: (pluginId: string, settings: Record<string, unknown>) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const createConfigSlice: StateCreator<AppStore, [], [], ConfigSlice> = (set) => ({
|
export const createConfigSlice: StateCreator<AppStore, [], [], ConfigSlice> = (set) => ({
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||||
import {
|
import {
|
||||||
describe, it, expect, beforeEach, vi
|
describe, it, expect, beforeEach, vi
|
||||||
} from 'vitest';
|
} from 'vitest';
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||||
import {
|
import {
|
||||||
describe, it, expect, beforeEach, vi, afterEach
|
describe, it, expect, beforeEach, vi, afterEach
|
||||||
} from 'vitest';
|
} from 'vitest';
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable no-console */
|
||||||
/**
|
/**
|
||||||
* @file favoritesSlice.ts
|
* @file favoritesSlice.ts
|
||||||
* @description State slice for managing user-bookmarked entities.
|
* @description State slice for managing user-bookmarked entities.
|
||||||
@@ -8,6 +9,7 @@ import type { StateCreator } from "zustand";
|
|||||||
import type { GeoEntity } from "@/core/plugins/PluginTypes";
|
import type { GeoEntity } from "@/core/plugins/PluginTypes";
|
||||||
import { isDemo } from "@/core/edition";
|
import { isDemo } from "@/core/edition";
|
||||||
import type { AppStore } from "./store";
|
import type { AppStore } from "./store";
|
||||||
|
import type { ReactNode, ComponentType } from "react";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A bookmarked entity with metadata for quick retrieval.
|
* A bookmarked entity with metadata for quick retrieval.
|
||||||
@@ -22,7 +24,7 @@ export interface FavoriteItem {
|
|||||||
/** Display name of the plugin for UI purposes. */
|
/** Display name of the plugin for UI purposes. */
|
||||||
pluginName: string;
|
pluginName: string;
|
||||||
/** Optional React icon element (not persisted to DB/Cookie). */
|
/** Optional React icon element (not persisted to DB/Cookie). */
|
||||||
icon?: any;
|
icon?: string | ComponentType<{ size?: number; color?: string }>;
|
||||||
/** Timestamp of when the bookmark was created or last updated. */
|
/** Timestamp of when the bookmark was created or last updated. */
|
||||||
lastSeen: number;
|
lastSeen: number;
|
||||||
}
|
}
|
||||||
@@ -34,7 +36,7 @@ export interface FavoritesSlice {
|
|||||||
/** List of all bookmarked items. */
|
/** List of all bookmarked items. */
|
||||||
favorites: FavoriteItem[];
|
favorites: FavoriteItem[];
|
||||||
/** Adds a new entity to the favorites list and persists it to the backend/cookie. */
|
/** Adds a new entity to the favorites list and persists it to the backend/cookie. */
|
||||||
addFavorite: (entity: GeoEntity, pluginName: string, icon?: any) => void;
|
addFavorite: (entity: GeoEntity, pluginName: string, icon?: string | ComponentType<{ size?: number; color?: string }>) => void;
|
||||||
/** Removes an entity from favorites and updates the persistence layer. */
|
/** Removes an entity from favorites and updates the persistence layer. */
|
||||||
removeFavorite: (id: string) => void;
|
removeFavorite: (id: string) => void;
|
||||||
/** Replaces the entire favorites list (typically called during initial app hydration). */
|
/** Replaces the entire favorites list (typically called during initial app hydration). */
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||||
import {
|
import {
|
||||||
describe, it, expect, beforeEach
|
describe, it, expect, beforeEach
|
||||||
} from 'vitest';
|
} from 'vitest';
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||||
import {
|
import {
|
||||||
describe, it, expect, beforeEach
|
describe, it, expect, beforeEach
|
||||||
} from 'vitest';
|
} from 'vitest';
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||||
import {
|
import {
|
||||||
describe, it, expect, beforeEach
|
describe, it, expect, beforeEach
|
||||||
} from 'vitest';
|
} from 'vitest';
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||||
import {
|
import {
|
||||||
describe, it, expect, beforeEach, vi
|
describe, it, expect, beforeEach, vi
|
||||||
} from 'vitest';
|
} from 'vitest';
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||||
import {
|
import {
|
||||||
describe, it, expect, beforeEach, vi
|
describe, it, expect, beforeEach, vi
|
||||||
} from 'vitest';
|
} from 'vitest';
|
||||||
|
|||||||
@@ -119,7 +119,7 @@ export interface UISlice {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const createUISlice: StateCreator<AppStore, [], [], UISlice> = (set) => ({
|
export const createUISlice: StateCreator<AppStore, [], [], UISlice> = (set) => ({
|
||||||
theme: typeof window !== "undefined" ? (localStorage.getItem("wwv-theme") as any) || "black" : "black",
|
theme: typeof window !== "undefined" ? ((localStorage.getItem("wwv-theme") as "dark" | "light" | "legacy" | "black") || "black") : "black",
|
||||||
leftSidebarOpen: true,
|
leftSidebarOpen: true,
|
||||||
rightSidebarOpen: false,
|
rightSidebarOpen: false,
|
||||||
configPanelOpen: true,
|
configPanelOpen: true,
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||||
import {
|
import {
|
||||||
describe, it, expect, vi, beforeEach
|
describe, it, expect, vi, beforeEach
|
||||||
} from "vitest";
|
} from "vitest";
|
||||||
import { isDemo } from "@/core/edition";
|
|
||||||
import { authConfig } from "./auth.config";
|
import { authConfig } from "./auth.config";
|
||||||
|
|
||||||
vi.mock("@/core/edition", () => ({
|
vi.mock("@/core/edition", () => ({
|
||||||
|
|||||||
+1
-1
@@ -60,7 +60,7 @@ export const {
|
|||||||
adapter: isCloud ? SupabaseAdapter({
|
adapter: isCloud ? SupabaseAdapter({
|
||||||
url: process.env.NEXT_PUBLIC_SUPABASE_URL || "http://dummy.supabase.co",
|
url: process.env.NEXT_PUBLIC_SUPABASE_URL || "http://dummy.supabase.co",
|
||||||
secret: process.env.SUPABASE_SERVICE_ROLE_KEY || "dummy",
|
secret: process.env.SUPABASE_SERVICE_ROLE_KEY || "dummy",
|
||||||
}) as any : undefined,
|
}) as never : undefined,
|
||||||
providers: [localCredentialsProvider],
|
providers: [localCredentialsProvider],
|
||||||
callbacks: {
|
callbacks: {
|
||||||
...authConfig.callbacks,
|
...authConfig.callbacks,
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||||
import { describe, it, expect } from "vitest";
|
import { describe, it, expect } from "vitest";
|
||||||
import { encryptCredential, decryptCredential } from "./encryption";
|
import { encryptCredential, decryptCredential } from "./encryption";
|
||||||
|
|
||||||
|
|||||||
+11
-10
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable no-console */
|
||||||
import { PrismaPg } from "@prisma/adapter-pg";
|
import { PrismaPg } from "@prisma/adapter-pg";
|
||||||
import { Pool } from "pg";
|
import { Pool } from "pg";
|
||||||
import { headers } from "next/headers";
|
import { headers } from "next/headers";
|
||||||
@@ -16,19 +17,19 @@ const globalForPrisma = globalThis as unknown as {
|
|||||||
prisma: PrismaClient | undefined;
|
prisma: PrismaClient | undefined;
|
||||||
};
|
};
|
||||||
|
|
||||||
function applyTenantIsolation(client: any) {
|
function applyTenantIsolation(client: PrismaClient) {
|
||||||
// Use Prisma Client Extension to inject RLS
|
// Use Prisma Client Extension to inject RLS
|
||||||
return client.$extends({
|
return client.$extends({
|
||||||
query: {
|
query: {
|
||||||
$allModels: {
|
$allModels: {
|
||||||
async $allOperations({
|
async $allOperations({
|
||||||
model, operation, args, query
|
model, operation, args, query
|
||||||
}: { model: string, operation: string, args: any, query: any }) {
|
}: { model: string, operation: string, args: Record<string, unknown>, query: (args: unknown) => unknown }) {
|
||||||
let tenantSubdomain = null;
|
let tenantSubdomain = null;
|
||||||
try {
|
try {
|
||||||
const headersList = await headers();
|
const headersList = await headers();
|
||||||
tenantSubdomain = headersList.get("x-tenant-subdomain");
|
tenantSubdomain = headersList.get("x-tenant-subdomain");
|
||||||
} catch (e) {
|
} catch {
|
||||||
// Not in a request context (e.g. scripts, background jobs)
|
// Not in a request context (e.g. scripts, background jobs)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -38,24 +39,24 @@ function applyTenantIsolation(client: any) {
|
|||||||
// Inject into data for creates
|
// Inject into data for creates
|
||||||
if (operation === 'create' || operation === 'createMany') {
|
if (operation === 'create' || operation === 'createMany') {
|
||||||
if (Array.isArray(args.data)) {
|
if (Array.isArray(args.data)) {
|
||||||
args.data = args.data.map((d: any) => ({ ...d, tenantId: tenantSubdomain }));
|
args.data = args.data.map((d: Record<string, unknown>) => ({ ...d, tenantId: tenantSubdomain }));
|
||||||
} else if (args.data) {
|
} else if (args.data && typeof args.data === 'object') {
|
||||||
args.data.tenantId = tenantSubdomain;
|
(args.data as Record<string, unknown>).tenantId = tenantSubdomain;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Inject into data for updates
|
// Inject into data for updates
|
||||||
if (operation === 'update' || operation === 'updateMany') {
|
if (operation === 'update' || operation === 'updateMany') {
|
||||||
if (args.data) args.data.tenantId = tenantSubdomain;
|
if (args.data && typeof args.data === 'object') (args.data as Record<string, unknown>).tenantId = tenantSubdomain;
|
||||||
}
|
}
|
||||||
if (operation === 'upsert') {
|
if (operation === 'upsert') {
|
||||||
if (args.create) args.create.tenantId = tenantSubdomain;
|
if (args.create && typeof args.create === 'object') (args.create as Record<string, unknown>).tenantId = tenantSubdomain;
|
||||||
if (args.update) args.update.tenantId = tenantSubdomain;
|
if (args.update && typeof args.update === 'object') (args.update as Record<string, unknown>).tenantId = tenantSubdomain;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Inject into where filters
|
// Inject into where filters
|
||||||
if (['findUnique', 'findFirst', 'findMany', 'update', 'updateMany', 'delete', 'deleteMany', 'count', 'upsert'].includes(operation)) {
|
if (['findUnique', 'findFirst', 'findMany', 'update', 'updateMany', 'delete', 'deleteMany', 'count', 'upsert'].includes(operation)) {
|
||||||
args.where = { ...(args.where || {}), tenantId: tenantSubdomain };
|
args.where = { ...((args.where as Record<string, unknown>) || {}), tenantId: tenantSubdomain };
|
||||||
}
|
}
|
||||||
|
|
||||||
return query(args);
|
return query(args);
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||||
import { describe, test, expect } from "vitest";
|
import { describe, test, expect } from "vitest";
|
||||||
import fc from "fast-check";
|
import fc from "fast-check";
|
||||||
import { normalizeToGeoJson } from "./normalizer";
|
import { normalizeToGeoJson } from "./normalizer";
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
|
/* eslint-disable no-console */
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useStore } from "@/core/state/store";
|
|
||||||
|
|
||||||
export interface CapturedLog {
|
export interface CapturedLog {
|
||||||
level: "log" | "warn" | "error" | "info" | "debug";
|
level: "log" | "warn" | "error" | "info" | "debug";
|
||||||
@@ -31,7 +31,7 @@ export function initLogCatcher() {
|
|||||||
];
|
];
|
||||||
|
|
||||||
levels.forEach(({ name, original }) => {
|
levels.forEach(({ name, original }) => {
|
||||||
console[name] = (...args: any[]) => {
|
console[name] = (...args: unknown[]) => {
|
||||||
// Forward to original console
|
// Forward to original console
|
||||||
original.apply(console, args);
|
original.apply(console, args);
|
||||||
|
|
||||||
@@ -44,8 +44,8 @@ export function initLogCatcher() {
|
|||||||
}
|
}
|
||||||
if (typeof arg === "object" && arg !== null) {
|
if (typeof arg === "object" && arg !== null) {
|
||||||
try {
|
try {
|
||||||
if (arg.message || arg.stack) {
|
if (("message" in arg) || ("stack" in arg)) {
|
||||||
return `ErrorLike: ${arg.message || ''}\n${arg.stack || ''}`;
|
return `ErrorLike: ${(arg as {message?: unknown}).message || ''}\n${(arg as {stack?: unknown}).stack || ''}`;
|
||||||
}
|
}
|
||||||
// Very shallow serialization. Do not traverse deeply.
|
// Very shallow serialization. Do not traverse deeply.
|
||||||
const str = JSON.stringify(arg, (key, value) => {
|
const str = JSON.stringify(arg, (key, value) => {
|
||||||
@@ -74,7 +74,7 @@ export function initLogCatcher() {
|
|||||||
if (capturedLogs.length > MAX_LOGS) {
|
if (capturedLogs.length > MAX_LOGS) {
|
||||||
capturedLogs.shift();
|
capturedLogs.shift();
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch {
|
||||||
// Ignore errors inside log catcher to avoid infinite loops
|
// Ignore errors inside log catcher to avoid infinite loops
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable no-console */
|
||||||
import { createPublicKey, verify } from "crypto";
|
import { createPublicKey, verify } from "crypto";
|
||||||
|
|
||||||
/** Ed25519 public key for verifying the WWV plugin registry. */
|
/** Ed25519 public key for verifying the WWV plugin registry. */
|
||||||
|
|||||||
@@ -71,5 +71,5 @@ export async function getDisabledPluginIds(): Promise<Set<string>> {
|
|||||||
where: { enabled: false },
|
where: { enabled: false },
|
||||||
select: { pluginId: true },
|
select: { pluginId: true },
|
||||||
});
|
});
|
||||||
return new Set(records.map((r: any) => r.pluginId));
|
return new Set(records.map((r: { pluginId: string }) => r.pluginId));
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||||
import {
|
import {
|
||||||
describe, it, expect, vi, beforeEach
|
describe, it, expect, vi, beforeEach
|
||||||
} from "vitest";
|
} from "vitest";
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable no-console */
|
||||||
import { isDemo } from "@/core/edition";
|
import { isDemo } from "@/core/edition";
|
||||||
import { validateManifest } from "@/core/plugins/validateManifest";
|
import { validateManifest } from "@/core/plugins/validateManifest";
|
||||||
import { prisma } from "../db";
|
import { prisma } from "../db";
|
||||||
@@ -78,7 +79,7 @@ export async function seedDefaultPlugins(): Promise<void> {
|
|||||||
|
|
||||||
await upsertPlugin(
|
await upsertPlugin(
|
||||||
pluginId,
|
pluginId,
|
||||||
manifest.version || "1.0.0",
|
(manifest.version as string | undefined) || "1.0.0",
|
||||||
JSON.stringify(manifest),
|
JSON.stringify(manifest),
|
||||||
);
|
);
|
||||||
installed += 1;
|
installed += 1;
|
||||||
@@ -103,7 +104,7 @@ export async function seedDefaultPlugins(): Promise<void> {
|
|||||||
/** Fetch a plugin manifest from the marketplace API. */
|
/** Fetch a plugin manifest from the marketplace API. */
|
||||||
async function fetchManifest(
|
async function fetchManifest(
|
||||||
pluginId: string,
|
pluginId: string,
|
||||||
): Promise<Record<string, any> | null> {
|
): Promise<Record<string, unknown> | null> {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`${MARKETPLACE_URL}/api/plugins/${pluginId}`);
|
const res = await fetch(`${MARKETPLACE_URL}/api/plugins/${pluginId}`);
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||||
import {
|
import {
|
||||||
describe, it, expect, vi, beforeEach
|
describe, it, expect, vi, beforeEach
|
||||||
} from "vitest";
|
} from "vitest";
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable no-console */
|
||||||
import type { NextRequest } from "next/server";
|
import type { NextRequest } from "next/server";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -69,12 +69,16 @@ describe("RateLimiter", () => {
|
|||||||
localLimiter.check("ip-cleanup");
|
localLimiter.check("ip-cleanup");
|
||||||
|
|
||||||
// Force the store resetAt to be in the past
|
// Force the store resetAt to be in the past
|
||||||
const entry = (localLimiter as any).store.get("ip-cleanup");
|
const limiterInternal = localLimiter as unknown as {
|
||||||
|
store: Map<string, { resetAt: number }>;
|
||||||
|
cleanup: () => void;
|
||||||
|
};
|
||||||
|
const entry = limiterInternal.store.get("ip-cleanup")!;
|
||||||
entry.resetAt = Date.now() - 1000;
|
entry.resetAt = Date.now() - 1000;
|
||||||
|
|
||||||
(localLimiter as any).cleanup();
|
limiterInternal.cleanup();
|
||||||
|
|
||||||
expect((localLimiter as any).store.has("ip-cleanup")).toBe(false);
|
expect(limiterInternal.store.has("ip-cleanup")).toBe(false);
|
||||||
localLimiter.destroy();
|
localLimiter.destroy();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,6 +1,4 @@
|
|||||||
import {
|
import { describe, it, expect } from "vitest";
|
||||||
describe, it, expect, vi, beforeEach
|
|
||||||
} from "vitest";
|
|
||||||
import { safeFetch, validateOrigin, isPrivateIP } from "./ssrf";
|
import { safeFetch, validateOrigin, isPrivateIP } from "./ssrf";
|
||||||
|
|
||||||
describe("SSRF Protection Utility", () => {
|
describe("SSRF Protection Utility", () => {
|
||||||
|
|||||||
@@ -42,9 +42,9 @@ export async function safeFetch(urlStr: string, options: FetchOptions = {}): Pro
|
|||||||
if (isPrivateIP(resolvedIp)) {
|
if (isPrivateIP(resolvedIp)) {
|
||||||
throw new Error("SSRF Error: Host resolves to a private IP.");
|
throw new Error("SSRF Error: Host resolves to a private IP.");
|
||||||
}
|
}
|
||||||
} catch (err: any) {
|
} catch (err: unknown) {
|
||||||
if (err.message.includes("SSRF")) throw err;
|
if (err instanceof Error && err.message.includes("SSRF")) throw err;
|
||||||
throw new Error(`SSRF Error: DNS resolution failed - ${err.message}`);
|
throw new Error(`SSRF Error: DNS resolution failed - ${err instanceof Error ? err.message : String(err)}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const customAgent = new Agent({
|
const customAgent = new Agent({
|
||||||
@@ -62,12 +62,12 @@ export async function safeFetch(urlStr: string, options: FetchOptions = {}): Pro
|
|||||||
const id = setTimeout(() => controller.abort(), timeout);
|
const id = setTimeout(() => controller.abort(), timeout);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const fetchOptions: any = {
|
const fetchOptions = {
|
||||||
...options,
|
...options,
|
||||||
dispatcher: customAgent,
|
dispatcher: customAgent,
|
||||||
redirect: "manual",
|
redirect: "manual" as const,
|
||||||
signal: controller.signal
|
signal: controller.signal
|
||||||
};
|
} as Parameters<typeof fetch>[1];
|
||||||
const response = await fetch(urlStr, fetchOptions);
|
const response = await fetch(urlStr, fetchOptions);
|
||||||
|
|
||||||
if (response.body) {
|
if (response.body) {
|
||||||
@@ -99,7 +99,7 @@ export async function safeFetch(urlStr: string, options: FetchOptions = {}): Pro
|
|||||||
|
|
||||||
return new Response(stream, {
|
return new Response(stream, {
|
||||||
status: response.status,
|
status: response.status,
|
||||||
headers: response.headers as any
|
headers: response.headers as unknown as HeadersInit
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -51,10 +51,10 @@ export function createGeoJsonPlugin(config: ImportedPluginConfig): WorldPlugin {
|
|||||||
category: "custom" as const,
|
category: "custom" as const,
|
||||||
version: "1.0.0",
|
version: "1.0.0",
|
||||||
|
|
||||||
async initialize(_ctx: PluginContext): Promise<void> { },
|
async initialize(): Promise<void> { },
|
||||||
destroy(): void { },
|
destroy(): void { },
|
||||||
|
|
||||||
async fetch(_timeRange: TimeRange): Promise<GeoEntity[]> {
|
async fetch(): Promise<GeoEntity[]> {
|
||||||
return entities;
|
return entities;
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -70,7 +70,7 @@ export function createGeoJsonPlugin(config: ImportedPluginConfig): WorldPlugin {
|
|||||||
};
|
};
|
||||||
},
|
},
|
||||||
|
|
||||||
renderEntity(_entity: GeoEntity): CesiumEntityOptions {
|
renderEntity(): CesiumEntityOptions {
|
||||||
return {
|
return {
|
||||||
type: "point",
|
type: "point",
|
||||||
color: config.color,
|
color: config.color,
|
||||||
|
|||||||
@@ -0,0 +1,114 @@
|
|||||||
|
// @vitest-environment node
|
||||||
|
import {
|
||||||
|
beforeEach, describe, expect, it, vi
|
||||||
|
} from "vitest";
|
||||||
|
import { GET } from "@/app/api/iss/route";
|
||||||
|
|
||||||
|
const validResponse = {
|
||||||
|
name: "iss",
|
||||||
|
id: 25544,
|
||||||
|
latitude: -34.814,
|
||||||
|
longitude: 170.22,
|
||||||
|
altitude: 431.6,
|
||||||
|
velocity: 27545.56,
|
||||||
|
visibility: "daylight",
|
||||||
|
footprint: 4566.04,
|
||||||
|
timestamp: 1778894864,
|
||||||
|
daynum: 2461176.56,
|
||||||
|
solar_lat: 19.07,
|
||||||
|
solar_lon: 157.16,
|
||||||
|
units: "kilometers",
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("/api/iss", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns validated ISS position data", async () => {
|
||||||
|
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
json: async () => validResponse,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const response = await GET();
|
||||||
|
const json = await response.json();
|
||||||
|
|
||||||
|
expect(response.status).toBe(200);
|
||||||
|
expect(json.id).toBe(25544);
|
||||||
|
expect(json.latitude).toBe(-34.814);
|
||||||
|
expect(json.longitude).toBe(170.22);
|
||||||
|
expect(json.altitude).toBe(431.6);
|
||||||
|
expect(json.velocity).toBe(27545.56);
|
||||||
|
expect(json.visibility).toBe("daylight");
|
||||||
|
expect(json.timestamp).toBe(1778894864);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("strips extra fields from upstream response", async () => {
|
||||||
|
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
json: async () => validResponse,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const response = await GET();
|
||||||
|
const json = await response.json();
|
||||||
|
|
||||||
|
expect(json).not.toHaveProperty("daynum");
|
||||||
|
expect(json).not.toHaveProperty("solar_lat");
|
||||||
|
expect(json).not.toHaveProperty("solar_lon");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 502 when upstream API fails", async () => {
|
||||||
|
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
|
||||||
|
ok: false,
|
||||||
|
status: 503,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const response = await GET();
|
||||||
|
const json = await response.json();
|
||||||
|
|
||||||
|
expect(response.status).toBe(502);
|
||||||
|
expect(json).toEqual({ error: "Failed to fetch ISS position" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 502 when response has invalid coordinates", async () => {
|
||||||
|
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
json: async () => ({
|
||||||
|
...validResponse,
|
||||||
|
latitude: "not-a-number",
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const response = await GET();
|
||||||
|
const json = await response.json();
|
||||||
|
|
||||||
|
expect(response.status).toBe(502);
|
||||||
|
expect(json).toEqual({ error: "Invalid ISS position data" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 502 when upstream returns null body", async () => {
|
||||||
|
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
json: async () => null,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const response = await GET();
|
||||||
|
const json = await response.json();
|
||||||
|
|
||||||
|
expect(response.status).toBe(502);
|
||||||
|
expect(json).toEqual({ error: "Invalid ISS position data" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 502 when fetch throws a network error", async () => {
|
||||||
|
vi.stubGlobal("fetch", vi.fn().mockRejectedValue(
|
||||||
|
new Error("Network error"),
|
||||||
|
));
|
||||||
|
|
||||||
|
const response = await GET();
|
||||||
|
const json = await response.json();
|
||||||
|
|
||||||
|
expect(response.status).toBe(502);
|
||||||
|
expect(json).toEqual({ error: "Failed to fetch ISS position" });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
// @vitest-environment node
|
||||||
|
import {
|
||||||
|
beforeEach, describe, expect, it, vi
|
||||||
|
} from "vitest";
|
||||||
|
import { GET } from "@/app/api/iss/positions/route";
|
||||||
|
|
||||||
|
const validPositions = [
|
||||||
|
{
|
||||||
|
name: "iss",
|
||||||
|
id: 25544,
|
||||||
|
latitude: -34.814,
|
||||||
|
longitude: 170.22,
|
||||||
|
altitude: 431.6,
|
||||||
|
velocity: 27545.56,
|
||||||
|
visibility: "daylight",
|
||||||
|
footprint: 4566.04,
|
||||||
|
timestamp: 1778894864,
|
||||||
|
daynum: 2461176.56,
|
||||||
|
units: "kilometers",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "iss",
|
||||||
|
id: 25544,
|
||||||
|
latitude: -34.389,
|
||||||
|
longitude: 170.77,
|
||||||
|
altitude: 431.38,
|
||||||
|
velocity: 27546.15,
|
||||||
|
visibility: "daylight",
|
||||||
|
footprint: 4564.91,
|
||||||
|
timestamp: 1778894874,
|
||||||
|
daynum: 2461176.56,
|
||||||
|
units: "kilometers",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
function makeRequest(timestamps: string): Request {
|
||||||
|
return new Request(`http://localhost:3000/api/iss/positions?timestamps=${timestamps}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("/api/iss/positions", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns validated position data for given timestamps", async () => {
|
||||||
|
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
json: async () => validPositions,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const response = await GET(makeRequest("1778894864,1778894874"));
|
||||||
|
const json = await response.json();
|
||||||
|
|
||||||
|
expect(response.status).toBe(200);
|
||||||
|
expect(json.positions).toHaveLength(2);
|
||||||
|
expect(json.positions[0].latitude).toBe(-34.814);
|
||||||
|
expect(json.positions[1].timestamp).toBe(1778894874);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("strips extra fields from position responses", async () => {
|
||||||
|
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
json: async () => validPositions,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const response = await GET(makeRequest("1778894864"));
|
||||||
|
const json = await response.json();
|
||||||
|
|
||||||
|
expect(json.positions[0]).not.toHaveProperty("name");
|
||||||
|
expect(json.positions[0]).not.toHaveProperty("footprint");
|
||||||
|
expect(json.positions[0]).not.toHaveProperty("daynum");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 400 when timestamps parameter is missing", async () => {
|
||||||
|
const request = new Request("http://localhost:3000/api/iss/positions");
|
||||||
|
const response = await GET(request);
|
||||||
|
const json = await response.json();
|
||||||
|
|
||||||
|
expect(response.status).toBe(400);
|
||||||
|
expect(json.error).toContain("timestamps");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 400 when timestamps are not numeric", async () => {
|
||||||
|
const response = await GET(makeRequest("abc,def"));
|
||||||
|
const json = await response.json();
|
||||||
|
|
||||||
|
expect(response.status).toBe(400);
|
||||||
|
expect(json.error).toContain("No valid timestamps");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 400 when exceeding maximum timestamps", async () => {
|
||||||
|
const ts = Array.from({ length: 11 }, (_, i) => String(1778894864 + i)).join(",");
|
||||||
|
const response = await GET(makeRequest(ts));
|
||||||
|
const json = await response.json();
|
||||||
|
|
||||||
|
expect(response.status).toBe(400);
|
||||||
|
expect(json.error).toContain("Maximum");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("filters out invalid positions from upstream", async () => {
|
||||||
|
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
json: async () => [
|
||||||
|
validPositions[0],
|
||||||
|
{ latitude: "bad", longitude: 0, altitude: 0, velocity: 0, timestamp: 0 },
|
||||||
|
{ latitude: 10, longitude: 20, altitude: 400, velocity: NaN, timestamp: 123 },
|
||||||
|
],
|
||||||
|
}));
|
||||||
|
|
||||||
|
const response = await GET(makeRequest("1778894864,1778894874,1778894884"));
|
||||||
|
const json = await response.json();
|
||||||
|
|
||||||
|
expect(json.positions).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 400 when timestamps param is empty string", async () => {
|
||||||
|
const response = await GET(makeRequest(""));
|
||||||
|
const json = await response.json();
|
||||||
|
|
||||||
|
expect(response.status).toBe(400);
|
||||||
|
expect(json.error).toContain("timestamps");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 502 when fetch throws a network error", async () => {
|
||||||
|
vi.stubGlobal("fetch", vi.fn().mockRejectedValue(
|
||||||
|
new Error("Network error"),
|
||||||
|
));
|
||||||
|
|
||||||
|
const response = await GET(makeRequest("1778894864"));
|
||||||
|
const json = await response.json();
|
||||||
|
|
||||||
|
expect(response.status).toBe(502);
|
||||||
|
expect(json).toEqual({ error: "Failed to fetch ISS positions" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 502 when upstream API fails", async () => {
|
||||||
|
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
|
||||||
|
ok: false,
|
||||||
|
status: 503,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const response = await GET(makeRequest("1778894864"));
|
||||||
|
const json = await response.json();
|
||||||
|
|
||||||
|
expect(response.status).toBe(502);
|
||||||
|
expect(json).toEqual({ error: "Failed to fetch ISS positions" });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
// @vitest-environment node
|
||||||
|
import {
|
||||||
|
beforeEach, describe, expect, it, vi
|
||||||
|
} from "vitest";
|
||||||
|
import { GET } from "@/app/api/iss/tle/route";
|
||||||
|
|
||||||
|
const validTle = {
|
||||||
|
requested_timestamp: 1778894871,
|
||||||
|
tle_timestamp: 1778772971,
|
||||||
|
id: "25544",
|
||||||
|
name: "iss",
|
||||||
|
header: "ISS (ZARYA)",
|
||||||
|
line1: "1 25544U 98067A 26134.65013167 .00004878 00000+0 95926-4 0 9996",
|
||||||
|
line2: "2 25544 51.6311 106.1165 0007514 58.4526 301.7195 15.49215603566555",
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("/api/iss/tle", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns validated TLE data", async () => {
|
||||||
|
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
json: async () => validTle,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const response = await GET();
|
||||||
|
const json = await response.json();
|
||||||
|
|
||||||
|
expect(response.status).toBe(200);
|
||||||
|
expect(json.id).toBe("25544");
|
||||||
|
expect(json.header).toBe("ISS (ZARYA)");
|
||||||
|
expect(json.line1).toContain("25544U");
|
||||||
|
expect(json.line2).toContain("51.6311");
|
||||||
|
expect(json.tleTimestamp).toBe(1778772971);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("normalizes tle_timestamp to tleTimestamp", async () => {
|
||||||
|
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
json: async () => validTle,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const response = await GET();
|
||||||
|
const json = await response.json();
|
||||||
|
|
||||||
|
expect(json).toHaveProperty("tleTimestamp");
|
||||||
|
expect(json).not.toHaveProperty("tle_timestamp");
|
||||||
|
expect(json).not.toHaveProperty("requested_timestamp");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 502 when upstream API fails", async () => {
|
||||||
|
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
|
||||||
|
ok: false,
|
||||||
|
status: 500,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const response = await GET();
|
||||||
|
const json = await response.json();
|
||||||
|
|
||||||
|
expect(response.status).toBe(502);
|
||||||
|
expect(json).toEqual({ error: "Failed to fetch ISS TLE data" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 502 when TLE lines are empty", async () => {
|
||||||
|
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
json: async () => ({
|
||||||
|
...validTle,
|
||||||
|
line1: "",
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const response = await GET();
|
||||||
|
const json = await response.json();
|
||||||
|
|
||||||
|
expect(response.status).toBe(502);
|
||||||
|
expect(json).toEqual({ error: "Invalid ISS TLE data" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 502 when upstream returns null body", async () => {
|
||||||
|
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
json: async () => null,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const response = await GET();
|
||||||
|
const json = await response.json();
|
||||||
|
|
||||||
|
expect(response.status).toBe(502);
|
||||||
|
expect(json).toEqual({ error: "Invalid ISS TLE data" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 502 when fetch throws a network error", async () => {
|
||||||
|
vi.stubGlobal("fetch", vi.fn().mockRejectedValue(
|
||||||
|
new Error("DNS resolution failed"),
|
||||||
|
));
|
||||||
|
|
||||||
|
const response = await GET();
|
||||||
|
const json = await response.json();
|
||||||
|
|
||||||
|
expect(response.status).toBe(502);
|
||||||
|
expect(json).toEqual({ error: "Failed to fetch ISS TLE data" });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable no-console */
|
||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import type { NextRequest } from "next/server";
|
import type { NextRequest } from "next/server";
|
||||||
import { getToken } from "next-auth/jwt";
|
import { getToken } from "next-auth/jwt";
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable no-console */
|
||||||
import { test, expect } from '@playwright/test';
|
import { test, expect } from '@playwright/test';
|
||||||
|
|
||||||
test.describe('Bottom Panel System', () => {
|
test.describe('Bottom Panel System', () => {
|
||||||
@@ -21,7 +22,7 @@ test.describe('Bottom Panel System', () => {
|
|||||||
await installBtn.waitFor({ state: 'visible', timeout: 5000 });
|
await installBtn.waitFor({ state: 'visible', timeout: 5000 });
|
||||||
await installBtn.click();
|
await installBtn.click();
|
||||||
console.log('Clicked "Install Selected" in unverified plugin dialog.');
|
console.log('Clicked "Install Selected" in unverified plugin dialog.');
|
||||||
} catch (e) {
|
} catch {
|
||||||
console.log('Unverified plugin dialog did not appear.');
|
console.log('Unverified plugin dialog did not appear.');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable no-console */
|
||||||
import { chromium, type FullConfig } from '@playwright/test';
|
import { chromium, type FullConfig } from '@playwright/test';
|
||||||
import { PrismaClient } from '../src/generated/prisma/index.js';
|
import { PrismaClient } from '../src/generated/prisma/index.js';
|
||||||
import { PrismaPg } from "@prisma/adapter-pg";
|
import { PrismaPg } from "@prisma/adapter-pg";
|
||||||
@@ -25,7 +26,7 @@ function loadEnv() {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch {
|
||||||
// Ignore read errors
|
// Ignore read errors
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -50,7 +51,7 @@ async function globalSetup(config: FullConfig) {
|
|||||||
await prisma.$queryRaw`SELECT 1`;
|
await prisma.$queryRaw`SELECT 1`;
|
||||||
dbConnected = true;
|
dbConnected = true;
|
||||||
break;
|
break;
|
||||||
} catch (e) {
|
} catch {
|
||||||
console.log(`[Setup] Waiting for database (attempt ${i + 1}/5)...`);
|
console.log(`[Setup] Waiting for database (attempt ${i + 1}/5)...`);
|
||||||
await new Promise(resolve => setTimeout(resolve, 2000));
|
await new Promise(resolve => setTimeout(resolve, 2000));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable no-console */
|
||||||
import { type FullConfig } from '@playwright/test';
|
import { type FullConfig } from '@playwright/test';
|
||||||
import { PrismaClient } from '../src/generated/prisma/index.js';
|
import { PrismaClient } from '../src/generated/prisma/index.js';
|
||||||
import { PrismaPg } from "@prisma/adapter-pg";
|
import { PrismaPg } from "@prisma/adapter-pg";
|
||||||
@@ -23,12 +24,12 @@ function loadEnv() {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch {
|
||||||
// Ignore read errors
|
// Ignore read errors
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function globalTeardown(config: FullConfig) {
|
async function globalTeardown() {
|
||||||
loadEnv();
|
loadEnv();
|
||||||
const pool = new Pool({ connectionString: process.env.DATABASE_URL || "postgresql://postgres:[email protected]:5432/worldwideview?schema=public" });
|
const pool = new Pool({ connectionString: process.env.DATABASE_URL || "postgresql://postgres:[email protected]:5432/worldwideview?schema=public" });
|
||||||
const adapter = new PrismaPg(pool);
|
const adapter = new PrismaPg(pool);
|
||||||
@@ -42,7 +43,7 @@ async function globalTeardown(config: FullConfig) {
|
|||||||
await prisma.user.deleteMany({
|
await prisma.user.deleteMany({
|
||||||
where: { email: TEST_USER_EMAIL },
|
where: { email: TEST_USER_EMAIL },
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch {
|
||||||
console.error(`[Teardown] Failed to delete test user:`, e);
|
console.error(`[Teardown] Failed to delete test user:`, e);
|
||||||
} finally {
|
} finally {
|
||||||
await prisma.$disconnect();
|
await prisma.$disconnect();
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable no-console */
|
||||||
import { test, expect } from '@playwright/test';
|
import { test, expect } from '@playwright/test';
|
||||||
|
|
||||||
test.describe('Dynamic Plugin System', () => {
|
test.describe('Dynamic Plugin System', () => {
|
||||||
@@ -30,7 +31,7 @@ test.describe('Dynamic Plugin System', () => {
|
|||||||
await installBtn.waitFor({ state: 'visible', timeout: 5000 });
|
await installBtn.waitFor({ state: 'visible', timeout: 5000 });
|
||||||
await installBtn.click();
|
await installBtn.click();
|
||||||
console.log('Clicked "Install Selected" in unverified plugin dialog.');
|
console.log('Clicked "Install Selected" in unverified plugin dialog.');
|
||||||
} catch (e) {
|
} catch {
|
||||||
// Dialog didn't appear, possibly because it's a verified plugin or already approved
|
// Dialog didn't appear, possibly because it's a verified plugin or already approved
|
||||||
console.log('Unverified plugin dialog did not appear.');
|
console.log('Unverified plugin dialog did not appear.');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ test.describe('UI Navigation and Panels', () => {
|
|||||||
try {
|
try {
|
||||||
await installBtn.waitFor({ state: 'visible', timeout: 2000 });
|
await installBtn.waitFor({ state: 'visible', timeout: 2000 });
|
||||||
await installBtn.click();
|
await installBtn.click();
|
||||||
} catch (e) {
|
} catch {
|
||||||
// Ignore if it doesn't appear
|
// Ignore if it doesn't appear
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in new issue
Block a user